Tk Source Code

Changes On Branch tip-510
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch tip-510 Excluding Merge-Ins

This is equivalent to a diff from 3fadeb90 to 3e448325

2019-05-08
19:47
New files from RenĂ© Zaumseil Leaf check-in: 3e448325 user: fvogel tags: tip-510
2019-04-12
20:10
Repair test tk-1.2 check-in: e608f7c6 user: fvogel tags: tip-510
2018-08-21
19:06
Fix [66db98f30d] regarding error messages spit by messageboxes in the test suite, while still not regress as described in [98dce84781] (yes and no answers were swapped) check-in: 854a060c user: fvogel tags: trunk
2018-08-19
14:14
merge trunk check-in: fc67d206 user: fvogel tags: tip-507
14:12
merge trunk check-in: d222f03a user: fvogel tags: tip-510
13:49
merge trunk (leaving out any changes in generic/tkText* however) check-in: 06b9d56a user: fvogel tags: revised_text, tip-466
2018-08-18
21:17
Fix bug [c2c5bdb4aa]: segfault when opening colorpicker check-in: 3fadeb90 user: culler tags: trunk
21:15
Fix bug [c2c5bdb4aa]: segfault when opening colorpicker check-in: 6f994d29 user: culler tags: core-8-6-branch
2018-08-15
16:22
Fix [98dce84781]: yesno messageBoxes on macOS return wrong values check-in: b2160d49 user: fvogel tags: trunk

Added doc/graph.n.md.








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# graph(n) -- 2D graph for plotting X-Y coordinate data

*   [SYNOPSIS](#SYNOPSIS)  
*   [STANDARD OPTIONS](#STANDARD-OPTIONS)  
  [-background or -bg, background, Background](options.htm#M-background)  
  [-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
  [-cursor, cursor, Cursor](options.htm#M-cursor)  
  [-foreground or -fg, foreground, Foreground](options.htm#M-foreground)  
  [-height, height, Height](options.htm#M-height)  
  [-width, width, Width](options.htm#M-width)  
*   [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  
  [-aspect, aspect, Aspect](#-aspect) *width/height*  
  [-barmode, barMode, BarMode](#-barmode)  
  [-barwidth, barWidth, BarWidth](#-barwidth)  
  [-baseline, baseline, Baseline](#-baseline)  
  [-bottommargin, bottomMargin, Margin](#-bottommargin) *pixels*  
  [-bottomvariable, bottomVariable, BottomVariable](#-bottomvariable)  
  [-bufferelements, bufferElements, BufferElements](#-bufferelements) *boolean*  
  [-buffergraph, bufferGraph, BufferGraph](#-buffergraph)  
  [-class, class, Class](options.htm#M-class)  
  [-font, font, Font](#-font) *fontName*  
  [-halo, halo, Halo](#-halo) *pixels*  
  [-highlightbackground, highlightBackground, HighlightBackground](#-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](#-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](#-highlightthickness)  
  [-invertxy, invertXY, InvertXY](#-invertxy) *boolean*  
  [-justify, justify, Justify](#-justify) *justify*  
  [-leftmargin or -lm, leftMargin, Margin](#-leftmargin) *pixels*  
  [-leftvariable, leftVariable, LeftVariable](#-leftvariable)  
  [-plotbackground, plotBackground, Background](#-plotbackground) *color*  
  [-plotborderwidth, plotBorderWidth, BorderWidth](#-plotborderwidth) *pixels*  
  [-plotpadx, plotPadX, PlotPad](#-plotpadx) *pad*  
  [-plotpady, plotPadY, PlotPad](#-plotpadx) *pad*  
  [-plotrelief, plotRelief, Relief](#-plotrelief) *relief*  
  [-relief, relief, Relief](#-relief) *relief*  
  [-rightmargin or -rm, rightMargin, Margin](#-rightmargin) *pixels*  
  [-rightvariable, rightVariable, RightVariable](#-rightvariable)  
  [-shadow, shadow, Shadow](#-shadow)  
  [-style, style, Style](#-style) *line|bar|strip*  
  [-takefocus, takeFocus, TakeFocus](#-takefocus)  
  [-tile, tile, Tile](#-tile)  
  [-title, title, Title](#-title) *text|image*  
  [-topmargin or -tm, topMargin, Margin](#-topmargin) *pixels*  
  [-topvariable, topVariable, TopVariable](#-topvariable)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **axis**](#pathName-axis) *operation ?arg?...*  
  [*pathName* **binding**](#pathName-binding) *?crosshairs? ?findelement? ?legend? ?zoom?*  
  [*pathName* **bar**](#pathName-bar) *elemName ?option value?...*  
  [*pathName* **cget**](#pathName-cget) *option*  
  [*pathName* **configure**](#pathName-configure) *?option value?...*  
  [*pathName* **crosshairs**](#pathName-crosshairs) *operation ?arg?*  
  [*pathName* **element**](#pathName-element) *operation ?arg?...*  
  [*pathName* **extents**](#pathName-extents) *item*  
  [*pathName* **grid**](#pathName-grid) *operation ?arg?...*  
  [*pathName* **invtransform**](#pathName-invtransform) *winX winY*  
  [*pathName* **inside**](#pathName-inside) *x y*  
  [*pathName* **legend**](#pathName-legend) *operation ?arg?...*  
  [*pathName* **line**](#pathName-line) *operation arg...*  
  [*pathName* **marker**](#pathName-marker) *operation ?arg?...*  
  [*pathName* **postscript**](#pathName-postscript) *operation ?arg?...*  
  [*pathName* **snap**](#pathName-snap) *?switches? outputName*  
  [*pathName* **transform**](#pathName-transform) *x y*  
  [*pathName* **xaxis**](#pathName-xaxis) *operation ?arg?...*  
  [*pathName* **x2axis**](#pathName-x2axis) *operation ?arg?...*  
  [*pathName* **yaxis**](#pathName-yaxis) *operation ?arg?...*  
  [*pathName* **y2axis**](#pathName-y2axis) *operation ?arg?...*  
* [AXIS COMPONENT](#AXIS-COMPONENT)  
  [*pathName* **axis bind**](#pathName-axis-bind) *tagName ?sequence? ?command?*  
  [*pathName* **axis cget**](#pathName-axis-cget) *axisName option*  
  [*pathName* **axis configure**](#pathName-axis-configure) *axisName ?axisName?... ?option value?...*  
  [*pathName* **axis create**](#pathName-axis-create) *axisName ?option value?...*  
  [*pathName* **axis delete**](#pathName-axis-delete) *?axisName?...*  
  [*pathName* **axis invtransform**](#pathName-axis-invtransform) *axisName value*  
  [*pathName* **axis limits**](#pathName-axis-limits) *axisName*  
  [*pathName* **axis names**](#pathName-axis-names) *?pattern?...*  
  [*pathName* **axis transform**](#pathName-axis-transform) *axisName value*  
  [*pathName* **axis view**](#pathName-axis-view) *axisName*  
* [CROSSHAIRS COMPONENT](#)  
  [*pathName* **crosshairs cget**](#pathName-crosshairs-cget) *option*  
  [*pathName* **crosshairs configure**](#pathName-crosshairs-configure) *?option value?...*  
  [*pathName* **crosshairs off**](#pathName-crosshairs-off)  
  [*pathName* **crosshairs on**](#pathName-crosshairs-on)  
  [*pathName* **crosshairs toggle**](#pathName-crosshairs-toggle)  
* [ELEMENT COMPONENT](#ELEMENT-COMPONENT)  
  [*pathName* **element activate**](#pathName-element-activate) *elemName ?index?...*  
  [*pathName* **element bind**](#pathName-element-bind) *tagName ?sequence? ?command?*  
  [*pathName* **element cget**](#pathName-element-cget) *elemName option*  
  [*pathName* **element closest**](#pathName-element-closest) *x y varName ?option value?... ?elemName?...*  
  [*pathName* **element configure**](#pathName-element-configure) *elemName ?elemName... ?option value?...*  
  [*pathName* **element create**](#pathName-element-create) *elemName ?option value?...*  
  [*pathName* **element deactivate**](#pathName-element-deactivate) *elemName ?elemName?...*  
  [*pathName* **element delete**](#pathName-element-delete) *?elemName?...*  
  [*pathName* **element exists**](#pathName-element-exists) *elemName*  
  [*pathName* **element names**](#pathName-element-names) *?pattern?...*  
  [*pathName* **element show**](#pathName-element-show) *?nameList?*  
  [*pathName* **element type**](#pathName-element-type) *elemName*  
* [GRID COMPONENT](#GRID-COMPONENT)  
  [*pathName* **grid cget**](#pathName-grid-cget) *option*  
  [*pathName* **grid configure**](#pathName-grid-configure) *?option value?...*  
  [*pathName* **grid off**](#pathName-grid-off)  
  [*pathName* **grid on**](#pathName-grid-on)  
  [*pathName* **grid toggle**](#pathName-grid-toggle)  
* [LEGEND COMPONENT](#LEGEND-COMPONENT)  
  [*pathName* **legend activate**](#pathName-legend-activate) *pattern...*  
  [*pathName* **legend bind**](#pathName-legend-bind) *tagName ?sequence? ?command?*  
  [*pathName* **legend cget**](#pathName-legend-cget) *option*  
  [*pathName* **legend configure**](#pathName-legend-configure) *?option value?...*  
  [*pathName* **legend deactivate**](#pathName-legend-deactivate) *pattern...*  
  [*pathName* **legend get**](#pathName-legend-get) *pos*  
* [PEN COMPONENT](#PEN-COMPONENT)  
  [*pathName* **pen cget**](#pathName-pen-cget) *penName option*  
  [*pathName* **pen configure**](#pathName-pen-configure) *penName ?penName... ?option value?...*  
  [*pathName* **pen create**](#pathName-pen-create) *penName ?option value?...*  
  [*pathName* **pen delete**](#pathName-pen-delete) *?penName?...*  
  [*pathName* **pen names**](#pathName-pen-names) *?pattern?...*  
* [POSTSCRIPT COMPONENT](#POSTSCRIPT-COMPONENT)  
  [*pathName* **postscript cget**](#pathName-postscript-cget) *option*  
  [*pathName* **postscript configure**](#pathName-postscript-configure) *?option value?...*  
  [*pathName* **postscript output**](#pathName-postscript-output) *?fileName? ?option value?...*  
* [MARKER COMPONENT](#MARKER-COMPONENT)  
  [*pathName* **marker after**](#pathName-marker-after) *markerId ?afterId?*  
  [*pathName* **marker before**](#pathName-marker-before) *markerId ?beforeId?*  
  [*pathName* **marker bind**](#pathName-marker-bind) *tagName ?sequence? ?command?*  
  [*pathName* **marker cget**](#pathName-marker-cget) *option*  
  [*pathName* **marker configure**](#pathName-marker-configure) *markerId ?option value?...*  
  [*pathName* **marker create**](#pathName-marker-create) *type ?option value?...*  
  [*pathName* **marker delete**](#pathName-marker-delete) *?name?...*  
  [*pathName* **marker exists**](#pathName-marker-exists) *markerId*  
  [*pathName* **marker names**](#pathName-marker-names) *?pattern?*  
  [*pathName* **marker type**](#pathName-marker-type) *markerId*  
  [BITMAP MARKERS](#BITMAP-MARKERS)  
  [*pathName* **marker create bitmap**](#pathName-marker-create-bitmap) *?option value?...*  
  [IMAGE MARKERS](#IMAGE-MARKERS)  
  [*pathName* **marker create image**](#pathName-marker-create-image) *?option value?...*  
  [LINE MARKERS](#LINE-MARKERS)  
  [*pathName* **marker create line**](#pathName-marker-create-line) *?option value?...*  
  [POLYGON MARKERS](#POLYGON-MARKERS)  
  [*pathName* **marker create polygon**](#pathName-marker-create-polygon) *?option value?...*  
  [TEXT MARKERS](#TEXT-MARKERS)  
  [*pathName* **marker create text**](#pathName-marker-create-text) *?option value?...*  
  [WINDOW MARKERS](#WINDOW-MARKERS)  
  [*pathName* **marker create window**](#pathName-marker-create-window) *?option value?...*  
*   [GRAPH COMPONENT BINDINGS](#GRAPH-COMPONENT-BINDINGS)  
*   [C LANGUAGE API](#[C-LANGUAGE-API)  
*   [SPEED TIPS](#SPEED-TIPS)  
*   [LIMITATIONS](#LIMITATIONS)  
*   [EXAMPLE](#EXAMPLE)  
*   [CREDITS](#CREDITS)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS 

**graph** *pathName ?-style line|bar|strip? ?option value?...*

The graph command creates a new window pathName and makes it into a graph widget. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist. Additional options may be specified on the command line or in the option database to configure aspects of the graph such as its colors and font. See the configure operation below for the exact details about what option and value pairs are valid.

The *-style* option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is "line".

If successful, graph returns the path name of the widget. It also creates a new Tcl command by the same name. You can use this command to invoke various operations that query or modify the graph. The general form is:

**pathName** *operation ?arg?...*

Both operation and its arguments determine the exact behavior of the command. The operations available for the graph are described in the section.

The command can also be used to access components of the graph.

**pathName component** *operation ?arg?...*

A graph is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, postscript, and annotation markers. Instead of one big set of configuration options and operations, the graph is partitioned, where each component has its own configuration options and operations that specifically control that aspect or part of the graph.

The operation, now located after the name of the component, is the function to be performed on that component. Each component has its own set of operations that manipulate that component. They will be described below in their own sections.

<a name="STANDARD-OPTIONS"></a>
## STANDARD OPTIONS

[-background or -bg, background, Background](options.htm#M-background) This includes the margins and legend, but not the plotting area.  
[-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
[-cursor, cursor, Cursor](options.htm#M-cursor)  
[-foreground or -fg, foreground, Foreground](options.htm#M-foreground)  
[-height, height, Height](options.htm#M-height) The default is 4i.  
[-width, width, Width](options.htm#M-width) The default is 5i.  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS

<a name="-aspect"></a>
Command-Line Name: **-aspect**  
Database Name: **aspect**  
Database Class: **Aspect**

> > Force a fixed aspect ratio of width/height, a floating point number.

<a name="-barmode"></a>
Command-Line Name: **-barmode**  
Database Name: **barMode**  
Database Class: **BarMode**

<a name="-barwidth"></a>
Command-Line Name: **-barwidth**  
Database Name: **barWidth**  
Database Class: **BarWidth**

<a name="-baseline"></a>
Command-Line Name: **-baseline**  
Database Name: **baseline**  
Database Class: **Baseline**

<a name="-bottommargin"></a>
Command-Line Name: **-bottommargin or -bm**  
Database Name: **bottomMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending below the X-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-bottomvariable"></a>
Command-Line Name: **-bottomvariable**  
Database Name: **bottomVariable**  
Database Class: **BottomVariable**

<a name="-bufferelements"></a>
Command-Line Name: **-bufferelements**  
Database Name: **bufferElements**  
Database Class: **BufferElements**

> > Indicates whether an internal pixmap to buffer the display of data elements should be used. If boolean is true, data elements are drawn to an internal pixmap. This option is especially useful when the graph is redrawn frequently while the remains data unchanged (for example, moving a marker across the plot). See the section. The default is 1.

<a name="-buffergraph"></a>
Command-Line Name: **-buffergraph**  
Database Name: **bufferGraph**  
Database Class: **BufferGraph**

<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**

> > Define class for use in getting values from option database.

<a name="-font"></a>
Command-Line Name: **-font**  
Database Name: **font**  
Database Class: **Font**

> > Specifies the font of the graph title. The default is `*-Helvetica-Bold-R-Normal-*-18-180-*`.

<a name="-halo"></a>
Command-Line Name: **-halo**  
Database Name: **halo**  
Database Class: **Halo**

> > Specifies a maximum distance to consider when searching for the closest data point (see the element's closest operation below). Data points further than pixels away are ignored. The default is 0.5i.

<a name="-highlightbackground"></a>
Command-Line Name: **-highlightbackground**  
Database Name: **highlightBackground**  
Database Class: **HighlightBackground**

<a name="-highlightcolor"></a>
Command-Line Name: **-highlightcolor**  
Database Name: **highlightColor**  
Database Class: **HighlightColor**

<a name="-highlightthickness"></a>
Command-Line Name: **-highlightthickness**  
Database Name: **highlightThickness**  
Database Class: **HighlightThickness**

<a name="-invertxy"></a>
Command-Line Name: **-invertxy**  
Database Name: **invertXY**  
Database Class: **InvertXY**

> > Indicates whether the placement X-axis and Y-axis should be inverted. If boolean is true, the X and Y axes are swapped. The default is 0.

<a name="-justify"></a>
Command-Line Name: **-justify**  
Database Name: **justify**  
Database Class: **Justify**

> > Specifies how the title should be justified. This matters only when the title contains more than one line of text. Justify must be left, right, or center. The default is center.

<a name="-leftmargin"></a>
Command-Line Name: **-leftmargin or -lm**  
Database Name: **leftMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending from the left edge of the window to the Y-coordinate axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-leftvariable"></a>
Command-Line Name: **-leftvariable**  
Database Name: **leftVariable**  
Database Class: **LeftVariable**

<a name="-plotbackground"></a>
Command-Line Name: **-plotbackground**  
Database Name: **plotBackground**  
Database Class: **Background**

> > Specifies the background color of the plotting area. The default is white.

<a name="-plotborderwidth"></a>
Command-Line Name: **-plotborderwidth**  
Database Name: **plotBorderWidth**  
Database Class: **BorderWidth**

> > Sets the width of the 3-D border around the plotting area. The -plotrelief option determines if a border is drawn. The default is 2.

<a name="-plotpadx"></a>
Command-Line Name: **-plotpadx**  
Database Name: **plotPadX**  
Database Class: **PlotPad**


> > Sets the amount of padding to be added to the left and right sides of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the plotting area entry is padded by the first distance and the right side by the second. If pad is just one distance, both the left and right sides are padded evenly. The default is 8.

<a name="-plotpady"></a>
Command-Line Name: **-plotpady**  
Database Name: **plotPadY**  
Database Class: **PlotPad**

> > Sets the amount of padding to be added to the top and bottom of the plotting area. Pad can be a list of one or two screen distances. If pad has two elements, the top of the plotting area is padded by the first distance and the bottom by the second. If pad is just one distance, both the top and bottom are padded evenly. The default is 8.

> **-plotrelief**
<a name="-plotrelief"></a>
Command-Line Name: **-plotrelief**  
Database Name: **plotRelief**  
Database Class: **Relief**

> > Specifies the 3-D effect for the plotting area. Relief specifies how the interior of the plotting area should appear relative to rest of the graph; for example, raised means the plot should appear to protrude from the graph, relative to the surface of the graph. The default is sunken.

> **-relief** *relief*
<a name="-relief"></a>
Command-Line Name: **-relief**  
Database Name: **relief**  
Database Class: **Relief**

> > Specifies the 3-D effect for the graph widget. Relief specifies how the graph should appear relative to widget it is packed into; for example, raised means the graph should appear to protrude. The default is flat.

<a name="-rightmargin"></a>
Command-Line Name: **-rightmargin**  
Database Name: **rightMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin extending from the plotting area to the right edge of the window. By default, the legend is drawn in this margin. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-rightvariable"></a>
Command-Line Name: **-rightvariable**  
Database Name: **rightVariable**  
Database Class: **RightVariable**

<a name="-shadow"></a>
Command-Line Name: **-shadow**  
Database Name: **shadow**  
Database Class: **Shadow**

<a name="-style"></a>
Command-Line Name: **-style**  
Database Name: **style**  
Database Class: **Style**

The option can only be set on creation time of the new window. The option control the appearance of the widget. Default value is **line**.

> **line**

> > Display X-Y plotchart

> **bar**

> > Display barchart.

> **strip**

> > Display stripchart.

> **-takefocus** *focus*
<a name="-takefocus"></a>
Command-Line Name: **-takefocus**  
Database Name: **takeFocus**  
Database Class: **TakeFocus**

> > Provides information used when moving the focus from window to window via keyboard traversal (e.g., Tab and Shift-Tab). If focus is 0, this means that this window should be skipped entirely during keyboard traversal. 1 means that the this window should always receive the input focus. An empty value means that the traversal scripts make the decision whether to focus on the window. The default is "".

<a name="-tile"></a>
Command-Line Name: **-tile**  
Database Name: **tile**  
Database Class: **Title**

> **image**

> > Specifies a tiled background for the widget. If image isn't "", the background is tiled using image. Otherwise, the normal background color is drawn (see the -background option). Image must be an image created using the Tk image command. The default is "".

> **text**

> > Sets the title to text. If text is "", no title will be displayed.

<a name="-topmargin"></a>
Command-Line Name: **-topmargin**  
Database Name: **topMargin**  
Database Class: **Margin**

> > If non-zero, overrides the computed size of the margin above the x2 axis. If pixels is 0, the automatically computed size is used. The default is 0.

<a name="-topvariable"></a>
Command-Line Name: **-topvariable**  
Database Name: **topVariable**  
Database Class: **TopVariable**

<a name="DESCRIPTION"></a>
## DESCRIPTION 

The graph command creates a new window for plotting two-dimensional data (X-Y coordinates). Data points are plotted in a rectangular area displayed in the center of the new window. This is the plotting area. The coordinate axes are drawn in the margins around the plotting area. By default, the legend is displayed in the right margin. The title is displayed in top margin. They allow you to customize the look and feel of the graph.

The graph widget is composed of several components: coordinate axes, data elements, legend, grid, cross hairs, pens, postscript, and annotation markers.

**axis**
    The graph has four standard axes (x, x2, y, and y2), but you can create and display any number of axes. Axes control what region of data is displayed and how the data is scaled. Each axis consists of the axis line, title, major and minor ticks, and tick labels. Tick labels display the value at each major tick.

**crosshairs**
    Cross hairs are used to position the mouse pointer relative to the X and Y coordinate axes. Two perpendicular lines, intersecting at the current location of the mouse, extend across the plotting area to the coordinate axes.

**element**
    An element represents a set of data points. Elements can be plotted with a symbol at each data point and lines connecting the points. The appearance of the element, such as its symbol, line width, and color is configurable.

**grid**
    Extends the major and minor ticks of the X-axis and/or Y-axis across the plotting area.

**legend**
    The legend displays the name and symbol of each data element. The legend can be drawn in any margin or in the plotting area.

**marker**
    Markers are used annotate or highlight areas of the graph. For example, you could use a polygon marker to fill an area under a curve, or a text marker to label a particular data point. Markers come in various forms: text strings, bitmaps, connected line segments, images, polygons, or embedded widgets.

**pen**
    Pens define attributes (both symbol and line style) for elements. Data elements use pens to specify how they should be drawn. A data element may use many pens at once. Here, the particular pen used for a data point is determined from each element's weight vector (see the element's -weight and -style options).

**postscript**
    The widget can generate encapsulated PostScript output. This component has several options to configure how the PostScript is generated.

<a name="WIDGET-COMMAND"></a>
## WIDGET COMMAND

<a name="pathName-axis"></a>
**pathName axis** *operation ?arg?...*

> See the [AXIS COMPONENT](#AXIS-COMPONENT) section.

<a name="pathName-bar"></a>
**pathName bar** *elemName ?option value?...*

> Creates a new barchart element elemName. It's an error if an element elemName already exists. See the manual for barchart for details about what option and value pairs are valid. TODO

name="pathName-binding"></a>
**pathName binding** *?crosshairs? ?findelement? ?legend? ?zoom?*

The procedure allows the setting of some default bindings. It will add bindings if a name is given and remove bindings if a name is not given.

> If given then the following bindings will be applied:

> *crosshairs*

> > <Any-Motion> will draw crosshairs in the graph window. Leaving the widget will remove the crosshairs.

> *findelement*

> > <Control-ButtonPress-2> This will display informations of the nearest element point.  
> > <Control-Buttonrelease-2> This will remove the displayed informations.  

> *legend* 

> > <Enter> an element will activate the elment entry in the legend window.  
> > <Leave> an element will deactivate the element entry in the legend window.  
> > <ButtonPress-1> will select the element entry in the legend window.  

> *zoom*

> > <ButtonPress-1> Create first and second point of a zooming window. When the second point is created the graph will be zoomed to the new window and the old window will be remembered.  
> > <ButtonPress-3> Undo the last zoom operation.  

<a name="pathName-cget"></a>
**pathName cget** *option*

> Returns the current value of the configuration option given by option. Option may be any option described below for the configure operation.

<a name="pathName-configure"></a>
**pathName configure** *?option value?...*

> Query or modify the configuration options of the widget. If no *option* is specified, returns a list describing all of the available options for pathName (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no *value*, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. *Option* may have any of the values accepted by the **graph** command. 

<a name="pathName-crosshairs"></a>
**pathName crosshairs** *operation ?arg?*

> See the [CROSSHAIRS COMPONENT](#CROSSHAIRS-COMPONENT) section.

<a name="pathName-element"></a>
**pathName element** *operation ?arg?...*

> See the [ELEMENT COMPONENT](#ELEMENT-COMPONENT) section.

<a name="pathName-extents"></a>
**pathName extents** *item*

> Returns the size of a particular item in the graph. Item must be either leftmargin, rightmargin, topmargin, bottommargin, plotwidth, or plotheight.

<a name="pathName-grid"></a>
**pathName grid** *operation ?arg?...*

> See the [GRID COMPONENT](#GRID-COMPONENT) section.

<a name="pathName-invtransform"></a>
**pathName invtransform** *winX winY*

> Performs an inverse coordinate transformation, mapping window coordinates back to graph coordinates, using the standard X-axis and Y-axis. Returns a list of containing the X-Y graph coordinates.

<a name="pathName-inside"></a>
**pathName inside** *x y*

> Returns 1 is the designated screen coordinate (x and y) is inside the plotting area and 0 otherwise.

<a name="pathName-legend"></a>
**pathName legend** *operation ?arg?...*

> See the [LEGEND COMPONENT](#LEGEND-COMPONENT) section.

<a name="pathName-line"></a>
**pathName line** *operation arg...*

> The operation is the same as element.

<a name="pathName-marker"></a>
**pathName marker** *operation ?arg?...*

> See the [MARKER COMPONENT](#MARKER-COMPONENT) section.

<a name="pathName-postscript"></a>
**pathName postscript** *operation ?arg?...*

> See the [POSTSCIPT COMPONENT](#POSTSCRIPT-COMPONENT)section.

<a name="pathName-snap"></a>
**pathName snap** *?switches? outputName*

> Takes a snapshot of the graph, saving the output in outputName. The following switches are available.

> **-format** *format*

> > Specifies how the snapshot is output. Format may be one of the following listed below. The default is photo.

> > **photo**

> > > Saves a Tk photo image. OutputName represents the name of a Tk photo image that must already have been created.

> > **wmf**

> > > Saves an Aldus Placeable Metafile. OutputName represents the filename where the metafile is written. If outputName is CLIPBOARD, then output is written directly to the Windows clipboard. This format is available only under Microsoft Windows.

> > **emf**

> > > Saves an Enhanced Metafile. OutputName represents the filename where the metafile is written. If outputName is CLIPBOARD, then output is written directly to the Windows clipboard. This format is available only under Microsoft Windows.

> **-height** *size*

> > Specifies the height of the graph. Size is a screen distance. The graph will be redrawn using this dimension, rather than its current window height.

> **-width** *size*

> > Specifies the width of the graph. Size is a screen distance. The graph will be redrawn using this dimension, rather than its current window width.

<a name="pathName-transform"></a>
**pathName transform** *x y*

> > Performs a coordinate transformation, mapping graph coordinates to window coordinates, using the standard X-axis and Y-axis. Returns a list containing the X-Y screen coordinates.

<a name="pathName-xaxis"></a>
**pathName xaxis** *operation ?arg?...*

<a name="pathName-x2axis"></a>
**pathName x2axis** *operation ?arg?...*

<a name="pathName-yaxis"></a>
**pathName yaxis** *operation ?arg?...*

<a name="pathName-y2axis"></a>
**pathName y2axis** *operation ?arg?...*

> See the [AXIS COMPONENT](#AXIS-COMPONENT) section.

<a name="AXIS-COMPONENT"></a>
## AXIS COMPONENT

Four coordinate axes are automatically created: two X-coordinate axes (x and x2) and two Y-coordinate axes (y, and y2). By default, the axis x is located in the bottom margin, y in the left margin, x2 in the top margin, and y2 in the right margin.

An axis consists of the axis line, title, major and minor ticks, and tick labels. Major ticks are drawn at uniform intervals along the axis. Each tick is labeled with its coordinate value. Minor ticks are drawn at uniform intervals within major ticks.

The range of the axis controls what region of data is plotted. Data points outside the minimum and maximum limits of the axis are not plotted. By default, the minimum and maximum limits are determined from the data, but you can reset either limit.

You can have several axes. To create an axis, invoke the axis component and its create operation.

> <code>
	# Create a new axis called "tempAxis"  
	.g axis create tempAxis  
</code>

You map data elements to an axis using the element's -mapy and -mapx configuration options. They specify the coordinate axes an element is mapped onto.

> <code>
	# Now map the tempAxis data to this axis.  
	.g element create "e1" -xdata $x -ydata $y -mapy tempAxis  
</code>

Any number of axes can be displayed simultaneously. They are drawn in the margins surrounding the plotting area. The default axes x and y are drawn in the bottom and left margins. The axes x2 and y2 are drawn in top and right margins. By default, only x and y are shown. Note that the axes can have different scales.

To display a different axis or more than one axis, you invoke one of the following components: xaxis, yaxis, x2axis, and y2axis. Each component has a use operation that designates the axis (or axes) to be drawn in that corresponding margin: xaxis in the bottom, yaxis in the left, x2axis in the top, and y2axis in the right.

> <code>
	# Display the axis tempAxis in the left margin.  
	.g yaxis use tempAxis  
</code>

The use operation takes a list of axis names as its last argument. This is the list of axes to be drawn in this margin.

You can configure axes in many ways. The axis scale can be linear or logarithmic. The values along the axis can either monotonically increase or decrease. If you need custom tick labels, you can specify a Tcl procedure to format the label any way you wish. You can control how ticks are drawn, by changing the major tick interval or the number of minor ticks. You can define non-uniform tick intervals, such as for time-series plots.

<a name="pathName-axis-bind"></a>
**pathName axis bind** *tagName ?sequence? ?command?*

> Associates command with tagName such that whenever the event sequence given by sequence occurs for an axis with this tag, command will be invoked. The syntax is similar to the bind command except that it operates on graph axes, rather than widgets. See the bind manual entry for complete details on sequence and the substitutions performed on command before invoking it.

> If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error occurs if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName.

<a name="pathName-axis-cget"></a>
**pathName axis cget** *axisName option*

> Returns the current value of the option given by option for axisName. Option may be any option described below for the axis configure operation.

<a name="pathName-axis-configure"></a>
**pathName axis configure** *axisName ?axisName?... ?option value?...*

> Queries or modifies the configuration options of axisName. Several axes can be changed. If option isn't specified, a list describing all the current options for axisName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the axis option option is set to value. The following options are valid for axes.

> **-bindtags** *tagList*

> > Specifies the binding tags for the axis. TagList is a list of binding tag names. The tags and their order will determine how events for axes are handled. Each tag in the list matching the current event sequence will have its Tcl command executed. Implicitly the name of the element is always the first tag in the list. The default value is all.

> **-color** *color*

> > Sets the color of the axis and tick labels. The default is black.

> **-command** *prefix*

> > Specifies a Tcl command to be invoked when formatting the axis tick labels. Prefix is a string containing the name of a Tcl proc and any extra arguments for the procedure. This command is invoked for each major tick on the axis. Two additional arguments are passed to the procedure: the pathname of the widget and the current the numeric value of the tick. The procedure returns the formatted tick label. If "" is returned, no label will appear next to the tick. You can get the standard tick labels again by setting prefix to "". The default is "".

> > Please note that this procedure is invoked while the graph is redrawn. You may query configuration options. But do not them, because this can have unexpected results.

> **-descending** *boolean*

> > Indicates whether the values along the axis are monotonically increasing or decreasing. If boolean is true, the axis values will be decreasing. The default is 0.

> **-hide** *boolean*

> > Indicates if the axis is displayed. If boolean is false the axis will be displayed. Any element mapped to the axis is displayed regardless. The default value is 0.

> **-justify** *justify*

> > Specifies how the axis title should be justified. This matters only when the axis title contains more than one line of text. Justify must be left, right, or center. The default is center.

> **-limits** *formatStr*

> > Specifies a printf-like description to format the minimum and maximum limits of the axis. The limits are displayed at the top/bottom or left/right sides of the plotting area. FormatStr is a list of one or two format descriptions. If one description is supplied, both the minimum and maximum limits are formatted in the same way. If two, the first designates the format for the minimum limit, the second for the maximum. If "" is given as either description, then the that limit will not be displayed. The default is "".

> **-linewidth** *pixels*

> > Sets the width of the axis and tick lines. The default is 1 pixel.

> **-logscale** *boolean*

> > Indicates whether the scale of the axis is logarithmic or linear. If boolean is true, the axis is logarithmic. The default scale is linear.

> **-loose** *boolean*

> > Indicates whether the limits of the axis should fit the data points tightly, at the outermost data points, or loosely, at the outer tick intervals. If the axis limit is set with the -min or -max option, the axes are displayed tightly. If boolean is true, the axis range is "loose". The default is 0.

> **-majorticks** *majorList*

> > Specifies where to display major axis ticks. You can use this option to display ticks at non-uniform intervals. MajorList is a list of axis coordinates designating the location of major ticks. No minor ticks are drawn. If majorList is "", major ticks will be automatically computed. The default is "".

> **-max** *value*

> > Sets the maximum limit of axisName. Any data point greater than value is not displayed. If value is "", the maximum limit is calculated using the largest data value. The default is "".

> **-min** *value*

> > Sets the minimum limit of axisName. Any data point less than value is not displayed. If value is "", the minimum limit is calculated using the smallest data value. The default is "".

> **-minorticks** *minorList*

> > Specifies where to display minor axis ticks. You can use this option to display minor ticks at non-uniform intervals. MinorList is a list of real values, ranging from 0.0 to 1.0, designating the placement of a minor tick. No minor ticks are drawn if the -majortick option is also set. If minorList is "", minor ticks will be automatically computed. The default is "".

> **-rotate** *theta*

> > Specifies the how many degrees to rotate the axis tick labels. Theta is a real value representing the number of degrees to rotate the tick labels. The default is 0.0 degrees.

> **-scrollcommand** *command*

> > Specify the prefix for a command used to communicate with scrollbars for this axis, such as .sbar set.

> **-scrollmax** *value*

> > Sets the maximum limit of the axis scroll region. If value is "", the maximum limit is calculated using the largest data value. The default is "".

> **-scrollmin** *value*

> > Sets the minimum limit of axis scroll region. If value is "", the minimum limit is calculated using the smallest data value. The default is "".

> **-showticks** *boolean*

> > Indicates whether axis ticks should be drawn. If boolean is true, ticks are drawn. If false, only the axis line is drawn. The default is 1.

> **-stepsize** *value*

> > Specifies the interval between major axis ticks. If value isn't a valid interval (must be less than the axis range), the request is ignored and the step size is automatically calculated.

> **-subdivisions** *number*

> > Indicates how many minor axis ticks are to be drawn. For example, if number is two, only one minor tick is drawn. If number is one, no minor ticks are displayed. The default is 2.

> **-tickfont** *fontName*

> > Specifies the font for axis tick labels. The default is `*-Courier-Bold-R-Normal-*-100-*`.

> **-ticklength** *pixels*

> > Sets the length of major and minor ticks (minor ticks are half the length of major ticks). If pixels is less than zero, the axis will be inverted with ticks drawn pointing towards the plot. The default is 0.1i.

> **-title** *text*

> > Sets the title of the axis. If text is "", no axis title will be displayed.

> **-titlealternate** *boolean*

> > Indicates to display the axis title in its alternate location. Normally the axis title is centered along the axis. This option places the axis either to the right (horizontal axes) or above (vertical axes) the axis. The default is 0.

> **-titlecolor** *color*

> > Sets the color of the axis title. The default is black.

> **-titlefont** *fontName*

> > Specifies the font for axis title. The default is `*-Helvetica-Bold-R-Normal-*-14-140-*`.

Axis configuration options may be also be set by the option command. The resource class is Axis. The resource names are the names of the axes (such as x or x2).

> <code>
        option add *Graph.Axis.Color  blue
        option add *Graph.x.LogScale  true
        option add *Graph.x2.LogScale false
</code>

<a name="pathName-axis-create"></a>
**pathName axis create** *axisName ?option value?...*

> Creates a new axis by the name axisName. No axis by the same name can already exist. Option and value are described in above in the axis configure operation.

<a name="pathName-axis-delete"></a>
**pathName axis delete** *?axisName?...*

> Deletes the named axes. An axis is not really deleted until it is not longer in use, so it's safe to delete axes mapped to elements.

<a name="pathName-axis-invtransform"></a>
**pathName axis invtransform** *axisName value*

> Performs the inverse transformation, changing the screen coordinate value to a graph coordinate, mapping the value mapped to axisName. Returns the graph coordinate.

<a name="pathName-axis-limits"></a>
**pathName axis limits** *axisName*

> Returns a list of the minimum and maximum limits for axisName. The order of the list is min max.

<a name="pathName-axis-names"></a>
**pathName axis names** *?pattern?...*

> Returns a list of axes matching zero or more patterns. If no pattern argument is give, the names of all axes are returned.

<a name="pathName-axis-transform"></a>
**pathName axis transform** *axisName value*

> Transforms the coordinate value to a screen coordinate by mapping the it to axisName. Returns the transformed screen coordinate.

<a name="pathName-axis-view"></a>
**pathName axis view** *axisName*

> Change the viewable area of this axis. Use as an argument to a scrollbar's "-command".

The default axes are x, y, x2, and y2. But you can display more than four axes simultaneously. You can also swap in a different axis with use operation of the special axis components: xaxis, x2axis, yaxis, and y2axis.

> <code>
	.g create axis temp  
	.g create axis time  
	...  
	.g xaxis use temp  
	.g yaxis use time  
</code>

Only the axes specified for use are displayed on the screen.

The xaxis, x2axis, yaxis, and y2axis components operate on an axis location rather than a specific axis like the more general axis component does. They implicitly control the axis that is currently using to that location. By default, xaxis uses the x axis, yaxis uses y, x2axis uses x2, and y2axis uses y2. When more than one axis is displayed in a margin, it represents the first axis displayed.

<a name="CROSSHAIRS-COMPONENT"></a>
## CROSSHAIRS COMPONENT

Cross hairs consist of two intersecting lines (one vertical and one horizontal) drawn completely across the plotting area. They are used to position the mouse in relation to the coordinate axes. Cross hairs differ from line markers in that they are implemented using XOR drawing primitives. This means that they can be quickly drawn and erased without redrawing the entire graph.

The following operations are available for cross hairs:

<a name="pathName-crosshairs-cget"></a>
**pathName crosshairs cget** *option*

> Returns the current value of the cross hairs configuration option given by option. Option may be any option described below for the cross hairs configure operation.

<a name="pathName-crosshairs-configure"></a>
**pathName crosshairs configure** *?option value?...*

> Queries or modifies the configuration options of the cross hairs. If option isn't specified, a list describing all the current options for the cross hairs is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the cross hairs option option is set to value. The following options are available for cross hairs.

> **-color** *color*

> > Sets the color of the cross hairs. The default is black.

> **-dashes** *dashList*

> > Sets the dash style of the cross hairs. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the cross hair lines. Each number must be between 1 and 255. If dashList is "", the cross hairs will be solid lines.

> **-hide** *boolean*

> > Indicates whether cross hairs are drawn. If boolean is true, cross hairs are not drawn. The default is yes.

> **-linewidth** *pixels*

> > Set the width of the cross hair lines. The default is 1.

> **-position** *pos*

> > Specifies the screen position where the cross hairs intersect. Pos must be in the form "@x,y", where x and y are the window coordinates of the intersection.

> Cross hairs configuration options may be also be set by the option command. The resource name and class are crosshairs and Crosshairs respectively.

> > <code>
        option add *Graph.Crosshairs.LineWidth 2  
        option add *Graph.Crosshairs.Color     red  
</code>

<a name="pathName-crosshairs-off"></a>
**pathName crosshairs off**

> Turns off the cross hairs.

<a name="pathName-crosshairs-on"></a>
**pathName crosshairs on**

> Turns on the display of the cross hairs.

<a name="pathName-crosshairs-toggle"></a>
**pathName crosshairs toggle**

> Toggles the current state of the cross hairs, alternately mapping and unmapping the cross hairs.

<a name="ELEMENT-COMPONENT"></a>
## ELEMENT COMPONENT

A data element represents a set of data. It contains x and y vectors containing the coordinates of the data points. Elements can be displayed with a symbol at each data point and lines connecting the points. Elements also control the appearance of the data, such as the symbol type, line width, color etc.

When new data elements are created, they are automatically added to a list of displayed elements. The display list controls what elements are drawn and in what order.

The following operations are available for elements.

<a name="pathName-element-activate"></a>
**pathName element activate** *elemName ?index?...*

> Specifies the data points of element elemName to be drawn using active foreground and background colors. ElemName is the name of the element and index is a number representing the index of the data point. If no indices are present then all data points become active.

<a name="pathName-element-bind"></a>
**pathName element bind** *tagName ?sequence? ?command?*

> Associates command with tagName such that whenever the event sequence given by sequence occurs for an element with this tag, command will be invoked. The syntax is similar to the bind command except that it operates on graph elements, rather than widgets. See the bind manual entry for complete details on sequence and the substitutions performed on command before invoking it.

> If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error occurs if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName.

<a name="pathName-element-cget"></a>
**pathName element cget** *elemName option*

> Returns the current value of the element configuration option given by option. Option may be any of the options described below for the element configure operation.

<a name="pathName-element-closest"></a>
**pathName element closest** *x y varName ?option value?... ?elemName?...*

> Searches for the data point closest to the window coordinates x and y. By default, all elements are searched. Hidden elements (see the -hide option is false) are ignored. You can limit the search by specifying only the elements you want to be considered. ElemName must be the name of an element that is not be hidden. VarName is the name of a Tcl array variable and will contain the search results: the name of the closest element, the index of the closest data point, and the graph coordinates of the point. Returns 0, if no data point within the threshold distance can be found, otherwise 1 is returned. The following option-value pairs are available.

> **-along** *direction*

> > Search for the closest element using the following criteria:

> > *x*

> > > Find closest element vertically from the given X-coordinate.

> > *y*

> > > Find the closest element horizontally from the given Y-coordinate.

> > *both*

> > > Find the closest element for the given point (using both the X and Y coordinates).

> **-halo** *pixels*

> > Specifies a threshold distance where selected data points are ignored. Pixels is a valid screen distance, such as 2 or 1.2i. If this option isn't specified, then it defaults to the value of the graph's -halo option.

> **-interpolate** *string*

> > Indicates whether to consider projections that lie along the line segments connecting data points when searching for the closest point. The default value is 0. The values for string are described below.

> > *no*

> > > Search only for the closest data point.

> > *yes*

> > > Search includes projections that lie along the line segments connecting the data points.

<a name="pathName-element-configure"></a>
**pathName element configure** *elemName ?elemName... ?option value?...*

> Queries or modifies the configuration options for elements. Several elements can be modified at the same time. If option isn't specified, a list describing all the current options for elemName is returned. If option is specified, but not value, then a list describing the option option is returned. If one or more option and value pairs are specified, then for each pair, the element option option is set to value. The following options are valid for elements.

> **-activepen** *penName*

> > Specifies pen to use to draw active element. If penName is "", no active elements will be drawn. The default is activeLine.

> **-bindtags** *tagList*

> > Specifies the binding tags for the element. TagList is a list of binding tag names. The tags and their order will determine how events are handled for elements. Each tag in the list matching the current event sequence will have its Tcl command executed. Implicitly the name of the element is always the first tag in the list. The default value is all.

> **-color** *color*

> > Sets the color of the traces connecting the data points.

> **-dashes** *dashList*

> > Sets the dash style of element line. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the element line. Each number must be between 1 and 255. If dashList is "", the lines will be solid.

> **-data** *coordList*

> > Specifies the X-Y coordinates of the data. CoordList is a list of numeric expressions representing the X-Y coordinate pairs of each data point.

> **-fill** *color*

> > Sets the interior color of symbols. If color is "", then the interior of the symbol is transparent. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-hide** *boolean*

> > Indicates whether the element is displayed. The default is no.

> **-label** *text*

> > Sets the element's label in the legend. If text is "", the element will have no entry in the legend. The default label is the element's name.

> **-linewidth** *pixels*

> > Sets the width of the connecting lines between data points. If pixels is 0, no connecting lines will be drawn between symbols. The default is 0.

> **-mapx** *xAxis*

> > Selects the X-axis to map the element's X-coordinates onto. XAxis must be the name of an axis. The default is x.

> **-mapy** *yAxis*

> > Selects the Y-axis to map the element's Y-coordinates onto. YAxis must be the name of an axis. The default is y.

> **-offdash** *color*

> > Sets the color of the stripes when traces are dashed (see the -dashes option). If color is "", then the "off" pixels will represent gaps instead of stripes. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-outline** *color*

> > Sets the color or the outline around each symbol. If color is "", then no outline is drawn. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-pen** *penname*

> > Set the pen to use for this element.

> **-outlinewidth** *pixels*

> > Sets the width of the outline bordering each symbol. If pixels is 0, no outline will be drawn. The default is 1.

> **-pixels** *pixels*

> > Sets the size of symbols. If pixels is 0, no symbols will be drawn. The default is 0.125i.

> **-scalesymbols** *boolean*

> > If boolean is true, the size of the symbols drawn for elemName will change with scale of the X-axis and Y-axis. At the time this option is set, the current ranges of the axes are saved as the normalized scales (i.e scale factor is 1.0) and the element is drawn at its designated size (see the -pixels option). As the scale of the axes change, the symbol will be scaled according to the smaller of the X-axis and Y-axis scales. If boolean is false, the element's symbols are drawn at the designated size, regardless of axis scales. The default is 0.

> **-smooth** *smooth*

> > Specifies how connecting line segments are drawn between data points. Smooth can be either linear, step, natural, or quadratic. If smooth is linear, a single line segment is drawn, connecting both data points. When smooth is step, two line segments are drawn. The first is a horizontal line segment that steps the next X-coordinate. The second is a vertical line, moving to the next Y-coordinate. Both natural and quadratic generate multiple segments between data points. If natural, the segments are generated using a cubic spline. If quadratic, a quadratic spline is used. The default is linear.

> **-styles** *styleList*

> > Specifies what pen to use based on the range of weights given. StyleList is a list of style specifications. Each style specification, in turn, is a list consisting of a pen name, and optionally a minimum and maximum range. Data points whose weight (see the -weight option) falls in this range, are drawn with this pen. If no range is specified it defaults to the index of the pen in the list. Note that this affects only symbol attributes. Line attributes, such as line width, dashes, etc. are ignored.

> **-symbol** *symbol*

> > Specifies the symbol for data points. Symbol can be either square, circle, diamond, plus, cross, splus, scross, triangle, "" (where no symbol is drawn), or a bitmap. Bitmaps are specified as "source ?mask?", where source is the name of the bitmap, and mask is the bitmap's optional mask. The default is circle.

> **-trace** *direction*

> > Indicates whether connecting lines between data points (whose X-coordinate values are either increasing or decreasing) are drawn. Direction must be increasing, decreasing, or both. For example, if direction is increasing, connecting lines will be drawn only between those data points where X-coordinate values are monotonically increasing. If direction is both, connecting lines will be draw between all data points. The default is both.

> **-weights** *wVec*

> > Specifies the weights of the individual data points. This, with the list pen styles (see the -styles option), controls how data points are drawn. WVec is the name of a graph vector or a list of numeric expressions representing the weights for each data point.

> **-xdata** *xVec*

> > Specifies the X-coordinates of the data. XVec is the name of a graph vector or a list of numeric expressions.

> **-ydata** *yVec*

> > Specifies the Y-coordinates of the data. YVec is the name of a graph vector or a list of numeric expressions.

> Element configuration options may also be set by the option command. The resource class is Element. The resource name is the name of the element.

> > <code>
        option add *Graph.Element.symbol line  
        option add *Graph.e1.symbol line  
</code>

<a name="pathName-element-create"></a>
**pathName element create** *elemName ?option value?...*

> Creates a new element elemName. It's an error is an element elemName already exists. If additional arguments are present, they specify options valid for the element configure operation.

<a name="pathName-element-deactivate"></a>
**pathName element deactivate** *elemName ?elemName?...*

> Deactivates all the elements matching pattern. Elements whose names match any of the patterns given are redrawn using their normal colors.

<a name="pathName-element-delete"></a>
**pathName element delete** *?elemName?...*

> Deletes all the named elements. The graph is automatically redrawn.

<a name="pathName-element-exists"></a>
**pathName element exists** *elemName*

> Returns 1 if an element elemName currently exists and 0 otherwise.

<a name="pathName-element-names"></a>
**pathName element names** *?pattern?...*

> Returns the elements matching one or more pattern. If no pattern is given, the names of all elements is returned.

<a name="pathName-element-show"></a>
**pathName element show** *?nameList?*

> Queries or modifies the element display list. The element display list designates the elements drawn and in what order. NameList is a list of elements to be displayed in the order they are named. If there is no nameList argument, the current display list is returned.

<a name="pathName-element-type"></a>
**pathName element type** *elemName*

> Returns the type of elemName. If the element is a bar element, the commands returns the string "bar", otherwise it returns "line".

<a name="GRID-COMPONENT"></a>
## GRID COMPONENT

Grid lines extend from the major and minor ticks of each axis horizontally or vertically across the plotting area. The following operations are available for grid lines.

<a name="pathName-grid-cget"></a>
**pathName grid cget** *option*

> Returns the current value of the grid line configuration option given by option. Option may be any option described below for the grid configure operation.

<a name="pathName-grid-configure"></a>
**pathName grid configure** *?option value?...*

> Queries or modifies the configuration options for grid lines. If option isn't specified, a list describing all the current grid options for pathName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the grid line option option is set to value. The following options are valid for grid lines.

> **-color** *color*

> > Sets the color of the grid lines. The default is black.

> **-dashes** *dashList*

> > Sets the dash style of the grid lines. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the grid lines. Each number must be between 1 and 255. If dashList is "", the grid will be solid lines.

> **-hide** *boolean*

> > Indicates whether the grid should be drawn. If boolean is true, grid lines are not shown. The default is yes.

> **-linewidth** *pixels*

> > Sets the width of grid lines. The default width is 1.

> **-mapx** *xAxis*

> > Specifies the X-axis to display grid lines. XAxis must be the name of an axis or "" for no grid lines. The default is "".

> **-mapy** *yAxis*

> > Specifies the Y-axis to display grid lines. YAxis must be the name of an axis or "" for no grid lines. The default is y.

> **-minor** *boolean*

> > Indicates whether the grid lines should be drawn for minor ticks. If boolean is true, the lines will appear at minor tick intervals. The default is 1.

> **-raised** *boolean*

> > Grid is to be raised or drawn over elements.

> Grid configuration options may also be set by the option command. The resource name and class are grid and Grid respectively.

> > <code>
        option add *Graph.grid.LineWidth 2  
        option add *Graph.Grid.Color     black  
</code>

<a name="pathName-grid-off"></a>
**pathName grid off**

> Turns off the display the grid lines.

<a name="pathName-grid-on"></a>
**pathName grid on**

> Turns on the display the grid lines.

<a name="pathName-grid-toggle"></a>
**pathName grid toggle**

> Toggles the display of the grid.

<a name="LEGEND-COMPONENT"></a>
## LEGEND COMPONENT

The legend displays a list of the data elements. Each entry consists of the element's symbol and label. The legend can appear in any margin (the default location is in the right margin). It can also be positioned anywhere within the plotting area.

The following operations are valid for the legend.

<a name="pathName-legend-activate"></a>
**pathName legend activate** *pattern...*

> Selects legend entries to be drawn using the active legend colors and relief. All entries whose element names match pattern are selected. To be selected, the element name must match only one pattern.

<a name="pathName-legend-bind"></a>
**pathName legend bind** *tagName ?sequence? ?command?*

> Associates command with tagName such that whenever the event sequence given by sequence occurs for a legend entry with this tag, command will be invoked. Implicitly the element names in the entry are tags. The syntax is similar to the bind command except that it operates on legend entries, rather than widgets. See the bind manual entry for complete details on sequence and the substitutions performed on command before invoking it.

> If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error occurs if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName.

<a name="pathName-legend-cget"></a>
**pathName legend cget** *option*

> Returns the current value of a legend configuration option. Option may be any option described below in the legend configure operation.

<a name="pathName-legend-configure"></a>
**pathName legend configure** *?option value?...*

> Queries or modifies the configuration options for the legend. If option isn't specified, a list describing the current legend options for pathName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the legend option option is set to value. The following options are valid for the legend.

> **-activebackground** *color*

> > Sets the background color for active legend entries. All legend entries marked active (see the legend activate operation) are drawn using this background color.

> **-activeborderwidth** *pixels*

> > Sets the width of the 3-D border around the outside edge of the active legend entries. The default is 2.

> **-activeforeground** *color*

> > Sets the foreground color for active legend entries. All legend entries marked as active (see the legend activate operation) are drawn using this foreground color.

> **-activerelief** *relief*

> > Specifies the 3-D effect desired for active legend entries. Relief denotes how the interior of the entry should appear relative to the legend; for example, raised means the entry should appear to protrude from the legend, relative to the surface of the legend. The default is flat.

> **-anchor** *anchor*

> > Tells how to position the legend relative to the positioning point for the legend. This is dependent on the value of the -position option. The default is center.

> > *left* or *right*

> > > The anchor describes how to position the legend vertically.

> > *top* or *bottom*

> > > The anchor describes how to position the legend horizontally.

> > *@x,y*

> > > The anchor specifies how to position the legend relative to the positioning point. For example, if anchor is center then the legend is centered on the point; if anchor is n then the legend will be drawn such that the top center point of the rectangular region occupied by the legend will be at the positioning point.

> > *plotarea*

> > > The anchor specifies how to position the legend relative to the plotting area. For example, if anchor is center then the legend is centered in the plotting area; if anchor is ne then the legend will be drawn such that occupies the upper right corner of the plotting area.

> **-background** *color*

> > Sets the background color of the legend. If color is "", the legend background with be transparent.

> **-bindtags** *tagList*

> > Specifies the binding tags for legend entries. TagList is a list of binding tag names. The tags and their order will determine how events are handled for legend entries. Each tag in the list matching the current event sequence will have its Tcl command executed. The default value is all.

> **-borderwidth** *pixels*

> > Sets the width of the 3-D border around the outside edge of the legend (if such border is being drawn; the relief option determines this). The default is 2 pixels.

> **-font** *fontName*

> > FontName specifies a font to use when drawing the labels of each element into the legend. The default is `*-Helvetica-Bold-R-Normal-*-12-120-*`.

> **-foreground** *color*

> > Sets the foreground color of the text drawn for the element's label. The default is black.

> **-hide** *boolean*

> > Indicates whether the legend should be displayed. If boolean is true, the legend will not be draw. The default is no.

> **-ipadx** *pad*

> > Sets the amount of internal padding to be added to the width of each legend entry. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the legend entry is padded by the first distance and the right side by the second. If pad is just one distance, both the left and right sides are padded evenly. The default is 2.

> **-ipady** *pad*

> > Sets an amount of internal padding to be added to the height of each legend entry. Pad can be a list of one or two screen distances. If pad has two elements, the top of the entry is padded by the first distance and the bottom by the second. If pad is just one distance, both the top and bottom of the entry are padded evenly. The default is 2.

> **-padx** *pad*

> > Sets the padding to the left and right exteriors of the legend. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the legend is padded by the first distance and the right side by the second. If pad has just one distance, both the left and right sides are padded evenly. The default is 4.

> **-pady** *pad*

> > Sets the padding above and below the legend. Pad can be a list of one or two screen distances. If pad has two elements, the area above the legend is padded by the first distance and the area below by the second. If pad is just one distance, both the top and bottom areas are padded evenly. The default is 0.

> **-position** *pos*

> > Specifies where the legend is drawn. The -anchor option also affects where the legend is positioned. If pos is left, left, top, or bottom, the legend is drawn in the specified margin. If pos is plotarea, then the legend is drawn inside the plotting area at a particular anchor. If pos is in the form "@x,y", where x and y are the window coordinates, the legend is drawn in the plotting area at the specified coordinates. The default is right.

> **-raised** *boolean*

> > Indicates whether the legend is above or below the data elements. This matters only if the legend is in the plotting area. If boolean is true, the legend will be drawn on top of any elements that may overlap it. The default is no.

> **-relief** *relief*

> > Specifies the 3-D effect for the border around the legend. Relief specifies how the interior of the legend should appear relative to the graph; for example, raised means the legend should appear to protrude from the graph, relative to the surface of the graph. The default is sunken.

> Legend configuration options may also be set by the option command. The resource name and class are legend and Legend respectively.

> > <code>
        option add *Graph.legend.Foreground blue  
        option add *Graph.Legend.Relief     raised  
</code>

<a name="pathName-legend-deactivate"></a>
**pathName legend deactivate** *pattern...*

> Selects legend entries to be drawn using the normal legend colors and relief. All entries whose element names match pattern are selected. To be selected, the element name must match only one pattern.

<a name="pathName-legend-get"></a>
**pathName legend get** *pos*

> Returns the name of the element whose entry is at the screen position pos in the legend. Pos must be in the form "@x,y", where x and y are window coordinates. If the given coordinates do not lie over a legend entry, "" is returned.

<a name="PEN-COMPONENT"></a>
## PEN COMPONENT

Pens define attributes (both symbol and line style) for elements. Pens mirror the configuration options of data elements that pertain to how symbols and lines are drawn. Data elements use pens to determine how they are drawn. A data element may use several pens at once. In this case, the pen used for a particular data point is determined from each element's weight vector (see the element's -weight and -style options).

One pen, called activeLine, is automatically created. It's used as the default active pen for elements. So you can change the active attributes for all elements by simply reconfiguring this pen.

> <code>
	.g pen configure "activeLine" -color green  
</code>

You can create and use several pens. To create a pen, invoke the pen component and its create operation.

> <code>
	.g pen create myPen  
</code>

You map pens to a data element using either the element's -pen or -activepen options.

> <code>
	.g element create "line1" -xdata $x -ydata $tempData -pen myPen  
</code>

An element can use several pens at once. This is done by specifying the name of the pen in the element's style list (see the -styles option).

> <code>
	.g element configure "line1" -styles { myPen 2.0 3.0 }  
</code>

This says that any data point with a weight between 2.0 and 3.0 is to be drawn using the pen myPen. All other points are drawn with the element's default attributes.

The following operations are available for pen components.

<a name="pathName-pen-cget"></a>
**pathName pen cget** *penName option*

> Returns the current value of the option given by option for penName. Option may be any option described below for the pen configure operation.

<a name="pathName-pen-configure"></a>
**pathName pen configure** *penName ?penName... ?option value?...*

> Queries or modifies the configuration options of penName. Several pens can be modified at once. If option isn't specified, a list describing the current options for penName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the pen option option is set to value. The following options are valid for pens.

> **-color** *color*

> > Sets the color of the traces connecting the data points.

> **-dashes** *dashList*

> > Sets the dash style of element line. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the element line. Each number must be between 1 and 255. If dashList is "", the lines will be solid.

> **-fill** *color*

> > Sets the interior color of symbols. If color is "", then the interior of the symbol is transparent. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-linewidth** *pixels*

> > Sets the width of the connecting lines between data points. If pixels is 0, no connecting lines will be drawn between symbols. The default is 0.

> **-offdash** *color*

> > Sets the color of the stripes when traces are dashed (see the -dashes option). If color is "", then the "off" pixels will represent gaps instead of stripes. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-outline** *color*

> > Sets the color or the outline around each symbol. If color is "", then no outline is drawn. If color is defcolor, then the color will be the same as the -color option. The default is defcolor.

> **-outlinewidth** *pixels*

> > Sets the width of the outline bordering each symbol. If pixels is 0, no outline will be drawn. The default is 1.

> **-pixels** *pixels*

> > Sets the size of symbols. If pixels is 0, no symbols will be drawn. The default is 0.125i.

> **-symbol** *symbol*

> Specifies the symbol for data points. Symbol can be either square, circle, diamond, plus, cross, splus, scross, triangle, "" (where no symbol is drawn), or a bitmap. Bitmaps are specified as "source ?mask?", where source is the name of the bitmap, and mask is the bitmap's optional mask. The default is circle.

> **-type** *elemType*

> > Specifies the type of element the pen is to be used with. This option should only be employed when creating the pen. This is for those that wish to mix different types of elements (bars and lines) on the same graph. The default type is "line".

> Pen configuration options may be also be set by the option command. The resource class is Pen. The resource names are the names of the pens.

> > <code>
        option add *Graph.Pen.Color  blue  
        option add *Graph.activeLine.color  green  
</code>

<a name="pathName-pen-create"></a>
**pathName pen create** *penName ?option value?...*

> Creates a new pen by the name penName. No pen by the same name can already exist. Option and value are described in above in the pen configure operation.

<a name="pathName-pen-delete"></a>
**pathName pen delete** *?penName?...*

> Deletes the named pens. A pen is not really deleted until it is not longer in use, so it's safe to delete pens mapped to elements.

<a name="pathName-pen-names"></a>
**pathName pen names** *?pattern?...*

> Returns a list of pens matching zero or more patterns. If no pattern argument is give, the names of all pens are returned.

<a name="POSTSCRIPT-COMPONENT"></a>
## POSTSCRIPT COMPONENT

The graph can generate encapsulated PostScript output. There are several configuration options you can specify to control how the plot will be generated. You can change the page dimensions and borders. The plot itself can be scaled, centered, or rotated to landscape. The PostScript output can be written directly to a file or returned through the interpreter.

The following postscript operations are available.

<a name="pathName-postscript-cget"></a>
**pathName postscript cget** *option*

> Returns the current value of the postscript option given by option. Option may be any option described below for the postscript configure operation.

<a name="pathName-postscript-configure"></a>
**pathName postscript configure** *?option value?...*

> Queries or modifies the configuration options for PostScript generation. If option isn't specified, a list describing the current postscript options for pathName is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the postscript option option is set to value. The following postscript options are available.

> **-center** *boolean*

> > Indicates whether the plot should be centered on the PostScript page. If boolean is false, the plot will be placed in the upper left corner of the page. The default is 1.

> **-colormap** *varName*

> > VarName must be the name of a global array variable that specifies a color mapping from the X color name to PostScript. Each element of varName must consist of PostScript code to set a particular color value (e.g. ``1.0 1.0 0.0 setrgbcolor''). When generating color information in PostScript, the array variable varName is checked if an element of the name as the color exists. If so, it uses its value as the PostScript command to set the color. If this option hasn't been specified, or if there isn't an entry in varName for a given color, then it uses the red, green, and blue intensities from the X color.

> **-colormode** *mode*

> > Specifies how to output color information. Mode must be either color (for full color output), gray (convert all colors to their gray-scale equivalents) or mono (convert foreground colors to black and background colors to white). The default mode is color.

> **-fontmap** *varName*

> > VarName must be the name of a global array variable that specifies a font mapping from the X font name to PostScript. Each element of varName must consist of a Tcl list with one or two elements; the name and point size of a PostScript font. When outputting PostScript commands for a particular font, the array variable varName is checked to see if an element by the specified font exists. If there is such an element, then the font information contained in that element is used in the PostScript output. (If the point size is omitted from the list, the point size of the X font is used). Otherwise the X font is examined in an attempt to guess what PostScript font to use. This works only for fonts whose foundry property is Adobe (such as Times, Helvetica, Courier, etc.). If all of this fails then the font defaults to Helvetica-Bold.

> **-decorations** *boolean*

> > Indicates whether PostScript commands to generate color backgrounds and 3-D borders will be output. If boolean is false, the background will be white and no 3-D borders will be generated. The default is 1.

> **-height** *pixels*

> > Sets the height of the plot. This lets you print the graph with a height different from the one drawn on the screen. If pixels is 0, the height is the same as the widget's height. The default is 0.

> **-landscape** *boolean*

> > If boolean is true, this specifies the printed area is to be rotated 90 degrees. In non-rotated output the X-axis of the printed area runs along the short dimension of the page (``portrait'' orientation); in rotated output the X-axis runs along the long dimension of the page (``landscape'' orientation). Defaults to 0.

> **-maxpect** *boolean*

> > Indicates to scale the plot so that it fills the PostScript page. The aspect ratio of the graph is still retained. The default is 0.

> **-padx** *pad*

> > Sets the horizontal padding for the left and right page borders. The borders are exterior to the plot. Pad can be a list of one or two screen distances. If pad has two elements, the left border is padded by the first distance and the right border by the second. If pad has just one distance, both the left and right borders are padded evenly. The default is 1i.

> **-pady** *pad*

> > Sets the vertical padding for the top and bottom page borders. The borders are exterior to the plot. Pad can be a list of one or two screen distances. If pad has two elements, the top border is padded by the first distance and the bottom border by the second. If pad has just one distance, both the top and bottom borders are padded evenly. The default is 1i.

> **-paperheight** *pixels*

> > Sets the height of the postscript page. This can be used to select between different page sizes (letter, A4, etc). The default height is 11.0i.

> **-paperwidth** *pixels*

> > Sets the width of the postscript page. This can be used to select between different page sizes (letter, A4, etc). The default width is 8.5i.

> **-width** *pixels*

> > Sets the width of the plot. This lets you generate a plot of a width different from that of the widget. If pixels is 0, the width is the same as the widget's width. The default is 0.

> Postscript configuration options may be also be set by the option command. The resource name and class are postscript and Postscript respectively.

> > <code>
        option add *Graph.postscript.Decorations false  
        option add *Graph.Postscript.Landscape   true  
</code>

<a name="pathName-postscript-output"></a>
**pathName postscript output** *?fileName? ?option value?...*

> Outputs a file of encapsulated PostScript. If a fileName argument isn't present, the command returns the PostScript. If any option-value pairs are present, they set configuration options controlling how the PostScript is generated. Option and value can be anything accepted by the postscript configure operation above.

<a name="MARKER-COMPONENT"></a>
## MARKER COMPONENT

Markers are simple drawing procedures used to annotate or highlight areas of the graph. Markers have various types: text strings, bitmaps, images, connected lines, windows, or polygons. They can be associated with a particular element, so that when the element is hidden or un-hidden, so is the marker. By default, markers are the last items drawn, so that data elements will appear in behind them. You can change this by configuring the -under option.

Markers, in contrast to elements, don't affect the scaling of the coordinate axes. They can also have elastic coordinates (specified by -Inf and Inf respectively) that translate into the minimum or maximum limit of the axis. For example, you can place a marker so it always remains in the lower left corner of the plotting area, by using the coordinates -Inf,-Inf.

The following operations are available for markers.

<a name="pathName-marker-after"></a>
**pathName marker after markerId ?afterId?
    Changes the order of the markers, drawing the first marker after the second. If no second afterId argument is specified, the marker is placed at the end of the display list. This command can be used to control how markers are displayed since markers are drawn in the order of this display list.

<a name="pathName-marker-before"></a>
**pathName marker before** *markerId ?beforeId?*

> Changes the order of the markers, drawing the first marker before the second. If no second beforeId argument is specified, the marker is placed at the beginning of the display list. This command can be used to control how markers are displayed since markers are drawn in the order of this display list.

<a name="pathName-marker-bind"></a>
**pathName marker bind** *tagName ?sequence? ?command?*

> Associates command with tagName such that whenever the event sequence given by sequence occurs for a marker with this tag, command will be invoked. The syntax is similar to the bind command except that it operates on graph markers, rather than widgets. See the bind manual entry for complete details on sequence and the substitutions performed on command before invoking it.

> If all arguments are specified then a new binding is created, replacing any existing binding for the same sequence and tagName. If the first character of command is + then command augments an existing binding rather than replacing it. If no command argument is provided then the command currently associated with tagName and sequence (it's an error occurs if there's no such binding) is returned. If both command and sequence are missing then a list of all the event sequences for which bindings have been defined for tagName.

<a name="pathName-marker-cget"></a>
**pathName marker cget** *option*

> Returns the current value of the marker configuration option given by option. Option may be any option described below in the configure operation.

<a name="pathName-marker-configure"></a>
**pathName marker configure** *markerId ?option value?...*

> Queries or modifies the configuration options for markers. If option isn't specified, a list describing the current options for markerId is returned. If option is specified, but not value, then a list describing option is returned. If one or more option and value pairs are specified, then for each pair, the marker option option is set to value.

> The following options are valid for all markers. Each type of marker also has its own type-specific options. They are described in the sections below.

> **-bindtags** *tagList*

> > Specifies the binding tags for the marker. TagList is a list of binding tag names. The tags and their order will determine how events for markers are handled. Each tag in the list matching the current event sequence will have its Tcl command executed. Implicitly the name of the marker is always the first tag in the list. The default value is all.

> **-coords** *coordList*

> > Specifies the coordinates of the marker. CoordList is a list of graph coordinates. The number of coordinates required is dependent on the type of marker. Text, image, and window markers need only two coordinates (an X-Y coordinate). Bitmap markers can take either two or four coordinates (if four, they represent the corners of the bitmap). Line markers need at least four coordinates, polygons at least six. If coordList is "", the marker will not be displayed. The default is "".

> **-element** *elemName*

> > Links the marker with the element elemName. The marker is drawn only if the element is also currently displayed (see the element's show operation). If elemName is "", the marker is always drawn. The default is "".

> **-hide** *boolean*

> > Indicates whether the marker is drawn. If boolean is true, the marker is not drawn. The default is no.

> **-mapx** *xAxis*

> > Specifies the X-axis to map the marker's X-coordinates onto. XAxis must the name of an axis. The default is x.

> **-mapy** *yAxis*

> > Specifies the Y-axis to map the marker's Y-coordinates onto. YAxis must the name of an axis. The default is y.

> **-name** *markerId*

> > Changes the identifier for the marker. The identifier markerId can not already be used by another marker. If this option isn't specified, the marker's name is uniquely generated.

> **-under** *boolean*

> > Indicates whether the marker is drawn below/above data elements. If boolean is true, the marker is be drawn underneath the data element symbols and lines. Otherwise, the marker is drawn on top of the element. The default is 0.

> **-xoffset** *pixels*

> > Specifies a screen distance to offset the marker horizontally. Pixels is a valid screen distance, such as 2 or 1.2i. The default is 0.

> **-yoffset** *pixels*

> > Specifies a screen distance to offset the markers vertically. Pixels is a valid screen distance, such as 2 or 1.2i. The default is 0.

> Marker configuration options may also be set by the option command. The resource class is either BitmapMarker, ImageMarker, LineMarker, PolygonMarker, TextMarker, or WindowMarker, depending on the type of marker. The resource name is the name of the marker.

> > <code>
        option add *Graph.TextMarker.Foreground white  
        option add *Graph.BitmapMarker.Foreground white  
        option add *Graph.m1.Background     blue  
</code>

<a name="pathName-marker-create"></a>
**pathName marker create** *type ?option value?...*

> Creates a marker of the selected type. Type may be either text, line, bitmap, image, polygon, or window. This command returns the marker identifier, used as the markerId argument in the other marker-related commands. If the -name option is used, this overrides the normal marker identifier. If the name provided is already used for another marker, the new marker will replace the old.

<a name="pathName-marker-delete"></a>
**pathName marker delete** *?name?...*

> Removes one of more markers. The graph will automatically be redrawn without the marker.

<a name="pathName-marker-exists"></a>
**pathName marker exists** *markerId*

> Returns 1 if the marker markerId exists and 0 otherwise.

<a name="pathName-marker-names"></a>
**pathName marker names** *?pattern?*

> Returns the names of all the markers that currently exist. If pattern is supplied, only those markers whose names match it will be returned.

<a name="pathName-marker-type"></a>
**pathName marker type** *markerId*

> Returns the type of the marker given by markerId, such as line or text. If markerId is not a valid a marker identifier, "" is returned.

<a name="BITMAP-MARKERS"></a>
### BITMAP MARKERS

A bitmap marker displays a bitmap. The size of the bitmap is controlled by the number of coordinates specified. If two coordinates, they specify the position of the top-left corner of the bitmap. The bitmap retains its normal width and height. If four coordinates, the first and second pairs of coordinates represent the corners of the bitmap. The bitmap will be stretched or reduced as necessary to fit into the bounding rectangle.

Bitmap markers are created with the marker's create operation in the form:

<a name="pathName-marker-create-bitmap"></a>
**pathName marker create bitmap** *?option value?...*

There may be many option-value pairs, each sets a configuration options for the marker. These same option-value pairs may be used with the marker's configure operation.

The following options are specific to bitmap markers:

> **-background** *color*

> > Same as the -fill option.

> **-bitmap** *bitmap*

> > Specifies the bitmap to be displayed. If bitmap is "", the marker will not be displayed. The default is "".

> **-fill** *color*

> > Sets the background color of the bitmap. If color is the empty string, no background will be transparent. The default background color is "".

> **-foreground** *color*

> > Same as the -outline option.

> **-mask** *mask*

> > Specifies a mask for the bitmap to be displayed. This mask is a bitmap itself, denoting the pixels that are transparent. If mask is "", all pixels of the bitmap will be drawn. The default is "".

> **-outline** *color*

> > Sets the foreground color of the bitmap. The default value is black.

> **-rotate** *theta*

> > Sets the rotation of the bitmap. Theta is a real number representing the angle of rotation in degrees. The marker is first rotated and then placed according to its anchor position. The default rotation is 0.0.

<a name="IMAGE-MARKERS"></a>
### IMAGE MARKERS

A image marker displays an image. Image markers are created with the marker's create operation in the form:

<a name="pathName-marker-create-image"></a>
**pathName marker create image** *?option value?...*

There may be many option-value pairs, each sets a configuration option for the marker. These same option-value pairs may be used with the marker's configure operation.

The following options are specific to image markers:

> **-anchor** *anchor*

> > Anchor tells how to position the image relative to the positioning point for the image. For example, if anchor is center then the image is centered on the point; if anchor is n then the image will be drawn such that the top center point of the rectangular region occupied by the image will be at the positioning point. This option defaults to center.

> **-image** *image*

> > Specifies the image to be drawn. If image is "", the marker will not be drawn. The default is "".

<a name="LINE-MARKERS"></a>
### LINE MARKERS

A line marker displays one or more connected line segments. Line markers are created with marker's create operation in the form:

<a name="pathName-marker-create-line"></a>
**pathName marker create line** *?option value?...*

There may be many option-value pairs, each sets a configuration option for the marker. These same option-value pairs may be used with the marker's configure operation.

The following options are specific to line markers:

> **-dashes** *dashList*

> > Sets the dash style of the line. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the line. Each number must be between 1 and 255. If dashList is "", the marker line will be solid.

> **-fill** *color*

> > Sets the background color of the line. This color is used with striped lines (see the -fdashes option). If color is the empty string, no background color is drawn (the line will be dashed, not striped). The default background color is "".

> **-linewidth** *pixels*

> > Sets the width of the lines. The default width is 0.

> **-outline** *color*

> > Sets the foreground color of the line. The default value is black.

> **-stipple** *bitmap*

> > Specifies a stipple pattern used to draw the line, rather than a solid line. Bitmap specifies a bitmap to use as the stipple pattern. If bitmap is "", then the line is drawn in a solid fashion. The default is "".

<a name=">POLYGON-MARKERS"></a>
### POLYGON MARKERS

A polygon marker displays a closed region described as two or more connected line segments. It is assumed the first and last points are connected. Polygon markers are created using the marker create operation in the form:

<a name="pathName-marker-create-polygon"></a>
**pathName marker create polygon** *?option value?...*

There may be many option-value pairs, each sets a configuration option for the marker. These same option-value pairs may be used with the marker configure command to change the marker's configuration. The following options are supported for polygon markers:

> **-dashes** *dashList*
    Sets the dash style of the outline of the polygon. DashList is a list of up to 11 numbers that alternately represent the lengths of the dashes and gaps on the outline. Each number must be between 1 and 255. If dashList is "", the outline will be a solid line.

> **-fill** *color*

> > Sets the fill color of the polygon. If color is "", then the interior of the polygon is transparent. The default is white.

> **-linewidth** *pixels*

> > Sets the width of the outline of the polygon. If pixels is zero, no outline is drawn. The default is 0.

> **-outline** *color*

> > Sets the color of the outline of the polygon. If the polygon is stippled (see the -stipple option), then this represents the foreground color of the stipple. The default is black.

> **-stipple** *bitmap*

> > Specifies that the polygon should be drawn with a stippled pattern rather than a solid color. Bitmap specifies a bitmap to use as the stipple pattern. If bitmap is "", then the polygon is filled with a solid color (if the -fill option is set). The default is "".

<a name=TEXT-MARKERS"></a>
### TEXT MARKERS

A text marker displays a string of characters on one or more lines of text. Embedded newlines cause line breaks. They may be used to annotate regions of the graph. Text markers are created with the create operation in the form:

<a name="pathName-marker-create-text"></a>
**pathName marker create text** *?option value?...*

There may be many option-value pairs, each sets a configuration option for the text marker. These same option-value pairs may be used with the marker's configure operation.

The following options are specific to text markers:

> **-anchor** *anchor*

> > Anchor tells how to position the text relative to the positioning point for the text. For example, if anchor is center then the text is centered on the point; if anchor is n then the text will be drawn such that the top center point of the rectangular region occupied by the text will be at the positioning point. This default is center.

> **-background** *color*

> > Same as the -fill option.

> **-font** *fontName*

> > Specifies the font of the text. The default is `*-Helvetica-Bold-R-Normal-*-120-*`.

> **-fill** *color*

> > Sets the background color of the text. If color is the empty string, no background will be transparent. The default background color is "".

> **-foreground** *color*

> > Same as the -outline option.

> **-justify** *justify*

> > Specifies how the text should be justified. This matters only when the marker contains more than one line of text. Justify must be left, right, or center. The default is center.

> **-outline** *color*

> > Sets the color of the text. The default value is black.

> **-padx** *pad*

> > Sets the padding to the left and right exteriors of the text. Pad can be a list of one or two screen distances. If pad has two elements, the left side of the text is padded by the first distance and the right side by the second. If pad has just one distance, both the left and right sides are padded evenly. The default is 4.

> **-pady** *pad*

> > Sets the padding above and below the text. Pad can be a list of one or two screen distances. If pad has two elements, the area above the text is padded by the first distance and the area below by the second. If pad is just one distance, both the top and bottom areas are padded evenly. The default is 4.

> **-rotate** *theta*

> > Specifies the number of degrees to rotate the text. Theta is a real number representing the angle of rotation. The marker is first rotated along its center and is then drawn according to its anchor position. The default is 0.0.

> **-text** *text*

> > Specifies the text of the marker. The exact way the text is displayed may be affected by other options such as -anchor or -rotate.

<a name="WINDOW-MARKERS"></a>
### WINDOW MARKERS

A window marker displays a widget at a given position. Window markers are created with the marker's create operation in the form:

<a name="pathName-marker-create-window"></a>
**pathName marker create window** *?option value?...*

There may be many option-value pairs, each sets a configuration option for the marker. These same option-value pairs may be used with the marker's configure command.

The following options are specific to window markers:

> **-anchor** *anchor*

> > Anchor tells how to position the widget relative to the positioning point for the widget. For example, if anchor is center then the widget is centered on the point; if anchor is n then the widget will be displayed such that the top center point of the rectangular region occupied by the widget will be at the positioning point. This option defaults to center.

> **-height** *pixels*

> > Specifies the height to assign to the marker's window. If this option isn't specified, or if it is specified as "", then the window is given whatever height the widget requests internally.

> **-width** *pixels*

> > Specifies the width to assign to the marker's window. If this option isn't specified, or if it is specified as "", then the window is given whatever width the widget requests internally.

> **-window** *pathName*

> > Specifies the widget to be managed by the graph. PathName must be a child of the graph widget.

<a name="GRAPH-COMPONENT-BINDINGS"></a>
## GRAPH COMPONENT BINDINGS

Specific graph components, such as elements, markers and legend entries, can have a command trigger when event occurs in them, much like canvas items in Tk's canvas widget. Not all event sequences are valid. The only binding events that may be specified are those related to the mouse and keyboard (such as Enter, Leave, ButtonPress, Motion, and KeyPress).

Only one element or marker can be picked during an event. This means, that if the mouse is directly over both an element and a marker, only the uppermost component is selected. This isn't true for legend entries. Both a legend entry and an element (or marker) binding commands will be invoked if both items are picked.

It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the element name and another is associated with one of the element's tags (see the -bindtags option). When this occurs, all of the matching bindings are invoked. A binding associated with the element name is invoked first, followed by one binding for each of the element's bindtags. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A continue command in a binding script terminates that script, and a break command terminates that script and skips any remaining scripts for the event, just as for the bind command.

The -bindtags option for these components controls addition tag names which can be matched. Implicitly elements and markers always have tags matching their names. Setting the value of the -bindtags option doesn't change this.

Some common bindings can be set with the [*pathName* **binding**](#pathName-binding) command.

## <a name="C-LANGUAGE-API"></a>
## C LANGUAGE API 

You can manipulate data elements from the C language. There may be situations where it is too expensive to translate the data values from ASCII strings. Or you might want to read data in a special file format.

Data can manipulated from the C language using graph vectors. You specify the X-Y data coordinates of an element as vectors and manipulate the vector from C. The graph will be redrawn automatically after the vectors are updated.

From Tcl, create the vectors and configure the element to use them.

> <code>
	vector X Y  
	.g element configure line1 -xdata X -ydata Y  
</code>

To set data points from C, you pass the values as arrays of doubles using the Rbc_ResetVector call. The vector is reset with the new data and at the next idle point (when Tk re-enters its event loop), the graph will be redrawn automatically.

> <code>
	#include "tcl.h"  
	#include "rbcInt.h"  

	register int i;  
	Rbc_Vector *xVec, *yVec;  
	double x[50], y[50];  

	/* Get the graph vectors "X" and "Y" (created above from Tcl) */  
	if ((Rbc_GetVector(interp, "X", &xVec) != TCL_OK) ||  
	    (Rbc_GetVector(interp, "Y", &yVec) != TCL_OK)) {  
	    return TCL_ERROR;  
 	}  

	for (i = 0; i < 50; i++) {  
	    x[i] = i * 0.02;  
	    y[i] = sin(x[i]);  
	}  

	/* Put the data into graph vectors */  
	if ((Rbc_ResetVector(xVec, x, 50, 50, TCL_VOLATILE) != TCL_OK) ||  
	    (Rbc_ResetVector(yVec, y, 50, 50, TCL_VOLATILE) != TCL_OK)) {  
	    return TCL_ERROR;  
	}  
</code>

See the vector manual page for more details.

<a name="SPEED-TIPS"></a>
## SPEED TIPS

There may be cases where the graph needs to be drawn and updated as quickly as possible. If drawing speed becomes a big problem, here are a few tips to speed up displays.

Try to minimize the number of data points. The more data points the looked at, the more work the graph must do.

If your data is generated as floating point values, the time required to convert the data values to and from ASCII strings can be significant, especially when there any many data points. You can avoid the redundant string-to-decimal conversions using the C API to graph vectors.

Data elements without symbols are drawn faster than with symbols. Set the data element's -symbol option to none. If you need to draw symbols, try using the simple symbols such as splus and scross.

Don't stipple or dash the element. Solid lines are much faster.

If you update data elements frequently, try turning off the widget's -bufferelements option. When the graph is first displayed, it draws data elements into an internal pixmap. The pixmap acts as a cache, so that when the graph needs to be redrawn again, and the data elements or coordinate axes haven't changed, the pixmap is simply copied to the screen. This is especially useful when you are using markers to highlight points and regions on the graph. But if the graph is updated frequently, changing either the element data or coordinate axes, the buffering becomes redundant.

## <a name="LIMITATIONS"></a>
## LIMITATIONS

Auto-scale routines do not use requested min/max limits as boundaries when the axis is logarithmically scaled.

The PostScript output generated for polygons with more than 1500 points may exceed the limits of some printers (See PostScript Language Reference Manual, page 568). The work-around is to break the polygon into separate pieces.

<a name="EXAMPLE"></a>
## EXAMPLE

The graph command creates a new graph.

> <code>
	# Create a new graph.  Plotting area is black.  
	graph .g -plotbackground black
</code>

A new Tcl command .g is also created. This command can be used to query and modify the graph. For example, to change the title of the graph to "My Plot", you use the new command and the graph's configure operation.

> <code>
	# Change the title.  
	.g configure -title "My Plot"
</code>

A graph has several components. To access a particular component you use the component's name. For example, to add data elements, you use the new command and the element component.

> <code>
	# Create a new element named "line1"  
	.g element create line1 \\  
	-xdata { 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0 } \\  
	-ydata { 26.18 50.46 72.85 93.31 111.86 128.47 143.14 155.85 166.60 175.38 }
</code>

The element's X-Y coordinates are specified using lists of numbers. Alternately, graph vectors could be used to hold the X-Y coordinates.

> <code>
	# Create two vectors and add them to the graph.
	vector xVec yVec  
	xVec set { 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0 }  
	yVec set { 26.18 50.46 72.85 93.31 111.86 128.47 143.14 155.85 166.60 175.38 }  
	.g element create line1 -xdata xVec -ydata yVec  
</code>

The advantage of using vectors is that when you modify one, the graph is automatically redrawn to reflect the new values.

> <code>
	# Change the y coordinate of the first point.  
	set yVector(0) 25.18
</code>

An element named e1 is now created in .b. It is automatically added to the display list of elements. You can use this list to control in what order elements are displayed. To query or reset the element display list, you use the element's show operation.

> <code>
	# Get the current display list 	
	set elemList [.b element show]  
	# Remove the first element so it won't be displayed.  
	.b element show [lrange $elemList 0 end]  
</code>

The element will be displayed by as many bars as there are data points (in this case there are ten). The bars will be drawn centered at the x-coordinate of the data point. All the bars will have the same attributes (colors, stipple, etc). The width of each bar is by default one unit. You can change this with using the -barwidth option.

> <code>
	# Change the X-Y coordinates of the first point.  
	set xVec(0) 0.18  
	set yVec(0) 25.18  
</code>

An element named line1 is now created in .g. By default, the element's label in the legend will be also line1. You can change the label, or specify no legend entry, again using the element's configure operation.

> <code>
	# Don't display "line1" in the legend.  
	.g element configure line1 -label ""  
</code>

You can configure more than just the element's label. An element has many attributes such as symbol type and size, dashed or solid lines, colors, line width, etc.

> <code>
	# Configure line1  
	.g element configure line1 -symbol square -color red -dashes { 2 4 2 } -linewidth 2 -pixels 2c  
</code>

Four coordinate axes are automatically created: x, x2, y, and y2. And by default, elements are mapped onto the axes x and y. This can be changed with the -mapx and -mapy options.

> <code>
	# Map "line1" on the alternate Y-axis "y2".  
	.g element configure line1 -mapy y2  
</code>
Axes can be configured in many ways too. For example, you change the scale of the Y-axis from linear to log using the axis component.

> <code>
	# Y-axis is log scale.  
	.g axis configure y -logscale yes  
</code>

One important way axes are used is to zoom in on a particular data region. Zooming is done by simply specifying new axis limits using the -min and -max configuration options.

> <code>
	.g axis configure x -min 1.0 -max 1.5  
	.g axis configure y -min 12.0 -max 55.15  
</code>

To zoom interactively, you link the axis configure operations with some user interaction (such as pressing the mouse button), using the bind command. To convert between screen and graph coordinates, use the invtransform operation.

> <code>
	# Click the button to set a new minimum  
	bind .g <ButtonPress-1> {  
    		%W axis configure x -min [%W axis invtransform x %x]  
    		%W axis configure x -min [%W axis invtransform x %y]  
	}  
</code>

By default, the limits of the axis are determined from data values. To reset back to the default limits, set the -min and -max options to the empty value.

> <code>
	# Reset the axes to autoscale again.  
	.g axis configure x -min {} -max {}  
	.g axis configure y -min {} -max {}  
</code>

By default, the legend is drawn in the right margin. You can change this or any legend configuration options using the legend component.

> <code>
	# Configure the legend font, color, and relief  
	.g legend configure -position left -relief raised -font fixed -fg blue  
</code>

To prevent the legend from being displayed, turn on the -hide option.

> <code>
	# Don't display the legend.  
	.g legend configure -hide yes  
</code>

The graph widget has simple drawing procedures called markers. They can be used to highlight or annotate data in the graph. The types of markers available are bitmaps, images, polygons, lines, or windows. Markers can be used, for example, to mark or brush points. In this example, is a text marker that labels the data first point. Markers are created using the marker component.

> <code>
	# Create a label for the first data point of "line1".  
	.g marker create text -name first_marker -coords { 0.2 26.18 } \\  
	-text "start" -anchor se -xoffset -10 -yoffset -10  
</code>
This creates a text marker named first_marker. It will display the text "start" near the coordinates of the first data point. The -anchor, -xoffset, and -yoffset options are used to display the marker above and to the left of the data point, so that the data point isn't covered by the marker. By default, markers are drawn last, on top of data. You can change this with the -under option.

> <code>
	# Draw the label before elements are drawn.  
	.g marker configure first_marker -under yes  
</code>

You can add cross hairs or grid lines using the crosshairs and grid components.

> <code>
	# Display both cross hairs and grid lines.  
	.g crosshairs configure -hide no -color red  
	.g grid configure -hide no -dashes { 2 2 }  

	# Set up a binding to reposition the crosshairs.  
	bind .g <Motion> {  
    		.g crosshairs configure -position @%x,%y  
	}  
</code>

The crosshairs are repositioned as the mouse pointer is moved in the graph. The pointer X-Y coordinates define the center of the crosshairs.

Finally, to get hardcopy of the graph, use the postscript component.

> <code>
	# Print the graph into file "file.ps"  
	.g postscript output file.ps -maxpect yes -decorations no  
</code>

This generates a file file.ps containing the encapsulated PostScript of the graph. The option -maxpect says to scale the plot to the size of the page. Turning off the -decorations option denotes that no borders or color backgrounds should be drawn (i.e. the background of the margins, legend, and plotting area will be white).

<a name="CREDITS"></a>
## CREDITS

[BLT][] was originally develeoped by George A. Howlett. It can be found at <https://sourceforge.net/projects/blt/>.

Refactored [BLT][] Components ([Rbc][]), includes data vectors and graph widgets from the original [BLT][]. Both can be found at sourceforge.

User visible changes to the original [Rbc][] code are:

- widget name is **graph**
- new **-style** *line|bar|strip* option instead of three different commands **graph**, **barchart** and **stripchart**
- no unique abbreviations of widget commands

<a name="KEYWORDS"></a>
## KEYWORDS

graph, widget

<a name="COPYRIGHT"></a>:1

## COPYRIGHT

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 RenĂ© Zaumseil <[email protected]>

[BLT]: <https://sourceforge.net/projects/blt/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>

Added doc/path.n.md.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# path(n) -- 2D canvas widget

*   [SYNOPSIS](#SYNOPSIS)
*   [STANDARD OPTIONS](#STANDARD-OPTIONS)  
  [-background or -bg, background, Background](options.htm#M-background)   
  [-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
  [-cursor, cursor, Cursor](options.htm#M-cursor)  
  [-highlightbackground, highlightBackground, HighlightBackground](options.htm#M-highlightbackground)  
  [-highlightcolor, highlightColor, HighlightColor](options.htm#M-highlightcolor)  
  [-highlightthickness, highlightThickness, HighlightThickness](options.htm#M-highlightthickness)  
  [-insertbackground, insertBackground, Foreground](options.htm#M-insertbackground)  
  [-insertborderwidth, insertBorderWidth, BorderWidth](options.htm#M-insertborderwidth)  
  [-insertofftime, insertOffTime, OffTime](options.htm#M-insertofftime)  
  [-insertontime, insertOnTime, OnTime](options.htm#M-insertontime)  
  [-insertwidth, insertWidth, InsertWidth](options.htm#M-insertwidth)  
  [-relief, relief, Relief](options.htm#M-relief)  
  [-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
  [-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
  [-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
  [-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
  [-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
  [-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  
* [WIDGET-SPECIFIC OPTIONS](#WIDGET-SPECIFIC-OPTIONS)  
  [-class, class, Class](#-class)  
  [-closeenough, closeEnough, CloseEnough](#-closeenough)  
  [-confine, confine, Confine](#-confine)  
  [-height, height, Height](#-height)  
  [-offset, offset, Offset](#-offset)  
  [-scrollregion, scrollRegion, ScrollRegion](#-scrollregion)  
  [-state, state, State](#-state)  
  [-tagstyle, tagstyle, Tagstyle](#-tagstyle)  
  [-width, width, Width](#-width)  
  [-xscrollincrement, xScrollIncrement, ScrollIncrement](#-xscrollincrement)  
  [-yscrollincrement, yScrollIncrement, ScrollIncrement](#-yscrollincrement)  
*   [DESCRIPTION](#DESCRIPTION)  
  * [DISPLAY LIST](#DISPLAY-LIST)  
  * [ITEM IDS AND TAGS](#ITEM-IDS-AND-TAGS)  
  * [COORDINATES](#COORDINATES)  
  * [TEXT INDICES](#TEXT-INDICES)  
  * [TRANSFORMATIONS](#TRANSFORMATIONS)    
  [**path::matrix rotate**](#path::matrix-rotate) *angle ?cx? ?cy?*  
  [**path::matrix scale**](#path::matrix-scale) *sx ?sy?*  
  [**path::matrix flip**](#path::matrix-flip) *?cx? ?cy? ?fx? ?fy?*  
  [**path::matrix rotateflip**](#path::matrix-rotateflip) *?angle? ?cx? ?cy? ?fx? ?fy?*  
  [**path::matrix skewx**](#path::matrix-skewx) *?angle?*  
  [**path::matrix skewy**](#path::matrix-skewy) *?angle?*  
  [**path::matrix move**](#path::matrix-move) *dx dy*  
  [**path::matrix mult**](#path::matrix-mult) *ma mb*  
  * [STYLES](#STYLES)  
  [**path::style cget**](#path::style-cget) *token option*  
  [**path::style configure**](#path::style-configure) *token ?option? ?value option value...?*  
  [**path::style create**](#path::style-create) *?fillOptions strokeOptions?*  
  [**path::style delete**](#path::style-delete) *token*  
  [**path::style inuse**](#path::style-inuse) *token*  
  [**path::style names**](#path::style-names)  
  * [GRADIENTS](#GRADIENTS)  
  [**path::gradient cget**](#path::gradient-cget) *token option*  
  [**path::gradient configure**](#path::gradient-configure) *token ?option? ?value option value...?*  
  [**path::gradient create**](#path::gradient-create) *type ?-key value ...?*  
  [**path::gradient delete**](#path::gradient-delete) *token*  
  [**path::gradient inuse**](#path::gradient-inuse) *token*  
  [**path::gradient names**](#path::gradient-names)  
  [**path::gradient type**](#path::gradient-type) *token*  
  * [SURFACE](#SURFACE)  
  [**path::surface names**](#path::surface-names)  
  [**path::surface new**](#path::surface-new) *width height*  
*   [WIDGET COMMAND](#WIDGET-COMMAND)  
  [*pathName* **addtag**](#pathName-addtag) *tag searchSpec ?arg arg ...?*  
  [*pathName* **ancestors**](#pathName-ancestors) *tagOrId*  
  [*pathName* **bind**](#pathName-bind) *tagOrId ?sequence? ?command?*  
  [*pathName* **canvasy**](#pathName-canvasy) *screeny ?gridspacing?*  
  [*pathName* **cget**](#pathName-cget) *option*  
  [*pathName* **children**](#pathName-children) *tagOrId*  
  [*pathName* **configure**](#pathName-configure) *?option? ?value? ?option value ...?*  
  [*pathName* **coords**](#pathName-coords) *tagOrId ?x0 y0 ...?*  
  [*pathName* **create**](#pathName-create) *type x y ?x y ...? ?option value ...?*  
  [*pathName* **dchars**](#pathName-dchars) *tagOrId first ?last?*  
  [*pathName* **delete**](#pathName-delete) *?*tagOrId* *tagOrId* ...?*  
  [*pathName* **depth**](#pathName-depth) *tagOrId*  
  [*pathName* **distance**](#pathName-distance) *tagOrId x y*  
  [*pathName* **dtag**](#pathName-dtag) *tagOrId ?tagToDelete?*  
  [*pathName* **find**](#pathName-find) *searchCommand ?arg arg ...?*  
  [*pathName* **firstchild**](#pathName-firstchild) *tagOrId*  
  [*pathName* **focus**](#pathName-focus) *?*tagOrId*?*  
  [*pathName* **gettags**](#pathName-gettags) *tagOrId*  
  [*pathName* **gradient**](#pathName-gradient) *command ?options?*  
  [*pathName* **icursor**](#pathName-icursor) *tagOrId index*   
  [*pathName* **imove**](#pathName-imove) *tagOrId index x y*  
  [*pathName* **index**](#pathName-index) *tagOrId index*  
  [*pathName* **insert**](#pathName-insert) *tagOrId beforeThis string*  
  [*pathName* **itemcget**](#pathName-itemcget) *tagOrId option*  
  [*pathName* **itemconfigure**](#pathName-itemconfigure) *tagOrId ?option? ?value? ?option value ...?*  
  [*pathName* **itempdf**](#pathName-itempdf) *tagOrId ?extgsProc objProc gradProc?*  
  [*pathName* **lastchild**](#pathName-lastchild) *tagOrId*  
  [*pathName* **lower**](#pathName-lower) *tagOrId ?belowThis?*  
  [*pathName* **move**](#pathName-move) *tagOrId xAmount yAmount*  
  [*pathName* **moveto**](#pathName-moveto) *tagOrId xPos yPos*  
  [*pathName* **nextsibling**](#pathName-nextsibling) *tagOrId*  
  [*pathName* **parent**](#pathName-parent) *tagOrId*  
  [*pathName* **prevsibling**](#pathName-prevsibling) *tagOrId*  
  [*pathName* **raise**](#pathName-raise) *tagOrId ?aboveThis?*  
  [*pathName* **rchars**](#pathName-rchars) *tagOrId first last string*  
  [*pathName* **scale**](#pathName-scale) *tagOrId xOrigin yOrigin xScale yScale*  
  [*pathName* **scan**](#pathName-scan) *option args*  
  [*pathName* **select**](#pathName-select) *option ?*tagOrId* arg?*  
  [*pathName* **style**](#pathName-style) *cmd ?options?*  
  [*pathName* **type**](#pathName-type) *tagOrId*  
  [*pathName* **types**](#pathName-types)  
  [*pathName* **xview**](#pathName-xview) *?args?*  
  [*pathName* **yview**](#pathName-yview) *?args?*  
*   [ITEM TYPES](#ITEM-TYPES)  
  * [COMMON ITEM OPTIONS](#COMMON-ITEM-OPTIONS)  
  [**-fill** *color\|gradientToken*](#ITEM-fill)  
  [**-fillopacity** *value*](#ITEM-fillopacity)  
  [**-fillrule** *nonzero\|evenodd*](#ITEM-fillrule)  
  [**-stroke** *color*](#ITEM-stroke)  
  [**-strokedasharray** *dashArray*](#ITEM-strokedasharray)  
  [**-strokelinecap** *butt\|round\|square*](#ITEM-strokelinecap)  
  [**-strokelinejoin** *miter\|round\|bevel*](#ITEM-strokelinejoin)  
  [**-strokemiterlimit** *float*](#ITEM-strokemiterlimit)  
  [**-strokeopacity** *value*](#ITEM-strokeopacity)  
  [**-strokewidth** *float*](#ITEM-strokewidth)  
  [**-matrix** *{a b c d tx ty}*](#ITEM-matrix)  
  [**-parent** *tagOrId*](#ITEM-parent)  
  [**-state** *active\|disabled\|normal\|hidden*](#ITEM-state)  
  [**-style** *styleToken*](#ITEM-style)  
  [**-tags** *tagList*](#ITEM-tags)  
  [**-startarrow** *boolean*](#ITEM-startarrow)  
  [**-startarrowlength** *float*](#ITEM-startarrowlength)  
  [**-startarrowwidth** *float*](#ITEM-startarrowwidth)  
  [**-startarrowfill** *float*](#ITEM-startarrowfill)  
  [**-endarrow** *boolean*](#ITEM-endarrow)  
  [**-endarrowlength** *float*](#ITEM-endarrowlength)  
  [**-endarrowwidth** *float*](#ITEM-endarrowwidth)  
  [**-endarrowfill** *float*](#ITEM-endarrowfill)  
  * [GROUP ITEM](#GROUP-ITEM)  
  [*pathName* **create group**](#pathName-create-group) *?fillOptions strokeOptions genericOptions?*  
  * [PATH ITEMS](#PATH-ITEM)  
  [*pathName* **create path**](#pathName-create-path) *pathSpec ?fillOptions strokeOptions arrowOptions genericOptions?*  
  * [LINE ITEM](#LINE-ITEM)  
  [*pathName* **create line**](#pathName-create-line) *x1 y1 x2 y2 ?strokeOptions arrowOptions genericOptions?*  
  * [POLYLINE ITEM](#POLYLINE-ITEM)  
  [*pathName* **create polyline**](#pathName-create-polyline) *x1 y1 x2 y2 .... ?strokeOptions arrowOptions genericOptions?*  
  * [POLYGON ITEM](#POLYGON-ITEM)  
  [*pathName* **create polygon**](#pathName-create-polygon) *x1 y1 x2 y2 .... ?fillOptions strokeOptions genericOptions?*  
  * [RECT ITEM](#RECT-ITEM)  
  [*pathName* **create rect**](#pathName-create-rect) *x1 y1 x2 y2 ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*  
  * [CIRCLE ITEM](#CIRCLE-ITEM)  
  [*pathName* **create circle**](#pathName-create-circle) *cx cy ?-r fillOptions strokeOptions genericOptions?*  
  * [ELLIPSE ITEM](#ELLIPSE-ITEM)  
  [*pathName* **create ellipse**](#pathName-create-ellipse) *cx cy ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*  
  * [IMAGE ITEM](#IMAGE-ITEM)  
  [*pathName* **create image**](#pathName-create-image) *x y ?-image -width -height genericOptions?*  
  * [TEXT ITEM](#TEXT-ITEM)  
  [*pathName* **create text**](#pathName-create-text) *x y ?-text string? ?-textanchor start\|middle\|end\|n\|w\|s\|e\|nw\|ne\|sw\|se\|c? ?-fontfamily fontname -fontsize float? ?-fontslant normal\|italic\|oblique? ?-fontweight normal\|bold? ?fillOptions strokeOptions genericOptions? ?-filloverstroke BOOLEAN?*  
  * [WINDOW ITEM](#WINDOW-ITEM)  
  [*pathName* **create window**](#pathName-create-window) *x y ?option value ...?*  
*   [CREDITS](#CREDITS)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS

**path** *pathName ?options?*

The **path** command creates a new Tcl command whose name is *pathName*. This command may be used to invoke various operations on the widget.

<a name="STANDARD-OPTIONS"></a>
## STANDARD OPTIONS

[-background or -bg, background, Background](options.htm#M-background)  
[-borderwidth or -bd, borderWidth, BorderWidth](options.htm#M-borderwidth)  
[-cursor, cursor, Cursor](options.htm#M-cursor)  
[-highlightbackground, highlightBackground, HighlightBackground](options.htm#M-highlightbackground)  
[-highlightcolor, highlightColor, HighlightColor](options.htm#M-highlightcolor)  
[-highlightthickness, highlightThickness, HighlightThickness](options.htm#M-highlightthickness)  
[-insertbackground, insertBackground, Foreground](options.htm#M-insertbackground)  
[-insertborderwidth, insertBorderWidth, BorderWidth](options.htm#M-insertborderwidth)  
[-insertofftime, insertOffTime, OffTime](options.htm#M-insertofftime)  
[-insertontime, insertOnTime, OnTime](options.htm#M-insertontime)  
[-insertwidth, insertWidth, InsertWidth](options.htm#M-insertwidth)  
[-relief, relief, Relief](options.htm#M-relief)  
[-selectbackground, selectBackground, Foreground](options.htm#M-selectbackground)  
[-selectborderwidth, selectBorderWidth, BorderWidth](options.htm#M-selectborderwidth)  
[-selectforeground, selectForeground, Background](options.htm#M-selectforeground)  
[-takefocus, takeFocus, TakeFocus](options.htm#M-takefocus)  
[-xscrollcommand, xScrollCommand, ScrollCommand](options.htm#M-xscrollcommand)  
[-yscrollcommand, yScrollCommand, ScrollCommand](options.htm#M-yscrollcommand)  

See the [options][] manual entry for details on the standard options.

<a name="WIDGET-SPECIFIC-OPTIONS"></a>
## WIDGET-SPECIFIC OPTIONS

<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**

> > Define class for use in getting values from option database.

<a name="-closeenough"></a>
Command-Line Name: **-closeenough**  
Database Name: **closeEnough**  
Database Class: **CloseEnough**

> Specifies a floating-point value indicating how close the mouse cursor must be to an item before it is considered to be "inside" the item. Defaults to 1.0. 

<a name="-confine"></a>
Command-Line Name: **-confine**  
Database Name: **confine**  
Database Class: **Confine**

> Specifies a boolean value that indicates whether or not it should be allowable to set the canvas's view outside the region defined by the **scrollRegion** argument. Defaults to true, which means that the view will be constrained within the scroll region. 

<a name="-height"></a>
Command-Line Name: **-height**  
Database Name: **height**  
Database Class: **Height**

> Specifies a desired window height that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 

<a name="-offset"></a>
Command-Line Name: **-offset**  
Database Name: **offset**  
Database Class: **Offset**

> Stipple offset for outline. 

<a name="-scrollregion"></a>
Command-Line Name: **-scrollregion**  
Database Name: **scrollRegion**  
Database Class: **ScrollRegion**

> Specifies a list with four coordinates describing the left, top, right, and bottom coordinates of a rectangular region. This region is used for scrolling purposes and is considered to be the boundary of the information in the canvas. Each of the coordinates may be specified in any of the forms given in the [COORDINATES][] section below. 

<a name="-state"></a>
Command-Line Name: **-state**  
Database Name: **state**  
Database Class: **State**

> Modifies the default state of the canvas where state may be set to one of: **normal**, **disabled**, or **hidden**. Individual canvas objects all have their own state option which may override the default state. Many options can take separate specifications such that the appearance of the item can be different in different situations. The options that start with **active** control the appearance when the mouse pointer is over it, while the option starting with **disabled** controls the appearance when the state is disabled. Canvas items which are **disabled** will not react to canvas bindings. 

<a name="-tagstyle"></a>
Command-Line Name: **-tagstyle**  
Database Name: **tagstyle**  
Database Class: **Tagstyle**

> Define working with tags. Possible values are *expr\|exact\|glob*. Default is *expr*. TODO

<a name="-width"></a>
Command-Line Name: **-width**  
Database Name: **width**  
Database Class: **Width**

> Specifies a desired window width that the canvas widget should request from its geometry manager. The value may be specified in any of the forms described in the [COORDINATES][] section below. 

<a name="-xscrollincrement"></a>
Command-Line Name: **-xscrollincrement**  
Database Name: **xScrollIncrement**  
Database Class: **ScrollIncrement**

> Specifies an increment for horizontal scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the horizontal view in the window will be constrained so that the canvas x coordinate at the left edge of the window is always an even multiple of **xScrollIncrement**; furthermore, the units for scrolling (e.g., the change in view when the left and right arrows of a scrollbar are selected) will also be **xScrollIncrement**. If the value of this option is less than or equal to zero, then horizontal scrolling is unconstrained. 

<a name="-yscrollincrement"></a>
Command-Line Name: **-yscrollincrement**  
Database Name: **yScrollIncrement**  
Database Class: **ScrollIncrement**

> Specifies an increment for vertical scrolling, in any of the usual forms permitted for screen distances. If the value of this option is greater than zero, the vertical view in the window will be constrained so that the canvas y coordinate at the top edge of the window is always an even multiple of **yScrollIncrement**; furthermore, the units for scrolling (e.g., the change in view when the top and bottom arrows of a scrollbar are selected) will also be **yScrollIncrement**. If the value of this option is less than or equal to zero, then vertical scrolling is unconstrained. 

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **path** command creates a new window (given by the pathName argument) and makes it into a canvas widget. Additional options, described above, may be specified on the command line or in the option database to configure aspects of the canvas such as its colors and 3-D relief. The **path** command returns its pathName argument. At the time this command is invoked, there must not exist a window named pathName, but pathName's parent must exist.

Canvas widgets implement structured graphics. A canvas displays any number of items, which may be things like rectangles, circles, lines, and text. Items may be manipulated (e.g. moved or re-colored) and commands may be associated with items in much the same way that the [bind][] command allows commands to be bound to widgets. For example, a particular command may be associated with the <Button-1> event so that the command is invoked whenever button 1 is pressed with the mouse cursor over an item. This means that items in a canvas can have behaviors defined by the Tcl scripts bound to them. 

This widget implements a canvas widget which is modelled after its [SVG][] counterpart. Items are put in a tree structure with a persistent root item with id 0. All other items are descendants of this root item. The path items, described below, are by default a child of the root item, but can be configured to be a child of any group item using the -parent option.

<a name="DISPLAY-LIST"></a>
### DISPLAY LIST

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being "on top" of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the Tk [raise][] command and [lower][] command instead. 

Items can be structured using groups.

A group item is merely a placeholder for other items, similar to how a frame widget is a container for other widgets. It is a building block for the tree structure. Unlike other items, and unlike frame widgets, it doesn't display anything. It has no coordinates which is an additional difference. The root item is a special group item with id 0 and tags equal to "root". The root group can be configured like other items, but its -tags and -parent options are read only. Group items define the canvas tree structure:

      0----
          1
          2
          3
          4
          5----
              6
              7
          8----
              9
             10
         11
         12

Antialiasing, if available, is controlled by the variable **path::antialias**. To switch on set it to 1.

<a name="ITEM-IDS-AND-TAGS"></a>
### ITEM IDS AND TAGS

Items in a canvas widget may be named in either of two ways: by id or by tag. Each item has a unique identifying number, which is assigned to that item when it is created. The id of an item never changes and id numbers are never re-used within the lifetime of a canvas widget. 
Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, "x123" is OK but "123" is not. The same tag may be associated with many different items. This is commonly done to group items in various interesting ways; for example, all selected items might be given the tag "selected". 

The tag **all** is implicitly associated with every item in the canvas; it may be used to invoke operations on all the items in the canvas. Note that this presently also includes the root item which can result in some unexpected behavior. In many case you can operate on the root item (0) instead. As an example, if you want to move, scale etc. all items in canvas, then do:

> <code>
    pathName move 0 x y  
</code>

The tag **current** is managed automatically by Tk; it applies to the current item, which is the topmost item whose drawn area covers the position of the mouse cursor (different item types interpret this in varying ways; see the individual item type documentation for details). If the mouse is not in the canvas widget or is not over an item, then no item has the **current** tag. 

When specifying items in canvas widget commands, if the specifier is an integer then it is assumed to refer to the single item with that id. If the specifier is not an integer, then it is assumed to refer to all of the items in the canvas that have a tag matching the specifier. The symbol *tagOrId* is used below to indicate that an argument specifies either an id that selects a single item or a tag that selects zero or more items. 

*tagOrId* may contain a logical expressions of tags by using operators: "**&&**", "**\|\|**", "**^**", "**!**", and parenthesized subexpressions. For example: 

> <code>
    .c find withtag {(a&&!b)||(!a&&b)}  
</code>

or equivalently:
 
> <code>
    .c find withtag {a^b}  
</code>

will find only those items with either "a" or "b" tags, but not both. 

Some widget commands only operate on a single item at a time; if *tagOrId* is specified in a way that names multiple items, then the normal behavior is for the command to use the first (lowest) of these items in the display list that is suitable for the command. Exceptions are noted in the widget command descriptions below. 

<a name="COORDINATES"></a>
### COORDINATES

All coordinates related to canvases are stored as floating-point numbers. Coordinates and distances are specified in screen units, which are floating-point numbers optionally followed by one of several letters. If no letter is supplied then the distance is in pixels. If the letter is **m** then the distance is in millimeters on the screen; if it is **c** then the distance is in centimeters; **i** means inches, and **p** means printers points (1/72 inch). Larger y-coordinates refer to points lower on the screen; larger x-coordinates refer to points farther to the right. Coordinates can be specified either as an even number of parameters, or as a single list parameter containing an even number of x and y coordinate values. 

The command **path::pixelalign** says how the platform graphics library draw when we specify integer coordinates. Some libraries position a one pixel wide line exactly at the pixel boundaries, and smears it out, if antialiasing, over the adjecent pixels. This can look blurred since a one pixel wide black line suddenly becomes a two pixel wide grey line.  It seems that cairo and quartz (MacOSX) do this, while gdi+ on Windows doesn't. This command just provides the info for you so you may take actions. Either you can manually position lines with odd integer widths at the center of pixels (adding 0.5), or set the **path::depixelize** equal to 1, see below.

With the boolean variable **path::depixelize** equal to 1 we try to adjust coordinates for objects with integer line widths.

There can be subtle differences compared to the original canvas. One such situation is where an option value has switched from an integer to float (double).

<a name="TEXT-INDICES"></a>
### TEXT INDICES

Text items support the notion of an index for identifying particular positions within the item. In a similar fashion, line and polygon items support index for identifying, inserting and deleting subsets of their coordinates. Indices are used for commands such as inserting or deleting a range of characters or coordinates, and setting the insertion cursor position. An index may be specified in any of a number of ways, and different types of items may support different forms for specifying indices. Text items support the following forms for an index; if you define new types of text-like items, it would be advisable to support as many of these forms as practical. Note that it is possible to refer to the character just after the last one in the text item; this is necessary for such tasks as inserting new text at the end of the item. Lines and Polygons do not support the insertion cursor and the selection. Their indices are supposed to be even always, because coordinates always appear in pairs. 

*number*

> A decimal number giving the position of the desired character within the text item. 0 refers to the first character, 1 to the next character, and so on. If indexes are odd for lines and polygons, they will be automatically decremented by one. A number less than 0 is treated as if it were zero, and a number greater than the length of the text item is treated as if it were equal to the length of the text item. For polygons, numbers less than 0 or greater then the length of the coordinate list will be adjusted by adding or subtracting the length until the result is between zero and the length, inclusive. 

**end**

> Refers to the character or coordinate just after the last one in the item (same as the number of characters or coordinates in the item). 

**insert**

> Refers to the character just before which the insertion cursor is drawn in this item. Not valid for lines and polygons. 

**sel.first**

> Refers to the first selected character in the item. If the selection is not in this item then this form is illegal. 

**sel.last**

> Refers to the last selected character in the item. If the selection is not in this item then this form is illegal. 

*@x,y*

> Refers to the character or coordinate at the point given by x and y, where x and y are specified in the coordinate system of the canvas. If x and y lie outside the coordinates covered by the text item, then they refer to the first or last character in the line that is closest to the given point. 

<a name="TRANSFORMATIONS"></a>
### TRANSFORMATIONS

Normally the origin of the canvas coordinate system is at the upper-left corner of the window containing the canvas. It is possible to adjust the origin of the canvas coordinate system relative to the origin of the window using the **xview** and **yview** widget commands; this is typically used for scrolling. Canvases do not support scaling or rotation of the canvas coordinate system relative to the window coordinate system. 
Individual items may be moved or scaled using widget commands described below, but they may not be rotated. 

Note that the default origin of the canvas's visible area is coincident with the origin for the whole window as that makes bindings using the mouse position easier to work with; you only need to use the **canvasx** and **canvasy** widget commands if you adjust the origin of the visible area. However, this also means that any focus ring (as controlled by the **-highlightthickness** option) and window border (as controlled by the **-borderwidth** option) must be taken into account before you get to the visible area of the canvas. 

Each path item has a **-matrix** option which defines the local coordinate system for that item. It is defined as a double list {a b c d tx ty} where a simple scaling is {sx 0 0 sy 0 0}, a translation {1 0 0 1 tx ty}, and a rotation around origin with an angle 'a' is {cos(a) sin(a) -sin(a) cos(a) 0 0}. The simplest way to interpret this is to design an extra coordinate system according to the matrix, and then draw the item in that system.

Inheritance works differently for the **-matrix** option than for the other options which are just overwritten. Instead any set -matrix option starting from the root, via any number of group items, to the actual item being displayed, are nested. That is, any defined matrices from the root down define a sequence of coordinate transformations.

The following functions provide some basic matrix operations such as rotation, translation etc.. All function return a matrix which can be used as value for the *-matrix* option.


<a name="path::matrix-rotate"></a>
**path::matrix rotate** *angle ?cx? ?cy?*

> Return matrix with rotation of *angle* around *cx, cy*.

<a name="path::matrix-scale"></a>
**path::matrix scale** *sx ?sy?*

> Return scaling matrix. If *sy* is not provided use *sx* for x and y direction.

<a name="path::matrix-flip"></a>
**path::matrix flip** *?cx? ?cy? ?fx? ?fy?*

> Return matrix with translation of *cx, cy* and flip with *fx* and *fy*.

<a name="path::matrix-rotateflip"></a>
**path::matrix rotateflip** *?angle? ?cx? ?cy? ?fx? ?fy?*

> Return matrix with rotation of *angle* around *cx, cy* and flip with *fx* and *fy*.

<a name="path::matrix-skewx"></a>
**path::matrix skewx** *?angle?*

> Return matrix with skew in x-direction of *angle*

<a name="path::matrix-skewy"></a>
**path::matrix skewy** *?angle?*

> Return matrix with skew in y-direction of *angle*

<a name="path::matrix-move"></a>
**path::matrix move** *dx dy*

> Return matrix with translation of *dx* in x-direction and *dy* in y-direction.

<a name="path::matrix-mult"></a>
**path::matrix mult** *ma mb*

> Return product of matrix multiplication of *ma* and *mb*.

<a name="STYLES"></a>
### STYLES

Styles are created and configured using:

> <code>
    path::style command ?options?  
</code>

<a name="path::style-cget"></a>
**path::style cget** *token option*

> Returns the value of an option.

<a name="path::style-configure"></a>
**path::style configure** *token ?option? ?value option value...?*

> Configures the object in the usual tcl way.

<a name="path::style-create"></a>
**path::style create** *?fillOptions strokeOptions?*

> Creates a style object and returns its token.

<a name="path::style-delete"></a>
**path::style delete** *token*

> Deletes the object.

<a name="path::style-inuse"></a>
**path::style inuse** *token*

> If any item is configured with the style token 1 is returned, else 0.

<a name="path::style-names"></a>
**path::style names**

> Returns all existing tokens.

The same options as for the item are supported with the exception of **-style**, **-state**, and **-tags**.

<a name="GRADIENTS"></a>
### GRADIENTS

Gradients are created and configured using:

> <code>
    path::gradient command ?options?  
</code>

<a name="path::gradient-cget"></a>
**path::gradient cget** *token option*

> Returns the value of an option.

<a name="path::gradient-configure"></a>
**path::gradient configure** *token ?option? ?value option value...?*

> Configures the object in the usual tcl way.

<a name="path::gradient-create"></a>
**path::gradient create** *type ?-key value ...?*

> Creates a linear gradient object with type any of linear or radial and returns its token.

<a name="path::gradient-delete"></a>
**path::gradient delete** *token*

> Deletes the object.

<a name="path::gradient-inuse"></a>
**path::gradient inuse** *token*

> If any item is configured with the gradient token 1 is returned, else 0.

<a name="path::gradient-names"></a>
**path::gradient names**

> Returns all existing tokens.

<a name="path::gradient-type"></a>
**path::gradient type** *token*

> Returns the type (linear\|radial) of the gradient. The options for linear gradients are:

> **-method** pad\|repeat\|reflect

> > Partial implementation; defaults to pad

> **-stops** *{stopSpec ?stopSpec...?}*

> > Where *stopSpec* is a list {offset color ?opacity?}. All offsets must be ordered and run from 0 to 1.

> **-lineartransition** *{x1 y1 x2 y2}*

> > Specifies the transtion vector relative the items bounding box. Depending on **-units** it gets interpreted differently. If **-units** is 'bbox' coordinates run from 0 to 1 and are relative the items bounding box. If **-units** is 'userspace' then they are defined in absolute coordinates but in the space of the items coordinate system. It defaults to {0 0 1 0}, left to right.

> **-matrix** *{a b c d tx ty}*

> > Sets a specific transformation for the gradient pattern only. NB: not sure about the order transforms, see **-units**.

> **-units** bbox\|userspace

> > Sets the units of the transition coordinates. See above. Defaults to 'bbox'.

The options for radial gradients are the same as for linear gradients except that the **-lineartransition** is replaced by a **-radialtransition**:

> **-radialtransition** *{cx cy ?r? ?fx fy?}*

> > Specifies the transition circles relative the items bounding box and run from 0 to 1. They default to {0.5 0.5 0.5 0.5 0.5}. *cx,cy* is the center of the end circle and *fx,fy* the center of the start point.

> **path::gradientstopstyle** *name args*

> Currently is only 'rainbow' as name supported. The function illustrate the  definition of gradients.

<a name="SURFACE"></a>
### SURFACE

In memory drawing surface.

<a name="path::surface-names"></a>
**path::surface names**

> Lists the existing surface tokens.

<a name="path::surface-new"></a>
**path::surface new** *width height*

> Creates an in memory drawing surface. Its format is platform dependent. It returns a *surfaceToken* which is a new command.

The surface token commands are:

> *surfaceToken* **copy** *imageName*

> > Copies the surface to an existing image (photo) and returns the name of
the image so you can do:

> > <code>
    set image [$token copy [image create photo]]  
</code>

> > See [Tk_PhotoPutBlock][] for how it affects the existing image.

> > The boolean variable **path::premultiplyalpha** controls how the copy action handles surfaces with the alpha component premultiplied. If 1 the copy process correctly handles any format with premultiplied alpha. This gets the highest quality for antialiasing and correct results for partial transparency. It is also slower. If 0 the alpha values are not remultiplied and the result is wrong for transparent regions, and gives poor antialiasing effects. But it is faster. The default is 1.

> *surfaceTtoken* **create** *type coords ?options?*

> > Draws the item of type to the surface. All item types except the group and the corresponding options as described above are supported, except the canvas specific **-tags** and **-state**.

> *surfaceToken* **destroy**

> > Destroys surface.

> *surfaceToken* **erase** *x y width height*

> > Erases the indicated area to transparent.

> *surfaceToken* **height**

> > Returns height.

> *surfaceToken* **width**

> > Returns width.

> Note that the surface behaves different from the canvas widget. When you have put an item there there is no way to configure it or to remove it. If you have done a mistake then you have to erase the complete surface and start all over. Better to experiment on the canvas and then reproduce your drawing to a surface when you are satisfied with it.

> NB: gdi+ seems unable to produce antialiasing effects here but there seems to be no gdi+ specific way of drawing in memory bitmaps but had to call CreateDIBSection() which is a Win32 GDI API.

<a name="WIDGET COMMAND"></a>
## WIDGET COMMAND

<a name="pathName-addtag"></a>
*pathName* **addtag** *tag searchSpec ?arg arg ...?*

> For each item that meets the constraints specified by *searchSpec* and the *args*, add *tag* to the list of tags associated with the item if it is not already present on that list. It is possible that no items will satisfy the constraints given by searchSpec and args, in which case the command has no effect. This command returns an empty string as result. *SearchSpec* and *arg'*s may take any of the following forms: 

> **above** *tagOrId*
	
> > Selects the item just after (above) the one given by *tagOrId* in the display list. If *tagOrId* denotes more than one item, then the last (topmost) of these items in the display list is used. The command is constrained to siblings.

> **all**

> > Selects all the items in the canvas. 

> **below** *tagOrId*

> > Selects the item just before (below) the one given by *tagOrId* in the display list. If *tagOrId* denotes more than one item, then the first (lowest) of these items in the display list is used. The command is constrained to siblings.

> **closest** *x y ?halo? ?start?*

> > Selects the item closest to the point given by *x* and *y*. If more than one item is at the same closest distance (e.g. two items overlap the point), then the topmost of these items (the last one in the display list) is used. If *halo* is specified, then it must be a non-negative value. Any item closer than *halo* to the point is considered to overlap it. The *start* argument may be used to step circularly through all the closest items. If *start* is specified, it names an item using a tag or id (if by tag, it selects the first item in the display list with the given tag). Instead of selecting the topmost closest item, this form will select the topmost closest item that is below start in the display list; if no such item exists, then the selection behaves as if the start argument had not been specified. 

> **enclosed** *x1 y1 x2 y2*

> > Selects all the items completely enclosed within the rectangular region given by *x1, y1, x2, and y2*. *X1* must be no greater then *x2* and *y1* must be no greater than *y2*. 

> **overlapping** *x1 y1 x2 y2*

> > Selects all the items that overlap or are enclosed within the rectangular region given by *x1, y1, x2,* and *y2*. *X1* must be no greater then *x2* and *y1* must be no greater than *y2*. 

> **withtag** *tagOrId*

> > Selects all the items given by *tagOrId*. 

<a name="pathName-ancestors"></a>
*pathName* **ancestors** *tagOrId*

> Returns a list of item id's of the first item matching *tagOrId* starting with the root item with id 0.

*pathName* **bbox** *tagOrId ?tagOrId tagOrId ...?*

> Returns a list with four elements giving an approximate bounding box for all the items named by the *tagOrId* arguments. The list has the form *x1 y1 x2 y2* such that the drawn areas of all the named elements are within the region bounded by *x1* on the left, *x2* on the right, *y1* on the top, and *y2* on the bottom. The return value may overestimate the actual bounding box by a few pixels. If no items match any of the *tagOrId* arguments or if the matching items have empty bounding boxes (i.e. they have nothing to display) then an empty string is returned. 

<a name="pathName-bind"></a>
*pathName* **bind** *tagOrId ?sequence? ?command?*

> This command associates *command* with all the items given by *tagOrId* such that whenever the event sequence given by *sequence* occurs for one of the items the command will be invoked. This widget command is similar to the [bind][] command except that it operates on items in a canvas rather than entire widgets. See the [bind][] manual entry for complete details on the syntax of sequence and the substitutions performed on command before invoking it. If all arguments are specified then a new binding is created, replacing any existing binding for the same *sequence* and *tagOrId* (if the first character of *command* is “+” then *command* augments an existing binding rather than replacing it). In this case the return value is an empty string. If *command* is omitted then the command returns the *command* associated with *tagOrId* and *sequence* (an error occurs if there is no such binding). If both *command* and *sequence* are omitted then the command returns a list of all the sequences for which bindings have been defined for *tagOrId*. 

> The only events for which bindings may be specified are those related to the mouse and keyboard (such as **Enter**, **Leave**, **ButtonPress**, **Motion**, and **KeyPress**) or virtual events. The handling of events in canvases uses the current item defined in [ITEM IDS AND TAGS][] above. **Enter** and **Leave** events trigger for an item when it becomes the current item or ceases to be the current item; note that these events are different than **Enter** and **Leave** events for windows. Mouse-related events are directed to the current item, if any. Keyboard-related events are directed to the focus item, if any (see the **focus** widget command below for more on this). If a virtual event is used in a binding, that binding can trigger only if the virtual event is defined by an underlying mouse-related or keyboard-related event. 

> It is possible for multiple bindings to match a particular event. This could occur, for example, if one binding is associated with the item's id and another is associated with one of the item's tags. When this occurs, all of the matching bindings are invoked. A binding associated with the **all** tag is invoked first, followed by one binding for each of the item's tags (in order), followed by a binding associated with the item's id. If there are multiple matching bindings for a single tag, then only the most specific binding is invoked. A [continue][] command in a binding script terminates that script, and a [break][] command terminates that script and skips any remaining scripts for the event, just as for the [bind][] command. 

> If bindings have been created for a canvas window using the [bind][] command, then they are invoked in addition to bindings created for the canvas's items using the **bind** widget command. The bindings for items will be invoked before any of the bindings for the window as a whole. 

<a name="pathName-canvasx"></a>
*pathName* **canvasx** *screenx ?gridspacing?*

> Given a window x-coordinate in the canvas *screenx*, this command returns the canvas x-coordinate that is displayed at that location. If *gridspacing* is specified, then the canvas coordinate is rounded to the nearest multiple of *gridspacing* units. 

<a name="pathName-canvasy"></a>
*pathName* **canvasy** *screeny ?gridspacing?*

> Given a window y-coordinate in the canvas *screeny*, this command returns the canvas y-coordinate that is displayed at that location. If *gridspacing* is specified, then the canvas coordinate is rounded to the nearest multiple of *gridspacing* units. 

<a name="pathName-cget"></a>
*pathName* **cget** *option*

> Returns the current value of the configuration option given by *option*. *Option* may have any of the values accepted by the **path** command. 

<a name="pathName-children"></a>
*pathName* **children** *tagOrId*

> Lists all children of the first item matching *tagOrId*.

<a name="pathName-configure"></a>
*pathName* **configure** *?option? ?value? ?option value ...?*

> Query or modify the configuration options of the widget. If no *option* is specified, returns a list describing all of the available options for pathName (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no *value*, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. *Option* may have any of the values accepted by the **path** command. 

<a name="pathName-coords"></a>
*pathName* **coords** *tagOrId ?x0 y0 ...?*

*pathName* **coords** *tagOrId ?coordList?*

> Query or modify the coordinates that define an item. If no coordinates are specified, this command returns a list whose elements are the coordinates of the item named by *tagOrId*. If coordinates are specified, then they replace the current coordinates for the named item. If *tagOrId* refers to multiple items, then the first one in the display list is used. 

<a name="pathName-create"></a>
*pathName* **create** *type x y ?x y ...? ?option value ...?*

*pathName* **create** *type coordList ?option value ...?*

> Create a new item in pathName of type *type*. The exact format of the arguments after type depends on *type*, but usually they consist of the coordinates for one or more points, followed by specifications for zero or more item options. See the subsections on individual item types below for more on the syntax of this command. This command returns the id for the new item. 

> For further informations about useable items see section [ITEM TYPES](#ITEM-TYPES).

<a name="pathName-dchars"></a>
*pathName* **dchars** *tagOrId first ?last?*

> For each item given by *tagOrId*, delete the characters, or coordinates, in the range given by *first* and *last*, inclusive. If some of the items given by *tagOrId* do not support indexing operations then they ignore this operation. Text items interpret *first* and *last* as indices to a character, line and polygon items interpret them as indices to a coordinate (an x,y pair). Indices are described in [INDICES][] above. If *last* is omitted, it defaults to *first*. This command returns an empty string. 

<a name="pathName-delete"></a>
*pathName* **delete** *?*tagOrId* *tagOrId* ...?*

> Delete each of the items given by each *tagOrId*, and return an empty string. 

<a name="pathName-depth"></a>
*pathName* **depth** *tagOrId*

> Returns the depth in the tree hierarchy of the first item matching *tagOrId*. The root item has depth 0 and children of the root has depth 1 and so on.

<a name="pathName-distance"></a>
*pathName* **distance** *tagOrId x y*

> Returns the closest distance between the point (*x, y*) and the first item matching *tagOrId*.

<a name="pathName-dtag"></a>
*pathName* **dtag** *tagOrId ?tagToDelete?*

> For each of the items given by *tagOrId*, delete the tag given by *tagToDelete* from the list of those associated with the item. If an item does not have the tag *tagToDelete* then the item is unaffected by the command. If *tagToDelete* is omitted then it defaults to *tagOrId*. This command returns an empty string. 

<a name="pathName-find"></a>
*pathName* **find** *searchCommand ?arg arg ...?*

> This command returns a list consisting of all the items that meet the constraints specified by *searchCommand* and *arg'*s. *SearchCommand* and *args* have any of the forms accepted by the **addtag** command. The items are returned in stacking order, with the lowest item first. 

<a name="pathName-firstchild"></a>
*pathName* **firstchild** *tagOrId*

> Returns the first child item of the first item matching *tagOrId*. Applies only for groups.

<a name="pathName-focus"></a>
*pathName* **focus** *?*tagOrId*?*

> Set the keyboard focus for the canvas widget to the item given by *tagOrId*. If *tagOrId* refers to several items, then the focus is set to the first such item in the display list that supports the insertion cursor. If *tagOrId* does not refer to any items, or if none of them support the insertion cursor, then the focus is not changed. If *tagOrId* is an empty string, then the focus item is reset so that no item has the focus. If *tagOrId* is not specified then the command returns the id for the item that currently has the focus, or an empty string if no item has the focus. 

> Once the focus has been set to an item, the item will display the insertion cursor and all keyboard events will be directed to that item. The focus item within a canvas and the focus window on the screen (set with the focus command) are totally independent: a given item does not actually have the input focus unless (a) its canvas is the focus window and (b) the item is the focus item within the canvas. In most cases it is advisable to follow the focus widget command with the focus command to set the focus window to the canvas (if it was not there already). 

<a name="pathName-gettags"></a>
*pathName* **gettags** *tagOrId*

> Return a list whose elements are the tags associated with the item given by *tagOrId*. If *tagOrId* refers to more than one item, then the tags are returned from the first such item in the display list. If *tagOrId* does not refer to any items, or if the item contains no tags, then an empty string is returned. 

<a name="pathName-gradient"></a>
*pathName* **gradient** *command ?options?*

> See [GRADIENTS][] for the commands. The gradients created with this command are local to the canvas instance. Only gradients defined this way can be used.

<a name="pathName-icursor"></a>
*pathName* **icursor** *tagOrId index*

> Set the position of the insertion cursor for the item(s) given by *tagOrId* to just before the character whose position is given by *index*. If some or all of the items given by *tagOrId* do not support an insertion cursor then this command has no effect on them. See INDICES above for a description of the legal forms for *index*. Note: the insertion cursor is only displayed in an item if that item currently has the keyboard focus (see the focus widget command, above), but the cursor position may be set even when the item does not have the focus. This command returns an empty string. 

<a name="pathName-imove"></a>
*pathName* **imove** *tagOrId index x y*

> This command causes the *index*'th coordinate of each of the items indicated by *tagOrId* to be relocated to the location (*x,y*). Each item interprets *index *independently according to the rules described in [INDICES][] above. Out of the standard set of items, only line and polygon items may have their coordinates relocated this way. 

> If you apply move on a group item it will apply this to all its descendants, also to child group items in a recursive way.

<a name="pathName-index"></a>
*pathName* **index** *tagOrId index*

> This command returns a decimal string giving the numerical index within *tagOrId* corresponding to *index*. Index gives a textual description of the desired position as described in INDICES above. Text items interpret *index* as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). The return value is guaranteed to lie between 0 and the number of characters, or coordinates, within the item, inclusive. If *tagOrId* refers to multiple items, then the *index* is processed in the first of these items that supports indexing operations (in display list order). 

<a name="pathName-insert"></a>
*pathName* **insert** *tagOrId beforeThis string*

> For each of the items given by *tagOrId*, if the item supports text or coordinate, insertion then string is inserted into the item's text just before the character, or coordinate, whose index is *beforeThis*. Text items interpret *beforeThis* as an index to a character, line and polygon items interpret it as an index to a coordinate (an x,y pair). For lines and polygons the string must be a valid coordinate sequence. See INDICES above for information about the forms allowed for *beforeThis*. This command returns an empty string. 

<a name="pathName-itemcget"></a>
*pathName* **itemcget** *tagOrId option*

> Returns the current value of the configuration option for the item given by *tagOrId* whose name is *option*. This command is similar to the **cget** widget command except that it applies to a particular item rather than the widget as a whole. *Option* may have any of the values accepted by the **create** widget command when the item was created. If *tagOrId* is a tag that refers to more than one item, the first (lowest) such item is used. 

<a name="pathName-itemconfigure"></a>
*pathName* **itemconfigure** *tagOrId ?option? ?value? ?option value ...?*

> This command is similar to the **configure** widget command except that it modifies item-specific options for the items given by *tagOrId* instead of modifying options for the overall canvas widget. If no *option* is specified, returns a list describing all of the available options for the first item given by *tagOrId* (see [Tk_ConfigureInfo][] for information on the format of this list). If *option* is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no *option* is specified). If one or more *option-value* pairs are specified, then the command modifies the given widget option(s) to have the given value(s) in each of the items given by *tagOrId*; in this case the command returns an empty string. The *options* and *values* are the same as those permissible in the **create** widget command when the item(s) were created; see the sections describing individual item types below for details on the legal options. 

<a name="pathName-itempdf"></a>
*pathName* **itempdf** *tagOrId ?extgsProc objProc gradProc?*

> The command return pdf code describing the given *tagOrId*. The function is optimised to work with [pdf4tcl][]. To create pdf from a **path** just call the **canvas** method from the pdf object p.e.:

    $pdf canvas $pathName -bbox [$pathName bbox] -x 0 -y 0

> See function `CanvasDoTkpathItem` in [pdf4tcl][] for details.

> If *extgsProc* is given and item has special graphic state *extgsProc* is called.

> If *objProc* is given and item has special object info *objProc* is called.

> If *gradProc* is given and the item uses a gradient the *gradProc* is called.

<a name="pathName-lastchild"></a>
*pathName* **lastchild** *tagOrId*

> Returns the last child item of the first item matching *tagOrId*. Applies only for groups.

<a name="pathName-lower"></a>
*pathName* **lower** *tagOrId ?belowThis?*

> Move all of the items given by *tagOrId* to a new position in the display list just before the item given by *belowThis*. If *tagOrId* refers to more than one item then all are moved but the relative order of the moved items will not be changed. *BelowThis* is a tag or id; if it refers to more than one item then the first (lowest) of these items in the display list is used as the destination location for the moved items. Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the [raise][] command and [lower][] command, not the **raise** widget command and **lower** widget command for canvases. This command returns an empty string.

> Movement is constrained to siblings. If reference *tagOrId* not given it defaults to first/last item of the root items children. Items which are not siblings to the reference *tagOrId* are silently ignored.

<a name="pathName-move"></a>
*pathName* **move** *tagOrId xAmount yAmount*

> Move each of the items given by *tagOrId* in the canvas coordinate space by adding *xAmount* to the x-coordinate of each point associated with the item and *yAmount* to the y-coordinate of each point associated with the item. This command returns an empty string. 

<a name="pathName-moveto"></a>
*pathName* **moveto** *tagOrId xPos yPos*

Move the items given by *tagOrId* in the canvas coordinate space so that the first coordinate pair of the bottommost item with tag *tagOrId* is located at position (*xPos,yPos*). *xPos* and *yPos* may be the empty string, in which case the corresponding coordinate will be unchanged. All items matching *tagOrId* remain in the same positions relative to each other. This command returns an empty string. 

<a name="pathName-nextsibling"></a>
*pathName* **nextsibling** *tagOrId*

> Returns the next sibling item of the first item matching *tagOrId*. If *tagOrId* is the last child we return empty.

<a name="pathName-parent"></a>
*pathName* **parent** *tagOrId*

> Returns the parent item of the first item matching *tagOrId*. This command works for all items, also for the standard ones. It is therefore better to use this than `cget id -parent` which is only supported for the new path items.

<a name="pathName-prevsibling"></a>
*pathName* **prevsibling** *tagOrId*

> Returns the previous sibling item of the first item matching *tagOrId*. If *tagOrId* is the first child we return empty.

<a name="pathName-raise"></a>
*pathName* **raise** *tagOrId ?aboveThis?*

> Move all of the items given by *tagOrId* to a new position in the display list just after the item given by aboveThis. If *tagOrId* refers to more than one item then all are moved but the relative order of the moved items will not be changed. AboveThis is a tag or id; if it refers to more than one item then the last (topmost) of these items in the display list is used as the destination location for the moved items. This command returns an empty string. 

> Movement is constrained to siblings. If reference *tagOrId* not given it defaults to first/last item of the root items children. Items which are not siblings to the reference *tagOrId* are silently ignored.

> Note: this command has no effect on window items. Window items always obscure other item types, and the stacking order of window items is determined by the raise command and lower command, not the raise widget command and lower widget command for canvases. 

<a name="pathName-rchars"></a>
*pathName* **rchars** *tagOrId first last string*

> This command causes the text or coordinates between *first* and *last* for each of the items indicated by *tagOrId* to be replaced by string. Each item interprets *first* and *last* independently according to the rules described in [INDICES][] above. Out of the standard set of items, text items support this operation by altering their text as directed, and line and polygon items support this operation by altering their coordinate list (in which case string should be a list of coordinates to use as a replacement). The other items ignore this operation. 

<a name="pathName-scale"></a>
*pathName* **scale** *tagOrId xOrigin yOrigin xScale yScale*

> Rescale the coordinates of all of the items given by *tagOrId* in canvas coordinate space. *XOrigin* and *yOrigin* identify the origin for the scaling operation and *xScale* and *yScale* identify the scale factors for x- and y-coordinates, respectively (a scale factor of 1.0 implies no change to that coordinate). For each of the points defining each item, the x-coordinate is adjusted to change the distance from *xOrigin* by a factor of *xScale*. Similarly, each y-coordinate is adjusted to change the distance from *yOrigin* by a factor of *yScale*. This command returns an empty string. 

> Note that some items have only a single pair of coordinates (e.g. windows) and so scaling of them by this command can only move them around.

> If you apply scale on a group item it will apply this to all its descendants, also to child group items in a recursive way. 

<a name="pathName-scan"></a>
*pathName* **scan** *option args*

> This command is used to implement scanning on canvases. It has two forms, depending on option: 

> *pathName* **scan mark** *x y*

> > Records *x* and *y* and the canvas's current view; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget and *x* and *y* are the coordinates of the mouse. It returns an empty string. 

> *pathName* **scan dragto** *x y ?gain?*

> > This command computes the difference between its *x* and *y* arguments (which are typically mouse coordinates) and the x and y arguments to the last scan mark command for the widget. It then adjusts the view by *gain* times the difference in coordinates, where *gain* defaults to 10. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the canvas at high speed through its window. The return value is an empty string. 

<a name="pathName-select"></a>
*pathName* **select** *option ?*tagOrId* arg?*

> Manipulates the selection in one of several ways, depending on *option*. The command may take any of the forms described below. In all of the descriptions below, *tagOrId* must refer to an item that supports indexing and selection; if it refers to multiple items then the first of these that supports indexing and the selection is used. Index gives a textual description of a position within *tagOrId*, as described in [INDICES][] above. 

> *pathName* **select adjust** *tagOrId index*

> > Locate the end of the selection in *tagOrId* nearest to the character given by *index*, and adjust that end of the selection to be at *index* (i.e. including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection is not currently in *tagOrId* then this command behaves the same as the select to widget command. Returns an empty string. 

> *pathName* **select clear**

> > Clear the selection if it is in this widget. If the selection is not in this widget then the command has no effect. Returns an empty string. 

> *pathName* **select from** *tagOrId index*

> > Set the selection anchor point for the widget to be just before the character given by *index* in the item given by *tagOrId*. This command does not change the selection; it just sets the fixed end of the selection for future select to commands. Returns an empty string. 

>  *pathName* **select item**

> > Returns the id of the selected item, if the selection is in an item in this canvas. If the selection is not in this canvas then an empty string is returned. 

> *pathName* **select to** *tagOrId index*

> > Set the selection to consist of those characters of *tagOrId* between the selection anchor point and *index*. The new selection will include the character given by *index*; it will include the character given by the anchor point only if *index* is greater than or equal to the anchor point. The anchor point is determined by the most recent select adjust or select from command for this widget. If the selection anchor point for the widget is not currently in *tagOrId*, then it is set to the same character given by *index*. Returns an empty string. 

<a name="pathName-style"></a>
*pathName* **style** *cmd ?options?*

> See [STYLES](#STYLES) for the commands. The styles created with this command are local to the canvas instance. Only styles defined this way can be used.

> The styleToken is a style created with 'pathName style create'. It's options take precedence over any other options set directly. This is how SVG works (bad?). Currently all a style's options ever set are recorded in a cumulative way using a mask. Even if an option is set to its default it takes precedence over an items option.

<a name="pathName-type"></a>
*pathName* **type** *tagOrId*

> Returns the type of the item given by *tagOrId*, such as rectangle or text. If *tagOrId* refers to more than one item, then the type of the first item in the display list is returned. If *tagOrId* does not refer to any items at all then an empty string is returned. 

<a name="pathName-types"></a>
*pathName* **types**

> List all item types defined in canvas.

<a name=*pathName-xview"></a>
*pathName* **xview** *?args?*

> This command is used to query and change the horizontal position of the information displayed in the canvas's window. It can take any of the following forms: 

> *pathName* **xview**

> > Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the horizontal span that is visible in the window. For example, if the first element is .2 and the second element is .6, 20% of the canvas's area (as defined by the **-scrollregion** option) is off-screen to the left, the middle 40% is visible in the window, and 40% of the canvas is off-screen to the right. These are the same values passed to scrollbars via the **-xscrollcommand** option. 

> *pathName* **xview moveto** *fraction*

> > Adjusts the view in the window so that *fraction* of the total width of the canvas is off-screen to the left. *Fraction* must be a fraction between 0 and 1. 

> *pathName* **xview scroll** *number what*

> > This command shifts the view in the window left or right according to *number* and *what*. *Number* must be an integer. *What* must be either **units** or **pages** or an abbreviation of one of these. If *what* is units, the view adjusts left or right in **units** of the **xScrollIncrement** option, if it is greater than zero, or in units of one-tenth the window's width otherwise. If what is **pages** then the view adjusts in units of nine-tenths the window's width. If *number* is negative then information farther to the left becomes visible; if it is positive then information farther to the right becomes visible. 

<a name="pathName-yview"></a>
*pathName* **yview** *?args?*

> This command is used to query and change the vertical position of the information displayed in the canvas's window. It can take any of the following forms: 

> *pathName* **yview**

> > Returns a list containing two elements. Each element is a real fraction between 0 and 1; together they describe the vertical span that is visible in the window. For example, if the first element is .6 and the second element is 1.0, the lowest 40% of the canvas's area (as defined by the **-scrollregion** option) is visible in the window. These are the same values passed to scrollbars via the **-yscrollcommand** option. 

> *pathName* **yview moveto** *fraction*

> > Adjusts the view in the window so that *fraction* of the canvas's area is off-screen to the top. *Fraction* is a fraction between 0 and 1. 

> *pathName* **yview scroll** *number what*

> > This command adjusts the view in the window up or down according to *number* and *what*. *Number* must be an integer. *What* must be either **units** or **pages**. If *what* is **units**, the view adjusts up or down in units of the **yScrollIncrement** option, if it is greater than zero, or in units of one-tenth the window's height otherwise. If what is pages then the view adjusts in units of nine-tenths the window's height. If *number* is negative then higher information becomes visible; if it is positive then lower information becomes visible. 

<a name="ITEM-TYPES"></a>
## ITEM TYPES

The sections below describe the various types of items supported by canvas widgets. Each item type is characterized by two things: first, the form of the **create** command used to create instances of the type; and second, a set of configuration options for items of that type, which may be used in the **create** and **itemconfigure** widget commands. Most items do not support indexing or selection or the commands related to them, such as **index** and **insert**. Where items do support these facilities, it is noted explicitly in the descriptions below. At present, text, line and polygon items provide this support. For lines and polygons the indexing facility is used to manipulate the coordinates of the item. 

<a name="COMMON-ITEM-OPTIONS"></a>
### COMMON ITEM OPTIONS

The options can be separated into a few groups depending on the nature of an item for which they apply. Not all are implemented.

Arrow options accepted by line, polyline and path objects. Arrows are not
implemented on surfaces (see path::surface).

Options set in a group are inherited by its children but they never override
options explicitly set in children. This also applies to group items configured
with a -style.

    .c create group ?fillOptions strokeOptions genericOptions?

<a name="ITEM-fill"></a>
**-fill** *color\|gradientToken*

> This is either a usual tk color or the name of a gradient.

<a name="ITEM-fillopacity"></a>
**-fillopacity** *value*

> The given *value* is a float value between 0.0 and 1.0

<a name="ITEM-fillrule"></a>
**-fillrule** *nonzero\|evenodd*

<a name="ITEM-stroke"></a>
**-stroke** *color*

<a name="ITEM-strokedasharray"></a>
**-strokedasharray** *dashArray*

> The *dashArray* is a list of integers. Each element represents the number of pixels of a line segment. Only the odd segments are drawn using the "outline" color. The other segments are drawn transparent. 

<a name="ITEM-strokelinecap"></a>
**-strokelinecap** *butt\|round\|square*

<a name="ITEM-strokelinejoin"></a>
**-strokelinejoin** *miter\|round\|bevel*

<a name="ITEM-strokemiterlimit"></a>
**-strokemiterlimit** *float*

<a name="ITEM-strokeopacity"></a>
**-strokeopacity** *value*

> The given *value* is a float value between 0.0 and 1.0

<a name="ITEM-strokewidth"></a>
**-strokewidth** *float*

<a name="ITEM-matrix"></a>
**-matrix** *{a b c d tx ty}*

<a name="ITEM-parent"></a>
**-parent** *tagOrId*

<a name="ITEM-state"></a>
**-state** *active\|disabled\|normal\|hidden*

<a name="ITEM-style"></a>
**-style** *styleToken*

<a name="ITEM-tags"></a>
**-tags** *tagList*

<a name="ITEM-startarrow"></a>
**-startarrow** *boolean*

> Arrowhead on/off; the default value is off.

<a name="ITEM-startarrowlength"></a>
**-startarrowlength** *float*

> Length of the arrowhead.
  * 0.0 is special and draws '|-----'
  * negative values draw '>----'

<a name="ITEM-startarrowwidth"></a>
**-startarrowwidth** *float*

> Arrow width; must be positive.

<a name="ITEM-startarrowfill"></a>
**-startarrowfill** *float*

> Relative to startarrowlength; for example:
  * 0.0: do not fill arrowhead, arrowhead will be two lines
  * 1.0: '<|-------'
  * 2.0: '<>-------'

<a name="ITEM-endarrow"></a>
**-endarrow** *boolean*

> See **-startarrow**.

<a name="ITEM-endarrowlength"></a>
**-endarrowlength** *float*

> See **-startarrowlength**.

<a name="ITEM-endarrowwidth"></a>
**-endarrowwidth** *float*

> See **-startarrowwidth**.

<a name="ITEM-endarrowfill"></a>
**-endarrowfill** *float*

> See **-startarrowfill**.

<a name="GROUP-ITEM"></a>
### GROUP ITEM

<a name="pathName-create-group"></a>
*pathName* **create group** *?fillOptions strokeOptions genericOptions?*

A group item is merely a placeholder for other items, similar to how a
frame widget is a container for other widgets. It is a building block for
the tree structure. Unlike other items, and unlike frame widgets, it
doesn't display anything. It has no coordinates which is an additional
difference. The root item is a special group item with id 0 and tags
equal to "root". The root group can be configured like other items, but
its -tags and -parent options are read only.
Options set in a group are inherited by its children but they never override
options explicitly set in children. This also applies to group items configured
with a -style.

<a name="PATH-ITEM"></a>
### PATH ITEM

<a name="pathName-create-path"></a>
*pathName* **create path** *pathSpec ?fillOptions strokeOptions arrowOptions genericOptions?*

The path specification must be a single list and not concateneted with the rest of the command:

    pathName create path {M 10 10 h 10 v 10 h -10 z} -fill blue
    pathName create path M 10 10 h 10 v 10 h -10 z -fill blue    ;# Error

Furthermore, coordinates are pixel coordinates and nothing else.
SVG: It implements the complete syntax of the path elements d attribute with
one major difference: all separators must be whitespace, no commas, no
implicit assumptions; all instructions and numbers must form a tcl list.

All path specifications are normalized initially to the fundamental atoms
M, L, A, Q, and C, all upper case. When you use the canvas 'coords' command
it is the normalized path spec that is returned. Bad?

Visualize this as a pen which always has a current coordinate after
the first M. Coordinates are floats:

* M x y

> Put the pen on the paper at specified coordinate. Must be the first atom but can appear any time later. The pen doesn't draw anything when moved to this point.

* L x y

> Draw a straight line to the given coordinate. 

* H x

> Draw a horizontal line to the given x coordinate.

* V y

> Draw a vertical line to the given y coordinate.

* A rx ry phi largeArc sweep x y

> Draw an elliptical arc from the current point to (x, y). The points are on an ellipse with x-radius rx and y-radius ry. The ellipse is rotated by phi degrees. If the arc is less than 180 degrees, largeArc is zero, else it is one. If the arc is to be drawn in cw direction, sweep is one, and zero for the ccw direction.

> NB: the start and end points may not coincide else the result  is undefined. If you want to make a circle just do two 180 degree arcs.

* Q x1 y1 x y

> Draw a qadratic Bezier curve from the current point to (x, y) using control point (x1, y1).

* T x y

> Draw a qadratic Bezier curve from the current point to (x, y) The control point will be the reflection of the previous Q atoms control point. This makes smooth paths.

* C x1 y1 x2 y2 x y

> Draw a cubic Bezier curve from the current point to (x, y) using control points (x1, y1) and (x2, y2).

* S x2 y2 x y

> Draw a cubic Bezier curve from the current point to (x, y), using (x2, y2) as the control point for this new endpoint. The first control point will be the reflection of the previous C atoms ending control point. This makes smooth paths.

* Z
   
> Close path by drawing from the current point to the preceeding M point.

You may use lower case characters for all atoms which then means that all
coordinates, where relevant, are interpreted as coordinates relative the
current point.

Helper function for making path definitions:

> **path::path ellipse** *x y rx ry*

> > The function return a path definition of an ellipse with a middle point at *x* and *y* and a radius in x-disrection of *rx* and a radius in y-direction of *ry*.

> **path::path circle** *x y r*

> > The function return a path definition of an circle with a middle point at *x* and *y* and a radius of *r*.

<a name="LINE-ITEM"></a>
### LINE ITEM

<a name="pathName-create-line"></a>
*pathName* **create line** *x1 y1 x2 y2 ?strokeOptions arrowOptions genericOptions?*

Makes a single-segment straight line.

<a name="POLYLINE-ITEM"></a>
### POLYLINE ITEM

<a name="pathName-create-polyline"></a>
*pathName* **create polyline** *x1 y1 x2 y2 .... ?strokeOptions arrowOptions genericOptions?*

Makes a multi-segment line with open ends.

<a name="POLYGON-ITEM"></a>
### POLYGON ITEM

<a name="pathName-create-polygon"></a>
*pathName* **create polygon** *x1 y1 x2 y2 .... ?fillOptions strokeOptions genericOptions?*

Makes a closed polygon.

<a name="RECT-ITEM"></a>
### RECT ITEM

<a name="pathName-create-rect"></a>
*pathName* **create rect** *x1 y1 x2 y2 ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*

This is a rectangle item with optionally rounded corners.
Item specific options:

**-rx** *value*

> Corner x-radius, or if -ry not given it sets the uniform radius.

**-ry** *value*

> Corner y-radius

<a name="CIRCLE-ITEM"></a>
### CIRCLE ITEM

<a name="pathName-create-circle"></a>
*pathName* **create circle** *cx cy ?-r fillOptions strokeOptions genericOptions?*

A plain circle item. Item specific options:

**-r** *value*

> Its radius; defaults to zero

<a name="ELLIPSE-ITEM"></a>
### ELLIPSE ITEM

<a name="pathName-create-ellipse"></a>
*pathName* **create ellipse** *cx cy ?-rx value? ?-ry value? ?fillOptions strokeOptions genericOptions?*

An ellipse item. Item specific options:

**-rx** *value*

> Its x-radius

**-ry** *value*

> Its y-radius


<a name="IMAGE-ITEM"></a>
### IMAGE ITEM

<a name="pathName-create-image"></a>
*pathName* **create image** *x y ?-image -width -height genericOptions?*

This displays an image in the canvas anchored nw. If -width or -height is
nonzero then the image is scaled to this size prior to any affine transform.

image extra options:

**-anchor** *n\|w\|s\|e\|nw\|ne\|sw\|se\|c*

> Default value is nw

**-tintcolor** *color*

> Tint color; the default value is "" which means no tinting

**-tintamount** *value*

*Value* is amount for tinting between 0. and 1.

**-interpolation** *mode*

> Image interpolation *mode* is one of **none, fast** or **best**

**-srcregion** *{x1 y1 x2 y2}*

> Shows only the specified region of image; if x2 or y2 are larger than the image bounds, then the image will be repeated (tiling)

These options are not implemented on surfaces (see path::surface).

<a name="TEXT-ITEM"></a>
### TEXT ITEM

<a name="pathName-create-text"></a>
*pathName* **create text** *x y ?-text string? ?-textanchor start\|middle\|end\|n\|w\|s\|e\|nw\|ne\|sw\|se\|c? ?-fontfamily fontname -fontsize float? ?-fontslant normal\|italic\|oblique? ?-fontweight normal\|bold? ?fillOptions strokeOptions genericOptions? ?-filloverstroke BOOLEAN?*

Displays text as expected. Note that the x coordinate marks the baseline
of the text. Gradient fills are unsupported so far. Especially the font
handling and settings will likely be developed further.
Editing not implemented. The default font family and size is platform dependent.

text extra options:

**-textanchor** *n\|w\|s\|e\|nw\|ne\|sw\|se\|c\|start\|middle\|end*

> Textanchor extended with points of compass.

**-fontslant** *normal\|italic\|oblique*

> Default value is normal

**-fontweight** *normal\|bold*

> Default value is normal

**-filloverstroke** *boolean*

> Fill drawn over the stroke; default value is false

These options are not implemented on surface items (path::surface), except for

**-textanchor** *start\|middle\|end*

<a name="WINDOW-ITEM"></a>
### WINDOW ITEM

Items of type window cause a particular window to be displayed at a given position on the canvas. Window items are created with widget commands of the following form: 

<a name="pathName-create-window"></a>
*pathName* **create window** *x y ?option value ...?*

*pathName* **create window** *coordList ?option value ...?*

The arguments x and y or coordList (which must have two elements) specify the coordinates of a point used to position the window on the display, as controlled by the -anchor option. After the coordinates there may be any number of option-value pairs, each of which sets one of the configuration options for the item. These same option-value pairs may be used in itemconfigure widget commands to change the item's configuration. Theoretically, a window item becomes the current item when the mouse pointer is over any part of its bounding box, but in practice this typically does not happen because the mouse pointer ceases to be over the canvas at that point. 

The following standard options are supported by window items: 

> **-anchor**

> **-state**

> **-tags**

The following extra options are supported for window items: 

**-height** *pixels*

> Specifies the height to assign to the item's window. Pixels may have any of the forms described in the [COORDINATES][] section above. If this option is not specified, or if it is specified as zero, then the window is given whatever height it requests internally. 

**-width** *pixels*

> Specifies the width to assign to the item's window. Pixels may have any of the forms described in the [COORDINATES][] section above. If this option is not specified, or if it is specified as zero, then the window is given whatever width it requests internally. 

**-window** *pathName*

> Specifies the window to associate with this item. The window specified by pathName must either be a child of the canvas widget or a child of some ancestor of the canvas widget. PathName may not refer to a top-level window. 

Note: due to restrictions in the ways that windows are managed, it is not possible to draw other graphical items (such as lines and images) on top of window items. A window item always obscures any graphics that overlap it, regardless of their order in the display list. Also note that window items, unlike other canvas items, are not clipped for display by their containing canvas's border, and are instead clipped by the parent widget of the window specified by the -window option; when the parent widget is the canvas, this means that the window item can overlap the canvas's border. 

<a name="BINDINGS"></a>
## BINDINGS

In the current implementation, new canvases are not given any default behavior: you will have to execute explicit Tcl commands to give the canvas its behavior. 

<a name="CREDITS"></a>
## CREDITS

Tk's canvas widget is a blatant ripoff of ideas from Joel Bartlett's ezd program. Ezd provides structured graphics in a Scheme environment and preceded canvases by a year or two. Its simple mechanisms for placing and animating graphical objects inspired the functions of canvases.

[Tkpath][] was originally developed by Matts Bengtsson.

User visisble changes to the original [Tkpath][] code are:

- changed widget name in **path** and use of namespace **::path**
- -matrix is now a flat list
- tk canvas items removed, only exception is **window** item
- changed item names to match [SVG][] names:
  - **pimage** => **image**
  - **pline** => **line**
  - **ppolygon** => **polygon**
  - **prect** => **rect**
  - **ptext** => **text**
- no unique abbreviations of widget commands

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, svg, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2005-2008 Mats Bengtsson

&copy; 2015- Christian Werner <[email protected]>

&copy; 2016- RenĂ© Zaumseil <[email protected]>

BSD style license.

<a name="SEE-ALSO"></a>
## SEE ALSO

[bind][], [font][], [image][], [scrollbar][], [pdf4tcl][], [SVG][], [Cairo][]

<a name="KEYWORDS"></a>
## KEYWORDS

canvas, pdf, svg, widget

[bind]: bind.htm
[break]: break.htm
[continue]: continue.htm
[font]: font.htm
[image]: image.htm
[options]: options.htm
[raise]: raise.htm
[scrollbar]: scrollbar.htm
[lower]: lower.htm
[Tk_ConfigureInfo]: ConfigWidg.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[pdf4tcl]: <https://sourceforge.net/projects/pdf4tcl/>
[SVG]: <http://www.w3.org/TR/SVG11/>
[Cairo]: <http://cairographics.org>


Added doc/tkoWidget.3.md.











































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# tkoWidget(3) -- oo class like widgets

*   [NAME](#NAME)
*   [SYNOPSIS](#SYNOPSIS)
*   [ARGUMENTS](#ARGUMENTS)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [SEE ALSO](#SEE-ALSO)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="NAME"></a>
## NAME

TkoWidgetClassDefine,
TkoWidgetOptionVar,
TkoWidgetOptionGet,
TkoWidgetOptionSet,
TkoWidgetWindow -- tko widget class commands

<a name="SYNOPSIS"></a>
## SYNOPSIS

**#include "tkoWidget.h"**

int  
**TkoWidgetClassDefine**(*interp,clazz,classname,methods,options*)  
Tk\_Window \*  
**TkoWidgetWindow**(*object*)  
Tcl\_Obj \*  
**TkoWidgetOptionVar**(*object*)  
Tcl\_Obj \*  
**TkoWidgetOptionGet**(*interp,object,option*)  
int  
**TkoWidgetOptionSet**(*interp,context,option,type,meta,offset*)  

<a name="ARGUMENTS"></a>
## ARGUMENTS

| Tcl\_Interp **\*interp** | Used interpreter.  
| Tcl\_Class **clazz** | Oo class of widget.  
| Tcl\_Obj **\*classname** |Oo class name of widget.  
| const Tcl\_MethodType **\*methods** | This array defines class methods to create. For creation methods see [Tcl_NewMethod] manpage. If the method name of the first array entry is not NULL it will be used as **constructor**, if the second method name is not NULL it used as **destructor**. Then follow public methods until an entry with an method name equal NULL comes. Then follow private methods until an entry with an method name equal NULL comes.  
| const tkoWidgetOptionDefine **\*options** | This array contain option definitions.  
| Tcl\_Object **object** | This is the current object reference.  
| Tcl\_Obj **\*option** | The name of the used option.  
| Tcl\_ObjectContext **context** | The context of the current object. Used to get associated object data.  
| tkoWidgetOptionType **type** | A type used in the common option setting routine.  
| Tcl\_ObjectMetadataType **\*meta** | The type of metadata attaches to the current object.  
| size\_t **offset** | Offset of variable to set in the attaches meta data record.  

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **TkoWidgetClassDefine** function can be used to define options and methods of an **tko::widget** subclass. The function is used in the widget class definition of a new tko widget class.

The **TkoWidgetWindow** function return the address of the internally created Tk\_Window. Subclasses should check the address on NULL after creation. If the Tk\_Window\* at these address is NULL the widget is destroyed and it should not be used.

The **TkoWidgetOptionVar** function return the globally accessible name of the array variable holding the option values. Additionall there is an field "**.**" containing the tk widget path name of the widget.

The **TkoWidgetOptionGet** function returns the current value of the given option.

The **TkoWidgetOptionSet** function can be used to check given *option* values and set C record structure fields at the given *offset*. The record will be retrieved using the given *meta* metadata. The *type* must be one of the **tkoWidgetOptionType** described below.

### Struct: `tkoWidgetOptionDefine`

    typedef struct tkoWidgetOptionDefine {
      const char *option;    /* Name of option. Starts with "-" minus sign */
      const char *dbname;    /* Option DB name or synonym option if dbclass is NULL */
      const char *dbclass;   /* Option DB class name or NULL for synonym options. */
      const char *defvalue;  /* Default value. */
      int flags;             /* bit array of TKO_OPTION_* values to configure option behaviour */
      Tcl_Obj *optionPtr;    /* tko internally used, always init with NULL! */
      const char *proc;      /* If not NULL it is the body of the newly created -option method */
      Tcl_MethodCallProc *method;     /* If not NULL it is the function name of the -option method */
      tkoWidgetOptionType type;       /* if greater 0 then option type used in common option set method */
      Tcl_ObjectMetadataType *meta;   /* meta data address used in common option set method */
      int offset;            /* offset in meta data struct */
    } tkoWidgetOptionDefine;
    #define TKO_OPTION_READONLY 0x1 /* option is only setable at creation time */
    #define TKO_OPTION_HIDE     0x2 /* option is hidden in configure method */ 

### Enum: `tkoWidgetOptionType`

Suported enum type in the TkowidgetOptinSet() function. In comments is the type of the address provided in the **TkoWidgetOptionSet** funtion.

    typedef enum tkoWidgetOptionType {
        TKO_SET_CLASS = 1,     /* (Tcl_Obj **)address */
        TKO_SET_VISUAL, /* (Tcl_Obj **)address */
        TKO_SET_COLORMAP,       /* (Tcl_Obj **)address */
        TKO_SET_USENULL,        /* (Tcl_Obj **)address */
        TKO_SET_CONTAINER,      /* (int *)address */
        TKO_SET_TCLOBJ, /* (Tcl_Obj **)address */
        TKO_SET_XCOLOR, /* (Xcolor **)address */
        TKO_SET_3DBORDER,       /* (Tk_3DBorder *)address */
        TKO_SET_PIXEL,  /* (int *)address */
        TKO_SET_PIXELNONEGATIV, /* (int *)address */
        TKO_SET_PIXELPOSITIV,   /* (int *)address */
        TKO_SET_DOUBLE, /* (double *)address */
        TKO_SET_BOOLEAN,        /* (int *)address */
        TKO_SET_CURSOR, /* (Tk_Cursor *)address */
        TKO_SET_INT,    /* (int *)address */
        TKO_SET_RELIEF, /* (int *)address */
        TKO_SET_ANCHOR, /* (int *)address */
        TKO_SET_WINDOW, /* (Tk_Window *)address */
        TKO_SET_FONT,   /* (Tk_Font *)address */
        TKO_SET_STRING, /* (char **)address */
        TKO_SET_STRINGNULL,     /* (char **)address */
        TKO_SET_SCROLLREGION,   /* (int *[4])address */
        TKO_SET_JUSTIFY /* (Tk_Justify *)address */
    } tkoWidgetOptionType;

<a name="SEE-ALSO"></a>
## SEE ALSO

[frame][], [labelframe][], [toplevel][], [oo::class][]

<a name="KEYWORDS"></a>
## KEYWORDS

oo widget method option

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2019- RenĂ© Zaumseil <[email protected]>

BSD style license.

[options]: options.htm
[frame]: frame.htm
[labelframe]: labelframe.htm
[toplevel]: toplevel.htm
[oo::class]: class.htm
[graph]: graph.htm
[path]: path.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>


Added doc/tkoWidget.n.md.





















































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# tko::widget(n) -- oo class like widgets

*   [SYNOPSIS](#SYNOPSIS)
*   [TKO STANDARD OPTIONS](#TKO-STANDARD-OPTIONS)  
  [-class, class, Class](#-class)  
  [-screen, screen, Screen](#-screen)  
*   [DESCRIPTION](#DESCRIPTION)  
*   [WIDGET METHODS](#WIDGET-METHODS)  
*   [WIDGET OPTIONS](#WIDGET-OPTIONS)  
*   [EXAMPLES](#EXAMPLES)  
*   [SEE ALSO](#SEE-ALSO)  
*   [KEYWORDS](#KEYWORDS)  
*   [COPYRIGHT](#COPYRIGHT)  

<a name="SYNOPSIS"></a>
## SYNOPSIS

    oo::class create myWidget {
      {*}$::tko::unknown    ;# define unknown method to support common tk widget style
      superclass "tkoClass" ;# one of the provided tko widget class's
      variable tko          ;# array with options *$tko(-option)* and widget path *$tko(.)*
      method -myoption {...};# deal with option when set
      ...
      constructor {optionlist arglist} {
        next [concat {
          {-myoption myOption MyOption value}
          ...
        } $optionlist] $arglist
        ...
      }
      destructor {next}
    }

The command creates a new Tcl class whose name is *widgetClass*. This command may be used to create new widgets. Each new widget class has as a *tkoClass* as superclass. The common functionality is in the **tko::widget** class. Currently the following *tkoClass* superclasses are provided:

**::tko::toplevel** *pathName ?option value? ..*

**::tko::frame** *pathName ?option value? ..*

**::tko::labelframe** *pathName ?option value? ..*

**::graph** *pathName ?option value? ..*

**::path** *pathName ?option value? ..*

<a name="TKO-STANDARD-OPTIONS"></a>
## TKO STANDARD OPTIONS

<a name="-class"></a>
Command-Line Name: **-class**  
Database Name: **class**  
Database Class: **Class**

> > Define class for use in getting values from option database. Can only be set on widget creation time.

<a name="-screen"></a>
Command-Line Name: **-screen**  
Database Name: **screen**  
Database Class: **Screen**

> > Affect creation of underlying widget structure. If given the created widget will be a toplevel widget.

<a name="DESCRIPTION"></a>
## DESCRIPTION

The **tko::widget** class contain the common widget functionality. To get these functionality you have to create a subclass of the **tko::widget** class. This can only be done in C. To use the functionality on tcl script level the following classes are provided.

<a name="tko-toplevel"></a>
## tko::toplevel

These class contain the functionality of the [toplevel][] widget command.

<a name="tko-frame"></a>
## tko::frame

These class contain the functionality of the [frame][] widget command.

<a name="tko-labelframe"></a>
## tko::labelframe

These class contain the functionality of the [labelframe][] widget command.

<a name="tko-graph"></a>
## graph

These class contain the functionality of the [Rbc][] graph widget command. It is described in detail in the [graph][] manpage.

<a name="tko-path"></a>
## path

These class contain the functionality of the [Tkpath][] widget command. It is described in detail in the [path][] manpage.

<a name="WIDGET-METHODS"></a>
### WIDGET METHODS

Widget methods can be dynamically added and removed at class or object level.

**NOTE** Do not change *tkoClass*'s behaviour. Instead create your own class and modify it to your need! Or change created widget objects behaviour.

The **tko::widget** class provides the following methods.

<a name="method-constructor"></a>
**constructor {optionlist arglist}**

> The *optionlist* contain a sorted list off option descriptions as described in **configure optonadd**. It will be processed in the **tko::widget** constructor in the given order. It should always start with the "-class" option definition. The necessary *-option* method's should already be exist.

> The *arglist* is the normal *-option value ..* list of all tk widgets.

> Each widget class constructor should call **next** *$optionlist $arglist*!


<a name="method-destructor"></a>
**destructor {}**

> Here you can free your own ressources. Don't forget to call **next**! After **next** the **tko::widget** data are gone (widget path, tko array variable).

<a name="method-cget"></a>
**cget** *option*

> Return the current vlaue of the given *option*.

<a name="method-configure"></a>
**configure** *args*

> **configure**

> > If *args* is empty the method will return a sorted list of all configuration options.

> **configure** *-option*

> > If we have one element in *args* starting with a minus sign ("-") then the method return the configuration list including the current value of the given *-option*.

> **configure** *-option value ..*

> > If we have an even number list in *args* and the first element starts with a minus sign ("-") then the method does configure all the given option-value pairs. If an error occurs the the corresponding element is not set and the method gives an error. Alrready successfull set options remain.

> **configure init**

> > This is an internal function used in constructing new widgets. It is used in the *unknown* method to initialize all options.

> **configure optionadd** *-synonym -option*

> > Add a *-synonym* for a given *-option*. The *-option* needs not to be defined at this time.

> **configure optionadd** *-synonym dbnam dbclass ?default? ?flags?*

> > Add a new option. If ?flags? is equal "1" then the option is readonly and can only be set in this call. Before adding a new option a *-option* method must created. The method will be called without any arguments. The method can access the new value using the *tko(-option)* array variable. If the method throws a n error the array variable will be reset to the old value.

> **configure optiondel** *-option*

> > Delete the given option and unset the entry in the tko array variable. The created *-option* method's are not deleted. This is the task of the caller.

> **configure optionhide** *?-option? ..*

> > If no *-option* is given return a list of all not configure'able options. Otherwise hide all of the given options.

> **configure optionshow** *?-option? ..*

> > If no *-option* is given return a list of all configure'able options. Otherwise make all of the given options configure'able.

> **configure optionvar**

> > The method return the global varname of the tko array variable holding all option values.

<a name="method-cget"></a>
**\_tko\_configure**

> This is an virtuel method of the **tko::widget** class. This method will be called at the end of each **configure** *-option value ..* call. It can be implemented in each class to amke necessary changes. If it is implemented it should also call **next** to notify underlying classes.

<a name="WIDGET-OPTIONS"></a>
### WIDGET OPTIONS

Widget option values are saved in an option array. The option name is the field name in the array. Additionally is an field "**.**" containing the tk widget path name of the widget. The name of the option array variable can be retrieved using the following code:
    set myVar [.w configure optionvar]
    parray $myVar

Widget options can be dynamically added and removed at class or object level.
It is possible to hide and unhide options.

<a name="EXAMPLES"></a>
### EXAMPLES

    # Add options at class creation:
    oo::class create ::myWidget {
      {*}$::tko::unknown
      superclass ::tko::frame
      variable tko
      method -myoption {} {puts $tko(-myoption)}
      method -myreadonly {} {puts $tko(-myreadonly)}
      constructor {optionlist arglist} {
        next [concat {
          {-myoption myOption MyOption value}
          {-myreadonly myReadonly MyReadonly value 1}
        } $optionlist] $arglist
      }
    }
    proc output {} {
      puts "config: [.w configure]"
      puts "normal: [.w configure optionhide]"
      puts "hidden: [.w configure optionshow]"
    }
    # Add options at object level:
    ::myWidget .w
    oo::objdefine .w method -o1 {} {my variable tko; puts $tko(-o1)}
    oo::objdefine .w method -o2 {} {my variable tko; puts $tko(-o2)}
    .w configure optionadd -o1 o1 O1 v1 1 ;#->
    .w configure optionadd -o2 o2 O2 v2
    output
    # Remove one and hide rest
    .w configure optiondel -o2
    .w configure optionhide {*}[.w configure optionshow]
    output
    # Reverse state
    .w configure optionshow {*}[.w configure optionhide]
    output


<a name="SEE-ALSO"></a>
## SEE ALSO

[frame][], [labelframe][], [toplevel][], [oo::class][]

<a name="KEYWORDS"></a>
## KEYWORDS

oo widget method option

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 2019- RenĂ© Zaumseil <[email protected]>

BSD style license.

[options]: options.htm
[frame]: frame.htm
[labelframe]: labelframe.htm
[toplevel]: toplevel.htm
[oo::class]: class.htm
[graph]: graph.htm
[path]: path.htm
[Tkpath]: <https://sourceforge.net/projects/tclbitprint/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>


Added doc/vector.n.md.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# graph::vector(n) -- Vector data type for graph widgets

*   [SYNOPSIS](#SYNOPSIS)
*   [DESCRIPTION](#DESCRIPTION)
*   [SYNTAX](#SYNTAX)
  * [graph::vector configure](#graph::vector-configure) *?option value?...*
  * [graph::vector create](#graph::vector-create) *vectorName?(...)? ?option value?...*
  * [graph::vector destroy](#graph::vector-destroy) *vectorName ?vectorName?...*
  * [graph::vector expression](#graph::vector-expression) *expression*
  * [graph::vector names](#graph::vector-names) *?pattern...?*
  * [graph::vector op](#graph::vector-op) *operation vectorName ?arg?...*
*   [VECTOR INDICES](#VECTOR-INDICES)
*   [VECTOR OPERATIONS](#VECTOR-OPERATIONS)
  * [vectorName +](#vectorName-plus") *item*
  * [vectorName -](#vectorName-minus") *item*
  * [vectorName `*`](#vectorName-mult") *item*
  * [vectorName /](#vectorName-div") *item*
  * [vectorName append](#vectorName-append) *item ?item?...*
  * [vectorName binread](#vectorName-binread) *channel ?length? ?switches?*
  * [vectorName binwrite](#vectorName-binwrite) *channel ?length? ?-at index?*
  * [vectorName clear](#vectorName-clear)
  * [vectorName delete](#vectorName-delete) *index ?index?...*
  * [vectorName dup](#vectorName-dup) *destName*
  * [vectorName expr](#vectorName-expr) *expression*
  * [vectorName index](#vectorName-index) *index ?value?...*
  * [vectorName insert](#vectorName-insert) *index item ?item?...*
  * [vectorName length](#vectorName-length) *?newSize?*
  * [vectorName matrix](#vectorName-matrix) *...*
    * [vectorName matrix copy](#vectorName-matrix-copy) *dstcolumn srccolumn ?srcVec?*
    * [vectorName matrix delete](#vectorName-matrix-delete) *column*
    * [vectorName matrix get](#vectorName-matrix-get) *column*
    * [vectorName matrix insert](#vectorName-matrix-insert) *column ?initvalue?*
    * [vectorName matrix multiply](#vectorName-matrix-multiply) *srcVec ?dstVec?*
    * [vectorName matrix numcols](#vectorName-matrix-numcols) *?size?*
    * [vectorName matrix numrows](#vectorName-matrix-numrows) *?size?*
    * [vectorName matrix set](#vectorName-matrix-set) *column ?valuelist?*
    * [vectorName matrix shift](#vectorName-matrix-shift) *column amount ?startoffset?*
    * [vectorName matrix sort](#vectorName-matrix-sort) *column ?-reverse?*
    * [vectorName matrix transpose](#vectorName-matrix-transpose)
  * [vectorName merge](#vectorName-merge) *srcName ?srcName?...*
  * [vectorName notify](#vectorName-notify) *?keyword? ?script?*
  * [vectorName populate](#vectorName-populate) *destName ?density?*
  * [vectorName range](#vectorName-range) *firstIndex ?lastIndex?...*
  * [vectorName search](#vectorName-search) *value ?value?*
  * [vectorName set](#vectorName-set) *item*
  * [vectorName seq](#vectorName-seq) *start ?finish? ?step?*
  * [vectorName sort](#vectorName-sort) *?-reverse? ?argName?...*
  * [vectorName split](#vectorName-split) *dstName ?dstName?...*
  * [vectorName variable](#vectorName-variable) *varName*
* [C LANGUAGE API](#C-LANGUAGE-API)
* [LIBRARY ROUTINES](#LIBRARY-ROUTINES)
* [C API EXAMPLE](#C-API-EXAMPLE)
* [INCOMPATIBILITIEA](#INCOMPATIBILITIES)
* [EXAMPLE](#EXAMPLE)
* [CREDITS](#CREDITS)  
* [KEYWORDS](#KEYWORDS)
* [COPYRIGHT](#COPYRIGHT)

<a name="SYNOPSIS"></a>
## SYNOPSIS 

**[graph::vector configure](#graph::vector-configure)** *?option value? ...*

**[graph::vector create](#graph::vector-create)** *vectorName?(...)? ?option value?...*

**[graph::vector destroy](#graph::vector-destroy)** *vectorName ?vectorName...?*

**[graph::vector expr](#graph::vector-expr)** *expression*

**[graph::vector names](#graph::vector-names)** *?pattern...?*

**[graph::vector op](#graph::vector-op)** *operation vectorName ?arg?...*

<a name="DESCRIPTION"></a>
## DESCRIPTION 

The vector command creates a vector of floating point values. The vector's components can be manipulated in three ways: through a Tcl array variable, a Tcl command, or the C API.

A vector is simply an ordered set of numbers. The components of a vector are real numbers, indexed by counting numbers.

Vectors are common data structures for many applications. For example, a graph may use two vectors to represent the X-Y coordinates of the data plotted. The graph will automatically be redrawn when the vectors are updated or changed. By using vectors, you can separate data analysis from the graph widget. This makes it easier, for example, to add data transformations, such as splines. It's possible to plot the same data to in multiple graphs, where each graph presents a different view or scale of the data.

You could try to use Tcl's associative arrays as vectors. Tcl arrays are easy to use. You can access individual elements randomly by specifying the index, or the set the entire array by providing a list of index and value pairs for each element. The disadvantages of associative arrays as vectors lie in the fact they are implemented as hash tables.

- There's no implied ordering to the associative arrays. If you used vectors for plotting, you would want to insure the second component comes after the first, an so on. This isn't possible since arrays are actually hash tables. For example, you can't get a range of values between two indices. Nor can you sort an array.

- Arrays consume lots of memory when the number of elements becomes large (tens of thousands). This is because each element's index and value are stored as strings in the hash table.

- The C programming interface is unwieldy. Normally with vectors, you would like to view the Tcl array as you do a C array, as an array of floats or doubles. But with hash tables, you must convert both the index and value to and from decimal strings, just to access an element in the array. This makes it cumbersome to perform operations on the array as a whole.

The vector command tries to overcome these disadvantages while still retaining the ease of use of Tcl arrays. The vector command creates both a new Tcl command and associate array which are linked to the vector components. You can randomly access vector components though the elements of array. Not all indices are generated for the array, so printing the array (using the parray procedure) does not print out all the component values. You can use the Tcl command to access the array as a whole. You can copy, append, or sort vector using its command. If you need greater performance, or customized behavior, you can write your own C code to manage vectors.

<a name="SYNTAX"></a>
## SYNTAX

<a name="graph::vector-configure"></a>
**graph::vector configure** *?-flush bool -watchunset bool -oldcreate bool -maxsize int -novariable bool -nocommand bool?*

> The configure operation sets the default options used in creating vectors: these options are global to the interpreter. The -maxsize option, when non-zero, limits creation size. The -oldcreate enable the creation shortcut: vector vec1 vec2 .... See the create command for details on the others. By default, these are all disabled or zero.

<a name="graph::vector-create"></a>
**graph::vector create** *vectorName?(...)? ?option value?*

> The create operation creates a new vector vectorName. This creates both a Tcl command and array variable called vectorName. The name vectorName must be unique, so another Tcl command or array variable can not already exist in the current scope. You may access the components of the vector using the variable. If you change a value in the array, or unset an array element, the vector is updated to reflect the changes. When the variable vectorName is unset, the vector and its Tcl command are also destroyed.

> *vectorName*

> > This creates a new vector vectorName which initially has no components.

> *vectorName(size)*

> > This second form creates a new vector which will contain size number of components. The components will be indexed starting from zero (0). The default value for the components is 0.0.

> *vectorName(rows,columns)*

> > This form allows creation of a matrix with the specified columns and `rows*columns` elements. See the matrix section for more details.

> *vectorName(first:last)*

> > The last form creates a new vector of indexed first through last. First and last can be any integer value so long as first is less than last.

> The vector has optional switches that affect how the vector is created. They are as follows:

> **-variable** *varName*

> > Specifies the name of a Tcl variable to be mapped to the vector. If the variable already exists, it is first deleted, then recreated. If varName is the empty string, then no variable will be mapped. You can always map a variable back to the vector using the vector's variable operation.

> **-command** *cmdName*

> > Maps a Tcl command to the vector. The vector can be accessed using cmdName and one of the vector instance operations. A Tcl command by that name cannot already exist. If cmdName is the empty string, no command mapping will be made.

> **-watchunset** *boolean*

> > Indicates that the vector should automatically delete itself if the variable associated with the vector is unset. By default, the vector will not be deleted. This is different from previous releases. Set boolean to "true" to get the old behavior.

> **-flush** *boolean*

> > Indicates that the vector should automatically flush the cached variable elements which unsets all the elements of the Tcl array variable associated with the vector, freeing memory associated with the variable. This includes both the hash table and the hash keys. The down side is that this effectively flushes the caching of vector elements in the array. This means that the subsequent reads of the array will require a decimal to string conversion. By default, flushing is disabled.

> Vector names must start with a letter and consist of letters, digits, or underscores.

> > <code>
	# Error: must start with letter  
	graph::vector create 1abc  
</code>

> You can automatically generate vector names using the "#auto" vector name. The create operation will generate a unique vector name.

> > <code>
	set vec [graph::vector create #auto]  
	puts "$vec has [$vec length] components"  
</code>

> If successful, vector returns the name of the vector. It also creates a new Tcl command by the same name. You can use this command to invoke various operations that query or modify the vector. The general form is:

> **vectorName** *operation ?arg?...*

> Both, operation and its arguments determine the exact behavior of the command. The operations available for the graph are described in section [VECTOR OPERATIONS](#VECTOR-OPERATIONS).

<a name="graph::vector-destroy"></a>
**graph::vector destroy** *vectorName ?vectorName...?*

> Destroy given vectors.

<a name="graph::vector-expr"></a>
**graph::vector expr** *expression*

> All binary operators take vectors as operands (remember that numbers are treated as one-component vectors).The exact action of binary operators depends upon the length of the second operand. If the second operand has only one component, then each element of the first vector operand is computed by that value. For example, the expression "x * 2" multiples all elements of the vector x by 2. If the second operand has more than one component, both operands must be the same length. Each pair of corresponding elements are computed. So "x + y" adds the the first components of x and y together, the second, and so on.

> The valid operators are listed below, grouped in decreasing order of precedence:

> **- !**

> > Unary minus and logical NOT. The unary minus flips the sign of each component in the vector. The logical not operator returns a vector of whose values are 0.0 or 1.0. For each non-zero component 1.0 is returned, 0.0 otherwise.

> **^**

> > Exponentiation.

> **\* / %**

> > Multiply, divide, remainder.

> **+ -**

> > Add and subtract.

> **<< >>**

> > Left and right shift. Circularly shifts the values of the vector

> **< > <= >=**

> > Boolean less, greater, less than or equal, and greater than or equal. Each operator returns a vector of ones and zeros. If the condition is true, 1.0 is the component value, 0.0 otherwise.

> **== !=**

> > Boolean equal and not equal. Each operator returns a vector of ones and zeros. If the condition is true, 1.0 is the component value, 0.0 otherwise.

> **&&**

> > Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise.

> **||**

> > Logical OR. Produces a 0 result if both operands are zero, 1 otherwise.

> **x?y:z**

> > If-then-else, as in C.

> See the C manual for more details on the results produced by each operator. All of the binary operators group left-to-right within the same precedence level.

> Several mathematical functions are supported for vectors. Each of the following functions invokes the math library function of the same name; see the manual entries for the library functions for details on what they do. The operation is applied to all elements of the vector returning the results. All functions take a vector operand. If no vector operand is used in the call, the current vector is assumed. eg.

> <code>
        vector create aVec
        aVec seq 0 100
        aVec expr {2*abs(aVec)-1}
        aVec length 100
        aVec expr {2*row()}
        vector expr {2*row()} ; # ERROR!
</code>

> Standard mathematical functions:

> > **acos	cos	hypot	sinh**  
> > **asin	cosh	log	sqrt**  
> > **atan	exp	log10	tan**    
> > **ceil	floor	sin	tanh**  

> Additional functions are:

> > **abs**

> > > Returns the absolute value of each component.

> > **random**

> > > Returns a vector of non-negative values uniformly distributed between [0.0, 1.0) using drand48. The seed comes from the internal clock of the machine or may be set manual with the srandom function.

> > **round**

> > > Rounds each component of the vector.

> > **srandom**

> > > Initializes the random number generator using srand48. The high order 32-bits are set using the integral portion of the first vector component. All other components are ignored. The low order 16-bits are set to an arbitrary value.

> The following functions return a single value.

> > **adev**

> > > Returns the average deviation (defined as the sum of the absolute values of the differences between component and the mean, divided by the length of the vector).

> > **kurtosis**

> > > Returns the degree of peakedness (fourth moment) of the vector.

> > **length**

> > > Returns the number of components in the vector.

> > **max**

> > > Returns the vector's maximum value.

> > **mean**

> > > Returns the mean value of the vector.

> > **median**

> > > Returns the median of the vector.

> > **min**

> > > Returns the vector's minimum value.

> > **q1**

> > > Returns the first quartile of the vector.

> > **q3**

> > > Returns the third quartile of the vector.

> > **prod**

> > > Returns the product of the components.

> > **sdev**

> > > Returns the standard deviation (defined as the square root of the variance) of the vector.

> > **skew**

> > > Returns the skewness (or third moment) of the vector. This characterizes the degree of asymmetry of the vector about the mean.

> > **sum**

> > > Returns the sum of the components.

> > **var**

> > > Returns the variance of the vector. The sum of the squared differences between each component and the mean is computed. The variance is the sum divided by the length of the vector minus 1.

> This last set of functions returns a vector of the same length as the argument.

> > **invert**

> > > Returns vector with elements in reversed order.

> > **norm**

> > > Scales the values of the vector to lie in the range [0.0..1.0].

> > **row**

> > > Psuedo function to get the current row.

> > **sort**

> > > Returns the vector components sorted in ascending order.

> > **shift(nVec,N)**

> > > This is the only function taking a second arg. It provides a version of nvec shifted by N places. When N is a scalar or vector with only one element, shift fills vacant area with 0. Otherwise the second element of nVec is used for the fill value. One use for this is providing running totals.

<a name="graph::vector-names"></a>
**graph::vector names** *?pattern?*

> Return names of all defined vectors.

<a name="graph::vector-op"></a>
**graph::vector op** *operation vectorName ?arg?...*

> Invoke instance operation. Supported operations are defined in the next section. Op is the only way to invoke instance operation sub-commands when -command is defined as empty in a vector. It also allows writing vector code that is checkable by a syntax checkers. eg.

> <code>
    graph::vector create v1  
    v1 op append {1 2 3}  
    v1 op modify 1 2.1  
</code>

<a name="VECTOR-INDICES"></a>
## VECTOR INDICES

Vectors are indexed by integers. You can access the individual vector components via its array variable or Tcl command. The string representing the index can be an integer, a numeric expression, a range, or a special keyword.

The index must lie within the current range of the vector, otherwise an an error message is returned. Normally the indices of a vector are start from 0. But you can use the offset operation to change a vector's indices on-the-fly.

> <code>
puts $vectorName(0)  
vectorName offset -5  
puts $vectorName(-5)  
</code>

When matrix numcols is > 1, 2D indexes are supported using ROW,COL form.

> <code>
vectorName matrix numcols 3  
puts vectorName(0,2)  
</code>

You can also use numeric expressions as indices. The result of the expression must be an integer value.

> <code>
set n 21  
set vectorName($n+3) 50.2  
</code>

The following special non-numeric indices are available: min, max, end, and ++end.

> <code>
puts "min = $vectorName($min)"  
set vectorName(end) -1.2  
</code>

The indices min and max will return the minimum and maximum values of the vector. Also available are: prod, sum, and mean. The index end returns the value of the last component in the vector. he index end,0 returns the value of the last row in column 0 of the vector. The index ++end is used to append new value onto the vector. It automatically extends the vector by numcols and sets its value.

> <code>
 # Append an new component to the end  
set vectorName(++end) 3.2  
</code>

A range of indices can be indicated by a colon (:).

> <code>
 # Set the first six components to 1.0  
set vectorName(0:5) 1.0  
</code>

If no index is supplied the first or last component is assumed.

> <code>
 # Print the values of all the components  
puts $vectorName(:)  
</code>

<a name="VECTOR-OPERATIONS"></a>
## VECTOR OPERATIONS

You can also use the vector's Tcl command to query or modify it. The general form is

> **vectorName** *operation arg...*

Note this is equivalent to the form:

> **graph::vector op** *operation vectorName ?arg?...*

Both operation and its arguments determine the exact behavior of the command. The operations available for vectors are listed below.

<a name="vectorName-plus"></a>
**vectorName +** *item*

<a name="vectorName-minus"></a>
**vectorName -** *item*

<a name="vectorName-mult"></a>
**vectorName** `*` *item*

<a name="vectorName-div"></a>
**vectorName /** *item*

> Perform binary op and return result as a list.

<a name="vectorName-append"></a>
**vectorName append** *item ?item?...*

> Appends the component values from item to vectorName. Item can be either the name of a vector or a list of numeric values.

<a name="vectorName-binread"></a>
**vectorName binread** *channel ?length? ?switches?*

> Reads binary values from a Tcl channel. Values are either appended to the end of the vector or placed at a given index (using the -at option), overwriting existing values. Data is read until EOF is found on the channel or a specified number of values length are read (note that this is not necessarily the same as the number of bytes). The following switches are supported:

> **-swap**

> > Swap bytes and words. The default endian is the host machine.

> **-at** *index*

> > New values will start at vector index index. This will overwrite any current values.

> **-format** *format*

> > Specifies the format of the data. Format can be one of the following: "i1", "i2", "i4", "i8", "u1, "u2", "u4", "u8", "r4", "r8", or "r16". The number indicates the number of bytes required for each value. The letter indicates the type: "i" for signed, "u" for unsigned, "r" or real. The default format is "r16".

<a name="vectorName-binwrite"></a>
**vectorName binwrite** *channel ?length? ?-at index?*

> Like binread, but writes data.

<a name="vectorName-clear"></a>
**vectorName clear**

> Clears the element indices from the array variable associated with vectorName. This doesn't affect the components of the vector. By default, the number of entries in the Tcl array doesn't match the number of components in the vector. This is because its too expensive to maintain decimal strings for both the index and value for each component. Instead, the index and value are saved only when you read or write an element with a new index. This command removes the index and value strings from the array. This is useful when the vector is large.

<a name="vectorName-delete"></a>
**vectorName delete** *index ?index?...*

> Deletes the indexth component from the vector vectorName. Index is the index of the element to be deleted. This is the same as unsetting the array variable element index. The vector is compacted after all the indices have been deleted.

<a name="vectorName-dup"></a>
**vectorName dup** *destName*

> Copies vectorName to destName. DestName is the name of a destination vector. If a vector destName already exists, it is overwritten with the components of vectorName. Otherwise a new vector is created.

<a name="vectorName-expr"></a>
**vectorName expr** *expression*

> Computes the expression and resets the values of the vector accordingly. Both scalar and vector math operations are allowed. All values in expressions are either real numbers or names of vectors. All numbers are treated as one component vectors.

<a name="vectorName-index"></a>
**vectorName index** *index ?value?...*

> Get/set individual vector values. This provides element updating when -variable is set to empty.

<a name="vectorName-insert"></a>
**vectorName insert** *index item ?item?...*

> Inserts the component values from item to vectorName at index Item can be either the name of a vector or a list of numeric values.

<a name="vectorName-length"></a>
**vectorName length** *?newSize?*

> Queries or resets the number of components in vectorName. NewSize is a number specifying the new size of the vector. If newSize is smaller than the current size of vectorName, vectorName is truncated. If newSize is greater, the vector is extended and the new components are initialized to 0.0. If no newSize argument is present, the current length of the vector is returned.

<a name="vectorName-matrix"></a>
**vectorName matrix** *...*

> Matrix provides a 2D array view into 1D data. It provides indexing operations in ROW,COL form making it suitable for use with TkTable. Data storage remains unchanged: vectors are still just a single long array. For example, here are two ways to create a 3 column by 10 row matrix:

> <code>
    graph::vector create aVec(10,3)  
    graph::vector create bVec(30)  
    bVec matrix numcols 3  
    set aVec(0,0) 99  
    set bVec(29,2) -99  
    aVec append {5 6 7}; # aVec now has 11 rows.  
    aVec append 1 2;     # Now aVec has 13 rows!  
</code>

> Note that data is appended only in increments of numcols. Elements 0-2 make up the first row, 3-5 the second, etc. Elements will appear only in increments of the column size.

<a name="vectorName-matrix-copy"></a>
**vectorName matrix copy** *dstcolumn srccolumn ?srcVec?*

> Copy a column of element values to column dstcolumn from srccolumn. If vector srcVec is given, and not the same as vectorName, the columns numbers must be different. If the srcVec column is longer, vectorName will be extended. If shorter, remaining destination values are not overwritten.

<a name="vectorName-matrix-delete"></a>
**vectorName matrix delete** *column*

> Delete elements in a column. Note that numcols, which must be greater than 1, will be decremented.

<a name="vectorName-matrix-get"></a>
**vectorName matrix get** *column*

> Get the element in a column: this number must be less than numcols. Note that numcols must be non-zero.

<a name="vectorName-matrix-insert"></a>
**vectorName matrix insert** *column ?initvalue?*

> Insert a new column of elements at column (default 0). The new column is initialized with initvalue, or 0.0 if not specified. Note that numcols will be incremented.

<a name="vectorName-matrix-multiply"></a>
**vectorName matrix multiply** *srcVec ?dstVec?*

> Perform matrix multiplication using srcVec, placing results either in dstVec, or returned as a list. The numrows of srcVec must equal numcols in vectorName. One application for multiply is coordinate transformation.

<a name="vectorName-matrix-numcols"></a>
**vectorName matrix numcols** *?size?*

> Get or set the number of columns for a vectors data. Values >1 enable array variables to accept 2d matrix indexes. For example with a numcols of 10, $vec1(1,2) refers to the 13th element in the vector. A vectors size is also constrained to multiples of numcols, as is it's offset. By default, numcols is 1.

<a name="vectorName-matrix-numrows"></a>
**vectorName matrix numrows** *?size?*

> Get or set the length of rows in a columns for a vector. By default, this is just the vector length/numcols. Setting this value simply provides a convenient way to increase or decrease the vector size by multiples of numcols.

<a name="vectorName-matrix-set"></a>
**vectorName matrix set** *column ?valuelist?*

> Set value elements in a column: this number must be less than numcols. The valuelist is a list values. If this list is shorter than the column, it's last value is used for all remaining columns. The column gets set to the values of item, or 0.0 by default.

<a name="vectorName-matrix-shift"></a>
**vectorName matrix shift** *column amount ?startoffset?*

> Shifts the values of a column by integer inamount. A negative value shifts upward. The startoffset indicates where to start shifting from.

<a name="vectorName-matrix-sort"></a>
**vectorName matrix sort** *column ?-reverse?*

> Sort the vector by the given column.

<a name="vectorName-matrix-transpose"></a>
**vectorName matrix transpose**

> Transpose all columns with rows in matrix. Note that this is a no-op if numcols is 1. Otherwise, numcols will change to vectorLength/numcols.

<a name="vectorName-merge"></a>
**vectorName merge** *srcName ?srcName?...*

> Merges the named vectors into a single vector. The resulting vector is formed by merging the components of each source vector one index at a time.

<a name="vectorName-notify"></a>
**vectorName notify** *?keyword? ?script?*

> Queries or controls how vector clients are notified of changes to the vector. Also allows setting a notifier callback. The exact behavior is determined by keyword.

> **always**

> > Indicates that clients are to be notified immediately whenever the vector is updated.

> **never**

> > Indicates that no clients are to be notified.

> **whenidle**

> > Indicates that clients are to be notified at the next idle point whenever the vector is updated.

> **now**

> > If any client notifications is currently pending, they are notified immediately.

> **cancel**

> > Cancels pending notifications of clients using the vector.

> **pending**

> > Returns 1 if a client notification is pending, and 0 otherwise.

> **callback** *?script?*

> > Query or set a Tcl callback script that is evaluated when a vector is updated.

<a name="vectorName-populate"></a>
**vectorName populate** *destName ?density?*

> Creates a vector destName which is a superset of vectorName. DestName will include all the components of vectorName, in addition the interval between each of the original components will contain a density number of new components, whose values are evenly distributed between the original components values. This is useful for generating abscissas to be interpolated along a spline.

<a name="vectorName-range"></a>
**vectorName range** *firstIndex ?lastIndex?...*

> Returns a list of numeric values representing the vector components between two indices. Both firstIndex and lastIndex are indices representing the range of components to be returned. If lastIndex is less than firstIndex, the components are listed in reverse order.

<a name="vectorName-search"></a>
**vectorName search** *value ?value?*

> Searches for a value or range of values among the components of vectorName. If one value argument is given, a list of indices of the components which equal value is returned. If a second value is also provided, then the indices of all components which lie within the range of the two values are returned. If no components are found, then "" is returned.

<a name="vectorName-set"></a>
**vectorName set** *item*

> Resets the components of the vector to item. Item can be either a list of numeric expressions or another vector.

<a name="vectorName-seq"></a>
**vectorName seq** *start ?finish? ?step?*

> Generates a sequence of values starting with the value start. Finish indicates the terminating value of the sequence. The vector is automatically resized to contain just the sequence. If three arguments are present, step designates the interval.

> With only two arguments (no finish argument), the sequence will continue until the vector is filled. With one argument, the interval defaults to 1.0.

<a name="vectorName-sort"></a>
**vectorName sort** *?-reverse? ?argName?...*

> Sorts the vector vectorName in increasing order. If the -reverse flag is present, the vector is sorted in decreasing order. If other arguments argName are present, they are the names of vectors which will be rearranged in the same manner as vectorName. Each vector must be the same length as vectorName. You could use this to sort the x vector of a graph, while still retaining the same x,y coordinate pairs in a y vector.

<a name="vectorName-split"></a>
**vectorName split** *dstName ?dstName?...*

> Split the vector into a multiple vectors. The resulting N vectors each contain the mod-Nth element from source.

<a name="vectorName-variable"></a>
**vectorName variable** *varName*

> Maps a Tcl variable to the vector, creating another means for accessing the vector. The variable varName can't already exist. This overrides any current variable mapping the vector may have.

<a name="C-LANGUAGE-API"></a>
## C LANGUAGE API

You can create, modify, and destroy vectors from C code, using library routines. You need to include the header file blt.h. It contains the definition of the structure `Rbc_Vector`, which represents the vector. It appears below.

> <code>
typedef struct {  
double valueArr;  
int numValues;  
int arraySize;    
double min, max;  
} **Rbc_Vector**;  
</code>

The field valueArr points to memory holding the vector components. The components are stored in a double precision array, whose size size is represented by arraySize. NumValues is the length of vector. The size of the array is always equal to or larger than the length of the vector. Min and max are minimum and maximum component values.

<a name="LIBRARY-ROUTINES"></a>
## LIBRARY ROUTINES

The following routines are available from C to manage vectors. Vectors are identified by the vector name.

**Rbc_CreateVector**

> Synopsis:

> > `int Rbc_CreateVector(Tcl_Interp *interp; char *vectorName; int length; Rbc_Vector **vecPtrPtr);`

> Description:

> > Creates a new vector vectorName with a length of length. Rbc_CreateVector creates both a new Tcl command and array variable vectorName. Neither a command nor variable named vectorName can already exist. A pointer to the vector is placed into vecPtrPtr.

> Results:

> > Returns TCL_OK if the vector is successfully created. If length is negative, a Tcl variable or command vectorName already exists, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message.

**Rbc_VectorFree**

> Synopsis:

> > `int Rbc_VectorFree(Rbc_Vector *vecPtr);`

> Description:

> > Removes the vector pointed to by vecPtr. VecPtr is a pointer to a vector, typically set by Rbc_GetVector or Rbc_CreateVector. Both the Tcl command and array variable of the vector are destroyed. All clients of the vector will be notified immediately that the vector has been destroyed.

> Results:

> > Returns TCL_OK if the vector is successfully deleted. If vectorName is not the name a vector, then TCL_ERROR is returned.

**Rbc_GetVector**

> Synopsis:

> > `int Rbc_GetVector(Tcl_Interp *interp; char *vectorName; Rbc_Vector **vecPtrPtr);`

> Description:

> > Retrieves the vector vectorName. VecName is the name of a vector which must already exist. VecPtrPtr will point be set to the address of the vector.

> Results:

> > Returns TCL_OK if the vector is successfully retrieved. If vectorName is not the name of a vector, then TCL_ERROR is returned and interp->result will contain an error message.

**Rbc_ResetVector**

> Synopsis:

> > `int Rbc_ResetVector(Rbc_Vector *vecPtr; double *dataArr; int *numValues; int *arraySize; Tcl_FreeProc *freeProc);` 

> Description:

> > Resets the components of the vector pointed to by vecPtr. Calling Rbc_ResetVector will trigger the vector to dispatch notifications to its clients. DataArr is the array of doubles which represents the vector data. NumValues is the number of elements in the array. ArraySize is the actual size of the array (the array may be bigger than the number of values stored in it). FreeProc indicates how the storage for the vector component array (dataArr) was allocated. It is used to determine how to reallocate memory when the vector is resized or destroyed. It must be TCL_DYNAMIC, TCL_STATIC, TCL_VOLATILE, or a pointer to a function to free the memory allocated for the vector array. If freeProc is TCL_VOLATILE, it indicates that dataArr must be copied and saved. If freeProc is TCL_DYNAMIC, it indicates that dataArr was dynamically allocated and that Tcl should free dataArr if necessary. Static indicates that nothing should be done to release storage for dataArr.

> Results:

> > Returns TCL_OK if the vector is successfully resized. If newSize is negative, a vector vectorName does not exist, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message.

**Rbc_ResizeVector**

> Synopsis:

> > `int Rbc_ResizeVector(Rbc_Vector *vecPtr; int newSize);`

> Description:

> > Resets the length of the vector pointed to by vecPtr to newSize. If newSize is smaller than the current size of the vector, it is truncated. If newSize is greater, the vector is extended and the new components are initialized to 0.0. Calling Rbc_ResetVector will trigger the vector to dispatch notifications.

> Results:

> > Returns TCL_OK if the vector is successfully resized. If newSize is negative or memory can not be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message.

**Rbc_VectorExists**

> Synopsis:

> > `int Rbc_VectorExists(Tcl_Interp *interp; char *vectorName);` 

> Description:

> > Indicates if a vector named vectorName exists in interp.

> Results:

> > Returns 1 if a vector vectorName exists and 0 otherwise.

If your application needs to be notified when a vector changes, it can allocate a unique client identifier for itself. Using this identifier, you can then register a call-back to be made whenever the vector is updated or destroyed. By default, the call-backs are made at the next idle point. This can be changed to occur at the time the vector is modified. An application can allocate more than one identifier for any vector. When the client application is done with the vector, it should free the identifier.

The call-back routine must of the following type.

> `typedef void (Rbc_VectorChangedProc) (Tcl_Interp *interp, ClientData clientData, Rbc_VectorNotify notify);`

ClientData is passed to this routine whenever it is called. You can use this to pass information to the call-back. The notify argument indicates whether the vector has been updated of destroyed. It is an enumerated type.

> `typedef enum { RBC_VECTOR_NOTIFY_UPDATE=1, RBC_VECTOR_NOTIFY_DESTROY=2 } Rbc_VectorNotify;`

**Rbc_AllocVectorId**

> Synopsis:

> > `Rbc_VectorId Rbc_AllocVectorId(Tcl_Interp *interp; char *vectorName);` 

> Description:

> > Allocates an client identifier for with the vector vectorName. This identifier can be used to specify a call-back which is triggered when the vector is updated or destroyed.

> Results:

> > Returns a client identifier if successful. If vectorName is not the name of a vector, then NULL is returned and interp->result will contain an error message.

**Rbc_GetVectorById**

> Synopsis:

> > `int Rbc_GetVectorById(Tcl_Interp *interp; Rbc_VectorId clientId; Rbc_Vector **vecPtrPtr);` 

> Description:

> > Retrieves the vector used by clientId. ClientId is a valid vector client identifier allocated by Rbc_AllocVectorId. VecPtrPtr will point be set to the address of the vector.

> Results:

> > Returns TCL_OK if the vector is successfully retrieved.

**Rbc_SetVectorChangedProc**

> Synopsis:

> > `void Rbc_SetVectorChangedProc(Rbc_VectorId clientId; Rbc_VectorChangedProc *proc; ClientData *clientData);` 

> Description:

> > Specifies a call-back routine to be called whenever the vector associated with clientId is updated or deleted. Proc is a pointer to call-back routine and must be of the type Rbc_VectorChangedProc. ClientData is a one-word value to be passed to the routine when it is invoked. If proc is NULL, then the client is not notified.

> Results:

> > The designated call-back procedure will be invoked when the vector is updated or destroyed.

**Rbc_FreeVectorId**

> Synopsis:

> > `void Rbc_FreeVectorId(Rbc_VectorId clientId);` 

> Description:

> > Frees the client identifier. Memory allocated for the identifier is released. The client will no longer be notified when the vector is modified.

> Results:

> > The designated call-back procedure will be no longer be invoked when the vector is updated or destroyed.

**Rbc_NameOfVectorId**

> Synopsis:

> > `char *Rbc_NameOfVectorId(Rbc_VectorId clientId);` 

> Description:

> > Retrieves the name of the vector associated with the client identifier clientId.

> Results:

> > Returns the name of the vector associated with clientId. If clientId is not an identifier or the vector has been destroyed, NULL is returned.

<a name="C-API-EXAMPLE"></a>
## C API EXAMPLE

The following example opens a file of binary data and stores it in an array of doubles. The array size is computed from the size of the file. If the vector "data" exists, calling Rbc_VectorExists, Rbc_GetVector is called to get the pointer to the vector. Otherwise the routine Rbc_CreateVector is called to create a new vector and returns a pointer to it. Just like the Tcl interface, both a new Tcl command and array variable are created when a new vector is created. It doesn't make any difference what the initial size of the vector is since it will be reset shortly. The vector is updated when lt_ResetVector is called. Rbc_ResetVector makes the changes visible to the Tcl interface and other vector clients (such as a graph widget).

> <code>
  #include "tcl.h"  
  #include "blt.h"  
  Rbc_Vector *vecPtr;  
  double *newArr;  
  FILE *f;  
  struct stat statBuf;  
  int numBytes, numValues;  
  f = fopen("binary.dat", "r");  
  fstat(fileno(f), &statBuf);  
  numBytes = (int)statBuf.st_size; /* Allocate an array big enough to hold all the data */  
  newArr = (double *)malloc(numBytes);  
  numValues = numBytes / sizeof(double);  
  fread((void *)newArr, numValues, sizeof(double), f);  
  fclose(f);  
  if (Rbc_VectorExists(interp, "data")) {  
    if (Rbc_GetVector(interp, "data", &vecPtr) != TCL_OK) {  
      return TCL_ERROR;  
    }  
  } else {  
    if (Rbc_CreateVector(interp, "data", 0, &vecPtr) != TCL_OK) {  
      return TCL_ERROR;  
    }  
  }  
  /* * Reset the vector. Clients will be notified when Tk is idle.  
   * TCL_DYNAMIC tells the vector to free the memory allocated  
   * if it needs to reallocate or destroy the vector.  
   */  
  if (Rbc_ResetVector(vecPtr, newArr, numValues, numValues, TCL_DYNAMIC) != TCL_OK) {  
    return TCL_ERROR;  
  }  
</code>

<a name="INCOMPATIBILITIES"></a>
## INCOMPATIBILITIES

In previous versions, if the array variable isn't global (i.e. local to a Tcl procedure), the vector is automatically destroyed when the procedure returns.

> <code>
proc doit {} {  
    # Temporary vector x  
    vector x(10)  
    set x(9) 2.0  
      ...  
}  
</code>

This has changed. Variables are not automatically destroyed when their variable is unset. You can restore the old behavior by setting the "-watchunset" switch.

<a name="EXAMPLE"></a>
## EXAMPLE

You create vectors using the vector command and its create operation.

> <code>
 # Create a new vector.  
graph::vector create y(50)  
</code>

This creates a new vector named y. It has fifty components, by default, initialized to 0.0. In addition, both a Tcl command and array variable, both named y, are created. You can use either the command or variable to query or modify components of the vector.

> <code>
 # Set the first value.  
set y(0) 9.25  
puts "y has [y length] components"  
</code>

The array y can be used to read or set individual components of the vector. Vector components are indexed from zero. The array index must be a number less than the number of components. For example, it's an error if you try to set the 51st element of y.

> <code>
 # This is an error. The vector only has 50 components.  
set y(50) 0.02  
</code>

You can also specify a range of indices using a colon (:) to separate the first and last indices of the range.

> <code>
 # Set the first six components of y  
set y(0:5) 25.2  
</code>

If you don't include an index, then it will default to the first and/or last component of the vector.

> <code>
 # Print out all the components of y  
puts "y = $y(:)"  
</code>

There are special non-numeric indices. The index end, specifies the last component of the vector. It's an error to use this index if the vector is empty (length is zero). The index ++end can be used to extend the vector by one component and initialize it to a specific value. You can't read from the array using this index, though.

> <code>
 # Extend the vector by one component.  
set y(++end) 0.02  
</code>

The other special indices are min and max. They return the current smallest and largest components of the vector.

> <code>
 # Print the bounds of the vector  
puts "min=$y(min) max=$y(max)"  
</code>

To delete components from a vector, simply unset the corresponding array element. In the following example, the first component of y is deleted. All the remaining components of y will be moved down by one index as the length of the vector is reduced by one.

> <code>
 # Delete the first component  
unset y(0)  
puts "new first element is $y(0)"  
</code>

The vector's Tcl command can also be used to query or set the vector.

> <code>
 # Create and set the components of a new vector  
graph::vector create x  
x set { 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20 }  
</code>

Here we've created a vector x without a initial length specification. In this case, the length is zero. The set operation resets the vector, extending it and setting values for each new component.

There are several operations for vectors. The range operation lists the components of a vector between two indices.

> <code>
 # List the components  
puts "x = [x range 0 end]"  
</code>

You can search for a particular value using the search operation. It returns a list of indices of the components with the same value. If no component has the same value, it returns "".

> <code>
 # Find the index of the biggest component  
set indices [x search $x(max)]  
</code>

Other operations copy, append, or sort vectors. You can append vectors or new values onto an existing vector with the append operation.

> <code>
 # Append assorted vectors and values to x  
x append x2 x3 { 2.3 4.5 } x4  
</code>

The sort operation sorts the vector. If any additional vectors are specified, they are rearranged in the same order as the vector. For example, you could use it to sort data points represented by x and y vectors.

> <code>
 # Sort the data points  
x sort y  
</code>

The vector x is sorted while the components of y are rearranged so that the original x,y coordinate pairs are retained.

The expr operation lets you perform arithmetic on vectors. The result is stored in the vector.

> <code>
 # Add the two vectors and a scalar  
x expr { x + y }  
x expr { x * 2 }  
</code>

When a vector is modified, resized, or deleted, it may trigger call-backs to notify the clients of the vector. For example, when a vector used in the graph widget is updated, the vector automatically notifies the widget that it has changed. The graph can then redrawn itself at the next idle point. By default, the notification occurs when Tk is next idle. This way you can modify the vector many times without incurring the penalty of the graph redrawing itself for each change. You can change this behavior using the notify operation.

> <code>
 # Make vector x notify after every change  
x notify always  
	...  
 # Never notify  
x notify never  
	...  
 # Force notification now  
x notify now  
 # Set Tcl callback for update of Tktable widget .t.  
x notify callback {.t conf -padx [.t cget -padx]; .t reread}  
</code>

To delete a vector, use the vector delete command. Both the vector and its corresponding Tcl command are destroyed.

> <code>
 # Remove vector x  
graph::vector destroy x  
</code>

The pseudo vector last can be used at the end of an expression to implement running totals. During execution it resolves to the result from the previous vector element evaluation.

> <code>
graph::vector create A(10)  
graph::vector create B(10)  
graph::vector create S(10)  
graph::vector create T(10)  
graph::S expr A+B  
graph::T expr S+last; # Running total  
</code>

<a name="CREDITS"></a>
## CREDITS

[BLT][] was originally develeoped by George A. Howlett. It can be found at <https://sourceforge.net/projects/blt/>.

Refactored [BLT][] Components ([Rbc][]), includes data vectors and graph widgets from the original [BLT][]. Both can be found at sourceforge.

User visible changes to the original [Rbc][] code are:

- command name is now **graph::vector**

<a name="KEYWORDS"></a>
## KEYWORDS

vector, graph, widget

<a name="COPYRIGHT"></a>
## COPYRIGHT

&copy; 1995-1997 Roger E. Critchlow Jr.

&copy; 2001 George A. Howlett.

&copy; 2018 RenĂ© Zaumseil <[email protected]>

[BLT]: <https://sourceforge.net/projects/blt/>
[Rbc]: <https://sourceforge.net/projects/rbctoolkit/>
Changes to generic/tkCmds.c.
38
39
40
41
42
43
44




45
46
47
48
49
50
51
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55







+
+
+
+







			    int objc, Tcl_Obj *const *objv);
static int		CaretCmd(ClientData dummy, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const *objv);
static int		InactiveCmd(ClientData dummy, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const *objv);
static int		ScalingCmd(ClientData dummy, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const *objv);
#ifndef MAC_OSX_TK
static int		SnapCmd(ClientData dummy, Tcl_Interp *interp,
			    int objc, Tcl_Obj *const *objv);
#endif
static int		UseinputmethodsCmd(ClientData dummy,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const *objv);
static int		WindowingsystemCmd(ClientData dummy,
			    Tcl_Interp *interp, int objc,
			    Tcl_Obj *const *objv);

64
65
66
67
68
69
70



71
72
73
74
75
76
77
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84







+
+
+







    {"busy",		Tk_BusyObjCmd, NULL },
    {"caret",		CaretCmd, NULL },
    {"inactive",	InactiveCmd, NULL },
    {"scaling",		ScalingCmd, NULL },
    {"useinputmethods",	UseinputmethodsCmd, NULL },
    {"windowingsystem",	WindowingsystemCmd, NULL },
    {"fontchooser",	NULL, tkFontchooserEnsemble},
#ifndef MAC_OSX_TK
    {"snap",		SnapCmd, NULL},
#endif
    {NULL, NULL, NULL}
};

/*
 *----------------------------------------------------------------------
 *
 * Tk_BellObjCmd --
969
970
971
972
973
974
975
























976
977
978
979
980
981
982
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







	Tcl_ResetResult(interp);
    } else {
	Tcl_WrongNumArgs(interp, 1, objv, "?-displayof window? ?reset?");
	return TCL_ERROR;
    }
    return TCL_OK;
}

#ifndef MAC_OSX_TK
int
SnapCmd(
    ClientData clientData,	/* Main window associated with interpreter. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int objc,			/* Number of arguments. */
    Tcl_Obj *const objv[])	/* Argument objects. */
{
    Tk_Window tkwin = clientData;
    int skip = TkGetDisplayOf(interp, objc - 1, objv + 1, &tkwin);

    if (skip < 0) {
	return TCL_ERROR;
    }
    if (objc != 3) {
	Tcl_WrongNumArgs(interp, 1, objv, "window photo");
	return TCL_ERROR;
    }

    return Rbc_SnapWindow(interp, tkwin, Tcl_GetString(objv[1]),
        Tcl_GetString(objv[2]), 0, 0);
}
#endif

/*
 *----------------------------------------------------------------------
 *
 * Tk_TkwaitObjCmd --
 *
 *	This function is invoked to process the "tkwait" Tcl command. See the
Changes to generic/tkInt.h.
1001
1002
1003
1004
1005
1006
1007










1008
1009
1010
1011
1012
1013
1014
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024







+
+
+
+
+
+
+
+
+
+








/*
 * Themed widget set init function:
 */

MODULE_SCOPE int	Ttk_Init(Tcl_Interp *interp);

/*
 * Used tko widget set functions:
 */
#ifndef MAC_OSX_TK
MODULE_SCOPE int	Tko_Init(Tcl_Interp *interp);
MODULE_SCOPE int	Rbc_SnapWindow(Tcl_Interp *interp,Tk_Window tkmain,
			    const char*pathname, const char *photoimage,
			    int destWidth, int destHeight);
#endif

/*
 * Internal functions shared among Tk modules but not exported to the outside
 * world:
 */

MODULE_SCOPE int	Tk_BellObjCmd(ClientData clientData,
			    Tcl_Interp *interp, int objc,
Changes to generic/tkWindow.c.
3308
3309
3310
3311
3312
3313
3314









3315
3316
3317
3318
3319
3320
3321
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330







+
+
+
+
+
+
+
+
+







     */

    code = Ttk_Init(interp);
    if (code != TCL_OK) {
	goto done;
    }

    /*
     * Initialize the tko widget set
     */
#ifndef MAC_OSX_TK
    code = Tko_Init(interp);
    if (code != TCL_OK) {
	goto done;
    }
#endif
    /*
     * Invoke platform-specific initialization. Unlock mutex before entering
     * TkpInit, as that may run through the Tk_Init routine again for the
     * console window interpreter.
     */

    code = TkpInit(interp);
Added generic/tko/tkoFrame.c.


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoFrame.c --
 *
 *	This module implements "frame", "labelframe" and "toplevel" widgets
 *	for the Tk toolkit. Frames are windows with a background color and
 *	possibly a 3-D effect, but not much else in the way of attributes.
 *
 * Copyright (c) 1990-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 2019 Rene Zaumseil
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoWidget.h"

 /*
  * The following enum is used to define the type of the frame.
  */
enum FrameType {
    TYPE_FRAME, TYPE_TOPLEVEL, TYPE_LABELFRAME
};

/*
 * tkoFrame --
 *
 * A data structure of the following type is kept for each
 * frame that currently exists for this process:
 */
typedef struct tkoFrame {
    Tk_Window *win;
    Tcl_Object object;
    Tcl_Interp *interp;
    Display *display;
    enum FrameType type;       /* Type of widget, such as TYPE_FRAME. */
    char *menuName;            /* Textual description of menu to use for
                                * menubar. Malloc-ed, may be NULL. */
    Colormap colormap;         /* If not None, identifies a colormap
                                * allocated for this window, which must be
                                * freed when the window is deleted. */
    Tk_3DBorder border;        /* Structure used to draw 3-D border and
                                * background. NULL means no background or
                                * border. */
    int borderWidth;           /* Width of 3-D border (if any). */
    int relief;                /* 3-d effect: TK_RELIEF_RAISED etc. */
    int highlightWidth;        /* Width in pixels of highlight to draw around
                                * widget when it has the focus. 0 means don't
                                * draw a highlight. */
    XColor *highlightBgColorPtr;
    /* Color for drawing traversal highlight area
     * when highlight is off. */
    XColor *highlightColorPtr; /* Color for drawing traversal highlight. */
    int width;                 /* Width to request for window. <= 0 means
                                * don't request any size. */
    int height;                /* Height to request for window. <= 0 means
                                * don't request any size. */
    Tk_Cursor cursor;          /* Current cursor for window, or None. */
    int isContainer;           /* 1 means this window is a container, 0 means
                                * that it isn't. */
    Tcl_Obj *useThis;          /* If the window is embedded, this points to
                                * the name of the window in which it is
                                * embedded (malloc'ed). For non-embedded
                                * windows this is NULL. */
    int flags;                 /* Various flags; see below for
                                * definitions. */
    int padX;                  /* Integer value corresponding to padXPtr. */
    int padY;                  /* Integer value corresponding to padYPtr. */
    unsigned int mask;
} tkoFrame;

/*
 * tkoLabelframe --
 *
 * A data structure of the following type is kept for each labelframe widget
 * managed by this file:
 */
typedef struct tkoLabelframe {
    tkoFrame frame;            /* A pointer to the generic frame structure.
                                * This must be the first element of the
                                * tkoLabelframe. */
    /*
     * tkoLabelframe specific configuration settings.
     */
    Tcl_Obj *textPtr;          /* Value of -text option: specifies text to
                                * display in button. */
    Tk_Font tkfont;            /* Value of -font option: specifies font to
                                * use for display text. */
    XColor *textColorPtr;      /* Value of -fg option: specifies foreground
                                * color in normal mode. */
    int labelAnchor;           /* Value of -labelanchor option: specifies
                                * where to place the label. */
    Tk_Window labelWin;        /* Value of -labelwidget option: Window to use
                                * as label for the frame. */
    /*
     * tkoLabelframe specific fields for use with configuration settings above.
     */
    GC  textGC;                /* GC for drawing text in normal mode. */
    Tk_TextLayout textLayout;  /* Stored text layout information. */
    XRectangle labelBox;       /* The label's actual size and position. */
    int labelReqWidth;         /* The label's requested width. */
    int labelReqHeight;        /* The label's requested height. */
    int labelTextX, labelTextY; /* Position of the text to be drawn. */
} tkoLabelframe;

/*
 * The following macros define how many extra pixels to leave around a label's
 * text.
 */
#define LABELSPACING 1
#define LABELMARGIN 4

 /*
  * Flag bits for frames:
  *
  * REDRAW_PENDING:             Non-zero means a DoWhenIdle handler has
  *                             already been queued to redraw this window.
  * GOT_FOCUS:                  Non-zero means this widget currently has the
  *                             input focus.
  */
#define REDRAW_PENDING		1
#define GOT_FOCUS		4

  /*
   * The following enum is used to define a type for the -labelanchor option of
   * the Labelframe widget. These values are used as indices into the string
   * table below.
   */
enum labelanchor {
    LABELANCHOR_E, LABELANCHOR_EN, LABELANCHOR_ES,
    LABELANCHOR_N, LABELANCHOR_NE, LABELANCHOR_NW,
    LABELANCHOR_S, LABELANCHOR_SE, LABELANCHOR_SW,
    LABELANCHOR_W, LABELANCHOR_WN, LABELANCHOR_WS
};

/*
* Methods
*/
static int FrameConstructorFrame(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameConstructorLabelframe(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameConstructorToplevel(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameMethod_tko_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameMethod_tko_option(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int FrameMethod_labelanchor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int FrameMethod_labelwidget(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);

/*
 * Functions
 */
static int FrameConstructor(
    int type,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static void FrameMetaDestroy(
    tkoFrame * frame);
static void
FrameMetaDelete(
    ClientData clientData)
{
    Tcl_EventuallyFree(clientData, (Tcl_FreeProc *) FrameMetaDestroy);
}

static void FrameComputeGeometry(
    tkoFrame * frame);
static void FrameDisplay(
    ClientData clientData);
static void FrameEventProc(
    ClientData clientData,
    XEvent * eventPtr);
static void FrameLostSlaveProc(
    ClientData clientData,
    Tk_Window tkWin);
static void FrameRequestProc(
    ClientData clientData,
    Tk_Window tkWin);
static void FrameStructureProc(
    ClientData clientData,
    XEvent * eventPtr);
static void FrameWorldChanged(
    ClientData instanceData);
static void FrameLabelwinRemove(
    tkoLabelframe * labelframe);
static void FrameMap(
    ClientData clientData);

/*
 * Data
 */

/*
 * frameMeta --
 *
 * The structure is used to identify our own data inoo objects.
 */
static Tcl_ObjectMetadataType frameMeta = {
    TCL_OO_METADATA_VERSION_CURRENT,
    "FrameMeta",
    FrameMetaDelete,
    NULL
};

/*
 * frameClass --
 *
 * The structure below defines frame class behavior by means of functions that
 * can be invoked from generic window code.
 */
static const Tk_ClassProcs frameClass = {
    sizeof(Tk_ClassProcs),      /* size */
    FrameWorldChanged,  /* worldChangedProc */
    NULL,      /* createProc */
    NULL       /* modalProc */
};

/*
 * frameGeomType --
 *
 * The structure below defines the official type record for the labelframe's
 * geometry manager:
 */
static const Tk_GeomMgr frameGeomType = {
    "labelframe",       /* name */
    FrameRequestProc,   /* requestProc */
    FrameLostSlaveProc  /* lostSlaveProc */
};

/*
 * Definition of options created in object constructor.
 * Order of used options in definition is important:
 * -class -visual -colormap -container -use
 */

/* Common options for all defined widgets. */
#define FRAME_COMMONDEFINE \
	{ "-background" , "background", "Background", DEF_FRAME_BG_COLOR, 0, NULL, \
        NULL, NULL,	TKO_SET_3DBORDER, &frameMeta, offsetof(tkoFrame, border)}, \
	{ "-bg" , "-background", NULL, NULL, 0, NULL, NULL, NULL,0,NULL,0}, \
	{ "-bd" , "-borderwidth", NULL, NULL, 0, NULL, NULL, NULL,0,NULL,0}, \
	{ "-cursor" , "cursor", "Cursor", DEF_FRAME_CURSOR, 0, NULL, \
		NULL, NULL, TKO_SET_CURSOR, &frameMeta, offsetof(tkoFrame, cursor)}, \
	{ "-height" , "height", "Height", DEF_FRAME_HEIGHT, 0, NULL, \
		NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, height)}, \
	{ "-highlightbackground", "highlightbackground", "highlightBackground", DEF_FRAME_HIGHLIGHT_BG, 0, NULL, \
		NULL, NULL, TKO_SET_XCOLOR, &frameMeta, offsetof(tkoFrame, highlightBgColorPtr)}, \
	{ "-highlightcolor", "highlightColor", "HighlightColor", DEF_FRAME_HIGHLIGHT, 0,NULL, \
		NULL, NULL, TKO_SET_XCOLOR, &frameMeta, offsetof(tkoFrame, highlightColorPtr)}, \
	{ "-highlightthickness" , "highlightThickness", "HighlightThickness", DEF_FRAME_HIGHLIGHT_WIDTH,  0,NULL, \
		NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, highlightWidth)}, \
	{ "-padx" , "padX", "Pad", DEF_FRAME_PADX, 0,NULL, \
		NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, padX)}, \
	{ "-pady" , "padY", "Pad", DEF_FRAME_PADY, 0,NULL, \
		NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, padY)}, \
	{ "-takefocus" , "takeFocus", "TakeFocus", DEF_FRAME_TAKE_FOCUS,  0,NULL, \
		NULL, NULL, TKO_SET_STRING, NULL, 0}, \
	{ "-width" , "width", "Width", DEF_FRAME_WIDTH,  0,NULL, \
		NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, width)}, \
	{ NULL,NULL,NULL,NULL,0,NULL, NULL,NULL,0,NULL,0}

/* tko::frame options */
static tkoWidgetOptionDefine frameOptions[] = {
    {"-class", "class", "Class", "TkoFrame", TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_CLASS, NULL, 0},
    {"-visual", "visual", "Visual", DEF_FRAME_VISUAL, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_VISUAL, NULL, 0},
    {"-colormap", "colormap", "Colormap", DEF_FRAME_COLORMAP, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_COLORMAP, NULL, 0},
    {"-container", "container", "Container", DEF_FRAME_CONTAINER, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_CONTAINER, &frameMeta, offsetof(tkoFrame, isContainer)},
    {"-borderwidth", "borderWidth", "BorderWidth", DEF_FRAME_BORDER_WIDTH, 0,NULL,
	NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, borderWidth)},
    {"-relief", "relief", "Relief", DEF_FRAME_RELIEF, 0,NULL,
	NULL, NULL, TKO_SET_RELIEF, &frameMeta, offsetof(tkoFrame, relief)},
    FRAME_COMMONDEFINE
};

/* tko::toplevel options */
static tkoWidgetOptionDefine toplevelOptions[] = {
    {"-screen", "screen", "Screen", "", TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_STRING, NULL, 0},
    {"-class", "class", "Class", "TkoToplevel", TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_CLASS, NULL, 0},
    {"-container", "container", "Container", DEF_FRAME_CONTAINER, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_CONTAINER, &frameMeta, offsetof(tkoFrame, isContainer)},
    {"-use", "use", "Use", DEF_TOPLEVEL_USE, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_USENULL, &frameMeta, offsetof(tkoFrame, useThis)},
    {"-visual", "visual", "Visual", DEF_FRAME_VISUAL, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_VISUAL, NULL, 0},
    {"-colormap", "colormap", "Colormap", DEF_FRAME_COLORMAP, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_COLORMAP, NULL, 0},
    {"-borderwidth", "borderWidth", "BorderWidth", DEF_FRAME_BORDER_WIDTH, 0,NULL,
	NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, borderWidth)},
    {"-menu", "menu", "Menu", DEF_TOPLEVEL_MENU, 0,NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &frameMeta, offsetof(tkoFrame, menuName)},
    {"-relief", "relief", "Relief", DEF_FRAME_RELIEF, 0,NULL,
	NULL, NULL, TKO_SET_RELIEF, &frameMeta, offsetof(tkoFrame, relief)},
    FRAME_COMMONDEFINE
};

/* tko::labelframe options */
static tkoWidgetOptionDefine labelframeOptions[] = {
    {"-class", "class", "Class", "TkoLabelframe", TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_CLASS, NULL, 0},
    {"-visual", "visual", "Visual", DEF_FRAME_VISUAL, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_VISUAL, NULL, 0},
    {"-colormap", "colormap", "Colormap", DEF_FRAME_COLORMAP, TKO_OPTION_READONLY,NULL,
	NULL, NULL, TKO_SET_COLORMAP, NULL, 0},
    {"-borderwidth", "borderWidth", "BorderWidth", DEF_LABELFRAME_BORDER_WIDTH, 0,NULL,
	NULL, NULL, TKO_SET_PIXEL, &frameMeta, offsetof(tkoFrame, borderWidth)},
    {"-fg", "-foreground", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-font", "font", "Font", DEF_LABELFRAME_FONT, 0,NULL,
	NULL, NULL, TKO_SET_FONT, &frameMeta, offsetof(tkoLabelframe, tkfont)},
	{"-foreground", "foreground", "Foreground", DEF_LABELFRAME_FG, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &frameMeta, offsetof(tkoLabelframe, textColorPtr)},
    {"-labelanchor", "labelAnchor", "LabelAnchor", DEF_LABELFRAME_LABELANCHOR, 0, NULL,
	NULL, FrameMethod_labelanchor, 0, NULL, 0},
    {"-labelwidget", "labelWidget", "LabelWidget", "",0, NULL,
	NULL, FrameMethod_labelwidget, 0, NULL, 0},
    {"-relief", "relief", "Relief", DEF_LABELFRAME_RELIEF, 0, NULL,
	NULL, NULL, TKO_SET_RELIEF, &frameMeta, offsetof(tkoFrame, relief)},
    {"-text", "text", "Text", DEF_LABELFRAME_TEXT, 0, NULL,
	NULL, NULL, TKO_SET_TCLOBJ, &frameMeta, offsetof(tkoLabelframe, textPtr)},
    FRAME_COMMONDEFINE
};

/*
 * Definition of object methods created in Tko_FrameInit() function.
 */

/* tko::frame methods. */
static Tcl_MethodType frameMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameConstructorFrame, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameDestructor, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure", FrameMethod_tko_configure,
            NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/* tko::labelframe methods. */
static Tcl_MethodType labelframeMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameConstructorLabelframe, NULL,
            NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameDestructor, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure", FrameMethod_tko_configure,
            NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/* tko::toplevel methods. */
static Tcl_MethodType toplevelMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameConstructorToplevel, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, FrameDestructor, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure", FrameMethod_tko_configure,
            NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/*
 * Tko_FrameInit --
 *
 * Create tko frame widget class objects.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
int
Tko_FrameInit(
    Tcl_Interp * interp)
{              /* Tcl interpreter. */
Tcl_Class clazz;
Tcl_Object object;

    /* Create class like tk command and remove oo functions from widget commands */
static const char *initScript =
    "::oo::class create ::tko::frame {superclass ::tko::widget; variable tko; {*}$::tko::unknown}\n"
    "::oo::class create ::tko::labelframe {superclass ::tko::widget; variable tko; {*}$::tko::unknown}\n"
    "::oo::class create ::tko::toplevel {superclass ::tko::widget; variable tko; {*}$::tko::unknown}\n";

    /* Create widget class. */
    if(Tcl_GlobalEval(interp, initScript) != TCL_OK) {
        return TCL_ERROR;
    }

    /*
     * ::tko::toplevel
     */
    /* Get class object */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.tko_toplevel)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /* Add methods and options */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            toplevelMethods, toplevelOptions) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * ::tko::frame
     */
    /* Get class object */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.tko_frame)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /* Add methods and options */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            frameMethods, frameOptions) != TCL_OK) {
        return TCL_ERROR;
    }

    /*
     * ::tko::labelframe
     */
    /* Get class object */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.tko_labelframe)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /* Add methods and options */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            labelframeMethods, labelframeOptions) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * FrameConstructorFrame --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameConstructorFrame(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    return FrameConstructor(TYPE_FRAME, interp, context, objc, objv);
}

/*
 * FrameConstructorLabelframe --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameConstructorLabelframe(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    return FrameConstructor(TYPE_LABELFRAME, interp, context, objc, objv);
}

/*
 * FrameConstructorToplevel --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameConstructorToplevel(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    return FrameConstructor(TYPE_TOPLEVEL, interp, context, objc, objv);
}

/*
 * FrameDestructor --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int skip;
    Tcl_Object object;
    tkoFrame *frame;
    Tk_Window tkWin = NULL;
    tkoLabelframe *labelframe;
    if((object = Tcl_ObjectContextObject(context)) == NULL) {
        return TCL_ERROR;
    }
    skip = Tcl_ObjectContextSkippedArgs(context);
    if((frame = (tkoFrame *) Tcl_ObjectGetMetadata(object, &frameMeta)) != NULL) {
        Tcl_Preserve(frame);
        labelframe = (tkoLabelframe *) frame;

        if(frame->win) {
            tkWin = *(frame->win);
            frame->win = NULL;
        }
        if(tkWin) {
            Tk_DeleteEventHandler(tkWin, frame->mask, FrameEventProc, frame);
        }
        if(frame->cursor != None) {
            if(frame->display != None) {
                Tk_FreeCursor(frame->display, frame->cursor);
            }
            frame->cursor = None;
        }
        frame->flags = 0;
        Tcl_CancelIdleCall(FrameDisplay, frame);
        Tcl_CancelIdleCall(FrameMap, frame);

        if(frame->menuName != NULL && tkWin) {
            TkSetWindowMenuBar(frame->interp, tkWin, frame->menuName, NULL);
            frame->menuName = NULL;
        }
        if(frame->type == TYPE_LABELFRAME && labelframe->labelWin) {
            Tk_ManageGeometry(labelframe->labelWin, NULL, NULL);
            if(tkWin && (tkWin != Tk_Parent(labelframe->labelWin))) {
                Tk_UnmaintainGeometry(labelframe->labelWin, tkWin);
            }
            Tk_UnmapWindow(labelframe->labelWin);
            labelframe->labelWin = NULL;
        }
        Tcl_Release(frame);
        Tcl_ObjectSetMetadata(object, &frameMeta, NULL);
    }
    /* ignore errors */
    Tcl_ObjectContextInvokeNext(interp, context, objc, objv, skip);

    return TCL_OK;
}

/*
 * FrameMethod_tko_configure --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameMethod_tko_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    char *oldMenuName;
    Tcl_Object object;
    tkoFrame *frame;
    tkoLabelframe *labelframe;
    Tk_Window oldWindow;
    Tk_Window tkwin;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (frame =
            (tkoFrame *) Tcl_ObjectGetMetadata(object, &frameMeta)) == NULL
        || frame->win == NULL || (tkwin = *(frame->win)) == NULL) {
        return TCL_ERROR;
    }
    labelframe = (tkoLabelframe *) frame;

    /*
     * Need the old menubar name for the menu code to delete it.
     */

    if(frame->menuName == NULL) {
        oldMenuName = NULL;
    } else {
        oldMenuName = ckalloc(strlen(frame->menuName) + 1);
        strcpy(oldMenuName, frame->menuName);
    }

    if(frame->type == TYPE_LABELFRAME) {
        oldWindow = labelframe->labelWin;
    }
    /*TODO ???      if (oldMenuName != NULL) {
     * ckfree(oldMenuName);
     * }
     */

    /*
     * A few of the options require additional processing.
     */

    if((((oldMenuName == NULL) && (frame->menuName != NULL))
            || ((oldMenuName != NULL) && (frame->menuName == NULL))
            || ((oldMenuName != NULL) && (frame->menuName != NULL)
                && strcmp(oldMenuName, frame->menuName) != 0))
        && frame->type == TYPE_TOPLEVEL) {
        TkSetWindowMenuBar(frame->interp, tkwin, oldMenuName, frame->menuName);
    }

    if(oldMenuName != NULL) {
        ckfree(oldMenuName);
    }

    if(frame->border != NULL) {
        Tk_SetBackgroundFromBorder(tkwin, frame->border);
    } else {
        Tk_SetWindowBackgroundPixmap(tkwin, None);
    }

    if(frame->highlightWidth < 0) {
        frame->highlightWidth = 0;
    }
    if(frame->padX < 0) {
        frame->padX = 0;
    }
    if(frame->padY < 0) {
        frame->padY = 0;
    }

    FrameWorldChanged(frame);
    if(Tcl_ObjectContextInvokeNext(interp, context, objc, objv,
            Tcl_ObjectContextSkippedArgs(context)) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * FrameMethod_labelanchor --
 *
 * Process -labelanchor option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameMethod_labelanchor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int index, code;
    Tcl_Object object;
    tkoLabelframe *labelframe;
    Tcl_Obj *value;
	static const char *const labelAnchorStrings[] = {
		"e", "en", "es", "n", "ne", "nw", "s", "se", "sw", "w", "wn", "ws",
		NULL
	};

	if((object = Tcl_ObjectContextObject(context)) == NULL
        || (labelframe =
            (tkoLabelframe *) Tcl_ObjectGetMetadata(object, &frameMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }
    code =
        Tcl_GetIndexFromObj(interp, value, labelAnchorStrings, "labelanchor", 0,
        &index);
    if(code != TCL_OK) {
        return TCL_ERROR;
    }
    labelframe->labelAnchor = (Tk_Anchor) index;
    return TCL_OK;
}

/*
 * FrameMethod_labelwidget --
 *
 * Process -labelwidget option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameMethod_labelwidget(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_Window oldWindow = NULL;
    Tk_Window newWindow = NULL;
    Tk_Window tkwin = NULL;
    Tk_Window ancestor, parent, sibling = NULL;
    Tcl_Object object;
    tkoLabelframe *labelframe;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (labelframe =
            (tkoLabelframe *) Tcl_ObjectGetMetadata(object, &frameMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    if(labelframe->frame.win == NULL
        || (tkwin = *(labelframe->frame.win)) == NULL) {
        return TCL_ERROR;
    }

    if(value == NULL || Tcl_GetCharLength(value) == 0) {
        newWindow = NULL;
    } else if(TkGetWindowFromObj(interp, tkwin, value, &newWindow) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * If a -labelwidget is specified, check that it is valid and set up
     * geometry management for it.
     */
    oldWindow = labelframe->labelWin;
    if(oldWindow != newWindow) {
        if(newWindow != NULL) {
            /*
             * Make sure that the frame is either the parent of the window
             * used as label or a descendant of that parent. Also, don't
             * allow a top-level window to be managed inside the frame.
             */
            parent = Tk_Parent(newWindow);
            for(ancestor = tkwin;; ancestor = Tk_Parent(ancestor)) {
                if(ancestor == parent) {
                    break;
                }
                sibling = ancestor;
                if(Tk_IsTopLevel(ancestor)) {
                    goto badLabelWindow;
                }
            }
            if(Tk_IsTopLevel(newWindow)) {
                goto badLabelWindow;
            }
            if(newWindow == tkwin) {
                goto badLabelWindow;
            }
        }
        if(oldWindow != NULL) {
            Tk_DeleteEventHandler(oldWindow, StructureNotifyMask,
                FrameStructureProc, labelframe);
            Tk_ManageGeometry(oldWindow, NULL, NULL);
            Tk_UnmaintainGeometry(oldWindow, tkwin);
            Tk_UnmapWindow(oldWindow);
        }
        if(newWindow != NULL) {
            Tk_CreateEventHandler(newWindow,
                StructureNotifyMask, FrameStructureProc, labelframe);
            Tk_ManageGeometry(newWindow, &frameGeomType, labelframe);
            /*
             * If the frame is not parent to the label, make sure the
             * label is above its sibling in the stacking order.
             */
            if(sibling != NULL) {
                Tk_RestackWindow(newWindow, Above, sibling);
            }
        }
        labelframe->labelWin = newWindow;
    }
    //      FrameWorldChanged(labelframe);
    return TCL_OK;

  badLabelWindow:
    Tcl_SetObjResult(interp,
        Tcl_ObjPrintf("can't use %s as label in this frame",
            Tk_PathName(labelframe->labelWin)));
    Tcl_SetErrorCode(interp, "TK", "GEOMETRY", "HIERARCHY", NULL);
    labelframe->labelWin = NULL;
    return TCL_ERROR;
}

/*
 * FrameConstructor --
 *
 * Common part of all widget contructors.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
FrameConstructor(
    int type,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    tkoFrame *frame;
    int skip;
    Tcl_Obj *myObjv[2];

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL) {
        return TCL_ERROR;
    }
    skip = Tcl_ObjectContextSkippedArgs(context);
    /* Check objv[] arguments: ... optionlist arglist */
    if(objc - skip != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "optionlist arglist");
        return TCL_ERROR;
    }
    if(type == TYPE_FRAME) {
        frame = ckalloc(sizeof(tkoFrame));
        memset(frame, 0, sizeof(tkoFrame));
        myObjv[0] =
            Tcl_ObjGetVar2(interp, TkoObj.tko_options, TkoObj.tko_frame,
            TCL_GLOBAL_ONLY);
        myObjv[1] = objv[objc - 1];
    } else if(type == TYPE_LABELFRAME) {
    tkoLabelframe *labelframe;

        frame = ckalloc(sizeof(tkoLabelframe));
        memset(frame, 0, sizeof(tkoLabelframe));
        myObjv[0] =
            Tcl_ObjGetVar2(interp, TkoObj.tko_options, TkoObj.tko_labelframe,
            TCL_GLOBAL_ONLY);
        myObjv[1] = objv[objc - 1];
        labelframe = (tkoLabelframe *) frame;
        labelframe->textPtr = NULL;
        labelframe->tkfont = NULL;
        labelframe->textColorPtr = NULL;
        labelframe->labelAnchor = LABELANCHOR_NW;
        labelframe->labelWin = NULL;
        labelframe->textGC = None;
        labelframe->textLayout = NULL;
        /*labelframe->labelBox */
        labelframe->labelReqWidth = 0;
        labelframe->labelReqHeight = 0;
        labelframe->labelTextX = 0;
        labelframe->labelTextY = 0;
    } else if(type == TYPE_TOPLEVEL) {
        myObjv[1] = Tcl_NewStringObj("-screen {}", -1);
        Tcl_IncrRefCount(myObjv[1]);
        if(Tcl_ListObjAppendList(interp, myObjv[1], objv[objc - 1]) != TCL_OK) {
            Tcl_DecrRefCount(myObjv[1]);
            return TCL_ERROR;
        }
        frame = ckalloc(sizeof(tkoFrame));
        memset(frame, 0, sizeof(tkoFrame));
        myObjv[0] =
            Tcl_ObjGetVar2(interp, TkoObj.tko_options, TkoObj.tko_toplevel,
            TCL_GLOBAL_ONLY);
    } else {
        Tcl_WrongNumArgs(interp, 1, objv, "internal type error");
        return TCL_ERROR;
    }
    if(myObjv[0] == NULL) {
        return TCL_ERROR;
    }
    frame->win = NULL;
    frame->object = object;
    frame->interp = interp;
    frame->display = None;
    frame->type = type;
    frame->menuName = NULL;
    frame->colormap = None;
    frame->border = NULL;
    frame->borderWidth = 0;
    frame->relief = TK_RELIEF_FLAT;
    frame->highlightWidth = 0;
    frame->highlightBgColorPtr = NULL;
    frame->highlightColorPtr = NULL;
    frame->width = 0;
    frame->height = 0;
    frame->cursor = None;
    frame->isContainer = 0;
    frame->useThis = NULL;
    frame->flags = 0;
    frame->padX = 0;
    frame->padY = 0;
    frame->mask = ExposureMask | StructureNotifyMask | FocusChangeMask;
    if(type == TYPE_TOPLEVEL) {
        frame->mask |= ActivateMask;
    }

    Tcl_ObjectSetMetadata(object, &frameMeta, (ClientData) frame);

    myObjv[0] = Tcl_DuplicateObj(myObjv[0]);
    Tcl_IncrRefCount(myObjv[0]);
    Tcl_ListObjAppendList(interp, myObjv[0], objv[objc - 2]);
    if(Tcl_ObjectContextInvokeNext(interp, context, 2, myObjv, 0) != TCL_OK) {
        Tcl_DecrRefCount(myObjv[0]);
        if(type == TYPE_TOPLEVEL) {
            Tcl_DecrRefCount(myObjv[1]);
        }
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(myObjv[0]);
    if(type == TYPE_TOPLEVEL) {
        Tcl_DecrRefCount(myObjv[1]);
    }
    frame->win = TkoWidgetWindow(object);
    if(frame->win == NULL || *(frame->win) == NULL) {
        return TCL_ERROR;
    }
    if((frame->display = Tk_Display(*(frame->win))) == None) {
        return TCL_ERROR;
    }
    if(frame->isContainer && frame->useThis != NULL) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj
            ("windows cannot have both the -use and the -container"
                " option set", -1));
        Tcl_SetErrorCode(interp, "TK", "FRAME", "CONTAINMENT", NULL);
        return TCL_ERROR;
    }
    /*
     * For top-level windows, provide an initial geometry request of 200x200,
     * just so the window looks nicer on the screen if it doesn't request a
     * size for itself.
     */
    if(type == TYPE_TOPLEVEL) {
        Tk_GeometryRequest(*(frame->win), 200, 200);
    }

    /*
     * Store backreference to frame widget in window structure.
     */

    Tk_SetClassProcs(*(frame->win), &frameClass, frame);

    /*
     * Mark Tk frames as suitable candidates for [wm manage].
     */

    ((TkWindow *) * (frame->win))->flags |= TK_WM_MANAGEABLE;

    Tk_CreateEventHandler(*(frame->win), frame->mask, FrameEventProc, frame);

    if(type == TYPE_TOPLEVEL) {
        Tcl_DoWhenIdle(FrameMap, frame);
    }

    return TCL_OK;
}

/*
 * FrameMetaDestroy --
 *
 *	This function is invoked by Tcl_EventuallyFree or Tcl_Release to clean
 *	up the internal structure of a frame at a safe time (when no-one is
 *	using it anymore).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the frame is freed up.
 */
static void
FrameMetaDestroy(
    tkoFrame * frame)
{              /* Info about frame widget. */
tkoLabelframe *labelframe = (tkoLabelframe *) frame;

    if(frame->menuName != NULL) {
        ckfree(frame->menuName);
    }
    if(frame->useThis) {
        Tcl_DecrRefCount(frame->useThis);
    }
    if(frame->type == TYPE_LABELFRAME) {
        if(labelframe->textLayout) {
            Tk_FreeTextLayout(labelframe->textLayout);
        }
        if(labelframe->textGC != None && frame->display != None) {
            Tk_FreeGC(frame->display, labelframe->textGC);
        }
    }
    if(frame->border) {
        Tk_Free3DBorder(frame->border);
    }
    if(frame->colormap != None && frame->display != None) {
        Tk_FreeColormap(frame->display, frame->colormap);
    }
    if(frame->highlightBgColorPtr != NULL) {
        Tk_FreeColor(frame->highlightBgColorPtr);
    }
    if(frame->highlightColorPtr != NULL) {
        Tk_FreeColor(frame->highlightColorPtr);
    }
    ckfree(frame);
}

/*
 * FrameWorldChanged --
 *
 *	This function is called when the world has changed in some way and the
 *	widget needs to recompute all its graphics contexts and determine its
 *	new geometry.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Frame will be relayed out and redisplayed.
 */
static void
FrameWorldChanged(
    ClientData instanceData)
{              /* Information about widget. */
tkoFrame *frame = instanceData;
tkoLabelframe *labelframe = instanceData;
XGCValues gcValues;
GC  gc;
int anyTextLabel, anyWindowLabel;
int bWidthLeft, bWidthRight, bWidthTop, bWidthBottom;
const char *labelText;
    if(frame->win == NULL || *(frame->win) == NULL)
        return;

    anyTextLabel = (frame->type == TYPE_LABELFRAME) &&
        (labelframe->textPtr != NULL) && (labelframe->labelWin == NULL);
    anyWindowLabel = (frame->type == TYPE_LABELFRAME) &&
        (labelframe->labelWin != NULL);

    if(frame->type == TYPE_LABELFRAME) {
        /*
         * The textGC is needed even in the labelWin case, so it's always
         * created for a labelframe.
         */

        gcValues.font = Tk_FontId(labelframe->tkfont);
        gcValues.foreground = labelframe->textColorPtr->pixel;
        gcValues.graphics_exposures = False;
        gc = Tk_GetGC(*(frame->win),
            GCForeground | GCFont | GCGraphicsExposures, &gcValues);
        if(labelframe->textGC != None) {
            Tk_FreeGC(frame->display, labelframe->textGC);
        }
        labelframe->textGC = gc;

        /*
         * Calculate label size.
         */

        labelframe->labelReqWidth = labelframe->labelReqHeight = 0;

        if(anyTextLabel) {
            labelText = Tcl_GetString(labelframe->textPtr);
            if(labelframe->textLayout) {
                Tk_FreeTextLayout(labelframe->textLayout);
            }
            labelframe->textLayout =
                Tk_ComputeTextLayout(labelframe->tkfont,
                labelText, -1, 0, TK_JUSTIFY_CENTER, 0,
                &labelframe->labelReqWidth, &labelframe->labelReqHeight);
            labelframe->labelReqWidth += 2 * LABELSPACING;
            labelframe->labelReqHeight += 2 * LABELSPACING;
        } else if(anyWindowLabel) {
            labelframe->labelReqWidth = Tk_ReqWidth(labelframe->labelWin);
            labelframe->labelReqHeight = Tk_ReqHeight(labelframe->labelWin);
        }

        /*
         * Make sure label size is at least as big as the border. This
         * simplifies later calculations and gives a better appearance with
         * thick borders.
         */

        if((labelframe->labelAnchor >= LABELANCHOR_N) &&
            (labelframe->labelAnchor <= LABELANCHOR_SW)) {
            if(labelframe->labelReqHeight < frame->borderWidth) {
                labelframe->labelReqHeight = frame->borderWidth;
            }
        } else {
            if(labelframe->labelReqWidth < frame->borderWidth) {
                labelframe->labelReqWidth = frame->borderWidth;
            }
        }
    }

    /*
     * Calculate individual border widths.
     */

    bWidthBottom = bWidthTop = bWidthRight = bWidthLeft =
        frame->borderWidth + frame->highlightWidth;

    bWidthLeft += frame->padX;
    bWidthRight += frame->padX;
    bWidthTop += frame->padY;
    bWidthBottom += frame->padY;

    if(anyTextLabel || anyWindowLabel) {
        switch (labelframe->labelAnchor) {
        case LABELANCHOR_E:
        case LABELANCHOR_EN:
        case LABELANCHOR_ES:
            bWidthRight += labelframe->labelReqWidth - frame->borderWidth;
            break;
        case LABELANCHOR_N:
        case LABELANCHOR_NE:
        case LABELANCHOR_NW:
            bWidthTop += labelframe->labelReqHeight - frame->borderWidth;
            break;
        case LABELANCHOR_S:
        case LABELANCHOR_SE:
        case LABELANCHOR_SW:
            bWidthBottom += labelframe->labelReqHeight - frame->borderWidth;
            break;
        default:
            bWidthLeft += labelframe->labelReqWidth - frame->borderWidth;
            break;
        }
    }

    Tk_SetInternalBorderEx(*(frame->win), bWidthLeft, bWidthRight, bWidthTop,
        bWidthBottom);

    FrameComputeGeometry(frame);

    /*
     * A labelframe should request size for its label.
     */

    if(frame->type == TYPE_LABELFRAME) {
int minwidth = labelframe->labelReqWidth;
int minheight = labelframe->labelReqHeight;
int padding = frame->highlightWidth;

        if(frame->borderWidth > 0) {
            padding += frame->borderWidth + LABELMARGIN;
        }
        padding *= 2;
        if((labelframe->labelAnchor >= LABELANCHOR_N) &&
            (labelframe->labelAnchor <= LABELANCHOR_SW)) {
            minwidth += padding;
            minheight += frame->borderWidth + frame->highlightWidth;
        } else {
            minheight += padding;
            minwidth += frame->borderWidth + frame->highlightWidth;
        }
        Tk_SetMinimumRequestSize(*(frame->win), minwidth, minheight);
    }

    if((frame->width > 0) || (frame->height > 0)) {
        Tk_GeometryRequest(*(frame->win), frame->width, frame->height);
    }

    if(Tk_IsMapped(*(frame->win))) {
        if(!(frame->flags & REDRAW_PENDING)) {
            Tcl_DoWhenIdle(FrameDisplay, frame);
        }
        frame->flags |= REDRAW_PENDING;
    }
}

/*
 * FrameComputeGeometry --
 *
 *	This function is called to compute various geometrical information for
 *	a frame, such as where various things get displayed. It's called when
 *	the window is reconfigured.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Display-related numbers get changed in *frame.
 */

static void
FrameComputeGeometry(
    register tkoFrame * frame)
{              /* Information about widget. */
    int otherWidth, otherHeight, otherWidthT, otherHeightT, padding;
    int maxWidth, maxHeight;
    tkoLabelframe *labelframe = (tkoLabelframe *) frame;
    if(frame->win == NULL || *(frame->win) == NULL)
        return;

    /*
     * We have nothing to do here unless there is a label.
     */

    if(frame->type != TYPE_LABELFRAME) {
        return;
    }
    if(labelframe->textPtr == NULL && labelframe->labelWin == NULL) {
        return;
    }

    /*
     * Calculate the available size for the label
     */

    labelframe->labelBox.width = labelframe->labelReqWidth;
    labelframe->labelBox.height = labelframe->labelReqHeight;

    padding = frame->highlightWidth;
    if(frame->borderWidth > 0) {
        padding += frame->borderWidth + LABELMARGIN;
    }
    padding *= 2;

    maxHeight = Tk_Height(*(frame->win));
    maxWidth = Tk_Width(*(frame->win));

    if((labelframe->labelAnchor >= LABELANCHOR_N) &&
        (labelframe->labelAnchor <= LABELANCHOR_SW)) {
        maxWidth -= padding;
        if(maxWidth < 1) {
            maxWidth = 1;
        }
    } else {
        maxHeight -= padding;
        if(maxHeight < 1) {
            maxHeight = 1;
        }
    }
    if(labelframe->labelBox.width > maxWidth) {
        labelframe->labelBox.width = maxWidth;
    }
    if(labelframe->labelBox.height > maxHeight) {
        labelframe->labelBox.height = maxHeight;
    }

    /*
     * Calculate label and text position. The text's position is based on the
     * requested size (= the text's real size) to get proper alignment if the
     * text does not fit.
     */

    otherWidth = Tk_Width(*(frame->win)) - labelframe->labelBox.width;
    otherHeight = Tk_Height(*(frame->win)) - labelframe->labelBox.height;
    otherWidthT = Tk_Width(*(frame->win)) - labelframe->labelReqWidth;
    otherHeightT = Tk_Height(*(frame->win)) - labelframe->labelReqHeight;
    padding = frame->highlightWidth;

    switch (labelframe->labelAnchor) {
    case LABELANCHOR_E:
    case LABELANCHOR_EN:
    case LABELANCHOR_ES:
        labelframe->labelTextX = otherWidthT - padding;
        labelframe->labelBox.x = otherWidth - padding;
        break;
    case LABELANCHOR_N:
    case LABELANCHOR_NE:
    case LABELANCHOR_NW:
        labelframe->labelTextY = padding;
        labelframe->labelBox.y = padding;
        break;
    case LABELANCHOR_S:
    case LABELANCHOR_SE:
    case LABELANCHOR_SW:
        labelframe->labelTextY = otherHeightT - padding;
        labelframe->labelBox.y = otherHeight - padding;
        break;
    default:
        labelframe->labelTextX = padding;
        labelframe->labelBox.x = padding;
        break;
    }

    if(frame->borderWidth > 0) {
        padding += frame->borderWidth + LABELMARGIN;
    }

    switch (labelframe->labelAnchor) {
    case LABELANCHOR_NW:
    case LABELANCHOR_SW:
        labelframe->labelTextX = padding;
        labelframe->labelBox.x = padding;
        break;
    case LABELANCHOR_N:
    case LABELANCHOR_S:
        labelframe->labelTextX = otherWidthT / 2;
        labelframe->labelBox.x = otherWidth / 2;
        break;
    case LABELANCHOR_NE:
    case LABELANCHOR_SE:
        labelframe->labelTextX = otherWidthT - padding;
        labelframe->labelBox.x = otherWidth - padding;
        break;
    case LABELANCHOR_EN:
    case LABELANCHOR_WN:
        labelframe->labelTextY = padding;
        labelframe->labelBox.y = padding;
        break;
    case LABELANCHOR_E:
    case LABELANCHOR_W:
        labelframe->labelTextY = otherHeightT / 2;
        labelframe->labelBox.y = otherHeight / 2;
        break;
    default:
        labelframe->labelTextY = otherHeightT - padding;
        labelframe->labelBox.y = otherHeight - padding;
        break;
    }
}

/*
 * FrameDisplay --
 *
 *	This function is invoked to display a frame widget.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Commands are output to X to display the frame in its current mode.
 */
static void
FrameDisplay(
    ClientData clientData /* Information about widget. */)
{             
    tkoFrame *frame = clientData;
    int bdX1, bdY1, bdX2, bdY2, hlWidth;
    Pixmap pixmap;
    TkRegion clipRegion = NULL;

    if(frame->win == NULL || *(frame->win) == NULL)
        return;

    frame->flags &= ~REDRAW_PENDING;
    if(!Tk_IsMapped(*(frame->win))) {
        return;
    }

    /*
     * Highlight shall always be drawn if it exists, so do that first.
     */

    hlWidth = frame->highlightWidth;

    if(hlWidth != 0) {
GC  fgGC, bgGC;

        bgGC = Tk_GCForColor(frame->highlightBgColorPtr,
            Tk_WindowId(*(frame->win)));
        if(frame->flags & GOT_FOCUS) {
            fgGC = Tk_GCForColor(frame->highlightColorPtr,
                Tk_WindowId(*(frame->win)));
            TkpDrawHighlightBorder(*(frame->win), fgGC, bgGC, hlWidth,
                Tk_WindowId(*(frame->win)));
        } else {
            TkpDrawHighlightBorder(*(frame->win), bgGC, bgGC, hlWidth,
                Tk_WindowId(*(frame->win)));
        }
    }

    /*
     * If -background is set to "", no interior is drawn.
     */

    if(frame->border == NULL) {
        return;
    }

    if(frame->type != TYPE_LABELFRAME) {
        /*
         * Pass to platform specific draw function. In general, it just draws
         * a simple rectangle, but it may "theme" the background.
         */

      noLabel:
        TkpDrawFrame(*(frame->win), frame->border, hlWidth,
            frame->borderWidth, frame->relief);
    } else {
        tkoLabelframe *labelframe = (tkoLabelframe *) frame;

        if((labelframe->textPtr == NULL) && (labelframe->labelWin == NULL)) {
            goto noLabel;
        }
#ifndef TK_NO_DOUBLE_BUFFERING
        /*
         * In order to avoid screen flashes, this function redraws the frame
         * into off-screen memory, then copies it back on-screen in a single
         * operation. This means there's no point in time where the on-screen
         * image has been cleared.
         */

        pixmap = Tk_GetPixmap(frame->display, Tk_WindowId(*(frame->win)),
            Tk_Width(*(frame->win)), Tk_Height(*(frame->win)),
            Tk_Depth(*(frame->win)));
#else
        pixmap = Tk_WindowId(tkWin);
#endif /* TK_NO_DOUBLE_BUFFERING */

        /*
         * Clear the pixmap.
         */

        Tk_Fill3DRectangle(*(frame->win), pixmap, frame->border, 0, 0,
            Tk_Width(*(frame->win)), Tk_Height(*(frame->win)), 0,
            TK_RELIEF_FLAT);

        /*
         * Calculate how the label affects the border's position.
         */

        bdX1 = bdY1 = hlWidth;
        bdX2 = Tk_Width(*(frame->win)) - hlWidth;
        bdY2 = Tk_Height(*(frame->win)) - hlWidth;

        switch (labelframe->labelAnchor) {
        case LABELANCHOR_E:
        case LABELANCHOR_EN:
        case LABELANCHOR_ES:
            bdX2 -= (labelframe->labelBox.width - frame->borderWidth) / 2;
            break;
        case LABELANCHOR_N:
        case LABELANCHOR_NE:
        case LABELANCHOR_NW:
            /*
             * Since the glyphs of the text tend to be in the lower part we
             * favor a lower border position by rounding up.
             */

            bdY1 += (labelframe->labelBox.height - frame->borderWidth + 1) / 2;
            break;
        case LABELANCHOR_S:
        case LABELANCHOR_SE:
        case LABELANCHOR_SW:
            bdY2 -= (labelframe->labelBox.height - frame->borderWidth) / 2;
            break;
        default:
            bdX1 += (labelframe->labelBox.width - frame->borderWidth) / 2;
            break;
        }

        /*
         * Draw border
         */

        Tk_Draw3DRectangle(*(frame->win), pixmap, frame->border, bdX1, bdY1,
            bdX2 - bdX1, bdY2 - bdY1, frame->borderWidth, frame->relief);

        if(labelframe->labelWin == NULL) {
            /*
             * Clear behind the label
             */

            Tk_Fill3DRectangle(*(frame->win), pixmap,
                frame->border, labelframe->labelBox.x,
                labelframe->labelBox.y, labelframe->labelBox.width,
                labelframe->labelBox.height, 0, TK_RELIEF_FLAT);

            /*
             * Draw label. If there is not room for the entire label, use
             * clipping to get a nice appearance.
             */

            if((labelframe->labelBox.width < labelframe->labelReqWidth)
                || (labelframe->labelBox.height < labelframe->labelReqHeight)) {
                clipRegion = TkCreateRegion();
                TkUnionRectWithRegion(&labelframe->labelBox, clipRegion,
                    clipRegion);
                TkSetRegion(frame->display, labelframe->textGC, clipRegion);
            }

            Tk_DrawTextLayout(frame->display, pixmap,
                labelframe->textGC, labelframe->textLayout,
                labelframe->labelTextX + LABELSPACING,
                labelframe->labelTextY + LABELSPACING, 0, -1);

            if(clipRegion != NULL) {
                XSetClipMask(frame->display, labelframe->textGC, None);
                TkDestroyRegion(clipRegion);
            }
        } else {
            /*
             * Reposition and map the window (but in different ways depending
             * on whether the frame is the window's parent).
             */

            if(*(frame->win) == Tk_Parent(labelframe->labelWin)) {
                if((labelframe->labelBox.x != Tk_X(labelframe->labelWin))
                    || (labelframe->labelBox.y != Tk_Y(labelframe->labelWin))
                    || (labelframe->labelBox.width !=
                        Tk_Width(labelframe->labelWin))
                    || (labelframe->labelBox.height !=
                        Tk_Height(labelframe->labelWin))) {
                    Tk_MoveResizeWindow(labelframe->labelWin,
                        labelframe->labelBox.x,
                        labelframe->labelBox.y,
                        labelframe->labelBox.width,
                        labelframe->labelBox.height);
                }
                Tk_MapWindow(labelframe->labelWin);
            } else {
                Tk_MaintainGeometry(labelframe->labelWin, *(frame->win),
                    labelframe->labelBox.x, labelframe->labelBox.y,
                    labelframe->labelBox.width, labelframe->labelBox.height);
            }
        }

#ifndef TK_NO_DOUBLE_BUFFERING
        /*
         * Everything's been redisplayed; now copy the pixmap onto the screen
         * and free up the pixmap.
         */

        XCopyArea(frame->display, pixmap, Tk_WindowId(*(frame->win)),
            labelframe->textGC, hlWidth, hlWidth,
            (unsigned)(Tk_Width(*(frame->win)) - 2 * hlWidth),
            (unsigned)(Tk_Height(*(frame->win)) - 2 * hlWidth),
            hlWidth, hlWidth);
        Tk_FreePixmap(frame->display, pixmap);
#endif /* TK_NO_DOUBLE_BUFFERING */
    }

}

/*
 * FrameEventProc --
 *
 *	This function is invoked by the Tk dispatcher on structure changes to
 *	a frame. For frames with 3D borders, this function is also invoked for
 *	exposures.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get cleaned up.
 *	When it gets exposed, it is redisplayed.
 */
static void
FrameEventProc(
    ClientData clientData,     /* Information about window. */
    register XEvent * eventPtr)
{              /* Information about event. */
    tkoFrame *frame = clientData;
    if(eventPtr->type == DestroyNotify || frame->win == NULL
        || *(frame->win) == NULL)
        return;

    if((eventPtr->type == Expose) && (eventPtr->xexpose.count == 0)) {
        goto redraw;
    } else if(eventPtr->type == ConfigureNotify) {
        FrameComputeGeometry(frame);
        goto redraw;
    } else if(eventPtr->type == FocusIn) {
        if(eventPtr->xfocus.detail != NotifyInferior) {
            frame->flags |= GOT_FOCUS;
            if(frame->highlightWidth > 0) {
                goto redraw;
            }
        }
    } else if(eventPtr->type == FocusOut) {
        if(eventPtr->xfocus.detail != NotifyInferior) {
            frame->flags &= ~GOT_FOCUS;
            if(frame->highlightWidth > 0) {
                goto redraw;
            }
        }
    } else if(eventPtr->type == ActivateNotify) {
        TkpSetMainMenubar(frame->interp, *(frame->win), frame->menuName);
    }
    return;

  redraw:
    if(!(frame->flags & REDRAW_PENDING)) {
        Tcl_DoWhenIdle(FrameDisplay, frame);
        frame->flags |= REDRAW_PENDING;
    }
}

/*
 * FrameMap --
 *
 *	This function is invoked as a when-idle handler to map a newly-created
 *	top-level frame.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The frame given by the clientData argument is mapped.
 */
static void
FrameMap(
    ClientData clientData)
{              /* Pointer to frame structure. */
tkoFrame *frame = clientData;
    if(frame->win == NULL || *(frame->win) == NULL)
        return;

    /*
     * Wait for all other background events to be processed before mapping
     * window. This ensures that the window's correct geometry will have been
     * determined before it is first mapped, so that the window manager
     * doesn't get a false idea of its desired geometry.
     */

    Tcl_Preserve(frame);
    while(1) {
        if(Tcl_DoOneEvent(TCL_IDLE_EVENTS) == 0) {
            break;
        }

        /*
         * After each event, make sure that the window still exists and quit
         * if the window has been destroyed.
         */
        if(frame->win == NULL || *(frame->win) == NULL) {
            Tcl_Release(frame);
            return;
        }
    }
    Tk_MapWindow(*(frame->win));
    Tcl_Release(frame);
}

/*
 * FrameStructureProc --
 *
 *	This function is invoked whenever StructureNotify events occur for a
 *	window that's managed as label for the frame. This procudure's only
 *	purpose is to clean up when windows are deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The window is disassociated from the frame when it is deleted.
 */
static void
FrameStructureProc(
    ClientData clientData,     /* Pointer to record describing frame. */
    XEvent * eventPtr)
{              /* Describes what just happened. */
tkoLabelframe *labelframe = clientData;

    /*
     * This should only happen in a labelframe but it doesn't hurt to be
     * careful.
     */
    if((eventPtr->type == DestroyNotify)
        && (labelframe->frame.type == TYPE_LABELFRAME)) {
        FrameLabelwinRemove(labelframe);
    }
}

/*
 * FrameLabelwinRemove --
 *
 * Results:
 *  None.
 *
 * Side effects:
 */
static void
FrameLabelwinRemove(
    tkoLabelframe * labelframe)
{
tkoFrame *frame = (tkoFrame *) labelframe;
Tcl_Obj *arrayName = TkoWidgetOptionVar(frame->object);
    labelframe->labelWin = NULL;
    if(arrayName == NULL)
        return;
    Tcl_ObjSetVar2(frame->interp, arrayName, TkoObj._labelwidget, TkoObj.empty,
        TCL_GLOBAL_ONLY);
    FrameWorldChanged(labelframe);
}

/*
 * FrameRequestProc --
 *
 *	This function is invoked whenever a window that's associated with a
 *	frame changes its requested dimensions.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The size and location on the screen of the window may change depending
 *	on the options specified for the frame.
 */
static void
FrameRequestProc(
    ClientData clientData,     /* Pointer to record for frame. */
    Tk_Window tkWin)
{              /* Window that changed its desired size. */
tkoFrame *frame = clientData;

    FrameWorldChanged(frame);
}

/*
 * FrameLostSlaveProc --
 *
 *	This function is invoked by Tk whenever some other geometry claims
 *	control over a slave that used to be managed by us.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Forgets all frame-related information about the slave.
 */
static void
FrameLostSlaveProc(
    ClientData clientData,     /* Frame structure for slave window that was
                                * stolen away. */
    Tk_Window tkWin            /* Tk's handle for the slave window. */)
{
    tkoLabelframe *labelframe = clientData;

    /*
     * This should only happen in a labelframe but it doesn't hurt to be
     * careful.
     */

    if(labelframe->frame.type == TYPE_LABELFRAME) {
        Tk_DeleteEventHandler(labelframe->labelWin, StructureNotifyMask,
            FrameStructureProc, labelframe);
        if(tkWin != Tk_Parent(labelframe->labelWin)) {
            Tk_UnmaintainGeometry(labelframe->labelWin, tkWin);
        }
        Tk_UnmapWindow(labelframe->labelWin);
        FrameLabelwinRemove(labelframe);
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraph.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGraph.c --
 *
 *      This module implements a graph widget for the rbc toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

/*
 * To do:
 *
 * 5) Surface, contour, and flow graphs
 *
 * 7) Arrows for line markers
 *
 */

#include "tkoGraph.h"

Tk_Uid rbcXAxisUid;
Tk_Uid rbcYAxisUid;
Tk_Uid rbcBarElementUid;
Tk_Uid rbcLineElementUid;
Tk_Uid rbcStripElementUid;
Tk_Uid rbcContourElementUid;
Tk_Uid rbcLineMarkerUid;
Tk_Uid rbcBitmapMarkerUid;
Tk_Uid rbcImageMarkerUid;
Tk_Uid rbcTextMarkerUid;
Tk_Uid rbcPolygonMarkerUid;
Tk_Uid rbcWindowMarkerUid;

extern Tk_CustomOption rbcLinePenOption;
extern Tk_CustomOption rbcBarPenOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcBarModeOption;
extern Tk_CustomOption rbcPadOption;
extern Tk_CustomOption rbcTileOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcStyleOption;

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

#define DEF_GRAPH_ASPECT_RATIO      "0.0"
#define DEF_GRAPH_BAR_BASELINE      "0.0"
#define DEF_GRAPH_BAR_MODE          "normal"
#define DEF_GRAPH_BAR_WIDTH         "0.8"
#define DEF_GRAPH_BACKGROUND        RBC_NORMAL_BACKGROUND
#define DEF_GRAPH_BG_MONO           RBC_NORMAL_BG_MONO
#define DEF_GRAPH_BORDERWIDTH       RBC_BORDERWIDTH
#define DEF_GRAPH_BUFFER_ELEMENTS   "1"
#define DEF_GRAPH_BUFFER_GRAPH	    "1"
#define DEF_GRAPH_CURSOR            "crosshair"
#define DEF_GRAPH_FONT              RBC_FONT_LARGE
#define DEF_GRAPH_HALO              "2m"
#define DEF_GRAPH_HALO_BAR          "0.1i"
#define DEF_GRAPH_HEIGHT            "4i"
#define DEF_GRAPH_HIGHLIGHT_BACKGROUND  RBC_NORMAL_BACKGROUND
#define DEF_GRAPH_HIGHLIGHT_BG_MONO RBC_NORMAL_BG_MONO
#define DEF_GRAPH_HIGHLIGHT_COLOR   "black"
#define DEF_GRAPH_HIGHLIGHT_WIDTH   "2"
#define DEF_GRAPH_INVERT_XY         "0"
#define DEF_GRAPH_JUSTIFY           "center"
#define DEF_GRAPH_MARGIN            "0"
#define DEF_GRAPH_MARGIN_VAR        (char *)NULL
#define DEF_GRAPH_PLOT_BACKGROUND   "white"
#define DEF_GRAPH_PLOT_BG_MONO      "white"
#define DEF_GRAPH_PLOT_BW_COLOR     RBC_BORDERWIDTH
#define DEF_GRAPH_PLOT_BW_MONO      "0"
#define DEF_GRAPH_PLOT_PADX         "8"
#define DEF_GRAPH_PLOT_PADY         "8"
#define DEF_GRAPH_PLOT_RELIEF       "sunken"
#define DEF_GRAPH_RELIEF            "flat"
#define DEF_GRAPH_SHADOW_COLOR      (char *)NULL
#define DEF_GRAPH_SHADOW_MONO       (char *)NULL
#define DEF_GRAPH_SHOW_VALUES       "no"
#define DEF_GRAPH_TAKE_FOCUS        ""
#define DEF_GRAPH_TITLE             (char *)NULL
#define DEF_GRAPH_TITLE_COLOR       RBC_NORMAL_FOREGROUND
#define DEF_GRAPH_TITLE_MONO        RBC_NORMAL_FG_MONO
#define DEF_GRAPH_WIDTH             "5i"
#define DEF_GRAPH_DATA              (char *)NULL
#define DEF_GRAPH_DATA_COMMAND      (char *)NULL

static RbcSwitchParseProc StringToFormat;
static RbcSwitchCustom formatSwitch = {
    StringToFormat, (RbcSwitchFreeProc *) NULL, (ClientData) 0,
};

/*
 * SnapData --
 */
typedef struct SnapData {
    char *name;
    int width, height;
    int format;
} SnapData;

enum SnapFormats { FORMAT_PHOTO, FORMAT_EMF, FORMAT_WMF };

/*
 * snapSwitches --
 */
static RbcSwitchSpec snapSwitches[] = {
    {RBC_SWITCH_INT_POSITIVE, "-width", Tk_Offset(SnapData, width), 0},
    {RBC_SWITCH_INT_POSITIVE, "-height", Tk_Offset(SnapData, height), 0},
    {RBC_SWITCH_CUSTOM, "-format", Tk_Offset(SnapData, format), 0,
        &formatSwitch},
    {RBC_SWITCH_END, NULL, 0, 0}
};

static Tcl_IdleProc DisplayGraph;
static Tk_EventProc GraphEventProc;

static RbcBindPickProc PickEntry;
static RbcTileChangedProc TileChangedProc;
/*
* Methods
*/
static int GraphConstructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_tko_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_style(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_barmode(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_barwidth(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_plotpadx(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_plotpady(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_shadow(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);
static int GraphMethod_tile(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[]);

/*
 * Functions
 */
static void AdjustAxisPointers(
    RbcGraph * graph);
static void DrawMargins(
    RbcGraph * graph,
    Drawable drawable);
static void DrawPlotRegion(
    RbcGraph * graph,
    Drawable drawable);
static void UpdateMarginTraces(
    RbcGraph * graph);
static int XAxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int X2AxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int YAxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int Y2AxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int BarOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int LineOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ElementOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ExtentsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int InsideOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int InvtransformOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int TransformOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int SnapOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
#ifdef __WIN32
static int InitMetaFileHeader(
    Tk_Window tkwin,
    int width,
    int height,
    APMHEADER * mfhPtr);
static int CreateAPMetaFile(
    Tcl_Interp * interp,
    HANDLE hMetaFile,
    HDC hDC,
    APMHEADER * mfhPtr,
    char *fileName);
#endif
static void GraphMetaDestroy(
    RbcGraph * graph);
static void
GraphMetaDelete(
    ClientData clientData)
{
    Tcl_EventuallyFree(clientData, (Tcl_FreeProc *) GraphMetaDestroy);
}

/*
 * graphMeta --
 */
static Tcl_ObjectMetadataType graphMeta = {
    TCL_OO_METADATA_VERSION_CURRENT,
    "GraphMeta",
    GraphMetaDelete,
    NULL
};

/*
 * RbcGraphFromObject --
 *
 * Return:
 *  RbcGraph structure from object meta data.
 */
RbcGraph *
RbcGraphFromObject(
    Tcl_Object object)
{
    return (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta);
}

/*
 * graphOptionDefine --
 *
 * Options and option methods created in class constructor.
 */
static tkoWidgetOptionDefine graphOptionDefine[] = {
    {"-class", "class", "Class", "TkoGraph", TKO_OPTION_READONLY, NULL,
	NULL, NULL, TKO_SET_CLASS, NULL, 0},
    {"-style", "style", "Style", "line", TKO_OPTION_READONLY, NULL,
	NULL, GraphMethod_style, 0, NULL, 0},
    {"-aspect", "aspect", "Aspect", DEF_GRAPH_ASPECT_RATIO, 0, NULL,
	NULL, NULL, TKO_SET_DOUBLE, &graphMeta, offsetof(RbcGraph, aspect)},
    {"-background", "background", "Background", DEF_GRAPH_BACKGROUND, 0, NULL,
	NULL, NULL, TKO_SET_3DBORDER, &graphMeta, offsetof(RbcGraph, border)},
    {"-barmode", "barMode", "BarMode", DEF_GRAPH_BAR_MODE, 0, NULL,
	NULL, GraphMethod_barmode, 0, NULL, 0},
    {"-barwidth", "barWidth", "BarWidth", DEF_GRAPH_BAR_WIDTH, 0, NULL,
	NULL, GraphMethod_barwidth, 0, NULL, 0},
    {"-baseline", "baseline", "Baseline", DEF_GRAPH_BAR_BASELINE, 0, NULL,
	NULL, NULL, TKO_SET_DOUBLE, &graphMeta, offsetof(RbcGraph, baseline)},
    {"-bd", "-borderwidth", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-bg", "-background", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-bm", "-bottommargin", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-borderwidth", "borderWidth", "BorderWidth", DEF_GRAPH_BORDERWIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph, borderWidth)},
    {"-bottommargin", "bottomMargin", "Margin", DEF_GRAPH_MARGIN, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_BOTTOM].reqSize)},
    {"-bottomvariable", "bottomVariable", "BottomVariable", DEF_GRAPH_MARGIN_VAR, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_BOTTOM].varName)},
    {"-bufferelements", "bufferElements", "BufferElements", DEF_GRAPH_BUFFER_ELEMENTS, 0, NULL,
	NULL, NULL, TKO_SET_BOOLEAN, &graphMeta, offsetof(RbcGraph, backingStore)},
    {"-buffergraph", "bufferGraph", "BufferGraph", DEF_GRAPH_BUFFER_GRAPH, 0, NULL,
	NULL, NULL, TKO_SET_BOOLEAN, &graphMeta, offsetof(RbcGraph, doubleBuffer)},
    {"-cursor", "cursor", "Cursor", DEF_GRAPH_CURSOR, 0, NULL,
	NULL, NULL, TKO_SET_CURSOR, &graphMeta, offsetof(RbcGraph, cursor)},
    {"-fg", "-foreground", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-font", "font", "Font", DEF_GRAPH_FONT, 0, NULL,
	NULL, NULL, TKO_SET_FONT, &graphMeta, offsetof(RbcGraph, titleTextStyle.font)},
    {"-foreground", "foreground", "Foreground", DEF_GRAPH_TITLE_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &graphMeta, offsetof(RbcGraph, titleTextStyle.color)},
    {"-halo", "halo", "Halo", DEF_GRAPH_HALO, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph, halo)},
    {"-height", "height", "Height", DEF_GRAPH_HEIGHT, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph, reqHeight)},
    {"-highlightbackground", "highlightBackground", "HighlightBackground", DEF_GRAPH_HIGHLIGHT_BACKGROUND, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &graphMeta, offsetof(RbcGraph, highlightBgColor)},
    {"-highlightcolor", "highlightColor", "HighlightColor", DEF_GRAPH_HIGHLIGHT_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &graphMeta, offsetof(RbcGraph, highlightColor)},
    {"-highlightthickness", "highlightThickness", "HighlightThickness", DEF_GRAPH_HIGHLIGHT_WIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXEL, &graphMeta, offsetof(RbcGraph, highlightWidth)},
    {"-invertxy", "invertXY", "InvertXY", DEF_GRAPH_INVERT_XY, 0, NULL,
	NULL, NULL, TKO_SET_BOOLEAN, &graphMeta, offsetof(RbcGraph, inverted)},
    {"-justify", "justify", "Justify", DEF_GRAPH_JUSTIFY, 0, NULL,
	NULL, NULL, TKO_SET_JUSTIFY, &graphMeta, offsetof(RbcGraph,titleTextStyle.justify)},
    {"-leftmargin", "leftMargin", "Margin", DEF_GRAPH_MARGIN, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_LEFT].reqSize)},
    {"-leftvariable", "leftVariable", "LeftVariable", DEF_GRAPH_MARGIN_VAR, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_LEFT].varName)},
    {"-lm", "-leftmargin", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-plotbackground", "plotBackground", "Background", DEF_GRAPH_PLOT_BG_MONO, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &graphMeta, offsetof(RbcGraph, plotBg)},
    {"-plotborderwidth", "plotBorderWidth", "BorderWidth", DEF_GRAPH_PLOT_BW_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph,plotBorderWidth)},
    {"-plotpadx", "plotPadX", "PlotPad", DEF_GRAPH_PLOT_PADX, 0, NULL,
	NULL, GraphMethod_plotpadx, 0, NULL, 0},
    {"-plotpady", "plotPadY", "PlotPad", DEF_GRAPH_PLOT_PADY, 0, NULL,
	NULL, GraphMethod_plotpady, 0, NULL, 0},
    {"-plotrelief", "plotRelief", "Relief", DEF_GRAPH_PLOT_RELIEF, 0, NULL,
	NULL, NULL, TKO_SET_RELIEF, &graphMeta, offsetof(RbcGraph, plotRelief)},
    {"-relief", "relief", "Relief", DEF_GRAPH_RELIEF, 0, NULL,
	NULL, NULL, TKO_SET_RELIEF, &graphMeta, offsetof(RbcGraph, relief)},
    {"-rightmargin", "rightMargin", "Margin", DEF_GRAPH_MARGIN, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_RIGHT].reqSize)},
    {"-rightvariable", "rightVariable", "RightVariable", DEF_GRAPH_MARGIN_VAR, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_RIGHT].varName)},
    {"-rm", "-rightmargin", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-shadow", "shadow", "Shadow", DEF_GRAPH_SHADOW_COLOR, 0, NULL,
	NULL, GraphMethod_shadow, 0, NULL, 0},
    {"-takefocus", "takeFocus", "TakeFocus", DEF_GRAPH_TAKE_FOCUS, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph, takeFocus)},
    {"-tile", "tile", "Tile", NULL, 0, NULL,
	NULL, GraphMethod_tile, 0, NULL, 0},
    {"-title", "title", "Title", DEF_GRAPH_TITLE, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph, title)},
    {"-tm", "-topmargin", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-topmargin", "-topmargin", "Margin", DEF_GRAPH_MARGIN, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_TOP].reqSize)},
    {"-topvariable", "topVariable", "TopVariable", DEF_GRAPH_MARGIN_VAR, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &graphMeta, offsetof(RbcGraph,margins[RBC_MARGIN_TOP].varName)},
    {"-width", "width", "Width", DEF_GRAPH_WIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &graphMeta, offsetof(RbcGraph, reqWidth)},
    {NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0}
};

/*
 * graphMethods --
 *
 * Methods created in class constructor.
 */
static Tcl_MethodType graphMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, GraphConstructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, GraphDestructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "axis", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "bar", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "crosshairs", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "element", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "extents", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "grid", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "inside", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "invtransform", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "legend", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "line", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "marker", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "pen", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "postscript", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "snap", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "transform", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "x2axis", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "xaxis", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "y2axis", GraphMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "yaxis", GraphMethod, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure", GraphMethod_tko_configure,
            NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/*
 * Tko_GraphInit --
 *
 *  Initializer for the graph widget package.
 *
 * Results:
 *  A standard Tcl result.
 *
 * Side Effects:
 *  Tcl commands created
 */
int
Tko_GraphInit(
    Tcl_Interp * interp)
{
Tcl_Class clazz;
Tcl_Object object;
static const char *initScript =
    "::oo::class create ::graph {superclass ::tko::widget; variable tko; {*}$::tko::unknown}";

    rbcBarElementUid = Tk_GetUid("BarElement");
    rbcLineElementUid = Tk_GetUid("LineElement");
    rbcStripElementUid = Tk_GetUid("StripElement");
    rbcContourElementUid = Tk_GetUid("ContourElement");

    rbcLineMarkerUid = Tk_GetUid("LineMarker");
    rbcBitmapMarkerUid = Tk_GetUid("BitmapMarker");
    rbcImageMarkerUid = Tk_GetUid("ImageMarker");
    rbcTextMarkerUid = Tk_GetUid("TextMarker");
    rbcPolygonMarkerUid = Tk_GetUid("PolygonMarker");
    rbcWindowMarkerUid = Tk_GetUid("WindowMarker");

    rbcXAxisUid = Tk_GetUid("X");
    rbcYAxisUid = Tk_GetUid("Y");

    /* Create widget class. */
    if(Tcl_Eval(interp, initScript) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Get class object
     */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.graph)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /*
     * Add methods and options
     */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            graphMethods, graphOptionDefine) != TCL_OK) {
        return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 * GraphConstructor --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphConstructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    RbcGraph *graph;
    int skip;
    Tcl_Obj *myObjv[5];

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL) {
        return TCL_ERROR;
    }
    skip = Tcl_ObjectContextSkippedArgs(context);
    /* Check calling args */
    if(skip != 3 || objc != 5 || strcmp("create", Tcl_GetString(objv[1])) != 0) {
        Tcl_WrongNumArgs(interp, 1, objv, "pathName ?options?");
        return TCL_ERROR;
    }
    if(objc < 3 || strcmp("create", Tcl_GetString(objv[1])) != 0) {
        Tcl_WrongNumArgs(interp, 1, objv, "pathName ?options?");
        return TCL_ERROR;
    }
    /* Get own options */
    myObjv[3] =
        Tcl_ObjGetVar2(interp, TkoObj.tko_options, TkoObj.graph,
        TCL_GLOBAL_ONLY);
    if(myObjv[3] == NULL) {
        return TCL_ERROR;
    }

    /*
     * Create and initialize the graph data structure.
     */
    graph = RbcCalloc(1, sizeof(RbcGraph));
    assert(graph);
    graph->interp = interp;
    graph->win = NULL;
    graph->classUid = rbcLineElementUid;
    graph->chartStyle = "line";
    graph->object = object;
    graph->display = None;
    graph->flags = (RBC_RESET_WORLD);
    graph->cursor = None;
    graph->inset = 0;
    graph->borderWidth = 0;
    graph->relief = TK_RELIEF_FLAT;
    graph->highlightWidth = 2;
    graph->cursor = None;
    graph->border = NULL;
    graph->highlightBgColor = NULL;
    graph->highlightColor = NULL;
    graph->title = NULL;
    graph->titleX = graph->titleY = 0;
    RbcInitTextStyle(&graph->titleTextStyle);
    graph->takeFocus = NULL;
    graph->reqWidth = graph->reqHeight = 0;
    graph->width = graph->height = 0;
    Tcl_InitHashTable(&graph->penTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->axes.table, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->axes.tagTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->elements.table, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->elements.tagTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->markers.table, TCL_STRING_KEYS);
    Tcl_InitHashTable(&graph->markers.tagTable, TCL_STRING_KEYS);
    graph->elements.displayList = RbcChainCreate();
    graph->markers.displayList = RbcChainCreate();
    graph->axes.displayList = RbcChainCreate();
    graph->classUid = NULL;
    graph->chartStyle = NULL;
    graph->bindTable = NULL;
    graph->nextMarkerId = 1;
    graph->axisChain[0] = NULL; /* set in RbcDefaultAxes() */
    graph->axisChain[1] = NULL; /* set in RbcDefaultAxes() */
    graph->axisChain[2] = NULL; /* set in RbcDefaultAxes() */
    graph->axisChain[3] = NULL; /* set in RbcDefaultAxes() */
    graph->margins[RBC_MARGIN_BOTTOM].site = RBC_MARGIN_BOTTOM;
    graph->margins[RBC_MARGIN_LEFT].site = RBC_MARGIN_LEFT;
    graph->margins[RBC_MARGIN_TOP].site = RBC_MARGIN_TOP;
    graph->margins[RBC_MARGIN_RIGHT].site = RBC_MARGIN_RIGHT;
    graph->postscript = NULL;
    graph->legend = NULL;
    graph->crosshairs = NULL;
    graph->gridPtr = NULL;
    graph->halo = 0;
    graph->inverted = 0;
    graph->tile = NULL;
    graph->drawGC = NULL;
    graph->fillGC = NULL;
    graph->plotBorderWidth = 0;
    graph->plotRelief = TK_RELIEF_SUNKEN;
    graph->plotBg = NULL;
    graph->plotFillGC = NULL;
    graph->aspect = 0.0;
    graph->left = graph->right = 0;
    graph->top = graph->bottom = 0;
    graph->padX.side1 = graph->padX.side2 = 8;
    graph->vRange = graph->vOffset = 0;
    graph->padY.side1 = graph->padY.side2 = 8;
    graph->hRange = graph->hOffset = 0;
    graph->vScale = graph->hScale = 0.;
    graph->doubleBuffer = TRUE;
    graph->backingStore = TRUE;
    graph->backPixmap = None;
    graph->backWidth = graph->backHeight = 0;
    graph->baseline = 0.;
    graph->barWidth = 0.;
    graph->mode = MODE_INFRONT;
    graph->freqArr = NULL;
/*      Tcl_HashTable   freqTable; */
    graph->nStacks = 0;

    Tcl_ObjectSetMetadata(object, &graphMeta, (ClientData) graph);

    graph->win = TkoWidgetWindow(object);
    if(graph)
        /* call next constructor */
        myObjv[0] = objv[0];
    myObjv[1] = objv[1];
    myObjv[2] = objv[2];
    myObjv[3] = Tcl_DuplicateObj(myObjv[3]);
    Tcl_IncrRefCount(myObjv[3]);
    Tcl_ListObjAppendList(interp, myObjv[3], objv[objc - 2]);
    myObjv[4] = objv[4];
    if(Tcl_ObjectContextInvokeNext(interp, context, objc, myObjv,
            skip) != TCL_OK) {
        Tcl_DecrRefCount(myObjv[3]);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(myObjv[3]);
    graph->win = TkoWidgetWindow(object);
    if(graph->win == NULL || *(graph->win) == NULL) {
        return TCL_ERROR;
    }
    if((graph->display = Tk_Display(*(graph->win))) == None) {
        return TCL_ERROR;
    }

    RbcSetWindowInstanceData(*(graph->win), graph);

    /*
     * Init pens
     */
    if(RbcCreatePen(graph, "activeLine", rbcLineElementUid, 0,
            (const char **)NULL) == NULL) {
        return TCL_ERROR;
    }
    if(RbcCreatePen(graph, "activeBar", rbcBarElementUid, 0,
            (const char **)NULL) == NULL) {
        return TCL_ERROR;
    }
    /*
     * Create axis
     */
    if(RbcDefaultAxes(graph) != TCL_OK) {
        return TCL_ERROR;
    }
    AdjustAxisPointers(graph);

    if(RbcCreatePostScript(graph) != TCL_OK) {
        return TCL_ERROR;
    }
    if(RbcCreateCrosshairs(graph) != TCL_OK) {
        return TCL_ERROR;
    }
    if(RbcCreateLegend(graph) != TCL_OK) {
        return TCL_ERROR;
    }
    if(RbcCreateGrid(graph) != TCL_OK) {
        return TCL_ERROR;
    }
    Tk_CreateEventHandler(*(graph->win),
        ExposureMask | StructureNotifyMask | FocusChangeMask, GraphEventProc,
        graph);

    graph->bindTable =
        RbcCreateBindingTable(interp, *(graph->win), graph, PickEntry);

    /* No need to set return value. It will be ignored by "oo::class create" */
    return TCL_OK;
}

/*
 * GraphDestructor --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    int skip;
    RbcGraph *graph;
    Tk_Window tkWin = NULL;

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL)
        return TCL_ERROR;
    skip = Tcl_ObjectContextSkippedArgs(context);

    if((graph = (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) != NULL) {
        Tcl_Preserve(graph);

        if(graph->win) {
            tkWin = *(graph->win);
            graph->win = NULL;
        }
        if(tkWin) {
            Tk_DeleteEventHandler(tkWin,
                ExposureMask | StructureNotifyMask | FocusChangeMask,
                GraphEventProc, graph);
        }

        Tcl_Release(graph);
        Tcl_ObjectSetMetadata(object, &graphMeta, NULL);
    }
    /* ignore errors */
    Tcl_ObjectContextInvokeNext(interp, context, objc, objv, skip);

    return TCL_OK;
}

/*
* GraphMetaDestroy --
*
*      This procedure is invoked by Tcl_EventuallyFree or Tcl_Release
*      to clean up the internal structure of a graph at a safe time
*      (when no-one is using it anymore).
*
* Results:
*      None.
*
* Side effects:
*      Everything associated with the widget is freed up.
*/
static void
GraphMetaDestroy(
    RbcGraph * graph)
{
    if(graph->flags & RBC_REDRAW_PENDING) {
        Tcl_CancelIdleCall(DisplayGraph, graph);
    }
    if(graph->border != NULL) {
        Tk_Free3DBorder(graph->border);
    }
    if(graph->highlightBgColor != NULL) {
        Tk_FreeColor(graph->highlightBgColor);
    }
    if(graph->highlightColor != NULL) {
        Tk_FreeColor(graph->highlightColor);
    }
    if(graph->plotBg != NULL) {
        Tk_FreeColor(graph->plotBg);
    }
    /*
     * Destroy the individual components of the graph: elements, markers,
     * X and Y axes, legend, display lists etc.
     */
    RbcDestroyMarkers(graph);
    RbcDestroyElements(graph);
    RbcDestroyAxes(graph);      /* take care of *axisChain */
    RbcDestroyPens(graph);

    if(graph->legend != NULL) {
        RbcDestroyLegend(graph);
    }
    if(graph->postscript != NULL) {
        RbcDestroyPostScript(graph);
    }
    if(graph->crosshairs != NULL) {
        RbcDestroyCrosshairs(graph);
    }
    if(graph->gridPtr != NULL) {
        RbcDestroyGrid(graph);
    }
    if(graph->bindTable != NULL) {
        RbcDestroyBindingTable(graph->bindTable);
    }

    /* Release allocated X resources and memory. */
    if(graph->display != None) {
        if(graph->cursor != None) {
            Tk_FreeCursor(graph->display, graph->cursor);
        }
        if(graph->drawGC != NULL) {
            Tk_FreeGC(graph->display, graph->drawGC);
        }
        if(graph->fillGC != NULL) {
            Tk_FreeGC(graph->display, graph->fillGC);
        }
        if(graph->plotFillGC != NULL) {
            Tk_FreeGC(graph->display, graph->plotFillGC);
        }
        RbcFreeTextStyle(graph->display, &graph->titleTextStyle);
        if(graph->backPixmap != None) {
            Tk_FreePixmap(graph->display, graph->backPixmap);
        }
    }
    if(graph->freqArr != NULL) {
        ckfree((char *)graph->freqArr);
    }
    if(graph->title != NULL) {
        ckfree(graph->title);
    }
    if(graph->takeFocus != NULL) {
        ckfree(graph->takeFocus);
    }
    if(graph->nStacks > 0) {
        Tcl_DeleteHashTable(&graph->freqTable);
    }
    if(graph->tile != NULL) {
        RbcFreeTile(graph->tile);
    }
    ckfree((char *)graph);
}

/*
* GraphMethod_tko_configure --
*
*      Allocates resources for the graph.
*
* Results:
*      None.
*
* Side effects:
*      Configuration information, such as text string, colors, font,
*      etc. get set for graph;  old resources get freed, if there
*      were any.  The graph is redisplayed.
*/
static int
GraphMethod_tko_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    RbcGraph *graph;
    XColor *colorPtr;
    GC  newGC;
    XGCValues gcValues;
    unsigned long gcMask;

    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL) {
        return TCL_ERROR;
    }
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    /* Don't allow negative bar widths. Reset to an arbitrary value (0.1) */
    if(graph->barWidth <= 0.0) {
        graph->barWidth = 0.1;
    }
    graph->inset = graph->borderWidth + graph->highlightWidth + 1;
    if((graph->reqHeight != Tk_ReqHeight(*(graph->win)))
        || (graph->reqWidth != Tk_ReqWidth(*(graph->win)))) {
        Tk_GeometryRequest(*(graph->win), graph->reqWidth, graph->reqHeight);
    }
    Tk_SetInternalBorder(*(graph->win), graph->borderWidth);
    colorPtr = Tk_3DBorderColor(graph->border);

    if(graph->title != NULL) {
    int w, h;

        RbcGetTextExtents(&graph->titleTextStyle, graph->title, &w, &h);
        graph->titleTextStyle.height = h + 10;
    } else {
        graph->titleTextStyle.width = graph->titleTextStyle.height = 0;
    }

    /*
     * Create GCs for interior and exterior regions, and a background
     * GC for clearing the margins with XFillRectangle
     */

    /* Margin GC */

    gcValues.foreground = graph->titleTextStyle.color->pixel;
    gcValues.background = colorPtr->pixel;
    gcMask = (GCForeground | GCBackground);
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(graph->drawGC != NULL) {
        Tk_FreeGC(graph->display, graph->drawGC);
    }
    graph->drawGC = newGC;

    /* Plot fill GC (Background = Foreground) */

    gcValues.foreground = graph->plotBg->pixel;
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(graph->plotFillGC != NULL) {
        Tk_FreeGC(graph->display, graph->plotFillGC);
    }
    graph->plotFillGC = newGC;

    /* Margin fill GC (Background = Foreground) */

    gcValues.foreground = colorPtr->pixel;
    gcValues.background = graph->titleTextStyle.color->pixel;
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(graph->fillGC != NULL) {
        Tk_FreeGC(graph->display, graph->fillGC);
    }
    graph->fillGC = newGC;
    if(graph->tile != NULL) {
        RbcSetTileChangedProc(graph->tile, TileChangedProc, graph);
    }

    RbcResetTextStyle(*(graph->win), &graph->titleTextStyle);

    if(RbcConfigModified(configSpecs, "-invertxy", (char *)NULL)) {

        /*
         * If the -inverted option changed, we need to readjust the pointers
         * to the axes and recompute the their scales.
         */

        AdjustAxisPointers(graph);
        graph->flags |= RBC_RESET_AXES;
    }
    if((!graph->backingStore) && (graph->backPixmap != None)) {

        /*
         * Free the pixmap if we're not buffering the display of elements
         * anymore.
         */

        Tk_FreePixmap(graph->display, graph->backPixmap);
        graph->backPixmap = None;
    }
    /*
     * Reconfigure the crosshairs, just in case the background color of
     * the plotarea has been changed.
     */
    RbcConfigureCrosshairs(graph);

    /*
     *  Update the layout of the graph (and redraw the elements) if
     *  any of the following graph options which affect the size of
     *  the plotting area has changed.
     *
     *      -aspect
     *      -borderwidth, -plotborderwidth
     *      -font, -title
     *      -width, -height
     *      -invertxy
     *      -bottommargin, -leftmargin, -rightmargin, -topmargin,
     *      -barmode, -barwidth
     */
    if(RbcConfigModified(configSpecs, "-invertxy", "-title", "-font",
            "-*margin", "-*width", "-height", "-barmode", "-*pad*", "-aspect",
            (char *)NULL)) {
        graph->flags |= RBC_RESET_WORLD;
    }
    if(RbcConfigModified(configSpecs, "-plotbackground", (char *)NULL)) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    graph->flags |= RBC_REDRAW_WORLD;
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * GraphMethod --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int cmdIndex, result;
    RbcOp proc;
    int i;
    const char **myArgv;
    static const char *const graphCmdNames[] = {
        "axis", "bar",
        "crosshairs", "element", "extents", "grid",
        "inside", "invtransform", "legend", "line",
        "marker", "pen", "postscript",
        "snap", "transform",
        "x2axis", "xaxis", "y2axis", "yaxis",
        NULL
    };

    enum graphCmd {
        COMMAND_AXIS, COMMAND_BAR,
        COMMAND_CROSSHAIRS, COMMAND_ELEMENT, COMMAND_EXTENTS, COMMAND_GRID,
        COMMAND_INSIDE, COMMAND_INVTRANSFORM, COMMAND_LEGEND, COMMAND_LINE,
        COMMAND_MARKER, COMMAND_PEN, COMMAND_POSTSCRIPT,
        COMMAND_SNAP, COMMAND_TRANSFORM,
        COMMAND_X2AXIS, COMMAND_XAXIS, COMMAND_Y2AXIS, COMMAND_YAXIS
    };

    RbcGraph *graph =
        (RbcGraph *) Tcl_ObjectGetMetadata(Tcl_ObjectContextObject(context),
        &graphMeta);

    /*
     * Parse the widget command by looking up the second token in the list of
     * valid command names.
     */

    result = Tcl_GetIndexFromObj(interp, objv[1], graphCmdNames, "option", 0,
        &cmdIndex);
    if(result != TCL_OK) {
        return result;
    }

    switch ((enum graphCmd)cmdIndex) {
    case COMMAND_AXIS:{
        proc = (RbcOp) RbcVirtualAxisOp;
        break;
    }
    case COMMAND_BAR:{
        proc = BarOp;
        break;
    }
    case COMMAND_CROSSHAIRS:{
        proc = RbcCrosshairsOp;
        break;
    }
    case COMMAND_ELEMENT:{
        proc = ElementOp;
        break;
    }
    case COMMAND_EXTENTS:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "item");
            return TCL_ERROR;
        }
        proc = ExtentsOp;
        break;
    }
    case COMMAND_GRID:{
        proc = RbcGridOp;
        break;
    }
    case COMMAND_INSIDE:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "winX winY");
            return TCL_ERROR;
        }
        proc = InsideOp;
        break;
    }
    case COMMAND_INVTRANSFORM:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "winX winY");
            return TCL_ERROR;
        }
        proc = InvtransformOp;
        break;
    }
    case COMMAND_LEGEND:{
        proc = RbcLegendOp;
        break;
    }
    case COMMAND_LINE:{
        proc = LineOp;
        break;
    }
    case COMMAND_MARKER:{
        proc = RbcMarkerOp;
        break;
    }
    case COMMAND_PEN:{
        proc = RbcPenOp;
        break;
    }
    case COMMAND_POSTSCRIPT:{
        proc = RbcPostScriptOp;
        break;
    }
    case COMMAND_SNAP:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "?switchse? name");
            return TCL_ERROR;
        }
        proc = SnapOp;
        break;
    }
    case COMMAND_TRANSFORM:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "x y");
            return TCL_ERROR;
        }
        proc = TransformOp;
        break;
    }
    case COMMAND_X2AXIS:{
        proc = X2AxisOp;
        break;
    }
    case COMMAND_XAXIS:{
        proc = XAxisOp;
        break;
    }
    case COMMAND_Y2AXIS:{
        proc = Y2AxisOp;
        break;
    }
    case COMMAND_YAXIS:{
        proc = YAxisOp;
        break;
    }
    default:{
        return TCL_ERROR;
    }
    }
    myArgv = ckalloc(objc * sizeof(char *));
    for(i = 0; i < objc; i++) {
        myArgv[i] = Tcl_GetString(objv[i]);
    }
    Tcl_Preserve(graph);
    result = (*proc) (graph, interp, objc, myArgv);
    Tcl_Release(graph);
    ckfree(myArgv);
    return result;
}

/*
 * GraphMethod_style --
 *
 *  Process -style option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_style(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    const char *chPtr;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    chPtr = Tcl_GetString(value);
    if(strcmp(chPtr, "line") == 0) {
        graph->classUid = rbcLineElementUid;
        graph->chartStyle = "line";
    } else if(strcmp(chPtr, "bar") == 0) {
        graph->classUid = rbcBarElementUid;
        graph->chartStyle = "bar";
    } else if(strcmp(chPtr, "chart") == 0) {
        graph->classUid = rbcStripElementUid;
        graph->chartStyle = "strip";
    } else {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("wrong -style option, should be line,bar or chart"));
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * GraphMethod_barmode --
 *
 *  Process -barmode option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_barmode(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    const char *string;
    int length;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    string = Tcl_GetStringFromObj(value, &length);
    if((string[0] == 'n') && (strncmp(string, "normal", length) == 0)) {
        graph->mode = MODE_INFRONT;
    } else if((string[0] == 'i') && (strncmp(string, "infront", length) == 0)) {
        graph->mode = MODE_INFRONT;
    } else if((string[0] == 's') && (strncmp(string, "stacked", length) == 0)) {
        graph->mode = MODE_STACKED;
    } else if((string[0] == 'a') && (strncmp(string, "aligned", length) == 0)) {
        graph->mode = MODE_ALIGNED;
    } else if((string[0] == 'o') && (strncmp(string, "overlap", length) == 0)) {
        graph->mode = MODE_OVERLAP;
    } else {
        Tcl_AppendResult(interp, "bad mode argument \"", string,
            "\": should be \"infront\", \"stacked\", \"overlap\", or \"aligned\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * GraphMethod_barwidth --
 *
 *  Process -barwidth option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_barwidth(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    double dblVal;
    Tcl_Obj *array;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    if(Tcl_GetDoubleFromObj(interp, value, &dblVal) != TCL_OK) {
        return TCL_ERROR;
    }
    if((array = TkoWidgetOptionVar(object)) == NULL) {
        return TCL_ERROR;
    }
    if(dblVal < 0.1) {
        dblVal = 0.1;
    }
    Tcl_ObjSetVar2(interp, array, objv[objc - 1], Tcl_NewDoubleObj(dblVal),
        TCL_GLOBAL_ONLY);
    graph->barWidth = dblVal;
    return TCL_OK;
}

/*
 * GraphMethod_plotpadx --
 *
 *  Process -plotpadx option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_plotpadx(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Obj *array;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    if((array = TkoWidgetOptionVar(object)) == NULL) {
        return TCL_ERROR;
    }
    if(RbcGraphOptionSetPad(interp, object, value, &graph->padX) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_ObjSetVar2(interp, array, objv[objc - 1],
        Tcl_ObjPrintf("%d %d", graph->padX.side1, graph->padX.side2),
        TCL_GLOBAL_ONLY);
    return TCL_OK;
}

/*
 * GraphMethod_plotpady --
 *
 *  Process -plotpady option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_plotpady(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Obj *array;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    if((array = TkoWidgetOptionVar(object)) == NULL) {
        return TCL_ERROR;
    }
    if(RbcGraphOptionSetPad(interp, object, value, &graph->padY) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_ObjSetVar2(interp, array, objv[objc - 1],
        Tcl_ObjPrintf("%d %d", graph->padY.side1, graph->padY.side2),
        TCL_GLOBAL_ONLY);
    return TCL_OK;
}

/*
 * GraphMethod_shadow --
 *
 * Process -shadow option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_shadow(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Obj *array;
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    if((array = TkoWidgetOptionVar(object)) == NULL) {
        return TCL_ERROR;
    }
    if(RbcGraphOptionSetShadow(interp, object, value,
            &graph->titleTextStyle.shadow) != TCL_OK) {
        return TCL_ERROR;
    }
    if(graph->titleTextStyle.shadow.color != NULL) {
        Tcl_ObjSetVar2(interp, array, objv[objc - 1],
            Tcl_ObjPrintf("%s %d",
                Tk_NameOfColor(graph->titleTextStyle.shadow.color),
                graph->titleTextStyle.shadow.offset), TCL_GLOBAL_ONLY);
    } else {
        Tcl_ObjSetVar2(interp, array, objv[objc - 1], TkoObj.empty,
            TCL_GLOBAL_ONLY);
    }
    return TCL_OK;
}

/*
 * GraphMethod_tile --
 *
 *  Process -tile option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
GraphMethod_tile(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    RbcGraph *graph;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (graph =
            (RbcGraph *) Tcl_ObjectGetMetadata(object, &graphMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }

    return (RbcGraphOptionSetTile(interp, object, value, &graph->tile));
}

/*
 * RbcEventuallyRedrawGraph --
 *
 *      Tells the Tk dispatcher to call the graph display routine at
 *      the next idle point.  This request is made only if the window
 *      is displayed and no other redraw request is pending.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The window is eventually redisplayed.
 */
void
RbcEventuallyRedrawGraph(
    RbcGraph * graph)
{              /* Graph widget record */
    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    if(!(graph->flags & RBC_REDRAW_PENDING)) {
        Tcl_DoWhenIdle(DisplayGraph, graph);
        graph->flags |= RBC_REDRAW_PENDING;
    }
}

/*
 * GraphEventProc --
 *
 *      This procedure is invoked by the Tk dispatcher for various
 *      events on graphs.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      When the window gets deleted, internal structures get
 *      cleaned up.  When it gets exposed, the graph is eventually
 *      redisplayed.
 */
static void
GraphEventProc(
    ClientData clientData,     /* Graph widget record */
    register XEvent * eventPtr)
{              /* Event which triggered call to routine */
    RbcGraph *graph = clientData;
    if(eventPtr->type == DestroyNotify || graph->win == NULL
        || *(graph->win) == NULL)
        return;

    if(eventPtr->type == Expose) {
        if(eventPtr->xexpose.count == 0) {
            graph->flags |= RBC_REDRAW_WORLD;
            RbcEventuallyRedrawGraph(graph);
        }
    } else if((eventPtr->type == FocusIn) || (eventPtr->type == FocusOut)) {
        if(eventPtr->xfocus.detail != NotifyInferior) {
            if(eventPtr->type == FocusIn) {
                graph->flags |= RBC_GRAPH_FOCUS;
            } else {
                graph->flags &= ~RBC_GRAPH_FOCUS;
            }
            graph->flags |= RBC_REDRAW_WORLD;
            RbcEventuallyRedrawGraph(graph);
        }
    } else if(eventPtr->type == ConfigureNotify) {
        graph->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
        RbcEventuallyRedrawGraph(graph);
    }
}

/*
 * TileChangedProc --
 *
 *      Rebuilds the designated GC with the new tile pixmap.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static void
TileChangedProc(
    ClientData clientData,
    RbcTile tile)
{              /* Not used. */
RbcGraph *graph = clientData;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    graph->flags |= RBC_REDRAW_WORLD;
    RbcEventuallyRedrawGraph(graph);
}

/*
 * AdjustAxisPointers --
 *
 *      Sets the axis pointers according to whether the axis is
 *      inverted on not.  The axis sites are also reset.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static void
AdjustAxisPointers(
    RbcGraph * graph)
{              /* Graph widget record */
    if(graph->inverted) {
        graph->margins[RBC_MARGIN_LEFT].axes = graph->axisChain[0];
        graph->margins[RBC_MARGIN_BOTTOM].axes = graph->axisChain[1];
        graph->margins[RBC_MARGIN_RIGHT].axes = graph->axisChain[2];
        graph->margins[RBC_MARGIN_TOP].axes = graph->axisChain[3];
    } else {
        graph->margins[RBC_MARGIN_LEFT].axes = graph->axisChain[1];
        graph->margins[RBC_MARGIN_BOTTOM].axes = graph->axisChain[0];
        graph->margins[RBC_MARGIN_RIGHT].axes = graph->axisChain[3];
        graph->margins[RBC_MARGIN_TOP].axes = graph->axisChain[2];
    }
}

/*
 * PickEntry --
 *
 *      Find the closest point from the set of displayed elements,
 *      searching the display list from back to front.  That way, if
 *      the points from two different elements overlay each other exactly,
 *      the one that's on top (visible) is picked.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static ClientData
PickEntry(
    ClientData clientData,
    int x,
    int y,
    ClientData * contextPtr)
{              /* Not used. */
    RbcGraph *graph = clientData;
    RbcChainLink *linkPtr;
    RbcElement *elemPtr;
    RbcMarker *markerPtr;
    RbcExtents2D exts;

    if(graph->flags & RBC_MAP_ALL) {
        /* Can't pick anything until the next
         * redraw occurs. */
        return NULL;
    }
    RbcGraphExtents(graph, &exts);

    if((x > exts.right) || (x < exts.left) || (y > exts.bottom)
        || (y < exts.top)) {
        /*
         * Sample coordinate is in one of the graph margins.  Can only
         * pick an axis.
         */
        return RbcNearestAxis(graph, x, y);
    }

    /*
     * From top-to-bottom check:
     *  1. markers drawn on top (-under false).
     *  2. elements using its display list back to front.
     *  3. markers drawn under element (-under true).
     */
    markerPtr = (RbcMarker *) RbcNearestMarker(graph, x, y, FALSE);
    if(markerPtr != NULL) {
        /* Found a marker (-under false). */
        return markerPtr;
    }
    {
    RbcClosestSearch search;

        search.along = RBC_SEARCH_BOTH;
        search.halo = graph->halo + 1;
        search.index = -1;
        search.x = x;
        search.y = y;
        search.dist = (double)(search.halo + 1);
        search.mode = RBC_SEARCH_AUTO;

        for(linkPtr = RbcChainLastLink(graph->elements.displayList);
            linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
            elemPtr = RbcChainGetValue(linkPtr);
            if((elemPtr->flags & RBC_MAP_ITEM)
                || (RbcVectorNotifyPending(elemPtr->x.clientId))
                || (RbcVectorNotifyPending(elemPtr->y.clientId))) {
                continue;
            }
            if((!elemPtr->hidden) && (elemPtr->state == RBC_STATE_NORMAL)) {
                (*elemPtr->procsPtr->closestProc) (graph, elemPtr, &search);
            }
        }
        if(search.dist <= (double)search.halo) {
            /* Found an element within the
             * minimum halo distance. */
            return search.elemPtr;
        }
    }
    markerPtr = (RbcMarker *) RbcNearestMarker(graph, x, y, TRUE);
    if(markerPtr != NULL) {
        /* Found a marker (-under true) */
        return markerPtr;
    }
    /* Nothing found. */
    return NULL;
}

/* Widget sub-commands */

/*
 * XAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
XAxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    int margin;

    margin = (graph->inverted) ? RBC_MARGIN_LEFT : RBC_MARGIN_BOTTOM;
    return RbcAxisOp(graph, margin, argc, argv);
}

/*
 * X2AxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
X2AxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    int margin;

    margin = (graph->inverted) ? RBC_MARGIN_RIGHT : RBC_MARGIN_TOP;
    return RbcAxisOp(graph, margin, argc, argv);
}

/*
 * YAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
YAxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    int margin;

    margin = (graph->inverted) ? RBC_MARGIN_BOTTOM : RBC_MARGIN_LEFT;
    return RbcAxisOp(graph, margin, argc, argv);
}

/*
 * Y2AxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
Y2AxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    int margin;

    margin = (graph->inverted) ? RBC_MARGIN_TOP : RBC_MARGIN_RIGHT;
    return RbcAxisOp(graph, margin, argc, argv);
}

/*
 * BarOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
BarOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    return RbcElementOp(graph, interp, argc, argv, rbcBarElementUid);
}

/*
 * LineOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
LineOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    return RbcElementOp(graph, interp, argc, argv, rbcLineElementUid);
}

/*
 * ElementOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
ElementOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    return RbcElementOp(graph, interp, argc, argv, graph->classUid);
}

/*
 * ExtentsOp --
 *
 *      Reports the size of one of several items within the graph.
 *      The following are valid items:
 *
 *        "bottommargin"    Height of the bottom margin
 *        "leftmargin"      Width of the left margin
 *        "legend"          x y w h of the legend
 *        "plotarea"        x y w h of the plotarea
 *        "plotheight"      Height of the plot area
 *        "rightmargin"     Width of the right margin
 *        "topmargin"       Height of the top margin
 *        "plotwidth"       Width of the plot area
 *
 * Results:
 *      Always returns TCL_OK.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
ExtentsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    char c;
    unsigned int length;
    char string[200];

    c = argv[2][0];
    length = strlen(argv[2]);
    if((c == 'p') && (length > 4)
        && (strncmp("plotheight", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(graph->bottom - graph->top + 1));
    } else if((c == 'p') && (length > 4)
        && (strncmp("plotwidth", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp, Tcl_NewIntObj(graph->right - graph->left + 1));
    } else if((c == 'p') && (length > 4)
        && (strncmp("plotarea", argv[2], length) == 0)) {
        sprintf(string, "%d %d %d %d", graph->left, graph->top,
            graph->right - graph->left + 1, graph->bottom - graph->top + 1);
        Tcl_SetObjResult(interp, Tcl_NewStringObj(string, -1));
    } else if((c == 'l') && (length > 2)
        && (strncmp("legend", argv[2], length) == 0)) {
        sprintf(string, "%d %d %d %d", RbcLegendX(graph->legend),
            RbcLegendY(graph->legend), RbcLegendWidth(graph->legend),
            RbcLegendHeight(graph->legend));
        Tcl_SetObjResult(interp, Tcl_NewStringObj(string, -1));
    } else if((c == 'l') && (length > 2)
        && (strncmp("leftmargin", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj(graph->margins[RBC_MARGIN_LEFT].width));
    } else if((c == 'r') && (length > 1)
        && (strncmp("rightmargin", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj(graph->margins[RBC_MARGIN_RIGHT].width));
    } else if((c == 't') && (length > 1)
        && (strncmp("topmargin", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj(graph->margins[RBC_MARGIN_TOP].height));
    } else if((c == 'b') && (length > 1)
        && (strncmp("bottommargin", argv[2], length) == 0)) {
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj(graph->margins[RBC_MARGIN_BOTTOM].height));
    } else {
        Tcl_AppendResult(interp, "bad extent item \"", argv[2],
            "\": should be plotheight, plotwidth, leftmargin, rightmargin, \
topmargin, bottommargin, plotarea, or legend", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * InsideOp --
 *
 *      Returns true of false whether the given point is inside
 *      the plotting area (defined by left,bottom right, top).
 *
 * Results:
 *      Always returns TCL_OK.  interp->result will contain
 *      the boolean string representation.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
InsideOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    int x, y;
    RbcExtents2D exts;
    int result;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(Tk_GetPixels(interp, *(graph->win), argv[2], &x) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tk_GetPixels(interp, *(graph->win), argv[3], &y) != TCL_OK) {
        return TCL_ERROR;
    }
    RbcGraphExtents(graph, &exts);
    result = RbcPointInRegion(&exts, x, y);
    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(result));
    return TCL_OK;
}

/*
 * InvtransformOp --
 *
 *      This procedure returns a list of the graph coordinate
 *      values corresponding with the given window X and Y
 *      coordinate positions.
 *
 * Results:
 *      Returns a standard Tcl result.  If an error occurred while
 *      parsing the window positions, TCL_ERROR is returned, and
 *      interp->result will contain the error message.  Otherwise
 *      interp->result will contain a Tcl list of the x and y
 *      coordinates.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
InvtransformOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    double x, y;
    RbcPoint2D point;
    RbcAxis2D axes;
    char stringDouble[TCL_DOUBLE_SPACE];

    if(Tcl_ExprDouble(interp, argv[2], &x) != TCL_OK ||
        Tcl_ExprDouble(interp, argv[3], &y) != TCL_OK) {
        return TCL_ERROR;
    }
    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    /* Perform the reverse transformation, converting from window
     * coordinates to graph data coordinates.  Note that the point is
     * always mapped to the bottom and left axes (which may not be
     * what the user wants).  */

    /*  Pick the first pair of axes */
    axes.x = RbcGetFirstAxis(graph->axisChain[0]);
    axes.y = RbcGetFirstAxis(graph->axisChain[1]);
    point = RbcInvMap2D(graph, x, y, &axes);

    Tcl_PrintDouble(NULL, point.x, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    Tcl_PrintDouble(NULL, point.y, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    return TCL_OK;
}

/*
 * TransformOp --
 *
 *      This procedure returns a list of the window coordinates
 *      corresponding with the given graph x and y coordinates.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the list of the graph coordinates. If an error occurred
 *      while parsing the window positions, TCL_ERROR is returned,
 *      then interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
TransformOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    double x, y;
    RbcPoint2D point;
    RbcAxis2D axes;

    if((Tcl_ExprDouble(interp, argv[2], &x) != TCL_OK) ||
        (Tcl_ExprDouble(interp, argv[3], &y) != TCL_OK)) {
        return TCL_ERROR;
    }
    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    /*
     * Perform the transformation from window to graph coordinates.
     * Note that the points are always mapped onto the bottom and left
     * axes (which may not be the what the user wants).
     */
    axes.x = RbcGetFirstAxis(graph->axisChain[0]);
    axes.y = RbcGetFirstAxis(graph->axisChain[1]);

    point = RbcMap2D(graph, x, y, &axes);
    Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
        "%d %d", ROUND(point.x), ROUND(point.y));
    return TCL_OK;
}

/*
 * StringToFormat --
 *
 *      Convert a string represent a node number into its integer
 *      value.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
StringToFormat(
    ClientData clientData,     /* Contains a pointer to the tabset containing
                                * this image. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    char *switchName,          /* Not used. */
    char *string,              /* String representation */
    char *record,              /* Structure record */
    int offset)
{              /* Offset to field in structure */
    int *formatPtr = (int *)(record + offset);
    char c;

    c = string[0];
    if((c == 'p') && (strcmp(string, "photo") == 0)) {
        *formatPtr = FORMAT_PHOTO;
#ifdef _WIN32
    } else if((c == 'e') && (strcmp(string, "emf") == 0)) {
        *formatPtr = FORMAT_EMF;
    } else if((c == 'w') && (strcmp(string, "wmf") == 0)) {
        *formatPtr = FORMAT_WMF;
#endif /* _WIN32 */
    } else {
#ifdef _WIN32
        Tcl_AppendResult(interp, "bad format \"", string,
            "\": should be photo, emf, or wmf.", (char *)NULL);
#else
        Tcl_AppendResult(interp, "bad format \"", string,
            "\": should be photo.", (char *)NULL);
#endif /* _WIN32 */
        return TCL_ERROR;
    }
    return TCL_OK;
}

#ifdef _WIN32

/*
 * InitMetaFileHeader --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
InitMetaFileHeader(
    Tk_Window tkwin,
    int width,
    int height,
    APMHEADER * mfhPtr)
{
    unsigned int *p;
    unsigned int sum;
    Screen *screen;
#define MM_INCH		25.4
    double dpiX, dpiY;

    mfhPtr->key = 0x9ac6cdd7L;
    mfhPtr->hmf = 0;
    mfhPtr->inch = 1440;

    screen = Tk_Screen(tkwin);
    dpiX = (WidthOfScreen(screen) * MM_INCH) / WidthMMOfScreen(screen);
    dpiY = (HeightOfScreen(screen) * MM_INCH) / HeightMMOfScreen(screen);

    mfhPtr->bbox.Left = mfhPtr->bbox.Top = 0;
    mfhPtr->bbox.Bottom = (SHORT) ((width * 1440) / dpiX);
    mfhPtr->bbox.Right = (SHORT) ((height * 1440) / dpiY);
    mfhPtr->reserved = 0;
    sum = 0;
    for(p = (unsigned int *)mfhPtr;
        p < (unsigned int *)&(mfhPtr->checksum); p++) {
        sum ^= *p;
    }
    mfhPtr->checksum = sum;
    return TCL_OK;
}

/*
 * CreateAPMetaFile --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
CreateAPMetaFile(
    Tcl_Interp * interp,
    HANDLE hMetaFile,
    HDC hDC,
    APMHEADER * mfhPtr,
    char *fileName)
{
    HANDLE hFile;
    HANDLE hMem;
    LPVOID buffer;
    int result;
    DWORD count, nBytes;

    result = TCL_ERROR;
    hMem = NULL;
    hFile = CreateFile((LPCWSTR) fileName,      /* File path */
        GENERIC_WRITE,  /* Access mode */
        0,     /* No sharing. */
        NULL,  /* Security attributes */
        CREATE_ALWAYS,  /* Overwrite any existing file */
        FILE_ATTRIBUTE_NORMAL, NULL);   /* No template file */
    if(hFile == INVALID_HANDLE_VALUE) {
        Tcl_AppendResult(interp, "can't create metafile \"", fileName,
            "\":", RbcLastError(), (char *)NULL);
        return TCL_ERROR;
    }
    if((!WriteFile(hFile, (LPVOID) mfhPtr, sizeof(APMHEADER), &count,
                NULL)) || (count != sizeof(APMHEADER))) {
        Tcl_AppendResult(interp, "can't create metafile header to \"",
            fileName, "\":", RbcLastError(), (char *)NULL);
        goto error;
    }
    nBytes = GetWinMetaFileBits(hMetaFile, 0, NULL, MM_ANISOTROPIC, hDC);
    hMem = GlobalAlloc(GHND, nBytes);
    if(hMem == NULL) {
        Tcl_AppendResult(interp, "can't create allocate global memory:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    buffer = (LPVOID) GlobalLock(hMem);
    if(!GetWinMetaFileBits(hMetaFile, nBytes, buffer, MM_ANISOTROPIC, hDC)) {
        Tcl_AppendResult(interp, "can't get metafile bits:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    if((!WriteFile(hFile, buffer, nBytes, &count, NULL)) || (count != nBytes)) {
        Tcl_AppendResult(interp, "can't write metafile bits:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    result = TCL_OK;
  error:
    CloseHandle(hFile);
    if(hMem != NULL) {
        GlobalUnlock(hMem);
        GlobalFree(hMem);
    }
    return result;
}

#endif /*_WIN32*/

/*
 * SnapOp --
 *
 *      Snaps a picture of the graph and stores it in the specified image
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the list of the graph coordinates. If an error occurred
 *      while parsing the window positions, TCL_ERROR is returned,
 *      then interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static int
SnapOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    int result;
    Pixmap drawable;
    int noBackingStore = 0;
    register int i;
    SnapData data;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    /* .g snap ?switches? name */
    data.height = Tk_Height(*(graph->win));
    data.width = Tk_Width(*(graph->win));
    data.format = FORMAT_PHOTO;
    /* Process switches  */
    i = RbcProcessSwitches(interp, snapSwitches, argc - 2, argv + 2,
        (char *)&data, RBC_SWITCH_OBJV_PARTIAL);
    if(i < 0) {
        return TCL_ERROR;
    }
    i += 2;
    if(i >= argc) {
        Tcl_AppendResult(interp, "missing name argument: should be \"",
            argv[0], "snap ?switches? name\"", (char *)NULL);
        return TCL_ERROR;
    }
    data.name = (char *)argv[i];
    if(data.width < 2) {
        data.width = 400;
    }
    if(data.height < 2) {
        data.height = 400;
    }
    /* Always re-compute the layout of the graph before snapping the photo. */
    graph->width = data.width;
    graph->height = data.height;
    RbcLayoutGraph(graph);

    drawable = Tk_WindowId(*(graph->win));
    if(data.format == FORMAT_PHOTO) {
        drawable = Tk_GetPixmap(graph->display, drawable, graph->width,
            graph->height, Tk_Depth(*(graph->win)));
#ifdef _WIN32
        assert(drawable != None);
#endif
        graph->flags |= RBC_RESET_WORLD;
        RbcDrawGraph(graph, drawable, noBackingStore);
        result = RbcSnapPhoto(interp, *(graph->win), drawable, 0, 0,
            data.width, data.height, data.width, data.height, data.name, 1.0);
        Tk_FreePixmap(graph->display, drawable);
#ifdef _WIN32
    } else if((data.format == FORMAT_WMF) || (data.format == FORMAT_EMF)) {
    TkWinDC drawableDC;
    TkWinDCState state;
    HDC hRefDC, hDC;
    HENHMETAFILE hMetaFile;
    Tcl_DString dString;
    char *title;

        hRefDC = TkWinGetDrawableDC(graph->display, drawable, &state);

        Tcl_DStringInit(&dString);
        Tcl_DStringAppend(&dString, "::graph ", -1);
        Tcl_DStringAppend(&dString, "\0", -1);
        Tcl_DStringAppend(&dString, Tk_PathName(*(graph->win)), -1);
        Tcl_DStringAppend(&dString, "\0", -1);
        title = Tcl_DStringValue(&dString);
        hDC = CreateEnhMetaFile(hRefDC, NULL, NULL, (LPCWSTR) title);
        Tcl_DStringFree(&dString);

        if(hDC == NULL) {
            Tcl_AppendResult(interp, "can't create metafile: ",
                RbcLastError(), (char *)NULL);
            return TCL_ERROR;
        }

        drawableDC.hdc = hDC;
        drawableDC.type = TWD_WINDC;

        RbcLayoutGraph(graph);
        graph->flags |= RBC_RESET_WORLD;
        RbcDrawGraph(graph, (Drawable) & drawableDC, FALSE);

        hMetaFile = CloseEnhMetaFile(hDC);
        if(strcmp(data.name, "CLIPBOARD") == 0) {
    HWND hWnd;

            hWnd = Tk_GetHWND(drawable);
            OpenClipboard(hWnd);
            EmptyClipboard();
            SetClipboardData(CF_ENHMETAFILE, hMetaFile);
            CloseClipboard();
            result = TCL_OK;
        } else {
            result = TCL_ERROR;
            if(data.format == FORMAT_WMF) {
    APMHEADER mfh;

                assert(sizeof(mfh) == 22);
                InitMetaFileHeader(*(graph->win), data.width, data.height,
                    &mfh);
                result = CreateAPMetaFile(interp, hMetaFile, hRefDC, &mfh,
                    data.name);
            } else {
    HENHMETAFILE hMetaFile2;

                hMetaFile2 = CopyEnhMetaFile(hMetaFile, (LPCWSTR) data.name);
                if(hMetaFile2 != NULL) {
                    result = TCL_OK;
                    DeleteEnhMetaFile(hMetaFile2);
                }
            }
            DeleteEnhMetaFile(hMetaFile);
        }
        TkWinReleaseDrawableDC(drawable, hRefDC, &state);

#endif /*_WIN32*/
    } else {
        Tcl_AppendResult(interp, "bad snapshot format", (char *)NULL);
        return TCL_ERROR;
    }
    graph->flags = RBC_MAP_WORLD;
    RbcEventuallyRedrawGraph(graph);
    return result;
}

static RbcOpSpec graphOps[] = {
    {"axis", 1, (RbcOp) RbcVirtualAxisOp, 2, 0, "oper ?args?",},
    {"bar", 2, (RbcOp) BarOp, 2, 0, "oper ?args?",},
    {"crosshairs", 2, (RbcOp) RbcCrosshairsOp, 2, 0, "oper ?args?",},
    {"element", 2, (RbcOp) ElementOp, 2, 0, "oper ?args?",},
    {"extents", 2, (RbcOp) ExtentsOp, 3, 3, "item",},
    {"grid", 1, (RbcOp) RbcGridOp, 2, 0, "oper ?args?",},
    {"inside", 3, (RbcOp) InsideOp, 4, 4, "winX winY",},
    {"invtransform", 3, (RbcOp) InvtransformOp, 4, 4, "winX winY",},
    {"legend", 2, (RbcOp) RbcLegendOp, 2, 0, "oper ?args?",},
    {"line", 2, (RbcOp) LineOp, 2, 0, "oper ?args?",},
    {"marker", 2, (RbcOp) RbcMarkerOp, 2, 0, "oper ?args?",},
    {"pen", 2, (RbcOp) RbcPenOp, 2, 0, "oper ?args?",},
    {"postscript", 2, (RbcOp) RbcPostScriptOp, 2, 0, "oper ?args?",},
    {"snap", 1, (RbcOp) SnapOp, 3, 0, "?switches? name",},
    {"transform", 1, (RbcOp) TransformOp, 4, 4, "x y",},
    {"x2axis", 2, (RbcOp) X2AxisOp, 2, 0, "oper ?args?",},
    {"xaxis", 2, (RbcOp) XAxisOp, 2, 0, "oper ?args?",},
    {"y2axis", 2, (RbcOp) Y2AxisOp, 2, 0, "oper ?args?",},
    {"yaxis", 2, (RbcOp) YAxisOp, 2, 0, "oper ?args?",},
};

static int nGraphOps = sizeof(graphOps) / sizeof(RbcOpSpec);

/*
 * RbcGraphInstCmdProc --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
int
RbcGraphInstCmdProc(
    ClientData clientData,
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcOp proc;
    int result;
    RbcGraph *graph = clientData;

    proc = RbcGetOp(interp, nGraphOps, graphOps, RBC_OP_ARG1, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    Tcl_Preserve(graph);
    result = (*proc) (graph, interp, argc, argv);
    Tcl_Release(graph);
    return result;
}

/*
 * DrawMargins --
 *
 *      Draws the exterior region of the graph (axes, ticks, titles, etc)
 *      onto a pixmap. The interior region is defined by the given
 *      rectangle structure.
 *
 *      ---------------------------------
 *          |                               |
 *          |           rectArr[0]          |
 *          |                               |
 *      ---------------------------------
 *          |     |top           right|     |
 *          |     |                   |     |
 *          |     |                   |     |
 *          | [1] |                   | [2] |
 *          |     |                   |     |
 *          |     |                   |     |
 *          |     |                   |     |
 *          |     |                   |     |
 *          |     |                   |     |
 *          |     |left         bottom|     |
 *      ---------------------------------
 *          |                               |
 *          |          rectArr[3]           |
 *          |                               |
 *      ---------------------------------
 *
 *          X coordinate axis
 *          Y coordinate axis
 *          legend
 *          interior border
 *          exterior border
 *          titles (X and Y axis, graph)
 *
 * Returns:
 *      None.
 *
 * Side Effects:
 *      Exterior of graph is displayed in its window.
 */
static void
DrawMargins(
    RbcGraph * graph,
    Drawable drawable /* Pixmap or window to draw into */)
{             
    XRectangle rects[4];

    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    /*
     * Draw the four outer rectangles which encompass the plotting
     * surface. This clears the surrounding area and clips the plot.
     */
    rects[0].x = rects[0].y = rects[3].x = rects[1].x = 0;
    rects[0].width = rects[3].width = (short int)graph->width;
    rects[0].height = (short int)graph->top;
    rects[3].y = graph->bottom;
    rects[3].height = graph->height - graph->bottom;
    rects[2].y = rects[1].y = graph->top;
    rects[1].width = graph->left;
    rects[2].height = rects[1].height = graph->bottom - graph->top;
    rects[2].x = graph->right;
    rects[2].width = graph->width - graph->right;

    if(graph->tile != NULL) {
        RbcSetTileOrigin(*(graph->win), graph->tile, 0, 0);
        RbcTileRectangles(*(graph->win), drawable, graph->tile, rects, 4);
    } else {
        XFillRectangles(graph->display, drawable, graph->fillGC, rects, 4);
    }

    /* Draw 3D border around the plotting area */

    if(graph->plotBorderWidth > 0) {
        int x, y, width, height;

        x = graph->left - graph->plotBorderWidth;
        y = graph->top - graph->plotBorderWidth;
        width = (graph->right - graph->left) + (2 * graph->plotBorderWidth);
        height = (graph->bottom - graph->top) + (2 * graph->plotBorderWidth);
        Tk_Draw3DRectangle(*(graph->win), drawable, graph->border, x, y,
            width, height, graph->plotBorderWidth, graph->plotRelief);
    }
    if(RbcLegendSite(graph->legend) & RBC_LEGEND_IN_MARGIN) {
        /* Legend is drawn on one of the graph margins */
        RbcDrawLegend(graph->legend, drawable);
    }
    if(graph->title != NULL) {
        RbcDrawText(*(graph->win), drawable, graph->title,
            &graph->titleTextStyle, graph->titleX, graph->titleY);
    }
    RbcDrawAxes(graph, drawable);

}

/*
 * DrawPlotRegion --
 *
 *      Draws the contents of the plotting area.  This consists of
 *      the elements, markers (draw under elements), axis limits,
 *      grid lines, and possibly the legend.  Typically, the output
 *      will be cached into a backing store pixmap, so that redraws
 *      can occur quickly.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static void
DrawPlotRegion(
    RbcGraph * graph,
    Drawable drawable)
{              /* Pixmap or window to draw into */
    /* Clear the background of the plotting area. */
    XFillRectangle(graph->display, drawable, graph->plotFillGC,
        graph->left, graph->top, graph->right - graph->left + 1,
        graph->bottom - graph->top + 1);

    /* Draw the elements, markers, legend, and axis limits. */

    if(!graph->gridPtr->hidden) {
        RbcDrawGrid(graph, drawable);
    }
    RbcDrawMarkers(graph, drawable, RBC_MARKER_UNDER);
    if((RbcLegendSite(graph->legend) & RBC_LEGEND_IN_PLOT) &&
        (!RbcLegendIsRaised(graph->legend))) {
        RbcDrawLegend(graph->legend, drawable);
    }
    RbcDrawAxisLimits(graph, drawable);
    RbcDrawElements(graph, drawable);
}

/*
 * RbcLayoutGraph --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
void
RbcLayoutGraph(
    RbcGraph * graph)
{
    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    if(graph->flags & RBC_LAYOUT_NEEDED) {
        RbcLayoutMargins(graph);
        graph->flags &= ~RBC_LAYOUT_NEEDED;
    }
    /* Compute coordinate transformations for graph components */
    if((graph->vRange > 1) && (graph->hRange > 1)) {
        if(graph->flags & RBC_MAP_WORLD) {
            RbcMapAxes(graph);
        }
        RbcMapElements(graph);
        RbcMapMarkers(graph);
        RbcMapGrid(graph);
        graph->flags &= ~(RBC_MAP_ALL);
    }
}

/*
 * RbcDrawGraph --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
void
RbcDrawGraph(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    int backingStore)
{              /* If non-zero, use backing store for
                * plotting area. */
    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    if(backingStore) {
        /*
         * Create another pixmap to save elements if one doesn't
         * already exist or the size of the window has changed.
         */
        if((graph->backPixmap == None) ||
            (graph->backWidth != graph->width) ||
            (graph->backHeight != graph->height)) {

            if(graph->backPixmap != None) {
                Tk_FreePixmap(graph->display, graph->backPixmap);
            }
            graph->backPixmap = Tk_GetPixmap(graph->display,
                Tk_WindowId(*(graph->win)), graph->width,
                graph->height, Tk_Depth(*(graph->win)));
            graph->backWidth = graph->width;
            graph->backHeight = graph->height;
            graph->flags |= RBC_REDRAW_BACKING_STORE;
        }
        if(graph->flags & RBC_REDRAW_BACKING_STORE) {
            /* The backing store is new or out-of-date. */
            DrawPlotRegion(graph, graph->backPixmap);
            graph->flags &= ~RBC_REDRAW_BACKING_STORE;
        }

        /* Copy the pixmap to the one used for drawing the entire graph. */

        XCopyArea(graph->display, graph->backPixmap, drawable,
            graph->drawGC, graph->left, graph->top,
            (graph->right - graph->left + 1),
            (graph->bottom - graph->top + 1), graph->left, graph->top);
    } else {
        DrawPlotRegion(graph, drawable);
    }

    /* Draw markers above elements */
    RbcDrawMarkers(graph, drawable, RBC_MARKER_ABOVE);
    RbcDrawActiveElements(graph, drawable);

    if(graph->flags & RBC_DRAW_MARGINS) {
        DrawMargins(graph, drawable);
    }
    if((RbcLegendSite(graph->legend) & RBC_LEGEND_IN_PLOT) &&
        (RbcLegendIsRaised(graph->legend))) {
        RbcDrawLegend(graph->legend, drawable);
    }
    /* Draw 3D border just inside of the focus highlight ring. */
    if((graph->borderWidth > 0) && (graph->relief != TK_RELIEF_FLAT)) {
        Tk_Draw3DRectangle(*(graph->win), drawable, graph->border,
            graph->highlightWidth, graph->highlightWidth,
            graph->width - 2 * graph->highlightWidth,
            graph->height - 2 * graph->highlightWidth,
            graph->borderWidth, graph->relief);
    }
    /* Draw focus highlight ring. */
    if((graph->highlightWidth > 0) && (graph->flags & RBC_GRAPH_FOCUS)) {
    GC  gc;

        gc = Tk_GCForColor(graph->highlightColor, drawable);
        Tk_DrawFocusHighlight(*(graph->win), gc, graph->highlightWidth,
            drawable);
    }
}

/*
 * UpdateMarginTraces --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
static void
UpdateMarginTraces(
    RbcGraph * graph)
{
    RbcMargin *marginPtr;
    int size;
    register int i;

    for(i = 0; i < 4; i++) {
        marginPtr = graph->margins + i;
        if(marginPtr->varName != NULL) {        /* Trigger variable traces */
            if((marginPtr->site == RBC_MARGIN_LEFT) ||
                (marginPtr->site == RBC_MARGIN_RIGHT)) {
                size = marginPtr->width;
            } else {
                size = marginPtr->height;
            }
            Tcl_SetVar2Ex(graph->interp, marginPtr->varName, NULL,
                Tcl_NewIntObj(size), TCL_GLOBAL_ONLY);
        }
    }
}

/*
 * DisplayGraph --
 *
 *      This procedure is invoked to display a graph widget.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Commands are output to X to display the graph in its
 *      current mode.
 */
static void
DisplayGraph(
    ClientData clientData)
{
    RbcGraph *graph = clientData;
    Pixmap drawable;
    graph->flags &= ~RBC_REDRAW_PENDING;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if(RbcGraphUpdateNeeded(graph)) {
        /*
         * One of the elements of the graph has a vector notification
         * pending.  This means that the vector will eventually notify
         * the graph that its data has changed.  Since the graph uses
         * the actual vector (not a copy) we need to keep in-sync.
         * Therefore don't draw right now but wait until we've been
         * notified before redrawing.
         */
        return;
    }
    graph->width = Tk_Width(*(graph->win));
    graph->height = Tk_Height(*(graph->win));
    RbcLayoutGraph(graph);
    RbcUpdateCrosshairs(graph);
    if(!Tk_IsMapped(*(graph->win))) {
        /* The graph's window isn't displayed, so don't bother
         * drawing anything.  By getting this far, we've at least
         * computed the coordinates of the graph's new layout.  */
        return;
    }

    /* Disable crosshairs before redisplaying to the screen */
    RbcDisableCrosshairs(graph);
    /*
     * Create a pixmap the size of the window for double buffering.
     */
    if(graph->doubleBuffer) {
        drawable = Tk_GetPixmap(graph->display, Tk_WindowId(*(graph->win)),
            graph->width, graph->height, Tk_Depth(*(graph->win)));
    } else {
        drawable = Tk_WindowId(*(graph->win));
    }
#ifdef _WIN32
    assert(drawable != None);
#endif
    RbcDrawGraph(graph, drawable, graph->backingStore && graph->doubleBuffer);
    if(graph->flags & RBC_DRAW_MARGINS) {
        XCopyArea(graph->display, drawable, Tk_WindowId(*(graph->win)),
            graph->drawGC, 0, 0, graph->width, graph->height, 0, 0);
    } else {
        XCopyArea(graph->display, drawable, Tk_WindowId(*(graph->win)),
            graph->drawGC, graph->left, graph->top,
            (graph->right - graph->left + 1),
            (graph->bottom - graph->top + 1), graph->left, graph->top);
    }
    if(graph->doubleBuffer) {
        Tk_FreePixmap(graph->display, drawable);
    }
    RbcEnableCrosshairs(graph);
    graph->flags &= ~RBC_RESET_WORLD;
    UpdateMarginTraces(graph);
}

/*
 * RbcGetGraphFromWindowData --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
RbcGraph *
RbcGetGraphFromWindowData(
    Tk_Window tkwin)
{
RbcGraph *graph;

    while(tkwin != NULL) {
        graph = (RbcGraph *) RbcGetWindowInstanceData(tkwin);
        if(graph != NULL) {
            return graph;
        }
        tkwin = Tk_Parent(tkwin);
    }
    return NULL;
}

/*
 * RbcGraphType --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 */
int
RbcGraphType(
    RbcGraph * graph)
{
    if(graph->classUid == rbcLineElementUid) {
        return RBC_GRAPH;
    } else if(graph->classUid == rbcBarElementUid) {
        return RBC_BARCHART;
    } else if(graph->classUid == rbcStripElementUid) {
        return RBC_STRIPCHART;
    }
    return 0;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraph.h.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoGraph.h --
 *
 *      This file constructs the basic functionality of the
 *      rbc commands.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#ifndef _TKOGRAPH_H
#define _TKOGRAPH_H

#include "tkoWidget.h"

/*
 * For C++ compilers, use extern "C"
 */
#ifdef __cplusplus
extern "C" {
#endif

/*
 * Used standard values
 */
#define RBC_NORMAL_BG_MONO	    "white"
#define RBC_NORMAL_FG_MONO	    "black"
#define RBC_ACTIVE_BG_MONO	    "black"
#define RBC_ACTIVE_FG_MONO	    "white"
#define RBC_SELECT_BG_MONO	    "black"
#define RBC_SELECT_FG_MONO      "black"
#define RBC_SELECT_BORDERWIDTH  "2"
#define RBC_BORDERWIDTH 	    "2"
#define RBC_FONT                "TkDefaultFont 10"
#define RBC_FONT_HUGE           "TkDefaultFontArial 16"
#define RBC_FONT_LARGE          "TkDefaultFontArial 12"
#define RBC_FONT_SMALL          "TkDefaultFontArial 8"
#define RBC_NORMAL_BACKGROUND   "gray85"
#define RBC_NORMAL_FOREGROUND   "black"
#define RBC_ACTIVE_BACKGROUND   "gray64"
#define RBC_ACTIVE_FOREGROUND   "black"
#define RBC_SELECT_BACKGROUND   "lightblue1"
#define RBC_SELECT_FOREGROUND   "black"
#define RBC_INDICATOR_COLOR	    "maroon"

#define RBC_OP_LINEAR_SEARCH	1
#define RBC_OP_BINARY_SEARCH	0

#define RBC_STATIC_STRING_SPACE 150

#define RBC_NS_SEARCH_NONE		(0)
#define RBC_NS_SEARCH_CURRENT	(1<<0)
#define RBC_NS_SEARCH_GLOBAL	(1<<1)
#define RBC_NS_SEARCH_BOTH		(RBC_NS_SEARCH_GLOBAL | RBC_NS_SEARCH_CURRENT)

/* Recognize "min", "max", and "++end" as valid indices */
#define RBC_INDEX_SPECIAL	(1<<0)

/* Also recognize a range of indices separated by a colon */
#define RBC_INDEX_COLON	(1<<1)

/* Verify that the specified index or range of indices are within limits */
#define RBC_INDEX_CHECK	(1<<2)
#define RBC_INDEX_ALL_FLAGS    (RBC_INDEX_SPECIAL | RBC_INDEX_COLON | RBC_INDEX_CHECK)
#define RBC_SPECIAL_INDEX		-2

/* The data of the vector has changed.  Update the min and max limits when they are needed */
#define RBC_UPDATE_RANGE		(1<<9)

#define RBC_COLOR_NONE		    (XColor *)0
#define RBC_COLOR_DEFAULT		(XColor *)1
#define RBC_COLOR_ALLOW_DEFAULTS	1

#define RBC_STATE_NORMAL	0
#define RBC_STATE_ACTIVE	(1<<0)
#define RBC_STATE_DISABLED	(1<<1)
#define RBC_STATE_EMPHASIS	(1<<2)

#define RBC_ROTATE_0	0
#define RBC_ROTATE_90	1
#define RBC_ROTATE_180	2
#define RBC_ROTATE_270	3

#define RBC_SEARCH_X	0
#define RBC_SEARCH_Y	1
#define RBC_SEARCH_BOTH	2

#define RBC_SHOW_NONE	0
#define RBC_SHOW_X		1
#define RBC_SHOW_Y		2
#define RBC_SHOW_BOTH	3

#define RBC_SEARCH_POINTS	0       /* Search for closest data point. */
#define RBC_SEARCH_TRACES	1       /* Search for closest point on trace.
                                         * Interpolate the connecting line segments
                                         * if necessary. */
#define RBC_SEARCH_AUTO	2      /* Automatically determine whether to search
                                * for data points or traces.  Look for
                                * traces if the linewidth is > 0 and if
                                * there is more than one data point. */

#define	RBC_ELEM_ACTIVE	(1<<8) /* Non-zero indicates that the element
                                * should be drawn in its active
                                * foreground and background
                                * colors. */
#define	RBC_ACTIVE_PENDING	(1<<7)

#define	RBC_LABEL_ACTIVE 	(1<<9)  /* Non-zero indicates that the
                                         * element's entry in the legend
                                         * should be drawn in its active
                                         * foreground and background
                                         * colors. */
#define RBC_SCALE_SYMBOL	(1<<10)

#define RBC_SWITCH_ARGV_ONLY		(1<<0)
#define RBC_SWITCH_OBJV_ONLY		(1<<0)
#define RBC_SWITCH_ARGV_PARTIAL		(1<<1)
#define RBC_SWITCH_OBJV_PARTIAL		(1<<1)

/*
 * Possible flag values for RbcSwitchSpec structures.  Any bits at
 * or above RBC_SWITCH_USER_BIT may be used by clients for selecting
 * certain entries.
 */
#define RBC_SWITCH_NULL_OK		(1<<0)
#define RBC_SWITCH_DONT_SET_DEFAULT	(1<<3)
#define RBC_SWITCH_SPECIFIED		(1<<4)
#define RBC_SWITCH_USER_BIT		(1<<8)

/*
 * Bit flags definitions:
 *
 * 	All kinds of state information kept here.  All these
 *	things happen when the window is available to draw into
 *	(DisplayGraph). Need the window width and height before
 *	we can calculate graph layout (i.e. the screen coordinates
 *	of the axes, elements, titles, etc). But we want to do this
 *	only when we have to, not every time the graph is redrawn.
 *
 *	Same goes for maintaining a pixmap to double buffer graph
 *	elements.  Need to mark when the pixmap needs to updated.
 *
 *
 *	MAP_ITEM		Indicates that the element/marker/axis
 *				configuration has changed such that
 *				its layout of the item (i.e. its
 *				position in the graph window) needs
 *				to be recalculated.
 *
 *	MAP_ALL			Indicates that the layout of the axes and
 *				all elements and markers and the graph need
 *				to be recalculated. Otherwise, the layout
 *				of only those markers and elements that
 *				have changed will be reset.
 *
 *	GET_AXIS_GEOMETRY	Indicates that the size of the axes needs
 *				to be recalculated.
 *
 *	RESET_AXES		Flag to call to RbcResetAxes routine.
 *				This routine recalculates the scale offset
 *				(used for mapping coordinates) of each axis.
 *				If an axis limit has changed, then it sets
 *				flags to re-layout and redraw the entire
 *				graph.  This needs to happend before the axis
 *				can compute transformations between graph and
 *				screen coordinates.
 *
 *	LAYOUT_NEEDED
 *
 *	REDRAW_BACKING_STORE	If set, redraw all elements into the pixmap
 *				used for buffering elements.
 *
 *	REDRAW_PENDING		Non-zero means a DoWhenIdle handler has
 *				already been queued to redraw this window.
 *
 *	DRAW_LEGEND		Non-zero means redraw the legend. If this is
 *				the only DRAW_* flag, the legend display
 *				routine is called instead of the graph
 *				display routine.
 *
 *	DRAW_MARGINS		Indicates that the margins bordering
 *				the plotting area need to be redrawn.
 *				The possible reasons are:
 *
 *				1) an axis configuration changed
 *				2) an axis limit changed
 *				3) titles have changed
 *				4) window was resized.
 *
 *	GRAPH_FOCUS
 */
#define	RBC_MAP_ITEM		(1<<0)  /* 0x0001 */
#define	RBC_MAP_ALL			(1<<1)  /* 0x0002 */
#define	RBC_GET_AXIS_GEOMETRY	(1<<2)  /* 0x0004 */
#define RBC_RESET_AXES		(1<<3)  /* 0x0008 */
#define RBC_LAYOUT_NEEDED		(1<<4)  /* 0x0010 */

#define RBC_REDRAW_PENDING		(1<<8)  /* 0x0100 */
#define RBC_DRAW_LEGEND		(1<<9)  /* 0x0200 */
#define RBC_DRAW_MARGINS		(1<<10) /* 0x0400 */
#define	RBC_REDRAW_BACKING_STORE	(1<<11) /* 0x0800 */

#define RBC_GRAPH_FOCUS		(1<<12) /* 0x1000 */
#define RBC_DATA_CHANGED		(1<<13) /* 0x2000 */

#define RBC_GRAPH_DELETED   (1<<15)     /* 0x8000 */

#define	RBC_MAP_WORLD		(RBC_MAP_ALL|RBC_RESET_AXES|RBC_GET_AXIS_GEOMETRY)
#define RBC_REDRAW_WORLD	(RBC_DRAW_MARGINS | RBC_DRAW_LEGEND)
#define RBC_RESET_WORLD		(RBC_REDRAW_WORLD | RBC_MAP_WORLD)

/* Legend */
#define RBC_LEGEND_RIGHT	(1<<0)  /* Right margin */
#define RBC_LEGEND_LEFT	(1<<1) /* Left margin */
#define RBC_LEGEND_BOTTOM	(1<<2)  /* Bottom margin */
#define RBC_LEGEND_TOP	(1<<3) /* Top margin, below the graph title. */
#define RBC_LEGEND_PLOT	(1<<4) /* Plot area */
#define RBC_LEGEND_XY	(1<<5) /* Screen coordinates in the plotting
                                * area. */
#define RBC_LEGEND_WINDOW	(1<<6)  /* External window. */
#define RBC_LEGEND_IN_MARGIN \
	(RBC_LEGEND_RIGHT | RBC_LEGEND_LEFT | RBC_LEGEND_BOTTOM | RBC_LEGEND_TOP)
#define RBC_LEGEND_IN_PLOT  (RBC_LEGEND_PLOT | RBC_LEGEND_XY)

#define RBC_MARKER_UNDER	1       /* Draw markers designated to lie underneath
                                         * elements, grids, legend, etc. */
#define RBC_MARKER_ABOVE	0       /* Draw markers designated to rest above
                                         * elements, grids, legend, etc. */

/*
 * Mask values used to selectively enable GRAPH or BARCHART entries in
 * the various configuration specs.
 */
#define RBC_GRAPH		(TK_CONFIG_USER_BIT << 1)
#define RBC_STRIPCHART	(TK_CONFIG_USER_BIT << 2)
#define RBC_BARCHART	(TK_CONFIG_USER_BIT << 3)
#define RBC_LINE_GRAPHS	(RBC_GRAPH | RBC_STRIPCHART)
#define RBC_ALL_GRAPHS	(RBC_GRAPH | RBC_BARCHART | RBC_STRIPCHART)

#define RBC_PEN_DELETE_PENDING	(1<<0)
#define RBC_ACTIVE_PEN		(TK_CONFIG_USER_BIT << 6)
#define RBC_NORMAL_PEN		(TK_CONFIG_USER_BIT << 7)
#define RBC_ALL_PENS		(RBC_NORMAL_PEN | RBC_ACTIVE_PEN)

#define RBC_MARGIN_NONE     -1
#define RBC_MARGIN_BOTTOM   0
#define RBC_MARGIN_LEFT     1
#define RBC_MARGIN_TOP      2
#define RBC_MARGIN_RIGHT    3

/* forward references, defined later */
    typedef struct RbcGraph RbcGraph;
    typedef struct RbcElement RbcElement;
    typedef struct RbcLegend RbcLegend;
    typedef struct RbcBindTable RbcBindTable;
    typedef struct RbcChainLink RbcChainLink;
    typedef struct RbcTileClient *RbcTile;      /* Opaque type for tiles */
    typedef struct RbcPsToken RbcPsToken;
    typedef struct RbcPen RbcPen;
    typedef struct RbcMarker RbcMarker;
    typedef struct RbcCrosshairs RbcCrosshairs;
    typedef struct RbcParseValue RbcParseValue;

/*
 * RbcPad --
 *
 * 	Specifies vertical and horizontal padding.
 *
 *	Padding can be specified on a per side basis.  The fields
 *	side1 and side2 refer to the opposite sides, either
 *	horizontally or vertically.
 *
 *		side1	side2
 *              -----   -----
 *      x | left    right
 *	    y | top     bottom
 */
    typedef struct {
        short int side1;
        short int side2;
    } RbcPad;

/*
 * RbcTextFragment --
 */
    typedef struct {
        char *text;            /* Text to be displayed */
        short int x, y;        /* X-Y offset of the baseline from the
                                * upper-left corner of the bbox. */
        short int sx, sy;      /* See rbcWinUtil.c */
        short int count;       /* Number of bytes in text. The actual
                                * character count may differ because of
                                * multi-byte UTF encodings. */
        short int width;       /* Width of segment in pixels. This
                                * information is used to draw
                                * PostScript strings the same width
                                * as X. */
    } RbcTextFragment;

/*
 * RbcTextLayout --
 */
    typedef struct {
        int nFrags;            /* # fragments of text */
        short int width, height;        /* Dimensions of text bounding box */
        RbcTextFragment fragArr[1];     /* Information about each fragment of text */
    } RbcTextLayout;

/*
 * RbcShadow --
 */
    typedef struct {
        XColor *color;
        int offset;
    } RbcShadow;

/*
 * RbcTextStyle --
 *
 * 	Represents a convenient structure to hold text attributes
 *	which determine how a text string is to be displayed on the
 *	window, or drawn with PostScript commands.  The alternative
 *	is to pass lots of parameters to the drawing and printing
 *	routines. This seems like a more efficient and less cumbersome
 *	way of passing parameters.
 */
    typedef struct {
        unsigned int state;    /* If non-zero, indicates to draw text
                                * in the active color */
        short int width, height;        /* Extents of text */
        XColor *color;         /* Normal color */
        XColor *activeColor;   /* Active color */
        Tk_Font font;          /* Font to use to draw text */
        Tk_3DBorder border;    /* Background color of text.  This is also
                                * used for drawing disabled text. */
        RbcShadow shadow;      /* Drop shadow color and offset */
        Tk_Justify justify;    /* Justification of the text string. This
                                * only matters if the text is composed
                                * of multiple lines. */
        GC  gc;                /* GC used to draw the text */
        double theta;          /* Rotation of text in degrees. */
        Tk_Anchor anchor;      /* Indicates how the text is anchored around
                                * its x and y coordinates. */
        RbcPad padX, padY;     /* # pixels padding of around text region */
        short int leader;      /* # pixels spacing between lines of text */
    } RbcTextStyle;

/*
 *
 */
    typedef ClientData(
        RbcBindPickProc) (
        ClientData clientData,
        int x,
        int y,
        ClientData * contextPtr);

/*
 * RbcBindTable --
 *
 * Binding structure information:
 */
    typedef struct RbcBindTable {
        unsigned int flags;
        Tk_BindingTable bindingTable;   /* Table of all bindings currently defined.
                                         * NULL means that no bindings exist, so the
                                         * table hasn't been created.  Each "object"
                                         * used for this table is either a Tk_Uid for
                                         * a tag or the address of an item named by
                                         * id. */
        ClientData currentItem; /* The item currently containing the mouse
                                 * pointer, or NULL if none. */
        ClientData currentContext;      /* One word indicating what kind of object
                                         * was picked. */
        ClientData newItem;    /* The item that is about to become the
                                * current one, or NULL.  This field is
                                * used to detect deletions of the new
                                * current item pointer that occur during
                                * Leave processing of the previous current
                                * tab.  */
        ClientData newContext; /* One-word indicating what kind of object
                                * was just picked. */
        ClientData focusItem;
        ClientData focusContext;
        XEvent pickEvent;      /* The event upon which the current choice
                                * of the current tab is based.  Must be saved
                                * so that if the current item is deleted,
                                * we can pick another. */
        int activePick;        /* The pick event has been initialized so
                                * that we can repick it */
        int state;             /* Last known modifier state.  Used to
                                * defer picking a new current object
                                * while buttons are down. */
        ClientData clientData;
        Tk_Window tkwin;
        RbcBindPickProc *pickProc;      /* Routine to report the item the mouse is
                                         * currently over. */
    } RbcBindTable;

/*
 * RbcChainLink --
 *
 * A RbcChainLink is the container structure for the RbcChain.
 */
    typedef struct RbcChainLink {
        RbcChainLink *prevPtr; /* Link to the previous link */
        RbcChainLink *nextPtr; /* Link to the next link */
        ClientData clientData; /* Pointer to the data object */
    } RbcChainLink;

    typedef int (
        RbcChainCompareProc) (
        RbcChainLink ** l1PtrPtr,
        RbcChainLink ** l2PtrPtr);

/*
 * RbcChain --
 *
 * A RbcChain is a doubly chained list structure.
 */
    typedef struct {
        RbcChainLink *headPtr; /* Pointer to first element in chain */
        RbcChainLink *tailPtr; /* Pointer to last element in chain */
        int nLinks;            /* Number of elements in chain */
    } RbcChain;

/*
 * Rbc_Vector --
 */
    typedef struct {
        double *valueArr;      /* Array of values (possibly malloc-ed) */
        int numValues;         /* Number of values in the array */
        int arraySize;         /* Size of the allocated space */
        double min, max;       /* Minimum and maximum values in the vector */
    } Rbc_Vector;

/*
 * RbcVectorInterpData --
 */
    typedef struct {
        Tcl_HashTable vectorTable;      /* Table of vectors */
        Tcl_HashTable mathProcTable;    /* Table of vector math functions */
        Tcl_HashTable indexProcTable;
        Tcl_Interp *interp;
        unsigned int nextId;
    } RbcVectorInterpData;

/*
 * RbcVectorObject --
 *
 *	A vector is an array of double precision values.  It can be
 *	accessed through a Tcl command, a Tcl array variable, or C
 *	API. The storage for the array points initially to a
 *	statically allocated buffer, but to malloc-ed memory if more
 *	is necessary.
 *
 *	Vectors can be shared by several clients (for example, two
 *	different graph widgets).  The data is shared. When a client
 *	wants to use a vector, it allocates a vector identifier, which
 *	identifies the client.  Clients use this ID to specify a
 *	callback routine to be invoked whenever the vector is modified
 *	or destroyed.  Whenever the vector is updated or destroyed,
 *	each client is notified of the change by their callback
 *	routine.
 */
    typedef struct {
        /*
         * If you change these fields, make sure you change the definition
         * of RbcVector in rbcVector.h too.
         */
        double *valueArr;      /* Array of values (malloc-ed) */
        int length;            /* Current number of values in the array. */
        int size;              /* Maximum number of values that can be stored
                                * in the value array. */
        double min, max;       /* Minimum and maximum values in the vector */
        /* The following fields are local to this module  */
        char *name;            /* The namespace-qualified name of the vector command.
                                * It points to the hash key allocated for the
                                * entry in the vector hash table. */
        RbcVectorInterpData *dataPtr;
        Tcl_Interp *interp;    /* Interpreter associated with the vector */
        Tcl_HashEntry *hashPtr; /* If non-NULL, pointer in a hash table to
                                 * track the vectors in use. */
        Tcl_FreeProc *freeProc; /* Address of procedure to call to
                                 * release storage for the value
                                 * array, Optionally can be one of the
                                 * following: TCL_STATIC, TCL_DYNAMIC,
                                 * or TCL_VOLATILE. */
        char *arrayName;       /* The namespace-qualified name of the
                                * Tcl array variable
                                * mapped to the vector
                                * (malloc'ed). If NULL, indicates
                                * that the vector isn't mapped to any variable */
        int offset;            /* Offset from zero of the vector's
                                * starting index */
        Tcl_Command cmdToken;  /* Token for vector's Tcl command. */
        RbcChain *chainPtr;    /* List of clients using this vector */
        int notifyFlags;       /* Notification flags. See definitions
                                * below */
        int varFlags;          /* Indicate if the variable is global,
                                * namespace, or local */
        int freeOnUnset;       /* For backward compatibility only: If
                                * non-zero, free the vector when its
                                * variable is unset. */
        int flush;
        int first, last;       /* Selected region of vector. This is used
                                * mostly for the math routines */
    } RbcVectorObject;

    typedef struct RbcVectorIdStruct *RbcVectorId;

/*
 * RbcVectorNotify --
 */
    typedef enum {
        RBC_VECTOR_NOTIFY_UPDATE = 1,   /* The vector's values has been updated */
        RBC_VECTOR_NOTIFY_DESTROY       /* The vector has been destroyed and the client
                                         * should no longer use its data (calling
                                         * Rbc_FreeVectorId) */
    } RbcVectorNotify;

    typedef void (
        RbcVectorChangedProc) (
        Tcl_Interp * interp,
        ClientData clientData,
        RbcVectorNotify notify);
    typedef double (
        Rbc_VectorIndexProc) (
        Rbc_Vector * vecPtr);

/*
 * RbcParseValue --
 *
 *	The following data structure is used by various parsing
 *	procedures to hold information about where to store the
 *	results of parsing (e.g. the substituted contents of a quoted
 *	argument, or the result of a nested command).  At any given
 *	time, the space available for output is fixed, but a procedure
 *	may be called to expand the space available if the current
 *	space runs out.
 */
    typedef struct RbcParseValue {
        char *buffer;          /* Address of first character in
                                * output buffer. */
        char *next;            /* Place to store next character in
                                * output buffer. */
        char *end;             /* Address of the last usable character
                                * in the buffer. */
        void (
            *expandProc) (
            RbcParseValue * pvPtr,
            int needed);
        /* Procedure to call when space runs out;
         * it will make more space. */
        ClientData clientData; /* Arbitrary information for use of
                                * expandProc. */
    } RbcParseValue;

/*
 * RbcParseVector --
 */
    typedef struct {
        RbcVectorObject *vPtr;
        char staticSpace[RBC_STATIC_STRING_SPACE];
        RbcParseValue pv;      /* Used to hold a string value, if any. */
    } RbcParseVector;

/*
 * RbcOp --
 *
 * 	Generic function prototype of CmdOptions.
 */
    typedef int (
        *RbcOp) (
        );

/*
 * RbcOpSpec --
 *
 * 	Structure to specify a set of operations for a Tcl command.
 *      This is passed to the RbcGetOp procedure to look
 *      for a function pointer associated with the operation name.
 */
    typedef struct {
        const char *name;      /* Name of operation */
        int minChars;          /* Minimum # characters to disambiguate */
        RbcOp proc;
        int minArgs;           /* Minimum # args required */
        int maxArgs;           /* Maximum # args required */
        const char *usage;     /* Usage message */
    } RbcOpSpec;

/*
 * RbcOpIndex --
 */
    typedef enum {
        RBC_OP_ARG0,           /* Op is the first argument. */
        RBC_OP_ARG1,           /* Op is the second argument. */
        RBC_OP_ARG2,           /* Op is the third argument. */
        RBC_OP_ARG3,           /* Op is the fourth argument. */
        RBC_OP_ARG4            /* Op is the fifth argument. */
    } RbcOpIndex;

    typedef int (
        QSortCompareProc) (
        const void *,
        const void *);

/*
 * RbcDashes --
 *
 * 	List of dash values (maximum 11 based upon PostScript limit).
 */
    typedef struct {
        char values[12];
        int offset;
    } RbcDashes;
#define RbcLineIsDashed(d) ((d).values[0] != 0)

/*
 * RbcPoint2D --
 *
 *	2-D coordinate.
 */
    typedef struct {
        double x;
        double y;
    } RbcPoint2D;

/*
 * RbcPoint3D --
 *
 *	3-D coordinate.
 */
    typedef struct {
        double x;
        double y;
        double z;
    } RbcPoint3D;

/*
 * RbcSegment2D --
 *
 *	2-D line segment.
 */
    typedef struct {
        RbcPoint2D p;          /* First end point of the segment. */
        RbcPoint2D q;          /* Last end point of the segment. */
    } RbcSegment2D;

/*
 * RbcDim2D --
 *
 *	2-D dimension.
 */
    typedef struct {
        short int width;
        short int height;
    } RbcDim2D;

/*
 * RbcRegion2D --
 *
 *      2-D region.  Used to copy parts of images.
 */
    typedef struct {
        int left;
        int right;
        int top;
        int bottom;
    } RbcRegion2D;

/*
 * RbcExtents2D --
 */
    typedef struct {
        double left;
        double right;
        double top;
        double bottom;
    } RbcExtents2D;

/*
 * RbcExtents3D --
 */
    typedef struct {
        double left;
        double right;
        double top;
        double bottom;
        double front;
        double back;
    } RbcExtents3D;

/* int RbcPointInRegion(RbcRegion2D e, int x, int y) */
#define RbcPointInRegion(e,x,y) \
	(((x) <= (e)->right) && ((x) >= (e)->left) && \
	 ((y) <= (e)->bottom) && ((y) >= (e)->top))

/*
 * RbcColorPair --
 *
 *	Holds a pair of foreground, background colors.
 */
    typedef struct {
        XColor *fgColor, *bgColor;
    } RbcColorPair;

    typedef void (
        RbcTileChangedProc) (
        ClientData clientData,
        RbcTile tile);

/*
 * RbcPix32 --
 *
 *      A union representing either a pixel as a RGB triplet or a
 *	single word value.
 */
    typedef union {
        unsigned int value;    /* Lookup table address */
        struct RGBA {
            unsigned char red; /* Red intensity 0..255 */
            unsigned char green;        /* Green intensity 0.255 */
            unsigned char blue; /* Blue intensity 0..255 */
            unsigned char alpha;        /* Alpha-channel for compositing. 0..255 */
        } rgba;
        unsigned char channel[4];
    } RbcPix32;

/*
 * RbcColorImage --
 *
 *      The structure below represents a color image.  Each pixel
 *	occupies a 32-bit word of memory: one byte for each of the
 *	red, green, and blue color intensities, and another for
 *	alpha-channel image compositing (e.g. transparency).
 */
    typedef struct RbcColorImage {
        int width;             /* Dimensions of the image */
        int height;            /* Dimensions of the image */
        RbcPix32 *bits;        /* Array of pixels representing the image. */
    } RbcColorImage;

/*
 * ResampleFilterProc --
 *
 *      A function implementing a 1-D filter.
 */
    typedef double (
        ResampleFilterProc) (
        double value);

/*
 * RbcFilter2D --
 *
 *      Defines a convolution mask for a 2-D filter.  Used to smooth or
 *	enhance images.
 */
    typedef struct {
        double support;        /* Radius of filter */
        double sum, scale;     /* Sum of kernel */
        double *kernel;        /* Array of values (malloc-ed) representing
                                * the discrete 2-D filter. */
    } RbcFilter2D;

/*
 * RbcPsColorMode --
 */
    typedef enum {
        PS_MODE_MONOCHROME,    /* Only black and white. */
        PS_MODE_GREYSCALE,     /* Color converted to greyscale. */
        PS_MODE_COLOR          /* Full color */
    } RbcPsColorMode;

/*
 * RbcPsToken --
 */
    typedef struct RbcPsToken {
        Tcl_Interp *interp;    /* Interpreter to report errors to. */
        Tk_Window tkwin;       /* Tk_Window used to get font and color
                                * information */
        Tcl_DString dString;   /* Dynamic string used to contain the
                                * PostScript generated. */
        char *fontVarName;     /* Name of a Tcl array variable to convert
                                * X font names to PostScript fonts. */
        char *colorVarName;    /* Name of a Tcl array variable to convert
                                * X color names to PostScript. */
        RbcPsColorMode colorMode;       /* Mode: color or greyscale */
        /*
         * Utility space for building strings.  Currently used to create
         * PostScript output for the "postscript" command.
         */
        char scratchArr[BUFSIZ * 2];
    } RbcPsToken;

/*
 * RbxAxisRange --
 *
 *	Designates a range of values by a minimum and maximum limit.
 */
    typedef struct {
        double min;
        double max;
        double range;
        double scale;
    } RbcAxisRange;

/*
 * RbcTicks --
 *
 * 	Structure containing information where the ticks (major or
 *	minor) will be displayed on the graph.
 */
    typedef struct {
        int nTicks;            /* # of ticks on axis */
        double values[1];      /* Array of tick values (malloc-ed). */
    } RbcTicks;

/*
 * RbcTickSweep --
 *
 * 	Structure containing information where the ticks (major or
 *	minor) will be displayed on the graph.
 */
    typedef struct {
        double initial;        /* Initial value */
        double step;           /* Size of interval */
        int nSteps;            /* Number of intervals. */
    } RbcTickSweep;

/*
 * RbcAxis --
 *
 * 	Structure contains options controlling how the axis will be
 * 	displayed.
 */
    typedef struct {
        char *name;            /* Identifier to refer the element.
                                * Used in the "insert", "delete", or
                                * "show", commands. */
        Tk_Uid classUid;       /* Type of axis. */
        RbcGraph *graphPtr;    /* Graph widget of element */
        unsigned int flags;    /* Set bit field definitions below */
        /*
         * AXIS_DRAWN               Axis is designated as a logical axis
         * AXIS_DIRTY
         *
         * AXIS_CONFIG_MAJOR        User specified major ticks.
         * AXIS_CONFIG_MINOR        User specified minor ticks.
         */
        char **tags;
        const char *detail;
        int deletePending;     /* Indicates that the axis was
                                * scheduled for deletion. The actual
                                * deletion may be deferred until the
                                * axis is no longer in use.  */
        int refCount;          /* Number of elements referencing this
                                * axis. */
        Tcl_HashEntry *hashPtr; /* Points to axis entry in hash
                                 * table. Used to quickly remove axis
                                 * entries. */
        int logScale;          /* If non-zero, scale the axis values
                                * logarithmically. */
        int hidden;            /* If non-zero, don't display the
                                * axis title, ticks, or line. */
        int showTicks;         /* If non-zero, display tick marks and
                                * labels. */
        int descending;        /* If non-zero, display the range of
                                * values on the axis in descending
                                * order, from high to low. */
        int looseMin, looseMax; /* If non-zero, axis range extends to
                                 * the outer major ticks, otherwise at
                                 * the limits of the data values. This
                                 * is overriddened by setting the -min
                                 * and -max options.  */
        char *title;           /* Title of the axis. */
        RbcTextStyle titleTextStyle;    /* Text attributes (color, font,
                                         * rotation, etc.)  of the axis
                                         * title. */
        int titleAlternate;    /* Indicates whether to position the
                                * title above/left of the axis. */
        RbcPoint2D titlePos;   /* Position of the title */
        unsigned short int titleWidth, titleHeight;
        int lineWidth;         /* Width of lines representing axis
                                * (including ticks).  If zero, then
                                * no axis lines or ticks are
                                * drawn. */
        const char **limitsFormats;     /* One or two strings of sprintf-like
                                         * formats describing how to display
                                         * virtual axis limits. If NULL,
                                         * display no limits. */
        int nFormats;
        RbcTextStyle limitsTextStyle;   /* Text attributes (color, font,
                                         * rotation, etc.)  of the limits. */
        double windowSize;     /* Size of a sliding window of values
                                * used to scale the axis automatically
                                * as new data values are added. The axis
                                * will always display the latest values
                                * in this range. */
        double shiftBy;        /* Shift maximum by this interval. */
        int tickLength;        /* Length of major ticks in pixels */
        RbcTextStyle tickTextStyle;     /* Text attributes (color, font, rotation,
                                         * etc.) for labels at each major tick. */
        char *formatCmd;       /* Specifies a Tcl command, to be invoked
                                * by the axis whenever it has to generate
                                * tick labels. */
        char *scrollCmdPrefix;
        int scrollUnits;
        double min, max;       /* The actual axis range. */
        double reqMin, reqMax; /* Requested axis bounds. Consult the
                                * axisPtr->flags field for
                                * AXIS_CONFIG_MIN and AXIS_CONFIG_MAX
                                * to see if the requested bound have
                                * been set.  They override the
                                * computed range of the axis
                                * (determined by auto-scaling). */
        double scrollMin, scrollMax;    /* Defines the scrolling reqion of the axis.
                                         * Normally the region is determined from
                                         * the data limits. If specified, these
                                         * values override the data-range. */
        RbcAxisRange valueRange;        /* Range of data values of elements mapped
                                         * to this axis. This is used to auto-scale
                                         * the axis in "tight" mode. */
        RbcAxisRange axisRange; /* Smallest and largest major tick values
                                 * for the axis.  The tick values lie outside
                                 * the range of data values.  This is used to
                                 * auto-scale the axis in "loose" mode. */
        double prevMin, prevMax;
        double reqStep;        /* If > 0.0, overrides the computed major
                                * tick interval.  Otherwise a stepsize
                                * is automatically calculated, based
                                * upon the range of elements mapped to the
                                * axis. The default value is 0.0. */
        double tickZoom;       /* If > 0.0, overrides the computed major
                                * tick interval.  Otherwise a stepsize
                                * is automatically calculated, based
                                * upon the range of elements mapped to the
                                * axis. The default value is 0.0. */
        GC  tickGC;            /* Graphics context for axis and tick labels */
        RbcTicks *t1Ptr;       /* Array of major tick positions. May be
                                * set by the user or generated from the
                                * major sweep below. */
        RbcTicks *t2Ptr;       /* Array of minor tick positions. May be
                                * set by the user or generated from the
                                * minor sweep below. */
        RbcTickSweep minorSweep, majorSweep;
        int reqNumMinorTicks;  /* If non-zero, represents the
                                * requested the number of minor ticks
                                * to be uniformally displayed along
                                * each major tick. */
        int labelOffset;       /* If non-zero, indicates that the tick
                                * label should be offset to sit in the
                                * middle of the next interval. */
        /* The following fields are specific to logical axes */
        RbcChainLink *linkPtr; /* Axis link in margin list. */
        RbcChain *chainPtr;
        short int width, height;        /* Extents of axis */
        RbcSegment2D *segments; /* Array of line segments representing
                                 * the major and minor ticks, but also
                                 * the axis line itself. The segment
                                 * coordinates are relative to the
                                 * axis. */
        int nSegments;         /* Number of segments in the above array. */
        RbcChain *tickLabels;  /* Contains major tick label strings
                                * and their offsets along the axis. */
        RbcRegion2D region;
        Tk_3DBorder border;
        int borderWidth;
        int relief;
    } RbcAxis;

/*
 * RbcAxis2D --
 *
 *	The pair of axes mapping a point onto the graph.
 */
    typedef struct {
        RbcAxis *x;
        RbcAxis *y;
    } RbcAxis2D;

/*
* RbcElemWeight --
*
*	Designates a range of values by a minimum and maximum limit.
*/
    typedef struct {
        double min;
        double max;
        double range;
    } RbcElemWeight;

/*
 * RbcPenStyle --
 *
 * An element has one or more vectors plus several attributes, such as
 * line style, thickness, color, and symbol type.  It has an
 * identifier which distinguishes it among the list of all elements.
 */
    typedef struct {
        RbcElemWeight weight;  /* Weight range where this pen is valid. */
        RbcPen *penPtr;        /* Pen to use. */
        RbcSegment2D *xErrorBars;       /* Point to start of this pen's X-error bar
                                         * segments in the element's array. */
        RbcSegment2D *yErrorBars;       /* Point to start of this pen's Y-error bar
                                         * segments in the element's array. */
        int xErrorBarCnt;      /* # of error bars for this pen. */
        int yErrorBarCnt;      /* # of error bars for this pen. */
        int errorBarCapWidth;  /* Length of the cap ends on each
                                * error bar. */
        int symbolSize;        /* Size of the pen's symbol scaled to
                                * the current graph size. */
    } RbcPenStyle;

    typedef struct {
        int halo;              /* Maximal distance a candidate point
                                * can be from the sample window
                                * coordinate */
        int mode;              /* Indicates whether to find the closest
                                * data point or the closest point on the
                                * trace by interpolating the line segments.
                                * Can also be SEARCH_AUTO, indicating to
                                * choose how to search.*/
        int x, y;              /* Screen coordinates of test point */
        int along;             /* Indicates to let search run along a
                                * particular axis: x, y, or both. */
        /* Output */
        RbcElement *elemPtr;   /* Name of the closest element */
        RbcPoint2D point;      /* Graph coordinates of closest point */
        int index;             /* Index of closest data point */
        double dist;           /* Distance in screen coordinates */
    } RbcClosestSearch;

    typedef void (
        RbcElementDrawProc) (
        RbcGraph * graphPtr,
        Drawable drawable,
        RbcElement * elemPtr);
    typedef void (
        RbcElementToPostScriptProc) (
        RbcGraph * graphPtr,
        RbcPsToken * psToken,
        RbcElement * elemPtr);
    typedef void (
        RbcElementDestroyProc) (
        RbcGraph * graphPtr,
        RbcElement * elemPtr);
    typedef int (
        RbcElementConfigProc) (
        RbcGraph * graphPtr,
        RbcElement * elemPtr);
    typedef void (
        RbcElementMapProc) (
        RbcGraph * graphPtr,
        RbcElement * elemPtr);
    typedef void (
        RbcElementExtentsProc) (
        RbcElement * elemPtr,
        RbcExtents2D * extsPtr);
    typedef void (
        RbcElementClosestProc) (
        RbcGraph * graphPtr,
        RbcElement * elemPtr,
        RbcClosestSearch * searchPtr);
    typedef void (
        RbcElementDrawSymbolProc) (
        RbcGraph * graphPtr,
        Drawable drawable,
        RbcElement * elemPtr,
        int x,
        int y,
        int symbolSize);
    typedef void (
        RbcElementSymbolToPostScriptProc) (
        RbcGraph * graphPtr,
        RbcPsToken * psToken,
        RbcElement * elemPtr,
        double x,
        double y,
        int symSize);

/*
 * RbcElementProcs --
 */
    typedef struct {
        RbcElementClosestProc *closestProc;
        RbcElementConfigProc *configProc;
        RbcElementDestroyProc *destroyProc;
        RbcElementDrawProc *drawActiveProc;
        RbcElementDrawProc *drawNormalProc;
        RbcElementDrawSymbolProc *drawSymbolProc;
        RbcElementExtentsProc *extentsProc;
        RbcElementToPostScriptProc *printActiveProc;
        RbcElementToPostScriptProc *printNormalProc;
        RbcElementSymbolToPostScriptProc *printSymbolProc;
        RbcElementMapProc *mapProc;
    } RbcElementProcs;

/*
 * RbcElemVector --
 *
 * The data structure below contains information pertaining to a line
 * vector.  It consists of an array of floating point data values and
 * for convenience, the number and minimum/maximum values.
 */
    typedef struct {
        Rbc_Vector *vecPtr;
        double *valueArr;
        int nValues;
        int arraySize;
        double min, max;
        RbcVectorId clientId;  /* If non-NULL, a client token identifying the
                                * external vector. */
        RbcElement *elemPtr;   /* Element associated with vector. */
    } RbcElemVector;

/*
 * RbcElement --
 */
    typedef struct RbcElement {
        char *name;            /* Identifier to refer the element.
                                * Used in the "insert", "delete", or
                                * "show", commands. */
        Tk_Uid classUid;       /* Type of element */
        RbcGraph *graphPtr;    /* Graph widget of element */
        unsigned int flags;    /* Indicates if the entire element is
                                * active, or if coordinates need to
                                * be calculated */
        char **tags;
        int hidden;            /* If non-zero, don't display the element. */
        Tcl_HashEntry *hashPtr;
        char *label;           /* Label displayed in legend */
        int labelRelief;       /* Relief of label in legend. */
        RbcAxis2D axes;        /* X-axis and Y-axis mapping the element */
        RbcElemVector x, y, w; /* Contains array of floating point
                                * graph coordinate values. Also holds
                                * min/max and the number of
                                * coordinates */
        RbcElemVector xError;  /* Relative/symmetric X error values. */
        RbcElemVector yError;  /* Relative/symmetric Y error values. */
        RbcElemVector xHigh, xLow;      /* Absolute/asymmetric X-coordinate high/low
                                         * error values. */
        RbcElemVector yHigh, yLow;      /* Absolute/asymmetric Y-coordinate high/low
                                         * error values. */
        int *activeIndices;    /* Array of indices (malloc-ed) which
                                * indicate which data points are
                                * active (drawn with "active"
                                * colors). */
        int nActiveIndices;    /* Number of active data points.
                                * Special case: if nActiveIndices < 0
                                * and the active bit is set in
                                * "flags", then all data points are
                                * drawn active. */
        RbcElementProcs *procsPtr;
        Tk_ConfigSpec *specsPtr;        /* Configuration specifications. */
        RbcSegment2D *xErrorBars;       /* Point to start of this pen's X-error bar
                                         * segments in the element's array. */
        RbcSegment2D *yErrorBars;       /* Point to start of this pen's Y-error bar
                                         * segments in the element's array. */
        int xErrorBarCnt;      /* # of error bars for this pen. */
        int yErrorBarCnt;      /* # of error bars for this pen. */
        int *xErrorToData;     /* Maps error bar segments back to the data
                                * point. */
        int *yErrorToData;     /* Maps error bar segments back to the data
                                * point. */
        int errorBarCapWidth;  /* Length of cap on error bars */
        RbcPen *activePenPtr;  /* Standard Pens */
        RbcPen *normalPenPtr;
        RbcChain *palette;     /* Palette of pens. */
        /* Symbol scaling */
        int scaleSymbols;      /* If non-zero, the symbols will scale
                                * in size as the graph is zoomed
                                * in/out.  */
        double xRange, yRange; /* Initial X-axis and Y-axis ranges:
                                * used to scale the size of element's
                                * symbol. */
        int state;
    } RbcElement;

/*
 * RbcFreqInfo --
 */
    typedef struct {
        int freq;              /* Number of occurrences of x-coordinate */
        RbcAxis2D axes;        /* Indicates which x and y axis are mapped to
                                * the x-value */
        double sum;            /* Sum of the ordinates of each duplicate
                                * abscissa */
        int count;
        double lastY;

    } RbcFreqInfo;

/*
 * RbcBarMode --
 *
 *	Bar elements are displayed according to their x-y coordinates.
 *	If two bars have the same abscissa (x-coordinate), the bar
 *	segments will be drawn according to one of the following
 *	modes:
 */
    typedef enum {
        MODE_INFRONT,          /* Each successive segment is drawn in
                                * front of the previous. */
        MODE_STACKED,          /* Each successive segment is drawn
                                * stacked above the previous. */
        MODE_ALIGNED,          /* Each successive segment is drawn
                                * aligned to the previous from
                                * right-to-left. */
        MODE_OVERLAP           /* Like "aligned", each successive segment
                                * is drawn from right-to-left. In addition
                                * the segments will overlap each other
                                * by a small amount */
    } RbcBarMode;

    typedef RbcPen *(
        PenCreateProc) (
        void);
    typedef int (
        PenConfigureProc) (
        RbcGraph * graphPtr,
        RbcPen * penPtr);
    typedef void (
        PenDestroyProc) (
        RbcGraph * graphPtr,
        RbcPen * penPtr);

/*
 * RbcPen --
 */
    typedef struct RbcPen {
        char *name;            /* Pen style identifier.  If NULL pen
                                * was statically allocated. */
        Tk_Uid classUid;       /* Type of pen */
        char *typeId;          /* String token identifying the type of pen */
        unsigned int flags;    /* Indicates if the pen element is active or
                                * normal */
        int refCount;          /* Reference count for elements using
                                * this pen. */
        Tcl_HashEntry *hashPtr;

        Tk_ConfigSpec *configSpecs;     /* Configuration specifications */

        PenConfigureProc *configProc;
        PenDestroyProc *destroyProc;

    } RbcPen;

/*
 * RbcPostScript --
 *
 * 	Structure contains information specific to the outputting of
 *	PostScript commands to print the graph.
 *
 */
    typedef struct {
        /* User configurable fields */

        int decorations;       /* If non-zero, print graph with
                                * color background and 3D borders */

        int reqWidth, reqHeight;        /* If greater than zero, represents the
                                         * requested dimensions of the printed graph */
        int reqPaperWidth;
        int reqPaperHeight;    /* Requested dimensions for the PostScript
                                * page. Can constrain the size of the graph
                                * if the graph (plus padding) is larger than
                                * the size of the page. */
        RbcPad padX, padY;     /* Requested padding on the exterior of the
                                * graph. This forms the bounding box for
                                * the page. */
        RbcPsColorMode colorMode;       /* Selects the color mode for PostScript page
                                         * (0=monochrome, 1=greyscale, 2=color) */
        char *colorVarName;    /* If non-NULL, is the name of a Tcl array
                                * variable containing X to PostScript color
                                * translations */
        char *fontVarName;     /* If non-NULL, is the name of a Tcl array
                                * variable containing X to PostScript font
                                * translations */
        int landscape;         /* If non-zero, orient the page 90 degrees */
        int center;            /* If non-zero, center the graph on the page */
        int maxpect;           /* If non-zero, indicates to scale the graph
                                * so that it fills the page (maintaining the
                                * aspect ratio of the graph) */
        int addPreview;        /* If non-zero, generate a preview image and
                                * add it to the PostScript output */
        int footer;            /* If non-zero, a footer with the title, date
                                * and user will be added to the PostScript
                                * output outside of the bounding box. */
        int previewFormat;     /* Format of EPS preview:
                                * PS_PREVIEW_WMF, PS_PREVIEW_EPSI, or
                                * PS_PREVIEW_TIFF. */

        /* Computed fields */

        int left, bottom;      /* Bounding box of PostScript plot. */
        int right, top;

        double pageScale;      /* Scale of page. Set if "-maxpect" option
                                * is set, otherwise 1.0. */
    } RbcPostScript;

/*
 * RbcGrid --
 *
 *	Contains attributes of describing how to draw grids (at major
 *	ticks) in the graph.  Grids may be mapped to either/both x and
 *	y axis.
 */
    typedef struct {
        GC  gc;                /* Graphics context for the grid. */
        RbcAxis2D axes;
        int hidden;            /* If non-zero, grid isn't displayed. */
        int minorGrid;         /* If non-zero, draw grid line for minor
                                * axis ticks too */
        RbcDashes dashes;      /* Dashstyle of the grid. This represents
                                * an array of alternatingly drawn pixel
                                * values. */
        int lineWidth;         /* Width of the grid lines */
        XColor *colorPtr;      /* Color of the grid lines */

        struct GridSegments {
            RbcSegment2D *segments;     /* Array of line segments representing the
                                         * x or y grid lines */
            int nSegments;     /* # of axis segments. */
        } x,
            y;

    } RbcGrid;

/*
 * RbcMargin --
 */
    typedef struct {
        short int width, height;        /* Extents of the margin */

        short int axesOffset;
        short int axesTitleLength;      /* Width of the widest title to be shown.
                                         * Multiple titles are displayed in
                                         * another margin. This is the minimum
                                         * space requirement. */
        unsigned int nAxes;    /* Number of axes to be displayed */
        RbcChain *axes;        /* Extra axes associated with this margin */

        char *varName;         /* If non-NULL, name of variable to be
                                * updated when the margin size changes */

        int reqSize;           /* Requested size of margin */
        int site;              /* Indicates where margin is located:
                                * left/right/top/bottom. */
    } RbcMargin;

/*
 * RbcGraph --
 *
 *	Top level structure containing everything pertaining to
 *	the graph.
 */
    typedef struct RbcGraph {
        Tk_Window *win;
        Tcl_Object object;
        Tcl_Interp *interp;    /* Interpreter associated with graph */
        Display *display;      /* Display containing widget; needed,
                                * among other things, to release
                                * resources after tkwin has already gone
                                * away. */
        unsigned int flags;    /* Flags;  see below for definitions. */
        Tk_Cursor cursor;
        int inset;             /* Sum of focus highlight and 3-D
                                * border.  Indicates how far to
                                * offset the graph from outside
                                * edge of the window. */
        int borderWidth;       /* Width of the exterior border */
        int relief;            /* Relief of the exterior border */
        Tk_3DBorder border;    /* 3-D border used to delineate the plot
                                * surface and outer edge of window */
        int highlightWidth;    /* Width in pixels of highlight to draw
                                * around widget when it has the focus.
                                * <= 0 means don't draw a highlight. */
        XColor *highlightBgColor;       /* Color for drawing traversal highlight
                                         * area when highlight is off. */
        XColor *highlightColor; /* Color for drawing traversal highlight. */
        char *title;
        short int titleX, titleY;
        RbcTextStyle titleTextStyle;    /* Graph title */
        char *takeFocus;
        int reqWidth, reqHeight;        /* Requested size of graph window */
        int width, height;     /* Size of graph window or PostScript
                                * page */
        Tcl_HashTable penTable; /* Table of pens */
        struct Component {
            Tcl_HashTable table;        /* Hash table of ids. */
            RbcChain *displayList;      /* Display list. */
            Tcl_HashTable tagTable;     /* Table of bind tags. */
        } elements,
            markers,
            axes;
        Tk_Uid classUid;       /* Default element type */
        const char *chartStyle; /* one of line, bar or strip */
        RbcBindTable *bindTable;
        int nextMarkerId;      /* Tracks next marker identifier available */
        RbcChain *axisChain[4]; /* Chain of axes for each of the
                                 * margins.  They're separate from the
                                 * margin structures to make it easier
                                 * to invert the X-Y axes by simply
                                 * switching chain pointers.
                                 */
        RbcMargin margins[4];
        RbcPostScript *postscript;      /* PostScript options: see rbcGrPS.c */
        RbcLegend *legend;     /* Legend information: see rbcGrLegd.c */
        RbcCrosshairs *crosshairs;      /* Crosshairs information: see rbcGrHairs.c */
        RbcGrid *gridPtr;      /* Grid attribute information */
        int halo;              /* Maximum distance allowed between points
                                * when searching for a point */
        int inverted;          /* If non-zero, indicates the x and y axis
                                * positions should be inverted. */
        RbcTile tile;
        GC  drawGC;            /* Used for drawing on the margins. This
                                * includes the axis lines */
        GC  fillGC;            /* Used to fill the background of the
                                * margins. The fill is governed by
                                * the background color or the tiled
                                * pixmap. */
        int plotBorderWidth;   /* Width of interior 3-D border. */
        int plotRelief;        /* 3-d effect: TK_RELIEF_RAISED etc. */
        XColor *plotBg;        /* Color of plotting surface */
        GC  plotFillGC;        /* Used to fill the plotting area with a
                                * solid background color. The fill color
                                * is stored in "plotBg". */
        /* If non-zero, force plot to conform to aspect ratio W/H */
        double aspect;
        short int left, right; /* Coordinates of plot bbox */
        short int top, bottom;
        RbcPad padX;           /* Vertical padding for plotarea */
        int vRange, vOffset;   /* Vertical axis range and offset from the
                                * left side of the graph window. Used to
                                * transform coordinates to vertical
                                * axes. */
        RbcPad padY;           /* Horizontal padding for plotarea */
        int hRange, hOffset;   /* Horizontal axis range and offset from
                                * the top of the graph window. Used to
                                * transform horizontal axes */
        double vScale, hScale;
        int doubleBuffer;      /* If non-zero, draw the graph into a pixmap
                                * first to reduce flashing. */
        int backingStore;      /* If non-zero, cache elements by drawing
                                * them into a pixmap */
        Pixmap backPixmap;     /* Pixmap used to cache elements
                                * displayed.  If *backingStore* is
                                * non-zero, each element is drawn
                                * into this pixmap before it is
                                * copied onto the screen.  The pixmap
                                * then acts as a cache (only the
                                * pixmap is redisplayed if the none
                                * of elements have changed). This is
                                * done so that markers can be redrawn
                                * quickly over elements without
                                * redrawing each element. */
        int backWidth, backHeight;      /* Size of element backing store pixmap. */
        /*
         * barchart specific information
         */
        double baseline;       /* Baseline from bar chart.  */
        double barWidth;       /* Default width of each bar in graph units.
                                * The default width is 1.0 units. */
        RbcBarMode mode;       /* Mode describing how to display bars
                                * with the same x-coordinates. Mode can
                                * be "stack", "align", or "normal" */
        RbcFreqInfo *freqArr;  /* Contains information about duplicate
                                * x-values in bar elements (malloc-ed).
                                * This information can also be accessed
                                * by the frequency hash table */
        Tcl_HashTable freqTable;        /* */
        int nStacks;           /* Number of entries in frequency array.
                                * If zero, indicates nothing special needs
                                * to be done for "stack" or "align" modes */
    } RbcGraph;

    typedef ClientData(
        MakeTagProc) (
        RbcGraph * graphPtr,
        const char *tagName);

    typedef int (
        RbcSwitchParseProc) (
        ClientData clientData,
        Tcl_Interp * interp,
        char *switchName,
        char *value,
        char *record,
        int offset);

    typedef void (
        RbcSwitchFreeProc) (
        char *ptr);

/*
 * RbcSwitchCustom --
 */
    typedef struct {
        RbcSwitchParseProc *parseProc;  /* Procedure to parse a switch value
                                         * and store it in its converted
                                         * form in the data record. */
        RbcSwitchFreeProc *freeProc;    /* Procedure to free a switch. */
        ClientData clientData; /* Arbitrary one-word value
                                * used by switch parser,
                                * passed to parseProc. */
    } RbcSwitchCustom;

/*
 * Type values for RbcSwitchSpec structures.  See the user
 * documentation for details.
 */
    typedef enum {
        RBC_SWITCH_BOOLEAN, RBC_SWITCH_INT, RBC_SWITCH_INT_POSITIVE,
        RBC_SWITCH_INT_NONNEGATIVE, RBC_SWITCH_DOUBLE, RBC_SWITCH_STRING,
        RBC_SWITCH_LIST, RBC_SWITCH_FLAG, RBC_SWITCH_VALUE, RBC_SWITCH_CUSTOM,
        RBC_SWITCH_END
    } RbcSwitchTypes;

    typedef struct {
        RbcSwitchTypes type;   /* Type of option, such as RBC_SWITCH_DOUBLE;
                                * see definitions above.  Last option in
                                * table must have type RBC_SWITCH_END. */
        const char *switchName; /* Switch used to specify option in argv.
                                 * NULL means this spec is part of a group. */
        int offset;            /* Where in widget record to store value;
                                * use RbcOffset macro to generate values
                                * for this. */
        int flags;             /* Any combination of the values defined
                                * below. */
        RbcSwitchCustom *customPtr;     /* If type is RBC_SWITCH_CUSTOM then this is
                                         * a pointer to info about how to parse and
                                         * print the option.  Otherwise it is
                                         * irrelevant. */
        int value;
    } RbcSwitchSpec;

/*
 * RbcResampleFilter --
 *
 *      Contains information about a 1-D filter (its support and
 *	the procedure implementing the filter).
 */
    typedef struct {
        const char *name;      /* Name of the filter */
        ResampleFilterProc *proc;       /* 1-D filter procedure. */
        double support;        /* Width of 1-D filter */
    } RbcResampleFilter;

/*
 * Data declarations:
 */
    extern double rbcNaN;
    extern RbcResampleFilter *rbcBoxFilterPtr;  /* The ubiquitous box filter */
    extern Tk_Uid rbcBarElementUid;
    extern Tk_Uid rbcLineElementUid;
    extern Tk_Uid rbcStripElementUid;
    extern Tk_Uid rbcLineMarkerUid;
    extern Tk_Uid rbcBitmapMarkerUid;
    extern Tk_Uid rbcImageMarkerUid;
    extern Tk_Uid rbcTextMarkerUid;
    extern Tk_Uid rbcPolygonMarkerUid;
    extern Tk_Uid rbcWindowMarkerUid;
    extern Tk_Uid rbcXAxisUid;
    extern Tk_Uid rbcYAxisUid;

/*
 * Inline function declarations:
 */

/* int RbcNumberOfPoints(RbcAxis2D e); */
#define RbcNumberOfPoints(e)	MIN((e)->x.nValues, (e)->y.nValues)

/* int RbcLineWidth(int w); */
#define RbcLineWidth(w)	(((w) > 1) ? (w) : 0)

/* int RbcPadding(RbcPad w); */
#define RbcPadding(x)	((x).side1 + (x).side2)

/* ClientData RbcGetCurrentItem(RbcBindTable *bindPtr); */
#define RbcGetCurrentItem(bindPtr)  ((bindPtr)->currentItem)
/* */
/* ClientData RbcGetBindingData(RbcBindTable *bindPtr); */
#define RbcGetBindingData(bindPtr)  ((bindPtr)->clientData)
/* int RbcChainGetLength(RbcChain *c); */
#define RbcChainGetLength(c)	(((c) == NULL) ? 0 : (c)->nLinks)
/* RbcChainLink *RbcChainFirstLink(RbcChain *c); */
#define RbcChainFirstLink(c)	(((c) == NULL) ? NULL : (c)->headPtr)
/* */
/* RbcChainLink *RbcChainLastLink(RbcChain *c); */
#define RbcChainLastLink(c)	(((c) == NULL) ? NULL : (c)->tailPtr)
/* RbcChainLink *RbcChainPrevLink(RbcChainLink *l); */
#define RbcChainPrevLink(l)	((l)->prevPtr)
/* RbcChainLink *RbcChainNextLink(RbcChainLink *l); */
#define RbcChainNextLink(l) 	((l)->nextPtr)
/* ClientData RbcChainGetValue(RbcChainLink *l); */
#define RbcChainGetValue(l)  	((l)->clientData)
/* void RbcChainSetValue(RbcChainLink *l, ClientData value); */
#define RbcChainSetValue(l, value) ((l)->clientData = (ClientData)(value))

/*
 * Function declarations:
 */

/* rbcBind.c */
    MODULE_SCOPE int RbcConfigureBindings(
        Tcl_Interp * interp,
        RbcBindTable * table,
        ClientData item,
        int argc,
        const char **argv);
    MODULE_SCOPE int RbcConfigureBindingsFromObj(
        Tcl_Interp * interp,
        RbcBindTable * table,
        ClientData item,
        int objc,
        Tcl_Obj * const *objv);
    MODULE_SCOPE RbcBindTable *RbcCreateBindingTable(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        ClientData clientData,
        RbcBindPickProc * pickProc);
    MODULE_SCOPE void RbcDestroyBindingTable(
        RbcBindTable * table);
    MODULE_SCOPE void RbcPickCurrentItem(
        RbcBindTable * table);
    MODULE_SCOPE void RbcDeleteBindings(
        RbcBindTable * table,
        ClientData object);
    MODULE_SCOPE void RbcMoveBindingTable(
        RbcBindTable * table,
        Tk_Window tkwin);

/* rbcChain,c */
    MODULE_SCOPE RbcChain *RbcChainCreate(
        );
    MODULE_SCOPE void RbcChainInit(
        RbcChain * chainPtr);
    MODULE_SCOPE void RbcChainLinkAfter(
        RbcChain * chainPtr,
        RbcChainLink * linkPtr,
        RbcChainLink * afterLinkPtr);
    MODULE_SCOPE void RbcChainLinkBefore(
        RbcChain * chainPtr,
        RbcChainLink * linkPtr,
        RbcChainLink * beforeLinkPtr);
    MODULE_SCOPE RbcChainLink *RbcChainNewLink(
        void);
    MODULE_SCOPE void RbcChainReset(
        RbcChain * chainPtr);
    MODULE_SCOPE void RbcChainDestroy(
        RbcChain * chainPtr);
    MODULE_SCOPE void RbcChainUnlinkLink(
        RbcChain * chainPtr,
        RbcChainLink * linkPtr);
    MODULE_SCOPE void RbcChainDeleteLink(
        RbcChain * chainPtr,
        RbcChainLink * linkPtr);
    MODULE_SCOPE RbcChainLink *RbcChainAppend(
        RbcChain * chainPtr,
        ClientData clientData);
    MODULE_SCOPE RbcChainLink *RbcChainPrepend(
        RbcChain * chainPtr,
        ClientData clientData);
    MODULE_SCOPE RbcChainLink *RbcChainAllocLink(
        unsigned int size);

/* rbcConfig.c */
    MODULE_SCOPE int RbcGraphOptionSetPad(
        Tcl_Interp * interp,
        Tcl_Object object,
        Tcl_Obj * value,
        RbcPad * address);
    MODULE_SCOPE int RbcGraphOptionSetShadow(
        Tcl_Interp * interp,
        Tcl_Object object,
        Tcl_Obj * value,
        RbcShadow * shadow);
    MODULE_SCOPE int RbcGraphOptionSetTile(
        Tcl_Interp * interp,
        Tcl_Object object,
        Tcl_Obj * value,
        RbcTile * tile);
    MODULE_SCOPE int RbcGetPixels(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        const char *string,
        int check,
        int *valuePtr);
    MODULE_SCOPE int RbcConfigModified(
        Tk_ConfigSpec * specs,
        ...);
    MODULE_SCOPE int RbcConfigureWidgetComponent(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        const char *name,
        const char *class,
        const Tk_ConfigSpec * specs,
        int argc,
        const char **argv,
        char *widgRec,
        int flags);

/* rbcGraph.c */
    MODULE_SCOPE RbcGraph *RbcGraphFromObject(
        Tcl_Object object);
    MODULE_SCOPE void RbcEventuallyRedrawGraph(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcGraphInstCmdProc(
        ClientData clientData,
        Tcl_Interp * interp,
        int argc,
        const char *argv[]);
    MODULE_SCOPE void RbcLayoutGraph(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDrawGraph(
        RbcGraph * graphPtr,
        Drawable drawable,
        int backingStore);
    MODULE_SCOPE RbcGraph *RbcGetGraphFromWindowData(
        Tk_Window tkwin);
    MODULE_SCOPE int RbcGraphType(
        RbcGraph * graphPtr);

/* rbcGrAxis.c */
    MODULE_SCOPE double RbcInvHMap(
        RbcGraph * graphPtr,
        RbcAxis * axisPtr,
        double x);
    MODULE_SCOPE double RbcInvVMap(
        RbcGraph * graphPtr,
        RbcAxis * axisPtr,
        double x);
    MODULE_SCOPE double RbcHMap(
        RbcGraph * graphPtr,
        RbcAxis * axisPtr,
        double x);
    MODULE_SCOPE double RbcVMap(
        RbcGraph * graphPtr,
        RbcAxis * axisPtr,
        double y);
    MODULE_SCOPE RbcPoint2D RbcMap2D(
        RbcGraph * graphPtr,
        double x,
        double y,
        RbcAxis2D * pairPtr);
    MODULE_SCOPE RbcPoint2D RbcInvMap2D(
        RbcGraph * graphPtr,
        double x,
        double y,
        RbcAxis2D * pairPtr);
    MODULE_SCOPE void RbcResetAxes(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcGetAxisSegments(
        RbcGraph * graphPtr,
        RbcAxis * axisPtr,
        RbcSegment2D ** segPtrPtr,
        int *nSegmentsPtr);
    MODULE_SCOPE void RbcLayoutMargins(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDestroyAxes(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcDefaultAxes(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcVirtualAxisOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);
    MODULE_SCOPE int RbcAxisOp(
        RbcGraph * graphPtr,
        int margin,
        int argc,
        const char **argv);
    MODULE_SCOPE void RbcMapAxes(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDrawAxes(
        RbcGraph * graphPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcAxesToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcDrawAxisLimits(
        RbcGraph * graphPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcAxisLimitsToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE RbcAxis *RbcGetFirstAxis(
        RbcChain * chainPtr);
    MODULE_SCOPE RbcAxis *RbcNearestAxis(
        RbcGraph * graphPtr,
        int x,
        int y);
    MODULE_SCOPE ClientData RbcMakeAxisTag(
        RbcGraph * graphPtr,
        const char *tagName);

/* rbcGrBar.c */
    MODULE_SCOPE RbcPen *RbcBarPen(
        const char *penName);
    MODULE_SCOPE RbcElement *RbcBarElement(
        RbcGraph * graphPtr,
        const char *name,
        Tk_Uid type);
    MODULE_SCOPE void RbcInitFreqTable(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcComputeStacks(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcResetStacks(
        RbcGraph * graphPtr);

/* rbcGrElem.c */
    MODULE_SCOPE double RbcFindElemVectorMinimum(
        RbcElemVector * vecPtr,
        double minLimit);
    MODULE_SCOPE void RbcFreePalette(
        RbcGraph * graphPtr,
        RbcChain * palette);
    MODULE_SCOPE int RbcStringToStyles(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        const char *string,
        char *widgRec,
        int offset);
    MODULE_SCOPE const char *RbcStylesToString(
        ClientData clientData,
        Tk_Window tkwin,
        char *widgRec,
        int offset,
        Tcl_FreeProc ** freeProcPtr);
    MODULE_SCOPE RbcPenStyle **RbcStyleMap(
        RbcElement * elemPtr);
    MODULE_SCOPE void RbcMapErrorBars(
        RbcGraph * graphPtr,
        RbcElement * elemPtr,
        RbcPenStyle ** dataToStyle);
    MODULE_SCOPE void RbcDestroyElements(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcMapElements(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDrawElements(
        RbcGraph * graphPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcDrawActiveElements(
        RbcGraph * graphPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcElementsToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcActiveElementsToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE int RbcGraphUpdateNeeded(
        RbcGraph * graphPtr);
    MODULE_SCOPE ClientData RbcMakeElementTag(
        RbcGraph * graphPtr,
        const char *tagName);
    MODULE_SCOPE int RbcElementOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv,
        Tk_Uid classUid);

/* rbcGrGrid.c */
    MODULE_SCOPE void RbcMapGrid(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDrawGrid(
        RbcGraph * graphPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcGridToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcDestroyGrid(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcCreateGrid(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcGridOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);

/* rbcGrHairs.c */
    MODULE_SCOPE void RbcConfigureCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcEnableCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDisableCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcUpdateCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDestroyCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcCreateCrosshairs(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcCrosshairsOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);

/* rbcGrLegd.c */
    MODULE_SCOPE void RbcMapLegend(
        RbcLegend * legendPtr,
        int width,
        int height);
    MODULE_SCOPE void RbcDrawLegend(
        RbcLegend * legendPtr,
        Drawable drawable);
    MODULE_SCOPE void RbcLegendToPostScript(
        RbcLegend * legendPtr,
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcDestroyLegend(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcCreateLegend(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcLegendOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);
    MODULE_SCOPE int RbcLegendSite(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendWidth(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendHeight(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendIsHidden(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendIsRaised(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendX(
        RbcLegend * legendPtr);
    MODULE_SCOPE int RbcLegendY(
        RbcLegend * legendPtr);
    MODULE_SCOPE void RbcLegendRemoveElement(
        RbcLegend * legendPtr,
        RbcElement * elemPtr);

/* rbcGrLine.c */
    MODULE_SCOPE RbcPen *RbcLinePen(
        const char *penName);
    MODULE_SCOPE RbcElement *RbcLineElement(
        RbcGraph * graphPtr,
        const char *name,
        Tk_Uid classUid);

/* rbcGrMarker.c */
    MODULE_SCOPE ClientData RbcMakeMarkerTag(
        RbcGraph * graphPtr,
        const char *tagName);
    MODULE_SCOPE int RbcMarkerOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);
    MODULE_SCOPE void RbcMarkersToPostScript(
        RbcGraph * graphPtr,
        RbcPsToken * psToken,
        int under);
    MODULE_SCOPE void RbcDrawMarkers(
        RbcGraph * graphPtr,
        Drawable drawable,
        int under);
    MODULE_SCOPE void RbcMapMarkers(
        RbcGraph * graphPtr);
    MODULE_SCOPE void RbcDestroyMarkers(
        RbcGraph * graphPtr);
    MODULE_SCOPE RbcMarker *RbcNearestMarker(
        RbcGraph * graphPtr,
        int x,
        int y,
        int under);

/* rbcGrMisc.c */
    MODULE_SCOPE int RbcGetXY(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        const char *string,
        int *x,
        int *y);
    MODULE_SCOPE void RbcFreeColorPair(
        RbcColorPair * pairPtr);
    MODULE_SCOPE int RbcPointInSegments(
        RbcPoint2D * samplePtr,
        RbcSegment2D * segments,
        int nSegments,
        double halo);
    MODULE_SCOPE int RbcPointInPolygon(
        RbcPoint2D * samplePtr,
        RbcPoint2D * screenPts,
        int nScreenPts);
    MODULE_SCOPE int RbcRegionInPolygon(
        RbcExtents2D * extsPtr,
        RbcPoint2D * points,
        int nPoints,
        int enclosed);
    MODULE_SCOPE void RbcGraphExtents(
        RbcGraph * graphPtr,
        RbcExtents2D * extsPtr);
    MODULE_SCOPE int RbcLineRectClip(
        RbcExtents2D * extsPtr,
        RbcPoint2D * p,
        RbcPoint2D * q);
    MODULE_SCOPE int RbcPolyRectClip(
        RbcExtents2D * extsPtr,
        RbcPoint2D * inputPts,
        int nInputPts,
        RbcPoint2D * outputPts);
    MODULE_SCOPE RbcPoint2D RbcGetProjection(
        int x,
        int y,
        RbcPoint2D * p,
        RbcPoint2D * q);
    MODULE_SCOPE int RbcAdjustViewport(
        int offset,
        int worldSize,
        int windowSize,
        int scrollUnits,
        int scrollMode);
    MODULE_SCOPE int RbcGetScrollInfo(
        Tcl_Interp * interp,
        int argc,
        char **argv,
        int *offsetPtr,
        int worldSize,
        int windowSize,
        int scrollUnits,
        int scrollMode);
    MODULE_SCOPE int RbcGetScrollInfoFromObj(
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const *objv,
        int *offsetPtr,
        int worldSize,
        int windowSize,
        int scrollUnits,
        int scrollMode);
    MODULE_SCOPE void RbcUpdateScrollbar(
        Tcl_Interp * interp,
        char *scrollCmd,
        double firstFract,
        double lastFract);
    MODULE_SCOPE GC RbcGetPrivateGCFromDrawable(
        Display * display,
        Drawable drawable,
        unsigned long gcMask,
        XGCValues * valuePtr);
    MODULE_SCOPE GC RbcGetPrivateGC(
        Tk_Window tkwin,
        unsigned long gcMask,
        XGCValues * valuePtr);
    MODULE_SCOPE void RbcFreePrivateGC(
        Display * display,
        GC gc);
    MODULE_SCOPE void RbcSetDashes(
        Display * display,
        GC gc,
        RbcDashes * dashesPtr);
    MODULE_SCOPE int RbcSimplifyLine(
        RbcPoint2D * origPts,
        int low,
        int high,
        double tolerance,
        int indices[]);
    MODULE_SCOPE void RbcDraw2DSegments(
        Display * display,
        Drawable drawable,
        GC gc,
        RbcSegment2D * segments,
        int nSegments);
    MODULE_SCOPE int RbcMaxRequestSize(
        Display * display,
        unsigned int elemSize);

/* rbcPen.c */
    MODULE_SCOPE void RbcFreePen(
        RbcGraph * graphPtr,
        RbcPen * penPtr);
    MODULE_SCOPE RbcPen *RbcCreatePen(
        RbcGraph * graphPtr,
        const char *penName,
        Tk_Uid classUid,
        int nOpts,
        const char **options);
    MODULE_SCOPE int RbcGetPen(
        RbcGraph * graphPtr,
        const char *name,
        Tk_Uid classUid,
        RbcPen ** penPtrPtr);
    MODULE_SCOPE void RbcDestroyPens(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcPenOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char **argv);

/* rbcGrPs.c */
    MODULE_SCOPE void RbcDestroyPostScript(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcCreatePostScript(
        RbcGraph * graphPtr);
    MODULE_SCOPE int RbcPostScriptOp(
        RbcGraph * graphPtr,
        Tcl_Interp * interp,
        int argc,
        const char *argv[]);

/* rbcImage.c */
    MODULE_SCOPE RbcColorImage *RbcCreateColorImage(
        int width,
        int height);
    MODULE_SCOPE void RbcFreeColorImage(
        RbcColorImage * image);
    MODULE_SCOPE void RbcGammaCorrectColorImage(
        RbcColorImage * src,
        double newGamma);
    MODULE_SCOPE void RbcColorImageToGreyscale(
        RbcColorImage * image);
    MODULE_SCOPE void RbcColorImageToPhoto(
        Tcl_Interp * interp,
        RbcColorImage * image,
        Tk_PhotoHandle photo);
    MODULE_SCOPE RbcColorImage *RbcPhotoRegionToColorImage(
        Tk_PhotoHandle photo,
        int x,
        int y,
        int width,
        int height);
    MODULE_SCOPE RbcColorImage *RbcPhotoToColorImage(
        Tk_PhotoHandle photo);
    MODULE_SCOPE int RbcGetResampleFilter(
        Tcl_Interp * interp,
        char *filterName,
        RbcResampleFilter ** filterPtrPtr);
    MODULE_SCOPE RbcColorImage *RbcResampleColorImage(
        RbcColorImage * image,
        int destWidth,
        int destHeight,
        RbcResampleFilter * horzFilterPtr,
        RbcResampleFilter * vertFilterPtr);
    MODULE_SCOPE void RbcResamplePhoto(
        Tcl_Interp * interp,
        Tk_PhotoHandle srcPhoto,
        int x,
        int y,
        int width,
        int height,
        Tk_PhotoHandle destPhoto,
        RbcResampleFilter * horzFilterPtr,
        RbcResampleFilter * vertFilterPtr);
    MODULE_SCOPE void RbcResizePhoto(
        Tcl_Interp * interp,
        Tk_PhotoHandle srcPhoto,
        int x,
        int y,
        int width,
        int height,
        Tk_PhotoHandle destPhoto);
    MODULE_SCOPE RbcColorImage *RbcResizeColorImage(
        RbcColorImage * src,
        int x,
        int y,
        int width,
        int height,
        int destWidth,
        int destHeight);
    MODULE_SCOPE RbcColorImage *RbcResizeColorSubimage(
        RbcColorImage * src,
        int x,
        int y,
        int width,
        int height,
        int destWidth,
        int destHeight);
    MODULE_SCOPE RbcColorImage *RbcConvolveColorImage(
        RbcColorImage * srcImage,
        RbcFilter2D * filter);
    MODULE_SCOPE int RbcSnapPhoto(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Drawable drawable,
        int x,
        int y,
        int width,
        int height,
        int destWidth,
        int destHeight,
        const char *photoName,
        double inputGamma);
    MODULE_SCOPE RbcColorImage *RbcRotateColorImage(
        RbcColorImage * image,
        double theta);
    MODULE_SCOPE int RbcQuantizeColorImage(
        RbcColorImage * src,
        RbcColorImage * dest,
        int nColors);
    MODULE_SCOPE RbcRegion2D *RbcSetRegion(
        int x,
        int y,
        int width,
        int height,
        RbcRegion2D * regionPtr);
    MODULE_SCOPE Tk_Image RbcCreateTemporaryImage(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        ClientData clientData);
    MODULE_SCOPE int RbcDestroyTemporaryImage(
        Tcl_Interp * interp,
        Tk_Image tkImage);
    MODULE_SCOPE const char *RbcNameOfImage(
        Tk_Image tkImage);
    MODULE_SCOPE int RbcImageIsDeleted(
        Tk_Image tkImage);

/* rbcParse.c */
    MODULE_SCOPE void RbcExpandParseValue(
        RbcParseValue * parsePtr,
        int needed);
    MODULE_SCOPE int RbcParseNestedCmd(
        Tcl_Interp * interp,
        char *string,
        int flags,
        char **termPtr,
        RbcParseValue * parsePtr);
    MODULE_SCOPE int RbcParseBraces(
        Tcl_Interp * interp,
        char *string,
        char **termPtr,
        RbcParseValue * parsePtr);
    MODULE_SCOPE int RbcParseQuotes(
        Tcl_Interp * interp,
        char *string,
        int termChar,
        int flags,
        char **termPtr,
        RbcParseValue * parsePtr);

/* rbcPs.c */
    MODULE_SCOPE RbcPsToken *RbcGetPsToken(
        Tcl_Interp * interp,
        Tk_Window tkwin);
    MODULE_SCOPE void RbcReleasePsToken(
        RbcPsToken * psToken);
    MODULE_SCOPE char *RbcPostScriptFromToken(
        RbcPsToken * psToken);
    MODULE_SCOPE char *RbcScratchBufferFromToken(
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcAppendToPostScript(
        RbcPsToken * psToken,
        ...);
    MODULE_SCOPE void RbcFormatToPostScript(
        RbcPsToken * psToken,
        ...);
    MODULE_SCOPE void RbcBackgroundToPostScript(
        RbcPsToken * psToken,
        XColor * colorPtr);
    MODULE_SCOPE void RbcForegroundToPostScript(
        RbcPsToken * psToken,
        XColor * colorPtr);
    MODULE_SCOPE void RbcBitmapDataToPostScript(
        RbcPsToken * psToken,
        Display * display,
        Pixmap bitmap,
        int width,
        int height);
    MODULE_SCOPE int RbcColorImageToPsData(
        RbcColorImage * image,
        int nComponents,
        Tcl_DString * resultPtr,
        const char *prefix);
    MODULE_SCOPE void RbcClearBackgroundToPostScript(
        RbcPsToken * psToken);
    MODULE_SCOPE void RbcLineWidthToPostScript(
        RbcPsToken * psToken,
        int lineWidth);
    MODULE_SCOPE void RbcLineDashesToPostScript(
        RbcPsToken * psToken,
        RbcDashes * dashesPtr);
    MODULE_SCOPE void RbcLineAttributesToPostScript(
        RbcPsToken * psToken,
        XColor * colorPtr,
        int lineWidth,
        RbcDashes * dashesPtr,
        int capStyle,
        int joinStyle);
    MODULE_SCOPE void RbcRectangleToPostScript(
        RbcPsToken * psToken,
        double x,
        double y,
        int width,
        int height);
    MODULE_SCOPE void RbcRegionToPostScript(
        RbcPsToken * psToken,
        double x,
        double y,
        int width,
        int height);
    MODULE_SCOPE void RbcPathToPostScript(
        RbcPsToken * psToken,
        RbcPoint2D * screenPts,
        int nScreenPts);
    MODULE_SCOPE void RbcPolygonToPostScript(
        RbcPsToken * psToken,
        RbcPoint2D * screenPts,
        int nScreenPts);
    MODULE_SCOPE void RbcSegmentsToPostScript(
        RbcPsToken * psToken,
        XSegment * segArr,
        int nSegs);
    MODULE_SCOPE void RbcRectanglesToPostScript(
        RbcPsToken * psToken,
        XRectangle * rectArr,
        int nRects);
    MODULE_SCOPE void RbcDraw3DRectangleToPostScript(
        RbcPsToken * psToken,
        Tk_3DBorder border,
        double x,
        double y,
        int width,
        int height,
        int borderWidth,
        int relief);
    MODULE_SCOPE void RbcFill3DRectangleToPostScript(
        RbcPsToken * psToken,
        Tk_3DBorder border,
        double x,
        double y,
        int width,
        int height,
        int borderWidth,
        int relief);
    MODULE_SCOPE void RbcStippleToPostScript(
        RbcPsToken * psToken,
        Display * display,
        Pixmap bitmap);
    MODULE_SCOPE void RbcColorImageToPostScript(
        RbcPsToken * psToken,
        RbcColorImage * image,
        double x,
        double y);
    MODULE_SCOPE void RbcWindowToPostScript(
        RbcPsToken * psToken,
        Tk_Window tkwin,
        double x,
        double y);
    MODULE_SCOPE void RbcPhotoToPostScript(
        RbcPsToken * psToken,
        Tk_PhotoHandle photoToken,
        double x,
        double y);
    MODULE_SCOPE void RbcFontToPostScript(
        RbcPsToken * psToken,
        Tk_Font font);
    MODULE_SCOPE void RbcTextToPostScript(
        RbcPsToken * psToken,
        char *string,
        RbcTextStyle * attrPtr,
        double x,
        double y);
    MODULE_SCOPE void RbcLineToPostScript(
        RbcPsToken * psToken,
        XPoint * pointArr,
        int nPoints);
    MODULE_SCOPE void RbcBitmapToPostScript(
        RbcPsToken * psToken,
        Display * display,
        Pixmap bitmap,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void Rbc2DSegmentsToPostScript(
        RbcPsToken * psToken,
        RbcSegment2D * segments,
        int nSegments);

/* rbcSpline.c */
    MODULE_SCOPE int RbcQuadraticSpline(
        RbcPoint2D * origPts,
        int nOrigPts,
        RbcPoint2D * intpPts,
        int nIntpPts);
    MODULE_SCOPE int RbcNaturalSpline(
        RbcPoint2D * origPts,
        int nOrigPts,
        RbcPoint2D * intpPts,
        int nIntpPts);
    MODULE_SCOPE int RbcSplineInit(
        Tcl_Interp * interp);
    MODULE_SCOPE int RbcNaturalParametricSpline(
        RbcPoint2D * origPts,
        int nOrigPts,
        RbcExtents2D * extsPtr,
        int isClosed,
        RbcPoint2D * intpPts,
        int nIntpPts);
    MODULE_SCOPE int RbcCatromParametricSpline(
        RbcPoint2D * origPts,
        int nOrigPts,
        RbcPoint2D * intpPts,
        int nIntpPts);

/* rbcSwitch.c */
    MODULE_SCOPE int RbcProcessSwitches(
        Tcl_Interp * interp,
        RbcSwitchSpec * specs,
        int argc,
        const char **argv,
        char *record,
        int flags);
    MODULE_SCOPE int RbcProcessObjSwitches(
        Tcl_Interp * interp,
        RbcSwitchSpec * specPtr,
        int objc,
        Tcl_Obj * const *objv,
        char *record,
        int flags);
    MODULE_SCOPE void RbcFreeSwitches(
        RbcSwitchSpec * specs,
        char *record,
        int flags);
    MODULE_SCOPE int RbcSwitchChanged(
        RbcSwitchSpec * specs,
        ...);

/* rbcText.c */
    MODULE_SCOPE RbcTextLayout *RbcGetTextLayout(
        char *string,
        RbcTextStyle * stylePtr);
    MODULE_SCOPE void RbcGetTextExtents(
        RbcTextStyle * stylePtr,
        char *text,
        int *widthPtr,
        int *heightPtr);
    MODULE_SCOPE void RbcGetBoundingBox(
        int width,
        int height,
        double theta,
        double *widthPtr,
        double *heightPtr,
        RbcPoint2D * points);
    MODULE_SCOPE void RbcTranslateAnchor(
        int x,
        int y,
        int width,
        int height,
        Tk_Anchor anchor,
        int *transXPtr,
        int *transYPtr);
    MODULE_SCOPE RbcPoint2D RbcTranslatePoint(
        RbcPoint2D * pointPtr,
        int width,
        int height,
        Tk_Anchor anchor);
    MODULE_SCOPE void RbcInitTextStyle(
        RbcTextStyle * stylePtr);
    MODULE_SCOPE void RbcSetDrawTextStyle(
        RbcTextStyle * stylePtr,
        Tk_Font font,
        GC gc,
        XColor * normalColor,
        XColor * activeColor,
        XColor * shadowColor,
        double theta,
        Tk_Anchor anchor,
        Tk_Justify justify,
        int leader,
        int shadowOffset);
    MODULE_SCOPE void RbcSetPrintTextStyle(
        RbcTextStyle * stylePtr,
        Tk_Font font,
        XColor * fgColor,
        XColor * bgColor,
        XColor * shadowColor,
        double theta,
        Tk_Anchor anchor,
        Tk_Justify justify,
        int leader,
        int shadowOffset);
    MODULE_SCOPE void RbcDrawTextLayout(
        Tk_Window tkwin,
        Drawable drawable,
        RbcTextLayout * textPtr,
        RbcTextStyle * stylePtr,
        int x,
        int y);
    MODULE_SCOPE void RbcDrawText2(
        Tk_Window tkwin,
        Drawable drawable,
        char *string,
        RbcTextStyle * stylePtr,
        int x,
        int y,
        RbcDim2D * dimPtr);
    MODULE_SCOPE void RbcDrawText(
        Tk_Window tkwin,
        Drawable drawable,
        char *string,
        RbcTextStyle * stylePtr,
        int x,
        int y);
    MODULE_SCOPE GC RbcGetBitmapGC(
        Tk_Window tkwin);
    MODULE_SCOPE void RbcResetTextStyle(
        Tk_Window tkwin,
        RbcTextStyle * stylePtr);
    MODULE_SCOPE void RbcFreeTextStyle(
        Display * display,
        RbcTextStyle * stylePtr);

/* rbcTile.c */
    MODULE_SCOPE int RbcGetTile(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        const char *imageName,
        RbcTile * tilePtr);
    MODULE_SCOPE void RbcFreeTile(
        RbcTile tile);
    MODULE_SCOPE const char *RbcNameOfTile(
        RbcTile tile);
    Pixmap RbcPixmapOfTile(
        RbcTile tile);
    MODULE_SCOPE void RbcSizeOfTile(
        RbcTile tile,
        int *widthPtr,
        int *heightPtr);
    MODULE_SCOPE void RbcSetTileChangedProc(
        RbcTile tile,
        RbcTileChangedProc * changeProc,
        ClientData clientData);
    MODULE_SCOPE void RbcSetTileOrigin(
        Tk_Window tkwin,
        RbcTile tile,
        int x,
        int y);
    MODULE_SCOPE void RbcSetTSOrigin(
        Tk_Window tkwin,
        RbcTile tile,
        int x,
        int y);
    MODULE_SCOPE void RbcTilePolygon(
        Tk_Window tkwin,
        Drawable drawable,
        RbcTile tile,
        XPoint * pointArr,
        int nPoints);
    MODULE_SCOPE void RbcTileRectangle(
        Tk_Window tkwin,
        Drawable drawable,
        RbcTile tile,
        int x,
        int y,
        unsigned int width,
        unsigned int height);
    MODULE_SCOPE void RbcTileRectangles(
        Tk_Window tkwin,
        Drawable drawable,
        RbcTile tile,
        XRectangle * rectArr,
        int nRects);

/* rbcUtil.c */
    MODULE_SCOPE void *RbcCalloc(
        unsigned int nElem,
        size_t size);
    MODULE_SCOPE char *RbcStrdup(
        const char *ptr);
    MODULE_SCOPE RbcOp RbcGetOp(
        Tcl_Interp * interp,
        int nSpecs,
        RbcOpSpec * specArr,
        int operPos,
        int argc,
        const char **argv,
        int flags);
    MODULE_SCOPE RbcOp RbcGetOpFromObj(
        Tcl_Interp * interp,
        int nSpecs,
        RbcOpSpec * specArr,
        int operPos,
        int objc,
        Tcl_Obj * const *objv,
        int flags);

/* rbcVecMath.c */
    MODULE_SCOPE void RbcVectorInstallMathFunctions(
        Tcl_HashTable * tablePtr);
    MODULE_SCOPE void RbcVectorInstallSpecialIndices(
        Tcl_HashTable * tablePtr);
    MODULE_SCOPE double RbcVecMin(
        Rbc_Vector * vecPtr);
    MODULE_SCOPE double RbcVecMax(
        Rbc_Vector * vecPtr);
    MODULE_SCOPE int RbcExprVector(
        Tcl_Interp * interp,
        char *string,
        Rbc_Vector * vecPtr);

/* rbcVecObjCmd.c */
    MODULE_SCOPE int RbcAppendOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcArithOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcBinreadOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcClearOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcDeleteOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcDupOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcExprOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcIndexOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcLengthOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcMergeOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcNormalizeOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcOffsetOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcPopulateOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcRandomOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcRangeOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcSearchOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcSeqOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcSetOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcSortOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcSplitOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int RbcVariableOp(
        RbcVectorObject * vPtr,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int *RbcVectorSortIndex(
        RbcVectorObject ** vPtrPtr,
        int nVectors);

/* rbcVector.c */
    MODULE_SCOPE double Rbcdrand48(
        void);
    MODULE_SCOPE RbcVectorInterpData *RbcVectorGetInterpData(
        Tcl_Interp * interp);
    MODULE_SCOPE RbcVectorObject *RbcVectorNew(
        RbcVectorInterpData * dataPtr);
    MODULE_SCOPE RbcVectorObject *RbcVectorCreate(
        RbcVectorInterpData * dataPtr,
        const char *vecName,
        const char *cmdName,
        const char *varName,
        int *newPtr);
    MODULE_SCOPE void Rbc_VectorFree(
        RbcVectorObject * vPtr);
    MODULE_SCOPE int RbcVectorDuplicate(
        RbcVectorObject * destPtr,
        RbcVectorObject * srcPtr);
    MODULE_SCOPE void RbcVectorFlushCache(
        RbcVectorObject * vPtr);
    MODULE_SCOPE int RbcVectorMapVariable(
        Tcl_Interp * interp,
        RbcVectorObject * vPtr,
        const char *name);
    MODULE_SCOPE int RbcVectorReset(
        RbcVectorObject * vPtr,
        double *valueArr,
        int length,
        int size,
        Tcl_FreeProc * freeProc);
    MODULE_SCOPE int RbcVectorNotifyPending(
        RbcVectorId clientId);
    MODULE_SCOPE int RbcVectorChangeLength(
        RbcVectorObject * vPtr,
        int length);
    MODULE_SCOPE int RbcVectorLookupName(
        RbcVectorInterpData * dataPtr,
        const char *vecName,
        RbcVectorObject ** vPtrPtr);
    MODULE_SCOPE void RbcVectorUpdateRange(
        RbcVectorObject * vPtr);
    MODULE_SCOPE int RbcVectorGetIndex(
        Tcl_Interp * interp,
        RbcVectorObject * vPtr,
        const char *string,
        int *indexPtr,
        int flags,
        Rbc_VectorIndexProc ** procPtrPtr);
    MODULE_SCOPE int RbcVectorGetIndexRange(
        Tcl_Interp * interp,
        RbcVectorObject * vPtr,
        const char *string,
        int flags,
        Rbc_VectorIndexProc ** procPtrPtr);
    RbcVectorObject *RbcVectorParseElement(
        Tcl_Interp * interp,
        RbcVectorInterpData * dataPtr,
        const char *start,
        char **endPtr,
        int flags);
    MODULE_SCOPE void RbcVectorUpdateClients(
        RbcVectorObject * vPtr);
    MODULE_SCOPE Tcl_Obj *RbcGetValues(
        RbcVectorObject * vPtr,
        int first,
        int last);
    MODULE_SCOPE void RbcReplicateValue(
        RbcVectorObject * vPtr,
        int first,
        int last,
        double value);
    MODULE_SCOPE int RbcGetDouble(
        Tcl_Interp * interp,
        Tcl_Obj * objPtr,
        double *valuePtr);
    MODULE_SCOPE void Rbc_FreeVectorId(
        RbcVectorId clientId);
    MODULE_SCOPE int Rbc_GetVectorById(
        Tcl_Interp * interp,
        RbcVectorId clientId,
        Rbc_Vector ** vecPtrPtr);
    MODULE_SCOPE int Rbc_VectorExists(
        Tcl_Interp * interp,
        const char *vecName);
    MODULE_SCOPE RbcVectorId RbcAllocVectorId(
        Tcl_Interp * interp,
        const char *vecName);
    MODULE_SCOPE void Rbc_SetVectorChangedProc(
        RbcVectorId clientId,
        RbcVectorChangedProc * proc,
        ClientData clientData);
    MODULE_SCOPE char *Rbc_NameOfVectorId(
        RbcVectorId clientId);
    MODULE_SCOPE int Rbc_GetVector(
        Tcl_Interp * interp,
        const char *vecName,
        Rbc_Vector ** vecPtrPtr);
    MODULE_SCOPE int RbcCreateVector2(
        Tcl_Interp * interp,
        const char *vecName,
        const char *cmdName,
        const char *varName,
        int initialSize,
        Rbc_Vector ** vecPtrPtr);
    MODULE_SCOPE int Rbc_CreateVector(
        Tcl_Interp * interp,
        const char *vecName,
        int size,
        Rbc_Vector ** vecPtrPtr);
    MODULE_SCOPE int Rbc_ResizeVector(
        Rbc_Vector * vecPtr,
        int nValues);
    MODULE_SCOPE char *RbcNameOfVector(
        Rbc_Vector * vecPtr);
    MODULE_SCOPE int Rbc_ResetVector(
        Rbc_Vector * vecPtr,
        double *dataArr,
        int nValues,
        int arraySize,
        Tcl_FreeProc * freeProc);

/* rbcWindow.c */
    MODULE_SCOPE Tk_Window RbcFindChild(
        Tk_Window parent,
        char *name);
    MODULE_SCOPE void RbcSetWindowInstanceData(
        Tk_Window tkwin,
        ClientData instanceData);
    MODULE_SCOPE ClientData RbcGetWindowInstanceData(
        Tk_Window tkwin);
    MODULE_SCOPE void RbcDeleteWindowInstanceData(
        Tk_Window tkwin);

/* rbcWinImage.c rbcUnixImage.c */
    MODULE_SCOPE RbcColorImage *RbcDrawableToColorImage(
        Tk_Window tkwin,
        Drawable drawable,
        int x,
        int y,
        int width,
        int height,
        double inputGamma);
    MODULE_SCOPE Pixmap RbcPhotoImageMask(
        Tk_Window tkwin,
        Tk_PhotoImageBlock src);
    MODULE_SCOPE Pixmap RbcRotateBitmap(
        Tk_Window tkwin,
        Pixmap bitmap,
        int width,
        int height,
        double theta,
        int *widthPtr,
        int *heightPtr);
    MODULE_SCOPE Pixmap RbcScaleBitmap(
        Tk_Window tkwin,
        Pixmap srcBitmap,
        int srcWidth,
        int srcHeight,
        int scaledWidth,
        int scaledHeight);
    MODULE_SCOPE Pixmap RbcScaleRotateBitmapRegion(
        Tk_Window tkwin,
        Pixmap srcBitmap,
        unsigned int srcWidth,
        unsigned int srcHeight,
        int regionX,
        int regionY,
        unsigned int regionWidth,
        unsigned int regionHeight,
        unsigned int virtWidth,
        unsigned int virtHeight,
        double theta);

/* Windows */
#ifdef _WIN32
#include "tkoRbcWin.h"
#endif

#ifndef _WIN32
#define PurifyPrintf  printf
#endif                         /* _WIN32 */

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

/*
 * end block for C++
 */

#ifdef __cplusplus
}
#endif
#endif                         /* _TKOGRAPH_H */
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphAxis.c.


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define AXIS_CONFIG_MAJOR (1<<4)        /* User specified major tick intervals. */
#define AXIS_CONFIG_MINOR (1<<5)        /* User specified minor tick intervals. */
#define AXIS_ONSCREEN	  (1<<6)        /* Axis is displayed on the screen via
                                         * the "use" operation */
#define AXIS_DIRTY	  (1<<7)
#define AXIS_ALLOW_NULL   (1<<12)

#define DEF_NUM_TICKS		10      /* Each major tick is 10% */
#define STATIC_TICK_SPACE	10

#define TICK_LABEL_SIZE		200
#define MAXTICKS		10001

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

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

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

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

#define HORIZMARGIN(m)	(!((m)->site & 0x1))    /* Even sites are horizontal */

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

/*
 * TickLabel --
 *
 * 	Structure containing the X-Y screen coordinates of the tick
 * 	label (anchored at its center).
 */
typedef struct {
    RbcPoint2D anchorPos;
    int width, height;
    char string[1];
} TickLabel;

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

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcPositiveDistanceOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcListOption;

static Tk_OptionParseProc StringToLimit;
static Tk_OptionPrintProc LimitToString;
static Tk_OptionParseProc StringToTicks;
static Tk_OptionPrintProc TicksToString;
static Tk_OptionParseProc StringToAxis;
static Tk_OptionPrintProc AxisToString;
static Tk_OptionParseProc StringToAnyAxis;
static Tk_OptionParseProc StringToFormat;
static Tk_OptionPrintProc FormatToString;
static Tk_OptionParseProc StringToLoose;
static Tk_OptionPrintProc LooseToString;

static Tk_CustomOption limitOption = {
    StringToLimit, LimitToString, (ClientData) 0
};

static Tk_CustomOption majorTicksOption = {
    StringToTicks, TicksToString, (ClientData) AXIS_CONFIG_MAJOR,
};

static Tk_CustomOption minorTicksOption = {
    StringToTicks, TicksToString, (ClientData) AXIS_CONFIG_MINOR,
};

Tk_CustomOption rbcXAxisOption = {
    StringToAxis, AxisToString, (ClientData) & rbcXAxisUid
};

Tk_CustomOption rbcYAxisOption = {
    StringToAxis, AxisToString, (ClientData) & rbcYAxisUid
};

Tk_CustomOption rbcAnyXAxisOption = {
    StringToAnyAxis, AxisToString, (ClientData) & rbcXAxisUid
};

Tk_CustomOption rbcAnyYAxisOption = {
    StringToAnyAxis, AxisToString, (ClientData) & rbcYAxisUid
};

static Tk_CustomOption formatOption = {
    StringToFormat, FormatToString, (ClientData) 0,
};

static Tk_CustomOption looseOption = {
    StringToLoose, LooseToString, (ClientData) 0,
};

/* Axis flags: */

#define DEF_AXIS_COMMAND            (char *)NULL
#define DEF_AXIS_DESCENDING         "no"
#define DEF_AXIS_FOREGROUND         "black"
#define DEF_AXIS_FG_MONO            "black"
#define DEF_AXIS_HIDE               "no"
#define DEF_AXIS_JUSTIFY            "center"
#define DEF_AXIS_LIMITS_FORMAT      (char *)NULL
#define DEF_AXIS_LINE_WIDTH         "1"
#define DEF_AXIS_LOGSCALE           "no"
#define DEF_AXIS_LOOSE              "no"
#define DEF_AXIS_RANGE              "0.0"
#define DEF_AXIS_ROTATE             "0.0"
#define DEF_AXIS_SCROLL_INCREMENT   "10"
#define DEF_AXIS_SHIFTBY            "0.0"
#define DEF_AXIS_SHOWTICKS          "yes"
#define DEF_AXIS_STEP               "0.0"
#define DEF_AXIS_STEP               "0.0"
#define DEF_AXIS_SUBDIVISIONS       "2"
#define DEF_AXIS_TAGS               "all"
#define DEF_AXIS_TICKS              "0"
#define DEF_AXIS_TICK_FONT          RBC_FONT_SMALL
#define DEF_AXIS_TICK_LENGTH        "8"
#define DEF_AXIS_TITLE_ALTERNATE    "0"
#define DEF_AXIS_TITLE_FG           "black"
#define DEF_AXIS_TITLE_FONT         RBC_FONT
#define DEF_AXIS_X_STEP_BARCHART    "1.0"
#define DEF_AXIS_X_SUBDIVISIONS_BARCHART    "0"
#define DEF_AXIS_BACKGROUND         (char *)NULL
#define DEF_AXIS_BORDERWIDTH        "0"
#define DEF_AXIS_RELIEF             "flat"

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_DOUBLE, "-autorange", "autoRange", "AutoRange", DEF_AXIS_RANGE,
            Tk_Offset(RbcAxis, windowSize),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_AXIS_BACKGROUND, Tk_Offset(RbcAxis, border),
        RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags", DEF_AXIS_TAGS,
            Tk_Offset(RbcAxis, tags), RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK,
        &rbcListOption},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *)NULL, (char *)NULL, 0,
        RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_AXIS_BORDERWIDTH, Tk_Offset(RbcAxis, borderWidth),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_AXIS_FOREGROUND,
            Tk_Offset(RbcAxis, tickTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_AXIS_FG_MONO,
            Tk_Offset(RbcAxis, tickTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_STRING, "-command", "command", "Command", DEF_AXIS_COMMAND,
        Tk_Offset(RbcAxis, formatCmd), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS},
    {TK_CONFIG_BOOLEAN, "-descending", "descending", "Descending",
            DEF_AXIS_DESCENDING, Tk_Offset(RbcAxis, descending),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_AXIS_HIDE,
            Tk_Offset(RbcAxis, hidden),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", DEF_AXIS_JUSTIFY,
            Tk_Offset(RbcAxis, titleTextStyle.justify),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-labeloffset", "labelOffset", "LabelOffset",
        (char *)NULL, Tk_Offset(RbcAxis, labelOffset), RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color",
            DEF_AXIS_FOREGROUND, Tk_Offset(RbcAxis, limitsTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color", DEF_AXIS_FG_MONO,
            Tk_Offset(RbcAxis, limitsTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-limitsfont", "limitsFont", "Font", DEF_AXIS_TICK_FONT,
        Tk_Offset(RbcAxis, limitsTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-limitsformat", "limitsFormat", "LimitsFormat",
            (char *)NULL, Tk_Offset(RbcAxis, limitsFormats),
        TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &formatOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, limitsTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, limitsTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_AXIS_LINE_WIDTH, Tk_Offset(RbcAxis, lineWidth),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-logscale", "logScale", "LogScale", DEF_AXIS_LOGSCALE,
            Tk_Offset(RbcAxis, logScale),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-loose", "loose", "Loose", DEF_AXIS_LOOSE, 0,
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &looseOption},
    {TK_CONFIG_CUSTOM, "-majorticks", "majorTicks", "MajorTicks", (char *)NULL,
            Tk_Offset(RbcAxis, t1Ptr), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &majorTicksOption},
    {TK_CONFIG_CUSTOM, "-max", "max", "Max", (char *)NULL, Tk_Offset(RbcAxis,
            reqMax), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &limitOption},
    {TK_CONFIG_CUSTOM, "-min", "min", "Min", (char *)NULL, Tk_Offset(RbcAxis,
            reqMin), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS, &limitOption},
    {TK_CONFIG_CUSTOM, "-minorticks", "minorTicks", "MinorTicks", (char *)NULL,
            Tk_Offset(RbcAxis, t2Ptr), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &minorTicksOption},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_AXIS_RELIEF,
            Tk_Offset(RbcAxis, relief),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-rotate", "rotate", "Rotate", DEF_AXIS_ROTATE,
            Tk_Offset(RbcAxis, tickTextStyle.theta),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-scrollcommand", "scrollCommand", "ScrollCommand",
            (char *)NULL, Tk_Offset(RbcAxis, scrollCmdPrefix),
        RBC_ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-scrollincrement", "scrollIncrement", "ScrollIncrement",
            DEF_AXIS_SCROLL_INCREMENT, Tk_Offset(RbcAxis, scrollUnits),
            RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPositiveDistanceOption},
    {TK_CONFIG_CUSTOM, "-scrollmax", "scrollMax", "ScrollMax", (char *)NULL,
            Tk_Offset(RbcAxis, scrollMax), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &limitOption},
    {TK_CONFIG_CUSTOM, "-scrollmin", "scrollMin", "ScrollMin", (char *)NULL,
            Tk_Offset(RbcAxis, scrollMin), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &limitOption},
    {TK_CONFIG_DOUBLE, "-shiftby", "shiftBy", "ShiftBy", DEF_AXIS_SHIFTBY,
            Tk_Offset(RbcAxis, shiftBy),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-showticks", "showTicks", "ShowTicks",
            DEF_AXIS_SHOWTICKS, Tk_Offset(RbcAxis, showTicks),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-stepsize", "stepSize", "StepSize", DEF_AXIS_STEP,
            Tk_Offset(RbcAxis, reqStep),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-tickdivider", "tickDivider", "TickDivider",
            DEF_AXIS_STEP, Tk_Offset(RbcAxis, tickZoom),
        RBC_ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_INT, "-subdivisions", "subdivisions", "Subdivisions",
            DEF_AXIS_SUBDIVISIONS, Tk_Offset(RbcAxis, reqNumMinorTicks),
        RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-tickfont", "tickFont", "Font", DEF_AXIS_TICK_FONT,
        Tk_Offset(RbcAxis, tickTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_PIXELS, "-ticklength", "tickLength", "TickLength",
            DEF_AXIS_TICK_LENGTH, Tk_Offset(RbcAxis, tickLength),
        RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, tickTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, tickTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_STRING, "-title", "title", "Title", (char *)NULL,
            Tk_Offset(RbcAxis, title),
        TK_CONFIG_DONT_SET_DEFAULT | TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS},
    {TK_CONFIG_BOOLEAN, "-titlealternate", "titleAlternate", "TitleAlternate",
            DEF_AXIS_TITLE_ALTERNATE, Tk_Offset(RbcAxis, titleAlternate),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "Color", DEF_AXIS_FOREGROUND,
            Tk_Offset(RbcAxis, titleTextStyle.color),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "TitleColor",
            DEF_AXIS_FG_MONO, Tk_Offset(RbcAxis, titleTextStyle.color),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_FONT, "-titlefont", "titleFont", "Font", DEF_AXIS_TITLE_FONT,
        Tk_Offset(RbcAxis, titleTextStyle.font), RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, titleTextStyle.shadow),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow", (char *)NULL,
            Tk_Offset(RbcAxis, titleTextStyle.shadow),
        TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS, &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

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

/* Forward declarations */
static int Round(
    register double x);
static void SetAxisRange(
    RbcAxisRange * rangePtr,
    double min,
    double max);
static int InRange(
    register double x,
    RbcAxisRange * rangePtr);
static int AxisIsHorizontal(
    RbcGraph * graph,
    RbcAxis * axisPtr);
static void FreeLabels(
    RbcChain * chainPtr);
static TickLabel *MakeLabel(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double value);
static void GetDataLimits(
    RbcAxis * axisPtr,
    double min,
    double max);
static void FixAxisRange(
    RbcAxis * axisPtr);
static double NiceNum(
    double x,
    int round);
static RbcTicks *GenerateTicks(
    RbcTickSweep * sweepPtr);
static void LogScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max);
static void LinearScaleAxis(
    RbcAxis * axisPtr,
    double min,
    double max);
static void SweepTicks(
    RbcAxis * axisPtr);
static void ResetTextStyles(
    RbcGraph * graph,
    RbcAxis * axisPtr);
static void DestroyAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr);
static void AxisOffsets(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int margin,
    int axisOffset,
    AxisInfo * infoPtr);
static void MakeAxisLine(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int line,
    RbcSegment2D * segPtr);
static void MakeTick(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double value,
    int tick,
    int line,
    RbcSegment2D * segPtr);
static void MapAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int offset,
    int margin);
static double AdjustViewport(
    double offset,
    double windowSize);
static int GetAxisScrollInfo(
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    double *offsetPtr,
    double windowSize,
    double scrollUnits);
static void DrawAxis(
    RbcGraph * graph,
    Drawable drawable,
    RbcAxis * axisPtr);
static void AxisToPostScript(
    RbcPsToken * psToken,
    RbcAxis * axisPtr);
static void MakeGridLine(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double value,
    RbcSegment2D * segPtr);
static void GetAxisGeometry(
    RbcGraph * graph,
    RbcAxis * axisPtr);
static int GetMarginGeometry(
    RbcGraph * graph,
    RbcMargin * marginPtr);
static void ComputeMargins(
    RbcGraph * graph);
static RbcAxis *CreateAxis(
    RbcGraph * graph,
    const char *name,
    int margin);
static int ConfigureAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr);
static int NameToAxis(
    RbcGraph * graph,
    const char *name,
    RbcAxis ** axisPtrPtr);
static int GetAxis(
    RbcGraph * graph,
    const char *name,
    Tk_Uid classUid,
    RbcAxis ** axisPtrPtr);
static void FreeAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr);

static int BindOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int CgetOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char *argv[]);
static int ConfigureOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char *argv[]);
static int GetOp(
    RbcGraph * graph,
    int argc,
    const char *argv[]);
static int LimitsOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int InvTransformOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int TransformOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int UseOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv);
static int CreateVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int BindVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int CgetVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int ConfigureVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int DeleteVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int InvTransformVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int LimitsVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int NamesVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int TransformVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv);
static int ViewOp(
    RbcGraph * graph,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
Round(
    register double x)
{
    return (int)(x + ((x < 0.0) ? -0.5 : 0.5));
}

/*
 *----------------------------------------------------------------------
 *
 * SetAxisRange --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SetAxisRange(
    RbcAxisRange * rangePtr,
    double min,
    double max)
{
    rangePtr->min = min;
    rangePtr->max = max;
    rangePtr->range = max - min;
    if(FABS(rangePtr->range) < DBL_EPSILON) {
        rangePtr->range = 1.0;
    }
    rangePtr->scale = 1.0 / rangePtr->range;
}

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

        norm = (x - rangePtr->min) * rangePtr->scale;
        return ((norm >= -DBL_EPSILON) && ((norm - 1.0) < DBL_EPSILON));
    }
}

static int
AxisIsHorizontal(
    RbcGraph * graph,
    RbcAxis * axisPtr)
{
    return ((axisPtr->classUid == rbcYAxisUid) == graph->inverted);
}

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

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

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

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

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

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

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

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

    if(axisPtr->limitsFormats != NULL) {
        ckfree((char *)axisPtr->limitsFormats);
    }
    axisPtr->limitsFormats = NULL;
    axisPtr->nFormats = 0;

    if((string == NULL) || (*string == '\0')) {
        return TCL_OK;
    }
    if(Tcl_SplitList(interp, string, &argc, &argv) != TCL_OK) {
        return TCL_ERROR;
    }
    if(argc > 2) {
        Tcl_AppendResult(interp, "too many elements in limits format list \"",
            string, "\"", (char *)NULL);
        ckfree((char *)argv);   /*TODO check really? */
        return TCL_ERROR;
    }
    axisPtr->limitsFormats = argv;
    axisPtr->nFormats = argc;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FormatToString --
 *
 *      Convert the window coordinates into a string.
 *
 * Results:
 *      The string representing the coordinate position is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
FormatToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record */
    int offset,                /* offset of limits field */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcAxis *axisPtr = (RbcAxis *) (widgRec);

    if(axisPtr->nFormats == 0) {
        return "";
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return Tcl_Merge(axisPtr->nFormats, axisPtr->limitsFormats);
}

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

    if((string == NULL) || (*string == '\0')) {
        *limitPtr = rbcNaN;
    } else if(Tcl_ExprDouble(interp, string, limitPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * LimitToString --
 *
 *      Convert the floating point axis limits into a string.
 *
 * Results:
 *      The string representation of the limits is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
LimitToString(
    ClientData clientData,     /* Either LMIN or LMAX */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr)
{
    double limit = *(double *)(widgRec + offset);
    const char *result;

    result = "";
    if(!TclIsNaN(limit)) {
    char string[TCL_DOUBLE_SPACE + 1];
    RbcGraph *graph;

        graph = RbcGetGraphFromWindowData(tkwin);
        Tcl_PrintDouble(graph->interp, limit, string);
        result = RbcStrdup(string);
        if(result == NULL) {
            return "";
        }
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    }
    return result;
}

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

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

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

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

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

    if(ticksPtr == NULL) {
        return "";
    }
    Tcl_DStringInit(&dString);
    graph = RbcGetGraphFromWindowData(tkwin);
    for(i = 0; i < ticksPtr->nTicks; i++) {
        Tcl_PrintDouble(graph->interp, ticksPtr->values[i], string);
        Tcl_DStringAppendElement(&dString, string);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    result = RbcStrdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    return result;
}

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

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

            if(Tcl_GetBoolean(interp, argv[i], &bool) != TCL_OK) {
                ckfree((char *)argv);
                return TCL_ERROR;
            }
            values[i] = bool;
        }
    }
    axisPtr->looseMin = axisPtr->looseMax = values[0];
    if(argc > 1) {
        axisPtr->looseMax = values[1];
    }
    ckfree((char *)argv);
    return TCL_OK;
}

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

    Tcl_DStringInit(&dString);
    if(axisPtr->looseMin == TICK_RANGE_TIGHT) {
        Tcl_DStringAppendElement(&dString, "0");
    } else if(axisPtr->looseMin == TICK_RANGE_LOOSE) {
        Tcl_DStringAppendElement(&dString, "1");
    } else if(axisPtr->looseMin == TICK_RANGE_ALWAYS_LOOSE) {
        Tcl_DStringAppendElement(&dString, "always");
    }
    if(axisPtr->looseMin != axisPtr->looseMax) {
        if(axisPtr->looseMax == TICK_RANGE_TIGHT) {
            Tcl_DStringAppendElement(&dString, "0");
        } else if(axisPtr->looseMax == TICK_RANGE_LOOSE) {
            Tcl_DStringAppendElement(&dString, "1");
        } else if(axisPtr->looseMax == TICK_RANGE_ALWAYS_LOOSE) {
            Tcl_DStringAppendElement(&dString, "always");
        }
    }
    result = RbcStrdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeLabels --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeLabels(
    RbcChain * chainPtr)
{
RbcChainLink *linkPtr;
TickLabel *labelPtr;

    for(linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        labelPtr = RbcChainGetValue(linkPtr);
        ckfree((char *)labelPtr);
    }
    RbcChainReset(chainPtr);
}

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

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

    if(axisPtr->formatCmd != NULL && *(graph->win) != NULL) {
    Tcl_Interp *interp = graph->interp;

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

            Tcl_ResetResult(interp);    /* Clear the interpreter's result. */
        }
    }
    labelPtr = (TickLabel *) ckalloc(sizeof(TickLabel) + strlen(string));
    assert(labelPtr);
    strcpy(labelPtr->string, string);
    labelPtr->anchorPos.x = labelPtr->anchorPos.y = DBL_MAX;
    return labelPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvHMap --
 *
 *      Maps the given screen coordinate back to a graph coordinate.
 *      Called by the graph locater routine.
 *
 * Results:
 *      Returns the graph coordinate value at the given window
 *      y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcInvHMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double x)
{
    double value;

    x = (double)(x - graph->hOffset) * graph->hScale;
    if(axisPtr->descending) {
        x = 1.0 - x;
    }
    value = (x * axisPtr->axisRange.range) + axisPtr->axisRange.min;
    if(axisPtr->logScale) {
        value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvVMap --
 *
 *      Maps the given window y-coordinate back to a graph coordinate
 *      value. Called by the graph locater routine.
 *
 * Results:
 *      Returns the graph coordinate value at the given window
 *      y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcInvVMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double y)
{
    double value;

    y = (double)(y - graph->vOffset) * graph->vScale;
    if(axisPtr->descending) {
        y = 1.0 - y;
    }
    value = ((1.0 - y) * axisPtr->axisRange.range) + axisPtr->axisRange.min;
    if(axisPtr->logScale) {
        value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcHMap --
 *
 *      Map the given graph coordinate value to its axis, returning a window
 *      position.
 *
 * Results:
 *      Returns a double precision number representing the window coordinate
 *      position on the given axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcHMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double x)
{
    if((axisPtr->logScale) && (x != 0.0)) {
        x = log10(FABS(x));
    }
    /* Map graph coordinate to normalized coordinates [0..1] */
    x = (x - axisPtr->axisRange.min) * axisPtr->axisRange.scale;
    if(axisPtr->descending) {
        x = 1.0 - x;
    }
    return (x * graph->hRange + graph->hOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVMap --
 *
 *      Map the given graph coordinate value to its axis, returning a window
 *      position.
 *
 * Results:
 *      Returns a double precision number representing the window coordinate
 *      position on the given axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
double
RbcVMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double y)
{
    if((axisPtr->logScale) && (y != 0.0)) {
        y = log10(FABS(y));
    }
    /* Map graph coordinate to normalized coordinates [0..1] */
    y = (y - axisPtr->axisRange.min) * axisPtr->axisRange.scale;
    if(axisPtr->descending) {
        y = 1.0 - y;
    }
    return (((1.0 - y) * graph->vRange) + graph->vOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcMap2D --
 *
 *      Maps the given graph x,y coordinate values to a window position.
 *
 * Results:
 *      Returns a XPoint structure containing the window coordinates of
 *      the given graph x,y coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
RbcPoint2D
RbcMap2D(
    RbcGraph * graph,
    double x,                  /* Graph x coordinate */
    double y,                  /* Graph y coordinate */
    RbcAxis2D * axesPtr)
{              /* Specifies which axes to use */
RbcPoint2D point;

    if(graph->inverted) {
        point.x = RbcHMap(graph, axesPtr->y, y);
        point.y = RbcVMap(graph, axesPtr->x, x);
    } else {
        point.x = RbcHMap(graph, axesPtr->x, x);
        point.y = RbcVMap(graph, axesPtr->y, y);
    }
    return point;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInvMap2D --
 *
 *      Maps the given window x,y coordinates to graph values.
 *
 * Results:
 *      Returns a structure containing the graph coordinates of
 *      the given window x,y coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
RbcPoint2D
RbcInvMap2D(
    RbcGraph * graph,
    double x,                  /* Window x coordinate */
    double y,                  /* Window y coordinate */
    RbcAxis2D * axesPtr)
{              /* Specifies which axes to use */
RbcPoint2D point;

    if(graph->inverted) {
        point.x = RbcInvVMap(graph, axesPtr->x, y);
        point.y = RbcInvHMap(graph, axesPtr->y, x);
    } else {
        point.x = RbcInvHMap(graph, axesPtr->x, x);
        point.y = RbcInvVMap(graph, axesPtr->y, y);
    }
    return point;
}

/*
 *----------------------------------------------------------------------
 *
 * GetDataLimits --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetDataLimits(
    RbcAxis * axisPtr,
    double min,
    double max)
{
    if(axisPtr->valueRange.min > min) {
        axisPtr->valueRange.min = min;
    }
    if(axisPtr->valueRange.max < max) {
        axisPtr->valueRange.max = max;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * FixAxisRange --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FixAxisRange(
    RbcAxis * axisPtr)
{
double min, max;
    /*
     * When auto-scaling, the axis limits are the bounds of the element
     * data.  If no data exists, set arbitrary limits (wrt to log/linear
     * scale).
     */
    min = axisPtr->valueRange.min;
    max = axisPtr->valueRange.max;

    if(min == DBL_MAX) {
        if(!TclIsNaN(axisPtr->reqMin)) {
            min = axisPtr->reqMin;
        } else {
            min = (axisPtr->logScale) ? 0.001 : 0.0;
        }
    }
    if(max == -DBL_MAX) {
        if(!TclIsNaN(axisPtr->reqMax)) {
            max = axisPtr->reqMax;
        } else {
            max = 1.0;
        }
    }
    if(min >= max) {
double value;

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

            x = FABS(value) * 0.1;
            min = value - x, max = value + x;
        }
    }
    SetAxisRange(&axisPtr->valueRange, min, max);

    /*
     * The axis limits are either the current data range or overridden
     * by the values selected by the user with the -min or -max
     * options.
     */
    axisPtr->min = min;
    axisPtr->max = max;
    if(!TclIsNaN(axisPtr->reqMin)) {
        axisPtr->min = axisPtr->reqMin;
    }
    if(!TclIsNaN(axisPtr->reqMax)) {
        axisPtr->max = axisPtr->reqMax;
    }

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

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

        if(TclIsNaN(axisPtr->reqMin)) {
            axisPtr->min = axisPtr->max - (FABS(axisPtr->max) * 0.1);
        }
        if(TclIsNaN(axisPtr->reqMax)) {
            axisPtr->max = axisPtr->min + (FABS(axisPtr->max) * 0.1);
        }
    }
    /*
     * If a window size is defined, handle auto ranging by shifting
     * the axis limits.
     */
    if((axisPtr->windowSize > 0.0) &&
        (TclIsNaN(axisPtr->reqMin)) && (TclIsNaN(axisPtr->reqMax))) {
        if(axisPtr->shiftBy < 0.0) {
            axisPtr->shiftBy = 0.0;
        }
        max = axisPtr->min + axisPtr->windowSize;
        if(axisPtr->max >= max) {
            if(axisPtr->shiftBy > 0.0) {
                max = UCEIL(axisPtr->max, axisPtr->shiftBy);
            }
            axisPtr->min = max - axisPtr->windowSize;
        }
        axisPtr->max = max;
    }
    if((axisPtr->max != axisPtr->prevMax) || (axisPtr->min != axisPtr->prevMin)) {
        /* Indicate if the axis limits have changed */
        axisPtr->flags |= AXIS_DIRTY;
        /* and save the previous minimum and maximum values */
        axisPtr->prevMin = axisPtr->min;
        axisPtr->prevMax = axisPtr->max;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * NiceNum --
 *
 *      Reference: Paul Heckbert, "Nice Numbers for Graph Labels",
 *             Graphics Gems, pp 61-63.
 *
 *      Finds a "nice" number approximately equal to x.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static double
NiceNum(
    double x,
    int round)
{              /* If non-zero, round. Otherwise take ceiling
                * of value. */
    double expt;               /* Exponent of x */
    double frac;               /* Fractional part of x */
    double nice;               /* Nice, rounded fraction */

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

/*
 *----------------------------------------------------------------------
 *
 * GenerateTicks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static RbcTicks *
GenerateTicks(
    RbcTickSweep * sweepPtr)
{
RbcTicks *ticksPtr;
register int i;

    ticksPtr =
        (RbcTicks *) ckalloc(sizeof(RbcTicks) +
        (sweepPtr->nSteps * sizeof(double)));
    assert(ticksPtr);

    if(sweepPtr->step == 0.0) {
static double logTable[] = {    /* Precomputed log10 values [1..10] */
    0.0,
    0.301029995663981, 0.477121254719662,
    0.602059991327962, 0.698970004336019,
    0.778151250383644, 0.845098040014257,
    0.903089986991944, 0.954242509439325,
    1.0
};
        /* Hack: A zero step indicates to use log values. */
        for(i = 0; i < sweepPtr->nSteps; i++) {
            ticksPtr->values[i] = logTable[i];
        }
    } else {
double value;

        value = sweepPtr->initial;      /* Start from smallest axis tick */
        for(i = 0; i < sweepPtr->nSteps; i++) {
            value = UROUND(value, sweepPtr->step);
            ticksPtr->values[i] = value;
            value += sweepPtr->step;
        }
    }
    ticksPtr->nTicks = sweepPtr->nSteps;
    return ticksPtr;
}

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

    min = (min != 0.0) ? log10(FABS(min)) : 0.0;
    max = (max != 0.0) ? log10(FABS(max)) : 1.0;

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

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

        minorStep = 0.0;        /* This is a special hack to pass
                                 * information to the GenerateTicks
                                 * routine. An interval of 0.0 tells
                                 *      1) this is a minor sweep and
                                 *      2) the axis is log scale.
                                 */
        nMinor = 10;
    }
    if((axisPtr->looseMin == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMin == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMin)))) {
        tickMin = min;
        nMajor++;
    }
    if((axisPtr->looseMax == TICK_RANGE_TIGHT) ||
        ((axisPtr->looseMax == TICK_RANGE_LOOSE) &&
            (!TclIsNaN(axisPtr->reqMax)))) {
        tickMax = max;
    }
    axisPtr->majorSweep.step = majorStep;
    axisPtr->majorSweep.initial = floor(tickMin);
    axisPtr->majorSweep.nSteps = nMajor;
    axisPtr->minorSweep.initial = axisPtr->minorSweep.step = minorStep;
    axisPtr->minorSweep.nSteps = nMinor;

    SetAxisRange(&axisPtr->axisRange, tickMin, tickMax);
}

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

    range = max - min;

    /* Calculate the major tick stepping. */
    if(axisPtr->reqStep > 0.0) {
        /* An interval was designated by the user.  Keep scaling it
         * until it fits comfortably within the current range of the
         * axis.  */
        step = axisPtr->reqStep;
        while((2 * step) >= range) {
            step *= 0.5;
        }
    } else {
        range = NiceNum(range, 0);
        step = NiceNum(range / DEF_NUM_TICKS, 1);
    }

    /* Find the outer tick values. Add 0.0 to prevent getting -0.0. */
    axisMin = tickMin = floor(min / step) * step + 0.0;
    axisMax = tickMax = ceil(max / step) * step + 0.0;

    nTicks = Round((tickMax - tickMin) / step) + 1;
    axisPtr->majorSweep.step = step;
    axisPtr->majorSweep.initial = tickMin;
    axisPtr->majorSweep.nSteps = nTicks;

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

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

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

/*
 *----------------------------------------------------------------------
 *
 * SweepTicks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SweepTicks(
    RbcAxis * axisPtr)
{
    if((axisPtr->flags & AXIS_CONFIG_MAJOR) == 0) {
        if(axisPtr->t1Ptr != NULL) {
            ckfree((char *)axisPtr->t1Ptr);
        }
        axisPtr->t1Ptr = GenerateTicks(&axisPtr->majorSweep);
    }
    if((axisPtr->flags & AXIS_CONFIG_MINOR) == 0) {
        if(axisPtr->t2Ptr != NULL) {
            ckfree((char *)axisPtr->t2Ptr);
        }
        axisPtr->t2Ptr = GenerateTicks(&axisPtr->minorSweep);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcResetAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
void
RbcResetAxes(
    RbcGraph * graph)
{
RbcChainLink *linkPtr;
RbcElement *elemPtr;
RbcAxis *axisPtr;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcExtents2D exts;
double min, max;

    /* FIXME: This should be called whenever the display list of
     *        elements change. Maybe yet another flag INIT_STACKS to
     *        indicate that the element display list has changed.
     *        Needs to be done before the axis limits are set.
     */
    RbcInitFreqTable(graph);
    if((graph->mode == MODE_STACKED) && (graph->nStacks > 0)) {
        RbcComputeStacks(graph);
    }
    /*
     * Step 1:  Reset all axes. Initialize the data limits of the axis to
     *          impossible values.
     */
    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        axisPtr->min = axisPtr->valueRange.min = DBL_MAX;
        axisPtr->max = axisPtr->valueRange.max = -DBL_MAX;
    }

    /*
     * Step 2:  For each element that's to be displayed, get the smallest
     *          and largest data values mapped to each X and Y-axis.  This
     *          will be the axis limits if the user doesn't override them
     *          with -min and -max options.
     */
    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        (*elemPtr->procsPtr->extentsProc) (elemPtr, &exts);
        GetDataLimits(elemPtr->axes.x, exts.left, exts.right);
        GetDataLimits(elemPtr->axes.y, exts.top, exts.bottom);
    }
    /*
     * Step 3:  Now that we know the range of data values for each axis,
     *          set axis limits and compute a sweep to generate tick values.
     */
    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        FixAxisRange(axisPtr);

        /* Calculate min/max tick (major/minor) layouts */
        min = axisPtr->min;
        max = axisPtr->max;
        if((!TclIsNaN(axisPtr->scrollMin)) && (min < axisPtr->scrollMin)) {
            min = axisPtr->scrollMin;
        }
        if((!TclIsNaN(axisPtr->scrollMax)) && (max > axisPtr->scrollMax)) {
            max = axisPtr->scrollMax;
        }
        if(axisPtr->logScale) {
            LogScaleAxis(axisPtr, min, max);
        } else {
            LinearScaleAxis(axisPtr, min, max);
        }

        if((axisPtr->flags & (AXIS_DIRTY | AXIS_ONSCREEN)) ==
            (AXIS_DIRTY | AXIS_ONSCREEN)) {
            graph->flags |= RBC_REDRAW_BACKING_STORE;
        }
    }

    graph->flags &= ~RBC_RESET_AXES;

    /*
     * When any axis changes, we need to layout the entire graph.
     */
    graph->flags |= (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED |
        RBC_MAP_ALL | RBC_REDRAW_WORLD);
}

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

    RbcResetTextStyle(*(graph->win), &axisPtr->titleTextStyle);
    RbcResetTextStyle(*(graph->win), &axisPtr->tickTextStyle);
    RbcResetTextStyle(*(graph->win), &axisPtr->limitsTextStyle);

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

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

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

    flags = RbcGraphType(graph);
    Tk_FreeOptions(configSpecs, (char *)axisPtr, graph->display, flags);
    if(graph->bindTable != NULL) {
        RbcDeleteBindings(graph->bindTable, axisPtr);
    }
    if(axisPtr->linkPtr != NULL) {
        RbcChainDeleteLink(axisPtr->chainPtr, axisPtr->linkPtr);
    }
    if(axisPtr->name != NULL) {
        ckfree((char *)axisPtr->name);
    }
    if(axisPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(axisPtr->hashPtr);
    }
    RbcFreeTextStyle(graph->display, &axisPtr->titleTextStyle);
    RbcFreeTextStyle(graph->display, &axisPtr->limitsTextStyle);
    RbcFreeTextStyle(graph->display, &axisPtr->tickTextStyle);

    if(axisPtr->tickGC != NULL) {
        Tk_FreeGC(graph->display, axisPtr->tickGC);
    }
    if(axisPtr->t1Ptr != NULL) {
        ckfree((char *)axisPtr->t1Ptr);
    }
    if(axisPtr->t2Ptr != NULL) {
        ckfree((char *)axisPtr->t2Ptr);
    }
    if(axisPtr->limitsFormats != NULL) {
        ckfree((char *)axisPtr->limitsFormats);
    }
    FreeLabels(axisPtr->tickLabels);
    RbcChainDestroy(axisPtr->tickLabels);
    if(axisPtr->segments != NULL) {
        ckfree((char *)axisPtr->segments);
    }
    if(axisPtr->tags != NULL) {
        ckfree((char *)axisPtr->tags);
    }
    ckfree((char *)axisPtr);
}

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

    axisPtr->titleTextStyle.theta = titleRotate[margin];

    majorOffset = minorOffset = 0;
    labelOffset = AXIS_TITLE_PAD;
    if(axisPtr->lineWidth > 0) {
        majorOffset = ABS(axisPtr->tickLength);
        minorOffset = 10 * majorOffset / 15;
        labelOffset = majorOffset + AXIS_TITLE_PAD + axisPtr->lineWidth / 2;
    }
    /* Adjust offset for the interior border width and the line width */
    pad = axisPtr->lineWidth + 1;
    if(graph->plotBorderWidth > 0) {
        pad += graph->plotBorderWidth + 1;
    }
    offset = axisOffset + 1 + pad;
    if((margin == RBC_MARGIN_LEFT) || (margin == RBC_MARGIN_TOP)) {
        majorOffset = -majorOffset;
        minorOffset = -minorOffset;
        labelOffset = -labelOffset;
    }
    /*
     * Pre-calculate the x-coordinate positions of the axis, tick labels, and
     * the individual major and minor ticks.
     */
    p = 0;     /* Suppress compiler warning */

    switch (margin) {
    case RBC_MARGIN_TOP:
        p = graph->top - axisOffset - pad;
        if(axisPtr->titleAlternate) {
            x = graph->right + AXIS_TITLE_PAD;
            y = graph->top - axisOffset - (axisPtr->height / 2);
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        } else {
            x = (graph->right + graph->left) / 2;
            y = graph->top - axisOffset - axisPtr->height - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_N;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_S;
        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.left = graph->hOffset - offset - 2;
        axisPtr->region.right = graph->hOffset + graph->hRange + offset - 1;
        axisPtr->region.top = p + labelOffset - 1;
        axisPtr->region.bottom = p;
        axisPtr->titlePos.x = x;
        axisPtr->titlePos.y = y;
        break;

    case RBC_MARGIN_BOTTOM:
        p = graph->bottom + axisOffset + pad;
        if(axisPtr->titleAlternate) {
            x = graph->right + AXIS_TITLE_PAD;
            y = graph->bottom + axisOffset + (axisPtr->height / 2);
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        } else {
            x = (graph->right + graph->left) / 2;
            y = graph->bottom + axisOffset + axisPtr->height + AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_S;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_N;
        offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
        axisPtr->region.left = graph->hOffset - offset - 2;
        axisPtr->region.right = graph->hOffset + graph->hRange + offset - 1;

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

    case RBC_MARGIN_LEFT:
        p = graph->left - axisOffset - pad;
        if(axisPtr->titleAlternate) {
            x = graph->left - axisOffset - (axisPtr->width / 2);
            y = graph->top - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_SW;
        } else {
            x = graph->left - axisOffset - axisPtr->width -
                graph->plotBorderWidth;
            y = (graph->bottom + graph->top) / 2;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_W;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_E;
        axisPtr->region.left = graph->left - offset + labelOffset - 1;
        axisPtr->region.right = graph->left - offset + 2;

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

    case RBC_MARGIN_RIGHT:
        p = graph->right + axisOffset + pad;
        if(axisPtr->titleAlternate) {
            x = graph->right + axisOffset + (axisPtr->width / 2);
            y = graph->top - AXIS_TITLE_PAD;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_SE;
        } else {
            x = graph->right + axisOffset + axisPtr->width + AXIS_TITLE_PAD;
            y = (graph->bottom + graph->top) / 2;
            axisPtr->titleTextStyle.anchor = TK_ANCHOR_E;
        }
        axisPtr->tickTextStyle.anchor = TK_ANCHOR_W;

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

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

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

    if(axisPtr->tickLength < 0) {
    int hold;

        hold = infoPtr->t1;
        infoPtr->t1 = infoPtr->axis;
        infoPtr->axis = hold;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeAxisLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeAxisLine(
    RbcGraph * graph,
    RbcAxis * axisPtr,         /* Axis information */
    int line,
    RbcSegment2D * segPtr)
{
    double min, max;

    min = axisPtr->axisRange.min;
    max = axisPtr->axisRange.max;
    if(axisPtr->logScale) {
        min = EXP10(min);
        max = EXP10(max);
    }
    if(AxisIsHorizontal(graph, axisPtr)) {
        segPtr->p.x = RbcHMap(graph, axisPtr, min);
        segPtr->q.x = RbcHMap(graph, axisPtr, max);
        segPtr->p.y = segPtr->q.y = line;
    } else {
        segPtr->q.x = segPtr->p.x = line;
        segPtr->p.y = RbcVMap(graph, axisPtr, min);
        segPtr->q.y = RbcVMap(graph, axisPtr, max);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeTick --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeTick(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double value,
    int tick,                  /* Lengths of tick. */
    int line,                  /* Lengths of axis line. */
    RbcSegment2D * segPtr)
{
    if(axisPtr->logScale) {
        value = EXP10(value);
    }
    if(AxisIsHorizontal(graph, axisPtr)) {
        segPtr->p.x = segPtr->q.x = RbcHMap(graph, axisPtr, value);
        segPtr->p.y = line;
        segPtr->q.y = tick;
    } else {
        segPtr->p.x = line;
        segPtr->p.y = segPtr->q.y = RbcVMap(graph, axisPtr, value);
        segPtr->q.x = tick;
    }
}

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

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

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

    if(axisPtr->segments != NULL) {
        ckfree((char *)axisPtr->segments);
    }
    nMajorTicks = nMinorTicks = 0;
    if(axisPtr->t1Ptr != NULL) {
        nMajorTicks = axisPtr->t1Ptr->nTicks;
    }
    if(axisPtr->t2Ptr != NULL) {
        nMinorTicks = axisPtr->t2Ptr->nTicks;
    }
    arraySize = 1 + (nMajorTicks * (nMinorTicks + 1));
    segments = (RbcSegment2D *) ckalloc(arraySize * sizeof(RbcSegment2D));
    assert(segments);

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

        isHoriz = AxisIsHorizontal(graph, axisPtr);
        for(i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            t1 = axisPtr->t1Ptr->values[i];
            /* Minor ticks */
            for(j = 0; j < axisPtr->t2Ptr->nTicks; j++) {
                t2 = t1 +
                    (axisPtr->majorSweep.step * axisPtr->t2Ptr->values[j]);
                if(InRange(t2, &axisPtr->axisRange)) {
                    MakeTick(graph, axisPtr, t2, info.t2, info.axis, segPtr);
                    segPtr++;
                }
            }
            if(!InRange(t1, &axisPtr->axisRange)) {
                continue;
            }
            /* Major tick */
            MakeTick(graph, axisPtr, t1, info.t1, info.axis, segPtr);
            segPtr++;
        }

        linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
        labelPos = (double)info.label;

        for(i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            t1 = axisPtr->t1Ptr->values[i];
            if(axisPtr->labelOffset) {
                t1 += axisPtr->majorSweep.step * 0.5;
            }
            if(!InRange(t1, &axisPtr->axisRange)) {
                continue;
            }
            labelPtr = RbcChainGetValue(linkPtr);
            linkPtr = RbcChainNextLink(linkPtr);
            MakeTick(graph, axisPtr, t1, info.t1, info.axis, &seg);
            /* Save tick label X-Y position. */
            if(isHoriz) {
                labelPtr->anchorPos.x = seg.p.x;
                labelPtr->anchorPos.y = labelPos;
            } else {
                labelPtr->anchorPos.x = labelPos;
                labelPtr->anchorPos.y = seg.p.y;
            }
        }
    }
    if(AxisIsHorizontal(graph, axisPtr)) {
        axisPtr->width = graph->right - graph->left;
    } else {
        axisPtr->height = graph->bottom - graph->top;
    }
    axisPtr->segments = segments;
    axisPtr->nSegments = segPtr - segments;
    assert(axisPtr->nSegments <= arraySize);
}

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

/*
 *----------------------------------------------------------------------
 *
 * GetAxisScrollInfo --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetAxisScrollInfo(
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    double *offsetPtr,
    double windowSize,
    double scrollUnits)
{
    char c;
    unsigned int length;
    double offset;
    int count;
    double fract;

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

/*
 * -----------------------------------------------------------------
 *
 * DrawAxis --
 *
 *      Draws the axis, ticks, and labels onto the canvas.
 *
 *      Initializes and passes text attribute information through
 *      TextStyle structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Axis gets drawn on window.
 *
 * -----------------------------------------------------------------
 */
static void
DrawAxis(
    RbcGraph * graph,
    Drawable drawable,
    RbcAxis * axisPtr)
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if(axisPtr->border != NULL) {
        Tk_Fill3DRectangle(*(graph->win), drawable, axisPtr->border,
            axisPtr->region.left + graph->plotBorderWidth,
            axisPtr->region.top + graph->plotBorderWidth,
            axisPtr->region.right - axisPtr->region.left,
            axisPtr->region.bottom - axisPtr->region.top,
            axisPtr->borderWidth, axisPtr->relief);
    }
    if(axisPtr->title != NULL) {
        RbcDrawText(*(graph->win), drawable, axisPtr->title,
            &axisPtr->titleTextStyle, (int)axisPtr->titlePos.x,
            (int)axisPtr->titlePos.y);
    }
    if(axisPtr->scrollCmdPrefix != NULL) {
double viewWidth, viewMin, viewMax;
double worldWidth, worldMin, worldMax;
double fract;
int isHoriz;

        worldMin = axisPtr->valueRange.min;
        worldMax = axisPtr->valueRange.max;
        if(!TclIsNaN(axisPtr->scrollMin)) {
            worldMin = axisPtr->scrollMin;
        }
        if(!TclIsNaN(axisPtr->scrollMax)) {
            worldMax = axisPtr->scrollMax;
        }
        viewMin = axisPtr->min;
        viewMax = axisPtr->max;
        if(viewMin < worldMin) {
            viewMin = worldMin;
        }
        if(viewMax > worldMax) {
            viewMax = worldMax;
        }
        if(axisPtr->logScale) {
            worldMin = log10(worldMin);
            worldMax = log10(worldMax);
            viewMin = log10(viewMin);
            viewMax = log10(viewMax);
        }
        worldWidth = worldMax - worldMin;
        viewWidth = viewMax - viewMin;
        isHoriz = AxisIsHorizontal(graph, axisPtr);

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

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

        for(linkPtr = RbcChainFirstLink(axisPtr->tickLabels); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            /* Draw major tick labels */
            labelPtr = RbcChainGetValue(linkPtr);
            RbcDrawText(*(graph->win), drawable, labelPtr->string,
                &axisPtr->tickTextStyle, (int)labelPtr->anchorPos.x,
                (int)labelPtr->anchorPos.y);
        }
    }
    if((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {
        /* Draw the tick marks and axis line. */
        RbcDraw2DSegments(graph->display, drawable, axisPtr->tickGC,
            axisPtr->segments, axisPtr->nSegments);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * AxisToPostScript --
 *
 *      Generates PostScript output to draw the axis, ticks, and
 *      labels.
 *
 *      Initializes and passes text attribute information through
 *      TextStyle structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      PostScript output is left in graph->interp->result;
 *
 * -----------------------------------------------------------------
 */
static void
AxisToPostScript(
    RbcPsToken * psToken,
    RbcAxis * axisPtr)
{
    if(axisPtr->title != NULL) {
        RbcTextToPostScript(psToken, axisPtr->title, &axisPtr->titleTextStyle,
            axisPtr->titlePos.x, axisPtr->titlePos.y);
    }
    if(axisPtr->showTicks) {
register RbcChainLink *linkPtr;
TickLabel *labelPtr;

        for(linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            labelPtr = RbcChainGetValue(linkPtr);
            RbcTextToPostScript(psToken, labelPtr->string,
                &axisPtr->tickTextStyle, labelPtr->anchorPos.x,
                labelPtr->anchorPos.y);
        }
    }
    if((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {
        RbcLineAttributesToPostScript(psToken, axisPtr->tickTextStyle.color,
            axisPtr->lineWidth, (RbcDashes *) NULL, CapButt, JoinMiter);
        Rbc2DSegmentsToPostScript(psToken, axisPtr->segments,
            axisPtr->nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MakeGridLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
MakeGridLine(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double value,
    RbcSegment2D * segPtr)
{
    if(axisPtr->logScale) {
        value = EXP10(value);
    }
    /* Grid lines run orthogonally to the axis */
    if(AxisIsHorizontal(graph, axisPtr)) {
        segPtr->p.y = graph->top;
        segPtr->q.y = graph->bottom;
        segPtr->p.x = segPtr->q.x = RbcHMap(graph, axisPtr, value);
    } else {
        segPtr->p.x = graph->left;
        segPtr->q.x = graph->right;
        segPtr->p.y = segPtr->q.y = RbcVMap(graph, axisPtr, value);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetAxisSegments --
 *
 *      Assembles the grid lines associated with an axis. Generates
 *      tick positions if necessary (this happens when the axis is
 *      not a logical axis too).
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcGetAxisSegments(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    RbcSegment2D ** segPtrPtr,
    int *nSegmentsPtr)
{
    int needed;
    RbcTicks *t1Ptr, *t2Ptr;
    register int i;
    double value;
    RbcSegment2D *segments, *segPtr;

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

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

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

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

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

/*
 *----------------------------------------------------------------------
 *
 * GetAxisGeometry --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetAxisGeometry(
    RbcGraph * graph,
    RbcAxis * axisPtr)
{
int height;

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

        SweepTicks(axisPtr);

        if(axisPtr->t1Ptr->nTicks < 0) {
            fprintf(stderr, "%s major ticks can't be %d\n",
                axisPtr->name, axisPtr->t1Ptr->nTicks);
            abort();
        }
        if(axisPtr->t1Ptr->nTicks > MAXTICKS) {
            fprintf(stderr, "too big, %s major ticks can't be %d\n",
                axisPtr->name, axisPtr->t1Ptr->nTicks);
            abort();
        }

        maxHeight = maxWidth = 0;
        nLabels = 0;
        for(i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
            x2 = x = axisPtr->t1Ptr->values[i];
            if(axisPtr->labelOffset) {
                x2 += axisPtr->majorSweep.step * 0.5;
            }
            if(!InRange(x2, &axisPtr->axisRange)) {
                continue;
            }
            labelPtr = MakeLabel(graph, axisPtr, x);
            RbcChainAppend(axisPtr->tickLabels, labelPtr);
            nLabels++;
            /*
             * Get the dimensions of each tick label.
             * Remember tick labels can be multi-lined and/or rotated.
             */
            RbcGetTextExtents(&axisPtr->tickTextStyle, labelPtr->string,
                &lw, &lh);
            labelPtr->width = lw;
            labelPtr->height = lh;

            if(axisPtr->tickTextStyle.theta > 0.0) {
double rotWidth, rotHeight;

                RbcGetBoundingBox(lw, lh, axisPtr->tickTextStyle.theta,
                    &rotWidth, &rotHeight, (RbcPoint2D *) NULL);
                lw = ROUND(rotWidth);
                lh = ROUND(rotHeight);
            }
            if(maxWidth < lw) {
                maxWidth = lw;
            }
            if(maxHeight < lh) {
                maxHeight = lh;
            }
        }
        assert(nLabels <= axisPtr->t1Ptr->nTicks);

        /* Because the axis cap style is "CapProjecting", we need to
         * account for an extra 1.5 linewidth at the end of each
         * line.  */

        pad = ((axisPtr->lineWidth * 15) / 10);

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

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

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

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

    isHoriz = HORIZMARGIN(marginPtr);
    /* Count the number of visible axes. */
    count = 0;
    length = width = height = 0;
    for(linkPtr = RbcChainFirstLink(marginPtr->axes); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        axisPtr = RbcChainGetValue(linkPtr);
        if((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
            count++;
            if(graph->flags & RBC_GET_AXIS_GEOMETRY) {
                GetAxisGeometry(graph, axisPtr);
            }
            if((axisPtr->titleAlternate) && (length < axisPtr->titleWidth)) {
                length = axisPtr->titleWidth;
            }
            if(isHoriz) {
                height += axisPtr->height;
            } else {
                width += axisPtr->width;
            }
        }
    }
    /* Enforce a minimum size for margins. */
    if(width < 3) {
        width = 3;
    }
    if(height < 3) {
        height = 3;
    }
    marginPtr->nAxes = count;
    marginPtr->axesTitleLength = length;
    marginPtr->width = width;
    marginPtr->height = height;
    marginPtr->axesOffset = (HORIZMARGIN(marginPtr)) ? height : width;
    return marginPtr->axesOffset;
}

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

    /*
     * Step 1:  Compute the amount of space needed to display the
     *          axes (there many be 0 or more) associated with the
     *          margin.
     */
    top = GetMarginGeometry(graph, &graph->margins[RBC_MARGIN_TOP]);
    bottom = GetMarginGeometry(graph, &graph->margins[RBC_MARGIN_BOTTOM]);
    left = GetMarginGeometry(graph, &graph->margins[RBC_MARGIN_LEFT]);
    right = GetMarginGeometry(graph, &graph->margins[RBC_MARGIN_RIGHT]);

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

    /*
     * Step 3:  Use the current estimate of the plot area to compute
     *          the legend size.  Add it to the proper margin.
     */
    width = graph->width - (insets + left + right);
    height = graph->height - (insets + top + bottom);
    RbcMapLegend(graph->legend, width, height);
    if(!RbcLegendIsHidden(graph->legend)) {
        switch (RbcLegendSite(graph->legend)) {
        case RBC_LEGEND_RIGHT:
            right += RbcLegendWidth(graph->legend) + 2;
            break;
        case RBC_LEGEND_LEFT:
            left += RbcLegendWidth(graph->legend) + 2;
            break;
        case RBC_LEGEND_TOP:
            top += RbcLegendHeight(graph->legend) + 2;
            break;
        case RBC_LEGEND_BOTTOM:
            bottom += RbcLegendHeight(graph->legend) + 2;
            break;
        case RBC_LEGEND_XY:
        case RBC_LEGEND_PLOT:
        case RBC_LEGEND_WINDOW:
            /* Do nothing. */
            break;
        }
    }

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

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

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

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

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

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

    if(top < graph->margins[RBC_MARGIN_LEFT].axesTitleLength) {
        top = graph->margins[RBC_MARGIN_LEFT].axesTitleLength;
    }
    if(right < graph->margins[RBC_MARGIN_BOTTOM].axesTitleLength) {
        right = graph->margins[RBC_MARGIN_BOTTOM].axesTitleLength;
    }
    if(top < graph->margins[RBC_MARGIN_RIGHT].axesTitleLength) {
        top = graph->margins[RBC_MARGIN_RIGHT].axesTitleLength;
    }
    if(right < graph->margins[RBC_MARGIN_TOP].axesTitleLength) {
        right = graph->margins[RBC_MARGIN_TOP].axesTitleLength;
    }

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

    graph->margins[RBC_MARGIN_LEFT].width = left;
    graph->margins[RBC_MARGIN_RIGHT].width = right;
    graph->margins[RBC_MARGIN_TOP].height = top;
    graph->margins[RBC_MARGIN_BOTTOM].height = bottom;

    if(graph->margins[RBC_MARGIN_LEFT].reqSize > 0) {
        graph->margins[RBC_MARGIN_LEFT].width =
            graph->margins[RBC_MARGIN_LEFT].reqSize;
    }
    if(graph->margins[RBC_MARGIN_RIGHT].reqSize > 0) {
        graph->margins[RBC_MARGIN_RIGHT].width =
            graph->margins[RBC_MARGIN_RIGHT].reqSize;
    }
    if(graph->margins[RBC_MARGIN_TOP].reqSize > 0) {
        graph->margins[RBC_MARGIN_TOP].height =
            graph->margins[RBC_MARGIN_TOP].reqSize;
    }
    if(graph->margins[RBC_MARGIN_BOTTOM].reqSize > 0) {
        graph->margins[RBC_MARGIN_BOTTOM].height =
            graph->margins[RBC_MARGIN_BOTTOM].reqSize;
    }
}

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

    ComputeMargins(graph);
    left = graph->margins[RBC_MARGIN_LEFT].width + graph->inset +
        graph->plotBorderWidth;
    right = graph->margins[RBC_MARGIN_RIGHT].width + graph->inset +
        graph->plotBorderWidth;
    top = graph->margins[RBC_MARGIN_TOP].height + graph->inset +
        graph->plotBorderWidth;
    bottom = graph->margins[RBC_MARGIN_BOTTOM].height + graph->inset +
        graph->plotBorderWidth;

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

    graph->vOffset = top + graph->padY.side1;   /*top */
    graph->vRange = height - RbcPadding(graph->padY);
    graph->hOffset = left + graph->padX.side1 /*left */ ;
    graph->hRange = width - RbcPadding(graph->padX);

    if(graph->vRange < 1) {
        graph->vRange = 1;
    }
    if(graph->hRange < 1) {
        graph->hRange = 1;
    }
    graph->hScale = 1.0 / (double)graph->hRange;
    graph->vScale = 1.0 / (double)graph->vRange;

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

}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureAxis --
 *
 *      Configures axis attributes (font, line width, label, etc).
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Axis layout is deferred until the height and width of the
 *      window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr)
{
char errMsg[200];

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

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

        RbcGetTextExtents(&axisPtr->titleTextStyle, axisPtr->title, &w, &h);
        axisPtr->titleWidth = (short int)w;
        axisPtr->titleHeight = (short int)h;
    }

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

    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateAxis --
 *
 *      Create and initialize a structure containing information to
 *      display a graph axis.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static RbcAxis *
CreateAxis(
    RbcGraph * graph,
    const char *name,          /* Identifier for axis. */
    int margin)
{
    RbcAxis *axisPtr;
    Tcl_HashEntry *hPtr;
    int isNew;
    if(graph->win == NULL || *(graph->win) == NULL)
        return NULL;

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

        axisPtr->name = RbcStrdup(name);
        axisPtr->hashPtr = hPtr;
        axisPtr->classUid = NULL;
        axisPtr->looseMin = axisPtr->looseMax = TICK_RANGE_TIGHT;
        axisPtr->reqNumMinorTicks = 2;
        axisPtr->scrollUnits = 10;
        axisPtr->showTicks = TRUE;
        axisPtr->reqMin = axisPtr->reqMax = rbcNaN;
        axisPtr->scrollMin = axisPtr->scrollMax = rbcNaN;

        if((graph->classUid == rbcBarElementUid) &&
            ((margin == RBC_MARGIN_TOP) || (margin == RBC_MARGIN_BOTTOM))) {
            axisPtr->reqStep = 1.0;
            axisPtr->reqNumMinorTicks = 0;
        }
        if((margin == RBC_MARGIN_RIGHT) || (margin == RBC_MARGIN_TOP)) {
            axisPtr->hidden = TRUE;
        }
        RbcInitTextStyle(&axisPtr->titleTextStyle);
        RbcInitTextStyle(&axisPtr->limitsTextStyle);
        RbcInitTextStyle(&axisPtr->tickTextStyle);
        axisPtr->tickLabels = RbcChainCreate();
        axisPtr->lineWidth = 1;
        axisPtr->tickTextStyle.padX.side1 = 2;
        axisPtr->tickTextStyle.padX.side2 = 2;
        Tcl_SetHashValue(hPtr, axisPtr);
    }
    return axisPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NameToAxis(
    RbcGraph * graph,          /* Graph widget record. */
    const char *name,          /* Name of the axis to be searched for. */
    RbcAxis ** axisPtrPtr)
{              /* (out) Pointer to found axis structure. */
    Tcl_HashEntry *hPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    hPtr = Tcl_FindHashEntry(&graph->axes.table, name);
    if(hPtr != NULL) {
    RbcAxis *axisPtr;

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

/*
 *----------------------------------------------------------------------
 *
 * GetAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetAxis(
    RbcGraph * graph,
    const char *axisName,
    Tk_Uid classUid,
    RbcAxis ** axisPtrPtr)
{
    RbcAxis *axisPtr;

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

/*
 *----------------------------------------------------------------------
 *
 * FreeAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeAxis(
    RbcGraph * graph,
    RbcAxis * axisPtr)
{
    axisPtr->refCount--;
    if((axisPtr->deletePending) && (axisPtr->refCount == 0)) {
        DestroyAxis(graph, axisPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyAxes(
    RbcGraph * graph)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcAxis *axisPtr;
int i;

    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        axisPtr->hashPtr = NULL;
        DestroyAxis(graph, axisPtr);
    }
    Tcl_DeleteHashTable(&graph->axes.table);
    for(i = 0; i < 4; i++) {
        RbcChainDestroy(graph->axisChain[i]);
    }
    Tcl_DeleteHashTable(&graph->axes.tagTable);
    RbcChainDestroy(graph->axes.displayList);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDefaultAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcDefaultAxes(
    RbcGraph * graph)
{
register int i;
RbcAxis *axisPtr;
RbcChain *chainPtr;
static const char *axisNames[4] = { "x", "y", "x2", "y2" };
int flags;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    flags = RbcGraphType(graph);
    for(i = 0; i < 4; i++) {
        chainPtr = RbcChainCreate();
        graph->axisChain[i] = chainPtr;

        /* Create a default axis for each chain. */
        axisPtr = CreateAxis(graph, axisNames[i], i);
        if(axisPtr == NULL) {
            return TCL_ERROR;
        }
        axisPtr->refCount = 1;  /* Default axes are assumed in use. */
        axisPtr->classUid = (i & 1) ? rbcYAxisUid : rbcXAxisUid;
        axisPtr->flags |= AXIS_ONSCREEN;

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

/*----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,
    const char **argv)
{
    Tcl_Interp *interp = graph->interp;

    return RbcConfigureBindings(interp, graph->bindTable,
        RbcMakeAxisTag(graph, axisPtr->name), argc, argv);
}

/*
 * ----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *      Return value is a standard Tcl result.  If querying configuration
 *      values, interp->result will contain the results.
 *
 * Side Effects:
 *      TODO: SIde Effects
 *
 * ----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,                  /* Not used. */
    const char *argv[])
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;
    return Tk_ConfigureValue(graph->interp, *(graph->win), configSpecs,
        (char *)axisPtr, argv[0], RbcGraphType(graph));
}

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

    flags = TK_CONFIG_ARGV_ONLY | RbcGraphType(graph);
    if(argc == 0) {
        return Tk_ConfigureInfo(graph->interp, *(graph->win), configSpecs,
            (char *)axisPtr, (char *)NULL, flags);
    } else if(argc == 1) {
        return Tk_ConfigureInfo(graph->interp, *(graph->win), configSpecs,
            (char *)axisPtr, argv[0], flags);
    }
    if(Tk_ConfigureWidget(graph->interp, *(graph->win), configSpecs,
            argc, argv, (char *)axisPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    if(ConfigureAxis(graph, axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(axisPtr->flags & AXIS_ONSCREEN) {
        if(!RbcConfigModified(configSpecs, "-*color", "-background", "-bg",
                (char *)NULL)) {
            graph->flags |= RBC_REDRAW_BACKING_STORE;
        }
        graph->flags |= RBC_DRAW_MARGINS;
        RbcEventuallyRedrawGraph(graph);
    }
    return TCL_OK;
}

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

    axisPtr = (RbcAxis *) RbcGetCurrentItem(graph->bindTable);
    /* Report only on axes. */
    if((axisPtr != NULL) &&
        ((axisPtr->classUid == rbcXAxisUid) ||
            (axisPtr->classUid == rbcYAxisUid) ||
            (axisPtr->classUid == NULL))) {
    char c;

        c = argv[3][0];
        if((c == 'c') && (strcmp(argv[3], "current") == 0)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(axisPtr->name, -1));
        } else if((c == 'd') && (strcmp(argv[3], "detail") == 0)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(axisPtr->detail, -1));
        }
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * LimitsOp --
 *
 *      This procedure returns a string representing the axis limits
 *      of the graph.  The format of the string is { left top right bottom}.
 *
 * Results:
 *      Always returns TCL_OK.  The interp->result field is
 *      a list of the graph axis limits.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
LimitsOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,                  /* Not used. */
    const char **argv)
{              /* Not used. */
    Tcl_Interp *interp = graph->interp;
    double min, max;
    char stringDouble[TCL_DOUBLE_SPACE];

    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    if(axisPtr->logScale) {
        min = EXP10(axisPtr->axisRange.min);
        max = EXP10(axisPtr->axisRange.max);
    } else {
        min = axisPtr->axisRange.min;
        max = axisPtr->axisRange.max;
    }
    Tcl_PrintDouble(NULL, min, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    Tcl_PrintDouble(NULL, max, stringDouble);
    Tcl_AppendElement(interp, stringDouble);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvTransformOp --
 *
 *      Maps the given window coordinate into an axis-value.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the axis value. If an error occurred, TCL_ERROR is returned
 *      and interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
InvTransformOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    int argc,                  /* Not used. */
    const char **argv)
{
    int x;                     /* Integer window coordinate */
    double y;                  /* Real graph coordinate */
    char stringDouble[TCL_DOUBLE_SPACE];

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

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

    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    if(Tcl_ExprDouble(graph->interp, argv[0], &x) != TCL_OK) {
        return TCL_ERROR;
    }
    if(AxisIsHorizontal(graph, axisPtr)) {
        x = RbcHMap(graph, axisPtr, x);
    } else {
        x = RbcVMap(graph, axisPtr, x);
    }
    Tcl_SetObjResult(graph->interp, Tcl_NewIntObj((int)x));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * UseOp --
 *
 *      Changes the virtual axis used by the logical axis.
 *
 * Results:
 *      A standard Tcl result.  If the named axis doesn't exist
 *      an error message is put in interp->result.
 *
 *      .g xaxis use "abc def gah"
 *      .g xaxis use [lappend abc [.g axis use]]
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
UseOp(
    RbcGraph * graph,
    RbcAxis * axisPtr,         /* Not used. */
    int argc,
    const char **argv)
{
    RbcChain *chainPtr;
    int nNames;
    const char **names;
    RbcChainLink *linkPtr;
    int i;
    Tk_Uid classUid;
    int margin;

    margin = (int)argv[-1];
    chainPtr = graph->margins[margin].axes;
    if(argc == 0) {
        for(linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            Tcl_AppendElement(graph->interp, axisPtr->name);
        }
        return TCL_OK;
    }
    if((margin == RBC_MARGIN_BOTTOM) || (margin == RBC_MARGIN_TOP)) {
        classUid = (graph->inverted) ? rbcYAxisUid : rbcXAxisUid;
    } else {
        classUid = (graph->inverted) ? rbcXAxisUid : rbcYAxisUid;
    }
    if(Tcl_SplitList(graph->interp, argv[0], &nNames, &names) != TCL_OK) {
        return TCL_ERROR;
    }
    for(linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        axisPtr = RbcChainGetValue(linkPtr);
        axisPtr->linkPtr = NULL;
        axisPtr->flags &= ~AXIS_ONSCREEN;
        /* Clear the axis type if it's not currently used. */
        if(axisPtr->refCount == 0) {
            axisPtr->classUid = NULL;
        }
    }
    RbcChainReset(chainPtr);
    for(i = 0; i < nNames; i++) {
        if(NameToAxis(graph, names[i], &axisPtr) != TCL_OK) {
            ckfree((char *)names);
            return TCL_ERROR;
        }
        if(axisPtr->classUid == NULL) {
            axisPtr->classUid = classUid;
        } else if(axisPtr->classUid != classUid) {
            Tcl_AppendResult(graph->interp, "wrong type axis \"",
                axisPtr->name, "\": can't use ", classUid, " type axis.",
                (char *)NULL);
            ckfree((char *)names);
            return TCL_ERROR;
        }
        if(axisPtr->linkPtr != NULL) {
            /* Move the axis from the old margin's "use" list to the new. */
            RbcChainUnlinkLink(axisPtr->chainPtr, axisPtr->linkPtr);
            RbcChainLinkBefore(chainPtr, axisPtr->linkPtr, (RbcChainLink *) NULL);      /* append on end */
        } else {
            axisPtr->linkPtr = RbcChainAppend(chainPtr, axisPtr);
        }
        axisPtr->chainPtr = chainPtr;
        axisPtr->flags |= AXIS_ONSCREEN;
    }
    graph->flags |=
        (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED | RBC_RESET_AXES);
    /* When any axis changes, we need to layout the entire graph.  */
    graph->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
    RbcEventuallyRedrawGraph(graph);

    ckfree((char *)names);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateVirtualOp --
 *
 *      Creates a new axis.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
CreateVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    RbcAxis *axisPtr;
    int flags;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    axisPtr = CreateAxis(graph, argv[3], RBC_MARGIN_NONE);
    if(axisPtr == NULL) {
        return TCL_ERROR;
    }
    flags = RbcGraphType(graph);
    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win),
            axisPtr->name, "Axis", configSpecs, argc - 4, argv + 4,
            (char *)axisPtr, flags) != TCL_OK) {
        goto error;
    }
    if(ConfigureAxis(graph, axisPtr) != TCL_OK) {
        goto error;
    }
    Tcl_SetResult(graph->interp, axisPtr->name, TCL_VOLATILE);
    return TCL_OK;
  error:
    DestroyAxis(graph, axisPtr);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * BindVirtualOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindVirtualOp(
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    Tcl_Interp *interp = graph->interp;

    if(argc == 3) {
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    char *tagName;

        for(hPtr = Tcl_FirstHashEntry(&graph->axes.tagTable, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tagName = Tcl_GetHashKey(&graph->axes.tagTable, hPtr);
            Tcl_AppendElement(interp, tagName);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graph->bindTable,
        RbcMakeAxisTag(graph, argv[3]), argc - 4, argv + 4);
}

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

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

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

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

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

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

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

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

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

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

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

/*
 * ----------------------------------------------------------------------
 *
 * NamesVirtualOp --
 *
 *      Return a list of the names of all the axes.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
NamesVirtualOp(
    RbcGraph * graph,
    int argc,                  /* Not used. */
    const char **argv)
{              /* Not used. */
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    RbcAxis *axisPtr;
    register int i;

    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if(axisPtr->deletePending) {
            continue;
        }
        if(argc == 3) {
            Tcl_AppendElement(graph->interp, axisPtr->name);
            continue;
        }
        for(i = 3; i < argc; i++) {
            if(Tcl_StringMatch(axisPtr->name, argv[i])) {
                Tcl_AppendElement(graph->interp, axisPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

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

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

/*
 *----------------------------------------------------------------------
 *
 * ViewOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ViewOp(
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    RbcAxis *axisPtr;
    Tcl_Interp *interp = graph->interp;
    double axisOffset, scrollUnits;
    double fract;
    double viewMin, viewMax, worldMin, worldMax;
    double viewWidth, worldWidth;
    char stringDouble[TCL_DOUBLE_SPACE];

    if(NameToAxis(graph, argv[3], &axisPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    worldMin = axisPtr->valueRange.min;
    worldMax = axisPtr->valueRange.max;
    /* Override data dimensions with user-selected limits. */
    if(!TclIsNaN(axisPtr->scrollMin)) {
        worldMin = axisPtr->scrollMin;
    }
    if(!TclIsNaN(axisPtr->scrollMax)) {
        worldMax = axisPtr->scrollMax;
    }
    viewMin = axisPtr->min;
    viewMax = axisPtr->max;
    /* Bound the view within scroll region. */
    if(viewMin < worldMin) {
        viewMin = worldMin;
    }
    if(viewMax > worldMax) {
        viewMax = worldMax;
    }
    if(axisPtr->logScale) {
        worldMin = log10(worldMin);
        worldMax = log10(worldMax);
        viewMin = log10(viewMin);
        viewMax = log10(viewMax);
    }
    worldWidth = worldMax - worldMin;
    viewWidth = viewMax - viewMin;

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

    if(AxisIsHorizontal(graph, axisPtr) != axisPtr->descending) {
        axisOffset = viewMin - worldMin;
        scrollUnits = (double)axisPtr->scrollUnits * graph->hScale;
    } else {
        axisOffset = worldMax - viewMax;
        scrollUnits = (double)axisPtr->scrollUnits * graph->vScale;
    }
    if(argc == 4) {
        /* Note: Bound the fractions between 0.0 and 1.0 to support
         * "canvas"-style scrolling. */
        fract = axisOffset / worldWidth;
        Tcl_PrintDouble(interp, CLAMP(fract, 0.0, 1.0), stringDouble);
        Tcl_AppendElement(interp, stringDouble);
        fract = (axisOffset + viewWidth) / worldWidth;
        Tcl_PrintDouble(interp, CLAMP(fract, 0.0, 1.0), stringDouble);
        Tcl_AppendElement(interp, stringDouble);
        return TCL_OK;
    }
    fract = axisOffset / worldWidth;
    if(GetAxisScrollInfo(interp, argc - 4, argv + 4, &fract,
            viewWidth / worldWidth, scrollUnits) != TCL_OK) {
        return TCL_ERROR;
    }
    if(AxisIsHorizontal(graph, axisPtr) != axisPtr->descending) {
        axisPtr->reqMin = (fract * worldWidth) + worldMin;
        axisPtr->reqMax = axisPtr->reqMin + viewWidth;
    } else {
        axisPtr->reqMax = worldMax - (fract * worldWidth);
        axisPtr->reqMin = axisPtr->reqMax - viewWidth;
    }
    if(axisPtr->logScale) {
        axisPtr->reqMin = EXP10(axisPtr->reqMin);
        axisPtr->reqMax = EXP10(axisPtr->reqMax);
    }
    graph->flags |=
        (RBC_GET_AXIS_GEOMETRY | RBC_LAYOUT_NEEDED | RBC_RESET_AXES);
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcVirtualAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcVirtualAxisOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp proc;
    int result;
    static RbcOpSpec axisOps[] = {
        {"bind", 1, (RbcOp) BindVirtualOp, 3, 6, "axisName sequence command",},
        {"cget", 2, (RbcOp) CgetVirtualOp, 5, 5, "axisName option",},
        {"configure", 2, (RbcOp) ConfigureVirtualOp, 4, 0,
            "axisName ?axisName?... ?option value?...",},
        {"create", 2, (RbcOp) CreateVirtualOp, 4, 0,
            "axisName ?option value?...",},
        {"delete", 1, (RbcOp) DeleteVirtualOp, 3, 0, "?axisName?...",},
        {"get", 1, (RbcOp) GetOp, 4, 4, "name",},
        {"invtransform", 1, (RbcOp) InvTransformVirtualOp, 5, 5,
            "axisName value",},
        {"limits", 1, (RbcOp) LimitsVirtualOp, 4, 4, "axisName",},
        {"names", 1, (RbcOp) NamesVirtualOp, 3, 0, "?pattern?...",},
        {"transform", 1, (RbcOp) TransformVirtualOp, 5, 5, "axisName value",},
        {"view", 1, (RbcOp) ViewOp, 4, 7,
            "axisName ?moveto fract? ?scroll number what?",},
    };
    static int nAxisOps = sizeof(axisOps) / sizeof(RbcOpSpec);

    proc = RbcGetOp(interp, nAxisOps, axisOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    result = (*proc) (graph, argc, argv);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAxisOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcAxisOp(
    RbcGraph * graph,
    int margin,
    int argc,
    const char **argv)
{
    int result;
    RbcOp proc;
    RbcAxis *axisPtr;
    static RbcOpSpec axisOps[] = {
        {"bind", 1, (RbcOp) BindOp, 2, 5, "sequence command",},
        {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
        {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?option value?...",},
        {"invtransform", 1, (RbcOp) InvTransformOp, 4, 4, "value",},
        {"limits", 1, (RbcOp) LimitsOp, 3, 3, "",},
        {"transform", 1, (RbcOp) TransformOp, 4, 4, "value",},
        {"use", 1, (RbcOp) UseOp, 3, 4, "?axisName?",},
    };
    static int nAxisOps = sizeof(axisOps) / sizeof(RbcOpSpec);

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

/*
 *----------------------------------------------------------------------
 *
 * RbcMapAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapAxes(
    RbcGraph * graph)
{
RbcAxis *axisPtr;
RbcChain *chainPtr;
RbcChainLink *linkPtr;
register int margin;
int offset;

    for(margin = 0; margin < 4; margin++) {
        chainPtr = graph->margins[margin].axes;
        offset = 0;
        for(linkPtr = RbcChainFirstLink(chainPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                MapAxis(graph, axisPtr, offset, margin);
                if(AxisIsHorizontal(graph, axisPtr)) {
                    offset += axisPtr->height;
                } else {
                    offset += axisPtr->width;
                }
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawAxes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDrawAxes(
    RbcGraph * graph,
    Drawable drawable)
{
RbcAxis *axisPtr;
RbcChainLink *linkPtr;
register int i;

    for(i = 0; i < 4; i++) {
        for(linkPtr = RbcChainFirstLink(graph->margins[i].axes);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                DrawAxis(graph, drawable, axisPtr);
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAxesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcAxesToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcAxis *axisPtr;
RbcChainLink *linkPtr;
register int i;

    for(i = 0; i < 4; i++) {
        for(linkPtr = RbcChainFirstLink(graph->margins[i].axes);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            axisPtr = RbcChainGetValue(linkPtr);
            if((!axisPtr->hidden) && (axisPtr->flags & AXIS_ONSCREEN)) {
                AxisToPostScript(psToken, axisPtr);
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcDrawAxisLimits --
 *
 *      Draws the min/max values of the axis in the plotting area.
 *      The text strings are formatted according to the "sprintf"
 *      format descriptors in the limitsFormats array.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws the numeric values of the axis limits into the outer
 *      regions of the plotting area.
 *
 * ----------------------------------------------------------------------
 */
void
RbcDrawAxisLimits(
    RbcGraph * graph,
    Drawable drawable)
{
RbcAxis *axisPtr;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcDim2D textDim;
int isHoriz;
char *minPtr, *maxPtr;
const char *minFormat, *maxFormat;
char minString[200], maxString[200];
int vMin, hMin, vMax, hMax;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

#define SPACING 8
    vMin = vMax = graph->left + graph->padX.side1 + 2;
    hMin = hMax = graph->bottom - graph->padY.side2 - 2;        /* Offsets */

    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);

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

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

/*
 *----------------------------------------------------------------------
 *
 * RbcAxisLimitsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcAxisLimitsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcAxis *axisPtr;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
double vMin, hMin, vMax, hMax;
char string[200];
int textWidth, textHeight;
const char *minFmt, *maxFmt;

#define SPACING 8
    vMin = vMax = graph->left + graph->padX.side1 + 2;
    hMin = hMax = graph->bottom - graph->padY.side2 - 2;        /* Offsets */
    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);

        if(axisPtr->nFormats == 0) {
            continue;
        }
        minFmt = maxFmt = axisPtr->limitsFormats[0];
        if(axisPtr->nFormats > 1) {
            maxFmt = axisPtr->limitsFormats[1];
        }
        if(*maxFmt != '\0') {
            sprintf(string, maxFmt, axisPtr->axisRange.max);
            RbcGetTextExtents(&axisPtr->tickTextStyle, string, &textWidth,
                &textHeight);
            if((textWidth > 0) && (textHeight > 0)) {
                if(axisPtr->classUid == rbcXAxisUid) {
                    axisPtr->limitsTextStyle.theta = 90.0;
                    axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SE;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle, (double)graph->right, hMax);
                    hMax -= (textWidth + SPACING);
                } else {
                    axisPtr->limitsTextStyle.theta = 0.0;
                    axisPtr->limitsTextStyle.anchor = TK_ANCHOR_NW;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle, vMax, (double)graph->top);
                    vMax += (textWidth + SPACING);
                }
            }
        }
        if(*minFmt != '\0') {
            sprintf(string, minFmt, axisPtr->axisRange.min);
            RbcGetTextExtents(&axisPtr->tickTextStyle, string, &textWidth,
                &textHeight);
            if((textWidth > 0) && (textHeight > 0)) {
                axisPtr->limitsTextStyle.anchor = TK_ANCHOR_SW;
                if(axisPtr->classUid == rbcXAxisUid) {
                    axisPtr->limitsTextStyle.theta = 90.0;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle, (double)graph->left, hMin);
                    hMin -= (textWidth + SPACING);
                } else {
                    axisPtr->limitsTextStyle.theta = 0.0;
                    RbcTextToPostScript(psToken, string,
                        &axisPtr->limitsTextStyle, vMin, (double)graph->bottom);
                    vMin += (textWidth + SPACING);
                }
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetFirstAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcAxis *
RbcGetFirstAxis(
    RbcChain * chainPtr)
{
RbcChainLink *linkPtr;

    linkPtr = RbcChainFirstLink(chainPtr);
    if(linkPtr == NULL) {
        return NULL;
    }
    return RbcChainGetValue(linkPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcNearestAxis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcAxis *
RbcNearestAxis(
    RbcGraph * graph,
    int x,                     /* Point to be tested */
    int y)
{              /* Point to be tested */
register Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcAxis *axisPtr;
int width, height;
double rotWidth, rotHeight;
RbcPoint2D bbox[5];

    for(hPtr = Tcl_FirstHashEntry(&graph->axes.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        axisPtr = (RbcAxis *) Tcl_GetHashValue(hPtr);
        if((axisPtr->hidden) || (!(axisPtr->flags & AXIS_ONSCREEN))) {
            continue;   /* Don't check hidden axes or axes
                         * that are virtual. */
        }
        if(axisPtr->showTicks) {
register RbcChainLink *linkPtr;
TickLabel *labelPtr;
RbcPoint2D t;

            for(linkPtr = RbcChainFirstLink(axisPtr->tickLabels);
                linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
                labelPtr = RbcChainGetValue(linkPtr);
                RbcGetBoundingBox(labelPtr->width, labelPtr->height,
                    axisPtr->tickTextStyle.theta, &rotWidth, &rotHeight, bbox);
                width = ROUND(rotWidth);
                height = ROUND(rotHeight);
                t = RbcTranslatePoint(&labelPtr->anchorPos, width, height,
                    axisPtr->tickTextStyle.anchor);
                t.x = x - t.x - (width * 0.5);
                t.y = y - t.y - (height * 0.5);

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

            RbcGetTextExtents(&axisPtr->titleTextStyle, axisPtr->title, &width,
                &height);
            RbcGetBoundingBox(width, height, axisPtr->titleTextStyle.theta,
                &rotWidth, &rotHeight, bbox);
            width = ROUND(rotWidth);
            height = ROUND(rotHeight);
            t = RbcTranslatePoint(&axisPtr->titlePos, width, height,
                axisPtr->titleTextStyle.anchor);
            /* Translate the point so that the 0,0 is the upper left
             * corner of the bounding box.  */
            t.x = x - t.x - (width / 2);
            t.y = y - t.y - (height / 2);

            bbox[4] = bbox[0];
            if(RbcPointInPolygon(&t, bbox, 5)) {
                axisPtr->detail = "title";
                return axisPtr;
            }
        }
        if(axisPtr->lineWidth > 0) {    /* Check for the axis region */
            if(RbcPointInRegion(&axisPtr->region, x, y)) {
                axisPtr->detail = "line";
                return axisPtr;
            }
        }
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMakeAxisTag --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
ClientData
RbcMakeAxisTag(
    RbcGraph * graph,
    const char *tagName)
{
Tcl_HashEntry *hPtr;
int isNew;

    hPtr = Tcl_CreateHashEntry(&graph->axes.tagTable, tagName, &isNew);
    assert(hPtr);
    return Tcl_GetHashKey(&graph->axes.tagTable, hPtr);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphBar.c.




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrBar.c --
 *
 *      This module implements barchart elements for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

/*
 * -------------------------------------------------------------------
 *
 * FreqKey --
 *
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    double value;              /* Duplicated abscissa */
    RbcAxis2D axes;            /* Axis mapping of element */
} FreqKey;

typedef struct {
    char *name;                /* Pen style identifier.  If NULL pen
                                * was statically allocated. */
    Tk_Uid classUid;           /* Type of pen */
    char *typeId;              /* String token identifying the type of pen */
    unsigned int flags;        /* Indicates if the pen element is active or
                                * normal */
    int refCount;              /* Reference count for elements using
                                * this pen. */
    Tcl_HashEntry *hashPtr;
    Tk_ConfigSpec *specsPtr;   /* Configuration specifications */

    PenConfigureProc *configProc;
    PenDestroyProc *destroyProc;

    XColor *fgColor;           /* Foreground color of bar */
    Tk_3DBorder border;        /* 3D border and background color */
    int borderWidth;           /* 3D border width of bar */
    int relief;                /* Relief of the bar */
    Pixmap stipple;            /* Stipple */
    GC  gc;                    /* Graphics context */

    /* Error bar attributes. */
    int errorBarShow;          /* Describes which error bars to
                                * display: none, x, y, or * both. */

    int errorBarLineWidth;     /* Width of the error bar segments. */

    int errorBarCapWidth;
    XColor *errorBarColor;     /* Color of the error bar. */

    GC  errorBarGC;            /* Error bar graphics context. */

    /* Show value attributes. */
    int valueShow;             /* Indicates whether to display data value.
                                * Values are x, y, or none. */

    char *valueFormat;         /* A printf format string. */
    RbcTextStyle valueStyle;   /* Text attributes (color, font,
                                * rotation, etc.) of the value. */

} BarPen;

typedef struct {
    RbcElemWeight weight;      /* Weight range where this pen is valid. */

    BarPen *penPtr;            /* Pen to draw */

    RbcSegment2D *xErrorBars;  /* Point to start of this pen's X-error bar
                                * segments in the element's array. */

    RbcSegment2D *yErrorBars;  /* Point to start of this pen's Y-error bar
                                * segments in the element's array. */
    int xErrorBarCnt;          /* # of error bars for this pen. */

    int yErrorBarCnt;          /* # of error bars for this pen. */

    int errorBarCapWidth;      /* Length of the cap ends on each
                                * error bar. */

    int symbolSize;            /* Size of the pen's symbol scaled to the
                                * current graph size. */

    /* Bar chart specific data. */
    XRectangle *rectangles;    /* Indicates starting location in bar
                                * array for this pen. */
    int nRects;                /* Number of bar segments for this pen. */

} BarPenStyle;

typedef struct {
    char *name;                /* Identifier to refer the
                                * element. Used in the "insert",
                                * "delete", or "show", commands. */

    Tk_Uid classUid;           /* Type of element; either
                                * rbcBarElementUid, rbcLineElementUid, or
                                * rbcStripElementUid. */

    RbcGraph *graph;           /* Graph widget of element */
    unsigned int flags;        /* Indicates if the entire element is
                                * active, or if coordinates need to
                                * be calculated */
    char **tags;
    int hidden;                /* If non-zero, don't display the element. */

    Tcl_HashEntry *hashPtr;
    char *label;               /* Label displayed in legend */
    int labelRelief;           /* Relief of label in legend. */

    RbcAxis2D axes;
    RbcElemVector x, y, w;     /* Contains array of numeric values */

    RbcElemVector xError;      /* Relative/symmetric X error values. */
    RbcElemVector yError;      /* Relative/symmetric Y error values. */
    RbcElemVector xHigh, xLow; /* Absolute/asymmetric X-coordinate high/low
                                * error values. */
    RbcElemVector yHigh, yLow; /* Absolute/asymmetric Y-coordinate high/low
                                * error values. */

    int *activeIndices;        /* Array of indices (malloc-ed) that
                                * indicate the data points have been
                                * selected as active (drawn with
                                * "active" colors). */

    int nActiveIndices;        /* Number of active data points. Special
                                * case: if nActiveIndices < 0 and the
                                * active bit is set in "flags", then all
                                * data points are drawn active. */

    RbcElementProcs *procsPtr; /* Class information for bar elements */
    Tk_ConfigSpec *specsPtr;   /* Configuration specifications */

    RbcSegment2D *xErrorBars;  /* Point to start of this pen's X-error bar
                                * segments in the element's array. */
    RbcSegment2D *yErrorBars;  /* Point to start of this pen's Y-error bar
                                * segments in the element's array. */
    int xErrorBarCnt;          /* # of error bars for this pen. */
    int yErrorBarCnt;          /* # of error bars for this pen. */

    int *xErrorToData;         /* Maps individual error bar segments back
                                * to the data point associated with it. */
    int *yErrorToData;         /* Maps individual error bar segments back
                                * to the data point associated with it. */

    int errorBarCapWidth;      /* Length of cap on error bars */

    BarPen *activePenPtr;      /* Standard Pens */
    BarPen *normalPenPtr;

    RbcChain *palette;         /* Chain of pen style information. */

    /* Symbol scaling */
    int scaleSymbols;          /* If non-zero, the symbols will scale
                                * in size as the graph is zoomed
                                * in/out.  */

    double xRange, yRange;     /* Initial X-axis and Y-axis ranges:
                                * used to scale the size of element's
                                * symbol. */
    int state;
    /*
     * Bar specific attributes
     */
    BarPen builtinPen;

    int *rectToData;
    XRectangle *rectangles;    /* Array of rectangles comprising the bar
                                * segments of the element. */
    int nRects;                /* # of visible bar segments for element */

    int padX;                  /* Spacing on either side of bar */
    double barWidth;
    int nActive;

    XRectangle *activeRects;
    int *activeToData;
} Bar;

extern Tk_CustomOption rbcBarPenOption;
extern Tk_CustomOption rbcDataOption;
extern Tk_CustomOption rbcDataPairsOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcListOption;
extern Tk_CustomOption rbcXAxisOption;
extern Tk_CustomOption rbcYAxisOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcFillOption;
extern Tk_CustomOption rbcColorOption;
extern Tk_CustomOption rbcStateOption;

static Tk_OptionParseProc StringToBarMode;
static Tk_OptionPrintProc BarModeToString;

static Tk_CustomOption stylesOption = {
    RbcStringToStyles, RbcStylesToString, (ClientData) sizeof(BarPenStyle)
};

Tk_CustomOption rbcBarModeOption = {
    StringToBarMode, BarModeToString, (ClientData) 0
};

#define DEF_BAR_ACTIVE_PEN          "activeBar"
#define DEF_BAR_AXIS_X              "x"
#define DEF_BAR_AXIS_Y              "y"
#define DEF_BAR_BACKGROUND          "navyblue"
#define DEF_BAR_BG_MONO             "black"
#define DEF_BAR_BORDERWIDTH         "2"
#define DEF_BAR_DATA                (char *)NULL
#define DEF_BAR_ERRORBAR_COLOR      "defcolor"
#define DEF_BAR_ERRORBAR_LINE_WIDTH "1"
#define DEF_BAR_ERRORBAR_CAP_WIDTH  "1"
#define DEF_BAR_FOREGROUND          "blue"
#define DEF_BAR_FG_MONO             "white"
#define DEF_BAR_HIDE                "no"
#define DEF_BAR_LABEL               (char *)NULL
#define DEF_BAR_LABEL_RELIEF        "flat"
#define DEF_BAR_NORMAL_STIPPLE      ""
#define DEF_BAR_RELIEF              "raised"
#define DEF_BAR_SHOW_ERRORBARS      "both"
#define DEF_BAR_STATE               "normal"
#define DEF_BAR_STYLES              ""
#define DEF_BAR_TAGS                "all"
#define DEF_BAR_WIDTH               "0.0"
#define DEF_BAR_DATA                (char *)NULL

#define DEF_PEN_ACTIVE_BACKGROUND   "red"
#define DEF_PEN_ACTIVE_BG_MONO      "white"
#define DEF_PEN_ACTIVE_FOREGROUND   "pink"
#define DEF_PEN_ACTIVE_FG_MONO      "black"
#define DEF_PEN_BORDERWIDTH         "2"
#define DEF_PEN_NORMAL_BACKGROUND   "navyblue"
#define DEF_PEN_NORMAL_BG_MONO      "black"
#define DEF_PEN_NORMAL_FOREGROUND   "blue"
#define DEF_PEN_NORMAL_FG_MONO      "white"
#define DEF_PEN_RELIEF              "raised"
#define DEF_PEN_STIPPLE             ""
#define DEF_PEN_TYPE                "bar"
#define	DEF_PEN_VALUE_ANCHOR        "s"
#define	DEF_PEN_VALUE_COLOR         "black"
#define	DEF_PEN_VALUE_FONT          RBC_FONT_SMALL
#define	DEF_PEN_VALUE_FORMAT        "%g"
#define	DEF_PEN_VALUE_ROTATE        (char *)NULL
#define	DEF_PEN_VALUE_SHADOW        (char *)NULL
#define DEF_PEN_SHOW_VALUES         "no"

#define FreeElemVector(v) \
    if ((v).clientId != NULL) { \
	Rbc_FreeVectorId((v).clientId); \
    } else if ((v).valueArr != NULL) { \
	ckfree((char *)(v).valueArr); \
    }

static Tk_ConfigSpec barPenConfigSpecs[] = {
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_ACTIVE_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_ACTIVE_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_NORMAL_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_PEN_NORMAL_BACKGROUND, Tk_Offset(BarPen, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *)NULL, (char *)NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_PEN_BORDERWIDTH, Tk_Offset(BarPen, borderWidth), RBC_ALL_PENS,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_BAR_ERRORBAR_COLOR, Tk_Offset(BarPen, errorBarColor),
        RBC_ALL_PENS, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_BAR_ERRORBAR_LINE_WIDTH, Tk_Offset(BarPen, errorBarLineWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap", "ErrorBarCap",
            DEF_BAR_ERRORBAR_CAP_WIDTH, Tk_Offset(BarPen, errorBarCapWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *)NULL, (char *)NULL, 0,
        RBC_ALL_PENS},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_ACTIVE_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_ACTIVE_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_ACTIVE_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_ACTIVE_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_NORMAL_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_NORMAL_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_PEN_NORMAL_FOREGROUND, Tk_Offset(BarPen, fgColor),
        RBC_NORMAL_PEN | TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_PEN_RELIEF,
        Tk_Offset(BarPen, relief), RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_BAR_SHOW_ERRORBARS, Tk_Offset(BarPen, errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(BarPen, valueShow),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple", DEF_PEN_STIPPLE,
        Tk_Offset(BarPen, stipple), RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-type", (char *)NULL, (char *)NULL, DEF_PEN_TYPE,
        Tk_Offset(BarPen, typeId), RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR, Tk_Offset(BarPen, valueStyle.anchor),
        RBC_ALL_PENS},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
            DEF_PEN_VALUE_COLOR, Tk_Offset(BarPen, valueStyle.color),
        RBC_ALL_PENS},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont", DEF_PEN_VALUE_FONT,
        Tk_Offset(BarPen, valueStyle.font), RBC_ALL_PENS},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(BarPen, valueFormat),
        RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
            DEF_PEN_VALUE_ROTATE, Tk_Offset(BarPen, valueStyle.theta),
        RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(BarPen, valueStyle.shadow),
        RBC_ALL_PENS, &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static Tk_ConfigSpec barElemConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-activepen", "activePen", "ActivePen",
            DEF_BAR_ACTIVE_PEN, Tk_Offset(Bar, activePenPtr), TK_CONFIG_NULL_OK,
        &rbcBarPenOption},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_BAR_BACKGROUND, Tk_Offset(Bar, builtinPen.border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_BAR_BACKGROUND, Tk_Offset(Bar, builtinPen.border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_DOUBLE, "-barwidth", "barWidth", "BarWidth", DEF_BAR_WIDTH,
        Tk_Offset(Bar, barWidth), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags", DEF_BAR_TAGS,
        Tk_Offset(Bar, tags), TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_BAR_BORDERWIDTH, Tk_Offset(Bar, builtinPen.borderWidth), 0,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_BAR_ERRORBAR_COLOR, Tk_Offset(Bar, builtinPen.errorBarColor), 0,
        &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_BAR_ERRORBAR_LINE_WIDTH, Tk_Offset(Bar,
                builtinPen.errorBarLineWidth), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap", "ErrorBarCap",
            DEF_BAR_ERRORBAR_CAP_WIDTH, Tk_Offset(Bar,
                builtinPen.errorBarCapWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-data", "data", "Data", (char *)NULL, 0, 0,
        &rbcDataPairsOption},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_BAR_FOREGROUND, Tk_Offset(Bar, builtinPen.fgColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_BAR_FOREGROUND, Tk_Offset(Bar, builtinPen.fgColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_STRING, "-label", "label", "Label", DEF_BAR_LABEL, Tk_Offset(Bar,
            label), TK_CONFIG_NULL_OK},
    {TK_CONFIG_RELIEF, "-labelrelief", "labelRelief", "LabelRelief",
            DEF_BAR_LABEL_RELIEF, Tk_Offset(Bar, labelRelief),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_BAR_HIDE, Tk_Offset(Bar,
            hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_BAR_AXIS_X, Tk_Offset(Bar,
            axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_BAR_AXIS_Y, Tk_Offset(Bar,
            axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_CUSTOM, "-pen", "pen", "Pen", (char *)NULL, Tk_Offset(Bar,
            normalPenPtr), TK_CONFIG_NULL_OK, &rbcBarPenOption},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_BAR_RELIEF,
        Tk_Offset(Bar, builtinPen.relief), 0},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_BAR_SHOW_ERRORBARS, Tk_Offset(Bar, builtinPen.errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(Bar, builtinPen.valueShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-state", "state", "State", DEF_BAR_STATE, Tk_Offset(Bar,
            state), TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple", DEF_BAR_NORMAL_STIPPLE,
        Tk_Offset(Bar, builtinPen.stipple), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-styles", "styles", "Styles", DEF_BAR_STYLES,
        Tk_Offset(Bar, palette), TK_CONFIG_NULL_OK, &stylesOption},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR, Tk_Offset(Bar, builtinPen.valueStyle.anchor),
        0},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
            DEF_PEN_VALUE_COLOR, Tk_Offset(Bar, builtinPen.valueStyle.color),
        0},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont", DEF_PEN_VALUE_FONT,
        Tk_Offset(Bar, builtinPen.valueStyle.font), 0},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(Bar, builtinPen.valueFormat),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
            DEF_PEN_VALUE_ROTATE, Tk_Offset(Bar, builtinPen.valueStyle.theta),
        0},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(Bar, builtinPen.valueStyle.shadow),
        0, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-weights", "weights", "Weights", (char *)NULL,
        Tk_Offset(Bar, w), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-x", "xdata", "Xdata", DEF_BAR_DATA, Tk_Offset(Bar, x),
        0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-y", "ydata", "Ydata", DEF_BAR_DATA, Tk_Offset(Bar, y),
        0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xdata", "xdata", "Xdata", DEF_BAR_DATA, Tk_Offset(Bar,
            x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ydata", "ydata", "Ydata", DEF_BAR_DATA, Tk_Offset(Bar,
            y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xerror", "xError", "XError", DEF_BAR_DATA,
        Tk_Offset(Bar, xError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xhigh", "xHigh", "XHigh", DEF_BAR_DATA, Tk_Offset(Bar,
            xHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xlow", "xLow", "XLow", DEF_BAR_DATA, Tk_Offset(Bar,
            xLow), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yerror", "yError", "YError", DEF_BAR_DATA,
        Tk_Offset(Bar, yError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yhigh", "yHigh", "YHigh", DEF_BAR_DATA, Tk_Offset(Bar,
            yHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ylow", "yLow", "YLow", DEF_BAR_DATA, Tk_Offset(Bar,
            yLow), 0, &rbcDataOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* Forward declarations */
static PenConfigureProc ConfigurePen;
static PenDestroyProc DestroyPen;
static RbcElementClosestProc ClosestBar;
static RbcElementConfigProc ConfigureBar;
static RbcElementDestroyProc DestroyBar;
static RbcElementDrawProc DrawActiveBar;
static RbcElementDrawProc DrawNormalBar;
static RbcElementDrawSymbolProc DrawSymbol;
static RbcElementExtentsProc GetBarExtents;
static RbcElementToPostScriptProc ActiveBarToPostScript;
static RbcElementToPostScriptProc NormalBarToPostScript;
static RbcElementSymbolToPostScriptProc SymbolToPostScript;
static RbcElementMapProc MapBar;

static int Round(
    register double x);
static const char *NameOfBarMode(
    RbcBarMode mode);
static void ClearPalette(
    RbcChain * palette);
static void InitPen(
    BarPen * penPtr);
static void CheckStacks(
    RbcGraph * graph,
    RbcAxis2D * pairPtr,
    double *minPtr,
    double *maxPtr);
static void MergePens(
    Bar * barPtr,
    RbcPenStyle ** dataToStyle);
static void MapActiveBars(
    Bar * barPtr);
static void ResetBar(
    Bar * barPtr);
static void DrawBarSegments(
    RbcGraph * graph,
    Drawable drawable,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects);
static void DrawBarValues(
    RbcGraph * graph,
    Drawable drawable,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData);
static void SegmentsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    BarPen * penPtr,
    register XRectangle * rectPtr,
    int nRects);
static void BarValuesToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData);

/*
 *----------------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
Round(
    register double x)
{
    return (int)(x + ((x < 0.0) ? -0.5 : 0.5));
}

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

/*
 * ----------------------------------------------------------------------
 *
 * NameOfBarMode --
 *
 *      Converts the integer representing the mode style into a string.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
NameOfBarMode(
    RbcBarMode mode)
{
    switch (mode) {
    case MODE_INFRONT:
        return "infront";
    case MODE_OVERLAP:
        return "overlap";
    case MODE_STACKED:
        return "stacked";
    case MODE_ALIGNED:
        return "aligned";
    default:
        return "unknown mode value";
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToMode --
 *
 *      Converts the mode string into its numeric representation.
 *
 *      Valid mode strings are:
 *
 *          "infront"   Draw a full bar at each point in the element.
 *
 *      "stacked"   Stack bar segments vertically. Each stack is defined
 *              by each ordinate at a particular abscissa. The height
 *              of each segment is represented by the sum the previous
 *              ordinates.
 *
 *      "aligned"   Align bar segments as smaller slices one next to
 *              the other.  Like "stacks", aligned segments are
 *              defined by each ordinate at a particular abscissa.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
StringToBarMode(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Mode style string */
    char *widgRec,             /* Cubicle structure record */
    int offset)
{              /* Offset of style in record */
    RbcBarMode *modePtr = (RbcBarMode *) (widgRec + offset);
    unsigned int length;
    char c;

    c = string[0];
    length = strlen(string);
    if((c == 'n') && (strncmp(string, "normal", length) == 0)) {
        *modePtr = MODE_INFRONT;
    } else if((c == 'i') && (strncmp(string, "infront", length) == 0)) {
        *modePtr = MODE_INFRONT;
    } else if((c == 's') && (strncmp(string, "stacked", length) == 0)) {
        *modePtr = MODE_STACKED;
    } else if((c == 'a') && (strncmp(string, "aligned", length) == 0)) {
        *modePtr = MODE_ALIGNED;
    } else if((c == 'o') && (strncmp(string, "overlap", length) == 0)) {
        *modePtr = MODE_OVERLAP;
    } else {
        Tcl_AppendResult(interp, "bad mode argument \"", string,
            "\": should be \"infront\", \"stacked\", \"overlap\", or \"aligned\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * BarModeToString --
 *
 *      Returns the mode style string based upon the mode flags.
 *
 * Results:
 *      The mode style string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
BarModeToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Row/column structure record */
    int offset,                /* Offset of mode in Partition record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcBarMode mode = *(RbcBarMode *) (widgRec + offset);

    return NameOfBarMode(mode);
}

/*
 *----------------------------------------------------------------------
 *
 * ClearPalette --
 *
 *      Zero out the style's number of rectangles and errorbars.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ClearPalette(
    RbcChain * palette)
{
register BarPenStyle *stylePtr;
RbcChainLink *linkPtr;

    for(linkPtr = RbcChainFirstLink(palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->xErrorBarCnt = stylePtr->yErrorBarCnt = stylePtr->nRects = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigurePen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ConfigurePen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
BarPen *bpPtr = (BarPen *) penPtr;
XGCValues gcValues;
unsigned long gcMask;
int fillStyle;
GC  newGC;
long defColor;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    RbcResetTextStyle(*(graph->win), &(bpPtr->valueStyle));
    gcMask = GCForeground;
    if(bpPtr->fgColor != NULL) {
        defColor = bpPtr->fgColor->pixel;
        gcValues.foreground = bpPtr->fgColor->pixel;
    } else if(bpPtr->border != NULL) {
        defColor = Tk_3DBorderColor(bpPtr->border)->pixel;
        gcValues.foreground = Tk_3DBorderColor(bpPtr->border)->pixel;
    } else {
        defColor = BlackPixel(graph->display, Tk_ScreenNumber(*(graph->win)));
    }
    if((bpPtr->fgColor != NULL) && (bpPtr->border != NULL)) {
        gcMask |= GCBackground;
        gcValues.background = Tk_3DBorderColor(bpPtr->border)->pixel;
        fillStyle = FillOpaqueStippled;
    } else {
        fillStyle = FillStippled;
    }
    if(bpPtr->stipple != None) {
        gcValues.stipple = bpPtr->stipple;
        gcValues.fill_style = fillStyle;
        gcMask |= (GCStipple | GCFillStyle);
    }
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(bpPtr->gc != NULL) {
        Tk_FreeGC(graph->display, bpPtr->gc);
    }
    bpPtr->gc = newGC;

    gcMask = GCForeground | GCLineWidth;
    if(bpPtr->errorBarColor == RBC_COLOR_DEFAULT) {
        gcValues.foreground = defColor;
    } else {
        gcValues.foreground = bpPtr->errorBarColor->pixel;
    }
    gcValues.line_width = RbcLineWidth(bpPtr->errorBarLineWidth);
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(bpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graph->display, bpPtr->errorBarGC);
    }
    bpPtr->errorBarGC = newGC;

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyPen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
BarPen *bpPtr = (BarPen *) penPtr;

    RbcFreeTextStyle(graph->display, &(bpPtr->valueStyle));
    if(bpPtr->gc != NULL) {
        Tk_FreeGC(graph->display, bpPtr->gc);
    }
    if(bpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graph->display, bpPtr->errorBarGC);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InitPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
InitPen(
    BarPen * penPtr)
{
    RbcInitTextStyle(&(penPtr->valueStyle));
    penPtr->specsPtr = barPenConfigSpecs;
    penPtr->configProc = ConfigurePen;
    penPtr->destroyProc = DestroyPen;
    penPtr->relief = TK_RELIEF_RAISED;
    penPtr->flags = RBC_NORMAL_PEN;
    penPtr->errorBarShow = RBC_SHOW_BOTH;
    penPtr->valueShow = RBC_SHOW_NONE;
    penPtr->borderWidth = 2;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcBarPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcPen *
RbcBarPen(
    const char *penName)
{
    BarPen *penPtr;

    penPtr = RbcCalloc(1, sizeof(BarPen));
    assert(penPtr);
    InitPen(penPtr);
    penPtr->name = RbcStrdup(penName);
    if(strcmp(penName, "activeBar") == 0) {
        penPtr->flags = RBC_ACTIVE_PEN;
    }
    return (RbcPen *) penPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * CheckStacks --
 *
 *      Check that the data limits are not superseded by the heights
 *      of stacked bar segments.  The heights are calculated by
 *      RbcComputeStacks.
 *
 * Results:
 *      If the y-axis limits need to be adjusted for stacked segments,
 *      *minPtr* or *maxPtr* are updated.
 *
 * Side effects:
 *      Autoscaling of the y-axis is affected.
 *
 * ----------------------------------------------------------------------
 */
static void
CheckStacks(
    RbcGraph * graph,
    RbcAxis2D * pairPtr,
    double *minPtr,            /* Current minimum for y-axis */
    double *maxPtr)
{              /* Current maximum for y-axis */
    RbcFreqInfo *infoPtr;
    register int i;

    if((graph->mode != MODE_STACKED) || (graph->nStacks == 0)) {
        return;
    }
    infoPtr = graph->freqArr;
    for(i = 0; i < graph->nStacks; i++) {
        if((infoPtr->axes.x == pairPtr->x) && (infoPtr->axes.y == pairPtr->y)) {
            /*
             * 
             * * Check if any of the y-values (because of stacking) are
             * * greater than the current limits of the graph.
             */
            if(infoPtr->sum < 0.0) {
                if(*minPtr > infoPtr->sum) {
                    *minPtr = infoPtr->sum;
                }
            } else {
                if(*maxPtr < infoPtr->sum) {
                    *maxPtr = infoPtr->sum;
                }
            }
        }
        infoPtr++;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureBar --
 *
 *      Sets up the appropriate configuration parameters in the GC.
 *      It is assumed the parameters have been previously set by
 *      a call to Tk_ConfigureWidget.
 *
 * 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 bar foreground/background
 *      color and stipple etc. get set in a new GC.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureBar(
    RbcGraph * graph,
    register RbcElement * elemPtr)
{
    Bar *barPtr = (Bar *) elemPtr;
    RbcChainLink *linkPtr;

    if(ConfigurePen(graph, (RbcPen *) & (barPtr->builtinPen)) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Point to the static normal pen if no external pens have
     * been selected.
     */
    if(barPtr->normalPenPtr == NULL) {
        barPtr->normalPenPtr = &(barPtr->builtinPen);
    }
    linkPtr = RbcChainFirstLink(barPtr->palette);
    if(linkPtr != NULL) {
    BarPenStyle *stylePtr;

        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->penPtr = barPtr->normalPenPtr;
    }
    if(RbcConfigModified(barPtr->specsPtr, "-barwidth", "-*data",
            "-map*", "-label", "-hide", "-x", "-y", (char *)NULL)) {
        barPtr->flags |= RBC_MAP_ITEM;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetBarExtents --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetBarExtents(
    RbcElement * elemPtr,
    RbcExtents2D * extsPtr)
{
RbcGraph *graph = elemPtr->graphPtr;
Bar *barPtr = (Bar *) elemPtr;
double middle, barWidth;
int nPoints;

    extsPtr->top = extsPtr->left = DBL_MAX;
    extsPtr->bottom = extsPtr->right = -DBL_MAX;

    nPoints = RbcNumberOfPoints(barPtr);
    if(nPoints < 1) {
        return; /* No data points */
    }
    barWidth = graph->barWidth;
    if(barPtr->barWidth > 0.0) {
        barWidth = barPtr->barWidth;
    }
    middle = barWidth * 0.5;
    extsPtr->left = barPtr->x.min - middle;
    extsPtr->right = barPtr->x.max + middle;

    extsPtr->top = barPtr->y.min;
    extsPtr->bottom = barPtr->y.max;
    if(extsPtr->bottom < graph->baseline) {
        extsPtr->bottom = graph->baseline;
    }
    /*
     * Handle "stacked" bar elements specially.
     *
     * If element is stacked, the sum of its ordinates may be outside
     * the minimum/maximum limits of the element's data points.
     */
    if((graph->mode == MODE_STACKED) && (graph->nStacks > 0)) {
        CheckStacks(graph, &(elemPtr->axes), &(extsPtr->top),
            &(extsPtr->bottom));
    }
    /* Warning: You get what you deserve if the x-axis is logScale */
    if(elemPtr->axes.x->logScale) {
        extsPtr->left = RbcFindElemVectorMinimum(&(barPtr->x), DBL_MIN) +
            middle;
    }
    /* Fix y-min limits for barchart */
    if(elemPtr->axes.y->logScale) {
        if((extsPtr->top <= 0.0) || (extsPtr->top > 1.0)) {
            extsPtr->top = 1.0;
        }
    } else {
        if(extsPtr->top > 0.0) {
            extsPtr->top = 0.0;
        }
    }
    /* Correct the extents for error bars if they exist. */
    if(elemPtr->xError.nValues > 0) {
register int i;
double x;

        /* Correct the data limits for error bars */
        nPoints = MIN(elemPtr->xError.nValues, nPoints);
        for(i = 0; i < nPoints; i++) {
            x = elemPtr->x.valueArr[i] + elemPtr->xError.valueArr[i];
            if(x > extsPtr->right) {
                extsPtr->right = x;
            }
            x = elemPtr->x.valueArr[i] - elemPtr->xError.valueArr[i];
            if(elemPtr->axes.x->logScale) {
                if(x < 0.0) {
                    x = -x;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if((x > DBL_MIN) && (x < extsPtr->left)) {
                    extsPtr->left = x;
                }
            } else if(x < extsPtr->left) {
                extsPtr->left = x;
            }
        }
    } else {
        if((elemPtr->xHigh.nValues > 0) &&
            (elemPtr->xHigh.max > extsPtr->right)) {
            extsPtr->right = elemPtr->xHigh.max;
        }
        if(elemPtr->xLow.nValues > 0) {
double left;

            if((elemPtr->xLow.min <= 0.0) && (elemPtr->axes.x->logScale)) {
                left = RbcFindElemVectorMinimum(&elemPtr->xLow, DBL_MIN);
            } else {
                left = elemPtr->xLow.min;
            }
            if(left < extsPtr->left) {
                extsPtr->left = left;
            }
        }
    }
    if(elemPtr->yError.nValues > 0) {
register int i;
double y;

        nPoints = MIN(elemPtr->yError.nValues, nPoints);
        for(i = 0; i < nPoints; i++) {
            y = elemPtr->y.valueArr[i] + elemPtr->yError.valueArr[i];
            if(y > extsPtr->bottom) {
                extsPtr->bottom = y;
            }
            y = elemPtr->y.valueArr[i] - elemPtr->yError.valueArr[i];
            if(elemPtr->axes.y->logScale) {
                if(y < 0.0) {
                    y = -y;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if((y > DBL_MIN) && (y < extsPtr->left)) {
                    extsPtr->top = y;
                }
            } else if(y < extsPtr->top) {
                extsPtr->top = y;
            }
        }
    } else {
        if((elemPtr->yHigh.nValues > 0) &&
            (elemPtr->yHigh.max > extsPtr->bottom)) {
            extsPtr->bottom = elemPtr->yHigh.max;
        }
        if(elemPtr->yLow.nValues > 0) {
double top;

            if((elemPtr->yLow.min <= 0.0) && (elemPtr->axes.y->logScale)) {
                top = RbcFindElemVectorMinimum(&elemPtr->yLow, DBL_MIN);
            } else {
                top = elemPtr->yLow.min;
            }
            if(top < extsPtr->top) {
                extsPtr->top = top;
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ClosestBar --
 *
 *      Find the bar segment closest to the window coordinates	point
 *      specified.
 *
 *      Note:  This does not return the height of the stacked segment
 *             (in graph coordinates) properly.
 *
 * Results:
 *      Returns 1 if the point is width any bar segment, otherwise 0.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
ClosestBar(
    RbcGraph * graph,          /* Graph widget record */
    RbcElement * elemPtr,      /* Bar element */
    RbcClosestSearch * searchPtr)
{              /* Info of closest point in element */
Bar *barPtr = (Bar *) elemPtr;
RbcPoint2D *pointPtr, *endPtr;
RbcPoint2D t, outline[5];
XRectangle *rectPtr;
double left, right, top, bottom;
double minDist, dist;
int imin;
register int i;

    minDist = searchPtr->dist;
    imin = 0;

    rectPtr = barPtr->rectangles;
    for(i = 0; i < barPtr->nRects; i++) {
        /* Point in rectangle */
        if(searchPtr->x <= (int)(rectPtr->x + rectPtr->width - 1)
            && searchPtr->x >= (int)(rectPtr->x)
            && searchPtr->y <= (int)(rectPtr->y + rectPtr->height - 1)
            && searchPtr->y >= (int)(rectPtr->y)) {
            imin = barPtr->rectToData[i];
            minDist = 0.0;
            break;
        }
        left = rectPtr->x, top = rectPtr->y;
        right = (double)(rectPtr->x + rectPtr->width);
        bottom = (double)(rectPtr->y + rectPtr->height);
        outline[4].x = outline[3].x = outline[0].x = left;
        outline[4].y = outline[1].y = outline[0].y = top;
        outline[2].x = outline[1].x = right;
        outline[3].y = outline[2].y = bottom;

        for(pointPtr = outline, endPtr = outline + 4; pointPtr < endPtr;
            pointPtr++) {
            t = RbcGetProjection(searchPtr->x, searchPtr->y,
                pointPtr, pointPtr + 1);
            if(t.x > right) {
                t.x = right;
            } else if(t.x < left) {
                t.x = left;
            }
            if(t.y > bottom) {
                t.y = bottom;
            } else if(t.y < top) {
                t.y = top;
            }
            dist = hypot((t.x - searchPtr->x), (t.y - searchPtr->y));
            if(dist < minDist) {
                minDist = dist;
                imin = barPtr->rectToData[i];
            }
        }
        rectPtr++;
    }
    if(minDist < searchPtr->dist) {
        searchPtr->elemPtr = (RbcElement *) elemPtr;
        searchPtr->dist = minDist;
        searchPtr->index = imin;
        searchPtr->point.x = (double)barPtr->x.valueArr[imin];
        searchPtr->point.y = (double)barPtr->y.valueArr[imin];
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MergePens --
 *
 *      Reorders the both arrays of points and errorbars to merge pens.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The old arrays are freed and new ones allocated containing
 *      the reordered points and errorbars.
 *
 *----------------------------------------------------------------------
 */
static void
MergePens(
    Bar * barPtr,
    RbcPenStyle ** dataToStyle)
{
BarPenStyle *stylePtr;
RbcChainLink *linkPtr;

    if(RbcChainGetLength(barPtr->palette) < 2) {
        linkPtr = RbcChainFirstLink(barPtr->palette);
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->nRects = barPtr->nRects;
        stylePtr->rectangles = barPtr->rectangles;
        stylePtr->symbolSize = barPtr->rectangles->width / 2;
        stylePtr->xErrorBarCnt = barPtr->xErrorBarCnt;
        stylePtr->xErrorBars = barPtr->xErrorBars;
        stylePtr->yErrorBarCnt = barPtr->yErrorBarCnt;
        stylePtr->yErrorBars = barPtr->yErrorBars;
        return;
    }
    /* We have more than one style. Group bar segments of like pen
     * styles together.  */

    if(barPtr->nRects > 0) {
XRectangle *rectangles;
int *rectToData;
int dataIndex;
register XRectangle *rectPtr;
register int *indexPtr;
register int i;

        rectangles =
            (XRectangle *) ckalloc(barPtr->nRects * sizeof(XRectangle));
        rectToData = (int *)ckalloc(barPtr->nRects * sizeof(int));
        assert(rectangles && rectToData);

        rectPtr = rectangles, indexPtr = rectToData;
        for(linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->symbolSize = rectPtr->width / 2;
            stylePtr->rectangles = rectPtr;
            for(i = 0; i < barPtr->nRects; i++) {
                dataIndex = barPtr->rectToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *rectPtr++ = barPtr->rectangles[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->nRects = rectPtr - stylePtr->rectangles;
        }
        ckfree((char *)barPtr->rectangles);
        barPtr->rectangles = rectangles;
        ckfree((char *)barPtr->rectToData);
        barPtr->rectToData = rectToData;
    }
    if(barPtr->xErrorBarCnt > 0) {
RbcSegment2D *errorBars, *segPtr;
int *errorToData, *indexPtr;
int dataIndex;
register int i;

        errorBars =
            (RbcSegment2D *) ckalloc(barPtr->xErrorBarCnt *
            sizeof(RbcSegment2D));
        errorToData = (int *)ckalloc(barPtr->xErrorBarCnt * sizeof(int));
        assert(errorBars);
        segPtr = errorBars, indexPtr = errorToData;
        for(linkPtr = RbcChainFirstLink(barPtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->xErrorBars = segPtr;
            for(i = 0; i < barPtr->xErrorBarCnt; i++) {
                dataIndex = barPtr->xErrorToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = barPtr->xErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->xErrorBarCnt = segPtr - stylePtr->xErrorBars;
        }
        ckfree((char *)barPtr->xErrorBars);
        barPtr->xErrorBars = errorBars;
        ckfree((char *)barPtr->xErrorToData);
        barPtr->xErrorToData = errorToData;
    }
    if(barPtr->yErrorBarCnt > 0) {
RbcSegment2D *errorBars, *segPtr;
int *errorToData, *indexPtr;
int dataIndex;
register int i;

        errorBars =
            (RbcSegment2D *) ckalloc(barPtr->yErrorBarCnt *
            sizeof(RbcSegment2D));
        errorToData = (int *)ckalloc(barPtr->yErrorBarCnt * sizeof(int));
        assert(errorBars);
        segPtr = errorBars, indexPtr = errorToData;
        for(linkPtr = RbcChainFirstLink(barPtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->yErrorBars = segPtr;
            for(i = 0; i < barPtr->yErrorBarCnt; i++) {
                dataIndex = barPtr->yErrorToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = barPtr->yErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->yErrorBarCnt = segPtr - stylePtr->yErrorBars;
        }
        ckfree((char *)barPtr->yErrorBars);
        barPtr->yErrorBars = errorBars;
        ckfree((char *)barPtr->yErrorToData);
        barPtr->yErrorToData = errorToData;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MapActiveBars --
 *
 *      Creates an array of points of the active graph coordinates.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the active point array.
 *
 *----------------------------------------------------------------------
 */
static void
MapActiveBars(
    Bar * barPtr)
{
    if(barPtr->activeRects != NULL) {
        ckfree((char *)barPtr->activeRects);
        barPtr->activeRects = NULL;
    }
    if(barPtr->activeToData != NULL) {
        ckfree((char *)barPtr->activeToData);
        barPtr->activeToData = NULL;
    }
    barPtr->nActive = 0;

    if(barPtr->nActiveIndices > 0) {
XRectangle *activeRects;
int *activeToData;
register int i, n;
register int count;

        activeRects =
            (XRectangle *) ckalloc(sizeof(XRectangle) * barPtr->nActiveIndices);
        assert(activeRects);
        activeToData = (int *)ckalloc(sizeof(int) * barPtr->nActiveIndices);
        assert(activeToData);
        count = 0;
        for(i = 0; i < barPtr->nRects; i++) {
            for(n = 0; n < barPtr->nActiveIndices; n++) {
                if(barPtr->rectToData[i] == barPtr->activeIndices[n]) {
                    activeRects[count] = barPtr->rectangles[i];
                    activeToData[count] = i;
                    count++;
                }
            }
        }
        barPtr->nActive = count;
        barPtr->activeRects = activeRects;
        barPtr->activeToData = activeToData;
    }
    barPtr->flags &= ~RBC_ACTIVE_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * ResetBar --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ResetBar(
    Bar * barPtr)
{
    /* Release any storage associated with the display of the bar */
    ClearPalette(barPtr->palette);
    if(barPtr->activeRects != NULL) {
        ckfree((char *)barPtr->activeRects);
    }
    if(barPtr->activeToData != NULL) {
        ckfree((char *)barPtr->activeToData);
    }
    if(barPtr->xErrorBars != NULL) {
        ckfree((char *)barPtr->xErrorBars);
    }
    if(barPtr->xErrorToData != NULL) {
        ckfree((char *)barPtr->xErrorToData);
    }
    if(barPtr->yErrorBars != NULL) {
        ckfree((char *)barPtr->yErrorBars);
    }
    if(barPtr->yErrorToData != NULL) {
        ckfree((char *)barPtr->yErrorToData);
    }
    if(barPtr->rectangles != NULL) {
        ckfree((char *)barPtr->rectangles);
    }
    if(barPtr->rectToData != NULL) {
        ckfree((char *)barPtr->rectToData);
    }
    barPtr->activeToData = barPtr->xErrorToData = barPtr->yErrorToData =
        barPtr->rectToData = NULL;
    barPtr->activeRects = barPtr->rectangles = NULL;
    barPtr->xErrorBars = barPtr->yErrorBars = NULL;
    barPtr->nActive = barPtr->xErrorBarCnt = barPtr->yErrorBarCnt =
        barPtr->nRects = 0;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapBar --
 *
 *      Calculates the actual window coordinates of the bar element.
 *      The window coordinates are saved in the bar element structure.
 *
 *      A bar can have multiple segments (more than one x,y pairs).
 *      In this case, the bar can be represented as either a set of
 *      non-contiguous bars or a single multi-segmented (stacked) bar.
 *
 *      The x-axis layout for a barchart may be presented in one of
 *      two ways.  If abscissas are used, the bars are placed at those
 *      coordinates.  Otherwise, the range will represent the number
 *      of values.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
MapBar(
    RbcGraph * graph,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;
FreqKey key;
RbcPenStyle **dataToStyle;
RbcPoint2D c1, c2;             /* Two opposite corners of the rectangle
                                * in graph coordinates. */
double *x, *y;
double barWidth, barOffset;
double baseline;
double dx, dy;
int *rectToData;               /* Maps rectangles to data point indices */
int height;
int invertBar;
int nPoints, count;
register XRectangle *rectPtr, *rectangles;
register int i;
int size;
RbcChainLink *linkPtr;
BarPenStyle *stylePtr;

    ResetBar(barPtr);
    nPoints = RbcNumberOfPoints(barPtr);
    if(nPoints < 1) {
        return; /* No data points */
    }
    barWidth = graph->barWidth;
    if(barPtr->barWidth > 0.0) {
        barWidth = barPtr->barWidth;
    }
    baseline = (barPtr->axes.y->logScale) ? 1.0 : graph->baseline;
    barOffset = barWidth * 0.5;

    /*
     * Create an array of rectangles representing the screen coordinates
     * of all the segments in the bar.
     */
    rectPtr = rectangles = (XRectangle *) ckalloc(nPoints * sizeof(XRectangle));
    assert(rectangles);
    rectToData = RbcCalloc(nPoints, sizeof(int));
    assert(rectToData);

    x = barPtr->x.valueArr, y = barPtr->y.valueArr;
    count = 0;
    for(i = 0; i < nPoints; i++) {
        if(((x[i] - barWidth) > barPtr->axes.x->axisRange.max) ||
            ((x[i] + barWidth) < barPtr->axes.x->axisRange.min)) {
            continue;   /* Abscissa is out of range of the x-axis */
        }
        c1.x = x[i] - barOffset;
        c1.y = y[i];
        c2.x = c1.x + barWidth;
        c2.y = baseline;

        /*
         * If the mode is "aligned" or "stacked" we need to adjust the
         * x or y coordinates of the two corners.
         */

        if((graph->nStacks > 0) && (graph->mode != MODE_INFRONT)) {
Tcl_HashEntry *hPtr;

            key.value = x[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_FindHashEntry(&(graph->freqTable), (char *)&key);
            if(hPtr != NULL) {
RbcFreqInfo *infoPtr;
double slice, width;

                infoPtr = (RbcFreqInfo *) Tcl_GetHashValue(hPtr);
                switch (graph->mode) {
                case MODE_STACKED:
                    c2.y = infoPtr->lastY;
                    c1.y += c2.y;
                    infoPtr->lastY = c1.y;
                    break;

                case MODE_ALIGNED:
                    infoPtr->count++;
                    slice = barWidth / (double)infoPtr->freq;
                    c1.x += slice * (infoPtr->freq - infoPtr->count);
                    c2.x = c1.x + slice;
                    break;

                case MODE_OVERLAP:
                    infoPtr->count++;
                    slice = barWidth / (double)(infoPtr->freq * 2);
                    width = slice * (infoPtr->freq + 1);
                    c1.x += slice * (infoPtr->freq - infoPtr->count);
                    c2.x = c1.x + width;
                    break;
                case MODE_INFRONT:
                    break;
                }
            }
        }
        invertBar = FALSE;
        if(c1.y < c2.y) {
double temp;

            /* Handle negative bar values by swapping ordinates */
            temp = c1.y, c1.y = c2.y, c2.y = temp;
            invertBar = TRUE;
        }
        /*
         * Get the two corners of the bar segment and compute the rectangle
         */
        c1 = RbcMap2D(graph, c1.x, c1.y, &barPtr->axes);
        c2 = RbcMap2D(graph, c2.x, c2.y, &barPtr->axes);

        /* Bound the bars vertically by the size of the graph window */
        if(c1.y < 0.0) {
            c1.y = 0.0;
        } else if(c1.y > (double)graph->height) {
            c1.y = (double)graph->height;
        }
        if(c2.y < 0.0) {
            c2.y = 0.0;
        } else if(c2.y > (double)graph->height) {
            c2.y = (double)graph->height;
        }
        dx = c1.x - c2.x;
        dy = c1.y - c2.y;
        height = (int)Round(FABS(dy));
        if(invertBar) {
            rectPtr->y = (short int)MIN(c1.y, c2.y);
        } else {
            rectPtr->y = (short int)(MAX(c1.y, c2.y)) - height;
        }
        rectPtr->x = (short int)MIN(c1.x, c2.x);
        rectPtr->width = (short int)Round(FABS(dx)) + 1;
        if(rectPtr->width < 1) {
            rectPtr->width = 1;
        }
        rectPtr->height = height + 1;
        if(rectPtr->height < 1) {
            rectPtr->height = 1;
        }
        rectToData[count] = i;  /* Save the data index corresponding to the
                                 * rectangle */
        rectPtr++;
        count++;
    }
    barPtr->nRects = count;
    barPtr->rectangles = rectangles;
    barPtr->rectToData = rectToData;
    if(barPtr->nActiveIndices > 0) {
        MapActiveBars(barPtr);
    }

    size = 20;
    if(count > 0) {
        size = rectangles->width;
    }
    /* Set the symbol size of all the pen styles. */
    for(linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->symbolSize = size;
        stylePtr->errorBarCapWidth = (stylePtr->penPtr->errorBarCapWidth > 0)
            ? stylePtr->penPtr->errorBarCapWidth : (int)(size * 0.6666666);
        stylePtr->errorBarCapWidth /= 2;
    }
    dataToStyle = RbcStyleMap((RbcElement *) barPtr);
    if(((barPtr->yHigh.nValues > 0) && (barPtr->yLow.nValues > 0)) ||
        ((barPtr->xHigh.nValues > 0) && (barPtr->xLow.nValues > 0)) ||
        (barPtr->xError.nValues > 0) || (barPtr->yError.nValues > 0)) {
        RbcMapErrorBars(graph, (RbcElement *) barPtr, dataToStyle);
    }
    MergePens(barPtr, dataToStyle);
    ckfree((char *)dataToStyle);
}

/*
 * -----------------------------------------------------------------
 *
 * DrawSymbol --
 *
 *      Draw a symbol centered at the given x,y window coordinate
 *      based upon the element symbol type and size.
 *
 *      Most notable problem is the round-off errors generated when
 *      calculating the centered position of the symbol.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawSymbol(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    RbcElement * elemPtr,
    int x,
    int y,
    int size)
{
    BarPen *penPtr = ((Bar *) elemPtr)->normalPenPtr;
    int radius;

    if((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    radius = (size / 2);
    size--;

    x -= radius;
    y -= radius;
    XSetTSOrigin(graph->display, penPtr->gc, x, y);
    XFillRectangle(graph->display, drawable, penPtr->gc, x, y, size, size);
    XSetTSOrigin(graph->display, penPtr->gc, 0, 0);
}

/*
 * -----------------------------------------------------------------
 *
 * DrawBarSegments --
 *
 *      Draws each of the rectangular segments for the element.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawBarSegments(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects)
{
    register XRectangle *rectPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    XFillRectangles(graph->display, drawable, penPtr->gc, rectangles, nRects);
    if((penPtr->border != NULL) && (penPtr->borderWidth > 0) &&
        (penPtr->relief != TK_RELIEF_FLAT)) {
    XRectangle *endPtr;

        for(rectPtr = rectangles, endPtr = rectangles + nRects;
            rectPtr < endPtr; rectPtr++) {
            Tk_Draw3DRectangle(*(graph->win), drawable, penPtr->border,
                rectPtr->x, rectPtr->y, rectPtr->width, rectPtr->height,
                penPtr->borderWidth, penPtr->relief);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * DrawBarValues --
 *
 *      Draws the numeric value of the bar.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
DrawBarValues(
    RbcGraph * graph,
    Drawable drawable,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData)
{
    XRectangle *rectPtr, *endPtr;
    int count;
    const char *fmt;
    char string[TCL_DOUBLE_SPACE * 2 + 2];
    double x, y;
    RbcPoint2D anchorPos;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    count = 0;
    fmt = penPtr->valueFormat;
    if(fmt == NULL) {
        fmt = "%g";
    }
    for(rectPtr = rectangles, endPtr = rectangles + nRects; rectPtr < endPtr;
        rectPtr++) {
        x = barPtr->x.valueArr[rectToData[count]];
        y = barPtr->y.valueArr[rectToData[count]];
        count++;
        if(penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if(penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if(penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        if(graph->inverted) {
            anchorPos.y = rectPtr->y + rectPtr->height * 0.5;
            anchorPos.x = rectPtr->x + rectPtr->width;
            if(y < graph->baseline) {
                anchorPos.x -= rectPtr->width;
            }
        } else {
            anchorPos.x = rectPtr->x + rectPtr->width * 0.5;
            anchorPos.y = rectPtr->y;
            if(y < graph->baseline) {
                anchorPos.y += rectPtr->height;
            }
        }
        RbcDrawText(*(graph->win), drawable, string, &(penPtr->valueStyle),
            (int)anchorPos.x, (int)anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawNormalBar --
 *
 *      Draws the rectangle representing the bar element.  If the
 *      relief option is set to "raised" or "sunken" and the bar
 *      borderwidth is set (borderwidth > 0), a 3D border is drawn
 *      around the bar.
 *
 *      Don't draw bars that aren't visible (i.e. within the limits
 *      of the axis).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawNormalBar(
    RbcGraph * graph,
    Drawable drawable,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;
int count;
RbcChainLink *linkPtr;
register BarPenStyle *stylePtr;
BarPen *penPtr;

    count = 0;
    for(linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        if(stylePtr->nRects > 0) {
            DrawBarSegments(graph, drawable, penPtr, stylePtr->rectangles,
                stylePtr->nRects);
        }
        if((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcDraw2DSegments(graph->display, drawable, penPtr->errorBarGC,
                stylePtr->xErrorBars, stylePtr->xErrorBarCnt);
        }
        if((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcDraw2DSegments(graph->display, drawable, penPtr->errorBarGC,
                stylePtr->yErrorBars, stylePtr->yErrorBarCnt);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            DrawBarValues(graph, drawable, barPtr, penPtr,
                stylePtr->rectangles, stylePtr->nRects,
                barPtr->rectToData + count);
        }
        count += stylePtr->nRects;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawActiveBar --
 *
 *      Draws rectangles representing the active segments of the
 *      bar element.  If the -relief option is set (other than "flat")
 *      and the borderwidth is greater than 0, a 3D border is drawn
 *      around the each bar segment.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawActiveBar(
    RbcGraph * graph,
    Drawable drawable,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;

    if(barPtr->activePenPtr != NULL) {
BarPen *penPtr = barPtr->activePenPtr;

        if(barPtr->nActiveIndices > 0) {
            if(barPtr->flags & RBC_ACTIVE_PENDING) {
                MapActiveBars(barPtr);
            }
            DrawBarSegments(graph, drawable, penPtr, barPtr->activeRects,
                barPtr->nActive);
            if(penPtr->valueShow != RBC_SHOW_NONE) {
                DrawBarValues(graph, drawable, barPtr, penPtr,
                    barPtr->activeRects, barPtr->nActive, barPtr->activeToData);
            }
        } else if(barPtr->nActiveIndices < 0) {
            DrawBarSegments(graph, drawable, penPtr, barPtr->rectangles,
                barPtr->nRects);
            if(penPtr->valueShow != RBC_SHOW_NONE) {
                DrawBarValues(graph, drawable, barPtr, penPtr,
                    barPtr->rectangles, barPtr->nRects, barPtr->rectToData);
            }
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * SymbolToPostScript --
 *
 *      Draw a symbol centered at the given x,y window coordinate
 *      based upon the element symbol type and size.
 *
 *      Most notable problem is the round-off errors generated when
 *      calculating the centered position of the symbol.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
SymbolToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    RbcElement * elemPtr,
    double x,
    double y,
    int size)
{
    Bar *barPtr = (Bar *) elemPtr;
    BarPen *bpPtr = barPtr->normalPenPtr;

    if((bpPtr->border == NULL) && (bpPtr->fgColor == NULL)) {
        return;
    }
    /*
     * Build a PostScript procedure to draw the fill and outline of
     * the symbol after the path of the symbol shape has been formed
     */
    RbcAppendToPostScript(psToken, "\n",
        "/DrawSymbolProc {\n", "  gsave\n    ", (char *)NULL);
    if(bpPtr->stipple != None) {
        if(bpPtr->border != NULL) {
            RbcBackgroundToPostScript(psToken, Tk_3DBorderColor(bpPtr->border));
            RbcAppendToPostScript(psToken, "    Fill\n    ", (char *)NULL);
        }
        if(bpPtr->fgColor != NULL) {
            RbcForegroundToPostScript(psToken, bpPtr->fgColor);
        } else {
            RbcForegroundToPostScript(psToken, Tk_3DBorderColor(bpPtr->border));
        }
        RbcStippleToPostScript(psToken, graph->display, bpPtr->stipple);
    } else if(bpPtr->fgColor != NULL) {
        RbcForegroundToPostScript(psToken, bpPtr->fgColor);
        RbcAppendToPostScript(psToken, "    fill\n", (char *)NULL);
    }
    RbcAppendToPostScript(psToken, "  grestore\n", (char *)NULL);
    RbcAppendToPostScript(psToken, "} def\n\n", (char *)NULL);
    RbcFormatToPostScript(psToken, "%g %g %d Sq\n", x, y, size);
}

/*
 *----------------------------------------------------------------------
 *
 * SegmentsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SegmentsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    BarPen * penPtr,
    register XRectangle * rectPtr,
    int nRects)
{
    XRectangle *endPtr;

    if((penPtr->border == NULL) && (penPtr->fgColor == NULL)) {
        return;
    }
    for(endPtr = rectPtr + nRects; rectPtr < endPtr; rectPtr++) {
        if((rectPtr->width < 1) || (rectPtr->height < 1)) {
            continue;
        }
        if(penPtr->stipple != None) {
            RbcRegionToPostScript(psToken,
                (double)rectPtr->x, (double)rectPtr->y,
                (int)rectPtr->width - 1, (int)rectPtr->height - 1);
            if(penPtr->border != NULL) {
                RbcBackgroundToPostScript(psToken,
                    Tk_3DBorderColor(penPtr->border));
                RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
            }
            if(penPtr->fgColor != NULL) {
                RbcForegroundToPostScript(psToken, penPtr->fgColor);
            } else {
                RbcForegroundToPostScript(psToken,
                    Tk_3DBorderColor(penPtr->border));
            }
            RbcStippleToPostScript(psToken, graph->display, penPtr->stipple);
        } else if(penPtr->fgColor != NULL) {
            RbcForegroundToPostScript(psToken, penPtr->fgColor);
            RbcRectangleToPostScript(psToken,
                (double)rectPtr->x, (double)rectPtr->y,
                (int)rectPtr->width - 1, (int)rectPtr->height - 1);
        }
        if((penPtr->border != NULL) && (penPtr->borderWidth > 0) &&
            (penPtr->relief != TK_RELIEF_FLAT)) {
            RbcDraw3DRectangleToPostScript(psToken, penPtr->border,
                (double)rectPtr->x, (double)rectPtr->y,
                (int)rectPtr->width, (int)rectPtr->height,
                penPtr->borderWidth, penPtr->relief);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * BarValuesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
BarValuesToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    Bar * barPtr,
    BarPen * penPtr,
    XRectangle * rectangles,
    int nRects,
    int *rectToData)
{
    XRectangle *rectPtr, *endPtr;
    int count;
    const char *fmt;
    char string[TCL_DOUBLE_SPACE * 2 + 2];
    double x, y;
    RbcPoint2D anchorPos;

    count = 0;
    fmt = penPtr->valueFormat;
    if(fmt == NULL) {
        fmt = "%g";
    }
    for(rectPtr = rectangles, endPtr = rectangles + nRects; rectPtr < endPtr;
        rectPtr++) {
        x = barPtr->x.valueArr[rectToData[count]];
        y = barPtr->y.valueArr[rectToData[count]];
        count++;
        if(penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if(penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if(penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        if(graph->inverted) {
            anchorPos.y = rectPtr->y + rectPtr->height * 0.5;
            anchorPos.x = rectPtr->x + rectPtr->width;
            if(y < graph->baseline) {
                anchorPos.x -= rectPtr->width;
            }
        } else {
            anchorPos.x = rectPtr->x + rectPtr->width * 0.5;
            anchorPos.y = rectPtr->y;
            if(y < graph->baseline) {
                anchorPos.y += rectPtr->height;
            }
        }
        RbcTextToPostScript(psToken, string, &(penPtr->valueStyle),
            anchorPos.x, anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ActiveBarToPostScript --
 *
 *      Similar to the NormalBarToPostScript procedure, generates
 *      PostScript commands to display the rectangles representing the
 *      active bar segments of the element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 * ----------------------------------------------------------------------
 */
static void
ActiveBarToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;

    if(barPtr->activePenPtr != NULL) {
BarPen *penPtr = barPtr->activePenPtr;

        if(barPtr->nActiveIndices > 0) {
            if(barPtr->flags & RBC_ACTIVE_PENDING) {
                MapActiveBars(barPtr);
            }
            SegmentsToPostScript(graph, psToken, penPtr,
                barPtr->activeRects, barPtr->nActive);
            if(penPtr->valueShow != RBC_SHOW_NONE) {
                BarValuesToPostScript(graph, psToken, barPtr, penPtr,
                    barPtr->activeRects, barPtr->nActive, barPtr->activeToData);
            }
        } else if(barPtr->nActiveIndices < 0) {
            SegmentsToPostScript(graph, psToken, penPtr,
                barPtr->rectangles, barPtr->nRects);
            if(penPtr->valueShow != RBC_SHOW_NONE) {
                BarValuesToPostScript(graph, psToken, barPtr, penPtr,
                    barPtr->rectangles, barPtr->nRects, barPtr->rectToData);
            }
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * NormalBarToPostScript --
 *
 *      Generates PostScript commands to form the rectangles
 *      representing the segments of the bar element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 * ----------------------------------------------------------------------
 */
static void
NormalBarToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;
RbcChainLink *linkPtr;
register BarPenStyle *stylePtr;
int count;
BarPen *penPtr;
XColor *colorPtr;

    count = 0;
    for(linkPtr = RbcChainFirstLink(barPtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        if(stylePtr->nRects > 0) {
            SegmentsToPostScript(graph, psToken, penPtr,
                stylePtr->rectangles, stylePtr->nRects);
        }
        colorPtr = penPtr->errorBarColor;
        if(colorPtr == RBC_COLOR_DEFAULT) {
            colorPtr = penPtr->fgColor;
        }
        if((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->xErrorBars,
                stylePtr->xErrorBarCnt);
        }
        if((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->yErrorBars,
                stylePtr->yErrorBarCnt);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            BarValuesToPostScript(graph, psToken, barPtr, penPtr,
                stylePtr->rectangles, stylePtr->nRects,
                barPtr->rectToData + count);
        }
        count += stylePtr->nRects;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyBar --
 *
 *      Release memory and resources allocated for the bar element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the bar element is freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyBar(
    RbcGraph * graph,
    RbcElement * elemPtr)
{
Bar *barPtr = (Bar *) elemPtr;

    if(barPtr->normalPenPtr != &(barPtr->builtinPen)) {
        RbcFreePen(graph, (RbcPen *) barPtr->normalPenPtr);
    }
    DestroyPen(graph, (RbcPen *) & (barPtr->builtinPen));
    if(barPtr->activePenPtr != NULL) {
        RbcFreePen(graph, (RbcPen *) barPtr->activePenPtr);
    }
    FreeElemVector(barPtr->x);
    FreeElemVector(barPtr->y);
    FreeElemVector(barPtr->w);
    FreeElemVector(barPtr->xHigh);
    FreeElemVector(barPtr->xLow);
    FreeElemVector(barPtr->xError);
    FreeElemVector(barPtr->yHigh);
    FreeElemVector(barPtr->yLow);
    FreeElemVector(barPtr->yError);

    ResetBar(barPtr);
    if(barPtr->activeIndices != NULL) {
        ckfree((char *)barPtr->activeIndices);
    }
    if(barPtr->palette != NULL) {
        RbcFreePalette(graph, barPtr->palette);
        RbcChainDestroy(barPtr->palette);
    }
    if(barPtr->tags != NULL) {
        ckfree((char *)barPtr->tags);
    }
}

static RbcElementProcs barProcs = {
    ClosestBar,
    ConfigureBar,
    DestroyBar,
    DrawActiveBar,
    DrawNormalBar,
    DrawSymbol,
    GetBarExtents,
    ActiveBarToPostScript,
    NormalBarToPostScript,
    SymbolToPostScript,
    MapBar,
};

/*
 * ----------------------------------------------------------------------
 *
 * RbcBarElement --
 *
 *      Allocate memory and initialize methods for the new bar element.
 *
 * Results:
 *      The pointer to the newly allocated element structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the bar element structure.
 *
 * ----------------------------------------------------------------------
 */
RbcElement *
RbcBarElement(
    RbcGraph * graph,
    const char *name,
    Tk_Uid type)
{
    register Bar *barPtr;

    barPtr = RbcCalloc(1, sizeof(Bar));
    assert(barPtr);
    barPtr->normalPenPtr = &(barPtr->builtinPen);
    barPtr->procsPtr = &barProcs;
    barPtr->specsPtr = barElemConfigSpecs;
    barPtr->labelRelief = TK_RELIEF_FLAT;
    barPtr->classUid = type;
    /* By default, an element's name and label are the same. */
    barPtr->label = RbcStrdup(name);
    barPtr->name = RbcStrdup(name);

    barPtr->graph = graph;
    barPtr->hidden = FALSE;

    InitPen(barPtr->normalPenPtr);
    barPtr->palette = RbcChainCreate();
    return (RbcElement *) barPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcInitFreqTable --
 *
 *      Generate a table of abscissa frequencies.  Duplicate
 *      x-coordinates (depending upon the bar drawing mode) indicate
 *      that something special should be done with each bar segment
 *      mapped to the same abscissa (i.e. it should be stacked,
 *      aligned, or overlay-ed with other segments)
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is allocated for the bar element structure.
 *
 * ----------------------------------------------------------------------
 */
void
RbcInitFreqTable(
    RbcGraph * graph)
{
register RbcElement *elemPtr;
RbcChainLink *linkPtr;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
Bar *barPtr;
int isNew, count;
int nStacks, nSegs;
int nPoints;
FreqKey key;
Tcl_HashTable freqTable;
register int i;
double *xArr;
    /*
     * Free resources associated with a previous frequency table. This
     * includes the array of frequency information and the table itself
     */
    if(graph->freqArr != NULL) {
        ckfree((char *)graph->freqArr);
        graph->freqArr = NULL;
    }
    if(graph->nStacks > 0) {
        Tcl_DeleteHashTable(&(graph->freqTable));
        graph->nStacks = 0;
    }
    if(graph->mode == MODE_INFRONT) {
        return; /* No frequency table is needed for
                 * "infront" mode */
    }
    Tcl_InitHashTable(&(graph->freqTable), sizeof(FreqKey) / sizeof(int));

    /*
     * Initialize a hash table and fill it with unique abscissas.
     * Keep track of the frequency of each x-coordinate and how many
     * abscissas have duplicate mappings.
     */
    Tcl_InitHashTable(&freqTable, sizeof(FreqKey) / sizeof(int));
    nSegs = nStacks = 0;
    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if((elemPtr->hidden) || (elemPtr->classUid != rbcBarElementUid)) {
            continue;
        }
        nSegs++;
        barPtr = (Bar *) elemPtr;
        xArr = barPtr->x.valueArr;
        nPoints = RbcNumberOfPoints(barPtr);
        for(i = 0; i < nPoints; i++) {
            key.value = xArr[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_CreateHashEntry(&freqTable, (char *)&key, &isNew);
            assert(hPtr != NULL);
            if(isNew) {
                count = 1;
            } else {
                count = (int)Tcl_GetHashValue(hPtr);
                if(count == 1) {
                    nStacks++;
                }
                count++;
            }
            Tcl_SetHashValue(hPtr, (ClientData) count);
        }
    }
    if(nSegs == 0) {
        return; /* No bar elements to be displayed */
    }
    if(nStacks > 0) {
RbcFreqInfo *infoPtr;
FreqKey *keyPtr;
Tcl_HashEntry *h2Ptr;

        graph->freqArr = RbcCalloc(nStacks, sizeof(RbcFreqInfo));
        assert(graph->freqArr);
        infoPtr = graph->freqArr;
        for(hPtr = Tcl_FirstHashEntry(&freqTable, &cursor); hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&cursor)) {
            count = (int)Tcl_GetHashValue(hPtr);
            keyPtr = (FreqKey *) Tcl_GetHashKey(&freqTable, hPtr);
            if(count > 1) {
                h2Ptr = Tcl_CreateHashEntry(&(graph->freqTable),
                    (char *)keyPtr, &isNew);
                count = (int)Tcl_GetHashValue(hPtr);
                infoPtr->freq = count;
                infoPtr->axes = keyPtr->axes;
                Tcl_SetHashValue(h2Ptr, infoPtr);
                infoPtr++;
            }
        }
    }
    Tcl_DeleteHashTable(&freqTable);
    graph->nStacks = nStacks;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcComputeStacks --
 *
 *      Determine the height of each stack of bar segments.  A stack
 *      is created by designating two or more points with the same
 *      abscissa.  Each ordinate defines the height of a segment in
 *      the stack.  This procedure simply looks at all the data points
 *      summing the heights of each stacked segment. The sum is saved
 *      in the frequency information table.  This value will be used
 *      to calculate the y-axis limits (data limits aren't sufficient).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The heights of each stack is computed. CheckStacks will
 *      use this information to adjust the y-axis limits if necessary.
 *
 * ----------------------------------------------------------------------
 */
void
RbcComputeStacks(
    RbcGraph * graph)
{
RbcElement *elemPtr;
Bar *barPtr;
FreqKey key;
RbcChainLink *linkPtr;
Tcl_HashEntry *hPtr;
int nPoints;
register int i;
register RbcFreqInfo *infoPtr;
double *xArr, *yArr;

    if((graph->mode != MODE_STACKED) || (graph->nStacks == 0)) {
        return;
    }
    /* Reset the sums for all duplicate values to zero. */

    infoPtr = graph->freqArr;
    for(i = 0; i < graph->nStacks; i++) {
        infoPtr->sum = 0.0;
        infoPtr++;
    }

    /* Look at each bar point, adding the ordinates of duplicate abscissas */

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if((elemPtr->hidden) || (elemPtr->classUid != rbcBarElementUid)) {
            continue;
        }
        barPtr = (Bar *) elemPtr;
        xArr = barPtr->x.valueArr;
        yArr = barPtr->y.valueArr;
        nPoints = RbcNumberOfPoints(barPtr);
        for(i = 0; i < nPoints; i++) {
            key.value = xArr[i];
            key.axes = barPtr->axes;
            hPtr = Tcl_FindHashEntry(&(graph->freqTable), (char *)&key);
            if(hPtr == NULL) {
                continue;
            }
            infoPtr = (RbcFreqInfo *) Tcl_GetHashValue(hPtr);
            infoPtr->sum += yArr[i];
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResetStacks --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcResetStacks(
    RbcGraph * graph)
{
register RbcFreqInfo *infoPtr, *endPtr;

    for(infoPtr = graph->freqArr,
        endPtr = graph->freqArr + graph->nStacks; infoPtr < endPtr; infoPtr++) {
        infoPtr->lastY = 0.0;
        infoPtr->count = 0;
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphConfig.c.
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcConfig.c --
 *
 *      This module implements custom configuration options for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define PIXELS_NONNEGATIVE	0
#define PIXELS_POSITIVE		1
#define PIXELS_ANY		2

#define COUNT_NONNEGATIVE	0
#define COUNT_POSITIVE		1
#define COUNT_ANY		2

/*
 * ----------------------------------------------------------------------
 *
 * The following enumerated values are used as bit flags.
 *	FILL_NONE		Neither coordinate plane is specified
 *	FILL_X			Horizontal plane.
 *	FILL_Y			Vertical plane.
 *	FILL_BOTH		Both vertical and horizontal planes.
 *
 * ----------------------------------------------------------------------
 */
#define FILL_NONE	0
#define FILL_X		1
#define FILL_Y		2
#define FILL_BOTH	3

static int StringToFill(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *FillToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcFillOption = {
    StringToFill, FillToString, (ClientData) 0
};

static int StringToStyle(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *StyleToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcStyleOption = {
    StringToStyle, StyleToString, (ClientData) 0
};

static int StringToPad(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int offset);
static const char *PadToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcPadOption = {
    StringToPad, PadToString, (ClientData) 0
};

static int StringToDistance(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *DistanceToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_NONNEGATIVE
};

Tk_CustomOption rbcPositiveDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_POSITIVE
};

Tk_CustomOption rbcAnyDistanceOption = {
    StringToDistance, DistanceToString, (ClientData) PIXELS_ANY
};

static int StringToCount(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *CountToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcCountOption = {
    StringToCount, CountToString, (ClientData) COUNT_NONNEGATIVE
};

Tk_CustomOption rbcPositiveCountOption = {
    StringToCount, CountToString, (ClientData) COUNT_POSITIVE
};

static int StringToDashes(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *DashesToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcDashesOption = {
    StringToDashes, DashesToString, (ClientData) 0
};

static int StringToShadow(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *ShadowToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcShadowOption = {
    StringToShadow, ShadowToString, (ClientData) 0
};

static int StringToState(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *StateToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcStateOption = {
    StringToState, StateToString, (ClientData) 0
};

static int StringToList(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    char *widgRec,
    int flags);
static const char *ListToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcListOption = {
    StringToList, ListToString, (ClientData) 0
};

static int StringToTile(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *value,
    char *widgRec,
    int flags);
static const char *TileToString(
    ClientData clientData,
    Tk_Window tkwin,
    char *widgRec,
    int offset,
    Tcl_FreeProc ** freeProcPtr);

Tk_CustomOption rbcTileOption = {
    StringToTile, TileToString, (ClientData) 0
};

static int GetInt(
    Tcl_Interp * interp,
    const char *string,
    int check,
    int *valuePtr);

int
RbcGraphOptionSetPad(
    Tcl_Interp * interp,
    Tcl_Object object,
    Tcl_Obj * value,
    RbcPad * address)
{
int nElem;
int pad1, pad2, result;
const char **padArr;
char *string;
RbcGraph *graph;
    if((graph = RbcGraphFromObject(object)) == NULL) {
        return TCL_ERROR;
    }
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    string = Tcl_GetString(value);
    if(Tcl_SplitList(interp, string, &nElem, &padArr) != TCL_OK) {
        return TCL_ERROR;
    }
    result = TCL_ERROR;
    if((nElem < 1) || (nElem > 2)) {
        Tcl_AppendResult(interp, "wrong # elements in padding list",
            (char *)NULL);
        goto error;
    }
    if(RbcGetPixels(interp, *(graph->win), padArr[0], PIXELS_NONNEGATIVE,
            &pad1) != TCL_OK) {
        goto error;
    }
    pad2 = 0;
    if(nElem > 1) {
        if(RbcGetPixels(interp, *(graph->win), padArr[1], PIXELS_NONNEGATIVE,
                &pad2) != TCL_OK) {
            goto error;
        }
    } else {
        pad2 = pad1;
    }
    address->side1 = pad1;
    address->side2 = pad2;
    result = TCL_OK;

  error:
    ckfree((char *)padArr);
    return result;
}

int
RbcGraphOptionSetShadow(
    Tcl_Interp * interp,
    Tcl_Object object,
    Tcl_Obj * value,
    RbcShadow * shadow)
{              /* Offset of pad in widget */
XColor *colorPtr;
int dropOffset;
char *string;
RbcGraph *graph;
    if((graph = RbcGraphFromObject(object)) == NULL) {
        return TCL_ERROR;
    }
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    string = Tcl_GetString(value);
    colorPtr = NULL;
    dropOffset = 0;
    if((string != NULL) && (string[0] != '\0')) {
int nElem;
const char **elemArr;

        if(Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if((nElem < 1) || (nElem > 2)) {
            Tcl_AppendResult(interp, "wrong # elements in drop shadow value",
                (char *)NULL);
            ckfree((char *)elemArr);
            return TCL_ERROR;
        }
        colorPtr = Tk_GetColor(interp, *(graph->win), Tk_GetUid(elemArr[0]));
        if(colorPtr == NULL) {
            ckfree((char *)elemArr);
            return TCL_ERROR;
        }
        dropOffset = 1;
        if(nElem == 2) {
            if(RbcGetPixels(interp, *(graph->win), elemArr[1],
                    PIXELS_NONNEGATIVE, &dropOffset) != TCL_OK) {
                Tk_FreeColor(colorPtr);
                ckfree((char *)elemArr);
                return TCL_ERROR;
            }
        }
        ckfree((char *)elemArr);
    }
    if(shadow->color != NULL) {
        Tk_FreeColor(shadow->color);
    }
    shadow->color = colorPtr;
    shadow->offset = dropOffset;
    return TCL_OK;
}

int
RbcGraphOptionSetTile(
    Tcl_Interp * interp,
    Tcl_Object object,
    Tcl_Obj * value,
    RbcTile * tile)
{              /* Offset of tile in record */
RbcTile tmpTile, oldTile;
char *string = Tcl_GetString(value);
RbcGraph *graph;
    if((graph = RbcGraphFromObject(object)) == NULL) {
        return TCL_ERROR;
    }
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    oldTile = *tile;
    tmpTile = NULL;
    if((string != NULL) && (*string != '\0')) {
        if(RbcGetTile(interp, *(graph->win), string, &tmpTile) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    /* Don't delete the information for the old tile, until we know
     * that we successfully allocated a new one. */
    if(oldTile != NULL) {
        RbcFreeTile(oldTile);
    }
    *tile = tmpTile;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToFill --
 *
 *      Converts the fill style string into its numeric representation.
 *
 *      Valid style strings are:
 *
 *         "none"   Use neither plane.
 *         "x"      X-coordinate plane.
 *         "y"	    Y-coordinate plane.
 *         "both"   Use both coordinate planes.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToFill(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Fill style string */
    char *widgRec,             /* Cubicle structure record */
    int offset)
{              /* Offset of style in record */
    int *fillPtr = (int *)(widgRec + offset);
    unsigned int length;
    char c;

    c = string[0];
    length = strlen(string);
    if((c == 'n') && (strncmp(string, "none", length) == 0)) {
        *fillPtr = FILL_NONE;
    } else if((c == 'x') && (strncmp(string, "x", length) == 0)) {
        *fillPtr = FILL_X;
    } else if((c == 'y') && (strncmp(string, "y", length) == 0)) {
        *fillPtr = FILL_Y;
    } else if((c == 'b') && (strncmp(string, "both", length) == 0)) {
        *fillPtr = FILL_BOTH;
    } else {
        Tcl_AppendResult(interp, "bad argument \"", string,
            "\": should be \"none\", \"x\", \"y\", or \"both\"", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FillToString --
 *
 *      Returns the fill style string based upon the fill flags.
 *
 * Results:
 *      The fill style string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
FillToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* Offset of fill in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int fill = *(int *)(widgRec + offset);

    switch (fill) {
    case FILL_X:
        return "x";
    case FILL_Y:
        return "y";
    case FILL_NONE:
        return "none";
    case FILL_BOTH:
        return "both";
    default:
        return "unknown value";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * StringToStyle --
 *
 *      Not possible. throw an error.
 *
 * Results:
 *      Return error message.
 *
 * Side Effects:
 *      None
 *
 *----------------------------------------------------------------------
 */
static int
StringToStyle(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New string */
    char *widgRec,             /* Structure record */
    int offset)
{              /* Offset of style in record */
    Tcl_AppendResult(interp, "-style can only be set in constructor",
        (char *)NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * StyleToString --
 *
 *      Returns the fill style string based upon the fill flags.
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      None
 *
 *----------------------------------------------------------------------
 */
static const char *
StyleToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* String in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    return (widgRec + offset);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetPixels --
 *
 *      Like Tk_GetPixels, but checks for negative, zero.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetPixels(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    int check,                 /* Can be PIXELS_POSITIVE, PIXELS_NONNEGATIVE,
                                * or PIXELS_ANY, */
    int *valuePtr)
{
    int length;

    if(Tk_GetPixels(interp, tkwin, string, &length) != TCL_OK) {
        return TCL_ERROR;
    }
    if(length >= SHRT_MAX) {
        Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
            "too big to represent", (char *)NULL);
        return TCL_ERROR;
    }
    switch (check) {
    case PIXELS_NONNEGATIVE:
        if(length < 0) {
            Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
                "can't be negative", (char *)NULL);
            return TCL_ERROR;
        }
        break;
    case PIXELS_POSITIVE:
        if(length <= 0) {
            Tcl_AppendResult(interp, "bad distance \"", string, "\": ",
                "must be positive", (char *)NULL);
            return TCL_ERROR;
        }
        break;
    case PIXELS_ANY:
        break;
    }
    *valuePtr = length;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDistance --
 *
 *      Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *      values.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToDistance(
    ClientData clientData,     /* Indicated how to check distance */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Window */
    const char *string,        /* Pixel value string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of pixel size in record */
    int *valuePtr = (int *)(widgRec + offset);
    return RbcGetPixels(interp, tkwin, string, (int)clientData, valuePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DistanceToString --
 *
 *      Returns the string representing the positive pixel size.
 *
 * Results:
 *      The pixel size string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DistanceToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* Offset in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int value = *(int *)(widgRec + offset);
    char *result;
    char stringInt[200];

    sprintf(stringInt, "%d", value);
    result = RbcStrdup(stringInt);
    assert(result);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetInt --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetInt(
    Tcl_Interp * interp,
    const char *string,
    int check,                 /* Can be COUNT_POSITIVE, COUNT_NONNEGATIVE,
                                * or COUNT_ANY, */
    int *valuePtr)
{
    int count;

    if(Tcl_GetInt(interp, string, &count) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (check) {
    case COUNT_NONNEGATIVE:
        if(count < 0) {
            Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                "can't be negative", (char *)NULL);
            return TCL_ERROR;
        }
        break;
    case COUNT_POSITIVE:
        if(count <= 0) {
            Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                "must be positive", (char *)NULL);
            return TCL_ERROR;
        }
        break;
    case COUNT_ANY:
        break;
    }
    *valuePtr = count;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToCount --
 *
 *      Like TK_CONFIG_PIXELS, but adds an extra check for negative
 *      values.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToCount(
    ClientData clientData,     /* Indicated how to check distance */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Pixel value string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of pixel size in record */
    int *valuePtr = (int *)(widgRec + offset);
    return GetInt(interp, string, (int)clientData, valuePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CountToString --
 *
 *      Returns the string representing the positive pixel size.
 *
 * Results:
 *      The pixel size string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
CountToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* Offset in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int value = *(int *)(widgRec + offset);
    char *result;
    char stringInt[200];

    sprintf(stringInt, "%d", value);
    result = RbcStrdup(stringInt);
    assert(result);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPad --
 *
 *      Convert a string into two pad values.  The string may be in one of
 *      the following forms:
 *
 *          n      - n is a non-negative integer. This sets both
 *                   pad values to n.
 *          {n m}  - both n and m are non-negative integers. side1
 *                   is set to n, side2 is set to m.
 *
 * Results:
 *      If the string is successfully converted, TCL_OK is returned.
 *      Otherwise, TCL_ERROR is returned and an error message is left in
 *      interp->result.
 *
 * Side Effects:
 *      The padding structure passed is updated with the new values.
 *
 *----------------------------------------------------------------------
 */
static int
StringToPad(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Window */
    const char *string,        /* Pixel value string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of pad in widget */
    RbcPad *padPtr = (RbcPad *) (widgRec + offset);
    int nElem;
    int pad, result;
    const char **padArr;

    if(Tcl_SplitList(interp, string, &nElem, &padArr) != TCL_OK) {
        return TCL_ERROR;
    }
    result = TCL_ERROR;
    if((nElem < 1) || (nElem > 2)) {
        Tcl_AppendResult(interp, "wrong # elements in padding list",
            (char *)NULL);
        goto error;
    }
    if(RbcGetPixels(interp, tkwin, padArr[0], PIXELS_NONNEGATIVE,
            &pad) != TCL_OK) {
        goto error;
    }
    padPtr->side1 = pad;
    if((nElem > 1)
        && (RbcGetPixels(interp, tkwin, padArr[1], PIXELS_NONNEGATIVE,
                &pad) != TCL_OK)) {
        goto error;
    }
    padPtr->side2 = pad;
    result = TCL_OK;

  error:
    ckfree((char *)padArr);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * PadToString --
 *
 *     Converts the two pad values into a Tcl list.  Each pad has two
 *     pixel values.  For vertical pads, they represent the top and bottom
 *     margins.  For horizontal pads, they're the left and right margins.
 *     All pad values are non-negative integers.
 *
 * Results:
 *     The padding list is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PadToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Structure record */
    int offset,                /* Offset of pad in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcPad *padPtr = (RbcPad *) (widgRec + offset);
    char *result;
    char string[200];

    sprintf(string, "%d %d", padPtr->side1, padPtr->side2);
    result = RbcStrdup(string);
    if(result == NULL) {
        return "out of memory";
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToShadow --
 *
 *      Convert a string into two pad values.  The string may be in one of
 *      the following forms:
 *
 *          n      - n is a non-negative integer. This sets both
 *                   pad values to n.
 *          {n m}  - both n and m are non-negative integers. side1
 *                   is set to n, side2 is set to m.
 *
 * Results:
 *      If the string is successfully converted, TCL_OK is returned.
 *      Otherwise, TCL_ERROR is returned and an error message is left in
 *      interp->result.
 *
 * Side Effects:
 *      The padding structure passed is updated with the new values.
 *
 *----------------------------------------------------------------------
 */
static int
StringToShadow(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Window */
    const char *string,        /* Pixel value string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of pad in widget */
    RbcShadow *shadowPtr = (RbcShadow *) (widgRec + offset);
    XColor *colorPtr;
    int dropOffset;

    colorPtr = NULL;
    dropOffset = 0;
    if((string != NULL) && (string[0] != '\0')) {
    int nElem;
    const char **elemArr;

        if(Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if((nElem < 1) || (nElem > 2)) {
            Tcl_AppendResult(interp, "wrong # elements in drop shadow value",
                (char *)NULL);
            ckfree((char *)elemArr);
            return TCL_ERROR;
        }
        colorPtr = Tk_GetColor(interp, tkwin, Tk_GetUid(elemArr[0]));
        if(colorPtr == NULL) {
            ckfree((char *)elemArr);
            return TCL_ERROR;
        }
        dropOffset = 1;
        if(nElem == 2) {
            if(RbcGetPixels(interp, tkwin, elemArr[1], PIXELS_NONNEGATIVE,
                    &dropOffset) != TCL_OK) {
                Tk_FreeColor(colorPtr);
                ckfree((char *)elemArr);
                return TCL_ERROR;
            }
        }
        ckfree((char *)elemArr);
    }
    if(shadowPtr->color != NULL) {
        Tk_FreeColor(shadowPtr->color);
    }
    shadowPtr->color = colorPtr;
    shadowPtr->offset = dropOffset;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ShadowToString --
 *
 *      Converts the two pad values into a Tcl list.  Each pad has two
 *      pixel values.  For vertical pads, they represent the top and bottom
 *      margins.  For horizontal pads, they're the left and right margins.
 *      All pad values are non-negative integers.
 *
 * Results:
 *      The padding list is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ShadowToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Structure record */
    int offset,                /* Offset of pad in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcShadow *shadowPtr = (RbcShadow *) (widgRec + offset);
    const char *result;

    result = "";
    if(shadowPtr->color != NULL) {
    char string[200];

        sprintf(string, "%s %d", Tk_NameOfColor(shadowPtr->color),
            shadowPtr->offset);
        result = RbcStrdup(string);
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetDashes --
 *
 *      Converts a Tcl list of dash values into a dash list ready for
 *      use with XSetDashes.
 *
 *      A valid list dash values can have zero through 11 elements
 *      (PostScript limit).  Values must be between 1 and 255. Although
 *      a list of 0 (like the empty string) means no dashes.
 *
 * Results:
 *      A standard Tcl result. If the list represented a valid dash
 *      list TCL_OK is returned and *dashesPtr* will contain the
 *      valid dash list. Otherwise, TCL_ERROR is returned and
 *      interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetDashes(
    Tcl_Interp * interp,
    const char *string,
    RbcDashes * dashesPtr)
{
    if((string == NULL) || (*string == '\0')) {
        dashesPtr->values[0] = 0;
    } else if(strcmp(string, "dash") == 0) {
        dashesPtr->values[0] = 5;
        dashesPtr->values[1] = 2;
        dashesPtr->values[2] = 0;
    } else if(strcmp(string, "dot") == 0) {
        dashesPtr->values[0] = 1;
        dashesPtr->values[1] = 0;
    } else if(strcmp(string, "dashdot") == 0) {
        dashesPtr->values[0] = 2;
        dashesPtr->values[1] = 4;
        dashesPtr->values[2] = 2;
        dashesPtr->values[3] = 0;
    } else if(strcmp(string, "dashdotdot") == 0) {
        dashesPtr->values[0] = 2;
        dashesPtr->values[1] = 4;
        dashesPtr->values[2] = 2;
        dashesPtr->values[3] = 2;
        dashesPtr->values[4] = 0;
    } else {
    int nValues;
    const char **strArr;
    long int value;
    register int i;

        if(Tcl_SplitList(interp, string, &nValues, &strArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if(nValues > 11) {
            /* This is the postscript limit */
            Tcl_AppendResult(interp, "too many values in dash list \"", string,
                "\"", (char *)NULL);
            ckfree((char *)strArr);
            return TCL_ERROR;
        }
        for(i = 0; i < nValues; i++) {
            if(Tcl_ExprLong(interp, strArr[i], &value) != TCL_OK) {
                ckfree((char *)strArr);
                return TCL_ERROR;
            }
            /*
             * Backward compatibility:
             * Allow list of 0 to turn off dashes
             */
            if((value == 0) && (nValues == 1)) {
                break;
            }
            if((value < 1) || (value > 255)) {
                Tcl_AppendResult(interp, "dash value \"", strArr[i],
                    "\" is out of range", (char *)NULL);
                ckfree((char *)strArr);
                return TCL_ERROR;
            }
            dashesPtr->values[i] = (unsigned char)value;
        }
        /* Make sure the array ends with a NUL byte  */
        dashesPtr->values[i] = 0;
        ckfree((char *)strArr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDashes --
 *
 *      Convert the list of dash values into a dashes array.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      The Dashes structure is updated with the new dash list.
 *
 *----------------------------------------------------------------------
 */
static int
StringToDashes(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New dash value list */
    char *widgRec,             /* Widget record */
    int offset)
{              /* offset to Dashes structure */
    RbcDashes *dashesPtr = (RbcDashes *) (widgRec + offset);

    return GetDashes(interp, string, dashesPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * DashesToString --
 *
 *      Convert the dashes array into a list of values.
 *
 * Results:
 *      The string representing the dashes returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DashesToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record */
    int offset,                /* offset of Dashes in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    RbcDashes *dashesPtr = (RbcDashes *) (widgRec + offset);
    Tcl_DString dString;
    char *p;
    char *result;
    char stringInt[200];

    if(dashesPtr->values[0] == 0) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for(p = dashesPtr->values; *p != 0; p++) {
        sprintf(stringInt, "%d", *p);
        Tcl_DStringAppendElement(&dString, stringInt);
    }
    result = Tcl_DStringValue(&dString);
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToState --
 *
 *      Converts the string to a state value. Valid states are
 *      disabled, normal.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToState(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representation of option value */
    char *widgRec,             /* Widget structure record */
    int offset)
{              /* Offset of field in record */
    int *statePtr = (int *)(widgRec + offset);

    if(strcmp(string, "normal") == 0) {
        *statePtr = RBC_STATE_NORMAL;
    } else if(strcmp(string, "disabled") == 0) {
        *statePtr = RBC_STATE_DISABLED;
    } else if(strcmp(string, "active") == 0) {
        *statePtr = RBC_STATE_ACTIVE;
    } else {
        Tcl_AppendResult(interp, "bad state \"", string,
            "\": should be normal, active, or disabled", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StateToString --
 *
 *      Returns the string representation of the state configuration field
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
StateToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* Offset of fill in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int state = *(int *)(widgRec + offset);

    switch (state) {
    case RBC_STATE_ACTIVE:
        return "active";
    case RBC_STATE_DISABLED:
        return "disabled";
    case RBC_STATE_NORMAL:
        return "normal";
    default:
        return "???";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * StringToList --
 *
 *      Converts the string to a list.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToList(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representation of option value */
    char *widgRec,             /* Widget structure record */
    int offset)
{              /* Offset of field in record */
    const char ***listPtr = (const char ***)(widgRec + offset);
    const char **elemArr;
    int nElem;

    if(*listPtr != NULL) {
        ckfree((char *)*listPtr);
        *listPtr = NULL;
    }
    if((string == NULL) || (*string == '\0')) {
        return TCL_OK;
    }
    if(Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(nElem > 0) {
        *listPtr = elemArr;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ListToString --
 *
 *      Returns the string representation of the state configuration field
 *
 * Results:
 *      The string is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ListToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record. */
    int offset,                /* Offset of fill in widget record. */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    char **list = *(char ***)(widgRec + offset);
    register char **p;
    char *result;
    Tcl_DString dString;

    if(list == NULL) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for(p = list; *p != NULL; p++) {
        Tcl_DStringAppendElement(&dString, *p);
    }
    result = Tcl_DStringValue(&dString);
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    Tcl_DStringFree(&dString);
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToTile --
 *
 *      Converts the name of an image into a tile.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToTile(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Window on same display as tile */
    const char *string,        /* Name of image */
    char *widgRec,             /* Widget structure record */
    int offset)
{              /* Offset of tile in record */
    RbcTile *tilePtr = (RbcTile *) (widgRec + offset);
    RbcTile tile, oldTile;

    oldTile = *tilePtr;
    tile = NULL;
    if((string != NULL) && (*string != '\0')) {
        if(RbcGetTile(interp, tkwin, string, &tile) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    /* Don't delete the information for the old tile, until we know
     * that we successfully allocated a new one. */
    if(oldTile != NULL) {
        RbcFreeTile(oldTile);
    }
    *tilePtr = tile;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TileToString --
 *
 *      Returns the name of the tile.
 *
 * Results:
 *      The name of the tile is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
TileToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget structure record */
    int offset,                /* Offset of tile in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcTile tile = *(RbcTile *) (widgRec + offset);

    return RbcNameOfTile(tile);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigModified --
 *
 *      Given the configuration specifications and one or more option
 *      patterns (terminated by a NULL), indicate if any of the matching
 *      configuration options has been reset.
 *
 * Results:
 *      Returns 1 if one of the options has changed, 0 otherwise.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcConfigModified(
    Tk_ConfigSpec * specs,
    ...)
{
    va_list argList;
    register Tk_ConfigSpec *specPtr;
    register char *option;

    va_start(argList, specs);
    while((option = va_arg(argList, char *)) != NULL) {
        for(specPtr = specs; specPtr->type != TK_CONFIG_END; specPtr++) {
            if((Tcl_StringMatch(specPtr->argvName, option))
                && (specPtr->specFlags & TK_CONFIG_OPTION_SPECIFIED)) {
                va_end(argList);
                return 1;
            }
        }
    }
    va_end(argList);
    return 1;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigureWidgetComponent --
 *
 *      Configures a component of a widget.  This is useful for
 *      widgets that have multiple components which aren't uniquely
 *      identified by a Tk_Window. It allows us, for example, set
 *      resources for axes of the graph widget. The graph really has
 *      only one window, but its convenient to specify components in a
 *      hierarchy of options.
 *
 *          *graph.x.logScale yes
 *          *graph.Axis.logScale yes
 *          *graph.temperature.scaleSymbols yes
 *          *graph.Element.scaleSymbols yes
 *
 *      This is really a hack to work around the limitations of the Tk
 *      resource database.  It creates a temporary window, needed to
 *      call Tk_ConfigureWidget, using the name of the component.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      A temporary window is created merely to pass to Tk_ConfigureWidget.
 *
 *----------------------------------------------------------------------
 */
int
RbcConfigureWidgetComponent(
    Tcl_Interp * interp,
    Tk_Window parent,          /* Window to associate with component */
    const char resName[],      /* Name of component */
    const char className[],
    const Tk_ConfigSpec * specsPtr,
    int argc,
    const char *argv[],
    char *widgRec,
    int flags)
{
    Tk_Window tkwin;
    int result;
    char *tempName;
    int isTemporary = FALSE;

    tempName = RbcStrdup(resName);

    /* Window name can't start with an upper case letter */
    tempName[0] = tolower(resName[0]);

    /*
     * Create component if a child window by the component's name
     * doesn't already exist.
     */
    tkwin = RbcFindChild(parent, tempName);
    if(tkwin == NULL) {
        tkwin = Tk_CreateWindow(interp, parent, tempName, (char *)NULL);
        isTemporary = TRUE;
    }
    if(tkwin == NULL) {
        Tcl_AppendResult(interp, "can't find window in \"", Tk_PathName(parent),
            "\"", (char *)NULL);
        return TCL_ERROR;
    }
    assert(Tk_Depth(tkwin) == Tk_Depth(parent));
    ckfree((char *)tempName);

    Tk_SetClass(tkwin, className);
    result =
        Tk_ConfigureWidget(interp, tkwin, specsPtr, argc, argv, widgRec, flags);
    if(isTemporary) {
        Tk_DestroyWindow(tkwin);
    }
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphElem.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrElem.c --
 *
 *      This module implements generic elements for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

static Tk_OptionParseProc StringToData;
static Tk_OptionPrintProc DataToString;
static Tk_OptionParseProc StringToDataPairs;
static Tk_OptionPrintProc DataPairsToString;
static Tk_OptionParseProc StringToAlong;
static Tk_OptionPrintProc AlongToString;
static Tk_CustomOption alongOption = {
    StringToAlong, AlongToString, (ClientData) 0
};

Tk_CustomOption rbcDataOption = {
    StringToData, DataToString, (ClientData) 0
};

Tk_CustomOption rbcDataPairsOption = {
    StringToDataPairs, DataPairsToString, (ClientData) 0
};

extern Tk_CustomOption rbcDistanceOption;

static int counter;

static RbcVectorChangedProc VectorChangedProc;

static int GetPenStyle(
    RbcGraph * graph,
    const char *string,
    Tk_Uid type,
    RbcPenStyle * stylePtr);
static void SyncElemVector(
    RbcElemVector * vPtr);
static void FindRange(
    RbcElemVector * vPtr);
static void FreeDataVector(
    RbcElemVector * vPtr);
static int EvalExprList(
    Tcl_Interp * interp,
    const char *list,
    int *nElemPtr,
    double **arrayPtr);
static int GetIndex(
    Tcl_Interp * interp,
    RbcElement * elemPtr,
    const char *string,
    int *indexPtr);
static int NameToElement(
    RbcGraph * graph,
    const char *name,
    RbcElement ** elemPtrPtr);
static int CreateElement(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid classUid);
static void DestroyElement(
    RbcGraph * graph,
    RbcElement * elemPtr);
static int RebuildDisplayList(
    RbcGraph * graph,
    const char *newList);

static int ActivateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int CreateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid type);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int DeactivateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int DeleteOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ExistsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int NamesOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ShowOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int TypeOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

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

/*
 *----------------------------------------------------------------------
 *
 * GetPenStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetPenStyle(
    RbcGraph * graph,
    const char *string,
    Tk_Uid type,
    RbcPenStyle * stylePtr)
{
    RbcPen *penPtr;
    Tcl_Interp *interp = graph->interp;
    const char **elemArr;
    int nElem;

    elemArr = NULL;
    if(Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if((nElem != 1) && (nElem != 3)) {
        Tcl_AppendResult(interp, "bad style \"", string, "\": should be ",
            "\"penName\" or \"penName min max\"", (char *)NULL);
        if(elemArr != NULL) {
            ckfree((char *)elemArr);
        }
        return TCL_ERROR;
    }
    if(RbcGetPen(graph, elemArr[0], type, &penPtr) != TCL_OK) {
        ckfree((char *)elemArr);
        return TCL_ERROR;
    }
    if(nElem == 3) {
    double min, max;

        if((Tcl_GetDouble(interp, elemArr[1], &min) != TCL_OK) ||
            (Tcl_GetDouble(interp, elemArr[2], &max) != TCL_OK)) {
            ckfree((char *)elemArr);
            return TCL_ERROR;
        }
        stylePtr->weight.min = min;
        stylePtr->weight.max = max;
        stylePtr->weight.range = (max > min) ? (max - min) : DBL_EPSILON;
    }
    stylePtr->penPtr = penPtr;
    ckfree((char *)elemArr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SyncElemVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SyncElemVector(
    RbcElemVector * vPtr)
{
    vPtr->nValues = vPtr->vecPtr->numValues;
    vPtr->valueArr = vPtr->vecPtr->valueArr;
    vPtr->min = RbcVecMin(vPtr->vecPtr);
    vPtr->max = RbcVecMax(vPtr->vecPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * FindRange --
 *
 *      Find the minimum, positive minimum, and maximum values in a
 *      given vector and store the results in the vector structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Minimum, positive minimum, and maximum values are stored in
 *      the vector.
 *
 *----------------------------------------------------------------------
 */
static void
FindRange(
    RbcElemVector * vPtr)
{
register int i;
register double *x;
register double min, max;

    if((vPtr->nValues < 1) || (vPtr->valueArr == NULL)) {
        return; /* This shouldn't ever happen. */
    }
    x = vPtr->valueArr;

    min = DBL_MAX, max = -DBL_MAX;
    for(i = 0; i < vPtr->nValues; i++) {
        if(!TclIsInfinite(x[i])) {
            min = max = x[i];
            break;
        }
    }
    /*  Initialize values to track the vector range */
    for( /* empty */ ; i < vPtr->nValues; i++) {
        if(!TclIsInfinite(x[i])) {
            if(x[i] < min) {
                min = x[i];
            } else if(x[i] > max) {
                max = x[i];
            }
        }
    }
    vPtr->min = min, vPtr->max = max;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFindElemVectorMinimum --
 *
 *      Find the minimum, positive minimum, and maximum values in a
 *      given vector and store the results in the vector structure.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Minimum, positive minimum, and maximum values are stored in
 *      the vector.
 *
 *----------------------------------------------------------------------
 */
double
RbcFindElemVectorMinimum(
    RbcElemVector * vPtr,
    double minLimit)
{
    register int i;
    register double *arr;
    register double min, x;

    min = DBL_MAX;
    arr = vPtr->valueArr;
    for(i = 0; i < vPtr->nValues; i++) {
        x = arr[i];
        if(x < 0.0) {
            /* What do you do about negative values when using log
             * scale values seems like a grey area.  Mirror. */
            x = -x;
        }
        if((x > minLimit) && (min > x)) {
            min = x;
        }
    }
    if(min == DBL_MAX) {
        min = minLimit;
    }
    return min;
}

/*
 *----------------------------------------------------------------------
 *
 * FreeDataVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeDataVector(
    RbcElemVector * vPtr)
{
    if(vPtr->clientId != NULL) {
        Rbc_FreeVectorId(vPtr->clientId);       /* Free the old vector */
        vPtr->clientId = NULL;
    } else if(vPtr->valueArr != NULL) {
        ckfree((char *)vPtr->valueArr);
    }
    vPtr->valueArr = NULL;
    vPtr->nValues = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * VectorChangedProc --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Graph is redrawn.
 *
 *----------------------------------------------------------------------
 */
static void
VectorChangedProc(
    Tcl_Interp * interp,
    ClientData clientData,
    RbcVectorNotify notify)
{
RbcElemVector *vPtr = clientData;
RbcElement *elemPtr = vPtr->elemPtr;
RbcGraph *graph = elemPtr->graphPtr;

    switch (notify) {
    case RBC_VECTOR_NOTIFY_DESTROY:
        vPtr->clientId = NULL;
        vPtr->valueArr = NULL;
        vPtr->nValues = 0;
        break;

    case RBC_VECTOR_NOTIFY_UPDATE:
    default:
        Rbc_GetVectorById(interp, vPtr->clientId, &vPtr->vecPtr);
        SyncElemVector(vPtr);
        break;
    }
    graph->flags |= RBC_RESET_AXES;
    elemPtr->flags |= RBC_MAP_ITEM;
    if(!elemPtr->hidden) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graph);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * EvalExprList --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
EvalExprList(
    Tcl_Interp * interp,
    const char *list,
    int *nElemPtr,
    double **arrayPtr)
{
    int nElem;
    const char **elemArr;
    double *array;
    int result;

    result = TCL_ERROR;
    elemArr = NULL;
    if(Tcl_SplitList(interp, list, &nElem, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    array = NULL;
    if(nElem > 0) {
    register double *valuePtr;
    register int i;

        counter++;
        array = (double *)ckalloc(sizeof(double) * nElem);
        if(array == NULL) {
            Tcl_AppendResult(interp, "can't allocate new vector", (char *)NULL);
            goto badList;
        }
        valuePtr = array;
        for(i = 0; i < nElem; i++) {
            if(Tcl_ExprDouble(interp, elemArr[i], valuePtr) != TCL_OK) {
                goto badList;
            }
            valuePtr++;
        }
    }
    result = TCL_OK;

  badList:
    ckfree((char *)elemArr);
    *arrayPtr = array;
    *nElemPtr = nElem;
    if(result != TCL_OK) {
        ckfree((char *)array);
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToData --
 *
 *      Given a Tcl list of numeric expression representing the element
 *      values, convert into an array of double precision values. In
 *      addition, the minimum and maximum values are saved.  Since
 *      elastic values are allow (values which translate to the
 *      min/max of the graph), we must try to get the non-elastic
 *      minimum and maximum.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vector is passed
 *      back via the vPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToData(
    ClientData clientData,     /* Type of axis vector to fill */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Tcl list of expressions */
    char *widgRec,             /* Element record */
    int offset)
{              /* Offset of vector in Element record */
    RbcElement *elemPtr = (RbcElement *) (widgRec);
    RbcElemVector *vPtr = (RbcElemVector *) (widgRec + offset);

    FreeDataVector(vPtr);
    if(Rbc_VectorExists(interp, string)) {
    RbcVectorId clientId;

        clientId = RbcAllocVectorId(interp, string);
        if(Rbc_GetVectorById(interp, clientId, &vPtr->vecPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        Rbc_SetVectorChangedProc(clientId, VectorChangedProc, vPtr);
        vPtr->elemPtr = elemPtr;
        vPtr->clientId = clientId;
        SyncElemVector(vPtr);
        elemPtr->flags |= RBC_MAP_ITEM;
    } else {
    double *newArr;
    int nValues;

        if(EvalExprList(interp, string, &nValues, &newArr) != TCL_OK) {
            return TCL_ERROR;
        }
        if(nValues > 0) {
            vPtr->valueArr = newArr;
        }
        vPtr->nValues = nValues;
        FindRange(vPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DataToString --
 *
 *      Convert the vector of floating point values into a Tcl list.
 *
 * Results:
 *      The string representation of the vector is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DataToString(
    ClientData clientData,     /* Type of axis vector to print */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element record */
    int offset,                /* Offset of vector in Element record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    RbcElemVector *vPtr = (RbcElemVector *) (widgRec + offset);
    RbcElement *elemPtr = (RbcElement *) (widgRec);
    Tcl_DString dString;
    char *result;
    char string[TCL_DOUBLE_SPACE + 1];
    double *p, *endPtr;

    if(vPtr->clientId != NULL) {
        return Rbc_NameOfVectorId(vPtr->clientId);
    }
    if(vPtr->nValues == 0) {
        return "";
    }
    Tcl_DStringInit(&dString);
    endPtr = vPtr->valueArr + vPtr->nValues;
    for(p = vPtr->valueArr; p < endPtr; p++) {
        Tcl_PrintDouble(elemPtr->graphPtr->interp, *p, string);
        Tcl_DStringAppendElement(&dString, string);
    }
    result = Tcl_DStringValue(&dString);

    /*
     * If memory wasn't allocated for the dynamic string, do it here (it's
     * currently on the stack), so that Tcl can free it normally.
     */
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToDataPairs --
 *
 *      This procedure is like StringToData except that it interprets
 *      the list of numeric expressions as X Y coordinate pairs.  The
 *      minimum and maximum for both the X and Y vectors are
 *      determined.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vectors are
 *      passed back via the widget record (elemPtr).
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToDataPairs(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Tcl list of numeric expressions */
    char *widgRec,             /* Element record */
    int offset)
{              /* Not used. */
    RbcElement *elemPtr = (RbcElement *) widgRec;
    int nElem;
    unsigned int newSize;
    double *newArr;

    if(EvalExprList(interp, string, &nElem, &newArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(nElem & 1) {
        Tcl_AppendResult(interp, "odd number of data points", (char *)NULL);
        ckfree((char *)newArr);
        return TCL_ERROR;
    }
    nElem /= 2;
    newSize = nElem * sizeof(double);

    FreeDataVector(&elemPtr->x);
    FreeDataVector(&elemPtr->y);

    elemPtr->x.valueArr = (double *)ckalloc(newSize);
    elemPtr->y.valueArr = (double *)ckalloc(newSize);
    assert(elemPtr->x.valueArr && elemPtr->y.valueArr);
    elemPtr->x.nValues = elemPtr->y.nValues = nElem;

    if(newSize > 0) {
    register double *dataPtr;
    register int i;

        for(dataPtr = newArr, i = 0; i < nElem; i++) {
            elemPtr->x.valueArr[i] = *dataPtr++;
            elemPtr->y.valueArr[i] = *dataPtr++;
        }
        ckfree((char *)newArr);
        FindRange(&elemPtr->x);
        FindRange(&elemPtr->y);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DataPairsToString --
 *
 *      Convert pairs of floating point values in the X and Y arrays
 *      into a Tcl list.
 *
 * Results:
 *      The return value is a string (Tcl list).
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
DataPairsToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element information record */
    int offset,                /* Not used. */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    RbcElement *elemPtr = (RbcElement *) widgRec;
    Tcl_Interp *interp = elemPtr->graphPtr->interp;
    int i;
    int length;
    char *result;
    char string[TCL_DOUBLE_SPACE + 1];
    Tcl_DString dString;

    length = RbcNumberOfPoints(elemPtr);
    if(length < 1) {
        return "";
    }
    Tcl_DStringInit(&dString);
    for(i = 0; i < length; i++) {
        Tcl_PrintDouble(interp, elemPtr->x.valueArr[i], string);
        Tcl_DStringAppendElement(&dString, string);
        Tcl_PrintDouble(interp, elemPtr->y.valueArr[i], string);
        Tcl_DStringAppendElement(&dString, string);
    }
    result = Tcl_DStringValue(&dString);

    /*
     * If memory wasn't allocated for the dynamic string, do it here
     * (it's currently on the stack), so that Tcl can free it
     * normally.
     */
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToAlong --
 *
 *      Given a Tcl list of numeric expression representing the element
 *      values, convert into an array of double precision values. In
 *      addition, the minimum and maximum values are saved.  Since
 *      elastic values are allow (values which translate to the
 *      min/max of the graph), we must try to get the non-elastic
 *      minimum and maximum.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vector is passed
 *      back via the vPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToAlong(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representation of value. */
    char *widgRec,             /* Widget record. */
    int offset)
{              /* Offset of field in widget record. */
    int *intPtr = (int *)(widgRec + offset);

    if((string[0] == 'x') && (string[1] == '\0')) {
        *intPtr = RBC_SEARCH_X;
    } else if((string[0] == 'y') && (string[1] == '\0')) {
        *intPtr = RBC_SEARCH_Y;
    } else if((string[0] == 'b') && (strcmp(string, "both") == 0)) {
        *intPtr = RBC_SEARCH_BOTH;
    } else {
        Tcl_AppendResult(interp, "bad along value \"", string, "\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * AlongToString --
 *
 *      Convert the vector of floating point values into a Tcl list.
 *
 * Results:
 *      The string representation of the vector is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
AlongToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record */
    int offset,                /* Offset of field in widget record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    int along = *(int *)(widgRec + offset);

    switch (along) {
    case RBC_SEARCH_X:
        return "x";
    case RBC_SEARCH_Y:
        return "y";
    case RBC_SEARCH_BOTH:
        return "both";
    default:
        return "unknown along value";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreePalette --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreePalette(
    RbcGraph * graph,
    RbcChain * palette)
{
RbcChainLink *linkPtr;

    /* Skip the first slot. It contains the built-in "normal" pen of
     * the element.  */
    linkPtr = RbcChainFirstLink(palette);
    if(linkPtr != NULL) {
register RbcPenStyle *stylePtr;
RbcChainLink *nextPtr;

        for(linkPtr = RbcChainNextLink(linkPtr); linkPtr != NULL;
            linkPtr = nextPtr) {
            nextPtr = RbcChainNextLink(linkPtr);
            stylePtr = RbcChainGetValue(linkPtr);
            RbcFreePen(graph, stylePtr->penPtr);
            RbcChainDeleteLink(palette, linkPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStringToStyles --
 *
 *      Parse the list of style names.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcStringToStyles(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing style list */
    char *widgRec,             /* Element information record */
    int offset)
{              /* Offset of symbol type field in record */
    RbcChain *palette = *(RbcChain **) (widgRec + offset);
    RbcChainLink *linkPtr;
    RbcElement *elemPtr = (RbcElement *) (widgRec);
    RbcPenStyle *stylePtr;
    const char **elemArr;
    int nStyles;
    register int i;
    size_t size = (size_t) clientData;

    elemArr = NULL;
    RbcFreePalette(elemPtr->graphPtr, palette);
    if((string == NULL) || (*string == '\0')) {
        nStyles = 0;
    } else if(Tcl_SplitList(interp, string, &nStyles, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    /* Reserve the first entry for the "normal" pen. We'll set the
     * style later */
    linkPtr = RbcChainFirstLink(palette);
    if(linkPtr == NULL) {
        linkPtr = RbcChainAllocLink(size);
        RbcChainLinkBefore(palette, linkPtr, NULL);
    }
    stylePtr = RbcChainGetValue(linkPtr);
    stylePtr->penPtr = elemPtr->normalPenPtr;

    for(i = 0; i < nStyles; i++) {
        linkPtr = RbcChainAllocLink(size);
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->weight.min = (double)i;
        stylePtr->weight.max = (double)i + 1.0;
        stylePtr->weight.range = 1.0;
        if(GetPenStyle(elemPtr->graphPtr, elemArr[i], elemPtr->classUid,
                (RbcPenStyle *) stylePtr) != TCL_OK) {
            ckfree((char *)elemArr);
            RbcFreePalette(elemPtr->graphPtr, palette);
            return TCL_ERROR;
        }
        RbcChainLinkBefore(palette, linkPtr, NULL);
    }
    if(elemArr != NULL) {
        ckfree((char *)elemArr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStylesToString --
 *
 *      Convert the style information into a string.
 *
 * Results:
 *      The string representing the style information is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
const char *
RbcStylesToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element information record */
    int offset,                /* Not used. */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcChain *palette = *(RbcChain **) (widgRec + offset);
    Tcl_DString dString;
    char *result;
    RbcChainLink *linkPtr;

    Tcl_DStringInit(&dString);
    linkPtr = RbcChainFirstLink(palette);
    if(linkPtr != NULL) {
    RbcElement *elemPtr = (RbcElement *) (widgRec);
    char string[TCL_DOUBLE_SPACE];
    Tcl_Interp *interp;
    RbcPenStyle *stylePtr;

        interp = elemPtr->graphPtr->interp;
        for(linkPtr = RbcChainNextLink(linkPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            Tcl_DStringStartSublist(&dString);
            Tcl_DStringAppendElement(&dString, stylePtr->penPtr->name);
            Tcl_PrintDouble(interp, stylePtr->weight.min, string);
            Tcl_DStringAppendElement(&dString, string);
            Tcl_PrintDouble(interp, stylePtr->weight.max, string);
            Tcl_DStringAppendElement(&dString, string);
            Tcl_DStringEndSublist(&dString);
        }
    }
    result = RbcStrdup(Tcl_DStringValue(&dString));
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStyleMap --
 *
 *      Creates an array of style indices and fills it based on the weight
 *      of each data point.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the index array.
 *
 *----------------------------------------------------------------------
 */
RbcPenStyle **
RbcStyleMap(
    RbcElement * elemPtr)
{
register int i;
int nWeights;                  /* Number of weights to be examined.
                                * If there are more data points than
                                * weights, they will default to the
                                * normal pen. */

RbcPenStyle **dataToStyle;     /* Directory of styles.  Each array
                                * element represents the style for
                                * the data point at that index */
RbcChainLink *linkPtr;
RbcPenStyle *stylePtr;
double *w;                     /* Weight vector */
int nPoints;

    nPoints = RbcNumberOfPoints(elemPtr);
    nWeights = MIN(elemPtr->w.nValues, nPoints);
    w = elemPtr->w.valueArr;
    linkPtr = RbcChainFirstLink(elemPtr->palette);
    stylePtr = RbcChainGetValue(linkPtr);

    /*
     * Create a style mapping array (data point index to style),
     * initialized to the default style.
     */
    dataToStyle = (RbcPenStyle **) ckalloc(nPoints * sizeof(RbcPenStyle *));
    assert(dataToStyle);
    for(i = 0; i < nPoints; i++) {
        dataToStyle[i] = stylePtr;
    }

    for(i = 0; i < nWeights; i++) {
        for(linkPtr = RbcChainLastLink(elemPtr->palette); linkPtr != NULL;
            linkPtr = RbcChainPrevLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);

            if(stylePtr->weight.range > 0.0) {
double norm;

                norm = (w[i] - stylePtr->weight.min) / stylePtr->weight.range;
                if(((norm - 1.0) <= DBL_EPSILON) &&
                    (((1.0 - norm) - 1.0) <= DBL_EPSILON)) {
                    dataToStyle[i] = stylePtr;
                    break;      /* Done: found range that matches. */
                }
            }
        }
    }
    return dataToStyle;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapErrorBars --
 *
 *      Creates two arrays of points and pen indices, filled with
 *      the screen coordinates of the visible
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the index array.
 *
 *----------------------------------------------------------------------
 */
void
RbcMapErrorBars(
    RbcGraph * graph,
    RbcElement * elemPtr,
    RbcPenStyle ** dataToStyle)
{
int n, nPoints;
RbcExtents2D exts;
RbcPenStyle *stylePtr;

    RbcGraphExtents(graph, &exts);
    nPoints = RbcNumberOfPoints(elemPtr);
    if(elemPtr->xError.nValues > 0) {
        n = MIN(elemPtr->xError.nValues, nPoints);
    } else {
        n = MIN3(elemPtr->xHigh.nValues, elemPtr->xLow.nValues, nPoints);
    }
    if(n > 0) {
RbcSegment2D *errorBars;
RbcSegment2D *segPtr;
double high, low;
double x, y;
int *errorToData;
int *indexPtr;
register int i;

        segPtr = errorBars =
            (RbcSegment2D *) ckalloc(n * 3 * sizeof(RbcSegment2D));
        indexPtr = errorToData = (int *)ckalloc(n * 3 * sizeof(int));
        for(i = 0; i < n; i++) {
            x = elemPtr->x.valueArr[i];
            y = elemPtr->y.valueArr[i];
            stylePtr = dataToStyle[i];
            if((!TclIsInfinite(x)) && (!TclIsInfinite(y))) {
                if(elemPtr->xError.nValues > 0) {
                    high = x + elemPtr->xError.valueArr[i];
                    low = x - elemPtr->xError.valueArr[i];
                } else {
                    high = elemPtr->xHigh.valueArr[i];
                    low = elemPtr->xLow.valueArr[i];
                }
                if((!TclIsInfinite(high)) && (!TclIsInfinite(low))) {
RbcPoint2D p, q;

                    p = RbcMap2D(graph, high, y, &elemPtr->axes);
                    q = RbcMap2D(graph, low, y, &elemPtr->axes);
                    segPtr->p = p;
                    segPtr->q = q;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Left cap */
                    segPtr->p.x = segPtr->q.x = p.x;
                    segPtr->p.y = p.y - stylePtr->errorBarCapWidth;
                    segPtr->q.y = p.y + stylePtr->errorBarCapWidth;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Right cap */
                    segPtr->p.x = segPtr->q.x = q.x;
                    segPtr->p.y = q.y - stylePtr->errorBarCapWidth;
                    segPtr->q.y = q.y + stylePtr->errorBarCapWidth;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                }
            }
        }
        elemPtr->xErrorBars = errorBars;
        elemPtr->xErrorBarCnt = segPtr - errorBars;
        elemPtr->xErrorToData = errorToData;
    }
    if(elemPtr->yError.nValues > 0) {
        n = MIN(elemPtr->yError.nValues, nPoints);
    } else {
        n = MIN3(elemPtr->yHigh.nValues, elemPtr->yLow.nValues, nPoints);
    }
    if(n > 0) {
RbcSegment2D *errorBars;
RbcSegment2D *segPtr;
double high, low;
double x, y;
int *errorToData;
int *indexPtr;
register int i;

        segPtr = errorBars =
            (RbcSegment2D *) ckalloc(n * 3 * sizeof(RbcSegment2D));
        indexPtr = errorToData = (int *)ckalloc(n * 3 * sizeof(int));
        for(i = 0; i < n; i++) {
            x = elemPtr->x.valueArr[i];
            y = elemPtr->y.valueArr[i];
            stylePtr = dataToStyle[i];
            if((!TclIsInfinite(x)) && (!TclIsInfinite(y))) {
                if(elemPtr->yError.nValues > 0) {
                    high = y + elemPtr->yError.valueArr[i];
                    low = y - elemPtr->yError.valueArr[i];
                } else {
                    high = elemPtr->yHigh.valueArr[i];
                    low = elemPtr->yLow.valueArr[i];
                }
                if((!TclIsInfinite(high)) && (!TclIsInfinite(low))) {
RbcPoint2D p, q;

                    p = RbcMap2D(graph, x, high, &elemPtr->axes);
                    q = RbcMap2D(graph, x, low, &elemPtr->axes);
                    segPtr->p = p;
                    segPtr->q = q;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Top cap. */
                    segPtr->p.y = segPtr->q.y = p.y;
                    segPtr->p.x = p.x - stylePtr->errorBarCapWidth;
                    segPtr->q.x = p.x + stylePtr->errorBarCapWidth;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                    /* Bottom cap. */
                    segPtr->p.y = segPtr->q.y = q.y;
                    segPtr->p.x = q.x - stylePtr->errorBarCapWidth;
                    segPtr->q.x = q.x + stylePtr->errorBarCapWidth;
                    if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                        segPtr++;
                        *indexPtr++ = i;
                    }
                }
            }
        }
        elemPtr->yErrorBars = errorBars;
        elemPtr->yErrorBarCnt = segPtr - errorBars;
        elemPtr->yErrorToData = errorToData;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetIndex --
 *
 *      Given a string representing the index of a pair of x,y
 *      coordinates, return the numeric index.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetIndex(
    Tcl_Interp * interp,
    RbcElement * elemPtr,
    const char *string,
    int *indexPtr)
{
    long ielem;
    int last;

    last = RbcNumberOfPoints(elemPtr) - 1;
    if((*string == 'e') && (strcmp("end", string) == 0)) {
        ielem = last;
    } else if(Tcl_ExprLong(interp, string, &ielem) != TCL_OK) {
        return TCL_ERROR;
    }
    *indexPtr = (int)ielem;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToElement --
 *
 *      Find the element represented the given name,  returning
 *      a pointer to its data structure via elemPtrPtr.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NameToElement(
    RbcGraph * graph,
    const char *name,
    RbcElement ** elemPtrPtr)
{
    Tcl_HashEntry *hPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(name == NULL) {
        return TCL_ERROR;
    }
    hPtr = Tcl_FindHashEntry(&graph->elements.table, name);
    if(hPtr == NULL) {
        Tcl_AppendResult(graph->interp, "can't find element \"", name,
            "\" in \"", Tk_PathName(*(graph->win)), "\"", (char *)NULL);
        return TCL_ERROR;
    }
    *elemPtrPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyElement --
 *
 *      Add a new element to the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyElement(
    RbcGraph * graph,
    RbcElement * elemPtr)
{
RbcChainLink *linkPtr;

    RbcDeleteBindings(graph->bindTable, elemPtr);
    RbcLegendRemoveElement(graph->legend, elemPtr);

    Tk_FreeOptions(elemPtr->specsPtr, (char *)elemPtr, graph->display, 0);
    /*
     * Call the element's own destructor to release the memory and
     * resources allocated for it.
     */
    (*elemPtr->procsPtr->destroyProc) (graph, elemPtr);

    /* Remove it also from the element display list */
    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        if(elemPtr == RbcChainGetValue(linkPtr)) {
            RbcChainDeleteLink(graph->elements.displayList, linkPtr);
            if(!elemPtr->hidden) {
                graph->flags |= RBC_RESET_WORLD;
                RbcEventuallyRedrawGraph(graph);
            }
            break;
        }
    }
    /* Remove the element for the graph's hash table of elements */
    if(elemPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(elemPtr->hashPtr);
    }
    if(elemPtr->name != NULL) {
        ckfree((char *)elemPtr->name);
    }
    ckfree((char *)elemPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateElement --
 *
 *      Add a new element to the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CreateElement(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid classUid)
{
    RbcElement *elemPtr;
    Tcl_HashEntry *hPtr;
    int isNew;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(argv[3][0] == '-') {
        Tcl_AppendResult(graph->interp, "name of element \"", argv[3],
            "\" can't start with a '-'", (char *)NULL);
        return TCL_ERROR;
    }
    hPtr = Tcl_CreateHashEntry(&graph->elements.table, argv[3], &isNew);
    if(!isNew) {
        Tcl_AppendResult(interp, "element \"", argv[3],
            "\" already exists in \"", argv[0], "\"", (char *)NULL);
        return TCL_ERROR;
    }
    if(classUid == rbcBarElementUid) {
        elemPtr = RbcBarElement(graph, argv[3], classUid);
    } else {
        /* Stripcharts are line graphs with some options enabled. */
        elemPtr = RbcLineElement(graph, argv[3], classUid);
    }
    elemPtr->hashPtr = hPtr;
    Tcl_SetHashValue(hPtr, elemPtr);

    if(RbcConfigureWidgetComponent(interp, *(graph->win), elemPtr->name,
            "Element", elemPtr->specsPtr, argc - 4, argv + 4,
            (char *)elemPtr, 0) != TCL_OK) {
        DestroyElement(graph, elemPtr);
        return TCL_ERROR;
    }
    (*elemPtr->procsPtr->configProc) (graph, elemPtr);
    RbcChainPrepend(graph->elements.displayList, elemPtr);

    if(!elemPtr->hidden) {
        /* If the new element isn't hidden then redraw the graph.  */
        graph->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graph);
    }
    elemPtr->flags |= RBC_MAP_ITEM;
    graph->flags |= RBC_RESET_AXES;
    Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->name, -1));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RebuildDisplayList --
 *
 *      Given a Tcl list of element names, this procedure rebuilds the
 *      display list, ignoring invalid element names. This list describes
 *      not only only which elements to draw, but in what order.  This is
 *      only important for bar and pie charts.
 *
 * Results:
 *      The return value is a standard Tcl result.  Only if the Tcl list
 *      can not be split, a TCL_ERROR is returned and interp->result contains
 *      an error message.
 *
 * Side effects:
 *      The graph is eventually redrawn using the new display list.
 *
 *----------------------------------------------------------------------
 */
static int
RebuildDisplayList(
    RbcGraph * graph,          /* Graph widget record */
    const char *newList)
{              /* Tcl list of element names */
    int nNames;                /* Number of names found in Tcl name list */
    const char **nameArr;      /* Broken out array of element names */
    Tcl_HashSearch cursor;
    register int i;
    register Tcl_HashEntry *hPtr;
    RbcElement *elemPtr;       /* Element information record */

    if(Tcl_SplitList(graph->interp, newList, &nNames, &nameArr) != TCL_OK) {
        Tcl_AppendResult(graph->interp, "can't split name list \"", newList,
            "\"", (char *)NULL);
        return TCL_ERROR;
    }
    /* Clear the display list and mark all elements as hidden.  */
    RbcChainReset(graph->elements.displayList);
    for(hPtr = Tcl_FirstHashEntry(&graph->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        elemPtr->hidden = TRUE;
    }

    /* Rebuild the display list, checking that each name it exists
     * (currently ignoring invalid element names).  */
    for(i = 0; i < nNames; i++) {
        if(NameToElement(graph, nameArr[i], &elemPtr) == TCL_OK) {
            elemPtr->hidden = FALSE;
            RbcChainAppend(graph->elements.displayList, elemPtr);
        }
    }
    ckfree((char *)nameArr);
    graph->flags |= RBC_RESET_WORLD;
    RbcEventuallyRedrawGraph(graph);
    Tcl_ResetResult(graph->interp);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyElements --
 *
 *      Removes all the graph's elements. This routine is called when
 *      the graph is destroyed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory allocated for the graph's elements is freed.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyElements(
    RbcGraph * graph)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcElement *elemPtr;

    for(hPtr = Tcl_FirstHashEntry(&graph->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        elemPtr->hashPtr = NULL;
        DestroyElement(graph, elemPtr);
    }
    Tcl_DeleteHashTable(&graph->elements.table);
    Tcl_DeleteHashTable(&graph->elements.tagTable);
    RbcChainDestroy(graph->elements.displayList);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapElements --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapElements(
    RbcGraph * graph)
{
RbcElement *elemPtr;
RbcChainLink *linkPtr;

    if(graph->mode != MODE_INFRONT) {
        RbcResetStacks(graph);
    }
    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(elemPtr->hidden) {
            continue;
        }
        if((graph->flags & RBC_MAP_ALL) || (elemPtr->flags & RBC_MAP_ITEM)) {
            (*elemPtr->procsPtr->mapProc) (graph, elemPtr);
            elemPtr->flags &= ~RBC_MAP_ITEM;
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcDrawElements --
 *
 *      Calls the individual element drawing routines for each
 *      element.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Elements are drawn into the drawable (pixmap) which will
 *      eventually be displayed in the graph window.
 *
 * -----------------------------------------------------------------
 */
void
RbcDrawElements(
    RbcGraph * graph,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcChainLink *linkPtr;
RbcElement *elemPtr;

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(!elemPtr->hidden) {
            (*elemPtr->procsPtr->drawNormalProc) (graph, drawable, elemPtr);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcDrawActiveElements --
 *
 *      Calls the individual element drawing routines to display
 *      the active colors for each element.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Elements are drawn into the drawable (pixmap) which will
 *      eventually be displayed in the graph window.
 *
 * -----------------------------------------------------------------
 */
void
RbcDrawActiveElements(
    RbcGraph * graph,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcChainLink *linkPtr;
RbcElement *elemPtr;

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if((!elemPtr->hidden) && (elemPtr->flags & RBC_ELEM_ACTIVE)) {
            (*elemPtr->procsPtr->drawActiveProc) (graph, drawable, elemPtr);
        }
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcElementsToPostScript --
 *
 *      Generates PostScript output for each graph element in the
 *      element display list.
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcElementsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcChainLink *linkPtr;
RbcElement *elemPtr;

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(!elemPtr->hidden) {
            /* Comment the PostScript to indicate the start of the element */
            RbcFormatToPostScript(psToken, "\n%% Element \"%s\"\n\n",
                elemPtr->name);
            (*elemPtr->procsPtr->printNormalProc) (graph, psToken, elemPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcActiveElementsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcActiveElementsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcChainLink *linkPtr;
RbcElement *elemPtr;

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if((!elemPtr->hidden) && (elemPtr->flags & RBC_ELEM_ACTIVE)) {
            RbcFormatToPostScript(psToken, "\n%% Active Element \"%s\"\n\n",
                elemPtr->name);
            (*elemPtr->procsPtr->printActiveProc) (graph, psToken, elemPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGraphUpdateNeeded --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGraphUpdateNeeded(
    RbcGraph * graph)
{
RbcChainLink *linkPtr;
RbcElement *elemPtr;

    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(elemPtr->hidden) {
            continue;
        }
        /* Check if the x or y vectors have notifications pending */
        if((RbcVectorNotifyPending(elemPtr->x.clientId)) ||
            (RbcVectorNotifyPending(elemPtr->y.clientId))) {
            return 1;
        }
    }
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * ActivateOp --
 *
 *      Marks data points of elements (given by their index) as active.
 *
 * Results:
 *      Returns TCL_OK if no errors occurred.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ActivateOp(
    RbcGraph * graph,          /* Graph widget */
    Tcl_Interp * interp,       /* Interpreter to report errors to */
    int argc,                  /* Number of element names */
    const char **argv)
{              /* List of element names */
    RbcElement *elemPtr;
    register int i;
    int *activeArr;
    int nActiveIndices;

    if(argc == 3) {
    register Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;

        /* List all the currently active elements */
        for(hPtr = Tcl_FirstHashEntry(&graph->elements.table, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
            if(elemPtr->flags & RBC_ELEM_ACTIVE) {
                Tcl_AppendElement(graph->interp, elemPtr->name);
            }
        }
        return TCL_OK;
    }
    if(NameToElement(graph, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    elemPtr->flags |= RBC_ELEM_ACTIVE | RBC_ACTIVE_PENDING;

    activeArr = NULL;
    nActiveIndices = -1;
    if(argc > 4) {
    register int *activePtr;

        nActiveIndices = argc - 4;
        activePtr = activeArr = (int *)ckalloc(sizeof(int) * nActiveIndices);
        assert(activeArr);
        for(i = 4; i < argc; i++) {
            if(GetIndex(interp, elemPtr, argv[i], activePtr) != TCL_OK) {
                return TCL_ERROR;
            }
            activePtr++;
        }
    }
    if(elemPtr->activeIndices != NULL) {
        ckfree((char *)elemPtr->activeIndices);
    }
    elemPtr->nActiveIndices = nActiveIndices;
    elemPtr->activeIndices = activeArr;
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMakeElementTag --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
ClientData
RbcMakeElementTag(
    RbcGraph * graph,
    const char *tagName)
{
Tcl_HashEntry *hPtr;
int isNew;

    hPtr = Tcl_CreateHashEntry(&graph->elements.tagTable, tagName, &isNew);
    assert(hPtr);
    return Tcl_GetHashKey(&graph->elements.tagTable, hPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    if(argc == 3) {
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    char *tagName;

        for(hPtr = Tcl_FirstHashEntry(&graph->elements.tagTable, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tagName = Tcl_GetHashKey(&graph->elements.tagTable, hPtr);
            Tcl_AppendElement(interp, tagName);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graph->bindTable,
        RbcMakeElementTag(graph, argv[3]), argc - 4, argv + 4);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateOp --
 *
 *      Add a new element to the graph (using the default type of the
 *      graph).
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CreateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv,
    Tk_Uid type)
{
    return CreateElement(graph, interp, argc, argv, type);
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    char *argv[])
{
    RbcElement *elemPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(NameToElement(graph, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    if(Tk_ConfigureValue(interp, *(graph->win), elemPtr->specsPtr,
            (char *)elemPtr, argv[4], 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

static Tk_ConfigSpec closestSpecs[] = {
    {TK_CONFIG_CUSTOM, "-halo", (char *)NULL, (char *)NULL,
            (char *)NULL, Tk_Offset(RbcClosestSearch, halo), 0,
        &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-interpolate", (char *)NULL, (char *)NULL,
        (char *)NULL, Tk_Offset(RbcClosestSearch, mode), 0},
    {TK_CONFIG_CUSTOM, "-along", (char *)NULL, (char *)NULL,
        (char *)NULL, Tk_Offset(RbcClosestSearch, along), 0, &alongOption},
    {TK_CONFIG_END, (char *)NULL, (char *)NULL, (char *)NULL,
        (char *)NULL, 0, 0}
};

/*
 *----------------------------------------------------------------------
 *
 * ClosestOp --
 *
 *      Find the element closest to the specified screen coordinates.
 *      Options:
 *      -halo		Consider points only with this maximum distance
 *      		from the picked coordinate.
 *      -interpolate	Find closest point along element traces, not just
 *      		data points.
 *      -along
 *
 * Results:
 *      A standard Tcl result. If an element could be found within
 *      the halo distance, the interpreter result is "1", otherwise
 *      "0".  If a closest element exists, the designated Tcl array
 *      variable will be set with the following information:
 *
 *      1) the element name,
 *      2) the index of the closest point,
 *      3) the distance (in screen coordinates) from the picked X-Y
 *         coordinate and the closest point,
 *      4) the X coordinate (graph coordinate) of the closest point,
 *      5) and the Y-coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClosestOp(
    RbcGraph * graph,          /* Graph widget */
    Tcl_Interp * interp,       /* Interpreter to report results to */
    int argc,                  /* Number of element names */
    const char **argv)
{              /* List of element names */
    RbcElement *elemPtr;
    RbcClosestSearch search;
    int i, x, y;
    int flags = TCL_LEAVE_ERR_MSG;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(graph->flags & RBC_RESET_AXES) {
        RbcResetAxes(graph);
    }
    if(Tk_GetPixels(interp, *(graph->win), argv[3], &x) != TCL_OK) {
        Tcl_AppendResult(interp, ": bad window x-coordinate", (char *)NULL);
        return TCL_ERROR;
    }
    if(Tk_GetPixels(interp, *(graph->win), argv[4], &y) != TCL_OK) {
        Tcl_AppendResult(interp, ": bad window y-coordinate", (char *)NULL);
        return TCL_ERROR;
    }
    if(graph->inverted) {
    int temp;

        temp = x, x = y, y = temp;
    }
    for(i = 6; i < argc; i += 2) {      /* Count switches-value pairs */
        if((argv[i][0] != '-') || ((argv[i][1] == '-') && (argv[i][2] == '\0'))) {
            break;
        }
    }
    if(i > argc) {
        i = argc;
    }

    search.mode = RBC_SEARCH_POINTS;
    search.halo = graph->halo;
    search.index = -1;
    search.along = RBC_SEARCH_BOTH;
    search.x = x;
    search.y = y;

    if(Tk_ConfigureWidget(interp, *(graph->win), closestSpecs, i - 6,
            argv + 6, (char *)&search, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
        return TCL_ERROR;       /* Error occurred processing an option. */
    }
    if((i < argc) && (argv[i][0] == '-')) {
        i++;   /* Skip "--" */
    }
    search.dist = (double)(search.halo + 1);

    if(i < argc) {
        for( /* empty */ ; i < argc; i++) {
            if(NameToElement(graph, argv[i], &elemPtr) != TCL_OK) {
                return TCL_ERROR;       /* Can't find named element */
            }
            if(elemPtr->hidden) {
                Tcl_AppendResult(interp, "element \"", argv[i], "\" is hidden",
                    (char *)NULL);
                return TCL_ERROR;       /* Element isn't visible */
            }
            /* Check if the X or Y vectors have notifications pending */
            if((elemPtr->flags & RBC_MAP_ITEM) ||
                (RbcVectorNotifyPending(elemPtr->x.clientId)) ||
                (RbcVectorNotifyPending(elemPtr->y.clientId))) {
                continue;
            }
            (*elemPtr->procsPtr->closestProc) (graph, elemPtr, &search);
        }
    } else {
    RbcChainLink *linkPtr;

        /*
         * Find the closest point from the set of displayed elements,
         * searching the display list from back to front.  That way if
         * the points from two different elements overlay each other
         * exactly, the last one picked will be the topmost.
         */
        for(linkPtr = RbcChainLastLink(graph->elements.displayList);
            linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
            elemPtr = RbcChainGetValue(linkPtr);

            /* Check if the X or Y vectors have notifications pending */
            if((elemPtr->flags & RBC_MAP_ITEM) ||
                (RbcVectorNotifyPending(elemPtr->x.clientId)) ||
                (RbcVectorNotifyPending(elemPtr->y.clientId))) {
                continue;
            }
            if(!elemPtr->hidden) {
                (*elemPtr->procsPtr->closestProc) (graph, elemPtr, &search);
            }
        }

    }
    if(search.dist < (double)search.halo) {
    char string[200];
        /*
         *  Return an array of 5 elements
         */
        if(Tcl_SetVar2(interp, argv[5], "name",
                search.elemPtr->name, flags) == NULL) {
            return TCL_ERROR;
        }
        sprintf(string, "%d", search.index);
        if(Tcl_SetVar2(interp, argv[5], "index", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.point.x, string);
        if(Tcl_SetVar2(interp, argv[5], "x", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.point.y, string);
        if(Tcl_SetVar2(interp, argv[5], "y", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_PrintDouble(interp, search.dist, string);
        if(Tcl_SetVar2(interp, argv[5], "dist", string, flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewIntObj(1));
    } else {
        if(Tcl_SetVar2(interp, argv[5], "name", "", flags) == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Sets the element specifications by the given the command line
 *      arguments and calls the element specification configuration
 *      routine. If zero or one command line options are given, only
 *      information about the option(s) is returned in interp->result.
 *      If the element configuration has changed and the element is
 *      currently displayed, the axis limits are updated and
 *      recomputed.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new display list.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcElement *elemPtr;
    int flags;
    int numNames, numOpts;
    const char **options;
    register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    /* Figure out where the option value pairs begin */
    argc -= 3;
    argv += 3;
    for(i = 0; i < argc; i++) {
        if(argv[i][0] == '-') {
            break;
        }
        if(NameToElement(graph, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
    }
    numNames = i;       /* Number of element names specified */
    numOpts = argc - i; /* Number of options specified */
    options = argv + numNames;  /* Start of options in argv  */

    for(i = 0; i < numNames; i++) {
        NameToElement(graph, argv[i], &elemPtr);
        flags = TK_CONFIG_ARGV_ONLY;
        if(numOpts == 0) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                elemPtr->specsPtr, (char *)elemPtr, (char *)NULL, flags);
        } else if(numOpts == 1) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                elemPtr->specsPtr, (char *)elemPtr, options[0], flags);
        }
        if(Tk_ConfigureWidget(interp, *(graph->win), elemPtr->specsPtr,
                numOpts, options, (char *)elemPtr, flags) != TCL_OK) {
            return TCL_ERROR;
        }
        if((*elemPtr->procsPtr->configProc) (graph, elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Failed to configure element */
        }
        if(RbcConfigModified(elemPtr->specsPtr, "-hide", (char *)NULL)) {
    RbcChainLink *linkPtr;

            for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
                linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
                if(elemPtr == RbcChainGetValue(linkPtr)) {
                    break;
                }
            }
            if((elemPtr->hidden) != (linkPtr == NULL)) {

                /* The element's "hidden" variable is out of sync with
                 * the display list. [That's what you get for having
                 * two ways to do the same thing.]  This affects what
                 * elements are considered for axis ranges and
                 * displayed in the legend. Update the display list by
                 * either by adding or removing the element.  */

                if(linkPtr == NULL) {
                    RbcChainPrepend(graph->elements.displayList, elemPtr);
                } else {
                    RbcChainDeleteLink(graph->elements.displayList, linkPtr);
                }
            }
            graph->flags |= RBC_RESET_AXES;
            elemPtr->flags |= RBC_MAP_ITEM;
        }
        /* If data points or axes have changed, reset the axes (may
         * affect autoscaling) and recalculate the screen points of
         * the element. */

        if(RbcConfigModified(elemPtr->specsPtr, "-*data", "-map*", "-x",
                "-y", (char *)NULL)) {
            graph->flags |= RBC_RESET_WORLD;
            elemPtr->flags |= RBC_MAP_ITEM;
        }
        /* The new label may change the size of the legend */
        if(RbcConfigModified(elemPtr->specsPtr, "-label", (char *)NULL)) {
            graph->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
        }
    }
    /* Update the pixmap if any configuration option changed */
    graph->flags |= (RBC_REDRAW_BACKING_STORE | RBC_DRAW_MARGINS);
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DeactivateOp --
 *
 *      Clears the active bit for the named elements.
 *
 * Results:
 *      Returns TCL_OK if no errors occurred.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
DeactivateOp(
    RbcGraph * graph,          /* Graph widget */
    Tcl_Interp * interp,       /* Not used. */
    int argc,                  /* Number of element names */
    const char **argv)
{              /* List of element names */
    RbcElement *elemPtr;
    register int i;

    for(i = 3; i < argc; i++) {
        if(NameToElement(graph, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
        elemPtr->flags &= ~RBC_ELEM_ACTIVE;
        if(elemPtr->activeIndices != NULL) {
            ckfree((char *)elemPtr->activeIndices);
            elemPtr->activeIndices = NULL;
        }
        elemPtr->nActiveIndices = 0;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DeleteOp --
 *
 *      Delete the named elements from the graph.
 *
 * Results:
 *      TCL_ERROR is returned if any of the named elements can not be
 *      found.  Otherwise TCL_OK is returned;
 *
 * Side Effects:
 *      If the element is currently displayed, the plotting area of
 *      the graph is redrawn. Memory and resources allocated by the
 *      elements are released.
 *
 *----------------------------------------------------------------------
 */
static int
DeleteOp(
    RbcGraph * graph,          /* Graph widget */
    Tcl_Interp * interp,       /* Not used. */
    int argc,                  /* Number of element names */
    const char **argv)
{              /* List of element names */
    RbcElement *elemPtr;
    register int i;

    for(i = 3; i < argc; i++) {
        if(NameToElement(graph, argv[i], &elemPtr) != TCL_OK) {
            return TCL_ERROR;   /* Can't find named element */
        }
        DestroyElement(graph, elemPtr);
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ExistsOp --
 *
 *      Indicates if the named element exists in the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.  The interpreter
 *      result will contain "1" or "0".
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ExistsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    Tcl_HashEntry *hPtr;

    hPtr = Tcl_FindHashEntry(&graph->elements.table, argv[3]);
    Tcl_SetObjResult(interp, Tcl_NewBooleanObj((hPtr != NULL)));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetOp --
 *
 *      Returns the name of the picked element (using the element
 *      bind operation).  Right now, the only name accepted is
 *      "current".
 *
 * Results:
 *      A standard Tcl result.  The interpreter result will contain
 *      the name of the element.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char *argv[])
{
    register RbcElement *elemPtr;

    if((argv[3][0] == 'c') && (strcmp(argv[3], "current") == 0)) {
        elemPtr = (RbcElement *) RbcGetCurrentItem(graph->bindTable);
        /* Report only on elements. */
        if((elemPtr != NULL) &&
            ((elemPtr->classUid == rbcBarElementUid) ||
                (elemPtr->classUid == rbcLineElementUid) ||
                (elemPtr->classUid == rbcStripElementUid))) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->name, -1));
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NamesOp --
 *
 *      Returns the names of the elements is the graph matching
 *      one of more patterns provided.  If no pattern arguments
 *      are given, then all element names will be returned.
 *
 * Results:
 *      The return value is a standard Tcl result. The interpreter
 *      result will contain a Tcl list of the element names.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NamesOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcElement *elemPtr;
    Tcl_HashSearch cursor;
    register Tcl_HashEntry *hPtr;
    register int i;

    for(hPtr = Tcl_FirstHashEntry(&graph->elements.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
        if(argc == 3) {
            Tcl_AppendElement(graph->interp, elemPtr->name);
            continue;
        }
        for(i = 3; i < argc; i++) {
            if(Tcl_StringMatch(elemPtr->name, argv[i])) {
                Tcl_AppendElement(interp, elemPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ShowOp --
 *
 *      Queries or resets the element display list.
 *
 * Results:
 *      The return value is a standard Tcl result. The interpreter
 *      result will contain the new display list of element names.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ShowOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcElement *elemPtr;
    RbcChainLink *linkPtr;

    if(argc == 4) {
        if(RebuildDisplayList(graph, argv[3]) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    for(linkPtr = RbcChainFirstLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        Tcl_AppendElement(interp, elemPtr->name);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TypeOp --
 *
 *      Returns the name of the type of the element given by some
 *      element name.
 *
 * Results:
 *      A standard Tcl result. Returns the type of the element in
 *      interp->result. If the identifier given doesn't represent an
 *      element, then an error message is left in interp->result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
TypeOp(
    RbcGraph * graph,          /* Graph widget */
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{              /* Element name */
    RbcElement *elemPtr;

    if(NameToElement(graph, argv[3], &elemPtr) != TCL_OK) {
        return TCL_ERROR;       /* Can't find named element */
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->classUid, -1));
    return TCL_OK;
}

/*
 * Global routines:
 */
static RbcOpSpec elemOps[] = {
    {"activate", 1, (RbcOp) ActivateOp, 3, 0, "?elemName? ?index...?",},
    {"bind", 1, (RbcOp) BindOp, 3, 6, "elemName sequence command",},
    {"cget", 2, (RbcOp) CgetOp, 5, 5, "elemName option",},
    {"closest", 2, (RbcOp) ClosestOp, 6, 0,
        "x y varName ?option value?... ?elemName?...",},
    {"configure", 2, (RbcOp) ConfigureOp, 4, 0,
        "elemName ?elemName?... ?option value?...",},
    {"create", 2, (RbcOp) CreateOp, 4, 0, "elemName ?option value?...",},
    {"deactivate", 3, (RbcOp) DeactivateOp, 3, 0, "?elemName?...",},
    {"delete", 3, (RbcOp) DeleteOp, 3, 0, "?elemName?...",},
    {"exists", 1, (RbcOp) ExistsOp, 4, 4, "elemName",},
    {"get", 1, (RbcOp) GetOp, 4, 4, "name",},
    {"names", 1, (RbcOp) NamesOp, 3, 0, "?pattern?...",},
    {"show", 1, (RbcOp) ShowOp, 3, 4, "?elemList?",},
    {"type", 1, (RbcOp) TypeOp, 4, 4, "elemName",},
};

static int numElemOps = sizeof(elemOps) / sizeof(RbcOpSpec);

/*
 * ----------------------------------------------------------------
 *
 * RbcElementOp --
 *
 *      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.
 *
 * ----------------------------------------------------------------
 */
int
RbcElementOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* # arguments */
    const char **argv,         /* Argument list */
    Tk_Uid type)
{
    RbcOp proc;
    int result;

    proc = RbcGetOp(interp, numElemOps, elemOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    if(proc == CreateOp) {
        result = CreateOp(graph, interp, argc, argv, type);
    } else {
        result = (*proc) (graph, interp, argc, argv);
    }
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphGrid.c.
































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrGrid.c --
 *
 *      This module implements grid lines for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcDashesOption;
extern Tk_CustomOption rbcAnyXAxisOption;
extern Tk_CustomOption rbcAnyYAxisOption;

#define DEF_GRID_DASHES             "dot"
#define DEF_GRID_FOREGROUND         "gray64"
#define DEF_GRID_FG_MONO            "black"
#define DEF_GRID_LINE_WIDTH         "0"
#define DEF_GRID_HIDE_BARCHART      "no"
#define DEF_GRID_HIDE_GRAPH         "yes"
#define DEF_GRID_MINOR              "yes"
#define DEF_GRID_MAP_X_GRAPH        "x"
#define DEF_GRID_MAP_X_BARCHART     (char *)NULL
#define DEF_GRID_MAP_Y              "y"
#define DEF_GRID_POSITION           (char *)NULL

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_GRID_FOREGROUND,
            Tk_Offset(RbcGrid, colorPtr),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-color", "color", "color", DEF_GRID_FG_MONO,
        Tk_Offset(RbcGrid, colorPtr), TK_CONFIG_MONO_ONLY | RBC_ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes", DEF_GRID_DASHES,
            Tk_Offset(RbcGrid, dashes), TK_CONFIG_NULL_OK | RBC_ALL_GRAPHS,
        &rbcDashesOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_GRID_HIDE_BARCHART,
        Tk_Offset(RbcGrid, hidden), RBC_BARCHART},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_GRID_HIDE_GRAPH,
        Tk_Offset(RbcGrid, hidden), RBC_GRAPH | RBC_STRIPCHART},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "Linewidth",
            DEF_GRID_LINE_WIDTH, Tk_Offset(RbcGrid, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_GRID_MAP_X_GRAPH,
            Tk_Offset(RbcGrid, axes.x), RBC_GRAPH | RBC_STRIPCHART,
        &rbcAnyXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_GRID_MAP_X_BARCHART,
        Tk_Offset(RbcGrid, axes.x), RBC_BARCHART, &rbcAnyXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_GRID_MAP_Y,
        Tk_Offset(RbcGrid, axes.y), RBC_ALL_GRAPHS, &rbcAnyYAxisOption},
    {TK_CONFIG_BOOLEAN, "-minor", "minor", "Minor", DEF_GRID_MINOR,
            Tk_Offset(RbcGrid, minorGrid),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_GRAPHS},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static void ConfigureGrid(
    RbcGraph * graph,
    RbcGrid * gridPtr);
static int CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int MapOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int UnmapOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ToggleOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * ConfigureGrid --
 *
 *      Configures attributes of the grid such as line width,
 *      dashes, and position.  The grid are first turned off
 *      before any of the attributes changes.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
static void
ConfigureGrid(
    RbcGraph * graph,
    RbcGrid * gridPtr)
{
XGCValues gcValues;
unsigned long gcMask;
GC  newGC;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    gcValues.background = gcValues.foreground = gridPtr->colorPtr->pixel;
    gcValues.line_width = RbcLineWidth(gridPtr->lineWidth);
    gcMask = (GCForeground | GCBackground | GCLineWidth);
    if(RbcLineIsDashed(gridPtr->dashes)) {
        gcValues.line_style = LineOnOffDash;
        gcMask |= GCLineStyle;
    }
    newGC = RbcGetPrivateGC(*(graph->win), gcMask, &gcValues);
    if(RbcLineIsDashed(gridPtr->dashes)) {
        RbcSetDashes(graph->display, newGC, &(gridPtr->dashes));
    }
    if(gridPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, gridPtr->gc);
    }
    gridPtr->gc = newGC;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapGrid --
 *
 *      Determines the coordinates of the line segments corresponding
 *      to the grid lines for each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapGrid(
    RbcGraph * graph)
{
RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;
int nSegments;
RbcSegment2D *segments;

    if(gridPtr->x.segments != NULL) {
        ckfree((char *)gridPtr->x.segments);
        gridPtr->x.segments = NULL;
    }
    if(gridPtr->y.segments != NULL) {
        ckfree((char *)gridPtr->y.segments);
        gridPtr->y.segments = NULL;
    }
    gridPtr->x.nSegments = gridPtr->y.nSegments = 0;
    /*
     * Generate line segments to represent the grid.  Line segments
     * are calculated from the major tick intervals of each axis mapped.
     */
    RbcGetAxisSegments(graph, gridPtr->axes.x, &segments, &nSegments);
    if(nSegments > 0) {
        gridPtr->x.nSegments = nSegments;
        gridPtr->x.segments = segments;
    }
    RbcGetAxisSegments(graph, gridPtr->axes.y, &segments, &nSegments);
    if(nSegments > 0) {
        gridPtr->y.nSegments = nSegments;
        gridPtr->y.segments = segments;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawGrid --
 *
 *      Draws the grid lines associated with each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDrawGrid(
    RbcGraph * graph,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    if(gridPtr->hidden) {
        return;
    }
    if(gridPtr->x.nSegments > 0) {
        RbcDraw2DSegments(graph->display, drawable, gridPtr->gc,
            gridPtr->x.segments, gridPtr->x.nSegments);
    }
    if(gridPtr->y.nSegments > 0) {
        RbcDraw2DSegments(graph->display, drawable, gridPtr->gc,
            gridPtr->y.segments, gridPtr->y.nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGridToPostScript --
 *
 *      Prints the grid lines associated with each axis.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcGridToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    if(gridPtr->hidden) {
        return;
    }
    RbcLineAttributesToPostScript(psToken, gridPtr->colorPtr,
        gridPtr->lineWidth, &(gridPtr->dashes), CapButt, JoinMiter);
    if(gridPtr->x.nSegments > 0) {
        Rbc2DSegmentsToPostScript(psToken, gridPtr->x.segments,
            gridPtr->x.nSegments);
    }
    if(gridPtr->y.nSegments > 0) {
        Rbc2DSegmentsToPostScript(psToken, gridPtr->y.segments,
            gridPtr->y.nSegments);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyGrid --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Grid GC is released.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyGrid(
    RbcGraph * graph)
{
RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    Tk_FreeOptions(configSpecs, (char *)gridPtr, graph->display,
        RbcGraphType(graph));
    if(gridPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, gridPtr->gc);
    }
    if(gridPtr->x.segments != NULL) {
        ckfree((char *)gridPtr->x.segments);
    }
    if(gridPtr->y.segments != NULL) {
        ckfree((char *)gridPtr->y.segments);
    }
    ckfree((char *)gridPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateGrid --
 *
 *      Creates and initializes a new grid structure.
 *
 * Results:
 *      Returns TCL_ERROR if the configuration failed, otherwise TCL_OK.
 *
 * Side Effects:
 *      Memory for grid structure is allocated.
 *
 *----------------------------------------------------------------------
 */
int
RbcCreateGrid(
    RbcGraph * graph)
{
RbcGrid *gridPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    gridPtr = RbcCalloc(1, sizeof(RbcGrid));
    assert(gridPtr);
    gridPtr->minorGrid = TRUE;
    graph->gridPtr = gridPtr;

    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win), "grid",
            "Grid", configSpecs, 0, (const char **)NULL, (char *)gridPtr,
            RbcGraphType(graph)) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureGrid(graph, gridPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries configuration attributes of the grid such as line
 *      width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    return Tk_ConfigureValue(interp, *(graph->win), configSpecs,
        (char *)gridPtr, argv[3], RbcGraphType(graph));
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets configuration attributes of the grid
 *      such as line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset.  The graph is redrawn at the
 *      next idle point.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;
    int flags;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    flags = RbcGraphType(graph) | TK_CONFIG_ARGV_ONLY;
    if(argc == 3) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)gridPtr, (char *)NULL, flags);
    } else if(argc == 4) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)gridPtr, argv[3], flags);
    }
    if(Tk_ConfigureWidget(graph->interp, *(graph->win), configSpecs,
            argc - 3, argv + 3, (char *)gridPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureGrid(graph, gridPtr);
    graph->flags |= RBC_REDRAW_BACKING_STORE;
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MapOp --
 *
 *      Maps the grid.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset and the graph is redrawn if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
MapOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    if(gridPtr->hidden) {
        gridPtr->hidden = FALSE;        /* Changes "-hide" configuration option */
        graph->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graph);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * MapOp --
 *
 *      Maps or unmaps the grid (off or on).
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid attributes are reset and the graph is redrawn if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
UnmapOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    if(!gridPtr->hidden) {
        gridPtr->hidden = TRUE; /* Changes "-hide" configuration option */
        graph->flags |= RBC_REDRAW_BACKING_STORE;
        RbcEventuallyRedrawGraph(graph);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleOp --
 *
 *      Toggles the state of the grid shown/hidden.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Grid is hidden/displayed. The graph is redrawn at the next
 *      idle time.
 *
 *----------------------------------------------------------------------
 */
static int
ToggleOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcGrid *gridPtr = (RbcGrid *) graph->gridPtr;

    gridPtr->hidden = (!gridPtr->hidden);
    graph->flags |= RBC_REDRAW_BACKING_STORE;
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

static RbcOpSpec gridOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?options...?",},
    {"off", 2, (RbcOp) UnmapOp, 3, 3, "",},
    {"on", 2, (RbcOp) MapOp, 3, 3, "",},
    {"toggle", 1, (RbcOp) ToggleOp, 3, 3, "",},
};

static int nGridOps = sizeof(gridOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcGridOp --
 *
 *      User routine to configure grid lines.  Grids are drawn
 *      at major tick intervals across the graph.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Grid may be drawn in the plotting area.
 *
 *----------------------------------------------------------------------
 */
int
RbcGridOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp proc;

    proc = RbcGetOp(interp, nGridOps, gridOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    return (*proc) (graph, interp, argc, argv);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphHairs.c.
















































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrHairs.c --
 *
 *      This module implements crosshairs for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/

#include "tkoGraph.h"

extern Tk_CustomOption rbcPointOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcDashesOption;

/*
 * -------------------------------------------------------------------
 *
 * RbcCrosshairs --
 *
 *      Contains the line segments positions and graphics context used
 *      to simulate crosshairs (by XORing) on the graph.
 *
 * -------------------------------------------------------------------
 */

typedef struct RbcCrosshairs {

    XPoint hotSpot;            /* Hot spot for crosshairs */
    int visible;               /* Internal state of crosshairs. If non-zero,
                                * crosshairs are displayed. */
    int hidden;                /* If non-zero, crosshairs are not displayed.
                                * This is not necessarily consistent with the
                                * internal state variable.  This is true when
                                * the hot spot is off the graph.  */
    RbcDashes dashes;          /* Dashstyle of the crosshairs. This represents
                                * an array of alternatingly drawn pixel
                                * values. If NULL, the hairs are drawn as a
                                * solid line */
    int lineWidth;             /* Width of the simulated crosshair lines */
    XSegment segArr[2];        /* Positions of line segments representing the
                                * simulated crosshairs. */
    XColor *colorPtr;          /* Foreground color of crosshairs */
    GC  gc;                    /* Graphics context for crosshairs. Set to
                                * GXxor to not require redraws of graph */
} RbcCrosshairs;

#define DEF_HAIRS_DASHES	(char *)NULL
#define DEF_HAIRS_FOREGROUND	"#000000"
#define DEF_HAIRS_FG_MONO	"#000000"
#define DEF_HAIRS_LINE_WIDTH	"0"
#define DEF_HAIRS_HIDE		"yes"
#define DEF_HAIRS_POSITION	(char *)NULL

static const Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_HAIRS_FOREGROUND,
        Tk_Offset(RbcCrosshairs, colorPtr), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-color", "color", "Color", DEF_HAIRS_FG_MONO,
        Tk_Offset(RbcCrosshairs, colorPtr), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes", DEF_HAIRS_DASHES,
            Tk_Offset(RbcCrosshairs, dashes), TK_CONFIG_NULL_OK,
        &rbcDashesOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_HAIRS_HIDE,
        Tk_Offset(RbcCrosshairs, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "Linewidth",
            DEF_HAIRS_LINE_WIDTH, Tk_Offset(RbcCrosshairs, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-position", "position", "Position", DEF_HAIRS_POSITION,
        Tk_Offset(RbcCrosshairs, hotSpot), 0, &rbcPointOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* TODO new object code
static const Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_COLOR, "-color", "color", "Color", DEF_HAIRS_FOREGROUND, -1, Tk_Offset(Crosshairs, colorPtr), TK_CONFIG_COLOR_ONLY, NULL, 0},
    {TK_OPTION_COLOR, "-color", "color", "Color", DEF_HAIRS_FG_MONO, -1, Tk_Offset(Crosshairs, colorPtr), TK_CONFIG_MONO_ONLY, NULL, 0},
    {TK_OPTION_CUSTOM, "-dashes", "dashes", "Dashes", DEF_HAIRS_DASHES, -1, Tk_Offset(Crosshairs, dashes), TK_CONFIG_NULL_OK, &rbcDashesOption, 0},
    {TK_OPTION_BOOLEAN, "-hide", "hide", "Hide", DEF_HAIRS_HIDE, -1, Tk_Offset(Crosshairs, hidden), TK_CONFIG_DONT_SET_DEFAULT, NULL, 0},
    {TK_OPTION_CUSTOM, "-linewidth", "lineWidth", "Linewidth", DEF_HAIRS_LINE_WIDTH, -1, Tk_Offset(Crosshairs, lineWidth), TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption, 0},
    {TK_OPTION_CUSTOM, "-position", "position", "Position", DEF_HAIRS_POSITION, -1, Tk_Offset(Crosshairs, hotSpot), 0, &rbcPointOption, 0},
    {TK_OPTION_END, NULL, NULL, NULL, NULL, 0, -1, 0, NULL, 0}
};
*/

static void TurnOffHairs(
    Tk_Window tkwin,
    RbcCrosshairs * chPtr);
static void TurnOnHairs(
    RbcGraph * graph,
    RbcCrosshairs * chPtr);
static int CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int OnOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int OffOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ToggleOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------
 *
 * TurnOffHairs --
 *
 *      XOR's the existing line segments (representing the crosshairs),
 *      thereby erasing them.  The internal state of the crosshairs is
 *      tracked.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshairs are erased.
 *
 *----------------------------------------------------------------------
 */
static void
TurnOffHairs(
    Tk_Window tkwin,
    RbcCrosshairs * chPtr)
{
    if(Tk_IsMapped(tkwin) && (chPtr->visible)) {
        XDrawSegments(Tk_Display(tkwin), Tk_WindowId(tkwin), chPtr->gc,
            chPtr->segArr, 2);
        chPtr->visible = FALSE;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TurnOnHairs --
 *
 *      Draws (by XORing) new line segments, creating the effect of
 *      crosshairs. The internal state of the crosshairs is tracked.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshairs are displayed.
 *
 *----------------------------------------------------------------------
 */
static void
TurnOnHairs(
    RbcGraph * graph,
    RbcCrosshairs * chPtr)
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if(Tk_IsMapped(*(graph->win)) && (!chPtr->visible)) {
        /* Coordinates are off the graph */
        if(chPtr->hotSpot.x > graph->right
            || chPtr->hotSpot.x < graph->left
            || chPtr->hotSpot.y > graph->bottom
            || chPtr->hotSpot.y < graph->top)
            return;
        XDrawSegments(graph->display, Tk_WindowId(*(graph->win)),
            chPtr->gc, chPtr->segArr, 2);
        chPtr->visible = TRUE;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcConfigureCrosshairs --
 *
 *      Configures attributes of the crosshairs such as line width,
 *      dashes, and position.  The crosshairs are first turned off
 *      before any of the attributes changes.
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
void
RbcConfigureCrosshairs(
    RbcGraph * graph)
{
XGCValues gcValues;
unsigned long gcMask;
GC  newGC;
long colorValue;
RbcCrosshairs *chPtr = graph->crosshairs;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    /*
     * Turn off the crosshairs temporarily. This is in case the new
     * configuration changes the size, style, or position of the lines.
     */
    TurnOffHairs(*(graph->win), chPtr);

    gcValues.function = GXxor;

    if(graph->plotBg == NULL) {
        /* The graph's color option may not have been set yet */
        colorValue = WhitePixelOfScreen(Tk_Screen(*(graph->win)));
    } else {
        colorValue = graph->plotBg->pixel;
    }
    gcValues.background = colorValue;
    gcValues.foreground = (colorValue ^ chPtr->colorPtr->pixel);

    gcValues.line_width = RbcLineWidth(chPtr->lineWidth);
    gcMask = (GCForeground | GCBackground | GCFunction | GCLineWidth);
    if(RbcLineIsDashed(chPtr->dashes)) {
        gcValues.line_style = LineOnOffDash;
        gcMask |= GCLineStyle;
    }
    newGC = RbcGetPrivateGC(*(graph->win), gcMask, &gcValues);
    if(RbcLineIsDashed(chPtr->dashes)) {
        RbcSetDashes(graph->display, newGC, &(chPtr->dashes));
    }
    if(chPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, chPtr->gc);
    }
    chPtr->gc = newGC;

    /*
     * Are the new coordinates on the graph?
     */
    chPtr->segArr[0].x2 = chPtr->segArr[0].x1 = chPtr->hotSpot.x;
    chPtr->segArr[0].y1 = graph->bottom;
    chPtr->segArr[0].y2 = graph->top;
    chPtr->segArr[1].y2 = chPtr->segArr[1].y1 = chPtr->hotSpot.y;
    chPtr->segArr[1].x1 = graph->left;
    chPtr->segArr[1].x2 = graph->right;

    if(!chPtr->hidden) {
        TurnOnHairs(graph, chPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcEnableCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcEnableCrosshairs(
    RbcGraph * graph)
{
    if(!graph->crosshairs->hidden) {
        TurnOnHairs(graph, graph->crosshairs);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDisableCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDisableCrosshairs(
    RbcGraph * graph)
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    if(!graph->crosshairs->hidden) {
        TurnOffHairs(*(graph->win), graph->crosshairs);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcUpdateCrosshairs --
 *
 *      Update the length of the hairs (not the hot spot).
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcUpdateCrosshairs(
    RbcGraph * graph)
{
RbcCrosshairs *chPtr = graph->crosshairs;

    chPtr->segArr[0].y1 = graph->bottom;
    chPtr->segArr[0].y2 = graph->top;
    chPtr->segArr[1].x1 = graph->left;
    chPtr->segArr[1].x2 = graph->right;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyCrosshairs --
 *
 *      TODO: Description
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyCrosshairs(
    RbcGraph * graph)
{
RbcCrosshairs *chPtr = graph->crosshairs;

    Tk_FreeOptions(configSpecs, (char *)chPtr, graph->display, 0);
    if(chPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, chPtr->gc);
    }
    ckfree((char *)chPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateCrosshairs --
 *
 *      Creates and initializes a new crosshair structure.
 *
 * Results:
 *      Returns TCL_ERROR if the crosshair structure can't be created,
 *      otherwise TCL_OK.
 *
 * Side Effects:
 *      Crosshair GC is allocated.
 *
 *----------------------------------------------------------------------
 */
int
RbcCreateCrosshairs(
    RbcGraph * graph)
{
RbcCrosshairs *chPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    chPtr = RbcCalloc(1, sizeof(RbcCrosshairs));
    assert(chPtr);
    chPtr->hidden = TRUE;
    chPtr->hotSpot.x = chPtr->hotSpot.y = -1;
    graph->crosshairs = chPtr;

    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win),
            "crosshairs", "Crosshairs", configSpecs, 0, (const char **)NULL,
            (char *)chPtr, 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries configuration attributes of the crosshairs such as
 *      line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char **argv)
{
    RbcCrosshairs *chPtr = graph->crosshairs;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    return Tk_ConfigureValue(interp, *(graph->win), configSpecs,
        (char *)chPtr, argv[3], 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets configuration attributes of the crosshairs
 *      such as line width, dashes, and position.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs *chPtr = graph->crosshairs;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(argc == 3) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)chPtr, (char *)NULL, 0);
    } else if(argc == 4) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)chPtr, argv[3], 0);
    }
    if(Tk_ConfigureWidget(interp, *(graph->win), configSpecs, argc - 3,
            argv + 3, (char *)chPtr, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
        return TCL_ERROR;
    }
    RbcConfigureCrosshairs(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * OnOp --
 *
 *      Maps the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
OnOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs *chPtr = graph->crosshairs;

    if(chPtr->hidden) {
        TurnOnHairs(graph, chPtr);
        chPtr->hidden = FALSE;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * OffOp --
 *
 *      Unmaps the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset if necessary.
 *
 *----------------------------------------------------------------------
 */
static int
OffOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs *chPtr = graph->crosshairs;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(!chPtr->hidden) {
        TurnOffHairs(*(graph->win), chPtr);
        chPtr->hidden = TRUE;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ToggleOp --
 *
 *      Toggles the state of the crosshairs.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs are reset.
 *
 *----------------------------------------------------------------------
 */
static int
ToggleOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcCrosshairs *chPtr = graph->crosshairs;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    chPtr->hidden = (chPtr->hidden == 0);
    if(chPtr->hidden) {
        TurnOffHairs(*(graph->win), chPtr);
    } else {
        TurnOnHairs(graph, chPtr);
    }
    return TCL_OK;
}

static RbcOpSpec xhairOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?options...?",},
    {"off", 2, (RbcOp) OffOp, 3, 3, "",},
    {"on", 2, (RbcOp) OnOp, 3, 3, "",},
    {"toggle", 1, (RbcOp) ToggleOp, 3, 3, "",},
};

static int nXhairOps = sizeof(xhairOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcCrosshairsOp --
 *
 *      User routine to configure crosshair simulation.  Crosshairs
 *      are simulated by drawing line segments parallel to both axes
 *      using the XOR drawing function. The allows the lines to be
 *      erased (by drawing them again) without redrawing the entire
 *      graph.  Care must be taken to erase crosshairs before redrawing
 *      the graph and redraw them after the graph is redraw.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Crosshairs may be drawn in the plotting area.
 *
 *----------------------------------------------------------------------
 */
int
RbcCrosshairsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp proc;

    proc = RbcGetOp(interp, nXhairOps, xhairOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    return (*proc) (graph, interp, argc, argv);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphLegd.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrLegd.c --
 *
 *      This module implements the legend for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

/*
 * -------------------------------------------------------------------
 *
 * Legend --
 *
 *      Contains information specific to how the legend will be
 *      displayed.
 *
 * -------------------------------------------------------------------
 */
typedef struct RbcLegend {
    unsigned int flags;
    Tk_Uid classUid;           /* Type: Element or Marker. */
    int hidden;                /* If non-zero, don't display the legend. */
    int raised;                /* If non-zero, draw the legend last, above
                                * everything else. */
    int nEntries;              /* Number of element entries in table. */
    short int width, height;   /* Dimensions of the legend */
    short int nColumns, nRows; /* Number of columns and rows in legend */
    int site;
    RbcPoint2D anchorPos;      /* Says how to position the legend. Indicates
                                * the site and/or x-y screen coordinates of
                                * the legend.  Used in conjunction with the
                                * anchor to determine its location. */
    Tk_Anchor anchor;          /* Anchor of legend. Used to interpret the
                                * positioning point of the legend in the
                                * graph*/
    int x, y;                  /* Computed origin of legend. */
    RbcGraph *graph;
    Tcl_Command cmdToken;      /* Token for graph's widget command. */
    int reqColumns, reqRows;
    RbcPad ipadX, ipadY;       /* # of pixels padding around legend entries */
    RbcPad padX, padY;         /* # of pixels padding to exterior of legend */
    Tk_Window tkwin;           /* Optional external window to draw legend. */
    RbcTextStyle style;
    int maxSymSize;            /* Size of largest symbol to be displayed.
                                * Used to calculate size of legend */
    Tk_3DBorder activeBorder;  /* Active legend entry background color. */
    int activeRelief;          /* 3-D effect on active entry. */
    int entryBorderWidth;      /* Border width around each entry in legend. */
    Tk_3DBorder border;        /* 3-D effect of legend. */
    int borderWidth;           /* Width of legend 3-D border */
    int relief;                /* 3-d effect of border around the legend:
                                * TK_RELIEF_RAISED etc. */
    RbcBindTable *bindTable;
} RbcLegend;

#define DEF_LEGEND_ACTIVE_BACKGROUND    RBC_ACTIVE_BACKGROUND
#define DEF_LEGEND_ACTIVE_BG_MONO       RBC_ACTIVE_BG_MONO
#define DEF_LEGEND_ACTIVE_BORDERWIDTH   "2"
#define DEF_LEGEND_ACTIVE_FOREGROUND    RBC_ACTIVE_FOREGROUND
#define DEF_LEGEND_ACTIVE_FG_MONO       RBC_ACTIVE_FG_MONO
#define DEF_LEGEND_ACTIVE_RELIEF        "flat"
#define DEF_LEGEND_ANCHOR               "n"
#define DEF_LEGEND_BACKGROUND           (char *)NULL
#define DEF_LEGEND_BG_MONO              (char *)NULL
#define DEF_LEGEND_BORDERWIDTH          RBC_BORDERWIDTH
#define DEF_LEGEND_FOREGROUND           RBC_NORMAL_FOREGROUND
#define DEF_LEGEND_FG_MONO              RBC_NORMAL_FG_MONO
#define DEF_LEGEND_FONT                 RBC_FONT_SMALL
#define DEF_LEGEND_HIDE                 "no"
#define DEF_LEGEND_IPAD_X               "1"
#define DEF_LEGEND_IPAD_Y               "1"
#define DEF_LEGEND_PAD_X                "1"
#define DEF_LEGEND_PAD_Y                "1"
#define DEF_LEGEND_POSITION             "rightmargin"
#define DEF_LEGEND_RAISED               "no"
#define DEF_LEGEND_RELIEF               "sunken"
#define DEF_LEGEND_SHADOW_COLOR         (char *)NULL
#define DEF_LEGEND_SHADOW_MONO          (char *)NULL
#define DEF_LEGEND_ROWS                 "0"
#define DEF_LEGEND_COLUMNS              "0"

static Tk_OptionParseProc StringToPosition;
static Tk_OptionPrintProc PositionToString;
static Tk_CustomOption legendPositionOption = {
    StringToPosition, PositionToString, (ClientData) 0
};

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcPadOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcCountOption;

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BORDER, "-activebackground", "activeBackground",
            "ActiveBackground", DEF_LEGEND_ACTIVE_BACKGROUND,
        Tk_Offset(RbcLegend, activeBorder), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-activebackground", "activeBackground",
            "ActiveBackground", DEF_LEGEND_ACTIVE_BG_MONO, Tk_Offset(RbcLegend,
            activeBorder), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-activeborderwidth", "activeBorderWidth", "BorderWidth",
            DEF_LEGEND_BORDERWIDTH, Tk_Offset(RbcLegend, entryBorderWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_COLOR, "-activeforeground", "activeForeground",
            "ActiveForeground", DEF_LEGEND_ACTIVE_FOREGROUND,
        Tk_Offset(RbcLegend, style.activeColor), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-activeforeground", "activeForeground",
            "ActiveForeground", DEF_LEGEND_ACTIVE_FG_MONO, Tk_Offset(RbcLegend,
            style.activeColor), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_RELIEF, "-activerelief", "activeRelief", "Relief",
            DEF_LEGEND_ACTIVE_RELIEF, Tk_Offset(RbcLegend, activeRelief),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", DEF_LEGEND_ANCHOR,
        Tk_Offset(RbcLegend, anchor), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_LEGEND_BG_MONO, Tk_Offset(RbcLegend, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
            DEF_LEGEND_BACKGROUND, Tk_Offset(RbcLegend, border),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
            DEF_LEGEND_BORDERWIDTH, Tk_Offset(RbcLegend, borderWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_CUSTOM, "-columns", "columns", "columns", DEF_LEGEND_COLUMNS,
            Tk_Offset(RbcLegend, reqColumns), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcCountOption},
    {TK_CONFIG_FONT, "-font", "font", "Font", DEF_LEGEND_FONT,
        Tk_Offset(RbcLegend, style.font), 0},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_LEGEND_FOREGROUND, Tk_Offset(RbcLegend, style.color),
        TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_LEGEND_FG_MONO, Tk_Offset(RbcLegend, style.color),
        TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_LEGEND_HIDE,
        Tk_Offset(RbcLegend, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-ipadx", "iPadX", "Pad", DEF_LEGEND_IPAD_X,
            Tk_Offset(RbcLegend, ipadX), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-ipady", "iPadY", "Pad", DEF_LEGEND_IPAD_Y,
            Tk_Offset(RbcLegend, ipadY), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-padx", "padX", "Pad", DEF_LEGEND_PAD_X,
            Tk_Offset(RbcLegend, padX), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-pady", "padY", "Pad", DEF_LEGEND_PAD_Y,
            Tk_Offset(RbcLegend, padY), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-position", "position", "Position", DEF_LEGEND_POSITION,
        0, TK_CONFIG_DONT_SET_DEFAULT, &legendPositionOption},
    {TK_CONFIG_BOOLEAN, "-raised", "raised", "Raised", DEF_LEGEND_RAISED,
        Tk_Offset(RbcLegend, raised), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief", DEF_LEGEND_RELIEF,
        Tk_Offset(RbcLegend, relief), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-rows", "rows", "rows", DEF_LEGEND_ROWS,
            Tk_Offset(RbcLegend, reqRows), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcCountOption},
    {TK_CONFIG_CUSTOM, "-shadow", "shadow", "Shadow", DEF_LEGEND_SHADOW_COLOR,
            Tk_Offset(RbcLegend, style.shadow), TK_CONFIG_COLOR_ONLY,
        &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-shadow", "shadow", "Shadow", DEF_LEGEND_SHADOW_MONO,
            Tk_Offset(RbcLegend, style.shadow), TK_CONFIG_MONO_ONLY,
        &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static Tcl_IdleProc DisplayLegend;
static RbcBindPickProc PickLegendEntry;
static Tk_EventProc LegendEventProc;

static void EventuallyRedrawLegend(
    RbcLegend * legendPtr);
static int CreateLegendWindow(
    Tcl_Interp * interp,
    RbcLegend * legendPtr,
    const char *pathName);
static void SetLegendOrigin(
    RbcLegend * legendPtr);
static void ConfigureLegend(
    RbcGraph * graph,
    RbcLegend * legendPtr);
static int GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int ActivateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);

/*
 *--------------------------------------------------------------
 *
 * EventuallyRedrawLegend --
 *
 *      Tells the Tk dispatcher to call the graph display routine at
 *      the next idle point.  This request is made only if the window
 *      is displayed and no other redraw request is pending.
 *
 * Results:
 *       None.
 *
 * Side effects:
 *      The window is eventually redisplayed.
 *
 *--------------------------------------------------------------
 */
static void
EventuallyRedrawLegend(
    RbcLegend * legendPtr)
{              /* Legend record */
    if((legendPtr->tkwin != NULL) && !(legendPtr->flags & RBC_REDRAW_PENDING)) {
        Tcl_DoWhenIdle(DisplayLegend, legendPtr);
        legendPtr->flags |= RBC_REDRAW_PENDING;
    }
}

/*
 *--------------------------------------------------------------
 *
 * LegendEventProc --
 *
 *      This procedure is invoked by the Tk dispatcher for various
 *      events on graphs.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      When the window gets deleted, internal structures get
 *      cleaned up.  When it gets exposed, the graph is eventually
 *      redisplayed.
 *
 *--------------------------------------------------------------
 */
static void
LegendEventProc(
    ClientData clientData,     /* Legend record */
    register XEvent * eventPtr)
{              /* Event which triggered call to routine */
    RbcLegend *legendPtr = clientData;

    if(eventPtr->type == Expose) {
        if(eventPtr->xexpose.count == 0) {
            EventuallyRedrawLegend(legendPtr);
        }
    } else if(eventPtr->type == DestroyNotify) {
    RbcGraph *graph = legendPtr->graph;
        if(graph->win == NULL || *(graph->win) == NULL)
            return;

        if(legendPtr->tkwin != *(graph->win)) {
            RbcDeleteWindowInstanceData(legendPtr->tkwin);
            if(legendPtr->cmdToken != NULL) {
                Tcl_DeleteCommandFromToken(graph->interp, legendPtr->cmdToken);
                legendPtr->cmdToken = NULL;
            }
            legendPtr->tkwin = *(graph->win);
        }
        if(legendPtr->flags & RBC_REDRAW_PENDING) {
            Tcl_CancelIdleCall(DisplayLegend, legendPtr);
            legendPtr->flags &= ~RBC_REDRAW_PENDING;
        }
        legendPtr->site = RBC_LEGEND_RIGHT;
        graph->flags |= (RBC_MAP_WORLD | RBC_REDRAW_WORLD);
        RbcMoveBindingTable(legendPtr->bindTable, *(graph->win));
        RbcEventuallyRedrawGraph(graph);
    } else if(eventPtr->type == ConfigureNotify) {
        EventuallyRedrawLegend(legendPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * CreateLegendWindow --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CreateLegendWindow(
    Tcl_Interp * interp,
    RbcLegend * legendPtr,
    const char *pathName)
{
    Tk_Window tkwin;
    if(legendPtr->graph->win == NULL || *(legendPtr->graph->win) == NULL)
        return TCL_ERROR;

    tkwin = Tk_MainWindow(interp);
    tkwin = Tk_CreateWindowFromPath(interp, tkwin, pathName, NULL);
    if(tkwin == NULL) {
        return TCL_ERROR;
    }
    RbcSetWindowInstanceData(tkwin, legendPtr);
    Tk_CreateEventHandler(tkwin, ExposureMask | StructureNotifyMask,
        LegendEventProc, legendPtr);
    /* Move the legend's binding table to the new window. */
    RbcMoveBindingTable(legendPtr->bindTable, tkwin);
    if(legendPtr->tkwin != *(legendPtr->graph->win)) {
        Tk_DestroyWindow(legendPtr->tkwin);
    }
    legendPtr->cmdToken =
        Tcl_CreateCommand(interp, pathName, RbcGraphInstCmdProc,
        legendPtr->graph, NULL);
    legendPtr->tkwin = tkwin;
    legendPtr->site = RBC_LEGEND_WINDOW;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPosition --
 *
 *      Convert the string representation of a legend XY position into
 *      window coordinates.  The form of the string must be "@x,y" or
 *      none.
 *
 * Results:
 *      The return value is a standard Tcl result.  The symbol type is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToPosition(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New legend position string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* offset to XPoint structure */
    RbcLegend *legendPtr = (RbcLegend *) widgRec;
    char c;
    unsigned int length;
    if(legendPtr->graph->win == NULL || *(legendPtr->graph->win) == NULL)
        return TCL_ERROR;

    c = string[0];
    length = strlen(string);

    if((string == NULL) || (*string == '\0')) {
        legendPtr->site = RBC_LEGEND_RIGHT;
    } else if((c == 'l') && (strncmp(string, "leftmargin", length) == 0)) {
        legendPtr->site = RBC_LEGEND_LEFT;
    } else if((c == 'r') && (strncmp(string, "rightmargin", length) == 0)) {
        legendPtr->site = RBC_LEGEND_RIGHT;
    } else if((c == 't') && (strncmp(string, "topmargin", length) == 0)) {
        legendPtr->site = RBC_LEGEND_TOP;
    } else if((c == 'b') && (strncmp(string, "bottommargin", length) == 0)) {
        legendPtr->site = RBC_LEGEND_BOTTOM;
    } else if((c == 'p') && (strncmp(string, "plotarea", length) == 0)) {
        legendPtr->site = RBC_LEGEND_PLOT;
    } else if(c == '@') {
    char *comma;
    long x, y;
    int result;

        comma = strchr(string + 1, ',');
        if(comma == NULL) {
            Tcl_AppendResult(interp, "bad screen position \"", string,
                "\": should be @x,y", (char *)NULL);
            return TCL_ERROR;
        }
        x = y = 0;
        *comma = '\0';
        result = ((Tcl_ExprLong(interp, string + 1, &x) == TCL_OK) &&
            (Tcl_ExprLong(interp, comma + 1, &y) == TCL_OK));
        *comma = ',';
        if(!result) {
            return TCL_ERROR;
        }
        legendPtr->anchorPos.x = (int)x;
        legendPtr->anchorPos.y = (int)y;
        legendPtr->site = RBC_LEGEND_XY;
    } else if(c == '.') {
        if(legendPtr->tkwin != *(legendPtr->graph->win)) {
            Tk_DestroyWindow(legendPtr->tkwin);
            legendPtr->tkwin = *(legendPtr->graph->win);
        }
        if(CreateLegendWindow(interp, legendPtr, string) != TCL_OK) {
            return TCL_ERROR;
        }
        legendPtr->site = RBC_LEGEND_WINDOW;
    } else {
        Tcl_AppendResult(interp, "bad position \"", string, "\": should be  \
\"leftmargin\", \"rightmargin\", \"topmargin\", \"bottommargin\", \
\"plotarea\", .window or @x,y", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * PositionToString --
 *
 *      Convert the window coordinates into a string.
 *
 * Results:
 *      The string representing the coordinate position is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PositionToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record */
    int offset,                /* offset of XPoint in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    RbcLegend *legendPtr = (RbcLegend *) widgRec;

    switch (legendPtr->site) {
    case RBC_LEGEND_LEFT:
        return "leftmargin";
    case RBC_LEGEND_RIGHT:
        return "rightmargin";
    case RBC_LEGEND_TOP:
        return "topmargin";
    case RBC_LEGEND_BOTTOM:
        return "bottommargin";
    case RBC_LEGEND_PLOT:
        return "plotarea";
    case RBC_LEGEND_WINDOW:
        return Tk_PathName(legendPtr->tkwin);
    case RBC_LEGEND_XY:{
    char string[200];
    char *result;

        sprintf(string, "@%d,%d", (int)legendPtr->anchorPos.x,
            (int)legendPtr->anchorPos.y);
        result = RbcStrdup(string);
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
        return result;
    }
    default:
        return "unknown legend position";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SetLegendOrigin --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SetLegendOrigin(
    RbcLegend * legendPtr)
{
RbcGraph *graph;
int x, y, width, height;

    graph = legendPtr->graph;
    x = y = width = height = 0; /* Suppress compiler warning. */
    switch (legendPtr->site) {
    case RBC_LEGEND_RIGHT:
        width =
            graph->margins[RBC_MARGIN_RIGHT].width -
            graph->margins[RBC_MARGIN_RIGHT].axesOffset;
        height = graph->bottom - graph->top;
        x = graph->width - (width + graph->inset);
        y = graph->top;
        break;
    case RBC_LEGEND_LEFT:
        width =
            graph->margins[RBC_MARGIN_LEFT].width -
            graph->margins[RBC_MARGIN_LEFT].axesOffset;
        height = graph->bottom - graph->top;
        x = graph->inset;
        y = graph->top;
        break;
    case RBC_LEGEND_TOP:
        width = graph->right - graph->left;
        height =
            graph->margins[RBC_MARGIN_TOP].height -
            graph->margins[RBC_MARGIN_TOP].axesOffset;
        if(graph->title != NULL) {
            height -= graph->titleTextStyle.height;
        }
        x = graph->left;
        y = graph->inset;
        if(graph->title != NULL) {
            y += graph->titleTextStyle.height;
        }
        break;
    case RBC_LEGEND_BOTTOM:
        width = graph->right - graph->left;
        height = graph->margins[RBC_MARGIN_BOTTOM].height -
            graph->margins[RBC_MARGIN_BOTTOM].axesOffset;
        x = graph->left;
        y = graph->height - (height + graph->inset);
        break;
    case RBC_LEGEND_PLOT:
        width = graph->right - graph->left;
        height = graph->bottom - graph->top;
        x = graph->left;
        y = graph->top;
        break;
    case RBC_LEGEND_XY:
        width = legendPtr->width;
        height = legendPtr->height;
        x = (int)legendPtr->anchorPos.x;
        y = (int)legendPtr->anchorPos.y;
        if(x < 0) {
            x += graph->width;
        }
        if(y < 0) {
            y += graph->height;
        }
        break;
    case RBC_LEGEND_WINDOW:
        legendPtr->anchor = TK_ANCHOR_NW;
        legendPtr->x = legendPtr->y = 0;
        return;
    }
    width = legendPtr->width - width;
    height = legendPtr->height - height;
    RbcTranslateAnchor(x, y, width, height, legendPtr->anchor, &x, &y);

    legendPtr->x = x + legendPtr->padX.side1;   /*left */
    legendPtr->y = y + legendPtr->padY.side1;   /*top */
}

/*
 *----------------------------------------------------------------------
 *
 * PickLegendEntry --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static ClientData
PickLegendEntry(
    ClientData clientData,
    int x,                     /* Point to be tested */
    int y,                     /* Point to be tested */
    ClientData * contextPtr)
{              /* Not used. */
    RbcGraph *graph = clientData;
    RbcLegend *legendPtr;
    int width, height;

    legendPtr = graph->legend;
    width = legendPtr->width;
    height = legendPtr->height;

    x -= legendPtr->x + legendPtr->borderWidth;
    y -= legendPtr->y + legendPtr->borderWidth;
    width -= 2 * legendPtr->borderWidth + RbcPadding(legendPtr->padX);
    height -= 2 * legendPtr->borderWidth + RbcPadding(legendPtr->padY);

    if((x >= 0) && (x < width) && (y >= 0) && (y < height)) {
    int row, column;
    int n;

        /*
         * It's in the bounding box, so compute the index.
         */
        row = y / legendPtr->style.height;
        column = x / legendPtr->style.width;
        n = (column * legendPtr->nRows) + row;
        if(n < legendPtr->nEntries) {
    RbcChainLink *linkPtr;
    RbcElement *elemPtr;
    int count;

            /* Legend entries are stored in reverse. */
            count = 0;
            for(linkPtr = RbcChainLastLink(graph->elements.displayList);
                linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
                elemPtr = RbcChainGetValue(linkPtr);
                if(elemPtr->label != NULL) {
                    if(count == n) {
                        return elemPtr;
                    }
                    count++;
                }
            }
            if(linkPtr != NULL) {
                return RbcChainGetValue(linkPtr);
            }
        }
    }
    return NULL;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcMapLegend --
 *
 *      Calculates the dimensions (width and height) needed for
 *      the legend.  Also determines the number of rows and columns
 *      necessary to list all the valid element labels.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The following fields of the legend are calculated and set.
 *
 *      nEntries   - number of valid labels of elements in the
 *      	      display list.
 *      nRows	    - number of rows of entries
 *      nColumns    - number of columns of entries
 *      style.height - height of each entry
 *      style.width  - width of each entry
 *      height	    - width of legend (includes borders and padding)
 *      width	    - height of legend (includes borders and padding)
 *
 * -----------------------------------------------------------------
 */
void
RbcMapLegend(
    RbcLegend * legendPtr,
    int plotWidth,             /* Maximum width available in window
                                * to draw the legend. Will calculate number
                                * of columns from this. */
    int plotHeight)
{              /* Maximum height available in window
                * to draw the legend. Will calculate number
                * of rows from this. */
    RbcChainLink *linkPtr;
    RbcElement *elemPtr;
    int nRows, nColumns, nEntries;
    int legendWidth, legendHeight;
    int entryWidth, entryHeight;
    int symbolWidth;
    Tk_FontMetrics fontMetrics;
    if(legendPtr->graph->win == NULL || *(legendPtr->graph->win) == NULL)
        return;

    /* Initialize legend values to default (no legend displayed) */

    legendPtr->style.width = legendPtr->style.height = 0;
    legendPtr->nRows = legendPtr->nColumns = 0;
    legendPtr->nEntries = 0;
    legendPtr->height = legendPtr->width = 0;

    if(legendPtr->site == RBC_LEGEND_WINDOW) {
        if(Tk_Width(legendPtr->tkwin) > 1) {
            plotWidth = Tk_Width(legendPtr->tkwin);
        }
        if(Tk_Height(legendPtr->tkwin) > 1) {
            plotHeight = Tk_Height(legendPtr->tkwin);
        }
    }
    if((legendPtr->hidden) || (plotWidth < 1) || (plotHeight < 1)) {
        return; /* Legend is not being displayed */
    }

    /*
     * Count the number of legend entries and determine the widest and
     * tallest label.  The number of entries would normally be the
     * number of elements, but 1) elements can be hidden and 2)
     * elements can have no legend entry (-label "").
     */
    nEntries = 0;
    entryWidth = entryHeight = 0;
    for(linkPtr = RbcChainLastLink(legendPtr->graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
    int width, height;

        elemPtr = RbcChainGetValue(linkPtr);
        if(elemPtr->label == NULL) {
            continue;   /* Element has no legend entry. */
        }
        RbcGetTextExtents(&legendPtr->style, elemPtr->label, &width, &height);
        if(entryWidth < width) {
            entryWidth = width;
        }
        if(entryHeight < height) {
            entryHeight = height;
        }
        nEntries++;
    }

    if(nEntries == 0) {
        return; /* No legend entries. */
    }

    Tk_GetFontMetrics(legendPtr->style.font, &fontMetrics);
    symbolWidth = 2 * fontMetrics.ascent;

    entryWidth +=
        2 * legendPtr->entryBorderWidth + RbcPadding(legendPtr->ipadX) + 5 +
        symbolWidth;
    entryHeight +=
        2 * legendPtr->entryBorderWidth + RbcPadding(legendPtr->ipadY);

    legendWidth = plotWidth - 2 * legendPtr->borderWidth -
        RbcPadding(legendPtr->padX);
    legendHeight = plotHeight - 2 * legendPtr->borderWidth -
        RbcPadding(legendPtr->padY);

    /*
     * The number of rows and columns is computed as one of the following:
     *
     *  both options set                User defined.
     *  -rows                           Compute columns from rows.
     *  -columns                        Compute rows from columns.
     *  neither set                     Compute rows and columns from
     *                                  size of plot.
     */
    if(legendPtr->reqRows > 0) {
        nRows = legendPtr->reqRows;
        if(nRows > nEntries) {
            nRows = nEntries;
        }
        if(legendPtr->reqColumns > 0) {
            nColumns = legendPtr->reqColumns;
            if(nColumns > nEntries) {
                nColumns = nEntries;    /* Both -rows, -columns set. */
            }
        } else {
            nColumns = ((nEntries - 1) / nRows) + 1;    /* Only -rows. */
        }
    } else if(legendPtr->reqColumns > 0) {      /* Only -columns. */
        nColumns = legendPtr->reqColumns;
        if(nColumns > nEntries) {
            nColumns = nEntries;
        }
        nRows = ((nEntries - 1) / nColumns) + 1;
    } else {
        /* Compute # of rows and columns from the legend size. */
        nRows = legendHeight / entryHeight;
        nColumns = legendWidth / entryWidth;

        if(nRows > nEntries) {
            nRows = nEntries;
        } else if(nRows < 1) {
            nRows = 1;
        }
        if(nColumns > nEntries) {
            nColumns = nEntries;
        } else if(nColumns < 1) {
            nColumns = 1;
        }
        if((legendPtr->site == RBC_LEGEND_TOP) ||
            (legendPtr->site == RBC_LEGEND_BOTTOM)) {
            nRows = ((nEntries - 1) / nColumns) + 1;
        } else {
            nColumns = ((nEntries - 1) / nRows) + 1;
        }
    }
    if(nRows < 1) {
        nRows = 1;
    }
    if(nColumns < 1) {
        nColumns = 1;
    }
    legendWidth = 2 * legendPtr->borderWidth + RbcPadding(legendPtr->padX);
    legendHeight = 2 * legendPtr->borderWidth + RbcPadding(legendPtr->padY);
    legendHeight += nRows * entryHeight;
    legendWidth += nColumns * entryWidth;

    legendPtr->height = legendHeight;
    legendPtr->width = legendWidth;
    legendPtr->nRows = nRows;
    legendPtr->nColumns = nColumns;
    legendPtr->nEntries = nEntries;
    legendPtr->style.height = entryHeight;
    legendPtr->style.width = entryWidth;

    if((legendPtr->tkwin != *(legendPtr->graph->win)) &&
        ((Tk_ReqWidth(legendPtr->tkwin) != legendWidth) ||
            (Tk_ReqHeight(legendPtr->tkwin) != legendHeight))) {
        Tk_GeometryRequest(legendPtr->tkwin, legendWidth, legendHeight);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawLegend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDrawLegend(
    RbcLegend * legendPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcGraph *graph = legendPtr->graph;
RbcChainLink *linkPtr;
Pixmap pixmap;
Tk_3DBorder border;
Tk_FontMetrics fontMetrics;
Tk_Window tkwin;
int count;
int labelX, startY, symbolX, symbolY;
int symbolSize, midX, midY;
int width, height;
int x, y;
register RbcElement *elemPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    graph->flags &= ~RBC_DRAW_LEGEND;
    if((legendPtr->hidden) || (legendPtr->nEntries == 0)) {
        return;
    }
    SetLegendOrigin(legendPtr);

    if(legendPtr->tkwin != *(graph->win)) {
        tkwin = legendPtr->tkwin;
        width = Tk_Width(tkwin);
        if(width < 1) {
            width = legendPtr->width;
        }
        height = Tk_Height(tkwin);
        if(height < 1) {
            height = legendPtr->height;
        }
    } else {
        width = legendPtr->width;
        height = legendPtr->height;
    }
    Tk_GetFontMetrics(legendPtr->style.font, &fontMetrics);

    symbolSize = fontMetrics.ascent;
    midX = symbolSize + 1 + legendPtr->entryBorderWidth;
    midY = (symbolSize / 2) + 1 + legendPtr->entryBorderWidth;
    labelX = 2 * symbolSize + legendPtr->entryBorderWidth +
        legendPtr->ipadX.side1 + 5;
    symbolY = midY + legendPtr->ipadY.side1;
    symbolX = midX + legendPtr->ipadX.side1;

    pixmap = Tk_GetPixmap(graph->display, Tk_WindowId(legendPtr->tkwin),
        width, height, Tk_Depth(legendPtr->tkwin));

    if(legendPtr->border != NULL) {
        /* Background color and relief. */
        Tk_Fill3DRectangle(legendPtr->tkwin, pixmap, legendPtr->border, 0, 0,
            width, height, 0, TK_RELIEF_FLAT);
    } else if(legendPtr->site & RBC_LEGEND_IN_PLOT) {
        /*
         * Legend background is transparent and is positioned over the
         * the plot area.  Either copy the part of the background from
         * the backing store pixmap or (if no backing store exists)
         * just fill it with the background color of the plot.
         */
        if(graph->backPixmap != None) {
            XCopyArea(graph->display, graph->backPixmap, pixmap,
                graph->drawGC, legendPtr->x, legendPtr->y, width, height, 0, 0);
        } else {
            XFillRectangle(graph->display, pixmap, graph->plotFillGC,
                0, 0, width, height);
        }
    } else {
        /*
         * The legend is positioned in one of the margins or the
         * external window.  Draw either the solid or tiled background
         * with the the border.
         */
        if(graph->tile != NULL) {
            RbcSetTileOrigin(legendPtr->tkwin, graph->tile, legendPtr->x,
                legendPtr->y);
            RbcTileRectangle(legendPtr->tkwin, pixmap, graph->tile, 0, 0,
                width, height);
        } else {
            XFillRectangle(graph->display, pixmap, graph->fillGC, 0, 0,
                width, height);
        }
    }
    x = legendPtr->padX.side1 + legendPtr->borderWidth; /*left */
    y = legendPtr->padY.side1 + legendPtr->borderWidth; /*top */
    count = 0;
    startY = y;
    for(linkPtr = RbcChainLastLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(elemPtr->label == NULL) {
            continue;   /* Skip this entry */
        }
        if(elemPtr->flags & RBC_LABEL_ACTIVE) {
            legendPtr->style.state |= RBC_STATE_ACTIVE;
            Tk_Fill3DRectangle(legendPtr->tkwin, pixmap,
                legendPtr->activeBorder, x, y,
                legendPtr->style.width, legendPtr->style.height,
                legendPtr->entryBorderWidth, legendPtr->activeRelief);
        } else {
            legendPtr->style.state &= ~RBC_STATE_ACTIVE;
            if(elemPtr->labelRelief != TK_RELIEF_FLAT) {
                Tk_Draw3DRectangle(legendPtr->tkwin, pixmap, graph->border,
                    x, y, legendPtr->style.width, legendPtr->style.height,
                    legendPtr->entryBorderWidth, elemPtr->labelRelief);
            }
        }
        (*elemPtr->procsPtr->drawSymbolProc) (graph, pixmap, elemPtr,
            x + symbolX, y + symbolY, symbolSize);
        RbcDrawText(legendPtr->tkwin, pixmap, elemPtr->label,
            &legendPtr->style, x + labelX,
            y + legendPtr->entryBorderWidth + legendPtr->ipadY.side1);
        count++;

        /* Check when to move to the next column */
        if((count % legendPtr->nRows) > 0) {
            y += legendPtr->style.height;
        } else {
            x += legendPtr->style.width;
            y = startY;
        }
    }
    /*
     * Draw the border and/or background of the legend.
     */
    border = legendPtr->border;
    if(border == NULL) {
        border = graph->border;
    }
    Tk_Draw3DRectangle(legendPtr->tkwin, pixmap, border, 0, 0, width, height,
        legendPtr->borderWidth, legendPtr->relief);

    XCopyArea(graph->display, pixmap, drawable, graph->drawGC, 0, 0,
        width, height, legendPtr->x, legendPtr->y);
    Tk_FreePixmap(graph->display, pixmap);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcLegendToPostScript(
    RbcLegend * legendPtr,
    RbcPsToken * psToken)
{
RbcGraph *graph;
double x, y, startY;
RbcElement *elemPtr;
int labelX, symbolX, symbolY;
int count;
RbcChainLink *linkPtr;
int symbolSize, midX, midY;
int width, height;
Tk_FontMetrics fontMetrics;

    if((legendPtr->hidden) || (legendPtr->nEntries == 0)) {
        return;
    }
    SetLegendOrigin(legendPtr);

    x = legendPtr->x, y = legendPtr->y;
    width = legendPtr->width - RbcPadding(legendPtr->padX);
    height = legendPtr->height - RbcPadding(legendPtr->padY);

    graph = legendPtr->graph;
    if(graph->postscript->decorations) {
        if(legendPtr->border != NULL) {
            RbcFill3DRectangleToPostScript(psToken, legendPtr->border, x, y,
                width, height, legendPtr->borderWidth, legendPtr->relief);
        } else {
            RbcDraw3DRectangleToPostScript(psToken, graph->border, x, y,
                width, height, legendPtr->borderWidth, legendPtr->relief);
        }
    } else {
        RbcClearBackgroundToPostScript(psToken);
        RbcRectangleToPostScript(psToken, x, y, width, height);
    }
    x += legendPtr->borderWidth;
    y += legendPtr->borderWidth;

    Tk_GetFontMetrics(legendPtr->style.font, &fontMetrics);
    symbolSize = fontMetrics.ascent;
    midX = symbolSize + 1 + legendPtr->entryBorderWidth;
    midY = (symbolSize / 2) + 1 + legendPtr->entryBorderWidth;
    labelX = 2 * symbolSize + legendPtr->entryBorderWidth +
        legendPtr->ipadX.side1 + 5;
    symbolY = midY + legendPtr->ipadY.side1;
    symbolX = midX + legendPtr->ipadX.side1;

    count = 0;
    startY = y;
    for(linkPtr = RbcChainLastLink(graph->elements.displayList);
        linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
        elemPtr = RbcChainGetValue(linkPtr);
        if(elemPtr->label == NULL) {
            continue;   /* Skip this label */
        }
        if(elemPtr->flags & RBC_LABEL_ACTIVE) {
            legendPtr->style.state |= RBC_STATE_ACTIVE;
            RbcFill3DRectangleToPostScript(psToken, legendPtr->activeBorder,
                x, y, legendPtr->style.width, legendPtr->style.height,
                legendPtr->entryBorderWidth, legendPtr->activeRelief);
        } else {
            legendPtr->style.state &= ~RBC_STATE_ACTIVE;
            if(elemPtr->labelRelief != TK_RELIEF_FLAT) {
                RbcDraw3DRectangleToPostScript(psToken, graph->border,
                    x, y, legendPtr->style.width, legendPtr->style.height,
                    legendPtr->entryBorderWidth, elemPtr->labelRelief);
            }
        }
        (*elemPtr->procsPtr->printSymbolProc) (graph, psToken, elemPtr,
            x + symbolX, y + symbolY, symbolSize);
        RbcTextToPostScript(psToken, elemPtr->label, &(legendPtr->style),
            x + labelX,
            y + legendPtr->entryBorderWidth + legendPtr->ipadY.side1);
        count++;
        if((count % legendPtr->nRows) > 0) {
            y += legendPtr->style.height;
        } else {
            x += legendPtr->style.width;
            y = startY;
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DisplayLegend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DisplayLegend(
    ClientData clientData)
{
RbcLegend *legendPtr = clientData;
int width, height;

    legendPtr->flags &= ~RBC_REDRAW_PENDING;

    if(legendPtr->tkwin == NULL) {
        return; /* Window has been destroyed. */
    }
    if(legendPtr->site == RBC_LEGEND_WINDOW) {
        width = Tk_Width(legendPtr->tkwin);
        height = Tk_Height(legendPtr->tkwin);
        if((width <= 1) || (height <= 1)) {
            return;
        }
        if((width != legendPtr->width) || (height != legendPtr->height)) {
            RbcMapLegend(legendPtr, width, height);
        }
    }
    if(!Tk_IsMapped(legendPtr->tkwin)) {
        return;
    }
    RbcDrawLegend(legendPtr, Tk_WindowId(legendPtr->tkwin));
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureLegend --
 *
 *      Routine to configure the legend.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static void
ConfigureLegend(
    RbcGraph * graph,
    RbcLegend * legendPtr)
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    RbcResetTextStyle(*(graph->win), &(legendPtr->style));

    if(legendPtr->site == RBC_LEGEND_WINDOW) {
        EventuallyRedrawLegend(legendPtr);
    } else {
        /*
         *  Update the layout of the graph (and redraw the elements) if
         *  any of the following legend options (all of which affect the
         *      size of the legend) have changed.
         *
         *              -activeborderwidth, -borderwidth
         *              -border
         *              -font
         *              -hide
         *              -ipadx, -ipady, -padx, -pady
         *              -rows
         *
         *  If the position of the legend changed to/from the default
         *  position, also indicate that a new layout is needed.
         *
         */
        if(RbcConfigModified(configSpecs, "-*border*", "-*pad?",
                "-position", "-hide", "-font", "-rows", (char *)NULL)) {
            graph->flags |= RBC_MAP_WORLD;
        }
        graph->flags |= (RBC_REDRAW_WORLD | RBC_REDRAW_BACKING_STORE);
        RbcEventuallyRedrawGraph(graph);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyLegend --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Resources associated with the legend are freed.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyLegend(
    RbcGraph * graph)
{
RbcLegend *legendPtr = graph->legend;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    Tk_FreeOptions(configSpecs, (char *)legendPtr, graph->display, 0);
    RbcFreeTextStyle(graph->display, &(legendPtr->style));
    RbcDestroyBindingTable(legendPtr->bindTable);
    if(legendPtr->tkwin != *(graph->win)) {
Tk_Window tkwin;

        /* The graph may be in the process of being torn down */
        if(legendPtr->cmdToken != NULL) {
            Tcl_DeleteCommandFromToken(graph->interp, legendPtr->cmdToken);
        }
        if(legendPtr->flags & RBC_REDRAW_PENDING) {
            Tcl_CancelIdleCall(DisplayLegend, legendPtr);
            legendPtr->flags &= ~RBC_REDRAW_PENDING;
        }
        tkwin = legendPtr->tkwin;
        legendPtr->tkwin = NULL;
        if(tkwin != NULL) {
            Tk_DeleteEventHandler(tkwin, ExposureMask | StructureNotifyMask,
                LegendEventProc, legendPtr);
            RbcDeleteWindowInstanceData(tkwin);
            Tk_DestroyWindow(tkwin);
        }
    }
    ckfree((char *)legendPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateLegend --
 *
 *      Creates and initializes a legend structure with default settings
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcCreateLegend(
    RbcGraph * graph)
{
RbcLegend *legendPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    legendPtr = RbcCalloc(1, sizeof(RbcLegend));
    assert(legendPtr);
    graph->legend = legendPtr;
    legendPtr->graph = graph;
    legendPtr->tkwin = *(graph->win);
    legendPtr->hidden = FALSE;
    legendPtr->anchorPos.x = legendPtr->anchorPos.y = -SHRT_MAX;
    legendPtr->relief = TK_RELIEF_SUNKEN;
    legendPtr->activeRelief = TK_RELIEF_FLAT;
    legendPtr->entryBorderWidth = legendPtr->borderWidth = 2;
    legendPtr->ipadX.side1 = legendPtr->ipadX.side2 = 1;
    legendPtr->ipadY.side1 = legendPtr->ipadY.side2 = 1;
    legendPtr->padX.side1 = legendPtr->padX.side2 = 1;
    legendPtr->padY.side1 = legendPtr->padY.side2 = 1;
    legendPtr->anchor = TK_ANCHOR_N;
    legendPtr->site = RBC_LEGEND_RIGHT;
    RbcInitTextStyle(&(legendPtr->style));
    legendPtr->style.justify = TK_JUSTIFY_LEFT;
    legendPtr->style.anchor = TK_ANCHOR_NW;
    legendPtr->bindTable = RbcCreateBindingTable(graph->interp,
        *(graph->win), graph, PickLegendEntry);

    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win),
            "legend", "Legend", configSpecs, 0, (const char **)NULL,
            (char *)legendPtr, 0) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureLegend(graph, legendPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetOp --
 *
 *      Find the legend entry from the given argument.  The argument
 *      can be either a screen position "@x,y" or the name of an
 *      element.
 *
 *      I don't know how useful it is to test with the name of an
 *      element.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static int
GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char *argv[])
{
    register RbcElement *elemPtr;
    RbcLegend *legendPtr = graph->legend;
    int x, y;
    char c;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if((legendPtr->hidden) || (legendPtr->nEntries == 0)) {
        return TCL_OK;
    }
    elemPtr = NULL;
    c = argv[3][0];
    if((c == 'c') && (strcmp(argv[3], "current") == 0)) {
        elemPtr = (RbcElement *) RbcGetCurrentItem(legendPtr->bindTable);
    } else if((c == '@') &&
        (RbcGetXY(interp, *(graph->win), argv[3], &x, &y) == TCL_OK)) {
        elemPtr = (RbcElement *) PickLegendEntry(graph, x, y, NULL);
    }
    if(elemPtr != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(elemPtr->name, -1));
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ActivateOp --
 *
 *      Activates a particular label in the legend.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static int
ActivateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcLegend *legendPtr = graph->legend;
    RbcElement *elemPtr;
    unsigned int active, redraw;
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    register int i;

    active = (argv[2][0] == 'a') ? RBC_LABEL_ACTIVE : 0;
    redraw = 0;
    for(hPtr = Tcl_FirstHashEntry(&(graph->elements.table), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = Tcl_GetHashValue(hPtr);
        for(i = 3; i < argc; i++) {
            if(Tcl_StringMatch(elemPtr->name, argv[i])) {
                break;
            }
        }
        if((i < argc) && (active != (elemPtr->flags & RBC_LABEL_ACTIVE))) {
            elemPtr->flags ^= RBC_LABEL_ACTIVE;
            if(elemPtr->label != NULL) {
                redraw++;
            }
        }
    }
    if((redraw) && (!legendPtr->hidden)) {
        /*
         * See if how much we need to draw. If the graph is already
         * schedule for a redraw, just make sure the right flags are
         * set.  Otherwise redraw only the legend: it's either in an
         * external window or it's the only thing that need updating.
         */
        if(graph->flags & RBC_REDRAW_PENDING) {
            if(legendPtr->site & RBC_LEGEND_IN_PLOT) {
                graph->flags |= RBC_REDRAW_BACKING_STORE;
            }
            graph->flags |= RBC_REDRAW_WORLD;   /* Redraw entire graph. */
        } else {
            EventuallyRedrawLegend(legendPtr);
        }
    }
    /* Return the names of all the active legend entries */
    for(hPtr = Tcl_FirstHashEntry(&(graph->elements.table), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        elemPtr = Tcl_GetHashValue(hPtr);
        if(elemPtr->flags & RBC_LABEL_ACTIVE) {
            Tcl_AppendElement(interp, elemPtr->name);
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    if(argc == 3) {
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    char *tagName;

        for(hPtr = Tcl_FirstHashEntry(&(graph->elements.tagTable), &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tagName = Tcl_GetHashKey(&(graph->elements.tagTable), hPtr);
            Tcl_AppendElement(interp, tagName);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graph->legend->bindTable,
        RbcMakeElementTag(graph, argv[3]), argc - 4, argv + 4);
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries or resets options for the legend.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    return Tk_ConfigureValue(interp, *(graph->win), configSpecs,
        (char *)graph->legend, argv[3], 0);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets options for the legend.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    int flags = TK_CONFIG_ARGV_ONLY;
    RbcLegend *legendPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    legendPtr = graph->legend;
    if(argc == 3) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)legendPtr, (char *)NULL, flags);
    } else if(argc == 4) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)legendPtr, argv[3], flags);
    }
    if(Tk_ConfigureWidget(interp, *(graph->win), configSpecs, argc - 3,
            argv + 3, (char *)legendPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    ConfigureLegend(graph, legendPtr);
    return TCL_OK;
}

static RbcOpSpec legendOps[] = {
    {"activate", 1, (RbcOp) ActivateOp, 3, 0, "?pattern?...",},
    {"bind", 1, (RbcOp) BindOp, 3, 6, "elemName sequence command",},
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?option value?...",},
    {"deactivate", 1, (RbcOp) ActivateOp, 3, 0, "?pattern?...",},
    {"get", 1, (RbcOp) GetOp, 4, 4, "index",},
};

static int nLegendOps = sizeof(legendOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendOp --
 *
 *      TODO: Description
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Legend is possibly redrawn.
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp proc;
    int result;

    proc = RbcGetOp(interp, nLegendOps, legendOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    result = (*proc) (graph, interp, argc, argv);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendSite --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendSite(
    RbcLegend * legendPtr)
{
    return legendPtr->site;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendWidth --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendWidth(
    RbcLegend * legendPtr)
{
    return legendPtr->width;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendHeight --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendHeight(
    RbcLegend * legendPtr)
{
    return legendPtr->height;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendIsHidden --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendIsHidden(
    RbcLegend * legendPtr)
{
    return legendPtr->hidden;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendIsRaised --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendIsRaised(
    RbcLegend * legendPtr)
{
    return legendPtr->raised;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendX --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendX(
    RbcLegend * legendPtr)
{
    return legendPtr->x;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendY --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLegendY(
    RbcLegend * legendPtr)
{
    return legendPtr->y;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLegendRemoveElement --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcLegendRemoveElement(
    RbcLegend * legendPtr,
    RbcElement * elemPtr)
{
    RbcDeleteBindings(legendPtr->bindTable, elemPtr);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphLine.c.


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"
#define PATTERN_SOLID	((Pixmap)1)
/* Draw line segments for only those
 * data points whose abscissas are
 * monotonically increasing in
 * order */
#define PEN_INCREASING  1
/* Lines will be drawn between only
 * those points whose abscissas are
 * decreasing in order */
#define PEN_DECREASING  2
#define PEN_BOTH_DIRECTIONS	(PEN_INCREASING | PEN_DECREASING)
/* Lines will be drawn between points regardless of the ordering of
 * the abscissas */
#define BROKEN_TRACE(dir,last,next) \
    (((((dir) & PEN_DECREASING) == 0) && ((next) < (last))) || \
     ((((dir) & PEN_INCREASING) == 0) && ((next) > (last))))
#define DRAW_SYMBOL(linePtr) \
	(((linePtr)->symbolCounter % (linePtr)->symbolInterval) == 0)
typedef enum {
    PEN_SMOOTH_NONE,           /* Line segments */
    PEN_SMOOTH_STEP,           /* Step-and-hold */
    PEN_SMOOTH_NATURAL,        /* Natural cubic spline */
    PEN_SMOOTH_QUADRATIC,      /* Quadratic spline */
    PEN_SMOOTH_CATROM,         /* Catrom parametric spline */
    PEN_SMOOTH_LAST            /* Sentinel */
} Smoothing;
typedef struct {
    const char *name;
    Smoothing value;
} SmoothingInfo;
static SmoothingInfo smoothingInfo[] = {
    {"linear", PEN_SMOOTH_NONE},
    {"step", PEN_SMOOTH_STEP},
    {"natural", PEN_SMOOTH_NATURAL},
    {"cubic", PEN_SMOOTH_NATURAL},
    {"quadratic", PEN_SMOOTH_QUADRATIC},
    {"catrom", PEN_SMOOTH_CATROM},
    {(const char *)NULL, PEN_SMOOTH_LAST}
};

typedef struct {
    RbcPoint2D *screenPts;     /* Array of transformed coordinates */
    int nScreenPts;            /* Number of coordinates */
    int *dataToStyle;          /* Index of pen styles  */
    int *indices;              /* Maps segments/traces to data points */
} MapInfo;
/*
 * Symbol types for line elements
 */
typedef enum {
    SYMBOL_NONE,
    SYMBOL_SQUARE,
    SYMBOL_CIRCLE,
    SYMBOL_DIAMOND,
    SYMBOL_PLUS,
    SYMBOL_CROSS,
    SYMBOL_SPLUS,
    SYMBOL_SCROSS,
    SYMBOL_TRIANGLE,
    SYMBOL_ARROW,
    SYMBOL_BITMAP
} SymbolType;
typedef struct {
    SymbolType type;           /* Type of symbol to be drawn/printed */
    int size;                  /* Requested size of symbol in pixels */
    XColor *outlineColor;      /* Outline color */
    int outlineWidth;          /* Width of the outline */
    GC  outlineGC;             /* Outline graphics context */
    XColor *fillColor;         /* Normal fill color */
    GC  fillGC;                /* Fill graphics context */
    /* The last two fields are used only for bitmap symbols. */
    Pixmap bitmap;             /* Bitmap to determine foreground/background
                                * pixels of the symbol */
    Pixmap mask;               /* Bitmap representing the transparent
                                * pixels of the symbol */
} Symbol;
typedef struct {
    int start;                 /* Index into the X-Y coordinate
                                * arrays indicating where trace
                                * starts. */
    int nScreenPts;            /* Number of points in the continuous
                                * trace */
    RbcPoint2D *screenPts;     /* Array of screen coordinates
                                * (malloc-ed) representing the
                                * trace. */
    int *symbolToData;         /* Reverse mapping of screen
                                * coordinate indices back to their
                                * data coordinates */
} LineTrace;
typedef struct {
    const char *name;          /* Name of pen style. If the pen was
                                * statically allocated the name will
                                * be NULL. */
    Tk_Uid classUid;           /* Type of pen */
    char *typeId;              /* String token identifying the type
                                * of pen */
    unsigned int flags;        /* Indicates if the pen element is
                                * active or normal */
    int refCount;              /* Reference count for elements using
                                * this pen. */
    Tcl_HashEntry *hashPtr;
    Tk_ConfigSpec *configSpecs; /* Configuration specifications */
    PenConfigureProc *configProc;
    PenDestroyProc *destroyProc;
    /* Symbol attributes. */
    Symbol symbol;             /* Element symbol type */
    /* LineTrace attributes. */
    int traceWidth;            /* Width of the line segments. If
                                * lineWidth is 0, no line will be
                                * drawn, only symbols. */
    RbcDashes traceDashes;     /* Dash on-off list value */
    XColor *traceColor;        /* Line segment color */
    XColor *traceOffColor;     /* Line segment dash gap color */
    GC  traceGC;               /* Line segment graphics context */
    /* Error bar attributes. */
    int errorBarShow;          /* Describes which error bars to
                                * display: none, x, y, or * both. */
    int errorBarLineWidth;     /* Width of the error bar segments. */
    int errorBarCapWidth;      /* Width of the cap on error bars. */
    XColor *errorBarColor;     /* Color of the error bar. */
    GC  errorBarGC;            /* Error bar graphics context. */
    /* Show value attributes. */
    int valueShow;             /* Indicates whether to display data
                                * value.  Values are x, y, both, or
                                * none. */
    char *valueFormat;         /* A printf format string. */
    RbcTextStyle valueStyle;   /* Text attributes (color, font,
                                * rotation, etc.) of the value. */
} LinePen;
typedef struct {
    RbcElemWeight weight;      /* Weight range where this pen is valid. */
    LinePen *penPtr;           /* Pen used to draw symbols, traces, error
                                * bars, segments, etc. */
    RbcSegment2D *xErrorBars;  /* Point to start of this pen's X-error bar
                                * segments in the element's array. */
    RbcSegment2D *yErrorBars;  /* Point to start of this pen's Y-error bar
                                * segments in the element's array. */
    int xErrorBarCnt;          /* # of error bars for this pen. */
    int yErrorBarCnt;          /* # of error bars for this pen. */
    int errorBarCapWidth;      /* Length of the cap ends on each
                                * error bar. */
    int symbolSize;            /* Size of the pen's symbol scaled to the
                                * current graph size. */
    /* Graph specific data. */
    RbcPoint2D *symbolPts;     /* Points to start of array for this pen. */
    int nSymbolPts;            /* # of points for this pen. */
    /* The last two fields are used only for stripcharts. */
    RbcSegment2D *strips;      /* Points to start of the line segments
                                * for this pen. */
    int nStrips;               /* # of line segments for this pen. */
} LinePenStyle;
typedef struct {
    char *name;                /* Identifier used to refer the
                                * element. Used in the "insert",
                                * "delete", or "show", operations. */
    Tk_Uid classUid;           /* Type of element */
    RbcGraph *graph;           /* Graph widget of element */
    unsigned int flags;        /* Indicates if the entire element is
                                * active, or if coordinates need to
                                * be calculated */
    char **tags;
    int hidden;                /* If non-zero, don't display the
                                * element. */
    Tcl_HashEntry *hashPtr;
    char *label;               /* Label displayed in legend */
    int labelRelief;           /* Relief of label in legend. */
    RbcAxis2D axes;
    RbcElemVector x, y, w;     /* Contains array of numeric values */
    RbcElemVector xError;      /* Relative/symmetric X error values. */
    RbcElemVector yError;      /* Relative/symmetric Y error values. */
    RbcElemVector xHigh, xLow; /* Absolute/asymmetric X-coordinate high/low
                                * error values. */
    RbcElemVector yHigh, yLow; /* Absolute/asymmetric Y-coordinate high/low
                                * error values. */
    int *activeIndices;        /* Array of indices (malloc-ed) that
                                * indicate the data points are active
                                * (drawn with "active" colors). */
    int nActiveIndices;        /* Number of active data points.
                                * Special case: if < 0 then all data
                                * points are drawn active. */
    RbcElementProcs *procsPtr;
    Tk_ConfigSpec *configSpecs; /* Configuration specifications */
    RbcSegment2D *xErrorBars;  /* Point to start of this pen's X-error bar
                                * segments in the element's array. */
    RbcSegment2D *yErrorBars;  /* Point to start of this pen's Y-error bar
                                * segments in the element's array. */
    int xErrorBarCnt;          /* # of error bars for this pen. */
    int yErrorBarCnt;          /* # of error bars for this pen. */
    int *xErrorToData;         /* Maps individual error bar segments back
                                * to the data point associated with it. */
    int *yErrorToData;         /* Maps individual error bar segments back
                                * to the data point associated with it. */
    int errorBarCapWidth;      /* Length of cap on error bars */
    LinePen *activePenPtr;     /* Pen to draw "active" elements. */
    LinePen *normalPenPtr;     /* Pen to draw elements normally. */
    RbcChain *palette;         /* Array of pen styles: pens are associated
                                * with specific ranges of data.*/
    /* Symbol scaling */
    int scaleSymbols;          /* If non-zero, the symbols will scale
                                * in size as the graph is zoomed
                                * in/out.  */
    double xRange, yRange;     /* Initial X-axis and Y-axis ranges:
                                * used to scale the size of element's
                                * symbol. */
    int state;
    /*
     * Line specific configurable attributes
     */
    LinePen builtinPen;
    /* Line smoothing */
    Smoothing reqSmooth;       /* Requested smoothing function to use
                                * for connecting the data points */
    Smoothing smooth;          /* Smoothing function used. */
    double rTolerance;         /* Tolerance to reduce the number of
                                * points displayed. */
    /*
     * Drawing related data structures.
     */
    /* Area-under-curve fill attributes. */
    XColor *fillFgColor;
    XColor *fillBgColor;
    GC  fillGC;
    RbcTile fillTile;          /* Tile for fill area. */
    Pixmap fillStipple;        /* Stipple for fill area. */
    int nFillPts;
    RbcPoint2D *fillPts;       /* Array of points used to draw
                                * polygon to fill area under the
                                * curve */
    /* Symbol points */
    RbcPoint2D *symbolPts;     /* Holds the screen coordinates of all
                                * the data points for the element. */
    int nSymbolPts;            /* Number of points */
    int *symbolToData;         /* Contains indices of data points.
                                * It's first used to map pens to the
                                * visible points to sort them by pen
                                * style, and later to find data
                                * points from the index of a visible
                                * point. */
    /* Active symbol points */
    RbcPoint2D *activePts;     /* Array of indices representing the
                                * "active" points. */
    int nActivePts;            /* Number of indices in the above array. */
    int *activeToData;         /* Contains indices of data points.
                                * It's first used to map pens to the
                                * visible points to sort them by pen
                                * style, and later to find data
                                * points from the index of a visible
                                * point. */
    int reqMaxSymbols;
    int symbolInterval;
    int symbolCounter;
    /* X-Y graph-specific fields */
    int penDir;                /* Indicates if a change in the pen
                                * direction should be considered a
                                * retrace (line segment is not
                                * drawn). */
    RbcChain *traces;          /* List of traces (a trace is a series
                                * of contiguous line segments).  New
                                * traces are generated when either
                                * the next segment changes the pen
                                * direction, or the end point is
                                * clipped by the plotting area. */
    /* Stripchart-specific fields */
    RbcSegment2D *strips;      /* Holds the the line segments of the
                                * element trace. The segments are
                                * grouped by pen style. */
    int nStrips;               /* Number of line segments to be drawn. */
    int *stripToData;          /* Pen to visible line segment mapping. */
} Line;
static Tk_OptionParseProc StringToPattern;
static Tk_OptionPrintProc PatternToString;
static Tk_OptionParseProc StringToSmooth;
static Tk_OptionPrintProc SmoothToString;
static Tk_OptionParseProc StringToPenDir;
static Tk_OptionPrintProc PenDirToString;
static Tk_OptionParseProc StringToSymbol;
static Tk_OptionPrintProc SymbolToString;
static Tk_CustomOption patternOption = {
    StringToPattern, PatternToString, (ClientData) 0
};

static Tk_CustomOption smoothOption = {
    StringToSmooth, SmoothToString, (ClientData) 0
};

static Tk_CustomOption stylesOption = {
    RbcStringToStyles, RbcStylesToString, (ClientData) sizeof(LinePenStyle)
};

static Tk_CustomOption penDirOption = {
    StringToPenDir, PenDirToString, (ClientData) 0
};

static Tk_CustomOption symbolOption = {
    StringToSymbol, SymbolToString, (ClientData) 0
};

extern Tk_CustomOption rbcColorOption;
extern Tk_CustomOption rbcDashesOption;
extern Tk_CustomOption rbcDataOption;
extern Tk_CustomOption rbcDataPairsOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcListOption;
extern Tk_CustomOption rbcLinePenOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcXAxisOption;
extern Tk_CustomOption rbcYAxisOption;
extern Tk_CustomOption rbcTileOption;
extern Tk_CustomOption rbcFillOption;
extern Tk_CustomOption rbcStateOption;
#define DEF_LINE_ACTIVE_PEN             "activeLine"
#define DEF_LINE_AXIS_X                 "x"
#define DEF_LINE_AXIS_Y                 "y"
#define DEF_LINE_DASHES                 (char *)NULL
#define DEF_LINE_DATA                   (char *)NULL
#define DEF_LINE_FILL_COLOR             "defcolor"
#define DEF_LINE_FILL_MONO              "defcolor"
#define DEF_LINE_HIDE                   "no"
#define DEF_LINE_LABEL                  (char *)NULL
#define DEF_LINE_LABEL_RELIEF           "flat"
#define DEF_LINE_MAX_SYMBOLS            "0"
#define DEF_LINE_OFFDASH_COLOR          (char *)NULL
#define DEF_LINE_OFFDASH_MONO           (char *)NULL
#define DEF_LINE_OUTLINE_COLOR          "defcolor"
#define DEF_LINE_OUTLINE_MONO           "defcolor"
#define DEF_LINE_OUTLINE_WIDTH          "1"
#define DEF_LINE_PATTERN                (char *)NULL
#define DEF_LINE_PATTERN_BG             "white"
#define DEF_LINE_PATTERN_FG             "black"
#define DEF_LINE_PATTERN_TILE           (char *)NULL
#define DEF_LINE_PEN_COLOR              "navyblue"
#define DEF_LINE_PEN_DIRECTION          "both"
#define DEF_LINE_PEN_MONO               "black"
#define DEF_LINE_PEN_WIDTH              "1"
#define DEF_LINE_PIXELS                 "0.125i"
#define DEF_LINE_REDUCE                 "0.0"
#define DEF_LINE_SCALE_SYMBOLS          "yes"
#define DEF_LINE_SMOOTH                 "linear"
#define DEF_LINE_STATE                  "normal"
#define DEF_LINE_STIPPLE                (char *)NULL
#define DEF_LINE_STYLES                 ""
#define DEF_LINE_SYMBOL                 "circle"
#define DEF_LINE_TAGS                   "all"
#define DEF_LINE_X_DATA                 (char *)NULL
#define DEF_LINE_Y_DATA                 (char *)NULL
#define DEF_LINE_ERRORBAR_COLOR         "defcolor"
#define DEF_LINE_ERRORBAR_LINE_WIDTH    "1"
#define DEF_LINE_ERRORBAR_CAP_WIDTH     "1"
#define DEF_LINE_SHOW_ERRORBARS         "both"
#define DEF_PEN_ACTIVE_COLOR            "blue"
#define DEF_PEN_ACTIVE_MONO             "black"
#define DEF_PEN_DASHES                  (char *)NULL
#define DEF_PEN_FILL_COLOR              "defcolor"
#define DEF_PEN_FILL_MONO               "defcolor"
#define DEF_PEN_LINE_WIDTH              "1"
#define DEF_PEN_NORMAL_COLOR            "navyblue"
#define DEF_PEN_NORMAL_MONO             "#000000"
#define DEF_PEN_OFFDASH_COLOR           (char *)NULL
#define DEF_PEN_OFFDASH_MONO            (char *)NULL
#define DEF_PEN_OUTLINE_COLOR           "defcolor"
#define DEF_PEN_OUTLINE_MONO            "defcolor"
#define DEF_PEN_OUTLINE_WIDTH           "1"
#define DEF_PEN_PIXELS                  "0.125i"
#define DEF_PEN_SYMBOL                  "circle"
#define DEF_PEN_TYPE                    "line"
#define	DEF_PEN_VALUE_ANCHOR            "s"
#define	DEF_PEN_VALUE_COLOR             "black"
#define	DEF_PEN_VALUE_FONT              RBC_FONT_SMALL
#define	DEF_PEN_VALUE_FORMAT            "%g"
#define	DEF_PEN_VALUE_ROTATE            (char *)NULL
#define	DEF_PEN_VALUE_SHADOW            (char *)NULL
#define DEF_PEN_SHOW_VALUES             "no"
static Tk_ConfigSpec lineElemConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-activepen", "activePen", "ActivePen",
            DEF_LINE_ACTIVE_PEN, Tk_Offset(Line, activePenPtr),
            TK_CONFIG_NULL_OK, &rbcLinePenOption},
    {TK_CONFIG_CUSTOM, "-areapattern", "areaPattern", "AreaPattern",
            DEF_LINE_PATTERN, Tk_Offset(Line, fillStipple),
        TK_CONFIG_NULL_OK, &patternOption},
    {TK_CONFIG_COLOR, "-areaforeground", "areaForeground", "areaForeground",
        DEF_LINE_PATTERN_FG, Tk_Offset(Line, fillFgColor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-areabackground", "areaBackground", "areaBackground",
        DEF_LINE_PATTERN_BG, Tk_Offset(Line, fillBgColor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-areatile", "areaTile", "AreaTile",
            DEF_LINE_PATTERN_TILE, Tk_Offset(Line, fillTile),
        TK_CONFIG_NULL_OK, &rbcTileOption},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_LINE_TAGS, Tk_Offset(Line, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_LINE_PEN_COLOR, Tk_Offset(Line, builtinPen.traceColor),
        TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_LINE_PEN_MONO, Tk_Offset(Line, builtinPen.traceColor),
        TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes",
            DEF_LINE_DASHES, Tk_Offset(Line, builtinPen.traceDashes),
        TK_CONFIG_NULL_OK, &rbcDashesOption},
    {TK_CONFIG_CUSTOM, "-data", "data", "Data",
        DEF_LINE_DATA, 0, 0, &rbcDataPairsOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_LINE_ERRORBAR_COLOR, Tk_Offset(Line, builtinPen.errorBarColor),
        0, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_LINE_ERRORBAR_LINE_WIDTH,
            Tk_Offset(Line, builtinPen.errorBarLineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap", "ErrorBarCap",
            DEF_LINE_ERRORBAR_CAP_WIDTH,
            Tk_Offset(Line, builtinPen.errorBarCapWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_LINE_FILL_COLOR, Tk_Offset(Line, builtinPen.symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_LINE_FILL_MONO, Tk_Offset(Line, builtinPen.symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
        DEF_LINE_HIDE, Tk_Offset(Line, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-label", "label", "Label",
        (char *)NULL, Tk_Offset(Line, label), TK_CONFIG_NULL_OK},
    {TK_CONFIG_RELIEF, "-labelrelief", "labelRelief", "LabelRelief",
            DEF_LINE_LABEL_RELIEF, Tk_Offset(Line, labelRelief),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_LINE_PEN_WIDTH, Tk_Offset(Line, builtinPen.traceWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_LINE_AXIS_X, Tk_Offset(Line, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_LINE_AXIS_Y, Tk_Offset(Line, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_CUSTOM, "-maxsymbols", "maxSymbols", "MaxSymbols",
            DEF_LINE_MAX_SYMBOLS, Tk_Offset(Line, reqMaxSymbols),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_LINE_OFFDASH_COLOR, Tk_Offset(Line, builtinPen.traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_LINE_OFFDASH_MONO, Tk_Offset(Line, builtinPen.traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_LINE_OUTLINE_COLOR, Tk_Offset(Line,
                builtinPen.symbol.outlineColor),
        TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_LINE_OUTLINE_MONO, Tk_Offset(Line,
                builtinPen.symbol.outlineColor),
        TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outlinewidth", "outlineWidth", "OutlineWidth",
            DEF_LINE_OUTLINE_WIDTH, Tk_Offset(Line,
                builtinPen.symbol.outlineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-pen", "pen", "Pen",
            (char *)NULL, Tk_Offset(Line, normalPenPtr),
        TK_CONFIG_NULL_OK, &rbcLinePenOption},
    {TK_CONFIG_CUSTOM, "-pixels", "pixels", "Pixels",
            DEF_LINE_PIXELS, Tk_Offset(Line, builtinPen.symbol.size),
        RBC_GRAPH | RBC_STRIPCHART, &rbcDistanceOption},
    {TK_CONFIG_DOUBLE, "-reduce", "reduce", "Reduce",
            DEF_LINE_REDUCE, Tk_Offset(Line, rTolerance),
        RBC_GRAPH | RBC_STRIPCHART | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-scalesymbols", "scaleSymbols", "ScaleSymbols",
            DEF_LINE_SCALE_SYMBOLS, Tk_Offset(Line, scaleSymbols),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_LINE_SHOW_ERRORBARS, Tk_Offset(Line, builtinPen.errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(Line, builtinPen.valueShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-smooth", "smooth", "Smooth",
            DEF_LINE_SMOOTH, Tk_Offset(Line, reqSmooth),
        TK_CONFIG_DONT_SET_DEFAULT, &smoothOption},
    {TK_CONFIG_CUSTOM, "-state", "state", "State",
            DEF_LINE_STATE, Tk_Offset(Line, state),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_CUSTOM, "-styles", "styles", "Styles",
            DEF_LINE_STYLES, Tk_Offset(Line, palette),
        TK_CONFIG_NULL_OK, &stylesOption},
    {TK_CONFIG_CUSTOM, "-symbol", "symbol", "Symbol",
            DEF_LINE_SYMBOL, Tk_Offset(Line, builtinPen.symbol),
        TK_CONFIG_DONT_SET_DEFAULT, &symbolOption},
    {TK_CONFIG_CUSTOM, "-trace", "trace", "Trace",
            DEF_LINE_PEN_DIRECTION, Tk_Offset(Line, penDir),
        TK_CONFIG_DONT_SET_DEFAULT, &penDirOption},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR,
        Tk_Offset(Line, builtinPen.valueStyle.anchor), 0},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
        DEF_PEN_VALUE_COLOR, Tk_Offset(Line, builtinPen.valueStyle.color), 0},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont",
        DEF_PEN_VALUE_FONT, Tk_Offset(Line, builtinPen.valueStyle.font), 0},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(Line, builtinPen.valueFormat),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
        DEF_PEN_VALUE_ROTATE, Tk_Offset(Line, builtinPen.valueStyle.theta),
            0},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(Line, builtinPen.valueStyle.shadow),
        0, &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-weights", "weights", "Weights",
        (char *)NULL, Tk_Offset(Line, w), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-x", "xData", "XData",
        (char *)NULL, Tk_Offset(Line, x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xdata", "xData", "XData",
        (char *)NULL, Tk_Offset(Line, x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xerror", "xError", "XError",
        (char *)NULL, Tk_Offset(Line, xError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xhigh", "xHigh", "XHigh",
        (char *)NULL, Tk_Offset(Line, xHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xlow", "xLow", "XLow",
        (char *)NULL, Tk_Offset(Line, xLow), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-y", "yData", "YData",
        (char *)NULL, Tk_Offset(Line, y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ydata", "yData", "YData",
        (char *)NULL, Tk_Offset(Line, y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yerror", "yError", "YError",
        (char *)NULL, Tk_Offset(Line, yError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yhigh", "yHigh", "YHigh",
        (char *)NULL, Tk_Offset(Line, yHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ylow", "yLow", "YLow",
        (char *)NULL, Tk_Offset(Line, yLow), 0, &rbcDataOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static Tk_ConfigSpec stripElemConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-activepen", "activePen", "ActivePen",
            DEF_LINE_ACTIVE_PEN, Tk_Offset(Line, activePenPtr),
        TK_CONFIG_NULL_OK, &rbcLinePenOption},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_LINE_TAGS, Tk_Offset(Line, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_LINE_PEN_COLOR, Tk_Offset(Line, builtinPen.traceColor),
        TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_LINE_PEN_MONO, Tk_Offset(Line, builtinPen.traceColor),
        TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes",
            DEF_LINE_DASHES, Tk_Offset(Line, builtinPen.traceDashes),
        TK_CONFIG_NULL_OK, &rbcDashesOption},
    {TK_CONFIG_CUSTOM, "-data", "data", "Data",
        DEF_LINE_DATA, 0, 0, &rbcDataPairsOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_LINE_ERRORBAR_COLOR, Tk_Offset(Line, builtinPen.errorBarColor),
        0, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_LINE_ERRORBAR_LINE_WIDTH,
            Tk_Offset(Line, builtinPen.errorBarLineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap",
            "ErrorBarCap", DEF_LINE_ERRORBAR_CAP_WIDTH,
            Tk_Offset(Line, builtinPen.errorBarCapWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_LINE_FILL_COLOR, Tk_Offset(Line, builtinPen.symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_LINE_FILL_MONO, Tk_Offset(Line, builtinPen.symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
        DEF_LINE_HIDE, Tk_Offset(Line, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-label", "label", "Label",
        (char *)NULL, Tk_Offset(Line, label), TK_CONFIG_NULL_OK},
    {TK_CONFIG_RELIEF, "-labelrelief", "labelRelief", "LabelRelief",
            DEF_LINE_LABEL_RELIEF, Tk_Offset(Line, labelRelief),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_LINE_PEN_WIDTH, Tk_Offset(Line, builtinPen.traceWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_LINE_AXIS_X, Tk_Offset(Line, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_LINE_AXIS_Y, Tk_Offset(Line, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_CUSTOM, "-maxsymbols", "maxSymbols", "MaxSymbols",
            DEF_LINE_MAX_SYMBOLS, Tk_Offset(Line, reqMaxSymbols),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_LINE_OFFDASH_COLOR, Tk_Offset(Line, builtinPen.traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_LINE_OFFDASH_MONO, Tk_Offset(Line, builtinPen.traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_LINE_OUTLINE_COLOR, Tk_Offset(Line,
                builtinPen.symbol.outlineColor),
        TK_CONFIG_COLOR_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_LINE_OUTLINE_MONO, Tk_Offset(Line,
                builtinPen.symbol.outlineColor),
        TK_CONFIG_MONO_ONLY, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outlinewidth", "outlineWidth", "OutlineWidth",
            DEF_LINE_OUTLINE_WIDTH, Tk_Offset(Line,
                builtinPen.symbol.outlineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-pen", "pen", "Pen",
            (char *)NULL, Tk_Offset(Line, normalPenPtr),
        TK_CONFIG_NULL_OK, &rbcLinePenOption},
    {TK_CONFIG_CUSTOM, "-pixels", "pixels", "Pixels",
            DEF_LINE_PIXELS, Tk_Offset(Line, builtinPen.symbol.size), 0,
        &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-scalesymbols", "scaleSymbols", "ScaleSymbols",
            DEF_LINE_SCALE_SYMBOLS, Tk_Offset(Line, scaleSymbols),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_LINE_SHOW_ERRORBARS, Tk_Offset(Line, builtinPen.errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(Line, builtinPen.valueShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-smooth", "smooth", "Smooth",
            DEF_LINE_SMOOTH, Tk_Offset(Line, reqSmooth),
        TK_CONFIG_DONT_SET_DEFAULT, &smoothOption},
    {TK_CONFIG_CUSTOM, "-styles", "styles", "Styles",
            DEF_LINE_STYLES, Tk_Offset(Line, palette),
        TK_CONFIG_NULL_OK, &stylesOption},
    {TK_CONFIG_CUSTOM, "-symbol", "symbol", "Symbol",
            DEF_LINE_SYMBOL, Tk_Offset(Line, builtinPen.symbol),
        TK_CONFIG_DONT_SET_DEFAULT, &symbolOption},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
            DEF_PEN_VALUE_ANCHOR,
        Tk_Offset(Line, builtinPen.valueStyle.anchor), 0},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
        DEF_PEN_VALUE_COLOR, Tk_Offset(Line, builtinPen.valueStyle.color), 0},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont",
        DEF_PEN_VALUE_FONT, Tk_Offset(Line, builtinPen.valueStyle.font), 0},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(Line, builtinPen.valueFormat),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
        DEF_PEN_VALUE_ROTATE, Tk_Offset(Line, builtinPen.valueStyle.theta),
            0},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(Line, builtinPen.valueStyle.shadow),
            0,
        &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-weights", "weights", "Weights",
        (char *)NULL, Tk_Offset(Line, w), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-x", "xData", "XData",
        (char *)NULL, Tk_Offset(Line, x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xdata", "xData", "XData",
        (char *)NULL, Tk_Offset(Line, x), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-y", "yData", "YData",
        (char *)NULL, Tk_Offset(Line, y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xerror", "xError", "XError", (char *)NULL,
        Tk_Offset(Line, xError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ydata", "yData", "YData",
        (char *)NULL, Tk_Offset(Line, y), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yerror", "yError", "YError", (char *)NULL,
        Tk_Offset(Line, yError), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xhigh", "xHigh", "XHigh", (char *)NULL,
        Tk_Offset(Line, xHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-xlow", "xLow", "XLow", (char *)NULL,
        Tk_Offset(Line, xLow), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-yhigh", "yHigh", "YHigh", (char *)NULL,
        Tk_Offset(Line, xHigh), 0, &rbcDataOption},
    {TK_CONFIG_CUSTOM, "-ylow", "yLow", "YLow", (char *)NULL,
        Tk_Offset(Line, yLow), 0, &rbcDataOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static Tk_ConfigSpec linePenConfigSpecs[] = {
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_PEN_ACTIVE_COLOR, Tk_Offset(LinePen, traceColor),
        TK_CONFIG_COLOR_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_PEN_ACTIVE_MONO, Tk_Offset(LinePen, traceColor),
        TK_CONFIG_MONO_ONLY | RBC_ACTIVE_PEN},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_PEN_NORMAL_COLOR, Tk_Offset(LinePen, traceColor),
        TK_CONFIG_COLOR_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
            DEF_PEN_NORMAL_MONO, Tk_Offset(LinePen, traceColor),
        TK_CONFIG_MONO_ONLY | RBC_NORMAL_PEN},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes",
            DEF_PEN_DASHES, Tk_Offset(LinePen, traceDashes),
        TK_CONFIG_NULL_OK | RBC_ALL_PENS, &rbcDashesOption},
    {TK_CONFIG_CUSTOM, "-errorbarcolor", "errorBarColor", "ErrorBarColor",
            DEF_LINE_ERRORBAR_COLOR, Tk_Offset(LinePen, errorBarColor),
        RBC_ALL_PENS, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-errorbarwidth", "errorBarWidth", "ErrorBarWidth",
            DEF_LINE_ERRORBAR_LINE_WIDTH, Tk_Offset(LinePen, errorBarLineWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-errorbarcap", "errorBarCap",
            "ErrorBarCap", DEF_LINE_ERRORBAR_CAP_WIDTH,
            Tk_Offset(LinePen, errorBarCapWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_PEN_FILL_COLOR, Tk_Offset(LinePen, symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_ALL_PENS,
            &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_PEN_FILL_MONO, Tk_Offset(LinePen, symbol.fillColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_ALL_PENS,
            &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            (char *)NULL, Tk_Offset(LinePen, traceWidth),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_PEN_OFFDASH_COLOR, Tk_Offset(LinePen, traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_COLOR_ONLY | RBC_ALL_PENS,
            &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-offdash", "offDash", "OffDash",
            DEF_PEN_OFFDASH_MONO, Tk_Offset(LinePen, traceOffColor),
        TK_CONFIG_NULL_OK | TK_CONFIG_MONO_ONLY | RBC_ALL_PENS,
            &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_PEN_OUTLINE_COLOR, Tk_Offset(LinePen, symbol.outlineColor),
        TK_CONFIG_COLOR_ONLY | RBC_ALL_PENS, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_PEN_OUTLINE_MONO, Tk_Offset(LinePen, symbol.outlineColor),
        TK_CONFIG_MONO_ONLY | RBC_ALL_PENS, &rbcColorOption},
    {TK_CONFIG_CUSTOM, "-outlinewidth", "outlineWidth", "OutlineWidth",
            DEF_PEN_OUTLINE_WIDTH, Tk_Offset(LinePen, symbol.outlineWidth),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_PENS, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-pixels", "pixels", "Pixels",
            DEF_PEN_PIXELS, Tk_Offset(LinePen, symbol.size),
        RBC_ALL_PENS, &rbcDistanceOption},
    {TK_CONFIG_CUSTOM, "-showerrorbars", "showErrorBars", "ShowErrorBars",
            DEF_LINE_SHOW_ERRORBARS, Tk_Offset(LinePen, errorBarShow),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-showvalues", "showValues", "ShowValues",
            DEF_PEN_SHOW_VALUES, Tk_Offset(LinePen, valueShow),
        RBC_ALL_PENS | TK_CONFIG_DONT_SET_DEFAULT, &rbcFillOption},
    {TK_CONFIG_CUSTOM, "-symbol", "symbol", "Symbol",
            DEF_PEN_SYMBOL, Tk_Offset(LinePen, symbol),
        TK_CONFIG_DONT_SET_DEFAULT | RBC_ALL_PENS, &symbolOption},
    {TK_CONFIG_STRING, "-type", (char *)NULL, (char *)NULL,
        DEF_PEN_TYPE, Tk_Offset(RbcPen, typeId),
            RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_ANCHOR, "-valueanchor", "valueAnchor", "ValueAnchor",
        DEF_PEN_VALUE_ANCHOR, Tk_Offset(LinePen, valueStyle.anchor),
            RBC_ALL_PENS},
    {TK_CONFIG_COLOR, "-valuecolor", "valueColor", "ValueColor",
        DEF_PEN_VALUE_COLOR, Tk_Offset(LinePen, valueStyle.color),
            RBC_ALL_PENS},
    {TK_CONFIG_FONT, "-valuefont", "valueFont", "ValueFont",
        DEF_PEN_VALUE_FONT, Tk_Offset(LinePen, valueStyle.font),
            RBC_ALL_PENS},
    {TK_CONFIG_STRING, "-valueformat", "valueFormat", "ValueFormat",
            DEF_PEN_VALUE_FORMAT, Tk_Offset(LinePen, valueFormat),
        RBC_ALL_PENS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_DOUBLE, "-valuerotate", "valueRotate", "ValueRotate",
        DEF_PEN_VALUE_ROTATE, Tk_Offset(LinePen, valueStyle.theta),
            RBC_ALL_PENS},
    {TK_CONFIG_CUSTOM, "-valueshadow", "valueShadow", "ValueShadow",
            DEF_PEN_VALUE_SHADOW, Tk_Offset(LinePen, valueStyle.shadow),
        RBC_ALL_PENS, &rbcShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

typedef double (
    DistanceProc) (
    int x,
    int y,
    RbcPoint2D * p,
    RbcPoint2D * q,
    RbcPoint2D * t);
/* Forward declarations */
static PenConfigureProc ConfigurePen;
static PenDestroyProc DestroyPen;
static RbcElementClosestProc ClosestLine;
static RbcElementConfigProc ConfigureLine;
static RbcElementDestroyProc DestroyLine;
static RbcElementDrawProc DrawActiveLine;
static RbcElementDrawProc DrawNormalLine;
static RbcElementDrawSymbolProc DrawSymbol;
static RbcElementExtentsProc GetLineExtents;
static RbcElementToPostScriptProc ActiveLineToPostScript;
static RbcElementToPostScriptProc NormalLineToPostScript;
static RbcElementSymbolToPostScriptProc SymbolToPostScript;
static RbcElementMapProc MapLine;
static DistanceProc DistanceToY;
static DistanceProc DistanceToX;
static DistanceProc DistanceToLine;
static RbcTileChangedProc TileChangedProc;
static int Round(
    register double x);
static int StringToBitmap(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Symbol * symbolPtr,
    const char *string);
static const char *NameOfSymbol(
    Symbol * symbolPtr);
static const char *NameOfSmooth(
    Smoothing value);
static const char *NameOfPenDir(
    int penDir);
static void ClearPalette(
    RbcChain * palette);
static void InitPen(
    LinePen * penPtr);
static int ScaleSymbol(
    RbcElement * elemPtr,
    int normalSize);
static void GetScreenPoints(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void ReducePoints(
    MapInfo * mapPtr,
    double tolerance);
static void GenerateSteps(
    MapInfo * mapPtr);
static void GenerateSpline(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void GenerateParametricSpline(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void MapSymbols(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void MapActiveSymbols(
    RbcGraph * graph,
    Line * linePtr);
static void MapStrip(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void MergePens(
    Line * linePtr,
    RbcPenStyle ** dataToStyle);
static int OutCode(
    RbcExtents2D * extsPtr,
    RbcPoint2D * p);
static int ClipSegment(
    RbcExtents2D * extsPtr,
    register int code1,
    register int code2,
    register RbcPoint2D * p,
    register RbcPoint2D * q);
static void SaveTrace(
    Line * linePtr,
    int start,
    int length,
    MapInfo * mapPtr);
static void FreeTraces(
    Line * linePtr);
static void MapTraces(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void MapFillArea(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr);
static void ResetLine(
    Line * linePtr);
static int ClosestTrace(
    RbcGraph * graph,
    Line * linePtr,
    RbcClosestSearch * searchPtr,
    DistanceProc * distProc);
static int ClosestStrip(
    RbcGraph * graph,
    Line * linePtr,
    RbcClosestSearch * searchPtr,
    DistanceProc * distProc);
static void ClosestPoint(
    Line * linePtr,
    RbcClosestSearch * searchPtr);
static void DrawCircles(
    Display * display,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int radius);
static void DrawSquares(
    Display * display,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    register RbcPoint2D * symbolPts,
    int r);
static void DrawSymbols(
    RbcGraph * graph,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int size,
    int nSymbolPts,
    RbcPoint2D * symbolPts);
static void DrawTraces(
    RbcGraph * graph,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr);
static void DrawValues(
    RbcGraph * graph,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int *pointToData);
static void GetSymbolPostScriptInfo(
    RbcGraph * graph,
    RbcPsToken * psToken,
    LinePen * penPtr,
    int size);
static void SymbolsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    LinePen * penPtr,
    int size,
    int nSymbolPts,
    RbcPoint2D * symbolPts);
static void SetLineAttributes(
    RbcPsToken * psToken,
    LinePen * penPtr);
static void TracesToPostScript(
    RbcPsToken * psToken,
    Line * linePtr,
    LinePen * penPtr);
static void ValuesToPostScript(
    RbcPsToken * psToken,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int *pointToData);
/*
 *----------------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
Round(
    register double x)
{
    return (int)(x + ((x < 0.0) ? -0.5 : 0.5));
}

/*
 * ----------------------------------------------------------------------
 * 	Custom configuration option (parse and print) routines
 * ----------------------------------------------------------------------
 */
/*
 *----------------------------------------------------------------------
 *
 * StringToBitmap --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToBitmap(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Symbol * symbolPtr,
    const char *string)
{
    Pixmap bitmap, mask;
    const char **elemArr;
    int nElems;
    int result;
    if(Tcl_SplitList(interp, string, &nElems, &elemArr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(nElems > 2) {
        Tcl_AppendResult(interp, "too many elements in bitmap list \"", string,
            "\": should be \"bitmap mask\"", (char *)NULL);
        result = TCL_ERROR;
        goto error;
    }
    mask = None;
    bitmap = Tk_GetBitmap(interp, tkwin, Tk_GetUid(elemArr[0]));
    if(bitmap == None) {
        result = TCL_BREAK;
        Tcl_ResetResult(interp);
        goto error;
    }
    if((nElems > 1) && (elemArr[1][0] != '\0')) {
        mask = Tk_GetBitmap(interp, tkwin, Tk_GetUid(elemArr[1]));
        if(mask == None) {
            Tk_FreeBitmap(Tk_Display(tkwin), bitmap);
            result = TCL_ERROR;
            goto error;
        }
    }
    ckfree((char *)elemArr);
    if(symbolPtr->bitmap != None) {
        Tk_FreeBitmap(Tk_Display(tkwin), symbolPtr->bitmap);
    }
    symbolPtr->bitmap = bitmap;
    if(symbolPtr->mask != None) {
        Tk_FreeBitmap(Tk_Display(tkwin), symbolPtr->mask);
    }
    symbolPtr->mask = mask;
    return TCL_OK;
  error:
    ckfree((char *)elemArr);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * PatternToString --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PatternToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,
    char *widgRec,             /* Element information record */
    int offset,                /* Offset of field in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    Pixmap stipple = *(Pixmap *) (widgRec + offset);
    if(stipple == None) {
        return "";
    }
    if(stipple == PATTERN_SOLID) {
        return "solid";
    }
    return Tk_NameOfBitmap(Tk_Display(tkwin), stipple);
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPattern --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToPattern(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing field */
    char *widgRec,             /* Element information record */
    int offset)
{              /* Offset of field in record */
    Pixmap *stipplePtr = (Pixmap *) (widgRec + offset);
    Pixmap stipple;
    if((string == NULL) || (string[0] == '\0')) {
        stipple = None;
    } else if(strcmp(string, "solid") == 0) {
        stipple = PATTERN_SOLID;
    } else {
        stipple = Tk_GetBitmap(interp, tkwin, Tk_GetUid(string));
        if(stipple == None) {
            return TCL_ERROR;
        }
    }
    if((*stipplePtr != None) && (*stipplePtr != PATTERN_SOLID)) {
        Tk_FreeBitmap(Tk_Display(tkwin), *stipplePtr);
    }
    *stipplePtr = stipple;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfSymbol --
 *
 *      Converts the symbol value into its string representation.
 *
 * Results:
 *      The static string representing the symbol type is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfSymbol(
    Symbol * symbolPtr)
{
    switch (symbolPtr->type) {
    case SYMBOL_NONE:
        return "none";
    case SYMBOL_SQUARE:
        return "square";
    case SYMBOL_CIRCLE:
        return "circle";
    case SYMBOL_DIAMOND:
        return "diamond";
    case SYMBOL_PLUS:
        return "plus";
    case SYMBOL_CROSS:
        return "cross";
    case SYMBOL_SPLUS:
        return "splus";
    case SYMBOL_SCROSS:
        return "scross";
    case SYMBOL_TRIANGLE:
        return "triangle";
    case SYMBOL_ARROW:
        return "arrow";
    case SYMBOL_BITMAP:
        return "bitmap";
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToSymbol --
 *
 *      Convert the string representation of a line style or symbol name
 *      into its numeric form.
 *
 * Results:
 *      The return value is a standard Tcl result.  The symbol type is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToSymbol(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing symbol type */
    char *widgRec,             /* Element information record */
    int offset)
{              /* Offset of symbol type field in record */
    Symbol *symbolPtr = (Symbol *) (widgRec + offset);
    unsigned int length;
    char c;
    c = string[0];
    length = strlen(string);
    if(c == '\0') {
        symbolPtr->type = SYMBOL_NONE;
    } else if((c == 'n') && (strncmp(string, "none", length) == 0)) {
        symbolPtr->type = SYMBOL_NONE;
    } else if((c == 'c') && (length > 1) &&
        (strncmp(string, "circle", length) == 0)) {
        symbolPtr->type = SYMBOL_CIRCLE;
    } else if((c == 's') && (length > 1) &&
        (strncmp(string, "square", length) == 0)) {
        symbolPtr->type = SYMBOL_SQUARE;
    } else if((c == 'd') && (strncmp(string, "diamond", length) == 0)) {
        symbolPtr->type = SYMBOL_DIAMOND;
    } else if((c == 'p') && (strncmp(string, "plus", length) == 0)) {
        symbolPtr->type = SYMBOL_PLUS;
    } else if((c == 'c') && (length > 1) &&
        (strncmp(string, "cross", length) == 0)) {
        symbolPtr->type = SYMBOL_CROSS;
    } else if((c == 's') && (length > 1) &&
        (strncmp(string, "splus", length) == 0)) {
        symbolPtr->type = SYMBOL_SPLUS;
    } else if((c == 's') && (length > 1) &&
        (strncmp(string, "scross", length) == 0)) {
        symbolPtr->type = SYMBOL_SCROSS;
    } else if((c == 't') && (strncmp(string, "triangle", length) == 0)) {
        symbolPtr->type = SYMBOL_TRIANGLE;
    } else if((c == 'a') && (strncmp(string, "arrow", length) == 0)) {
        symbolPtr->type = SYMBOL_ARROW;
    } else {
    int result;
        result = StringToBitmap(interp, tkwin, symbolPtr, string);
        if(result != TCL_OK) {
            if(result != TCL_ERROR) {
                Tcl_AppendResult(interp, "bad symbol \"", string,
                    "\": should be \"none\", \"circle\", \"square\", \"diamond\", \"plus\", \
\"cross\", \"splus\", \"scross\", \"triangle\", \"arrow\" \
or the name of a bitmap", (char *)NULL);
            }
            return TCL_ERROR;
        }
        symbolPtr->type = SYMBOL_BITMAP;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * SymbolToString --
 *
 *      Convert the symbol value into a string.
 *
 * Results:
 *      The string representing the symbol type or line style is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
SymbolToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,
    char *widgRec,             /* Element information record */
    int offset,                /* Offset of symbol type field in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    Symbol *symbolPtr = (Symbol *) (widgRec + offset);
    const char *result;
    if(symbolPtr->type == SYMBOL_BITMAP) {
    Tcl_DString dString;
        Tcl_DStringInit(&dString);
        Tcl_DStringAppendElement(&dString,
            Tk_NameOfBitmap(Tk_Display(tkwin), symbolPtr->bitmap));
        Tcl_DStringAppendElement(&dString, (symbolPtr->mask == None) ? "" :
            Tk_NameOfBitmap(Tk_Display(tkwin), symbolPtr->mask));
        result = RbcStrdup(Tcl_DStringValue(&dString));
        Tcl_DStringFree(&dString);
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    } else {
        result = NameOfSymbol(symbolPtr);
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfSmooth --
 *
 *      Converts the smooth value into its string representation.
 *
 * Results:
 *      The static string representing the smooth type is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfSmooth(
    Smoothing value)
{
    if((value < 0) || (value >= PEN_SMOOTH_LAST)) {
        return "unknown smooth value";
    }
    return smoothingInfo[value].name;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToSmooth --
 *
 *      Convert the string representation of a line style or smooth name
 *      into its numeric form.
 *
 * Results:
 *      The return value is a standard Tcl result.  The smooth type is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToSmooth(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing smooth type */
    char *widgRec,             /* Element information record */
    int offset)
{              /* Offset of smooth type field in record */
    Smoothing *valuePtr = (Smoothing *) (widgRec + offset);
    register SmoothingInfo *siPtr;
    for(siPtr = smoothingInfo; siPtr->name != NULL; siPtr++) {
        if(strcmp(string, siPtr->name) == 0) {
            *valuePtr = siPtr->value;
            return TCL_OK;
        }
    }
    Tcl_AppendResult(interp, "bad smooth value \"", string, "\": should be \
linear, step, natural, or quadratic", (char *)NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * SmoothToString --
 *
 *      Convert the smooth value into a string.
 *
 * Results:
 *      The string representing the smooth type or line style is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
SmoothToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element information record */
    int offset,                /* Offset of smooth type field in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int smooth = *(int *)(widgRec + offset);
    return NameOfSmooth(smooth);
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPenDir --
 *
 *      Convert the string representation of a line style or symbol name
 *      into its numeric form.
 *
 * Results:
 *      The return value is a standard Tcl result.  The symbol type is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToPenDir(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing pen direction */
    char *widgRec,             /* Element information record */
    int offset)
{              /* Offset of pen direction field in record */
    int *penDirPtr = (int *)(widgRec + offset);
    unsigned int length;
    char c;
    c = string[0];
    length = strlen(string);
    if((c == 'i') && (strncmp(string, "increasing", length) == 0)) {
        *penDirPtr = PEN_INCREASING;
    } else if((c == 'd') && (strncmp(string, "decreasing", length) == 0)) {
        *penDirPtr = PEN_DECREASING;
    } else if((c == 'b') && (strncmp(string, "both", length) == 0)) {
        *penDirPtr = PEN_BOTH_DIRECTIONS;
    } else {
        Tcl_AppendResult(interp, "bad trace value \"", string,
            "\" : should be \"increasing\", \"decreasing\", or \"both\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfPenDir --
 *
 *      Convert the pen direction into a string.
 *
 * Results:
 *      The static string representing the pen direction is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfPenDir(
    int penDir)
{              /* Direction for pen drawing between points */
    switch (penDir) {
    case PEN_INCREASING:
        return "increasing";
    case PEN_DECREASING:
        return "decreasing";
    case PEN_BOTH_DIRECTIONS:
        return "both";
    default:
        return "unknown trace direction";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * PenDirToString --
 *
 *      Convert the pen direction into a string.
 *
 * Results:
 *      The string representing the pen drawing direction is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PenDirToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element information record */
    int offset,                /* Offset of pen direction field in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int penDir = *(int *)(widgRec + offset);
    return NameOfPenDir(penDir);
}

/*
 *----------------------------------------------------------------------
 *
 * ClearPalette --
 *
 *      Clear the number of points and segments, in case there are no
 *      segments or points
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ClearPalette(
    RbcChain * palette)
{
register LinePenStyle *stylePtr;
RbcChainLink *linkPtr;
    for(linkPtr = RbcChainFirstLink(palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->nStrips = stylePtr->nSymbolPts = 0;
        stylePtr->xErrorBarCnt = stylePtr->yErrorBarCnt = 0;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigurePen --
 *
 *      Sets up the appropriate configuration parameters in the GC.
 *      It is assumed the parameters have been previously set by
 *      a call to Tk_ConfigureWidget.
 *
 * Results:
 *      The return value is a standard Tcl result.  If TCL_ERROR is
 *      returned, then Tcl_GetString(Tcl_GetObjResult(interp)) contains an error message.
 *
 * Side effects:
 *      Configuration information such as line width, line style, color
 *      etc. get set in a new GC.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigurePen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
LinePen *lpPtr = (LinePen *) penPtr;
unsigned long gcMask;
GC  newGC;
XGCValues gcValues;
XColor *colorPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    RbcResetTextStyle(*(graph->win), &(lpPtr->valueStyle));
    /*
     * Set the outline GC for this pen: GCForeground is outline color.
     * GCBackground is the fill color (only used for bitmap symbols).
     */
    gcMask = (GCLineWidth | GCForeground);
    colorPtr = lpPtr->symbol.outlineColor;
    if(colorPtr == RBC_COLOR_DEFAULT) {
        colorPtr = lpPtr->traceColor;
    }
    gcValues.foreground = colorPtr->pixel;
    if(lpPtr->symbol.type == SYMBOL_BITMAP) {
        colorPtr = lpPtr->symbol.fillColor;
        if(colorPtr == RBC_COLOR_DEFAULT) {
            colorPtr = lpPtr->traceColor;
        }
        /*
         * Set a clip mask if either
         *      1) no background color was designated or
         *      2) a masking bitmap was specified.
         *
         * These aren't necessarily the bitmaps we'll be using for
         * clipping. But this makes it unlikely that anyone else will
         * be sharing this GC when we set the clip origin (at the time
         * the bitmap is drawn).
         */
        if(colorPtr != NULL) {
            gcValues.background = colorPtr->pixel;
            gcMask |= GCBackground;
            if(lpPtr->symbol.mask != None) {
                gcValues.clip_mask = lpPtr->symbol.mask;
                gcMask |= GCClipMask;
            }
        } else {
            gcValues.clip_mask = lpPtr->symbol.bitmap;
            gcMask |= GCClipMask;
        }
    }
    gcValues.line_width = RbcLineWidth(lpPtr->symbol.outlineWidth);
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(lpPtr->symbol.outlineGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->symbol.outlineGC);
    }
    lpPtr->symbol.outlineGC = newGC;
    /* Fill GC for symbols: GCForeground is fill color */
    gcMask = (GCLineWidth | GCForeground);
    colorPtr = lpPtr->symbol.fillColor;
    if(colorPtr == RBC_COLOR_DEFAULT) {
        colorPtr = lpPtr->traceColor;
    }
    newGC = NULL;
    if(colorPtr != NULL) {
        gcValues.foreground = colorPtr->pixel;
        newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    }
    if(lpPtr->symbol.fillGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->symbol.fillGC);
    }
    lpPtr->symbol.fillGC = newGC;
    /* Line segments */
    gcMask = (GCLineWidth | GCForeground | GCLineStyle | GCCapStyle |
        GCJoinStyle);
    gcValues.cap_style = CapButt;
    gcValues.join_style = JoinRound;
    gcValues.line_style = LineSolid;
    gcValues.line_width = RbcLineWidth(lpPtr->traceWidth);
    colorPtr = lpPtr->traceOffColor;
    if(colorPtr == RBC_COLOR_DEFAULT) {
        colorPtr = lpPtr->traceColor;
    }
    if(colorPtr != NULL) {
        gcMask |= GCBackground;
        gcValues.background = colorPtr->pixel;
    }
    gcValues.foreground = lpPtr->traceColor->pixel;
    if(RbcLineIsDashed(lpPtr->traceDashes)) {
        gcValues.line_width = lpPtr->traceWidth;
        gcValues.line_style =
            (colorPtr == NULL) ? LineOnOffDash : LineDoubleDash;
    }
    newGC = RbcGetPrivateGC(*(graph->win), gcMask, &gcValues);
    if(lpPtr->traceGC != NULL) {
        RbcFreePrivateGC(graph->display, lpPtr->traceGC);
    }
    if(RbcLineIsDashed(lpPtr->traceDashes)) {
        lpPtr->traceDashes.offset = lpPtr->traceDashes.values[0] / 2;
        RbcSetDashes(graph->display, newGC, &(lpPtr->traceDashes));
    }
    lpPtr->traceGC = newGC;
    gcMask = (GCLineWidth | GCForeground);
    colorPtr = lpPtr->errorBarColor;
    if(colorPtr == RBC_COLOR_DEFAULT) {
        colorPtr = lpPtr->traceColor;
    }
    gcValues.line_width = RbcLineWidth(lpPtr->errorBarLineWidth);
    gcValues.foreground = colorPtr->pixel;
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(lpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->errorBarGC);
    }
    lpPtr->errorBarGC = newGC;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyPen --
 *
 *      Release memory and resources allocated for the style.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the pen style is freed up.
 *
 *----------------------------------------------------------------------
 */
static void
DestroyPen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
LinePen *lpPtr = (LinePen *) penPtr;
    RbcFreeTextStyle(graph->display, &(lpPtr->valueStyle));
    if(lpPtr->symbol.outlineGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->symbol.outlineGC);
    }
    if(lpPtr->symbol.fillGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->symbol.fillGC);
    }
    if(lpPtr->errorBarGC != NULL) {
        Tk_FreeGC(graph->display, lpPtr->errorBarGC);
    }
    if(lpPtr->traceGC != NULL) {
        RbcFreePrivateGC(graph->display, lpPtr->traceGC);
    }
    if(lpPtr->symbol.bitmap != None) {
        Tk_FreeBitmap(graph->display, lpPtr->symbol.bitmap);
        lpPtr->symbol.bitmap = None;
    }
    if(lpPtr->symbol.mask != None) {
        Tk_FreeBitmap(graph->display, lpPtr->symbol.mask);
        lpPtr->symbol.mask = None;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * InitPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
InitPen(
    LinePen * penPtr)
{
    RbcInitTextStyle(&penPtr->valueStyle);
    penPtr->configProc = ConfigurePen;
    penPtr->configSpecs = linePenConfigSpecs;
    penPtr->destroyProc = DestroyPen;
    penPtr->errorBarLineWidth = 1;
    penPtr->errorBarShow = RBC_SHOW_BOTH;
    penPtr->flags = RBC_NORMAL_PEN;
    penPtr->name = "";
    penPtr->symbol.bitmap = penPtr->symbol.mask = None;
    penPtr->symbol.outlineColor = penPtr->symbol.fillColor = RBC_COLOR_DEFAULT;
    penPtr->symbol.outlineWidth = penPtr->traceWidth = 1;
    penPtr->symbol.type = SYMBOL_CIRCLE;
    penPtr->valueShow = RBC_SHOW_NONE;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLinePen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcPen *
RbcLinePen(
    const char *penName)
{
    LinePen *penPtr;
    penPtr = RbcCalloc(1, sizeof(LinePen));
    assert(penPtr);
    InitPen(penPtr);
    penPtr->name = RbcStrdup(penName);
    if(strcmp(penName, "activeLine") == 0) {
        penPtr->flags = RBC_ACTIVE_PEN;
    }
    return (RbcPen *) penPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 *  In this section, the routines deal with building and filling
 *  the element's data structures with transformed screen
 *  coordinates.  They are triggered from TranformLine which is
 *  called whenever the data or coordinates axes have changed and
 *  new screen coordinates need to be calculated.
 *
 * ----------------------------------------------------------------------
 */
/*
 *----------------------------------------------------------------------
 *
 * ScaleSymbol --
 *
 *      Returns the scaled size for the line element. Scaling depends
 *      upon when the base line ranges for the element were set and
 *      the current range of the graph.
 *
 * Results:
 *      The new size of the symbol, after considering how much the
 *      graph has been scaled, is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ScaleSymbol(
    RbcElement * elemPtr,
    int normalSize)
{
    int maxSize;
    double scale;
    int newSize;
    scale = 1.0;
    if(elemPtr->scaleSymbols) {
    double xRange, yRange;
        xRange = (elemPtr->axes.x->max - elemPtr->axes.x->min);
        yRange = (elemPtr->axes.y->max - elemPtr->axes.y->min);
        if(elemPtr->flags & RBC_SCALE_SYMBOL) {
            /* Save the ranges as a baseline for future scaling. */
            elemPtr->xRange = xRange;
            elemPtr->yRange = yRange;
            elemPtr->flags &= ~RBC_SCALE_SYMBOL;
        } else {
    double xScale, yScale;
            /* Scale the symbol by the smallest change in the X or Y axes */
            xScale = elemPtr->xRange / xRange;
            yScale = elemPtr->yRange / yRange;
            scale = MIN(xScale, yScale);
        }
    }
    newSize = Round(normalSize * scale);
    /*
     * Don't let the size of symbols go unbounded. Both X and Win32
     * drawing routines assume coordinates to be a signed short int.
     */
    maxSize = (int)MIN(elemPtr->graphPtr->hRange, elemPtr->graphPtr->vRange);
    if(newSize > maxSize) {
        newSize = maxSize;
    }
    /* Make the symbol size odd so that its center is a single pixel. */
    newSize |= 0x01;
    return newSize;
}

/*
 *----------------------------------------------------------------------
 *
 * GetScreenPoints --
 *
 *      Generates a coordinate array of transformed screen coordinates
 *      from the data points.
 *
 * Results:
 *      The transformed screen coordinates are returned.
 *
 * Side effects:
 *      Memory is allocated for the coordinate array.
 *
 *----------------------------------------------------------------------
 */
static void
GetScreenPoints(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
double *x, *y;
register int i, n;
register int count;
register RbcPoint2D *screenPts;
register int *indices;
    n = RbcNumberOfPoints(linePtr);
    x = linePtr->x.valueArr;
    y = linePtr->y.valueArr;
    screenPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * n);
    assert(screenPts);
    indices = (int *)ckalloc(sizeof(int) * n);
    assert(indices);
    count = 0; /* Count the valid screen coordinates */
    if(graph->inverted) {
        for(i = 0; i < n; i++) {
            if((!TclIsInfinite(x[i])) && (!TclIsInfinite(y[i]))) {
                screenPts[count].x = RbcHMap(graph, linePtr->axes.y, y[i]);
                screenPts[count].y = RbcVMap(graph, linePtr->axes.x, x[i]);
                indices[count] = i;
                count++;
            }
        }
    } else {
        for(i = 0; i < n; i++) {
            if((!TclIsInfinite(x[i])) && (!TclIsInfinite(y[i]))) {
                screenPts[count].x = RbcHMap(graph, linePtr->axes.x, x[i]);
                screenPts[count].y = RbcVMap(graph, linePtr->axes.y, y[i]);
                indices[count] = i;
                count++;
            }
        }
    }
    mapPtr->screenPts = screenPts;
    mapPtr->nScreenPts = count;
    mapPtr->indices = indices;
}

/*
 *----------------------------------------------------------------------
 *
 * ReducePoints --
 *
 *      Generates a coordinate array of transformed screen coordinates
 *      from the data points.
 *
 * Results:
 *      The transformed screen coordinates are returned.
 *
 * Side effects:
 *      Memory is allocated for the coordinate array.
 *
 *----------------------------------------------------------------------
 */
static void
ReducePoints(
    MapInfo * mapPtr,
    double tolerance)
{
    register int i, k, n;
    RbcPoint2D *screenPts;
    int *indices, *simple;
    simple = (int *)ckalloc(sizeof(int) * mapPtr->nScreenPts);
    indices = (int *)ckalloc(sizeof(int) * mapPtr->nScreenPts);
    screenPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * mapPtr->nScreenPts);
    n = RbcSimplifyLine(mapPtr->screenPts, 0, mapPtr->nScreenPts - 1,
        tolerance, simple);
    for(i = 0; i < n; i++) {
        k = simple[i];
        screenPts[i] = mapPtr->screenPts[k];
        indices[i] = mapPtr->indices[k];
    }
    ckfree((char *)mapPtr->screenPts);
    ckfree((char *)mapPtr->indices);
    ckfree((char *)simple);
    mapPtr->screenPts = screenPts;
    mapPtr->indices = indices;
    mapPtr->nScreenPts = n;
}

/*
 *----------------------------------------------------------------------
 *
 * GenerateSteps --
 *
 *      Resets the coordinate and pen index arrays adding new points
 *      for step-and-hold type smoothing.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The temporary arrays for screen coordinates and pen indices
 *      are updated.
 *
 *----------------------------------------------------------------------
 */
static void
GenerateSteps(
    MapInfo * mapPtr)
{
int newSize;
register int i, count;
RbcPoint2D *screenPts;
int *indices;
    newSize = ((mapPtr->nScreenPts - 1) * 2) + 1;
    screenPts = (RbcPoint2D *) ckalloc(newSize * sizeof(RbcPoint2D));
    assert(screenPts);
    indices = (int *)ckalloc(sizeof(int) * newSize);
    assert(indices);
    screenPts[0] = mapPtr->screenPts[0];
    indices[0] = 0;
    count = 1;
    for(i = 1; i < mapPtr->nScreenPts; i++) {
        screenPts[count + 1] = mapPtr->screenPts[i];
        /* Hold last y-coordinate, use new x-coordinate */
        screenPts[count].x = screenPts[count + 1].x;
        screenPts[count].y = screenPts[count - 1].y;
        /* Use the same style for both the hold and the step points */
        indices[count] = indices[count + 1] = mapPtr->indices[i];
        count += 2;
    }
    ckfree((char *)mapPtr->screenPts);
    ckfree((char *)mapPtr->indices);
    mapPtr->indices = indices;
    mapPtr->screenPts = screenPts;
    mapPtr->nScreenPts = newSize;
}

/*
 *----------------------------------------------------------------------
 *
 * GenerateSpline --
 *
 *      Computes a spline based upon the data points, returning a new
 *      (larger) coordinate array or points.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The temporary arrays for screen coordinates and data indices
 *      are updated based upon spline.
 *
 * FIXME:  Can't interpolate knots along the Y-axis.   Need to break
 *	   up point array into interchangable X and Y vectors earlier.
 *	   Pass extents (left/right or top/bottom) as parameters.
 *
 *----------------------------------------------------------------------
 */
static void
GenerateSpline(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
int extra;
register int i, j, count;
RbcPoint2D *origPts, *intpPts;
int *indices;
int nIntpPts, nOrigPts;
int result;
int x;
    nOrigPts = mapPtr->nScreenPts;
    origPts = mapPtr->screenPts;
    assert(mapPtr->nScreenPts > 0);
    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        if(origPts[j].x <= origPts[i].x) {
            return;     /* Points are not monotonically increasing */
        }
    }
    if(((origPts[0].x > (double)graph->right)) ||
        ((origPts[mapPtr->nScreenPts - 1].x < (double)graph->left))) {
        return; /* All points are clipped */
    }
    /*
     * The spline is computed in screen coordinates instead of data
     * points so that we can select the abscissas of the interpolated
     * points from each pixel horizontally across the plotting area.
     */
    extra = (graph->right - graph->left) + 1;
    if(extra < 1) {
        return;
    }
    nIntpPts = nOrigPts + extra + 1;
    intpPts = (RbcPoint2D *) ckalloc(nIntpPts * sizeof(RbcPoint2D));
    assert(intpPts);
    indices = (int *)ckalloc(sizeof(int) * nIntpPts);
    assert(indices);
    /* Populate the x2 array with both the original X-coordinates and
     * extra X-coordinates for each horizontal pixel that the line
     * segment contains. */
    count = 0;
    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        /* Add the original x-coordinate */
        intpPts[count].x = origPts[i].x;
        /* Include the starting offset of the point in the offset array */
        indices[count] = mapPtr->indices[i];
        count++;
        /* Is any part of the interval (line segment) in the plotting
         * area?  */
        if((origPts[j].x >= (double)graph->left) ||
            (origPts[i].x <= (double)graph->right)) {
int last;
            x = (int)(origPts[i].x + 1.0);
            /*
             * Since the line segment may be partially clipped on the
             * left or right side, the points to interpolate are
             * always interior to the plotting area.
             *
             *           left                       right
             *      x1----|--------------------------|---x2
             *
             * Pick the max of the starting X-coordinate and the
             * left edge and the min of the last X-coordinate and
             * the right edge.
             */
            x = MAX(x, graph->left);
            last = (int)MIN(origPts[j].x, graph->right);
            /* Add the extra x-coordinates to the interval. */
            while(x < last) {
                indices[count] = mapPtr->indices[i];
                intpPts[count++].x = (double)x;
                x++;
            }
        }
    }
    nIntpPts = count;
    result = FALSE;
    if(linePtr->smooth == PEN_SMOOTH_NATURAL) {
        result = RbcNaturalSpline(origPts, nOrigPts, intpPts, nIntpPts);
    } else if(linePtr->smooth == PEN_SMOOTH_QUADRATIC) {
        result = RbcQuadraticSpline(origPts, nOrigPts, intpPts, nIntpPts);
    }
    if(!result) {
        /* The spline interpolation failed.  We'll fallback to the
         * current coordinates and do no smoothing (standard line
         * segments).  */
        linePtr->smooth = PEN_SMOOTH_NONE;
        ckfree((char *)intpPts);
        ckfree((char *)indices);
    } else {
        ckfree((char *)mapPtr->screenPts);
        ckfree((char *)mapPtr->indices);
        mapPtr->indices = indices;
        mapPtr->screenPts = intpPts;
        mapPtr->nScreenPts = nIntpPts;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GenerateParametricSpline --
 *
 *      Computes a spline based upon the data points, returning a new
 *      (larger) coordinate array or points.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The temporary arrays for screen coordinates and data indices
 *      are updated based upon spline.
 *
 * FIXME:  Can't interpolate knots along the Y-axis.   Need to break
 *	   up point array into interchangable X and Y vectors earlier.
 *	   Pass extents (left/right or top/bottom) as parameters.
 *
 *----------------------------------------------------------------------
 */
static void
GenerateParametricSpline(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
RbcExtents2D exts;
RbcPoint2D *origPts, *intpPts;
RbcPoint2D p, q;
double dist;
int *indices;
int nIntpPts, nOrigPts;
int result;
register int i, j, count;
    nOrigPts = mapPtr->nScreenPts;
    origPts = mapPtr->screenPts;
    assert(mapPtr->nScreenPts > 0);
    RbcGraphExtents(graph, &exts);
    /*
     * Populate the x2 array with both the original X-coordinates and
     * extra X-coordinates for each horizontal pixel that the line
     * segment contains.
     */
    count = 1;
    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        p = origPts[i];
        q = origPts[j];
        count++;
        if(RbcLineRectClip(&exts, &p, &q)) {
            count += (int)(hypot(q.x - p.x, q.y - p.y) * 0.5);
        }
    }
    nIntpPts = count;
    intpPts = (RbcPoint2D *) ckalloc(nIntpPts * sizeof(RbcPoint2D));
    assert(intpPts);
    indices = (int *)ckalloc(sizeof(int) * nIntpPts);
    assert(indices);
    /*
     * FIXME: This is just plain wrong.  The spline should be computed
     *        and evaluated in separate steps.  This will mean breaking
     *        up this routine since the catrom coefficients can be
     *        independently computed for original data point.  This
     *        also handles the problem of allocating enough points
     *        since evaluation is independent of the number of points
     *          to be evalualted.  The interpolated
     *        line segments should be clipped, not the original segments.
     */
    count = 0;
    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        p = origPts[i];
        q = origPts[j];
        dist = hypot(q.x - p.x, q.y - p.y);
        /* Add the original x-coordinate */
        intpPts[count].x = (double)i;
        intpPts[count].y = 0.0;
        /* Include the starting offset of the point in the offset array */
        indices[count] = mapPtr->indices[i];
        count++;
        /* Is any part of the interval (line segment) in the plotting
         * area?  */
        if(RbcLineRectClip(&exts, &p, &q)) {
double distP, distQ;
            distP = hypot(p.x - origPts[i].x, p.y - origPts[i].y);
            distQ = hypot(q.x - origPts[i].x, q.y - origPts[i].y);
            distP += 2.0;
            while(distP <= distQ) {
                /* Point is indicated by its interval and parameter t. */
                intpPts[count].x = (double)i;
                intpPts[count].y = distP / dist;
                indices[count] = mapPtr->indices[i];
                count++;
                distP += 2.0;
            }
        }
    }
    intpPts[count].x = (double)i;
    intpPts[count].y = 0.0;
    indices[count] = mapPtr->indices[i];
    count++;
    nIntpPts = count;
    result = FALSE;
    if(linePtr->smooth == PEN_SMOOTH_NATURAL) {
        result = RbcNaturalParametricSpline(origPts, nOrigPts, &exts, FALSE,
            intpPts, nIntpPts);
    } else if(linePtr->smooth == PEN_SMOOTH_CATROM) {
        result = RbcCatromParametricSpline(origPts, nOrigPts, intpPts,
            nIntpPts);
    }
    if(!result) {
        /* The spline interpolation failed.  We'll fallback to the
         * current coordinates and do no smoothing (standard line
         * segments).  */
        linePtr->smooth = PEN_SMOOTH_NONE;
        ckfree((char *)intpPts);
        ckfree((char *)indices);
    } else {
        ckfree((char *)mapPtr->screenPts);
        ckfree((char *)mapPtr->indices);
        mapPtr->indices = indices;
        mapPtr->screenPts = intpPts;
        mapPtr->nScreenPts = nIntpPts;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MapSymbols --
 *
 *      Creates two arrays of points and pen indices, filled with
 *      the screen coordinates of the visible
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the index array.
 *
 *----------------------------------------------------------------------
 */
static void
MapSymbols(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
RbcExtents2D exts;
RbcPoint2D *symbolPts;
int *indices;
register int i, count;
    symbolPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * mapPtr->nScreenPts);
    assert(symbolPts);
    indices = (int *)ckalloc(sizeof(int) * mapPtr->nScreenPts);
    assert(indices);
    RbcGraphExtents(graph, &exts);
    count = 0; /* Count the number of visible points */
    for(i = 0; i < mapPtr->nScreenPts; i++) {
        if(RbcPointInRegion(&exts, mapPtr->screenPts[i].x,
                mapPtr->screenPts[i].y)) {
            symbolPts[count].x = mapPtr->screenPts[i].x;
            symbolPts[count].y = mapPtr->screenPts[i].y;
            indices[count] = mapPtr->indices[i];
            count++;
        }
    }
    linePtr->symbolPts = symbolPts;
    linePtr->nSymbolPts = count;
    linePtr->symbolToData = indices;
}

/*
 *----------------------------------------------------------------------
 *
 * MapActiveSymbols --
 *
 *      Creates an array of points of the active graph coordinates.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is freed and allocated for the active point array.
 *
 *----------------------------------------------------------------------
 */
static void
MapActiveSymbols(
    RbcGraph * graph,
    Line * linePtr)
{
RbcExtents2D exts;
double x, y;
int count;
RbcPoint2D *activePts;
register int i;
int pointIndex;
int nPoints;
int *activeToData;
    if(linePtr->activePts != NULL) {
        ckfree((char *)linePtr->activePts);
        linePtr->activePts = NULL;
    }
    if(linePtr->activeToData != NULL) {
        ckfree((char *)linePtr->activeToData);
        linePtr->activeToData = NULL;
    }
    RbcGraphExtents(graph, &exts);
    activePts =
        (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * linePtr->nActiveIndices);
    assert(activePts);
    activeToData = (int *)ckalloc(sizeof(int) * linePtr->nActiveIndices);
    nPoints = RbcNumberOfPoints(linePtr);
    count = 0; /* Count the visible active points */
    for(i = 0; i < linePtr->nActiveIndices; i++) {
        pointIndex = linePtr->activeIndices[i];
        if(pointIndex >= nPoints) {
            continue;   /* Index not available */
        }
        x = linePtr->x.valueArr[pointIndex];
        y = linePtr->y.valueArr[pointIndex];
        activePts[count] = RbcMap2D(graph, x, y, &(linePtr->axes));
        activeToData[count] = pointIndex;
        if(RbcPointInRegion(&exts, activePts[count].x, activePts[count].y)) {
            count++;
        }
    }
    if(count > 0) {
        linePtr->activePts = activePts;
        linePtr->activeToData = activeToData;
    } else {
        /* No active points were visible. */
        ckfree((char *)activePts);
        ckfree((char *)activeToData);
    }
    linePtr->nActivePts = count;
    linePtr->flags &= ~RBC_ACTIVE_PENDING;
}

/*
 *----------------------------------------------------------------------
 *
 * MapStrip --
 *
 *      Creates an array of line segments of the graph coordinates.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is  allocated for the line segment array.
 *
 *----------------------------------------------------------------------
 */
static void
MapStrip(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
RbcExtents2D exts;
RbcSegment2D *strips;
int *indices, *indexPtr;
register RbcPoint2D *endPtr, *pointPtr;
register RbcSegment2D *segPtr;
register int count;
    indices = (int *)ckalloc(sizeof(int) * mapPtr->nScreenPts);
    assert(indices);
    /*
     * Create array to hold points for line segments (not polyline
     * coordinates).  So allocate twice the number of points.
     */
    segPtr = strips =
        (RbcSegment2D *) ckalloc(mapPtr->nScreenPts * sizeof(RbcSegment2D));
    assert(strips);
    RbcGraphExtents(graph, &exts);
    count = 0; /* Count the number of segments. */
    indexPtr = mapPtr->indices;
    for(pointPtr = mapPtr->screenPts,
        endPtr = mapPtr->screenPts + (mapPtr->nScreenPts - 1);
        pointPtr < endPtr; pointPtr++, indexPtr++) {
        segPtr->p = pointPtr[0];
        segPtr->q = pointPtr[1];
        if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
            segPtr++;
            indices[count] = *indexPtr;
            count++;
        }
    }
    linePtr->stripToData = indices;
    linePtr->nStrips = count;
    linePtr->strips = strips;
}

/*
 *----------------------------------------------------------------------
 *
 * MergePens --
 *
 *      Reorders the both arrays of points and segments to merge pens.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The old arrays are freed and new ones allocated containing
 *      the reordered points and segments.
 *
 *----------------------------------------------------------------------
 */
static void
MergePens(
    Line * linePtr,
    RbcPenStyle ** dataToStyle)
{
LinePenStyle *stylePtr;
register int i;
RbcChainLink *linkPtr;
    if(RbcChainGetLength(linePtr->palette) < 2) {
        linkPtr = RbcChainFirstLink(linePtr->palette);
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->nStrips = linePtr->nStrips;
        stylePtr->strips = linePtr->strips;
        stylePtr->nSymbolPts = linePtr->nSymbolPts;
        stylePtr->symbolPts = linePtr->symbolPts;
        stylePtr->xErrorBarCnt = linePtr->xErrorBarCnt;
        stylePtr->yErrorBarCnt = linePtr->yErrorBarCnt;
        stylePtr->xErrorBars = linePtr->xErrorBars;
        stylePtr->yErrorBars = linePtr->yErrorBars;
        stylePtr->errorBarCapWidth = linePtr->errorBarCapWidth;
        return;
    }
    /* We have more than one style. Group line segments and points of
     * like pen styles.  */
    if(linePtr->nStrips > 0) {
RbcSegment2D *strips;
int *stripToData;
register RbcSegment2D *segPtr;
register int *indexPtr;
int dataIndex;
        strips =
            (RbcSegment2D *) ckalloc(linePtr->nStrips * sizeof(RbcSegment2D));
        stripToData = (int *)ckalloc(linePtr->nStrips * sizeof(int));
        assert(strips && stripToData);
        segPtr = strips, indexPtr = stripToData;
        for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->strips = segPtr;
            for(i = 0; i < linePtr->nStrips; i++) {
                dataIndex = linePtr->stripToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = linePtr->strips[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->nStrips = segPtr - stylePtr->strips;
        }
        ckfree((char *)linePtr->strips);
        linePtr->strips = strips;
        ckfree((char *)linePtr->stripToData);
        linePtr->stripToData = stripToData;
    }
    if(linePtr->nSymbolPts > 0) {
int *indexPtr;
register RbcPoint2D *symbolPts, *pointPtr;
register int *symbolToData;
int dataIndex;
        symbolPts =
            (RbcPoint2D *) ckalloc(linePtr->nSymbolPts * sizeof(RbcPoint2D));
        symbolToData = (int *)ckalloc(linePtr->nSymbolPts * sizeof(int));
        assert(symbolPts && symbolToData);
        pointPtr = symbolPts, indexPtr = symbolToData;
        for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->symbolPts = pointPtr;
            for(i = 0; i < linePtr->nSymbolPts; i++) {
                dataIndex = linePtr->symbolToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *pointPtr++ = linePtr->symbolPts[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->nSymbolPts = pointPtr - stylePtr->symbolPts;
        }
        ckfree((char *)linePtr->symbolPts);
        linePtr->symbolPts = symbolPts;
        ckfree((char *)linePtr->symbolToData);
        linePtr->symbolToData = symbolToData;
    }
    if(linePtr->xErrorBarCnt > 0) {
RbcSegment2D *xErrorBars, *segPtr;
int *xErrorToData, *indexPtr;
int dataIndex;
        xErrorBars =
            (RbcSegment2D *) ckalloc(linePtr->xErrorBarCnt *
            sizeof(RbcSegment2D));
        xErrorToData = (int *)ckalloc(linePtr->xErrorBarCnt * sizeof(int));
        assert(xErrorBars);
        segPtr = xErrorBars, indexPtr = xErrorToData;
        for(linkPtr = RbcChainFirstLink(linePtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->xErrorBars = segPtr;
            for(i = 0; i < linePtr->xErrorBarCnt; i++) {
                dataIndex = linePtr->xErrorToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = linePtr->xErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->xErrorBarCnt = segPtr - stylePtr->xErrorBars;
        }
        ckfree((char *)linePtr->xErrorBars);
        linePtr->xErrorBars = xErrorBars;
        ckfree((char *)linePtr->xErrorToData);
        linePtr->xErrorToData = xErrorToData;
    }
    if(linePtr->yErrorBarCnt > 0) {
RbcSegment2D *errorBars, *segPtr;
int *errorToData, *indexPtr;
int dataIndex;
        errorBars =
            (RbcSegment2D *) ckalloc(linePtr->yErrorBarCnt *
            sizeof(RbcSegment2D));
        errorToData = (int *)ckalloc(linePtr->yErrorBarCnt * sizeof(int));
        assert(errorBars);
        segPtr = errorBars, indexPtr = errorToData;
        for(linkPtr = RbcChainFirstLink(linePtr->palette);
            linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            stylePtr->yErrorBars = segPtr;
            for(i = 0; i < linePtr->yErrorBarCnt; i++) {
                dataIndex = linePtr->yErrorToData[i];
                if(dataToStyle[dataIndex] == (RbcPenStyle *) stylePtr) {
                    *segPtr++ = linePtr->yErrorBars[i];
                    *indexPtr++ = dataIndex;
                }
            }
            stylePtr->yErrorBarCnt = segPtr - stylePtr->yErrorBars;
        }
        ckfree((char *)linePtr->yErrorBars);
        linePtr->yErrorBars = errorBars;
        ckfree((char *)linePtr->yErrorToData);
        linePtr->yErrorToData = errorToData;
    }
}

#define CLIP_TOP	(1<<0)
#define CLIP_BOTTOM	(1<<1)
#define CLIP_RIGHT	(1<<2)
#define CLIP_LEFT	(1<<3)
/*
 *----------------------------------------------------------------------
 *
 * OutCode --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
OutCode(
    RbcExtents2D * extsPtr,
    RbcPoint2D * p)
{
int code;
    code = 0;
    if(p->x > extsPtr->right) {
        code |= CLIP_RIGHT;
    } else if(p->x < extsPtr->left) {
        code |= CLIP_LEFT;
    }
    if(p->y > extsPtr->bottom) {
        code |= CLIP_BOTTOM;
    } else if(p->y < extsPtr->top) {
        code |= CLIP_TOP;
    }
    return code;
}

/*
 *----------------------------------------------------------------------
 *
 * ClipSegment --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClipSegment(
    RbcExtents2D * extsPtr,
    register int code1,
    register int code2,
    register RbcPoint2D * p,
    register RbcPoint2D * q)
{
    int inside, outside;
    inside = ((code1 | code2) == 0);
    outside = ((code1 & code2) != 0);
    /*
     * In the worst case, we'll clip the line segment against each of
     * the four sides of the bounding rectangle.
     */
    while((!outside) && (!inside)) {
        if(code1 == 0) {
    RbcPoint2D *tmp;
    int code;
            /* Swap pointers and out codes */
            tmp = p, p = q, q = tmp;
            code = code1, code1 = code2, code2 = code;
        }
        if(code1 & CLIP_LEFT) {
            p->y += (q->y - p->y) * (extsPtr->left - p->x) / (q->x - p->x);
            p->x = extsPtr->left;
        } else if(code1 & CLIP_RIGHT) {
            p->y += (q->y - p->y) * (extsPtr->right - p->x) / (q->x - p->x);
            p->x = extsPtr->right;
        } else if(code1 & CLIP_BOTTOM) {
            p->x += (q->x - p->x) * (extsPtr->bottom - p->y) / (q->y - p->y);
            p->y = extsPtr->bottom;
        } else if(code1 & CLIP_TOP) {
            p->x += (q->x - p->x) * (extsPtr->top - p->y) / (q->y - p->y);
            p->y = extsPtr->top;
        }
        code1 = OutCode(extsPtr, p);
        inside = ((code1 | code2) == 0);
        outside = ((code1 & code2) != 0);
    }
    return (!inside);
}

/*
 *----------------------------------------------------------------------
 *
 * SaveTrace --
 *
 *      Creates a new trace and inserts it into the line's
 *      list of traces.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SaveTrace(
    Line * linePtr,
    int start,                 /* Starting index of the trace in data point
                                * array.  Used to figure out closest point */
    int length,                /* Number of points forming the trace */
    MapInfo * mapPtr)
{
    LineTrace *tracePtr;
    RbcPoint2D *screenPts;
    int *indices;
    register int i, j;
    tracePtr = (LineTrace *) ckalloc(sizeof(LineTrace));
    assert(tracePtr);
    screenPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * length);
    assert(screenPts);
    indices = (int *)ckalloc(sizeof(int) * length);
    assert(indices);
    /* Copy the screen coordinates of the trace into the point array */
    if(mapPtr->indices != NULL) {
        for(i = 0, j = start; i < length; i++, j++) {
            screenPts[i].x = mapPtr->screenPts[j].x;
            screenPts[i].y = mapPtr->screenPts[j].y;
            indices[i] = mapPtr->indices[j];
        }
    } else {
        for(i = 0, j = start; i < length; i++, j++) {
            screenPts[i].x = mapPtr->screenPts[j].x;
            screenPts[i].y = mapPtr->screenPts[j].y;
            indices[i] = j;
        }
    }
    tracePtr->nScreenPts = length;
    tracePtr->screenPts = screenPts;
    tracePtr->symbolToData = indices;
    tracePtr->start = start;
    if(linePtr->traces == NULL) {
        linePtr->traces = RbcChainCreate();
    }
    RbcChainAppend(linePtr->traces, tracePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * FreeTraces --
 *
 *      Deletes all the traces for the line.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
FreeTraces(
    Line * linePtr)
{
RbcChainLink *linkPtr;
LineTrace *tracePtr;
    for(linkPtr = RbcChainFirstLink(linePtr->traces); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        tracePtr = RbcChainGetValue(linkPtr);
        ckfree((char *)tracePtr->symbolToData);
        ckfree((char *)tracePtr->screenPts);
        ckfree((char *)tracePtr);
    }
    RbcChainDestroy(linePtr->traces);
    linePtr->traces = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * MapTraces --
 *
 *      Creates an array of line segments of the graph coordinates.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is  allocated for the line segment array.
 *
 *----------------------------------------------------------------------
 */
static void
MapTraces(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
int start, count;
int code1, code2;
RbcPoint2D *p, *q;
RbcPoint2D s;
RbcExtents2D exts;
register int i;
int broken, offscreen;
    RbcGraphExtents(graph, &exts);
    count = 1;
    code1 = OutCode(&exts, mapPtr->screenPts);
    p = mapPtr->screenPts;
    q = p + 1;
    for(i = 1; i < mapPtr->nScreenPts; i++, p++, q++) {
        code2 = OutCode(&exts, q);
        if(code2 != 0) {
            /* Save the coordinates of the last point, before clipping */
            s = *q;
        }
        broken = BROKEN_TRACE(linePtr->penDir, p->x, q->x);
        offscreen = ClipSegment(&exts, code1, code2, p, q);
        if(broken || offscreen) {
            /*
             * The last line segment is either totally clipped by the plotting
             * area or the x-direction is wrong, breaking the trace.  Either
             * way, save information about the last trace (if one exists),
             * discarding the current line segment
             */
            if(count > 1) {
                start = i - count;
                SaveTrace(linePtr, start, count, mapPtr);
                count = 1;
            }
        } else {
            count++;    /* Add the point to the trace. */
            if(code2 != 0) {
                /*
                 * If the last point is clipped, this means that the trace is
                 * broken after this point.  Restore the original coordinate
                 * (before clipping) after saving the trace.
                 */
                start = i - (count - 1);
                SaveTrace(linePtr, start, count, mapPtr);
                mapPtr->screenPts[i] = s;
                count = 1;
            }
        }
        code1 = code2;
    }
    if(count > 1) {
        start = i - count;
        SaveTrace(linePtr, start, count, mapPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * MapFillArea --
 *
 *      Creates an array of points that represent a polygon that fills
 *      the area under the element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is  allocated for the polygon point array.
 *
 *----------------------------------------------------------------------
 */
static void
MapFillArea(
    RbcGraph * graph,
    Line * linePtr,
    MapInfo * mapPtr)
{
RbcPoint2D *origPts, *clipPts;
RbcExtents2D exts;
double maxY;
register int i, n;
    if(linePtr->fillPts != NULL) {
        ckfree((char *)linePtr->fillPts);
        linePtr->fillPts = NULL;
        linePtr->nFillPts = 0;
    }
    if(mapPtr->nScreenPts < 3) {
        return;
    }
    n = mapPtr->nScreenPts + 3;
    RbcGraphExtents(graph, &exts);
    maxY = (double)graph->bottom;
    origPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * n);
    for(i = 0; i < mapPtr->nScreenPts; i++) {
        origPts[i].x = mapPtr->screenPts[i].x + 1;
        origPts[i].y = mapPtr->screenPts[i].y;
        if(origPts[i].y > maxY) {
            maxY = origPts[i].y;
        }
    }
    /* Add edges to make (if necessary) the polygon fill to the bottom
     * of plotting window */
    origPts[i].x = origPts[i - 1].x;
    origPts[i].y = maxY;
    i++;
    origPts[i].x = origPts[0].x;
    origPts[i].y = maxY;
    i++;
    origPts[i] = origPts[0];
    clipPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * n * 3);
    assert(clipPts);
    n = RbcPolyRectClip(&exts, origPts, n - 1, clipPts);
    ckfree((char *)origPts);
    if(n < 3) {
        ckfree((char *)clipPts);
    } else {
        linePtr->fillPts = clipPts;
        linePtr->nFillPts = n;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ResetLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ResetLine(
    Line * linePtr)
{
    FreeTraces(linePtr);
    ClearPalette(linePtr->palette);
    if(linePtr->symbolPts != NULL) {
        ckfree((char *)linePtr->symbolPts);
    }
    if(linePtr->symbolToData != NULL) {
        ckfree((char *)linePtr->symbolToData);
    }
    if(linePtr->strips != NULL) {
        ckfree((char *)linePtr->strips);
    }
    if(linePtr->stripToData != NULL) {
        ckfree((char *)linePtr->stripToData);
    }
    if(linePtr->activePts != NULL) {
        ckfree((char *)linePtr->activePts);
    }
    if(linePtr->activeToData != NULL) {
        ckfree((char *)linePtr->activeToData);
    }
    if(linePtr->xErrorBars != NULL) {
        ckfree((char *)linePtr->xErrorBars);
    }
    if(linePtr->xErrorToData != NULL) {
        ckfree((char *)linePtr->xErrorToData);
    }
    if(linePtr->yErrorBars != NULL) {
        ckfree((char *)linePtr->yErrorBars);
    }
    if(linePtr->yErrorToData != NULL) {
        ckfree((char *)linePtr->yErrorToData);
    }
    linePtr->xErrorBars = linePtr->yErrorBars = linePtr->strips = NULL;
    linePtr->symbolPts = linePtr->activePts = NULL;
    linePtr->stripToData = linePtr->symbolToData = linePtr->xErrorToData =
        linePtr->yErrorToData = linePtr->activeToData = NULL;
    linePtr->nActivePts = linePtr->nSymbolPts = linePtr->nStrips =
        linePtr->xErrorBarCnt = linePtr->yErrorBarCnt = 0;
}

/*
 *----------------------------------------------------------------------
 *
 * MapLine --
 *
 *      Calculates the actual window coordinates of the line element.
 *      The window coordinates are saved in an allocated point array.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Memory is (re)allocated for the point array.
 *
 *----------------------------------------------------------------------
 */
static void
MapLine(
    RbcGraph * graph,          /* Graph widget record */
    RbcElement * elemPtr)
{              /* Element component record */
Line *linePtr = (Line *) elemPtr;
MapInfo mapInfo;
int size, nPoints;
RbcPenStyle **dataToStyle;
RbcChainLink *linkPtr;
LinePenStyle *stylePtr;
    ResetLine(linePtr);
    nPoints = RbcNumberOfPoints(linePtr);
    if(nPoints < 1) {
        return; /* No data points */
    }
    GetScreenPoints(graph, linePtr, &mapInfo);
    MapSymbols(graph, linePtr, &mapInfo);
    if((linePtr->flags & RBC_ACTIVE_PENDING) && (linePtr->nActiveIndices > 0)) {
        MapActiveSymbols(graph, linePtr);
    }
    /*
     * Map connecting line segments if they are to be displayed.
     */
    if((nPoints > 1) && ((graph->classUid == rbcStripElementUid) ||
            (linePtr->builtinPen.traceWidth > 0))) {
        linePtr->smooth = linePtr->reqSmooth;
        /*
         * Do smoothing if necessary.  This can extend the coordinate array,
         * so both mapInfo.points and mapInfo.nPoints may change.
         */
        switch (linePtr->smooth) {
        case PEN_SMOOTH_STEP:
            GenerateSteps(&mapInfo);
            break;
        case PEN_SMOOTH_NATURAL:
        case PEN_SMOOTH_QUADRATIC:
            if(mapInfo.nScreenPts < 3) {
                /* Can't interpolate with less than three points. */
                linePtr->smooth = PEN_SMOOTH_NONE;
            } else {
                GenerateSpline(graph, linePtr, &mapInfo);
            }
            break;
        case PEN_SMOOTH_CATROM:
            if(mapInfo.nScreenPts < 3) {
                /* Can't interpolate with less than three points. */
                linePtr->smooth = PEN_SMOOTH_NONE;
            } else {
                GenerateParametricSpline(graph, linePtr, &mapInfo);
            }
            break;
        default:
            break;
        }
        if(linePtr->rTolerance > 0.0) {
            ReducePoints(&mapInfo, linePtr->rTolerance);
        }
        if((linePtr->fillTile != NULL) || (linePtr->fillStipple != None)) {
            MapFillArea(graph, linePtr, &mapInfo);
        }
        if(graph->classUid == rbcStripElementUid) {
            MapStrip(graph, linePtr, &mapInfo);
        } else {
            MapTraces(graph, linePtr, &mapInfo);
        }
    }
    ckfree((char *)mapInfo.screenPts);
    ckfree((char *)mapInfo.indices);
    /* Set the symbol size of all the pen styles. */
    for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        size = ScaleSymbol(elemPtr, stylePtr->penPtr->symbol.size);
        stylePtr->symbolSize = size;
        stylePtr->errorBarCapWidth = (stylePtr->penPtr->errorBarCapWidth > 0)
            ? stylePtr->penPtr->errorBarCapWidth : (int)(size * 0.6666666);
        stylePtr->errorBarCapWidth /= 2;
    }
    dataToStyle = RbcStyleMap((RbcElement *) linePtr);
    if(((linePtr->yHigh.nValues > 0) && (linePtr->yLow.nValues > 0)) ||
        ((linePtr->xHigh.nValues > 0) && (linePtr->xLow.nValues > 0)) ||
        (linePtr->xError.nValues > 0) || (linePtr->yError.nValues > 0)) {
        RbcMapErrorBars(graph, (RbcElement *) linePtr, dataToStyle);
    }
    MergePens(linePtr, dataToStyle);
    ckfree((char *)dataToStyle);
}

/*
 *----------------------------------------------------------------------
 *
 * DistanceToLine --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static double
DistanceToLine(
    int x,                     /* Sample X coordinate. */
    int y,                     /* Sample Y coordinate. */
    RbcPoint2D * p,            /* End points of the line segment. */
    RbcPoint2D * q,            /* End points of the line segment. */
    RbcPoint2D * t)
{              /* (out) Point on line segment. */
    double right, left, top, bottom;
    *t = RbcGetProjection(x, y, p, q);
    if(p->x > q->x) {
        right = p->x, left = q->x;
    } else {
        left = p->x, right = q->x;
    }
    if(p->y > q->y) {
        bottom = p->y, top = q->y;
    } else {
        top = p->y, bottom = q->y;
    }
    if(t->x > right) {
        t->x = right;
    } else if(t->x < left) {
        t->x = left;
    }
    if(t->y > bottom) {
        t->y = bottom;
    } else if(t->y < top) {
        t->y = top;
    }
    return hypot((t->x - x), (t->y - y));
}

/*
 *----------------------------------------------------------------------
 *
 * DistanceToX --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static double
DistanceToX(
    int x,                     /* Search X coordinate. */
    int y,                     /* Search Y coordinate. */
    RbcPoint2D * p,            /* End points of the line segment. */
    RbcPoint2D * q,            /* End points of the line segment. */
    RbcPoint2D * t)
{              /* (out) Point on line segment. */
    double dx, dy;
    double dist;
    if(p->x > q->x) {
        if((x > p->x) || (x < q->x)) {
            return DBL_MAX;     /* X-coordinate outside line segment. */
        }
    } else {
        if((x > q->x) || (x < p->x)) {
            return DBL_MAX;     /* X-coordinate outside line segment. */
        }
    }
    dx = p->x - q->x;
    dy = p->y - q->y;
    t->x = (double)x;
    if(FABS(dx) < DBL_EPSILON) {
    double d1, d2;
        /* Same X-coordinate indicates a vertical line.  Pick the
         * closest end point. */
        d1 = p->y - y;
        d2 = q->y - y;
        if(FABS(d1) < FABS(d2)) {
            t->y = p->y, dist = d1;
        } else {
            t->y = q->y, dist = d2;
        }
    } else if(FABS(dy) < DBL_EPSILON) {
        /* Horizontal line. */
        t->y = p->y, dist = p->y - y;
    } else {
    double m, b;
        m = dy / dx;
        b = p->y - (m * p->x);
        t->y = (x * m) + b;
        dist = y - t->y;
    }
    return FABS(dist);
}

/*
 *----------------------------------------------------------------------
 *
 * DistanceToY --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static double
DistanceToY(
    int x,                     /* Search X-Y coordinate. */
    int y,                     /* Search X-Y coordinate. */
    RbcPoint2D * p,            /* End points of the line segment. */
    RbcPoint2D * q,            /* End points of the line segment. */
    RbcPoint2D * t)
{              /* (out) Point on line segment. */
    double dx, dy;
    double dist;
    if(p->y > q->y) {
        if((y > p->y) || (y < q->y)) {
            return DBL_MAX;
        }
    } else {
        if((y > q->y) || (y < p->y)) {
            return DBL_MAX;
        }
    }
    dx = p->x - q->x;
    dy = p->y - q->y;
    t->y = y;
    if(FABS(dy) < DBL_EPSILON) {
    double d1, d2;
        /* Save Y-coordinate indicates an horizontal line. Pick the
         * closest end point. */
        d1 = p->x - x;
        d2 = q->x - x;
        if(FABS(d1) < FABS(d2)) {
            t->x = p->x, dist = d1;
        } else {
            t->x = q->x, dist = d2;
        }
    } else if(FABS(dx) < DBL_EPSILON) {
        /* Vertical line. */
        t->x = p->x, dist = p->x - x;
    } else {
    double m, b;
        m = dy / dx;
        b = p->y - (m * p->x);
        t->x = (y - b) / m;
        dist = x - t->x;
    }
    return FABS(dist);
}

/*
 *----------------------------------------------------------------------
 *
 * ClosestTrace --
 *
 *      Find the line segment closest to the given window coordinate
 *      in the element.
 *
 * Results:
 *      If a new minimum distance is found, the information regarding
 *      it is returned via searchPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClosestTrace(
    RbcGraph * graph,          /* Graph widget record */
    Line * linePtr,            /* Line element record */
    RbcClosestSearch * searchPtr,       /* Info about closest point in element */
    DistanceProc * distProc)
{
RbcChainLink *linkPtr;
RbcPoint2D closest = { 0., 0. };        /* make compiler happy */
RbcPoint2D b;
LineTrace *tracePtr;
double dist, minDist;
register RbcPoint2D *pointPtr, *endPtr;
int i;
    i = -1;    /* Suppress compiler warning. */
    minDist = searchPtr->dist;
    for(linkPtr = RbcChainFirstLink(linePtr->traces); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        tracePtr = RbcChainGetValue(linkPtr);
        for(pointPtr = tracePtr->screenPts,
            endPtr = tracePtr->screenPts + (tracePtr->nScreenPts - 1);
            pointPtr < endPtr; pointPtr++) {
            dist = (*distProc) (searchPtr->x, searchPtr->y, pointPtr,
                pointPtr + 1, &b);
            if(dist < minDist) {
                closest = b;
                i = tracePtr->symbolToData[pointPtr - tracePtr->screenPts];
                minDist = dist;
            }
        }
    }
    if(minDist < searchPtr->dist) {
        searchPtr->dist = minDist;
        searchPtr->elemPtr = (RbcElement *) linePtr;
        searchPtr->index = i;
        searchPtr->point =
            RbcInvMap2D(graph, closest.x, closest.y, &(linePtr->axes));
        return TRUE;
    }
    return FALSE;
}

/*
 *----------------------------------------------------------------------
 *
 * ClosestStrip --
 *
 *      Find the line segment closest to the given window coordinate
 *      in the element.
 *
 * Results:
 *      If a new minimum distance is found, the information regarding
 *      it is returned via searchPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClosestStrip(
    RbcGraph * graph,          /* Graph widget record */
    Line * linePtr,            /* Line element record */
    RbcClosestSearch * searchPtr,       /* Info about closest point in element */
    DistanceProc * distProc)
{
RbcPoint2D closest = { 0., 0. };        /* make compiler happy */
RbcPoint2D b;
double dist, minDist;
int count;
int i;
register RbcSegment2D *s;
    i = 0;
    minDist = searchPtr->dist;
    s = linePtr->strips;
    for(count = 0; count < linePtr->nStrips; count++, s++) {
        dist = (*distProc) (searchPtr->x, searchPtr->y, &(s->p), &(s->q), &b);
        if(dist < minDist) {
            closest = b;
            i = linePtr->stripToData[count];
            minDist = dist;
        }
    }
    if(minDist < searchPtr->dist) {
        searchPtr->dist = minDist;
        searchPtr->elemPtr = (RbcElement *) linePtr;
        searchPtr->index = i;
        searchPtr->point =
            RbcInvMap2D(graph, closest.x, closest.y, &(linePtr->axes));
        return TRUE;
    }
    return FALSE;
}

/*
 *----------------------------------------------------------------------
 *
 * ClosestPoint --
 *
 *      Find the element whose data point is closest to the given screen
 *      coordinate.
 *
 * Results:
 *      If a new minimum distance is found, the information regarding
 *      it is returned via searchPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ClosestPoint(
    Line * linePtr,            /* Line element that we are looking at */
    RbcClosestSearch * searchPtr)
{              /* Assorted information related to searching
                * for the closest point */
double dist, minDist;
double dx, dy;
int count, i;
register RbcPoint2D *pointPtr;
    minDist = searchPtr->dist;
    i = 0;
    /*
     * Instead of testing each data point in graph coordinates, look at
     * the array of mapped screen coordinates. The advantages are
     *   1) only examine points that are visible (unclipped), and
     *   2) the computed distance is already in screen coordinates.
     */
    pointPtr = linePtr->symbolPts;
    for(count = 0; count < linePtr->nSymbolPts; count++, pointPtr++) {
        dx = (double)(searchPtr->x - pointPtr->x);
        dy = (double)(searchPtr->y - pointPtr->y);
        if(searchPtr->along == RBC_SEARCH_BOTH) {
            dist = hypot(dx, dy);
        } else if(searchPtr->along == RBC_SEARCH_X) {
            dist = dx;
        } else if(searchPtr->along == RBC_SEARCH_Y) {
            dist = dy;
        } else {
            /* This can't happen */
            continue;
        }
        if(dist < minDist) {
            i = linePtr->symbolToData[count];
            minDist = dist;
        }
    }
    if(minDist < searchPtr->dist) {
        searchPtr->elemPtr = (RbcElement *) linePtr;
        searchPtr->dist = minDist;
        searchPtr->index = i;
        searchPtr->point.x = linePtr->x.valueArr[i];
        searchPtr->point.y = linePtr->y.valueArr[i];
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetLineExtents --
 *
 *      Retrieves the range of the line element
 *
 * Results:
 *      Returns the number of data points in the element.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
GetLineExtents(
    RbcElement * elemPtr,
    RbcExtents2D * extsPtr)
{
int nPoints;
    extsPtr->top = extsPtr->left = DBL_MAX;
    extsPtr->bottom = extsPtr->right = -DBL_MAX;
    nPoints = RbcNumberOfPoints(elemPtr);
    if(nPoints < 1) {
        return;
    }
    extsPtr->right = elemPtr->x.max;
    if((elemPtr->x.min <= 0.0) && (elemPtr->axes.x->logScale)) {
        extsPtr->left = RbcFindElemVectorMinimum(&elemPtr->x, DBL_MIN);
    } else {
        extsPtr->left = elemPtr->x.min;
    }
    extsPtr->bottom = elemPtr->y.max;
    if((elemPtr->y.min <= 0.0) && (elemPtr->axes.y->logScale)) {
        extsPtr->top = RbcFindElemVectorMinimum(&elemPtr->y, DBL_MIN);
    } else {
        extsPtr->top = elemPtr->y.min;
    }
    /* Correct the data limits for error bars */
    if(elemPtr->xError.nValues > 0) {
register int i;
double x;
        nPoints = MIN(elemPtr->xError.nValues, nPoints);
        for(i = 0; i < nPoints; i++) {
            x = elemPtr->x.valueArr[i] + elemPtr->xError.valueArr[i];
            if(x > extsPtr->right) {
                extsPtr->right = x;
            }
            x = elemPtr->x.valueArr[i] - elemPtr->xError.valueArr[i];
            if(elemPtr->axes.x->logScale) {
                if(x < 0.0) {
                    x = -x;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if((x > DBL_MIN) && (x < extsPtr->left)) {
                    extsPtr->left = x;
                }
            } else if(x < extsPtr->left) {
                extsPtr->left = x;
            }
        }
    } else {
        if((elemPtr->xHigh.nValues > 0) &&
            (elemPtr->xHigh.max > extsPtr->right)) {
            extsPtr->right = elemPtr->xHigh.max;
        }
        if(elemPtr->xLow.nValues > 0) {
double left;
            if((elemPtr->xLow.min <= 0.0) && (elemPtr->axes.x->logScale)) {
                left = RbcFindElemVectorMinimum(&elemPtr->xLow, DBL_MIN);
            } else {
                left = elemPtr->xLow.min;
            }
            if(left < extsPtr->left) {
                extsPtr->left = left;
            }
        }
    }
    if(elemPtr->yError.nValues > 0) {
register int i;
double y;
        nPoints = MIN(elemPtr->yError.nValues, nPoints);
        for(i = 0; i < nPoints; i++) {
            y = elemPtr->y.valueArr[i] + elemPtr->yError.valueArr[i];
            if(y > extsPtr->bottom) {
                extsPtr->bottom = y;
            }
            y = elemPtr->y.valueArr[i] - elemPtr->yError.valueArr[i];
            if(elemPtr->axes.y->logScale) {
                if(y < 0.0) {
                    y = -y;     /* Mirror negative values, instead
                                 * of ignoring them. */
                }
                if((y > DBL_MIN) && (y < extsPtr->left)) {
                    extsPtr->top = y;
                }
            } else if(y < extsPtr->top) {
                extsPtr->top = y;
            }
        }
    } else {
        if((elemPtr->yHigh.nValues > 0) &&
            (elemPtr->yHigh.max > extsPtr->bottom)) {
            extsPtr->bottom = elemPtr->yHigh.max;
        }
        if(elemPtr->yLow.nValues > 0) {
double top;
            if((elemPtr->yLow.min <= 0.0) && (elemPtr->axes.y->logScale)) {
                top = RbcFindElemVectorMinimum(&elemPtr->yLow, DBL_MIN);
            } else {
                top = elemPtr->yLow.min;
            }
            if(top < extsPtr->top) {
                extsPtr->top = top;
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TileChangedProc
 *
 *      Rebuilds the designated GC with the new tile pixmap.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
TileChangedProc(
    ClientData clientData,
    RbcTile tile)
{              /* Not used. */
Line *linePtr = clientData;
RbcGraph *graph;
    graph = linePtr->graph;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    graph->flags |= RBC_REDRAW_WORLD;
    RbcEventuallyRedrawGraph(graph);
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureLine --
 *
 *      Sets up the appropriate configuration parameters in the GC.
 *      It is assumed the parameters have been previously set by
 *      a call to Tk_ConfigureWidget.
 *
 * Results:
 *      The return value is a standard Tcl result.  If TCL_ERROR is
 *      returned, then Tcl_GetString(Tcl_GetObjResult(interp)) contains an error message.
 *
 * Side effects:
 *      Configuration information such as line width, line style, color
 *      etc. get set in a new GC.
 *
 *----------------------------------------------------------------------
 */
static int
ConfigureLine(
    RbcGraph * graph,
    RbcElement * elemPtr)
{
Line *linePtr = (Line *) elemPtr;
unsigned long gcMask;
XGCValues gcValues;
GC  newGC;
RbcChainLink *linkPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(ConfigurePen(graph, (RbcPen *) & (linePtr->builtinPen)) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Point to the static normal/active pens if no external pens have
     * been selected.
     */
    if(linePtr->normalPenPtr == NULL) {
        linePtr->normalPenPtr = &(linePtr->builtinPen);
    }
    linkPtr = RbcChainFirstLink(linePtr->palette);
    if(linkPtr != NULL) {
LinePenStyle *stylePtr;
        stylePtr = RbcChainGetValue(linkPtr);
        stylePtr->penPtr = linePtr->normalPenPtr;
    }
    if(linePtr->fillTile != NULL) {
        RbcSetTileChangedProc(linePtr->fillTile, TileChangedProc, linePtr);
    }
    /*
     * Set the outline GC for this pen: GCForeground is outline color.
     * GCBackground is the fill color (only used for bitmap symbols).
     */
    gcMask = 0;
    if(linePtr->fillFgColor != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = linePtr->fillFgColor->pixel;
    }
    if(linePtr->fillBgColor != NULL) {
        gcMask |= GCBackground;
        gcValues.background = linePtr->fillBgColor->pixel;
    }
    if((linePtr->fillStipple != None) &&
        (linePtr->fillStipple != PATTERN_SOLID)) {
        gcMask |= (GCStipple | GCFillStyle);
        gcValues.stipple = linePtr->fillStipple;
        gcValues.fill_style = (linePtr->fillBgColor == NULL)
            ? FillStippled : FillOpaqueStippled;
    }
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(linePtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, linePtr->fillGC);
    }
    linePtr->fillGC = newGC;
    if(RbcConfigModified(linePtr->configSpecs, "-scalesymbols", (char *)NULL)) {
        linePtr->flags |= (RBC_MAP_ITEM | RBC_SCALE_SYMBOL);
    }
    if(RbcConfigModified(linePtr->configSpecs, "-pixels", "-trace", "-*data",
            "-smooth", "-map*", "-label", "-hide", "-x", "-y", "-areapattern",
            (char *)NULL)) {
        linePtr->flags |= RBC_MAP_ITEM;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ClosestLine --
 *
 *      Find the closest point or line segment (if interpolated) to
 *      the given window coordinate in the line element.
 *
 * Results:
 *      Returns the distance of the closest point among other
 *      information.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ClosestLine(
    RbcGraph * graph,          /* Graph widget record */
    RbcElement * elemPtr,      /* Element to examine */
    RbcClosestSearch * searchPtr)
{              /* Info about closest point in element */
Line *linePtr = (Line *) elemPtr;
int mode;
    mode = searchPtr->mode;
    if(mode == RBC_SEARCH_AUTO) {
LinePen *penPtr = linePtr->normalPenPtr;
        mode = RBC_SEARCH_POINTS;
        if((RbcNumberOfPoints(linePtr) > 1) && (penPtr->traceWidth > 0)) {
            mode = RBC_SEARCH_TRACES;
        }
    }
    if(mode == RBC_SEARCH_POINTS) {
        ClosestPoint(linePtr, searchPtr);
    } else {
DistanceProc *distProc;
int found;
        if(searchPtr->along == RBC_SEARCH_X) {
            distProc = DistanceToX;
        } else if(searchPtr->along == RBC_SEARCH_Y) {
            distProc = DistanceToY;
        } else {
            distProc = DistanceToLine;
        }
        if(elemPtr->classUid == rbcStripElementUid) {
            found = ClosestStrip(graph, linePtr, searchPtr, distProc);
        } else {
            found = ClosestTrace(graph, linePtr, searchPtr, distProc);
        }
        if((!found) && (searchPtr->along != RBC_SEARCH_BOTH)) {
            ClosestPoint(linePtr, searchPtr);
        }
    }
}

/*
 * XDrawLines() points: XMaxRequestSize(dpy) - 3
 * XFillPolygon() points:  XMaxRequestSize(dpy) - 4
 * XDrawSegments() segments:  (XMaxRequestSize(dpy) - 3) / 2
 * XDrawRectangles() rectangles:  (XMaxRequestSize(dpy) - 3) / 2
 * XFillRectangles() rectangles:  (XMaxRequestSize(dpy) - 3) / 2
 * XDrawArcs() or XFillArcs() arcs:  (XMaxRequestSize(dpy) - 3) / 3
 */
#define MAX_DRAWLINES(d)	    RbcMaxRequestSize(d, sizeof(XPoint))
#define MAX_DRAWPOLYGON(d)	    RbcMaxRequestSize(d, sizeof(XPoint))
#define MAX_DRAWSEGMENTS(d)	    RbcMaxRequestSize(d, sizeof(XSegment))
#define MAX_DRAWRECTANGLES(d)	RbcMaxRequestSize(d, sizeof(XRectangle))
#define MAX_DRAWARCS(d)		    RbcMaxRequestSize(d, sizeof(XArc))
#ifdef _WIN32
/*
 *----------------------------------------------------------------------
 *
 * DrawCircles --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawCircles(
    Display * display,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int radius)
{
    HBRUSH brush, oldBrush;
    HPEN pen, oldPen;
    HDC dc;
    TkWinDCState state;
    register RbcPoint2D *pointPtr, *endPtr;
    if(drawable == None) {
        return; /* Huh? */
    }
    if((penPtr->symbol.fillGC == NULL) && (penPtr->symbol.outlineWidth == 0)) {
        return;
    }
    dc = TkWinGetDrawableDC(display, drawable, &state);
    /* RbcSetROP2(dc, penPtr->symbol.fillGC->function); */
    if(penPtr->symbol.fillGC != NULL) {
        brush = CreateSolidBrush(penPtr->symbol.fillGC->foreground);
    } else {
        brush = GetStockBrush(NULL_BRUSH);
    }
    if(penPtr->symbol.outlineWidth > 0) {
        pen = RbcGCToPen(dc, penPtr->symbol.outlineGC);
    } else {
        pen = GetStockPen(NULL_PEN);
    }
    oldPen = SelectPen(dc, pen);
    oldBrush = SelectBrush(dc, brush);
    for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
        pointPtr < endPtr; pointPtr++) {
        Ellipse(dc, (int)pointPtr->x - radius, (int)pointPtr->y - radius,
            (int)pointPtr->x + radius + 1, (int)pointPtr->y + radius + 1);
    }
    DeleteBrush(SelectBrush(dc, oldBrush));
    DeletePen(SelectPen(dc, oldPen));
    TkWinReleaseDrawableDC(drawable, dc, &state);
}
#else
/*
 *----------------------------------------------------------------------
 *
 * DrawCircles --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawCircles(
    Display * display,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int radius)
{
    register int i;
    XArc *arcArr;              /* Array of arcs (circle) */
    register XArc *arcPtr;
    int reqSize, nArcs;
    int s;
    int count;
    register RbcPoint2D *pointPtr, *endPtr;
    s = radius + radius;
    arcArr = (XArc *) ckalloc(nSymbolPts * sizeof(XArc));
    arcPtr = arcArr;
    if(linePtr->symbolInterval > 0) {
        count = 0;
        for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
            pointPtr < endPtr; pointPtr++) {
            if(DRAW_SYMBOL(linePtr)) {
                arcPtr->x = (short int)pointPtr->x - radius;
                arcPtr->y = (short int)pointPtr->y - radius;
                arcPtr->width = arcPtr->height = (unsigned short)s;
                arcPtr->angle1 = 0;
                arcPtr->angle2 = 23040;
                arcPtr++, count++;
            }
            linePtr->symbolCounter++;
        }
    } else {
        count = nSymbolPts;
        for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
            pointPtr < endPtr; pointPtr++) {
            arcPtr->x = (short int)pointPtr->x - radius;
            arcPtr->y = (short int)pointPtr->y - radius;
            arcPtr->width = arcPtr->height = (unsigned short)s;
            arcPtr->angle1 = 0;
            arcPtr->angle2 = 23040;
            arcPtr++;
        }
    }
    reqSize = MAX_DRAWARCS(display);
    for(i = 0; i < count; i += reqSize) {
        nArcs = ((i + reqSize) > count) ? (count - i) : reqSize;
        if(penPtr->symbol.fillGC != NULL) {
            XFillArcs(display, drawable, penPtr->symbol.fillGC, arcArr + i,
                nArcs);
        }
        if(penPtr->symbol.outlineWidth > 0) {
            XDrawArcs(display, drawable, penPtr->symbol.outlineGC, arcArr + i,
                nArcs);
        }
    }
    ckfree((char *)arcArr);
}
#endif
/*
 *----------------------------------------------------------------------
 *
 * DrawSquares --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawSquares(
    Display * display,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    register RbcPoint2D * symbolPts,
    int r)
{
    XRectangle *rectArr;
    register RbcPoint2D *pointPtr, *endPtr;
    register XRectangle *rectPtr;
    int reqSize, nRects;
    int s;
    register int i;
    int count;
    s = r + r;
    rectArr = (XRectangle *) ckalloc(nSymbolPts * sizeof(XRectangle));
    rectPtr = rectArr;
    if(linePtr->symbolInterval > 0) {
        count = 0;
        for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
            pointPtr < endPtr; pointPtr++) {
            if(DRAW_SYMBOL(linePtr)) {
                rectPtr->x = (short int)(pointPtr->x - r);
                rectPtr->y = (short int)(pointPtr->y - r);
                rectPtr->width = rectPtr->height = (unsigned short)s;
                rectPtr++, count++;
            }
            linePtr->symbolCounter++;
        }
    } else {
        count = nSymbolPts;
        for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
            pointPtr < endPtr; pointPtr++) {
            rectPtr->x = (short int)(pointPtr->x - r);
            rectPtr->y = (short int)(pointPtr->y - r);
            rectPtr->width = rectPtr->height = (unsigned short)s;
            rectPtr++;
        }
    }
    reqSize = MAX_DRAWRECTANGLES(display);
    for(i = 0; i < count; i += reqSize) {
        nRects = ((i + reqSize) > count) ? (count - i) : reqSize;
        if(penPtr->symbol.fillGC != NULL) {
            XFillRectangles(display, drawable, penPtr->symbol.fillGC,
                rectArr + i, nRects);
        }
        if(penPtr->symbol.outlineWidth > 0) {
            XDrawRectangles(display, drawable, penPtr->symbol.outlineGC,
                rectArr + i, nRects);
        }
    }
    ckfree((char *)rectArr);
}

/*
 * -----------------------------------------------------------------
 *
 * DrawSymbols --
 *
 *      Draw the symbols centered at the each given x,y coordinate
 *      in the array of points.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws a symbol at each coordinate given.  If active,
 *      only those coordinates which are currently active are
 *      drawn.
 *
 * -----------------------------------------------------------------
 */
static void
DrawSymbols(
    RbcGraph * graph,          /* Graph widget record */
    Drawable drawable,         /* Pixmap or window to draw into */
    Line * linePtr,
    LinePen * penPtr,
    int size,                  /* Size of element */
    int nSymbolPts,            /* Number of coordinates in array */
    RbcPoint2D * symbolPts)
{              /* Array of x,y coordinates for line */
    XPoint pattern[13];        /* Template for polygon symbols */
    int r1, r2;
    register int i, n;
    int count;
    register RbcPoint2D *pointPtr, *endPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

#define SQRT_PI		1.77245385090552
#define S_RATIO		0.886226925452758
    if(size < 3) {
        if(penPtr->symbol.fillGC != NULL) {
    XPoint *points;
            points = (XPoint *) ckalloc(nSymbolPts * sizeof(XPoint));
            count = 0;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                points[count].x = (short int)pointPtr->x;
                points[count].y = (short int)pointPtr->y;
                count++;
            }
            XDrawPoints(graph->display, drawable, penPtr->symbol.fillGC, points,
                nSymbolPts, CoordModeOrigin);
            ckfree((char *)points);
        }
        return;
    }
    r1 = (int)ceil(size * 0.5);
    r2 = (int)ceil(size * S_RATIO * 0.5);
    switch (penPtr->symbol.type) {
    case SYMBOL_NONE:
        break;
    case SYMBOL_SQUARE:
        DrawSquares(graph->display, drawable, linePtr, penPtr, nSymbolPts,
            symbolPts, r2);
        break;
    case SYMBOL_CIRCLE:
        DrawCircles(graph->display, drawable, linePtr, penPtr, nSymbolPts,
            symbolPts, r1);
        break;
    case SYMBOL_SPLUS:
    case SYMBOL_SCROSS:{
    XSegment *segArr;          /* Array of line segments (splus, scross) */
    register XSegment *segPtr;
    int reqSize, nSegs, chunk;
        if(penPtr->symbol.type == SYMBOL_SCROSS) {
            r2 = Round(r2 * M_SQRT1_2);
            pattern[3].y = pattern[2].x = pattern[0].x = pattern[0].y = -r2;
            pattern[3].x = pattern[2].y = pattern[1].y = pattern[1].x = r2;
        } else {
            pattern[0].y = pattern[1].y = pattern[2].x = pattern[3].x = 0;
            pattern[0].x = pattern[2].y = -r2;
            pattern[1].x = pattern[3].y = r2;
        }
        segArr = (XSegment *) ckalloc(nSymbolPts * 2 * sizeof(XSegment));
        segPtr = segArr;
        if(linePtr->symbolInterval > 0) {
            count = 0;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                if(DRAW_SYMBOL(linePtr)) {
                    segPtr->x1 = pattern[0].x + (short int)pointPtr->x;
                    segPtr->y1 = pattern[0].y + (short int)pointPtr->y;
                    segPtr->x2 = pattern[1].x + (short int)pointPtr->x;
                    segPtr->y2 = pattern[1].y + (short int)pointPtr->y;
                    segPtr++;
                    segPtr->x1 = pattern[2].x + (short int)pointPtr->x;
                    segPtr->y1 = pattern[2].y + (short int)pointPtr->y;
                    segPtr->x2 = pattern[3].x + (short int)pointPtr->x;
                    segPtr->y2 = pattern[3].y + (short int)pointPtr->y;
                    segPtr++;
                    count++;
                }
                linePtr->symbolCounter++;
            }
        } else {
            count = nSymbolPts;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                segPtr->x1 = pattern[0].x + (short int)pointPtr->x;
                segPtr->y1 = pattern[0].y + (short int)pointPtr->y;
                segPtr->x2 = pattern[1].x + (short int)pointPtr->x;
                segPtr->y2 = pattern[1].y + (short int)pointPtr->y;
                segPtr++;
                segPtr->x1 = pattern[2].x + (short int)pointPtr->x;
                segPtr->y1 = pattern[2].y + (short int)pointPtr->y;
                segPtr->x2 = pattern[3].x + (short int)pointPtr->x;
                segPtr->y2 = pattern[3].y + (short int)pointPtr->y;
                segPtr++;
            }
        }
        nSegs = count * 2;
        /* Always draw skinny symbols regardless of the outline width */
        reqSize = MAX_DRAWSEGMENTS(graph->display);
        for(i = 0; i < nSegs; i += reqSize) {
            chunk = ((i + reqSize) > nSegs) ? (nSegs - i) : reqSize;
            XDrawSegments(graph->display, drawable,
                penPtr->symbol.outlineGC, segArr + i, chunk);
        }
        ckfree((char *)segArr);
    }
        break;
    case SYMBOL_PLUS:
    case SYMBOL_CROSS:{
    XPoint *polygon;
    register XPoint *p;
    int d;                     /* Small delta for cross/plus thickness */
        d = (r2 / 3);
        /*
         *
         *          2   3       The plus/cross symbol is a closed polygon
         *                      of 12 points. The diagram to the left
         *    0,12  1   4    5  represents the positions of the points
         *           x,y        which are computed below. The extra
         *     11  10   7    6  (thirteenth) point connects the first and
         *                      last points.
         *          9   8
         */
        pattern[0].x = pattern[11].x = pattern[12].x = -r2;
        pattern[2].x = pattern[1].x = pattern[10].x = pattern[9].x = -d;
        pattern[3].x = pattern[4].x = pattern[7].x = pattern[8].x = d;
        pattern[5].x = pattern[6].x = r2;
        pattern[2].y = pattern[3].y = -r2;
        pattern[0].y = pattern[1].y = pattern[4].y = pattern[5].y =
            pattern[12].y = -d;
        pattern[11].y = pattern[10].y = pattern[7].y = pattern[6].y = d;
        pattern[9].y = pattern[8].y = r2;
        if(penPtr->symbol.type == SYMBOL_CROSS) {
    double dx, dy;
            /* For the cross symbol, rotate the points by 45 degrees. */
            for(n = 0; n < 12; n++) {
                dx = (double)pattern[n].x * M_SQRT1_2;
                dy = (double)pattern[n].y * M_SQRT1_2;
                pattern[n].x = Round(dx - dy);
                pattern[n].y = Round(dx + dy);
            }
            pattern[12] = pattern[0];
        }
        polygon = (XPoint *) ckalloc(nSymbolPts * 13 * sizeof(XPoint));
        p = polygon;
        if(linePtr->symbolInterval > 0) {
            count = 0;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                if(DRAW_SYMBOL(linePtr)) {
                    for(n = 0; n < 13; n++) {
                        p->x = pattern[n].x + (short int)pointPtr->x;
                        p->y = pattern[n].y + (short int)pointPtr->y;
                        p++;
                    }
                    count++;
                }
                linePtr->symbolCounter++;
            }
        } else {
            count = nSymbolPts;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                for(n = 0; n < 13; n++) {
                    p->x = pattern[n].x + (short int)pointPtr->x;
                    p->y = pattern[n].y + (short int)pointPtr->y;
                    p++;
                }
            }
        }
        if(penPtr->symbol.fillGC != NULL) {
            for(p = polygon, i = 0; i < count; i++, p += 13) {
                XFillPolygon(graph->display, drawable,
                    penPtr->symbol.fillGC, p, 13, Complex, CoordModeOrigin);
            }
        }
        if(penPtr->symbol.outlineWidth > 0) {
            for(p = polygon, i = 0; i < count; i++, p += 13) {
                XDrawLines(graph->display, drawable,
                    penPtr->symbol.outlineGC, p, 13, CoordModeOrigin);
            }
        }
        ckfree((char *)polygon);
    }
        break;
    case SYMBOL_DIAMOND:{
    XPoint *polygon;
    register XPoint *p;
        /*
         *
         *                      The plus symbol is a closed polygon
         *            1         of 4 points. The diagram to the left
         *                      represents the positions of the points
         *       0,4 x,y  2     which are computed below. The extra
         *                      (fifth) point connects the first and
         *            3         last points.
         *
         */
        pattern[1].y = pattern[0].x = -r1;
        pattern[2].y = pattern[3].x = pattern[0].y = pattern[1].x = 0;
        pattern[3].y = pattern[2].x = r1;
        pattern[4] = pattern[0];
        polygon = (XPoint *) ckalloc(nSymbolPts * 5 * sizeof(XPoint));
        p = polygon;
        if(linePtr->symbolInterval > 0) {
            count = 0;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                if(DRAW_SYMBOL(linePtr)) {
                    for(n = 0; n < 5; n++, p++) {
                        p->x = pattern[n].x + (short int)pointPtr->x;
                        p->y = pattern[n].y + (short int)pointPtr->y;
                    }
                    count++;
                }
                linePtr->symbolCounter++;
            }
        } else {
            count = nSymbolPts;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                for(n = 0; n < 5; n++, p++) {
                    p->x = pattern[n].x + (short int)pointPtr->x;
                    p->y = pattern[n].y + (short int)pointPtr->y;
                }
            }
        }
        if(penPtr->symbol.fillGC != NULL) {
            for(p = polygon, i = 0; i < count; i++, p += 5) {
                XFillPolygon(graph->display, drawable,
                    penPtr->symbol.fillGC, p, 5, Convex, CoordModeOrigin);
            }
        }
        if(penPtr->symbol.outlineWidth > 0) {
            for(p = polygon, i = 0; i < count; i++, p += 5) {
                XDrawLines(graph->display, drawable,
                    penPtr->symbol.outlineGC, p, 5, CoordModeOrigin);
            }
        }
        ckfree((char *)polygon);
    }
        break;
    case SYMBOL_TRIANGLE:
    case SYMBOL_ARROW:{
    XPoint *polygon;
    register XPoint *p;
    double b;
    int b2, h1, h2;
#define H_RATIO		1.1663402261671607
#define B_RATIO		1.3467736870885982
#define TAN30		0.57735026918962573
#define COS30		0.86602540378443871
        b = Round(size * B_RATIO * 0.7);
        b2 = Round(b * 0.5);
        h2 = Round(TAN30 * b2);
        h1 = Round(b2 / COS30);
        /*
         *
         *                      The triangle symbol is a closed polygon
         *           0,3         of 3 points. The diagram to the left
         *                      represents the positions of the points
         *           x,y        which are computed below. The extra
         *                      (fourth) point connects the first and
         *      2           1   last points.
         *
         */
        if(penPtr->symbol.type == SYMBOL_ARROW) {
            pattern[3].x = pattern[0].x = 0;
            pattern[3].y = pattern[0].y = h1;
            pattern[1].x = b2;
            pattern[2].y = pattern[1].y = -h2;
            pattern[2].x = -b2;
        } else {
            pattern[3].x = pattern[0].x = 0;
            pattern[3].y = pattern[0].y = -h1;
            pattern[1].x = b2;
            pattern[2].y = pattern[1].y = h2;
            pattern[2].x = -b2;
        }
        polygon = (XPoint *) ckalloc(nSymbolPts * 4 * sizeof(XPoint));
        p = polygon;
        if(linePtr->symbolInterval > 0) {
            count = 0;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                if(DRAW_SYMBOL(linePtr)) {
                    for(n = 0; n < 4; n++) {
                        p->x = pattern[n].x + (short int)pointPtr->x;
                        p->y = pattern[n].y + (short int)pointPtr->y;
                        p++;
                    }
                    count++;
                }
                linePtr->symbolCounter++;
            }
        } else {
            count = nSymbolPts;
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                for(n = 0; n < 4; n++) {
                    p->x = pattern[n].x + (short int)pointPtr->x;
                    p->y = pattern[n].y + (short int)pointPtr->y;
                    p++;
                }
            }
        }
        if(penPtr->symbol.fillGC != NULL) {
            for(p = polygon, i = 0; i < count; i++, p += 4) {
                XFillPolygon(graph->display, drawable,
                    penPtr->symbol.fillGC, p, 4, Convex, CoordModeOrigin);
            }
        }
        if(penPtr->symbol.outlineWidth > 0) {
            for(p = polygon, i = 0; i < count; i++, p += 4) {
                XDrawLines(graph->display, drawable,
                    penPtr->symbol.outlineGC, p, 4, CoordModeOrigin);
            }
        }
        ckfree((char *)polygon);
    }
        break;
    case SYMBOL_BITMAP:{
    Pixmap bitmap, mask;
    int width, height, bmWidth, bmHeight;
    double scale, sx, sy;
    int dx, dy;
    register int x, y;
        Tk_SizeOfBitmap(graph->display, penPtr->symbol.bitmap, &width, &height);
        mask = None;
        /*
         * Compute the size of the scaled bitmap.  Stretch the
         * bitmap to fit a nxn bounding box.
         */
        sx = (double)size / (double)width;
        sy = (double)size / (double)height;
        scale = MIN(sx, sy);
        bmWidth = (int)(width * scale);
        bmHeight = (int)(height * scale);
        XSetClipMask(graph->display, penPtr->symbol.outlineGC, None);
        if(penPtr->symbol.mask != None) {
            mask =
                RbcScaleBitmap(*(graph->win), penPtr->symbol.mask, width,
                height, bmWidth, bmHeight);
            XSetClipMask(graph->display, penPtr->symbol.outlineGC, mask);
        }
        bitmap =
            RbcScaleBitmap(*(graph->win), penPtr->symbol.bitmap, width, height,
            bmWidth, bmHeight);
        if(penPtr->symbol.fillGC == NULL) {
            XSetClipMask(graph->display, penPtr->symbol.outlineGC, bitmap);
        }
        dx = bmWidth / 2;
        dy = bmHeight / 2;
        if(linePtr->symbolInterval > 0) {
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                if(DRAW_SYMBOL(linePtr)) {
                    x = (int)pointPtr->x - dx;
                    y = (int)pointPtr->y - dy;
                    if((penPtr->symbol.fillGC == NULL) || (mask != None)) {
                        XSetClipOrigin(graph->display,
                            penPtr->symbol.outlineGC, x, y);
                    }
                    XCopyPlane(graph->display, bitmap, drawable,
                        penPtr->symbol.outlineGC, 0, 0, bmWidth, bmHeight,
                        x, y, 1);
                }
                linePtr->symbolCounter++;
            }
        } else {
            for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
                pointPtr < endPtr; pointPtr++) {
                x = (int)pointPtr->x - dx;
                y = (int)pointPtr->y - dy;
                if((penPtr->symbol.fillGC == NULL) || (mask != None)) {
                    XSetClipOrigin(graph->display,
                        penPtr->symbol.outlineGC, x, y);
                }
                XCopyPlane(graph->display, bitmap, drawable,
                    penPtr->symbol.outlineGC, 0, 0, bmWidth, bmHeight, x, y, 1);
            }
        }
        Tk_FreePixmap(graph->display, bitmap);
        if(mask != None) {
            Tk_FreePixmap(graph->display, mask);
        }
    }
        break;
    }
}

/*
 * -----------------------------------------------------------------
 *
 * DrawSymbol --
 *
 *      Draw the symbol centered at the each given x,y coordinate.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws a symbol at the coordinate given.
 *
 * -----------------------------------------------------------------
 */
static void
DrawSymbol(
    RbcGraph * graph,          /* Graph widget record */
    Drawable drawable,         /* Pixmap or window to draw into */
    RbcElement * elemPtr,      /* Line element information */
    int x,                     /* Center position of symbol */
    int y,                     /* Center position of symbol */
    int size)
{              /* Size of symbol. */
    Line *linePtr = (Line *) elemPtr;
    LinePen *penPtr = linePtr->normalPenPtr;
    if(penPtr->traceWidth > 0) {
        /*
         * Draw an extra line offset by one pixel from the previous to
         * give a thicker appearance.  This is only for the legend
         * entry.  This routine is never called for drawing the actual
         * line segments.
         */
        XDrawLine(graph->display, drawable, penPtr->traceGC, x - size,
            y, x + size, y);
        XDrawLine(graph->display, drawable, penPtr->traceGC, x - size,
            y + 1, x + size, y + 1);
    }
    if(penPtr->symbol.type != SYMBOL_NONE) {
    RbcPoint2D point;
        point.x = x, point.y = y;
        DrawSymbols(graph, drawable, linePtr, linePtr->normalPenPtr, size,
            1, &point);
    }
}

#ifdef _WIN32
/*
 *----------------------------------------------------------------------
 *
 * DrawTraces --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawTraces(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    Line * linePtr,
    LinePen * penPtr)
{
RbcChainLink *linkPtr;
HBRUSH brush, oldBrush;
HDC dc;
HPEN pen, oldPen;
POINT *points;
TkWinDCState state;
LineTrace *tracePtr;
int j;
int nPoints, remaining;
register POINT *p;
register int count;
    /*
     * Depending if the line is wide (> 1 pixel), arbitrarily break
     * the line in sections of 100 points.  This bit of weirdness has
     * to do with wide geometric pens.  The longer the polyline, the
     * slower it draws.  The trade off is that we lose dash and cap
     * uniformity for unbearably slow polyline draws.
     */
    if(penPtr->traceGC->line_width > 1) {
        nPoints = 100;
    } else {
        nPoints = RbcMaxRequestSize(graph->display, sizeof(POINT)) - 1;
    }
    points = (POINT *) ckalloc((nPoints + 1) * sizeof(POINT));
    dc = TkWinGetDrawableDC(graph->display, drawable, &state);
    pen = RbcGCToPen(dc, penPtr->traceGC);
    oldPen = SelectPen(dc, pen);
    brush = CreateSolidBrush(penPtr->traceGC->foreground);
    oldBrush = SelectBrush(dc, brush);
    RbcSetROP2(dc, penPtr->traceGC->function);
    for(linkPtr = RbcChainFirstLink(linePtr->traces); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        tracePtr = RbcChainGetValue(linkPtr);
        /*
         * If the trace has to be split into separate XDrawLines
         * calls, then the end point of the current trace is also the
         * starting point of the new split.
         */
        /* Step 1. Convert and draw the first section of the trace.
         *         It may contain the entire trace. */
        for(p = points, count = 0; count < MIN(nPoints, tracePtr->nScreenPts);
            count++, p++) {
            p->x = (int)tracePtr->screenPts[count].x;
            p->y = (int)tracePtr->screenPts[count].y;
        }
        Polyline(dc, points, count);
        /* Step 2. Next handle any full-size chunks left. */
        while((count + nPoints) < tracePtr->nScreenPts) {
            /* Start with the last point of the previous trace. */
            points[0].x = points[nPoints - 1].x;
            points[0].y = points[nPoints - 1].y;
            for(p = points + 1, j = 0; j < nPoints; j++, count++, p++) {
                p->x = (int)tracePtr->screenPts[count].x;
                p->y = (int)tracePtr->screenPts[count].y;
            }
            Polyline(dc, points, nPoints + 1);
        }
        /* Step 3. Convert and draw the remaining points. */
        remaining = tracePtr->nScreenPts - count;
        if(remaining > 0) {
            /* Start with the last point of the previous trace. */
            points[0].x = points[nPoints - 1].x;
            points[0].y = points[nPoints - 1].y;
            for(p = points + 1; count < tracePtr->nScreenPts; count++, p++) {
                p->x = (int)tracePtr->screenPts[count].x;
                p->y = (int)tracePtr->screenPts[count].y;
            }
            Polyline(dc, points, remaining + 1);
        }
    }
    ckfree((char *)points);
    DeletePen(SelectPen(dc, oldPen));
    DeleteBrush(SelectBrush(dc, oldBrush));
    TkWinReleaseDrawableDC(drawable, dc, &state);
}
#else
/*
 *----------------------------------------------------------------------
 *
 * DrawTraces --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawTraces(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    Line * linePtr,
    LinePen * penPtr)
{
RbcChainLink *linkPtr;
LineTrace *tracePtr;
XPoint *points;
int j;
int nPoints, remaining;
register XPoint *p;
register int count;
    nPoints = RbcMaxRequestSize(graph->display, sizeof(XPoint)) - 1;
    points = (XPoint *) ckalloc((nPoints + 1) * sizeof(XPoint));
    for(linkPtr = RbcChainFirstLink(linePtr->traces); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
int n;
        tracePtr = RbcChainGetValue(linkPtr);
        /*
         * If the trace has to be split into separate XDrawLines
         * calls, then the end point of the current trace is also the
         * starting point of the new split.
         */
        /* Step 1. Convert and draw the first section of the trace.
         *         It may contain the entire trace. */
        n = MIN(nPoints, tracePtr->nScreenPts);
        for(p = points, count = 0; count < n; count++, p++) {
            p->x = (short int)tracePtr->screenPts[count].x;
            p->y = (short int)tracePtr->screenPts[count].y;
        }
        XDrawLines(graph->display, drawable, penPtr->traceGC, points,
            count, CoordModeOrigin);
        /* Step 2. Next handle any full-size chunks left. */
        while((count + nPoints) < tracePtr->nScreenPts) {
            /* Start with the last point of the previous trace. */
            points[0].x = points[nPoints - 1].x;
            points[0].y = points[nPoints - 1].y;
            for(p = points + 1, j = 0; j < nPoints; j++, count++, p++) {
                p->x = (short int)tracePtr->screenPts[count].x;
                p->y = (short int)tracePtr->screenPts[count].y;
            }
            XDrawLines(graph->display, drawable, penPtr->traceGC, points,
                nPoints + 1, CoordModeOrigin);
        }
        /* Step 3. Convert and draw the remaining points. */
        remaining = tracePtr->nScreenPts - count;
        if(remaining > 0) {
            /* Start with the last point of the previous trace. */
            points[0].x = points[nPoints - 1].x;
            points[0].y = points[nPoints - 1].y;
            for(p = points + 1; count < tracePtr->nScreenPts; count++, p++) {
                p->x = (short int)tracePtr->screenPts[count].x;
                p->y = (short int)tracePtr->screenPts[count].y;
            }
            XDrawLines(graph->display, drawable, penPtr->traceGC, points,
                remaining + 1, CoordModeOrigin);
        }
    }
    ckfree((char *)points);
}
#endif /* _WIN32 */
/*
 *----------------------------------------------------------------------
 *
 * DrawValues --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawValues(
    RbcGraph * graph,
    Drawable drawable,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int *pointToData)
{
    RbcPoint2D *pointPtr, *endPtr;
    int count;
    char string[TCL_DOUBLE_SPACE * 2 + 2];
    const char *fmt;
    double x, y;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    fmt = penPtr->valueFormat;
    if(fmt == NULL) {
        fmt = "%g";
    }
    count = 0;
    for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
        pointPtr < endPtr; pointPtr++) {
        x = linePtr->x.valueArr[pointToData[count]];
        y = linePtr->y.valueArr[pointToData[count]];
        count++;
        if(penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if(penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if(penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        RbcDrawText(*(graph->win), drawable, string, &(penPtr->valueStyle),
            (int)pointPtr->x, (int)pointPtr->y);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DrawActiveLine --
 *
 *      Draws the connected line(s) representing the element. If the
 *      line is made up of non-line symbols and the line width
 *      parameter has been set (linewidth > 0), the element will also
 *      be drawn as a line (with the linewidth requested).  The line
 *      may consist of separate line segments.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 *----------------------------------------------------------------------
 */
static void
DrawActiveLine(
    RbcGraph * graph,          /* Graph widget record */
    Drawable drawable,         /* Pixmap or window to draw into */
    RbcElement * elemPtr)
{              /* Element to be drawn */
Line *linePtr = (Line *) elemPtr;
LinePen *penPtr = linePtr->activePenPtr;
int symbolSize;
    if(penPtr == NULL) {
        return;
    }
    symbolSize = ScaleSymbol(elemPtr, linePtr->activePenPtr->symbol.size);
    /*
     * nActiveIndices
     *    > 0           Some points are active.  Uses activeArr.
     *    < 0           All points are active.
     *    == 0          No points are active.
     */
    if(linePtr->nActiveIndices > 0) {
        if(linePtr->flags & RBC_ACTIVE_PENDING) {
            MapActiveSymbols(graph, linePtr);
        }
        if(penPtr->symbol.type != SYMBOL_NONE) {
            DrawSymbols(graph, drawable, linePtr, penPtr, symbolSize,
                linePtr->nActivePts, linePtr->activePts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            DrawValues(graph, drawable, linePtr, penPtr,
                linePtr->nActivePts, linePtr->activePts, linePtr->activeToData);
        }
    } else if(linePtr->nActiveIndices < 0) {
        if(penPtr->traceWidth > 0) {
            if(linePtr->nStrips > 0) {
                RbcDraw2DSegments(graph->display, drawable,
                    penPtr->traceGC, linePtr->strips, linePtr->nStrips);
            } else if(RbcChainGetLength(linePtr->traces) > 0) {
                DrawTraces(graph, drawable, linePtr, penPtr);
            }
        }
        if(penPtr->symbol.type != SYMBOL_NONE) {
            DrawSymbols(graph, drawable, linePtr, penPtr, symbolSize,
                linePtr->nSymbolPts, linePtr->symbolPts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            DrawValues(graph, drawable, linePtr, penPtr,
                linePtr->nSymbolPts, linePtr->symbolPts, linePtr->symbolToData);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DrawNormalLine --
 *
 *      Draws the connected line(s) representing the element. If the
 *      line is made up of non-line symbols and the line width parameter
 *      has been set (linewidth > 0), the element will also be drawn as
 *      a line (with the linewidth requested).  The line may consist of
 *      separate line segments.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      X drawing commands are output.
 *
 *----------------------------------------------------------------------
 */
static void
DrawNormalLine(
    RbcGraph * graph,          /* Graph widget record */
    Drawable drawable,         /* Pixmap or window to draw into */
    RbcElement * elemPtr)
{              /* Element to be drawn */
Line *linePtr = (Line *) elemPtr;
LinePen *penPtr;
RbcChainLink *linkPtr;
register LinePenStyle *stylePtr;
unsigned int count;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    /* Fill area under the curve */
    if(linePtr->fillPts != NULL) {
XPoint *points;
RbcPoint2D *endPtr, *pointPtr;
        points = (XPoint *) ckalloc(sizeof(XPoint) * linePtr->nFillPts);
        count = 0;
        for(pointPtr = linePtr->fillPts,
            endPtr = linePtr->fillPts + linePtr->nFillPts;
            pointPtr < endPtr; pointPtr++) {
            points[count].x = (short int)pointPtr->x;
            points[count].y = (short int)pointPtr->y;
            count++;
        }
        if(linePtr->fillTile != NULL) {
            RbcSetTileOrigin(*(graph->win), linePtr->fillTile, 0, 0);
            RbcTilePolygon(*(graph->win), drawable, linePtr->fillTile,
                points, linePtr->nFillPts);
        } else if(linePtr->fillStipple != None) {
            XFillPolygon(graph->display, drawable, linePtr->fillGC,
                points, linePtr->nFillPts, Complex, CoordModeOrigin);
        }
        ckfree((char *)points);
    }
    /* Lines: stripchart segments or graph traces. */
    if(linePtr->nStrips > 0) {
        for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            penPtr = stylePtr->penPtr;
            if((stylePtr->nStrips > 0) && (penPtr->errorBarLineWidth > 0)) {
                RbcDraw2DSegments(graph->display, drawable,
                    penPtr->traceGC, stylePtr->strips, stylePtr->nStrips);
            }
        }
    } else if((RbcChainGetLength(linePtr->traces) > 0) &&
        (linePtr->normalPenPtr->traceWidth > 0)) {
        DrawTraces(graph, drawable, linePtr, linePtr->normalPenPtr);
    }
    if(linePtr->reqMaxSymbols > 0) {
int total;
        total = 0;
        for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            total += stylePtr->nSymbolPts;
        }
        linePtr->symbolInterval = total / linePtr->reqMaxSymbols;
        linePtr->symbolCounter = 0;
    }
    /* Symbols, error bars, values. */
    count = 0;
    for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        if((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcDraw2DSegments(graph->display, drawable, penPtr->errorBarGC,
                stylePtr->xErrorBars, stylePtr->xErrorBarCnt);
        }
        if((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcDraw2DSegments(graph->display, drawable, penPtr->errorBarGC,
                stylePtr->yErrorBars, stylePtr->yErrorBarCnt);
        }
        if((stylePtr->nSymbolPts > 0) && (penPtr->symbol.type != SYMBOL_NONE)) {
            DrawSymbols(graph, drawable, linePtr, penPtr,
                stylePtr->symbolSize, stylePtr->nSymbolPts,
                stylePtr->symbolPts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            DrawValues(graph, drawable, linePtr, penPtr,
                stylePtr->nSymbolPts, stylePtr->symbolPts,
                linePtr->symbolToData + count);
        }
        count += stylePtr->nSymbolPts;
    }
    linePtr->symbolInterval = 0;
}

/*
 * -----------------------------------------------------------------
 *
 * GetSymbolPostScriptInfo --
 *
 *      Set up the PostScript environment with the macros and
 *      attributes needed to draw the symbols of the element.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
GetSymbolPostScriptInfo(
    RbcGraph * graph,
    RbcPsToken * psToken,
    LinePen * penPtr,
    int size)
{
    XColor *outlineColor, *fillColor, *defaultColor;
    /* Set line and foreground attributes */
    outlineColor = penPtr->symbol.outlineColor;
    fillColor = penPtr->symbol.fillColor;
    defaultColor = penPtr->traceColor;
    if(fillColor == RBC_COLOR_DEFAULT) {
        fillColor = defaultColor;
    }
    if(outlineColor == RBC_COLOR_DEFAULT) {
        outlineColor = defaultColor;
    }
    if(penPtr->symbol.type == SYMBOL_NONE) {
        RbcLineAttributesToPostScript(psToken, defaultColor,
            penPtr->traceWidth + 2, &(penPtr->traceDashes), CapButt, JoinMiter);
    } else {
        RbcLineWidthToPostScript(psToken, penPtr->symbol.outlineWidth);
        RbcLineDashesToPostScript(psToken, (RbcDashes *) NULL);
    }
    /*
     * Build a PostScript procedure to draw the symbols.  For bitmaps,
     * paint both the bitmap and its mask. Otherwise fill and stroke
     * the path formed already.
     */
    RbcAppendToPostScript(psToken, "\n/DrawSymbolProc {\n", (char *)NULL);
    switch (penPtr->symbol.type) {
    case SYMBOL_NONE:
        break; /* Do nothing */
    case SYMBOL_BITMAP:{
    int width, height;
    double sx, sy, scale;
        /*
         * Compute how much to scale the bitmap.  Don't let the
         * scaled bitmap exceed the bounding square for the
         * symbol.
         */
        Tk_SizeOfBitmap(graph->display, penPtr->symbol.bitmap, &width, &height);
        sx = (double)size / (double)width;
        sy = (double)size / (double)height;
        scale = MIN(sx, sy);
        if((penPtr->symbol.mask != None) && (fillColor != NULL)) {
            RbcAppendToPostScript(psToken,
                "\n  % Bitmap mask is \"",
                Tk_NameOfBitmap(graph->display, penPtr->symbol.mask),
                "\"\n\n  ", (char *)NULL);
            RbcBackgroundToPostScript(psToken, fillColor);
            RbcBitmapToPostScript(psToken, graph->display,
                penPtr->symbol.mask, scale, scale);
        }
        RbcAppendToPostScript(psToken,
            "\n  % Bitmap symbol is \"",
            Tk_NameOfBitmap(graph->display, penPtr->symbol.bitmap),
            "\"\n\n  ", (char *)NULL);
        RbcForegroundToPostScript(psToken, outlineColor);
        RbcBitmapToPostScript(psToken, graph->display,
            penPtr->symbol.bitmap, scale, scale);
    }
        break;
    default:
        if(fillColor != NULL) {
            RbcAppendToPostScript(psToken, "  ", (char *)NULL);
            RbcBackgroundToPostScript(psToken, fillColor);
            RbcAppendToPostScript(psToken, "  Fill\n", (char *)NULL);
        }
        if((outlineColor != NULL) && (penPtr->symbol.outlineWidth > 0)) {
            RbcAppendToPostScript(psToken, "  ", (char *)NULL);
            RbcForegroundToPostScript(psToken, outlineColor);
            RbcAppendToPostScript(psToken, "  stroke\n", (char *)NULL);
        }
        break;
    }
    RbcAppendToPostScript(psToken, "} def\n\n", (char *)NULL);
}

/*
 * -----------------------------------------------------------------
 *
 * SymbolsToPostScript --
 *
 *      Draw a symbol centered at the given x,y window coordinate
 *      based upon the element symbol type and size.
 *
 *      Most notable problem is the round-off errors generated when
 *      calculating the centered position of the symbol.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static void
SymbolsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    LinePen * penPtr,
    int size,
    int nSymbolPts,
    RbcPoint2D * symbolPts)
{
    double symbolSize;
    register RbcPoint2D *pointPtr, *endPtr;
    static const char *symbolMacros[] = {
        "Li", "Sq", "Ci", "Di", "Pl", "Cr", "Sp", "Sc", "Tr", "Ar", "Bm",
        (char *)NULL,
    };
    GetSymbolPostScriptInfo(graph, psToken, penPtr, size);
    symbolSize = (double)size;
    switch (penPtr->symbol.type) {
    case SYMBOL_SQUARE:
    case SYMBOL_CROSS:
    case SYMBOL_PLUS:
    case SYMBOL_SCROSS:
    case SYMBOL_SPLUS:
        symbolSize = (double)Round(size * S_RATIO);
        break;
    case SYMBOL_TRIANGLE:
    case SYMBOL_ARROW:
        symbolSize = (double)Round(size * 0.7);
        break;
    case SYMBOL_DIAMOND:
        symbolSize = (double)Round(size * M_SQRT1_2);
        break;
    default:
        break;
    }
    for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
        pointPtr < endPtr; pointPtr++) {
        RbcFormatToPostScript(psToken, "%g %g %g %s\n", pointPtr->x,
            pointPtr->y, symbolSize, symbolMacros[penPtr->symbol.type]);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * SymbolToPostScript --
 *
 *      Draw the symbol centered at the each given x,y coordinate.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws a symbol at the coordinate given.
 *
 * -----------------------------------------------------------------
 */
static void
SymbolToPostScript(
    RbcGraph * graph,          /* Graph widget record */
    RbcPsToken * psToken,
    RbcElement * elemPtr,      /* Line element information */
    double x,                  /* Center position of symbol */
    double y,                  /* Center position of symbol */
    int size)
{              /* Size of element */
    Line *linePtr = (Line *) elemPtr;
    LinePen *penPtr = linePtr->normalPenPtr;
    if(penPtr->traceWidth > 0) {
        /*
         * Draw an extra line offset by one pixel from the previous to
         * give a thicker appearance.  This is only for the legend
         * entry.  This routine is never called for drawing the actual
         * line segments.
         */
        RbcLineAttributesToPostScript(psToken, penPtr->traceColor,
            penPtr->traceWidth + 2, &(penPtr->traceDashes), CapButt, JoinMiter);
        RbcFormatToPostScript(psToken, "%g %g %d Li\n", x, y, size + size);
    }
    if(penPtr->symbol.type != SYMBOL_NONE) {
    RbcPoint2D point;
        point.x = x, point.y = y;
        SymbolsToPostScript(graph, psToken, penPtr, size, 1, &point);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * SetLineAttributes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
SetLineAttributes(
    RbcPsToken * psToken,
    LinePen * penPtr)
{
    /* Set the attributes of the line (color, dashes, linewidth) */
    RbcLineAttributesToPostScript(psToken, penPtr->traceColor,
        penPtr->traceWidth, &(penPtr->traceDashes), CapButt, JoinMiter);
    if((RbcLineIsDashed(penPtr->traceDashes)) &&
        (penPtr->traceOffColor != NULL)) {
        RbcAppendToPostScript(psToken, "/DashesProc {\n  gsave\n    ",
            (char *)NULL);
        RbcBackgroundToPostScript(psToken, penPtr->traceOffColor);
        RbcAppendToPostScript(psToken, "    ", (char *)NULL);
        RbcLineDashesToPostScript(psToken, (RbcDashes *) NULL);
        RbcAppendToPostScript(psToken, "stroke\n  grestore\n} def\n",
            (char *)NULL);
    } else {
        RbcAppendToPostScript(psToken, "/DashesProc {} def\n", (char *)NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TracesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
TracesToPostScript(
    RbcPsToken * psToken,
    Line * linePtr,
    LinePen * penPtr)
{
RbcChainLink *linkPtr;
LineTrace *tracePtr;
register RbcPoint2D *pointPtr, *endPtr;
int count;
    SetLineAttributes(psToken, penPtr);
    for(linkPtr = RbcChainFirstLink(linePtr->traces); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        tracePtr = RbcChainGetValue(linkPtr);
        if(tracePtr->nScreenPts <= 0) {
            continue;
        }
#define PS_MAXPATH	1500    /* Maximum number of components in a PostScript
                                 * (level 1) path. */
        pointPtr = tracePtr->screenPts;
        RbcFormatToPostScript(psToken, " newpath %g %g moveto\n",
            pointPtr->x, pointPtr->y);
        pointPtr++;
        count = 0;
        for(endPtr = tracePtr->screenPts + (tracePtr->nScreenPts - 1);
            pointPtr < endPtr; pointPtr++) {
            RbcFormatToPostScript(psToken, " %g %g lineto\n",
                pointPtr->x, pointPtr->y);
            if((count % PS_MAXPATH) == 0) {
                RbcFormatToPostScript(psToken,
                    "DashesProc stroke\n newpath  %g %g moveto\n",
                    pointPtr->x, pointPtr->y);
            }
            count++;
        }
        RbcFormatToPostScript(psToken, " %g %g lineto\n",
            pointPtr->x, pointPtr->y);
        RbcAppendToPostScript(psToken, "DashesProc stroke\n", (char *)NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ValuesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ValuesToPostScript(
    RbcPsToken * psToken,
    Line * linePtr,
    LinePen * penPtr,
    int nSymbolPts,
    RbcPoint2D * symbolPts,
    int *pointToData)
{
    RbcPoint2D *pointPtr, *endPtr;
    int count;
    char string[TCL_DOUBLE_SPACE * 2 + 2];
    const char *fmt;
    double x, y;
    fmt = penPtr->valueFormat;
    if(fmt == NULL) {
        fmt = "%g";
    }
    count = 0;
    for(pointPtr = symbolPts, endPtr = symbolPts + nSymbolPts;
        pointPtr < endPtr; pointPtr++) {
        x = linePtr->x.valueArr[pointToData[count]];
        y = linePtr->y.valueArr[pointToData[count]];
        count++;
        if(penPtr->valueShow == RBC_SHOW_X) {
            sprintf(string, fmt, x);
        } else if(penPtr->valueShow == RBC_SHOW_Y) {
            sprintf(string, fmt, y);
        } else if(penPtr->valueShow == RBC_SHOW_BOTH) {
            sprintf(string, fmt, x);
            strcat(string, ",");
            sprintf(string + strlen(string), fmt, y);
        }
        RbcTextToPostScript(psToken, string, &(penPtr->valueStyle),
            pointPtr->x, pointPtr->y);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ActiveLineToPostScript --
 *
 *      Generates PostScript commands to draw as "active" the points
 *      (symbols) and or line segments (trace) representing the
 *      element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 *----------------------------------------------------------------------
 */
static void
ActiveLineToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
Line *linePtr = (Line *) elemPtr;
LinePen *penPtr = linePtr->activePenPtr;
int symbolSize;
    if(penPtr == NULL) {
        return;
    }
    symbolSize = ScaleSymbol(elemPtr, penPtr->symbol.size);
    if(linePtr->nActiveIndices > 0) {
        if(linePtr->flags & RBC_ACTIVE_PENDING) {
            MapActiveSymbols(graph, linePtr);
        }
        if(penPtr->symbol.type != SYMBOL_NONE) {
            SymbolsToPostScript(graph, psToken, penPtr, symbolSize,
                linePtr->nActivePts, linePtr->activePts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            ValuesToPostScript(psToken, linePtr, penPtr, linePtr->nActivePts,
                linePtr->activePts, linePtr->activeToData);
        }
    } else if(linePtr->nActiveIndices < 0) {
        if(penPtr->traceWidth > 0) {
            if(linePtr->nStrips > 0) {
                SetLineAttributes(psToken, penPtr);
                Rbc2DSegmentsToPostScript(psToken, linePtr->strips,
                    linePtr->nStrips);
            }
            if(RbcChainGetLength(linePtr->traces) > 0) {
                TracesToPostScript(psToken, linePtr, (LinePen *) penPtr);
            }
        }
        if(penPtr->symbol.type != SYMBOL_NONE) {
            SymbolsToPostScript(graph, psToken, penPtr, symbolSize,
                linePtr->nSymbolPts, linePtr->symbolPts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            ValuesToPostScript(psToken, linePtr, penPtr, linePtr->nSymbolPts,
                linePtr->symbolPts, linePtr->symbolToData);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * NormalLineToPostScript --
 *
 *      Similar to the DrawLine procedure, prints PostScript related
 *      commands to form the connected line(s) representing the element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript pen width, dashes, and color settings are changed.
 *
 *----------------------------------------------------------------------
 */
static void
NormalLineToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    RbcElement * elemPtr)
{
Line *linePtr = (Line *) elemPtr;
register LinePenStyle *stylePtr;
RbcChainLink *linkPtr;
LinePen *penPtr;
unsigned int count;
XColor *colorPtr;
    /* Draw fill area */
    if(linePtr->fillPts != NULL) {
        /* Create a path to use for both the polygon and its outline. */
        RbcPathToPostScript(psToken, linePtr->fillPts, linePtr->nFillPts);
        RbcAppendToPostScript(psToken, "closepath\n", (char *)NULL);
        /* If the background fill color was specified, draw the
         * polygon in a solid fashion with that color.  */
        if(linePtr->fillBgColor != NULL) {
            RbcBackgroundToPostScript(psToken, linePtr->fillBgColor);
            RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
        }
        RbcForegroundToPostScript(psToken, linePtr->fillFgColor);
        if(linePtr->fillTile != NULL) {
            /* TBA: Transparent tiling is the hard part. */
        } else if((linePtr->fillStipple != None) &&
            (linePtr->fillStipple != PATTERN_SOLID)) {
            /* Draw the stipple in the foreground color. */
            RbcStippleToPostScript(psToken, graph->display,
                linePtr->fillStipple);
        } else {
            RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
        }
    }
    /* Draw lines */
    if(linePtr->nStrips > 0) {
        for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            stylePtr = RbcChainGetValue(linkPtr);
            penPtr = stylePtr->penPtr;
            if((stylePtr->nStrips > 0) && (penPtr->traceWidth > 0)) {
                SetLineAttributes(psToken, penPtr);
                Rbc2DSegmentsToPostScript(psToken, stylePtr->strips,
                    stylePtr->nStrips);
            }
        }
    } else if((RbcChainGetLength(linePtr->traces) > 0) &&
        (linePtr->normalPenPtr->traceWidth > 0)) {
        TracesToPostScript(psToken, linePtr, linePtr->normalPenPtr);
    }
    /* Draw symbols, error bars, values. */
    count = 0;
    for(linkPtr = RbcChainFirstLink(linePtr->palette); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        stylePtr = RbcChainGetValue(linkPtr);
        penPtr = stylePtr->penPtr;
        colorPtr = penPtr->errorBarColor;
        if(colorPtr == RBC_COLOR_DEFAULT) {
            colorPtr = penPtr->traceColor;
        }
        if((stylePtr->xErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_X)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->xErrorBars,
                stylePtr->xErrorBarCnt);
        }
        if((stylePtr->yErrorBarCnt > 0) && (penPtr->errorBarShow & RBC_SHOW_Y)) {
            RbcLineAttributesToPostScript(psToken, colorPtr,
                penPtr->errorBarLineWidth, NULL, CapButt, JoinMiter);
            Rbc2DSegmentsToPostScript(psToken, stylePtr->yErrorBars,
                stylePtr->yErrorBarCnt);
        }
        if((stylePtr->nSymbolPts > 0) &&
            (stylePtr->penPtr->symbol.type != SYMBOL_NONE)) {
            SymbolsToPostScript(graph, psToken, penPtr,
                stylePtr->symbolSize, stylePtr->nSymbolPts,
                stylePtr->symbolPts);
        }
        if(penPtr->valueShow != RBC_SHOW_NONE) {
            ValuesToPostScript(psToken, linePtr, penPtr,
                stylePtr->nSymbolPts, stylePtr->symbolPts,
                linePtr->symbolToData + count);
        }
        count += stylePtr->nSymbolPts;
    }
}

#define FreeVector(v) \
    if ((v).clientId != NULL) { \
	Rbc_FreeVectorId((v).clientId); \
    } else if ((v).valueArr != NULL) { \
	ckfree((char *)(v).valueArr); \
    }
/*
 *----------------------------------------------------------------------
 *
 * DestroyLine --
 *
 *      Release memory and resources allocated for the line element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the line element is freed up.
 *
 *----------------------------------------------------------------------
 */
static void
DestroyLine(
    RbcGraph * graph,
    RbcElement * elemPtr)
{
Line *linePtr = (Line *) elemPtr;
    if(linePtr->normalPenPtr != &(linePtr->builtinPen)) {
        RbcFreePen(graph, (RbcPen *) linePtr->normalPenPtr);
    }
    DestroyPen(graph, (RbcPen *) & (linePtr->builtinPen));
    if(linePtr->activePenPtr != NULL) {
        RbcFreePen(graph, (RbcPen *) linePtr->activePenPtr);
    }
    FreeVector(linePtr->w);
    FreeVector(linePtr->x);
    FreeVector(linePtr->xHigh);
    FreeVector(linePtr->xLow);
    FreeVector(linePtr->xError);
    FreeVector(linePtr->y);
    FreeVector(linePtr->yHigh);
    FreeVector(linePtr->yLow);
    FreeVector(linePtr->yError);
    ResetLine(linePtr);
    if(linePtr->palette != NULL) {
        RbcFreePalette(graph, linePtr->palette);
        RbcChainDestroy(linePtr->palette);
    }
    if(linePtr->tags != NULL) {
        ckfree((char *)linePtr->tags);
    }
    if(linePtr->activeIndices != NULL) {
        ckfree((char *)linePtr->activeIndices);
    }
    if(linePtr->fillPts != NULL) {
        ckfree((char *)linePtr->fillPts);
    }
    if(linePtr->fillTile != NULL) {
        RbcFreeTile(linePtr->fillTile);
    }
    if((linePtr->fillStipple != None) &&
        (linePtr->fillStipple != PATTERN_SOLID)) {
        Tk_FreeBitmap(graph->display, linePtr->fillStipple);
    }
    if(linePtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, linePtr->fillGC);
    }
}

static RbcElementProcs lineProcs = {
    ClosestLine,        /* Finds the closest element/data point */
    ConfigureLine,      /* Configures the element. */
    DestroyLine,        /* Destroys the element. */
    DrawActiveLine,     /* Draws active element */
    DrawNormalLine,     /* Draws normal element */
    DrawSymbol, /* Draws the element symbol. */
    GetLineExtents,     /* Find the extents of the element's data. */
    ActiveLineToPostScript,     /* Prints active element. */
    NormalLineToPostScript,     /* Prints normal element. */
    SymbolToPostScript, /* Prints the line's symbol. */
    MapLine    /* Compute element's screen coordinates. */
};

/*
 *----------------------------------------------------------------------
 *
 * RbcLineElement --
 *
 *      Allocate memory and initialize methods for the new line element.
 *
 * Results:
 *      The pointer to the newly allocated element structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the line element structure.
 *
 *----------------------------------------------------------------------
 */
RbcElement *
RbcLineElement(
    RbcGraph * graph,
    const char *name,
    Tk_Uid classUid)
{
    register Line *linePtr;
    linePtr = RbcCalloc(1, sizeof(Line));
    assert(linePtr);
    linePtr->procsPtr = &lineProcs;
    if(classUid == rbcLineElementUid) {
        linePtr->configSpecs = lineElemConfigSpecs;
    } else {
        linePtr->configSpecs = stripElemConfigSpecs;
    }
    /* By default an element's name and label are the same. */
    linePtr->label = RbcStrdup(name);
    linePtr->name = RbcStrdup(name);
    linePtr->classUid = classUid;
    linePtr->flags = RBC_SCALE_SYMBOL;
    linePtr->graph = graph;
    linePtr->labelRelief = TK_RELIEF_FLAT;
    linePtr->normalPenPtr = &linePtr->builtinPen;
    linePtr->palette = RbcChainCreate();
    linePtr->penDir = PEN_BOTH_DIRECTIONS;
    linePtr->reqSmooth = PEN_SMOOTH_NONE;
    InitPen(linePtr->normalPenPtr);
    return (RbcElement *) linePtr;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphMarker.c.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define MAX_OUTLINE_POINTS	12

/* Map graph coordinates to normalized coordinates [0..1] */
#define NORMALIZE(A,x) 	(((x) - (A)->axisRange.min) / (A)->axisRange.range)

#define DEF_MARKER_ANCHOR       "center"
#define DEF_MARKER_BACKGROUND   "white"
#define DEF_MARKER_BG_MONO      "white"
#define DEF_MARKER_BITMAP       (char *)NULL
#define DEF_MARKER_CAP_STYLE    "butt"
#define DEF_MARKER_COORDS       (char *)NULL
#define DEF_MARKER_DASHES       (char *)NULL
#define DEF_MARKER_DASH_OFFSET  "0"
#define DEF_MARKER_ELEMENT      (char *)NULL
#define DEF_MARKER_FOREGROUND   "black"
#define DEF_MARKER_FG_MONO      "black"
#define DEF_MARKER_FILL_COLOR   "red"
#define DEF_MARKER_FILL_MONO    "white"
#define DEF_MARKER_FONT         RBC_FONT
#define DEF_MARKER_GAP_COLOR    "pink"
#define DEF_MARKER_GAP_MONO     "black"
#define DEF_MARKER_HEIGHT       "0"
#define DEF_MARKER_HIDE         "no"
#define DEF_MARKER_JOIN_STYLE   "miter"
#define DEF_MARKER_JUSTIFY      "left"
#define DEF_MARKER_LINE_WIDTH   "1"
#define DEF_MARKER_MAP_X        "x"
#define DEF_MARKER_MAP_Y        "y"
#define DEF_MARKER_NAME         (char *)NULL
#define DEF_MARKER_OUTLINE_COLOR    "black"
#define DEF_MARKER_OUTLINE_MONO "black"
#define DEF_MARKER_PAD          "4"
#define DEF_MARKER_ROTATE       "0.0"
#define DEF_MARKER_SCALE        "1.0"
#define DEF_MARKER_SHADOW_COLOR (char *)NULL
#define DEF_MARKER_SHADOW_MONO  (char *)NULL
#define DEF_MARKER_STATE        "normal"
#define DEF_MARKER_STIPPLE      (char *)NULL
#define DEF_MARKER_TEXT         (char *)NULL
#define DEF_MARKER_UNDER        "no"
#define DEF_MARKER_WIDTH        "0"
#define DEF_MARKER_WINDOW       (char *)NULL
#define DEF_MARKER_XOR          "no"
#define DEF_MARKER_X_OFFSET     "0"
#define DEF_MARKER_Y_OFFSET     "0"

#define DEF_MARKER_TEXT_TAGS    "Text all"
#define DEF_MARKER_IMAGE_TAGS   "Image all"
#define DEF_MARKER_BITMAP_TAGS  "Bitmap all"
#define DEF_MARKER_WINDOW_TAGS  "Window all"
#define DEF_MARKER_POLYGON_TAGS "Polygon all"
#define DEF_MARKER_LINE_TAGS    "Line all"

static Tk_OptionParseProc StringToCoordinates;
static Tk_OptionPrintProc CoordinatesToString;
static Tk_CustomOption coordsOption = {
    StringToCoordinates, CoordinatesToString, (ClientData) 0
};

extern Tk_CustomOption rbcColorPairOption;
extern Tk_CustomOption rbcDashesOption;
extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcListOption;
extern Tk_CustomOption rbcPadOption;
extern Tk_CustomOption rbcPositiveDistanceOption;
extern Tk_CustomOption rbcShadowOption;
extern Tk_CustomOption rbcStateOption;
extern Tk_CustomOption rbcXAxisOption;
extern Tk_CustomOption rbcYAxisOption;

typedef RbcMarker *(
    MarkerCreateProc) (
    void);
typedef void (
    MarkerDrawProc) (
    RbcMarker * markerPtr,
    Drawable drawable);
typedef void (
    MarkerFreeProc) (
    RbcGraph * graph,
    RbcMarker * markerPtr);
typedef int (
    MarkerConfigProc) (
    RbcMarker * markerPtr);
typedef void (
    MarkerMapProc) (
    RbcMarker * markerPtr);
typedef void (
    MarkerPostScriptProc) (
    RbcMarker * markerPtr,
    RbcPsToken * psToken);
typedef int (
    MarkerPointProc) (
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr);
typedef int (
    MarkerRegionProc) (
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed);

typedef struct {
    Tk_ConfigSpec *configSpecs; /* Marker configuration specifications */
    MarkerConfigProc *configProc;
    MarkerDrawProc *drawProc;
    MarkerFreeProc *freeProc;
    MarkerMapProc *mapProc;
    MarkerPointProc *pointProc;
    MarkerRegionProc *regionProc;
    MarkerPostScriptProc *postscriptProc;

} MarkerClass;

/*
 * -------------------------------------------------------------------
 *
 * Marker --
 *
 *      Structure defining the generic marker.  In C++ parlance this
 *      would be the base type from which all markers are derived.
 *
 *      This structure corresponds with the specific types of markers.
 *      Don't change this structure without changing the individual
 *      marker structures of each type below.
 *
 * -------------------------------------------------------------------
 */
typedef struct RbcMarker {
    char *name;                /* Identifier for marker in list */
    Tk_Uid classUid;           /* Type of marker. */
    RbcGraph *graph;           /* Graph widget of marker. */
    unsigned int flags;
    char **tags;
    int hidden;                /* If non-zero, don't display the marker. */
    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;
    RbcPoint2D *worldPts;      /* Coordinate array to position marker */
    int nWorldPts;             /* Number of points in above array */
    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. This can
                                * be a performance penalty because
                                * the graph must be redraw entirely
                                * each time the marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset from graph position */
    MarkerClass *classPtr;
    int state;
} RbcMarker;

/*
 * -------------------------------------------------------------------
 *
 * TextMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type of marker */
    RbcGraph *graph;           /* The graph this marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* If non-zero, don't display the
                                * marker. */
    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;
    RbcPoint2D *worldPts;      /* Position of marker (1 X-Y coordinate) in
                                * world (graph) coordinates. */
    int nWorldPts;             /* Number of points */
    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* pixel offset from anchor */
    MarkerClass *classPtr;
    int state;

    /*
     * Text specific fields and attributes
     */
    char *string;              /* Text string to be display.  The string
                                * make contain newlines. */
    Tk_Anchor anchor;          /* Indicates how to translate the given
                                * marker position. */
    RbcPoint2D anchorPos;      /* Translated anchor point. */
    int width, height;         /* Dimension of bounding box.  */
    RbcTextStyle style;        /* Text attributes (font, fg, anchor, etc) */
    RbcTextLayout *textPtr;    /* Contains information about the layout
                                * of the text. */
    RbcPoint2D outline[5];
    XColor *fillColor;
    GC  fillGC;
} TextMarker;

static Tk_ConfigSpec textConfigSpecs[] = {
    {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", DEF_MARKER_ANCHOR,
        Tk_Offset(TextMarker, anchor), 0},
    {TK_CONFIG_COLOR, "-background", "background", "MarkerBackground",
        (char *)NULL, Tk_Offset(TextMarker, fillColor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bg", "background", "Background", (char *)NULL, 0, 0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_TEXT_TAGS, Tk_Offset(RbcMarker, tags), TK_CONFIG_NULL_OK,
        &rbcListOption},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords", DEF_MARKER_COORDS,
        Tk_Offset(RbcMarker, worldPts), TK_CONFIG_NULL_OK, &coordsOption},
    {TK_CONFIG_STRING, "-element", "element", "Element", DEF_MARKER_ELEMENT,
        Tk_Offset(RbcMarker, elemName), TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", "Foreground", (char *)NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-fill", "background", (char *)NULL, (char *)NULL, 0,
        0},
    {TK_CONFIG_FONT, "-font", "font", "Font", DEF_MARKER_FONT,
        Tk_Offset(TextMarker, style.font), 0},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_MARKER_FOREGROUND, Tk_Offset(TextMarker, style.color),
        TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_MARKER_FG_MONO, Tk_Offset(TextMarker, style.color),
        TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify", DEF_MARKER_JUSTIFY,
        Tk_Offset(TextMarker, style.justify), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_MARKER_HIDE,
        Tk_Offset(RbcMarker, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_MARKER_MAP_X,
        Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_MARKER_MAP_Y,
        Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL, DEF_MARKER_NAME,
        Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-outline", "foreground", (char *)NULL, (char *)NULL,
        0, 0},
    {TK_CONFIG_CUSTOM, "-padx", "padX", "PadX", DEF_MARKER_PAD,
            Tk_Offset(TextMarker, style.padX), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-pady", "padY", "PadY", DEF_MARKER_PAD,
            Tk_Offset(TextMarker, style.padY), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPadOption},
    {TK_CONFIG_DOUBLE, "-rotate", "rotate", "Rotate", DEF_MARKER_ROTATE,
        Tk_Offset(TextMarker, style.theta), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-shadow", "shadow", "Shadow", DEF_MARKER_SHADOW_COLOR,
            Tk_Offset(TextMarker, style.shadow), TK_CONFIG_COLOR_ONLY,
        &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-shadow", "shadow", "Shadow", DEF_MARKER_SHADOW_MONO,
            Tk_Offset(TextMarker, style.shadow), TK_CONFIG_MONO_ONLY,
        &rbcShadowOption},
    {TK_CONFIG_CUSTOM, "-state", "state", "State", DEF_MARKER_STATE,
            Tk_Offset(RbcMarker, state), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcStateOption},
    {TK_CONFIG_STRING, "-text", "text", "Text", DEF_MARKER_TEXT,
        Tk_Offset(TextMarker, string), TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under", DEF_MARKER_UNDER,
        Tk_Offset(RbcMarker, drawUnder), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset", DEF_MARKER_X_OFFSET,
        Tk_Offset(RbcMarker, xOffset), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset", DEF_MARKER_Y_OFFSET,
        Tk_Offset(RbcMarker, yOffset), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/*
 * -------------------------------------------------------------------
 *
 * WindowMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type of marker */
    RbcGraph *graph;           /* Graph marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* Indicates if the marker is
                                * currently hidden or not. */
    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;
    RbcPoint2D *worldPts;      /* Position of marker (1 X-Y coordinate) in
                                * world (graph) coordinates. */
    int nWorldPts;             /* Number of points */
    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset from anchor. */
    MarkerClass *classPtr;
    int state;

    /*
     * Window specific attributes
     */
    char *pathName;            /* Name of child widget to be displayed. */
    Tk_Window tkwin;           /* Window to display. */
    int reqWidth, reqHeight;   /* If non-zero, this overrides the size
                                * requested by the child widget. */
    Tk_Anchor anchor;          /* Indicates how to translate the given
                                * marker position. */
    RbcPoint2D anchorPos;      /* Translated anchor point. */
    int width, height;         /* Current size of the child window. */
} WindowMarker;

static Tk_ConfigSpec windowConfigSpecs[] = {
    {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor", DEF_MARKER_ANCHOR,
        Tk_Offset(WindowMarker, anchor), 0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_WINDOW_TAGS, Tk_Offset(RbcMarker, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords", DEF_MARKER_COORDS,
            Tk_Offset(WindowMarker, worldPts), TK_CONFIG_NULL_OK,
        &coordsOption},
    {TK_CONFIG_STRING, "-element", "element", "Element", DEF_MARKER_ELEMENT,
        Tk_Offset(RbcMarker, elemName), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-height", "height", "Height", DEF_MARKER_HEIGHT,
            Tk_Offset(WindowMarker, reqHeight), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPositiveDistanceOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide", DEF_MARKER_HIDE,
        Tk_Offset(RbcMarker, hidden), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX", DEF_MARKER_MAP_X,
        Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY", DEF_MARKER_MAP_Y,
        Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL, DEF_MARKER_NAME,
        Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-state", "state", "State", DEF_MARKER_STATE,
            Tk_Offset(RbcMarker, state), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcStateOption},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under", DEF_MARKER_UNDER,
        Tk_Offset(RbcMarker, drawUnder), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-width", "width", "Width", DEF_MARKER_WIDTH,
            Tk_Offset(WindowMarker, reqWidth), TK_CONFIG_DONT_SET_DEFAULT,
        &rbcPositiveDistanceOption},
    {TK_CONFIG_STRING, "-window", "window", "Window", DEF_MARKER_WINDOW,
        Tk_Offset(WindowMarker, pathName), TK_CONFIG_NULL_OK},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset", DEF_MARKER_X_OFFSET,
        Tk_Offset(RbcMarker, xOffset), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset", DEF_MARKER_Y_OFFSET,
        Tk_Offset(RbcMarker, yOffset), TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/*
 * -------------------------------------------------------------------
 *
 * BitmapMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type of marker */
    RbcGraph *graph;           /* Graph marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* Indicates if the marker is currently
                                * hidden or not. */
    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;
    RbcPoint2D *worldPts;      /* Position of marker in world (graph)
                                * coordinates. If 2 pairs of X-Y
                                * coordinates are specified, then the
                                * bitmap is resized to fit this area.
                                * Otherwise if 1 pair, then the bitmap
                                * is positioned at the coordinate at its
                                * normal size. */
    int nWorldPts;             /* Number of points */
    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset from origin of bitmap */
    MarkerClass *classPtr;
    int state;

    /* Bitmap specific attributes */
    Pixmap srcBitmap;          /* Original bitmap. May be further
                                * scaled or rotated. */
    double rotate;             /* Requested rotation of the bitmap */
    double theta;              /* Normalized rotation (0..360
                                * degrees) */
    Tk_Anchor anchor;          /* If only one X-Y coordinate is
                                * given, indicates how to translate
                                * the given marker position.  Otherwise,
                                * if there are two X-Y coordinates, then
                                * this value is ignored. */
    RbcPoint2D anchorPos;      /* Translated anchor point. */
    XColor *outlineColor;      /* Foreground color */
    XColor *fillColor;         /* Background color */
    GC  gc;                    /* Private graphic context */
    GC  fillGC;                /* Shared graphic context */
    Pixmap destBitmap;         /* Bitmap to be drawn. */
    int destWidth, destHeight; /* Dimensions of the final bitmap */
    RbcPoint2D outline[MAX_OUTLINE_POINTS];     /* Polygon representing the background
                                                 * of the bitmap. */
    int nOutlinePts;
} BitmapMarker;

static Tk_ConfigSpec bitmapConfigSpecs[] = {
    {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor",
        DEF_MARKER_ANCHOR, Tk_Offset(BitmapMarker, anchor), 0},
    {TK_CONFIG_COLOR, "-background", "background", "Background",
            DEF_MARKER_BACKGROUND, Tk_Offset(BitmapMarker, fillColor),
        TK_CONFIG_COLOR_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-background", "background", "Background",
            DEF_MARKER_BG_MONO, Tk_Offset(BitmapMarker, fillColor),
        TK_CONFIG_MONO_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL,
        (char *)NULL, 0, 0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_BITMAP_TAGS, Tk_Offset(RbcMarker, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_BITMAP, "-bitmap", "bitmap", "Bitmap",
            DEF_MARKER_BITMAP, Tk_Offset(BitmapMarker, srcBitmap),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords",
            DEF_MARKER_COORDS, Tk_Offset(RbcMarker, worldPts),
        TK_CONFIG_NULL_OK, &coordsOption},
    {TK_CONFIG_STRING, "-element", "element", "Element",
            DEF_MARKER_ELEMENT, Tk_Offset(RbcMarker, elemName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *)NULL,
        (char *)NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-fill", "background", (char *)NULL,
        (char *)NULL, 0, 0},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_MARKER_FOREGROUND, Tk_Offset(BitmapMarker, outlineColor),
        TK_CONFIG_COLOR_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
            DEF_MARKER_FG_MONO, Tk_Offset(BitmapMarker, outlineColor),
        TK_CONFIG_MONO_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
            DEF_MARKER_HIDE, Tk_Offset(RbcMarker, hidden),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_MARKER_MAP_X, Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_MARKER_MAP_Y, Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL,
        DEF_MARKER_NAME, Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-outline", "foreground", (char *)NULL,
        (char *)NULL, 0, 0},
    {TK_CONFIG_DOUBLE, "-rotate", "rotate", "Rotate",
            DEF_MARKER_ROTATE, Tk_Offset(BitmapMarker, rotate),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-state", "state", "State",
            DEF_MARKER_STATE, Tk_Offset(RbcMarker, state),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under",
            DEF_MARKER_UNDER, Tk_Offset(RbcMarker, drawUnder),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset",
            DEF_MARKER_X_OFFSET, Tk_Offset(RbcMarker, xOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset",
            DEF_MARKER_Y_OFFSET, Tk_Offset(RbcMarker, yOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/*
 * -------------------------------------------------------------------
 *
 * ImageMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type of marker */
    RbcGraph *graph;           /* Graph marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* Indicates if the marker is
                                * currently hidden or not. */

    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;
    RbcPoint2D *worldPts;      /* Position of marker in world (graph)
                                * coordinates. If 2 pairs of X-Y
                                * coordinates are specified, then the
                                * image is resized to fit this area.
                                * Otherwise if 1 pair, then the image
                                * is positioned at the coordinate at
                                * its normal size. */
    int nWorldPts;             /* Number of points */

    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset from anchor */

    MarkerClass *classPtr;

    int state;

    /* Image specific attributes */
    char *imageName;           /* Name of image to be displayed. */
    Tk_Image tkImage;          /* Tk image to be displayed. */
    Tk_Anchor anchor;          /* Indicates how to translate the given
                                * marker position. */
    RbcPoint2D anchorPos;      /* Translated anchor point. */
    int width, height;         /* Dimensions of the image */
    Tk_Image tmpImage;
    Pixmap pixmap;             /* Pixmap containing the scaled image */
    RbcColorImage *srcImage;
    GC  gc;

} ImageMarker;

static Tk_ConfigSpec imageConfigSpecs[] = {
    {TK_CONFIG_ANCHOR, "-anchor", "anchor", "Anchor",
        DEF_MARKER_ANCHOR, Tk_Offset(ImageMarker, anchor), 0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_IMAGE_TAGS, Tk_Offset(RbcMarker, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords",
            DEF_MARKER_COORDS, Tk_Offset(RbcMarker, worldPts),
        TK_CONFIG_NULL_OK, &coordsOption},
    {TK_CONFIG_STRING, "-element", "element", "Element",
            DEF_MARKER_ELEMENT, Tk_Offset(RbcMarker, elemName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
            DEF_MARKER_HIDE, Tk_Offset(RbcMarker, hidden),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-image", "image", "Image",
        (char *)NULL, Tk_Offset(ImageMarker, imageName), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_MARKER_MAP_X, Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_MARKER_MAP_Y, Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL,
        DEF_MARKER_NAME, Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-state", "state", "State",
            DEF_MARKER_STATE, Tk_Offset(RbcMarker, state),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under",
            DEF_MARKER_UNDER, Tk_Offset(RbcMarker, drawUnder),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset",
            DEF_MARKER_X_OFFSET, Tk_Offset(RbcMarker, xOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset",
            DEF_MARKER_Y_OFFSET, Tk_Offset(RbcMarker, yOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/*
 * -------------------------------------------------------------------
 *
 * LineMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type is "linemarker" */
    RbcGraph *graph;           /* Graph marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* Indicates if the marker is currently
                                * hidden or not. */

    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;

    RbcPoint2D *worldPts;      /* Position of marker (X-Y coordinates) in
                                * world (graph) coordinates. */
    int nWorldPts;             /* Number of points */

    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset */

    MarkerClass *classPtr;

    int state;

    /* Line specific attributes */
    XColor *fillColor;
    XColor *outlineColor;      /* Foreground and background colors */

    int lineWidth;             /* Line width. */
    int capStyle;              /* Cap style. */
    int joinStyle;             /* Join style. */
    RbcDashes dashes;          /* Dash list values (max 11) */

    GC  gc;                    /* Private graphic context */

    RbcSegment2D *segments;    /* Malloc'ed array of points.
                                * Represents individual line segments
                                * (2 points per segment) comprising
                                * the mapped line.  The segments may
                                * not necessarily be connected after
                                * clipping. */
    int nSegments;             /* # segments in the above array. */

    int xor;
    int xorState;              /* State of the XOR drawing. Indicates
                                * if the marker is currently drawn. */
} LineMarker;

static Tk_ConfigSpec lineConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_LINE_TAGS, Tk_Offset(RbcMarker, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CAP_STYLE, "-cap", "cap", "Cap",
            DEF_MARKER_CAP_STYLE, Tk_Offset(LineMarker, capStyle),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords",
            DEF_MARKER_COORDS, Tk_Offset(RbcMarker, worldPts),
        TK_CONFIG_NULL_OK, &coordsOption},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes",
            DEF_MARKER_DASHES, Tk_Offset(LineMarker, dashes),
        TK_CONFIG_NULL_OK, &rbcDashesOption},
    {TK_CONFIG_CUSTOM, "-dashoffset", "dashOffset", "DashOffset",
            DEF_MARKER_DASH_OFFSET, Tk_Offset(LineMarker, dashes.offset),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_STRING, "-element", "element", "Element",
            DEF_MARKER_ELEMENT, Tk_Offset(RbcMarker, elemName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-fill", "fill", "Fill",
        (char *)NULL, Tk_Offset(LineMarker, fillColor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_JOIN_STYLE, "-join", "join", "Join",
            DEF_MARKER_JOIN_STYLE, Tk_Offset(LineMarker, joinStyle),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_MARKER_LINE_WIDTH, Tk_Offset(LineMarker, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
            DEF_MARKER_HIDE, Tk_Offset(RbcMarker, hidden),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_MARKER_MAP_X, Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_MARKER_MAP_Y, Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL,
        DEF_MARKER_NAME, Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-outline", "outline", "Outline",
            DEF_MARKER_OUTLINE_COLOR, Tk_Offset(LineMarker, outlineColor),
        TK_CONFIG_COLOR_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-outline", "outline", "Outline",
            DEF_MARKER_OUTLINE_MONO, Tk_Offset(LineMarker, outlineColor),
        TK_CONFIG_MONO_ONLY | TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-state", "state", "State",
            DEF_MARKER_STATE, Tk_Offset(RbcMarker, state),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under",
            DEF_MARKER_UNDER, Tk_Offset(RbcMarker, drawUnder),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset",
            DEF_MARKER_X_OFFSET, Tk_Offset(RbcMarker, xOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-xor", "xor", "Xor",
            DEF_MARKER_XOR, Tk_Offset(LineMarker, xor),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset",
            DEF_MARKER_Y_OFFSET, Tk_Offset(RbcMarker, yOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/*
 * -------------------------------------------------------------------
 *
 * PolygonMarker --
 *
 * -------------------------------------------------------------------
 */
typedef struct {
    char *name;                /* Identifier for marker */
    Tk_Uid classUid;           /* Type of marker */
    RbcGraph *graph;           /* Graph marker belongs to */
    unsigned int flags;
    char **tags;
    int hidden;                /* Indicates if the marker is currently
                                * hidden or not. */

    Tcl_HashEntry *hashPtr;
    RbcChainLink *linkPtr;

    RbcPoint2D *worldPts;      /* Position of marker (X-Y coordinates) in
                                * world (graph) coordinates. */
    int nWorldPts;             /* Number of points */

    char *elemName;            /* Element associated with marker */
    RbcAxis2D axes;
    int drawUnder;             /* If non-zero, draw the marker
                                * underneath any elements. There can
                                * be a performance because the graph
                                * must be redraw entirely each time
                                * this marker is redrawn. */
    int clipped;               /* Indicates if the marker is totally
                                * clipped by the plotting area. */
    int xOffset, yOffset;      /* Pixel offset */

    MarkerClass *classPtr;

    int state;

    /* Polygon specific attributes and fields */

    RbcPoint2D *screenPts;

    RbcColorPair outline;
    RbcColorPair fill;

    Pixmap stipple;            /* Stipple pattern to fill the polygon. */
    int lineWidth;             /* Width of polygon outline. */
    int capStyle;
    int joinStyle;
    RbcDashes dashes;          /* List of dash values.  Indicates how
                                * draw the dashed line.  If no dash
                                * values are provided, or the first value
                                * is zero, then the line is drawn solid. */

    GC  outlineGC;             /* Graphics context to draw the outline of
                                * the polygon. */
    GC  fillGC;                /* Graphics context to draw the filled
                                * polygon. */

    RbcPoint2D *fillPts;       /* Malloc'ed array of points used to draw
                                * the filled polygon. These points may
                                * form a degenerate polygon after clipping.
                                */

    int nFillPts;              /* # points in the above array. */

    RbcSegment2D *outlinePts;  /* Malloc'ed array of points.
                                * Represents individual line segments
                                * (2 points per segment) comprising
                                * the outline of the polygon.  The
                                * segments may not necessarily be
                                * closed or connected after clipping. */

    int nOutlinePts;           /* # points in the above array. */

    int xor;
    int xorState;              /* State of the XOR drawing. Indicates
                                * if the marker is visible. We have
                                * to drawn it again to erase it. */
} PolygonMarker;

static Tk_ConfigSpec polygonConfigSpecs[] = {
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
            DEF_MARKER_POLYGON_TAGS, Tk_Offset(RbcMarker, tags),
        TK_CONFIG_NULL_OK, &rbcListOption},
    {TK_CONFIG_CAP_STYLE, "-cap", "cap", "Cap",
            DEF_MARKER_CAP_STYLE, Tk_Offset(PolygonMarker, capStyle),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-coords", "coords", "Coords",
            DEF_MARKER_COORDS, Tk_Offset(RbcMarker, worldPts),
        TK_CONFIG_NULL_OK, &coordsOption},
    {TK_CONFIG_CUSTOM, "-dashes", "dashes", "Dashes",
            DEF_MARKER_DASHES, Tk_Offset(PolygonMarker, dashes),
        TK_CONFIG_NULL_OK, &rbcDashesOption},
    {TK_CONFIG_STRING, "-element", "element", "Element",
            DEF_MARKER_ELEMENT, Tk_Offset(RbcMarker, elemName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_MARKER_FILL_COLOR, Tk_Offset(PolygonMarker, fill),
        TK_CONFIG_COLOR_ONLY | TK_CONFIG_NULL_OK, &rbcColorPairOption},
    {TK_CONFIG_CUSTOM, "-fill", "fill", "Fill",
            DEF_MARKER_FILL_MONO, Tk_Offset(PolygonMarker, fill),
        TK_CONFIG_MONO_ONLY | TK_CONFIG_NULL_OK, &rbcColorPairOption},
    {TK_CONFIG_JOIN_STYLE, "-join", "join", "Join",
            DEF_MARKER_JOIN_STYLE, Tk_Offset(PolygonMarker, joinStyle),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
            DEF_MARKER_LINE_WIDTH, Tk_Offset(PolygonMarker, lineWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-hide", "hide", "Hide",
            DEF_MARKER_HIDE, Tk_Offset(RbcMarker, hidden),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-mapx", "mapX", "MapX",
        DEF_MARKER_MAP_X, Tk_Offset(RbcMarker, axes.x), 0, &rbcXAxisOption},
    {TK_CONFIG_CUSTOM, "-mapy", "mapY", "MapY",
        DEF_MARKER_MAP_Y, Tk_Offset(RbcMarker, axes.y), 0, &rbcYAxisOption},
    {TK_CONFIG_STRING, "-name", (char *)NULL, (char *)NULL,
        DEF_MARKER_NAME, Tk_Offset(RbcMarker, name), TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_MARKER_OUTLINE_COLOR, Tk_Offset(PolygonMarker, outline),
        TK_CONFIG_COLOR_ONLY | TK_CONFIG_NULL_OK, &rbcColorPairOption},
    {TK_CONFIG_CUSTOM, "-outline", "outline", "Outline",
            DEF_MARKER_OUTLINE_MONO, Tk_Offset(PolygonMarker, outline),
        TK_CONFIG_MONO_ONLY | TK_CONFIG_NULL_OK, &rbcColorPairOption},
    {TK_CONFIG_CUSTOM, "-state", "state", "State",
            DEF_MARKER_STATE, Tk_Offset(RbcMarker, state),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcStateOption},
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple",
            DEF_MARKER_STIPPLE, Tk_Offset(PolygonMarker, stipple),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-under", "under", "Under",
            DEF_MARKER_UNDER, Tk_Offset(RbcMarker, drawUnder),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-xoffset", "xOffset", "XOffset",
            DEF_MARKER_X_OFFSET, Tk_Offset(RbcMarker, xOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-xor", "xor", "Xor",
            DEF_MARKER_XOR, Tk_Offset(PolygonMarker, xor),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_PIXELS, "-yoffset", "yOffset", "YOffset",
            DEF_MARKER_Y_OFFSET, Tk_Offset(RbcMarker, yOffset),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

static MarkerCreateProc CreateBitmapMarker,
    CreateLineMarker,
    CreateImageMarker,
    CreatePolygonMarker, CreateTextMarker, CreateWindowMarker;
static MarkerDrawProc DrawBitmapMarker,
    DrawLineMarker,
    DrawImageMarker, DrawPolygonMarker, DrawTextMarker, DrawWindowMarker;
static MarkerFreeProc FreeBitmapMarker,
    FreeLineMarker,
    FreeImageMarker, FreePolygonMarker, FreeTextMarker, FreeWindowMarker;
static MarkerConfigProc ConfigureBitmapMarker,
    ConfigureLineMarker,
    ConfigureImageMarker,
    ConfigurePolygonMarker, ConfigureTextMarker, ConfigureWindowMarker;
static MarkerMapProc MapBitmapMarker,
    MapLineMarker,
    MapImageMarker, MapPolygonMarker, MapTextMarker, MapWindowMarker;
static MarkerPostScriptProc BitmapMarkerToPostScript,
    LineMarkerToPostScript,
    ImageMarkerToPostScript,
    PolygonMarkerToPostScript, TextMarkerToPostScript, WindowMarkerToPostScript;
static MarkerPointProc PointInBitmapMarker,
    PointInLineMarker,
    PointInImageMarker,
    PointInPolygonMarker, PointInTextMarker, PointInWindowMarker;
static MarkerRegionProc RegionInBitmapMarker,
    RegionInLineMarker,
    RegionInImageMarker,
    RegionInPolygonMarker, RegionInTextMarker, RegionInWindowMarker;
static Tk_ImageChangedProc ImageChangedProc;

static int BoxesDontOverlap(
    RbcGraph * graph,
    RbcExtents2D * extsPtr);
static int GetCoordinate(
    Tcl_Interp * interp,
    const char *expr,
    double *valuePtr);
static const char *PrintCoordinate(
    Tcl_Interp * interp,
    double x);
static int ParseCoordinates(
    Tcl_Interp * interp,
    RbcMarker * markerPtr,
    int nExprs,
    const char **exprArr);
static double HMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double x);
static double VMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double y);
static RbcPoint2D MapPoint(
    RbcGraph * graph,
    RbcPoint2D * pointPtr,
    RbcAxis2D * axesPtr);
static RbcMarker *CreateMarker(
    RbcGraph * graph,
    const char *name,
    Tk_Uid classUid);
static void DestroyMarker(
    RbcMarker * markerPtr);
static int NameToMarker(
    RbcGraph * graph,
    Tk_Window tkWin,
    const char *name,
    RbcMarker ** markerPtrPtr);
static int RenameMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr,
    char *oldName,
    char *newName);
static int NamesOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int CreateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int DeleteOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int RelinkOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int FindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ExistsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int TypeOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static void ChildEventProc(
    ClientData clientData,
    XEvent * eventPtr);
static void ChildGeometryProc(
    ClientData clientData,
    Tk_Window tkwin);
static void ChildCustodyProc(
    ClientData clientData,
    Tk_Window tkwin);

static MarkerClass bitmapMarkerClass = {
    bitmapConfigSpecs,
    ConfigureBitmapMarker,
    DrawBitmapMarker,
    FreeBitmapMarker,
    MapBitmapMarker,
    PointInBitmapMarker,
    RegionInBitmapMarker,
    BitmapMarkerToPostScript,
};

static MarkerClass imageMarkerClass = {
    imageConfigSpecs,
    ConfigureImageMarker,
    DrawImageMarker,
    FreeImageMarker,
    MapImageMarker,
    PointInImageMarker,
    RegionInImageMarker,
    ImageMarkerToPostScript,
};

static MarkerClass lineMarkerClass = {
    lineConfigSpecs,
    ConfigureLineMarker,
    DrawLineMarker,
    FreeLineMarker,
    MapLineMarker,
    PointInLineMarker,
    RegionInLineMarker,
    LineMarkerToPostScript,
};

static MarkerClass polygonMarkerClass = {
    polygonConfigSpecs,
    ConfigurePolygonMarker,
    DrawPolygonMarker,
    FreePolygonMarker,
    MapPolygonMarker,
    PointInPolygonMarker,
    RegionInPolygonMarker,
    PolygonMarkerToPostScript,
};

static MarkerClass textMarkerClass = {
    textConfigSpecs,
    ConfigureTextMarker,
    DrawTextMarker,
    FreeTextMarker,
    MapTextMarker,
    PointInTextMarker,
    RegionInTextMarker,
    TextMarkerToPostScript,
};

static MarkerClass windowMarkerClass = {
    windowConfigSpecs,
    ConfigureWindowMarker,
    DrawWindowMarker,
    FreeWindowMarker,
    MapWindowMarker,
    PointInWindowMarker,
    RegionInWindowMarker,
    WindowMarkerToPostScript,
};

/*
 * ----------------------------------------------------------------------
 *
 * BoxesDontOverlap --
 *
 *      Tests if the bounding box of a marker overlaps the plotting
 *      area in any way.  If so, the marker will be drawn.  Just do a
 *      min/max test on the extents of both boxes.
 *
 *      Note: It's assumed that the extents of the bounding box lie
 *            within the area.  So for a 10x10 rectangle, bottom and
 *            left would be 9.
 *
 * Results:
 *      Returns 0 is the marker is visible in the plotting area, and
 *      1 otherwise (marker is clipped).
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
BoxesDontOverlap(
    RbcGraph * graph,
    RbcExtents2D * extsPtr)
{
    assert(extsPtr->right >= extsPtr->left);
    assert(extsPtr->bottom >= extsPtr->top);
    assert(graph->right >= graph->left);
    assert(graph->bottom >= graph->top);

    return (((double)graph->right < extsPtr->left) ||
        ((double)graph->bottom < extsPtr->top) ||
        (extsPtr->right < (double)graph->left) ||
        (extsPtr->bottom < (double)graph->top));
}

/*
 * ----------------------------------------------------------------------
 *
 * GetCoordinate --
 *
 *      Convert the expression string into a floating point value. The
 *      only reason we use this routine instead of RbcExprDouble is to
 *      handle "elastic" bounds.  That is, convert the strings "-Inf",
 *      "Inf" into -(DBL_MAX) and DBL_MAX respectively.
 *
 * Results:
 *      The return value is a standard Tcl result.  The value of the
 *      expression is passed back via valuePtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
GetCoordinate(
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    const char *expr,          /* Numeric expression string to parse */
    double *valuePtr)
{              /* Real-valued result of expression */
    char c;

    c = expr[0];
    if((c == 'I') && (strcmp(expr, "Inf") == 0)) {
        *valuePtr = DBL_MAX;    /* Elastic upper bound */
    } else if((c == '-') && (expr[1] == 'I') && (strcmp(expr, "-Inf") == 0)) {
        *valuePtr = -DBL_MAX;   /* Elastic lower bound */
    } else if((c == '+') && (expr[1] == 'I') && (strcmp(expr, "+Inf") == 0)) {
        *valuePtr = DBL_MAX;    /* Elastic upper bound */
    } else if(Tcl_ExprDouble(interp, expr, valuePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * PrintCoordinate --
 *
 *      Convert the floating point value into its string
 *      representation.  The only reason this routine is used in
 *      instead of sprintf, is to handle the "elastic" bounds.  That
 *      is, convert the values DBL_MAX and -(DBL_MAX) into "+Inf" and
 *      "-Inf" respectively.
 *
 * Results:
 *      The return value is a standard Tcl result.  The string of the
 *      expression is passed back via string.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------- */
static const char *
PrintCoordinate(
    Tcl_Interp * interp,
    double x)
{              /* Numeric value */
    if(x == DBL_MAX) {
        return "+Inf";
    } else if(x == -DBL_MAX) {
        return "-Inf";
    } else {
    static char string[TCL_DOUBLE_SPACE + 1];

        Tcl_PrintDouble(interp, (double)x, string);
        return string;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ParseCoordinates --
 *
 *      The Tcl coordinate list is converted to their floating point
 *      values. It will then replace the current marker coordinates.
 *
 *      Since different marker types require different number of
 *      coordinates this must be checked here.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side effects:
 *      If the marker coordinates are reset, the graph is eventually
 *      redrawn with at the new marker coordinates.
 *
 * ----------------------------------------------------------------------
 */
static int
ParseCoordinates(
    Tcl_Interp * interp,
    RbcMarker * markerPtr,
    int nExprs,
    const char **exprArr)
{
    int nWorldPts;
    int minArgs, maxArgs;
    RbcPoint2D *worldPts;
    register int i;
    register RbcPoint2D *pointPtr;
    double x, y;

    if(nExprs == 0) {
        return TCL_OK;
    }
    if(nExprs & 1) {
        Tcl_AppendResult(interp, "odd number of marker coordinates specified",
            (char *)NULL);
        return TCL_ERROR;
    }
    if(markerPtr->classUid == rbcLineMarkerUid) {
        minArgs = 4, maxArgs = 0;
    } else if(markerPtr->classUid == rbcPolygonMarkerUid) {
        minArgs = 6, maxArgs = 0;
    } else if((markerPtr->classUid == rbcWindowMarkerUid) ||
        (markerPtr->classUid == rbcTextMarkerUid)) {
        minArgs = 2, maxArgs = 2;
    } else if((markerPtr->classUid == rbcImageMarkerUid) ||
        (markerPtr->classUid == rbcBitmapMarkerUid)) {
        minArgs = 2, maxArgs = 4;
    } else {
        Tcl_AppendResult(interp, "unknown marker type", (char *)NULL);
        return TCL_ERROR;
    }

    if(nExprs < minArgs) {
        Tcl_AppendResult(interp, "too few marker coordinates specified",
            (char *)NULL);
        return TCL_ERROR;
    }
    if((maxArgs > 0) && (nExprs > maxArgs)) {
        Tcl_AppendResult(interp, "too many marker coordinates specified",
            (char *)NULL);
        return TCL_ERROR;
    }
    nWorldPts = nExprs / 2;
    worldPts = (RbcPoint2D *) ckalloc(nWorldPts * sizeof(RbcPoint2D));
    if(worldPts == NULL) {
        Tcl_AppendResult(interp, "can't allocate new coordinate array",
            (char *)NULL);
        return TCL_ERROR;
    }

    /* Don't free the old coordinate array until we've parsed the new
     * coordinates without errors.  */
    pointPtr = worldPts;
    for(i = 0; i < nExprs; i += 2) {
        if((GetCoordinate(interp, exprArr[i], &x) != TCL_OK) ||
            (GetCoordinate(interp, exprArr[i + 1], &y) != TCL_OK)) {
            ckfree((char *)worldPts);
            return TCL_ERROR;
        }
        pointPtr->x = x, pointPtr->y = y;
        pointPtr++;
    }
    if(markerPtr->worldPts != NULL) {
        ckfree((char *)markerPtr->worldPts);
    }
    markerPtr->worldPts = worldPts;
    markerPtr->nWorldPts = nWorldPts;
    markerPtr->flags |= RBC_MAP_ITEM;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToCoordinates --
 *
 *      Given a Tcl list of numeric expression representing the
 *      element values, convert into an array of floating point
 *      values. In addition, the minimum and maximum values are saved.
 *      Since elastic values are allow (values which translate to the
 *      min/max of the graph), we must try to get the non-elastic
 *      minimum and maximum.
 *
 * Results:
 *      The return value is a standard Tcl result.  The vector is
 *      passed back via the vecPtr.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
StringToCoordinates(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* Tcl list of numeric expressions */
    char *widgRec,             /* Marker record */
    int offset)
{              /* Not used. */
    RbcMarker *markerPtr = (RbcMarker *) widgRec;
    int nExprs;
    const char **exprArr;
    int result;

    nExprs = 0;
    if((string != NULL) &&
        (Tcl_SplitList(interp, string, &nExprs, &exprArr) != TCL_OK)) {
        return TCL_ERROR;
    }
    if(nExprs == 0) {
        if(markerPtr->worldPts != NULL) {
            ckfree((char *)markerPtr->worldPts);
            markerPtr->worldPts = NULL;
        }
        markerPtr->nWorldPts = 0;
        return TCL_OK;
    }
    result = ParseCoordinates(interp, markerPtr, nExprs, exprArr);
    ckfree((char *)exprArr);
    return result;
}

/*
 * ----------------------------------------------------------------------
 *
 * CoordinatesToString --
 *
 *      Convert the vector of floating point values into a Tcl list.
 *
 * Results:
 *      The string representation of the vector is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static const char *
CoordinatesToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Marker record */
    int offset,                /* Not used. */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    RbcMarker *markerPtr = (RbcMarker *) widgRec;
    Tcl_Interp *interp;
    Tcl_DString dString;
    char *result;
    register int i;
    register RbcPoint2D *p;

    if(markerPtr->nWorldPts < 1) {
        return "";
    }
    interp = markerPtr->graph->interp;

    Tcl_DStringInit(&dString);
    p = markerPtr->worldPts;
    for(i = 0; i < markerPtr->nWorldPts; i++) {
        Tcl_DStringAppendElement(&dString, PrintCoordinate(interp, p->x));
        Tcl_DStringAppendElement(&dString, PrintCoordinate(interp, p->y));
        p++;
    }
    result = Tcl_DStringValue(&dString);

    /*
     * If memory wasn't allocated for the dynamic string, do it here (it's
     * currently on the stack), so that Tcl can free it normally.
     */
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 * ----------------------------------------------------------------------
 *
 * HMap --
 *
 *      Map the given graph coordinate value to its axis, returning a
 *      window position.
 *
 * Results:
 *      Returns a floating point number representing the window
 *      coordinate position on the given axis.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static double
HMap(
    RbcGraph * graph,
    RbcAxis * axisPtr,
    double x)
{
    register double norm;

    if(x == DBL_MAX) {
        norm = 1.0;
    } else if(x == -DBL_MAX) {
        norm = 0.0;
    } else {
        if(axisPtr->logScale) {
            if(x > 0.0) {
                x = log10(x);
            } else if(x < 0.0) {
                x = 0.0;
            }
        }
        norm = NORMALIZE(axisPtr, x);
    }
    if(axisPtr->descending) {
        norm = 1.0 - norm;
    }
    /* Horizontal transformation */
    return ((norm * graph->hRange) + graph->hOffset);
}

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

    if(y == DBL_MAX) {
        norm = 1.0;
    } else if(y == -DBL_MAX) {
        norm = 0.0;
    } else {
        if(axisPtr->logScale) {
            if(y > 0.0) {
                y = log10(y);
            } else if(y < 0.0) {
                y = 0.0;
            }
        }
        norm = NORMALIZE(axisPtr, y);
    }
    if(axisPtr->descending) {
        norm = 1.0 - norm;
    }
    /* Vertical transformation */
    return (((1.0 - norm) * graph->vRange) + graph->vOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * MapPoint --
 *
 *      Maps the given graph x,y coordinate values to a window position.
 *
 * Results:
 *      Returns a XPoint structure containing the window coordinates
 *      of the given graph x,y coordinate.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static RbcPoint2D
MapPoint(
    RbcGraph * graph,
    RbcPoint2D * pointPtr,     /* Graph X-Y coordinate. */
    RbcAxis2D * axesPtr)
{              /* Specifies which axes to use */
RbcPoint2D result;

    if(graph->inverted) {
        result.x = HMap(graph, axesPtr->y, pointPtr->y);
        result.y = VMap(graph, axesPtr->x, pointPtr->x);
    } else {
        result.x = HMap(graph, axesPtr->x, pointPtr->x);
        result.y = VMap(graph, axesPtr->y, pointPtr->y);
    }
    return result;      /* Result is screen coordinate. */
}

/*
 *----------------------------------------------------------------------
 *
 * CreateMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static RbcMarker *
CreateMarker(
    RbcGraph * graph,
    const char *name,
    Tk_Uid classUid)
{
    RbcMarker *markerPtr;

    /* Create the new marker based upon the given type */
    if(classUid == rbcBitmapMarkerUid) {
        markerPtr = CreateBitmapMarker();       /* bitmap */
    } else if(classUid == rbcLineMarkerUid) {
        markerPtr = CreateLineMarker(); /* line */
    } else if(classUid == rbcImageMarkerUid) {
        markerPtr = CreateImageMarker();        /* image */
    } else if(classUid == rbcTextMarkerUid) {
        markerPtr = CreateTextMarker(); /* text */
    } else if(classUid == rbcPolygonMarkerUid) {
        markerPtr = CreatePolygonMarker();      /* polygon */
    } else if(classUid == rbcWindowMarkerUid) {
        markerPtr = CreateWindowMarker();       /* window */
    } else {
        return NULL;
    }
    assert(markerPtr);
    markerPtr->graph = graph;
    markerPtr->hidden = markerPtr->drawUnder = FALSE;
    markerPtr->flags |= RBC_MAP_ITEM;
    markerPtr->name = RbcStrdup(name);
    markerPtr->classUid = classUid;
    return markerPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;

    if(markerPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    /* Free the resources allocated for the particular type of marker */
    (*markerPtr->classPtr->freeProc) (graph, markerPtr);
    if(markerPtr->worldPts != NULL) {
        ckfree((char *)markerPtr->worldPts);
    }
    RbcDeleteBindings(graph->bindTable, markerPtr);
    Tk_FreeOptions(markerPtr->classPtr->configSpecs, (char *)markerPtr,
        graph->display, 0);
    if(markerPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(markerPtr->hashPtr);
    }
    if(markerPtr->linkPtr != NULL) {
        RbcChainDeleteLink(graph->markers.displayList, markerPtr->linkPtr);
    }
    if(markerPtr->name != NULL) {
        ckfree((char *)markerPtr->name);
    }
    if(markerPtr->elemName != NULL) {
        ckfree((char *)markerPtr->elemName);
    }
    if(markerPtr->tags != NULL) {
        ckfree((char *)markerPtr->tags);
    }
    ckfree((char *)markerPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureBitmapMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or reconfigure)
 *      a bitmap marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as bitmap pixmap, colors,
 *      rotation, etc. get set for markerPtr; old resources get freed,
 *      if there were any.  The marker is eventually redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureBitmapMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;
GC  newGC;
XGCValues gcValues;
unsigned long gcMask;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(bmPtr->srcBitmap == None) {
        return TCL_OK;
    }
    if(bmPtr->destBitmap == None) {
        bmPtr->destBitmap = bmPtr->srcBitmap;
    }
    bmPtr->theta = FMOD(bmPtr->rotate, 360.0);
    if(bmPtr->theta < 0.0) {
        bmPtr->theta += 360.0;
    }
    gcMask = 0;
    if(bmPtr->outlineColor != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = bmPtr->outlineColor->pixel;
    }
    if(bmPtr->fillColor != NULL) {
        gcValues.background = bmPtr->fillColor->pixel;
        gcMask |= GCBackground;
    } else {
        gcValues.clip_mask = bmPtr->srcBitmap;
        gcMask |= GCClipMask;
    }

    /* Note that while this is a "shared" GC, we're going to change
     * the clip origin right before the bitmap is drawn anyways.  This
     * assumes that any drawing code using this GC (with GCClipMask
     * set) is going to want to set the clip origin anyways.  */
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(bmPtr->gc != NULL) {
        Tk_FreeGC(graph->display, bmPtr->gc);
    }
    bmPtr->gc = newGC;

    /* Create background GC color */

    if(bmPtr->fillColor != NULL) {
        gcValues.foreground = bmPtr->fillColor->pixel;
        newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
        if(bmPtr->fillGC != NULL) {
            Tk_FreeGC(graph->display, bmPtr->fillGC);
        }
        bmPtr->fillGC = newGC;
    }
    bmPtr->flags |= RBC_MAP_ITEM;
    if(bmPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapBitmapMarker --
 *
 *      This procedure gets called each time the layout of the graph
 *      changes.  The x, y window coordinates of the bitmap marker are
 *      saved in the marker structure.
 *
 *      Additionly, if no background color was specified, the
 *      GCTileStipXOrigin and GCTileStipYOrigin attributes are set in
 *      the private GC.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Window coordinates are saved and if no background color was
 *      set, the GC stipple origins are changed to calculated window
 *      coordinates.
 *
 * ----------------------------------------------------------------------
 */
static void
MapBitmapMarker(
    RbcMarker * markerPtr)
{
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;
RbcExtents2D exts;
RbcGraph *graph = markerPtr->graph;
RbcPoint2D anchorPos;
RbcPoint2D corner1, corner2;
int destWidth, destHeight;
int srcWidth, srcHeight;
register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if(bmPtr->srcBitmap == None) {
        return;
    }
    if(bmPtr->destBitmap != bmPtr->srcBitmap) {
        Tk_FreePixmap(graph->display, bmPtr->destBitmap);
        bmPtr->destBitmap = bmPtr->srcBitmap;
    }
    /*
     * Collect the coordinates.  The number of coordinates will determine
     * the calculations to be made.
     *
     *     x1 y1        A single pair of X-Y coordinates.  They represent
     *                  the anchor position of the bitmap.
     *
     *  x1 y1 x2 y2     Two pairs of X-Y coordinates.  They represent
     *                  two opposite corners of a bounding rectangle. The
     *                  bitmap is possibly rotated and scaled to fit into
     *                  this box.
     *
     */
    Tk_SizeOfBitmap(graph->display, bmPtr->srcBitmap, &srcWidth, &srcHeight);
    corner1 = MapPoint(graph, bmPtr->worldPts, &bmPtr->axes);
    if(bmPtr->nWorldPts > 1) {
double hold;

        corner2 = MapPoint(graph, bmPtr->worldPts + 1, &bmPtr->axes);
        /* Flip the corners if necessary */
        if(corner1.x > corner2.x) {
            hold = corner1.x, corner1.x = corner2.x, corner2.x = hold;
        }
        if(corner1.y > corner2.y) {
            hold = corner1.y, corner1.y = corner2.y, corner2.y = hold;
        }
    } else {
        corner2.x = corner1.x + srcWidth - 1;
        corner2.y = corner1.y + srcHeight - 1;
    }
    destWidth = (int)(corner2.x - corner1.x) + 1;
    destHeight = (int)(corner2.y - corner1.y) + 1;

    if(bmPtr->nWorldPts == 1) {
        anchorPos = RbcTranslatePoint(&corner1, destWidth, destHeight,
            bmPtr->anchor);
    } else {
        anchorPos = corner1;
    }
    anchorPos.x += bmPtr->xOffset;
    anchorPos.y += bmPtr->yOffset;

    /* Check if the bitmap sits at least partially in the plot area. */
    exts.left = anchorPos.x;
    exts.top = anchorPos.y;
    exts.right = anchorPos.x + destWidth - 1;
    exts.bottom = anchorPos.y + destHeight - 1;

    bmPtr->clipped = BoxesDontOverlap(graph, &exts);
    if(bmPtr->clipped) {
        return; /* Bitmap is offscreen. Don't generate
                 * rotated or scaled bitmaps. */
    }

    /*
     * Scale the bitmap if necessary. It's a little tricky because we
     * only want to scale what's visible on the screen, not the entire
     * bitmap.
     */
    if((bmPtr->theta != 0.0) || (destWidth != srcWidth) ||
        (destHeight != srcHeight)) {
int regionWidth, regionHeight;
RbcRegion2D region;            /* Indicates the portion of the scaled
                                * bitmap that we want to display. */
double left, right, top, bottom;

        /*
         * Determine the region of the bitmap visible in the plot area.
         */
        left = MAX(graph->left, exts.left);
        right = MIN(graph->right, exts.right);
        top = MAX(graph->top, exts.top);
        bottom = MIN(graph->bottom, exts.bottom);

        region.left = region.top = 0;
        if(graph->left > exts.left) {
            region.left = (int)(graph->left - exts.left);
        }
        if(graph->top > exts.top) {
            region.top = (int)(graph->top - exts.top);
        }
        regionWidth = (int)(right - left) + 1;
        regionHeight = (int)(bottom - top) + 1;
        region.right = region.left + (int)(right - left);
        region.bottom = region.top + (int)(bottom - top);

        anchorPos.x = left;
        anchorPos.y = top;
        bmPtr->destBitmap = RbcScaleRotateBitmapRegion(*(graph->win),
            bmPtr->srcBitmap, srcWidth, srcHeight,
            region.left, region.top, regionWidth, regionHeight,
            destWidth, destHeight, bmPtr->theta);
        bmPtr->destWidth = regionWidth;
        bmPtr->destHeight = regionHeight;
    } else {
        bmPtr->destWidth = srcWidth;
        bmPtr->destHeight = srcHeight;
        bmPtr->destBitmap = bmPtr->srcBitmap;
    }
    bmPtr->anchorPos = anchorPos;
    {
double xScale, yScale;
double tx, ty;
double rotWidth, rotHeight;
RbcPoint2D polygon[5];
int n;

        /*
         * Compute a polygon to represent the background area of the bitmap.
         * This is needed for backgrounds of arbitrarily rotated bitmaps.
         * We also use it to print a background in PostScript.
         */
        RbcGetBoundingBox(srcWidth, srcHeight, bmPtr->theta, &rotWidth,
            &rotHeight, polygon);
        xScale = (double)destWidth / rotWidth;
        yScale = (double)destHeight / rotHeight;

        /*
         * Adjust each point of the polygon. Both scale it to the new size
         * and translate it to the actual screen position of the bitmap.
         */
        tx = exts.left + destWidth * 0.5;
        ty = exts.top + destHeight * 0.5;
        for(i = 0; i < 4; i++) {
            polygon[i].x = (polygon[i].x * xScale) + tx;
            polygon[i].y = (polygon[i].y * yScale) + ty;
        }
        RbcGraphExtents(graph, &exts);
        n = RbcPolyRectClip(&exts, polygon, 4, bmPtr->outline);
        assert(n <= MAX_OUTLINE_POINTS);
        if(n < 3) {
            memcpy(&bmPtr->outline, polygon, sizeof(RbcPoint2D) * 4);
            bmPtr->nOutlinePts = 4;
        } else {
            bmPtr->nOutlinePts = n;
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * PointInBitmapMarker --
 *
 *      Indicates if the given point is over the bitmap marker.  The
 *      area of the bitmap is the rectangle.
 *
 * Results:
 *      Returns 1 is the point is over the bitmap marker, 0 otherwise.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
PointInBitmapMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;

    if(bmPtr->srcBitmap == None) {
        return 0;
    }
    if(bmPtr->theta != 0.0) {
RbcPoint2D points[MAX_OUTLINE_POINTS];
register int i;

        /*
         * Generate the bounding polygon (isolateral) for the bitmap
         * and see if the point is inside of it.
         */
        for(i = 0; i < bmPtr->nOutlinePts; i++) {
            points[i].x = bmPtr->outline[i].x + bmPtr->anchorPos.x;
            points[i].y = bmPtr->outline[i].y + bmPtr->anchorPos.y;
        }
        return RbcPointInPolygon(samplePtr, points, bmPtr->nOutlinePts);
    }
    return ((samplePtr->x >= bmPtr->anchorPos.x) &&
        (samplePtr->x < (bmPtr->anchorPos.x + bmPtr->destWidth)) &&
        (samplePtr->y >= bmPtr->anchorPos.y) &&
        (samplePtr->y < (bmPtr->anchorPos.y + bmPtr->destHeight)));
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInBitmapMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInBitmapMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;

    if(bmPtr->nWorldPts < 1) {
        return FALSE;
    }
    if(bmPtr->theta != 0.0) {
    RbcPoint2D points[MAX_OUTLINE_POINTS];
    register int i;

        /*
         * Generate the bounding polygon (isolateral) for the bitmap
         * and see if the point is inside of it.
         */
        for(i = 0; i < bmPtr->nOutlinePts; i++) {
            points[i].x = bmPtr->outline[i].x + bmPtr->anchorPos.x;
            points[i].y = bmPtr->outline[i].y + bmPtr->anchorPos.y;
        }
        return RbcRegionInPolygon(extsPtr, points, bmPtr->nOutlinePts,
            enclosed);
    }
    if(enclosed) {
        return ((bmPtr->anchorPos.x >= extsPtr->left) &&
            (bmPtr->anchorPos.y >= extsPtr->top) &&
            ((bmPtr->anchorPos.x + bmPtr->destWidth) <= extsPtr->right) &&
            ((bmPtr->anchorPos.y + bmPtr->destHeight) <= extsPtr->bottom));
    }
    return !((bmPtr->anchorPos.x >= extsPtr->right) ||
        (bmPtr->anchorPos.y >= extsPtr->bottom) ||
        ((bmPtr->anchorPos.x + bmPtr->destWidth) <= extsPtr->left) ||
        ((bmPtr->anchorPos.y + bmPtr->destHeight) <= extsPtr->top));
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawBitmapMarker --
 *
 *      Draws the bitmap marker that have a transparent of filled
 *      background.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      GC stipple origins are changed to current window coordinates.
 *      Commands are output to X to draw the marker in its current
 *      mode.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawBitmapMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcGraph *graph = markerPtr->graph;
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;
double theta;

    if((bmPtr->destBitmap == None) || (bmPtr->destWidth < 1) ||
        (bmPtr->destHeight < 1)) {
        return;
    }
    theta = FMOD(bmPtr->theta, (double)90.0);
    if((bmPtr->fillColor == NULL) || (theta != 0.0)) {

        /*
         * If the bitmap is rotated and a filled background is
         * required, then a filled polygon is drawn before the
         * bitmap.
         */

        if(bmPtr->fillColor != NULL) {
int i;
XPoint polygon[MAX_OUTLINE_POINTS];

            for(i = 0; i < bmPtr->nOutlinePts; i++) {
                polygon[i].x = (short int)bmPtr->outline[i].x;
                polygon[i].y = (short int)bmPtr->outline[i].y;
            }
            XFillPolygon(graph->display, drawable, bmPtr->fillGC,
                polygon, bmPtr->nOutlinePts, Convex, CoordModeOrigin);
        }
        XSetClipMask(graph->display, bmPtr->gc, bmPtr->destBitmap);
        XSetClipOrigin(graph->display, bmPtr->gc, (int)bmPtr->anchorPos.x,
            (int)bmPtr->anchorPos.y);
    } else {
        XSetClipMask(graph->display, bmPtr->gc, None);
        XSetClipOrigin(graph->display, bmPtr->gc, 0, 0);
    }
    XCopyPlane(graph->display, bmPtr->destBitmap, drawable, bmPtr->gc, 0, 0,
        bmPtr->destWidth, bmPtr->destHeight, (int)bmPtr->anchorPos.x,
        (int)bmPtr->anchorPos.y, 1);
}

/*
 * ----------------------------------------------------------------------
 *
 * BitmapMarkerToPostScript --
 *
 *      Generates PostScript to print a bitmap marker.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
BitmapMarkerToPostScript(
    RbcMarker * markerPtr,     /* Marker to be printed */
    RbcPsToken * psToken)
{
RbcGraph *graph = markerPtr->graph;
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;

    if(bmPtr->destBitmap == None) {
        return;
    }
    if(bmPtr->fillColor != NULL) {
        RbcBackgroundToPostScript(psToken, bmPtr->fillColor);
        RbcPolygonToPostScript(psToken, bmPtr->outline, 4);
    }
    RbcForegroundToPostScript(psToken, bmPtr->outlineColor);

    RbcFormatToPostScript(psToken,
        "  gsave\n    %g %g translate\n    %d %d scale\n",
        bmPtr->anchorPos.x, bmPtr->anchorPos.y + bmPtr->destHeight,
        bmPtr->destWidth, -bmPtr->destHeight);
    RbcFormatToPostScript(psToken, "    %d %d true [%d 0 0 %d 0 %d] {",
        bmPtr->destWidth, bmPtr->destHeight, bmPtr->destWidth,
        -bmPtr->destHeight, bmPtr->destHeight);
    RbcBitmapDataToPostScript(psToken, graph->display, bmPtr->destBitmap,
        bmPtr->destWidth, bmPtr->destHeight);
    RbcAppendToPostScript(psToken, "    } imagemask\n",
        "grestore\n", (char *)NULL);
}

/*
 * ----------------------------------------------------------------------
 *
 * FreeBitmapMarker --
 *
 *      Releases the memory and attributes of the bitmap marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Bitmap attributes (GCs, colors, bitmap, etc) get destroyed.
 *      Memory is released, X resources are freed, and the graph is
 *      redrawn.
 *
 * ----------------------------------------------------------------------
 */
static void
FreeBitmapMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
BitmapMarker *bmPtr = (BitmapMarker *) markerPtr;

    if(bmPtr->gc != NULL) {
        Tk_FreeGC(graph->display, bmPtr->gc);
    }
    if(bmPtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, bmPtr->fillGC);
    }
    if(bmPtr->destBitmap != bmPtr->srcBitmap) {
        Tk_FreePixmap(graph->display, bmPtr->destBitmap);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateBitmapMarker --
 *
 *      Allocate memory and initialize methods for the new bitmap marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the bitmap marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreateBitmapMarker(
    )
{
BitmapMarker *bmPtr;

    bmPtr = RbcCalloc(1, sizeof(BitmapMarker));
    if(bmPtr != NULL) {
        bmPtr->classPtr = &bitmapMarkerClass;
    }
    return (RbcMarker *) bmPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * ImageChangedProc
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ImageChangedProc(
    ClientData clientData,
    int x,                     /* Not used. */
    int y,                     /* Not used. */
    int width,                 /* Not used. */
    int height,                /* Not used. */
    int imageWidth,            /* Not used. */
    int imageHeight)
{              /* Not used. */
    ImageMarker *imPtr = clientData;
    Tk_PhotoHandle photo;

    photo = Tk_FindPhoto(imPtr->graph->interp, imPtr->imageName);
    if(photo != NULL) {
        if(imPtr->srcImage != NULL) {
            RbcFreeColorImage(imPtr->srcImage);
        }
        /* Convert the latest incarnation of the photo image back to a
         * color image that we can scale. */
        imPtr->srcImage = RbcPhotoToColorImage(photo);
    }
    imPtr->graph->flags |= RBC_REDRAW_BACKING_STORE;
    imPtr->flags |= RBC_MAP_ITEM;
    RbcEventuallyRedrawGraph(imPtr->graph);
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureImageMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or reconfigure)
 *      a image marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as image pixmap, colors,
 *      rotation, etc. get set for markerPtr; old resources get freed,
 *      if there were any.  The marker is eventually redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureImageMarker(
    RbcMarker * markerPtr)
{
ImageMarker *imPtr = (ImageMarker *) markerPtr;
RbcGraph *graph = markerPtr->graph;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(RbcConfigModified(markerPtr->classPtr->configSpecs, "-image",
            (char *)NULL)) {
Tcl_Interp *interp = graph->interp;

        if(imPtr->tkImage != NULL) {
            Tk_FreeImage(imPtr->tkImage);
            imPtr->tkImage = NULL;
        }
        if(imPtr->imageName != NULL && imPtr->imageName[0] != '\0') {
GC  newGC;
Tk_PhotoHandle photo;

            imPtr->tkImage = Tk_GetImage(interp, *(graph->win),
                imPtr->imageName, ImageChangedProc, imPtr);
            if(imPtr->tkImage == NULL) {
                Tcl_AppendResult(interp, "can't find an image \"",
                    imPtr->imageName, "\"", (char *)NULL);
                ckfree((char *)imPtr->imageName);
                imPtr->imageName = NULL;
                return TCL_ERROR;
            }
            photo = Tk_FindPhoto(interp, imPtr->imageName);
            if(photo != NULL) {
                if(imPtr->srcImage != NULL) {
                    RbcFreeColorImage(imPtr->srcImage);
                }
                /* Convert the photo into a color image */
                imPtr->srcImage = RbcPhotoToColorImage(photo);
            }
            newGC = Tk_GetGC(*(graph->win), 0L, (XGCValues *) NULL);
            if(imPtr->gc != NULL) {
                Tk_FreeGC(graph->display, imPtr->gc);
            }
            imPtr->gc = newGC;
        }
    }
    imPtr->flags |= RBC_MAP_ITEM;
    if(imPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapImageMarker --
 *
 *      This procedure gets called each time the layout of the graph
 *      changes.  The x, y window coordinates of the image marker are
 *      saved in the marker structure.
 *
 *      Additionly, if no background color was specified, the
 *      GCTileStipXOrigin and GCTileStipYOrigin attributes are set in
 *      the private GC.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Window coordinates are saved and if no background color was *
 *      set, the GC stipple origins are changed to calculated window
 *      coordinates.
 *
 * ----------------------------------------------------------------------
 */
static void
MapImageMarker(
    RbcMarker * markerPtr)
{
RbcExtents2D exts;
RbcGraph *graph;
ImageMarker *imPtr;
RbcPoint2D anchorPos;
RbcPoint2D corner1, corner2;
int scaledWidth, scaledHeight;
int srcWidth, srcHeight;

    imPtr = (ImageMarker *) markerPtr;
    if(imPtr->tkImage == NULL) {
        return;
    }
    graph = imPtr->graph;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;
    corner1 = MapPoint(graph, imPtr->worldPts, &imPtr->axes);
    if(imPtr->srcImage == NULL) {
        /*
         * Don't scale or rotate non-photo images.
         */
        Tk_SizeOfImage(imPtr->tkImage, &srcWidth, &srcHeight);
        imPtr->width = srcWidth;
        imPtr->height = srcHeight;
        imPtr->anchorPos.x = corner1.x + imPtr->xOffset;
        imPtr->anchorPos.y = corner1.y + imPtr->yOffset;
        exts.left = imPtr->anchorPos.x;
        exts.top = imPtr->anchorPos.y;
        exts.right = exts.left + srcWidth - 1;
        exts.bottom = exts.top + srcHeight - 1;
        imPtr->clipped = BoxesDontOverlap(graph, &exts);
        return;
    }

    imPtr->width = srcWidth = imPtr->srcImage->width;
    imPtr->height = srcHeight = imPtr->srcImage->height;
    if((srcWidth == 0) && (srcHeight == 0)) {
        imPtr->clipped = TRUE;
        return; /* Empty image. */
    }
    if(imPtr->nWorldPts > 1) {
double hold;

        corner2 = MapPoint(graph, imPtr->worldPts + 1, &imPtr->axes);
        /* Flip the corners if necessary */
        if(corner1.x > corner2.x) {
            hold = corner1.x, corner1.x = corner2.x, corner2.x = hold;
        }
        if(corner1.y > corner2.y) {
            hold = corner1.y, corner1.y = corner2.y, corner2.y = hold;
        }
    } else {
        corner2.x = corner1.x + srcWidth - 1;
        corner2.y = corner1.y + srcHeight - 1;
    }
    scaledWidth = (int)(corner2.x - corner1.x) + 1;
    scaledHeight = (int)(corner2.y - corner1.y) + 1;

    if(imPtr->nWorldPts == 1) {
        anchorPos = RbcTranslatePoint(&corner1, scaledWidth, scaledHeight,
            imPtr->anchor);
    } else {
        anchorPos = corner1;
    }
    anchorPos.x += imPtr->xOffset;
    anchorPos.y += imPtr->yOffset;

    /* Check if the image sits at least partially in the plot area. */
    exts.left = anchorPos.x;
    exts.top = anchorPos.y;
    exts.right = anchorPos.x + scaledWidth - 1;
    exts.bottom = anchorPos.y + scaledHeight - 1;

    imPtr->clipped = BoxesDontOverlap(graph, &exts);
    if(imPtr->clipped) {
        return; /* Image is offscreen. Don't generate
                 * rotated or scaled images. */
    }
    if((scaledWidth != srcWidth) || (scaledHeight != srcHeight)) {
Tk_PhotoHandle photo;
RbcColorImage *destImage;
int x, y, width, height;
int left, right, top, bottom;

        /* Determine the region of the subimage inside of the
         * destination image. */
        left = MAX((int)exts.left, graph->left);
        top = MAX((int)exts.top, graph->top);
        right = MIN((int)exts.right, graph->right);
        bottom = MIN((int)exts.bottom, graph->bottom);

        /* Reset image location and coordinates to that of the region */
        anchorPos.x = left;
        anchorPos.y = top;

        x = y = 0;
        if(graph->left > (int)exts.left) {
            x = graph->left - (int)exts.left;
        }
        if(graph->top > (int)exts.top) {
            y = graph->top - (int)exts.top;
        }
        width = (int)(right - left + 1);
        height = (int)(bottom - top + 1);

        destImage = RbcResizeColorSubimage(imPtr->srcImage, x, y, width,
            height, scaledWidth, scaledHeight);
        imPtr->pixmap = None;
        if(imPtr->tmpImage == NULL) {
            imPtr->tmpImage = RbcCreateTemporaryImage(graph->interp,
                *(graph->win), imPtr);
            if(imPtr->tmpImage == NULL) {
                return;
            }
        }
        /* Put the scaled colorimage into the photo. */
        photo = Tk_FindPhoto(graph->interp, RbcNameOfImage(imPtr->tmpImage));
        RbcColorImageToPhoto(graph->interp, destImage, photo);

        RbcFreeColorImage(destImage);
        imPtr->width = width;
        imPtr->height = height;
    }
    imPtr->anchorPos = anchorPos;
}

/*
 * ----------------------------------------------------------------------
 *
 * PointInWindowMarker --
 *
 *      Indicates if the given point is over the window marker.  The
 *      area of the window is the rectangle.
 *
 * Results:
 *      Returns 1 is the point is over the window marker, 0 otherwise.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
PointInImageMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
ImageMarker *imPtr = (ImageMarker *) markerPtr;

    return ((samplePtr->x >= imPtr->anchorPos.x) &&
        (samplePtr->x < (imPtr->anchorPos.x + imPtr->width)) &&
        (samplePtr->y >= imPtr->anchorPos.y) &&
        (samplePtr->y < (imPtr->anchorPos.y + imPtr->height)));
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInImageMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInImageMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    ImageMarker *imPtr = (ImageMarker *) markerPtr;

    if(imPtr->nWorldPts < 1) {
        return FALSE;
    }
    if(enclosed) {
        return ((imPtr->anchorPos.x >= extsPtr->left) &&
            (imPtr->anchorPos.y >= extsPtr->top) &&
            ((imPtr->anchorPos.x + imPtr->width) <= extsPtr->right) &&
            ((imPtr->anchorPos.y + imPtr->height) <= extsPtr->bottom));
    }
    return !((imPtr->anchorPos.x >= extsPtr->right) ||
        (imPtr->anchorPos.y >= extsPtr->bottom) ||
        ((imPtr->anchorPos.x + imPtr->width) <= extsPtr->left) ||
        ((imPtr->anchorPos.y + imPtr->height) <= extsPtr->top));
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawImageMarker --
 *
 *      This procedure is invoked to draw a image marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      GC stipple origins are changed to current window coordinates.
 *      Commands are output to X to draw the marker in its current mode.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawImageMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
ImageMarker *imPtr = (ImageMarker *) markerPtr;
int width, height;

    /* check is image still exists */
    if((imPtr->tkImage == NULL) || (RbcImageIsDeleted(imPtr->tkImage))) {
        return;
    }
    if(imPtr->pixmap == None) {
Pixmap pixmap;
Tk_Image tkImage;

        tkImage = (imPtr->tmpImage != NULL) ? imPtr->tmpImage : imPtr->tkImage;
        Tk_SizeOfImage(tkImage, &width, &height);
        pixmap = None;
        if(pixmap == None) {    /* May not be a "photo" image. */
            Tk_RedrawImage(tkImage, 0, 0, width, height, drawable,
                (int)imPtr->anchorPos.x, (int)imPtr->anchorPos.y);
        } else {
            XCopyArea(imPtr->graph->display, pixmap, drawable,
                imPtr->gc, 0, 0, width, height, (int)imPtr->anchorPos.x,
                (int)imPtr->anchorPos.y);
        }
    } else {
        XCopyArea(imPtr->graph->display, imPtr->pixmap, drawable,
            imPtr->gc, 0, 0, imPtr->width, imPtr->height,
            (int)imPtr->anchorPos.x, (int)imPtr->anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ImageMarkerToPostScript --
 *
 *      This procedure is invoked to print a image marker.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
ImageMarkerToPostScript(
    RbcMarker * markerPtr,     /* Marker to be printed */
    RbcPsToken * psToken)
{
ImageMarker *imPtr = (ImageMarker *) markerPtr;
const char *imageName;
Tk_PhotoHandle photo;

    if((imPtr->tkImage == NULL) || (RbcImageIsDeleted(imPtr->tkImage))) {
        return; /* Image doesn't exist anymore */
    }
    imageName = (imPtr->tmpImage == NULL)
        ? RbcNameOfImage(imPtr->tkImage) : RbcNameOfImage(imPtr->tmpImage);
    photo = Tk_FindPhoto(markerPtr->graph->interp, imageName);
    if(photo == NULL) {
        return; /* Image isn't a photo image */
    }
    RbcPhotoToPostScript(psToken, photo, imPtr->anchorPos.x,
        imPtr->anchorPos.y);
}

/*
 * ----------------------------------------------------------------------
 *
 * FreeImageMarker --
 *
 *      Destroys the structure containing the attributes of the image
 *      marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Image attributes (GCs, colors, image, etc) get destroyed.
 *      Memory is released, X resources are freed, and the graph is
 *      redrawn.
 *
 * ----------------------------------------------------------------------
 */
static void
FreeImageMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
ImageMarker *imPtr = (ImageMarker *) markerPtr;

    if(imPtr->pixmap != None) {
        Tk_FreePixmap(graph->display, imPtr->pixmap);
    }
    if(imPtr->tkImage != NULL) {
        Tk_FreeImage(imPtr->tkImage);
    }
    if(imPtr->tmpImage != NULL) {
        RbcDestroyTemporaryImage(graph->interp, imPtr->tmpImage);
    }
    if(imPtr->srcImage != NULL) {
        RbcFreeColorImage(imPtr->srcImage);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateImageMarker --
 *
 *      Allocate memory and initialize methods for the new image marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the image marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreateImageMarker(
    )
{
ImageMarker *imPtr;

    imPtr = RbcCalloc(1, sizeof(ImageMarker));
    if(imPtr != NULL) {
        imPtr->classPtr = &imageMarkerClass;
    }
    return (RbcMarker *) imPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureTextMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or
 *      reconfigure) a text marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as text string, colors, font,
 *      etc. get set for markerPtr;  old resources get freed, if there
 *      were any.  The marker is eventually redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureTextMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
TextMarker *tmPtr = (TextMarker *) markerPtr;
GC  newGC;
XGCValues gcValues;
unsigned long gcMask;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    tmPtr->style.theta = FMOD(tmPtr->style.theta, 360.0);
    if(tmPtr->style.theta < 0.0) {
        tmPtr->style.theta += 360.0;
    }
    newGC = NULL;
    if(tmPtr->fillColor != NULL) {
        gcMask = GCForeground;
        gcValues.foreground = tmPtr->fillColor->pixel;
        newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    }
    if(tmPtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, tmPtr->fillGC);
    }
    tmPtr->fillGC = newGC;
    RbcResetTextStyle(*(graph->win), &tmPtr->style);

    if(RbcConfigModified(tmPtr->classPtr->configSpecs, "-text", (char *)NULL)) {
        if(tmPtr->textPtr != NULL) {
            ckfree((char *)tmPtr->textPtr);
            tmPtr->textPtr = NULL;
        }
        tmPtr->width = tmPtr->height = 0;
        if(tmPtr->string != NULL) {
register int i;
double rotWidth, rotHeight;

            tmPtr->textPtr = RbcGetTextLayout(tmPtr->string, &tmPtr->style);
            RbcGetBoundingBox(tmPtr->textPtr->width, tmPtr->textPtr->height,
                tmPtr->style.theta, &rotWidth, &rotHeight, tmPtr->outline);
            tmPtr->width = ROUND(rotWidth);
            tmPtr->height = ROUND(rotHeight);
            for(i = 0; i < 4; i++) {
                tmPtr->outline[i].x += ROUND(rotWidth * 0.5);
                tmPtr->outline[i].y += ROUND(rotHeight * 0.5);
            }
            tmPtr->outline[4].x = tmPtr->outline[0].x;
            tmPtr->outline[4].y = tmPtr->outline[0].y;
        }
    }
    tmPtr->flags |= RBC_MAP_ITEM;
    if(tmPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapTextMarker --
 *
 *      Calculate the layout position for a text marker.  Positional
 *      information is saved in the marker.  If the text is rotated,
 *      a bitmap containing the text is created.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      If no background color has been specified, the GC stipple
 *      origins are changed to current window coordinates. For both
 *      rotated and non-rotated text, if any old bitmap is leftover,
 *      it is freed.
 *
 * ----------------------------------------------------------------------
 */
static void
MapTextMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
TextMarker *tmPtr = (TextMarker *) markerPtr;
RbcExtents2D exts;
RbcPoint2D anchorPos;

    if(tmPtr->string == NULL) {
        return;
    }
    anchorPos = MapPoint(graph, tmPtr->worldPts, &tmPtr->axes);
    anchorPos = RbcTranslatePoint(&anchorPos, tmPtr->width, tmPtr->height,
        tmPtr->anchor);
    anchorPos.x += tmPtr->xOffset;
    anchorPos.y += tmPtr->yOffset;
    /*
     * Determine the bounding box of the text and test to see if it
     * is at least partially contained within the plotting area.
     */
    exts.left = anchorPos.x;
    exts.top = anchorPos.y;
    exts.right = anchorPos.x + tmPtr->width - 1;
    exts.bottom = anchorPos.y + tmPtr->height - 1;
    tmPtr->clipped = BoxesDontOverlap(graph, &exts);
    tmPtr->anchorPos = anchorPos;

}

/*
 *----------------------------------------------------------------------
 *
 * PointInTextMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
PointInTextMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
TextMarker *tmPtr = (TextMarker *) markerPtr;

    if(tmPtr->string == NULL) {
        return 0;
    }
    if(tmPtr->style.theta != 0.0) {
RbcPoint2D points[5];
register int i;

        /*
         * Figure out the bounding polygon (isolateral) for the text
         * and see if the point is inside of it.
         */

        for(i = 0; i < 5; i++) {
            points[i].x = tmPtr->outline[i].x + tmPtr->anchorPos.x;
            points[i].y = tmPtr->outline[i].y + tmPtr->anchorPos.y;
        }
        return RbcPointInPolygon(samplePtr, points, 5);
    }
    return ((samplePtr->x >= tmPtr->anchorPos.x) &&
        (samplePtr->x < (tmPtr->anchorPos.x + tmPtr->width)) &&
        (samplePtr->y >= tmPtr->anchorPos.y) &&
        (samplePtr->y < (tmPtr->anchorPos.y + tmPtr->height)));
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInTextMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInTextMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    TextMarker *tmPtr = (TextMarker *) markerPtr;

    if(tmPtr->nWorldPts < 1) {
        return FALSE;
    }
    if(tmPtr->style.theta != 0.0) {
    RbcPoint2D points[5];
    register int i;

        /*
         * Generate the bounding polygon (isolateral) for the bitmap
         * and see if the point is inside of it.
         */
        for(i = 0; i < 4; i++) {
            points[i].x = tmPtr->outline[i].x + tmPtr->anchorPos.x;
            points[i].y = tmPtr->outline[i].y + tmPtr->anchorPos.y;
        }
        return RbcRegionInPolygon(extsPtr, points, 4, enclosed);
    }
    if(enclosed) {
        return ((tmPtr->anchorPos.x >= extsPtr->left) &&
            (tmPtr->anchorPos.y >= extsPtr->top) &&
            ((tmPtr->anchorPos.x + tmPtr->width) <= extsPtr->right) &&
            ((tmPtr->anchorPos.y + tmPtr->height) <= extsPtr->bottom));
    }
    return !((tmPtr->anchorPos.x >= extsPtr->right) ||
        (tmPtr->anchorPos.y >= extsPtr->bottom) ||
        ((tmPtr->anchorPos.x + tmPtr->width) <= extsPtr->left) ||
        ((tmPtr->anchorPos.y + tmPtr->height) <= extsPtr->top));
}

/*
 * ----------------------------------------------------------------------
 *
 * DrawTextMarker --
 *
 *      Draws the text marker on the graph.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Commands are output to X to draw the marker in its current
 *      mode.
 *
 * ----------------------------------------------------------------------
 */
static void
DrawTextMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
TextMarker *tmPtr = (TextMarker *) markerPtr;
RbcGraph *graph = markerPtr->graph;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    if(tmPtr->string == NULL) {
        return;
    }
    if(tmPtr->fillGC != NULL) {
XPoint pointArr[4];
register int i;

        /*
         * Simulate the rotated background of the bitmap by
         * filling a bounding polygon with the background color.
         */
        for(i = 0; i < 4; i++) {
            pointArr[i].x = (short int)
                (tmPtr->outline[i].x + tmPtr->anchorPos.x);
            pointArr[i].y = (short int)
                (tmPtr->outline[i].y + tmPtr->anchorPos.y);
        }
        XFillPolygon(graph->display, drawable, tmPtr->fillGC, pointArr, 4,
            Convex, CoordModeOrigin);
    }
    if(tmPtr->style.color != NULL) {
        RbcDrawTextLayout(*(graph->win), drawable, tmPtr->textPtr,
            &tmPtr->style, (int)tmPtr->anchorPos.x, (int)tmPtr->anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * TextMarkerToPostScript --
 *
 *      Outputs PostScript commands to draw a text marker at a given
 *      x,y coordinate, rotation, anchor, and font.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript font and color settings are changed.
 *
 * ----------------------------------------------------------------------
 */
static void
TextMarkerToPostScript(
    RbcMarker * markerPtr,
    RbcPsToken * psToken)
{
TextMarker *tmPtr = (TextMarker *) markerPtr;

    if(tmPtr->string == NULL) {
        return;
    }
    if(tmPtr->fillGC != NULL) {
RbcPoint2D polygon[4];
register int i;

        /*
         * Simulate the rotated background of the bitmap by
         * filling a bounding polygon with the background color.
         */
        for(i = 0; i < 4; i++) {
            polygon[i].x = tmPtr->outline[i].x + tmPtr->anchorPos.x;
            polygon[i].y = tmPtr->outline[i].y + tmPtr->anchorPos.y;
        }
        RbcBackgroundToPostScript(psToken, tmPtr->fillColor);
        RbcPolygonToPostScript(psToken, polygon, 4);
    }
    RbcTextToPostScript(psToken, tmPtr->string, &tmPtr->style,
        tmPtr->anchorPos.x, tmPtr->anchorPos.y);
}

/*
 * ----------------------------------------------------------------------
 *
 * FreeTextMarker --
 *
 *      Destroys the structure containing the attributes of the text
 *      marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Text attributes (GCs, colors, stipple, font, etc) get destroyed.
 *      Memory is released, X resources are freed, and the graph is
 *      redrawn.
 *
 * ----------------------------------------------------------------------
 */
static void
FreeTextMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
TextMarker *tmPtr = (TextMarker *) markerPtr;

    RbcFreeTextStyle(graph->display, &tmPtr->style);
    if(tmPtr->textPtr != NULL) {
        ckfree((char *)tmPtr->textPtr);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateTextMarker --
 *
 *      Allocate memory and initialize methods for the new text marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the text marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreateTextMarker(
    )
{
TextMarker *tmPtr;

    tmPtr = RbcCalloc(1, sizeof(TextMarker));
    assert(tmPtr);

    tmPtr->classPtr = &textMarkerClass;
    RbcInitTextStyle(&tmPtr->style);
    tmPtr->style.anchor = TK_ANCHOR_NW;
    tmPtr->style.padX.side1 = tmPtr->style.padX.side2 = 4;      /*x */
    tmPtr->style.padY.side1 = tmPtr->style.padY.side2 = 4;      /*y */

    return (RbcMarker *) tmPtr;
}

static Tk_GeomMgr winMarkerMgrInfo = {
    "graph",   /* Name of geometry manager used by winfo */
    ChildGeometryProc,  /* Procedure to for new geometry requests */
    ChildCustodyProc,   /* Procedure when window is taken away */
};

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureWindowMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or reconfigure)
 *      a window marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as window pathname, placement,
 *      etc. get set for markerPtr; old resources get freed, if there
 *      were any.  The marker is eventually redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureWindowMarker(
    RbcMarker * markerPtr)
{
    RbcGraph *graph = markerPtr->graph;
    WindowMarker *wmPtr = (WindowMarker *) markerPtr;
    Tk_Window tkwin;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(wmPtr->pathName == NULL) {
        return TCL_OK;
    }
    tkwin = Tk_NameToWindow(graph->interp, wmPtr->pathName, *(graph->win));
    if(tkwin == NULL) {
        return TCL_ERROR;
    }
    if(Tk_Parent(tkwin) != *(graph->win)) {
        Tcl_AppendResult(graph->interp, "\"", wmPtr->pathName,
            "\" is not a child of \"", Tk_PathName(*(graph->win)), "\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    if(tkwin != wmPtr->tkwin) {
        if(wmPtr->tkwin != NULL) {
            Tk_DeleteEventHandler(wmPtr->tkwin, StructureNotifyMask,
                ChildEventProc, wmPtr);
            Tk_ManageGeometry(wmPtr->tkwin, (Tk_GeomMgr *) 0, (ClientData) 0);
            Tk_UnmapWindow(wmPtr->tkwin);
        }
        Tk_CreateEventHandler(tkwin, StructureNotifyMask, ChildEventProc,
            wmPtr);
        Tk_ManageGeometry(tkwin, &winMarkerMgrInfo, wmPtr);
    }
    wmPtr->tkwin = tkwin;

    wmPtr->flags |= RBC_MAP_ITEM;
    if(wmPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapWindowMarker --
 *
 *      Calculate the layout position for a window marker.  Positional
 *      information is saved in the marker.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
MapWindowMarker(
    RbcMarker * markerPtr)
{
WindowMarker *wmPtr = (WindowMarker *) markerPtr;
RbcGraph *graph = markerPtr->graph;
RbcExtents2D exts;
int width, height;

    if(wmPtr->tkwin == (Tk_Window) NULL) {
        return;
    }
    wmPtr->anchorPos = MapPoint(graph, wmPtr->worldPts, &wmPtr->axes);

    width = Tk_ReqWidth(wmPtr->tkwin);
    height = Tk_ReqHeight(wmPtr->tkwin);
    if(wmPtr->reqWidth > 0) {
        width = wmPtr->reqWidth;
    }
    if(wmPtr->reqHeight > 0) {
        height = wmPtr->reqHeight;
    }
    wmPtr->anchorPos = RbcTranslatePoint(&wmPtr->anchorPos, width, height,
        wmPtr->anchor);
    wmPtr->anchorPos.x += wmPtr->xOffset;
    wmPtr->anchorPos.y += wmPtr->yOffset;
    wmPtr->width = width;
    wmPtr->height = height;

    /*
     * Determine the bounding box of the window and test to see if it
     * is at least partially contained within the plotting area.
     */
    exts.left = wmPtr->anchorPos.x;
    exts.top = wmPtr->anchorPos.y;
    exts.right = wmPtr->anchorPos.x + wmPtr->width - 1;
    exts.bottom = wmPtr->anchorPos.y + wmPtr->height - 1;
    wmPtr->clipped = BoxesDontOverlap(graph, &exts);
}

/*
 *----------------------------------------------------------------------
 *
 * PointInWindowMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
PointInWindowMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
WindowMarker *wmPtr = (WindowMarker *) markerPtr;

    return ((samplePtr->x >= wmPtr->anchorPos.x) &&
        (samplePtr->x < (wmPtr->anchorPos.x + wmPtr->width)) &&
        (samplePtr->y >= wmPtr->anchorPos.y) &&
        (samplePtr->y < (wmPtr->anchorPos.y + wmPtr->height)));
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInWindowMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInWindowMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    WindowMarker *wmPtr = (WindowMarker *) markerPtr;

    if(wmPtr->nWorldPts < 1) {
        return FALSE;
    }
    if(enclosed) {
        return ((wmPtr->anchorPos.x >= extsPtr->left) &&
            (wmPtr->anchorPos.y >= extsPtr->top) &&
            ((wmPtr->anchorPos.x + wmPtr->width) <= extsPtr->right) &&
            ((wmPtr->anchorPos.y + wmPtr->height) <= extsPtr->bottom));
    }
    return !((wmPtr->anchorPos.x >= extsPtr->right) ||
        (wmPtr->anchorPos.y >= extsPtr->bottom) ||
        ((wmPtr->anchorPos.x + wmPtr->width) <= extsPtr->left) ||
        ((wmPtr->anchorPos.y + wmPtr->height) <= extsPtr->top));
}

/*
 *----------------------------------------------------------------------
 *
 * DrawWindowMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawWindowMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
WindowMarker *wmPtr = (WindowMarker *) markerPtr;

    if(wmPtr->tkwin == NULL) {
        return;
    }
    if((wmPtr->height != Tk_Height(wmPtr->tkwin)) ||
        (wmPtr->width != Tk_Width(wmPtr->tkwin)) ||
        ((int)wmPtr->anchorPos.x != Tk_X(wmPtr->tkwin)) ||
        ((int)wmPtr->anchorPos.y != Tk_Y(wmPtr->tkwin))) {
        Tk_MoveResizeWindow(wmPtr->tkwin, (int)wmPtr->anchorPos.x,
            (int)wmPtr->anchorPos.y, wmPtr->width, wmPtr->height);
    }
    if(!Tk_IsMapped(wmPtr->tkwin)) {
        Tk_MapWindow(wmPtr->tkwin);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * WindowMarkerToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
WindowMarkerToPostScript(
    RbcMarker * markerPtr,
    RbcPsToken * psToken)
{
WindowMarker *wmPtr = (WindowMarker *) markerPtr;

    if(wmPtr->tkwin == NULL) {
        return;
    }
    if(Tk_IsMapped(wmPtr->tkwin)) {
        RbcWindowToPostScript(psToken, wmPtr->tkwin, wmPtr->anchorPos.x,
            wmPtr->anchorPos.y);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * FreeWindowMarker --
 *
 *      Destroys the structure containing the attributes of the window
 *      marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Window is destroyed and removed from the screen.
 *
 * ----------------------------------------------------------------------
 */
static void
FreeWindowMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
WindowMarker *wmPtr = (WindowMarker *) markerPtr;

    if(wmPtr->tkwin != NULL) {
        Tk_DeleteEventHandler(wmPtr->tkwin, StructureNotifyMask,
            ChildEventProc, wmPtr);
        Tk_ManageGeometry(wmPtr->tkwin, (Tk_GeomMgr *) 0, (ClientData) 0);
        Tk_DestroyWindow(wmPtr->tkwin);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateWindowMarker --
 *
 *      Allocate memory and initialize methods for the new window marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the window marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreateWindowMarker(
    )
{
WindowMarker *wmPtr;

    wmPtr = RbcCalloc(1, sizeof(WindowMarker));
    if(wmPtr != NULL) {
        wmPtr->classPtr = &windowMarkerClass;
    }
    return (RbcMarker *) wmPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * ChildEventProc --
 *
 *      This procedure is invoked whenever StructureNotify events
 *      occur for a window that's managed as part of a graph window
 *      marker. This procedure's only purpose is to clean up when
 *      windows are deleted.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The window is disassociated from the window item when it is
 *      deleted.
 *
 * ----------------------------------------------------------------------
 */
static void
ChildEventProc(
    ClientData clientData,     /* Pointer to record describing window item. */
    XEvent * eventPtr)
{              /* Describes what just happened. */
WindowMarker *wmPtr = clientData;

    if(eventPtr->type == DestroyNotify) {
        wmPtr->tkwin = NULL;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ChildGeometryProc --
 *
 *      This procedure is invoked whenever a window that's associated
 *      with a window item changes its requested dimensions.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The size and location on the window of the window may change,
 *      depending on the options specified for the window item.
 *
 * ----------------------------------------------------------------------
 */
static void
ChildGeometryProc(
    ClientData clientData,     /* Pointer to record for window item. */
    Tk_Window tkwin)
{              /* Window that changed its desired size. */
WindowMarker *wmPtr = clientData;

    if(wmPtr->reqWidth == 0) {
        wmPtr->width = Tk_ReqWidth(tkwin);
    }
    if(wmPtr->reqHeight == 0) {
        wmPtr->height = Tk_ReqHeight(tkwin);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ChildCustodyProc --
 *
 *      This procedure is invoked when an embedded window has been
 *      stolen by another geometry manager.  The information and
 *      memory associated with the widget is released.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Arranges for the graph to be redrawn without the embedded
 *      widget at the next idle point.
 *
 * ----------------------------------------------------------------------
 */
static void
ChildCustodyProc(
    ClientData clientData,     /* Window marker to be destroyed. */
    Tk_Window tkwin)
{              /* Not used. */
RbcMarker *markerPtr = clientData;
RbcGraph *graph;

    graph = markerPtr->graph;
    DestroyMarker(markerPtr);
    /*
     * Not really needed. We should get an Expose event when the
     * child window is unmapped.
     */
    RbcEventuallyRedrawGraph(graph);
}

/*
 * ----------------------------------------------------------------------
 *
 * MapLineMarker --
 *
 *      Calculate the layout position for a line marker.  Positional
 *      information is saved in the marker.  The line positions are
 *      stored in an array of points (malloc'ed).
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
MapLineMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
LineMarker *lmPtr = (LineMarker *) markerPtr;
RbcPoint2D *srcPtr, *endPtr;
RbcSegment2D *segments, *segPtr;
RbcPoint2D p, q, next;
RbcExtents2D exts;

    lmPtr->nSegments = 0;
    if(lmPtr->segments != NULL) {
        ckfree((char *)lmPtr->segments);
    }
    if(lmPtr->nWorldPts < 2) {
        return; /* Too few points */
    }
    RbcGraphExtents(graph, &exts);

    /*
     * Allow twice the number of world coordinates. The line will
     * represented as series of line segments, not one continous
     * polyline.  This is because clipping against the plot area may
     * chop the line into several disconnected segments.
     */
    segments =
        (RbcSegment2D *) ckalloc(lmPtr->nWorldPts * sizeof(RbcSegment2D));
    srcPtr = lmPtr->worldPts;
    p = MapPoint(graph, srcPtr, &lmPtr->axes);
    p.x += lmPtr->xOffset;
    p.y += lmPtr->yOffset;

    segPtr = segments;
    for(srcPtr++, endPtr = lmPtr->worldPts + lmPtr->nWorldPts;
        srcPtr < endPtr; srcPtr++) {
        next = MapPoint(graph, srcPtr, &lmPtr->axes);
        next.x += lmPtr->xOffset;
        next.y += lmPtr->yOffset;
        q = next;
        if(RbcLineRectClip(&exts, &p, &q)) {
            segPtr->p = p;
            segPtr->q = q;
            segPtr++;
        }
        p = next;
    }
    lmPtr->nSegments = segPtr - segments;
    lmPtr->segments = segments;
    lmPtr->clipped = (lmPtr->nSegments == 0);
}

/*
 *----------------------------------------------------------------------
 *
 * PointInLineMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
PointInLineMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
LineMarker *lmPtr = (LineMarker *) markerPtr;

    return RbcPointInSegments(samplePtr, lmPtr->segments, lmPtr->nSegments,
        (double)lmPtr->graph->halo);
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInLineMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInLineMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    LineMarker *lmPtr = (LineMarker *) markerPtr;

    if(lmPtr->nWorldPts < 2) {
        return FALSE;
    }
    if(enclosed) {
    RbcPoint2D p;
    RbcPoint2D *pointPtr, *endPtr;

        for(pointPtr = lmPtr->worldPts,
            endPtr = lmPtr->worldPts + lmPtr->nWorldPts;
            pointPtr < endPtr; pointPtr++) {
            p = MapPoint(lmPtr->graph, pointPtr, &lmPtr->axes);
            if((p.x < extsPtr->left) && (p.x > extsPtr->right) &&
                (p.y < extsPtr->top) && (p.y > extsPtr->bottom)) {
                return FALSE;
            }
        }
        return TRUE;    /* All points inside bounding box. */
    } else {
    RbcPoint2D p, q;
    int count;
    RbcPoint2D *pointPtr, *endPtr;

        count = 0;
        for(pointPtr = lmPtr->worldPts,
            endPtr = lmPtr->worldPts + (lmPtr->nWorldPts - 1);
            pointPtr < endPtr; pointPtr++) {
            p = MapPoint(lmPtr->graph, pointPtr, &lmPtr->axes);
            q = MapPoint(lmPtr->graph, pointPtr + 1, &lmPtr->axes);
            if(RbcLineRectClip(extsPtr, &p, &q)) {
                count++;
            }
        }
        return (count > 0);     /* At least 1 segment passes through region. */
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DrawLineMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawLineMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
LineMarker *lmPtr = (LineMarker *) markerPtr;

    if(lmPtr->nSegments > 0) {
RbcGraph *graph = markerPtr->graph;

        RbcDraw2DSegments(graph->display, drawable, lmPtr->gc,
            lmPtr->segments, lmPtr->nSegments);
        if(lmPtr->xor) {        /* Toggle the drawing state */
            lmPtr->xorState = (lmPtr->xorState == 0);
        }
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureLineMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or reconfigure)
 *      a line marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as line width, colors, dashes,
 *      etc. get set for markerPtr; old resources get freed, if there
 *      were any.  The marker is eventually redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureLineMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
LineMarker *lmPtr = (LineMarker *) markerPtr;
GC  newGC;
XGCValues gcValues;
unsigned long gcMask;
Drawable drawable;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    drawable = Tk_WindowId(*(graph->win));
    gcMask = (GCLineWidth | GCLineStyle | GCCapStyle | GCJoinStyle);
    if(lmPtr->outlineColor != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = lmPtr->outlineColor->pixel;
    }
    if(lmPtr->fillColor != NULL) {
        gcMask |= GCBackground;
        gcValues.background = lmPtr->fillColor->pixel;
    }
    gcValues.cap_style = lmPtr->capStyle;
    gcValues.join_style = lmPtr->joinStyle;
    gcValues.line_width = RbcLineWidth(lmPtr->lineWidth);
    gcValues.line_style = LineSolid;
    if(RbcLineIsDashed(lmPtr->dashes)) {
        gcValues.line_style =
            (gcMask & GCBackground) ? LineDoubleDash : LineOnOffDash;
    }
    if(lmPtr->xor) {
unsigned long pixel;
        gcValues.function = GXxor;

        gcMask |= GCFunction;
        if(graph->plotBg == NULL) {
            pixel = WhitePixelOfScreen(Tk_Screen(*(graph->win)));
        } else {
            pixel = graph->plotBg->pixel;
        }
        if(gcMask & GCBackground) {
            gcValues.background ^= pixel;
        }
        gcValues.foreground ^= pixel;
        if(drawable != None) {
            DrawLineMarker(markerPtr, drawable);
        }
    }
    newGC = RbcGetPrivateGC(*(graph->win), gcMask, &gcValues);
    if(lmPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, lmPtr->gc);
    }
    if(RbcLineIsDashed(lmPtr->dashes)) {
        RbcSetDashes(graph->display, newGC, &lmPtr->dashes);
    }
    lmPtr->gc = newGC;
    if(lmPtr->xor) {
        if(drawable != None) {
            MapLineMarker(markerPtr);
            DrawLineMarker(markerPtr, drawable);
        }
        return TCL_OK;
    }
    lmPtr->flags |= RBC_MAP_ITEM;
    if(lmPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * LineMarkerToPostScript --
 *
 *      Prints postscript commands to display the connect line.
 *      Dashed lines need to be handled specially, especially if a
 *      background color is designated.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      PostScript output commands are saved in the interpreter
 *      (infoPtr->interp) result field.
 *
 * ----------------------------------------------------------------------
 */
static void
LineMarkerToPostScript(
    RbcMarker * markerPtr,
    RbcPsToken * psToken)
{
LineMarker *lmPtr = (LineMarker *) markerPtr;

    if(lmPtr->nSegments > 0) {
        RbcLineAttributesToPostScript(psToken, lmPtr->outlineColor,
            lmPtr->lineWidth, &lmPtr->dashes, lmPtr->capStyle,
            lmPtr->joinStyle);
        if((RbcLineIsDashed(lmPtr->dashes)) && (lmPtr->fillColor != NULL)) {
            RbcAppendToPostScript(psToken, "/DashesProc {\n  gsave\n    ",
                (char *)NULL);
            RbcBackgroundToPostScript(psToken, lmPtr->fillColor);
            RbcAppendToPostScript(psToken, "    ", (char *)NULL);
            RbcLineDashesToPostScript(psToken, (RbcDashes *) NULL);
            RbcAppendToPostScript(psToken,
                "stroke\n", "  grestore\n", "} def\n", (char *)NULL);
        } else {
            RbcAppendToPostScript(psToken, "/DashesProc {} def\n",
                (char *)NULL);
        }
        Rbc2DSegmentsToPostScript(psToken, lmPtr->segments, lmPtr->nSegments);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * FreeLineMarker --
 *
 *      Destroys the structure and attributes of a line marker.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Line attributes (GCs, colors, stipple, etc) get released.
 *      Memory is deallocated, X resources are freed.
 *
 * ----------------------------------------------------------------------
 */
static void
FreeLineMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
LineMarker *lmPtr = (LineMarker *) markerPtr;

    if(lmPtr->gc != NULL) {
        RbcFreePrivateGC(graph->display, lmPtr->gc);
    }
    if(lmPtr->segments != NULL) {
        ckfree((char *)lmPtr->segments);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateLineMarker --
 *
 *      Allocate memory and initialize methods for a new line marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is returned.
 *
 * Side effects:
 *      Memory is allocated for the line marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreateLineMarker(
    )
{
LineMarker *lmPtr;

    lmPtr = RbcCalloc(1, sizeof(LineMarker));
    if(lmPtr != NULL) {
        lmPtr->classPtr = &lineMarkerClass;
        lmPtr->xor = FALSE;
        lmPtr->capStyle = CapButt;
        lmPtr->joinStyle = JoinMiter;
    }
    return (RbcMarker *) lmPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * MapPolygonMarker --
 *
 *      Calculate the layout position for a polygon marker.  Positional
 *      information is saved in the polygon in an array of points
 *      (malloc'ed).
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
MapPolygonMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;
RbcPoint2D *srcPtr, *destPtr, *endPtr;
RbcPoint2D *screenPts;
RbcExtents2D exts;
int nScreenPts;

    if(pmPtr->outlinePts != NULL) {
        ckfree((char *)pmPtr->outlinePts);
        pmPtr->outlinePts = NULL;
        pmPtr->nOutlinePts = 0;
    }
    if(pmPtr->fillPts != NULL) {
        ckfree((char *)pmPtr->fillPts);
        pmPtr->fillPts = NULL;
        pmPtr->nFillPts = 0;
    }
    if(pmPtr->screenPts != NULL) {
        ckfree((char *)pmPtr->screenPts);
        pmPtr->screenPts = NULL;
    }
    if(pmPtr->nWorldPts < 3) {
        return; /* Too few points */
    }

    /*
     * Allocate and fill a temporary array to hold the screen
     * coordinates of the polygon.
     */
    nScreenPts = pmPtr->nWorldPts + 1;
    screenPts = (RbcPoint2D *) ckalloc((nScreenPts + 1) * sizeof(RbcPoint2D));
    endPtr = pmPtr->worldPts + pmPtr->nWorldPts;
    destPtr = screenPts;
    for(srcPtr = pmPtr->worldPts; srcPtr < endPtr; srcPtr++) {
        *destPtr = MapPoint(graph, srcPtr, &pmPtr->axes);
        destPtr->x += pmPtr->xOffset;
        destPtr->y += pmPtr->yOffset;
        destPtr++;
    }
    *destPtr = screenPts[0];

    RbcGraphExtents(graph, &exts);
    pmPtr->clipped = TRUE;
    if(pmPtr->fill.fgColor != NULL) {   /* Polygon fill required. */
RbcPoint2D *fillPts;
int n;

        fillPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * nScreenPts * 3);
        assert(fillPts);
        n = RbcPolyRectClip(&exts, screenPts, pmPtr->nWorldPts, fillPts);
        if(n < 3) {
            ckfree((char *)fillPts);
        } else {
            pmPtr->nFillPts = n;
            pmPtr->fillPts = fillPts;
            pmPtr->clipped = FALSE;
        }
    }
    if((pmPtr->outline.fgColor != NULL) && (pmPtr->lineWidth > 0)) {
RbcSegment2D *outlinePts;
register RbcSegment2D *segPtr;
        /*
         * Generate line segments representing the polygon outline.
         * The resulting outline may or may not be closed from
         * viewport clipping.
         */
        outlinePts =
            (RbcSegment2D *) ckalloc(nScreenPts * sizeof(RbcSegment2D));
        if(outlinePts == NULL) {
            return;     /* Can't allocate point array */
        }
        /*
         * Note that this assumes that the point array contains an
         * extra point that closes the polygon.
         */
        segPtr = outlinePts;
        for(srcPtr = screenPts, endPtr = screenPts + (nScreenPts - 1);
            srcPtr < endPtr; srcPtr++) {
            segPtr->p = srcPtr[0];
            segPtr->q = srcPtr[1];
            if(RbcLineRectClip(&exts, &segPtr->p, &segPtr->q)) {
                segPtr++;
            }
        }
        pmPtr->nOutlinePts = segPtr - outlinePts;
        pmPtr->outlinePts = outlinePts;
        if(pmPtr->nOutlinePts > 0) {
            pmPtr->clipped = FALSE;
        }
    }
    pmPtr->screenPts = screenPts;
}

/*
 *----------------------------------------------------------------------
 *
 * PointInPolygonMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
PointInPolygonMarker(
    RbcMarker * markerPtr,
    RbcPoint2D * samplePtr)
{
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;

    if(pmPtr->nWorldPts < 2) {
        return FALSE;
    }
    return RbcPointInPolygon(samplePtr, pmPtr->screenPts, pmPtr->nWorldPts + 1);
}

/*
 *----------------------------------------------------------------------
 *
 * RegionInPolygonMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RegionInPolygonMarker(
    RbcMarker * markerPtr,
    RbcExtents2D * extsPtr,
    int enclosed)
{
    PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;

    if(pmPtr->nWorldPts >= 3) {
        return RbcRegionInPolygon(extsPtr, pmPtr->screenPts, pmPtr->nWorldPts,
            enclosed);
    }
    return FALSE;
}

/*
 *----------------------------------------------------------------------
 *
 * DrawPolygonMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DrawPolygonMarker(
    RbcMarker * markerPtr,
    Drawable drawable)
{              /* Pixmap or window to draw into */
RbcGraph *graph = markerPtr->graph;
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;

    /* Draw polygon fill region */
    if((pmPtr->nFillPts > 0) && (pmPtr->fill.fgColor != NULL)) {
XPoint *destPtr, *pointArr;
RbcPoint2D *srcPtr, *endPtr;

        pointArr = (XPoint *) ckalloc(pmPtr->nFillPts * sizeof(XPoint));
        if(pointArr == NULL) {
            return;
        }
        destPtr = pointArr;
        for(srcPtr = pmPtr->fillPts,
            endPtr = pmPtr->fillPts + pmPtr->nFillPts; srcPtr < endPtr;
            srcPtr++) {
            destPtr->x = (short int)srcPtr->x;
            destPtr->y = (short int)srcPtr->y;
            destPtr++;
        }
        XFillPolygon(graph->display, drawable, pmPtr->fillGC,
            pointArr, pmPtr->nFillPts, Complex, CoordModeOrigin);
        ckfree((char *)pointArr);
    }
    /* and then the outline */
    if((pmPtr->nOutlinePts > 0) && (pmPtr->lineWidth > 0) &&
        (pmPtr->outline.fgColor != NULL)) {
        RbcDraw2DSegments(graph->display, drawable, pmPtr->outlineGC,
            pmPtr->outlinePts, pmPtr->nOutlinePts);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * PolygonMarkerToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
PolygonMarkerToPostScript(
    RbcMarker * markerPtr,
    RbcPsToken * psToken)
{
RbcGraph *graph = markerPtr->graph;
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;

    if(pmPtr->fill.fgColor != NULL) {

        /*
         * Options:  fg bg
         *                      Draw outline only.
         *           x          Draw solid or stipple.
         *           x  x       Draw solid or stipple.
         */

        /* Create a path to use for both the polygon and its outline. */
        RbcPathToPostScript(psToken, pmPtr->fillPts, pmPtr->nFillPts);
        RbcAppendToPostScript(psToken, "closepath\n", (char *)NULL);

        /* If the background fill color was specified, draw the
         * polygon in a solid fashion with that color.  */
        if(pmPtr->fill.bgColor != NULL) {
            RbcBackgroundToPostScript(psToken, pmPtr->fill.bgColor);
            RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
        }
        RbcForegroundToPostScript(psToken, pmPtr->fill.fgColor);
        if(pmPtr->stipple != None) {
            /* Draw the stipple in the foreground color. */
            RbcStippleToPostScript(psToken, graph->display, pmPtr->stipple);
        } else {
            RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
        }
    }

    /* Draw the outline in the foreground color.  */
    if((pmPtr->lineWidth > 0) && (pmPtr->outline.fgColor != NULL)) {

        /*  Set up the line attributes.  */
        RbcLineAttributesToPostScript(psToken, pmPtr->outline.fgColor,
            pmPtr->lineWidth, &pmPtr->dashes, pmPtr->capStyle,
            pmPtr->joinStyle);

        /*
         * Define on-the-fly a PostScript macro "DashesProc" that
         * will be executed for each call to the Polygon drawing
         * routine.  If the line isn't dashed, simply make this an
         * empty definition.
         */
        if((pmPtr->outline.bgColor != NULL)
            && (RbcLineIsDashed(pmPtr->dashes))) {
            RbcAppendToPostScript(psToken, "/DashesProc {\n", "gsave\n    ",
                (char *)NULL);
            RbcBackgroundToPostScript(psToken, pmPtr->outline.bgColor);
            RbcAppendToPostScript(psToken, "    ", (char *)NULL);
            RbcLineDashesToPostScript(psToken, (RbcDashes *) NULL);
            RbcAppendToPostScript(psToken,
                "stroke\n", "  grestore\n", "} def\n", (char *)NULL);
        } else {
            RbcAppendToPostScript(psToken, "/DashesProc {} def\n",
                (char *)NULL);
        }
        Rbc2DSegmentsToPostScript(psToken, pmPtr->outlinePts,
            pmPtr->nOutlinePts);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigurePolygonMarker --
 *
 *      This procedure is called to process an argv/argc list, plus
 *      the Tk option database, in order to configure (or reconfigure)
 *      a polygon marker.
 *
 * Results:
 *      A standard Tcl result.  If TCL_ERROR is returned, then
 *      interp->result contains an error message.
 *
 * Side effects:
 *      Configuration information, such as polygon color, dashes,
 *      fillstyle, etc. get set for markerPtr; old resources get
 *      freed, if there were any.  The marker is eventually
 *      redisplayed.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigurePolygonMarker(
    RbcMarker * markerPtr)
{
RbcGraph *graph = markerPtr->graph;
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;
GC  newGC;
XGCValues gcValues;
unsigned long gcMask;
Drawable drawable;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    drawable = Tk_WindowId(*(graph->win));
    gcMask = (GCLineWidth | GCLineStyle);
    if(pmPtr->outline.fgColor != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = pmPtr->outline.fgColor->pixel;
    }
    if(pmPtr->outline.bgColor != NULL) {
        gcMask |= GCBackground;
        gcValues.background = pmPtr->outline.bgColor->pixel;
    }
    gcMask |= (GCCapStyle | GCJoinStyle);
    gcValues.cap_style = pmPtr->capStyle;
    gcValues.join_style = pmPtr->joinStyle;
    gcValues.line_style = LineSolid;
    gcValues.dash_offset = 0;
    gcValues.line_width = RbcLineWidth(pmPtr->lineWidth);
    if(RbcLineIsDashed(pmPtr->dashes)) {
        gcValues.line_style = (pmPtr->outline.bgColor == NULL)
            ? LineOnOffDash : LineDoubleDash;
    }
    if(pmPtr->xor) {
unsigned long pixel;
        gcValues.function = GXxor;

        gcMask |= GCFunction;
        if(graph->plotBg == NULL) {
            /* The graph's color option may not have been set yet */
            pixel = WhitePixelOfScreen(Tk_Screen(*(graph->win)));
        } else {
            pixel = graph->plotBg->pixel;
        }
        if(gcMask & GCBackground) {
            gcValues.background ^= pixel;
        }
        gcValues.foreground ^= pixel;
        if(drawable != None) {
            DrawPolygonMarker(markerPtr, drawable);
        }
    }
    newGC = RbcGetPrivateGC(*(graph->win), gcMask, &gcValues);
    if(RbcLineIsDashed(pmPtr->dashes)) {
        RbcSetDashes(graph->display, newGC, &pmPtr->dashes);
    }
    if(pmPtr->outlineGC != NULL) {
        RbcFreePrivateGC(graph->display, pmPtr->outlineGC);
    }
    pmPtr->outlineGC = newGC;

    gcMask = 0;
    if(pmPtr->fill.fgColor != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = pmPtr->fill.fgColor->pixel;
    }
    if(pmPtr->fill.bgColor != NULL) {
        gcMask |= GCBackground;
        gcValues.background = pmPtr->fill.bgColor->pixel;
    }
    if(pmPtr->stipple != None) {
        gcValues.stipple = pmPtr->stipple;
        gcValues.fill_style = (pmPtr->fill.bgColor != NULL)
            ? FillOpaqueStippled : FillStippled;
        gcMask |= (GCStipple | GCFillStyle);
    }
    newGC = Tk_GetGC(*(graph->win), gcMask, &gcValues);
    if(pmPtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, pmPtr->fillGC);
    }
    pmPtr->fillGC = newGC;

    if((gcMask == 0) && !(graph->flags & RBC_RESET_AXES) && (pmPtr->xor)) {
        if(drawable != None) {
            MapPolygonMarker(markerPtr);
            DrawPolygonMarker(markerPtr, drawable);
        }
        return TCL_OK;
    }
    pmPtr->flags |= RBC_MAP_ITEM;
    if(pmPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * FreePolygonMarker --
 *
 *      Release memory and resources allocated for the polygon element.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the polygon element is freed up.
 *
 * ----------------------------------------------------------------------
 */
static void
FreePolygonMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr)
{
PolygonMarker *pmPtr = (PolygonMarker *) markerPtr;

    if(pmPtr->fillGC != NULL) {
        Tk_FreeGC(graph->display, pmPtr->fillGC);
    }
    if(pmPtr->outlineGC != NULL) {
        RbcFreePrivateGC(graph->display, pmPtr->outlineGC);
    }
    if(pmPtr->fillPts != NULL) {
        ckfree((char *)pmPtr->fillPts);
    }
    if(pmPtr->outlinePts != NULL) {
        ckfree((char *)pmPtr->outlinePts);
    }
    RbcFreeColorPair(&pmPtr->outline);
    RbcFreeColorPair(&pmPtr->fill);
}

/*
 * ----------------------------------------------------------------------
 *
 * CreatePolygonMarker --
 *
 *      Allocate memory and initialize methods for the new polygon
 *      marker.
 *
 * Results:
 *      The pointer to the newly allocated marker structure is
 *      returned.
 *
 * Side effects:
 *      Memory is allocated for the polygon marker structure.
 *
 * ----------------------------------------------------------------------
 */
static RbcMarker *
CreatePolygonMarker(
    )
{
PolygonMarker *pmPtr;

    pmPtr = RbcCalloc(1, sizeof(PolygonMarker));
    if(pmPtr != NULL) {
        pmPtr->classPtr = &polygonMarkerClass;
        pmPtr->capStyle = CapButt;
        pmPtr->joinStyle = JoinMiter;

    }
    return (RbcMarker *) pmPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
NameToMarker(
    RbcGraph * graph,
    Tk_Window tkWin,
    const char *name,
    RbcMarker ** markerPtrPtr)
{
    Tcl_HashEntry *hPtr;

    hPtr = Tcl_FindHashEntry(&graph->markers.table, name);
    if(hPtr != NULL) {
        *markerPtrPtr = (RbcMarker *) Tcl_GetHashValue(hPtr);
        return TCL_OK;
    }
    Tcl_AppendResult(graph->interp, "can't find marker \"", name,
        "\" in \"", Tk_PathName(tkWin), (char *)NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * RenameMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
RenameMarker(
    RbcGraph * graph,
    RbcMarker * markerPtr,
    char *oldName,
    char *newName)
{
    int isNew;
    Tcl_HashEntry *hPtr;

    /* Rename the marker only if no marker already exists by that name */
    hPtr = Tcl_CreateHashEntry(&graph->markers.table, newName, &isNew);
    if(!isNew) {
        Tcl_AppendResult(graph->interp, "can't rename marker: \"", newName,
            "\" already exists", (char *)NULL);
        return TCL_ERROR;
    }
    markerPtr->name = RbcStrdup(newName);
    markerPtr->hashPtr = hPtr;
    Tcl_SetHashValue(hPtr, (char *)markerPtr);

    /* Delete the old hash entry */
    hPtr = Tcl_FindHashEntry(&graph->markers.table, oldName);
    Tcl_DeleteHashEntry(hPtr);
    if(oldName != NULL) {
        ckfree((char *)oldName);
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * NamesOp --
 *
 *      Returns a list of marker identifiers in interp->result;
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
NamesOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    RbcChainLink *linkPtr;
    register int i;

    Tcl_ResetResult(interp);
    for(linkPtr = RbcChainFirstLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);
        if(argc == 3) {
            Tcl_AppendElement(interp, markerPtr->name);
            continue;
        }
        for(i = 3; i < argc; i++) {
            if(Tcl_StringMatch(markerPtr->name, argv[i])) {
                Tcl_AppendElement(interp, markerPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMakeMarkerTag --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
ClientData
RbcMakeMarkerTag(
    RbcGraph * graph,
    const char *tagName)
{
Tcl_HashEntry *hPtr;
int isNew;

    hPtr = Tcl_CreateHashEntry(&graph->markers.tagTable, tagName, &isNew);
    assert(hPtr);
    return Tcl_GetHashKey(&graph->markers.tagTable, hPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * BindOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    if(argc == 3) {
    Tcl_HashEntry *hPtr;
    Tcl_HashSearch cursor;
    char *tag;

        for(hPtr = Tcl_FirstHashEntry(&graph->markers.tagTable, &cursor);
            hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
            tag = Tcl_GetHashKey(&graph->markers.tagTable, hPtr);
            Tcl_AppendElement(interp, tag);
        }
        return TCL_OK;
    }
    return RbcConfigureBindings(interp, graph->bindTable,
        RbcMakeMarkerTag(graph, argv[3]), argc - 4, argv + 4);
}

/*
 *----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(NameToMarker(graph, *(graph->win), argv[3], &markerPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tk_ConfigureValue(interp, *(graph->win),
            markerPtr->classPtr->configSpecs, (char *)markerPtr, argv[4], 0)
        != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      TODO: Description
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    int flags = TK_CONFIG_ARGV_ONLY;
    char *oldName;
    int nNames, nOpts;
    const char **options;
    register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

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

    for(i = 0; i < nNames; i++) {
        NameToMarker(graph, *(graph->win), argv[i], &markerPtr);
        if(nOpts == 0) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                markerPtr->classPtr->configSpecs, (char *)markerPtr,
                (char *)NULL, flags);
        } else if(nOpts == 1) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                markerPtr->classPtr->configSpecs, (char *)markerPtr,
                options[0], flags);
        }
        /* Save the old marker. */
        oldName = markerPtr->name;
        if(Tk_ConfigureWidget(interp, *(graph->win),
                markerPtr->classPtr->configSpecs, nOpts, options,
                (char *)markerPtr, flags) != TCL_OK) {
            return TCL_ERROR;
        }
        if(oldName != markerPtr->name) {
            if(RenameMarker(graph, markerPtr, oldName, markerPtr->name)
                != TCL_OK) {
                markerPtr->name = oldName;
                return TCL_ERROR;
            }
        }
        if((*markerPtr->classPtr->configProc) (markerPtr) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateOp --
 *
 *      This procedure creates and initializes a new marker.
 *
 * Results:
 *      The return value is a pointer to a structure describing
 *      the new element.  If an error occurred, then the return
 *      value is NULL and an error message is left in interp->result.
 *
 * Side effects:
 *      Memory is allocated, etc.
 *
 * ----------------------------------------------------------------------
 */
static int
CreateOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    Tcl_HashEntry *hPtr;
    int isNew;
    Tk_Uid classUid;
    register int i;
    const char *name;
    char string[200];
    unsigned int length;
    char c;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    c = argv[3][0];
    /* Create the new marker based upon the given type */
    if((c == 't') && (strcmp(argv[3], "text") == 0)) {
        classUid = rbcTextMarkerUid;
    } else if((c == 'l') && (strcmp(argv[3], "line") == 0)) {
        classUid = rbcLineMarkerUid;
    } else if((c == 'p') && (strcmp(argv[3], "polygon") == 0)) {
        classUid = rbcPolygonMarkerUid;
    } else if((c == 'i') && (strcmp(argv[3], "image") == 0)) {
        classUid = rbcImageMarkerUid;
    } else if((c == 'b') && (strcmp(argv[3], "bitmap") == 0)) {
        classUid = rbcBitmapMarkerUid;
    } else if((c == 'w') && (strcmp(argv[3], "window") == 0)) {
        classUid = rbcWindowMarkerUid;
    } else {
        Tcl_AppendResult(interp, "unknown marker type \"", argv[3],
            "\": should be \"text\", \"line\", \"polygon\", \"bitmap\", \"image\", or \
\"window\"", (char *)NULL);
        return TCL_ERROR;
    }
    /* Scan for "-name" option. We need it for the component name */
    name = NULL;
    for(i = 4; i < argc; i += 2) {
        length = strlen(argv[i]);
        if((length > 1) && (strncmp(argv[i], "-name", length) == 0)) {
            name = argv[i + 1];
            break;
        }
    }
    /* If no name was given for the marker, make up one. */
    if(name == NULL) {
        sprintf(string, "marker%d", graph->nextMarkerId++);
        name = string;
    } else if(name[0] == '-') {
        Tcl_AppendResult(interp, "name of marker \"", name,
            "\" can't start with a '-'", (char *)NULL);
        return TCL_ERROR;
    }
    markerPtr = CreateMarker(graph, name, classUid);
    if(RbcConfigureWidgetComponent(interp, *(graph->win), name,
            markerPtr->classUid, markerPtr->classPtr->configSpecs,
            argc - 4, argv + 4, (char *)markerPtr, 0) != TCL_OK) {
        DestroyMarker(markerPtr);
        return TCL_ERROR;
    }
    if((*markerPtr->classPtr->configProc) (markerPtr) != TCL_OK) {
        DestroyMarker(markerPtr);
        return TCL_ERROR;
    }
    hPtr = Tcl_CreateHashEntry(&graph->markers.table, name, &isNew);
    if(!isNew) {
    RbcMarker *oldMarkerPtr;
        /*
         * Marker by the same name already exists.  Delete the old
         * marker and it's list entry.  But save the hash entry.
         */
        oldMarkerPtr = (RbcMarker *) Tcl_GetHashValue(hPtr);
        oldMarkerPtr->hashPtr = NULL;
        DestroyMarker(oldMarkerPtr);
    }
    Tcl_SetHashValue(hPtr, markerPtr);
    markerPtr->hashPtr = hPtr;
    markerPtr->linkPtr = RbcChainAppend(graph->markers.displayList, markerPtr);
    if(markerPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(name, -1));
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * DeleteOp --
 *
 *      Deletes the marker given by markerId.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new display list.
 *
 * ----------------------------------------------------------------------
 */
static int
DeleteOp(
    RbcGraph * graph,
    Tcl_Interp * interp,       /* Not used. */
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    for(i = 3; i < argc; i++) {
        if(NameToMarker(graph, *(graph->win), argv[i], &markerPtr) == TCL_OK) {
            DestroyMarker(markerPtr);
        }
    }
    Tcl_ResetResult(interp);
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GetOp --
 *
 *      Find the legend entry from the given argument.  The argument
 *      can be either a screen position "@x,y" or the name of an
 *      element.
 *
 *      I don't know how useful it is to test with the name of an
 *      element.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new legend attributes.
 *
 *----------------------------------------------------------------------
 */
static int
GetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Not used. */
    const char *argv[])
{
    register RbcMarker *markerPtr;

    if((argv[3][0] == 'c') && (strcmp(argv[3], "current") == 0)) {
        markerPtr = (RbcMarker *) RbcGetCurrentItem(graph->bindTable);
        /* Report only on markers. */
        if(markerPtr == NULL) {
            return TCL_OK;
        }
        if((markerPtr->classUid == rbcBitmapMarkerUid) ||
            (markerPtr->classUid == rbcLineMarkerUid) ||
            (markerPtr->classUid == rbcWindowMarkerUid) ||
            (markerPtr->classUid == rbcPolygonMarkerUid) ||
            (markerPtr->classUid == rbcTextMarkerUid) ||
            (markerPtr->classUid == rbcImageMarkerUid)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(markerPtr->name, -1));
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RelinkOp --
 *
 *      Reorders the marker (given by the first name) before/after
 *      the another marker (given by the second name) in the
 *      marker display list.  If no second name is given, the
 *      marker is placed at the beginning/end of the list.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      Graph will be redrawn to reflect the new display list.
 *
 * ----------------------------------------------------------------------
 */
static int
RelinkOp(
    RbcGraph * graph,
    Tcl_Interp * interp,       /* Not used. */
    int argc,
    const char **argv)
{
    RbcChainLink *linkPtr, *placePtr;
    RbcMarker *markerPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    /* Find the marker to be raised or lowered. */
    if(NameToMarker(graph, *(graph->win), argv[3], &markerPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    /* Right now it's assumed that all markers are always in the
     * display list. */
    linkPtr = markerPtr->linkPtr;
    RbcChainUnlinkLink(graph->markers.displayList, markerPtr->linkPtr);

    placePtr = NULL;
    if(argc == 5) {
        if(NameToMarker(graph, *(graph->win), argv[4], &markerPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        placePtr = markerPtr->linkPtr;
    }

    /* Link the marker at its new position. */
    if(argv[2][0] == 'a') {
        RbcChainLinkAfter(graph->markers.displayList, linkPtr, placePtr);
    } else {
        RbcChainLinkBefore(graph->markers.displayList, linkPtr, placePtr);
    }
    if(markerPtr->drawUnder) {
        graph->flags |= RBC_REDRAW_BACKING_STORE;
    }
    RbcEventuallyRedrawGraph(graph);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * FindOp --
 *
 *      Returns if marker by a given ID currently exists.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
FindOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcChainLink *linkPtr;
    RbcExtents2D exts;
    RbcMarker *markerPtr;
    int mode;
    int left, right, top, bottom;
    int enclosed;

#define FIND_ENCLOSED	 (1<<0)
#define FIND_OVERLAPPING (1<<1)
    if(strcmp(argv[3], "enclosed") == 0) {
        mode = FIND_ENCLOSED;
    } else if(strcmp(argv[3], "overlapping") == 0) {
        mode = FIND_OVERLAPPING;
    } else {
        Tcl_AppendResult(interp, "bad search type \"", argv[3],
            ": should be \"enclosed\", or \"overlapping\"", (char *)NULL);
        return TCL_ERROR;
    }

    if((Tcl_GetInt(interp, argv[4], &left) != TCL_OK) ||
        (Tcl_GetInt(interp, argv[5], &top) != TCL_OK) ||
        (Tcl_GetInt(interp, argv[6], &right) != TCL_OK) ||
        (Tcl_GetInt(interp, argv[7], &bottom) != TCL_OK)) {
        return TCL_ERROR;
    }
    if(left < right) {
        exts.left = (double)left;
        exts.right = (double)right;
    } else {
        exts.left = (double)right;
        exts.right = (double)left;
    }
    if(top < bottom) {
        exts.top = (double)top;
        exts.bottom = (double)bottom;
    } else {
        exts.top = (double)bottom;
        exts.bottom = (double)top;
    }
    enclosed = (mode == FIND_ENCLOSED);
    for(linkPtr = RbcChainFirstLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);
        if(markerPtr->hidden) {
            continue;
        }
        if(markerPtr->elemName != NULL) {
    Tcl_HashEntry *hPtr;

            hPtr = Tcl_FindHashEntry(&graph->elements.table,
                markerPtr->elemName);
            if(hPtr != NULL) {
    RbcElement *elemPtr;

                elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
                if(elemPtr->hidden) {
                    continue;
                }
            }
        }
        if((*markerPtr->classPtr->regionProc) (markerPtr, &exts, enclosed)) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(markerPtr->name, -1));
            return TCL_OK;
        }
    }
    Tcl_ResetResult(interp);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * ExistsOp --
 *
 *      Returns if marker by a given ID currently exists.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
ExistsOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    Tcl_HashEntry *hPtr;

    hPtr = Tcl_FindHashEntry(&graph->markers.table, argv[3]);
    Tcl_SetObjResult(interp, Tcl_NewBooleanObj((hPtr != NULL)));
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TypeOp --
 *
 *      Returns a symbolic name for the type of the marker whose ID is
 *      given.
 *
 * Results:
 *      A standard Tcl result. interp->result will contain the symbolic
 *      type of the marker.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
TypeOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcMarker *markerPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(NameToMarker(graph, *(graph->win), argv[3], &markerPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(markerPtr->classUid, -1));
    return TCL_OK;
}

/* Public routines */

static RbcOpSpec markerOps[] = {
    {"after", 1, (RbcOp) RelinkOp, 4, 5, "marker ?afterMarker?",},
    {"before", 2, (RbcOp) RelinkOp, 4, 5, "marker ?beforeMarker?",},
    {"bind", 2, (RbcOp) BindOp, 3, 6, "marker sequence command",},
    {"cget", 2, (RbcOp) CgetOp, 5, 5, "marker option",},
    {"configure", 2, (RbcOp) ConfigureOp, 4, 0,
        "marker ?marker?... ?option value?...",},
    {"create", 2, (RbcOp) CreateOp, 4, 0,
        "type ?option value?...",},
    {"delete", 1, (RbcOp) DeleteOp, 3, 0, "?marker?...",},
    {"exists", 1, (RbcOp) ExistsOp, 4, 4, "marker",},
    {"find", 1, (RbcOp) FindOp, 8, 8, "enclosed|overlapping x1 y1 x2 y2",},
    {"get", 1, (RbcOp) GetOp, 4, 4, "name",},
    {"names", 1, (RbcOp) NamesOp, 3, 0, "?pattern?...",},
    {"type", 1, (RbcOp) TypeOp, 4, 4, "marker",},
};

static int nMarkerOps = sizeof(markerOps) / sizeof(RbcOpSpec);

/*
 * ----------------------------------------------------------------------
 *
 * RbcMarkerOp --
 *
 *      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.
 *
 * ----------------------------------------------------------------------
 */
int
RbcMarkerOp(
    RbcGraph * graph,
    Tcl_Interp * interp,       /* Not used. */
    int argc,
    const char **argv)
{
    RbcOp proc;
    int result;

    proc = RbcGetOp(interp, nMarkerOps, markerOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    result = (*proc) (graph, interp, argc, argv);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMarkersToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMarkersToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    int under)
{
    RbcChainLink *linkPtr;
    register RbcMarker *markerPtr;

    for(linkPtr = RbcChainFirstLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);
        if((markerPtr->classPtr->postscriptProc == NULL) ||
            (markerPtr->nWorldPts == 0)) {
            continue;
        }
        if(markerPtr->drawUnder != under) {
            continue;
        }
        if(markerPtr->hidden) {
            continue;
        }
        if(markerPtr->elemName != NULL) {
    Tcl_HashEntry *hPtr;

            hPtr = Tcl_FindHashEntry(&graph->elements.table,
                markerPtr->elemName);
            if(hPtr != NULL) {
    RbcElement *elemPtr;

                elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
                if(elemPtr->hidden) {
                    continue;
                }
            }
        }
        RbcAppendToPostScript(psToken, "\n% Marker \"", markerPtr->name,
            "\" is a ", markerPtr->classUid, " marker\n", (char *)NULL);
        (*markerPtr->classPtr->postscriptProc) (markerPtr, psToken);
    }
}

/*
 * -------------------------------------------------------------------------
 *
 * RbcDrawMarkers --
 *
 *      Calls the individual drawing routines (based on marker type)
 *      for each marker in the display list.
 *
 *      A marker will not be drawn if
 *
 *      1) An element linked to the marker (indicated by elemName)
 *         is currently hidden.
 *
 *      2) No coordinates have been specified for the marker.
 *
 *      3) The marker is requesting to be drawn at a different level
 *         (above/below the elements) from the current mode.
 *
 *      4) The marker is configured as hidden (-hide option).
 *
 *      5) The marker isn't visible in the current viewport
 *         (i.e. clipped).
 *
 * Results:
 *      None
 *
 * Side Effects:
 *      Markers are drawn into the drawable (pixmap) which will eventually
 *      be displayed in the graph window.
 *
 * -------------------------------------------------------------------------
 */
void
RbcDrawMarkers(
    RbcGraph * graph,
    Drawable drawable,         /* Pixmap or window to draw into */
    int under)
{
    RbcChainLink *linkPtr;
    RbcMarker *markerPtr;

    for(linkPtr = RbcChainFirstLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);

        if((markerPtr->nWorldPts == 0) ||
            (markerPtr->drawUnder != under) ||
            (markerPtr->hidden) || (markerPtr->clipped)) {
            continue;
        }
        if(markerPtr->elemName != NULL) {
    Tcl_HashEntry *hPtr;

            /* Look up the named element and see if it's hidden */
            hPtr = Tcl_FindHashEntry(&graph->elements.table,
                markerPtr->elemName);
            if(hPtr != NULL) {
    RbcElement *elemPtr;

                elemPtr = (RbcElement *) Tcl_GetHashValue(hPtr);
                if(elemPtr->hidden) {
                    continue;
                }
            }
        }

        (*markerPtr->classPtr->drawProc) (markerPtr, drawable);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMapMarkers --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcMapMarkers(
    RbcGraph * graph)
{
RbcChainLink *linkPtr;
RbcMarker *markerPtr;

    for(linkPtr = RbcChainFirstLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainNextLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);
        if((markerPtr->nWorldPts == 0) || (markerPtr->hidden)) {
            continue;
        }
        if((graph->flags & RBC_MAP_ALL)
            || (markerPtr->flags & RBC_MAP_ITEM)) {
            (*markerPtr->classPtr->mapProc) (markerPtr);
            markerPtr->flags &= ~RBC_MAP_ITEM;
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyMarkers --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyMarkers(
    RbcGraph * graph)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcMarker *markerPtr;

    for(hPtr = Tcl_FirstHashEntry(&graph->markers.table, &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        markerPtr = (RbcMarker *) Tcl_GetHashValue(hPtr);
        /*
         * Dereferencing the pointer to the hash table prevents the
         * hash table entry from being automatically deleted.
         */
        markerPtr->hashPtr = NULL;
        DestroyMarker(markerPtr);
    }
    Tcl_DeleteHashTable(&graph->markers.table);
    Tcl_DeleteHashTable(&graph->markers.tagTable);
    RbcChainDestroy(graph->markers.displayList);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcNearestMarker --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcMarker *
RbcNearestMarker(
    RbcGraph * graph,
    int x,                     /* Screen coordinates */
    int y,                     /* Screen coordinates */
    int under)
{
    RbcChainLink *linkPtr;
    RbcMarker *markerPtr;
    RbcPoint2D point;

    point.x = (double)x;
    point.y = (double)y;
    for(linkPtr = RbcChainLastLink(graph->markers.displayList);
        linkPtr != NULL; linkPtr = RbcChainPrevLink(linkPtr)) {
        markerPtr = RbcChainGetValue(linkPtr);
        if((markerPtr->drawUnder == under) && (markerPtr->nWorldPts > 0) &&
            (!markerPtr->hidden) && (markerPtr->state == RBC_STATE_NORMAL)) {
            if((*markerPtr->classPtr->pointProc) (markerPtr, &point)) {
                return markerPtr;
            }
        }
    }
    return NULL;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphMisc.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrMisc.c --
 *
 *      This module implements miscellaneous routines for the rbc
 *      graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define RBC_SCROLL_MODE_CANVAS	(1<<0)
#define RBC_SCROLL_MODE_LISTBOX	(1<<1)
#define RBC_SCROLL_MODE_HIERBOX	(1<<2)

typedef struct {
    double hue, sat, val;
} HSV;

static Tk_OptionParseProc StringToPoint;
static Tk_OptionPrintProc PointToString;
static Tk_OptionParseProc StringToColorPair;
static Tk_OptionPrintProc ColorPairToString;
Tk_CustomOption rbcPointOption = {
    StringToPoint, PointToString, (ClientData) 0
};

Tk_CustomOption rbcColorPairOption = {
    StringToColorPair, ColorPairToString, (ClientData) 0
};

static int GetColorPair(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *fgStr,
    const char *bgStr,
    RbcColorPair * pairPtr,
    int allowDefault);
static const char *NameOfColor(
    XColor * colorPtr);
static int ClipTest(
    double ds,
    double dr,
    double *t1,
    double *t2);
static double FindSplit(
    RbcPoint2D points[],
    int i,
    int j,
    int *split);

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

/*
 *----------------------------------------------------------------------
 *
 * RbcGetXY --
 *
 *      Converts a string in the form "@x,y" into an XPoint structure
 *      of the x and y coordinates.
 *
 * Results:
 *      A standard Tcl result. If the string represents a valid position
 *      *pointPtr* will contain the converted x and y coordinates and
 *      TCL_OK is returned.  Otherwise,	TCL_ERROR is returned and
 *      interp->result will contain an error message.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetXY(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *string,
    int *xPtr,
    int *yPtr)
{
    char *comma;
    int result;
    int x, y;

    if((string == NULL) || (*string == '\0')) {
        *xPtr = *yPtr = -SHRT_MAX;
        return TCL_OK;
    }
    if(*string != '@') {
        goto badFormat;
    }
    comma = strchr(string + 1, ',');
    if(comma == NULL) {
        goto badFormat;
    }
    *comma = '\0';
    result = ((Tk_GetPixels(interp, tkwin, string + 1, &x) == TCL_OK) &&
        (Tk_GetPixels(interp, tkwin, comma + 1, &y) == TCL_OK));
    *comma = ',';
    if(!result) {
        Tcl_AppendResult(interp, ": can't parse position \"", string, "\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    *xPtr = x, *yPtr = y;
    return TCL_OK;

  badFormat:
    Tcl_AppendResult(interp, "bad position \"", string,
        "\": should be \"@x,y\"", (char *)NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPoint --
 *
 *      Convert the string representation of a legend XY position into
 *      window coordinates.  The form of the string must be "@x,y" or
 *      none.
 *
 * Results:
 *      A standard Tcl result.  The symbol type is written into the
 *      widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToPoint(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New legend position string */
    char *widgRec,             /* Widget record */
    int offset)
{              /* offset to XPoint structure */
    XPoint *pointPtr = (XPoint *) (widgRec + offset);
    int x, y;

    if(RbcGetXY(interp, tkwin, string, &x, &y) != TCL_OK) {
        return TCL_ERROR;
    }
    pointPtr->x = x, pointPtr->y = y;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * PointToString --
 *
 *      Convert the window coordinates into a string.
 *
 * Results:
 *      The string representing the coordinate position is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
PointToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record */
    int offset,                /* offset of XPoint in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Memory deallocation scheme to use */
    const char *result;
    XPoint *pointPtr = (XPoint *) (widgRec + offset);

    result = "";
    if((pointPtr->x != -SHRT_MAX) && (pointPtr->y != -SHRT_MAX)) {
    char string[200];

        sprintf(string, "@%d,%d", pointPtr->x, pointPtr->y);
        result = RbcStrdup(string);
        assert(result);
        *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * GetColorPair --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
GetColorPair(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *fgStr,
    const char *bgStr,
    RbcColorPair * pairPtr,
    int allowDefault)
{
    unsigned int length;
    XColor *fgColor, *bgColor;

    length = strlen(fgStr);
    if(fgStr[0] == '\0') {
        fgColor = NULL;
    } else if((allowDefault) && (fgStr[0] == 'd') &&
        (strncmp(fgStr, "defcolor", length) == 0)) {
        fgColor = RBC_COLOR_DEFAULT;
    } else {
        fgColor = Tk_GetColor(interp, tkwin, Tk_GetUid(fgStr));
        if(fgColor == NULL) {
            return TCL_ERROR;
        }
    }
    length = strlen(bgStr);
    if(bgStr[0] == '\0') {
        bgColor = NULL;
    } else if((allowDefault) && (bgStr[0] == 'd') &&
        (strncmp(bgStr, "defcolor", length) == 0)) {
        bgColor = RBC_COLOR_DEFAULT;
    } else {
        bgColor = Tk_GetColor(interp, tkwin, Tk_GetUid(bgStr));
        if(bgColor == NULL) {
            return TCL_ERROR;
        }
    }
    pairPtr->fgColor = fgColor;
    pairPtr->bgColor = bgColor;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreeColorPair --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreeColorPair(
    RbcColorPair * pairPtr)
{
    if((pairPtr->bgColor != NULL) && (pairPtr->bgColor != RBC_COLOR_DEFAULT)) {
        Tk_FreeColor(pairPtr->bgColor);
    }
    if((pairPtr->fgColor != NULL) && (pairPtr->fgColor != RBC_COLOR_DEFAULT)) {
        Tk_FreeColor(pairPtr->fgColor);
    }
    pairPtr->bgColor = pairPtr->fgColor = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToColorPair --
 *
 *      Convert the color names into pair of XColor pointers.
 *
 * Results:
 *      A standard Tcl result.  The color pointer is written into the
 *      widget record.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
StringToColorPair(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing color */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of color field in record */
    RbcColorPair *pairPtr = (RbcColorPair *) (widgRec + offset);
    RbcColorPair sample;
    int allowDefault = (int)clientData;

    sample.fgColor = sample.bgColor = NULL;
    if((string != NULL) && (*string != '\0')) {
    int nColors;
    const char **colors;
    int result;

        if(Tcl_SplitList(interp, string, &nColors, &colors) != TCL_OK) {
            return TCL_ERROR;
        }
        switch (nColors) {
        case 0:
            result = TCL_OK;
            break;
        case 1:
            result = GetColorPair(interp, tkwin, colors[0], "", &sample,
                allowDefault);
            break;
        case 2:
            result = GetColorPair(interp, tkwin, colors[0], colors[1],
                &sample, allowDefault);
            break;
        default:
            result = TCL_ERROR;
            Tcl_AppendResult(interp, "too many names in colors list",
                (char *)NULL);
        }
        ckfree((char *)colors);
        if(result != TCL_OK) {
            return TCL_ERROR;
        }
    }
    RbcFreeColorPair(pairPtr);
    *pairPtr = sample;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfColor --
 *
 *      Convert the color option value into a string.
 *
 * Results:
 *      The static string representing the color option is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfColor(
    XColor * colorPtr)
{
    if(colorPtr == NULL) {
        return "";
    } else if(colorPtr == RBC_COLOR_DEFAULT) {
        return "defcolor";
    } else {
        return Tk_NameOfColor(colorPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ColorPairToString --
 *
 *      Convert the color pairs into color names.
 *
 * Results:
 *      The string representing the symbol color is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ColorPairToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Element information record */
    int offset,                /* Offset of symbol type field in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcColorPair *pairPtr = (RbcColorPair *) (widgRec + offset);
    Tcl_DString dString;
    char *result;

    Tcl_DStringInit(&dString);
    Tcl_DStringAppendElement(&dString, NameOfColor(pairPtr->fgColor));
    Tcl_DStringAppendElement(&dString, NameOfColor(pairPtr->bgColor));
    result = Tcl_DStringValue(&dString);
    if(result == dString.staticSpace) {
        result = RbcStrdup(result);
    }
    *freeProcPtr = (Tcl_FreeProc *) Tcl_Free;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcPointInSegments --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcPointInSegments(
    RbcPoint2D * samplePtr,
    RbcSegment2D * segments,
    int nSegments,
    double halo)
{
    register RbcSegment2D *segPtr, *endPtr;
    double left, right, top, bottom;
    RbcPoint2D p, t;
    double dist, minDist;

    minDist = DBL_MAX;
    for(segPtr = segments, endPtr = segments + nSegments; segPtr < endPtr;
        segPtr++) {
        t = RbcGetProjection((int)samplePtr->x, (int)samplePtr->y, &segPtr->p,
            &segPtr->q);
        if(segPtr->p.x > segPtr->q.x) {
            right = segPtr->p.x, left = segPtr->q.x;
        } else {
            right = segPtr->q.x, left = segPtr->p.x;
        }
        if(segPtr->p.y > segPtr->q.y) {
            bottom = segPtr->p.y, top = segPtr->q.y;
        } else {
            bottom = segPtr->q.y, top = segPtr->p.y;
        }
        if(t.x > right) {
            p.x = right;
        } else if(t.x < left) {
            p.x = left;
        } else {
            p.x = t.x;
        }
        if(t.y > bottom) {
            p.y = bottom;
        } else if(t.y < top) {
            p.y = top;
        } else {
            p.y = t.y;
        }
        dist = hypot(p.x - samplePtr->x, p.y - samplePtr->y);
        if(dist < minDist) {
            minDist = dist;
        }
    }
    return (minDist < halo);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcPointInPolygon --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcPointInPolygon(
    RbcPoint2D * samplePtr,
    RbcPoint2D * points,
    int nPoints)
{
    double b;
    register RbcPoint2D *p, *q, *endPtr;
    register int count;

    count = 0;
    for(p = points, q = p + 1, endPtr = p + nPoints; q < endPtr; p++, q++) {
        if(((p->y <= samplePtr->y) && (samplePtr->y < q->y)) ||
            ((q->y <= samplePtr->y) && (samplePtr->y < p->y))) {
            b = (q->x - p->x) * (samplePtr->y - p->y) / (q->y - p->y) + p->x;
            if(samplePtr->x < b) {
                count++;        /* Count the number of intersections. */
            }
        }
    }
    return (count & 0x01);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcRegionInPolygon --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcRegionInPolygon(
    RbcExtents2D * extsPtr,
    RbcPoint2D * points,
    int nPoints,
    int enclosed)
{
    register RbcPoint2D *pointPtr, *endPtr;

    if(enclosed) {
        /*
         * All points of the polygon must be inside the rectangle.
         */
        for(pointPtr = points, endPtr = points + nPoints; pointPtr < endPtr;
            pointPtr++) {
            if((pointPtr->x < extsPtr->left) ||
                (pointPtr->x > extsPtr->right) ||
                (pointPtr->y < extsPtr->top) ||
                (pointPtr->y > extsPtr->bottom)) {
                return FALSE;   /* One point is exterior. */
            }
        }
        return TRUE;
    } else {
    RbcPoint2D p, q;

        /*
         * If any segment of the polygon clips the bounding region, the
         * polygon overlaps the rectangle.
         */
        points[nPoints] = points[0];
        for(pointPtr = points, endPtr = points + nPoints; pointPtr < endPtr;
            pointPtr++) {
            p = *pointPtr;
            q = *(pointPtr + 1);
            if(RbcLineRectClip(extsPtr, &p, &q)) {
                return TRUE;
            }
        }
        /*
         * Otherwise the polygon and rectangle are either disjoint
         * or enclosed.  Check if one corner of the rectangle is
         * inside the polygon.
         */
        p.x = extsPtr->left;
        p.y = extsPtr->top;
        return RbcPointInPolygon(&p, points, nPoints);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGraphExtents --
 *
 *      Generates a bounding box representing the plotting area of
 *      the graph. This data structure is used to clip the points and
 *      line segments of the line element.
 *
 *      The clip region is the plotting area plus such arbitrary extra
 *      space.  The reason we clip with a bounding box larger than the
 *      plot area is so that symbols will be drawn even if their center
 *      point isn't in the plotting area.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The bounding box is filled with the dimensions of the plotting
 *      area.
 *
 *----------------------------------------------------------------------
 */
void
RbcGraphExtents(
    RbcGraph * graphPtr,
    RbcExtents2D * extsPtr)
{
    extsPtr->left = (double)(graphPtr->hOffset - graphPtr->padX.side1);
    extsPtr->top = (double)(graphPtr->vOffset - graphPtr->padY.side1);
    extsPtr->right = (double)(graphPtr->hOffset + graphPtr->hRange +
        graphPtr->padX.side2);
    extsPtr->bottom = (double)(graphPtr->vOffset + graphPtr->vRange +
        graphPtr->padY.side2);
}

/*
 *----------------------------------------------------------------------
 *
 * ClipTest --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
ClipTest(
    double ds,
    double dr,
    double *t1,
    double *t2)
{
    double t;

    if(ds < 0.0) {
        t = dr / ds;
        if(t > *t2) {
            return FALSE;
        }
        if(t > *t1) {
            *t1 = t;
        }
    } else if(ds > 0.0) {
        t = dr / ds;
        if(t < *t1) {
            return FALSE;
        }
        if(t < *t2) {
            *t2 = t;
        }
    } else {
        /* d = 0, so line is parallel to this clipping edge */
        if(dr < 0.0) {  /* Line is outside clipping edge */
            return FALSE;
        }
    }
    return TRUE;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcLineRectClip --
 *
 *      Clips the given line segment to a rectangular region.  The
 *      coordinates of the clipped line segment are returned.  The
 *      original coordinates are overwritten.
 *
 *      Reference:  Liang-Barsky Line Clipping Algorithm.
 *
 * Results:
 *      Returns if line segment is visible within the region. The
 *      coordinates of the original line segment are overwritten
 *      by the clipped coordinates.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcLineRectClip(
    RbcExtents2D * extsPtr,    /* Rectangular region to clip. */
    RbcPoint2D * p,            /* (in/out) Coordinates of original
                                * and clipped line segment. */
    RbcPoint2D * q)
{              /* (in/out) Coordinates of original
                * and clipped line segment. */
double t1, t2;
double dx, dy;

    t1 = 0.0;
    t2 = 1.0;
    dx = q->x - p->x;
    if((ClipTest(-dx, p->x - extsPtr->left, &t1, &t2)) &&
        (ClipTest(dx, extsPtr->right - p->x, &t1, &t2))) {
        dy = q->y - p->y;
        if((ClipTest(-dy, p->y - extsPtr->top, &t1, &t2)) &&
            (ClipTest(dy, extsPtr->bottom - p->y, &t1, &t2))) {
            if(t2 < 1.0) {
                q->x = p->x + t2 * dx;
                q->y = p->y + t2 * dy;
            }
            if(t1 > 0.0) {
                p->x += t1 * dx;
                p->y += t1 * dy;
            }
            return TRUE;
        }
    }
    return FALSE;
}

#define EPSILON  FLT_EPSILON
#define AddVertex(vx, vy)	    r->x=(vx), r->y=(vy), r++, count++
#define LastVertex(vx, vy)	    r->x=(vx), r->y=(vy), count++

/*
 *----------------------------------------------------------------------
 *
 * RbcPolyRectClip --
 *
 *      Clips the given polygon to a rectangular region.  The resulting
 *      polygon is returned. Note that the resulting polyon may be
 *      complex, connected by zero width/height segments.  The drawing
 *      routine (such as XFillPolygon) will not draw a connecting
 *      segment.
 *
 *      Reference:  Liang-Barsky Polygon Clipping Algorithm
 *
 * Results:
 *      Returns the number of points in the clipped polygon. The
 *      points of the clipped polygon are stored in *outputPts*.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcPolyRectClip(
    RbcExtents2D * extsPtr,
    RbcPoint2D * points,
    int nPoints,
    RbcPoint2D * clipPts)
{
    RbcPoint2D *endPtr;
    double dx, dy;
    double tin1, tin2;
    double tinx, tiny;
    double xin, yin, xout, yout;
    int count;
    register RbcPoint2D *p;    /* First vertex of input polygon edge. */
    register RbcPoint2D *q;    /* Last vertex of input polygon edge. */
    register RbcPoint2D *r;

    r = clipPts;
    count = 0; /* Counts # of vertices in output polygon. */

    points[nPoints] = points[0];

    for(p = points, q = p + 1, endPtr = p + nPoints; p < endPtr; p++, q++) {
        dx = q->x - p->x;       /* X-direction */
        dy = q->y - p->y;       /* Y-direction */

        if(FABS(dx) < EPSILON) {
            dx = (p->x > extsPtr->left) ? -EPSILON : EPSILON;
        }
        if(FABS(dy) < EPSILON) {
            dy = (p->y > extsPtr->top) ? -EPSILON : EPSILON;
        }

        if(dx > 0.0) {  /* Left */
            xin = extsPtr->left;
            xout = extsPtr->right + 1.0;
        } else {        /* Right */
            xin = extsPtr->right + 1.0;
            xout = extsPtr->left;
        }
        if(dy > 0.0) {  /* Top */
            yin = extsPtr->top;
            yout = extsPtr->bottom + 1.0;
        } else {        /* Bottom */
            yin = extsPtr->bottom + 1.0;
            yout = extsPtr->top;
        }

        tinx = (xin - p->x) / dx;
        tiny = (yin - p->y) / dy;

        if(tinx < tiny) {       /* Hits x first */
            tin1 = tinx;
            tin2 = tiny;
        } else {        /* Hits y first */
            tin1 = tiny;
            tin2 = tinx;
        }

        if(tin1 <= 1.0) {
            if(tin1 > 0.0) {
                AddVertex(xin, yin);
            }
            if(tin2 <= 1.0) {
    double toutx, touty, tout1;

                toutx = (xout - p->x) / dx;
                touty = (yout - p->y) / dy;
                tout1 = MIN(toutx, touty);

                if((tin2 > 0.0) || (tout1 > 0.0)) {
                    if(tin2 <= tout1) {
                        if(tin2 > 0.0) {
                            if(tinx > tiny) {
                                AddVertex(xin, p->y + tinx * dy);
                            } else {
                                AddVertex(p->x + tiny * dx, yin);
                            }
                        }
                        if(tout1 < 1.0) {
                            if(toutx < touty) {
                                AddVertex(xout, p->y + toutx * dy);
                            } else {
                                AddVertex(p->x + touty * dx, yout);
                            }
                        } else {
                            AddVertex(q->x, q->y);
                        }
                    } else {
                        if(tinx > tiny) {
                            AddVertex(xin, yout);
                        } else {
                            AddVertex(xout, yin);
                        }
                    }
                }
            }
        }
    }
    if(count > 0) {
        LastVertex(clipPts[0].x, clipPts[0].y);
    }
    return count;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetProjection --
 *
 *      Computes the projection of a point on a line.  The line (given
 *      by two points), is assumed the be infinite.
 *
 *      Compute the slope (angle) of the line and rotate it 90 degrees.
 *      Using the slope-intercept method (we know the second line from
 *      the sample test point and the computed slope), then find the
 *      intersection of both lines. This will be the projection of the
 *      sample point on the first line.
 *
 * Results:
 *      Returns the coordinates of the projection on the line.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcPoint2D
RbcGetProjection(
    int x,                     /* Screen coordinates of the sample point. */
    int y,                     /* Screen coordinates of the sample point. */
    RbcPoint2D * p,            /* Line segment to project point onto */
    RbcPoint2D * q)
{              /* Line segment to project point onto */
double dx, dy;
RbcPoint2D t;

    dx = p->x - q->x;
    dy = p->y - q->y;

    /* Test for horizontal and vertical lines */
    if(FABS(dx) < DBL_EPSILON) {
        t.x = p->x, t.y = (double)y;
    } else if(FABS(dy) < DBL_EPSILON) {
        t.x = (double)x, t.y = p->y;
    } else {
double m1, m2;                 /* Slope of both lines */
double b1, b2;                 /* y-intercepts */
double midX, midY;             /* Midpoint of line segment. */
double ax, ay, bx, by;

        /* Compute the slop and intercept of the line segment. */
        m1 = (dy / dx);
        b1 = p->y - (p->x * m1);

        /*
         * Compute the slope and intercept of a second line segment:
         * one that intersects through sample X-Y coordinate with a
         * slope perpendicular to original line.
         */

        /* Find midpoint of original segment. */
        midX = (p->x + q->x) * 0.5;
        midY = (p->y + q->y) * 0.5;

        /* Rotate the line 90 degrees */
        ax = midX - (0.5 * dy);
        ay = midY - (0.5 * -dx);
        bx = midX + (0.5 * dy);
        by = midY + (0.5 * -dx);

        m2 = (ay - by) / (ax - bx);
        b2 = y - (x * m2);

        /*
         * Given the equations of two lines which contain the same point,
         *
         *    y = m1 * x + b1
         *    y = m2 * x + b2
         *
         * solve for the intersection.
         *
         *    x = (b2 - b1) / (m1 - m2)
         *    y = m1 * x + b1
         *
         */

        t.x = (b2 - b1) / (m1 - m2);
        t.y = m1 * t.x + b1;
    }
    return t;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcAdjustViewport --
 *
 *      Adjusts the offsets of the viewport according to the scroll mode.
 *      This is to accommodate both "listbox" and "canvas" style scrolling.
 *
 *      "canvas"    The viewport scrolls within the range of world
 *              coordinates.  This way the viewport always displays
 *              a full page of the world.  If the world is smaller
 *              than the viewport, then (bizarrely) the world and
 *              viewport are inverted so that the world moves up
 *              and down within the viewport.
 *
 *      "listbox"    The viewport can scroll beyond the range of world
 *              coordinates.  Every entry can be displayed at the
 *              top of the viewport.  This also means that the
 *              scrollbar thumb weirdly shrinks as the last entry
 *              is scrolled upward.
 *
 * Results:
 *      The corrected offset is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcAdjustViewport(
    int offset,
    int worldSize,
    int windowSize,
    int scrollUnits,
    int scrollMode)
{
    switch (scrollMode) {
    case RBC_SCROLL_MODE_CANVAS:

        /*
         * Canvas-style scrolling allows the world to be scrolled
         * within the window.
         */

        if(worldSize < windowSize) {
            if((worldSize - offset) > windowSize) {
                offset = worldSize - windowSize;
            }
            if(offset > 0) {
                offset = 0;
            }
        } else {
            if((offset + windowSize) > worldSize) {
                offset = worldSize - windowSize;
            }
            if(offset < 0) {
                offset = 0;
            }
        }
        break;

    case RBC_SCROLL_MODE_LISTBOX:
        if(offset < 0) {
            offset = 0;
        }
        if(offset >= worldSize) {
            offset = worldSize - scrollUnits;
        }
        break;

    case RBC_SCROLL_MODE_HIERBOX:

        /*
         * Hierbox-style scrolling allows the world to be scrolled
         * within the window.
         */
        if((offset + windowSize) > worldSize) {
            offset = worldSize - windowSize;
        }
        if(offset < 0) {
            offset = 0;
        }
        break;
    }
    return offset;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetScrollInfo --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetScrollInfo(
    Tcl_Interp * interp,
    int argc,
    char **argv,
    int *offsetPtr,
    int worldSize,
    int windowSize,
    int scrollUnits,
    int scrollMode)
{
    char c;
    unsigned int length;
    int offset;
    int count;
    double fract;

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

#if (TCL_MAJOR_VERSION >= 8)

/*
 *----------------------------------------------------------------------
 *
 * RbcGetScrollInfoFromObj --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetScrollInfoFromObj(
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const *objv,
    int *offsetPtr,
    int worldSize,
    int windowSize,
    int scrollUnits,
    int scrollMode)
{
    char c;
    unsigned int length;
    int offset;
    int count;
    double fract;
    char *string;

    offset = *offsetPtr;

    string = Tcl_GetString(objv[0]);
    c = string[0];
    length = strlen(string);
    if((c == 's') && (strncmp(string, "scroll", length) == 0)) {
        if(objc != 3) {
            return TCL_ERROR;
        }
        /* scroll number unit/page */
        if(Tcl_GetIntFromObj(interp, objv[1], &count) != TCL_OK) {
            return TCL_ERROR;
        }
        string = Tcl_GetString(objv[2]);
        c = string[0];
        length = strlen(string);
        if((c == 'u') && (strncmp(string, "units", length) == 0)) {
    fract = (double)count *scrollUnits;
        } else if((c == 'p') && (strncmp(string, "pages", length) == 0)) {
            /* A page is 90% of the view-able window. */
    fract = (double)count *windowSize * 0.9;
        } else {
            Tcl_AppendResult(interp, "unknown \"scroll\" units \"",
                Tcl_GetString(objv[2]), "\"", (char *)NULL);
            return TCL_ERROR;
        }
        offset += (int)fract;
    } else if((c == 'm') && (strncmp(string, "moveto", length) == 0)) {
        if(objc != 2) {
            return TCL_ERROR;
        }
        /* moveto fraction */
        if(Tcl_GetDoubleFromObj(interp, objv[1], &fract) != TCL_OK) {
            return TCL_ERROR;
        }
        offset = (int)(worldSize * fract);
    } else {
        /* Treat like "scroll units" */
        if(Tcl_GetIntFromObj(interp, objv[0], &count) != TCL_OK) {
            return TCL_ERROR;
        }
    fract = (double)count *scrollUnits;
        offset += (int)fract;
    }
    *offsetPtr = RbcAdjustViewport(offset, worldSize, windowSize, scrollUnits,
        scrollMode);
    return TCL_OK;
}
#endif /* TCL_MAJOR_VERSION >= 8 */

/*
 * ----------------------------------------------------------------------
 *
 * RbcUpdateScrollbar --
 *
 *      Invoke a Tcl command to the scrollbar, defining the new
 *      position and length of the scroll. See the Tk documentation
 *      for further information on the scrollbar.  It is assumed the
 *      scrollbar command prefix is valid.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Scrollbar is commanded to change position and/or size.
 *
 * ----------------------------------------------------------------------
 */
void
RbcUpdateScrollbar(
    Tcl_Interp * interp,
    char *scrollCmd,           /* scrollbar command */
    double firstFract,
    double lastFract)
{
    char string[200];
    Tcl_DString dString;

    Tcl_DStringInit(&dString);
    Tcl_DStringAppend(&dString, scrollCmd, -1);
    sprintf(string, " %f %f", firstFract, lastFract);
    Tcl_DStringAppend(&dString, string, -1);
    if(Tcl_GlobalEval(interp, Tcl_DStringValue(&dString)) != TCL_OK) {
        Tcl_BackgroundError(interp);
    }
    Tcl_DStringFree(&dString);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetPrivateGCFromDrawable --
 *
 *      Like Tk_GetGC, but doesn't share the GC with any other widget.
 *      This is needed because the certain GC parameters (like dashes)
 *      can not be set via XCreateGC, therefore there is no way for
 *      Tk's hashing mechanism to recognize that two such GCs differ.
 *
 * Results:
 *      A new GC is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
GC
RbcGetPrivateGCFromDrawable(
    Display * display,
    Drawable drawable,
    unsigned long gcMask,
    XGCValues * valuePtr)
{
    GC  newGC;

#ifdef _WIN32
    newGC = RbcEmulateXCreateGC(display, drawable, gcMask, valuePtr);
#else
    newGC = XCreateGC(display, drawable, gcMask, valuePtr);
#endif
    return newGC;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetPrivateGC --
 *
 *      Like Tk_GetGC, but doesn't share the GC with any other widget.
 *      This is needed because the certain GC parameters (like dashes)
 *      can not be set via XCreateGC, therefore there is no way for
 *      Tk's hashing mechanism to recognize that two such GCs differ.
 *
 * Results:
 *      A new GC is returned.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
GC
RbcGetPrivateGC(
    Tk_Window tkwin,
    unsigned long gcMask,
    XGCValues * valuePtr)
{
GC  gc;
Pixmap pixmap;
Drawable drawable;
Display *display;

    pixmap = None;
    drawable = Tk_WindowId(tkwin);
    display = Tk_Display(tkwin);

    if(drawable == None) {
Drawable root;
int depth;

        root = RootWindow(display, Tk_ScreenNumber(tkwin));
        depth = Tk_Depth(tkwin);

        if(depth == DefaultDepth(display, Tk_ScreenNumber(tkwin))) {
            drawable = root;
        } else {
            pixmap = Tk_GetPixmap(display, root, 1, 1, depth);
            drawable = pixmap;
        }
    }
    gc = RbcGetPrivateGCFromDrawable(display, drawable, gcMask, valuePtr);
    if(pixmap != None) {
        Tk_FreePixmap(display, pixmap);
    }
    return gc;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreePrivateGC --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreePrivateGC(
    Display * display,
    GC gc)
{
    Tk_FreeXId(display, (XID) XGContextFromGC(gc));
    XFreeGC(display, gc);
}

#ifndef _WIN32

/*
 *----------------------------------------------------------------------
 *
 * RbcSetDashes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcSetDashes(
    Display * display,
    GC gc,
    RbcDashes * dashesPtr)
{
    XSetDashes(display, gc, dashesPtr->offset,
        (const char *)dashesPtr->values, strlen((char *)dashesPtr->values));
}
#endif

/*
 *----------------------------------------------------------------------
 *
 * FindSplit --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static double
FindSplit(
    RbcPoint2D points[],
    int i,                     /* Indices specifying the range of points. */
    int j,                     /* Indices specifying the range of points. */
    int *split)
{              /* (out) Index of next split. */
    double maxDist;

    maxDist = -1.0;
    if((i + 1) < j) {
    register int k;
    double a, b, c;
    double sqDist;

        /*
         *
         * sqDist P(k) =  |  1  P(i).x  P(i).y  |
         *                |  1  P(j).x  P(j).y  |
         *                |  1  P(k).x  P(k).y  |
         *              ---------------------------
         *       (P(i).x - P(j).x)^2 + (P(i).y - P(j).y)^2
         */

        a = points[i].y - points[j].y;
        b = points[j].x - points[i].x;
        c = (points[i].x * points[j].y) - (points[i].y * points[j].x);
        for(k = (i + 1); k < j; k++) {
            sqDist = (points[k].x * a) + (points[k].y * b) + c;
            if(sqDist < 0.0) {
                sqDist = -sqDist;
            }
            if(sqDist > maxDist) {
                maxDist = sqDist;       /* Track the maximum. */
                *split = k;
            }
        }
        /* Correction for segment length---should be redone if can == 0 */
        maxDist *= maxDist / (a * a + b * b);
    }
    return maxDist;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSimplifyLine --
 *
 *      Douglas-Peucker line simplification algorithm
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcSimplifyLine(
    RbcPoint2D inputPts[],
    int low,
    int high,
    double tolerance,
    int indices[])
{
#define StackPush(a)	s++, stack[s] = (a)
#define StackPop(a)	(a) = stack[s], s--
#define StackEmpty()	(s < 0)
#define StackTop()	stack[s]
    int *stack;
    int split = -1;
    double sqDist, sqTolerance;
    int s = -1;                /* Points to top stack item. */
    int count;

    stack = (int *)ckalloc(sizeof(int) * (high - low + 1));
    StackPush(high);
    count = 0;
    indices[count++] = 0;
    sqTolerance = tolerance * tolerance;
    while(!StackEmpty()) {
        sqDist = FindSplit(inputPts, low, StackTop(), &split);
        if(sqDist > sqTolerance) {
            StackPush(split);
        } else {
            indices[count++] = StackTop();
            StackPop(low);
        }
    }
    ckfree((char *)stack);
    return count;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDraw2DSegments --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcDraw2DSegments(
    Display * display,
    Drawable drawable,
    GC gc,
    register RbcSegment2D * segPtr,
    int nSegments)
{
    XSegment *xSegPtr, *xSegArr;
    RbcSegment2D *endPtr;

    xSegArr = (XSegment *) ckalloc(nSegments * sizeof(XSegment));
    if(xSegArr == NULL) {
        return;
    }
    xSegPtr = xSegArr;
    for(endPtr = segPtr + nSegments; segPtr < endPtr; segPtr++) {
        xSegPtr->x1 = (short int)segPtr->p.x;
        xSegPtr->y1 = (short int)segPtr->p.y;
        xSegPtr->x2 = (short int)segPtr->q.x;
        xSegPtr->y2 = (short int)segPtr->q.y;
        xSegPtr++;
    }
    XDrawSegments(display, drawable, gc, xSegArr, nSegments);
    ckfree((char *)xSegArr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcMaxRequestSize --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcMaxRequestSize(
    Display * display,
    unsigned int elemSize)
{
    long size;

    size = SHRT_MAX / 4;        /* XMaxRequestSize emulation */
    size -= 4;
    return ((size * 4) / elemSize);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphPen.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrPen.c --
 *
 *      This module implements pens for the rbc graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

static Tk_OptionParseProc StringToColor;
static Tk_OptionPrintProc ColorToString;
static Tk_OptionParseProc StringToPen;
static Tk_OptionPrintProc PenToString;
Tk_CustomOption rbcColorOption = {
    StringToColor, ColorToString, (ClientData) 0
};

Tk_CustomOption rbcPenOption = {
    StringToPen, PenToString, (ClientData) 0
};

Tk_CustomOption rbcBarPenOption = {
    StringToPen, PenToString, (ClientData) & rbcBarElementUid
};

Tk_CustomOption rbcLinePenOption = {
    StringToPen, PenToString, (ClientData) & rbcLineElementUid
};

static const char *NameOfColor(
    XColor * colorPtr);
static RbcPen *NameToPen(
    RbcGraph * graph,
    const char *name);
static int CgetOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char *argv[]);
static int ConfigureOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char *argv[]);
static int CreateOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv);
static int DeleteOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv);
static int NamesOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv);
static int TypeOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv);

/*
 *----------------------------------------------------------------------

 * StringToColor --
 *
 *      Convert the string representation of a color into a XColor pointer.
 *
 * Results:
 *      The return value is a standard Tcl result.  The color pointer is
 *      written into the widget record.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static int
StringToColor(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing color */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of color field in record */
    XColor **colorPtrPtr = (XColor **) (widgRec + offset);
    XColor *colorPtr;
    unsigned int length;
    char c;

    if((string == NULL) || (*string == '\0')) {
        *colorPtrPtr = NULL;
        return TCL_OK;
    }
    c = string[0];
    length = strlen(string);

    if((c == 'd') && (strncmp(string, "defcolor", length) == 0)) {
        colorPtr = RBC_COLOR_DEFAULT;
    } else {
        colorPtr = Tk_GetColor(interp, tkwin, Tk_GetUid(string));
        if(colorPtr == NULL) {
            return TCL_ERROR;
        }
    }
    *colorPtrPtr = colorPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfColor --
 *
 *      Convert the color option value into a string.
 *
 * Results:
 *      The static string representing the color option is returned.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfColor(
    XColor * colorPtr)
{
    if(colorPtr == NULL) {
        return "";
    } else if(colorPtr == RBC_COLOR_DEFAULT) {
        return "defcolor";
    } else {
        return Tk_NameOfColor(colorPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ColorToString --
 *
 *      Convert the color value into a string.
 *
 * Results:
 *      The string representing the symbol color is returned.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static const char *
ColorToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget information record */
    int offset,                /* Offset of symbol type in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    XColor *colorPtr = *(XColor **) (widgRec + offset);

    return NameOfColor(colorPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * StringToPen --
 *
 *      Convert the color value into a string.
 *
 * Results:
 *      The string representing the symbol color is returned.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static int
StringToPen(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* String representing pen */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of pen field in record */
    Tk_Uid classUid = *(Tk_Uid *) clientData;   /* Element type. */
    RbcPen **penPtrPtr = (RbcPen **) (widgRec + offset);
    RbcPen *penPtr;
    RbcGraph *graph;

    penPtr = NULL;
    graph = RbcGetGraphFromWindowData(tkwin);

    if(classUid == NULL) {
        classUid = graph->classUid;
    }
    if((string != NULL) && (string[0] != '\0')) {
        if(RbcGetPen(graph, string, classUid, &penPtr) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    /* Release the old pen */
    if(*penPtrPtr != NULL) {
        RbcFreePen(graph, *penPtrPtr);
    }
    *penPtrPtr = penPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * PenToString --
 *
 *      Parse the name of the name.
 *
 * Results:
 *      The return value is a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static const char *
PenToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget information record */
    int offset,                /* Offset of pen in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcPen *penPtr = *(RbcPen **) (widgRec + offset);

    return penPtr->name;
}

/*
 *----------------------------------------------------------------------
 *
 * NameToPen --
 *
 *      Find and return the pen style from a given name.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static RbcPen *
NameToPen(
    RbcGraph * graph,
    const char *name)
{
    Tcl_HashEntry *hPtr;
    RbcPen *penPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return NULL;

    hPtr = Tcl_FindHashEntry(&(graph->penTable), name);
    if(hPtr == NULL) {
        goto notFound;
    }
    penPtr = (RbcPen *) Tcl_GetHashValue(hPtr);
    if(penPtr->flags & RBC_PEN_DELETE_PENDING) {
        goto notFound;
    }
    return penPtr;
  notFound:
    Tcl_AppendResult(graph->interp, "can't find pen \"", name,
        "\" in \"", Tk_PathName(*(graph->win)), "\"", (char *)NULL);
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyPen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
    Tk_FreeOptions(penPtr->configSpecs, (char *)penPtr, graph->display, 0);
    (*penPtr->destroyProc) (graph, penPtr);
    if((penPtr->name != NULL) && (penPtr->name[0] != '\0')) {
        ckfree((char *)penPtr->name);
    }
    if(penPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(penPtr->hashPtr);
    }
    ckfree((char *)penPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreePen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreePen(
    RbcGraph * graph,
    RbcPen * penPtr)
{
    penPtr->refCount--;
    if((penPtr->refCount == 0) && (penPtr->flags & RBC_PEN_DELETE_PENDING)) {
        DestroyPen(graph, penPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreatePen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcPen *
RbcCreatePen(
    RbcGraph * graph,
    const char *penName,
    Tk_Uid classUid,
    int nOpts,
    const char **options)
{

    RbcPen *penPtr;
    Tcl_HashEntry *hPtr;
    unsigned int length, configFlags;
    int isNew;
    register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return NULL;

    /*
     * Scan the option list for a "-type" entry.  This will indicate
     * what type of pen we are creating. Otherwise we'll default to the
     * suggested type.  Last -type option wins.
     */
    for(i = 0; i < nOpts; i += 2) {
        length = strlen(options[i]);
        if((length > 2) && (strncmp(options[i], "-type", length) == 0)) {
    const char *arg;

            arg = options[i + 1];
            if(strcmp(arg, "bar") == 0) {
                classUid = rbcBarElementUid;
            } else if(strcmp(arg, "line") != 0) {
                classUid = rbcLineElementUid;
            } else if(strcmp(arg, "strip") != 0) {
                classUid = rbcLineElementUid;
            } else {
                Tcl_AppendResult(graph->interp, "unknown pen type \"",
                    arg, "\" specified", (char *)NULL);
                return NULL;
            }
        }
    }
    if(classUid == rbcStripElementUid) {
        classUid = rbcLineElementUid;
    }
    hPtr = Tcl_CreateHashEntry(&(graph->penTable), penName, &isNew);
    if(!isNew) {
        penPtr = (RbcPen *) Tcl_GetHashValue(hPtr);
        if(!(penPtr->flags & RBC_PEN_DELETE_PENDING)) {
            Tcl_AppendResult(graph->interp, "pen \"", penName,
                "\" already exists in \"", Tk_PathName(*(graph->win)), "\"",
                (char *)NULL);
            return NULL;
        }
        if(penPtr->classUid != classUid) {
            Tcl_AppendResult(graph->interp, "pen \"", penName,
                "\" in-use: can't change pen type from \"", penPtr->classUid,
                "\" to \"", classUid, "\"", (char *)NULL);
            return NULL;
        }
        penPtr->flags &= ~RBC_PEN_DELETE_PENDING;
    } else {
        if(classUid == rbcBarElementUid) {
            penPtr = RbcBarPen(penName);
        } else {
            penPtr = RbcLinePen(penName);
        }
        penPtr->classUid = classUid;
        penPtr->hashPtr = hPtr;
        Tcl_SetHashValue(hPtr, penPtr);
    }

    configFlags = (penPtr->flags & (RBC_ACTIVE_PEN | RBC_NORMAL_PEN));
    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win),
            penPtr->name, "Pen", penPtr->configSpecs, nOpts, options,
            (char *)penPtr, configFlags) != TCL_OK) {
        if(isNew) {
            DestroyPen(graph, penPtr);
        }
        return NULL;
    }
    (*penPtr->configProc) (graph, penPtr);
    return penPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetPen --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetPen(
    RbcGraph * graph,
    const char *name,
    Tk_Uid classUid,
    RbcPen ** penPtrPtr)
{
    RbcPen *penPtr;

    penPtr = NameToPen(graph, name);
    if(penPtr == NULL) {
        return TCL_ERROR;
    }
    if(classUid == rbcStripElementUid) {
        classUid = rbcLineElementUid;
    }
    if(penPtr->classUid != classUid) {
        Tcl_AppendResult(graph->interp, "pen \"", name,
            "\" is the wrong type (is \"", penPtr->classUid, "\"",
            ", wanted \"", classUid, "\")", (char *)NULL);
        return TCL_ERROR;
    }
    penPtr->refCount++;
    *penPtrPtr = penPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDestroyPens --
 *
 *      Release memory and resources allocated for the style.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Everything associated with the pen style is freed up.
 *
 *----------------------------------------------------------------------
 */
void
RbcDestroyPens(
    RbcGraph * graph)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcPen *penPtr;

    for(hPtr = Tcl_FirstHashEntry(&(graph->penTable), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        penPtr = (RbcPen *) Tcl_GetHashValue(hPtr);
        penPtr->hashPtr = NULL;
        DestroyPen(graph, penPtr);
    }
    Tcl_DeleteHashTable(&(graph->penTable));
}

/*
 * ----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *      Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *      A standard Tcl result.  If querying configuration values,
 *      interp->result will contain the results.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 * ----------------------------------------------------------------------
 */
static int
CgetOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,                  /* Not used. */
    const char *argv[])
{
    RbcPen *penPtr;
    unsigned int configFlags;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    penPtr = NameToPen(graph, argv[3]);
    if(penPtr == NULL) {
        return TCL_ERROR;
    }
    configFlags = (penPtr->flags & (RBC_ACTIVE_PEN | RBC_NORMAL_PEN));
    return Tk_ConfigureValue(interp, *(graph->win), penPtr->configSpecs,
        (char *)penPtr, argv[4], configFlags);
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      Queries or resets pen attributes (font, line width, color, etc).
 *
 * Results:
 *      A standard Tcl result.  If querying configuration values,
 *      interp->result will contain the results.
 *
 * Side Effects:
 *      Pen resources are possibly allocated (GC, font).
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char *argv[])
{
    int flags;
    RbcPen *penPtr;
    int nNames, nOpts;
    int redraw;
    const char **options;
    register int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

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

    redraw = 0;
    for(i = 0; i < nNames; i++) {
        penPtr = NameToPen(graph, argv[i]);
        flags =
            TK_CONFIG_ARGV_ONLY | (penPtr->flags & (RBC_ACTIVE_PEN |
                RBC_NORMAL_PEN));
        if(nOpts == 0) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                penPtr->configSpecs, (char *)penPtr, (char *)NULL, flags);
        } else if(nOpts == 1) {
            return Tk_ConfigureInfo(interp, *(graph->win),
                penPtr->configSpecs, (char *)penPtr, options[0], flags);
        }
        if(Tk_ConfigureWidget(interp, *(graph->win), penPtr->configSpecs,
                nOpts, options, (char *)penPtr, flags) != TCL_OK) {
            break;
        }
        (*penPtr->configProc) (graph, penPtr);
        if(penPtr->refCount > 0) {
            redraw++;
        }
    }
    if(redraw) {
        graph->flags |= RBC_REDRAW_BACKING_STORE | RBC_DRAW_MARGINS;
        RbcEventuallyRedrawGraph(graph);
    }
    if(i < nNames) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * CreateOp --
 *
 *      Adds a new penstyle to the graph.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *----------------------------------------------------------------------
 */
static int
CreateOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    RbcPen *penPtr;

    penPtr = RbcCreatePen(graph, argv[3], graph->classUid, argc - 4, argv + 4);
    if(penPtr == NULL) {
        return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(penPtr->name, -1));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * DeleteOp --
 *
 *      Delete the given pen.
 *
 * Results:
 *      Always returns TCL_OK.  The interp->result field is
 *      a list of the graph axis limits.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 *--------------------------------------------------------------
 */
static int
DeleteOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    RbcPen *penPtr;
    int i;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    for(i = 3; i < argc; i++) {
        penPtr = NameToPen(graph, argv[i]);
        if(penPtr == NULL) {
            return TCL_ERROR;
        }
        if(penPtr->flags & RBC_PEN_DELETE_PENDING) {
            Tcl_AppendResult(graph->interp, "can't find pen \"", argv[i],
                "\" in \"", Tk_PathName(*(graph->win)), "\"", (char *)NULL);
            return TCL_ERROR;
        }
        penPtr->flags |= RBC_PEN_DELETE_PENDING;
        if(penPtr->refCount == 0) {
            DestroyPen(graph, penPtr);
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * NamesOp --
 *
 *      Return a list of the names of all the axes.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 * ----------------------------------------------------------------------
 */
static int
NamesOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    Tcl_HashSearch cursor;
    RbcPen *penPtr;
    register int i;
    register Tcl_HashEntry *hPtr;

    for(hPtr = Tcl_FirstHashEntry(&(graph->penTable), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        penPtr = (RbcPen *) Tcl_GetHashValue(hPtr);
        if(penPtr->flags & RBC_PEN_DELETE_PENDING) {
            continue;
        }
        if(argc == 3) {
            Tcl_AppendElement(interp, penPtr->name);
            continue;
        }
        for(i = 3; i < argc; i++) {
            if(Tcl_StringMatch(penPtr->name, argv[i])) {
                Tcl_AppendElement(interp, penPtr->name);
                break;
            }
        }
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TypeOp --
 *
 *      Return the type of pen.
 *
 * Results:
 *      Returns a standard Tcl result.
 *
 * Side Effects:
 *      TODO: Side Effects:
 *
 * ----------------------------------------------------------------------
 */
static int
TypeOp(
    Tcl_Interp * interp,
    RbcGraph * graph,
    int argc,
    const char **argv)
{
    RbcPen *penPtr;

    penPtr = NameToPen(graph, argv[3]);
    if(penPtr == NULL) {
        return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(penPtr->classUid, -1));
    return TCL_OK;
}

static RbcOpSpec penOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 5, 5, "penName option",},
    {"configure", 2, (RbcOp) ConfigureOp, 4, 0,
        "penName ?penName?... ?option value?...",},
    {"create", 2, (RbcOp) CreateOp, 4, 0, "penName ?option value?...",},
    {"delete", 2, (RbcOp) DeleteOp, 3, 0, "?penName?...",},
    {"names", 1, (RbcOp) NamesOp, 3, 0, "?pattern?...",},
    {"type", 1, (RbcOp) TypeOp, 4, 4, "penName",},
};

static int nPenOps = sizeof(penOps) / sizeof(RbcOpSpec);

/*
 *----------------------------------------------------------------------
 *
 * RbcPenOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcPenOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv)
{
    RbcOp proc;

    proc = RbcGetOp(interp, nPenOps, penOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    return (*proc) (interp, graph, argc, argv);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoGraphPs.c.
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcGrPs.c --
 *
 *      This module implements the "postscript" operation for rbc
 *      graph widget.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define PS_PREVIEW_EPSI	0
#define PS_PREVIEW_WMF	1
#define PS_PREVIEW_TIFF	2

static Tk_OptionParseProc StringToColorMode;
static Tk_OptionPrintProc ColorModeToString;
static Tk_CustomOption colorModeOption = {
    StringToColorMode, ColorModeToString, (ClientData) 0,
};

static Tk_OptionParseProc StringToFormat;
static Tk_OptionPrintProc FormatToString;
static Tk_CustomOption formatOption = {
    StringToFormat, FormatToString, (ClientData) 0,
};

extern Tk_CustomOption rbcDistanceOption;
extern Tk_CustomOption rbcPositiveDistanceOption;
extern Tk_CustomOption rbcPadOption;

#define DEF_PS_CENTER		"yes"
#define DEF_PS_COLOR_MAP	(char *)NULL
#define DEF_PS_COLOR_MODE	"color"
#define DEF_PS_DECORATIONS	"yes"
#define DEF_PS_FONT_MAP		(char *)NULL
#define DEF_PS_FOOTER		"no"
#define DEF_PS_HEIGHT		"0"
#define DEF_PS_LANDSCAPE	"no"
#define DEF_PS_MAXPECT		"no"
#define DEF_PS_PADX		"1.0i"
#define DEF_PS_PADY		"1.0i"
#define DEF_PS_PAPERHEIGHT	"11.0i"
#define DEF_PS_PAPERWIDTH	"8.5i"
#define DEF_PS_PREVIEW		"no"
#define DEF_PS_PREVIEW_FORMAT   "epsi"
#define DEF_PS_WIDTH		"0"

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BOOLEAN, "-center", "center", "Center",
            DEF_PS_CENTER, Tk_Offset(RbcPostScript, center),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-colormap", "colorMap", "ColorMap",
            DEF_PS_COLOR_MAP, Tk_Offset(RbcPostScript, colorVarName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-colormode", "colorMode", "ColorMode",
            DEF_PS_COLOR_MODE, Tk_Offset(RbcPostScript, colorMode),
        TK_CONFIG_DONT_SET_DEFAULT, &colorModeOption},
    {TK_CONFIG_BOOLEAN, "-decorations", "decorations", "Decorations",
            DEF_PS_DECORATIONS, Tk_Offset(RbcPostScript, decorations),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-fontmap", "fontMap", "FontMap",
            DEF_PS_FONT_MAP, Tk_Offset(RbcPostScript, fontVarName),
        TK_CONFIG_NULL_OK},
    {TK_CONFIG_BOOLEAN, "-footer", "footer", "Footer",
            DEF_PS_FOOTER, Tk_Offset(RbcPostScript, footer),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-height", "height", "Height",
            DEF_PS_HEIGHT, Tk_Offset(RbcPostScript, reqHeight),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_BOOLEAN, "-landscape", "landscape", "Landscape",
            DEF_PS_LANDSCAPE, Tk_Offset(RbcPostScript, landscape),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-maxpect", "maxpect", "Maxpect",
            DEF_PS_MAXPECT, Tk_Offset(RbcPostScript, maxpect),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-padx", "padX", "PadX",
        DEF_PS_PADX, Tk_Offset(RbcPostScript, padX), 0, &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-pady", "padY", "PadY",
        DEF_PS_PADY, Tk_Offset(RbcPostScript, padY), 0, &rbcPadOption},
    {TK_CONFIG_CUSTOM, "-paperheight", "paperHeight", "PaperHeight",
            DEF_PS_PAPERHEIGHT, Tk_Offset(RbcPostScript, reqPaperHeight),
        0, &rbcPositiveDistanceOption},
    {TK_CONFIG_CUSTOM, "-paperwidth", "paperWidth", "PaperWidth",
            DEF_PS_PAPERWIDTH, Tk_Offset(RbcPostScript, reqPaperWidth),
        0, &rbcPositiveDistanceOption},
    {TK_CONFIG_BOOLEAN, "-preview", "preview", "Preview",
            DEF_PS_PREVIEW, Tk_Offset(RbcPostScript, addPreview),
        TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-previewformat", "previewFormat", "PreviewFormat",
            DEF_PS_PREVIEW_FORMAT, Tk_Offset(RbcPostScript, previewFormat),
        TK_CONFIG_DONT_SET_DEFAULT, &formatOption},
    {TK_CONFIG_CUSTOM, "-width", "width", "Width",
            DEF_PS_WIDTH, Tk_Offset(RbcPostScript, reqWidth),
        TK_CONFIG_DONT_SET_DEFAULT, &rbcDistanceOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* TODO: These do not belong here */
/*
extern void     RbcMarkersToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken,
    int under);
extern void     RbcElementsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
extern void     RbcActiveElementsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
extern void     RbcLegendToPostScript(
    RbcLegend * legendPtr,
    RbcPsToken * psToken);
extern void     RbcGridToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
extern void     RbcAxesToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
extern void     RbcAxisLimitsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
*/
static const char *NameOfColorMode(
    RbcPsColorMode colorMode);
static int CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[]);
static int ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int OutputOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char **argv);
static int ComputeBoundingBox(
    RbcGraph * graph,
    RbcPostScript * psPtr);
static void PreviewImage(
    RbcGraph * graph,
    RbcPsToken * psToken);
static int PostScriptPreamble(
    RbcGraph * graph,
    const char *fileName,
    RbcPsToken * psToken);
static void MarginsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken);
static int GraphToPostScript(
    RbcGraph * graph,
    const char *ident,
    RbcPsToken * psToken);

#ifdef _WIN32
static int CreateWindowsEPS(
    RbcGraph * graph,
    RbcPsToken * psToken,
    FILE * f);
#endif

/*
 *----------------------------------------------------------------------
 *
 * StringToColorMode --
 *
 *      Convert the string representation of a PostScript color mode
 *      into the enumerated type representing the color level:
 *
 *          PS_MODE_COLOR 	- Full color
 *          PS_MODE_GREYSCALE  	- Color converted to greyscale
 *          PS_MODE_MONOCHROME 	- Only black and white
 *
 * Results:
 *      A standard Tcl result.  The color level is written into the
 *      page layout information structure.
 *
 * Side Effects:
 *      Future invocations of the "postscript" option will use this
 *      variable to determine how color information will be displayed
 *      in the PostScript output it produces.
 *
 *----------------------------------------------------------------------
 */
static int
StringToColorMode(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New value. */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of field in record */
    RbcPsColorMode *modePtr = (RbcPsColorMode *) (widgRec + offset);
    unsigned int length;
    char c;

    c = string[0];
    length = strlen(string);
    if((c == 'c') && (strncmp(string, "color", length) == 0)) {
        *modePtr = PS_MODE_COLOR;
    } else if((c == 'g') && (strncmp(string, "grayscale", length) == 0)) {
        *modePtr = PS_MODE_GREYSCALE;
    } else if((c == 'g') && (strncmp(string, "greyscale", length) == 0)) {
        *modePtr = PS_MODE_GREYSCALE;
    } else if((c == 'm') && (strncmp(string, "monochrome", length) == 0)) {
        *modePtr = PS_MODE_MONOCHROME;
    } else {
        Tcl_AppendResult(interp, "bad color mode \"", string, "\": should be \
\"color\", \"greyscale\", or \"monochrome\"", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NameOfColorMode --
 *
 *      Convert the PostScript mode value into the string representing
 *      a valid color mode.
 *
 * Results:
 *      The static string representing the color mode is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfColorMode(
    RbcPsColorMode colorMode)
{
    switch (colorMode) {
    case PS_MODE_COLOR:
        return "color";
    case PS_MODE_GREYSCALE:
        return "greyscale";
    case PS_MODE_MONOCHROME:
        return "monochrome";
    default:
        return "unknown color mode";
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ColorModeToString --
 *
 *      Convert the current color mode into the string representing a
 *      valid color mode.
 *
 * Results:
 *      The string representing the color mode is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
ColorModeToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* Widget record. */
    int offset,                /* field of colorMode in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    RbcPsColorMode mode = *(RbcPsColorMode *) (widgRec + offset);

    return NameOfColorMode(mode);
}

/*
 *----------------------------------------------------------------------
 *
 * StringToFormat --
 *
 *      Convert the string of the PostScript preview format into
 *      an enumerated type representing the desired format.  The
 *      available formats are:
 *
 *        PS_PREVIEW_WMF 	- Windows Metafile.
 *        PS_PREVIEW_TIFF  	- TIFF bitmap image.
 *        PS_PREVIEW_EPSI 	- Device independent ASCII preview
 *
 * Results:
 *      A standard Tcl result.  The format is written into the
 *      page layout information structure.
 *
 * Side Effects:
 *      Future invocations of the "postscript" option will use this
 *      variable to determine how to format a preview image (if one
 *      is selected) when the PostScript output is produced.
 *
 *----------------------------------------------------------------------
 */
static int
StringToFormat(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,       /* Interpreter to send results back to */
    Tk_Window tkwin,           /* Not used. */
    const char *string,        /* New value. */
    char *widgRec,             /* Widget record */
    int offset)
{              /* Offset of field in record */
    int *formatPtr = (int *)(widgRec + offset);
    unsigned int length;
    char c;

    c = string[0];
    length = strlen(string);
    if((c == 'c') && (strncmp(string, "epsi", length) == 0)) {
        *formatPtr = PS_PREVIEW_EPSI;
#ifdef _WIN32
#ifdef HAVE_TIFF_H
    } else if((c == 't') && (strncmp(string, "tiff", length) == 0)) {
        *formatPtr = PS_PREVIEW_TIFF;
#endif /* HAVE_TIFF_H */
    } else if((c == 'w') && (strncmp(string, "wmf", length) == 0)) {
        *formatPtr = PS_PREVIEW_WMF;
#endif /* _WIN32 */
    } else {
        Tcl_AppendResult(interp, "bad format \"", string, "\": should be ",
#ifdef _WIN32
#ifdef HAVE_TIFF_H
            "\"tiff\" or ",
#endif /* HAVE_TIFF_H */
            "\"wmf\" or ",
#endif /* _WIN32 */
            "\"epsi\"", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FormatToString --
 *
 *      Convert the preview format into the string representing its
 *      type.
 *
 * Results:
 *      The string representing the preview format is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
FormatToString(
    ClientData clientData,     /* Not used. */
    Tk_Window tkwin,           /* Not used. */
    char *widgRec,             /* PostScript structure record */
    int offset,                /* field of colorMode in record */
    Tcl_FreeProc ** freeProcPtr)
{              /* Not used. */
    int format = *(int *)(widgRec + offset);

    switch (format) {
    case PS_PREVIEW_EPSI:
        return "epsi";
    case PS_PREVIEW_WMF:
        return "wmf";
    case PS_PREVIEW_TIFF:
        return "tiff";
    }
    return "?unknown preview format?";
}

/*
 *--------------------------------------------------------------
 *
 * RbcDestroyPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDestroyPostScript(
    RbcGraph * graph)
{
    Tk_FreeOptions(configSpecs, (char *)graph->postscript, graph->display, 0);
    ckfree((char *)graph->postscript);
}

/*
 *--------------------------------------------------------------
 *
 * CgetOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
CgetOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(Tk_ConfigureValue(interp, *(graph->win), configSpecs, (char *)psPtr,
            argv[3], 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *      This procedure is invoked to print the graph in a file.
 *
 * Results:
 *      A standard TCL result.
 *
 * Side effects:
 *      A new PostScript file is created.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureOp(
    RbcGraph * graph,
    Tcl_Interp * interp,
    int argc,                  /* Number of options in argv vector */
    const char **argv)
{              /* Option vector */
    int flags = TK_CONFIG_ARGV_ONLY;
    RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    if(argc == 3) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)psPtr, (char *)NULL, flags);
    } else if(argc == 4) {
        return Tk_ConfigureInfo(interp, *(graph->win), configSpecs,
            (char *)psPtr, argv[3], flags);
    }
    if(Tk_ConfigureWidget(interp, *(graph->win), configSpecs, argc - 3,
            argv + 3, (char *)psPtr, flags) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * --------------------------------------------------------------------------
 *
 * ComputeBoundingBox --
 *
 *      Computes the bounding box for the PostScript plot.  First get
 *      the size of the plot (by default, it's the size of graph's X
 *      window).  If the plot plus the page border is bigger than the
 *      designated paper size, or if the "-maxpect" option is turned
 *      on, scale the plot to the page.
 *
 *      Note: All coordinates/sizes are in screen coordinates, not
 *            PostScript coordinates.  This includes the computed
 *            bounding box and paper size.  They will be scaled to
 *            printer points later.
 *
 * Results:
 *      Returns the height of the paper in screen coordinates.
 *
 * Side Effects:
 *      The graph dimensions (width and height) are changed to the
 *      requested PostScript plot size.
 *
 * --------------------------------------------------------------------------
 */
static int
ComputeBoundingBox(
    RbcGraph * graph,
    RbcPostScript * psPtr)
{
int paperWidth, paperHeight;
int x, y, hSize, vSize, hBorder, vBorder;
double hScale, vScale, scale;

    x = psPtr->padX.side1;      /*left */
    y = psPtr->padY.side1;      /*top */
    hBorder = RbcPadding(psPtr->padX);
    vBorder = RbcPadding(psPtr->padY);

    if(psPtr->reqWidth > 0) {
        graph->width = psPtr->reqWidth;
    }
    if(psPtr->reqHeight > 0) {
        graph->height = psPtr->reqHeight;
    }
    if(psPtr->landscape) {
        hSize = graph->height;
        vSize = graph->width;
    } else {
        hSize = graph->width;
        vSize = graph->height;
    }
    /*
     * If the paper size wasn't specified, set it to the graph size plus
     * the paper border.
     */
    paperWidth = psPtr->reqPaperWidth;
    paperHeight = psPtr->reqPaperHeight;
    if(paperWidth < 1) {
        paperWidth = hSize + hBorder;
    }
    if(paperHeight < 1) {
        paperHeight = vSize + vBorder;
    }
    hScale = vScale = 1.0;
    /*
     * Scale the plot size (the graph itself doesn't change size) if
     * it's bigger than the paper or if -maxpect was set.
     */
    if((psPtr->maxpect) || ((hSize + hBorder) > paperWidth)) {
        hScale = (double)(paperWidth - hBorder) / (double)hSize;
    }
    if((psPtr->maxpect) || ((vSize + vBorder) > paperHeight)) {
        vScale = (double)(paperHeight - vBorder) / (double)vSize;
    }
    scale = MIN(hScale, vScale);
    if(scale != 1.0) {
        hSize = (int)((hSize * scale) + 0.5);
        vSize = (int)((vSize * scale) + 0.5);
    }
    psPtr->pageScale = scale;
    if(psPtr->center) {
        if(paperWidth > hSize) {
            x = (paperWidth - hSize) / 2;
        }
        if(paperHeight > vSize) {
            y = (paperHeight - vSize) / 2;
        }
    }
    psPtr->left = x;
    psPtr->bottom = y;
    psPtr->right = x + hSize - 1;
    psPtr->top = y + vSize - 1;

    graph->flags |= RBC_LAYOUT_NEEDED | RBC_MAP_WORLD;
    RbcLayoutGraph(graph);
    return paperHeight;
}

/*
 * --------------------------------------------------------------------------
 *
 * PreviewImage --
 *
 *      Generates a EPSI thumbnail of the graph.  The thumbnail is
 *      restricted to a certain size.  This is to keep the size of the
 *      PostScript file small and the processing time low.
 *
 *      The graph is drawn into a pixmap.  We then take a snapshot
 *      of that pixmap, and rescale it to a smaller image.  Finally,
 *       the image is dumped to PostScript.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * --------------------------------------------------------------------------
 */
static void
PreviewImage(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
int noBackingStore = 0;
Pixmap drawable;
RbcColorImage *image;
int nLines;
Tcl_DString dString;
    if(graph->win == NULL || *(graph->win) == NULL)
        return;

    /* Create a pixmap and draw the graph into it. */

    drawable = Tk_GetPixmap(graph->display, Tk_WindowId(*(graph->win)),
        graph->width, graph->height, Tk_Depth(*(graph->win)));
    RbcDrawGraph(graph, drawable, noBackingStore);

    /* Get a color image from the pixmap */
    image =
        RbcDrawableToColorImage(*(graph->win), drawable, 0, 0,
        graph->width, graph->height, 1.0);
    Tk_FreePixmap(graph->display, drawable);
    if(image == NULL) {
        return; /* Can't grab pixmap? */
    }
#ifdef THUMBNAIL_PREVIEW
    {
double scale, xScale, yScale;
int width, height;
RbcColorImage *destImage;

        /* Scale the source image into a size appropriate for a thumbnail. */
#define PS_MAX_PREVIEW_WIDTH	300.0
#define PS_MAX_PREVIEW_HEIGHT	300.0
        xScale = PS_MAX_PREVIEW_WIDTH / (double)graph->width;
        yScale = PS_MAX_PREVIEW_HEIGHT / (double)graph->height;
        scale = MIN(xScale, yScale);

        width = (int)(scale * graph->width + 0.5);
        height = (int)(scale * graph->height + 0.5);
        destImage = RbcResampleColorImage(image, width, height,
            rbcBoxFilterPtr, rbcBoxFilterPtr);
        RbcFreeColorImage(image);
        image = destImage;
    }
#endif /* THUMBNAIL_PREVIEW */
    RbcColorImageToGreyscale(image);
    if(psPtr->landscape) {
RbcColorImage *oldImage;

        oldImage = image;
        image = RbcRotateColorImage(image, 90.0);
        RbcFreeColorImage(oldImage);
    }
    Tcl_DStringInit(&dString);
    /* Finally, we can generate PostScript for the image */
    nLines = RbcColorImageToPsData(image, 1, &dString, "%");

    RbcAppendToPostScript(psToken, "%%BeginPreview: ", (char *)NULL);
    RbcFormatToPostScript(psToken, "%d %d 8 %d\n", image->width,
        image->height, nLines);
    RbcAppendToPostScript(psToken, Tcl_DStringValue(&dString), (char *)NULL);
    RbcAppendToPostScript(psToken, "%%EndPreview\n\n", (char *)NULL);
    Tcl_DStringFree(&dString);
    RbcFreeColorImage(image);
}

#ifdef TIME_WITH_SYS_TIME
#include <sys/time.h>
#include <time.h>
#else
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#include <time.h>
#endif /* HAVE_SYS_TIME_H */
#endif /* TIME_WITH_SYS_TIME */

/*
 *--------------------------------------------------------------
 *
 * PostScriptPreamble --
 *
 *      The PostScript preamble calculates the needed
 *      translation and scaling to make X11 coordinates
 *      compatible with PostScript.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
PostScriptPreamble(
    RbcGraph * graph,
    const char *fileName,
    RbcPsToken * psToken)
{
    RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
    time_t ticks;
    char date[200];            /* Hold the date string from ctime() */
    const char *version;
    double dpiX, dpiY;
    double xPixelsToPica, yPixelsToPica;        /* Scales to convert pixels to pica */
    Screen *screenPtr;
    char *nl;
    int paperHeightPixels;
    Tcl_Obj *preambleObj;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    paperHeightPixels = ComputeBoundingBox(graph, psPtr);
    if(fileName == NULL) {
        fileName = Tk_PathName(*(graph->win));
    }
    RbcAppendToPostScript(psToken, "%!PS-Adobe-3.0 EPSF-3.0\n", (char *)NULL);

    /*
     * Compute the scale factors to convert PostScript to X11 coordinates.
     * Round the pixels per inch (dpi) to an integral value before computing
     * the scale.
     */
#define MM_INCH		25.4
#define PICA_INCH	72.0
    screenPtr = Tk_Screen(*(graph->win));
    dpiX = (WidthOfScreen(screenPtr) * MM_INCH) / WidthMMOfScreen(screenPtr);
    xPixelsToPica = PICA_INCH / dpiX;
    dpiY = (HeightOfScreen(screenPtr) * MM_INCH) / HeightMMOfScreen(screenPtr);
    yPixelsToPica = PICA_INCH / dpiY;

    /*
     * The "BoundingBox" comment is required for EPS files. The box
     * coordinates are integers, so we need round away from the
     * center of the box.
     */
    RbcFormatToPostScript(psToken, "%%%%BoundingBox: %d %d %d %d\n",
        (int)floor(psPtr->left * xPixelsToPica),
        (int)floor((paperHeightPixels - psPtr->top) * yPixelsToPica),
        (int)ceil(psPtr->right * xPixelsToPica),
        (int)ceil((paperHeightPixels - psPtr->bottom) * yPixelsToPica));

    RbcAppendToPostScript(psToken, "%%Pages: 0\n", (char *)NULL);

    version = Tcl_GetVar(graph->interp, "rbc_version", TCL_GLOBAL_ONLY);
    if(version == NULL) {
        version = "???";
    }
    RbcFormatToPostScript(psToken, "%%%%Creator: (Rbc %s %s)\n", version,
        Tk_Class(*(graph->win)));

    ticks = time((time_t *) NULL);
    strcpy(date, ctime(&ticks));
    nl = date + strlen(date) - 1;
    if(*nl == '\n') {
        *nl = '\0';
    }
    RbcFormatToPostScript(psToken, "%%%%CreationDate: (%s)\n", date);
    RbcFormatToPostScript(psToken, "%%%%Title: (%s)\n", fileName);
    RbcAppendToPostScript(psToken, "%%DocumentData: Clean7Bit\n", (char *)NULL);
    if(psPtr->landscape) {
        RbcAppendToPostScript(psToken, "%%Orientation: Landscape\n",
            (char *)NULL);
    } else {
        RbcAppendToPostScript(psToken, "%%Orientation: Portrait\n",
            (char *)NULL);
    }
    RbcAppendToPostScript(psToken,
        "%%DocumentNeededResources: font Helvetica Courier\n", (char *)NULL);
    RbcAppendToPostScript(psToken, "%%EndComments\n\n", (char *)NULL);
    if((psPtr->addPreview) && (psPtr->previewFormat == PS_PREVIEW_EPSI)) {
        PreviewImage(graph, psToken);
    }
    preambleObj = Tcl_GetVar2Ex(graph->interp, "::graph::ps_preamble", NULL,
        TCL_LEAVE_ERR_MSG);
    if(preambleObj == NULL) {
        return TCL_ERROR;
    }
    RbcAppendToPostScript(psToken, Tcl_GetString(preambleObj), (char *)NULL);
    if(psPtr->footer) {
    const char *who;

        who = getenv("LOGNAME");
        if(who == NULL) {
            who = "???";
        }
        RbcAppendToPostScript(psToken,
            "8 /Helvetica SetFont\n",
            "10 30 moveto\n",
            "(Date: ", date, ") show\n",
            "10 20 moveto\n",
            "(File: ", fileName, ") show\n",
            "10 10 moveto\n",
            "(Created by: ", who, "@", Tcl_GetHostName(), ") show\n",
            "0 0 moveto\n", (char *)NULL);
    }
    /*
     * Set the conversion from PostScript to X11 coordinates.  Scale
     * pica to pixels and flip the y-axis (the origin is the upperleft
     * corner).
     */
    RbcAppendToPostScript(psToken,
        "% Transform coordinate system to use X11 coordinates\n\n",
        "% 1. Flip y-axis over by reversing the scale,\n",
        "% 2. Translate the origin to the other side of the page,\n",
        "%    making the origin the upper left corner\n", (char *)NULL);
    RbcFormatToPostScript(psToken, "%g -%g scale\n", xPixelsToPica,
        yPixelsToPica);
    /* Papersize is in pixels.  Translate the new origin *after*
     * changing the scale. */
    RbcFormatToPostScript(psToken, "0 %d translate\n\n", -paperHeightPixels);
    RbcAppendToPostScript(psToken, "% User defined page layout\n\n",
        "% Set color level\n", (char *)NULL);
    RbcFormatToPostScript(psToken, "/CL %d def\n\n", psPtr->colorMode);
    RbcFormatToPostScript(psToken, "%% Set origin\n%d %d translate\n\n",
        psPtr->left, psPtr->bottom);
    if(psPtr->landscape) {
        RbcFormatToPostScript(psToken,
            "%% Landscape orientation\n0 %g translate\n-90 rotate\n",
            ((double)graph->width * psPtr->pageScale));
    }
    if(psPtr->pageScale != 1.0) {
        RbcAppendToPostScript(psToken, "\n% Setting graph scale factor\n",
            (char *)NULL);
        RbcFormatToPostScript(psToken, " %g %g scale\n", psPtr->pageScale,
            psPtr->pageScale);
    }
    RbcAppendToPostScript(psToken, "\n%%EndSetup\n\n", (char *)NULL);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * MarginsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
MarginsToPostScript(
    RbcGraph * graph,
    RbcPsToken * psToken)
{
RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
XRectangle margin[4];

    margin[0].x = margin[0].y = margin[3].x = margin[1].x = 0;
    margin[0].width = margin[3].width = graph->width;
    margin[0].height = graph->top;
    margin[3].y = graph->bottom;
    margin[3].height = graph->height - graph->bottom;
    margin[2].y = margin[1].y = graph->top;
    margin[1].width = graph->left;
    margin[2].height = margin[1].height = graph->bottom - graph->top;
    margin[2].x = graph->right;
    margin[2].width = graph->width - graph->right;

    /* Clear the surrounding margins and clip the plotting surface */
    if(psPtr->decorations) {
        RbcBackgroundToPostScript(psToken, Tk_3DBorderColor(graph->border));
    } else {
        RbcClearBackgroundToPostScript(psToken);
    }
    RbcRectanglesToPostScript(psToken, margin, 4);

    /* Interior 3D border */
    if((psPtr->decorations) && (graph->plotBorderWidth > 0)) {
int x, y, width, height;

        x = graph->left - graph->plotBorderWidth;
        y = graph->top - graph->plotBorderWidth;
        width = (graph->right - graph->left) + (2 * graph->plotBorderWidth);
        height = (graph->bottom - graph->top) + (2 * graph->plotBorderWidth);
        RbcDraw3DRectangleToPostScript(psToken, graph->border,
            (double)x, (double)y, width, height, graph->plotBorderWidth,
            graph->plotRelief);
    }
    if(RbcLegendSite(graph->legend) & RBC_LEGEND_IN_MARGIN) {
        /*
         * Print the legend if we're using a site which lies in one
         * of the margins (left, right, top, or bottom) of the graph.
         */
        RbcLegendToPostScript(graph->legend, psToken);
    }
    if(graph->title != NULL) {
        RbcTextToPostScript(psToken, graph->title,
            &graph->titleTextStyle, (double)graph->titleX,
            (double)graph->titleY);
    }
    RbcAxesToPostScript(graph, psToken);
}

/*
 *--------------------------------------------------------------
 *
 * GraphToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
GraphToPostScript(
    RbcGraph * graph,
    const char *ident,         /* Identifier string (usually the filename) */
    RbcPsToken * psToken)
{
    int x, y, width, height;
    int result;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    /*
     * We need to know how big a graph to print.  If the graph hasn't
     * been drawn yet, the width and height will be 1.  Instead use
     * the requested size of the widget.  The user can still override
     * this with the -width and -height postscript options.
     */
    if(graph->height <= 1) {
        graph->height = Tk_ReqHeight(*(graph->win));
    }
    if(graph->width <= 1) {
        graph->width = Tk_ReqWidth(*(graph->win));
    }
    result = PostScriptPreamble(graph, ident, psToken);
    if(result != TCL_OK) {
        goto error;
    }
    /*
     * Determine rectangle of the plotting area for the graph window
     */
    x = graph->left - graph->plotBorderWidth;
    y = graph->top - graph->plotBorderWidth;

    width = (graph->right - graph->left + 1) + (2 * graph->plotBorderWidth);
    height = (graph->bottom - graph->top + 1) + (2 * graph->plotBorderWidth);

    RbcFontToPostScript(psToken, graph->titleTextStyle.font);
    RbcRegionToPostScript(psToken, (double)x, (double)y, width, height);
    if(graph->postscript->decorations) {
        RbcBackgroundToPostScript(psToken, graph->plotBg);
    } else {
        RbcClearBackgroundToPostScript(psToken);
    }
    RbcAppendToPostScript(psToken, "Fill\n", (char *)NULL);
    RbcAppendToPostScript(psToken, "gsave clip\n\n", (char *)NULL);
    /* Draw the grid, elements, and markers in the plotting area. */
    if(!graph->gridPtr->hidden) {
        RbcGridToPostScript(graph, psToken);
    }
    RbcMarkersToPostScript(graph, psToken, TRUE);
    if((RbcLegendSite(graph->legend) & RBC_LEGEND_IN_PLOT) &&
        (!RbcLegendIsRaised(graph->legend))) {
        /* Print legend underneath elements and markers */
        RbcLegendToPostScript(graph->legend, psToken);
    }
    RbcAxisLimitsToPostScript(graph, psToken);
    RbcElementsToPostScript(graph, psToken);
    if((RbcLegendSite(graph->legend) & RBC_LEGEND_IN_PLOT) &&
        (RbcLegendIsRaised(graph->legend))) {
        /* Print legend above elements (but not markers) */
        RbcLegendToPostScript(graph->legend, psToken);
    }
    RbcMarkersToPostScript(graph, psToken, FALSE);
    RbcActiveElementsToPostScript(graph, psToken);
    RbcAppendToPostScript(psToken, "\n",
        "% Unset clipping\n", "grestore\n\n", (char *)NULL);
    MarginsToPostScript(graph, psToken);
    RbcAppendToPostScript(psToken,
        "showpage\n",
        "%Trailer\n", "grestore\n", "end\n", "%EOF\n", (char *)NULL);
  error:
    /* Reset height and width of graph window */
    graph->width = Tk_Width(*(graph->win));
    graph->height = Tk_Height(*(graph->win));
    graph->flags = RBC_MAP_WORLD;

    /*
     * Redraw the graph in order to re-calculate the layout as soon as
     * possible. This is in the case the crosshairs are active.
     */
    RbcEventuallyRedrawGraph(graph);
    return result;
}

#ifdef _WIN32

/*
 * TODO: Determine if neccessary
 *
 *static void
 *InitAPMHeader(tkwin, width, height, headerPtr)
 *    Tk_Window tkwin;
 *    int width, height;
 *    APMHEADER *headerPtr;
 *{
 *    unsigned int *p;
 *    unsigned int sum;
 *    Screen *screen;
 *#define MM_INCH		25.4
 *    double dpiX, dpiY;
 *
 *    headerPtr->key = 0x9ac6cdd7L;
 *    headerPtr->hmf = 0;
 *    headerPtr->inch = 1440;
 *
 *    screen = Tk_Screen(tkwin);
 *    dpiX = (WidthOfScreen(screen) * MM_INCH) / WidthMMOfScreen(screen);
 *    dpiY = (HeightOfScreen(screen) * MM_INCH) / HeightMMOfScreen(screen);
 *
 *    headerPtr->bbox.Left = headerPtr->bbox.Top = 0;
 *    headerPtr->bbox.Bottom = (SHORT)((width * 1440) / dpiX);
 *    headerPtr->bbox.Right = (SHORT)((height * 1440) / dpiY);
 *    headerPtr->reserved = 0;
 *    sum = 0;
 *    for (p = (unsigned int *)headerPtr;
 *            p < (unsigned int *)&(headerPtr->checksum); p++) {
 *        sum ^= *p;
 *    }
 *    headerPtr->checksum = sum;
 *}
 */

/*
 * --------------------------------------------------------------------------
 *
 * CreateWindowEPS --
 *
 *      Generates an EPS file with a Window metafile preview.
 *
 *      Windows metafiles aren't very robust.  Including exactly the
 *      same metafile (one embedded in a DOS EPS, the other as .wmf
 *      file) will play back differently.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * --------------------------------------------------------------------------
 */
static int
CreateWindowsEPS(
    RbcGraph * graph,
    RbcPsToken * psToken,
    FILE * f)
{
DWORD size;
DOSEPSHEADER epsHeader;
HANDLE hMem;
HDC hRefDC, hDC;
HENHMETAFILE hMetaFile;
Tcl_DString dString;
TkWinDC drawableDC;
TkWinDCState state;
int result;
unsigned char *buffer;
char *psBuffer;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    RbcAppendToPostScript(psToken, "\n", (char *)NULL);
    psBuffer = RbcPostScriptFromToken(psToken);
    /*
     * Fill out as much information as we can into the DOS EPS header.
     * We won't know the start of the length of the WMF segment until
     * we create the metafile.
     */
    epsHeader.magic[0] = 0xC5;
    epsHeader.magic[1] = 0xD0;
    epsHeader.magic[2] = 0xD3;
    epsHeader.magic[3] = 0xC6;
    epsHeader.psStart = sizeof(epsHeader);
    epsHeader.psLength = strlen(psBuffer) + 1;
    epsHeader.wmfStart = epsHeader.psStart + epsHeader.psLength;
    epsHeader.wmfLength = 0L;   /* Fill in later. */
    epsHeader.tiffStart = 0L;
    epsHeader.tiffLength = 0L;
    epsHeader.checksum = 0xFFFF;

    result = TCL_ERROR;
    hRefDC = TkWinGetDrawableDC(graph->display,
        Tk_WindowId(*(graph->win)), &state);

    /* Build a description string. */
    Tcl_DStringInit(&dString);
    Tcl_DStringAppend(&dString, "Rbc Graph ", -1);
    Tcl_DStringAppend(&dString, "\0", -1);
    Tcl_DStringAppend(&dString, Tk_PathName(*(graph->win)), -1);
    Tcl_DStringAppend(&dString, "\0", -1);

    hDC = CreateEnhMetaFileA(hRefDC, NULL, NULL, Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);

    if(hDC == NULL) {
        Tcl_AppendResult(graph->interp, "can't create metafile: ",
            RbcLastError(), (char *)NULL);
        return TCL_ERROR;
    }
    /* Assemble a Tk drawable that points to the metafile and let the
     * graph's drawing routine draw into it. */
    drawableDC.hdc = hDC;
    drawableDC.type = TWD_WINDC;

    graph->width = Tk_Width(*(graph->win));
    graph->height = Tk_Height(*(graph->win));
    graph->flags |= RBC_RESET_WORLD;
    RbcLayoutGraph(graph);
    RbcDrawGraph(graph, (Drawable) & drawableDC, FALSE);
    GdiFlush();
    hMetaFile = CloseEnhMetaFile(hDC);

    size = GetWinMetaFileBits(hMetaFile, 0, NULL, MM_ANISOTROPIC, hRefDC);
    hMem = GlobalAlloc(GHND, size);
    if(hMem == NULL) {
        Tcl_AppendResult(graph->interp, "can't allocate global memory:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    buffer = (LPVOID) GlobalLock(hMem);
    if(!GetWinMetaFileBits(hMetaFile, size, buffer, MM_ANISOTROPIC, hRefDC)) {
        Tcl_AppendResult(graph->interp, "can't get metafile data:",
            RbcLastError(), (char *)NULL);
        goto error;
    }

    /*
     * Fix up the EPS header with the correct metafile length and PS
     * offset (now that we what they are).
     */
    epsHeader.wmfLength = size;
    epsHeader.wmfStart = epsHeader.psStart + epsHeader.psLength;

    /* Write out the eps header, */
    if(fwrite(&epsHeader, 1, sizeof(epsHeader), f) != sizeof(epsHeader)) {
        Tcl_AppendResult(graph->interp, "error writing eps header:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    /* the PostScript, */
    if(fwrite(psBuffer, 1, epsHeader.psLength, f) != epsHeader.psLength) {
        Tcl_AppendResult(graph->interp, "error writing PostScript data:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    /* and finally the metadata itself. */
    if(fwrite(buffer, 1, size, f) != size) {
        Tcl_AppendResult(graph->interp, "error writing metafile data:",
            RbcLastError(), (char *)NULL);
        goto error;
    }
    result = TCL_OK;

  error:
    DeleteEnhMetaFile(hMetaFile);
    TkWinReleaseDrawableDC(Tk_WindowId(*(graph->win)), hRefDC, &state);
    fclose(f);
    if(hMem != NULL) {
        GlobalUnlock(hMem);
        GlobalFree(hMem);
    }
    graph->flags = RBC_MAP_WORLD;
    RbcEventuallyRedrawGraph(graph);
    return result;
}

#endif /*_WIN32*/

/*
 *----------------------------------------------------------------------
 *
 * OutputOp --
 *
 *      This procedure is invoked to print the graph in a file.
 *
 * Results:
 *      Standard TCL result.  TCL_OK if plot was successfully printed,
 *      TCL_ERROR otherwise.
 *
 * Side effects:
 *      A new PostScript file is created.
 *
 *----------------------------------------------------------------------
 */
static int
OutputOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* Number of options in argv vector */
    const char **argv)
{              /* Option vector */
    RbcPostScript *psPtr = (RbcPostScript *) graph->postscript;
    FILE *f = NULL;
    RbcPsToken *psToken;
    const char *fileName;      /* Name of file to write PostScript output
                                * If NULL, output is returned via
                                * interp->result. */
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    fileName = NULL;
    if(argc > 3) {
        if(argv[3][0] != '-') {
            fileName = argv[3]; /* First argument is the file name. */
            argv++, argc--;
        }
        if(Tk_ConfigureWidget(interp, *(graph->win), configSpecs, argc - 3,
                argv + 3, (char *)psPtr, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
            return TCL_ERROR;
        }
        if(fileName != NULL) {
#ifdef _WIN32
            f = fopen(fileName, "wb");
#else
            f = fopen(fileName, "w");
#endif
            if(f == NULL) {
                Tcl_AppendResult(interp, "can't create \"", fileName, "\": ",
                    Tcl_PosixError(interp), (char *)NULL);
                return TCL_ERROR;
            }
        }
    }
    psToken = RbcGetPsToken(graph->interp, *(graph->win));
    psToken->fontVarName = psPtr->fontVarName;
    psToken->colorVarName = psPtr->colorVarName;
    psToken->colorMode = psPtr->colorMode;

    if(GraphToPostScript(graph, fileName, psToken) != TCL_OK) {
        goto error;
    }
    /*
     * If a file name was given, write the results to that file
     */
    if(f != NULL) {
#ifdef _WIN32
        if((psPtr->addPreview) && (psPtr->previewFormat != PS_PREVIEW_EPSI)) {
            if(CreateWindowsEPS(graph, psToken, f)) {
                return TCL_ERROR;
            }
        } else {
            fputs(RbcPostScriptFromToken(psToken), f);
            if(ferror(f)) {
                Tcl_AppendResult(interp, "error writing file \"", fileName,
                    "\": ", Tcl_PosixError(interp), (char *)NULL);
                goto error;
            }
        }
#else
        fputs(RbcPostScriptFromToken(psToken), f);
        if(ferror(f)) {
            Tcl_AppendResult(interp, "error writing file \"", fileName, "\": ",
                Tcl_PosixError(interp), (char *)NULL);
            goto error;
        }
#endif /* _WIN32 */
        fclose(f);
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj(RbcPostScriptFromToken(psToken), -1));
    }
    RbcReleasePsToken(psToken);
    return TCL_OK;

  error:
    if(f != NULL) {
        fclose(f);
    }
    RbcReleasePsToken(psToken);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCreatePostScript --
 *
 *      Creates a postscript structure.
 *
 * Results:
 *      Always TCL_OK.
 *
 * Side effects:
 *      A new PostScript structure is created.
 *
 *----------------------------------------------------------------------
 */
int
RbcCreatePostScript(
    RbcGraph * graph)
{
RbcPostScript *psPtr;
    if(graph->win == NULL || *(graph->win) == NULL)
        return TCL_ERROR;

    psPtr = RbcCalloc(1, sizeof(RbcPostScript));
    assert(psPtr);
    psPtr->colorMode = PS_MODE_COLOR;
    psPtr->center = TRUE;
    psPtr->decorations = TRUE;
    graph->postscript = psPtr;

    if(RbcConfigureWidgetComponent(graph->interp, *(graph->win),
            "postscript", "Postscript", configSpecs, 0, (const char **)NULL,
            (char *)psPtr, 0) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcPostScriptOp --
 *
 *      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 RbcOpSpec psOps[] = {
    {"cget", 2, (RbcOp) CgetOp, 4, 4, "option",},
    {"configure", 2, (RbcOp) ConfigureOp, 3, 0, "?option value?...",},
    {"output", 1, (RbcOp) OutputOp, 3, 0,
        "?fileName? ?option value?...",},
};

static int nPsOps = sizeof(psOps) / sizeof(RbcOpSpec);

/*
 *--------------------------------------------------------------
 *
 * RbcPostScriptOp --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcPostScriptOp(
    RbcGraph * graph,          /* Graph widget record */
    Tcl_Interp * interp,
    int argc,                  /* # arguments */
    const char *argv[])
{              /* Argument list */
    RbcOp proc;
    int result;

    proc = RbcGetOp(interp, nPsOps, psOps, RBC_OP_ARG2, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    result = (*proc) (graph, interp, argc, argv);
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPath.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPath.c --
 *
 *    This module implements canvas widgets for the Tk toolkit. A canvas
 *    displays a background and a collection of graphical objects such as
 *    rectangles, lines, and texts.
 *
 * Copyright (c) 1991-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 * Copyright (c) 1998-1999 by Scriptics Corporation.
 * Copyright (c) 2008 Mats Bengtsson
 * Copyright (c) 2019 Rene Zaumseil
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#ifdef MAC_OSX_TK
#define TK_PATH_NO_DOUBLE_BUFFERING
#endif

#include "tkoPath.h"

int Tk_PathAntiAlias = 1;
int Tk_PathDepixelize = 1;
int Tk_PathSurfaceCopyPremultiplyAlpha = 1;

/*
 * Flag bits for canvases:
 *
 * REDRAW_PENDING -        1 means a DoWhenIdle handler has already been
 *                created to redraw some or all of the canvas.
 * REDRAW_BORDERS -         1 means that the borders need to be redrawn
 *                during the next redisplay operation.
 * REPICK_NEEDED -        1 means PathDisplay should pick a new
 *                current item before redrawing the canvas.
 * GOT_FOCUS -            1 means the focus is currently in this widget,
 *                so should draw the insertion cursor and
 *                traversal highlight.
 * CURSOR_ON -            1 means the insertion cursor is in the "on"
 *                phase of its blink cycle. 0 means either we
 *                don't have the focus or the cursor is in the
 *                "off" phase of its cycle.
 * UPDATE_SCROLLBARS -        1 means the scrollbars should get updated as
 *                part of the next display operation.
 * LEFT_GRABBED_ITEM -        1 means that the mouse left the current item
 *                while a grab was in effect, so we didn't
 *                change path->currentItemPtr.
 * REPICK_IN_PROGRESS -        1 means PickCurrentItem is currently
 *                executing. If it should be called recursively,
 *                it should simply return immediately.
 * BBOX_NOT_EMPTY -        1 means that the bounding box of the area that
 *                should be redrawn is not empty.
 */
#define REDRAW_PENDING        (1 << 1)
#define REDRAW_BORDERS        (1 << 2)
#define REPICK_NEEDED        (1 << 3)
#define GOT_FOCUS        (1 << 4)
#define CURSOR_ON        (1 << 5)
#define UPDATE_SCROLLBARS    (1 << 6)
#define LEFT_GRABBED_ITEM    (1 << 7)
#define REPICK_IN_PROGRESS    (1 << 8)
#define BBOX_NOT_EMPTY        (1 << 9)

/*
 * Flag bits for canvas items (redraw_flags):
 *
 * FORCE_REDRAW -        1 means that the new coordinates of some item
 *                are not yet registered using
 *                Tk_PathCanvasEventuallyRedraw(). It should still
 *                be done by the general canvas code.
 */
#define FORCE_REDRAW        8

/*
 * TagSearch --
 *
 * The structure defined below is used to keep track of a tag search in
 * progress. No field should be accessed by anyone other than TagSearchScan,
 * TagSearchFirst, TagSearchNext, TagSearchScanExpr, TagSearchEvalExpr,
 * TagSearchExprInit, TagSearchExprDestroy, TagSearchDestroy.
 * (
 *   Not quite accurate: the TagSearch structure is also accessed from:
 *    CanvasWidgetCmd, FindItems, RelinkItems
 *   The only instances of the structure are owned by:
 *    CanvasWidgetCmd
 *   CanvasWidgetCmd is the only function that calls:
 *    FindItems, RelinkItems
 *   CanvasWidgetCmd, FindItems, RelinkItems, are the only functions that call
 *    TagSearch*
 * )
 */
typedef struct TagSearch {
    TkPathCanvas *path;        /* Canvas widget being searched. */
    Tk_PathItem *currentPtr;   /* Pointer to last item returned. */
    Tk_PathItem *lastPtr;      /* The item right before the currentPtr is
                                * tracked so if the currentPtr is deleted we
                                * don't have to start from the beginning. */
    int searchOver;            /* Non-zero means NextItem should always
                                * return NULL. */
    int type;                  /* Search type (see #defs below) */
    int id;                    /* Item id for searches by id */
    char *string;              /* Tag expression string */
    int stringIndex;           /* Current position in string scan */
    int stringLength;          /* Length of tag expression string */
    char *rewritebuffer;       /* Tag string (after removing escapes) */
    unsigned int rewritebufferAllocated;
    /* Available space for rewrites. */
    TkPathTagSearchExpr *expr; /* Compiled tag expression. */
} TagSearch;

/*
 * Values for the TagSearch type field.
 */
#define SEARCH_TYPE_EMPTY    0  /* Looking for empty tag */
#define SEARCH_TYPE_ID        1 /* Looking for an item by id */
#define SEARCH_TYPE_ALL        2        /* Looking for all items */
#define SEARCH_TYPE_TAG        3        /* Looking for an item by simple tag */
#define SEARCH_TYPE_EXPR    4   /* Compound search */
#define SEARCH_TYPE_ROOT    5   /* Looking for the root item */

#define PATH_DEF_STATE "normal"

/* These MUST be kept in sync with enums! X.h */

static const char *stateStrings[] = {
    "active", "disabled", "normal", "hidden", NULL
};

static const char *tagStyleStrings[] = {
    "exact", "expr", "glob", NULL
};

/*
 * List of all the item types known at present.
 */
static Tk_PathItemType *typeList = NULL;        /* NULL means initialization hasn't
                                                 * been done yet. */

/*
 * Uids for operands in compiled advanced tag search expressions.
 * Initialization is done by GetStaticUids()
 */
typedef struct {
    Tk_Uid allUid;             /* "all" */
    Tk_Uid currentUid;         /* "current" */
    Tk_Uid rootUid;            /* "root" */
    Tk_Uid andUid;
    Tk_Uid orUid;
    Tk_Uid xorUid;
    Tk_Uid parenUid;
    Tk_Uid negparenUid;
    Tk_Uid endparenUid;
    Tk_Uid tagvalUid;
    Tk_Uid negtagvalUid;
} SearchUids;

static Tcl_ThreadDataKey dataKey;
static SearchUids *GetStaticUids(
    void);

/*
* Macros that significantly simplify all code that finds items.
*/

#define FIRST_CANVAS_ITEM_MATCHING(objPtr,searchPtrPtr,errorExitClause) \
    if ((result = TagSearchScan(path,(objPtr),(searchPtrPtr))) != TCL_OK) { \
    errorExitClause; \
    } \
    itemPtr = TagSearchFirst(*(searchPtrPtr));

#define FOR_EVERY_CANVAS_ITEM_MATCHING(objPtr,searchPtrPtr,errorExitClause) \
    if ((result = TagSearchScan(path,(objPtr),(searchPtrPtr))) != TCL_OK) { \
    errorExitClause; \
    } \
    for (itemPtr = TagSearchFirst(*(searchPtrPtr)); \
        itemPtr != NULL; itemPtr = TagSearchNext(*(searchPtrPtr)))
#if defined(_WIN32) && defined(AGG_CUSTOM_ALLOCATOR)
/* AGG custom allocator functions */
void *(
    *agg_custom_alloc) (
    unsigned int size) = NULL;
void (
    *agg_custom_free) (
    void *ptr) = NULL;
#endif

/*
* Methods
*/
static int PathConstructor(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathDestructor(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathMethod(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathMethod_tko_configure(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathMethod_offset(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathMethod_state(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int PathMethod_tagstyle(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);

/*
 * Functions
 */
static void CanvasBindProc(
    ClientData clientData,
    XEvent * eventPtr);
static void CanvasBlinkProc(
    ClientData clientData);
static void CanvasDoEvent(
    TkPathCanvas * path,
    XEvent * eventPtr);
static void CanvasEventProc(
    ClientData clientData,
    XEvent * eventPtr);
static int CanvasFetchSelection(
    ClientData clientData,
    int offset,
    char *buffer,
    int maxBytes);
static Tk_PathItem *CanvasFindClosest(
    TkPathCanvas * path,
    double coords[2]);
static void CanvasFocusProc(
    TkPathCanvas * path,
    int gotFocus);
static void CanvasLostSelection(
    ClientData clientData);
static void CanvasSelectTo(
    TkPathCanvas * path,
    Tk_PathItem * itemPtr,
    int index);
static void CanvasSetOrigin(
    TkPathCanvas * path,
    int xOrigin,
    int yOrigin);
static void CanvasUpdateScrollbars(
    TkPathCanvas * path);
static void PathCanvasWorldChanged(
    ClientData instanceData);
static void PathDisplay(
    ClientData clientData);
static void DoItem(
    Tcl_Interp * interp,
    Tk_PathItem * itemPtr,
    Tk_Uid tag);
static void EventuallyRedrawItem(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr);
static void EventuallyRedrawItemAndChildren(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr);
static Tcl_Obj *UnshareObj(
    Tcl_Obj * objPtr);
#ifdef NOT_USED
static Tk_PathItem *ItemIteratorSubNext(
    Tk_PathItem * itemPtr,
    Tk_PathItem * groupPtr);
#endif
static void ItemAddToParent(
    Tk_PathItem * parentPtr,
    Tk_PathItem * itemPtr);
static void ItemDelete(
    TkPathCanvas * path,
    Tk_PathItem * itemPtr);
static int ItemCreate(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    Tk_PathItemType * typePtr,
    int isRoot,
    Tk_PathItem ** itemPtrPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int ItemGetNumTags(
    Tk_PathItem * itemPtr);
static void SetAncestorsDirtyBbox(
    Tk_PathItem * itemPtr);
static void DebugGetItemInfo(
    Tk_PathItem * itemPtr,
    char *s);
static int FindItems(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    int objc,
    Tcl_Obj * const *objv,
    Tcl_Obj * newTagObj,
    int first,
    TagSearch ** searchPtrPtr);
static int FindArea(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    Tcl_Obj * const *objv,
    Tk_Uid uid,
    int enclosed);
static double GridAlign(
    double coord,
    double spacing);
static const char **GetStringsFromObjs(
    int objc,
    Tcl_Obj * const *objv);
static void PickCurrentItem(
    TkPathCanvas * path,
    XEvent * eventPtr);
static Tcl_Obj *ScrollFractions(
    int screen1,
    int screen2,
    int object1,
    int object2);
static int RelinkItems(
    TkPathCanvas * path,
    Tcl_Obj * tag,
    Tk_PathItem * prevPtr,
    TagSearch ** searchPtrPtr);
static void TagSearchExprInit(
    TkPathTagSearchExpr ** exprPtrPtr);
static void TagSearchExprDestroy(
    TkPathTagSearchExpr * expr);
static void TagSearchDestroy(
    TagSearch * searchPtr);
static int TagSearchScan(
    TkPathCanvas * path,
    Tcl_Obj * tag,
    TagSearch ** searchPtrPtr);
static int TagSearchScanExpr(
    Tcl_Interp * interp,
    TagSearch * searchPtr,
    TkPathTagSearchExpr * expr);
static int TagSearchEvalExpr(
    TkPathTagSearchExpr * expr,
    Tk_PathItem * itemPtr);
static Tk_PathItem *TagSearchFirst(
    TagSearch * searchPtr);
static Tk_PathItem *TagSearchNext(
    TagSearch * searchPtr);
static void PathMetaDestroy(
    TkPathCanvas * path);
static void
PathMetaDelete(
    ClientData clientData)
{
    Tcl_EventuallyFree(clientData, (Tcl_FreeProc *) PathMetaDestroy);
}

/*
* pathMeta --
*/
static Tcl_ObjectMetadataType pathMeta = {
    TCL_OO_METADATA_VERSION_CURRENT,
    "PathMeta",
    PathMetaDelete,
    NULL
};

/* 
 * pathOptionDefine --
 *
 * Options and option methods created in class constructor.
 */
static tkoWidgetOptionDefine pathOptionDefine[] = {
    {"-class", "class", "Class", "TkoPath", TKO_OPTION_READONLY, NULL,
	NULL, NULL, TKO_SET_CLASS, NULL, 0},
    {"-background", "background", "Background", DEF_CANVAS_BG_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_3DBORDER, &pathMeta, offsetof(TkPathCanvas, bgBorder)},
    {"-bd", "-borderwidth", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-bg", "-background", NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0},
    {"-borderwidth", "borderWidth", "BorderWidth", DEF_CANVAS_BORDER_WIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &pathMeta, offsetof(TkPathCanvas,borderWidth)},
    {"-closeenough", "closeEnough", "CloseEnough", DEF_CANVAS_CLOSE_ENOUGH, 0, NULL,
	NULL, NULL, TKO_SET_DOUBLE, &pathMeta, offsetof(TkPathCanvas, closeEnough)},
    {"-confine", "confine", "Confine", DEF_CANVAS_CONFINE, 0, NULL,
	NULL, NULL, TKO_SET_BOOLEAN, &pathMeta, offsetof(TkPathCanvas, confine)},
    {"-cursor", "cursor", "Cursor", DEF_CANVAS_CURSOR, 0, NULL,
	NULL, NULL, TKO_SET_CURSOR, &pathMeta, offsetof(TkPathCanvas, cursor)},
    {"-height", "height", "Height", DEF_CANVAS_HEIGHT, 0, NULL,
	NULL, NULL, TKO_SET_PIXEL, &pathMeta, offsetof(TkPathCanvas, height)},
    {"-highlightbackground", "highlightBackground", "HighlightBackground", DEF_CANVAS_HIGHLIGHT_BG, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &pathMeta, offsetof(TkPathCanvas, highlightBgColorPtr)},
    {"-highlightcolor", "highlightColor", "HighlightColor", DEF_CANVAS_HIGHLIGHT, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &pathMeta, offsetof(TkPathCanvas, highlightColorPtr)},
    {"-highlightthickness", "highlightThickness", "HighlightThickness", DEF_CANVAS_HIGHLIGHT_WIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &pathMeta, offsetof(TkPathCanvas,highlightWidth)},
    {"-insertbackground", "insertBackground", "Foreground", DEF_CANVAS_INSERT_BG, 0, NULL,
	NULL, NULL, TKO_SET_3DBORDER, &pathMeta, offsetof(TkPathCanvas,textInfo.insertBorder)},
    {"-insertborderwidth", "insertBorderWidth", "BorderWidth", DEF_CANVAS_INSERT_BD_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &pathMeta, offsetof(TkPathCanvas,textInfo.insertBorderWidth)},
    {"-insertofftime", "insertOffTime", "OffTime", DEF_CANVAS_INSERT_OFF_TIME, 0, NULL,
	NULL, NULL, TKO_SET_INT, &pathMeta, offsetof(TkPathCanvas, insertOffTime)},
    {"-insertontime", "insertOnTime", "OnTime", DEF_CANVAS_INSERT_ON_TIME, 0, NULL,
	NULL, NULL, TKO_SET_INT, &pathMeta, offsetof(TkPathCanvas, insertOnTime)},
    {"-insertwidth", "insertWidth", "InsertWidth", DEF_CANVAS_INSERT_ON_TIME, 0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &pathMeta, offsetof(TkPathCanvas,textInfo.insertWidth)},
    {"-offset", "offset", "Offset", "0,0", 0, NULL,
	NULL, PathMethod_offset, 0, NULL, 0},
    {"-relief", "relief", "Relief", DEF_CANVAS_RELIEF, 0, NULL,
	NULL, NULL, TKO_SET_RELIEF, &pathMeta, offsetof(TkPathCanvas, relief)},
    {"-scrollregion", "scrollRegion", "ScrollRegion", DEF_CANVAS_SCROLL_REGION, 0, NULL,
	NULL, NULL, TKO_SET_SCROLLREGION, &pathMeta, offsetof(TkPathCanvas, scroll)},
    {"-selectbackground", "selectBackground", "Foreground", DEF_CANVAS_SELECT_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_3DBORDER, &pathMeta, offsetof(TkPathCanvas,textInfo.selBorder)},
    {"-selectborderwidth", "selectBorderWidth", "BorderWidth", DEF_CANVAS_SELECT_BD_COLOR,0, NULL,
	NULL, NULL, TKO_SET_PIXELNONEGATIV, &pathMeta, offsetof(TkPathCanvas,textInfo.selBorderWidth)},
    {"-selectforeground", "selectForeground", "Background", DEF_CANVAS_SELECT_FG_COLOR, 0, NULL,
	NULL, NULL, TKO_SET_XCOLOR, &pathMeta, offsetof(TkPathCanvas,textInfo.selFgColorPtr)},
    {"-state", "state", "State", PATH_DEF_STATE, 0, NULL,
	NULL, PathMethod_state, 0, NULL, 0},
    {"-tagstyle", "", "", "expr", 0, NULL,
	NULL, PathMethod_tagstyle, 0, NULL, 0},
    {"-takefocus", "takeFocus", "TakeFocus", DEF_CANVAS_TAKE_FOCUS, 0, NULL,
	NULL, NULL, TKO_SET_STRING, NULL, 0},
    {"-width", "width", "Width", DEF_CANVAS_WIDTH, 0, NULL,
	NULL, NULL, TKO_SET_PIXEL, &pathMeta, offsetof(TkPathCanvas, width)},
    {"-xscrollcommand", "xScrollCommand", "ScrollCommand", DEF_CANVAS_X_SCROLL_CMD, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &pathMeta, offsetof(TkPathCanvas, xScrollCmd)},
    {"-xscrollincrement", "xScrollIncrement", "ScrollIncrement", DEF_CANVAS_X_SCROLL_INCREMENT, 0, NULL,
	NULL, NULL, TKO_SET_PIXEL, &pathMeta, offsetof(TkPathCanvas, xScrollIncrement)},
    {"-yscrollcommand", "yScrollCommand", "ScrollCommand", DEF_CANVAS_Y_SCROLL_CMD, 0, NULL,
	NULL, NULL, TKO_SET_STRINGNULL, &pathMeta, offsetof(TkPathCanvas, yScrollCmd)},
    {"-yscrollincrement", "yScrollIncrement", "ScrollIncrement", DEF_CANVAS_Y_SCROLL_INCREMENT, 0, NULL,
	NULL, NULL, TKO_SET_PIXEL, &pathMeta, offsetof(TkPathCanvas, yScrollIncrement)},
    {NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0, NULL, 0}
};

/*
 * pathMethods --
 *
 * Methods created in class constructor.
 */
static Tcl_MethodType pathMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, PathConstructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, PathDestructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "addtag", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "ancestors", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "bbox", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "bind", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "canvasx", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "canvasy", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "children", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "cmove", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "coords", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "create", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "cscale", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "dchars", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "delete", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "depth", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "distance", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "dtag", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "find", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "firstchild", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "focus", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "gettags", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "gradient", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "icursor", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "index", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "insert", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "itemcget", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "itemconfigure", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "itempdf", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "lastchild", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "lower", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "move", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "nextsibling", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "parent", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "prevsibling", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "raise", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "scale", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "scan", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "select", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "style", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "type", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "types", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "xview", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "yview", PathMethod, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "debugtree", PathMethod, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure", PathMethod_tko_configure,
            NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/*
 * canvasClass --
 *
 * The structure below defines canvas class behavior by means of functions
 * that can be invoked from generic window code.
 */
static Tk_ClassProcs canvasClass = {
    sizeof(Tk_ClassProcs),      /* size */
    PathCanvasWorldChanged,     /* worldChangedProc */
    NULL,      /* createProc */
    NULL       /* modalProc */
};

/*
 * Tko_PathInit --
 *
 *        Initializer for the tko path widget package.
 *
 * Results:
 *        A standard Tcl result.
 *
 * Side Effects:
 *       Tcl commands created
 */
int
Tko_PathInit(
    Tcl_Interp * interp /* Tcl interpreter. */)
{             
    Tcl_Class clazz;
    Tcl_Object object;

    /* Create class like tk command and remove oo functions from widget commands */
static const char *initScript =
    "::oo::class create ::path {superclass ::tko::widget; variable tko; {*}$::tko::unknown}";

#if defined(_WIN32) && defined(AGG_CUSTOM_ALLOCATOR)
    agg_custom_alloc = (void *(*)(unsigned int))Tcl_Alloc;
    agg_custom_free = (void (*)(void *))Tcl_Free;
#endif

    if(TkPathSetup(interp) == TCL_ERROR) {
        return TCL_ERROR;
    }

    /*
     * Create widget class
     */
    if(Tcl_Eval(interp, initScript) != TCL_OK) {
        return TCL_ERROR;
    }
    /*
     * Get class object
     */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.path)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /*
     * Add methods and options
     */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            pathMethods, pathOptionDefine) != TCL_OK) {
        return TCL_ERROR;
    }

    /*
     * Link the variable to control antialiasing.
     */
    if(Tcl_LinkVar(interp, TK_PATHVAR_ANTIALIAS,
            (char *)&Tk_PathAntiAlias, TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }

    /*
     * With Tk_PathSurfaceCopyPremultiplyAlpha true we ignore the "premultiply alpha"
     * and use RGB as is. Else we need to divide each RGB with alpha
     * to get "true" values.
     */
    if(Tcl_LinkVar(interp, TK_PATHVAR_PREMULTIPLYALPHA,
            (char *)&Tk_PathSurfaceCopyPremultiplyAlpha,
            TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }
    if(Tcl_LinkVar(interp, TK_PATHVAR_DEPIXELIZE,
            (char *)&Tk_PathDepixelize, TCL_LINK_BOOLEAN) != TCL_OK) {
        Tcl_ResetResult(interp);
    }

    /*
     * Create additional Tcl commands
     */
    Tcl_CreateObjCommand(interp, TK_PATHCMD_PIXELALIGN,
        TkPathPixelAlignObjCmd, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);

    /*
     * tkpath specific item types. Hopefully ordered by usage.
     */
    typeList = &tkPathTypeGroup;
    tkPathTypeGroup.nextPtr = &tkPathTypePath;
    tkPathTypePath.nextPtr = &tkPathTypeText;
    tkPathTypeText.nextPtr = &tkPathTypeLine;
    tkPathTypeLine.nextPtr = &tkPathTypePolyline;
    tkPathTypePolyline.nextPtr = &tkPathTypePolygon;
    tkPathTypePolygon.nextPtr = &tkPathTypeRect;
    tkPathTypeRect.nextPtr = &tkPathTypeCircle;
    tkPathTypeCircle.nextPtr = &tkPathTypeEllipse;
    tkPathTypeEllipse.nextPtr = &tkPathTypeImage;
    tkPathTypeImage.nextPtr = &tkPathTypeWindow;
    tkPathTypeWindow.nextPtr = NULL;

    /*
     * Make separate gradient objects, similar to SVG.
     */
    TkPathGradientInit(interp);
    TkPathSurfaceInit(interp);

    /*
     * Style object.
     */
    TkPathStyleInit(interp);

    return TCL_OK;
}

/*
 * PathConstructor --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathConstructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    TkPathCanvas *path;
    Tk_PathItem *rootItemPtr;
    Tcl_Obj *rootObj;
    int skip;
    Tcl_Obj *myObjv[5];

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL) {
        return TCL_ERROR;
    }
    skip = Tcl_ObjectContextSkippedArgs(context);
    /* Check objv[]: 0=class 1="create" 2=.path 3=opts 4=args */
    if(skip != 3 || objc != 5 || strcmp("create", Tcl_GetString(objv[1])) != 0) {
        Tcl_WrongNumArgs(interp, 1, objv, "pathname ?options?");
        return TCL_ERROR;
    }
    /* Get own options */
    myObjv[3] =
        Tcl_ObjGetVar2(interp, TkoObj.tko_options, TkoObj.path,
        TCL_GLOBAL_ONLY);
    if(myObjv[3] == NULL) {
        return TCL_ERROR;
    }

    /*
     * Initialize fields that won't be initialized by ConfigureCanvas, or
     * which ConfigureCanvas expects to have reasonable values (e.g. resource
     * pointers).
     */

    path = (TkPathCanvas *) ckalloc(sizeof(TkPathCanvas));
    path->win = NULL;
    path->display = None;
    path->interp = interp;
    path->rootItemPtr = NULL;   /* root item created below. */
    path->borderWidth = 0;
    path->bgBorder = NULL;
    path->relief = TK_RELIEF_FLAT;
    path->highlightWidth = 0;
    path->highlightBgColorPtr = NULL;
    path->highlightColorPtr = NULL;
    path->inset = 0;
    path->pixmapGC = None;
    path->width = 0;
    path->height = 0;
    path->confine = 0;
    path->textInfo.selBorder = NULL;
    path->textInfo.selBorderWidth = 0;
    path->textInfo.selFgColorPtr = NULL;
    path->textInfo.selItemPtr = NULL;
    path->textInfo.selectFirst = -1;
    path->textInfo.selectLast = -1;
    path->textInfo.anchorItemPtr = NULL;
    path->textInfo.selectAnchor = 0;
    path->textInfo.insertBorder = NULL;
    path->textInfo.insertWidth = 0;
    path->textInfo.insertBorderWidth = 0;
    path->textInfo.focusItemPtr = NULL;
    path->textInfo.gotFocus = 0;
    path->textInfo.cursorOn = 0;
    path->insertOnTime = 0;
    path->insertOffTime = 0;
    path->insertBlinkHandler = (Tcl_TimerToken) NULL;
    path->xOrigin = path->yOrigin = 0;
    path->drawableXOrigin = path->drawableYOrigin = 0;
    path->bindingTable = NULL;
    path->currentItemPtr = NULL;
    path->newCurrentPtr = NULL;
    path->closeEnough = 0.0;
    path->pickEvent.type = LeaveNotify;
    path->pickEvent.xcrossing.x = 0;
    path->pickEvent.xcrossing.y = 0;
    path->state = 0;
    path->xScrollCmd = NULL;
    path->yScrollCmd = NULL;
    path->scroll[0] = 0;
    path->scroll[1] = 0;
    path->scroll[2] = 0;
    path->scroll[3] = 0;
    path->xScrollIncrement = 0;
    path->yScrollIncrement = 0;
    path->scanX = 0;
    path->scanXOrigin = 0;
    path->scanY = 0;
    path->scanYOrigin = 0;
    path->hotPtr = NULL;
    path->hotPrevPtr = NULL;
    path->cursor = None;
    path->pixelsPerMM = 76.;    /*TODO default */
    path->nextId = 1;   /* id = 0 reserved for root item */
    Tcl_InitHashTable(&path->idTable, TCL_ONE_WORD_KEYS);
    Tcl_InitHashTable(&path->styleTable, TCL_STRING_KEYS);
    Tcl_InitHashTable(&path->gradientTable, TCL_STRING_KEYS);
    path->styleUid = 0;
    path->gradientUid = 0;
    path->tagStyle = 0;
    /*TODO*/ path->flags = 0;
    path->canvas_state = TK_PATHSTATE_NORMAL;
    path->context = NULL;
    path->tsoffsetPtr = NULL;
    path->bindTagExprs = NULL;

    Tcl_ObjectSetMetadata(object, &pathMeta, (ClientData) path);

    /* call next constructor */
    myObjv[0] = objv[0];
    myObjv[1] = objv[1];
    myObjv[2] = objv[2];
    myObjv[3] = Tcl_DuplicateObj(myObjv[3]);
    Tcl_IncrRefCount(myObjv[3]);
    Tcl_ListObjAppendList(interp, myObjv[3], objv[objc - 2]);
    myObjv[4] = objv[4];
    if(Tcl_ObjectContextInvokeNext(interp, context, objc, myObjv,
            skip) != TCL_OK) {
        Tcl_DecrRefCount(myObjv[3]);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(myObjv[3]);
    path->win = TkoWidgetWindow(object);
    if(path->win == NULL || *(path->win) == NULL) {
        return TCL_ERROR;
    }
    if((path->display = Tk_Display(*(path->win))) == None) {
        return TCL_ERROR;
    }
#ifdef PLATFORM_SDL
    {
    double dW, dH;

        dW = WidthOfScreen(Tk_Screen(*(path->win)));
        dW /= WidthMMOfScreen(Tk_Screen(*(path->win)));
        dH = HeightOfScreen(Tk_Screen(*(path->win)));
        dH /= HeightMMOfScreen(Tk_Screen(*(path->win)));
        path->pixelsPerMM = (dH > dW) ? dH : dW;
    }
#else
    path->pixelsPerMM = WidthOfScreen(Tk_Screen(*(path->win)));
    path->pixelsPerMM /= WidthMMOfScreen(Tk_Screen(*(path->win)));
#endif

    Tk_SetClassProcs(*(path->win), &canvasClass, (ClientData) path);
    Tk_CreateEventHandler(*(path->win),
        ExposureMask | StructureNotifyMask | FocusChangeMask,
        CanvasEventProc, (ClientData) path);
    Tk_CreateEventHandler(*(path->win), KeyPressMask | KeyReleaseMask
        | ButtonPressMask | ButtonReleaseMask | EnterWindowMask
        | LeaveWindowMask | PointerMotionMask | VirtualEventMask,
        CanvasBindProc, (ClientData) path);
    Tk_CreateSelHandler(*(path->win), XA_PRIMARY, XA_STRING,
        CanvasFetchSelection, (ClientData) path, XA_STRING);

    /*
     * Create the root item as a group item.
     * Need to set the tag "root" by hand since its configProc
     * forbids this for the root item.
     */
    ItemCreate(interp, path, &tkPathTypeGroup, 1, &rootItemPtr, 0, NULL);
    rootObj = Tcl_NewStringObj("root", -1);
    Tcl_IncrRefCount(rootObj);
    rootItemPtr->pathTagsPtr = TkPathAllocTagsFromObj(NULL, rootObj);
    Tcl_DecrRefCount(rootObj);
    path->rootItemPtr = rootItemPtr;

    //TODO configure

    /* No need to set return value. It will be ignored by "oo::class create" */
    return TCL_OK;
}

/*
 * PathDestructor --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    TkPathCanvas *path;
    int skip;
    Tk_Window tkWin = NULL;
    Tk_PathItem *itemPtr, *prevItemPtr, *lastPtr = NULL;
    TkPathTagSearchExpr *expr, *next;

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL)
        return TCL_ERROR;
    skip = Tcl_ObjectContextSkippedArgs(context);
    if((path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object,
                &pathMeta)) != NULL) {
        Tcl_Preserve(path);
        if(path->win) {
            tkWin = *(path->win);
            path->win = NULL;
        }
        /* Delete event handlers */
        if(tkWin) {
            Tk_DeleteEventHandler(tkWin,
                ExposureMask | StructureNotifyMask | FocusChangeMask,
                CanvasEventProc, (ClientData) path);
            Tk_DeleteEventHandler(tkWin, KeyPressMask | KeyReleaseMask
                | ButtonPressMask | ButtonReleaseMask | EnterWindowMask
                | LeaveWindowMask | PointerMotionMask | VirtualEventMask,
                CanvasBindProc, (ClientData) path);
            Tk_DeleteSelHandler(tkWin, XA_PRIMARY, XA_STRING);
        }
        if(path->insertBlinkHandler != NULL) {
            Tcl_DeleteTimerHandler(path->insertBlinkHandler);
            path->insertBlinkHandler = NULL;
        }
        /* Cancel idle calls */
        Tcl_CancelIdleCall(PathDisplay, (ClientData) path);

        /*
         * Free up all of the items in the canvas.
         * NB: We need to traverse the tree from the last item
         *     until reached the root item.
         */
        for(itemPtr = path->rootItemPtr; itemPtr != NULL;
            itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
            lastPtr = itemPtr;
        }
        for(itemPtr = lastPtr; itemPtr != NULL;) {
            prevItemPtr = TkPathCanvasItemIteratorPrev(itemPtr);
            if(path->display != None) {
                (*itemPtr->typePtr->deleteProc) ((Tk_PathCanvas) path, itemPtr,
                    path->display);
            }
            ckfree((char *)itemPtr);
            itemPtr = prevItemPtr;
        }
        path->rootItemPtr = NULL;
        /*
         * Free up all the stuff that requires special handling, then let
         * PathMetaDestroy() handle all the standard option-related stuff.
         */
        if(tkWin) {
            TkPathStylesFree(tkWin, &path->styleTable);
        }
        TkPathCanvasGradientsFree(path);

        expr = path->bindTagExprs;
        while(expr) {
            next = expr->next;
            TagSearchExprDestroy(expr);
            expr = next;
        }
        path->bindTagExprs = NULL;
        if(path->bindingTable != NULL) {
            Tk_DeleteBindingTable(path->bindingTable);
            path->bindingTable = NULL;
        }

        Tcl_Release(path);
        if(tkWin) {
            Tcl_ObjectSetMetadata(object, &pathMeta, NULL);
        }
    }
    /* ignore errors */
    Tcl_ObjectContextInvokeNext(interp, context, objc, objv, skip);

    return TCL_OK;
}

/*
* PathMetaDestroy --
*
*    This function is invoked by Tcl_EventuallyFree or Tcl_Release to clean
*    up the internal structure of a canvas at a safe time (when no-one is
*    using it anymore).
*
* Results:
*    None.
*
* Side effects:
*    Everything associated with the canvas is freed up.
*/
static void
PathMetaDestroy(
    TkPathCanvas * path)
{
    if(path->bgBorder != NULL) {
        Tk_Free3DBorder(path->bgBorder);
    }
    if(path->highlightBgColorPtr != NULL) {
        Tk_FreeColor(path->highlightBgColorPtr);
    }
    if(path->highlightColorPtr != NULL) {
        Tk_FreeColor(path->highlightColorPtr);
    }
    if(path->pixmapGC != None && path->display != None) {
        Tk_FreeGC(path->display, path->pixmapGC);
    }
    if(path->textInfo.insertBorder != NULL) {
        Tk_Free3DBorder(path->textInfo.insertBorder);
    }
    if(path->textInfo.selBorder != NULL) {
        Tk_Free3DBorder(path->textInfo.selBorder);
    }
    if(path->textInfo.selFgColorPtr != NULL) {
        Tk_FreeColor(path->textInfo.selFgColorPtr);
    }
    if(path->display != None) {
        if(path->cursor != None) {
            Tk_FreeCursor(path->display, path->cursor);
        }
    }
    if(path->xScrollCmd != NULL) {
        ckfree(path->xScrollCmd);
    }
    if(path->yScrollCmd != NULL) {
        ckfree(path->yScrollCmd);
    }
    Tcl_DeleteHashTable(&path->idTable);
    Tcl_DeleteHashTable(&path->styleTable);
    Tcl_DeleteHashTable(&path->gradientTable);
    if(path->context != NULL) {
        TkPathFree(path->context);
    }
    if(path->tsoffsetPtr != NULL) {
        ckfree(path->tsoffsetPtr);
    }
    ckfree((char *)path);
}

/*
 * PathMethod_tko_configure --
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathMethod_tko_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    XGCValues gcValues;
    GC  newGC;
    int flags;
    Tcl_Object object;
    TkPathCanvas *path;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object, &pathMeta)) == NULL
        || path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;

    /*
     * A few options need special processing, such as setting the background
     * from a 3-D border and creating a GC for copying bits to the screen.
     */
    Tk_SetBackgroundFromBorder(*(path->win), path->bgBorder);

    if(path->highlightWidth < 0) {
        path->highlightWidth = 0;
    }
    path->inset = path->borderWidth + path->highlightWidth;

    gcValues.function = GXcopy;
    gcValues.graphics_exposures = False;
    gcValues.foreground = Tk_3DBorderColor(path->bgBorder)->pixel;
    newGC = Tk_GetGC(*(path->win),
        GCFunction | GCGraphicsExposures | GCForeground, &gcValues);
    if(path->pixmapGC != None) {
        Tk_FreeGC(path->display, path->pixmapGC);
    }
    path->pixmapGC = newGC;

    /*
     * Reset the desired dimensions for the window.
     */
    Tk_GeometryRequest(*(path->win), path->width + 2 * path->inset,
        path->height + 2 * path->inset);

    /*
     * Restart the cursor timing sequence in case the on-time or off-time just
     * changed.
     */
    if(path->textInfo.gotFocus) {
        CanvasFocusProc(path, 1);
    }

    /* @@@ TODO: I don't see anywhere this is used. Nothing in man page. */
    if(path->tsoffsetPtr != NULL) {
        flags = path->tsoffsetPtr->flags;
        if(flags & TK_OFFSET_LEFT) {
            path->tsoffsetPtr->xoffset = 0;
        } else if(flags & TK_OFFSET_CENTER) {
            path->tsoffsetPtr->xoffset = path->width / 2;
        } else if(flags & TK_OFFSET_RIGHT) {
            path->tsoffsetPtr->xoffset = path->width;
        }
        if(flags & TK_OFFSET_TOP) {
            path->tsoffsetPtr->yoffset = 0;
        } else if(flags & TK_OFFSET_MIDDLE) {
            path->tsoffsetPtr->yoffset = path->height / 2;
        } else if(flags & TK_OFFSET_BOTTOM) {
            path->tsoffsetPtr->yoffset = path->height;
        }
    }
    /*
     * Reset the canvas's origin (this is a no-op unless confine mode has just
     * been turned on or the scroll region has changed).
     */

    CanvasSetOrigin(path, path->xOrigin, path->yOrigin);
    path->flags |= UPDATE_SCROLLBARS | REDRAW_BORDERS;
    Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
        path->xOrigin, path->yOrigin,
        path->xOrigin + Tk_Width(*(path->win)),
        path->yOrigin + Tk_Height(*(path->win)));
    return TCL_OK;
}

/*
 * PathMethod_offset --
 *
 *  Process -offset option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathMethod_offset(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_TSOffset *offset;
    Tcl_Object object;
    TkPathCanvas *path;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object, &pathMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }
    if(path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;
    offset =
        TkPathOffsetNew(interp,
        (ClientData) (TK_OFFSET_RELATIVE | TK_OFFSET_INDEX), *(path->win),
        value);
    if(offset == NULL) {
        return TCL_ERROR;
    }
    if(path->tsoffsetPtr != NULL) {
        ckfree(path->tsoffsetPtr);
    }
    path->tsoffsetPtr = offset;
    return TCL_OK;
}

/*
 * PathMethod_state --
 *
 *  Process -state option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathMethod_state(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int state;
    Tcl_Object object;
    TkPathCanvas *path;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object, &pathMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, value,
            stateStrings, "state", TCL_EXACT, &state) != TCL_OK) {
        return TCL_ERROR;
    }
    path->canvas_state = state;
    return TCL_OK;
}

/*
 * PathMethod_tagstyle --
 *
 *  Process -tagstyle option.
 *
 * Results:
 *  TODO
 *
 * Side effects:
 *  TODO
 */
static int
PathMethod_tagstyle(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int tagstyle;
    Tcl_Object object;
    TkPathCanvas *path;
    Tcl_Obj *value;
    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object, &pathMeta)) == NULL
        || (value =
            TkoWidgetOptionGet(interp, object, objv[objc - 1])) == NULL) {
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, value,
            tagStyleStrings, "tagstyle", TCL_EXACT, &tagstyle) != TCL_OK) {
        return TCL_ERROR;
    }
    path->tagStyle = tagstyle;
    return TCL_OK;
}

/*
 * PathMethod --
 *
 *    This function 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
PathMethod(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int c, result;
    Tcl_Obj *resultObjPtr;
    Tk_PathItem *itemPtr = NULL;        /* Initialization needed only to prevent
                                         * compiler warning. */
    TagSearch *searchPtr = NULL;        /* Allocated by first TagSearchScan, freed by
                                         * TagSearchDestroy */
    int index;
    static const char *optionStrings[] = {
        "addtag", "ancestors", "bbox", "bind",
        "canvasx", "canvasy", "children",
        "cmove", "coords", "create",
        "cscale", "dchars",
        "delete", "depth", "distance", "dtag",
        "find", "firstchild", "focus", "gettags",
        "gradient", "icursor", "index", "insert",
        "itemcget", "itemconfigure", "itempdf", "lastchild",
        "lower", "move", "nextsibling", "parent",
        "prevsibling", "raise", "scale",
        "scan", "select", "style", "type",
        "types", "xview", "yview",
#if 1
        "debugtree",
#endif
        NULL
    };
    enum options {
        CANV_ADDTAG, CANV_ANCESTORS, CANV_BBOX, CANV_BIND,
        CANV_CANVASX, CANV_CANVASY, CANV_CHILDREN,
        CANV_CMOVE, CANV_COORDS, CANV_CREATE,
        CANV_CSCALE, CANV_DCHARS,
        CANV_DELETE, CANV_DEPTH, CANV_DISTANCE, CANV_DTAG,
        CANV_FIND, CANV_FIRSTCHILD, CANV_FOCUS, CANV_GETTAGS,
        CANV_GRADIENT, CANV_ICURSOR, CANV_INDEX, CANV_INSERT,
        CANV_ITEMCGET, CANV_ITEMCONFIGURE, CANV_ITEMPDF, CANV_LASTCHILD,
        CANV_LOWER, CANV_MOVE, CANV_NEXTSIBLING, CANV_PARENT,
        CANV_PREVSIBLING, CANV_RAISE, CANV_SCALE,
        CANV_SCAN, CANV_SELECT, CANV_STYLE, CANV_TYPE,
        CANV_TYPES, CANV_XVIEW, CANV_YVIEW,
#if 1
        CANV_DEBUGTREE,
#endif
    };
    Tcl_Object object;
    TkPathCanvas *path;

    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (path =
            (TkPathCanvas *) Tcl_ObjectGetMetadata(object, &pathMeta)) == NULL
        || path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "option ?arg arg ...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[1], optionStrings, "option", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_Preserve((ClientData) path);

    result = TCL_OK;
    switch ((enum options)index) {
    case CANV_ADDTAG:{
        if(objc < 4) {
            Tcl_WrongNumArgs(interp, 2, objv,
                "tag searchCommand ?arg arg ...?");
            result = TCL_ERROR;
            goto done;
        }
        result = FindItems(interp, path, objc, objv, objv[2], 3, &searchPtr);
        break;
    }
    case CANV_ANCESTORS:{

        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
    Tcl_Obj *listPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    Tcl_Obj *obj;
    Tk_PathItem *walkPtr;

            walkPtr = itemPtr->parentPtr;
            while(walkPtr != NULL) {

                /*
                 * Insert items higher in the tree first.
                 */
                obj = Tcl_NewIntObj(walkPtr->id);
                Tcl_ListObjReplace(NULL, listPtr, 0, 0, 1, &obj);
                walkPtr = walkPtr->parentPtr;
            }
            Tcl_SetObjResult(interp, listPtr);
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_BBOX:{
    int i, gotAny;
    int x1 = 0, y1 = 0, x2 = 0, y2 = 0; /* Initializations needed only
                                         * to prevent overcautious
                                         * compiler warnings. */

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?tagOrId ...?");
            result = TCL_ERROR;
            goto done;
        }
        gotAny = 0;
        for(i = 2; i < objc; i++) {
            FOR_EVERY_CANVAS_ITEM_MATCHING(objv[i], &searchPtr, goto done) {

                /*
                 * Groups bbox are only updated lazily, when needed.
                 */
                if(itemPtr->firstChildPtr != NULL) {
                    TkPathCanvasGroupBbox((Tk_PathCanvas) path, itemPtr,
                        &itemPtr->x1, &itemPtr->y1, &itemPtr->x2, &itemPtr->y2);
                }
                if((itemPtr->x1 >= itemPtr->x2)
                    || (itemPtr->y1 >= itemPtr->y2)) {
                    continue;
                }
                if(!gotAny) {
                    x1 = itemPtr->x1;
                    y1 = itemPtr->y1;
                    x2 = itemPtr->x2;
                    y2 = itemPtr->y2;
                    gotAny = 1;
                } else {
                    if(itemPtr->x1 < x1) {
                        x1 = itemPtr->x1;
                    }
                    if(itemPtr->y1 < y1) {
                        y1 = itemPtr->y1;
                    }
                    if(itemPtr->x2 > x2) {
                        x2 = itemPtr->x2;
                    }
                    if(itemPtr->y2 > y2) {
                        y2 = itemPtr->y2;
                    }
                }
            }
        }
        if(gotAny) {
    Tcl_Obj *listObj = Tcl_NewListObj(0, NULL);

            Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x1));
            Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y1));
            Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(x2));
            Tcl_ListObjAppendElement(interp, listObj, Tcl_NewIntObj(y2));
            Tcl_SetObjResult(interp, listObj);
        }
        break;
    }
    case CANV_BIND:{
    ClientData object;

        if((objc < 3) || (objc > 5)) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?sequence? ?command?");
            result = TCL_ERROR;
            goto done;
        }

        /*
         * Figure out what object to use for the binding (individual item vs.
         * tag).
         */

        object = 0;
        result = TagSearchScan(path, objv[2], &searchPtr);
        if(result != TCL_OK) {
            goto done;
        }
        if(searchPtr->type == SEARCH_TYPE_ID) {
    Tcl_HashEntry *entryPtr;

            entryPtr = Tcl_FindHashEntry(&path->idTable,
                (char *)INT2PTR(searchPtr->id));
            if(entryPtr != NULL) {
                itemPtr = (Tk_PathItem *) Tcl_GetHashValue(entryPtr);
                object = (ClientData) itemPtr;
            }

            if(object == 0) {
                Tcl_AppendResult(interp, "item \"", Tcl_GetString(objv[2]),
                    "\" doesn't exist", NULL);
                result = TCL_ERROR;
                goto done;
            }
        } else {
            object = (ClientData) searchPtr->expr->uid;
        }

        /*
         * Make a binding table if the canvas doesn't already have one.
         */

        if(path->bindingTable == NULL) {
            path->bindingTable = Tk_CreateBindingTable(interp);
        }

        if(objc == 5) {
    int append = 0;
    unsigned long mask;
    char *argv4 = Tcl_GetString(objv[4]);

            if(argv4[0] == 0) {
                result = Tk_DeleteBinding(interp, path->bindingTable,
                    object, Tcl_GetString(objv[3]));
                goto done;
            }
            if(searchPtr->type == SEARCH_TYPE_EXPR) {
                /*
                 * If new tag expression, then insert in linked list.
                 */

    TkPathTagSearchExpr *expr, **lastPtr;

                lastPtr = &(path->bindTagExprs);
                while((expr = *lastPtr) != NULL) {
                    if(expr->uid == searchPtr->expr->uid) {
                        break;
                    }
                    lastPtr = &(expr->next);
                }
                if(!expr) {
                    /*
                     * Transfer ownership of expr to bindTagExprs list.
                     */

                    *lastPtr = searchPtr->expr;
                    searchPtr->expr->next = NULL;

                    /*
                     * Flag in TagSearch that expr has changed ownership so
                     * that TagSearchDestroy doesn't try to free it.
                     */

                    searchPtr->expr = NULL;
                }
            }
            if(argv4[0] == '+') {
                argv4++;
                append = 1;
            }
            mask = Tk_CreateBinding(interp, path->bindingTable,
                object, Tcl_GetString(objv[3]), argv4, append);
            if(mask == 0) {
                result = TCL_ERROR;
                goto done;
            }
            if(mask & (unsigned)~(ButtonMotionMask | Button1MotionMask
                    | Button2MotionMask | Button3MotionMask | Button4MotionMask
                    | Button5MotionMask | ButtonPressMask | ButtonReleaseMask
                    | EnterWindowMask | LeaveWindowMask | KeyPressMask
                    | KeyReleaseMask | PointerMotionMask | VirtualEventMask)) {
                Tk_DeleteBinding(interp, path->bindingTable,
                    object, Tcl_GetString(objv[3]));
                Tcl_ResetResult(interp);
                Tcl_AppendResult(interp, "requested illegal events; ",
                    "only key, button, motion, enter, leave, and virtual ",
                    "events may be used", NULL);
                result = TCL_ERROR;
                goto done;
            }
        } else if(objc == 4) {
    const char *command;

            command = Tk_GetBinding(interp, path->bindingTable,
                object, Tcl_GetString(objv[3]));
            if(command == NULL) {
    const char *string;

                string = Tcl_GetStringResult(interp);

                /*
                 * Ignore missing binding errors. This is a special hack that
                 * relies on the error message returned by FindSequence in
                 * tkBind.c.
                 */

                if(string[0] != '\0') {
                    result = TCL_ERROR;
                    goto done;
                } else {
                    Tcl_ResetResult(interp);
                }
            } else {
                Tcl_SetResult(interp, (char *)command, TCL_STATIC);
            }
        } else {
            Tk_GetAllBindings(interp, path->bindingTable, object);
        }
        break;
    }
    case CANV_CANVASX:{
    int x;
    double grid;
    char buf[TCL_DOUBLE_SPACE];

        if((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "screenx ?gridspacing?");
            result = TCL_ERROR;
            goto done;
        }
        if(Tk_GetPixelsFromObj(interp, *(path->win), objv[2], &x) != TCL_OK) {
            result = TCL_ERROR;
            goto done;
        }
        if(objc == 4) {
            if(Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[3], &grid) != TCL_OK) {
                result = TCL_ERROR;
                goto done;
            }
        } else {
            grid = 0.0;
        }
        x += path->xOrigin;
        Tcl_PrintDouble(interp, GridAlign((double)x, grid), buf);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        break;
    }
    case CANV_CANVASY:{
    int y;
    double grid;
    char buf[TCL_DOUBLE_SPACE];

        if((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "screeny ?gridspacing?");
            result = TCL_ERROR;
            goto done;
        }
        if(Tk_GetPixelsFromObj(interp, *(path->win), objv[2], &y) != TCL_OK) {
            result = TCL_ERROR;
            goto done;
        }
        if(objc == 4) {
            if(Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[3], &grid) != TCL_OK) {
                result = TCL_ERROR;
                goto done;
            }
        } else {
            grid = 0.0;
        }
        y += path->yOrigin;
        Tcl_PrintDouble(interp, GridAlign((double)y, grid), buf);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        break;
    }
    case CANV_CHILDREN:{
    Tcl_Obj *listObj;
    Tk_PathItem *childPtr;

        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            listObj = Tcl_NewListObj(0, NULL);
            childPtr = itemPtr->firstChildPtr;
            while(childPtr != NULL) {
                Tcl_ListObjAppendElement(interp, listObj,
                    Tcl_NewIntObj(childPtr->id));
                childPtr = childPtr->nextPtr;
            }
            Tcl_SetObjResult(interp, listObj);
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_COORDS:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?x y x y ...?");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            if(objc != 3) {
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            }
            if(itemPtr->typePtr->coordProc != NULL) {
                result = (*itemPtr->typePtr->coordProc) (interp,
                    (Tk_PathCanvas) path, itemPtr, objc - 3, objv + 3);
            }
            if(objc != 3) {
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            }
        }
        break;
    }
    case CANV_CREATE:{
    Tk_PathItemType *typePtr;
    Tk_PathItemType *matchPtr = NULL;
    Tk_PathItem *itemPtr;
    char *arg;
    int length;

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "type coords ?arg arg ...?");
            result = TCL_ERROR;
            goto done;
        }
        arg = Tcl_GetStringFromObj(objv[2], &length);
        c = arg[0];
        for(typePtr = typeList; typePtr != NULL; typePtr = typePtr->nextPtr) {
            if((c == typePtr->name[0])
                && (strncmp(arg, typePtr->name, (unsigned)length) == 0)) {
                if(matchPtr != NULL) {
                  badType:
                    Tcl_AppendResult(interp,
                        "unknown or ambiguous item type \"", arg, "\"", NULL);
                    result = TCL_ERROR;
                    goto done;
                }
                matchPtr = typePtr;
            }
        }
        if(matchPtr == NULL) {
            goto badType;
        }
        if((strncmp("group", matchPtr->name, (unsigned)length) != 0) &&
            (objc < 4)) {
            /*
             * Allow more specific error return. Groups have no coords.
             */
            Tcl_WrongNumArgs(interp, 3, objv, "coords ?arg arg ...?");
            result = TCL_ERROR;
            goto done;
        }
        typePtr = matchPtr;

        result =
            ItemCreate(interp, path, typePtr, 0, &itemPtr, objc - 3, objv + 3);
        if(result != TCL_OK) {
            result = TCL_ERROR;
            goto done;
        }
        path->hotPtr = itemPtr;
        path->hotPrevPtr = itemPtr->prevPtr;

        EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
        path->flags |= REPICK_NEEDED;
        Tcl_SetObjResult(interp, Tcl_NewIntObj(itemPtr->id));
        break;
    }
    case CANV_DCHARS:{
    int first, last;
    int x1, x2, y1, y2;

        if((objc != 4) && (objc != 5)) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId first ?last?");
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if((itemPtr->typePtr->indexProc == NULL)
                || (itemPtr->typePtr->dCharsProc == NULL)) {
                continue;
            }
            result = itemPtr->typePtr->indexProc(interp,
                (Tk_PathCanvas) path, itemPtr, (char *)objv[3], &first);
            if(result != TCL_OK) {
                goto done;
            }
            if(objc == 5) {
                result = itemPtr->typePtr->indexProc(interp,
                    (Tk_PathCanvas) path, itemPtr, (char *)objv[4], &last);
                if(result != TCL_OK) {
                    goto done;
                }
            } else {
                last = first;
            }

            /*
             * Redraw both item's old and new areas: it's possible that a
             * delete could result in a new area larger than the old area.
             * Except if the insertProc sets the TK_ITEM_DONT_REDRAW flag,
             * nothing more needs to be done.
             */

            x1 = itemPtr->x1;
            y1 = itemPtr->y1;
            x2 = itemPtr->x2;
            y2 = itemPtr->y2;
            itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
            (*itemPtr->typePtr->dCharsProc) ((Tk_PathCanvas) path,
                itemPtr, first, last);
            if(!(itemPtr->redraw_flags & TK_ITEM_DONT_REDRAW)) {
                Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
                    x1, y1, x2, y2);
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            }
            itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
        }
        break;
    }
    case CANV_DEBUGTREE:{
    Tk_PathItem *walkPtr, *tmpPtr;
    char tmp[256], info[256];
    const char *s;
    int depth;

        if(objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "");
            result = TCL_ERROR;
            goto done;
        }
        for(walkPtr = path->rootItemPtr; walkPtr != NULL;
            walkPtr = TkPathCanvasItemIteratorNext(walkPtr)) {
            depth = 0;
            tmpPtr = walkPtr;
            while(tmpPtr->parentPtr != NULL) {
                depth++;
                tmpPtr = tmpPtr->parentPtr;
            }
            if(walkPtr->firstChildPtr != NULL) {
                s = "----";
            } else {
                s = "";
            }
            info[0] = '\0';
            DebugGetItemInfo(walkPtr, info);
            sprintf(tmp, "%*d%s\t%s (itemPtr=%p)\n", 4 * depth + 3, walkPtr->id,
                s, info, walkPtr);
            Tcl_WriteChars(Tcl_GetChannel(interp, "stdout", NULL), tmp, -1);
        }
        break;
    }
    case CANV_DELETE:{
    int i;

        /*
         * Since deletinga group item implicitly deletes all its children
         * we may unintentionally try to delete an item more than once.
         * We therefore flatten (parent = root) all items first.
         */
        for(i = 2; i < objc; i++) {
            FOR_EVERY_CANVAS_ITEM_MATCHING(objv[i], &searchPtr, goto done) {

                /*
                 * Silently ignoring the root item.
                 */
                if(itemPtr->id == 0)
                    continue;

                /*
                 * This will also delete all its descendants by
                 * recursive calls.
                 */
                ItemDelete(path, itemPtr);
            }
        }
        break;
    }
    case CANV_DEPTH:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            Tcl_SetObjResult(interp,
                Tcl_NewIntObj(TkPathCanvasGetDepth(itemPtr)));
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_DISTANCE:{
    double point[2], dist;

        if(objc != 5) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId x y");
            result = TCL_ERROR;
            goto done;
        }
        if((Tcl_GetDoubleFromObj(interp, objv[3], &point[0]) != TCL_OK) ||
            (Tcl_GetDoubleFromObj(interp, objv[4], &point[1]) != TCL_OK)) {
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            dist =
                (*itemPtr->typePtr->pointProc) ((Tk_PathCanvas) path, itemPtr,
                point);
            Tcl_SetObjResult(interp, Tcl_NewDoubleObj(dist));
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_DTAG:{
    Tk_PathTags *ptagsPtr;
    Tk_Uid tag;
    int i;

        if((objc != 3) && (objc != 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?tagToDelete?");
            result = TCL_ERROR;
            goto done;
        }
        if(objc == 4) {
            tag = Tk_GetUid(Tcl_GetString(objv[3]));
        } else {
            tag = Tk_GetUid(Tcl_GetString(objv[2]));
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            ptagsPtr = itemPtr->pathTagsPtr;
            if(ptagsPtr != NULL) {
                for(i = ptagsPtr->numTags - 1; i >= 0; i--) {
                    if(ptagsPtr->tagPtr[i] == tag) {
                        ptagsPtr->tagPtr[i] =
                            ptagsPtr->tagPtr[ptagsPtr->numTags - 1];
                        ptagsPtr->numTags--;
                    }
                }
            }
        }
        break;
    }
    case CANV_FIND:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "searchCommand ?arg arg ...?");
            result = TCL_ERROR;
            goto done;
        }
        result = FindItems(interp, path, objc, objv, NULL, 2, &searchPtr);
        break;
    }
    case CANV_FIRSTCHILD:{
    Tk_PathItem *childPtr;

        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            childPtr = itemPtr->firstChildPtr;
            if(childPtr != NULL) {
                Tcl_SetObjResult(interp, Tcl_NewIntObj(childPtr->id));
            }
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_FOCUS:{
        if(objc > 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "?tagOrId?");
            result = TCL_ERROR;
            goto done;
        }
        itemPtr = path->textInfo.focusItemPtr;
        if(objc == 2) {
            if(itemPtr != NULL) {
    char buf[TCL_INTEGER_SPACE];

                sprintf(buf, "%d", itemPtr->id);
                Tcl_SetResult(interp, buf, TCL_VOLATILE);
            }
            goto done;
        }
        if((itemPtr != NULL) && (path->textInfo.gotFocus)) {
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
        }
        if(Tcl_GetString(objv[2])[0] == 0) {
            path->textInfo.focusItemPtr = NULL;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if(itemPtr->typePtr->icursorProc != NULL) {
                break;
            }
        }
        if(itemPtr == NULL) {
            goto done;
        }
        path->textInfo.focusItemPtr = itemPtr;
        if(path->textInfo.gotFocus) {
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
        }
        break;
    }
    case CANV_GETTAGS:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
    int i;
    Tk_PathTags *ptagsPtr;

            ptagsPtr = itemPtr->pathTagsPtr;
            if(ptagsPtr != NULL) {
                for(i = 0; i < ptagsPtr->numTags; i++) {
                    Tcl_AppendElement(interp, (char *)ptagsPtr->tagPtr[i]);
                }
            }
        }
        break;
    }
    case CANV_GRADIENT:{
        result = TkPathCanvasGradientObjCmd(interp, path, objc, objv);
        break;
    }
    case CANV_ICURSOR:{
    int index;

        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId index");
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if((itemPtr->typePtr->indexProc == NULL)
                || (itemPtr->typePtr->icursorProc == NULL)) {
                goto done;
            }
            result = itemPtr->typePtr->indexProc(interp,
                (Tk_PathCanvas) path, itemPtr, (char *)objv[3], &index);
            if(result != TCL_OK) {
                goto done;
            }
            (*itemPtr->typePtr->icursorProc) ((Tk_PathCanvas) path, itemPtr,
                index);
            if((itemPtr == path->textInfo.focusItemPtr)
                && (path->textInfo.cursorOn)) {
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            }
        }
        break;
    }
    case CANV_INDEX:{
    int index;
    char buf[TCL_INTEGER_SPACE];

        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId string");
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if(itemPtr->typePtr->indexProc != NULL) {
                break;
            }
        }
        if(itemPtr == NULL) {
            Tcl_AppendResult(interp, "can't find an indexable item \"",
                Tcl_GetString(objv[2]), "\"", NULL);
            result = TCL_ERROR;
            goto done;
        }
        result = itemPtr->typePtr->indexProc(interp, (Tk_PathCanvas) path,
            itemPtr, (char *)objv[3], &index);
        if(result != TCL_OK) {
            goto done;
        }
        sprintf(buf, "%d", index);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        break;
    }
    case CANV_INSERT:{
    int beforeThis;
    int x1, x2, y1, y2;

        if(objc != 5) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId beforeThis string");
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if((itemPtr->typePtr->indexProc == NULL)
                || (itemPtr->typePtr->insertProc == NULL)) {
                continue;
            }
            result = itemPtr->typePtr->indexProc(interp,
                (Tk_PathCanvas) path, itemPtr, (char *)objv[3], &beforeThis);
            if(result != TCL_OK) {
                goto done;
            }

            /*
             * Redraw both item's old and new areas: it's possible that an
             * insertion could result in a new area either larger or smaller
             * than the old area. Except if the insertProc sets the
             * TK_ITEM_DONT_REDRAW flag, nothing more needs to be done.
             */

            x1 = itemPtr->x1;
            y1 = itemPtr->y1;
            x2 = itemPtr->x2;
            y2 = itemPtr->y2;
            itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
            (*itemPtr->typePtr->insertProc) ((Tk_PathCanvas) path,
                itemPtr, beforeThis, (char *)objv[4]);
            if(!(itemPtr->redraw_flags & TK_ITEM_DONT_REDRAW)) {
                Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
                    x1, y1, x2, y2);
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            }
            itemPtr->redraw_flags &= ~TK_ITEM_DONT_REDRAW;
        }
        break;
    }
    case CANV_ITEMCGET:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId option");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            resultObjPtr = Tk_GetOptionValue(path->interp, (char *)itemPtr,
                itemPtr->optionTable, objv[3], *(path->win));
            if(resultObjPtr == NULL) {
                result = TCL_ERROR;
                goto done;
            } else {
                Tcl_SetObjResult(interp, resultObjPtr);
            }
        }
        break;
    }
    case CANV_ITEMCONFIGURE:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?option value ...?");
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            if(objc <= 4) {
                resultObjPtr = Tk_GetOptionInfo(path->interp, (char *)itemPtr,
                    itemPtr->optionTable, (objc == 4) ? objv[3] : NULL,
                    *(path->win));
                if(resultObjPtr == NULL) {
                    result = TCL_ERROR;
                    goto done;
                } else {
                    Tcl_SetObjResult(interp, resultObjPtr);
                }
            } else {
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
                result = (*itemPtr->typePtr->configProc) (interp,
                    (Tk_PathCanvas) path, itemPtr, objc - 3, objv + 3,
                    TK_CONFIG_ARGV_ONLY);
                EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
                path->flags |= REPICK_NEEDED;
            }
            if((result != TCL_OK) || (objc < 5)) {
                break;
            }
        }
        break;
    }
    case CANV_ITEMPDF:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ...");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            if(itemPtr->typePtr->pdfProc != NULL) {
                result = (*itemPtr->typePtr->pdfProc) (interp,
                    (Tk_PathCanvas) path, itemPtr, objc - 3, objv + 3, 0);
            }
        }
        break;
    }
    case CANV_LASTCHILD:{
    Tk_PathItem *childPtr;

        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            childPtr = itemPtr->lastChildPtr;
            if(childPtr != NULL) {
                Tcl_SetObjResult(interp, Tcl_NewIntObj(childPtr->id));
            }
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_LOWER:{
    Tk_PathItem *itemPtr;

        if((objc != 3) && (objc != 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?belowThis?");
            result = TCL_ERROR;
            goto done;
        }

        /*
         * First find the item just after which we'll insert the named items.
         */

        if(objc == 3) {
            itemPtr = NULL;
        } else {
            FIRST_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done);
            if(itemPtr == NULL) {
                Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[3]),
                    "\" doesn't match any items", NULL);
                result = TCL_ERROR;
                goto done;
            }
            itemPtr = itemPtr->prevPtr;
        }
        result = RelinkItems(path, objv[2], itemPtr, &searchPtr);
        break;
    }
    case CANV_CMOVE:
    case CANV_MOVE:{
    int compensate = ((enum options)index) == CANV_CMOVE;
    double xAmount, yAmount;

        if(objc != 5) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId xAmount yAmount");
            result = TCL_ERROR;
            goto done;
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path, objv[3],
                    &xAmount) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[4], &yAmount) != TCL_OK)) {
            result = TCL_ERROR;
            goto done;
        }

        /* Round the deltas to the nearest integer to avoid round-off errors */
        xAmount = (double)((int)(xAmount + (xAmount > 0 ? 0.5 : -0.5)));
        yAmount = (double)((int)(yAmount + (yAmount > 0 ? 0.5 : -0.5)));

        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            (void)(*itemPtr->typePtr->translateProc) ((Tk_PathCanvas) path,
                itemPtr, compensate, xAmount, yAmount);
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            path->flags |= REPICK_NEEDED;
        }
        break;
    }
    case CANV_NEXTSIBLING:{
    Tk_PathItem *nextPtr;

        /* @@@ TODO: add optional argument like TreeCtrl has. */
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            nextPtr = itemPtr->nextPtr;
            if(nextPtr != NULL) {
                Tcl_SetObjResult(interp, Tcl_NewIntObj(nextPtr->id));
            }
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_PARENT:{
    int id;

        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "id");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            if(itemPtr->id == 0) {
                id = -1;        /* @@@ TODO: What else to return? */
            } else {
                id = itemPtr->parentPtr->id;
            }
            Tcl_SetObjResult(interp, Tcl_NewIntObj(id));
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_PREVSIBLING:{
    Tk_PathItem *prevPtr;

        /* @@@ TODO: add optional argument like TreeCtrl has. */
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            prevPtr = itemPtr->prevPtr;
            if(prevPtr != NULL) {
                Tcl_SetObjResult(interp, Tcl_NewIntObj(prevPtr->id));
            }
        } else {
            Tcl_AppendResult(interp, "tag \"", Tcl_GetString(objv[2]),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
            goto done;
        }
        break;
    }
    case CANV_RAISE:{
    Tk_PathItem *prevPtr;

        if((objc != 3) && (objc != 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "tagOrId ?aboveThis?");
            result = TCL_ERROR;
            goto done;
        }

        /*
         * First find the item just after which we'll insert the named items.
         */

        if(objc == 3) {
            prevPtr = path->rootItemPtr->lastChildPtr;
        } else {
            prevPtr = NULL;
            FOR_EVERY_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done) {
                prevPtr = itemPtr;
            }
            if(prevPtr == NULL) {
                Tcl_AppendResult(interp, "tagOrId \"", Tcl_GetString(objv[3]),
                    "\" doesn't match any items", NULL);
                result = TCL_ERROR;
                goto done;
            }
        }
        result = RelinkItems(path, objv[2], prevPtr, &searchPtr);
        break;
    }
    case CANV_CSCALE:
    case CANV_SCALE:{
    int compensate = ((enum options)index) == CANV_CSCALE;
    double xOrigin, yOrigin, xScale, yScale;

        if(objc != 7) {
            Tcl_WrongNumArgs(interp, 2, objv,
                "tagOrId xOrigin yOrigin xScale yScale");
            result = TCL_ERROR;
            goto done;
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[3], &xOrigin) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[4], &yOrigin) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[5], &xScale) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[6], &yScale) != TCL_OK)) {
            result = TCL_ERROR;
            goto done;
        }
        if((xScale == 0.0) || (yScale == 0.0)) {
            Tcl_SetResult(interp, (char *)"scale factor cannot be zero",
                TCL_STATIC);
            result = TCL_ERROR;
            goto done;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done) {
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            (void)(*itemPtr->typePtr->scaleProc) ((Tk_PathCanvas) path,
                itemPtr, compensate, xOrigin, yOrigin, xScale, yScale);
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            path->flags |= REPICK_NEEDED;
        }
        break;
    }
    case CANV_SCAN:{
    int x, y;
#ifdef ANDROID
    int gain = 2;
#else
    int gain = 10;
#endif
    static const char *optionStrings[] = {
        "mark", "dragto", NULL
    };

        if(objc < 5) {
            Tcl_WrongNumArgs(interp, 2, objv, "mark|dragto x y ?dragGain?");
            result = TCL_ERROR;
        } else if(Tcl_GetIndexFromObj(interp, objv[2], optionStrings,
                "scan option", 0, &index) != TCL_OK) {
            result = TCL_ERROR;
        } else if((objc != 5) && (objc != 5 + index)) {
            Tcl_WrongNumArgs(interp, 3, objv, index ? "x y ?gain?" : "x y");
            result = TCL_ERROR;
        } else if((Tcl_GetIntFromObj(interp, objv[3], &x) != TCL_OK)
            || (Tcl_GetIntFromObj(interp, objv[4], &y) != TCL_OK)) {
            result = TCL_ERROR;
        } else if((objc == 6) &&
            (Tcl_GetIntFromObj(interp, objv[5], &gain) != TCL_OK)) {
            result = TCL_ERROR;
        } else if(!index) {
            path->scanX = x;
            path->scanXOrigin = path->xOrigin;
            path->scanY = y;
            path->scanYOrigin = path->yOrigin;
        } else {
    int newXOrigin, newYOrigin, tmp;

            /*
             * Compute a new view origin for the canvas, amplifying the
             * mouse motion.
             */

            tmp = path->scanXOrigin - gain * (x - path->scanX)
                - path->scroll[0];
            newXOrigin = path->scroll[0] + tmp;
            tmp = path->scanYOrigin - gain * (y - path->scanY)
                - path->scroll[1];
            newYOrigin = path->scroll[1] + tmp;
            CanvasSetOrigin(path, newXOrigin, newYOrigin);
        }
        break;
    }
    case CANV_SELECT:{
    int index, optionindex;
    static const char *optionStrings[] = {
        "adjust", "clear", "from", "item", "to", NULL
    };
    enum options {
        CANV_ADJUST, CANV_CLEAR, CANV_FROM, CANV_ITEM, CANV_TO
    };

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "option ?tagOrId? ?arg?");
            result = TCL_ERROR;
            goto done;
        }
        if(objc >= 4) {
            FOR_EVERY_CANVAS_ITEM_MATCHING(objv[3], &searchPtr, goto done) {
                if((itemPtr->typePtr->indexProc != NULL)
                    && (itemPtr->typePtr->selectionProc != NULL)) {
                    break;
                }
            }
            if(itemPtr == NULL) {
                Tcl_AppendResult(interp,
                    "can't find an indexable and selectable item \"",
                    Tcl_GetString(objv[3]), "\"", NULL);
                result = TCL_ERROR;
                goto done;
            }
        }
        if(objc == 5) {
            result = itemPtr->typePtr->indexProc(interp,
                (Tk_PathCanvas) path, itemPtr, (char *)objv[4], &index);
            if(result != TCL_OK) {
                goto done;
            }
        }
        if(Tcl_GetIndexFromObj(interp, objv[2], optionStrings,
                "select option", 0, &optionindex) != TCL_OK) {
            result = TCL_ERROR;
            goto done;
        }
        switch ((enum options)optionindex) {
        case CANV_ADJUST:
            if(objc != 5) {
                Tcl_WrongNumArgs(interp, 3, objv, "tagOrId index");
                result = TCL_ERROR;
                goto done;
            }
            if(path->textInfo.selItemPtr == itemPtr) {
                if(index < (path->textInfo.selectFirst
                        + path->textInfo.selectLast) / 2) {
                    path->textInfo.selectAnchor = path->textInfo.selectLast + 1;
                } else {
                    path->textInfo.selectAnchor = path->textInfo.selectFirst;
                }
            }
            CanvasSelectTo(path, itemPtr, index);
            break;
        case CANV_CLEAR:
            if(objc != 3) {
                Tcl_AppendResult(interp, 3, objv, NULL);
                result = TCL_ERROR;
                goto done;
            }
            if(path->textInfo.selItemPtr != NULL) {
                EventuallyRedrawItem((Tk_PathCanvas) path,
                    path->textInfo.selItemPtr);
                path->textInfo.selItemPtr = NULL;
            }
            goto done;
            break;
        case CANV_FROM:
            if(objc != 5) {
                Tcl_WrongNumArgs(interp, 3, objv, "tagOrId index");
                result = TCL_ERROR;
                goto done;
            }
            path->textInfo.anchorItemPtr = itemPtr;
            path->textInfo.selectAnchor = index;
            break;
        case CANV_ITEM:
            if(objc != 3) {
                Tcl_WrongNumArgs(interp, 3, objv, NULL);
                result = TCL_ERROR;
                goto done;
            }
            if(path->textInfo.selItemPtr != NULL) {
                Tcl_SetObjResult(interp,
                    Tcl_NewIntObj(path->textInfo.selItemPtr->id));
            }
            break;
        case CANV_TO:
            if(objc != 5) {
                Tcl_WrongNumArgs(interp, 2, objv, "tagOrId index");
                result = TCL_ERROR;
                goto done;
            }
            CanvasSelectTo(path, itemPtr, index);
            break;
        }
        break;
    }
    case CANV_STYLE:{
        result = TkPathCanvasStyleObjCmd(interp, path, objc, objv);
        break;
    }
    case CANV_TYPE:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "tag");
            result = TCL_ERROR;
            goto done;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[2], &searchPtr, goto done);
        if(itemPtr != NULL) {
            Tcl_SetResult(interp, (char *)itemPtr->typePtr->name, TCL_STATIC);
        }
        break;
    }
    case CANV_TYPES:{
    Tk_PathItemType *typePtr;
    Tcl_Obj *listObj;

        if(objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "");
            result = TCL_ERROR;
            goto done;
        }
        listObj = Tcl_NewListObj(0, NULL);
        for(typePtr = typeList; typePtr != NULL; typePtr = typePtr->nextPtr) {
            Tcl_ListObjAppendElement(interp, listObj,
                Tcl_NewStringObj(typePtr->name, -1));
        }
        Tcl_SetObjResult(interp, listObj);
        break;
    }
    case CANV_XVIEW:{
    int count, type;
    int newX = 0;              /* Initialization needed only to prevent
                                * gcc warnings. */
    double fraction;

        if(objc == 2) {
            Tcl_SetObjResult(interp,
                ScrollFractions(path->xOrigin + path->inset,
                    path->xOrigin + Tk_Width(*(path->win))
                    - path->inset, path->scroll[0], path->scroll[2]));
        } else {
    const char **args = GetStringsFromObjs(objc, objv);
            type = Tk_GetScrollInfo(interp, objc, args, &fraction, &count);
            if(args != NULL) {
                ckfree((char *)args);
            }
            switch (type) {
            case TK_SCROLL_ERROR:
                result = TCL_ERROR;
                goto done;
            case TK_SCROLL_MOVETO:
                newX = path->scroll[0] - path->inset
                    + (int)(fraction * (path->scroll[2]
                        - path->scroll[0]) + 0.5);
                break;
            case TK_SCROLL_PAGES:
                newX = (int)(path->xOrigin + count * .9
                    * (Tk_Width(*(path->win)) - 2 * path->inset));
                break;
            case TK_SCROLL_UNITS:
                if(path->xScrollIncrement > 0) {
                    newX = path->xOrigin + count * path->xScrollIncrement;
                } else {
                    newX = (int)(path->xOrigin + count * .1
                        * (Tk_Width(*(path->win))
                            - 2 * path->inset));
                }
                break;
            }
            CanvasSetOrigin(path, newX, path->yOrigin);
        }
        break;
    }
    case CANV_YVIEW:{
    int count, type;
    int newY = 0;              /* Initialization needed only to prevent
                                * gcc warnings. */
    double fraction;

        if(objc == 2) {
            Tcl_SetObjResult(interp,
                ScrollFractions(path->yOrigin + path->inset,
                    path->yOrigin + Tk_Height(*(path->win))
                    - path->inset, path->scroll[1], path->scroll[3]));
        } else {
    const char **args = GetStringsFromObjs(objc, objv);
            type = Tk_GetScrollInfo(interp, objc, args, &fraction, &count);
            if(args != NULL) {
                ckfree((char *)args);
            }
            switch (type) {
            case TK_SCROLL_ERROR:
                result = TCL_ERROR;
                goto done;
            case TK_SCROLL_MOVETO:
                newY = path->scroll[1] - path->inset
                    + (int)(fraction * (path->scroll[3]
                        - path->scroll[1]) + 0.5);
                break;
            case TK_SCROLL_PAGES:
                newY = (int)(path->yOrigin + count * .9
                    * (Tk_Height(*(path->win))
                        - 2 * path->inset));
                break;
            case TK_SCROLL_UNITS:
                if(path->yScrollIncrement > 0) {
                    newY = path->yOrigin + count * path->yScrollIncrement;
                } else {
                    newY = (int)(path->yOrigin + count * .1
                        * (Tk_Height(*(path->win))
                            - 2 * path->inset));
                }
                break;
            }
            CanvasSetOrigin(path, path->xOrigin, newY);
        }
        break;
    }
    }

  done:
    TagSearchDestroy(searchPtr);
    Tcl_Release((ClientData) path);
    return result;
}

/*
 * PathCanvasWorldChanged --
 *
 *    This function is called when the world has changed in some way and the
 *    widget needs to recompute all its graphics contexts and determine its
 *    new geometry.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Configures all items in the canvas with a empty argc/argv, for the
 *    side effect of causing all the items to recompute their geometry and
 *    to be redisplayed.
 */
static void
PathCanvasWorldChanged(
    ClientData instanceData)
{              /* Information about widget. */
TkPathCanvas *path = (TkPathCanvas *) instanceData;
Tk_PathItem *itemPtr;
int result;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    itemPtr = path->rootItemPtr;
    for(; itemPtr != NULL; itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
        result = (*itemPtr->typePtr->configProc) (path->interp,
            (Tk_PathCanvas) path, itemPtr, 0, NULL, TK_CONFIG_ARGV_ONLY);
        if(result != TCL_OK) {
            Tcl_ResetResult(path->interp);
        }
    }
    path->flags |= REPICK_NEEDED;
    Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
        path->xOrigin, path->yOrigin,
        path->xOrigin + Tk_Width(*(path->win)),
        path->yOrigin + Tk_Height(*(path->win)));
}

/*
 * PathDisplay --
 *
 *    This function redraws the contents of a canvas 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
PathDisplay(
    ClientData clientData /* Information about widget. */)
{             
    TkPathCanvas *path = (TkPathCanvas *) clientData;
    Tk_PathItem *itemPtr;
    Pixmap pixmap;
    int screenX1, screenX2, screenY1, screenY2, width, height;

    if(path->win == NULL || *(path->win) == NULL)
        return;
    if(!Tk_IsMapped(*(path->win))) {
        goto done;
    }

    /*
     * Choose a new current item if that is needed (this could cause event
     * handlers to be invoked).
     */

    Tcl_Preserve((ClientData) path);
    while(path->flags & REPICK_NEEDED) {
        path->flags &= ~REPICK_NEEDED;
        PickCurrentItem(path, &path->pickEvent);
        if(path->win == NULL || *(path->win) == NULL) {
            Tcl_Release((ClientData) path);
            return;
        }
    }
    Tcl_Release((ClientData) path);

    /*
     * Scan through the item list, registering the bounding box for all items
     * that didn't do that for the final coordinates yet. This can be
     * determined by the FORCE_REDRAW flag.
     */

    for(itemPtr = path->rootItemPtr; itemPtr != NULL;
        itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
        if(itemPtr->redraw_flags & FORCE_REDRAW) {
            itemPtr->redraw_flags &= ~FORCE_REDRAW;
            EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
            itemPtr->redraw_flags &= ~FORCE_REDRAW;
        }
    }

    /*
     * Compute the intersection between the area that needs redrawing and the
     * area that's visible on the screen.
     */

    if((path->redrawX1 < path->redrawX2)
        && (path->redrawY1 < path->redrawY2)) {
        screenX1 = path->xOrigin + path->inset;
        screenY1 = path->yOrigin + path->inset;
        screenX2 = path->xOrigin + Tk_Width(*(path->win)) - path->inset;
        screenY2 = path->yOrigin + Tk_Height(*(path->win)) - path->inset;
        if(path->redrawX1 > screenX1) {
            screenX1 = path->redrawX1;
        }
        if(path->redrawY1 > screenY1) {
            screenY1 = path->redrawY1;
        }
        if(path->redrawX2 < screenX2) {
            screenX2 = path->redrawX2;
        }
        if(path->redrawY2 < screenY2) {
            screenY2 = path->redrawY2;
        }
        if((screenX1 >= screenX2) || (screenY1 >= screenY2)) {
            goto borders;
        }

        width = screenX2 - screenX1;
        height = screenY2 - screenY1;

#ifndef TK_PATH_NO_DOUBLE_BUFFERING
        /*
         * Redrawing is done in a temporary pixmap that is allocated here and
         * freed at the end of the function. All drawing is done to the
         * pixmap, and the pixmap is copied to the screen at the end of the
         * function. The temporary pixmap serves two purposes:
         *
         * 1. It provides a smoother visual effect (no clearing and gradual
         *    redraw will be visible to users).
         * 2. It allows us to redraw only the objects that overlap the redraw
         *    area. Otherwise incorrect results could occur from redrawing
         *    things that stick outside of the redraw area (we'd have to
         *    redraw everything in order to make the overlaps look right).
         *
         * Some tricky points about the pixmap:
         *
         * 1. We only allocate a large enough pixmap to hold the area that has
         *    to be redisplayed. This saves time in in the X server for large
         *    objects that cover much more than the area being redisplayed:
         *    only the area of the pixmap will actually have to be redrawn.
         * 2. Some X servers (e.g. the one for DECstations) have troubles with
         *    with characters that overlap an edge of the pixmap (on the DEC
         *    servers, as of 8/18/92, such characters are drawn one pixel too
         *    far to the right). To handle this problem, make the pixmap a bit
         *    larger than is absolutely needed so that for normal-sized fonts
         *    the characters that overlap the edge of the pixmap will be
         *    outside the area we care about.
         */

#ifdef PLATFORM_SDL
        path->drawableXOrigin = screenX1;
        path->drawableYOrigin = screenY1;
        pixmap =
            Tk_GetPixmap(Tk_Display(*(path->win)), Tk_WindowId(*(path->win)),
            width, height, (unsigned)-32);
#else
        path->drawableXOrigin = screenX1 - 30;
        path->drawableYOrigin = screenY1 - 30;
        pixmap =
            Tk_GetPixmap(Tk_Display(*(path->win)), Tk_WindowId(*(path->win)),
            (screenX2 + 30 - path->drawableXOrigin),
            (screenY2 + 30 - path->drawableYOrigin), Tk_Depth(*(path->win)));
#endif
#else
        path->drawableXOrigin = path->xOrigin;
        path->drawableYOrigin = path->yOrigin;
        pixmap = Tk_WindowId(*(path->win));
        TkpClipDrawableToRect(Tk_Display(*(path->win)), pixmap,
            screenX1 - path->xOrigin, screenY1 - path->yOrigin, width, height);
#endif /* TK_PATH_NO_DOUBLE_BUFFERING */

        /*
         * Clear the area to be redrawn.
         */

        XFillRectangle(Tk_Display(*(path->win)), pixmap, path->pixmapGC,
            screenX1 - path->drawableXOrigin,
            screenY1 - path->drawableYOrigin, (unsigned int)width,
            (unsigned int)height);

        /*
         * Scan through the item list, redrawing those items that need it. An
         * item must be redraw if either (a) it intersects the smaller
         * on-screen area or (b) it intersects the full canvas area and its
         * type requests that it be redrawn always (e.g. so subwindows can be
         * unmapped when they move off-screen).
         */

#if defined(_WIN32) && !defined(PLATFORM_SDL)
        path->context = NULL;
#else
        path->context = TkPathInit(*(path->win), pixmap);
#endif
        for(itemPtr = path->rootItemPtr; itemPtr != NULL;
            itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
            if((itemPtr->x1 >= screenX2)
                || (itemPtr->y1 >= screenY2)
                || (itemPtr->x2 < screenX1)
                || (itemPtr->y2 < screenY1)) {
                if(!(itemPtr->typePtr->alwaysRedraw & 1)
                    || (itemPtr->x1 >= path->redrawX2)
                    || (itemPtr->y1 >= path->redrawY2)
                    || (itemPtr->x2 < path->redrawX1)
                    || (itemPtr->y2 < path->redrawY1)) {
                    continue;
                }
            }
            if(itemPtr->state == TK_PATHSTATE_HIDDEN ||
                (itemPtr->state == TK_PATHSTATE_NULL &&
                    path->canvas_state == TK_PATHSTATE_HIDDEN)) {
                continue;
            }
#if defined(_WIN32) && !defined(PLATFORM_SDL)
            if(itemPtr->typePtr->isPathType) {
                if(path->context == NULL) {
                    path->context = TkPathInit(*(path->win), pixmap);
                } else {
                    TkPathResetTMatrix(path->context);
                }
            } else if(path->context != NULL) {
                TkPathFree(path->context);
                path->context = NULL;
            }
#else
            if(itemPtr->typePtr->isPathType) {
                TkPathResetTMatrix(path->context);
            }
#endif
            (*itemPtr->typePtr->displayProc) ((Tk_PathCanvas) path, itemPtr,
                path->display, pixmap, screenX1, screenY1, width, height);
        }
        if(path->context != NULL) {
            TkPathFree(path->context);
            path->context = NULL;
        }
#ifndef TK_PATH_NO_DOUBLE_BUFFERING
        /*
         * Copy from the temporary pixmap to the screen, then free up the
         * temporary pixmap.
         */

        XCopyArea(Tk_Display(*(path->win)), pixmap, Tk_WindowId(*(path->win)),
            path->pixmapGC,
            screenX1 - path->drawableXOrigin,
            screenY1 - path->drawableYOrigin,
            (unsigned int)width, (unsigned int)height,
            screenX1 - path->xOrigin, screenY1 - path->yOrigin);
        Tk_FreePixmap(Tk_Display(*(path->win)), pixmap);
#else
        TkpClipDrawableToRect(Tk_Display(*(path->win)), pixmap, 0, 0, -1, -1);
#endif /* TK_PATH_NO_DOUBLE_BUFFERING */
    }

    /*
     * Draw the window borders, if needed.
     */

  borders:
    if(path->flags & REDRAW_BORDERS) {
        path->flags &= ~REDRAW_BORDERS;
        if(path->borderWidth > 0) {
            Tk_Draw3DRectangle(*(path->win), Tk_WindowId(*(path->win)),
                path->bgBorder, path->highlightWidth,
                path->highlightWidth,
                Tk_Width(*(path->win)) - 2 * path->highlightWidth,
                Tk_Height(*(path->win)) - 2 * path->highlightWidth,
                path->borderWidth, path->relief);
        }
        if(path->highlightWidth != 0) {
GC  fgGC, bgGC;

            bgGC = Tk_GCForColor(path->highlightBgColorPtr,
                Tk_WindowId(*(path->win)));
            if(path->textInfo.gotFocus) {
                fgGC = Tk_GCForColor(path->highlightColorPtr,
                    Tk_WindowId(*(path->win)));
                TkpDrawHighlightBorder(*(path->win), fgGC, bgGC,
                    path->highlightWidth, Tk_WindowId(*(path->win)));
            } else {
                TkpDrawHighlightBorder(*(path->win), bgGC, bgGC,
                    path->highlightWidth, Tk_WindowId(*(path->win)));
            }
        }
    }

  done:
    path->flags &= ~(REDRAW_PENDING | BBOX_NOT_EMPTY);
    path->redrawX1 = path->redrawX2 = 0;
    path->redrawY1 = path->redrawY2 = 0;
    if(path->flags & UPDATE_SCROLLBARS) {
        CanvasUpdateScrollbars(path);
    }
}

/*
 * CanvasEventProc --
 *
 *    This function is invoked by the Tk dispatcher for various events on
 *    canvases.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    When the window gets deleted, internal structures get cleaned up.
 *    When it gets exposed, it is redisplayed.
 */
static void
CanvasEventProc(
    ClientData clientData,     /* Information about window. */
    XEvent * eventPtr /* Information about event. */)
{             
    TkPathCanvas *path = (TkPathCanvas *) clientData;
    if(eventPtr->type == DestroyNotify || path->win == NULL
        || *(path->win) == NULL)
        return;

    if(eventPtr->type == Expose) {
int x, y;

        x = eventPtr->xexpose.x + path->xOrigin;
        y = eventPtr->xexpose.y + path->yOrigin;
        Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path, x, y,
            x + eventPtr->xexpose.width, y + eventPtr->xexpose.height);
        if((eventPtr->xexpose.x < path->inset)
            || (eventPtr->xexpose.y < path->inset)
            || ((eventPtr->xexpose.x + eventPtr->xexpose.width)
                > (Tk_Width(*(path->win)) - path->inset))
            || ((eventPtr->xexpose.y + eventPtr->xexpose.height)
                > (Tk_Height(*(path->win)) - path->inset))) {
            path->flags |= REDRAW_BORDERS;
        }
    } else if(eventPtr->type == ConfigureNotify) {
        path->flags |= UPDATE_SCROLLBARS;

        /*
         * The call below is needed in order to recenter the canvas if it's
         * confined and its scroll region is smaller than the window.
         */

        CanvasSetOrigin(path, path->xOrigin, path->yOrigin);
        Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path, path->xOrigin,
            path->yOrigin,
            path->xOrigin + Tk_Width(*(path->win)),
            path->yOrigin + Tk_Height(*(path->win)));
        path->flags |= REDRAW_BORDERS;
    } else if(eventPtr->type == FocusIn) {
        if(eventPtr->xfocus.detail != NotifyInferior) {
            CanvasFocusProc(path, 1);
        }
    } else if(eventPtr->type == FocusOut) {
        if(eventPtr->xfocus.detail != NotifyInferior) {
            CanvasFocusProc(path, 0);
        }
    } else if(eventPtr->type == UnmapNotify) {
Tk_PathItem *itemPtr;

        /*
         * Special hack: if the canvas is unmapped, then must notify all items
         * with "alwaysRedraw" set, so that they know that they are no longer
         * displayed.
         */

        for(itemPtr = path->rootItemPtr; itemPtr != NULL;
            itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
            if(itemPtr->typePtr->alwaysRedraw & 1) {
                (*itemPtr->typePtr->displayProc) ((Tk_PathCanvas) path,
                    itemPtr, path->display, None, 0, 0, 0, 0);
            }
        }
    }
}

/*
 * Tk_PathCanvasEventuallyRedraw --
 *
 *    Arrange for part or all of a canvas widget to redrawn at some
 *    convenient time in the future.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The screen will eventually be refreshed.
 */
void
Tk_PathCanvasEventuallyRedraw(
    Tk_PathCanvas canvas,      /* Information about widget. */
    int x1,
    int y1,                    /* Upper left corner of area to redraw. Pixels
                                * on edge are redrawn. */
    int x2,
    int y2)
{              /* Lower right corner of area to redraw.
                * Pixels on edge are not redrawn. */
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    if(path->win == NULL || *(path->win) == NULL || !Tk_IsMapped(*(path->win)))
        return;

    if((x1 >= x2) || (y1 >= y2) ||
        (x2 < path->xOrigin) || (y2 < path->yOrigin) ||
        (x1 >= path->xOrigin + Tk_Width(*(path->win))) ||
        (y1 >= path->yOrigin + Tk_Height(*(path->win)))) {
        return;
    }
    if(path->flags & BBOX_NOT_EMPTY) {
        if(x1 <= path->redrawX1) {
            path->redrawX1 = x1;
        }
        if(y1 <= path->redrawY1) {
            path->redrawY1 = y1;
        }
        if(x2 >= path->redrawX2) {
            path->redrawX2 = x2;
        }
        if(y2 >= path->redrawY2) {
            path->redrawY2 = y2;
        }
    } else {
        path->redrawX1 = x1;
        path->redrawY1 = y1;
        path->redrawX2 = x2;
        path->redrawY2 = y2;
        path->flags |= BBOX_NOT_EMPTY;
    }
    if(!(path->flags & REDRAW_PENDING)) {
        Tcl_DoWhenIdle(PathDisplay, (ClientData) path);
        path->flags |= REDRAW_PENDING;
    }
}

/*
 * EventuallyRedrawItem --
 *
 *    Arrange for part or all of a canvas widget to redrawn at some
 *    convenient time in the future.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The screen will eventually be refreshed.
 */
static void
EventuallyRedrawItem(
    Tk_PathCanvas canvas,      /* Information about widget. */
    Tk_PathItem * itemPtr)
{              /* Item to be redrawn. */
TkPathCanvas *path = (TkPathCanvas *) canvas;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    if((itemPtr->x1 >= itemPtr->x2) || (itemPtr->y1 >= itemPtr->y2) ||
        (itemPtr->x2 < path->xOrigin) ||
        (itemPtr->y2 < path->yOrigin) ||
        (itemPtr->x1 >= path->xOrigin + Tk_Width(*(path->win))) ||
        (itemPtr->y1 >= path->yOrigin + Tk_Height(*(path->win)))) {
        if(!(itemPtr->typePtr->alwaysRedraw & 1)) {
            return;
        }
    }
    if(!(itemPtr->redraw_flags & FORCE_REDRAW)) {
        if(path->flags & BBOX_NOT_EMPTY) {
            if(itemPtr->x1 <= path->redrawX1) {
                path->redrawX1 = itemPtr->x1;
            }
            if(itemPtr->y1 <= path->redrawY1) {
                path->redrawY1 = itemPtr->y1;
            }
            if(itemPtr->x2 >= path->redrawX2) {
                path->redrawX2 = itemPtr->x2;
            }
            if(itemPtr->y2 >= path->redrawY2) {
                path->redrawY2 = itemPtr->y2;
            }
        } else {
            path->redrawX1 = itemPtr->x1;
            path->redrawY1 = itemPtr->y1;
            path->redrawX2 = itemPtr->x2;
            path->redrawY2 = itemPtr->y2;
            path->flags |= BBOX_NOT_EMPTY;
        }
        itemPtr->redraw_flags |= FORCE_REDRAW;
    }
    SetAncestorsDirtyBbox(itemPtr);
    if(!(path->flags & REDRAW_PENDING)) {
        Tcl_DoWhenIdle(PathDisplay, (ClientData) path);
        path->flags |= REDRAW_PENDING;
    }
}

/*
 * EventuallyRedrawItemAndChildren --
 *
 *    Arrange for part or all of a canvas widget to redrawn at some
 *    convenient time in the future. This version traverses over all
 *    child items, too.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The screen will eventually be refreshed.
 */
static void
EventuallyRedrawItemAndChildren(
    Tk_PathCanvas canvas,      /* Information about widget. */
    Tk_PathItem * itemPtr)
{              /* Item to be redrawn. */
Tk_PathItem *childPtr = itemPtr->firstChildPtr;

    while(childPtr != NULL) {
        EventuallyRedrawItemAndChildren(canvas, childPtr);
        childPtr = childPtr->nextPtr;
    }
    EventuallyRedrawItem(canvas, itemPtr);
}

/*
 * TkPathCanvasSetParent --
 *
 *    Appends an item as the last sibling to a parent item.
 *    May unlink any existing linkage.
 *
 * Results:
 *    Standard tcl result.
 *
 * Side effects:
 *    Links in item in display list.
 */
void
TkPathCanvasSetParent(
    Tk_PathItem * parentPtr,
    Tk_PathItem * itemPtr)
{

    /*
     * Unlink any present parent, then link in again.
     */
    if(itemPtr->parentPtr != NULL) {
        TkPathCanvasItemDetach(itemPtr);
    }
    ItemAddToParent(parentPtr, itemPtr);

    /*
     * We may have configured -parent with a tag but need to return an id.
     */
    itemPtr->parentObj = UnshareObj(itemPtr->parentObj);
    Tcl_SetIntObj(itemPtr->parentObj, parentPtr->id);
}

/*
* TkPathCanvasSetParentToRoot --
*
*
* Results:
*    Standard tcl result.
*
* Side effects:
*/
void
TkPathCanvasSetParentToRoot(
    Tk_PathItem * itemPtr)
{
Tk_PathItemEx *itemExPtr = (Tk_PathItemEx *) itemPtr;
Tk_PathCanvas canvas = itemExPtr->canvas;
TkPathCanvas *path = (TkPathCanvas *) canvas;
    TkPathCanvasSetParent(path->rootItemPtr, itemPtr);
}

/*
 * TkPathCanvasFindGroup --
 *
 *    Searches for the first group item described by the tagOrId parentObj.
 *
 * Results:
 *    Standard tcl result. parentPtrPtr filled in on success.
 *
 * Side effects:
 *    Leaves any error result in interp.
 */
int
TkPathCanvasFindGroup(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tcl_Obj * parentObj,
    Tk_PathItem ** parentPtrPtr)
{
TkPathCanvas *path = (TkPathCanvas *) canvas;
Tk_PathItem *parentPtr;
int result = TCL_OK;
TagSearch *searchPtr = NULL;   /* Allocated by first TagSearchScan, freed by
                                * TagSearchDestroy */

    if(parentObj != NULL) {
        if((result = TagSearchScan(path, parentObj, &searchPtr)) != TCL_OK) {
            return TCL_ERROR;
        }
        parentPtr = TagSearchFirst(searchPtr);
        if(parentPtr == NULL) {
            Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
                "tag \"", Tcl_GetString(parentObj),
                "\" doesn't match any items", NULL);
            result = TCL_ERROR;
        } else if(strcmp(parentPtr->typePtr->name, "group") != 0) {
            Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
                "tag \"", Tcl_GetString(parentObj),
                "\" is not a group item", NULL);
            result = TCL_ERROR;
        } else {
            *parentPtrPtr = parentPtr;
        }
        TagSearchDestroy(searchPtr);
    }
    return result;
}

/*
* TkPathCanvasTranslateGroup --
*
*
* Results:
*
* Side effects:
*/
void
TkPathCanvasTranslateGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    Tk_PathItem *walkPtr;

    /* Round the deltas to the nearest integer to avoid round-off errors */
    deltaX = (double)((int)(deltaX + (deltaX > 0 ? 0.5 : -0.5)));
    deltaY = (double)((int)(deltaY + (deltaY > 0 ? 0.5 : -0.5)));

    /*
     * Invoke all its childs translateProc. Any child groups will call this
     * function recursively.
     */
    for(walkPtr = itemPtr->firstChildPtr; walkPtr != NULL;
        walkPtr = walkPtr->nextPtr) {
        EventuallyRedrawItem(canvas, walkPtr);
        (void)(*walkPtr->typePtr->translateProc) (canvas, walkPtr, compensate,
            deltaX, deltaY);
        EventuallyRedrawItem(canvas, walkPtr);
        path->flags |= REPICK_NEEDED;
    }
}

/*
 * TkPathGroupItemConfigured --
 *
 *    Schedules all children of a group for redisplay in a recursive way.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    A number of items scheduled for redisplay.
 */
void
TkPathGroupItemConfigured(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    Tk_PathItem *walkPtr;

    for(walkPtr = itemPtr->firstChildPtr; walkPtr != NULL;
        walkPtr = walkPtr->nextPtr) {
        EventuallyRedrawItem(canvas, walkPtr);
        if(walkPtr->typePtr->bboxProc != NULL) {
            (*walkPtr->typePtr->bboxProc) (canvas, walkPtr, mask);
            /*
             * Only if the item responds to the bboxProc we need to redraw it.
             */
            EventuallyRedrawItem(canvas, walkPtr);
        }
        if(walkPtr->typePtr == &tkPathTypeGroup) {
            /*
             * Call ourself recursively for each group.
             * @@@ An alternative would be to have this call in the group's
             *     own bbox proc.
             */
            TkPathGroupItemConfigured(canvas, walkPtr, mask);
        }
    }
}

/*
* TkPathCanvasScaleGroup --
*
*
* Results:
*
* Side effects:
*/
void
TkPathCanvasScaleGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    Tk_PathItem *walkPtr;

    /*
     * Invoke all its childs scaleProc. Any child groups will call this
     * function recursively.
     */
    for(walkPtr = itemPtr->firstChildPtr; walkPtr != NULL;
        walkPtr = walkPtr->nextPtr) {
        EventuallyRedrawItem(canvas, walkPtr);
        (void)(*walkPtr->typePtr->scaleProc) (canvas, walkPtr,
            compensate, originX, originY, scaleX, scaleY);
        EventuallyRedrawItem(canvas, walkPtr);
        path->flags |= REPICK_NEEDED;
    }
}

/*
 * SetAncestorsDirtyBbox --
 *
 *    Used by items when they need a redisplay for some reason
 *    so that its ancestor groups know that they need to compute
 *    a new bbox when requested.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Groups get their dirty bbox flag set.
 */
static void
SetAncestorsDirtyBbox(
    Tk_PathItem * itemPtr)
{
Tk_PathItem *walkPtr;

    walkPtr = itemPtr->parentPtr;
    while(walkPtr != NULL) {
        TkPathCanvasSetGroupDirtyBbox(walkPtr);
        walkPtr = walkPtr->parentPtr;
    }
}

/*
* TkPathCanvasGroupBbox --
*
*
* Results:
*
* Side effects:
*/
void
TkPathCanvasGroupBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int *x1Ptr,
    int *y1Ptr,
    int *x2Ptr,
    int *y2Ptr)
{
    int gotAny = 0;
    Tk_PathItem *walkPtr;
    int x1 = -1, y1 = -1, x2 = -1, y2 = -1;

    for(walkPtr = itemPtr->firstChildPtr; walkPtr != NULL;
        walkPtr = walkPtr->nextPtr) {

        /*
         * Make sure sub groups have its bbox updated.
         * We may be called recursively.
         */
        if(walkPtr->firstChildPtr != NULL) {
            TkPathCanvasUpdateGroupBbox(canvas, walkPtr);
        }
        if((walkPtr->x1 >= walkPtr->x2)
            || (walkPtr->y1 >= walkPtr->y2)) {
            continue;
        }
        if(!gotAny) {
            x1 = walkPtr->x1;
            y1 = walkPtr->y1;
            x2 = walkPtr->x2;
            y2 = walkPtr->y2;
            gotAny = 1;
        } else {
            if(walkPtr->x1 < x1) {
                x1 = walkPtr->x1;
            }
            if(walkPtr->y1 < y1) {
                y1 = walkPtr->y1;
            }
            if(walkPtr->x2 > x2) {
                x2 = walkPtr->x2;
            }
            if(walkPtr->y2 > y2) {
                y2 = walkPtr->y2;
            }
        }
    }
    *x1Ptr = x1, *y1Ptr = y1, *x2Ptr = x2, *y2Ptr = y2;
}

/*
 * ItemCreate --
 *
 *    Creates a new item, configures it, and add it to the display tree.
 *    It remains for the calling code to call EventuallyRedrawItem
 *    and a few more canvas admin stuff.
 *    The item's creatProc may leave any error message in interp.
 *
 * Results:
 *    Standard Tcl result and a new item pointer in itemPtrPtr.
 *
 * Side effects:
 *    Item allocated, configured, and linked into display list.
 */
static int
ItemCreate(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    Tk_PathItemType * typePtr,
    int isRoot,
    Tk_PathItem ** itemPtrPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_PathItem *itemPtr;
    Tcl_HashEntry *entryPtr;
    int isNew = 0;
    int result;

    itemPtr = (Tk_PathItem *) ckalloc((unsigned)typePtr->itemSize);
    if(isRoot) {
        itemPtr->id = 0;
    } else {
        itemPtr->id = path->nextId;
        path->nextId++;
    }
    itemPtr->typePtr = typePtr;
    itemPtr->state = TK_PATHSTATE_NULL;
    itemPtr->redraw_flags = 0;
    itemPtr->optionTable = NULL;
    itemPtr->pathTagsPtr = NULL;
    itemPtr->nextPtr = NULL;
    itemPtr->prevPtr = NULL;
    itemPtr->firstChildPtr = NULL;
    itemPtr->lastChildPtr = NULL;

    /*
     * This is just to be able to detect if createProc processes
     * any -parent option.
     * NB: It is absolutely vital to set parentObj to NULL
     *     else option free bails.
     */
    itemPtr->parentPtr = NULL;
    itemPtr->parentObj = NULL;

    result = (*typePtr->createProc) (interp, (Tk_PathCanvas) path,
        itemPtr, objc, objv);
    if(result != TCL_OK) {
        ckfree((char *)itemPtr);
        return TCL_ERROR;
    }
    entryPtr = Tcl_CreateHashEntry(&path->idTable,
        (char *)INT2PTR(itemPtr->id), &isNew);
    Tcl_SetHashValue(entryPtr, itemPtr);

    /*
     * If item's createProc didn't put it in the display list we do.
     * Typically done only for the tk::canvas items which don't have
     * a -parent option.
     */
    if(!isRoot && (itemPtr->parentPtr == NULL)) {
        ItemAddToParent(path->rootItemPtr, itemPtr);
    }
    itemPtr->redraw_flags |= FORCE_REDRAW;
    *itemPtrPtr = itemPtr;

    return TCL_OK;
}

/*
* UnshareObj --
*
*
* Results:
*
* Side effects:
*/
static Tcl_Obj *
UnshareObj(
    Tcl_Obj * objPtr)
{
    if(Tcl_IsShared(objPtr)) {
Tcl_Obj *newObj = Tcl_DuplicateObj(objPtr);
        Tcl_DecrRefCount(objPtr);
        Tcl_IncrRefCount(newObj);
        return newObj;
    }
    return objPtr;
}

/*
 * TkPathCanvasItemIteratorNext --
 *
 *    Convinience function to obtain the next item in the item tree.
 *
 * Results:
 *    Tk_PathItem pointer.
 *
 * Side effects:
 *    None.
 */
Tk_PathItem *
TkPathCanvasItemIteratorNext(
    Tk_PathItem * itemPtr)
{
    if(itemPtr->firstChildPtr != NULL) {
        return itemPtr->firstChildPtr;
    }
    while(itemPtr->nextPtr == NULL) {
        itemPtr = itemPtr->parentPtr;
        if(itemPtr == NULL) {   /* root item */
            return NULL;
        }
    }
    return itemPtr->nextPtr;
}

/*
* TkPathCanvasItemIteratorPrev --
*
*
* Results:
*
* Side effects:
*/
Tk_PathItem *
TkPathCanvasItemIteratorPrev(
    Tk_PathItem * itemPtr)
{
Tk_PathItem *walkPtr;

    if(itemPtr->parentPtr == NULL) {    /* root item */
        return NULL;
    } else {
        walkPtr = itemPtr->parentPtr;
        if(itemPtr->prevPtr != NULL) {
            walkPtr = itemPtr->prevPtr;
            while(walkPtr != NULL && walkPtr->lastChildPtr != NULL) {
                walkPtr = walkPtr->lastChildPtr;
            }
        }
        return walkPtr;
    }
}

/*
* ItemGetNumTags --
*
*
* Results:
*
* Side effects:
*/
static int
ItemGetNumTags(
    Tk_PathItem * itemPtr)
{
    if(itemPtr->pathTagsPtr != NULL) {
        return itemPtr->pathTagsPtr->numTags;
    } else {
        return 0;
    }
}

/*
 * TkPathCanvasItemDetach --
 *
 *    Splice out (unlink) an item from the display list.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Item will be unlinked from the display list.
 */
void
TkPathCanvasItemDetach(
    Tk_PathItem * itemPtr)
{
Tk_PathItem *parentPtr;

    if(itemPtr->prevPtr != NULL) {
        itemPtr->prevPtr->nextPtr = itemPtr->nextPtr;
    }
    if(itemPtr->nextPtr != NULL) {
        itemPtr->nextPtr->prevPtr = itemPtr->prevPtr;
    }
    parentPtr = itemPtr->parentPtr;
    if((parentPtr != NULL) && (parentPtr->firstChildPtr == itemPtr)) {
        parentPtr->firstChildPtr = itemPtr->nextPtr;
        if(parentPtr->firstChildPtr == NULL) {
            parentPtr->lastChildPtr = NULL;
        }
    }
    if((parentPtr != NULL) && (parentPtr->lastChildPtr == itemPtr)) {
        parentPtr->lastChildPtr = itemPtr->prevPtr;
    }

    /*
     * This signals an orfan item.
     */
    itemPtr->nextPtr = itemPtr->prevPtr = itemPtr->parentPtr = NULL;
}

/*
 * ItemAddToParent --
 *
 *    Appends an item as the last sibling to a parent item.
 *    It doesn't do any unlinking from a previous tree position.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Display list updated.
 */
static void
ItemAddToParent(
    Tk_PathItem * parentPtr,
    Tk_PathItem * itemPtr)
{
    itemPtr->nextPtr = NULL;
    itemPtr->prevPtr = parentPtr->lastChildPtr;
    if(parentPtr->lastChildPtr != NULL) {
        parentPtr->lastChildPtr->nextPtr = itemPtr;
    } else {
        parentPtr->firstChildPtr = itemPtr;
    }
    parentPtr->lastChildPtr = itemPtr;
    itemPtr->parentPtr = parentPtr;
}

/*
 * ItemDelete --
 *
 *    Recursively frees all resources associated with an Item and its
 *    descendants and removes it from display list.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Items are removed from their parent and freed.
 */
static void
ItemDelete(
    TkPathCanvas * path,
    Tk_PathItem * itemPtr)
{
Tcl_HashEntry *entryPtr;

    /*
     * Remove any children by recursively calling us.
     * NB: This is very tricky code! Children updates
     *     the itemPtr->firstChildPtr here via calls
     *     to TkPathCanvasItemDetach.
     */
    while(itemPtr->firstChildPtr != NULL) {
        ItemDelete(path, itemPtr->firstChildPtr);
    }

    EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
    if(path->bindingTable != NULL) {
        Tk_DeleteAllBindings(path->bindingTable, (ClientData) itemPtr);
    }

    /*
     * The item type deleteProc is responsible for calling
     * Tk_FreeConfigOptions which will implicitly also clean up
     * the Tk_PathTags via its custom free proc.
     */
    (*itemPtr->typePtr->deleteProc) ((Tk_PathCanvas) path, itemPtr,
        path->display);

    entryPtr = Tcl_FindHashEntry(&path->idTable, (char *)INT2PTR(itemPtr->id));
    Tcl_DeleteHashEntry(entryPtr);
    TkPathCanvasItemDetach(itemPtr);

    if(itemPtr == path->currentItemPtr) {
        path->currentItemPtr = NULL;
        path->flags |= REPICK_NEEDED;
    }
    if(itemPtr == path->newCurrentPtr) {
        path->newCurrentPtr = NULL;
        path->flags |= REPICK_NEEDED;
    }
    if(itemPtr == path->textInfo.focusItemPtr) {
        path->textInfo.focusItemPtr = NULL;
    }
    if(itemPtr == path->textInfo.selItemPtr) {
        path->textInfo.selItemPtr = NULL;
    }
    if((itemPtr == path->hotPtr)
        || (itemPtr == path->hotPrevPtr)) {
        path->hotPtr = NULL;
    }
    ckfree((char *)itemPtr);
}

/*
* DebugGetItemInfo --
*
*
* Results:
*
* Side effects:
*/
static void
DebugGetItemInfo(
    Tk_PathItem * itemPtr,
    char *s)
{
    Tk_PathItem *p = itemPtr;
    char tmp[256];

    sprintf(tmp, " parentPtr->id=%d\t", (p->parentPtr ? p->parentPtr->id : -1));
    strcat(s, tmp);
    sprintf(tmp, " prevPtr->id=%d\t", (p->prevPtr ? p->prevPtr->id : -1));
    strcat(s, tmp);
    sprintf(tmp, " nextPtr->id=%d\t", (p->nextPtr ? p->nextPtr->id : -1));
    strcat(s, tmp);
    sprintf(tmp, " firstChildPtr->id=%d\t",
        (p->firstChildPtr ? p->firstChildPtr->id : -1));
    strcat(s, tmp);
    sprintf(tmp, " lastChildPtr->id=%d\t",
        (p->lastChildPtr ? p->lastChildPtr->id : -1));
    strcat(s, tmp);
}

/*
 * GetStaticUids --
 *
 *    This function is invoked to return a structure filled with the Uids
 *    used when doing tag searching. If it was never before called in the
 *    current thread, it initializes the structure for that thread (uids are
 *    only ever local to one thread [Bug 1114977]).
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 */
static SearchUids *
GetStaticUids(
    void)
{
    SearchUids *searchUids = (SearchUids *)
        Tcl_GetThreadData(&dataKey, sizeof(SearchUids));

    if(searchUids->allUid == NULL) {
        searchUids->allUid = Tk_GetUid("all");
        searchUids->currentUid = Tk_GetUid("current");
        searchUids->rootUid = Tk_GetUid("root");
        searchUids->andUid = Tk_GetUid("&&");
        searchUids->orUid = Tk_GetUid("||");
        searchUids->xorUid = Tk_GetUid("^");
        searchUids->parenUid = Tk_GetUid("(");
        searchUids->endparenUid = Tk_GetUid(")");
        searchUids->negparenUid = Tk_GetUid("!(");
        searchUids->tagvalUid = Tk_GetUid("!!");
        searchUids->negtagvalUid = Tk_GetUid("!");
    }
    return searchUids;
}

/*
 * TagSearchExprInit --
 *
 *    This function allocates and initializes one TagSearchExpr struct.
 *
 * Results:
 *
 * Side effects:
 */
static void
TagSearchExprInit(
    TkPathTagSearchExpr ** exprPtrPtr)
{
TkPathTagSearchExpr *expr = *exprPtrPtr;

    if(!expr) {
        expr = (TkPathTagSearchExpr *) ckalloc(sizeof(TkPathTagSearchExpr));
        expr->allocated = 0;
        expr->uids = NULL;
        expr->next = NULL;
    }
    expr->uid = NULL;
    expr->index = 0;
    expr->length = 0;
    *exprPtrPtr = expr;
}

/*
 * TagSearchExprDestroy --
 *
 *    This function destroys one TkPathTagSearchExpr structure.
 *
 * Results:
 *
 * Side effects:
 */
static void
TagSearchExprDestroy(
    TkPathTagSearchExpr * expr)
{
    if(expr) {
        if(expr->uids) {
            ckfree((char *)expr->uids);
        }
        ckfree((char *)expr);
    }
}

/*
 * TagSearchScan --
 *
 *    This function is called to initiate an enumeration of all items in a
 *    given canvas that contain a tag that matches the tagOrId expression.
 *
 * Results:
 *    The return value indicates if the tagOrId expression was successfully
 *    scanned (syntax). The information at *searchPtr is initialized such
 *    that a call to TagSearchFirst, followed by successive calls to
 *    TagSearchNext will return items that match tag.
 *
 * Side effects:
 *    SearchPtr is linked into a list of searches in progress on path,
 *    so that elements can safely be deleted while the search is in
 *    progress.
 */
static int
TagSearchScan(
    TkPathCanvas * path,       /* Canvas whose items are to be searched. */
    Tcl_Obj * tagObj,          /* Object giving tag value. */
    TagSearch ** searchPtrPtr)
{              /* Record describing tag search; will be
                * initialized here. */
char *tag = Tcl_GetString(tagObj);
int i;
TagSearch *searchPtr;

    /*
     * Initialize the search.
     */

    if(*searchPtrPtr) {
        searchPtr = *searchPtrPtr;
    } else {
        /*
         * Allocate primary search struct on first call.
         */

        *searchPtrPtr = searchPtr = (TagSearch *) ckalloc(sizeof(TagSearch));
        searchPtr->expr = NULL;

        /*
         * Allocate buffer for rewritten tags (after de-escaping).
         */

        searchPtr->rewritebufferAllocated = 100;
        searchPtr->rewritebuffer =
            (char *)ckalloc(searchPtr->rewritebufferAllocated);
    }
    TagSearchExprInit(&(searchPtr->expr));

    /*
     * How long is the tagOrId?
     */

    searchPtr->stringLength = (int)strlen(tag);

    /*
     * Make sure there is enough buffer to hold rewritten tags.
     */

    if((unsigned int)searchPtr->stringLength >=
        searchPtr->rewritebufferAllocated) {
        searchPtr->rewritebufferAllocated = searchPtr->stringLength + 100;
        searchPtr->rewritebuffer = (char *)
            ckrealloc(searchPtr->rewritebuffer,
            searchPtr->rewritebufferAllocated);
    }

    /*
     * Initialize search.
     */

    searchPtr->path = path;
    searchPtr->searchOver = 0;
    searchPtr->type = SEARCH_TYPE_EMPTY;

    /*
     * Find the first matching item in one of several ways. If the tag is a
     * number then it selects the single item with the matching identifier.
     * In this case see if the item being requested is the hot item, in which
     * case the search can be skipped.
     */

    if(searchPtr->stringLength && isdigit(UCHAR(*tag))) {
char *end;

        searchPtr->id = strtoul(tag, &end, 0);
        if(*end == 0) {
            searchPtr->type = SEARCH_TYPE_ID;
            return TCL_OK;
        }
    }

    /*
     * For all other tags and tag expressions convert to a UID. This UID is
     * kept forever, but this should be thought of as a cache rather than as a
     * memory leak.
     */
    searchPtr->expr->uid = Tk_GetUid(tag);

    /*
     * Short circuit impossible searches for null tags.
     */

    if(searchPtr->stringLength == 0) {
        return TCL_OK;
    }

    /*
     * Pre-scan tag for at least one unquoted "&&" "||" "^" "!"
     *   if not found then use string as simple tag
     */

    for(i = 0; i < searchPtr->stringLength; i++) {
        if(tag[i] == '"') {
            i++;
            for(; i < searchPtr->stringLength; i++) {
                if(tag[i] == '\\') {
                    i++;
                    continue;
                }
                if(tag[i] == '"') {
                    break;
                }
            }
        } else if((tag[i] == '&' && tag[i + 1] == '&')
            || (tag[i] == '|' && tag[i + 1] == '|')
            || (tag[i] == '^')
            || (tag[i] == '!')) {
            searchPtr->type = SEARCH_TYPE_EXPR;
            break;
        }
    }

    searchPtr->string = tag;
    searchPtr->stringIndex = 0;
    if(searchPtr->type == SEARCH_TYPE_EXPR) {
        /*
         * An operator was found in the prescan, so now compile the tag
         * expression into array of Tk_Uid flagging any syntax errors found.
         */

        if(TagSearchScanExpr(path->interp, searchPtr,
                searchPtr->expr) != TCL_OK) {
            /*
             * Syntax error in tag expression. The result message was set by
             * TagSearchScanExpr.
             */

            return TCL_ERROR;
        }
        searchPtr->expr->length = searchPtr->expr->index;
    } else if(searchPtr->expr->uid == GetStaticUids()->allUid) {
        /*
         * All items match.
         */

        searchPtr->type = SEARCH_TYPE_ALL;
    } else if(searchPtr->expr->uid == GetStaticUids()->rootUid) {
        searchPtr->type = SEARCH_TYPE_ROOT;
    } else {
        /*
         * Optimized single-tag search
         */

        searchPtr->type = SEARCH_TYPE_TAG;
    }
    return TCL_OK;
}

/*
 * TagSearchDestroy --
 *
 *    This function destroys any dynamic structures that may have been
 *    allocated by TagSearchScan.
 *
 * Results:
 *    None
 *
 * Side effects:
 *    Deallocates memory.
 */
static void
TagSearchDestroy(
    TagSearch * searchPtr)
{              /* Record describing tag search */
    if(searchPtr) {
        TagSearchExprDestroy(searchPtr->expr);
        ckfree((char *)searchPtr->rewritebuffer);
        ckfree((char *)searchPtr);
    }
}

/*
 * TagSearchScanExpr --
 *
 *    This recursive function is called to scan a tag expression and compile
 *    it into an array of Tk_Uids.
 *
 * Results:
 *    The return value indicates if the tagOrId expression was successfully
 *    scanned (syntax). The information at *searchPtr is initialized such
 *    that a call to TagSearchFirst, followed by successive calls to
 *    TagSearchNext will return items that match tag.
 *
 * Side effects:
 */
static int
TagSearchScanExpr(
    Tcl_Interp * interp,       /* Current interpreter. */
    TagSearch * searchPtr,     /* Search data */
    TkPathTagSearchExpr * expr /* compiled expression result */)
{             
    int looking_for_tag;       /* When true, scanner expects next char(s) to
                                * be a tag, else operand expected */
    int found_tag;             /* One or more tags found */
    int found_endquote;        /* For quoted tag string parsing */
    int negate_result;         /* Pending negation of next tag value */
    char *tag;                 /* Tag from tag expression string */
    char c;
    SearchUids *searchUids;    /* Collection of uids for basic search
                                * expression terms. */

    searchUids = GetStaticUids();
    negate_result = 0;
    found_tag = 0;
    looking_for_tag = 1;
    while(searchPtr->stringIndex < searchPtr->stringLength) {
        c = searchPtr->string[searchPtr->stringIndex++];

        /*
         * Need two slots free at this point, not one. [Bug 2931374]
         */

        if(expr->index >= expr->allocated - 1) {
            expr->allocated += 15;
            if(expr->uids) {
                expr->uids = (Tk_Uid *)
                    ckrealloc((char *)(expr->uids),
                    (expr->allocated) * sizeof(Tk_Uid));
            } else {
                expr->uids = (Tk_Uid *)
                    ckalloc((expr->allocated) * sizeof(Tk_Uid));
            }
        }

        if(looking_for_tag) {
            switch (c) {
            case ' ':  /* ignore unquoted whitespace */
            case '\t':
            case '\n':
            case '\r':
                break;

            case '!':  /* negate next tag or subexpr */
                if(looking_for_tag > 1) {
                    Tcl_AppendResult(interp,
                        "Too many '!' in tag search expression", NULL);
                    return TCL_ERROR;
                }
                looking_for_tag++;
                negate_result = 1;
                break;

            case '(':  /* scan (negated) subexpr recursively */
                if(negate_result) {
                    expr->uids[expr->index++] = searchUids->negparenUid;
                    negate_result = 0;
                } else {
                    expr->uids[expr->index++] = searchUids->parenUid;
                }
                if(TagSearchScanExpr(interp, searchPtr, expr) != TCL_OK) {
                    /*
                     * Result string should be already set by nested call to
                     * tag_expr_scan()
                     */

                    return TCL_ERROR;
                }
                looking_for_tag = 0;
                found_tag = 1;
                break;

            case '"':  /* quoted tag string */
                if(negate_result) {
                    expr->uids[expr->index++] = searchUids->negtagvalUid;
                    negate_result = 0;
                } else {
                    expr->uids[expr->index++] = searchUids->tagvalUid;
                }
                tag = searchPtr->rewritebuffer;
                found_endquote = 0;
                while(searchPtr->stringIndex < searchPtr->stringLength) {
                    c = searchPtr->string[searchPtr->stringIndex++];
                    if(c == '\\') {
                        c = searchPtr->string[searchPtr->stringIndex++];
                    }
                    if(c == '"') {
                        found_endquote = 1;
                        break;
                    }
                    *tag++ = c;
                }
                if(!found_endquote) {
                    Tcl_AppendResult(interp,
                        "Missing endquote in tag search expression", NULL);
                    return TCL_ERROR;
                }
                if(!(tag - searchPtr->rewritebuffer)) {
                    Tcl_AppendResult(interp,
                        "Null quoted tag string in tag search expression",
                        NULL);
                    return TCL_ERROR;
                }
                *tag++ = '\0';
                expr->uids[expr->index++] = Tk_GetUid(searchPtr->rewritebuffer);
                looking_for_tag = 0;
                found_tag = 1;
                break;

            case '&':  /* illegal chars when looking for tag */
            case '|':
            case '^':
            case ')':
                Tcl_AppendResult(interp,
                    "Unexpected operator in tag search expression", NULL);
                return TCL_ERROR;

            default:   /* unquoted tag string */
                if(negate_result) {
                    expr->uids[expr->index++] = searchUids->negtagvalUid;
                    negate_result = 0;
                } else {
                    expr->uids[expr->index++] = searchUids->tagvalUid;
                }
                tag = searchPtr->rewritebuffer;
                *tag++ = c;

                /*
                 * Copy rest of tag, including any embedded whitespace.
                 */

                while(searchPtr->stringIndex < searchPtr->stringLength) {
                    c = searchPtr->string[searchPtr->stringIndex];
                    if(c == '!' || c == '&' || c == '|' || c == '^'
                        || c == '(' || c == ')' || c == '"') {
                        break;
                    }
                    *tag++ = c;
                    searchPtr->stringIndex++;
                }

                /*
                 * Remove trailing whitespace.
                 */

                while(1) {
                    c = *--tag;

                    /*
                     * There must have been one non-whitespace char, so this
                     * will terminate.
                     */

                    if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
                        break;
                    }
                }
                *++tag = '\0';
                expr->uids[expr->index++] = Tk_GetUid(searchPtr->rewritebuffer);
                looking_for_tag = 0;
                found_tag = 1;
            }

        } else {        /* ! looking_for_tag */
            switch (c) {
            case ' ':  /* ignore whitespace */
            case '\t':
            case '\n':
            case '\r':
                break;

            case '&':  /* AND operator */
                c = searchPtr->string[searchPtr->stringIndex++];
                if(c != '&') {
                    Tcl_AppendResult(interp,
                        "Singleton '&' in tag search expression", NULL);
                    return TCL_ERROR;
                }
                expr->uids[expr->index++] = searchUids->andUid;
                looking_for_tag = 1;
                break;

            case '|':  /* OR operator */
                c = searchPtr->string[searchPtr->stringIndex++];
                if(c != '|') {
                    Tcl_AppendResult(interp,
                        "Singleton '|' in tag search expression", NULL);
                    return TCL_ERROR;
                }
                expr->uids[expr->index++] = searchUids->orUid;
                looking_for_tag = 1;
                break;

            case '^':  /* XOR operator */
                expr->uids[expr->index++] = searchUids->xorUid;
                looking_for_tag = 1;
                break;

            case ')':  /* end subexpression */
                expr->uids[expr->index++] = searchUids->endparenUid;
                goto breakwhile;

            default:   /* syntax error */
                Tcl_AppendResult(interp,
                    "Invalid boolean operator in tag search expression", NULL);
                return TCL_ERROR;
            }
        }
    }

  breakwhile:
    if(found_tag && !looking_for_tag) {
        return TCL_OK;
    }
    Tcl_AppendResult(interp, "Missing tag in tag search expression", NULL);
    return TCL_ERROR;
}

/*
 * TagSearchEvalExpr --
 *
 *    This recursive function is called to eval a tag expression.
 *
 * Results:
 *    The return value indicates if the tagOrId expression successfully
 *    matched the tags of the current item.
 *
 * Side effects:
 */
static int
TagSearchEvalExpr(
    TkPathTagSearchExpr * expr, /* Search expression */
    Tk_PathItem * itemPtr       /* Item being test for match */)
{          
    int looking_for_tag;       /* When true, scanner expects next char(s) to
                                * be a tag, else operand expected. */
    int negate_result;         /* Pending negation of next tag value */
    Tk_Uid uid;
    Tk_Uid *tagPtr;
    Tk_PathTags *ptagsPtr;
    int count;
    int result;                /* Value of expr so far */
    int parendepth;
    SearchUids *searchUids;    /* Collection of uids for basic search
                                * expression terms. */

    searchUids = GetStaticUids();
    result = 0; /* just to keep the compiler quiet */

    negate_result = 0;
    looking_for_tag = 1;
    while(expr->index < expr->length) {
        uid = expr->uids[expr->index++];
        if(looking_for_tag) {
            if(uid == searchUids->tagvalUid) {
/*
 *        assert(expr->index < expr->length);
 */
                uid = expr->uids[expr->index++];
                result = 0;

                /*
                 * set result 1 if tag is found in item's tags
                 */

                ptagsPtr = itemPtr->pathTagsPtr;
                if(ptagsPtr != NULL) {
                    for(tagPtr = ptagsPtr->tagPtr, count = ptagsPtr->numTags;
                        count > 0; tagPtr++, count--) {
                        if(*tagPtr == uid) {
                            result = 1;
                            break;
                        }
                    }
                }
            } else if(uid == searchUids->negtagvalUid) {
                negate_result = !negate_result;
/*
 *        assert(expr->index < expr->length);
 */
                uid = expr->uids[expr->index++];
                result = 0;

                /*
                 * set result 1 if tag is found in item's tags
                 */
                ptagsPtr = itemPtr->pathTagsPtr;
                if(ptagsPtr != NULL) {
                    for(tagPtr = ptagsPtr->tagPtr, count = ptagsPtr->numTags;
                        count > 0; tagPtr++, count--) {
                        if(*tagPtr == uid) {
                            result = 1;
                            break;
                        }
                    }
                }
            } else if(uid == searchUids->parenUid) {
                /*
                 * Evaluate subexpressions with recursion
                 */

                result = TagSearchEvalExpr(expr, itemPtr);

            } else if(uid == searchUids->negparenUid) {
                negate_result = !negate_result;

                /*
                 * Evaluate subexpressions with recursion
                 */

                result = TagSearchEvalExpr(expr, itemPtr);
/*
 *        } else {
 *        assert(0);
 */
            }
            if(negate_result) {
                result = !result;
                negate_result = 0;
            }
            looking_for_tag = 0;
        } else {        /* ! looking_for_tag */
            if(((uid == searchUids->andUid) && (!result)) ||
                ((uid == searchUids->orUid) && result)) {
                /*
                 * Short circuit expression evaluation.
                 *
                 * if result before && is 0, or result before || is 1, then
                 * the expression is decided and no further evaluation is
                 * needed.
                 */

                parendepth = 0;
                while(expr->index < expr->length) {
                    uid = expr->uids[expr->index++];
                    if(uid == searchUids->tagvalUid ||
                        uid == searchUids->negtagvalUid) {
                        expr->index++;
                        continue;
                    }
                    if(uid == searchUids->parenUid ||
                        uid == searchUids->negparenUid) {
                        parendepth++;
                        continue;
                    }
                    if(uid == searchUids->endparenUid) {
                        parendepth--;
                        if(parendepth < 0) {
                            break;
                        }
                    }
                }
                return result;

            } else if(uid == searchUids->xorUid) {
                /*
                 * If the previous result was 1 then negate the next result.
                 */

                negate_result = result;

            } else if(uid == searchUids->endparenUid) {
                return result;
/*
 *        } else {
 *        assert(0);
 */
            }
            looking_for_tag = 1;
        }
    }
/*
 *  assert(! looking_for_tag);
 */
    return result;
}

/*
 * TagSearchFirst --
 *
 *    This function is called to get the first item item that matches a
 *    preestablished search predicate that was set by TagSearchScan.
 *
 * Results:
 *    The return value is a pointer to the first item, or NULL if there is
 *    no such item. The information at *searchPtr is updated such that
 *    successive calls to TagSearchNext will return successive items.
 *
 * Side effects:
 *    SearchPtr is linked into a list of searches in progress on path,
 *    so that elements can safely be deleted while the search is in
 *    progress.
 */
static Tk_PathItem *
TagSearchFirst(
    TagSearch * searchPtr /* Record describing tag search */)
{             
    Tk_PathItem *itemPtr, *lastPtr;
    Tk_Uid uid, *tagPtr;
    Tk_PathTags *ptagsPtr;
    int count;

    /*
     * Short circuit impossible searches for null tags.
     */

    if(searchPtr->stringLength == 0) {
        return NULL;
    }

    /*
     * Find the first matching item in one of several ways. If the tag is a
     * number then it selects the single item with the matching identifier.
     * In this case see if the item being requested is the hot item, in which
     * case the search can be skipped.
     */

    if(searchPtr->type == SEARCH_TYPE_ID) {
Tcl_HashEntry *entryPtr;

        itemPtr = searchPtr->path->hotPtr;
        lastPtr = searchPtr->path->hotPrevPtr;
        if((itemPtr == NULL) || (itemPtr->id != searchPtr->id)
            || (lastPtr == NULL)
            || (TkPathCanvasItemIteratorNext(lastPtr) != itemPtr)) {
            entryPtr =
                Tcl_FindHashEntry(&searchPtr->path->idTable,
                (char *)INT2PTR(searchPtr->id));
            if(entryPtr != NULL) {
                itemPtr = (Tk_PathItem *) Tcl_GetHashValue(entryPtr);
                lastPtr = TkPathCanvasItemIteratorPrev(itemPtr);
            } else {
                lastPtr = itemPtr = NULL;
            }
        }
        searchPtr->lastPtr = lastPtr;
        searchPtr->searchOver = 1;
        searchPtr->path->hotPtr = itemPtr;
        searchPtr->path->hotPrevPtr = lastPtr;
        return itemPtr;
    }

    if(searchPtr->type == SEARCH_TYPE_ALL) {
        /*
         * All items match.
         */

        searchPtr->lastPtr = NULL;
        searchPtr->currentPtr = searchPtr->path->rootItemPtr;
        return searchPtr->path->rootItemPtr;
    }
    if(searchPtr->type == SEARCH_TYPE_ROOT) {
        itemPtr = searchPtr->path->rootItemPtr;
        lastPtr = NULL;
        searchPtr->lastPtr = lastPtr;
        searchPtr->searchOver = 1;
        searchPtr->path->hotPtr = itemPtr;
        searchPtr->path->hotPrevPtr = lastPtr;
        return itemPtr;
    }

    if(searchPtr->type == SEARCH_TYPE_TAG) {
        /*
         * Optimized single-tag search
         */

        uid = searchPtr->expr->uid;
        for(lastPtr = NULL, itemPtr = searchPtr->path->rootItemPtr;
            itemPtr != NULL;
            lastPtr = itemPtr, itemPtr =
            TkPathCanvasItemIteratorNext(itemPtr)) {
            ptagsPtr = itemPtr->pathTagsPtr;
            if(ptagsPtr != NULL) {
                for(tagPtr = ptagsPtr->tagPtr, count = ptagsPtr->numTags;
                    count > 0; tagPtr++, count--) {
                    if(*tagPtr == uid) {
                        searchPtr->lastPtr = lastPtr;
                        searchPtr->currentPtr = itemPtr;
                        return itemPtr;
                    }
                }
            }
        }
    } else {

        /*
         * None of the above. Search for an item matching the tag expression.
         */

        for(lastPtr = NULL, itemPtr = searchPtr->path->rootItemPtr;
            itemPtr != NULL;
            lastPtr = itemPtr, itemPtr =
            TkPathCanvasItemIteratorNext(itemPtr)) {
            searchPtr->expr->index = 0;
            if(TagSearchEvalExpr(searchPtr->expr, itemPtr)) {
                searchPtr->lastPtr = lastPtr;
                searchPtr->currentPtr = itemPtr;
                return itemPtr;
            }
        }
    }
    searchPtr->lastPtr = lastPtr;
    searchPtr->searchOver = 1;
    return NULL;
}

/*
 * TagSearchNext --
 *
 *    This function returns successive items that match a given tag; it
 *    should be called only after TagSearchFirst has been used to begin a
 *    search.
 *
 * Results:
 *    The return value is a pointer to the next item that matches the tag
 *    expr specified to TagSearchScan, or NULL if no such item exists.
 *    *SearchPtr is updated so that the next call to this function will
 *    return the next item.
 *
 * Side effects:
 *    None.
 */
static Tk_PathItem *
TagSearchNext(
    TagSearch * searchPtr  /* Record describing search in progress. */)
{            
Tk_PathItem *itemPtr, *lastPtr;
Tk_PathTags *ptagsPtr;
Tk_Uid uid, *tagPtr;
int count;

    /*
     * Find next item in list (this may not actually be a suitable one to
     * return), and return if there are no items left.
     */

    lastPtr = searchPtr->lastPtr;
    if(lastPtr == NULL) {
        itemPtr = searchPtr->path->rootItemPtr;
    } else {
        itemPtr = TkPathCanvasItemIteratorNext(lastPtr);
    }
    if((itemPtr == NULL) || (searchPtr->searchOver)) {
        searchPtr->searchOver = 1;
        return NULL;
    }
    if(itemPtr != searchPtr->currentPtr) {
        /*
         * The structure of the list has changed. Probably the previously-
         * returned item was removed from the list. In this case, don't
         * advance lastPtr; just return its new successor (i.e. do nothing
         * here).
         */
    } else {
        lastPtr = itemPtr;
        itemPtr = TkPathCanvasItemIteratorNext(lastPtr);
    }

    if(searchPtr->type == SEARCH_TYPE_ALL) {
        /*
         * All items match.
         */

        searchPtr->lastPtr = lastPtr;
        searchPtr->currentPtr = itemPtr;
        return itemPtr;
    }

    if(searchPtr->type == SEARCH_TYPE_TAG) {
        /*
         * Optimized single-tag search
         */

        uid = searchPtr->expr->uid;
        for(; itemPtr != NULL;
            lastPtr = itemPtr, itemPtr =
            TkPathCanvasItemIteratorNext(itemPtr)) {
            ptagsPtr = itemPtr->pathTagsPtr;
            if(ptagsPtr != NULL) {
                for(tagPtr = ptagsPtr->tagPtr, count = ptagsPtr->numTags;
                    count > 0; tagPtr++, count--) {
                    if(*tagPtr == uid) {
                        searchPtr->lastPtr = lastPtr;
                        searchPtr->currentPtr = itemPtr;
                        return itemPtr;
                    }
                }
            }
        }
        searchPtr->lastPtr = lastPtr;
        searchPtr->searchOver = 1;
        return NULL;
    }

    /*
     * Else.... evaluate tag expression
     */

    for(; itemPtr != NULL;
        lastPtr = itemPtr, itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
        searchPtr->expr->index = 0;
        if(TagSearchEvalExpr(searchPtr->expr, itemPtr)) {
            searchPtr->lastPtr = lastPtr;
            searchPtr->currentPtr = itemPtr;
            return itemPtr;
        }
    }
    searchPtr->lastPtr = lastPtr;
    searchPtr->searchOver = 1;
    return NULL;
}

/*
 * DoItem --
 *
 *    This is a utility function called by FindItems. It either adds
 *    itemPtr's id to the result forming in interp, or it adds a new tag to
 *    itemPtr, depending on the value of tag.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    If tag is NULL then itemPtr's id is added as a list element to the
 *    interp's result; otherwise tag is added to itemPtr's list of tags.
 */
static void
DoItem(
    Tcl_Interp * interp,       /* Interpreter in which to (possibly) record
                                * item id. */
    Tk_PathItem * itemPtr,     /* Item to (possibly) modify. */
    Tk_Uid tag)
{              /* Tag to add to those already present for
                * item, or NULL. */
Tk_Uid *tagPtr;
Tk_PathTags *ptagsPtr;
int count;

    /*
     * Handle the "add-to-result" case and return, if appropriate.
     */

    if(tag == NULL) {
char msg[TCL_INTEGER_SPACE];

        sprintf(msg, "%d", itemPtr->id);
        Tcl_AppendElement(interp, msg);
        return;
    }

    /*
     * Do not add if already there.
     */

    ptagsPtr = itemPtr->pathTagsPtr;
    if(ptagsPtr != NULL) {
        for(tagPtr = ptagsPtr->tagPtr, count = ptagsPtr->numTags;
            count > 0; tagPtr++, count--) {
            if(tag == *tagPtr) {
                return;
            }
        }
    }

    /*
     * Grow the tag space if there's no more room left in the current block.
     */

    if(itemPtr->pathTagsPtr == NULL) {
        ptagsPtr = TkPathAllocTagsFromObj(NULL, NULL);
        itemPtr->pathTagsPtr = ptagsPtr;
        tagPtr = ptagsPtr->tagPtr;
    } else {
        ptagsPtr = itemPtr->pathTagsPtr;
        if(ptagsPtr->tagSpace == ptagsPtr->numTags) {
Tk_Uid *newTagPtr;

            ptagsPtr->tagSpace += 5;
            newTagPtr = (Tk_Uid *)
                ckalloc((unsigned)(ptagsPtr->tagSpace * sizeof(Tk_Uid)));
            memcpy((void *)newTagPtr, ptagsPtr->tagPtr,
                ptagsPtr->numTags * sizeof(Tk_Uid));
            ckfree((char *)ptagsPtr->tagPtr);
            ptagsPtr->tagPtr = newTagPtr;
        }

        /* NB: This returns the first free tag address. */
        tagPtr = &ptagsPtr->tagPtr[ptagsPtr->numTags];
    }

    /*
     * Add in the new tag.
     */

    *tagPtr = tag;
    ptagsPtr->numTags++;
}

/*
 * FindItems --
 *
 *    This function does all the work of implementing the "find" and
 *    "addtag" options of the canvas widget command, which locate items that
 *    have certain features (location, tags, position in display list, etc.)
 *
 * Results:
 *    A standard Tcl return value. If newTag is NULL, then a list of ids
 *    from all the items that match objc/objv is returned in the interp's
 *    result. If newTag is NULL, then the normal the interp's result is an
 *    empty string. If an error occurs, then the interp's result will hold
 *    an error message.
 *
 * Side effects:
 *    If newTag is non-NULL, then all the items that match the information
 *    in objc/objv have that tag added to their lists of tags.
 */
static int
    FindItems(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    TkPathCanvas * path,       /* Canvas whose items are to be searched. */
    int objc,                  /* Number of entries in argv. Must be greater
                                * than zero. */
    Tcl_Obj * const *objv,     /* Arguments that describe what items to
                                * search for (see user doc on "find" and
                                * "addtag" options). */
    Tcl_Obj * newTag,          /* If non-NULL, gives new tag to set on all
                                * found items; if NULL, then ids of found
                                * items are returned in the interp's
                                * result. */
    int first,                 /* For error messages: gives number of
                                * elements of objv which are already
                                * handled. */
    TagSearch ** searchPtrPtr  /* From CanvasWidgetCmd local vars */
    ) {
    Tk_PathItem *itemPtr;
    Tk_Uid uid;
    int index, result;
    static const char *optionStrings[] = {
        "above", "all", "below", "closest",
        "enclosed", "overlapping", "withtag", NULL
    };
    enum options {
        CANV_ABOVE, CANV_ALL, CANV_BELOW, CANV_CLOSEST,
        CANV_ENCLOSED, CANV_OVERLAPPING, CANV_WITHTAG
    };

    if(newTag != NULL) {
        uid = Tk_GetUid(Tcl_GetString(newTag));
    } else {
        uid = NULL;
    }
    if(Tcl_GetIndexFromObj(interp, objv[first], optionStrings,
            "search command", 0, &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch ((enum options)index) {
    case CANV_ABOVE:{
    Tk_PathItem *lastPtr = NULL;

        if(objc != first + 2) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "tagOrId");
            return TCL_ERROR;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[first + 1], searchPtrPtr,
            return TCL_ERROR) {
            lastPtr = itemPtr;
        }

        /* We constrain this to siblings. */
        if((lastPtr != NULL) && (lastPtr->nextPtr != NULL)) {
            DoItem(interp, lastPtr->nextPtr, uid);
        }
        break;
    }
    case CANV_ALL:
        if(objc != first + 1) {
            Tcl_WrongNumArgs(interp, first + 1, objv, NULL);
            return TCL_ERROR;
        }
        for(itemPtr = path->rootItemPtr; itemPtr != NULL;
            itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
            DoItem(interp, itemPtr, uid);
        }
        break;

    case CANV_BELOW:
        if(objc != first + 2) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "tagOrId");
            return TCL_ERROR;
        }
        FIRST_CANVAS_ITEM_MATCHING(objv[first + 1], searchPtrPtr,
            return TCL_ERROR);
        if(itemPtr != NULL) {

            /* We constrain this to siblings. */
            if(itemPtr->prevPtr != NULL) {
                DoItem(interp, itemPtr->prevPtr, uid);
            }
        }
        break;
    case CANV_CLOSEST:{
    double closestDist;
    Tk_PathItem *startPtr, *closestPtr;
    double coords[2], halo;
    int x1, y1, x2, y2;

        if((objc < first + 3) || (objc > first + 5)) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "x y ?halo? ?start?");
            return TCL_ERROR;
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[first + 1], &coords[0]) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[first + 2], &coords[1]) != TCL_OK)) {
            return TCL_ERROR;
        }
        if(objc > first + 3) {
            if(Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path,
                    objv[first + 3], &halo) != TCL_OK) {
                return TCL_ERROR;
            }
            if(halo < 0.0) {
                Tcl_AppendResult(interp, "can't have negative halo value \"",
                    Tcl_GetString(objv[3]), "\"", NULL);
                return TCL_ERROR;
            }
        } else {
            halo = 0.0;
        }

        /*
         * Find the item at which to start the search.
         */

        startPtr = path->rootItemPtr;
        if(objc == first + 5) {
            FIRST_CANVAS_ITEM_MATCHING(objv[first + 4], searchPtrPtr,
                return TCL_ERROR);
            if(itemPtr != NULL) {
                startPtr = itemPtr;
            }
        }

        /*
         * The code below is optimized so that it can eliminate most items
         * without having to call their item-specific functions. This is done
         * by keeping a bounding box (x1, y1, x2, y2) that an item's bbox must
         * overlap if the item is to have any chance of being closer than the
         * closest so far.
         */

        itemPtr = startPtr;
        while(itemPtr && (itemPtr->state == TK_PATHSTATE_HIDDEN ||
                (itemPtr->state == TK_PATHSTATE_NULL &&
                    path->canvas_state == TK_PATHSTATE_HIDDEN))) {
            itemPtr = TkPathCanvasItemIteratorNext(itemPtr);
        }
        if(itemPtr == NULL) {
            return TCL_OK;
        }
        closestDist = (*itemPtr->typePtr->pointProc) ((Tk_PathCanvas) path,
            itemPtr, coords) - halo;
        if(closestDist < 0.0) {
            closestDist = 0.0;
        }
        while(1) {
    double newDist;

            /*
             * Update the bounding box using itemPtr, which is the new closest
             * item.
             */

            x1 = (int)(coords[0] - closestDist - halo - 1);
            y1 = (int)(coords[1] - closestDist - halo - 1);
            x2 = (int)(coords[0] + closestDist + halo + 1);
            y2 = (int)(coords[1] + closestDist + halo + 1);
            closestPtr = itemPtr;

            /*
             * Search for an item that beats the current closest one. Work
             * circularly through the canvas's item list until getting back to
             * the starting item.
             */

            while(1) {
                itemPtr = TkPathCanvasItemIteratorNext(itemPtr);
                if(itemPtr == NULL) {
                    itemPtr = path->rootItemPtr;
                }
                if(itemPtr == startPtr) {
                    DoItem(interp, closestPtr, uid);
                    return TCL_OK;
                }
                if(itemPtr->state == TK_PATHSTATE_HIDDEN ||
                    (itemPtr->state == TK_PATHSTATE_NULL &&
                        path->canvas_state == TK_PATHSTATE_HIDDEN)) {
                    continue;
                }
                if((itemPtr->x1 >= x2) || (itemPtr->x2 <= x1)
                    || (itemPtr->y1 >= y2) || (itemPtr->y2 <= y1)) {
                    continue;
                }
                newDist = (*itemPtr->typePtr->pointProc) ((Tk_PathCanvas) path,
                    itemPtr, coords) - halo;
                if(newDist < 0.0) {
                    newDist = 0.0;
                }
                if(newDist <= closestDist) {
                    closestDist = newDist;
                    break;
                }
            }
        }
        break;
    }
    case CANV_ENCLOSED:
        if(objc != first + 5) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "x1 y1 x2 y2");
            return TCL_ERROR;
        }
        return FindArea(interp, path, objv + first + 1, uid, 1);
    case CANV_OVERLAPPING:
        if(objc != first + 5) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "x1 y1 x2 y2");
            return TCL_ERROR;
        }
        return FindArea(interp, path, objv + first + 1, uid, 0);
    case CANV_WITHTAG:
        if(objc != first + 2) {
            Tcl_WrongNumArgs(interp, first + 1, objv, "tagOrId");
            return TCL_ERROR;
        }
        FOR_EVERY_CANVAS_ITEM_MATCHING(objv[first + 1], searchPtrPtr,
            return TCL_ERROR) {
            DoItem(interp, itemPtr, uid);
        }
    }
    return TCL_OK;
}

/*
 * FindArea --
 *
 *    This function implements area searches for the "find" and "addtag"
 *    options.
 *
 * Results:
 *    A standard Tcl return value. If newTag is NULL, then a list of ids
 *    from all the items overlapping or enclosed by the rectangle given by
 *    objc is returned in the interp's result. If newTag is NULL, then the
 *    normal the interp's result is an empty string. If an error occurs,
 *    then the interp's result will hold an error message.
 *
 * Side effects:
 *    If uid is non-NULL, then all the items overlapping or enclosed by the
 *    area in objv have that tag added to their lists of tags.
 */
static int
    FindArea(
    Tcl_Interp * interp,       /* Interpreter for error reporting and result
                                * storing. */
    TkPathCanvas * path,       /* Canvas whose items are to be searched. */
    Tcl_Obj * const *objv,     /* Array of four arguments that give the
                                * coordinates of the rectangular area to
                                * search. */
    Tk_Uid uid,                /* If non-NULL, gives new tag to set on all
                                * found items; if NULL, then ids of found
                                * items are returned in the interp's
                                * result. */
    int enclosed) {     /* 0 means overlapping or enclosed items are
                         * OK, 1 means only enclosed items are OK. */
    double rect[4], tmp;
    int x1, y1, x2, y2;
    Tk_PathItem *itemPtr;

    if((Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path, objv[0],
                &rect[0]) != TCL_OK)
        || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path, objv[1],
                &rect[1]) != TCL_OK)
        || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path, objv[2],
                &rect[2]) != TCL_OK)
        || (Tk_PathCanvasGetCoordFromObj(interp, (Tk_PathCanvas) path, objv[3],
                &rect[3]) != TCL_OK)) {
        return TCL_ERROR;
    }
    if(rect[0] > rect[2]) {
        tmp = rect[0];
        rect[0] = rect[2];
        rect[2] = tmp;
    }
    if(rect[1] > rect[3]) {
        tmp = rect[1];
        rect[1] = rect[3];
        rect[3] = tmp;
    }

    /*
     * Use an integer bounding box for a quick test, to avoid calling
     * item-specific code except for items that are close.
     */

    x1 = (int)(rect[0] - 1.0);
    y1 = (int)(rect[1] - 1.0);
    x2 = (int)(rect[2] + 1.0);
    y2 = (int)(rect[3] + 1.0);
    for(itemPtr = path->rootItemPtr; itemPtr != NULL;
        itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
        if(itemPtr->state == TK_PATHSTATE_HIDDEN
            || (itemPtr->state == TK_PATHSTATE_NULL
                && path->canvas_state == TK_PATHSTATE_HIDDEN)) {
            continue;
        }
        if((itemPtr->x1 >= x2) || (itemPtr->x2 <= x1)
            || (itemPtr->y1 >= y2) || (itemPtr->y2 <= y1)) {
            continue;
        }
        if((*itemPtr->typePtr->areaProc) ((Tk_PathCanvas) path, itemPtr, rect)
            >= enclosed) {
            DoItem(interp, itemPtr, uid);
        }
    }
    return TCL_OK;
}

/*
 * RelinkItems --
 *
 *    Move one or more items to a different place in the display order for a
 *    canvas.
 *    Only items with same parent as prevPtr will be moved. Items matching
 *    tag but with different parent will be silently ignored.
 *    If we didn't do this we would break the tree hierarchy structure
 *    which would create a mess!
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The items identified by "tag" are moved so that they are all together
 *    in the display list and immediately after prevPtr. The order of the
 *    moved items relative to each other is not changed.
 */
static int
RelinkItems(
    TkPathCanvas * path,       /* Canvas to be modified. */
    Tcl_Obj * tag,             /* Tag identifying items to be moved in the
                                * redisplay list. */
    Tk_PathItem * prevPtr,     /* Reposition the items so that they go just
                                * after this item (NULL means put at
                                * beginning of list). */
    TagSearch ** searchPtrPtr)
{              /* From CanvasWidgetCmd local vars */
Tk_PathItem *itemPtr;
Tk_PathItem *firstMovePtr, *lastMovePtr;
Tk_PathItem *parentPtr, *rootItemPtr;
int result;

    rootItemPtr = path->rootItemPtr;
    if(prevPtr == rootItemPtr) {
        return TCL_OK;
    }

    /*
     * Keep track of parentPtr for the selection of items.
     * prevPtr equal to NULL means use the root item as parent.
     * This keeps compatiblity with old canvas.
     */
    if(prevPtr != NULL) {
        parentPtr = prevPtr->parentPtr;
    } else {
        parentPtr = NULL;       /* later resolved, see below */
    }

    /*
     * Find all of the items to be moved and remove them from the list, making
     * an auxiliary list running from firstMovePtr to lastMovePtr. Record
     * their areas for redisplay.
     */
    firstMovePtr = lastMovePtr = NULL;
    FOR_EVERY_CANVAS_ITEM_MATCHING(tag, searchPtrPtr, return TCL_ERROR) {
        if(itemPtr->parentPtr == NULL) {
            continue;
        }
        if(parentPtr == NULL) {
            /* first matching item determines parent */
            parentPtr = itemPtr->parentPtr;
        } else if(itemPtr->parentPtr != parentPtr) {
            continue;
        }
        if(itemPtr == prevPtr) {
            /*
             * Item after which insertion is to occur is being moved! Switch
             * to insert after its predecessor.
             */

            prevPtr = prevPtr->prevPtr;
        }

        /*
         * Detach (splice out) item to be moved.
         */
        if(itemPtr->parentPtr->firstChildPtr == itemPtr) {
            itemPtr->parentPtr->firstChildPtr = itemPtr->nextPtr;
        }
        if(itemPtr->parentPtr->lastChildPtr == itemPtr) {
            itemPtr->parentPtr->lastChildPtr = itemPtr->prevPtr;
        }
        if(itemPtr->prevPtr != NULL) {
            itemPtr->prevPtr->nextPtr = itemPtr->nextPtr;
        }
        if(itemPtr->nextPtr != NULL) {
            itemPtr->nextPtr->prevPtr = itemPtr->prevPtr;
        }

        /*
         * Place moved item as the last item of the
         * moved linked list.
         */
        if(firstMovePtr == NULL) {
            itemPtr->prevPtr = NULL;
            itemPtr->nextPtr = NULL;
            firstMovePtr = itemPtr;
        } else {
            itemPtr->prevPtr = lastMovePtr;
            lastMovePtr->nextPtr = itemPtr;
        }
        lastMovePtr = itemPtr;
        EventuallyRedrawItemAndChildren((Tk_PathCanvas) path, itemPtr);
        path->flags |= REPICK_NEEDED;
    }

    if(firstMovePtr == NULL) {
        return TCL_OK;
    }

    /*
     * Insert the list of to-be-moved items back into the canvas's at the
     * desired position.
     */
    firstMovePtr->prevPtr = prevPtr;
    if(prevPtr != NULL) {
        if(prevPtr->nextPtr != NULL) {
            prevPtr->nextPtr->prevPtr = lastMovePtr;
        }
        lastMovePtr->nextPtr = prevPtr->nextPtr;
        prevPtr->nextPtr = firstMovePtr;
    } else {
        if(parentPtr->firstChildPtr != NULL) {
            parentPtr->firstChildPtr->prevPtr = lastMovePtr;
        }
        lastMovePtr->nextPtr = parentPtr->firstChildPtr;
        parentPtr->firstChildPtr = firstMovePtr;
    }
    if(parentPtr->lastChildPtr == prevPtr) {
        parentPtr->lastChildPtr = lastMovePtr;
    }

    return TCL_OK;
}

/*
 * CanvasBindProc --
 *
 *    This function is invoked by the Tk dispatcher to handle events
 *    associated with bindings on items.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Depends on the command invoked as part of the binding (if there was
 *    any).
 */
static void
CanvasBindProc(
    ClientData clientData,     /* Pointer to canvas structure. */
    XEvent * eventPtr)
{              /* Pointer to X event that just happened. */
TkPathCanvas *path = (TkPathCanvas *) clientData;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    Tcl_Preserve((ClientData) path);

    /*
     * This code below keeps track of the current modifier state in
     * path>state. This information is used to defer repicks of the
     * current item while buttons are down.
     */

    if((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) {
int mask;

        switch (eventPtr->xbutton.button) {
        case Button1:
            mask = Button1Mask;
            break;
        case Button2:
            mask = Button2Mask;
            break;
        case Button3:
            mask = Button3Mask;
            break;
        case Button4:
            mask = Button4Mask;
            break;
        case Button5:
            mask = Button5Mask;
            break;
        default:
            mask = 0;
            break;
        }

        /*
         * For button press events, repick the current item using the button
         * state before the event, then process the event. For button release
         * events, first process the event, then repick the current item using
         * the button state *after* the event (the button has logically gone
         * up before we change the current item).
         */

        if(eventPtr->type == ButtonPress) {
            /*
             * On a button press, first repick the current item using the
             * button state before the event, the process the event.
             */

            path->state = eventPtr->xbutton.state;
            PickCurrentItem(path, eventPtr);
            path->state ^= mask;
            CanvasDoEvent(path, eventPtr);
        } else {
            /*
             * Button release: first process the event, with the button still
             * considered to be down. Then repick the current item under the
             * assumption that the button is no longer down.
             */

            path->state = eventPtr->xbutton.state;
            CanvasDoEvent(path, eventPtr);
            eventPtr->xbutton.state ^= mask;
            path->state = eventPtr->xbutton.state;
            PickCurrentItem(path, eventPtr);
            eventPtr->xbutton.state ^= mask;
        }
        goto done;
    } else if((eventPtr->type == EnterNotify)
        || (eventPtr->type == LeaveNotify)) {
        path->state = eventPtr->xcrossing.state;
        PickCurrentItem(path, eventPtr);
        goto done;
    } else if(eventPtr->type == MotionNotify) {
        path->state = eventPtr->xmotion.state;
        PickCurrentItem(path, eventPtr);
    }
    CanvasDoEvent(path, eventPtr);

  done:
    Tcl_Release((ClientData) path);
}

/*
 * PickCurrentItem --
 *
 *    Find the topmost item in a canvas that contains a given location and
 *    mark the the current item. If the current item has changed, generate a
 *    fake exit event on the old current item, a fake enter event on the new
 *    current item item and force a redraw of the two items. Canvas items
 *    that are hidden or disabled are ignored.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The current item for path may change. If it does, then the
 *    commands associated with item entry and exit could do just about
 *    anything. A binding script could delete the canvas, so callers should
 *    protect themselves with Tcl_Preserve and Tcl_Release.
 */
static void
PickCurrentItem(
    TkPathCanvas * path,       /* Canvas widget in which to select current
                                * item. */
    XEvent * eventPtr)
{              /* Event describing location of mouse cursor.
                * Must be EnterWindow, LeaveWindow,
                * ButtonRelease, or MotionNotify. */
double coords[2];
int buttonDown;
Tk_PathItem *prevItemPtr;
SearchUids *searchUids = GetStaticUids();
    if(path->win == NULL || *(path->win) == NULL)
        return;
    /*
     * Check whether or not a button is down. If so, we'll log entry and exit
     * into and out of the current item, but not entry into any other item.
     * This implements a form of grabbing equivalent to what the X server does
     * for windows.
     */

    buttonDown = path->state
        & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask);

    /*
     * Save information about this event in the canvas. The event in the
     * canvas is used for two purposes:
     *
     * 1. Event bindings: if the current item changes, fake events are
     *    generated to allow item-enter and item-leave bindings to trigger.
     * 2. Reselection: if the current item gets deleted, can use the saved
     *    event to find a new current item.
     *
     * Translate MotionNotify events into EnterNotify events, since that's
     * what gets reported to item handlers.
     */

    if(eventPtr != &path->pickEvent) {
        if((eventPtr->type == MotionNotify)
            || (eventPtr->type == ButtonRelease)) {
            path->pickEvent.xcrossing.type = EnterNotify;
            path->pickEvent.xcrossing.serial = eventPtr->xmotion.serial;
            path->pickEvent.xcrossing.send_event = eventPtr->xmotion.send_event;
            path->pickEvent.xcrossing.display = eventPtr->xmotion.display;
            path->pickEvent.xcrossing.window = eventPtr->xmotion.window;
            path->pickEvent.xcrossing.root = eventPtr->xmotion.root;
            path->pickEvent.xcrossing.subwindow = None;
            path->pickEvent.xcrossing.time = eventPtr->xmotion.time;
            path->pickEvent.xcrossing.x = eventPtr->xmotion.x;
            path->pickEvent.xcrossing.y = eventPtr->xmotion.y;
            path->pickEvent.xcrossing.x_root = eventPtr->xmotion.x_root;
            path->pickEvent.xcrossing.y_root = eventPtr->xmotion.y_root;
            path->pickEvent.xcrossing.mode = NotifyNormal;
            path->pickEvent.xcrossing.detail = NotifyNonlinear;
            path->pickEvent.xcrossing.same_screen =
                eventPtr->xmotion.same_screen;
            path->pickEvent.xcrossing.focus = False;
            path->pickEvent.xcrossing.state = eventPtr->xmotion.state;
        } else {
            path->pickEvent = *eventPtr;
        }
    }

    /*
     * If this is a recursive call (there's already a partially completed call
     * pending on the stack; it's in the middle of processing a Leave event
     * handler for the old current item) then just return; the pending call
     * will do everything that's needed.
     */

    if(path->flags & REPICK_IN_PROGRESS) {
        return;
    }

    /*
     * A LeaveNotify event automatically means that there's no current object,
     * so the check for closest item can be skipped.
     */

    coords[0] = path->pickEvent.xcrossing.x + path->xOrigin;
    coords[1] = path->pickEvent.xcrossing.y + path->yOrigin;
    if(path->pickEvent.type != LeaveNotify) {
        path->newCurrentPtr = CanvasFindClosest(path, coords);
    } else {
        path->newCurrentPtr = NULL;
    }

    if((path->newCurrentPtr == path->currentItemPtr)
        && !(path->flags & LEFT_GRABBED_ITEM)) {
        /*
         * Nothing to do:  the current item hasn't changed.
         */

        return;
    }

    if(!buttonDown) {
        path->flags &= ~LEFT_GRABBED_ITEM;
    }

    /*
     * Simulate a LeaveNotify event on the previous current item and an
     * EnterNotify event on the new current item. Remove the "current" tag
     * from the previous current item and place it on the new current item.
     */

    if((path->newCurrentPtr != path->currentItemPtr)
        && (path->currentItemPtr != NULL)
        && !(path->flags & LEFT_GRABBED_ITEM)) {
XEvent event;
Tk_PathItem *itemPtr = path->currentItemPtr;
Tk_PathTags *ptagsPtr;
int i;

        event = path->pickEvent;
        event.type = LeaveNotify;

        /*
         * If the event's detail happens to be NotifyInferior the binding
         * mechanism will discard the event. To be consistent, always use
         * NotifyAncestor.
         */

        event.xcrossing.detail = NotifyAncestor;
        path->flags |= REPICK_IN_PROGRESS;
        CanvasDoEvent(path, &event);
        path->flags &= ~REPICK_IN_PROGRESS;

        /*
         * The check below is needed because there could be an event handler
         * for <LeaveNotify> that deletes the current item.
         */

        if((itemPtr == path->currentItemPtr) && !buttonDown &&
            (itemPtr->pathTagsPtr != NULL)) {
            ptagsPtr = itemPtr->pathTagsPtr;
            for(i = ptagsPtr->numTags - 1; i >= 0; i--) {
                if(ptagsPtr->tagPtr[i] == searchUids->currentUid)
                    /* then */  {
                    ptagsPtr->tagPtr[i] =
                        ptagsPtr->tagPtr[ptagsPtr->numTags - 1];
                    ptagsPtr->numTags--;
                    break;
                    }
            }
        }

        /*
         * Note: during CanvasDoEvent above, it's possible that
         * path->newCurrentPtr got reset to NULL because the item was
         * deleted.
         */
    }
    if((path->newCurrentPtr != path->currentItemPtr) && buttonDown) {
        path->flags |= LEFT_GRABBED_ITEM;
        return;
    }

    /*
     * Special note: it's possible that path->newCurrentPtr ==
     * path->currentItemPtr here. This can happen, for example, if
     * LEFT_GRABBED_ITEM was set.
     */

    prevItemPtr = path->currentItemPtr;
    path->flags &= ~LEFT_GRABBED_ITEM;
    path->currentItemPtr = path->newCurrentPtr;
    if(prevItemPtr != NULL && prevItemPtr != path->currentItemPtr &&
        (prevItemPtr->redraw_flags & TK_ITEM_STATE_DEPENDANT)) {
        EventuallyRedrawItem((Tk_PathCanvas) path, prevItemPtr);
        (*prevItemPtr->typePtr->configProc) (path->interp,
            (Tk_PathCanvas) path, prevItemPtr, 0, NULL, TK_CONFIG_ARGV_ONLY);
    }
    if(path->currentItemPtr != NULL) {
XEvent event;

        DoItem(NULL, path->currentItemPtr, searchUids->currentUid);
        if((path->currentItemPtr->redraw_flags & TK_ITEM_STATE_DEPENDANT &&
                prevItemPtr != path->currentItemPtr)) {
            (*path->currentItemPtr->typePtr->configProc) (path->interp,
                (Tk_PathCanvas) path, path->currentItemPtr, 0, NULL,
                TK_CONFIG_ARGV_ONLY);
            EventuallyRedrawItem((Tk_PathCanvas) path, path->currentItemPtr);
        }
        event = path->pickEvent;
        event.type = EnterNotify;
        event.xcrossing.detail = NotifyAncestor;
        CanvasDoEvent(path, &event);
    }
}

/*
 * CanvasFindClosest --
 *
 *    Given x and y coordinates, find the topmost canvas item that is
 *    "close" to the coordinates. Canvas items that are hidden or disabled
 *    are ignored.
 *
 * Results:
 *    The return value is a pointer to the topmost item that is close to
 *    (x,y), or NULL if no item is close.
 *
 * Side effects:
 *    None.
 */
static Tk_PathItem *
CanvasFindClosest(
    TkPathCanvas * path,       /* Canvas widget to search. */
    double coords[2])
{              /* Desired x,y position in canvas, not screen,
                * coordinates.) */
    Tk_PathItem *itemPtr;
    Tk_PathItem *bestPtr;
    int x1, y1, x2, y2;

    x1 = (int)(coords[0] - path->closeEnough);
    y1 = (int)(coords[1] - path->closeEnough);
    x2 = (int)(coords[0] + path->closeEnough);
    y2 = (int)(coords[1] + path->closeEnough);

    bestPtr = NULL;
    for(itemPtr = path->rootItemPtr; itemPtr != NULL;
        itemPtr = TkPathCanvasItemIteratorNext(itemPtr)) {
        if((itemPtr->state == TK_PATHSTATE_HIDDEN) ||
            (itemPtr->state == TK_PATHSTATE_DISABLED) ||
            ((itemPtr->state == TK_PATHSTATE_NULL) &&
                ((path->canvas_state == TK_PATHSTATE_HIDDEN) ||
                    (path->canvas_state == TK_PATHSTATE_DISABLED)))) {
            continue;
        }
        if((itemPtr->x1 > x2) || (itemPtr->x2 < x1)
            || (itemPtr->y1 > y2) || (itemPtr->y2 < y1)) {
            continue;
        }
        if((*itemPtr->typePtr->pointProc) ((Tk_PathCanvas) path,
                itemPtr, coords) <= path->closeEnough) {
            bestPtr = itemPtr;
        }
    }
    return bestPtr;
}

/*
 * CanvasDoEvent --
 *
 *    This function is called to invoke binding processing for a new event
 *    that is associated with the current item for a canvas.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Depends on the bindings for the canvas. A binding script could delete
 *    the canvas, so callers should protect themselves with Tcl_Preserve and
 *    Tcl_Release.
 */
static void
CanvasDoEvent(
    TkPathCanvas * path,       /* Canvas widget in which event occurred. */
    XEvent * eventPtr)
{              /* Real or simulated X event that is to be
                * processed. */
#define NUM_STATIC 3
ClientData staticObjects[NUM_STATIC];
ClientData *objectPtr;
int numObjects, i;
int numTags;
Tk_PathItem *itemPtr;
Tk_PathTags *ptagsPtr;
TkPathTagSearchExpr *expr;
int numExprs;
SearchUids *searchUids = GetStaticUids();
    if(path->win == NULL || *(path->win) == NULL)
        return;

    itemPtr = path->currentItemPtr;
    if((eventPtr->type == KeyPress) || (eventPtr->type == KeyRelease)) {
        itemPtr = path->textInfo.focusItemPtr;
    }
    if(itemPtr == NULL) {
        return;
    }
    ptagsPtr = itemPtr->pathTagsPtr;
    numTags = ItemGetNumTags(itemPtr);

    /*
     * Set up an array with all the relevant objects for processing this
     * event. The relevant objects are:
     * (a) the event's item,
     * (b) the tags associated with the event's item,
     * (c) the expressions that are true for the event's item's tags, and
     * (d) the tag "all".
     *
     * If there are a lot of tags then malloc an array to hold all of the
     * objects.
     */

    /*
     * Flag and count all expressions that match item's tags.
     */

    numExprs = 0;
    expr = path->bindTagExprs;
    while(expr) {
        expr->index = 0;
        expr->match = TagSearchEvalExpr(expr, itemPtr);
        if(expr->match) {
            numExprs++;
        }
        expr = expr->next;
    }
    numObjects = numTags + numExprs + 2;

    if(numObjects <= NUM_STATIC) {
        objectPtr = staticObjects;
    } else {
        objectPtr = (ClientData *) ckalloc((unsigned)
            (numObjects * sizeof(ClientData)));
    }
    objectPtr[0] = (ClientData) searchUids->allUid;

    if(ptagsPtr != NULL) {
        for(i = ptagsPtr->numTags - 1; i >= 0; i--) {
            objectPtr[i + 1] = (ClientData) ptagsPtr->tagPtr[i];
        }
    }
    objectPtr[numTags + 1] = (ClientData) itemPtr;

    /*
     * Copy uids of matching expressions into object array
     */

    i = numTags + 2;
    expr = path->bindTagExprs;
    while(expr) {
        if(expr->match) {
            objectPtr[i++] = (int *)expr->uid;
        }
        expr = expr->next;
    }

    /*
     * Invoke the binding system, then free up the object array if it was
     * malloc-ed.
     */

    Tk_BindEvent(path->bindingTable, eventPtr, *(path->win),
        numObjects, objectPtr);
    if(objectPtr != staticObjects) {
        ckfree((char *)objectPtr);
    }
}

/*
 * CanvasBlinkProc --
 *
 *    This function is called as a timer handler to blink the insertion
 *    cursor off and on.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The cursor gets turned on or off, redisplay gets invoked, and this
 *    function reschedules itself.
 */

static void
CanvasBlinkProc(
    ClientData clientData)
{              /* Pointer to record describing entry. */
TkPathCanvas *path = (TkPathCanvas *) clientData;

    if(!path->textInfo.gotFocus || (path->insertOffTime == 0)) {
        return;
    }
    if(path->textInfo.cursorOn) {
        path->textInfo.cursorOn = 0;
        path->insertBlinkHandler =
            Tcl_CreateTimerHandler(path->insertOffTime, CanvasBlinkProc,
            (ClientData) path);
    } else {
        path->textInfo.cursorOn = 1;
        path->insertBlinkHandler =
            Tcl_CreateTimerHandler(path->insertOnTime, CanvasBlinkProc,
            (ClientData) path);
    }
    if(path->textInfo.focusItemPtr != NULL) {
        EventuallyRedrawItem((Tk_PathCanvas) path, path->textInfo.focusItemPtr);
    }
}

/*
 * CanvasFocusProc --
 *
 *    This function is called whenever a canvas gets or loses the input
 *    focus. It's also called whenever the window is reconfigured while it
 *    has the focus.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The cursor gets turned on or off.
 */
static void
CanvasFocusProc(
    TkPathCanvas * path,       /* Canvas that just got or lost focus. */
    int gotFocus)
{              /* 1 means window is getting focus, 0 means
                * it's losing it. */
    Tcl_DeleteTimerHandler(path->insertBlinkHandler);
    if(gotFocus) {
        path->textInfo.gotFocus = 1;
        path->textInfo.cursorOn = 1;
        if(path->insertOffTime != 0) {
            path->insertBlinkHandler =
                Tcl_CreateTimerHandler(path->insertOffTime, CanvasBlinkProc,
                (ClientData) path);
        }
    } else {
        path->textInfo.gotFocus = 0;
        path->textInfo.cursorOn = 0;
        path->insertBlinkHandler = (Tcl_TimerToken) NULL;
    }
    if(path->textInfo.focusItemPtr != NULL) {
        EventuallyRedrawItem((Tk_PathCanvas) path, path->textInfo.focusItemPtr);
    }
    if(path->highlightWidth > 0) {
        path->flags |= REDRAW_BORDERS;
        if(!(path->flags & REDRAW_PENDING)) {
            Tcl_DoWhenIdle(PathDisplay, (ClientData) path);
            path->flags |= REDRAW_PENDING;
        }
    }
}

/*
 * CanvasSelectTo --
 *
 *    Modify the selection by moving its un-anchored end. This could make
 *    the selection either larger or smaller.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The selection changes.
 */
static void
CanvasSelectTo(
    TkPathCanvas * path,       /* Information about widget. */
    Tk_PathItem * itemPtr,     /* Item that is to hold selection. */
    int index)
{              /* Index of element that is to become the
                * "other" end of the selection. */
    int oldFirst, oldLast;
    Tk_PathItem *oldSelPtr;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    oldFirst = path->textInfo.selectFirst;
    oldLast = path->textInfo.selectLast;
    oldSelPtr = path->textInfo.selItemPtr;

    /*
     * Grab the selection if we don't own it already.
     */

    if(path->textInfo.selItemPtr == NULL) {
        Tk_OwnSelection(*(path->win), XA_PRIMARY, CanvasLostSelection,
            (ClientData) path);
    } else if(path->textInfo.selItemPtr != itemPtr) {
        EventuallyRedrawItem((Tk_PathCanvas) path, path->textInfo.selItemPtr);
    }
    path->textInfo.selItemPtr = itemPtr;

    if(path->textInfo.anchorItemPtr != itemPtr) {
        path->textInfo.anchorItemPtr = itemPtr;
        path->textInfo.selectAnchor = index;
    }
    if(path->textInfo.selectAnchor <= index) {
        path->textInfo.selectFirst = path->textInfo.selectAnchor;
        path->textInfo.selectLast = index;
    } else {
        path->textInfo.selectFirst = index;
        path->textInfo.selectLast = path->textInfo.selectAnchor - 1;
    }
    if((path->textInfo.selectFirst != oldFirst)
        || (path->textInfo.selectLast != oldLast)
        || (itemPtr != oldSelPtr)) {
        EventuallyRedrawItem((Tk_PathCanvas) path, itemPtr);
    }
}

/*
 * CanvasFetchSelection --
 *
 *    This function is invoked by Tk to return part or all of the selection,
 *    when the selection is in a canvas widget. This function always returns
 *    the selection as a STRING.
 *
 * Results:
 *    The return value is the number of non-NULL bytes stored at buffer.
 *    Buffer is filled (or partially filled) with a NULL-terminated string
 *    containing part or all of the selection, as given by offset and
 *    maxBytes.
 *
 * Side effects:
 *    None.
 */
static int
CanvasFetchSelection(
    ClientData clientData,     /* Information about canvas widget. */
    int offset,                /* Offset within selection of first character
                                * to be returned. */
    char *buffer,              /* Location in which to place selection. */
    int maxBytes)
{              /* Maximum number of bytes to place at buffer,
                * not including terminating NULL
                * character. */
    TkPathCanvas *path = (TkPathCanvas *) clientData;
    if(path->win == NULL || *(path->win) == NULL)
        return -1;

    if(path->textInfo.selItemPtr == NULL) {
        return -1;
    }
    if(path->textInfo.selItemPtr->typePtr->selectionProc == NULL) {
        return -1;
    }
    return (*path->textInfo.selItemPtr->typePtr->selectionProc) (
        (Tk_PathCanvas) path, path->textInfo.selItemPtr, offset,
        buffer, maxBytes);
}

/*
 * CanvasLostSelection --
 *
 *    This function is called back by Tk when the selection is grabbed away
 *    from a canvas widget.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The existing selection is unhighlighted, and the window is marked as
 *    not containing a selection.
 */
static void
CanvasLostSelection(
    ClientData clientData)
{              /* Information about entry widget. */
TkPathCanvas *path = (TkPathCanvas *) clientData;

    if(path->textInfo.selItemPtr != NULL) {
        EventuallyRedrawItem((Tk_PathCanvas) path, path->textInfo.selItemPtr);
    }
    path->textInfo.selItemPtr = NULL;
}

/*
 * GridAlign --
 *
 *    Given a coordinate and a grid spacing, this function computes the
 *    location of the nearest grid line to the coordinate.
 *
 * Results:
 *    The return value is the location of the grid line nearest to coord.
 *
 * Side effects:
 *    None.
 */
static double
GridAlign(
    double coord,              /* Coordinate to grid-align. */
    double spacing)
{              /* Spacing between grid lines. If <= 0 then no
                * alignment is done. */
    if(spacing <= 0.0) {
        return coord;
    }
    if(coord < 0) {
        return -((int)((-coord) / spacing + 0.5)) * spacing;
    }
    return ((int)(coord / spacing + 0.5)) * spacing;
}

/*
 * ScrollFractions --
 *
 *    Given the range that's visible in the window and the "100% range" for
 *    what's in the canvas, return a list of two doubles representing the
 *    scroll fractions. This function is used for both x and y scrolling.
 *
 * Results:
 *    A List Tcl_Obj with two real numbers (Double Tcl_Objs) containing the
 *    scroll fractions (between 0 and 1) corresponding to the other
 *    arguments.
 *
 * Side effects:
 *    None.
 */
static Tcl_Obj *
ScrollFractions(
    int screen1,               /* Lowest coordinate visible in the window. */
    int screen2,               /* Highest coordinate visible in the window. */
    int object1,               /* Lowest coordinate in the object. */
    int object2)
{              /* Highest coordinate in the object. */
    Tcl_Obj *buffer[2];
    double range, f1, f2;

    range = object2 - object1;
    if(range <= 0) {
        f1 = 0;
        f2 = 1.0;
    } else {
        f1 = (screen1 - object1) / range;
        if(f1 < 0) {
            f1 = 0.0;
        }
        f2 = (screen2 - object1) / range;
        if(f2 > 1.0) {
            f2 = 1.0;
        }
        if(f2 < f1) {
            f2 = f1;
        }
    }
    buffer[0] = Tcl_NewDoubleObj(f1);
    buffer[1] = Tcl_NewDoubleObj(f2);
    return Tcl_NewListObj(2, buffer);
}

/*
 * CanvasUpdateScrollbars --
 *
 *    This function is invoked whenever a canvas has changed in a way that
 *    requires scrollbars to be redisplayed (e.g. the view in the canvas has
 *    changed).
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    If there are scrollbars associated with the canvas, then their
 *    scrolling commands are invoked to cause them to redisplay. If errors
 *    occur, additional Tcl commands may be invoked to process the errors.
 */
static void
CanvasUpdateScrollbars(
    TkPathCanvas * path)
{              /* Information about canvas. */
int result;
Tcl_Interp *interp;
int xOrigin, yOrigin, inset, width, height;
int scrollX1, scrollX2, scrollY1, scrollY2;
char *xScrollCmd, *yScrollCmd;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    /*
     * Save all the relevant values from the path, because it might be
     * deleted as part of either of the two calls to Tcl_VarEval below.
     */

    interp = path->interp;
    Tcl_Preserve((ClientData) interp);
    xScrollCmd = path->xScrollCmd;
    if(xScrollCmd != NULL) {
        Tcl_Preserve((ClientData) xScrollCmd);
    }
    yScrollCmd = path->yScrollCmd;
    if(yScrollCmd != NULL) {
        Tcl_Preserve((ClientData) yScrollCmd);
    }
    xOrigin = path->xOrigin;
    yOrigin = path->yOrigin;
    inset = path->inset;
    width = Tk_Width(*(path->win));
    height = Tk_Height(*(path->win));
    scrollX1 = path->scroll[0];
    scrollX2 = path->scroll[2];
    scrollY1 = path->scroll[1];
    scrollY2 = path->scroll[3];
    path->flags &= ~UPDATE_SCROLLBARS;
    if(path->xScrollCmd != NULL) {
Tcl_Obj *fractions = ScrollFractions(xOrigin + inset,
            xOrigin + width - inset, scrollX1, scrollX2);
        result = Tcl_VarEval(interp, xScrollCmd, " ", Tcl_GetString(fractions),
            NULL);
        Tcl_DecrRefCount(fractions);
        if(result != TCL_OK) {
            Tcl_BackgroundError(interp);
        }
        Tcl_ResetResult(interp);
        Tcl_Release((ClientData) xScrollCmd);
    }

    if(yScrollCmd != NULL) {
Tcl_Obj *fractions = ScrollFractions(yOrigin + inset,
            yOrigin + height - inset, scrollY1, scrollY2);
        result = Tcl_VarEval(interp, yScrollCmd, " ", Tcl_GetString(fractions),
            NULL);
        Tcl_DecrRefCount(fractions);
        if(result != TCL_OK) {
            Tcl_BackgroundError(interp);
        }
        Tcl_ResetResult(interp);
        Tcl_Release((ClientData) yScrollCmd);
    }
    Tcl_Release((ClientData) interp);
}

/*
 * CanvasSetOrigin --
 *
 *    This function is invoked to change the mapping between canvas
 *    coordinates and screen coordinates in the canvas window.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The canvas will be redisplayed to reflect the change in view. In
 *    addition, scrollbars will be updated if there are any.
 */
static void
CanvasSetOrigin(
    TkPathCanvas * path,       /* Information about canvas. */
    int xOrigin,               /* New X origin for canvas (canvas x-coord
                                * corresponding to left edge of canvas
                                * window). */
    int yOrigin)
{              /* New Y origin for canvas (canvas y-coord
                * corresponding to top edge of canvas
                * window). */
    int left, right, top, bottom, delta;
    if(path->win == NULL || *(path->win) == NULL)
        return;

    /*
     * If scroll increments have been set, round the window origin to the
     * nearest multiple of the increments. Remember, the origin is the place
     * just inside the borders, not the upper left corner.
     */

    if(path->xScrollIncrement > 0) {
        if(xOrigin >= 0) {
            xOrigin += path->xScrollIncrement / 2;
            xOrigin -= (xOrigin + path->inset)
                % path->xScrollIncrement;
        } else {
            xOrigin = (-xOrigin) + path->xScrollIncrement / 2;
            xOrigin = -(xOrigin - (xOrigin - path->inset)
                % path->xScrollIncrement);
        }
    }
    if(path->yScrollIncrement > 0) {
        if(yOrigin >= 0) {
            yOrigin += path->yScrollIncrement / 2;
            yOrigin -= (yOrigin + path->inset)
                % path->yScrollIncrement;
        } else {
            yOrigin = (-yOrigin) + path->yScrollIncrement / 2;
            yOrigin = -(yOrigin - (yOrigin - path->inset)
                % path->yScrollIncrement);
        }
    }

    /*
     * Adjust the origin if necessary to keep as much as possible of the
     * canvas in the view. The variables left, right, etc. keep track of how
     * much extra space there is on each side of the view before it will stick
     * out past the scroll region.  If one side sticks out past the edge of
     * the scroll region, adjust the view to bring that side back to the edge
     * of the scrollregion (but don't move it so much that the other side
     * sticks out now). If scroll increments are in effect, be sure to adjust
     * only by full increments.
     */

    if((path->confine) && (path->scroll[0] != 0 || path->scroll[1] != 0 ||
            path->scroll[2] != 0 || path->scroll[3] != 0)) {
        left = xOrigin + path->inset - path->scroll[0];
        right = path->scroll[2]
            - (xOrigin + Tk_Width(*(path->win)) - path->inset);
        top = yOrigin + path->inset - path->scroll[1];
        bottom = path->scroll[3]
            - (yOrigin + Tk_Height(*(path->win)) - path->inset);
        if((left < 0) && (right > 0)) {
            delta = (right > -left) ? -left : right;
            if(path->xScrollIncrement > 0) {
                delta -= delta % path->xScrollIncrement;
            }
            xOrigin += delta;
        } else if((right < 0) && (left > 0)) {
            delta = (left > -right) ? -right : left;
            if(path->xScrollIncrement > 0) {
                delta -= delta % path->xScrollIncrement;
            }
            xOrigin -= delta;
        }
        if((top < 0) && (bottom > 0)) {
            delta = (bottom > -top) ? -top : bottom;
            if(path->yScrollIncrement > 0) {
                delta -= delta % path->yScrollIncrement;
            }
            yOrigin += delta;
        } else if((bottom < 0) && (top > 0)) {
            delta = (top > -bottom) ? -bottom : top;
            if(path->yScrollIncrement > 0) {
                delta -= delta % path->yScrollIncrement;
            }
            yOrigin -= delta;
        }
    }

    if((xOrigin == path->xOrigin) && (yOrigin == path->yOrigin)) {
        return;
    }

    /*
     * Tricky point: must redisplay not only everything that's visible in the
     * window's final configuration, but also everything that was visible in
     * the initial configuration. This is needed because some item types, like
     * windows, need to know when they move off-screen so they can explicitly
     * undisplay themselves.
     */

    Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
        path->xOrigin, path->yOrigin,
        path->xOrigin + Tk_Width(*(path->win)),
        path->yOrigin + Tk_Height(*(path->win)));
    path->xOrigin = xOrigin;
    path->yOrigin = yOrigin;
    path->flags |= UPDATE_SCROLLBARS;
    Tk_PathCanvasEventuallyRedraw((Tk_PathCanvas) path,
        path->xOrigin, path->yOrigin,
        path->xOrigin + Tk_Width(*(path->win)),
        path->yOrigin + Tk_Height(*(path->win)));
}

/*
 * GetStringsFromObjs --
 *
 * Results:
 *    Converts object list into string list.
 *
 * Side effects:
 *    Memory is allocated for the objv array, which must be freed using
 *    ckfree() when no longer needed.
	* @@@ TODO: this shouldn't be needed when fully objectified!
 */
static const char **
GetStringsFromObjs(
    int objc,
    Tcl_Obj * const objv[])
{
    int i;
    const char **argv;
    if(objc <= 0) {
        return NULL;
    }
    argv = (const char **)ckalloc((objc + 1) * sizeof(char *));
    for(i = 0; i < objc; i++) {
        argv[i] = Tcl_GetString(objv[i]);
    }
    argv[objc] = 0;
    return argv;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPath.h.
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPath.h --
 *
 *    Header file for the internals of the tko path package.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 * Copyright (c) 2019 Rene Zaumseil
 *
 */

#ifndef _TKOPATH_H
#define _TKOPATH_H

#include "tkoWidget.h"

/*
 * For C++ compilers, use extern "C"
 */
#ifdef __cplusplus
extern "C" {
#endif

/*
 * Tkpath defines start here
 */
#define TKPATH_VERSION    "0.3"
#define TKPATH_PATCHLEVEL "0.3.3"
#define TKPATH_REQUIRE    "8.6.8"

/*
 *  Global variables set in tkpathMain.c
 */
    MODULE_SCOPE int Tk_PathAntiAlias;
    MODULE_SCOPE int Tk_PathDepixelize;
    MODULE_SCOPE int Tk_PathSurfaceCopyPremultiplyAlpha;

/*
 * So far we use a fixed number of straight line segments when
 * doing various things, but it would be better to use the de Castlejau
 * algorithm to iterate these segments.
 */
#define TK_PATH_NUMSEGEMENTS_CurveTo         18
#define TK_PATH_NUMSEGEMENTS_QuadBezier     12
#define TK_PATH_NUMSEGEMENTS_Max        18
#define TK_PATH_NUMSEGEMENTS_Ellipse         48

#define TK_PATH_UNIT_TMATRIX  {1.0, 0.0, 0.0, 1.0, 0.0, 0.0}

/*
 * Flag bits for gradient and style changes.
 */
    enum {
        TK_PATH_GRADIENT_FLAG_CONFIGURE = (1L << 0),
        TK_PATH_GRADIENT_FLAG_DELETE
    };

    enum {
        TK_PATH_STYLE_FLAG_CONFIGURE = (1L << 0),
        TK_PATH_STYLE_FLAG_DELETE
    };

    enum {
        TK_PATH_TEXTANCHOR_Start = 0L,
        TK_PATH_TEXTANCHOR_Middle,
        TK_PATH_TEXTANCHOR_End,
        TK_PATH_TEXTANCHOR_N,
        TK_PATH_TEXTANCHOR_W,
        TK_PATH_TEXTANCHOR_S,
        TK_PATH_TEXTANCHOR_E,
        TK_PATH_TEXTANCHOR_NW,
        TK_PATH_TEXTANCHOR_NE,
        TK_PATH_TEXTANCHOR_SW,
        TK_PATH_TEXTANCHOR_SE,
        TK_PATH_TEXTANCHOR_C
    };

    enum {
        TK_PATH_IMAGEINTERPOLATION_None = 0,
        TK_PATH_IMAGEINTERPOLATION_Fast,
        TK_PATH_IMAGEINTERPOLATION_Best
    };

/* These MUST be kept in sync with methodST and unitsST! */
    enum {
        TK_PATH_GRADIENTMETHOD_Pad = 0L,
        TK_PATH_GRADIENTMETHOD_Repeat,
        TK_PATH_GRADIENTMETHOD_Reflect
    };

    enum {
        TK_PATH_GRADIENTUNITS_BoundingBox = 0L,
        TK_PATH_GRADIENTUNITS_UserSpace
    };

    enum {
        TK_PATH_ARC_OK,
        TK_PATH_ARC_Line,
        TK_PATH_ARC_Skip
    };

    enum {
        TK_PATH_GRADIENTTYPE_LINEAR = 0L,
        TK_PATH_GRADIENTTYPE_RADIAL
    };

/*
 * Flags for 'TkPathStyleMergeStyles'.
 */
    enum {
        TK_PATH_MERGESTYLE_NOTFILL = 0L,
        TK_PATH_MERGESTYLE_NOTSTROKE
    };

/*
 * The enum below defines the valid types for the TkPathAtom's.
 */
    typedef enum {
        TK_PATH_ATOM_M = 'M',
        TK_PATH_ATOM_L = 'L',
        TK_PATH_ATOM_A = 'A',
        TK_PATH_ATOM_Q = 'Q',
        TK_PATH_ATOM_C = 'C',
        TK_PATH_ATOM_Z = 'Z',
        TK_PATH_ATOM_ELLIPSE = '1',     /* These are not a standard atoms
                                         * since they are more complex (molecule).
                                         * Not all features supported for these! */
        TK_PATH_ATOM_RECT = '2'
    } TkPathAtomType;

/*
 * TkPathRect --
 */
    typedef struct TkPathRect {
        double x1;
        double y1;
        double x2;
        double y2;
    } TkPathRect;

/*
 * TkPathPoint --
 */
    typedef struct TkPathPoint {
        double x;
        double y;
    } TkPathPoint;

/*
 * TkPathMatrix --
 *
 * The transformation matrix:
 *        | a  b  0 |
 *        | c  d  0 |
 *        | tx ty 1 |
 */
    typedef struct TkPathMatrix {
        double a, b, c, d;
        double tx, ty;
    } TkPathMatrix;

/*
 * TkPathAtom --
 *
 * Records used for parsing path to a linked list of primitive
 * drawing instructions.
 *
 * PathAtom: vaguely modelled after Tk_PathItem. Each atom has a PathAtom record
 * in its first position, padded with type specific data.
 */
    typedef struct TkPathAtom {
        TkPathAtomType type;   /* Type of PathAtom. */
        struct TkPathAtom *nextPtr;     /* Next PathAtom along the path. */
    } TkPathAtom;

/*
 * TkLookupTable --
 */
    typedef struct TkLookupTable {
        int from;
        int to;
    } TkLookupTable;

/*
 * TkMoveAtom --
 *
 * Records used for parsing path to a linked list of primitive
 * drawing instructions.
 *
 * TkPathAtom: vaguely modelled after Tk_PathItem. Each atom has a TkPathAtom record
 * in its first position, padded with type specific data.
 */

    typedef struct TkMoveToAtom {
        TkPathAtom pathAtom;   /* Generic stuff that's the same for all
                                * types.  MUST BE FIRST IN STRUCTURE. */
        double x;
        double y;
    } TkMoveToAtom;

/*
 * TkLineAtom --
 */
    typedef struct TkLineToAtom {
        TkPathAtom pathAtom;
        double x;
        double y;
    } TkLineToAtom;

/*
 * TkArcAtom --
 */
    typedef struct TkArcAtom {
        TkPathAtom pathAtom;
        double radX;
        double radY;
        double angle;          /* In degrees! */
        char largeArcFlag;
        char sweepFlag;
        double x;
        double y;
    } TkArcAtom;

/*
 * TkQuadBetierAtom --
 */
    typedef struct TkQuadBezierAtom {
        TkPathAtom pathAtom;
        double ctrlX;
        double ctrlY;
        double anchorX;
        double anchorY;
    } TkQuadBezierAtom;

/*
 * TkCurveToAtom --
 */
    typedef struct TkCurveToAtom {
        TkPathAtom pathAtom;
        double ctrlX1;
        double ctrlY1;
        double ctrlX2;
        double ctrlY2;
        double anchorX;
        double anchorY;
    } TkCurveToAtom;

/*
 * TkCloseAtom --
 */
    typedef struct TkCloseAtom {
        TkPathAtom pathAtom;
        double x;
        double y;
    } TkCloseAtom;

/*
 * TkellipseAtom --
 */
    typedef struct TkEllipseAtom {
        TkPathAtom pathAtom;
        double cx;
        double cy;
        double rx;
        double ry;
    } TkEllipseAtom;

/*
 * TkRectAtom --
 */
    typedef struct TkRectAtom {
        TkPathAtom pathAtom;
        double x;
        double y;
        double width;
        double height;
    } TkRectAtom;

/*
 * TkPathDash --
 *
 * Structures used for Dashing and Outline.
 */
    typedef struct TkPathDash {
        int number;
        float *array;
    } TkPathDash;

/*
 * TkGradientStop --
 *
 * Records for gradient fills.
 * We need a separate GradientStopArray to simplify option parsing.
 */
    typedef struct TkGradientStop {
        double offset;
        XColor *color;
        double opacity;
    } TkGradientStop;

/*
 * TkGradientStopArray --
 */
    typedef struct TkGradientStopArray {
        int nstops;
        TkGradientStop **stops; /* Array of pointers to GradientStop. */
    } TkGradientStopArray;

/*
 * TkLinearGradientFill --
 */
    typedef struct TkLinearGradientFill {
        TkPathRect *transitionPtr;      /* Actually not a proper rect but a vector. */
        int method;
        int fillRule;          /* Not yet used. */
        int units;
        TkGradientStopArray *stopArrPtr;
    } TkLinearGradientFill;

/*
 * TkRadialTransition --
 */
    typedef struct TkRadialTransition {
        double centerX;
        double centerY;
        double radius;
        double focalX;
        double focalY;
    } TkRadialTransition;

/*
 * TkRadialGradientFill --
 */
    typedef struct TkRadialGradientFill {
        TkRadialTransition *radialPtr;
        int method;
        int fillRule;          /* Not yet used. */
        int units;
        TkGradientStopArray *stopArrPtr;
    } TkRadialGradientFill;

/*
 * Tk_PathCanvas_ is just a dummy which is never defined anywhere.
 * This happens to work because Tk_PathCanvas is a pointer.
 * Its reason is to hide the internals of TkPathCanvas to item code.
 */
    typedef struct Tk_PathCanvas_ *Tk_PathCanvas;

/*
 * TkPathGradientMaster --
 *
 * This is the main record for a gradient object.
 */
    typedef struct TkPathGradientMaster {
        int type;              /* Any of TK_PATH_GRADIENTTYPE_LINEAR or TK_PATH_GRADIENTTYPE_RADIAL */
        Tk_OptionTable optionTable;
        Tk_Uid name;
        Tcl_Obj *transObj;
        Tcl_Obj *stopsObj;
        TkPathMatrix *matrixPtr;        /*  a  b   default (NULL): 1 0
                                         * c  d           0 1
                                         * tx ty            0 0 */

        struct TkPathGradientInst *instancePtr;
        /* Pointer to first in list of instances
         * derived from this gradient name. */
        union {                /* Depending on the 'type'. */
            TkLinearGradientFill linearFill;
            TkRadialGradientFill radialFill;
        };
    } TkPathGradientMaster;

    typedef void (
        TkPathGradientChangedProc) (
        ClientData clientData,
        int flags);

/*
 * TkPathGradientInst --
 *
 * This defines an instance of a gradient with specified name and hash table.
 */
    typedef struct TkPathGradientInst {
        struct TkPathGradientMaster *masterPtr;
        /* Each instance also points to the actual
         * TkPathGradientMaster in order to remove itself
         * from its linked list. */
        TkPathGradientChangedProc *changeProc;
        /* Code in item to call when gradient changes
         * in a way that affects redisplay. */
        ClientData clientData; /* Argument to pass to changeProc. */
        struct TkPathGradientInst *nextPtr;
        /* Next in list of all gradient instances
         * associated with the same gradient name. */
    } TkPathGradientInst;

/*
 * TkPathColor --
 *
 * Only one of color and gradientInstPtr must be non NULL!
 */
    typedef struct TkPathColor {
        XColor *color;         /* Foreground color for filling. */
        TkPathGradientInst *gradientInstPtr;
        /* This is an instance of a gradient.
         * It points to the actual gradient object, the master. */
    } TkPathColor;

#define TK_PATH_STYLE_OPTION_INDEX_END 17       /* Use this for item specific flags */

/*
 * Tk_PathStyle --
 */
    typedef struct Tk_PathStyle {
        Tk_OptionTable optionTable;     /* Not used for canvas. */
        Tk_Uid name;           /* Not used for canvas. */
        int mask;              /* Bits set for actual options modified. */
        XColor *strokeColor;   /* Stroke color. */
        double strokeWidth;    /* Width of stroke. */
        double strokeOpacity;
        int offset;            /* Dash offset */
        TkPathDash *dashPtr;   /* Dash pattern. */
        int capStyle;          /* Cap style for stroke. */
        int joinStyle;         /* Join style for stroke. */
        double miterLimit;
        Tcl_Obj *fillObj;      /* This is just used for option parsing. */
        TkPathColor *fill;     /* Record XColor + TkPathGradientInst. */
        double fillOpacity;
        int fillRule;          /* WindingRule or EvenOddRule. */
        TkPathMatrix *matrixPtr;        /*  a  b   default (NULL): 1 0
                                         * c  d           0 1
                                         * tx ty            0 0 */
        struct TkPathStyleInst *instancePtr;
        /* Pointer to first in list of instances
         * derived from this style name. */
    } Tk_PathStyle;

    typedef void (
        TkPathStyleChangedProc) (
        ClientData clientData,
        int flags);

/*
 * TkPathStyleInst --
 *
 * This defines an instance of a style with specified name and hash table.
 */
    typedef struct TkPathStyleInst {
        struct Tk_PathStyle *masterPtr;
        /* Each instance also points to the actual
         * Tk_PathStyle in order to remove itself
         * from its linked list. */
        TkPathStyleChangedProc *changeProc;
        /* Code in item to call when style changes
         * in a way that affects redisplay. */
        ClientData clientData; /* Argument to pass to changeProc. */
        struct TkPathStyleInst *nextPtr;
        /* Next in list of all style instances
         * associated with the same style name. */
    } TkPathStyleInst;

/*
 *--------------------------------------------------------------
 *
 * Procedure prototypes and structures used for defining new canvas items:
 *
 *--------------------------------------------------------------
 */

    typedef enum {
        TK_PATHSTATE_NULL = -1, TK_PATHSTATE_ACTIVE, TK_PATHSTATE_DISABLED,
        TK_PATHSTATE_NORMAL, TK_PATHSTATE_HIDDEN
    } Tk_PathState;

/*
 * Tk_PathSmoothMethod --
 */
    typedef struct Tk_PathSmoothMethod {
        const char *name;
        int (
            *coordProc) (
            Tk_PathCanvas canvas,
            double *pointPtr,
            int numPoints,
            int numSteps,
            XPoint xPoints[],
            double dblPoints[]);
        void (
            *postscriptProc) (
            Tcl_Interp * interp,
            Tk_PathCanvas canvas,
            double *coordPtr,
            int numPoints,
            int numSteps);
    } Tk_PathSmoothMethod;

/*
 * For each item in a canvas widget there exists one record with the following
 * structure. Each actual item is represented by a record with the following
 * stuff at its beginning, plus additional type-specific stuff after that.
 */

#define TK_PATHTAG_SPACE 3

/*
 * Tk_PathTags --
 */
    typedef struct Tk_PathTags {
        Tk_Uid *tagPtr;        /* Pointer to array of tags. */
        int tagSpace;          /* Total amount of tag space available at
                                * tagPtr. */
        int numTags;           /* Number of tag slots actually used at
                                * *tagPtr. */
    } Tk_PathTags;

/*
 * Tk_PathItem --
 */
    typedef struct Tk_PathItem {
        int id;                /* Unique identifier for this item (also
                                * serves as first tag for item). */
        Tk_OptionTable optionTable;     /* Option table */
        struct Tk_PathItem *nextPtr;    /* Next sibling in display list of this group.
                                         * Later items in list are drawn on
                                         * top of earlier ones. */
        struct Tk_PathItem *prevPtr;    /* Previous sibling in display list of this group. */
        struct Tk_PathItem *parentPtr;
        /* Parent of item or NULL if root. */
        struct Tk_PathItem *firstChildPtr;
        /* First child item, only for groups. */
        struct Tk_PathItem *lastChildPtr;
        /* Last child item, only for groups. */
        Tcl_Obj *parentObj;    /*   */
        Tk_PathTags *pathTagsPtr;       /* Allocated struct for storing tags.
                                         * This is needed by the custom option handling. */

        struct Tk_PathItemType *typePtr;        /* Table of procedures that implement this
                                                 * type of item. */
        int x1, y1, x2, y2;    /* Bounding box for item, in integer canvas
                                * units. Set by item-specific code and
                                * guaranteed to contain every pixel drawn in
                                * item. Item area includes x1 and y1 but not
                                * x2 and y2. */
        Tk_PathState state;    /* State of item. */
        TkPathRect bbox;       /* Bounding box with zero width outline.
                                * Untransformed coordinates. */
        TkPathRect totalBbox;  /* Bounding box including stroke.
                                * Untransformed coordinates. */
        char *reserved1;       /* reserved for future use */
        int redraw_flags;      /* Some flags used in the canvas */

        /*
         *------------------------------------------------------------------
         * Starting here is additional type-specific stuff; see the declarations
         * for individual types to see what is part of each type. The actual space
         * below is determined by the "itemInfoSize" of the type's Tk_PathItemType
         * record.
         *------------------------------------------------------------------
         */
    } Tk_PathItem;

/*
 * Records of the following type are used to describe a type of item (e.g.
 * lines, circles, etc.) that can form part of a canvas widget.
 */

    typedef int Tk_PathItemCreateProc(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int objc,
        Tcl_Obj * const objv[]);
    typedef int Tk_PathItemConfigureProc(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int objc,
        Tcl_Obj * const objv[],
        int flags);
    typedef int Tk_PathItemCoordProc(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int objc,
        Tcl_Obj * const objv[]);
    typedef void Tk_PathItemDeleteProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        Display * display);
    typedef void Tk_PathItemDisplayProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        Display * display,
        Drawable dst,
        int x,
        int y,
        int width,
        int height);
    typedef void TkPathItemBboxProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int mask);
    typedef double Tk_PathItemPointProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        double *pointPtr);
    typedef int Tk_PathItemAreaProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        double *rectPtr);
    typedef int Tk_PathItemPdfProc(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int objc,
        Tcl_Obj * const objv[],
        int prepass);
    typedef void Tk_PathItemScaleProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int compensate,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    typedef void Tk_PathItemTranslateProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int compensate,
        double deltaX,
        double deltaY);
    typedef int Tk_PathItemIndexProc(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        char *indexString,
        int *indexPtr);
    typedef void Tk_PathItemCursorProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int index);
    typedef int Tk_PathItemSelectionProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int offset,
        char *buffer,
        int maxBytes);
    typedef void Tk_PathItemInsertProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int beforeThis,
        char *string);
    typedef void Tk_PathItemDCharsProc(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int first,
        int last);

#ifndef __NO_OLD_CONFIG

/*
 * Tk_PathItemType --
 */
    typedef struct Tk_PathItemType {
        const char *name;      /* The name of this type of item, such as
                                * "line". */
        int itemSize;          /* Total amount of space needed for item's
                                * record. */
        Tk_PathItemCreateProc *createProc;
        /* Procedure to create a new item of this
         * type. */
        Tk_OptionSpec *optionSpecs;     /* Pointer to array of option specs for
                                         * this type. Used for returning option
                                         * info. */
        Tk_PathItemConfigureProc *configProc;
        /* Procedure to call to change configuration
         * options. */
        Tk_PathItemCoordProc *coordProc;        /* Procedure to call to get and set the item's
                                                 * coordinates. */
        Tk_PathItemDeleteProc *deleteProc;
        /* Procedure to delete existing item of this
         * type. */
        Tk_PathItemDisplayProc *displayProc;
        /* Procedure to display items of this type. */
        int alwaysRedraw;      /* Non-zero means displayProc should be called
                                * even when the item has been moved
                                * off-screen. */
        TkPathItemBboxProc *bboxProc;
        /* Procedure that is invoked by group items
         * on its children when it has reconfigured in
         * any way that affect the childrens bbox display. */
        Tk_PathItemPointProc *pointProc;
        /* Computes distance from item to a given
         * point. */
        Tk_PathItemAreaProc *areaProc;
        /* Computes whether item is inside, outside,
         * or overlapping an area. */
        Tk_PathItemPdfProc *pdfProc;
        /* Procedure to write a Pdf description
         * for items of this type. */
        Tk_PathItemScaleProc *scaleProc;        /* Procedure to rescale items of this type. */
        Tk_PathItemTranslateProc *translateProc;
        /* Procedure to translate items of this
         * type. */
        Tk_PathItemIndexProc *indexProc;        /* Procedure to determine index of indicated
                                                 * character. NULL if item doesn't support
                                                 * indexing. */
        Tk_PathItemCursorProc *icursorProc;
        /* Procedure to set insert cursor posn to just
         * before a given position. */
        Tk_PathItemSelectionProc *selectionProc;
        /* Procedure to return selection (in STRING
         * format) when it is in this item. */
        Tk_PathItemInsertProc *insertProc;
        /* Procedure to insert something into an
         * item. */
        Tk_PathItemDCharsProc *dCharsProc;
        /* Procedure to delete characters from an
         * item. */
        struct Tk_PathItemType *nextPtr;        /* Used to link types together into a list. */
        int isPathType;        /* False for original canvas item types. */
    } Tk_PathItemType;

#endif

/*
 * Tk_PathCanvasTextInfo --
 *
 * The following structure provides information about the selection and the
 * insertion cursor. It is needed by only a few items, such as those that
 * display text. It is shared by the generic canvas code and the item-specific
 * code, but most of the fields should be written only by the canvas generic
 * code.
 */
    typedef struct Tk_PathCanvasTextInfo {
        Tk_3DBorder selBorder; /* Border and background for selected
                                * characters. Read-only to items.*/
        int selBorderWidth;    /* Width of border around selection. Read-only
                                * to items. */
        XColor *selFgColorPtr; /* Foreground color for selected text.
                                * Read-only to items. */
        Tk_PathItem *selItemPtr;        /* Pointer to selected item. NULL means
                                         * selection isn't in this canvas. Writable by
                                         * items. */
        int selectFirst;       /* Character index of first selected
                                * character. Writable by items. */
        int selectLast;        /* Character index of last selected character.
                                * Writable by items. */
        Tk_PathItem *anchorItemPtr;     /* Item corresponding to "selectAnchor": not
                                         * necessarily selItemPtr. Read-only to
                                         * items. */
        int selectAnchor;      /* Character index of fixed end of selection
                                * (i.e. "select to" operation will use this
                                * as one end of the selection). Writable by
                                * items. */
        Tk_3DBorder insertBorder;       /* Used to draw vertical bar for insertion
                                         * cursor. Read-only to items. */
        int insertWidth;       /* Total width of insertion cursor. Read-only
                                * to items. */
        int insertBorderWidth; /* Width of 3-D border around insert cursor.
                                * Read-only to items. */
        Tk_PathItem *focusItemPtr;      /* Item that currently has the input focus, or
                                         * NULL if no such item. Read-only to items. */
        int gotFocus;          /* Non-zero means that the canvas widget has
                                * the input focus. Read-only to items.*/
        int cursorOn;          /* Non-zero means that an insertion cursor
                                * should be displayed in focusItemPtr.
                                * Read-only to items.*/
    } Tk_PathCanvasTextInfo;

/*
 * Tk_PathOutline --
 */
    typedef struct Tk_PathOutline {
        GC  gc;                /* Graphics context. */
        double width;          /* Width of outline. */
        double activeWidth;    /* Width of outline. */
        double disabledWidth;  /* Width of outline. */
        int offset;            /* Dash offset. */
        Tk_Dash *dashPtr;      /* Dash pattern. */
        Tk_Dash *activeDashPtr; /* Dash pattern if state is active. */
        Tk_Dash *disabledDashPtr;       /* Dash pattern if state is disabled. */

        void *reserved1;       /* Reserved for future expansion. */
        void *reserved2;
        void *reserved3;
        Tk_TSOffset *tsoffsetPtr;       /* Stipple offset for outline. */
        XColor *color;         /* Outline color. */
        XColor *activeColor;   /* Outline color if state is active. */
        XColor *disabledColor; /* Outline color if state is disabled. */
        Pixmap stipple;        /* Outline Stipple pattern. */
        Pixmap activeStipple;  /* Outline Stipple pattern if state is
                                * active. */
        Pixmap disabledStipple; /* Outline Stipple pattern if state is
                                 * disabled. */
    } Tk_PathOutline;

#define TK_PATH_OPTION_SPEC_ARROWLENGTH_DEFAULT  "10.0"
#define TK_PATH_OPTION_SPEC_ARROWWIDTH_DEFAULT    "5.0"
#define TK_PATH_OPTION_SPEC_ARROWFILL_DEFAULT     "0.7"

#define TK_PATH_OPTION_SPEC_STARTARROW(Item)                \
    {TK_OPTION_BOOLEAN, "-startarrow", NULL, NULL,            \
    "0", -1, Tk_Offset(Item, startarrow.arrowEnabled),        \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_STARTARROWLENGTH(Item)                \
    {TK_OPTION_DOUBLE, "-startarrowlength", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWLENGTH_DEFAULT, -1,            \
    Tk_Offset(Item, startarrow.arrowLength),            \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_STARTARROWWIDTH(Item)                \
    {TK_OPTION_DOUBLE, "-startarrowwidth", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWWIDTH_DEFAULT, -1,            \
    Tk_Offset(Item, startarrow.arrowWidth),                \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_STARTARROWFILL(Item)                \
    {TK_OPTION_DOUBLE, "-startarrowfill", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWFILL_DEFAULT, -1,                \
    Tk_Offset(Item, startarrow.arrowFillRatio),            \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_ENDARROW(Item)                    \
    {TK_OPTION_BOOLEAN, "-endarrow", NULL, NULL,            \
    "0", -1, Tk_Offset(Item, endarrow.arrowEnabled),        \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_ENDARROWLENGTH(Item)                \
    {TK_OPTION_DOUBLE, "-endarrowlength", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWLENGTH_DEFAULT, -1,            \
    Tk_Offset(Item, endarrow.arrowLength),                \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_ENDARROWWIDTH(Item)                \
    {TK_OPTION_DOUBLE, "-endarrowwidth", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWWIDTH_DEFAULT, -1,            \
    Tk_Offset(Item, endarrow.arrowWidth),                \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_ENDARROWFILL(Item)                \
    {TK_OPTION_DOUBLE, "-endarrowfill", NULL, NULL,            \
    TK_PATH_OPTION_SPEC_ARROWFILL_DEFAULT, -1,                \
    Tk_Offset(Item, endarrow.arrowFillRatio),            \
    0, 0, 0}

#define TK_PATH_OPTION_SPEC_STARTARROW_GRP(Item)        \
    TK_PATH_OPTION_SPEC_STARTARROW(Item),        \
    TK_PATH_OPTION_SPEC_STARTARROWLENGTH(Item),    \
    TK_PATH_OPTION_SPEC_STARTARROWWIDTH(Item),        \
    TK_PATH_OPTION_SPEC_STARTARROWFILL(Item)

#define TK_PATH_OPTION_SPEC_ENDARROW_GRP(Item)        \
    TK_PATH_OPTION_SPEC_ENDARROW(Item),        \
    TK_PATH_OPTION_SPEC_ENDARROWLENGTH(Item),        \
    TK_PATH_OPTION_SPEC_ENDARROWWIDTH(Item),        \
    TK_PATH_OPTION_SPEC_ENDARROWFILL(Item)

    typedef struct TkPathTagSearchExpr_s TkPathTagSearchExpr;

/*
 * TkPathTagSearchExpr_s --
 */
    struct TkPathTagSearchExpr_s {
        TkPathTagSearchExpr *next;      /* For linked lists of expressions - used in
                                         * bindings. */
        Tk_Uid uid;            /* The uid of the whole expression. */
        Tk_Uid *uids;          /* Expresion compiled to an array of uids. */
        int allocated;         /* Available space for array of uids. */
        int length;            /* Length of expression. */
        int index;             /* Current position in expression
                                * evaluation. */
        int match;             /* This expression matches event's item's
                                * tags. */
    };

/*
 * Opaque platform dependent struct.
 */
    typedef ClientData TkPathContext;

/*
 * TkPathCanvas --
 *
 * The record below describes a canvas widget. It is made available to the
 * item functions so they can access certain shared fields such as the overall
 * displacement and scale factor for the canvas.
 */
    typedef struct TkPathCanvas {
        Tk_Window *win;
        Display *display;
        Tcl_Interp *interp;

        Tk_PathItem *rootItemPtr;       /* The root item with id 0, always there. */

        /*
         * Information used when displaying widget:
         */

        int borderWidth;       /* Width of 3-D border around window. *
                                * Integer value corresponding to
                                * borderWidthPtr. Always >= 0. */
        Tk_3DBorder bgBorder;  /* Used for canvas background. */
        int relief;            /* Indicates whether window as a whole is
                                * raised, sunken, or flat. */
        int highlightWidth;    /* Integer value corresponding to
                                * highlightWidthPtr. Always >= 0. */
        XColor *highlightBgColorPtr;
        /* Color for drawing traversal highlight area
         * when highlight is off. */
        XColor *highlightColorPtr;      /* Color for drawing traversal highlight. */
        int inset;             /* Total width of all borders, including
                                * traversal highlight and 3-D border.
                                * Indicates how much interior stuff must be
                                * offset from outside edges to leave room for
                                * borders. */
        GC  pixmapGC;          /* Used to copy bits from a pixmap to the
                                * screen and also to clear the pixmap. */
        int width, height;     /* Dimensions to request for canvas window,
                                * specified in pixels. */
        int redrawX1, redrawY1; /* Upper left corner of area to redraw, in
                                 * pixel coordinates. Border pixels are
                                 * included. Only valid if REDRAW_PENDING flag
                                 * is set. */
        int redrawX2, redrawY2; /* Lower right corner of area to redraw, in
                                 * integer canvas coordinates. Border pixels
                                 * will *not* be redrawn. */
        int confine;           /* Non-zero means constrain view to keep as
                                * much of canvas visible as possible. */

        /*
         * Information used to manage the selection and insertion cursor:
         */

        Tk_PathCanvasTextInfo textInfo; /* Contains lots of fields; see tk.h for
                                         * details. This structure is shared with the
                                         * code that implements individual items. */
        int insertOnTime;      /* Number of milliseconds cursor should spend
                                * in "on" state for each blink. */
        int insertOffTime;     /* Number of milliseconds cursor should spend
                                * in "off" state for each blink. */
        Tcl_TimerToken insertBlinkHandler;
        /* Timer handler used to blink cursor on and
         * off. */

        /*
         * Transformation applied to canvas as a whole: to compute screen
         * coordinates (X,Y) from canvas coordinates (x,y), do the following:
         *
         * X = x - xOrigin;
         * Y = y - yOrigin;
         */

        int xOrigin, yOrigin;  /* Canvas coordinates corresponding to
                                * upper-left corner of window, given in
                                * canvas pixel units. */
        int drawableXOrigin, drawableYOrigin;
        /* During redisplay, these fields give the
         * canvas coordinates corresponding to the
         * upper-left corner of the drawable where
         * items are actually being drawn (typically a
         * pixmap smaller than the whole window). */

        /*
         * Information used for event bindings associated with items.
         */

        Tk_BindingTable bindingTable;
        /* Table of all bindings currently defined for
         * this canvas. NULL means that no bindings
         * exist, so the table hasn't been created.
         * Each "object" used for this table is either
         * a Tk_Uid for a tag or the address of an
         * item named by id. */
        Tk_PathItem *currentItemPtr;    /* The item currently containing the mouse
                                         * pointer, or NULL if none. */
        Tk_PathItem *newCurrentPtr;     /* The item that is about to become the
                                         * current one, or NULL. This field is used to
                                         * detect deletions of the new current item
                                         * pointer that occur during Leave processing
                                         * of the previous current item. */
        double closeEnough;    /* The mouse is assumed to be inside an item
                                * if it is this close to it. */
        XEvent pickEvent;      /* The event upon which the current choice of
                                * currentItem is based. Must be saved so that
                                * if the currentItem is deleted, can pick
                                * another. */
        int state;             /* Last known modifier state. Used to defer
                                * picking a new current object while buttons
                                * are down. */

        /*
         * Information used for managing scrollbars:
         */

        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 scroll[4];
        /* These four coordinates (x1,y1,x2,y2) define the region
         * that is the 100% area for scrolling (i.e.
         * these numbers determine the size and
         * location of the sliders on scrollbars).
         * Units are pixels in canvas coords. */
        int xScrollIncrement;  /* If >0, defines a grid for horizontal
                                * scrolling. This is the size of the "unit",
                                * and the left edge of the screen will always
                                * lie on an even unit boundary. */
        int yScrollIncrement;  /* If >0, defines a grid for horizontal
                                * scrolling. This is the size of the "unit",
                                * and the left edge of the screen will always
                                * lie on an even unit boundary. */

        /*
         * Information used for scanning:
         */

        int scanX;             /* X-position at which scan started (e.g.
                                * button was pressed here). */
        int scanXOrigin;       /* Value of xOrigin field when scan started. */
        int scanY;             /* Y-position at which scan started (e.g.
                                * button was pressed here). */
        int scanYOrigin;       /* Value of yOrigin field when scan started. */

        /*
         * Information used to speed up searches by remembering the last item
         * created or found with an item id search.
         */

        Tk_PathItem *hotPtr;   /* Pointer to "hot" item (one that's been
                                * recently used. NULL means there's no hot
                                * item. */
        Tk_PathItem *hotPrevPtr;        /* Pointer to predecessor to hotPtr (NULL
                                         * means item is first in list). This is only
                                         * a hint and may not really be hotPtr's
                                         * predecessor. */

        /*
         * Miscellaneous information:
         */

        Tk_Cursor cursor;      /* Current cursor for window, or None. */
        double pixelsPerMM;    /* Scale factor between MM and pixels; used
                                * when converting coordinates. */
        int nextId;            /* Number to use as id for next item created
                                * in widget. */
        Tcl_HashTable idTable; /* Table of integer indices. */
/* @@@ TODO: as pointers instead??? */
        Tcl_HashTable styleTable;       /* Table for styles.
                                         * This defines the namespace for style names. */
        Tcl_HashTable gradientTable;    /* Table for gradients.
                                         * This defines the namespace for gradient names. */
        int styleUid;          /* Running integer used to number style tokens. */
        int gradientUid;       /* Running integer used to number gradient tokens. */
        int tagStyle;
        int flags;

        Tk_PathState canvas_state;      /* State of canvas. */
        TkPathContext context; /* Path context allocated during a redraw. */
        Tk_TSOffset *tsoffsetPtr;
        TkPathTagSearchExpr *bindTagExprs;      /* Linked list of tag expressions used in
                                                 * bindings. */
    } TkPathCanvas;

/*
 * Tk_PathItemEx --
 *
 * This is an extended item record that is used for the new
 * path based items to allow more generic code to be used for them
 * since all of them (?) anyhow include a Tk_PathStyle record.
 */
    typedef struct Tk_PathItemEx {
        Tk_PathItem header;    /* Generic stuff that's the same for all
                                * types.  MUST BE FIRST IN STRUCTURE. */
        Tk_PathCanvas canvas;  /* Canvas containing item. */
        Tk_PathStyle style;    /* Contains most drawing info. */
        Tcl_Obj *styleObj;     /* Object with style name. */
        TkPathStyleInst *styleInst;
        /* The referenced style instance from styleObj. */

        /*
         *------------------------------------------------------------------
         * Starting here is additional type-specific stuff; see the declarations
         * for individual types to see what is part of each type. The actual space
         * below is determined by the "itemInfoSize" of the type's Tk_PathItemType
         * record.
         *------------------------------------------------------------------
         */
    } Tk_PathItemEx;

/*
 * Retrieve TkPathContext from Tk_PathCanvas.
 */

#define ContextOfCanvas(canvas) (((TkPathCanvas *) (canvas))->context)

/*
 * New API option parsing.
 */

#define TK_PATH_DEF_STATE "normal"

/* These MUST be kept in sync with Tk_PathState! */

#define TK_PATH_OPTION_STRING_TABLES_STATE                    \
    static const char *stateStrings[] = {                \
    "active", "disabled", "normal", "hidden", NULL            \
    };

#define TK_PATH_CUSTOM_OPTION_TAGS                        \
    static Tk_ObjCustomOption tagsCO = {                \
        "tags",                                \
        Tk_PathCanvasTagsOptionSetProc,                    \
        Tk_PathCanvasTagsOptionGetProc,                    \
        Tk_PathCanvasTagsOptionRestoreProc,                \
        Tk_PathCanvasTagsOptionFreeProc,                \
        (ClientData) NULL                        \
    };

#define TK_PATH_OPTION_SPEC_PARENT                        \
    {TK_OPTION_STRING, "-parent", NULL, NULL,                \
        "0", Tk_Offset(Tk_PathItem, parentObj), -1,            \
    0, 0, TK_PATH_CORE_OPTION_PARENT}

#define TK_PATH_OPTION_SPEC_CORE(typeName)                    \
    {TK_OPTION_STRING_TABLE, "-state", NULL, NULL,            \
        TK_PATH_DEF_STATE, -1, Tk_Offset(Tk_PathItem, state),        \
        0, (ClientData) stateStrings, 0},                \
    {TK_OPTION_STRING, "-style", (char *) NULL, (char *) NULL,        \
    "", Tk_Offset(typeName, styleObj), -1,                \
    TK_OPTION_NULL_OK, 0, TK_PATH_CORE_OPTION_STYLENAME},        \
    {TK_OPTION_CUSTOM, "-tags", NULL, NULL,                \
    NULL, -1, Tk_Offset(Tk_PathItem, pathTagsPtr),            \
    TK_OPTION_NULL_OK, (ClientData) &tagsCO, TK_PATH_CORE_OPTION_TAGS}

/*
 * Information used for parsing configuration options.
 * Mask bits for options changed.
 */

    enum {
        TK_PATH_STYLE_OPTION_FILL = (1L << 0),
        TK_PATH_STYLE_OPTION_FILL_OFFSET = (1L << 1),
        TK_PATH_STYLE_OPTION_FILL_OPACITY = (1L << 2),
        TK_PATH_STYLE_OPTION_FILL_RULE = (1L << 3),
        TK_PATH_STYLE_OPTION_FILL_STIPPLE = (1L << 4),
        TK_PATH_STYLE_OPTION_MATRIX = (1L << 5),
        TK_PATH_STYLE_OPTION_STROKE = (1L << 6),
        TK_PATH_STYLE_OPTION_STROKE_DASHARRAY = (1L << 7),
        TK_PATH_STYLE_OPTION_STROKE_LINECAP = (1L << 8),
        TK_PATH_STYLE_OPTION_STROKE_LINEJOIN = (1L << 9),
        TK_PATH_STYLE_OPTION_STROKE_MITERLIMIT = (1L << 10),
        TK_PATH_STYLE_OPTION_STROKE_OFFSET = (1L << 11),
        TK_PATH_STYLE_OPTION_STROKE_OPACITY = (1L << 12),
        TK_PATH_STYLE_OPTION_STROKE_STIPPLE = (1L << 13),
        TK_PATH_STYLE_OPTION_STROKE_WIDTH = (1L << 14),
        TK_PATH_CORE_OPTION_PARENT = (1L << 15),
        TK_PATH_CORE_OPTION_STYLENAME = (1L << 16),
        TK_PATH_CORE_OPTION_TAGS = (1L << 17),
    };
/* @@@ TODO: Much more to be added here! */

    enum TkFontWeight {
        TK_PATH_TEXT_WEIGHT_NORMAL,
        TK_PATH_TEXT_WEIGHT_BOLD
    };

    enum TkFontSlant {
        TK_PATH_TEXT_SLANT_NORMAL,
        TK_PATH_TEXT_SLANT_ITALIC,
        TK_PATH_TEXT_SLANT_OBLIQUE
    };

/*
 * Tk_PathTextStyle --
 */
    typedef struct Tk_PathTextStyle {
        char *fontFamily;
        double fontSize;
        enum TkFontWeight fontWeight;
        enum TkFontSlant fontSlant;
    } Tk_PathTextStyle;

#define TK_PATH_STYLE_CUSTOM_OPTION_MATRIX                \
    static Tk_ObjCustomOption matrixCO = {            \
        "matrix",                        \
        TkPathMatrixSetOption,                    \
        TkPathMatrixGetOption,                    \
        TkPathMatrixRestoreOption,                    \
        TkPathMatrixFreeOption,                    \
        (ClientData) NULL                    \
    };

#define TK_PATH_STYLE_CUSTOM_OPTION_DASH                \
    static Tk_ObjCustomOption dashCO = {            \
        "dasharray",                        \
        Tk_PathDashOptionSetProc,                \
        Tk_PathDashOptionGetProc,                \
        Tk_PathDashOptionRestoreProc,                \
        Tk_PathDashOptionFreeProc,                \
        (ClientData) NULL                    \
    };

#define TK_PATH_STYLE_CUSTOM_OPTION_PATHCOLOR            \
    static Tk_ObjCustomOption pathColorCO = {            \
        "pathcolor",                        \
        TkPathColorSetOption,                    \
        TkPathColorGetOption,                    \
        TkPathColorRestoreOption,                    \
        TkPathColorFreeOption,                    \
        (ClientData) NULL                    \
    };

#define TK_PATH_STYLE_CUSTOM_OPTION_RECORDS            \
    TK_PATH_STYLE_CUSTOM_OPTION_MATRIX                 \
    TK_PATH_STYLE_CUSTOM_OPTION_DASH

/*
 * These must be kept in sync with defines in X.h!
 */

#define TK_PATH_OPTION_STRING_TABLES_FILL                \
    static const char *fillRuleST[] = {                \
    "evenodd", "nonzero", (char *) NULL            \
    };

#define TK_PATH_OPTION_STRING_TABLES_STROKE            \
    static const char *lineCapST[] = {                \
    "notlast", "butt", "round", "projecting", (char *) NULL    \
    };                                \
    static const char *lineJoinST[] = {                \
    "miter", "round", "bevel", (char *) NULL        \
    };

#define TK_PATH_OPTION_SPEC_STYLENAME(typeName)                \
    {TK_OPTION_STRING, "-style", NULL, NULL,                \
        "", Tk_Offset(typeName, styleObj), -1, TK_OPTION_NULL_OK, 0, 0}

/*
 * This assumes that we have a Tk_PathStyle struct element named 'style'.
 */

#define TK_PATH_OPTION_SPEC_STYLE_FILL(typeName, theColor)            \
    {TK_OPTION_STRING, "-fill", NULL, NULL,                \
    theColor, Tk_Offset(typeName, style.fillObj), -1,        \
    TK_OPTION_NULL_OK, 0, TK_PATH_STYLE_OPTION_FILL},            \
    {TK_OPTION_DOUBLE, "-fillopacity", NULL, NULL,            \
        "1.0", -1, Tk_Offset(typeName, style.fillOpacity), 0, 0,        \
        TK_PATH_STYLE_OPTION_FILL_OPACITY},                                \
    {TK_OPTION_STRING_TABLE, "-fillrule", NULL, NULL,            \
        "nonzero", -1, Tk_Offset(typeName, style.fillRule),             \
        0, (ClientData) fillRuleST, TK_PATH_STYLE_OPTION_FILL_RULE}

#define TK_PATH_OPTION_SPEC_STYLE_MATRIX(typeName)                         \
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,                \
    NULL, -1, Tk_Offset(typeName, style.matrixPtr),            \
    TK_OPTION_NULL_OK, (ClientData) &matrixCO, TK_PATH_STYLE_OPTION_MATRIX}

#define TK_PATH_OPTION_SPEC_STYLE_STROKE(typeName, theColor)        \
    {TK_OPTION_COLOR, "-stroke", NULL, NULL,                \
        theColor, -1, Tk_Offset(typeName, style.strokeColor),        \
        TK_OPTION_NULL_OK, 0, TK_PATH_STYLE_OPTION_STROKE},        \
    {TK_OPTION_CUSTOM, "-strokedasharray", NULL, NULL,            \
    NULL, -1, Tk_Offset(typeName, style.dashPtr),            \
    0, (ClientData) &dashCO,                    \
        TK_PATH_STYLE_OPTION_STROKE_DASHARRAY},                \
    {TK_OPTION_STRING_TABLE, "-strokelinecap", NULL, NULL,        \
        "butt", -1, Tk_Offset(typeName, style.capStyle),        \
        0, (ClientData) lineCapST, TK_PATH_STYLE_OPTION_STROKE_LINECAP},    \
    {TK_OPTION_STRING_TABLE, "-strokelinejoin", NULL, NULL,        \
        "round", -1, Tk_Offset(typeName, style.joinStyle),        \
        0, (ClientData) lineJoinST, TK_PATH_STYLE_OPTION_STROKE_LINEJOIN}, \
    {TK_OPTION_DOUBLE, "-strokemiterlimit", NULL, NULL,            \
        "4.0", -1, Tk_Offset(typeName, style.miterLimit), 0, 0,        \
        TK_PATH_STYLE_OPTION_STROKE_MITERLIMIT},                           \
    {TK_OPTION_DOUBLE, "-strokeopacity", NULL, NULL,            \
        "1.0", -1, Tk_Offset(typeName, style.strokeOpacity), 0, 0,    \
        TK_PATH_STYLE_OPTION_STROKE_OPACITY},                \
    {TK_OPTION_DOUBLE, "-strokewidth", NULL, NULL,            \
        "1.0", -1, Tk_Offset(typeName, style.strokeWidth), 0, 0,        \
        TK_PATH_STYLE_OPTION_STROKE_WIDTH}

#define TK_PATH_OPTION_SPEC_END                        \
    {TK_OPTION_END, NULL, NULL, NULL,                \
        NULL, 0, -1, 0, (ClientData) NULL, 0}

/* for arrows: */

/* ARROW_BOTH = ARROWS_FIRST | ARROWS_LAST */
    typedef enum {
        TK_PATH_ARROWS_OFF = 0, TK_PATH_ARROWS_ON = 1
    } TkPathArrowState;

/*
 * TkPathArrowDescr --
 */
    typedef struct TkPathArrowDescr {
        TkPathArrowState arrowEnabled;  /* Indicates whether or not to draw arrowheads: off/on */
        double arrowLength;    /* Length of arrowhead. */
        double arrowWidth;     /* width of arrowhead. */
        double arrowFillRatio; /* filled part of arrow head, relative to arrowLengthRel.
                                * 0: special case, arrowhead only 2 line, without fill */
        TkPathPoint *arrowPointsPtr;    /* Points to array of PTS_IN_ARROW points
                                         * describing polygon for arrowhead in line.
                                         * NULL means no arrowhead at current point. */
    } TkPathArrowDescr;

/*
 * Inline function declarations:
 */

/*
 * If stroke width is an integer, widthCode=1,2, move coordinate
 * to pixel boundary if even stroke width, widthCode=2,
 * or to pixel center if odd stroke width, widthCode=1.
 */
#define TK_PATH_DEPIXELIZE(widthCode,x) \
    (!(widthCode) ? (x) : ((int) (floor((x) + 0.001)) + (((widthCode) == 1) ? 0.5 : 0)));

#define GetColorFromPathColor(pcol)\
    (((pcol != NULL) && (pcol->color != NULL)) ? pcol->color : NULL )
#define GetGradientMasterFromPathColor(pcol) \
    (((pcol != NULL) && (pcol->gradientInstPtr != NULL)) ? pcol->gradientInstPtr->masterPtr : NULL )
#define HaveAnyFillFromPathColor(pcol) \
    (((pcol != NULL) && ((pcol->color != NULL) || (pcol->gradientInstPtr != NULL))) ? 1 : 0 )

/*
 * tkpath specific item types.
 */
    MODULE_SCOPE Tk_PathItemType tkPathTypeWindow;
    MODULE_SCOPE Tk_PathItemType tkPathTypePath;
    MODULE_SCOPE Tk_PathItemType tkPathTypeRect;
    MODULE_SCOPE Tk_PathItemType tkPathTypeLine;
    MODULE_SCOPE Tk_PathItemType tkPathTypePolyline;
    MODULE_SCOPE Tk_PathItemType tkPathTypePolygon;
    MODULE_SCOPE Tk_PathItemType tkPathTypeCircle;
    MODULE_SCOPE Tk_PathItemType tkPathTypeEllipse;
    MODULE_SCOPE Tk_PathItemType tkPathTypeImage;
    MODULE_SCOPE Tk_PathItemType tkPathTypeText;
    MODULE_SCOPE Tk_PathItemType tkPathTypeGroup;
    MODULE_SCOPE Tk_PathSmoothMethod tkPathBezierSmoothMethod;

/*
 * Tcl variable and command names
 */
/* Tcl variables */
#define TK_PATHVAR_PREMULTIPLYALPHA "::path::premultiplyalpha"
#define TK_PATHVAR_DEPIXELIZE		"::path::depixelize"
#define TK_PATHVAR_ANTIALIAS		"::path::antialias"
/* Tcl commands */
#define TK_PATHCMD_PIXELALIGN		"::path::pixelalign"
#define TK_PATHCMD_GRADIENT			"::gradient"
#define TK_PATHCMD_PATHGRADIENT		"::path::gradient"
#define TK_PATHCMD_STYLE			"::style"
#define TK_PATHCMD_PATHSTYLE		"::path::style"
#define TK_PATHCMD_PATHSURFACE		"::path::surface"

/*
 * Function declarations:
 */

/* tkPathCanvArrow.c */
    MODULE_SCOPE void TkPathArrowDescrInit(
        TkPathArrowDescr * descr);
    MODULE_SCOPE void TkPathIncludeArrowPointsInRect(
        TkPathRect * bbox,
        TkPathArrowDescr * arrowDescrPtr);
    MODULE_SCOPE void TkPathIncludeArrowPoints(
        Tk_PathItem * itemPtr,
        TkPathArrowDescr * arrowDescrPtr);
    MODULE_SCOPE void TkPathPreconfigureArrow(
        TkPathPoint * pf,
        TkPathArrowDescr * arrowDescr);
    MODULE_SCOPE TkPathPoint TkPathConfigureArrow(
        TkPathPoint pf,
        TkPathPoint pl,
        TkPathArrowDescr * arrow,
        Tk_PathStyle * lineStyle,
        int updateFirstPoint);
    MODULE_SCOPE void TkPathTranslateArrow(
        TkPathArrowDescr * arrowDescr,
        double deltaX,
        double deltaY);
    MODULE_SCOPE void TkPathScaleArrow(
        TkPathArrowDescr * arrowDescr,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void TkPathFreeArrow(
        TkPathArrowDescr * arrowDescr);
    MODULE_SCOPE int TkPathGetSegmentsFromPathAtomList(
        TkPathAtom * firstAtom,
        TkPathPoint ** firstPt,
        TkPathPoint * secondPt,
        TkPathPoint * penultPt,
        TkPathPoint ** lastPt);
    MODULE_SCOPE TkPathAtom *TkPathMakePathAtomsFromArrow(
        TkPathArrowDescr * arrowDescr);
    MODULE_SCOPE void TkPathDisplayArrow(
        Tk_PathCanvas canvas,
        TkPathArrowDescr * arrowDescr,
        Tk_PathStyle * const style,
        TkPathMatrix * mPtr,
        TkPathRect * bboxPtr);
    MODULE_SCOPE void TkPathPaintArrow(
        TkPathContext context,
        TkPathArrowDescr * arrowDescr,
        Tk_PathStyle * const style,
        TkPathRect * bboxPtr);

/* tkPathCanvas.c */
    MODULE_SCOPE int Tk_PathCanvasObjCmd(
        ClientData clientData,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE void Tk_PathCanvasEventuallyRedraw(
        Tk_PathCanvas canvas,
        int x1,
        int y1,
        int x2,
        int y2);
    MODULE_SCOPE void TkPathCanvasSetParent(
        Tk_PathItem * parentPtr,
        Tk_PathItem * itemPtr);
    MODULE_SCOPE int TkPathCanvasFindGroup(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tcl_Obj * parentObj,
        Tk_PathItem ** parentPtrPtr);
    MODULE_SCOPE void TkPathCanvasGroupBbox(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int *x1Ptr,
        int *y1Ptr,
        int *x2Ptr,
        int *y2Ptr);
    MODULE_SCOPE Tk_PathItem *TkPathCanvasItemIteratorNext(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE Tk_PathItem *TkPathCanvasItemIteratorPrev(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE void TkPathCanvasItemDetach(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE void TkPathGroupItemConfigured(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int mask);
    MODULE_SCOPE void TkPathCanvasTranslateGroup(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int compensate,
        double deltaX,
        double deltaY);
    MODULE_SCOPE void TkPathCanvasScaleGroup(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        int compensate,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void TkPathCanvasSetParentToRoot(
        Tk_PathItem * itemPtr);

/* tkPathCanvEllipse.c */

/* tkPathCanvGroup.c */
    MODULE_SCOPE void TkPathCanvasSetGroupDirtyBbox(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE void TkPathCanvasUpdateGroupBbox(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr);

/* tkPathCanvImage.c */

/* tkPathCanvLine.c */

/* tkPathCanvPath.c */

/* tkPathCanvPoly.c */

/* tkPathCanvRect.c */

/* tkPathCanvText.c */

/* tkPathCanvWindow.c */

/* tkPathGeneric.c */
    MODULE_SCOPE int TkPathParseToAtoms(
        Tcl_Interp * interp,
        Tcl_Obj * listObjPtr,
        TkPathAtom ** atomPtrPtr,
        int *lenPtr);
    MODULE_SCOPE void TkPathFreeAtoms(
        TkPathAtom * pathAtomPtr);
    MODULE_SCOPE int TkPathNormalize(
        Tcl_Interp * interp,
        TkPathAtom * atomPtr,
        Tcl_Obj ** listObjPtrPtr);
    MODULE_SCOPE int TkPathMakePath(
        TkPathContext ctx,
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr);
    MODULE_SCOPE void TkPathArcToUsingBezier(
        TkPathContext ctx,
        double rx,
        double ry,
        double phiDegrees,
        char largeArcFlag,
        char sweepFlag,
        double x2,
        double y2);
    MODULE_SCOPE int TkPathPdfNumber(
        Tcl_Obj * ret,
        int fracDigis,
        double number,
        const char *append);
    MODULE_SCOPE int TkPathPdfColor(
        Tcl_Obj * ret,
        XColor * colorPtr,
        const char *command);
    MODULE_SCOPE int TkPathPdfArrow(
        Tcl_Interp * interp,
        TkPathArrowDescr * arrow,
        Tk_PathStyle * const style);
    MODULE_SCOPE int TkPathPdf(
        Tcl_Interp * interp,
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr,
        TkPathRect * bboxPtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE Tcl_Obj *TkPathExtGS(
        Tk_PathStyle * stylePtr,
        long *smaskRef);
    MODULE_SCOPE TkPathAtom *TkPathNewMoveToAtom(
        double x,
        double y);
    MODULE_SCOPE TkPathAtom *TkPathNewLineToAtom(
        double x,
        double y);
    MODULE_SCOPE TkPathAtom *TkPathNewArcAtom(
        double radX,
        double radY,
        double angle,
        char largeArcFlag,
        char sweepFlag,
        double x,
        double y);
    MODULE_SCOPE TkPathAtom *TkPathNewQuadBezierAtom(
        double ctrlX,
        double ctrlY,
        double anchorX,
        double anchorY);
    MODULE_SCOPE TkPathAtom *TkPathNewCurveToAtom(
        double ctrlX1,
        double ctrlY1,
        double ctrlX2,
        double ctrlY2,
        double anchorX,
        double anchorY);
    MODULE_SCOPE TkPathAtom *TkPathNewRectAtom(
        double pointsPtr[]);
    MODULE_SCOPE TkPathAtom *TkPathNewCloseAtom(
        double x,
        double y);
    MODULE_SCOPE int TkPathPixelAlignObjCmd(
        ClientData clientData,
        Tcl_Interp * interp,
        int objc,
        Tcl_Obj * const objv[]);

/* tkPathGradient.c */
    MODULE_SCOPE TkPathColor *TkPathGetPathColorStatic(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj * nameObj);
    MODULE_SCOPE TkPathGradientInst *TkPathGetGradient(
        Tcl_Interp * interp,
        const char *name,
        Tcl_HashTable * tablePtr,
        TkPathGradientChangedProc * changeProc,
        ClientData clientData);
    MODULE_SCOPE void TkPathFreeGradient(
        TkPathGradientInst * gradientPtr);
    MODULE_SCOPE void TkPathGradientChanged(
        TkPathGradientMaster * masterPtr,
        int flags);
    MODULE_SCOPE void TkPathGradientInit(
        Tcl_Interp * interp);
    MODULE_SCOPE void TkPathGradientPaint(
        TkPathContext ctx,
        TkPathRect * bbox,
        TkPathGradientMaster * gradientStylePtr,
        int fillRule,
        double fillOpacity);
    MODULE_SCOPE void TkPathGradientInit(
        Tcl_Interp * interp);
    MODULE_SCOPE void TkPathGradientPaint(
        TkPathContext ctx,
        TkPathRect * bbox,
        TkPathGradientMaster * gradientStylePtr,
        int fillRule,
        double fillOpacity);
    MODULE_SCOPE int TkPathCanvasGradientObjCmd(
        Tcl_Interp * interp,
        TkPathCanvas * canvasPtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE void TkPathCanvasGradientsFree(
        TkPathCanvas * canvasPtr);

/* tkPathInit.c */
    MODULE_SCOPE int TkPathSurfaceInit(
        Tcl_Interp * interp);

/* tkPathStyle.c */
    MODULE_SCOPE TkPathDash *TkPathDashNew(
        Tcl_Interp * interp,
        Tcl_Obj * dashObjPtr);
    MODULE_SCOPE void TkPathDashFree(
        TkPathDash * dashPtr);
    MODULE_SCOPE Tcl_Obj *Tk_PathDashOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void Tk_PathDashOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void Tk_PathDashOptionFreeProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);
    MODULE_SCOPE int TkPathConfigStyle(
        Tcl_Interp * interp,
        Tk_PathStyle * stylePtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int TkPathStyleMergeStyleStatic(
        Tcl_Interp * interp,
        Tcl_Obj * styleObj,
        Tk_PathStyle * dstStyle,
        long flags);
    MODULE_SCOPE void TkPathStyleMergeStyles(
        Tk_PathStyle * srcStyle,
        Tk_PathStyle * dstStyle,
        long flags);
    MODULE_SCOPE void TkPathInitStyle(
        Tk_PathStyle * style);
    MODULE_SCOPE void TkPathDeleteStyle(
        Tk_PathStyle * style);
    MODULE_SCOPE TkPathStyleInst *TkPathGetStyle(
        Tcl_Interp * interp,
        const char *name,
        Tcl_HashTable * tablePtr,
        TkPathStyleChangedProc * changeProc,
        ClientData clientData);
    MODULE_SCOPE void TkPathFreeStyle(
        TkPathStyleInst * stylePtr);
    MODULE_SCOPE void TkPathStyleChanged(
        Tk_PathStyle * masterPtr,
        int flags);
    MODULE_SCOPE void TkPathStyleInit(
        Tcl_Interp * interp);
    MODULE_SCOPE int Tk_PathDashOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE void TkPathStylesFree(
        Tk_Window tkwin,
        Tcl_HashTable * hashTablePtr);
    MODULE_SCOPE int TkPathCanvasStyleObjCmd(
        Tcl_Interp * interp,
        TkPathCanvas * canvasPtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int TkPathMatrixSetOption(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *TkPathMatrixGetOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void TkPathMatrixRestoreOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void TkPathMatrixFreeOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);
    MODULE_SCOPE int TkPathColorSetOption(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *TkPathColorGetOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void TkPathColorRestoreOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void TkPathColorFreeOption(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);

/* tkPathSurface.c */

/* tkPathUtil.c */
    MODULE_SCOPE Tk_TSOffset *TkPathOffsetNew(
        Tcl_Interp * interp,
        ClientData clientData,
        Tk_Window tkwin,
        Tcl_Obj * offsetObj);
    MODULE_SCOPE void TkPathMakePrectAtoms(
        double *pointsPtr,
        double rx,
        double ry,
        TkPathAtom ** atomPtrPtr);
    MODULE_SCOPE void TkPathDrawPath(
        TkPathContext context,
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr,
        TkPathMatrix * mPtr,
        TkPathRect * bboxPtr);
    MODULE_SCOPE void TkPathPaintPath(
        TkPathContext context,
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr,
        TkPathRect * bboxPtr);
    MODULE_SCOPE TkPathRect TkPathGetTotalBbox(
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr);
    MODULE_SCOPE TkPathColor *TkPathNewPathColor(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj * nameObj);
    MODULE_SCOPE TkPathColor *TkPathGetPathColor(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj * nameObj,
        Tcl_HashTable * tablePtr,
        TkPathGradientChangedProc * changeProc,
        ClientData clientData);
    MODULE_SCOPE void TkPathFreePathColor(
        TkPathColor * colorPtr);
    MODULE_SCOPE void TkPathCopyBitsARGB(
        unsigned char *from,
        unsigned char *to,
        int width,
        int height,
        int bytesPerRow);
    MODULE_SCOPE void TkPathCopyBitsBGRA(
        unsigned char *from,
        unsigned char *to,
        int width,
        int height,
        int bytesPerRow);
    MODULE_SCOPE void TkPathCopyBitsPremultipliedAlphaRGBA(
        unsigned char *from,
        unsigned char *to,
        int width,
        int height,
        int bytesPerRow);
    MODULE_SCOPE void TkPathCopyBitsPremultipliedAlphaARGB(
        unsigned char *from,
        unsigned char *to,
        int width,
        int height,
        int bytesPerRow);
    MODULE_SCOPE void TkPathCopyBitsPremultipliedAlphaBGRA(
        unsigned char *from,
        unsigned char *to,
        int width,
        int height,
        int bytesPerRow);
    MODULE_SCOPE int TkPathTableLookup(
        TkLookupTable * map,
        int n,
        int from);
    MODULE_SCOPE void TkPathMMulTMatrix(
        TkPathMatrix * m1,
        TkPathMatrix * m2);
    MODULE_SCOPE int TkPathGetTMatrix(
        Tcl_Interp * interp,
        const char *list,
        TkPathMatrix * matrixPtr);
    MODULE_SCOPE int TkPathGetTclObjFromTMatrix(
        Tcl_Interp * interp,
        TkPathMatrix * matrixPtr,
        Tcl_Obj ** listObjPtrPtr);
    MODULE_SCOPE int TkPathGenericCmdDispatcher(
        Tcl_Interp * interp,
        Tk_Window tkwin,
        int objc,
        Tcl_Obj * const objv[],
        char *baseName,
        int *baseNameUIDPtr,
        Tcl_HashTable * hashTablePtr,
        Tk_OptionTable optionTable,
        char *(*createAndConfigProc) (Tcl_Interp * interp,
            char *name,
            int objc,
            Tcl_Obj * const objv[]),
        void (*configNotifyProc) (char *recordPtr,
            int mask,
            int objc,
            Tcl_Obj * const objv[]),
        void (*freeProc) (Tcl_Interp * interp,
            char *recordPtr));
    MODULE_SCOPE int TkPathObjectIsEmpty(
        Tcl_Obj * objPtr);
    MODULE_SCOPE void TkPathIncludePoint(
        Tk_PathItem * itemPtr,
        double *pointPtr);
    MODULE_SCOPE void TkPathBezierScreenPoints(
        Tk_PathCanvas canvas,
        double control[],
        int numSteps,
        XPoint * xPointPtr);
    MODULE_SCOPE void TkPathBezierPoints(
        double control[],
        int numSteps,
        double *coordPtr);
    MODULE_SCOPE int TkPathMakeBezierCurve(
        Tk_PathCanvas canvas,
        double *pointPtr,
        int numPoints,
        int numSteps,
        XPoint xPoints[],
        double dblPoints[]);
    MODULE_SCOPE int TkPathMakeRawCurve(
        Tk_PathCanvas canvas,
        double *pointPtr,
        int numPoints,
        int numSteps,
        XPoint xPoints[],
        double dblPoints[]);
    MODULE_SCOPE int TkPathOffsetOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *TkPathOffsetOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void TkPathOffsetOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void TkPathOffsetOptionFreeProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);
    MODULE_SCOPE int Tk_PathPixelOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *Tk_PathPixelOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void Tk_PathPixelOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE Tk_Window Tk_PathCanvasTkwin(
        Tk_PathCanvas canvas);
    MODULE_SCOPE void Tk_PathCanvasDrawableCoords(
        Tk_PathCanvas canvas,
        double x,
        double y,
        short *drawableXPtr,
        short *drawableYPtr);
    MODULE_SCOPE void Tk_PathCanvasWindowCoords(
        Tk_PathCanvas canvas,
        double x,
        double y,
        short *screenXPtr,
        short *screenYPtr);
    MODULE_SCOPE int Tk_PathCanvasGetCoord(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        const char *string,
        double *doublePtr);
    MODULE_SCOPE int Tk_PathCanvasGetCoordFromObj(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tcl_Obj * obj,
        double *doublePtr);
    MODULE_SCOPE void Tk_PathCanvasSetStippleOrigin(
        Tk_PathCanvas canvas,
        GC gc);
    MODULE_SCOPE void Tk_PathCanvasSetOffset(
        Tk_PathCanvas canvas,
        GC gc,
        Tk_TSOffset * offset);
    MODULE_SCOPE int TkPathCanvasGetDepth(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE Tk_PathStyle TkPathCanvasInheritStyle(
        Tk_PathItem * itemPtr,
        long flags);
    MODULE_SCOPE void TkPathCanvasFreeInheritedStyle(
        Tk_PathStyle * stylePtr);
    MODULE_SCOPE TkPathMatrix TkPathCanvasInheritTMatrix(
        Tk_PathItem * itemPtr);
    MODULE_SCOPE Tcl_HashTable *TkPathCanvasGradientTable(
        Tk_PathCanvas canvas);
    MODULE_SCOPE Tcl_HashTable *TkPathCanvasStyleTable(
        Tk_PathCanvas canvas);
    MODULE_SCOPE Tk_PathState TkPathCanvasState(
        Tk_PathCanvas canvas);
    MODULE_SCOPE Tk_PathItem *TkPathCanvasCurrentItem(
        Tk_PathCanvas canvas);
    MODULE_SCOPE Tk_PathCanvasTextInfo *Tk_PathCanvasGetTextInfo(
        Tk_PathCanvas canvas);
    MODULE_SCOPE Tk_PathTags *TkPathAllocTagsFromObj(
        Tcl_Interp * interp,
        Tcl_Obj * valuePtr);
    MODULE_SCOPE int Tk_PathCanvasTagsOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *Tk_PathCanvasTagsOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void Tk_PathCanvasTagsOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void Tk_PathCanvasTagsOptionFreeProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);
    MODULE_SCOPE int Tk_DashOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *Tk_DashOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void Tk_DashOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void Tk_DashOptionFreeProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr);
    MODULE_SCOPE void Tk_PathCreateSmoothMethod(
        Tcl_Interp * interp,
        Tk_PathSmoothMethod * method);
    MODULE_SCOPE int TkPathSmoothOptionSetProc(
        ClientData clientData,
        Tcl_Interp * interp,
        Tk_Window tkwin,
        Tcl_Obj ** value,
        char *recordPtr,
        int internalOffset,
        char *oldInternalPtr,
        int flags);
    MODULE_SCOPE Tcl_Obj *TkPathSmoothOptionGetProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *recordPtr,
        int internalOffset);
    MODULE_SCOPE void TkPathSmoothOptionRestoreProc(
        ClientData clientData,
        Tk_Window tkwin,
        char *internalPtr,
        char *oldInternalPtr);
    MODULE_SCOPE void Tk_PathCreateOutline(
        Tk_PathOutline * outline);
    MODULE_SCOPE void Tk_PathDeleteOutline(
        Display * display,
        Tk_PathOutline * outline);
    MODULE_SCOPE int Tk_PathConfigOutlineGC(
        XGCValues * gcValues,
        Tk_PathCanvas canvas,
        Tk_PathItem * item,
        Tk_PathOutline * outline);
    MODULE_SCOPE int Tk_PathChangeOutlineGC(
        Tk_PathCanvas canvas,
        Tk_PathItem * item,
        Tk_PathOutline * outline);
    MODULE_SCOPE int Tk_PathResetOutlineGC(
        Tk_PathCanvas canvas,
        Tk_PathItem * item,
        Tk_PathOutline * outline);
    MODULE_SCOPE int TkPathCanvTranslatePath(
        TkPathCanvas * canvPtr,
        int numVertex,
        double *coordPtr,
        int closed,
        XPoint * outPtr);
    MODULE_SCOPE int TkPathCanvasItemExConfigure(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        Tk_PathItemEx * itemExPtr,
        int mask);
    MODULE_SCOPE int TkPathEndpointToCentralArcParameters(
        /* Endpoints. */
        double x1,
        double y1,
        double x2,
        double y2,
        /* Radius. */
        double rx,
        double ry,
        double phi,
        char largeArcFlag,
        char sweepFlag,
        /* Output. */
        double *cxPtr,
        double *cyPtr,
        double *rxPtr,
        double *ryPtr,
        double *theta1Ptr,
        double *dthetaPtr);
    MODULE_SCOPE void TkPathGradientChangedPrc(
        ClientData clientData,
        int flags);
    MODULE_SCOPE void TkPathStyleChangedPrc(
        ClientData clientData,
        int flags);
    MODULE_SCOPE void TkPathCurveSegments(
        double control[],
        int includeFirst,
        int numSteps,
        double *coordPtr);
    MODULE_SCOPE double TkPathRectToPoint(
        double rectPtr[],
        double width,
        int filled,
        double pointPtr[]);
    MODULE_SCOPE int TkPathRectToArea(
        double rectPtr[],
        double width,
        int filled,
        double *areaPtr);
    MODULE_SCOPE int TkPathRectToAreaWithMatrix(
        TkPathRect bbox,
        TkPathMatrix * mPtr,
        double *areaPtr);
    MODULE_SCOPE double TkPathRectToPointWithMatrix(
        TkPathRect bbox,
        TkPathMatrix * mPtr,
        double *pointPtr);
    MODULE_SCOPE void TkPathCompensateScale(
        Tk_PathItem * itemPtr,
        int compensate,
        double *originX,
        double *originY,
        double *scaleX,
        double *scaleY);
    MODULE_SCOPE void TkPathCompensateTranslate(
        Tk_PathItem * itemPtr,
        int compensate,
        double *deltaX,
        double *deltaY);
    MODULE_SCOPE void TkPathScaleItemHeader(
        Tk_PathItem * itemPtr,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void TkPathScalePathRect(
        TkPathRect * r,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void TkPathTranslateItemHeader(
        Tk_PathItem * itemPtr,
        double deltaX,
        double deltaY);
    MODULE_SCOPE int TkPathCoordsForPointItems(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        double *pointPtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE int TkPathCoordsForRectangularItems(
        Tcl_Interp * interp,
        Tk_PathCanvas canvas,
        TkPathRect * rectPtr,
        int objc,
        Tcl_Obj * const objv[]);
    MODULE_SCOPE TkPathRect TkPathGetGenericBarePathBbox(
        TkPathAtom * atomPtr);
    MODULE_SCOPE TkPathRect TkPathGetGenericPathTotalBboxFromBare(
        TkPathAtom * atomPtr,
        Tk_PathStyle * stylePtr,
        TkPathRect * bboxPtr);
    MODULE_SCOPE void TkPathSetGenericPathHeaderBbox(
        Tk_PathItem * headerPtr,
        TkPathMatrix * mPtr,
        TkPathRect * totalBboxPtr);
    MODULE_SCOPE TkPathMatrix TkPathGetCanvasTMatrix(
        Tk_PathCanvas canvas);

    MODULE_SCOPE TkPathRect TkPathNewEmptyPathRect(
        void);
    MODULE_SCOPE void TkPathIncludePointInRect(
        TkPathRect * r,
        double x,
        double y);
    MODULE_SCOPE double TkPathGenericPathToPoint(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        Tk_PathStyle * stylePtr,
        TkPathAtom * atomPtr,
        int maxNumSegments,
        double *pointPtr);
    MODULE_SCOPE int TkPathGenericPathToArea(
        Tk_PathCanvas canvas,
        Tk_PathItem * itemPtr,
        Tk_PathStyle * stylePtr,
        TkPathAtom * atomPtr,
        int maxNumSegments,
        double *areaPtr);
    MODULE_SCOPE void TkPathTranslatePathAtoms(
        TkPathAtom * atomPtr,
        double deltaX,
        double deltaY);
    MODULE_SCOPE void TkPathScalePathAtoms(
        TkPathAtom * atomPtr,
        double originX,
        double originY,
        double scaleX,
        double scaleY);
    MODULE_SCOPE void TkPathTranslatePathRect(
        TkPathRect * r,
        double deltaX,
        double deltaY);

/* tkMacOSXPath.c tkSDLAGGPath.cpp tkUnixCairoPath.c tkWinGDIPlusPath.cpp */
    MODULE_SCOPE int TkPathSetup(
        Tcl_Interp * interp);
    MODULE_SCOPE TkPathContext TkPathInit(
        Tk_Window tkwin,
        Drawable d);
    MODULE_SCOPE TkPathContext TkPathInitSurface(
        Display * display,
        int width,
        int height);
    MODULE_SCOPE void TkPathBeginPath(
        TkPathContext ctx,
        Tk_PathStyle * stylePtr);
    MODULE_SCOPE void TkPathEndPath(
        TkPathContext ctx);
    MODULE_SCOPE void TkPathMoveTo(
        TkPathContext ctx,
        double x,
        double y);
    MODULE_SCOPE void TkPathLineTo(
        TkPathContext ctx,
        double x,
        double y);
    MODULE_SCOPE void TkPathArcTo(
        TkPathContext ctx,
        double rx,
        double ry,
        double angle,
        char largeArcFlag,
        char sweepFlag,
        double x,
        double y);
    MODULE_SCOPE void TkPathQuadBezier(
        TkPathContext ctx,
        double ctrlX,
        double ctrlY,
        double x,
        double y);
    MODULE_SCOPE void TkPathCurveTo(
        TkPathContext ctx,
        double ctrlX1,
        double ctrlY1,
        double ctrlX2,
        double ctrlY2,
        double x,
        double y);
    MODULE_SCOPE void TkPathRectangle(
        TkPathContext ctx,
        double x,
        double y,
        double width,
        double height);
    MODULE_SCOPE void TkPathOval(
        TkPathContext ctx,
        double cx,
        double cy,
        double rx,
        double ry);
    MODULE_SCOPE void TkPathClosePath(
        TkPathContext ctx);
    MODULE_SCOPE void TkPathImage(
        TkPathContext ctx,
        Tk_Image image,
        Tk_PhotoHandle photo,
        double x,
        double y,
        double width,
        double height,
        double fillOpacity,
        XColor * tintColor,
        double tintAmount,
        int interpolation,
        TkPathRect * srcRegion);
    MODULE_SCOPE int TkPathTextConfig(
        Tcl_Interp * interp,
        Tk_PathTextStyle * textStylePtr,
        char *utf8,
        void **customPtr);
    MODULE_SCOPE void TkPathTextDraw(
        TkPathContext ctx,
        Tk_PathStyle * style,
        Tk_PathTextStyle * textStylePtr,
        double x,
        double y,
        int fillOverStroke,
        char *utf8,
        void *custom);
    MODULE_SCOPE void TkPathTextFree(
        Tk_PathTextStyle * textStylePtr,
        void *custom);
    MODULE_SCOPE TkPathRect TkPathTextMeasureBbox(
        Display * display,
        Tk_PathTextStyle * textStylePtr,
        char *utf8,
        double *lineSpacing,
        void *custom);
    MODULE_SCOPE void TkPathSurfaceErase(
        TkPathContext ctx,
        double x,
        double y,
        double width,
        double height);
    MODULE_SCOPE void TkPathSurfaceToPhoto(
        Tcl_Interp * interp,
        TkPathContext ctx,
        Tk_PhotoHandle photo);
    MODULE_SCOPE void TkPathClipToPath(
        TkPathContext ctx,
        int fillRule);
    MODULE_SCOPE void TkPathReleaseClipToPath(
        TkPathContext ctx);
    MODULE_SCOPE void TkPathStroke(
        TkPathContext ctx,
        Tk_PathStyle * style);
    MODULE_SCOPE void TkPathFill(
        TkPathContext ctx,
        Tk_PathStyle * style);
    MODULE_SCOPE void TkPathFillAndStroke(
        TkPathContext ctx,
        Tk_PathStyle * style);
    MODULE_SCOPE int TkPathGetCurrentPosition(
        TkPathContext ctx,
        TkPathPoint * ptPtr);
    MODULE_SCOPE int TkPathBoundingBox(
        TkPathContext ctx,
        TkPathRect * rPtr);
    MODULE_SCOPE void TkPathPaintLinearGradient(
        TkPathContext ctx,
        TkPathRect * bbox,
        TkLinearGradientFill * fillPtr,
        int fillRule,
        double fillOpacity,
        TkPathMatrix * matrixPtr);
    MODULE_SCOPE void TkPathPaintRadialGradient(
        TkPathContext ctx,
        TkPathRect * bbox,
        TkRadialGradientFill * fillPtr,
        int fillRule,
        double fillOpacity,
        TkPathMatrix * mPtr);
    MODULE_SCOPE void TkPathFree(
        TkPathContext ctx);
    MODULE_SCOPE int TkPathDrawingDestroysPath(
        void);
    MODULE_SCOPE int TkPathPixelAlign(
        void);
    MODULE_SCOPE void TkPathPushTMatrix(
        TkPathContext ctx,
        TkPathMatrix * mPtr);
    MODULE_SCOPE void TkPathResetTMatrix(
        TkPathContext ctx);
    MODULE_SCOPE void TkPathSaveState(
        TkPathContext ctx);
    MODULE_SCOPE void TkPathRestoreState(
        TkPathContext ctx);

/*
 * end block for C++
 */

#ifdef __cplusplus
}
#endif
#endif                         /* _TKOPATH_H */
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvArrow.c.
























































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvArrow.c --
 *
 *    This file implements arrow heads
 *
 * Copyright (c) 2014 OpenSim Ltd., author:Zoltan Bojthe
 *
 * $Id$
 */

#include "tkoPath.h"

#ifdef _MSC_VER
#ifndef isnan
#define isnan(x) ((x) != (x))
#endif
#endif

/*
 * Points in an arrowHead:
 */
#define PTS_IN_ARROW 6
#define DRAWABLE_PTS_IN_ARROW 5
#define ORIG_PT_IN_ARROW 2
#define LINE_PT_IN_ARROW 5

static const double zero = 0.0; // just for NaN
#define NaN (zero/zero)

TkPathAtom *
TkPathMakePathAtomsFromArrow(
    TkPathArrowDescr * arrowDescr)
{
TkPathPoint *coords = arrowDescr->arrowPointsPtr;
TkPathAtom *atomPtr = NULL, *ret = NULL;
    if(coords) {
int i = 0;
        if(isnan(coords[0].x) || isnan(coords[0].y)) {
            i = 1;
        }
        ret = atomPtr = TkPathNewMoveToAtom(coords[i].x, coords[i].y);
        for(i++; i < DRAWABLE_PTS_IN_ARROW; i++) {
            if(isnan(coords[i].x) || isnan(coords[i].y))
                continue;
            atomPtr->nextPtr = TkPathNewLineToAtom(coords[i].x, coords[i].y);
            atomPtr = atomPtr->nextPtr;
        }
    }
    return ret;
}

void
TkPathDisplayArrow(
    Tk_PathCanvas canvas,
    TkPathArrowDescr * arrowDescr,
    Tk_PathStyle * const style,
    TkPathMatrix * mPtr,
    TkPathRect * bboxPtr)
{
    if(arrowDescr->arrowEnabled && arrowDescr->arrowPointsPtr != NULL) {
    Tk_PathStyle arrowStyle = *style;
    TkPathColor fc;
    TkPathAtom *atomPtr;

        TkPathResetTMatrix(ContextOfCanvas(canvas));
        if(arrowDescr->arrowFillRatio > 0.0 && arrowDescr->arrowLength != 0.0) {
            arrowStyle.strokeWidth = 0.0;
            fc.color = arrowStyle.strokeColor;
            fc.gradientInstPtr = NULL;
            arrowStyle.fill = &fc;
            arrowStyle.fillOpacity = arrowStyle.strokeOpacity;
        } else {
            arrowStyle.fill = NULL;
            arrowStyle.fillOpacity = 1.0;
            arrowStyle.joinStyle = 1;
            arrowStyle.dashPtr = NULL;
        }
        atomPtr = TkPathMakePathAtomsFromArrow(arrowDescr);
        TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &arrowStyle,
            mPtr, bboxPtr);
        TkPathFreeAtoms(atomPtr);
    }
}

void
TkPathPaintArrow(
    TkPathContext context,
    TkPathArrowDescr * arrowDescr,
    Tk_PathStyle * const style,
    TkPathRect * bboxPtr)
{
    if(arrowDescr->arrowEnabled && arrowDescr->arrowPointsPtr != NULL) {
    Tk_PathStyle arrowStyle = *style;
    TkPathColor fc;
    TkPathAtom *atomPtr;

        arrowStyle.matrixPtr = NULL;
        if(arrowDescr->arrowFillRatio > 0.0 && arrowDescr->arrowLength != 0.0) {
            arrowStyle.strokeWidth = 0.0;
            fc.color = arrowStyle.strokeColor;
            fc.gradientInstPtr = NULL;
            arrowStyle.fill = &fc;
            arrowStyle.fillOpacity = arrowStyle.strokeOpacity;
        } else {
            arrowStyle.fill = NULL;
            arrowStyle.fillOpacity = 1.0;
            arrowStyle.joinStyle = 1;
            arrowStyle.dashPtr = NULL;
        }
        atomPtr = TkPathMakePathAtomsFromArrow(arrowDescr);
        if(TkPathMakePath(context, atomPtr, &arrowStyle) == TCL_OK) {
            TkPathPaintPath(context, atomPtr, &arrowStyle, bboxPtr);
        }
        TkPathFreeAtoms(atomPtr);
    }
}

void
TkPathArrowDescrInit(
    TkPathArrowDescr * descrPtr)
{
    descrPtr->arrowEnabled = TK_PATH_ARROWS_OFF;
    descrPtr->arrowLength = (float)8.0;
    descrPtr->arrowWidth = (float)4.0;
    descrPtr->arrowFillRatio = (float)1.0;
    descrPtr->arrowPointsPtr = NULL;
}

void
TkPathIncludeArrowPointsInRect(
    TkPathRect * bbox,
    TkPathArrowDescr * arrowDescrPtr)
{
    if(arrowDescrPtr->arrowEnabled && arrowDescrPtr->arrowPointsPtr) {
int i;

        for(i = 0; i < PTS_IN_ARROW; i++)
            if(!isnan(arrowDescrPtr->arrowPointsPtr[i].x) &&
                !isnan(arrowDescrPtr->arrowPointsPtr[i].y))
                TkPathIncludePointInRect(bbox,
                    arrowDescrPtr->arrowPointsPtr[i].x,
                    arrowDescrPtr->arrowPointsPtr[i].y);
    }
}

void
TkPathIncludeArrowPoints(
    Tk_PathItem * itemPtr,
    TkPathArrowDescr * arrowDescrPtr)
{
    if(arrowDescrPtr->arrowEnabled) {
int i;

        for(i = 0; i < PTS_IN_ARROW; i++)
            if(!isnan(arrowDescrPtr->arrowPointsPtr[i].x) &&
                !isnan(arrowDescrPtr->arrowPointsPtr[i].y))
                TkPathIncludePoint(itemPtr,
                    (double *)&arrowDescrPtr->arrowPointsPtr[i]);
    }
}

void
TkPathPreconfigureArrow(
    TkPathPoint * pf,
    TkPathArrowDescr * arrowDescr)
{
    if(arrowDescr->arrowPointsPtr == NULL) {
        if(arrowDescr->arrowEnabled) {
            arrowDescr->arrowPointsPtr = (TkPathPoint *)
                ckalloc((unsigned)(PTS_IN_ARROW * sizeof(TkPathPoint)));
            arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW] = *pf;
            arrowDescr->arrowPointsPtr[ORIG_PT_IN_ARROW] = *pf;
        }
    } else {
        if(pf->x == arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW].x &&
            pf->y == arrowDescr->arrowPointsPtr[LINE_PT_IN_ARROW].y) {
            *pf = arrowDescr->arrowPointsPtr[ORIG_PT_IN_ARROW];
        }
        if(!arrowDescr->arrowEnabled) {
            ckfree((char *)arrowDescr->arrowPointsPtr);
            arrowDescr->arrowPointsPtr = NULL;
        }
    }
}

TkPathPoint
TkPathConfigureArrow(
    TkPathPoint pf,
    TkPathPoint pl,
    TkPathArrowDescr * arrowDescr,
    Tk_PathStyle * lineStyle,
    int updateFirstPoint)
{
    if(arrowDescr->arrowEnabled) {
    TkPathPoint p0;
    double lineWidth = lineStyle->strokeWidth;
    double shapeLength = arrowDescr->arrowLength;
    double shapeWidth = arrowDescr->arrowWidth;
    double shapeFill = arrowDescr->arrowFillRatio;
    double dx, dy, length, sinTheta, cosTheta;
    double backup;             /* Distance to backup end points so the line
                                * ends in the middle of the arrowhead. */
    double minsShapeFill;
    TkPathPoint *poly = arrowDescr->arrowPointsPtr;
    int capStyle = lineStyle->capStyle;
        /*  CapButt, CapProjecting, or CapRound. */

        if(!poly) {
            Tcl_Panic("Internal error: TkPathPoint list is NULL pointer\n");
        }
        if(shapeWidth < lineWidth) {
            shapeWidth = lineWidth;
        }
        minsShapeFill = lineWidth * shapeLength / shapeWidth;
        if(shapeFill > 0.0 &&
            fabs(shapeLength * shapeFill) < fabs(minsShapeFill))
            shapeFill = 1.1 * minsShapeFill / shapeLength;

        backup = 0.0;
        if(lineWidth > 1.0) {
            backup = (capStyle == CapProjecting) ? 0.5 * lineWidth : 0.0;
            if(shapeFill > 0.0 && shapeLength != 0.0) {
                backup += 0.5 * lineWidth * shapeLength / shapeWidth;
            }
        }

        dx = pf.x - pl.x;
        dy = pf.y - pl.y;
        length = hypot(dx, dy);
        if(length == 0) {
            sinTheta = cosTheta = 0.0;
        } else {
            sinTheta = dy / length;
            cosTheta = dx / length;
        }

        p0.x = pf.x - shapeLength * cosTheta;
        p0.y = pf.y - shapeLength * sinTheta;
        if(shapeFill > 0.0 && shapeLength != 0.0) {
            poly[0].x = pf.x - shapeLength * shapeFill * cosTheta;
            poly[0].y = pf.y - shapeLength * shapeFill * sinTheta;
            poly[4] = poly[0];
        } else {
            poly[0].x = poly[0].y = poly[4].x = poly[4].y = NaN;
        }
        poly[1].x = p0.x - shapeWidth * sinTheta;
        poly[1].y = p0.y + shapeWidth * cosTheta;
        poly[2].x = pf.x;
        poly[2].y = pf.y;
        poly[3].x = p0.x + shapeWidth * sinTheta;
        poly[3].y = p0.y - shapeWidth * cosTheta;
        /*
         * Polygon done. Now move the first point towards the second so that
         * the corners at the end of the line are inside the arrowhead.
         */

        poly[LINE_PT_IN_ARROW] = poly[ORIG_PT_IN_ARROW];
        if(updateFirstPoint) {
            poly[LINE_PT_IN_ARROW].x -= backup * cosTheta;
            poly[LINE_PT_IN_ARROW].y -= backup * sinTheta;
        }

        return poly[LINE_PT_IN_ARROW];
    }
    return pf;
}

void
TkPathTranslateArrow(
    TkPathArrowDescr * arrowDescr,
    double deltaX,
    double deltaY)
{
    if(arrowDescr->arrowPointsPtr != NULL) {
    int i;
        for(i = 0; i < PTS_IN_ARROW; i++) {
            arrowDescr->arrowPointsPtr[i].x += deltaX;
            arrowDescr->arrowPointsPtr[i].y += deltaY;
        }
    }
}

void
TkPathScaleArrow(
    TkPathArrowDescr * arrowDescr,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    if(arrowDescr->arrowPointsPtr != NULL) {
    int i;
    TkPathPoint *pt;
        for(i = 0, pt = arrowDescr->arrowPointsPtr; i < PTS_IN_ARROW; i++, pt++) {
            pt->x = originX + scaleX * (pt->x - originX);
            pt->y = originX + scaleX * (pt->y - originX);
        }
    }
}

void
TkPathFreeArrow(
    TkPathArrowDescr * arrowDescr)
{
    if(arrowDescr->arrowPointsPtr != NULL) {
        ckfree((char *)arrowDescr->arrowPointsPtr);
        arrowDescr->arrowPointsPtr = NULL;
    }
}

typedef TkPathPoint *PathPointPtr;

int
TkPathGetSegmentsFromPathAtomList(
    TkPathAtom * firstAtom,
    TkPathPoint ** firstPt,
    TkPathPoint * secondPt,
    TkPathPoint * penultPt,
    TkPathPoint ** lastPt)
{
TkPathAtom *atom;
int i;

    *firstPt = *lastPt = NULL;
    secondPt->x = secondPt->y = penultPt->x = penultPt->y = NaN;

    if(firstAtom && firstAtom->type != TK_PATH_ATOM_M) {
        Tcl_Panic("Invalid path! Path must start with M(move) atom");
    }
    for(i = 0, atom = firstAtom; atom; atom = atom->nextPtr) {
        switch (atom->type) {
        case TK_PATH_ATOM_M:
        {
TkMoveToAtom *moveto = (TkMoveToAtom *) atom;
            if(i == 0) {
                *firstPt = (PathPointPtr) & moveto->x;
                i++;
            } else if(i == 1) {
                secondPt->x = moveto->x;
                secondPt->y = moveto->y;
                i++;
            }
            penultPt->x = penultPt->y = NaN;
            *lastPt = (PathPointPtr) & moveto->x;
            break;
        }
        case TK_PATH_ATOM_L:
        {
TkLineToAtom *lineto = (TkLineToAtom *) atom;
            if(i == 1) {
                secondPt->x = lineto->x;
                secondPt->y = lineto->y;
                i++;
            }
            *penultPt = **lastPt;
            *lastPt = (PathPointPtr) & lineto->x;
            break;
        }
        case TK_PATH_ATOM_A:{
TkArcAtom *arc = (TkArcAtom *) atom;

            /*
             * Draw an elliptical arc from the current point to (x, y).
             * The points are on an ellipse with x-radius <radX> and
             * y-radius <radY>. The ellipse is rotated by <angle> degrees.
             * If the arc is less than 180 degrees, <largeArcFlag> is
             * zero, else it is one. If the arc is to be drawn in cw
             * direction, sweepFlag is one, and zero for the ccw
             * direction.
             * NB: the start and end points may not coincide else the
             * result is undefined. If you want to make a circle just
             * do two 180 degree arcs.
             */
int result;
double cx, cy, rx, ry;
double theta1, dtheta;
TkPathPoint startPt = **lastPt;
double phi = DEGREES_TO_RADIANS * arc->angle;

            result = TkPathEndpointToCentralArcParameters(startPt.x, startPt.y,
                arc->x, arc->y, arc->radX, arc->radY,
                phi,
                arc->largeArcFlag, arc->sweepFlag,
                &cx, &cy, &rx, &ry, &theta1, &dtheta);
            if(result == TK_PATH_ARC_OK) {
double sinTheta2, cosTheta2;
double sinPhi = sin(phi);
double cosPhi = cos(phi);
double theta2 = theta1 + dtheta;

                if(dtheta > 0.0) {
                    theta1 += M_PI * 0.01;
                    theta2 -= M_PI * 0.01;
                } else {
                    theta1 -= M_PI * 0.01;
                    theta2 += M_PI * 0.01;
                }

                sinTheta2 = sin(theta2);
                cosTheta2 = cos(theta2);

                if(i == 1) {
double sinTheta1 = sin(theta1);
double cosTheta1 = cos(theta1);
                    /* auxiliary point 1 */
                    secondPt->x = cx + rx * cosTheta1 * cosPhi -
                        ry * sinTheta1 * sinPhi;
                    secondPt->y = cy + rx * cosTheta1 * sinPhi +
                        ry * sinTheta1 * cosPhi;
                    i++;
                }
                /* auxiliary point 2 */
                penultPt->x = cx + rx * cosTheta2 * cosPhi -
                    ry * sinTheta2 * sinPhi;
                penultPt->y = cy + rx * cosTheta2 * sinPhi +
                    ry * sinTheta2 * cosPhi;
            } else {
                /* arc is line */
                if(i == 1) {
                    secondPt->x = arc->x;
                    secondPt->y = arc->y;
                    i++;
                }
                *penultPt = **lastPt;
            }

            *lastPt = (PathPointPtr) & arc->x;
            break;
        }
        case TK_PATH_ATOM_Q:{
TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atom;
            if(i == 1) {
                secondPt->x = quad->ctrlX;
                secondPt->y = quad->ctrlY;
                i++;
            }
            penultPt->x = quad->ctrlX;
            penultPt->y = quad->ctrlY;
            *lastPt = (PathPointPtr) & quad->anchorX;
            break;
        }
        case TK_PATH_ATOM_C:{
TkCurveToAtom *curve = (TkCurveToAtom *) atom;
            if(i == 1) {
                secondPt->x = curve->ctrlX1;
                secondPt->y = curve->ctrlY1;
                i++;
            }
            penultPt->x = curve->ctrlX2;
            penultPt->y = curve->ctrlY2;
            *lastPt = (PathPointPtr) & curve->anchorX;
            break;
        }
        case TK_PATH_ATOM_Z:{
TkCloseAtom *closeAtom = (TkCloseAtom *) atom;
            *penultPt = **lastPt;
            *lastPt = (PathPointPtr) & closeAtom->x;
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            /* Empty. */
            break;
        }
        default:
            break;
        }
    }
    return (i >= 2) ? TCL_OK : TCL_ERROR;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvEllipse.c.























































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvEllipse.c --
 *
 *    This file implements the circle and ellipse canvas items modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each circle and ellipse item.
 */

typedef struct EllipseItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    char type;                 /* Circle or ellipse. */
    double center[2];          /* Center coord. */
    double rx;                 /* Radius. Circle uses rx for overall radius. */
    double ry;
} EllipseItem;

enum {
    kOvalTypeCircle,
    kOvalTypeEllipse
};

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputeEllipseBbox(
    Tk_PathCanvas canvas,
    EllipseItem * ellPtr);
static int ConfigureEllipse(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreateAny(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    char type);
static int CreateCircle(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int CreateEllipse(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeleteEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void EllipseBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int EllipseCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int EllipseToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int EllipseToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double EllipseToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScaleEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslateEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);

enum {
    ELLIPSE_OPTION_INDEX_RX = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    ELLIPSE_OPTION_INDEX_RY = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    ELLIPSE_OPTION_INDEX_R = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE TK_PATH_OPTION_STRING_TABLES_STATE
#define TK_PATH_OPTION_SPEC_R(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, ELLIPSE_OPTION_INDEX_R}
#define TK_PATH_OPTION_SPEC_RX(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, ELLIPSE_OPTION_INDEX_RX}
#define TK_PATH_OPTION_SPEC_RY(typeName)            \
    {TK_OPTION_DOUBLE, "-ry", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, ry),        \
    0, 0, ELLIPSE_OPTION_INDEX_RY}
static Tk_OptionSpec optionSpecsCircle[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_R(EllipseItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec optionSpecsEllipse[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_RX(EllipseItem),
    TK_PATH_OPTION_SPEC_RY(EllipseItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below define the 'circle' and 'ellipse' item types by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeCircle = {
    "circle",  /* name */
    sizeof(EllipseItem),        /* itemSize */
    CreateCircle,       /* createProc */
    optionSpecsCircle,  /* optionSpecs */
    ConfigureEllipse,   /* configureProc */
    EllipseCoords,      /* coordProc */
    DeleteEllipse,      /* deleteProc */
    DisplayEllipse,     /* displayProc */
    0,         /* flags */
    EllipseBbox,        /* bboxProc */
    EllipseToPoint,     /* pointProc */
    EllipseToArea,      /* areaProc */
    EllipseToPdf,       /* pdfProc */
    ScaleEllipse,       /* scaleProc */
    TranslateEllipse,   /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

Tk_PathItemType tkPathTypeEllipse = {
    "ellipse", /* name */
    sizeof(EllipseItem),        /* itemSize */
    CreateEllipse,      /* createProc */
    optionSpecsEllipse, /* optionSpecs */
    ConfigureEllipse,   /* configureProc */
    EllipseCoords,      /* coordProc */
    DeleteEllipse,      /* deleteProc */
    DisplayEllipse,     /* displayProc */
    0,         /* flags */
    EllipseBbox,        /* bboxProc */
    EllipseToPoint,     /* pointProc */
    EllipseToArea,      /* areaProc */
    EllipseToPdf,       /* pdfProc */
    ScaleEllipse,       /* scaleProc */
    TranslateEllipse,   /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreateCircle(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kOvalTypeCircle);
}

static int
CreateEllipse(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kOvalTypeEllipse);
}

static int
CreateAny(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    char type)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_OptionTable optionTable;
    int i;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    ellPtr->type = type;

    if(ellPtr->type == kOvalTypeCircle) {
        optionTable = Tk_CreateOptionTable(interp, optionSpecsCircle);
    } else {
        optionTable = Tk_CreateOptionTable(interp, optionSpecsEllipse);
    }
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)ellPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(TkPathCoordsForPointItems(interp, canvas, ellPtr->center, i,
            objv) != TCL_OK) {
        goto error;
    }
    if(ConfigureEllipse(interp, canvas, itemPtr, objc - i, objv + i,
            0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeleteEllipse(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
EllipseCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    int result;

    result =
        TkPathCoordsForPointItems(interp, canvas, ellPtr->center, objc, objv);
    if((result == TCL_OK) && ((objc == 1) || (objc == 2))) {
        ComputeEllipseBbox(canvas, ellPtr);
    }
    return result;
}

static TkPathRect
GetBareBbox(
    EllipseItem * ellPtr)
{
TkPathRect bbox;

    bbox.x1 = ellPtr->center[0] - ellPtr->rx;
    bbox.y1 = ellPtr->center[1] - ellPtr->ry;
    bbox.x2 = ellPtr->center[0] + ellPtr->rx;
    bbox.y2 = ellPtr->center[1] + ellPtr->ry;
    return bbox;
}

static void
ComputeEllipseBbox(
    Tk_PathCanvas canvas,
    EllipseItem * ellPtr)
{
Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
            itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->bbox = GetBareBbox(ellPtr);
    itemPtr->totalBbox =
        TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigureEllipse(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)ellPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));
    ellPtr->rx = MAX(0.0, ellPtr->rx);
    ellPtr->ry = MAX(0.0, ellPtr->ry);
    if(ellPtr->type == kOvalTypeCircle) {
        /* Practical. */
        ellPtr->ry = ellPtr->rx;
    }
    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputeEllipseBbox(canvas, ellPtr);
        return TCL_OK;
    }
}

static void
DeleteEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
EllipseItem *ellPtr = (EllipseItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &ellPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
#if 0
    TkPathRect bbox;
#endif
    TkPathAtom *atomPtr;
    TkEllipseAtom ellAtom;
    Tk_PathStyle style;

    /*
     * We create the atom on the fly to save some memory.
     */
    atomPtr = (TkPathAtom *) & ellAtom;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_ELLIPSE;
    ellAtom.cx = ellPtr->center[0];
    ellAtom.cy = ellPtr->center[1];
    ellAtom.rx = ellPtr->rx;
    ellAtom.ry = ellPtr->ry;

    itemPtr->bbox = GetBareBbox(ellPtr);
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style,
        &m, &itemPtr->bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
EllipseBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    ComputeEllipseBbox(canvas, ellPtr);
}

static double
EllipseToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    double bareOval[4];
    double width, dist;
    int rectiLinear = 0;
    int haveDist = 0;
    int filled;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if(style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;
    if(mPtr == NULL) {
        rectiLinear = 1;
        bareOval[0] = ellPtr->center[0] - ellPtr->rx;
        bareOval[1] = ellPtr->center[1] - ellPtr->ry;
        bareOval[2] = ellPtr->center[0] + ellPtr->rx;
        bareOval[3] = ellPtr->center[1] + ellPtr->ry;

        /* For tiny points make it simple. */
        if((ellPtr->rx <= 2.0) && (ellPtr->ry <= 2.0)) {
            dist =
                hypot(ellPtr->center[0] - pointPtr[0],
                ellPtr->center[1] - pointPtr[1]);
            dist = MAX(0.0, dist - (ellPtr->rx + ellPtr->ry) / 2.0);
            haveDist = 1;
        }
    } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
    double rx, ry;

        /* This is a situation we can treat in a simplified way. Apply the transform here. */
        rectiLinear = 1;
        bareOval[0] = mPtr->a * (ellPtr->center[0] - ellPtr->rx) + mPtr->tx;
        bareOval[1] = mPtr->d * (ellPtr->center[1] - ellPtr->ry) + mPtr->ty;
        bareOval[2] = mPtr->a * (ellPtr->center[0] + ellPtr->rx) + mPtr->tx;
        bareOval[3] = mPtr->d * (ellPtr->center[1] + ellPtr->ry) + mPtr->ty;

        /* For tiny points make it simple. */
        rx = fabs(bareOval[0] - bareOval[2]) / 2.0;
        ry = fabs(bareOval[1] - bareOval[3]) / 2.0;
        if((rx <= 2.0) && (ry <= 2.0)) {
            dist = hypot((bareOval[0] + bareOval[2] / 2.0) - pointPtr[0],
                (bareOval[1] + bareOval[3] / 2.0) - pointPtr[1]);
            dist = MAX(0.0, dist - (rx + ry) / 2.0);
            haveDist = 1;
        }
    }
    if(!haveDist) {
        if(rectiLinear) {
            dist = TkOvalToPoint(bareOval, width, filled, pointPtr);
        } else {
    TkPathAtom *atomPtr;
    TkEllipseAtom ellAtom;

            /*
             * We create the atom on the fly to save some memory.
             */
            atomPtr = (TkPathAtom *) & ellAtom;
            atomPtr->nextPtr = NULL;
            atomPtr->type = TK_PATH_ATOM_ELLIPSE;
            ellAtom.cx = ellPtr->center[0];
            ellAtom.cy = ellPtr->center[1];
            ellAtom.rx = ellPtr->rx;
            ellAtom.ry = ellPtr->ry;
            dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
                TK_PATH_NUMSEGEMENTS_Ellipse + 1, pointPtr);
        }
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
EllipseToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    double center[2], bareOval[4], halfWidth;
    int rectiLinear = 0;
    int result;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    halfWidth = 0.0;
    center[0] = ellPtr->center[0];
    center[1] = ellPtr->center[1];
    if(style.strokeColor != NULL) {
        halfWidth = style.strokeWidth / 2.0;
    }
    mPtr = style.matrixPtr;
    if(mPtr == NULL) {
        rectiLinear = 1;
        bareOval[0] = center[0] - ellPtr->rx;
        bareOval[1] = center[1] - ellPtr->ry;
        bareOval[2] = center[0] + ellPtr->rx;
        bareOval[3] = center[1] + ellPtr->ry;
    } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
        /*
         * This is a situation we can treat in a simplified way.
         * Apply the transform here.
         */
        rectiLinear = 1;
        bareOval[0] = mPtr->a * (center[0] - ellPtr->rx) + mPtr->tx;
        bareOval[1] = mPtr->d * (center[1] - ellPtr->ry) + mPtr->ty;
        bareOval[2] = mPtr->a * (center[0] + ellPtr->rx) + mPtr->tx;
        bareOval[3] = mPtr->d * (center[1] + ellPtr->ry) + mPtr->ty;
        center[0] = mPtr->a * center[0] + mPtr->tx;
        center[1] = mPtr->d * center[1] + mPtr->ty;
    }

    if(rectiLinear) {
    double oval[4];

        /* @@@ Assuming untransformed strokes */
        oval[0] = bareOval[0] - halfWidth;
        oval[1] = bareOval[1] - halfWidth;
        oval[2] = bareOval[2] + halfWidth;
        oval[3] = bareOval[3] + halfWidth;

        result = TkOvalToArea(oval, areaPtr);

        /*
         * If the rectangle appears to overlap the oval and the oval
         * isn't filled, do one more check to see if perhaps all four
         * of the rectangle's corners are totally inside the oval's
         * unfilled center, in which case we should return "outside".
         */
        if((result == 0) && (style.strokeColor != NULL)
            && !HaveAnyFillFromPathColor(style.fill)) {
    double width, height;
    double xDelta1, yDelta1, xDelta2, yDelta2;

            width = (bareOval[2] - bareOval[0]) / 2.0 - halfWidth;
            height = (bareOval[3] - bareOval[1]) / 2.0 - halfWidth;
            if((width <= 0.0) || (height <= 0.0)) {
                return 0;
            }
            xDelta1 = (areaPtr[0] - center[0]) / width;
            xDelta1 *= xDelta1;
            yDelta1 = (areaPtr[1] - center[1]) / height;
            yDelta1 *= yDelta1;
            xDelta2 = (areaPtr[2] - center[0]) / width;
            xDelta2 *= xDelta2;
            yDelta2 = (areaPtr[3] - center[1]) / height;
            yDelta2 *= yDelta2;
            if(((xDelta1 + yDelta1) < 1.0)
                && ((xDelta1 + yDelta2) < 1.0)
                && ((xDelta2 + yDelta1) < 1.0)
                && ((xDelta2 + yDelta2) < 1.0)) {
                result = -1;
            }
        }
    } else {
    TkPathAtom *atomPtr;
    TkEllipseAtom ellAtom;

        /*
         * We create the atom on the fly to save some memory.
         */
        atomPtr = (TkPathAtom *) & ellAtom;
        atomPtr->nextPtr = NULL;
        atomPtr->type = TK_PATH_ATOM_ELLIPSE;
        ellAtom.cx = ellPtr->center[0];
        ellAtom.cy = ellPtr->center[1];
        ellAtom.rx = ellPtr->rx;
        ellAtom.ry = ellPtr->ry;
        result = TkPathGenericPathToArea(canvas, itemPtr, &style, atomPtr,
            TK_PATH_NUMSEGEMENTS_Ellipse + 1, areaPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static int
EllipseToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;
    TkEllipseAtom atom;
    Tk_PathState state = itemPtr->state;
    int result;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        return TCL_OK;
    }
    /* We create the atom on the fly to save some memory.  */
    atomPtr = (TkPathAtom *) & atom;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_ELLIPSE;
    atom.cx = ellPtr->center[0];
    atom.cy = ellPtr->center[1];
    atom.rx = ellPtr->rx;
    atom.ry = ellPtr->ry;
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScaleEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    ellPtr->center[0] = originX + scaleX * (ellPtr->center[0] - originX);
    ellPtr->center[1] = originY + scaleY * (ellPtr->center[1] - originY);
    ellPtr->rx *= scaleX;
    ellPtr->ry *= scaleY;
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslateEllipse(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    EllipseItem *ellPtr = (EllipseItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    ellPtr->center[0] += deltaX;
    ellPtr->center[1] += deltaY;
#if 0
    TkPathTranslatePathAtoms(ellPtr->atomPtr, deltaX, deltaY);
#endif
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvGroup.c.


















































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvGroup.c --
 *
 *    This file implements a line canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

enum {
    /* When childs update themself so they set all
     * its ancestors dirty bbox flag so they know
     * when they need to recompute its bbox. */
    GROUP_FLAG_DIRTY_BBOX = (1L << 0)
};

/*
 * The structure below defines the record for each path item.
 */

typedef struct GroupItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    TkPathRect totalBbox;      /* Bounding box including stroke.
                                * Untransformed coordinates. */
    long flags;                /* Various flags, see enum. */
} GroupItem;

/*
 * Prototypes for procedures defined in this file:
 */

void GroupUpdateBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr);
static int ConfigureGroup(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreateGroup(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeleteGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void GroupBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int flags);
static int GroupCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int GroupToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int GroupToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double GroupToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScaleGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslateGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE
    TK_PATH_OPTION_STRING_TABLES_STATE static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeGroup = {
    "group",   /* name */
    sizeof(GroupItem),  /* itemSize */
    CreateGroup,        /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigureGroup,     /* configureProc */
    GroupCoords,        /* coordProc */
    DeleteGroup,        /* deleteProc */
    DisplayGroup,       /* displayProc */
    0,         /* flags */
    GroupBbox, /* bboxProc */
    GroupToPoint,       /* pointProc */
    GroupToArea,        /* areaProc */
    GroupToPdf, /* pdfProc */
    ScaleGroup, /* scaleProc */
    TranslateGroup,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreateGroup(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
    Tk_OptionTable optionTable;

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    groupPtr->totalBbox = TkPathNewEmptyPathRect();
    groupPtr->flags = 0L;
    itemExPtr->header.x1 = itemExPtr->header.x2 =
        itemExPtr->header.y1 = itemExPtr->header.y2 = -1;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)groupPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }
    if(ConfigureGroup(interp, canvas, itemPtr, objc, objv, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeleteGroup(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
ConfigureGroup(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    GroupItem *groupPtr = (GroupItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)groupPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * Root item's -tags and -parent is read only.
         */
        if(itemPtr->id == 0) {
            if(mask & TK_PATH_CORE_OPTION_PARENT) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("root items -parent is not configurable",
                        -1));
                continue;
            }
            if(mask & TK_PATH_CORE_OPTION_TAGS) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("root items -tags is not configurable",
                        -1));
                continue;
            }
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));

    /*
     * We must notify all children to update themself
     * since they may inherit features.
     */
    if(!error) {
        TkPathGroupItemConfigured(canvas, itemPtr, mask);
    }
    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        return TCL_OK;
    }
}

static void
DeleteGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
GroupItem *groupPtr = (GroupItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &groupPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    /* Empty. */
}

static void
GroupBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int flags)
{
    /* Empty. */
}

static int
GroupCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_SetObjResult(interp,
        Tcl_NewStringObj("group items have no coords", -1));
    return TCL_ERROR;
}

static int
GroupToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr)
{
    /*
     * This says that the group is entirely outside any area.
     */
    return -1;
}

static double
GroupToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr)
{
    /*
     * This says that the group is nowhere.
     */
    return DBL_MAX;
}

static int
GroupToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    return TCL_OK;
}

static void
ScaleGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    TkPathCanvasScaleGroup(canvas, itemPtr, compensate,
        originX, originY, scaleX, scaleY);
    /* @@@ TODO: we could handle bbox ourselves? */
}

static void
TranslateGroup(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    TkPathCanvasTranslateGroup(canvas, itemPtr, compensate, deltaX, deltaY);
    /* @@@ TODO: we could handle bbox ourselves? */
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasSetGroupDirtyBbox --
 *
 *    This function is invoked by canvas code to tell us that one or
 *    more of our childrens have changed somehow so that our bbox
 *    need to be recomputed next time TkPathCanvasUpdateGroupBbox
 *    is called.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

void
TkPathCanvasSetGroupDirtyBbox(
    Tk_PathItem * itemPtr)
{
GroupItem *groupPtr = (GroupItem *) itemPtr;
    groupPtr->flags &= GROUP_FLAG_DIRTY_BBOX;
}

void
TkPathCanvasUpdateGroupBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr)
{
GroupItem *groupPtr = (GroupItem *) itemPtr;

    if(groupPtr->flags & GROUP_FLAG_DIRTY_BBOX) {
        TkPathCanvasGroupBbox(canvas, itemPtr,
            &itemPtr->x1, &itemPtr->y1, &itemPtr->x2, &itemPtr->y2);
        groupPtr->flags &= ~GROUP_FLAG_DIRTY_BBOX;
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvImage.c.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvImage.c --
 *
 *    This file implements an image canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

#define BBOX_OUT 2.0

/*
 * The structure below defines the record for each path item.
 */

typedef struct PimageItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * types.  MUST BE FIRST IN STRUCTURE. */
    Tk_PathCanvas canvas;      /* Canvas containing item. */
    double fillOpacity;
    TkPathMatrix *matrixPtr;   /*  a  b   default (NULL): 1 0
                                * c  d           0 1
                                * tx ty            0 0 */
    double coord[2];           /* nw coord. */
    Tcl_Obj *imageObj;         /* Object describing the -image option.
                                * NULL means no image right now. */
    Tk_Image image;            /* Image to display in window, or NULL if
                                * no image at present. */
    Tk_PhotoHandle photo;
    double width;              /* If 0 use natural width or height. */
    double height;
    Tk_Anchor anchor;          /* Where to anchor image relative to (x,y). */
    XColor *tintColor;
    double tintAmount;
    int interpolation;
    TkPathRect *srcRegionPtr;
} PimageItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePimageBbox(
    Tk_PathCanvas canvas,
    PimageItem * pimagePtr);
static int ConfigurePimage(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreatePimage(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void PimageBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int PimageCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PimageToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int PimageToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * item,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PimageToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static void ImageChangedProc(
    ClientData clientData,
    int x,
    int y,
    int width,
    int height,
    int imgWidth,
    int imgHeight);
static void PimageStyleChangedProc(
    ClientData clientData,
    int flags);

enum {
    PIMAGE_OPTION_INDEX_FILLOPACITY =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    PIMAGE_OPTION_INDEX_HEIGHT = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
    PIMAGE_OPTION_INDEX_IMAGE = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 3)),
    PIMAGE_OPTION_INDEX_MATRIX = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 4)),
    PIMAGE_OPTION_INDEX_WIDTH = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 5)),
    PIMAGE_OPTION_INDEX_ANCHOR = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 6)),
    PIMAGE_OPTION_INDEX_TINTCOLOR =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 7)),
    PIMAGE_OPTION_INDEX_TINTAMOUNT =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 8)),
    PIMAGE_OPTION_INDEX_INTERPOLATION =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 9)),
    PIMAGE_OPTION_INDEX_SRCREGION =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 10))
};

static const char *imageInterpolationST[] = {
    "none", "fast", "best", NULL
};

static int PathRectSetOption(
    ClientData clientData,
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Tcl_Obj ** value,
    char *recordPtr,
    int internalOffset,
    char *oldInternalPtr,
    int flags);
static Tcl_Obj *PathRectGetOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,
    int internalOffset);
static void PathRectRestoreOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,
    char *oldInternalPtr);
static void PathRectFreeOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr);

#define TK_PATH_STYLE_CUSTOM_OPTION_PATHRECT    \
    static Tk_ObjCustomOption pathRectCO = {    \
    "pathrect",                \
    PathRectSetOption,            \
    PathRectGetOption,            \
    PathRectRestoreOption,            \
    PathRectFreeOption,            \
    (ClientData) NULL            \
    };

TK_PATH_STYLE_CUSTOM_OPTION_MATRIX
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_STATE TK_PATH_STYLE_CUSTOM_OPTION_PATHRECT
#define TK_PATH_OPTION_SPEC_FILLOPACITY                \
    {TK_OPTION_DOUBLE, "-fillopacity", NULL, NULL,        \
    "1.0", -1, Tk_Offset(PimageItem, fillOpacity),        \
    0, 0, PIMAGE_OPTION_INDEX_FILLOPACITY}
#define TK_PATH_OPTION_SPEC_HEIGHT                    \
    {TK_OPTION_DOUBLE, "-height", NULL, NULL,            \
    "0", -1, Tk_Offset(PimageItem, height),            \
    0, 0, PIMAGE_OPTION_INDEX_HEIGHT}
#define TK_PATH_OPTION_SPEC_IMAGE                    \
    {TK_OPTION_STRING, "-image", NULL, NULL,            \
    NULL, Tk_Offset(PimageItem, imageObj), -1,        \
    TK_OPTION_NULL_OK, 0, PIMAGE_OPTION_INDEX_IMAGE}
#define TK_PATH_OPTION_SPEC_MATRIX                    \
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,            \
    NULL, -1, Tk_Offset(PimageItem, matrixPtr),        \
    TK_OPTION_NULL_OK, (ClientData) &matrixCO,        \
    PIMAGE_OPTION_INDEX_MATRIX}
#define TK_PATH_OPTION_SPEC_WIDTH                    \
    {TK_OPTION_DOUBLE, "-width", NULL, NULL,            \
    "0", -1, Tk_Offset(PimageItem, width),            \
    0, 0, PIMAGE_OPTION_INDEX_WIDTH}
#define TK_PATH_OPTION_SPEC_ANCHOR                    \
    {TK_OPTION_ANCHOR, "-anchor", NULL, NULL,            \
    "nw", -1, Tk_Offset(PimageItem, anchor),        \
    0, 0, 0}
#define TK_PATH_OPTION_SPEC_TINTCOLOR                \
    {TK_OPTION_COLOR, "-tintcolor", NULL, NULL,            \
    NULL, -1, Tk_Offset(PimageItem, tintColor),        \
    TK_OPTION_NULL_OK, 0, PIMAGE_OPTION_INDEX_TINTCOLOR}
#define TK_PATH_OPTION_SPEC_TINTAMOUNT                \
    {TK_OPTION_DOUBLE, "-tintamount", NULL, NULL,        \
    "0.5", -1, Tk_Offset(PimageItem, tintAmount),        \
    0, 0, PIMAGE_OPTION_INDEX_TINTAMOUNT}
#define TK_PATH_OPTION_SPEC_INTERPOLATION                \
    {TK_OPTION_STRING_TABLE, "-interpolation", NULL, NULL,  \
    "fast", -1, Tk_Offset(PimageItem, interpolation),   \
    0, (ClientData) imageInterpolationST, 0}
#define TK_PATH_OPTION_SPEC_SRCREGION                \
    {TK_OPTION_CUSTOM, "-srcregion", NULL, NULL,        \
    NULL, -1, Tk_Offset(PimageItem, srcRegionPtr),        \
    TK_OPTION_NULL_OK, (ClientData) &pathRectCO,        \
    PIMAGE_OPTION_INDEX_SRCREGION}
static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_MATRIX,
    TK_PATH_OPTION_SPEC_FILLOPACITY,
    TK_PATH_OPTION_SPEC_HEIGHT,
    TK_PATH_OPTION_SPEC_IMAGE,
    TK_PATH_OPTION_SPEC_WIDTH,
    TK_PATH_OPTION_SPEC_ANCHOR,
    TK_PATH_OPTION_SPEC_TINTCOLOR,
    TK_PATH_OPTION_SPEC_TINTAMOUNT,
    TK_PATH_OPTION_SPEC_INTERPOLATION,
    TK_PATH_OPTION_SPEC_SRCREGION,
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'image' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeImage = {
    "image",   /* name */
    sizeof(PimageItem), /* itemSize */
    CreatePimage,       /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigurePimage,    /* configureProc */
    PimageCoords,       /* coordProc */
    DeletePimage,       /* deleteProc */
    DisplayPimage,      /* displayProc */
    0,         /* flags */
    PimageBbox, /* bboxProc */
    PimageToPoint,      /* pointProc */
    PimageToArea,       /* areaProc */
    PimageToPdf,        /* pdfProc */
    ScalePimage,        /* scaleProc */
    TranslatePimage,    /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreatePimage(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pimagePtr->headerEx;
    int i;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    pimagePtr->fillOpacity = 1.0;
    pimagePtr->matrixPtr = NULL;
    pimagePtr->imageObj = NULL;
    pimagePtr->image = NULL;
    pimagePtr->photo = NULL;
    pimagePtr->height = 0;
    pimagePtr->width = 0;
    pimagePtr->anchor = TK_ANCHOR_NW;
    pimagePtr->tintColor = NULL;
    pimagePtr->tintAmount = 0.0;
    pimagePtr->interpolation = TK_PATH_IMAGEINTERPOLATION_Fast;
    pimagePtr->srcRegionPtr = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)pimagePtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(TkPathCoordsForPointItems(interp, canvas, pimagePtr->coord, i, objv)
        != TCL_OK) {
        goto error;
    }
    if(ConfigurePimage(interp, canvas, itemPtr, objc - i, objv + i, 0)
        == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the ConfigurePimage()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePimage(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PimageCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    int result;

    result =
        TkPathCoordsForPointItems(interp, canvas, pimagePtr->coord, objc, objv);
    if((result == TCL_OK) && ((objc == 1) || (objc == 2))) {
        ComputePimageBbox(canvas, pimagePtr);
    }
    return result;
}

/*
 * This is just a convenience function to obtain any style matrix.
 */

static TkPathMatrix
GetTMatrix(
    PimageItem * pimagePtr)
{
TkPathMatrix *matrixPtr;
Tk_PathStyle *stylePtr;
TkPathMatrix matrix = TkPathCanvasInheritTMatrix((Tk_PathItem *) pimagePtr);

    matrixPtr = pimagePtr->matrixPtr;
    if(pimagePtr->headerEx.styleInst != NULL) {
        stylePtr = pimagePtr->headerEx.styleInst->masterPtr;
        if(stylePtr->mask & TK_PATH_STYLE_OPTION_MATRIX) {
            matrixPtr = stylePtr->matrixPtr;
        }
    }
    if(matrixPtr != NULL) {
        TkPathMMulTMatrix(matrixPtr, &matrix);
    }
    return matrix;
}

void
ComputePimageBbox(
    Tk_PathCanvas canvas,
    PimageItem * pimagePtr)
{
Tk_PathItem *itemPtr = (Tk_PathItem *) pimagePtr;
Tk_PathState state = pimagePtr->headerEx.header.state;
TkPathMatrix matrix;
double width = 0.0, height = 0.0;
TkPathRect bbox;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(pimagePtr->image == NULL) {
        pimagePtr->headerEx.header.x1 = pimagePtr->headerEx.header.x2 =
            pimagePtr->headerEx.header.y1 = pimagePtr->headerEx.header.y2 = -1;
        return;
    }
    if(pimagePtr->srcRegionPtr) {
        width = pimagePtr->srcRegionPtr->x2 - pimagePtr->srcRegionPtr->x1;
        height = pimagePtr->srcRegionPtr->y2 - pimagePtr->srcRegionPtr->y1;
    } else {
int iwidth = 0, iheight = 0;
        Tk_SizeOfImage(pimagePtr->image, &iwidth, &iheight);
        width = iwidth;
        height = iheight;
    }
    if(pimagePtr->width > 0.0) {
        width = pimagePtr->width + 1.0;
    }
    if(pimagePtr->height > 0.0) {
        height = pimagePtr->height + 1.0;
    }

    switch (pimagePtr->anchor) {
    case TK_ANCHOR_NW:
    case TK_ANCHOR_W:
    case TK_ANCHOR_SW:
        bbox.x1 = pimagePtr->coord[0];
        break;

    case TK_ANCHOR_N:
    case TK_ANCHOR_CENTER:
    case TK_ANCHOR_S:
        bbox.x1 = pimagePtr->coord[0] - width / 2.0;
        break;

    case TK_ANCHOR_NE:
    case TK_ANCHOR_E:
    case TK_ANCHOR_SE:
        bbox.x1 = pimagePtr->coord[0] - width;
        break;
    }
    bbox.x2 = bbox.x1 + width;

    switch (pimagePtr->anchor) {
    case TK_ANCHOR_NW:
    case TK_ANCHOR_N:
    case TK_ANCHOR_NE:
        bbox.y1 = pimagePtr->coord[1];
        break;

    case TK_ANCHOR_W:
    case TK_ANCHOR_CENTER:
    case TK_ANCHOR_E:
        bbox.y1 = pimagePtr->coord[1] - height / 2.0;
        break;

    case TK_ANCHOR_SW:
    case TK_ANCHOR_S:
    case TK_ANCHOR_SE:
        bbox.y1 = pimagePtr->coord[1] - height;
        break;
    }
    bbox.y2 = bbox.y1 + height;

    bbox.x1 -= BBOX_OUT;
    bbox.x2 += BBOX_OUT;
    bbox.y1 -= BBOX_OUT;
    bbox.y2 += BBOX_OUT;

    itemPtr->bbox = bbox;
    itemPtr->totalBbox = itemPtr->bbox; /* FIXME */
    matrix = GetTMatrix(pimagePtr);
    TkPathSetGenericPathHeaderBbox(&pimagePtr->headerEx.header, &matrix, &bbox);
}

static int
ConfigurePimage(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tk_Window tkwin;
    Tk_Image image;
    Tk_PhotoHandle photo;
    Tk_SavedOptions savedOptions;
    Tk_PathItem *parentPtr;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)pimagePtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            if(errorResult != NULL) {
                Tcl_DecrRefCount(errorResult);
            }
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }

        /*
         * Take each custom option, not handled in Tk_SetOptions, in turn.
         */
        if(mask & TK_PATH_CORE_OPTION_PARENT) {
            if(TkPathCanvasFindGroup(interp, canvas, itemPtr->parentObj,
                    &parentPtr) != TCL_OK) {
                continue;
            }
            TkPathCanvasSetParent(parentPtr, itemPtr);
        } else if((itemPtr->id != 0) && (itemPtr->parentPtr == NULL)) {
            /*
             * If item not root and parent not set we must set it
             * to root by default.
             */
            TkPathCanvasSetParentToRoot(itemPtr);
        }

        /*
         * If we have got a style name it's options take precedence
         * over the actual path configuration options. This is how SVG does it.
         * Good or bad?
         */
        if(mask & TK_PATH_CORE_OPTION_STYLENAME) {
    TkPathStyleInst *styleInst = NULL;

            if(pimagePtr->headerEx.styleObj != NULL) {
                styleInst = TkPathGetStyle(interp,
                    Tcl_GetString(pimagePtr->headerEx.styleObj),
                    TkPathCanvasStyleTable(canvas), PimageStyleChangedProc,
                    (ClientData) itemPtr);
                if(styleInst == NULL) {
                    continue;
                }
            } else {
                styleInst = NULL;
            }
            if(pimagePtr->headerEx.styleInst != NULL) {
                TkPathFreeStyle(pimagePtr->headerEx.styleInst);
            }
            pimagePtr->headerEx.styleInst = styleInst;
        }

        /*
         * Create the image.  Save the old image around and don't free it
         * until after the new one is allocated.  This keeps the reference
         * count from going to zero so the image doesn't have to be recreated
         * if it hasn't changed.
         */
        if(!error && (mask & PIMAGE_OPTION_INDEX_IMAGE)) {
            if(pimagePtr->imageObj != NULL) {
    const char *name = Tcl_GetString(pimagePtr->imageObj);

                image = Tk_GetImage(interp, tkwin, name,
                    ImageChangedProc, (ClientData) pimagePtr);
                if(image == NULL) {
                    continue;
                }
                photo = Tk_FindPhoto(interp, name);
                if(photo == NULL) {
                    Tk_FreeImage(image);
                    Tcl_SetObjResult(interp,
                        Tcl_NewStringObj("no photo with the given name", -1));
                    continue;
                }
            } else {
                image = NULL;
                photo = NULL;
            }
            if(pimagePtr->image != NULL) {
                Tk_FreeImage(pimagePtr->image);
            }
            pimagePtr->image = image;
            pimagePtr->photo = photo;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
    }
    pimagePtr->fillOpacity = MAX(0.0, MIN(1.0, pimagePtr->fillOpacity));

    if(errorResult != NULL) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    }
    /*
     * Recompute bounding box for path.
     */
    ComputePimageBbox(canvas, pimagePtr);
    return TCL_OK;
}

static void
DeletePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
PimageItem *pimagePtr = (PimageItem *) itemPtr;

    if(pimagePtr->headerEx.styleInst != NULL) {
        TkPathFreeStyle(pimagePtr->headerEx.styleInst);
    }
    if(pimagePtr->image != NULL) {
        Tk_FreeImage(pimagePtr->image);
    }
    Tk_FreeConfigOptions((char *)pimagePtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathContext ctx;

    ctx = ContextOfCanvas(canvas);
    TkPathPushTMatrix(ctx, &m);
    m = GetTMatrix(pimagePtr);
    TkPathPushTMatrix(ctx, &m);
    /* @@@ Maybe we should taking care of x, y etc.? */
    TkPathImage(ctx, pimagePtr->image, pimagePtr->photo,
        itemPtr->bbox.x1 + BBOX_OUT, itemPtr->bbox.y1 + BBOX_OUT,
        pimagePtr->width, pimagePtr->height, pimagePtr->fillOpacity,
        pimagePtr->tintColor, pimagePtr->tintAmount,
        pimagePtr->interpolation, pimagePtr->srcRegionPtr);
}

static void
PimageBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    ComputePimageBbox(canvas, pimagePtr);
}

static double
PimageToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = GetTMatrix(pimagePtr);
    return TkPathRectToPointWithMatrix(itemPtr->bbox, &m, pointPtr);
}

static int
PimageToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    TkPathMatrix m = GetTMatrix(pimagePtr);
    return TkPathRectToAreaWithMatrix(itemPtr->bbox, &m, areaPtr);
}

static int
PimageToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    PimageItem *pimagePtr = (PimageItem *) itemPtr;
    Tcl_Obj *ret, *obj;
    TkPathMatrix matrix = { 1., 0., 0., 1., 0., 0. };
    Tk_PathState state = itemPtr->state;
    Tk_PhotoImageBlock block;
    int x, y;
    unsigned char *p;
    double tintR, tintG, tintB, tintAmount;
    TkPathRect srcRegion, bbox;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((pimagePtr->photo == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        return TCL_OK;  /* nothing to display */
    }
    Tk_PhotoGetImage(pimagePtr->photo, &block);
    if((block.width <= 0) || (block.height <= 0)) {
        return TCL_OK;  /* nothing to display */
    }
    if(pimagePtr->srcRegionPtr == NULL) {
        srcRegion.x1 = 0;
        srcRegion.y1 = 0;
        srcRegion.x2 = block.width;
        srcRegion.y2 = block.height;
    } else {
        srcRegion = *pimagePtr->srcRegionPtr;
    }
    bbox = itemPtr->bbox;
    /* undo effect of BBOX_OUT */
    bbox.x1 += BBOX_OUT - 1;
    bbox.x2 -= BBOX_OUT + 1;
    bbox.y1 += BBOX_OUT - 1;
    bbox.y2 -= BBOX_OUT + 1;

    if(objc > 0) {
    long id;
    int retc, opacity, tx, ty;
    int zLen;
    double scaleX, scaleY, dx, dy;
    Tcl_Obj *pixObj, *nameObj, **retv;

        /*
         * Callback provided, first make alpha mask.
         */
        opacity = (int)(pimagePtr->fillOpacity * 256);
        if(opacity > 256) {
            opacity = 256;
        } else if(opacity < 0) {
            opacity = 0;
        }
        pixObj = Tcl_NewObj();
        p = Tcl_SetByteArrayLength(pixObj, block.width * block.height);
        for(y = 0; y < block.height; y++) {
    unsigned char *q = block.pixelPtr + y * block.pitch;

            for(x = 0; x < block.width; x++) {
                *p++ = ((int)q[block.offset[3]] * opacity) >> 8;
                q += block.pixelSize;
            }
        }
        zLen = 0;
        if(Tcl_ZlibDeflate(interp, TCL_ZLIB_FORMAT_ZLIB,
                pixObj, 9, NULL) == TCL_OK) {
            p = Tcl_GetByteArrayFromObj(Tcl_GetObjResult(interp), &zLen);
            if(zLen > 0) {
                Tcl_DecrRefCount(pixObj);
                pixObj = Tcl_GetObjResult(interp);
            }
            Tcl_IncrRefCount(pixObj);
        }
        Tcl_ResetResult(interp);
        obj = Tcl_NewObj();
        Tcl_AppendPrintfToObj(obj, "<<\n/Type /XObject\n/Subtype /Image\n"
            "/ColorSpace /DeviceGray\n/BitsPerComponent 8\n"
            "/Width %d\n/Height %d\n", block.width, block.height);
        if(zLen > 0) {
            Tcl_AppendPrintfToObj(obj, "/Filter /FlateDecode\n"
                "/Length %d\n>>\nstream\n", zLen);
        } else {
            Tcl_AppendPrintfToObj(obj, "/Length %d\n>>\nstream\n",
                block.width * block.height);
        }
        Tcl_AppendObjToObj(obj, pixObj);
        Tcl_DecrRefCount(pixObj);
        Tcl_AppendToObj(obj, "\nendstream\n", 11);
        ret = Tcl_DuplicateObj(objv[0]);
        Tcl_IncrRefCount(ret);
        if((Tcl_ListObjAppendElement(interp, ret,
                    Tcl_NewIntObj(block.width)) != TCL_OK) ||
            (Tcl_ListObjAppendElement(interp, ret,
                    Tcl_NewIntObj(block.height)) != TCL_OK) ||
            (Tcl_ListObjAppendElement(interp, ret, obj) != TCL_OK)) {
            Tcl_DecrRefCount(ret);
            Tcl_DecrRefCount(obj);
            return TCL_ERROR;
        }
        if(Tcl_EvalObjEx(interp, ret, TCL_EVAL_DIRECT) != TCL_OK) {
            Tcl_DecrRefCount(ret);
            return TCL_ERROR;
        }
        Tcl_DecrRefCount(ret);
        /*
         * Remember result information (object id of alpha channel).
         */
        if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                &retc, &retv) != TCL_OK) {
            return TCL_ERROR;
        }
        if(retc < 1) {
            Tcl_SetResult(interp, (char *)"missing PDF id", TCL_STATIC);
            return TCL_ERROR;
        }
        Tcl_GetLongFromObj(NULL, retv[0], &id);
        /*
         * Make RGB image.
         */
        tintAmount = pimagePtr->tintAmount;
        if((pimagePtr->tintColor != NULL) && (tintAmount > 0.0)) {
            if(tintAmount > 1.0) {
                tintAmount = 1.0;
            }
            tintR = (double)(pimagePtr->tintColor->red >> 8) / 0xff;
            tintG = (double)(pimagePtr->tintColor->green >> 8) / 0xff;
            tintB = (double)(pimagePtr->tintColor->blue >> 8) / 0xff;
        } else {
            tintAmount = 0.0;
            tintR = 0.0;
            tintG = 0.0;
            tintB = 0.0;
        }
        pixObj = Tcl_NewObj();
        p = Tcl_SetByteArrayLength(pixObj, block.width * block.height * 3);
        for(y = 0; y < block.height; y++) {
    unsigned char R, G, B;
    unsigned char *q = block.pixelPtr + y * block.pitch;

            for(x = 0; x < block.width; x++) {
                R = q[block.offset[0]];
                G = q[block.offset[1]];
                B = q[block.offset[2]];
                if(tintAmount > 0.0) {
    int RR, GG, BB;

                    RR = (int)((1.0 - tintAmount) * R +
                        (tintAmount * tintR * 0.2126 * R +
                            tintAmount * tintR * 0.7152 * G +
                            tintAmount * tintR * 0.0722 * B));
                    GG = (int)((1.0 - tintAmount) * G +
                        (tintAmount * tintG * 0.2126 * R +
                            tintAmount * tintG * 0.7152 * G +
                            tintAmount * tintG * 0.0722 * B));
                    BB = (int)((1.0 - tintAmount) * B +
                        (tintAmount * tintB * 0.2126 * R +
                            tintAmount * tintB * 0.7152 * G +
                            tintAmount * tintB * 0.0722 * B));
                    R = (RR > 0xff) ? 0xff : RR;
                    G = (GG > 0xff) ? 0xff : GG;
                    B = (BB > 0xff) ? 0xff : BB;
                }
                *p++ = R;
                *p++ = G;
                *p++ = B;
                q += block.pixelSize;
            }
        }
        zLen = 0;
        if(Tcl_ZlibDeflate(interp, TCL_ZLIB_FORMAT_ZLIB,
                pixObj, 9, NULL) == TCL_OK) {
            p = Tcl_GetByteArrayFromObj(Tcl_GetObjResult(interp), &zLen);
            if(zLen > 0) {
                Tcl_DecrRefCount(pixObj);
                pixObj = Tcl_GetObjResult(interp);
            }
            Tcl_IncrRefCount(pixObj);
        }
        Tcl_ResetResult(interp);
        obj = Tcl_NewObj();
        Tcl_AppendPrintfToObj(obj, "<<\n/Type /XObject\n/Subtype /Image\n"
            "/ColorSpace /DeviceRGB\n/BitsPerComponent 8\n"
            "/Width %d\n/Height %d\n/SMask %ld 0 R\n",
            block.width, block.height, id);
        if((pimagePtr->interpolation == TK_PATH_IMAGEINTERPOLATION_Fast) ||
            (pimagePtr->interpolation == TK_PATH_IMAGEINTERPOLATION_Best)) {
            Tcl_AppendToObj(obj, "/Interpolate true\n", 18);
        }
        if(zLen > 0) {
            Tcl_AppendPrintfToObj(obj, "/Filter /FlateDecode\n"
                "/Length %d\n>>\nstream\n", zLen);
        } else {
            Tcl_AppendPrintfToObj(obj, "/Length %d\n>>\nstream\n",
                block.width * block.height * 3);
        }
        Tcl_AppendObjToObj(obj, pixObj);
        Tcl_DecrRefCount(pixObj);
        Tcl_AppendToObj(obj, "\nendstream\n", 11);
        ret = Tcl_DuplicateObj(objv[0]);
        Tcl_IncrRefCount(ret);
        if((Tcl_ListObjAppendElement(interp, ret,
                    Tcl_NewIntObj(block.width)) != TCL_OK) ||
            (Tcl_ListObjAppendElement(interp, ret,
                    Tcl_NewIntObj(block.height)) != TCL_OK) ||
            (Tcl_ListObjAppendElement(interp, ret, obj) != TCL_OK)) {
            Tcl_DecrRefCount(ret);
            Tcl_DecrRefCount(obj);
            return TCL_ERROR;
        }
        if(Tcl_EvalObjEx(interp, ret, TCL_EVAL_DIRECT) != TCL_OK) {
            Tcl_DecrRefCount(ret);
            return TCL_ERROR;
        }
        Tcl_DecrRefCount(ret);
        /*
         * Remember result information (name of RGB image).
         */
        if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                &retc, &retv) != TCL_OK) {
            return TCL_ERROR;
        }
        if(retc < 2) {
            Tcl_SetResult(interp, (char *)"missing PDF id/name", TCL_STATIC);
            return TCL_ERROR;
        }
        nameObj = retv[1];
        Tcl_IncrRefCount(nameObj);
        /*
         * Print image object(s).
         */
        ret = Tcl_NewObj();
        style = TkPathCanvasInheritStyle(itemPtr, 0);
        matrix = GetTMatrix(pimagePtr);
        /* TkPathMatrix */
        TkPathPdfNumber(ret, 6, matrix.a, " ");
        TkPathPdfNumber(ret, 6, matrix.b, " ");
        TkPathPdfNumber(ret, 6, matrix.c, " ");
        TkPathPdfNumber(ret, 6, matrix.d, " ");
        TkPathPdfNumber(ret, 3, matrix.tx, " ");
        TkPathPdfNumber(ret, 3, matrix.ty, " cm\n");
        /* translate */
        Tcl_AppendToObj(ret, "1 0 0 1 ", 8);
        TkPathPdfNumber(ret, 3, bbox.x1, " ");
        TkPathPdfNumber(ret, 3, bbox.y2, " cm\n");
        /* clipping */
        Tcl_AppendToObj(ret, "0 0 m ", 6);
        TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " 0 l ");
        TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " ");
        TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l 0 ");
        TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l W n\n");
        tx = ty = 1;
        dx = srcRegion.x2 - srcRegion.x1;
        if(dx > block.width) {
            tx += (int)((srcRegion.x2 - srcRegion.x1) / block.width);
        } else {
            srcRegion.x1 = fmod(srcRegion.x1, (double)block.width);
            srcRegion.x2 = srcRegion.x1 + dx;
            if(srcRegion.x1 != 0) {
                tx++;
            }
        }
        dy = srcRegion.y2 - srcRegion.y1;
        if(dy > block.height) {
            ty += (int)((srcRegion.y2 - srcRegion.y1) / block.height);
        } else {
            srcRegion.y1 = fmod(srcRegion.y1, (double)block.height);
            srcRegion.y2 = srcRegion.y1 + dy;
            if(srcRegion.y1 != 0) {
                ty++;
            }
        }
        if(pimagePtr->width > 0) {
            scaleX = pimagePtr->width / (double)block.width;
            scaleX /= (srcRegion.x2 - srcRegion.x1) / block.width;
        } else {
            scaleX = 1.0;
        }
        if(pimagePtr->height > 0) {
            scaleY = pimagePtr->height / (double)block.height;
            scaleY /= (srcRegion.y2 - srcRegion.y1) / block.height;
        } else {
            scaleY = 1.0;
        }
        for(x = 0; x < tx; x++) {
            for(y = 0; y < ty; y++) {
                /* translate */
                Tcl_AppendToObj(ret, "q\n1 0 0 1 ", 10);
                TkPathPdfNumber(ret, 6, (x * block.width - srcRegion.x1) *
                    scaleX, " ");
                TkPathPdfNumber(ret, 6, -(srcRegion.y2 - (ty - y) *
                        block.height) * scaleY, " cm\n");
                /* scale to requested image size */
                TkPathPdfNumber(ret, 6, scaleX * block.width, " 0 0 ");
                TkPathPdfNumber(ret, 6, -scaleY * block.height, " 0 0 cm\n");
                /* print it */
                Tcl_AppendPrintfToObj(ret, "/%s Do\nQ\n",
                    Tcl_GetString(nameObj));
            }
        }
        Tcl_DecrRefCount(nameObj);
        Tcl_SetObjResult(interp, ret);
        TkPathCanvasFreeInheritedStyle(&style);
    } else {
        /*
         * No callback, make direct RGB image without alpha mask.
         */
        ret = Tcl_NewObj();
        style = TkPathCanvasInheritStyle(itemPtr, 0);
        matrix = GetTMatrix(pimagePtr);
        /* TkPathMatrix */
        TkPathPdfNumber(ret, 6, matrix.a, " ");
        TkPathPdfNumber(ret, 6, matrix.b, " ");
        TkPathPdfNumber(ret, 6, matrix.c, " ");
        TkPathPdfNumber(ret, 6, matrix.d, " ");
        TkPathPdfNumber(ret, 3, matrix.tx, " ");
        TkPathPdfNumber(ret, 3, matrix.ty, " cm\n");
        /* translate */
        Tcl_AppendToObj(ret, "1 0 0 1 ", 8);
        TkPathPdfNumber(ret, 3, bbox.x1, " ");
        TkPathPdfNumber(ret, 3, bbox.y2, " cm\n");
        /* clipping */
        Tcl_AppendToObj(ret, "0 0 m ", 6);
        TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " 0 l ");
        TkPathPdfNumber(ret, 3, bbox.x2 - bbox.x1, " ");
        TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l 0 ");
        TkPathPdfNumber(ret, 3, bbox.y1 - bbox.y2, " l W n\n");
        /* scale to requested image size, no cropping/tiling */
        TkPathPdfNumber(ret, 6, (pimagePtr->width > 0) ? pimagePtr->width :
            (double)block.width, " 0 0 ");
        TkPathPdfNumber(ret, 6, (pimagePtr->height > 0) ? pimagePtr->height :
            (double)-block.height, " 0 0 cm\n");
        Tcl_AppendToObj(ret, "BI\n", 3);
        Tcl_AppendPrintfToObj(ret, "/W %d\n/H %d\n", block.width, block.height);
        Tcl_AppendToObj(ret, "/CS /RGB\n/BPC 8\nID\n", 19);
        tintAmount = pimagePtr->tintAmount;
        if((pimagePtr->tintColor != NULL) && (tintAmount > 0.0)) {
            if(tintAmount > 1.0) {
                tintAmount = 1.0;
            }
            tintR = (double)(pimagePtr->tintColor->red >> 8) / 0xff;
            tintG = (double)(pimagePtr->tintColor->green >> 8) / 0xff;
            tintB = (double)(pimagePtr->tintColor->blue >> 8) / 0xff;
        } else {
            tintAmount = 0.0;
            tintR = 0.0;
            tintG = 0.0;
            tintB = 0.0;
        }
        obj = Tcl_NewObj();
        p = Tcl_SetByteArrayLength(obj, block.width * block.height * 3);
        for(y = 0; y < block.height; y++) {
    unsigned char R, G, B;
    unsigned char *q = block.pixelPtr + y * block.pitch;

            for(x = 0; x < block.width; x++) {
                R = q[block.offset[0]];
                G = q[block.offset[1]];
                B = q[block.offset[2]];
                if(tintAmount > 0.0) {
    int RR, GG, BB;

                    RR = (int)((1.0 - tintAmount) * R +
                        (tintAmount * tintR * 0.2126 * R +
                            tintAmount * tintR * 0.7152 * G +
                            tintAmount * tintR * 0.0722 * B));
                    GG = (int)((1.0 - tintAmount) * G +
                        (tintAmount * tintG * 0.2126 * R +
                            tintAmount * tintG * 0.7152 * G +
                            tintAmount * tintG * 0.0722 * B));
                    BB = (int)((1.0 - tintAmount) * B +
                        (tintAmount * tintB * 0.2126 * R +
                            tintAmount * tintB * 0.7152 * G +
                            tintAmount * tintB * 0.0722 * B));
                    R = (RR > 0xff) ? 0xff : RR;
                    G = (GG > 0xff) ? 0xff : GG;
                    B = (BB > 0xff) ? 0xff : BB;
                }
                *p++ = R;
                *p++ = G;
                *p++ = B;
                q += block.pixelSize;
            }
        }
        Tcl_AppendObjToObj(ret, obj);
        Tcl_DecrRefCount(obj);
        Tcl_AppendToObj(ret, "\nEI\n", 4);
        Tcl_SetObjResult(interp, ret);
        TkPathCanvasFreeInheritedStyle(&style);
    }
    return TCL_OK;
}

static void
ScalePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    /* Skip? */
}

static void
TranslatePimage(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    PimageItem *pimagePtr = (PimageItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Translate coordinates. */
    pimagePtr->coord[0] += deltaX;
    pimagePtr->coord[1] += deltaY;
    /* Recompute bounding box. */
    ComputePimageBbox(canvas, pimagePtr);
}

static void
ImageChangedProc(
    ClientData clientData,     /* Pointer to canvas item for image. */
    int x,
    int y,                     /* Upper left pixel (within image)
                                * that must be redisplayed. */
    int width,
    int height,                /* Dimensions of area to redisplay
                                * (may be <= 0). */
    int imgWidth,
    int imgHeight)
{              /* New dimensions of image. */
    PimageItem *pimagePtr = (PimageItem *) clientData;

    /*
     * If the image's size changed and it's not anchored at its
     * northwest corner then just redisplay the entire area of the
     * image.  This is a bit over-conservative, but we need to do
     * something because a size change also means a position change.
     */

    /* @@@ MUST consider our own width and height settings as well and TMatrix. */

    if(((pimagePtr->headerEx.header.x2 - pimagePtr->headerEx.header.x1) !=
            imgWidth)
        || ((pimagePtr->headerEx.header.y2 - pimagePtr->headerEx.header.y1) !=
            imgHeight)) {
        x = y = 0;
        width = imgWidth;
        height = imgHeight;
        Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
            pimagePtr->headerEx.header.x1, pimagePtr->headerEx.header.y1,
            pimagePtr->headerEx.header.x2, pimagePtr->headerEx.header.y2);
    }
    ComputePimageBbox(pimagePtr->headerEx.canvas, pimagePtr);
    Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
        pimagePtr->headerEx.header.x1 + x,
        pimagePtr->headerEx.header.y1 + y,
        (int)(pimagePtr->headerEx.header.x1 + x + width),
        (int)(pimagePtr->headerEx.header.y1 + y + height));
}

static void
PimageStyleChangedProc(
    ClientData clientData,
    int flags)
{
    Tk_PathItem *itemPtr = (Tk_PathItem *) clientData;
    PimageItem *pimagePtr = (PimageItem *) itemPtr;

    if(flags) {
        if(flags & TK_PATH_STYLE_FLAG_DELETE) {
            TkPathFreeStyle(pimagePtr->headerEx.styleInst);
            pimagePtr->headerEx.styleInst = NULL;
            Tcl_DecrRefCount(pimagePtr->headerEx.styleObj);
            pimagePtr->headerEx.styleObj = NULL;
        }
        Tk_PathCanvasEventuallyRedraw(pimagePtr->headerEx.canvas,
            itemPtr->x1, itemPtr->y1, itemPtr->x2, itemPtr->y2);
    }
}

static int
PathGetPathRect(
    Tcl_Interp * interp,
    const char *list,          /* Object containg the lists for the matrix. */
    TkPathRect * rectPtr)
{              /* Where to store TkPathMatrix corresponding
                * to list. Must be allocated! */
    const char **argv = NULL;
    int i, argc;
    int result = TCL_OK;
    double tmp[4];

    /* Check matrix consistency. */
    if(Tcl_SplitList(interp, list, &argc, &argv) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(argc != 4) {
        Tcl_AppendResult(interp, "rect \"", list, "\" is inconsistent",
            (char *)NULL);
        result = TCL_ERROR;
        goto bail;
    }

    /* Take each row in turn. */
    for(i = 0; i < 4; i++) {
        if(Tcl_GetDouble(interp, argv[i], &(tmp[i])) != TCL_OK) {
            Tcl_AppendResult(interp, "rect \"", list, "\" is inconsistent",
                (char *)NULL);
            result = TCL_ERROR;
            goto bail;
        }
    }

    /* TkPathRect. */
    rectPtr->x1 = tmp[0];
    rectPtr->y1 = tmp[1];
    rectPtr->x2 = tmp[2];
    rectPtr->y2 = tmp[3];

  bail:
    if(argv != NULL) {
        Tcl_Free((char *)argv);
    }
    return result;
}

static int
PathGetTclObjFromPathRect(
    Tcl_Interp * interp,
    TkPathRect * rectPtr,
    Tcl_Obj ** listObjPtrPtr)
{
Tcl_Obj *listObj;

    /* @@@ Error handling remains. */

    listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    if(rectPtr != NULL) {
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(rectPtr->x1));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(rectPtr->y1));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(rectPtr->x2));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(rectPtr->y2));
    }
    *listObjPtrPtr = listObj;
    return TCL_OK;
}

/*
 * The -srcregion custom option.
 */

static int
    PathRectSetOption(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    char *list;
    int length;
    Tcl_Obj *valuePtr;
    TkPathRect *newPtr;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            list = Tcl_GetStringFromObj(valuePtr, &length);
            newPtr = (TkPathRect *) ckalloc(sizeof(TkPathRect));
            if(PathGetPathRect(interp, list, newPtr) != TCL_OK) {
                ckfree((char *)newPtr);
                return TCL_ERROR;
            }
        } else {
            newPtr = NULL;
        }
        *((TkPathRect **) oldInternalPtr) = *((TkPathRect **) internalPtr);
        *((TkPathRect **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

static Tcl_Obj *
PathRectGetOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
    char *internalPtr;
    TkPathRect *pathRectPtr;
    Tcl_Obj *listObj;

    /* @@@ An alternative to this could be to have an objOffset in option table. */
    internalPtr = recordPtr + internalOffset;
    pathRectPtr = *((TkPathRect **) internalPtr);
    PathGetTclObjFromPathRect(NULL, pathRectPtr, &listObj);
    return listObj;
}

static void
PathRectRestoreOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkPathRect **) internalPtr = *(TkPathRect **) oldInternalPtr;
}

static void
PathRectFreeOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        ckfree(*((char **)internalPtr));
        *((char **)internalPtr) = NULL;
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvLine.c.




























































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvLine.c --
 *
 *    This file implements a line canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PlineItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    TkPathRect coords;         /* Coordinates (unorders bare bbox). */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
} PlineItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePlineBbox(
    Tk_PathCanvas canvas,
    PlineItem * plinePtr);
static int ConfigurePline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreatePline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void PlineBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int ProcessCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PlineCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PlineToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int PlineToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PlineToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static TkPathAtom *MakePathAtoms(
    PlineItem * plinePtr);
static int ConfigureArrows(
    Tk_PathCanvas canvas,
    PlineItem * linePtr);

TK_PATH_STYLE_CUSTOM_OPTION_MATRIX
    TK_PATH_STYLE_CUSTOM_OPTION_DASH
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_STROKE
    TK_PATH_OPTION_STRING_TABLES_STATE static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PlineItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PlineItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeLine = {
    "line",    /* name */
    sizeof(PlineItem),  /* itemSize */
    CreatePline,        /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigurePline,     /* configureProc */
    PlineCoords,        /* coordProc */
    DeletePline,        /* deleteProc */
    DisplayPline,       /* displayProc */
    0,         /* flags */
    PlineBbox, /* bboxProc */
    PlineToPoint,       /* pointProc */
    PlineToArea,        /* areaProc */
    PlineToPdf, /* pdfProc */
    ScalePline, /* scaleProc */
    TranslatePline,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreatePline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
    int i;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    TkPathArrowDescrInit(&plinePtr->startarrow);
    TkPathArrowDescrInit(&plinePtr->endarrow);

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)plinePtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(ProcessCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
        goto error;
    }
    if(ConfigurePline(interp, canvas, itemPtr, objc - i, objv + i, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePline(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
ProcessCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    TkPathRect *p = &plinePtr->coords;

    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewObj();
    Tcl_Obj *subobj = Tcl_NewDoubleObj(p->x1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->y1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->x2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(p->y2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if((objc == 1) || (objc == 4)) {
        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 4) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coordinates: expected 0 or 4",
                        -1));
                return TCL_ERROR;
            }
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0],
                    &p->x1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                    &p->y1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[2],
                    &p->x2) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[3],
                    &p->y2) != TCL_OK)) {
            return TCL_ERROR;
        }
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coordinates: expected 0 or 4", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
PlineCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    int result;

    result = ProcessCoords(interp, canvas, itemPtr, objc, objv);
    if((result == TCL_OK) && ((objc == 1) || (objc == 4))) {
        ConfigureArrows(canvas, plinePtr);
        ComputePlineBbox(canvas, plinePtr);
    }
    return result;
}

static void
ComputePlineBbox(
    Tk_PathCanvas canvas,
    PlineItem * plinePtr)
{
Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;
TkPathRect r;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
            itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    r.x1 = MIN(plinePtr->coords.x1, plinePtr->coords.x2);
    r.x2 = MAX(plinePtr->coords.x1, plinePtr->coords.x2);
    r.y1 = MIN(plinePtr->coords.y1, plinePtr->coords.y2);
    r.y2 = MAX(plinePtr->coords.y1, plinePtr->coords.y2);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->startarrow);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->endarrow);
    itemPtr->bbox = r;
    itemPtr->totalBbox =
        TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &r);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error;
    int mask = 0;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)plinePtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }

    /*
     * Setup arrowheads, if needed. If arrowheads are turned off, restore the
     * line's endpoints (they were shortened when the arrowheads were added).
     */
    ConfigureArrows(canvas, plinePtr);

    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePlineBbox(canvas, plinePtr);
        return TCL_OK;
    }
}

static TkPathAtom *
MakePathAtoms(
    PlineItem * plinePtr)
{
TkPathAtom *atomPtr;

    atomPtr = TkPathNewMoveToAtom(plinePtr->coords.x1, plinePtr->coords.y1);
    atomPtr->nextPtr =
        TkPathNewLineToAtom(plinePtr->coords.x2, plinePtr->coords.y2);
    return atomPtr;
}

static void
DeletePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
PlineItem *plinePtr = (PlineItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &plinePtr->headerEx;

    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    TkPathFreeArrow(&plinePtr->startarrow);
    TkPathFreeArrow(&plinePtr->endarrow);
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathRect r;
    TkPathAtom *atomPtr;
    Tk_PathStyle style;

    r.x1 = MIN(plinePtr->coords.x1, plinePtr->coords.x2);
    r.x2 = MAX(plinePtr->coords.x1, plinePtr->coords.x2);
    r.y1 = MIN(plinePtr->coords.y1, plinePtr->coords.y2);
    r.y2 = MAX(plinePtr->coords.y1, plinePtr->coords.y2);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->startarrow);
    TkPathIncludeArrowPointsInRect(&r, &plinePtr->endarrow);

    atomPtr = MakePathAtoms(plinePtr);
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style, &m, &r);
    TkPathFreeAtoms(atomPtr);

    /*
     * Display arrowheads, if they are wanted.
     */
    TkPathDisplayArrow(canvas, &plinePtr->startarrow, &style, &m, &r);
    TkPathDisplayArrow(canvas, &plinePtr->endarrow, &style, &m, &r);

    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PlineBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    ComputePlineBbox(canvas, plinePtr);
}

static double
PlineToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    double point;

    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /* @@@ Perhaps we should do a simplified treatment here instead of the generic. */
    atomPtr = MakePathAtoms(plinePtr);
    point = TkPathGenericPathToPoint(canvas, itemPtr, &style,
        atomPtr, 2, pointPtr);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return point;
}

static int
PlineToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /* @@@ Perhaps we should do a simplified treatment here instead of the generic. */
    atomPtr = MakePathAtoms(plinePtr);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
        atomPtr, 2, areaPtr);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PlineToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    PlineItem *plinePtr = (PlineItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    atomPtr = TkPathNewMoveToAtom(plinePtr->coords.x1, plinePtr->coords.y1);
    atomPtr->nextPtr =
        TkPathNewLineToAtom(plinePtr->coords.x2, plinePtr->coords.y2);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    if(result == TCL_OK) {
        result = TkPathPdfArrow(interp, &plinePtr->startarrow, &style);
        if(result == TCL_OK) {
            result = TkPathPdfArrow(interp, &plinePtr->endarrow, &style);
        }
    }
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScalePathRect(&plinePtr->coords, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&plinePtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&plinePtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, plinePtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePline(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    PlineItem *plinePtr = (PlineItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Just translate the bbox as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslatePathRect(&plinePtr->coords, deltaX, deltaY);
    TkPathTranslateArrow(&plinePtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&plinePtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*--------------------------------------------------------------
 *
 * ConfigureArrows --
 *
 *  If arrowheads have been requested for a line, this function makes
 *  arrangements for the arrowheads.
 *
 * Results:
 *  Always returns TCL_OK.
 *
 * Side effects:
 *  Information in linePtr is set up for one or two arrowheads. The
 *  startarrowPtr and endarrowPtr polygons are allocated and initialized,
 *  if need be, and the end points of the line are adjusted so that a
 *  thick line doesn't stick out past the arrowheads.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureArrows(
    Tk_PathCanvas canvas,      /* Canvas in which arrows will be displayed
                                * (interp and tkwin fields are needed). */
    PlineItem * linePtr)
{              /* Item to configure for arrows. */
TkPathPoint pf, pl, newp;
Tk_PathStyle *lineStyle = &linePtr->headerEx.style;
int dontFill = lineStyle->fill == NULL;
Tk_PathState state = linePtr->headerEx.header.state;

    if(state == TK_PATHSTATE_NULL) {
        state = ((TkPathCanvas *) canvas)->canvas_state;
    }

    pf.x = linePtr->coords.x1;
    pf.y = linePtr->coords.y1;
    pl.x = linePtr->coords.x2;
    pl.y = linePtr->coords.y2;

    TkPathPreconfigureArrow(&pf, &linePtr->startarrow);
    TkPathPreconfigureArrow(&pl, &linePtr->endarrow);

    newp =
        TkPathConfigureArrow(pf, pl, &linePtr->startarrow, lineStyle, dontFill);
    linePtr->coords.x1 = newp.x;
    linePtr->coords.y1 = newp.y;

    newp =
        TkPathConfigureArrow(pl, pf, &linePtr->endarrow, lineStyle, dontFill);
    linePtr->coords.x2 = newp.x;
    linePtr->coords.y2 = newp.y;

    return TCL_OK;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvPath.c.












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvPath.c --
 *
 *  This file implements a path canvas item modelled after its
 *  SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/* Values for the PathItem's flag. */

enum {
    kPathItemNeedNewNormalizedPath = (1L << 0)
};

/*
 * The structure below defines the record for each path item.
 */

typedef struct PathItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    Tcl_Obj *pathObjPtr;       /* The object containing the path definition. */
    int pathLen;
    Tcl_Obj *normPathObjPtr;   /* The object containing the normalized path. */
    TkPathAtom *atomPtr;
    int maxNumSegments;        /* Max number of straight segments (for subpath)
                                * needed for Area and Point functions. */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
    long flags;                /* Various flags, see enum. */
} PathItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePathBbox(
    Tk_PathCanvas canvas,
    PathItem * pathPtr);
static int ConfigurePath(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreatePath(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int ProcessPath(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PathCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePath(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPath(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable dst,
    int x,
    int y,
    int width,
    int height);
static void PathBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int PathToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr);
static int PathToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PathToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePath(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePath(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static int ConfigureArrows(
    Tk_PathCanvas canvas,
    PathItem * pathPtr);

/* Support functions. */

static int GetSubpathMaxNumSegments(
    TkPathAtom * atomPtr);

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE
    TK_PATH_OPTION_STRING_TABLES_STATE static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PathItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PathItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'path' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypePath = {
    "path",    /* name */
    sizeof(PathItem),   /* itemSize */
    CreatePath, /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigurePath,      /* configureProc */
    PathCoords, /* coordProc */
    DeletePath, /* deleteProc */
    DisplayPath,        /* displayProc */
    0,         /* flags */
    PathBbox,  /* bboxProc */
    PathToPoint,        /* pointProc */
    PathToArea, /* areaProc */
    PathToPdf, /* pdfProc */
    ScalePath, /* scaleProc */
    TranslatePath,      /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

/* Be sure rect is not empty (see above) before doing this. */
static void
NormalizePathRect(
    TkPathRect * r)
{
double min, max;

    min = MIN(r->x1, r->x2);
    max = MAX(r->x1, r->x2);
    r->x1 = min;
    r->x2 = max;
    min = MIN(r->y1, r->y2);
    max = MAX(r->y1, r->y2);
    r->y1 = min;
    r->y2 = max;
}

/*
 +++ This starts the canvas item part +++
 */

/*
 *--------------------------------------------------------------
 *
 * CreatePath --
 *
 *    This procedure is invoked to create a new line item in
 *    a canvas.
 *
 * Results:
 *    A standard Tcl return value.  If an error occurred in
 *    creating the item, then an error message is left in
 *    the interp's result;  in this case itemPtr is left uninitialized,
 *    so it can be safely freed by the caller.
 *
 * Side effects:
 *    A new line item is created.
 *
 *--------------------------------------------------------------
 */

static int
CreatePath(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to create. */
    int objc,                  /* Number of elements in objv.  */
    Tcl_Obj * const objv[])
{              /* Arguments describing the item. */
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    pathPtr->pathObjPtr = NULL;
    pathPtr->pathLen = 0;
    pathPtr->normPathObjPtr = NULL;
    pathPtr->atomPtr = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    pathPtr->maxNumSegments = 0;
    TkPathArrowDescrInit(&pathPtr->startarrow);
    TkPathArrowDescrInit(&pathPtr->endarrow);
    pathPtr->flags = 0L;

    /* Forces a computation of the normalized path in PathCoords. */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)pathPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    /*
     * The first argument must be the path definition list.
     */

    if(ProcessPath(interp, canvas, itemPtr, 1, objv) != TCL_OK) {
        goto error;
    }
    if(ConfigurePath(interp, canvas, itemPtr, objc - 1, objv + 1, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePath(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * ProcessPath --
 *
 *    Does the main job of processing the drawing path in 'PathCoords'
 *      but doesn't do the bbox calculation since this cannot be done
 *      before we have callaed 'ConfigurePath' because we need
 *      the inherited style.
 *
 * Results:
 *    Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *    The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
ProcessPath(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item whose coordinates are to be
                                * read or modified. */
    int objc,                  /*  */
    Tcl_Obj * const objv[])
{              /*  */
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = NULL;
    int result, len;

    if(objc == 0) {
        /* @@@ We have an option here if to return the normalized or original path. */
#if 0
        Tcl_SetObjResult(interp, pathPtr->pathObjPtr);
#endif

        /* We may need to recompute the normalized path from the atoms. */
        if(pathPtr->flags & kPathItemNeedNewNormalizedPath) {
            if(pathPtr->normPathObjPtr != NULL) {
                Tcl_DecrRefCount(pathPtr->normPathObjPtr);
            }
            TkPathNormalize(interp, pathPtr->atomPtr,
                &(pathPtr->normPathObjPtr));
            Tcl_IncrRefCount(pathPtr->normPathObjPtr);
            pathPtr->flags &= ~kPathItemNeedNewNormalizedPath;
        }
        Tcl_SetObjResult(interp, pathPtr->normPathObjPtr);
        return TCL_OK;
    } else if(objc == 1) {
        result = TkPathParseToAtoms(interp, objv[0], &atomPtr, &len);
        if(result == TCL_OK) {

            /* Free any old atoms. */
            if(pathPtr->atomPtr != NULL) {
                TkPathFreeAtoms(pathPtr->atomPtr);
            }
            pathPtr->atomPtr = atomPtr;
            pathPtr->pathLen = len;
            if(pathPtr->pathObjPtr != NULL) {
                Tcl_DecrRefCount(pathPtr->pathObjPtr);
            }
            pathPtr->pathObjPtr = objv[0];
            pathPtr->maxNumSegments = GetSubpathMaxNumSegments(atomPtr);
            Tcl_IncrRefCount(pathPtr->pathObjPtr);
            pathPtr->flags |= kPathItemNeedNewNormalizedPath;
        }
        return result;
    } else {
        Tcl_WrongNumArgs(interp, 0, objv, "pathName coords id ?pathSpec?");
        return TCL_ERROR;
    }
}

/*
 *--------------------------------------------------------------
 *
 * PathCoords --
 *
 *    This procedure is invoked to process the "coords" widget
 *    command on lines.  See the user documentation for details
 *    on what it does.
 *
 * Results:
 *    Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *    The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
PathCoords(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item whose coordinates are to be
                                * read or modified. */
    int objc,                  /*  */
    Tcl_Obj * const objv[])
{              /*  */
    PathItem *pathPtr = (PathItem *) itemPtr;
    int result;

    result = ProcessPath(interp, canvas, itemPtr, objc, objv);
    if((result == TCL_OK) && (objc == 1)) {
        ConfigureArrows(canvas, pathPtr);
        ComputePathBbox(canvas, pathPtr);
    }
    return result;
}

/*
 *--------------------------------------------------------------
 *
 * ComputePathBbox --
 *
 *    This procedure is invoked to compute the bounding box of
 *    all the pixels that may be drawn as part of a path.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The fields x1, y1, x2, and y2 are updated in the header
 *    for itemPtr.
 *
 *--------------------------------------------------------------
 */

static void
ComputePathBbox(
    Tk_PathCanvas canvas,      /* Canvas that contains item. */
    PathItem * pathPtr)
{              /* Item whose bbox is to be
                * recomputed. */
Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(pathPtr->pathObjPtr == NULL || (pathPtr->pathLen < 4)
        || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 = itemExPtr->header.y1 =
            itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);

    /*
     * Get an approximation of the path's bounding box
     * assuming zero stroke width.
     */
    itemPtr->bbox = TkPathGetGenericBarePathBbox(pathPtr->atomPtr);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &pathPtr->startarrow);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &pathPtr->endarrow);
    itemPtr->totalBbox = TkPathGetGenericPathTotalBboxFromBare(pathPtr->atomPtr,
        &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigureArrows(
    Tk_PathCanvas canvas,
    PathItem * pathPtr)
{
TkPathPoint *pfirstp;
TkPathPoint psecond;
TkPathPoint ppenult;
TkPathPoint *plastp;

int error = TkPathGetSegmentsFromPathAtomList(pathPtr->atomPtr, &pfirstp,
        &psecond, &ppenult, &plastp);

    if(error == TCL_OK) {
TkPathPoint pfirst = *pfirstp;
TkPathPoint plast = *plastp;
Tk_PathStyle *lineStyle = &pathPtr->headerEx.style;
int isOpen = lineStyle->fill == NULL &&
    ((pfirst.x != plast.x) || (pfirst.y != plast.y));

        TkPathPreconfigureArrow(&pfirst, &pathPtr->startarrow);
        TkPathPreconfigureArrow(&plast, &pathPtr->endarrow);

        *pfirstp = TkPathConfigureArrow(pfirst, psecond,
            &pathPtr->startarrow, lineStyle, isOpen);
        *plastp = TkPathConfigureArrow(plast, ppenult, &pathPtr->endarrow,
            lineStyle, isOpen);
    } else {
        TkPathFreeArrow(&pathPtr->startarrow);
        TkPathFreeArrow(&pathPtr->endarrow);
    }

    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ConfigurePath --
 *
 *    This procedure is invoked to configure various aspects
 *    of a line item such as its background color.
 *
 * Results:
 *    A standard Tcl result code.  If an error occurs, then
 *    an error message is left in the interp's result.
 *
 * Side effects:
 *    Configuration information, such as colors and stipple
 *    patterns, may be set for itemPtr.
 *
 *--------------------------------------------------------------
 */

static int
ConfigurePath(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing itemPtr. */
    Tk_PathItem * itemPtr,     /* Line item to reconfigure. */
    int objc,                  /* Number of elements in objv.  */
    Tcl_Obj * const objv[],    /* Arguments describing things to configure. */
    int flags)
{              /* Flags to pass to Tk_ConfigureWidget. */
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)pathPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));

    ConfigureArrows(canvas, pathPtr);

    /*
     * Recompute bounding box for path.
     */
    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePathBbox(canvas, pathPtr);
        return TCL_OK;
    }
}

/*
 *--------------------------------------------------------------
 *
 * DeletePath --
 *
 *    This procedure is called to clean up the data structure
 *    associated with a line item.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Resources associated with itemPtr are released.
 *
 *--------------------------------------------------------------
 */

static void
DeletePath(
    Tk_PathCanvas canvas,      /* Info about overall canvas widget. */
    Tk_PathItem * itemPtr,     /* Item that is being deleted. */
    Display * display)
{              /* Display containing window for
                * canvas. */
PathItem *pathPtr = (PathItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &pathPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    if(pathPtr->pathObjPtr != NULL) {
        Tcl_DecrRefCount(pathPtr->pathObjPtr);
    }
    if(pathPtr->normPathObjPtr != NULL) {
        Tcl_DecrRefCount(pathPtr->normPathObjPtr);
    }
    if(pathPtr->atomPtr != NULL) {
        TkPathFreeAtoms(pathPtr->atomPtr);
        pathPtr->atomPtr = NULL;
    }
    TkPathFreeArrow(&pathPtr->startarrow);
    TkPathFreeArrow(&pathPtr->endarrow);
    Tk_FreeConfigOptions((char *)pathPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

/*
 *--------------------------------------------------------------
 *
 * DisplayPath --
 *
 *    This procedure is invoked to draw a line item in a given
 *    drawable.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    ItemPtr is drawn in drawable using the transformation
 *    information in canvas.
 *
 *--------------------------------------------------------------
 */

static void
DisplayPath(
    Tk_PathCanvas canvas,      /* Canvas that contains item. */
    Tk_PathItem * itemPtr,     /* Item to be displayed. */
    Display * display,         /* Display on which to draw item. */
    Drawable drawable,         /* Pixmap or window in which to draw
                                * item. */
    int x,
    int y,                     /* Describes region of canvas that */
    int width,
    int height)
{              /* must be redisplayed (not used). */
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    Tk_PathStyle style;

    if(pathPtr->pathLen > 2) {
        style = TkPathCanvasInheritStyle(itemPtr, 0);
        TkPathDrawPath(ContextOfCanvas(canvas), pathPtr->atomPtr, &style,
            &m, &itemPtr->bbox);
        /*
         * Display arrowheads, if they are wanted.
         */
        TkPathDisplayArrow(canvas, &pathPtr->startarrow, &style, &m,
            &itemPtr->bbox);
        TkPathDisplayArrow(canvas, &pathPtr->endarrow, &style, &m,
            &itemPtr->bbox);

        TkPathCanvasFreeInheritedStyle(&style);
    }
}

static void
PathBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PathItem *pathPtr = (PathItem *) itemPtr;
    /*
     * Try to be economical here.
     */
    if((mask & TK_PATH_STYLE_OPTION_MATRIX) ||
        (mask & TK_PATH_STYLE_OPTION_STROKE) ||
        (mask & TK_PATH_STYLE_OPTION_STROKE_WIDTH) ||
        (mask & TK_PATH_CORE_OPTION_PARENT) ||
        (mask & TK_PATH_CORE_OPTION_STYLENAME)) {
        ComputePathBbox(canvas, pathPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * PathToPoint --
 *
 *    Computes the distance from a given point to a given
 *    line, in canvas units.
 *
 * Results:
 *    The return value is 0 if the point whose x and y coordinates
 *    are pointPtr[0] and pointPtr[1] is inside the line.  If the
 *    point isn't inside the line then the return value is the
 *    distance from the point to the line.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static double
PathToPoint(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against point. */
    double *pointPtr)
{              /* Pointer to x and y coordinates. */
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = pathPtr->atomPtr;
    Tk_PathStyle style;
    double dist;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
        pathPtr->maxNumSegments, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

/*
 * Get maximum number of segments needed to describe path.
 * Needed to see if we can use static space or need to allocate more.
 */

static int
GetArcNumSegments(
    double currentX,
    double currentY,
    TkArcAtom * arc)
{
    int result;
    int ntheta, nlength;
    int numSteps;              /* Number of curve points to
                                * generate.  */
    double cx, cy, rx, ry;
    double theta1, dtheta;

    result = TkPathEndpointToCentralArcParameters(currentX, currentY,
        arc->x, arc->y, arc->radX, arc->radY,
        DEGREES_TO_RADIANS * arc->angle,
        arc->largeArcFlag, arc->sweepFlag,
        &cx, &cy, &rx, &ry, &theta1, &dtheta);
    if(result == TK_PATH_ARC_Line) {
        return 2;
    } else if(result == TK_PATH_ARC_Skip) {
        return 0;
    }

    /* Estimate the number of steps needed.
     * Max 10 degrees or length 50.
     */
    ntheta = (int)(dtheta / 5.0 + 0.5);
    nlength = (int)(0.5 * (rx + ry) * dtheta / 50 + 0.5);
    numSteps = MAX(4, MAX(ntheta, nlength));;
    return numSteps;
}

static int
GetSubpathMaxNumSegments(
    TkPathAtom * atomPtr)
{
int num;
int maxNumSegments;
double currentX = 0.0, currentY = 0.0;
double startX = 0.0, startY = 0.0;
TkMoveToAtom *move;
TkLineToAtom *line;
TkArcAtom *arc;
TkQuadBezierAtom *quad;
TkCurveToAtom *curve;

    num = 0;
    maxNumSegments = 0;

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
            move = (TkMoveToAtom *) atomPtr;
            num = 1;
            currentX = move->x;
            currentY = move->y;
            startX = currentX;
            startY = currentY;
            break;
        }
        case TK_PATH_ATOM_L:{
            line = (TkLineToAtom *) atomPtr;
            num++;
            currentX = line->x;
            currentY = line->y;
            break;
        }
        case TK_PATH_ATOM_A:{
            arc = (TkArcAtom *) atomPtr;
            num += GetArcNumSegments(currentX, currentY, arc);
            currentX = arc->x;
            currentY = arc->y;
            break;
        }
        case TK_PATH_ATOM_Q:{
            quad = (TkQuadBezierAtom *) atomPtr;
            num += TK_PATH_NUMSEGEMENTS_QuadBezier;
            currentX = quad->anchorX;
            currentY = quad->anchorY;
            break;
        }
        case TK_PATH_ATOM_C:{
            curve = (TkCurveToAtom *) atomPtr;
            num += TK_PATH_NUMSEGEMENTS_CurveTo;
            currentX = curve->anchorX;
            currentY = curve->anchorY;
            break;
        }
        case TK_PATH_ATOM_Z:{
            num++;
            currentX = startX;
            currentY = startY;
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            /* Empty. */
            break;
        }
        }
        if(num > maxNumSegments) {
            maxNumSegments = num;
        }
        atomPtr = atomPtr->nextPtr;
    }
    return maxNumSegments;
}

/*
 *--------------------------------------------------------------
 *
 * PathToArea --
 *
 *    This procedure is called to determine whether an item
 *    lies entirely inside, entirely outside, or overlapping
 *    a given rectangular area.
 *
 *    Each subpath is treated in turn. Generate straight line
 *    segments for each subpath and treat it as a polygon.
 *
 * Results:
 *    -1 is returned if the item is entirely outside the
 *    area, 0 if it overlaps, and 1 if it is entirely
 *    inside the given area.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathToArea(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against line. */
    double *areaPtr)
{              /* Pointer to array of four coordinates
                * (x1, y1, x2, y2) describing rectangular
                * area.  */
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathStyle style;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
        pathPtr->atomPtr, pathPtr->maxNumSegments, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

/*
 *--------------------------------------------------------------
 *
 * ScalePath --
 *
 *    This procedure is invoked to rescale a path item.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The line referred to by itemPtr is rescaled so that the
 *    following transformation is applied to all point
 *    coordinates:
 *    x' = originX + scaleX*(x-originX)
 *    y' = originY + scaleY*(y-originY)
 *
 *--------------------------------------------------------------
 */

static void
ScalePath(
    Tk_PathCanvas canvas,      /* Canvas containing line. */
    Tk_PathItem * itemPtr,     /* Path to be scaled. */
    int compensate,            /* Compensate matrix. */
    double originX,
    double originY,            /* Origin about which to scale rect. */
    double scaleX,             /* Amount to scale in X direction. */
    double scaleY)
{              /* Amount to scale in Y direction. */
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = pathPtr->atomPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    /* @@@ TODO: Arc atoms with nonzero rotation angle is WRONG! */

    TkPathScalePathAtoms(atomPtr, originX, originY, scaleX, scaleY);

    /*
     * Set flags bit so we know that PathCoords need to update the
     * normalized path before being used.
     */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    /* Just scale the bbox'es as well. */
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    NormalizePathRect(&itemPtr->bbox);

    TkPathScaleArrow(&pathPtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&pathPtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, pathPtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

/*
 *--------------------------------------------------------------
 *
 * TranslatePath --
 *
 *    This procedure is called to move a path by a given amount.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The position of the line is offset by (xDelta, yDelta), and
 *    the bounding box is updated in the generic part of the item
 *    structure.
 *
 *--------------------------------------------------------------
 */

static void
TranslatePath(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item that is being moved. */
    int compensate,            /* Compensate matrix. */
    double deltaX,             /* Amount by which item is to be */
    double deltaY)
{              /* moved. */
    PathItem *pathPtr = (PathItem *) itemPtr;
    TkPathAtom *atomPtr = pathPtr->atomPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    TkPathTranslatePathAtoms(atomPtr, deltaX, deltaY);

    /*
     * Set flags bit so we know that PathCoords need to update the
     * normalized path before being used.
     */
    pathPtr->flags |= kPathItemNeedNewNormalizedPath;

    /* Just translate the bbox'es as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateArrow(&pathPtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&pathPtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*
 *--------------------------------------------------------------
 *
 * PathToPdf --
 *
 *    This procedure is called to generate Pdf for
 *    path items.
 *
 * Results:
 *    The return value is a standard Tcl result.  If an error
 *    occurs in generating Pdf then an error message is
 *    left in the interp's result, replacing whatever used
 *    to be there.  If no error occurs, then Pdf for the
 *    item is appended to the result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathToPdf(
    Tcl_Interp * interp,       /* Leave Pdf or error message
                                * here. */
    Tk_PathCanvas canvas,      /* Information about overall canvas. */
    Tk_PathItem * itemPtr,     /* Item for which Pdf is
                                * wanted. */
    int objc,                  /* Number of arguments. */
    Tcl_Obj * const objv[],    /* Argument list. */
    int prepass)
{              /* 1 means this is a prepass to
                * collect font information;  0 means
                * final Pdf is being created. */
    Tk_PathStyle style;
    PathItem *pathPtr = (PathItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result = TCL_OK;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((pathPtr->pathObjPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        return result;
    }
    if(pathPtr->pathLen > 2) {
        style = TkPathCanvasInheritStyle(itemPtr, 0);
        result = TkPathPdf(interp, pathPtr->atomPtr, &style, &itemPtr->bbox,
            objc, objv);
        if(result == TCL_OK) {
            result = TkPathPdfArrow(interp, &pathPtr->startarrow, &style);
            if(result == TCL_OK) {
                result = TkPathPdfArrow(interp, &pathPtr->endarrow, &style);
            }
        }
        TkPathCanvasFreeInheritedStyle(&style);
    }
    return result;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvPoly.c.



































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvPoly.c --
 *
 *    This file implements polygon and polyline canvas items modelled after its
 *  SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PpolyItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    char type;                 /* Polyline or polygon. */
    TkPathAtom *atomPtr;
    int maxNumSegments;        /* Max number of straight segments (for subpath)
                                * needed for Area and Point functions. */
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
} PpolyItem;

enum {
    kPpolyTypePolyline,
    kPpolyTypePolygon
};

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePpolyBbox(
    Tk_PathCanvas canvas,
    PpolyItem * ppolyPtr);
static int ConfigurePpoly(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CoordsForPolygonline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    int closed,
    int objc,
    Tcl_Obj * const objv[],
    TkPathAtom ** atomPtrPtr,
    int *lenPtr);
static int CreateAny(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    char type);
static int CreatePolyline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int CreatePpolygon(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void PpolyBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int PpolyCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PpolyToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int PpolyToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PpolyToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static int ConfigureArrows(
    Tk_PathCanvas canvas,
    PpolyItem * ppolyPtr);

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE
    TK_PATH_OPTION_STRING_TABLES_STATE
    static Tk_OptionSpec optionSpecsPolyline[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(PpolyItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(PpolyItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec optionSpecsPpolygon[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'polyline' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypePolyline = {
    "polyline", /* name */
    sizeof(PpolyItem),  /* itemSize */
    CreatePolyline,     /* createProc */
    optionSpecsPolyline,        /* OptionSpecs */
    ConfigurePpoly,     /* configureProc */
    PpolyCoords,        /* coordProc */
    DeletePpoly,        /* deleteProc */
    DisplayPpoly,       /* displayProc */
    0,         /* flags */
    PpolyBbox, /* bboxProc */
    PpolyToPoint,       /* pointProc */
    PpolyToArea,        /* areaProc */
    PpolyToPdf, /* pdfProc */
    ScalePpoly, /* scaleProc */
    TranslatePpoly,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

Tk_PathItemType tkPathTypePolygon = {
    "polygon", /* name */
    sizeof(PpolyItem),  /* itemSize */
    CreatePpolygon,     /* createProc */
    optionSpecsPpolygon,        /* OptionSpecs */
    ConfigurePpoly,     /* configureProc */
    PpolyCoords,        /* coordProc */
    DeletePpoly,        /* deleteProc */
    DisplayPpoly,       /* displayProc */
    0,         /* flags */
    PpolyBbox, /* bboxProc */
    PpolyToPoint,       /* pointProc */
    PpolyToArea,        /* areaProc */
    PpolyToPdf, /* pdfProc */
    ScalePpoly, /* scaleProc */
    TranslatePpoly,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreatePolyline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kPpolyTypePolyline);
}

static int
CreatePpolygon(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    return CreateAny(interp, canvas, itemPtr, objc, objv, kPpolyTypePolygon);
}

static int
CreateAny(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    char type)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_OptionTable optionTable;
    int i, len;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    ppolyPtr->atomPtr = NULL;
    ppolyPtr->type = type;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    ppolyPtr->maxNumSegments = 0;
    TkPathArrowDescrInit(&ppolyPtr->startarrow);
    TkPathArrowDescrInit(&ppolyPtr->endarrow);

    if(ppolyPtr->type == kPpolyTypePolyline) {
        optionTable = Tk_CreateOptionTable(interp, optionSpecsPolyline);
    } else {
        optionTable = Tk_CreateOptionTable(interp, optionSpecsPpolygon);
    }
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)ppolyPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(CoordsForPolygonline(interp, canvas,
            (ppolyPtr->type == kPpolyTypePolyline) ? 0 : 1,
            i, objv, &(ppolyPtr->atomPtr), &len) != TCL_OK) {
        goto error;
    }
    ppolyPtr->maxNumSegments = len;

    if(ConfigurePpoly(interp, canvas, itemPtr, objc - i, objv + i, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePpoly(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PpolyCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    int len, closed;

    closed = (ppolyPtr->type == kPpolyTypePolyline) ? 0 : 1;
    if(CoordsForPolygonline(interp, canvas, closed, objc, objv,
            &(ppolyPtr->atomPtr), &len) != TCL_OK) {
        return TCL_ERROR;
    }
    if(objc > 0) {
        ppolyPtr->maxNumSegments = len;
        ConfigureArrows(canvas, ppolyPtr);
        ComputePpolyBbox(canvas, ppolyPtr);
    }
    return TCL_OK;
}

void
ComputePpolyBbox(
    Tk_PathCanvas canvas,
    PpolyItem * ppolyPtr)
{
Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((ppolyPtr->atomPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
            itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->bbox = TkPathGetGenericBarePathBbox(ppolyPtr->atomPtr);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &ppolyPtr->startarrow);
    TkPathIncludeArrowPointsInRect(&itemPtr->bbox, &ppolyPtr->endarrow);
    itemPtr->totalBbox =
        TkPathGetGenericPathTotalBboxFromBare(ppolyPtr->atomPtr, &style,
        &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

/*--------------------------------------------------------------
 *
 * ConfigureArrows --
 *
 *  If arrowheads have been requested for a line, this function makes
 *  arrangements for the arrowheads.
 *
 * Results:
 *  Always returns TCL_OK.
 *
 * Side effects:
 *  Information in ppolyPtr is set up for one or two arrowheads. The
 *  startarrowPtr and endarrowPtr polygons are allocated and initialized,
 *  if need be, and the end points of the line are adjusted so that a
 *  thick line doesn't stick out past the arrowheads.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureArrows(
    Tk_PathCanvas canvas,
    PpolyItem * ppolyPtr)
{
TkPathPoint *pfirstp;
TkPathPoint psecond;
TkPathPoint ppenult;
TkPathPoint *plastp;

int error = TkPathGetSegmentsFromPathAtomList(ppolyPtr->atomPtr,
        &pfirstp, &psecond, &ppenult, &plastp);

    if(error == TCL_OK) {
TkPathPoint pfirst = *pfirstp;
TkPathPoint plast = *plastp;
Tk_PathStyle *lineStyle = &ppolyPtr->headerEx.style;
int isOpen = lineStyle->fill == NULL &&
    ((pfirst.x != plast.x) || (pfirst.y != plast.y));

        TkPathPreconfigureArrow(&pfirst, &ppolyPtr->startarrow);
        TkPathPreconfigureArrow(&plast, &ppolyPtr->endarrow);

        *pfirstp = TkPathConfigureArrow(pfirst, psecond,
            &ppolyPtr->startarrow, lineStyle, isOpen);
        *plastp = TkPathConfigureArrow(plast, ppenult, &ppolyPtr->endarrow,
            lineStyle, isOpen);
    } else {
        TkPathFreeArrow(&ppolyPtr->startarrow);
        TkPathFreeArrow(&ppolyPtr->endarrow);
    }

    return TCL_OK;
}

static int
ConfigurePpoly(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int mask, error;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)ppolyPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));

    ConfigureArrows(canvas, ppolyPtr);

    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePpolyBbox(canvas, ppolyPtr);
        return TCL_OK;
    }
}

static void
DeletePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &ppolyPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    if(ppolyPtr->atomPtr != NULL) {
        TkPathFreeAtoms(ppolyPtr->atomPtr);
        ppolyPtr->atomPtr = NULL;
    }
    TkPathFreeArrow(&ppolyPtr->startarrow);
    TkPathFreeArrow(&ppolyPtr->endarrow);
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    Tk_PathStyle style;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    TkPathDrawPath(ContextOfCanvas(canvas), ppolyPtr->atomPtr, &style,
        &m, &itemPtr->bbox);
    /*
     * Display arrowheads, if they are wanted.
     */
    TkPathDisplayArrow(canvas, &ppolyPtr->startarrow, &style, &m,
        &itemPtr->bbox);
    TkPathDisplayArrow(canvas, &ppolyPtr->endarrow, &style, &m, &itemPtr->bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PpolyBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    ComputePpolyBbox(canvas, ppolyPtr);
}

static double
PpolyToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathStyle style;
    double dist;
    long flags;

    flags = (ppolyPtr->type == kPpolyTypePolyline) ?
        TK_PATH_MERGESTYLE_NOTFILL : 0;
    style = TkPathCanvasInheritStyle(itemPtr, flags);
    dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, ppolyPtr->atomPtr,
        ppolyPtr->maxNumSegments, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PpolyToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathStyle style;
    int area;
    long flags;

    flags = (ppolyPtr->type == kPpolyTypePolyline) ?
        TK_PATH_MERGESTYLE_NOTFILL : 0;
    style = TkPathCanvasInheritStyle(itemPtr, flags);
    area = TkPathGenericPathToArea(canvas, itemPtr, &style,
        ppolyPtr->atomPtr, ppolyPtr->maxNumSegments, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PpolyToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;
    Tk_PathState state = itemPtr->state;
    int result;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((ppolyPtr->atomPtr == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    result = TkPathPdf(interp, ppolyPtr->atomPtr, &style, &itemPtr->bbox,
        objc, objv);
    if(result == TCL_OK) {
        result = TkPathPdfArrow(interp, &ppolyPtr->startarrow, &style);
        if(result == TCL_OK) {
            result = TkPathPdfArrow(interp, &ppolyPtr->endarrow, &style);
        }
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    TkPathScalePathAtoms(ppolyPtr->atomPtr, originX, originY, scaleX, scaleY);
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&ppolyPtr->startarrow, originX, originY, scaleX, scaleY);
    TkPathScaleArrow(&ppolyPtr->endarrow, originX, originY, scaleX, scaleY);
    ConfigureArrows(canvas, ppolyPtr);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePpoly(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    PpolyItem *ppolyPtr = (PpolyItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    TkPathTranslatePathAtoms(ppolyPtr->atomPtr, deltaX, deltaY);
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateArrow(&ppolyPtr->startarrow, deltaX, deltaY);
    TkPathTranslateArrow(&ppolyPtr->endarrow, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/*
 *--------------------------------------------------------------
 *
 * CoordsForPolygonline --
 *
 *        Used as coordProc for polyline and polygon items.
 *
 * Results:
 *        Standard tcl result.
 *
 * Side effects:
 *        May store new atoms in atomPtrPtr and max number of points
 *        in lenPtr.
 *
 *--------------------------------------------------------------
 */

int
CoordsForPolygonline(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    int closed,                /* Polyline (0) or polygon (1) */
    int objc,
    Tcl_Obj * const objv[],
    TkPathAtom ** atomPtrPtr,
    int *lenPtr)
{
    TkPathAtom *atomPtr = *atomPtrPtr;

    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);

        while(atomPtr != NULL) {
            switch (atomPtr->type) {
            case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;
                Tcl_ListObjAppendElement(interp, obj,
                    Tcl_NewDoubleObj(move->x));
                Tcl_ListObjAppendElement(interp, obj,
                    Tcl_NewDoubleObj(move->y));
                break;
            }
            case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;
                Tcl_ListObjAppendElement(interp, obj,
                    Tcl_NewDoubleObj(line->x));
                Tcl_ListObjAppendElement(interp, obj,
                    Tcl_NewDoubleObj(line->y));
                break;
            }
            case TK_PATH_ATOM_Z:{

                break;
            }
            default:{
                /* empty */
            }
            }
            atomPtr = atomPtr->nextPtr;
        }
        Tcl_SetObjResult(interp, obj);
        *lenPtr = 0;
        return TCL_OK;
    }
    if(objc == 1) {
        if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                (Tcl_Obj ***) & objv) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if(objc & 1) {
    char buf[64 + TCL_INTEGER_SPACE];
        sprintf(buf, "wrong # coordinates: expected an even number, got %d",
            objc);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        return TCL_ERROR;
    } else if(objc < 4) {
    char buf[64 + TCL_INTEGER_SPACE];
        sprintf(buf, "wrong # coordinates: expected at least 4, got %d", objc);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        return TCL_ERROR;
    } else {
    int i;
    double x, y;
    double firstX = 0.0, firstY = 0.0;
    TkPathAtom *firstAtomPtr = NULL;

        /*
         * Free any old stuff.
         */
        if(atomPtr != NULL) {
            TkPathFreeAtoms(atomPtr);
            atomPtr = NULL;
        }
        for(i = 0; i < objc; i += 2) {
            if(Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[i],
                    &x) != TCL_OK) {
                /* @@@ error recovery? */
                return TCL_ERROR;
            }
            if(Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[i + 1],
                    &y) != TCL_OK) {
                return TCL_ERROR;
            }
            if(i == 0) {
                firstX = x;
                firstY = y;
                atomPtr = TkPathNewMoveToAtom(x, y);
                firstAtomPtr = atomPtr;
            } else {
                atomPtr->nextPtr = TkPathNewLineToAtom(x, y);
                atomPtr = atomPtr->nextPtr;
            }
        }
        if(closed) {
            atomPtr->nextPtr = TkPathNewCloseAtom(firstX, firstY);
        }
        *atomPtrPtr = firstAtomPtr;
        *lenPtr = i / 2 + 2;
    }
    return TCL_OK;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvRect.c.


























































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvRect.c --
 *
 *    This file implements a rectangle canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PrectItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    double rx;                 /* Radius of corners. */
    double ry;
    int maxNumSegments;        /* Max number of straight segments (for subpath)
                                * needed for Area and Point functions. */
} PrectItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePrectBbox(
    Tk_PathCanvas canvas,
    PrectItem * prectPtr);
static int ConfigurePrect(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreatePrect(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void PrectBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int PrectCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PrectToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int PrectToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PrectToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static TkPathAtom *MakePathAtoms(
    PrectItem * prectPtr);

enum {
    PRECT_OPTION_INDEX_RX = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    PRECT_OPTION_INDEX_RY = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE TK_PATH_OPTION_STRING_TABLES_STATE
#define TK_PATH_OPTION_SPEC_RX(typeName)            \
    {TK_OPTION_DOUBLE, "-rx", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, rx),        \
    0, 0, PRECT_OPTION_INDEX_RX}
#define TK_PATH_OPTION_SPEC_RY(typeName)            \
    {TK_OPTION_DOUBLE, "-ry", NULL, NULL,        \
        "0.0", -1, Tk_Offset(typeName, ry),        \
    0, 0, PRECT_OPTION_INDEX_RY}
static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_RX(PrectItem),
    TK_PATH_OPTION_SPEC_RY(PrectItem),
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeRect = {
    "rect",    /* name */
    sizeof(PrectItem),  /* itemSize */
    CreatePrect,        /* createProc */
    optionSpecs,        /* optionSpecs OBSOLTE !!! ??? */
    ConfigurePrect,     /* configureProc */
    PrectCoords,        /* coordProc */
    DeletePrect,        /* deleteProc */
    DisplayPrect,       /* displayProc */
    0,         /* flags */
    PrectBbox, /* bboxProc */
    PrectToPoint,       /* pointProc */
    PrectToArea,        /* areaProc */
    PrectToPdf, /* pdfProc */
    ScalePrect, /* scaleProc */
    TranslatePrect,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreatePrect(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    int i;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    itemPtr->totalBbox = TkPathNewEmptyPathRect();
    prectPtr->maxNumSegments = 100;     /* Crude overestimate. */

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)prectPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(TkPathCoordsForRectangularItems(interp, canvas, &itemPtr->bbox, i,
            objv) != TCL_OK) {
        goto error;
    }
    if(ConfigurePrect(interp, canvas, itemPtr, objc - i, objv + i, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePrect(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
PrectCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    int result;

    result =
        TkPathCoordsForRectangularItems(interp, canvas, &itemPtr->bbox, objc,
        objv);
    if((result == TCL_OK) && ((objc == 1) || (objc == 4))) {
        ComputePrectBbox(canvas, prectPtr);
    }
    return result;
}

void
ComputePrectBbox(
    Tk_PathCanvas canvas,
    PrectItem * prectPtr)
{
Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
            itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    itemPtr->totalBbox =
        TkPathGetGenericPathTotalBboxFromBare(NULL, &style, &itemPtr->bbox);
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr,
        &itemPtr->totalBbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePrect(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)prectPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask) != TCL_OK) {
            continue;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }
    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    stylePtr->fillOpacity = MAX(0.0, MIN(1.0, stylePtr->fillOpacity));
    prectPtr->rx = MAX(0.0, prectPtr->rx);
    prectPtr->ry = MAX(0.0, prectPtr->ry);

    /*
     * Recompute bounding box for path.
     */
    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePrectBbox(canvas, prectPtr);
        return TCL_OK;
    }
}

static TkPathAtom *
MakePathAtoms(
    PrectItem * prectPtr)
{
Tk_PathItem *itemPtr = (Tk_PathItem *) prectPtr;
TkPathAtom *atomPtr;
double points[4];

    points[0] = itemPtr->bbox.x1;
    points[1] = itemPtr->bbox.y1;
    points[2] = itemPtr->bbox.x2;
    points[3] = itemPtr->bbox.y2;
    TkPathMakePrectAtoms(points, prectPtr->rx, prectPtr->ry, &atomPtr);
    return atomPtr;
}

static void
DeletePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
PrectItem *prectPtr = (PrectItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathAtom *atomPtr;
    Tk_PathStyle style;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    atomPtr = MakePathAtoms(prectPtr);
    TkPathDrawPath(ContextOfCanvas(canvas), atomPtr, &style,
        &m, &itemPtr->bbox);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PrectBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    ComputePrectBbox(canvas, prectPtr);
}

static double
PrectToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathStyle style;
    TkPathMatrix *mPtr;
    TkPathRect *rectPtr = &itemPtr->bbox;
    double bareRect[4];
    double width, dist;
    int rectiLinear = 0;
    int filled;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if(style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;

    /* Try to be economical about this for pure rectangles. */
    if((prectPtr->rx <= 1.0) && (prectPtr->ry <= 1.0)) {
        if(mPtr == NULL) {
            rectiLinear = 1;
            bareRect[0] = rectPtr->x1;
            bareRect[1] = rectPtr->y1;
            bareRect[2] = rectPtr->x2;
            bareRect[3] = rectPtr->y2;
        } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {

            /* This is a situation we can treat in a simplified way. Apply the transform here. */
            rectiLinear = 1;
            bareRect[0] = mPtr->a * rectPtr->x1 + mPtr->tx;
            bareRect[1] = mPtr->d * rectPtr->y1 + mPtr->ty;
            bareRect[2] = mPtr->a * rectPtr->x2 + mPtr->tx;
            bareRect[3] = mPtr->d * rectPtr->y2 + mPtr->ty;
        }
    }
    if(rectiLinear) {
        dist = TkPathRectToPoint(bareRect, width, filled, pointPtr);
    } else {
    TkPathAtom *atomPtr = MakePathAtoms(prectPtr);
        dist = TkPathGenericPathToPoint(canvas, itemPtr, &style, atomPtr,
            prectPtr->maxNumSegments, pointPtr);
        TkPathFreeAtoms(atomPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PrectToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &prectPtr->headerEx;
    Tk_PathStyle style = itemExPtr->style;      /* NB: We *copy* the style for temp usage. */
    TkPathMatrix *mPtr;
    TkPathRect *rectPtr = &(itemPtr->bbox);
    double bareRect[4];
    double width;
    int rectiLinear = 0;
    int filled, area;

    style = TkPathCanvasInheritStyle(itemPtr, 0);
    filled = HaveAnyFillFromPathColor(style.fill);
    width = 0.0;
    if(style.strokeColor != NULL) {
        width = style.strokeWidth;
    }
    mPtr = style.matrixPtr;

    /* Try to be economical about this for pure rectangles. */
    if((prectPtr->rx <= 1.0) && (prectPtr->ry <= 1.0)) {
        if(mPtr == NULL) {
            rectiLinear = 1;
            bareRect[0] = rectPtr->x1;
            bareRect[1] = rectPtr->y1;
            bareRect[2] = rectPtr->x2;
            bareRect[3] = rectPtr->y2;
        } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {

            /* This is a situation we can treat in a simplified way. Apply the transform here. */
            rectiLinear = 1;
            bareRect[0] = mPtr->a * rectPtr->x1 + mPtr->tx;
            bareRect[1] = mPtr->d * rectPtr->y1 + mPtr->ty;
            bareRect[2] = mPtr->a * rectPtr->x2 + mPtr->tx;
            bareRect[3] = mPtr->d * rectPtr->y2 + mPtr->ty;
        }
    }
    if(rectiLinear) {
        area = TkPathRectToArea(bareRect, width, filled, areaPtr);
    } else {
    TkPathAtom *atomPtr = MakePathAtoms(prectPtr);
        area = TkPathGenericPathToArea(canvas, itemPtr, &style,
            atomPtr, prectPtr->maxNumSegments, areaPtr);
        TkPathFreeAtoms(atomPtr);
    }
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

static int
PrectToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    TkPathAtom *atomPtr;
    PrectItem *prectPtr = (PrectItem *) itemPtr;
    double points[4];
    Tk_PathState state = itemPtr->state;
    int result;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        return TCL_OK;
    }
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    points[0] = itemPtr->bbox.x1;
    points[1] = itemPtr->bbox.y1;
    points[2] = itemPtr->bbox.x2;
    points[3] = itemPtr->bbox.y2;
    TkPathMakePrectAtoms(points, prectPtr->rx, prectPtr->ry, &atomPtr);
    result = TkPathPdf(interp, atomPtr, &style, &itemPtr->bbox, objc, objv);
    TkPathFreeAtoms(atomPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return result;
}

static void
ScalePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePrect(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    /* Just translate the bbox'es as well. */
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvText.c.


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvText.c --
 *
 *    This file implements a text canvas item modelled after its
 *    SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each path item.
 */

typedef struct PtextItem {
    Tk_PathItemEx headerEx;    /* Generic stuff that's the same for all
                                * path types.  MUST BE FIRST IN STRUCTURE. */
    Tk_PathTextStyle textStyle;
    int textAnchor;
    int fillOverStroke;        /* boolean parameter */
    double x;
    double y;
    double baseHeightRatio;
    double lineSpacing;
    Tcl_Obj *utf8Obj;          /* The actual text to display; UTF-8 */
    int numChars;              /* Length of text in characters. */
    int numBytes;              /* Length of text in bytes. */
    void *custom;              /* Place holder for platform dependent stuff. */
} PtextItem;

/*
 * Prototypes for procedures defined in this file:
 */

static void ComputePtextBbox(
    Tk_PathCanvas canvas,
    PtextItem * ptextPtr);
static int ConfigurePtext(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreatePtext(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeletePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayPtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height);
static void PtextBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask);
static int PtextCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int ProcessPtextCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int PtextToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int PtextToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double PtextToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *coordPtr);
static void ScalePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslatePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
#if 0
static void PtextDeleteChars(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int first,
    int last);
#endif
static int drawptext(
    Tcl_Interp * interp,
    PtextItem * ptextPtr,
    Tcl_Obj * ret,
    Tcl_Obj * cmdl);
static char *linebreak(
    char *str,
    char **nextp);

enum {
    PRECT_OPTION_INDEX_FONTFAMILY =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 0)),
    PRECT_OPTION_INDEX_FONTSIZE = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 1)),
    PRECT_OPTION_INDEX_TEXT = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 2)),
    PRECT_OPTION_INDEX_TEXTANCHOR =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 3)),
    PRECT_OPTION_INDEX_FONTWEIGHT =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 4)),
    PRECT_OPTION_INDEX_FONTSLANT = (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 5)),
    PRECT_OPTION_INDEX_FILLOVERSTROKE =
        (1L << (TK_PATH_STYLE_OPTION_INDEX_END + 6)),
};

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_CUSTOM_OPTION_TAGS
    TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE TK_PATH_OPTION_STRING_TABLES_STATE
/*
 * Best would be to extract font information from the named font
 * "TkDefaultFont" but the option defaults need static strings.
 * Perhaps using NULL and extracting family and size dynamically?
 */
#if (defined(__WIN32__) || defined(_WIN32) || \
    defined(__CYGWIN__) || defined(__MINGW32__)) && !defined(PLATFORM_SDL)
#   define DEF_PATHCANVTEXT_FONTFAMILY         "Tahoma"
#   define DEF_PATHCANVTEXT_FONTSIZE         "8"
#else
#   if defined(MAC_OSX_TK)
#    define DEF_PATHCANVTEXT_FONTFAMILY     "Lucida Grande"
#    define DEF_PATHCANVTEXT_FONTSIZE     "13"
#   else
#    define DEF_PATHCANVTEXT_FONTFAMILY     "Helvetica"
#    define DEF_PATHCANVTEXT_FONTSIZE     "12"
#   endif
#endif
#define DEF_PATHCANVTEXT_FONTWEIGHT "normal"
#define DEF_PATHCANVTEXT_FONTSLANT  "normal"
/*
 * The enum TK_PATH_TEXTANCHOR_Start... MUST be kept in sync!
 */
static const char *textAnchorST[] = {
    "start", "middle", "end", "n", "w", "s", "e",
    "nw", "ne", "sw", "se", "c", NULL
};

static const char *fontWeightST[] = {
    "normal", "bold", NULL
};

static const char *fontSlantST[] = {
    "normal", "italic", "oblique", NULL
};

#define TK_PATH_OPTION_SPEC_FONTFAMILY                \
    {TK_OPTION_STRING, "-fontfamily", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTFAMILY, -1,            \
        Tk_Offset(PtextItem, textStyle.fontFamily),        \
        0, 0, PRECT_OPTION_INDEX_FONTFAMILY}

#define TK_PATH_OPTION_SPEC_FONTSIZE                \
    {TK_OPTION_DOUBLE, "-fontsize", NULL, NULL,            \
        DEF_PATHCANVTEXT_FONTSIZE, -1,            \
        Tk_Offset(PtextItem, textStyle.fontSize),        \
        0, 0, PRECT_OPTION_INDEX_FONTSIZE}

#define TK_PATH_OPTION_SPEC_TEXT                    \
    {TK_OPTION_STRING, "-text", NULL, NULL,            \
        NULL, Tk_Offset(PtextItem, utf8Obj), -1,        \
        TK_OPTION_NULL_OK, 0, PRECT_OPTION_INDEX_TEXT}

#define TK_PATH_OPTION_SPEC_TEXTANCHOR                \
    {TK_OPTION_STRING_TABLE, "-textanchor", NULL, NULL,        \
        "start", -1, Tk_Offset(PtextItem, textAnchor),    \
        0, (ClientData) textAnchorST, 0}

#define TK_PATH_OPTION_SPEC_FONTWEIGHT                \
    {TK_OPTION_STRING_TABLE, "-fontweight", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTWEIGHT, -1,            \
        Tk_Offset(PtextItem, textStyle.fontWeight),        \
        0, (ClientData) fontWeightST, PRECT_OPTION_INDEX_FONTWEIGHT}

#define TK_PATH_OPTION_SPEC_FONTSLANT                \
    {TK_OPTION_STRING_TABLE, "-fontslant", NULL, NULL,        \
        DEF_PATHCANVTEXT_FONTSLANT, -1,            \
        Tk_Offset(PtextItem, textStyle.fontSlant),        \
        0, (ClientData) fontSlantST, PRECT_OPTION_INDEX_FONTSLANT}

#define TK_PATH_OPTION_SPEC_FILLOVERSTROKE                \
    {TK_OPTION_BOOLEAN, "-filloverstroke", NULL, NULL,        \
        0, -1, Tk_Offset(PtextItem, fillOverStroke),    \
        0, 0, PRECT_OPTION_INDEX_FILLOVERSTROKE}

static Tk_OptionSpec optionSpecs[] = {
    TK_PATH_OPTION_SPEC_CORE(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_PARENT,
    TK_PATH_OPTION_SPEC_STYLE_FILL(Tk_PathItemEx, "black"),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(Tk_PathItemEx),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(Tk_PathItemEx, ""),
    TK_PATH_OPTION_SPEC_FONTFAMILY,
    TK_PATH_OPTION_SPEC_FONTSIZE,
    TK_PATH_OPTION_SPEC_FONTSLANT,
    TK_PATH_OPTION_SPEC_FONTWEIGHT,
    TK_PATH_OPTION_SPEC_TEXT,
    TK_PATH_OPTION_SPEC_TEXTANCHOR,
    TK_PATH_OPTION_SPEC_FILLOVERSTROKE,
    TK_PATH_OPTION_SPEC_END
};

/*
 * The structures below defines the 'prect' item type by means
 * of procedures that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeText = {
    "text",    /* name */
    sizeof(PtextItem),  /* itemSize */
    CreatePtext,        /* createProc */
    optionSpecs,        /* configSpecs */
    ConfigurePtext,     /* configureProc */
    PtextCoords,        /* coordProc */
    DeletePtext,        /* deleteProc */
    DisplayPtext,       /* displayProc */
    0,         /* flags */
    PtextBbox, /* bboxProc */
    PtextToPoint,       /* pointProc */
    PtextToArea,        /* areaProc */
    PtextToPdf, /* pdfProc */
    ScalePtext, /* scaleProc */
    TranslatePtext,     /* translateProc */
    (Tk_PathItemIndexProc *) NULL,      /* indexProc */
    (Tk_PathItemCursorProc *) NULL,     /* icursorProc */
    (Tk_PathItemSelectionProc *) NULL,  /* selectionProc */
    (Tk_PathItemInsertProc *) NULL,     /* insertProc */
    (Tk_PathItemDCharsProc *) NULL,     /* dTextProc */
    (Tk_PathItemType *) NULL,   /* nextPtr */
    1,         /* isPathType */
};

static int
CreatePtext(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    int i;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Carry out initialization that is needed to set defaults and to
     * allow proper cleanup after errors during the the remainder of
     * this procedure.
     */
    TkPathInitStyle(&itemExPtr->style);
    itemExPtr->canvas = canvas;
    itemExPtr->styleObj = NULL;
    itemExPtr->styleInst = NULL;
    itemPtr->bbox = TkPathNewEmptyPathRect();
    ptextPtr->utf8Obj = NULL;
    ptextPtr->numChars = 0;
    ptextPtr->numBytes = 0;
    ptextPtr->textAnchor = TK_PATH_TEXTANCHOR_Start;
    ptextPtr->textStyle.fontFamily = NULL;
    ptextPtr->textStyle.fontSize = 0.0;
    ptextPtr->fillOverStroke = 0;
    ptextPtr->custom = NULL;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)ptextPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    if(ProcessPtextCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
        goto error;
    }
    if(ConfigurePtext(interp, canvas, itemPtr, objc - i, objv + i, 0) == TCL_OK) {
        return TCL_OK;
    }

  error:
    /*
     * NB: We must unlink the item here since the TkPathCanvasItemExConfigure()
     *     link it to the root by default.
     */
    TkPathCanvasItemDetach(itemPtr);
    DeletePtext(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

static int
ProcessPtextCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewObj();
    Tcl_Obj *subobj = Tcl_NewDoubleObj(ptextPtr->x);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(ptextPtr->y);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if(objc < 3) {
        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 2) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coordinates: expected 0 or 2",
                        -1));
                return TCL_ERROR;
            }
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0],
                    &ptextPtr->x) != TCL_OK) ||
            (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                    &ptextPtr->y) != TCL_OK)) {
            return TCL_ERROR;
        }
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coordinates: expected 0 or 2", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
PtextCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    int result;

    result = ProcessPtextCoords(interp, canvas, itemPtr, objc, objv);
    if((result == TCL_OK) && (objc > 0) && (objc < 3)) {
        ComputePtextBbox(canvas, ptextPtr);
    }
    return result;
}

void
ComputePtextBbox(
    Tk_PathCanvas canvas,
    PtextItem * ptextPtr)
{
Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
Tk_PathItem *itemPtr = &itemExPtr->header;
Tk_PathStyle style;
Tk_PathState state = itemExPtr->header.state;
Tk_Window tkwin = Tk_PathCanvasTkwin(canvas);
double width;
double height;
double bheight;
double lineSpacing;
TkPathRect bbox, r;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((ptextPtr->utf8Obj == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        itemExPtr->header.x1 = itemExPtr->header.x2 =
            itemExPtr->header.y1 = itemExPtr->header.y2 = -1;
        return;
    }
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    r = TkPathTextMeasureBbox(Tk_Display(tkwin), &ptextPtr->textStyle,
        Tcl_GetString(ptextPtr->utf8Obj), &lineSpacing, ptextPtr->custom);
    width = r.x2 - r.x1;
    height = r.y2 - r.y1;
    bheight = -r.y1;

    switch (ptextPtr->textAnchor) {
    case TK_PATH_TEXTANCHOR_Start:
    case TK_PATH_TEXTANCHOR_W:
    case TK_PATH_TEXTANCHOR_NW:
    case TK_PATH_TEXTANCHOR_SW:
        bbox.x1 = ptextPtr->x;
        bbox.x2 = bbox.x1 + width;
        break;
    case TK_PATH_TEXTANCHOR_Middle:
    case TK_PATH_TEXTANCHOR_N:
    case TK_PATH_TEXTANCHOR_S:
    case TK_PATH_TEXTANCHOR_C:
        bbox.x1 = ptextPtr->x - width / 2;
        bbox.x2 = ptextPtr->x + width / 2;
        break;
    case TK_PATH_TEXTANCHOR_End:
    case TK_PATH_TEXTANCHOR_E:
    case TK_PATH_TEXTANCHOR_NE:
    case TK_PATH_TEXTANCHOR_SE:
        bbox.x1 = ptextPtr->x - width;
        bbox.x2 = ptextPtr->x;
        break;
    default:
        break;
    }

    switch (ptextPtr->textAnchor) {
    case TK_PATH_TEXTANCHOR_Start:
    case TK_PATH_TEXTANCHOR_Middle:
    case TK_PATH_TEXTANCHOR_End:
        bbox.y1 = ptextPtr->y + r.y1;   /* r.y1 is negative! */
        bbox.y2 = ptextPtr->y + r.y2;
        break;
    case TK_PATH_TEXTANCHOR_N:
    case TK_PATH_TEXTANCHOR_NW:
    case TK_PATH_TEXTANCHOR_NE:
        bbox.y1 = ptextPtr->y;
        bbox.y2 = ptextPtr->y + height;
        break;
    case TK_PATH_TEXTANCHOR_W:
    case TK_PATH_TEXTANCHOR_E:
    case TK_PATH_TEXTANCHOR_C:
        bbox.y1 = ptextPtr->y - height / 2;
        bbox.y2 = ptextPtr->y + height / 2;
        break;
    case TK_PATH_TEXTANCHOR_S:
    case TK_PATH_TEXTANCHOR_SW:
    case TK_PATH_TEXTANCHOR_SE:
        bbox.y1 = ptextPtr->y - height;
        bbox.y2 = ptextPtr->y;
        break;
    default:
        break;
    }

    /* Fudge for antialiasing etc. */
    bbox.x1 -= 1.0;
    bbox.y1 -= 1.0;
    bbox.x2 += 1.0;
    bbox.y2 += 1.0;
    height += 2.0;
    bheight += 1.0;
    if(style.strokeColor) {
double halfWidth = style.strokeWidth / 2;
        bbox.x1 -= halfWidth;
        bbox.y1 -= halfWidth;
        bbox.x2 += halfWidth;
        bbox.x2 += halfWidth;
        height += style.strokeWidth;
        bheight += halfWidth;
    }
    itemPtr->bbox = bbox;
    ptextPtr->baseHeightRatio = bheight / height;
    ptextPtr->lineSpacing = lineSpacing;
    itemPtr->totalBbox = itemPtr->bbox; /* FIXME */
    TkPathSetGenericPathHeaderBbox(&itemExPtr->header, style.matrixPtr, &bbox);
    TkPathCanvasFreeInheritedStyle(&style);
}

static int
ConfigurePtext(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathStyle *stylePtr = &itemExPtr->style;
    Tk_Window tkwin;
    Tk_SavedOptions savedOptions;
    Tcl_Obj *errorResult = NULL;
    int error, mask;

    tkwin = Tk_PathCanvasTkwin(canvas);
    for(error = 0; error <= 1; error++) {
        if(!error) {
            if(Tk_SetOptions(interp, (char *)ptextPtr, itemPtr->optionTable,
                    objc, objv, tkwin, &savedOptions, &mask) != TCL_OK) {
                continue;
            }
        } else {
            errorResult = Tcl_GetObjResult(interp);
            Tcl_IncrRefCount(errorResult);
            Tk_RestoreSavedOptions(&savedOptions);
        }

        /*
         * Since we have -fill default equal to black we need to force
         * setting the fill member of the style.
         */
        if(TkPathCanvasItemExConfigure(interp, canvas, itemExPtr,
                mask | TK_PATH_STYLE_OPTION_FILL)
            != TCL_OK) {
            continue;
        }
        /* @@@ TkPathTextConfig needs to be reworked! */
        if(ptextPtr->utf8Obj != NULL) {
    void *custom = NULL;

            ptextPtr->textStyle.fontSize = fabs(ptextPtr->textStyle.fontSize);
            if(TkPathTextConfig(interp, &ptextPtr->textStyle,
                    Tcl_GetString(ptextPtr->utf8Obj), &custom) != TCL_OK) {
                continue;
            }
            if(ptextPtr->custom != NULL) {
                TkPathTextFree(&ptextPtr->textStyle, ptextPtr->custom);
            }
            ptextPtr->custom = custom;
        }

        /*
         * If we reach this on the first pass we are OK and continue below.
         */
        break;
    }
    if(!error) {
        Tk_FreeSavedOptions(&savedOptions);
        stylePtr->mask |= mask;
    }

    stylePtr->strokeOpacity = MAX(0.0, MIN(1.0, stylePtr->strokeOpacity));
    if(ptextPtr->utf8Obj != NULL) {
        ptextPtr->numBytes = Tcl_GetCharLength(ptextPtr->utf8Obj);
        ptextPtr->numChars = Tcl_NumUtfChars(Tcl_GetString(ptextPtr->utf8Obj),
            ptextPtr->numBytes);
    } else {
        ptextPtr->numBytes = 0;
        ptextPtr->numChars = 0;
    }
    if(error) {
        Tcl_SetObjResult(interp, errorResult);
        Tcl_DecrRefCount(errorResult);
        return TCL_ERROR;
    } else {
        ComputePtextBbox(canvas, ptextPtr);
        return TCL_OK;
    }
}

static void
DeletePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display)
{
PtextItem *ptextPtr = (PtextItem *) itemPtr;
Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
Tk_PathStyle *stylePtr = &itemExPtr->style;

    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    if(itemExPtr->styleInst != NULL) {
        TkPathFreeStyle(itemExPtr->styleInst);
    }
    TkPathTextFree(&ptextPtr->textStyle, ptextPtr->custom);
    ptextPtr->custom = NULL;
    Tk_FreeConfigOptions((char *)ptextPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

static void
DisplayPtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tk_PathItemEx *itemExPtr = &ptextPtr->headerEx;
    Tk_PathStyle style;
    TkPathMatrix m = TkPathGetCanvasTMatrix(canvas);
    TkPathContext ctx;

    if(ptextPtr->utf8Obj == NULL) {
        return;
    }

    /*
     * The defaults for -fill and -stroke differ for the ptext item.
     */
    style = TkPathCanvasInheritStyle(itemPtr, 0);
    if(!(style.mask & TK_PATH_STYLE_OPTION_FILL)) {
        style.fill = itemExPtr->style.fill;
    }
    if(!(style.mask & TK_PATH_STYLE_OPTION_STROKE)) {
        style.strokeColor = itemExPtr->style.strokeColor;
    }

    ctx = ContextOfCanvas(canvas);
    TkPathPushTMatrix(ctx, &m);
    if(style.matrixPtr != NULL) {
        TkPathPushTMatrix(ctx, style.matrixPtr);
    }
    TkPathBeginPath(ctx, &style);
    /* @@@ We need to handle gradients as well here!
     *     Wait to see what the other APIs have to say.
     */
    TkPathTextDraw(ctx, &style, &ptextPtr->textStyle,
        itemPtr->bbox.x1,
        itemPtr->bbox.y1 + ptextPtr->baseHeightRatio *
        (itemPtr->bbox.y2 - itemPtr->bbox.y1),
        ptextPtr->fillOverStroke,
        Tcl_GetString(ptextPtr->utf8Obj), ptextPtr->custom);
    TkPathEndPath(ctx);
    TkPathCanvasFreeInheritedStyle(&style);
}

static void
PtextBbox(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int mask)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    ComputePtextBbox(canvas, ptextPtr);
}

static double
PtextToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr)
{
    Tk_PathStyle style;
    double dist;

    style = TkPathCanvasInheritStyle(itemPtr,
        TK_PATH_MERGESTYLE_NOTFILL | TK_PATH_MERGESTYLE_NOTSTROKE);
    dist =
        TkPathRectToPointWithMatrix(itemPtr->bbox, style.matrixPtr, pointPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return dist;
}

static int
PtextToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *areaPtr)
{
    Tk_PathStyle style;
    int area;

    style = TkPathCanvasInheritStyle(itemPtr,
        TK_PATH_MERGESTYLE_NOTFILL | TK_PATH_MERGESTYLE_NOTSTROKE);
    area = TkPathRectToAreaWithMatrix(itemPtr->bbox, style.matrixPtr, areaPtr);
    TkPathCanvasFreeInheritedStyle(&style);
    return area;
}

/* From tkUnixCairoPath.c */
static char *
linebreak(
    char *str,
    char **nextp)
{
    char *ret;

    if(str == NULL) {
        str = *nextp;
    }
    str += strspn(str, "\r\n");
    if(*str == '\0') {
        return NULL;
    }
    ret = str;
    str += strcspn(str, "\r\n");
    if(*str) {
    int ch = *str;

        *str++ = '\0';
        if((ch == '\r') && (*str == '\n')) {
            str++;
        }
    }
    *nextp = str;
    return ret;
}

static int
drawptext(
    Tcl_Interp * interp,
    PtextItem * ptextPtr,
    Tcl_Obj * ret,
    Tcl_Obj * cmdl)
{
char *utf8, *token, *savep;
Tcl_DString ds;
int i, result = TCL_OK;

    savep = Tcl_GetStringFromObj(ptextPtr->utf8Obj, &i);
    utf8 = (char *)ckalloc((unsigned)i + 1);
    strcpy(utf8, savep);
    Tcl_DStringInit(&ds);
    for(token = linebreak(utf8, &savep); token != NULL;
        token = linebreak(NULL, &savep)) {
        if(cmdl != NULL) {
Tcl_Obj *cmd;

            /*
             * Use provided callback for formatting/encoding text.
             */
            cmd = Tcl_DuplicateObj(cmdl);
            Tcl_IncrRefCount(cmd);
            if(Tcl_ListObjAppendElement(interp, cmd,
                    Tcl_NewStringObj(token, strlen(token))) != TCL_OK) {
                Tcl_DecrRefCount(cmd);
                result = TCL_ERROR;
                break;
            }
            if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
                Tcl_DecrRefCount(cmd);
                result = TCL_ERROR;
                break;
            }
            Tcl_DecrRefCount(cmd);
            Tcl_AppendToObj(ret, "(", 1);
            Tcl_AppendObjToObj(ret, Tcl_GetObjResult(interp));
            Tcl_AppendToObj(ret, ") Tj\nT*\n", 8);
        } else {
            Tcl_DStringSetLength(&ds, 0);
            Tcl_DStringAppend(&ds, "(", 1);
            i = 0;
            while(token[i] != '\0') {
                switch (token[i]) {
                case '(':
                case ')':
                case '\\':
                    Tcl_DStringAppend(&ds, "\\", 1);
                default:
                    if((token[i] < 0) || (token[i] >= ' ')) {
                        Tcl_DStringAppend(&ds, token + i, 1);
                    } else {
char obuf[8];

                        sprintf(obuf, "\\%03o", token[i]);
                        Tcl_DStringAppend(&ds, obuf, -1);
                    }
                    break;
                case '\n':
                    Tcl_DStringAppend(&ds, "\\n", 2);
                    break;
                case '\r':
                    Tcl_DStringAppend(&ds, "\\r", 2);
                    break;
                case '\t':
                    Tcl_DStringAppend(&ds, "\\t", 2);
                    break;
                case '\b':
                    Tcl_DStringAppend(&ds, "\\b", 2);
                    break;
                case '\f':
                    Tcl_DStringAppend(&ds, "\\f", 2);
                    break;
                }
                i++;
            }
            Tcl_DStringAppend(&ds, ") Tj\nT*\n", -1);
            Tcl_AppendToObj(ret, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
        }
    }
    Tcl_DStringFree(&ds);
    ckfree(utf8);
    return result;
}

static int
PtextToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass)
{
    Tk_PathStyle style;
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    Tcl_Obj *ret, *cmdl;
    TkPathMatrix matrix = { 1., 0., 0., 1., 0., 0. };
    TkPathMatrix tmp = { 1., 0., 0., -1., 0., 0. };
    Tk_PathState state = itemPtr->state;
    TkPathRect bbox = itemPtr->bbox;
    int hasStroke;
    char *font;
    int result = TCL_OK;

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((ptextPtr->utf8Obj == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        return result;
    }
    ret = Tcl_NewObj();
    style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
    if(style.matrixPtr != NULL) {
        matrix = *(style.matrixPtr);
    }
    tmp.tx = bbox.x1;   /* value with anchoring applied */
    tmp.ty = ptextPtr->y;       /* TODO */
    tmp.ty = bbox.y1 + ptextPtr->baseHeightRatio * (bbox.y2 - bbox.y1);
    TkPathMMulTMatrix(&tmp, &matrix);
    /*
     * The defaults for -fill and -stroke differ for the ptext item.
     */
    if(!(style.mask & TK_PATH_STYLE_OPTION_FILL)) {
        style.fill = ptextPtr->headerEx.style.fill;
    } else if(GetGradientMasterFromPathColor(style.fill) != NULL) {
        style.fill = NULL;
    }
    if(!(style.mask & TK_PATH_STYLE_OPTION_STROKE)) {
        style.strokeColor = ptextPtr->headerEx.style.strokeColor;
    }
    if(objc > 0) {
    int retc;
    Tcl_Obj *gs, *cmd, **retv;

        gs = TkPathExtGS(&style, NULL);
        if(gs != NULL) {
            cmd = Tcl_DuplicateObj(objv[0]);
            Tcl_IncrRefCount(cmd);
            if(Tcl_ListObjAppendElement(interp, cmd, gs) != TCL_OK) {
                Tcl_DecrRefCount(cmd);
                Tcl_DecrRefCount(gs);
                result = TCL_ERROR;
                goto done;
            }
            if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
                Tcl_DecrRefCount(cmd);
                result = TCL_ERROR;
                goto done;
            }
            Tcl_DecrRefCount(cmd);
            /*
             * Get name of extended graphics state.
             */
            if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                    &retc, &retv) != TCL_OK) {
                result = TCL_ERROR;
                goto done;
            }
            if(retc < 2) {
                Tcl_SetResult(interp, (char *)"missing PDF id/name",
                    TCL_STATIC);
                result = TCL_ERROR;
                goto done;
            }
            Tcl_AppendPrintfToObj(ret, "/%s gs\n", Tcl_GetString(retv[1]));
        }
    }
    hasStroke = (style.strokeColor != NULL);
    cmdl = (objc > 1) ? objv[1] : NULL;
    font = (objc > 2) ? Tcl_GetString(objv[2]) : ptextPtr->textStyle.fontFamily;
    /*
     * TODO: ptextPtr->textStyle.fontSlant ptextPtr->textStyle.fontWeight
     */
    Tcl_AppendPrintfToObj(ret, "q\nBT\n/%s ", font);
    TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " Tf\n");
    TkPathPdfNumber(ret, 3, ptextPtr->lineSpacing, " TL\n");
    TkPathPdfNumber(ret, 6, matrix.a, " ");
    TkPathPdfNumber(ret, 6, matrix.b, " ");
    TkPathPdfNumber(ret, 6, matrix.c, " ");
    TkPathPdfNumber(ret, 6, matrix.d, " ");
    TkPathPdfNumber(ret, 3, matrix.tx, " ");
    TkPathPdfNumber(ret, 3, matrix.ty, " Tm\n");
    if(ptextPtr->fillOverStroke && hasStroke &&
        (style.fill != NULL) && (style.fill->color != NULL)) {
        /* first pass w/o fill */
        TkPathPdfColor(ret, style.strokeColor, "RG");
        Tcl_AppendToObj(ret, "1 Tr\n", 5);
        TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
        result = drawptext(interp, ptextPtr, ret, cmdl);
        if(result == TCL_OK) {
            /* second pass w/o stroke */
            Tcl_AppendPrintfToObj(ret, "ET\nQ\nq\nBT\n/%s ", font);
            TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " Tf\n");
            TkPathPdfNumber(ret, 3, ptextPtr->textStyle.fontSize, " TL\n");
            TkPathPdfNumber(ret, 6, matrix.a, " ");
            TkPathPdfNumber(ret, 6, matrix.b, " ");
            TkPathPdfNumber(ret, 6, matrix.c, " ");
            TkPathPdfNumber(ret, 6, matrix.d, " ");
            TkPathPdfNumber(ret, 3, matrix.tx, " ");
            TkPathPdfNumber(ret, 3, matrix.ty, " Tm\n");
            TkPathPdfColor(ret, style.fill->color, "rg");
            Tcl_AppendToObj(ret, "0 Tr\n", 5);
            result = drawptext(interp, ptextPtr, ret, cmdl);
        }
    } else if((style.fill != NULL) && (style.fill->color != NULL)) {
        TkPathPdfColor(ret, style.fill->color, "rg");
        if(hasStroke) {
            TkPathPdfColor(ret, style.strokeColor, "RG");
            Tcl_AppendToObj(ret, "2 Tr\n", 5);
            TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
        } else {
            Tcl_AppendToObj(ret, "0 Tr\n", 5);
        }
        result = drawptext(interp, ptextPtr, ret, cmdl);
    } else if(hasStroke) {
        TkPathPdfColor(ret, style.strokeColor, "RG");
        Tcl_AppendToObj(ret, "1 Tr\n", 5);
        TkPathPdfNumber(ret, 3, style.strokeWidth, " w\n");
        result = drawptext(interp, ptextPtr, ret, cmdl);
    }
  done:
    TkPathCanvasFreeInheritedStyle(&style);
    if(result == TCL_OK) {
        Tcl_AppendToObj(ret, "ET\nQ\n", 5);
        Tcl_SetObjResult(interp, ret);
    } else {
        Tcl_DecrRefCount(ret);
    }
    return result;
}

static void
ScalePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    TkPathCompensateScale(itemPtr, compensate, &originX, &originY, &scaleX,
        &scaleY);

    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    ptextPtr->x = originX + scaleX * (ptextPtr->x - originX);
    ptextPtr->y = originY + scaleY * (ptextPtr->y - originY);
    TkPathScalePathRect(&itemPtr->bbox, originX, originY, scaleX, scaleY);
    TkPathScaleItemHeader(itemPtr, originX, originY, scaleX, scaleY);
}

static void
TranslatePtext(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;

    TkPathCompensateTranslate(itemPtr, compensate, &deltaX, &deltaY);

    ptextPtr->x += deltaX;
    ptextPtr->y += deltaY;
    TkPathTranslatePathRect(&itemPtr->bbox, deltaX, deltaY);
    TkPathTranslateItemHeader(itemPtr, deltaX, deltaY);
}

#if 0          /* TODO */
static void
PtextDeleteChars(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int first,
    int last)
{
    PtextItem *ptextPtr = (PtextItem *) itemPtr;
    int byteIndex, byteCount, charsRemoved;
    char *new, *text;

    text = ptextPtr->utf8;
    if(first < 0) {
        first = 0;
    }
    if(last >= ptextPtr->numChars) {
        last = ptextPtr->numChars - 1;
    }
    if(first > last) {
        return;
    }
    charsRemoved = last + 1 - first;

    byteIndex = Tcl_UtfAtIndex(text, first) - text;
    byteCount = Tcl_UtfAtIndex(text + byteIndex, charsRemoved)
        - (text + byteIndex);

    new = (char *)ckalloc((unsigned)(ptextPtr->numBytes + 1 - byteCount));
    memcpy(new, text, (size_t) byteIndex);
    strcpy(new + byteIndex, text + byteIndex + byteCount);

    ckfree(text);
    ptextPtr->utf8 = new;
    ptextPtr->numChars -= charsRemoved;
    ptextPtr->numBytes -= byteCount;

    /*
     * TkPathTextConfig(interp, &ptextPtr->textStyle,
     *                  ptextPtr->utf8, &ptextPtr->custom);
     */
    ComputePtextBbox(canvas, ptextPtr);
    return;
}
#endif
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathCanvWindow.c.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathCanvWind.c --
 *
 *	This file implements window items for canvas widgets.
 *
 * Copyright (c) 1992-1994 The Regents of the University of California.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#include "tkoPath.h"

/*
 * The structure below defines the record for each window item.
 */

typedef struct WindowItem {
    Tk_PathItem header;        /* Generic stuff that's the same for all
                                * types.  MUST BE FIRST IN STRUCTURE. */
    double x, y;               /* Coordinates of positioning point for
                                * window. */
    Tk_Window tkwin;           /* Window associated with item.  NULL means
                                * window has been destroyed. */
    int width;                 /* Width to use for window (<= 0 means use
                                * window's requested width). */
    int height;                /* Width to use for window (<= 0 means use
                                * window's requested width). */
    Tk_Anchor anchor;          /* Where to anchor window relative to
                                * (x,y). */
    Tk_PathCanvas canvas;      /* Canvas containing this item. */
} WindowItem;

#define PATH_DEF_STATE "normal"

static const char *stateStrings[] = {
    "active", "disabled", "normal", "hidden", NULL
};

static Tk_ObjCustomOption tagsCO = {
    "tags",
    Tk_PathCanvasTagsOptionSetProc,
    Tk_PathCanvasTagsOptionGetProc,
    Tk_PathCanvasTagsOptionRestoreProc,
    Tk_PathCanvasTagsOptionFreeProc,
    (ClientData) NULL
};

static Tk_OptionSpec optionSpecs[] = {
    {TK_OPTION_ANCHOR, "-anchor", NULL, NULL,
        "center", -1, Tk_Offset(WindowItem, anchor), 0, 0, 0},
    {TK_OPTION_PIXELS, "-height", NULL, NULL,
        "0", -1, Tk_Offset(WindowItem, height), 0, 0, 0},
    {TK_OPTION_STRING_TABLE, "-state", NULL, NULL,
            PATH_DEF_STATE, -1, Tk_Offset(Tk_PathItem, state),
        0, (ClientData) stateStrings, 0},
    {TK_OPTION_CUSTOM, "-tags", NULL, NULL,
            NULL, -1, Tk_Offset(Tk_PathItem, pathTagsPtr),
        TK_OPTION_NULL_OK, (ClientData) & tagsCO, 0},
    {TK_OPTION_PIXELS, "-width", NULL, NULL,
        "0", -1, Tk_Offset(WindowItem, width), 0, 0, 0},
    {TK_OPTION_WINDOW, "-window", NULL, NULL,
            NULL, -1, Tk_Offset(WindowItem, tkwin),
        TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_END, NULL, NULL, NULL,
        NULL, 0, -1, 0, (ClientData) NULL, 0}
};

/*
 * Prototypes for functions defined in this file:
 */

static void ComputeWindowBbox(
    Tk_PathCanvas canvas,
    WindowItem * winItemPtr);
static int ConfigureWinItem(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int flags);
static int CreateWinItem(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    struct Tk_PathItem *itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void DeleteWinItem(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display);
static void DisplayWinItem(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    Display * display,
    Drawable dst,
    int x,
    int y,
    int width,
    int height);
static void ScaleWinItem(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double originX,
    double originY,
    double scaleX,
    double scaleY);
static void TranslateWinItem(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int compensate,
    double deltaX,
    double deltaY);
static int WinItemCoords(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[]);
static void WinItemLostSlaveProc(
    ClientData clientData,
    Tk_Window tkwin);
static void WinItemRequestProc(
    ClientData clientData,
    Tk_Window tkwin);
static void WinItemStructureProc(
    ClientData clientData,
    XEvent * eventPtr);
static int WinItemToArea(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *rectPtr);
static int WinItemToPdf(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    int objc,
    Tcl_Obj * const objv[],
    int prepass);
static double WinItemToPoint(
    Tk_PathCanvas canvas,
    Tk_PathItem * itemPtr,
    double *pointPtr);
#ifdef X_GetImage
static int xerrorhandler(
    ClientData clientData,
    XErrorEvent * e);
#endif

/*
 * The structure below defines the window item type by means of functions
 * that can be invoked by generic item code.
 */

Tk_PathItemType tkPathTypeWindow = {
    "window",  /* name */
    sizeof(WindowItem), /* itemSize */
    CreateWinItem,      /* createProc */
    optionSpecs,        /* optionSpecs */
    ConfigureWinItem,   /* configureProc */
    WinItemCoords,      /* coordProc */
    DeleteWinItem,      /* deleteProc */
    DisplayWinItem,     /* displayProc */
    1,         /* flags */
    NULL,      /* bboxProc */
    WinItemToPoint,     /* pointProc */
    WinItemToArea,      /* areaProc */
    WinItemToPdf,       /* pdfProc */
    ScaleWinItem,       /* scaleProc */
    TranslateWinItem,   /* translateProc */
    NULL,      /* indexProc */
    NULL,      /* cursorProc */
    NULL,      /* selectionProc */
    NULL,      /* insertProc */
    NULL,      /* dTextProc */
    NULL,      /* nextPtr */
    0,         /* isPathType */
};

/*
 * The structure below defines the official type record for the canvas (as
 * geometry manager):
 */

static const Tk_GeomMgr canvasGeomType = {
    "canvas",  /* name */
    WinItemRequestProc, /* requestProc */
    WinItemLostSlaveProc,       /* lostSlaveProc */
};

/*
 *--------------------------------------------------------------
 *
 * CreateWinItem --
 *
 *	This function is invoked to create a new window item in a canvas.
 *
 * Results:
 *	A standard Tcl return value. If an error occurred in creating the
 *	item, then an error message is left in the interp's result; in this
 *	case itemPtr is left uninitialized, so it can be safely freed by the
 *	caller.
 *
 * Side effects:
 *	A new window item is created.
 *
 *--------------------------------------------------------------
 */

static int
    CreateWinItem(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas to hold new item. */
    Tk_PathItem * itemPtr,     /* Record to hold new item; header has been
                                * initialized by caller. */
    int objc,                  /* Number of arguments in objv. */
    Tcl_Obj * const objv[]) {   /* Arguments describing window. */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    int i;
    Tk_OptionTable optionTable;

    if(objc == 0) {
        Tcl_Panic("canvas did not pass any coords\n");
    }

    /*
     * Initialize item's record.
     */

    winItemPtr->tkwin = NULL;
    winItemPtr->width = 0;
    winItemPtr->height = 0;
    winItemPtr->anchor = TK_ANCHOR_CENTER;
    winItemPtr->canvas = canvas;

    optionTable = Tk_CreateOptionTable(interp, optionSpecs);
    itemPtr->optionTable = optionTable;
    if(Tk_InitOptions(interp, (char *)winItemPtr, optionTable,
            Tk_PathCanvasTkwin(canvas)) != TCL_OK) {
        goto error;
    }

    /*
     * Process the arguments to fill in the item record. Only 1 (list) or 2 (x
     * y) coords are allowed.
     */

    if(objc == 1) {
        i = 1;
    } else {
    char *arg = Tcl_GetString(objv[1]);
        i = 2;
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            i = 1;
        }
    }
    if(WinItemCoords(interp, canvas, itemPtr, i, objv) != TCL_OK) {
        goto error;
    }
    if(ConfigureWinItem(interp, canvas, itemPtr, objc - i, objv + i, 0)
        == TCL_OK) {
        return TCL_OK;
    }

  error:
    DeleteWinItem(canvas, itemPtr, Tk_Display(Tk_PathCanvasTkwin(canvas)));
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * WinItemCoords --
 *
 *	This function is invoked to process the "coords" widget command on
 *	window items. See the user documentation for details on what it does.
 *
 * Results:
 *	Returns TCL_OK or TCL_ERROR, and sets the interp's result.
 *
 * Side effects:
 *	The coordinates for the given item may be changed.
 *
 *--------------------------------------------------------------
 */

static int
WinItemCoords(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item whose coordinates are to be read or
                                * modified. */
    int objc,                  /* Number of coordinates supplied in objv. */
    Tcl_Obj * const objv[])
{              /* Array of coordinates: x1, y1, x2, y2, ... */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewObj();
    Tcl_Obj *subobj = Tcl_NewDoubleObj(winItemPtr->x);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(winItemPtr->y);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if(objc < 3) {
        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 2) {
    char buf[64 + TCL_INTEGER_SPACE];

                sprintf(buf, "wrong # coordinates: expected 2, got %d", objc);
                Tcl_SetResult(interp, buf, TCL_VOLATILE);
                return TCL_ERROR;
            }
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0],
                    &winItemPtr->x)
                != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                    &winItemPtr->y) != TCL_OK)) {
            return TCL_ERROR;
        }
        ComputeWindowBbox(canvas, winItemPtr);
    } else {
    char buf[64 + TCL_INTEGER_SPACE];

        sprintf(buf, "wrong # coordinates: expected 0 or 2, got %d", objc);
        Tcl_SetResult(interp, buf, TCL_VOLATILE);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ConfigureWinItem --
 *
 *	This function is invoked to configure various aspects of a window
 *	item, such as its anchor position.
 *
 * Results:
 *	A standard Tcl result code. If an error occurs, then an error message
 *	is left in the interp's result.
 *
 * Side effects:
 *	Configuration information may be set for itemPtr.
 *
 *--------------------------------------------------------------
 */

static int
ConfigureWinItem(
    Tcl_Interp * interp,       /* Used for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas containing itemPtr. */
    Tk_PathItem * itemPtr,     /* Window item to reconfigure. */
    int objc,                  /* Number of elements in objv.  */
    Tcl_Obj * const objv[],    /* Arguments describing things to configure. */
    int flags)
{              /* Flags to pass to Tk_ConfigureWidget. */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    Tk_Window oldWindow;
    Tk_Window canvasTkwin;

    oldWindow = winItemPtr->tkwin;
    canvasTkwin = Tk_PathCanvasTkwin(canvas);
    if(TCL_OK != Tk_SetOptions(interp, (char *)winItemPtr,
            itemPtr->optionTable, objc, objv, canvasTkwin, NULL, NULL)) {
        return TCL_ERROR;
    }

    /*
     * A few of the options require additional processing.
     */

    if(oldWindow != winItemPtr->tkwin) {
        if(oldWindow != NULL) {
            Tk_DeleteEventHandler(oldWindow, StructureNotifyMask,
                WinItemStructureProc, (ClientData) winItemPtr);
            Tk_ManageGeometry(oldWindow, NULL, (ClientData) NULL);
            Tk_UnmaintainGeometry(oldWindow, canvasTkwin);
            Tk_UnmapWindow(oldWindow);
        }
        if(winItemPtr->tkwin != NULL) {
    Tk_Window ancestor, parent;

            /*
             * Make sure that the canvas is either the parent of the window
             * associated with the item or a descendant of that parent. Also,
             * don't allow a top-of-hierarchy window to be managed inside a
             * canvas.
             */

            parent = Tk_Parent(winItemPtr->tkwin);
            for(ancestor = canvasTkwin;; ancestor = Tk_Parent(ancestor)) {
                if(ancestor == parent) {
                    break;
                }
                if(((Tk_FakeWin *) (ancestor))->flags & TK_TOP_HIERARCHY) {
                  badWindow:
                    Tcl_AppendResult(interp, "can't use ",
                        Tk_PathName(winItemPtr->tkwin),
                        " in a window item of this canvas", NULL);
                    winItemPtr->tkwin = NULL;
                    return TCL_ERROR;
                }
            }
            if(((Tk_FakeWin *) (winItemPtr->tkwin))->flags & TK_TOP_HIERARCHY) {
                goto badWindow;
            }
            if(winItemPtr->tkwin == canvasTkwin) {
                goto badWindow;
            }
            Tk_CreateEventHandler(winItemPtr->tkwin, StructureNotifyMask,
                WinItemStructureProc, (ClientData) winItemPtr);
            Tk_ManageGeometry(winItemPtr->tkwin, &canvasGeomType,
                (ClientData) winItemPtr);
        }
    }
    if((winItemPtr->tkwin != NULL)
        && (itemPtr->state == TK_PATHSTATE_HIDDEN)) {
        if(canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
            Tk_UnmapWindow(winItemPtr->tkwin);
        } else {
            Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
        }
    }

    ComputeWindowBbox(canvas, winItemPtr);

    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * DeleteWinItem --
 *
 *	This function is called to clean up the data structure associated with
 *	a window item.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Resources associated with itemPtr are released.
 *
 *--------------------------------------------------------------
 */

static void
DeleteWinItem(
    Tk_PathCanvas canvas,      /* Overall info about widget. */
    Tk_PathItem * itemPtr,     /* Item that is being deleted. */
    Display * display)
{              /* Display containing window for canvas. */
WindowItem *winItemPtr = (WindowItem *) itemPtr;
Tk_Window canvasTkwin = Tk_PathCanvasTkwin(canvas);

    if(winItemPtr->tkwin != NULL) {
        Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask,
            WinItemStructureProc, (ClientData) winItemPtr);
        Tk_ManageGeometry(winItemPtr->tkwin, NULL, (ClientData) NULL);
        if(canvasTkwin != Tk_Parent(winItemPtr->tkwin)) {
            Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
        }
        Tk_UnmapWindow(winItemPtr->tkwin);
    }
    Tk_FreeConfigOptions((char *)itemPtr, itemPtr->optionTable,
        Tk_PathCanvasTkwin(canvas));
}

/*
 *--------------------------------------------------------------
 *
 * ComputeWindowBbox --
 *
 *	This function is invoked to compute the bounding box of all the pixels
 *	that may be drawn as part of a window item. This function is where the
 *	child window's placement is computed.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The fields x1, y1, x2, and y2 are updated in the header for itemPtr.
 *
 *--------------------------------------------------------------
 */

static void
ComputeWindowBbox(
    Tk_PathCanvas canvas,      /* Canvas that contains item. */
    WindowItem * winItemPtr)
{              /* Item whose bbox is to be recomputed. */
int width, height, x, y;
Tk_PathState state = winItemPtr->header.state;

    x = (int)(winItemPtr->x + ((winItemPtr->x >= 0) ? 0.5 : -0.5));
    y = (int)(winItemPtr->y + ((winItemPtr->y >= 0) ? 0.5 : -0.5));

    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if((winItemPtr->tkwin == NULL) || (state == TK_PATHSTATE_HIDDEN)) {
        /*
         * There is no window for this item yet. Just give it a 1x1 bounding
         * box. Don't give it a 0x0 bounding box; there are strange cases
         * where this bounding box might be used as the dimensions of the
         * window, and 0x0 causes problems under X.
         */

        winItemPtr->header.x1 = x;
        winItemPtr->header.x2 = winItemPtr->header.x1 + 1;
        winItemPtr->header.y1 = y;
        winItemPtr->header.y2 = winItemPtr->header.y1 + 1;
        return;
    }

    /*
     * Compute dimensions of window.
     */

    width = winItemPtr->width;
    if(width <= 0) {
        width = Tk_ReqWidth(winItemPtr->tkwin);
        if(width <= 0) {
            width = 1;
        }
    }
    height = winItemPtr->height;
    if(height <= 0) {
        height = Tk_ReqHeight(winItemPtr->tkwin);
        if(height <= 0) {
            height = 1;
        }
    }

    /*
     * Compute location of window, using anchor information.
     */

    switch (winItemPtr->anchor) {
    case TK_ANCHOR_N:
        x -= width / 2;
        break;
    case TK_ANCHOR_NE:
        x -= width;
        break;
    case TK_ANCHOR_E:
        x -= width;
        y -= height / 2;
        break;
    case TK_ANCHOR_SE:
        x -= width;
        y -= height;
        break;
    case TK_ANCHOR_S:
        x -= width / 2;
        y -= height;
        break;
    case TK_ANCHOR_SW:
        y -= height;
        break;
    case TK_ANCHOR_W:
        y -= height / 2;
        break;
    case TK_ANCHOR_NW:
        break;
    case TK_ANCHOR_CENTER:
        x -= width / 2;
        y -= height / 2;
        break;
    }

    /*
     * Store the information in the item header.
     */

    winItemPtr->header.x1 = x;
    winItemPtr->header.y1 = y;
    winItemPtr->header.x2 = x + width;
    winItemPtr->header.y2 = y + height;
}

/*
 *--------------------------------------------------------------
 *
 * DisplayWinItem --
 *
 *	This function is invoked to "draw" a window item in a given drawable.
 *	Since the window draws itself, we needn't do any actual redisplay
 *	here. However, this function takes care of actually repositioning the
 *	child window so that it occupies the correct screen position.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The child window's position may get changed. Note: this function gets
 *	called both when a window needs to be displayed and when it ceases to
 *	be visible on the screen (e.g. it was scrolled or moved off-screen or
 *	the enclosing canvas is unmapped).
 *
 *--------------------------------------------------------------
 */

static void
DisplayWinItem(
    Tk_PathCanvas canvas,      /* Canvas that contains item. */
    Tk_PathItem * itemPtr,     /* Item to be displayed. */
    Display * display,         /* Display on which to draw item. */
    Drawable drawable,         /* Pixmap or window in which to draw item. */
    int regionX,
    int regionY,
    int regionWidth,
    int regionHeight)
                                /* Describes region of canvas that must be
                                 * redisplayed (not used). */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    int width, height;
    short x, y;
    Tk_Window canvasTkwin = Tk_PathCanvasTkwin(canvas);
    Tk_PathState state = itemPtr->state;

    if(winItemPtr->tkwin == NULL) {
        return;
    }
    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }

    /*
     * A drawable of None is used by the canvas UnmapNotify handler
     * to indicate that we should no longer display ourselves.
     */
    if(state == TK_PATHSTATE_HIDDEN || drawable == None) {
        if(canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
            Tk_UnmapWindow(winItemPtr->tkwin);
        } else {
            Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
        }
        return;
    }
    Tk_PathCanvasWindowCoords(canvas, (double)winItemPtr->header.x1,
        (double)winItemPtr->header.y1, &x, &y);
    width = winItemPtr->header.x2 - winItemPtr->header.x1;
    height = winItemPtr->header.y2 - winItemPtr->header.y1;

    /*
     * If the window is completely out of the visible area of the canvas then
     * unmap it. This code used not to be present (why unmap the window if it
     * isn't visible anyway?) but this could cause the window to suddenly
     * reappear if the canvas window got resized.
     */

    if(((x + width) <= 0) || ((y + height) <= 0)
        || (x >= Tk_Width(canvasTkwin)) || (y >= Tk_Height(canvasTkwin))) {
        if(canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
            Tk_UnmapWindow(winItemPtr->tkwin);
        } else {
            Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
        }
        return;
    }

    /*
     * Reposition and map the window (but in different ways depending on
     * whether the canvas is the window's parent).
     */

    if(canvasTkwin == Tk_Parent(winItemPtr->tkwin)) {
        if((x != Tk_X(winItemPtr->tkwin)) || (y != Tk_Y(winItemPtr->tkwin))
            || (width != Tk_Width(winItemPtr->tkwin))
            || (height != Tk_Height(winItemPtr->tkwin))) {
            Tk_MoveResizeWindow(winItemPtr->tkwin, x, y, width, height);
        }
        Tk_MapWindow(winItemPtr->tkwin);
    } else {
        Tk_MaintainGeometry(winItemPtr->tkwin, canvasTkwin, x, y,
            width, height);
    }
}

/*
 *--------------------------------------------------------------
 *
 * WinItemToPoint --
 *
 *	Computes the distance from a given point to a given window, in canvas
 *	units.
 *
 * Results:
 *	The return value is 0 if the point whose x and y coordinates are
 *	coordPtr[0] and coordPtr[1] is inside the window. If the point isn't
 *	inside the window then the return value is the distance from the point
 *	to the window.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static double
WinItemToPoint(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against point. */
    double *pointPtr)
{              /* Pointer to x and y coordinates. */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;
    double x1, x2, y1, y2, xDiff, yDiff;

    x1 = winItemPtr->header.x1;
    y1 = winItemPtr->header.y1;
    x2 = winItemPtr->header.x2;
    y2 = winItemPtr->header.y2;

    /*
     * Point is outside window.
     */

    if(pointPtr[0] < x1) {
        xDiff = x1 - pointPtr[0];
    } else if(pointPtr[0] >= x2) {
        xDiff = pointPtr[0] + 1 - x2;
    } else {
        xDiff = 0;
    }

    if(pointPtr[1] < y1) {
        yDiff = y1 - pointPtr[1];
    } else if(pointPtr[1] >= y2) {
        yDiff = pointPtr[1] + 1 - y2;
    } else {
        yDiff = 0;
    }

    return hypot(xDiff, yDiff);
}

/*
 *--------------------------------------------------------------
 *
 * WinItemToArea --
 *
 *	This function is called to determine whether an item lies entirely
 *	inside, entirely outside, or overlapping a given rectangle.
 *
 * Results:
 *	-1 is returned if the item is entirely outside the area given by
 *	rectPtr, 0 if it overlaps, and 1 if it is entirely inside the given
 *	area.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
WinItemToArea(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against rectangle. */
    double *rectPtr)
{              /* Pointer to array of four coordinates
                * (x1,y1,x2,y2) describing rectangular
                * area.  */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    if((rectPtr[2] <= winItemPtr->header.x1)
        || (rectPtr[0] >= winItemPtr->header.x2)
        || (rectPtr[3] <= winItemPtr->header.y1)
        || (rectPtr[1] >= winItemPtr->header.y2)) {
        return -1;
    }
    if((rectPtr[0] <= winItemPtr->header.x1)
        && (rectPtr[1] <= winItemPtr->header.y1)
        && (rectPtr[2] >= winItemPtr->header.x2)
        && (rectPtr[3] >= winItemPtr->header.y2)) {
        return 1;
    }
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * xerrorhandler --
 *
 *	This is a dummy function to catch X11 errors during an attempt to
 *	print a canvas window.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

#ifdef X_GetImage
static int
xerrorhandler(
    ClientData clientData,
    XErrorEvent * e)
{
    return 0;
}
#endif

/*
 *--------------------------------------------------------------
 *
 * WinItemToPdf --
 *
 *	This function is called to generate Pdf for window items.
 *
 * Results:
 *	The return value is a standard Tcl result. If an error occurs in
 *	generating Pdf then an error message is left in interp->result,
 *	replacing whatever used to be there. If no error occurs, then
 *	Pdf for the item is appended to the result.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */

static int
WinItemToPdf(
    Tcl_Interp * interp,       /* Leave Pdf or error message here. */
    Tk_PathCanvas canvas,      /* Information about overall canvas. */
    Tk_PathItem * itemPtr,     /* Item for which Pdf is wanted. */
    int objc,                  /* Number of arguments. */
    Tcl_Obj * const objv[],    /* Argument list. */
    int prepass)
{              /* 1 means this is a prepass to collect font
                * information; 0 means final Pdf is
                * being created. */
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ScaleWinItem --
 *
 *	This function is invoked to rescale a window item.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The window referred to by itemPtr is rescaled so that the following
 *	transformation is applied to all point coordinates:
 *		x' = originX + scaleX*(x-originX)
 *		y' = originY + scaleY*(y-originY)
 *
 *--------------------------------------------------------------
 */

static void
ScaleWinItem(
    Tk_PathCanvas canvas,      /* Canvas containing window. */
    Tk_PathItem * itemPtr,     /* Window to be scaled. */
    int compensate,            /* Unused. */
    double originX,
    double originY,
    /* Origin about which to scale window. */
    double scaleX,             /* Amount to scale in X direction. */
    double scaleY)
{              /* Amount to scale in Y direction. */
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    winItemPtr->x = originX + scaleX * (winItemPtr->x - originX);
    winItemPtr->y = originY + scaleY * (winItemPtr->y - originY);
    if(winItemPtr->width > 0) {
        winItemPtr->width = (int)(scaleX * winItemPtr->width);
    }
    if(winItemPtr->height > 0) {
        winItemPtr->height = (int)(scaleY * winItemPtr->height);
    }
    ComputeWindowBbox(canvas, winItemPtr);
}

/*
 *--------------------------------------------------------------
 *
 * TranslateWinItem --
 *
 *	This function is called to move a window by a given amount.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The position of the window is offset by (xDelta, yDelta), and the
 *	bounding box is updated in the generic part of the item structure.
 *
 *--------------------------------------------------------------
 */

static void
TranslateWinItem(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item that is being moved. */
    int compensate,            /* Unused. */
    double deltaX,
    double deltaY)
                                /* Amount by which item is to be moved. */
{
    WindowItem *winItemPtr = (WindowItem *) itemPtr;

    winItemPtr->x += deltaX;
    winItemPtr->y += deltaY;
    ComputeWindowBbox(canvas, winItemPtr);
}

/*
 *--------------------------------------------------------------
 *
 * WinItemStructureProc --
 *
 *	This function is invoked whenever StructureNotify events occur for a
 *	window that's managed as part of a canvas window item. This function's
 *	only purpose is to clean up when windows are deleted.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The window is disassociated from the window item when it is deleted.
 *
 *--------------------------------------------------------------
 */

static void
WinItemStructureProc(
    ClientData clientData,     /* Pointer to record describing window item. */
    XEvent * eventPtr)
{              /* Describes what just happened. */
WindowItem *winItemPtr = (WindowItem *) clientData;

    if(eventPtr->type == DestroyNotify) {
        winItemPtr->tkwin = NULL;
    }
}

/*
 *--------------------------------------------------------------
 *
 * WinItemRequestProc --
 *
 *	This function is invoked whenever a window that's associated with a
 *	window canvas item changes its requested dimensions.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The size and location on the screen of the window may change,
 *	depending on the options specified for the window item.
 *
 *--------------------------------------------------------------
 */

static void
WinItemRequestProc(
    ClientData clientData,     /* Pointer to record for window item. */
    Tk_Window tkwin)
{              /* Window that changed its desired size. */
WindowItem *winItemPtr = (WindowItem *) clientData;

    ComputeWindowBbox(winItemPtr->canvas, winItemPtr);

    /*
     * A drawable argument of None to DisplayWinItem is used by the canvas
     * UnmapNotify handler to indicate that we should no longer display
     * ourselves, so need to pass a (bogus) non-zero drawable value here.
     */
    DisplayWinItem(winItemPtr->canvas, (Tk_PathItem *) winItemPtr, NULL,
        (Drawable) - 1, 0, 0, 0, 0);
}

/*
 *--------------------------------------------------------------
 *
 * WinItemLostSlaveProc --
 *
 *	This function is invoked by Tk whenever some other geometry claims
 *	control over a slave that used to be managed by us.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Forgets all canvas-related information about the slave.
 *
 *--------------------------------------------------------------
 */

        /* ARGSUSED */
static void
WinItemLostSlaveProc(
    ClientData clientData,     /* WindowItem structure for slave window that
                                * was stolen away. */
    Tk_Window tkwin)
{              /* Tk's handle for the slave window. */
WindowItem *winItemPtr = (WindowItem *) clientData;
Tk_Window canvasTkwin = Tk_PathCanvasTkwin(winItemPtr->canvas);

    Tk_DeleteEventHandler(winItemPtr->tkwin, StructureNotifyMask,
        WinItemStructureProc, (ClientData) winItemPtr);
    if(canvasTkwin != Tk_Parent(winItemPtr->tkwin)) {
        Tk_UnmaintainGeometry(winItemPtr->tkwin, canvasTkwin);
    }
    Tk_UnmapWindow(winItemPtr->tkwin);
    winItemPtr->tkwin = NULL;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
Added generic/tko/tkoPathGeneric.c.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathGeneric.c --
 *
 *        This file implements a path drawing model
 *      SVG counterpart. See http://www.w3.org/TR/SVG11/.
 *        It contains the generic parts that do not refer to the canvas.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

MODULE_SCOPE int Tk_PathDepixelize;

static const char TK_PATH_SyntaxError[] = "syntax error in path definition";

enum {
    PATH_NEXT_ERROR,
    PATH_NEXT_INSTRUCTION,
    PATH_NEXT_OTHER
};

/*
 * A placeholder for the context we are working in.
 * The current and lastMove are always original untransformed coordinates.
 */

typedef struct TkPointsContext_ {
    double current[2];
    double lastMove[2];
    int widthCode;
} TkPointsContext_;

/*---------------------------------------------------------------------------*/

static void PathPdfMoveTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y);
static void PathPdfLineTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y);
static void PathPdfCurveTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x1,
    double y1,
    double x2,
    double y2,
    double x,
    double y);
static void PathPdfArcTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double rx,
    double ry,
    double phiDegrees,
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y);
static void PathPdfQuadBezier(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double ctrlX,
    double ctrlY,
    double x,
    double y);
static void PathPdfArcToUsingBezier(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double rx,
    double ry,
    double phiDegrees,
    char largeArcFlag,
    char sweepFlag,
    double x2,
    double y2);
static void PathPdfClosePath(
    Tcl_Obj * list,
    TkPointsContext_ * context);
static void PathPdfOval(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double cx,
    double cy,
    double rx,
    double ry);
static void PathPdfRect(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y,
    double width,
    double height);
static int PathPdfGradFuncType2(
    Tcl_Interp * interp,
    Tcl_Obj * mkobj,
    int isAlpha,
    TkGradientStop * stop0,
    TkGradientStop * stop1);
static int PathPdfGradSoftMask(
    Tcl_Interp * interp,
    Tcl_Obj * mkobj,
    TkPathRect * bbox,
    const char *gradName,
    long gradId,
    TkPathMatrix * tmPtr);
static int PathPdfGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bbox,
    TkPathGradientMaster * gradientPtr,
    char **gradName,
    long *gradId,
    TkPathMatrix * tmPtr);
static int PathPdfLinearGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bbox,
    TkLinearGradientFill * fillPtr,
    TkPathMatrix * mPtr);
static int PathPdfRadialGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bbox,
    TkRadialGradientFill * fillPtr,
    TkPathMatrix * mPtr,
    TkPathMatrix * tmPtr);

/*---------------------------------------------------------------------------*/

MODULE_SCOPE int
TkPathPixelAlignObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(TkPathPixelAlign()));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * GetPathInstruction --
 *
 *        Gets the path instruction at position index of objv.
 *        If unrecognized instruction returns PATH_NEXT_ERROR.
 *
 * Results:
 *        A PATH_NEXT_* result.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

static int
GetPathInstruction(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int index,
    char *c)
{
    int len;
    int result;
    char *str;

    *c = '\0';
    str = Tcl_GetStringFromObj(objv[index], &len);
    if(isalpha(str[0])) {
        if(len != 1) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
            result = PATH_NEXT_ERROR;
        } else {
            switch (str[0]) {
            case 'M':
            case 'm':
            case 'L':
            case 'l':
            case 'H':
            case 'h':
            case 'V':
            case 'v':
            case 'A':
            case 'a':
            case 'Q':
            case 'q':
            case 'T':
            case 't':
            case 'C':
            case 'c':
            case 'S':
            case 's':
            case 'Z':
            case 'z':
                result = PATH_NEXT_INSTRUCTION;
                *c = str[0];
                break;
            default:
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
                result = PATH_NEXT_ERROR;
                break;
            }
        }
    } else {
        result = PATH_NEXT_OTHER;
    }
    return result;
}

/*
 *--------------------------------------------------------------
 *
 * GetPathDouble, GetPathBoolean, GetPathPoint, GetPathTwoPoints,
 * GetPathThreePoints, GetPathArcParameters --
 *
 *        Gets a certain number of numbers from objv.
 *        Increments indexPtr by the number of numbers extracted
 *        if succesful, else it is unchanged.
 *
 * Results:
 *        A standard tcl result.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

static int
GetPathDouble(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    double *zPtr)
{
    int result;

    if(*indexPtr > len - 1) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
        result = TCL_ERROR;
    } else {
        result = Tcl_GetDoubleFromObj(interp, objv[*indexPtr], zPtr);
        if(result == TCL_OK) {
            (*indexPtr)++;
        }
    }
    return result;
}

static int
GetPathBoolean(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    char *boolPtr)
{
    int result;
    int boolean;

    if(*indexPtr > len - 1) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
        result = TCL_ERROR;
    } else {
        result = Tcl_GetBooleanFromObj(interp, objv[*indexPtr], &boolean);
        if(result == TCL_OK) {
            (*indexPtr)++;
            *boolPtr = boolean;
        }
    }
    return result;
}

static int
GetPathPoint(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    double *xPtr,
    double *yPtr)
{
    int result = TCL_OK;
    int indIn = *indexPtr;

    if(*indexPtr > len - 2) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
        result = TCL_ERROR;
    } else if(Tcl_GetDoubleFromObj(interp, objv[(*indexPtr)++], xPtr) != TCL_OK) {
        *indexPtr = indIn;
        result = TCL_ERROR;
    } else if(Tcl_GetDoubleFromObj(interp, objv[(*indexPtr)++], yPtr) != TCL_OK) {
        *indexPtr = indIn;
        result = TCL_ERROR;
    }
    return result;
}

static int
GetPathTwoPoints(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    double *x1Ptr,
    double *y1Ptr,
    double *x2Ptr,
    double *y2Ptr)
{
    int result;
    int indIn = *indexPtr;

    result = GetPathPoint(interp, objv, len, indexPtr, x1Ptr, y1Ptr);
    if(result == TCL_OK) {
        if(GetPathPoint(interp, objv, len, indexPtr, x2Ptr, y2Ptr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        }
    }
    return result;
}

static int
GetPathThreePoints(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    double *x1Ptr,
    double *y1Ptr,
    double *x2Ptr,
    double *y2Ptr,
    double *x3Ptr,
    double *y3Ptr)
{
    int result;
    int indIn = *indexPtr;

    result = GetPathPoint(interp, objv, len, indexPtr, x1Ptr, y1Ptr);
    if(result == TCL_OK) {
        if(GetPathPoint(interp, objv, len, indexPtr, x2Ptr, y2Ptr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        } else if(GetPathPoint(interp, objv, len, indexPtr,
                x3Ptr, y3Ptr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        }
    }
    return result;
}

static int
GetPathArcParameters(
    Tcl_Interp * interp,
    Tcl_Obj * const objv[],
    int len,
    int *indexPtr,
    double *radXPtr,
    double *radYPtr,
    double *anglePtr,
    char *largeArcFlagPtr,
    char *sweepFlagPtr,
    double *xPtr,
    double *yPtr)
{
    int result;
    int indIn = *indexPtr;

    result = GetPathPoint(interp, objv, len, indexPtr, radXPtr, radYPtr);
    if(result == TCL_OK) {
        if(GetPathDouble(interp, objv, len, indexPtr, anglePtr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        } else if(GetPathBoolean(interp, objv, len, indexPtr,
                largeArcFlagPtr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        } else if(GetPathBoolean(interp, objv, len, indexPtr,
                sweepFlagPtr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        } else if(GetPathPoint(interp, objv, len, indexPtr,
                xPtr, yPtr) != TCL_OK) {
            *indexPtr = indIn;
            result = TCL_ERROR;
        }
    }
    return result;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathNewMoveToAtom, TkPathNewLineToAtom, TkPathNewArcAtom, TkPathNewQuadBezierAtom,
 * TkPathNewCurveToAtom, TkPathNewCloseAtom --
 *
 *        Creates a TkPathAtom of the specified type using the given
 *        parameters. It updates the currentX and currentY.
 *
 * Results:
 *        A TkPathAtom pointer.
 *
 * Side effects:
 *        Memory allocated.
 *
 *--------------------------------------------------------------
 */

TkPathAtom *
TkPathNewMoveToAtom(
    double x,
    double y)
{
TkPathAtom *atomPtr;
TkMoveToAtom *moveToAtomPtr;

    moveToAtomPtr = (TkMoveToAtom *) ckalloc((unsigned)(sizeof(TkMoveToAtom)));
    atomPtr = (TkPathAtom *) moveToAtomPtr;
    atomPtr->type = TK_PATH_ATOM_M;
    atomPtr->nextPtr = NULL;
    moveToAtomPtr->x = x;
    moveToAtomPtr->y = y;
    return atomPtr;
}

TkPathAtom *
TkPathNewLineToAtom(
    double x,
    double y)
{
TkPathAtom *atomPtr;
TkLineToAtom *lineToAtomPtr;

    lineToAtomPtr = (TkLineToAtom *) ckalloc((unsigned)(sizeof(TkLineToAtom)));
    atomPtr = (TkPathAtom *) lineToAtomPtr;
    atomPtr->type = TK_PATH_ATOM_L;
    atomPtr->nextPtr = NULL;
    lineToAtomPtr->x = x;
    lineToAtomPtr->y = y;
    return atomPtr;
}

TkPathAtom *
TkPathNewArcAtom(
    double radX,
    double radY,
    double angle,
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
TkPathAtom *atomPtr;
TkArcAtom *arcAtomPtr;

    arcAtomPtr = (TkArcAtom *) ckalloc((unsigned)(sizeof(TkArcAtom)));
    atomPtr = (TkPathAtom *) arcAtomPtr;
    atomPtr->type = TK_PATH_ATOM_A;
    atomPtr->nextPtr = NULL;
    arcAtomPtr->radX = radX;
    arcAtomPtr->radY = radY;
    arcAtomPtr->angle = angle;
    arcAtomPtr->largeArcFlag = largeArcFlag;
    arcAtomPtr->sweepFlag = sweepFlag;
    arcAtomPtr->x = x;
    arcAtomPtr->y = y;
    return atomPtr;
}

TkPathAtom *
TkPathNewQuadBezierAtom(
    double ctrlX,
    double ctrlY,
    double anchorX,
    double anchorY)
{
TkPathAtom *atomPtr;
TkQuadBezierAtom *quadBezierAtomPtr;

    quadBezierAtomPtr =
        (TkQuadBezierAtom *) ckalloc((unsigned)(sizeof(TkQuadBezierAtom)));
    atomPtr = (TkPathAtom *) quadBezierAtomPtr;
    atomPtr->type = TK_PATH_ATOM_Q;
    atomPtr->nextPtr = NULL;
    quadBezierAtomPtr->ctrlX = ctrlX;
    quadBezierAtomPtr->ctrlY = ctrlY;
    quadBezierAtomPtr->anchorX = anchorX;
    quadBezierAtomPtr->anchorY = anchorY;
    return atomPtr;
}

TkPathAtom *
TkPathNewCurveToAtom(
    double ctrlX1,
    double ctrlY1,
    double ctrlX2,
    double ctrlY2,
    double anchorX,
    double anchorY)
{
TkPathAtom *atomPtr;
TkCurveToAtom *curveToAtomPtr;

    curveToAtomPtr =
        (TkCurveToAtom *) ckalloc((unsigned)(sizeof(TkCurveToAtom)));
    atomPtr = (TkPathAtom *) curveToAtomPtr;
    atomPtr->type = TK_PATH_ATOM_C;
    atomPtr->nextPtr = NULL;
    curveToAtomPtr->ctrlX1 = ctrlX1;
    curveToAtomPtr->ctrlY1 = ctrlY1;
    curveToAtomPtr->ctrlX2 = ctrlX2;
    curveToAtomPtr->ctrlY2 = ctrlY2;
    curveToAtomPtr->anchorX = anchorX;
    curveToAtomPtr->anchorY = anchorY;
    return atomPtr;
}

TkPathAtom *
TkPathNewRectAtom(
    double pointsPtr[])
{
TkPathAtom *atomPtr;
TkRectAtom *rectAtomPtr;

    rectAtomPtr = (TkRectAtom *) ckalloc((unsigned)(sizeof(TkRectAtom)));
    atomPtr = (TkPathAtom *) rectAtomPtr;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_RECT;
    rectAtomPtr->x = pointsPtr[0];
    rectAtomPtr->y = pointsPtr[1];
    rectAtomPtr->width = pointsPtr[2] - pointsPtr[0];
    rectAtomPtr->height = pointsPtr[3] - pointsPtr[1];
    return atomPtr;
}

TkPathAtom *
TkPathNewCloseAtom(
    double x,
    double y)
{
TkPathAtom *atomPtr;
TkCloseAtom *closeAtomPtr;

    closeAtomPtr = (TkCloseAtom *) ckalloc((unsigned)(sizeof(TkCloseAtom)));
    atomPtr = (TkPathAtom *) closeAtomPtr;
    atomPtr->type = TK_PATH_ATOM_Z;
    atomPtr->nextPtr = NULL;
    closeAtomPtr->x = x;
    closeAtomPtr->y = y;
    return atomPtr;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathParseToAtoms
 *
 *        Takes a tcl list of values which defines the path item and
 *        parses them into a linked list of path atoms.
 *
 * Results:
 *        A standard Tcl result.
 *
 * Side effects:
 *        None
 *
 *--------------------------------------------------------------
 */

int
TkPathParseToAtoms(
    Tcl_Interp * interp,
    Tcl_Obj * listObjPtr,
    TkPathAtom ** atomPtrPtr,
    int *lenPtr)
{
    char currentInstr;         /* current instruction (M, l, c, etc.) */
    char lastInstr;            /* previous instruction */
    int len;
    int currentInd;
    int index;
    int next;
    int relative;
    double currentX, currentY; /* current point */
    double startX, startY;     /* the current moveto point */
    double ctrlX, ctrlY;       /* last control point, for s, S, t, T */
    double x, y;
    Tcl_Obj **objv;
    TkPathAtom *atomPtr = NULL;
    TkPathAtom *currentAtomPtr = NULL;

    *atomPtrPtr = NULL;
    currentX = 0.0;
    currentY = 0.0;
    startX = 0.0;
    startY = 0.0;
    ctrlX = 0.0;
    ctrlY = 0.0;
    lastInstr = 'M';    /* If first instruction is missing it defaults to M ? */
    relative = 0;

    if(Tcl_ListObjGetElements(interp, listObjPtr, lenPtr, &objv) != TCL_OK) {
        return TCL_ERROR;
    }
    len = *lenPtr;

    /* First some error checking. Necessary??? */
    if(len < 3) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("path specification too short", -1));
        return TCL_ERROR;
    }
    if((GetPathInstruction(interp, objv, 0, &currentInstr)
            != PATH_NEXT_INSTRUCTION) || (toupper(currentInstr) != 'M')) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("path must start with M or m",
                -1));
        return TCL_ERROR;
    }
    currentInd = 1;
    if(GetPathPoint(interp, objv, len, &currentInd, &x, &y) != TCL_OK) {
        return TCL_ERROR;
    }
    currentInd = 0;

    while(currentInd < len) {

        next = GetPathInstruction(interp, objv, currentInd, &currentInstr);
        if(next == PATH_NEXT_ERROR) {
            goto error;
        } else if(next == PATH_NEXT_INSTRUCTION) {
            relative = islower(currentInstr);
            currentInd++;
        } else if(next == PATH_NEXT_OTHER) {

            /* Use rule to find instruction to use. */
            if(lastInstr == 'M') {
                currentInstr = 'L';
            } else if(lastInstr == 'm') {
                currentInstr = 'l';
            } else {
                currentInstr = lastInstr;
            }
            relative = islower(currentInstr);
        }
        index = currentInd;

        switch (currentInstr) {

        case 'M':
        case 'm':{
            if(GetPathPoint(interp, objv, len, &index, &x, &y) != TCL_OK) {
                goto error;
            }
            if(relative) {
                x += currentX;
                y += currentY;
            }
            atomPtr = TkPathNewMoveToAtom(x, y);
            if(currentAtomPtr == NULL) {
                *atomPtrPtr = atomPtr;
            } else {
                currentAtomPtr->nextPtr = atomPtr;
            }
            currentAtomPtr = atomPtr;
            currentX = x;
            currentY = y;
            startX = x;
            startY = y;
            break;
        }

        case 'L':
        case 'l':{
            if(index > len - 2) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
                goto error;
            }
            if(GetPathPoint(interp, objv, len, &index, &x, &y) == TCL_OK) {
                if(relative) {
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewLineToAtom(x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'A':
        case 'a':{
    double radX, radY, angle;
    char largeArcFlag, sweepFlag;

            if(GetPathArcParameters(interp, objv, len, &index,
                    &radX, &radY, &angle, &largeArcFlag, &sweepFlag,
                    &x, &y) == TCL_OK) {
                if(relative) {
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewArcAtom(radX, radY, angle,
                    largeArcFlag, sweepFlag, x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'C':
        case 'c':{
    double x1, y1, x2, y2;     /* The two control points. */

            if(index > len - 6) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj(TK_PATH_SyntaxError, -1));
                goto error;
            }
            if(GetPathThreePoints(interp, objv, len, &index,
                    &x1, &y1, &x2, &y2, &x, &y) == TCL_OK) {
                if(relative) {
                    x1 += currentX;
                    y1 += currentY;
                    x2 += currentX;
                    y2 += currentY;
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewCurveToAtom(x1, y1, x2, y2, x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                ctrlX = x2;     /* Keep track of the last control point. */
                ctrlY = y2;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'S':
        case 's':{
    double x1, y1;             /* The first control point. */
    double x2, y2;             /* The second control point. */

            if((toupper(lastInstr) == 'C') || (toupper(lastInstr) == 'S')) {
                /*
                 * The first controlpoint is the reflection
                 * of the last one about the current point:
                 */
                x1 = 2 * currentX - ctrlX;
                y1 = 2 * currentY - ctrlY;
            } else {
                /* The first controlpoint is equal to the current point: */
                x1 = currentX;
                y1 = currentY;
            }
            if(index > len - 4) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj(TK_PATH_SyntaxError,
                        -1));
                goto error;
            }
            if(GetPathTwoPoints(interp, objv, len, &index,
                    &x2, &y2, &x, &y) == TCL_OK) {
                if(relative) {
                    x2 += currentX;
                    y2 += currentY;
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewCurveToAtom(x1, y1, x2, y2, x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                ctrlX = x2;     /* Keep track of the last control point. */
                ctrlY = y2;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'Q':
        case 'q':{
    double x1, y1;             /* The control point. */

            if(GetPathTwoPoints(interp, objv, len, &index,
                    &x1, &y1, &x, &y) == TCL_OK) {
                if(relative) {
                    x1 += currentX;
                    y1 += currentY;
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewQuadBezierAtom(x1, y1, x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                ctrlX = x1;     /* Keep track of the last control point. */
                ctrlY = y1;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'T':
        case 't':{
    double x1, y1;             /* The control point. */

            if((toupper(lastInstr) == 'Q') || (toupper(lastInstr) == 'T')) {
                /*
                 * The controlpoint is the reflection
                 * of the last one about the current point:
                 */
                x1 = 2 * currentX - ctrlX;
                y1 = 2 * currentY - ctrlY;
            } else {
                /* The controlpoint is equal to the current point: */
                x1 = currentX;
                y1 = currentY;
            }
            if(GetPathPoint(interp, objv, len, &index, &x, &y) == TCL_OK) {
                if(relative) {
                    x += currentX;
                    y += currentY;
                }
                atomPtr = TkPathNewQuadBezierAtom(x1, y1, x, y);
                currentAtomPtr->nextPtr = atomPtr;
                currentAtomPtr = atomPtr;
                ctrlX = x1;     /* Keep track of the last control point. */
                ctrlY = y1;
                currentX = x;
                currentY = y;
            } else {
                goto error;
            }
            break;
        }

        case 'H':{
            while((index < len) && (GetPathDouble(interp, objv, len, &index, &x)
                    == TCL_OK));
            atomPtr = TkPathNewLineToAtom(x, currentY);
            currentAtomPtr->nextPtr = atomPtr;
            currentAtomPtr = atomPtr;
            currentX = x;
            break;
        }

        case 'h':{
    double z;

            x = currentX;
            while((index < len) && (GetPathDouble(interp, objv, len, &index, &z)
                    == TCL_OK)) {
                x += z;
            }
            atomPtr = TkPathNewLineToAtom(x, currentY);
            currentAtomPtr->nextPtr = atomPtr;
            currentAtomPtr = atomPtr;
            currentX = x;
            break;
        }

        case 'V':{
            while((index < len) && (GetPathDouble(interp, objv, len, &index, &y)
                    == TCL_OK));
            atomPtr = TkPathNewLineToAtom(currentX, y);
            currentAtomPtr->nextPtr = atomPtr;
            currentAtomPtr = atomPtr;
            currentY = y;
            break;
        }

        case 'v':{
    double z;

            y = currentY;
            while((index < len) && (GetPathDouble(interp, objv, len, &index, &z)
                    == TCL_OK)) {
                y += z;
            }
            atomPtr = TkPathNewLineToAtom(currentX, y);
            currentAtomPtr->nextPtr = atomPtr;
            currentAtomPtr = atomPtr;
            currentY = y;
            break;
        }

        case 'Z':
        case 'z':{
            atomPtr = TkPathNewCloseAtom(startX, startY);
            currentAtomPtr->nextPtr = atomPtr;
            currentAtomPtr = atomPtr;
            currentX = startX;
            currentY = startY;
            break;
        }

        default:{
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj("unrecognized path instruction", -1));
            goto error;
        }
        }
        currentInd = index;
        lastInstr = currentInstr;
    }

    /* When we parse coordinates there may be some junk result
     * left in the interpreter to be cleared out. */
    Tcl_ResetResult(interp);
    return TCL_OK;

  error:

    TkPathFreeAtoms(*atomPtrPtr);
    *atomPtrPtr = NULL;
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathFreeAtoms
 *
 *        Frees up all memory allocated for the path atoms.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

void
TkPathFreeAtoms(
    TkPathAtom * pathAtomPtr)
{
TkPathAtom *tmpAtomPtr;

    while(pathAtomPtr != NULL) {
        tmpAtomPtr = pathAtomPtr;
        pathAtomPtr = tmpAtomPtr->nextPtr;
        ckfree((char *)tmpAtomPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathNormalize
 *
 *        Takes a list of TkPathAtoms and creates a tcl list where
 *        elements have a standard form. All upper case instructions,
 *        no repeates.
 *
 * Results:
 *        A standard Tcl result.
 *
 * Side effects:
 *        New list returned in listObjPtrPtr.
 *
 *--------------------------------------------------------------
 */

int
TkPathNormalize(
    Tcl_Interp * interp,
    TkPathAtom * atomPtr,
    Tcl_Obj ** listObjPtrPtr)
{
Tcl_Obj *normObjPtr;

    normObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("M", -1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(move->x));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(move->y));
            break;
        }
        case TK_PATH_ATOM_L:{
TkLineToAtom *line = (TkLineToAtom *) atomPtr;

            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("L", -1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(line->x));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(line->y));
            break;
        }
        case TK_PATH_ATOM_A:{
TkArcAtom *arc = (TkArcAtom *) atomPtr;

            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("A", -1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(arc->radX));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(arc->radY));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(arc->angle));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewBooleanObj(arc->largeArcFlag));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewBooleanObj(arc->sweepFlag));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(arc->x));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(arc->y));
            break;
        }
        case TK_PATH_ATOM_Q:{
TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;

            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("Q", -1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(quad->ctrlX));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(quad->ctrlY));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(quad->anchorX));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(quad->anchorY));
            break;
        }
        case TK_PATH_ATOM_C:{
TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("C", -1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->ctrlX1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->ctrlY1));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->ctrlX2));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->ctrlY2));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->anchorX));
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewDoubleObj(curve->anchorY));
            break;
        }
        case TK_PATH_ATOM_Z:{
            Tcl_ListObjAppendElement(interp, normObjPtr,
                Tcl_NewStringObj("Z", -1));
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            /* Empty. */
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
    *listObjPtrPtr = normObjPtr;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathMakePath
 *
 *        Defines the path using the TkPathAtom.
 *
 * Results:
 *        A standard Tcl result.
 *
 * Side effects:
 *        Defines the current path in drawable.
 *
 *--------------------------------------------------------------
 */

int
TkPathMakePath(
    TkPathContext context,
    TkPathAtom * atomPtr,
    Tk_PathStyle * stylePtr)
{
    TkPathBeginPath(context, stylePtr);

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;
            TkPathMoveTo(context, move->x, move->y);
            break;
        }
        case TK_PATH_ATOM_L:{
TkLineToAtom *line = (TkLineToAtom *) atomPtr;
            TkPathLineTo(context, line->x, line->y);
            break;
        }
        case TK_PATH_ATOM_A:{
TkArcAtom *arc = (TkArcAtom *) atomPtr;
            TkPathArcTo(context, arc->radX, arc->radY, arc->angle,
                arc->largeArcFlag, arc->sweepFlag, arc->x, arc->y);
            break;
        }
        case TK_PATH_ATOM_Q:{
TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;
            TkPathQuadBezier(context,
                quad->ctrlX, quad->ctrlY, quad->anchorX, quad->anchorY);
            break;
        }
        case TK_PATH_ATOM_C:{
TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;
            TkPathCurveTo(context,
                curve->ctrlX1, curve->ctrlY1,
                curve->ctrlX2, curve->ctrlY2, curve->anchorX, curve->anchorY);
            break;
        }
        case TK_PATH_ATOM_Z:{
            TkPathClosePath(context);
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:{
TkEllipseAtom *ell = (TkEllipseAtom *) atomPtr;
            TkPathOval(context, ell->cx, ell->cy, ell->rx, ell->ry);
            break;
        }
        case TK_PATH_ATOM_RECT:{
TkRectAtom *rect = (TkRectAtom *) atomPtr;
            TkPathRectangle(context, rect->x, rect->y,
                rect->width, rect->height);
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
    TkPathEndPath(context);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathArcToUsingBezier
 *
 *        Translates an ArcTo drawing into a sequence of CurveTo.
 *        Helper function for the platform specific drawing code.
 *
 * Results:
 *        None.
 *
 * Side effects:
 *        None.
 *
 *--------------------------------------------------------------
 */

void
TkPathArcToUsingBezier(
    TkPathContext ctx,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x2,
    double y2)
{
    int result;
    int i, segments;
    double x1, y1;
    double cx, cy;
    double theta1, dtheta, phi;
    double sinPhi, cosPhi;
    double delta, t;
    TkPathPoint pt;

    TkPathGetCurrentPosition(ctx, &pt);
    x1 = pt.x;
    y1 = pt.y;

    /* All angles except phi is in radians! */
    phi = phiDegrees * DEGREES_TO_RADIANS;

    /* Check return value and take action. */
    result = TkPathEndpointToCentralArcParameters(x1, y1,
        x2, y2, rx, ry, phi, largeArcFlag, sweepFlag,
        &cx, &cy, &rx, &ry, &theta1, &dtheta);
    if(result == TK_PATH_ARC_Skip) {
        return;
    } else if(result == TK_PATH_ARC_Line) {
        TkPathLineTo(ctx, x2, y2);
        return;
    }
    sinPhi = sin(phi);
    cosPhi = cos(phi);

    /*
     * Convert into cubic bezier segments <= 90deg
     * (from mozilla/svg; not checked)
     */
    segments = (int)ceil(fabs(dtheta / (M_PI / 2.0)));
    delta = dtheta / segments;
    t = 8.0 / 3.0 * sin(delta / 4.0) * sin(delta / 4.0) / sin(delta / 2.0);

    for(i = 0; i < segments; ++i) {
    double cosTheta1 = cos(theta1);
    double sinTheta1 = sin(theta1);
    double theta2 = theta1 + delta;
    double cosTheta2 = cos(theta2);
    double sinTheta2 = sin(theta2);

        /* a) calculate endpoint of the segment: */
    double xe = cosPhi * rx * cosTheta2 - sinPhi * ry * sinTheta2 + cx;
    double ye = sinPhi * rx * cosTheta2 + cosPhi * ry * sinTheta2 + cy;

        /* b) calculate gradients at start/end points of segment: */
    double dx1 = t * (-cosPhi * rx * sinTheta1 - sinPhi * ry * cosTheta1);
    double dy1 = t * (-sinPhi * rx * sinTheta1 + cosPhi * ry * cosTheta1);

    double dxe = t * (cosPhi * rx * sinTheta2 + sinPhi * ry * cosTheta2);
    double dye = t * (sinPhi * rx * sinTheta2 - cosPhi * ry * cosTheta2);

        /* c) draw the cubic bezier: */
        TkPathCurveTo(ctx, x1 + dx1, y1 + dy1, xe + dxe, ye + dye, xe, ye);

        /* do next segment */
        theta1 = theta2;
        x1 = (float)xe;
        y1 = (float)ye;
    }
}

/*---------------------------------------------------------------------------*/

static int
PrintNumber(
    char *buffer,
    int fracDigits,
    double number)
{
    int len;

    sprintf(buffer, "%.*f", fracDigits, number);
    len = strlen(buffer);
    while(len > 0) {
        if(buffer[len - 1] != '0') {
            break;
        }
        --len;
        buffer[len] = '\0';
    }
    if((len > 0) && (buffer[len - 1] == '.')) {
        --len;
        buffer[len] = '\0';
    }
    if((len == 0) || (strcmp(buffer, "-0") == 0)) {
        strcpy(buffer, "0");
        len = 1;
    }
    return len;
}

/*---------------------------------------------------------------------------*/

MODULE_SCOPE int
TkPathPdfNumber(
    Tcl_Obj * ret,
    int fracDigits,
    double number,
    const char *append)
{
    char buffer[TCL_DOUBLE_SPACE * 2];
    int len = PrintNumber(buffer, fracDigits, number);

    Tcl_AppendToObj(ret, buffer, len);
    if(append != NULL) {
        Tcl_AppendToObj(ret, append, -1);
    }
    return len;
}

/*---------------------------------------------------------------------------*/

MODULE_SCOPE int
TkPathPdfColor(
    Tcl_Obj * ret,
    XColor * colorPtr,
    const char *command)
{
    double red, green, blue;

    /*
     * No color map entry for this color. Grab the color's intensities and
     * output Postscript commands for them. Special note: X uses a range of
     * 0-65535 for intensities, but most displays only use a range of 0-255,
     * which maps to (0, 256, 512, ... 65280) in the X scale. This means that
     * there's no way to get perfect white, since the highest intensity is
     * only 65280 out of 65535. To work around this problem, rescale the X
     * intensity to a 0-255 scale and use that as the basis for the Postscript
     * colors. This scheme still won't work if the display only uses 4 bits
     * per color, but most diplays use at least 8 bits.
     */

    red = ((double)(((int)colorPtr->red) >> 8)) / 255.0;
    green = ((double)(((int)colorPtr->green) >> 8)) / 255.0;
    blue = ((double)(((int)colorPtr->blue) >> 8)) / 255.0;
    TkPathPdfNumber(ret, 3, red, " ");
    TkPathPdfNumber(ret, 3, green, " ");
    TkPathPdfNumber(ret, 3, blue, " ");
    Tcl_AppendToObj(ret, command, -1);
    Tcl_AppendToObj(ret, "\n", 1);
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

MODULE_SCOPE int
TkPathPdfArrow(
    Tcl_Interp * interp,
    TkPathArrowDescr * arrow,
    Tk_PathStyle * const style)
{
    Tk_PathStyle arrowStyle = *style;
    TkPathColor fc;
    TkPathAtom *atomPtr;

    if(arrow->arrowEnabled && arrow->arrowPointsPtr != NULL) {
    Tcl_Obj *ret;

        arrowStyle.matrixPtr = NULL;
        if(arrow->arrowFillRatio > 0.0 && arrow->arrowLength != 0.0) {
            arrowStyle.strokeWidth = 0.0;
            fc.color = arrowStyle.strokeColor;
            fc.gradientInstPtr = NULL;
            arrowStyle.fill = &fc;
            arrowStyle.fillOpacity = arrowStyle.strokeOpacity;
        } else {
            arrowStyle.fill = NULL;
            arrowStyle.fillOpacity = 1.0;
            arrowStyle.joinStyle = 1;
            arrowStyle.dashPtr = NULL;
        }
        atomPtr = TkPathMakePathAtomsFromArrow(arrow);
        ret = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(ret);
        Tcl_ResetResult(interp);
        if(TkPathPdf(interp, atomPtr, &arrowStyle, NULL, 0, NULL) != TCL_OK) {
            Tcl_DecrRefCount(ret);
            TkPathFreeAtoms(atomPtr);
            return TCL_ERROR;
        }
        Tcl_AppendObjToObj(ret, Tcl_GetObjResult(interp));
        Tcl_SetObjResult(interp, ret);
        TkPathFreeAtoms(atomPtr);
    }
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

MODULE_SCOPE int
TkPathPdf(
    Tcl_Interp * interp,       /* Used to return resulting info */
    TkPathAtom * atom0Ptr,     /* The actual path as a linked list
                                * of TkPathAtoms. */
    Tk_PathStyle * stylePtr,   /* The path's style. */
    TkPathRect * bboxPtr,      /* The bounding box or NULL. */
    int objc,                  /* Number of arguments of callback. */
    Tcl_Obj * const objv[])
{              /* Argument list of callback. */
    Tcl_Obj *ret = Tcl_NewObj();
    Tcl_Obj *mkextgs = (objc > 0) ? objv[0] : NULL;
    Tcl_Obj *mkobj = (objc > 1) ? objv[1] : NULL;
    Tcl_Obj *mkgrad = (objc > 2) ? objv[2] : NULL;
    Tcl_Obj *gsAlpha = NULL;
    int myZ = 0, f = 0, s = 0, isLinear = 0, i;
    TkPointsContext_ context;
    TkPathAtom *atomPtr;
    char *gradName = NULL;
    TkPathMatrix gm;

    context.current[0] = context.current[1] = 0.;
    context.lastMove[0] = context.lastMove[1] = 0.;
    context.widthCode = 0;      /* TODO check */

    if(stylePtr != NULL) {
    TkPathGradientMaster *gradientPtr =
        GetGradientMasterFromPathColor(stylePtr->fill);

        if((stylePtr->dashPtr != NULL) && (stylePtr->dashPtr->number > 0)) {
            Tcl_AppendToObj(ret, "q [ ", 4);
            for(i = 0; i < stylePtr->dashPtr->number; i++) {
                TkPathPdfNumber(ret, 6, stylePtr->dashPtr->array[i], " ");
            }
            Tcl_AppendToObj(ret, "] ", 2);
            TkPathPdfNumber(ret, 6, stylePtr->offset, " d\n");
        }

        if(gradientPtr != NULL) {
            isLinear = (gradientPtr->type == TK_PATH_GRADIENTTYPE_LINEAR);
        }
        if(mkextgs != NULL) {
    int retc;
    long gradId, smaskId;
    char *gradAlpha = NULL;
    Tcl_Obj *gs, *cmd, **retv;

            if((mkgrad != NULL) && (gradientPtr != NULL) && (bboxPtr != NULL)) {
                if(PathPdfGradient(interp, 1, mkobj, mkgrad, bboxPtr,
                        gradientPtr, &gradAlpha, &gradId, &gm)
                    != TCL_OK) {
                    return TCL_ERROR;
                }
            }
            if(gradAlpha != NULL) {
                if(PathPdfGradSoftMask(interp, mkobj, bboxPtr,
                        gradAlpha, gradId, isLinear ? NULL : &gm) != TCL_OK) {
                    return TCL_ERROR;
                }
                Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &smaskId);
                gs = TkPathExtGS(stylePtr, &smaskId);
                cmd = Tcl_DuplicateObj(mkextgs);
                Tcl_IncrRefCount(cmd);
                if((Tcl_ListObjAppendElement(interp, cmd, gs) != TCL_OK) ||
                    (Tcl_ListObjAppendElement(interp, cmd,
                            Tcl_NewLongObj(smaskId)) != TCL_OK)) {
                    Tcl_DecrRefCount(cmd);
                    Tcl_DecrRefCount(gs);
                    Tcl_DecrRefCount(ret);
                    return TCL_ERROR;
                }
                if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
                    Tcl_DecrRefCount(cmd);
                    Tcl_DecrRefCount(ret);
                    return TCL_ERROR;
                }
                Tcl_DecrRefCount(cmd);
                /*
                 * Get name of extended graphics state.
                 */
                if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                        &retc, &retv) != TCL_OK) {
                    Tcl_DecrRefCount(ret);
                    return TCL_ERROR;
                }
                if(retc < 2) {
                    Tcl_SetResult(interp, (char *)"missing PDF id/name",
                        TCL_STATIC);
                    Tcl_DecrRefCount(ret);
                    return TCL_ERROR;
                }
                gsAlpha = retv[1];
                Tcl_IncrRefCount(gsAlpha);
            }
            gs = TkPathExtGS(stylePtr, NULL);
            if(gs != NULL) {
                cmd = Tcl_DuplicateObj(mkextgs);
                Tcl_IncrRefCount(cmd);
                if((Tcl_ListObjAppendElement(interp, cmd, gs) != TCL_OK) ||
                    ((gradAlpha != NULL) &&
                        (Tcl_ListObjAppendElement(interp, cmd,
                                Tcl_NewLongObj(smaskId)) != TCL_OK))) {
                    Tcl_DecrRefCount(cmd);
                    Tcl_DecrRefCount(gs);
                    Tcl_DecrRefCount(ret);
                    if(gsAlpha != NULL) {
                        Tcl_DecrRefCount(gsAlpha);
                    }
                    return TCL_ERROR;
                }
                if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
                    Tcl_DecrRefCount(cmd);
                    Tcl_DecrRefCount(ret);
                    if(gsAlpha != NULL) {
                        Tcl_DecrRefCount(gsAlpha);
                    }
                    return TCL_ERROR;
                }
                Tcl_DecrRefCount(cmd);
                /*
                 * Get name of extended graphics state.
                 */
                if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                        &retc, &retv) != TCL_OK) {
                    Tcl_DecrRefCount(ret);
                    if(gsAlpha != NULL) {
                        Tcl_DecrRefCount(gsAlpha);
                    }
                    return TCL_ERROR;
                }
                if(retc < 2) {
                    Tcl_SetResult(interp, (char *)"missing PDF id/name",
                        TCL_STATIC);
                    Tcl_DecrRefCount(ret);
                    if(gsAlpha != NULL) {
                        Tcl_DecrRefCount(gsAlpha);
                    }
                    return TCL_ERROR;
                }
                Tcl_AppendPrintfToObj(ret, "/%s gs\n", Tcl_GetString(retv[1]));
            }
        }
        if(stylePtr->matrixPtr != NULL) {
            /* TkPathMatrix */
            TkPathPdfNumber(ret, 6, stylePtr->matrixPtr->a, " ");
            TkPathPdfNumber(ret, 6, stylePtr->matrixPtr->b, " ");
            TkPathPdfNumber(ret, 6, stylePtr->matrixPtr->c, " ");
            TkPathPdfNumber(ret, 6, stylePtr->matrixPtr->d, " ");
            TkPathPdfNumber(ret, 3, stylePtr->matrixPtr->tx, " ");
            TkPathPdfNumber(ret, 3, stylePtr->matrixPtr->ty, " cm\n");
        }
        if((mkgrad != NULL) && (gradientPtr != NULL) && (bboxPtr != NULL)) {
            if(PathPdfGradient(interp, 0, mkobj, mkgrad, bboxPtr,
                    gradientPtr, &gradName, NULL, &gm) != TCL_OK) {
                Tcl_DecrRefCount(ret);
                if(gsAlpha != NULL) {
                    Tcl_DecrRefCount(gsAlpha);
                }
                return TCL_ERROR;
            }
        }
        TkPathPdfNumber(ret, 3, stylePtr->strokeWidth, " w\n");
        if(stylePtr->strokeColor) {
            TkPathPdfColor(ret, stylePtr->strokeColor, "RG");
            s = 1;
        }
        if(stylePtr->fill && stylePtr->fill->color) {
            TkPathPdfColor(ret, stylePtr->fill->color, "rg");
            f = 1;
        }
        if(stylePtr->capStyle == CapRound) {
            Tcl_AppendToObj(ret, "1 J\n", 4);
        } else if(stylePtr->capStyle == CapProjecting) {
            Tcl_AppendToObj(ret, "2 J\n", 4);
        }
        if(stylePtr->joinStyle == JoinRound) {
            Tcl_AppendToObj(ret, "1 j\n", 4);
        } else if(stylePtr->joinStyle == JoinBevel) {
            Tcl_AppendToObj(ret, "2 j\n", 4);
        }
    }
    if(gradName != NULL) {
        Tcl_AppendToObj(ret, "q\n", 2);
        if(isLinear && (gsAlpha != NULL)) {
            Tcl_AppendPrintfToObj(ret, "/%s gs\n", Tcl_GetString(gsAlpha));
            Tcl_DecrRefCount(gsAlpha);
            gsAlpha = NULL;
        }
    }
  again:
    atomPtr = atom0Ptr;
    /* borrowed from TkPathMakePath() */
    while(atomPtr != NULL) {
        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;
            PathPdfMoveTo(ret, &context, move->x, move->y);
            myZ = 0;
            break;
        }
        case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;
            PathPdfLineTo(ret, &context, line->x, line->y);
            myZ = 1;
            break;
        }
        case TK_PATH_ATOM_A:{
    TkArcAtom *arc = (TkArcAtom *) atomPtr;
            PathPdfArcTo(ret, &context, arc->radX, arc->radY, arc->angle,
                arc->largeArcFlag, arc->sweepFlag, arc->x, arc->y);
            myZ = 1;
            break;
        }
        case TK_PATH_ATOM_Q:{
    TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;
            PathPdfQuadBezier(ret, &context,
                quad->ctrlX, quad->ctrlY, quad->anchorX, quad->anchorY);
            myZ = 1;
            break;
        }
        case TK_PATH_ATOM_C:{
    TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            PathPdfCurveTo(ret, &context,
                curve->ctrlX1, curve->ctrlY1,
                curve->ctrlX2, curve->ctrlY2, curve->anchorX, curve->anchorY);
            myZ = 1;
            break;
        }
        case TK_PATH_ATOM_Z:{
            if(myZ) {
                PathPdfClosePath(ret, &context);
                myZ = 0;
            }
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:{
    TkEllipseAtom *ell = (TkEllipseAtom *) atomPtr;
            PathPdfOval(ret, &context, ell->cx, ell->cy, ell->rx, ell->ry);
            myZ = 0;
            break;
        }
        case TK_PATH_ATOM_RECT:{
    TkRectAtom *rect = (TkRectAtom *) atomPtr;
            PathPdfRect(ret, &context, rect->x, rect->y,
                rect->width, rect->height);
            myZ = 0;
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
    if(gradName != NULL) {
        f = 0;
        /* set clipping and fill using gradient */
        Tcl_AppendToObj(ret, "W n\n", 4);
        TkPathPdfNumber(ret, 6, gm.a, " ");
        TkPathPdfNumber(ret, 6, gm.b, " ");
        TkPathPdfNumber(ret, 6, gm.c, " ");
        TkPathPdfNumber(ret, 6, gm.d, " ");
        TkPathPdfNumber(ret, 3, gm.tx, " ");
        TkPathPdfNumber(ret, 3, gm.ty, " cm\n");
        if(gsAlpha != NULL) {
            Tcl_AppendPrintfToObj(ret, "/%s gs\n", Tcl_GetString(gsAlpha));
            Tcl_DecrRefCount(gsAlpha);
            gsAlpha = NULL;
        }
        Tcl_AppendPrintfToObj(ret, "/%s sh\nQ\n", gradName);
        gradName = NULL;
        if(s) {
            goto again;
        }
    }
    if(gsAlpha != NULL) {
        Tcl_DecrRefCount(gsAlpha);
        gsAlpha = NULL;
    }
    if(f && s) {
        Tcl_AppendToObj(ret, (stylePtr->fillRule == EvenOddRule) ?
            "B*\n" : "B\n", -1);
    } else if(f && !s) {
        Tcl_AppendToObj(ret, (stylePtr->fillRule == EvenOddRule) ?
            "f*\n" : "f\n", -1);
    } else if(s) {
        Tcl_AppendToObj(ret, "S\n", 2);
    } else {
        Tcl_AppendToObj(ret, "n\n", 2);
    }
    if((stylePtr != NULL) && (stylePtr->dashPtr != NULL) &&
        (stylePtr->dashPtr->number > 1)) {
        Tcl_AppendToObj(ret, "Q\n", 2);
    }
    Tcl_SetObjResult(interp, ret);
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

static void
PathPdfMoveTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y)
{
    context->current[0] = x;
    context->current[1] = y;
    context->lastMove[0] = x;
    context->lastMove[1] = y;
    TkPathPdfNumber(list, 3, x, " ");
    TkPathPdfNumber(list, 3, y, " m\n");
}

/*---------------------------------------------------------------------------*/

static void
PathPdfLineTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y)
{
    context->current[0] = x;
    context->current[1] = y;
    TkPathPdfNumber(list, 3, x, " ");
    TkPathPdfNumber(list, 3, y, " l\n");
}

/*---------------------------------------------------------------------------*/

static void
PathPdfCurveTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x1,
    double y1,
    double x2,
    double y2,
    double x,
    double y)
{
    double coordPtr[2 * TK_PATH_NUMSEGEMENTS_CurveTo];
    double control[8];
    int i;

    control[0] = context->current[0];
    control[1] = context->current[1];
    control[2] = x1;
    control[3] = y1;
    control[4] = x2;
    control[5] = y2;
    control[6] = x;
    control[7] = y;
    TkPathCurveSegments(control, 0, TK_PATH_NUMSEGEMENTS_CurveTo, coordPtr);
    for(i = 0; i < 2 * TK_PATH_NUMSEGEMENTS_CurveTo; i = i + 2) {
        TkPathPdfNumber(list, 3, coordPtr[i], " ");
        TkPathPdfNumber(list, 3, coordPtr[i + 1], " l\n");
    }
    context->current[0] = x;
    context->current[1] = y;
}

/*---------------------------------------------------------------------------*/

static void
PathPdfArcTo(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    PathPdfArcToUsingBezier(list, context, rx, ry, phiDegrees,
        largeArcFlag, sweepFlag, x, y);
}

/*---------------------------------------------------------------------------*/

static void
PathPdfQuadBezier(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double ctrlX,
    double ctrlY,
    double x,
    double y)
{
    double cx, cy;
    double x31, y31, x32, y32;

    cx = context->current[0];
    cy = context->current[1];

    /*
     * Conversion of quadratic bezier curve to cubic bezier curve:
     * (mozilla/svg) Unchecked! Must be an approximation!
     */
    x31 = cx + (ctrlX - cx) * 2 / 3;
    y31 = cy + (ctrlY - cy) * 2 / 3;
    x32 = ctrlX + (x - ctrlX) / 3;
    y32 = ctrlY + (y - ctrlY) / 3;

    PathPdfCurveTo(list, context, x31, y31, x32, y32, x, y);
}

/*---------------------------------------------------------------------------*/

static void
PathPdfArcToUsingBezier(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x2,
    double y2)
{
    int result;
    int i, segments;
    double x1, y1;
    double cx, cy;
    double theta1, dtheta, phi;
    double sinPhi, cosPhi;
    double delta, t;

    x1 = context->current[0];
    y1 = context->current[1];

    /* All angles except phi is in radians! */
    phi = phiDegrees * DEGREES_TO_RADIANS;

    /* Check return value and take action. */
    result = TkPathEndpointToCentralArcParameters(x1, y1,
        x2, y2, rx, ry, phi, largeArcFlag, sweepFlag,
        &cx, &cy, &rx, &ry, &theta1, &dtheta);
    if(result == TK_PATH_ARC_Skip) {
        return;
    } else if(result == TK_PATH_ARC_Line) {
        PathPdfLineTo(list, context, x2, y2);
        return;
    }
    sinPhi = sin(phi);
    cosPhi = cos(phi);

    /*
     * Convert into cubic bezier segments <= 90deg
     * (from mozilla/svg; not checked)
     */
    segments = (int)ceil(fabs(dtheta / (M_PI / 2.0)));
    delta = dtheta / segments;
    t = 8.0 / 3.0 * sin(delta / 4.0) * sin(delta / 4.0) / sin(delta / 2.0);

    for(i = 0; i < segments; ++i) {
    double cosTheta1 = cos(theta1);
    double sinTheta1 = sin(theta1);
    double theta2 = theta1 + delta;
    double cosTheta2 = cos(theta2);
    double sinTheta2 = sin(theta2);

        /* a) calculate endpoint of the segment: */
    double xe = cosPhi * rx * cosTheta2 - sinPhi * ry * sinTheta2 + cx;
    double ye = sinPhi * rx * cosTheta2 + cosPhi * ry * sinTheta2 + cy;

        /* b) calculate gradients at start/end points of segment: */
    double dx1 = t * (-cosPhi * rx * sinTheta1 - sinPhi * ry * cosTheta1);
    double dy1 = t * (-sinPhi * rx * sinTheta1 + cosPhi * ry * cosTheta1);

    double dxe = t * (cosPhi * rx * sinTheta2 + sinPhi * ry * cosTheta2);
    double dye = t * (sinPhi * rx * sinTheta2 - cosPhi * ry * cosTheta2);

        /* c) draw the cubic bezier: */
        PathPdfCurveTo(list, context, x1 + dx1, y1 + dy1, xe + dxe, ye + dye,
            xe, ye);

        /* do next segment */
        theta1 = theta2;
        x1 = (float)xe;
        y1 = (float)ye;
    }
}

/*---------------------------------------------------------------------------*/

static void
PathPdfClosePath(
    Tcl_Obj * list,
    TkPointsContext_ * context)
{
double xy[2];

    xy[0] = context->current[0] = context->lastMove[0];
    xy[1] = context->current[1] = context->lastMove[1];
    TkPathPdfNumber(list, 3, xy[0], " ");
    TkPathPdfNumber(list, 3, xy[1], " l\n");
}

/*---------------------------------------------------------------------------*/

static void
PathPdfOval(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double cx,
    double cy,
    double rx,
    double ry)
{
    PathPdfMoveTo(list, context, cx + rx, cy);
    PathPdfArcToUsingBezier(list, context, rx, ry, 0.0, 1, 1, cx - rx, cy);
    PathPdfArcToUsingBezier(list, context, rx, ry, 0.0, 1, 1, cx + rx, cy);
    PathPdfClosePath(list, context);
}

/*---------------------------------------------------------------------------*/

static void
PathPdfRect(
    Tcl_Obj * list,
    TkPointsContext_ * context,
    double x,
    double y,
    double width,
    double height)
{
    context->current[0] = context->lastMove[0] = x;
    context->current[1] = context->lastMove[1] = y;
    TkPathPdfNumber(list, 3, x, " ");
    TkPathPdfNumber(list, 3, y, " ");
    TkPathPdfNumber(list, 3, width, " ");
    TkPathPdfNumber(list, 3, height, " re\n");
}

/*---------------------------------------------------------------------------*/

Tcl_Obj *
TkPathExtGS(
    Tk_PathStyle * stylePtr,
    long *smaskRef)
{
    Tcl_Obj *obj;
    char smaskBuf[128], cabuf[TCL_DOUBLE_SPACE * 2],
        CAbuf[TCL_DOUBLE_SPACE * 2];
    double ca = 1.0, CA = 1.0;

    if(smaskRef != NULL) {
        sprintf(smaskBuf, "\n/AIS false\n/SMask %ld 0 R", *smaskRef);
    } else {
        ca = stylePtr->fillOpacity;
        if(ca < 0.0) {
            ca = 0.0;
        } else if(ca > 1.0) {
            ca = 1.0;
        }
        CA = stylePtr->strokeOpacity;
        if(CA < 0.0) {
            CA = 0.0;
        } else if(CA > 1.0) {
            CA = 1.0;
        }
    }
    if((ca >= 1.0) && (CA >= 1.0) && (smaskBuf[0] == '\0')) {
        return NULL;
    }
    PrintNumber(CAbuf, 3, CA);
    PrintNumber(cabuf, 3, ca);
    obj = Tcl_NewObj();
    Tcl_AppendPrintfToObj(obj, "<<\n/Type /ExtGState\n"
        "/BM /Normal\n/CA %s\n/ca %s%s\n>>",
        CAbuf, cabuf, (smaskRef != NULL) ? smaskBuf : "");
    return obj;
}

/*---------------------------------------------------------------------------*/

static int
PathPdfGradFuncType2(
    Tcl_Interp * interp,
    Tcl_Obj * mkobj,
    int isAlpha,
    TkGradientStop * stop0,
    TkGradientStop * stop1)
{
    Tcl_Obj *cmd, *obj = Tcl_NewObj();

    if(isAlpha) {
        Tcl_AppendToObj(obj, "<<\n/Domain [0 1]\n"
            "/FunctionType 2\n/N 1\n/C0 [", -1);
        TkPathPdfNumber(obj, 3, stop0->opacity, "]\n/C1 [");
        TkPathPdfNumber(obj, 3, stop1->opacity, "]\n>>");
    } else {
        Tcl_AppendToObj(obj, "<<\n/Domain [0 1]\n"
            "/FunctionType 2\n/N 1\n/C0 [", -1);
        TkPathPdfNumber(obj, 3, (stop0->color->red >> 8) / 255.0, " ");
        TkPathPdfNumber(obj, 3, (stop0->color->green >> 8) / 255.0, " ");
        TkPathPdfNumber(obj, 3, (stop0->color->blue >> 8) / 255.0, "]\n/C1 [");
        TkPathPdfNumber(obj, 3, (stop1->color->red >> 8) / 255.0, " ");
        TkPathPdfNumber(obj, 3, (stop1->color->green >> 8) / 255.0, " ");
        TkPathPdfNumber(obj, 3, (stop1->color->blue >> 8) / 255.0, "]\n>>");
    }
    cmd = Tcl_DuplicateObj(mkobj);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

static int
PathPdfGradSoftMask(
    Tcl_Interp * interp,
    Tcl_Obj * mkobj,
    TkPathRect * bbox,
    const char *gradName,
    long gradId,
    TkPathMatrix * tmPtr)
{
    Tcl_Obj *cmd, *obj = Tcl_NewObj();
    long id;
    char fillBbox[128];
    TkPathRect r;

    /* form XObject with softmask */
    sprintf(fillBbox, "/%s sh", gradName);
    obj = Tcl_NewObj();
    r = *bbox;
    if(tmPtr != NULL) {
        r.x2 -= r.x1;
        r.x1 = 0;
        r.y2 -= r.y1;
        r.y1 = 0;
    }
    Tcl_AppendToObj(obj, "<<\n/Type /XObject\n/Subtype /Form\n" "/BBox [", -1);
    TkPathPdfNumber(obj, 3, r.x1, " ");
    TkPathPdfNumber(obj, 3, r.y1, " ");
    TkPathPdfNumber(obj, 3, r.x2, " ");
    TkPathPdfNumber(obj, 3, r.y2, "]\n");
    Tcl_AppendPrintfToObj(obj, "/Length %d\n"
        "/Group << /S /Transparency /CS /DeviceGray "
        "/I true /K false >>\n/Resources <<\n"
        "/Shading << /%s %ld 0 R >>\n"
        ">>\n>>\nstream\n", (int)strlen(fillBbox), gradName, gradId);
    Tcl_AppendPrintfToObj(obj, "%s\nendstream", fillBbox);
    cmd = Tcl_DuplicateObj(mkobj);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    /* softmask for ExtGS */
    obj = Tcl_NewObj();
    Tcl_AppendPrintfToObj(obj, "<<\n/Type /Mask\n"
        "/S /Luminosity\n/G %ld 0 R\n>>", id);
    cmd = Tcl_DuplicateObj(mkobj);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

static int
PathPdfGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bboxPtr,
    TkPathGradientMaster * gradientPtr,
    char **gradName,
    long *gradId,
    TkPathMatrix * tmPtr)
{
    int retc, code;
    Tcl_Obj **retv;

    if(tmPtr != NULL) {
        tmPtr->a = tmPtr->d = 1.0;
        tmPtr->b = tmPtr->c = 0.0;
        tmPtr->tx = tmPtr->ty = 0.0;
    }
    *gradName = NULL;
    /* prepare shading/pattern/function for gradient */
    if(!TkPathObjectIsEmpty(gradientPtr->stopsObj)) {
        if(gradientPtr->type == TK_PATH_GRADIENTTYPE_LINEAR) {
            code = PathPdfLinearGradient(interp, isAlpha, mkobj, mkgrad,
                bboxPtr, &gradientPtr->linearFill, gradientPtr->matrixPtr);
        } else {
            code = PathPdfRadialGradient(interp, isAlpha, mkobj, mkgrad,
                bboxPtr, &gradientPtr->radialFill,
                gradientPtr->matrixPtr, tmPtr);
        }
        if(code != TCL_OK) {
            return (code == TCL_BREAK) ? TCL_OK : TCL_ERROR;
        }

        /*
         * Get name of shading/pattern/function for gradient
         */
        if(Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
                &retc, &retv) != TCL_OK) {
            return TCL_ERROR;
        }
        if(retc < 2) {
            Tcl_SetResult(interp, (char *)"missing PDF id/name", TCL_STATIC);
            return TCL_ERROR;
        }
        if(gradId != NULL) {
            *gradId = 0;
            Tcl_GetLongFromObj(NULL, retv[0], gradId);
        }
        *gradName = Tcl_GetString(retv[1]);
    }
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

static int
PathPdfLinearGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bbox,
    TkLinearGradientFill * fillPtr,
    TkPathMatrix * mPtr)
{
    TkPathRect *tPtr = fillPtr->transitionPtr;
    double x1, y1, x2, y2;
    TkGradientStop *stop0, *stop1;
    long id;
    Tcl_Obj *obj, *cmd;

    if(isAlpha) {
    int i;

        for(i = 0; i < fillPtr->stopArrPtr->nstops; i++) {
            if(fillPtr->stopArrPtr->stops[i]->opacity < 1.0) {
                break;
            }
        }
        if(i >= fillPtr->stopArrPtr->nstops) {
            /* nothing to do */
            return TCL_BREAK;
        }
    }

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
    double x = bbox->x1;
    double y = bbox->y1;
    double width = bbox->x2 - bbox->x1;
    double height = bbox->y2 - bbox->y1;

        x1 = x + tPtr->x1 * width;
        y1 = y + tPtr->y1 * height;
        x2 = x + tPtr->x2 * width;
        y2 = y + tPtr->y2 * height;
    } else {
        x1 = tPtr->x1;
        y1 = tPtr->y1;
        x2 = tPtr->x2;
        y2 = tPtr->y2;
    }
    if(fillPtr->stopArrPtr->nstops < 2) {
        Tcl_SetResult(interp, (char *)"need two or more stops "
            "for linear gradient", TCL_STATIC);
        return TCL_ERROR;
    }
    if(fillPtr->stopArrPtr->nstops == 2) {
        stop0 = fillPtr->stopArrPtr->stops[0];
        stop1 = fillPtr->stopArrPtr->stops[1];
        if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop0, stop1)
            != TCL_OK) {
            return TCL_ERROR;
        }
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    } else {
    int i;
    Tcl_DString stitchF, enc, bounds;
    char buffer[64];

        Tcl_DStringInit(&stitchF);
        Tcl_DStringInit(&enc);
        Tcl_DStringInit(&bounds);
        for(i = 1; i < fillPtr->stopArrPtr->nstops; i++) {
            stop0 = fillPtr->stopArrPtr->stops[i - 1];
            stop1 = fillPtr->stopArrPtr->stops[i];
            if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop0, stop1)
                != TCL_OK) {
                Tcl_DStringFree(&stitchF);
                Tcl_DStringFree(&enc);
                Tcl_DStringFree(&bounds);
                return TCL_ERROR;
            }
            Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
            sprintf(buffer, "%s%ld 0 R", (i > 1) ? " " : "", id);
            Tcl_DStringAppend(&stitchF, buffer, -1);
            sprintf(buffer, "%s0 1", (i > 1) ? " " : "");
            Tcl_DStringAppend(&enc, buffer, -1);
            if(i > 1) {
                Tcl_DStringAppend(&bounds, " ", 1);
            }
            PrintNumber(buffer, 3, stop1->offset);
            Tcl_DStringAppend(&bounds, buffer, -1);
        }
        stop1 = fillPtr->stopArrPtr->stops[fillPtr->stopArrPtr->nstops - 1];
        if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop1, stop1)
            != TCL_OK) {
            Tcl_DStringFree(&stitchF);
            Tcl_DStringFree(&enc);
            Tcl_DStringFree(&bounds);
            return TCL_ERROR;
        }
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
        sprintf(buffer, "%s%ld 0 R", (i > 1) ? " " : "", id);
        Tcl_DStringAppend(&stitchF, buffer, -1);
        sprintf(buffer, "%s0 1", (i > 1) ? " " : "");
        Tcl_DStringAppend(&enc, buffer, -1);
        obj = Tcl_NewObj();
        Tcl_AppendPrintfToObj(obj, "<<\n/Domain [0 1]\n"
            "/FunctionType 3\n/Bounds [%s]\n"
            "/Functions [%s]\n/Encode [%s]\n>>",
            Tcl_DStringValue(&bounds),
            Tcl_DStringValue(&stitchF), Tcl_DStringValue(&enc));
        Tcl_DStringFree(&stitchF);
        Tcl_DStringFree(&enc);
        Tcl_DStringFree(&bounds);
        cmd = Tcl_DuplicateObj(mkobj);
        Tcl_IncrRefCount(cmd);
        if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
            Tcl_DecrRefCount(cmd);
            Tcl_DecrRefCount(obj);
            return TCL_ERROR;
        }
        if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
            Tcl_DecrRefCount(cmd);
            return TCL_ERROR;
        }
        Tcl_DecrRefCount(cmd);
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    }
    obj = Tcl_NewObj();
    Tcl_AppendToObj(obj, "<<\n/ShadingType 2\n/Extend [true true]\n"
        "/Coords [", -1);
    TkPathPdfNumber(obj, 3, x1, " ");
    TkPathPdfNumber(obj, 3, y1, " ");
    TkPathPdfNumber(obj, 3, x2, " ");
    TkPathPdfNumber(obj, 3, y2, "]\n");
    Tcl_AppendPrintfToObj(obj, "/ColorSpace %s\n/Function %ld 0 R\n>>",
        isAlpha ? "/DeviceGray" : "/DeviceRGB", id);
    cmd = Tcl_DuplicateObj(mkobj);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    cmd = Tcl_DuplicateObj(mkgrad);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, Tcl_NewLongObj(id))
        != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    return TCL_OK;
}

/*---------------------------------------------------------------------------*/

static int
PathPdfRadialGradient(
    Tcl_Interp * interp,
    int isAlpha,
    Tcl_Obj * mkobj,
    Tcl_Obj * mkgrad,
    TkPathRect * bbox,
    TkRadialGradientFill * fillPtr,
    TkPathMatrix * mPtr,
    TkPathMatrix * tmPtr)
{
    TkRadialTransition *tPtr = fillPtr->radialPtr;
    double centerX, centerY;
    double radiusX /*, radiusY */ ;
    double focalX, focalY;
    double width, height;
    TkGradientStop *stop0, *stop1;
    long id;
    Tcl_Obj *obj, *cmd;

    if(isAlpha) {
    int i;

        for(i = 0; i < fillPtr->stopArrPtr->nstops; i++) {
            if(fillPtr->stopArrPtr->stops[i]->opacity < 1.0) {
                break;
            }
        }
        if(i >= fillPtr->stopArrPtr->nstops) {
            /* nothing to do */
            return TCL_BREAK;
        }
    }
    width = bbox->x2 - bbox->x1;
    height = bbox->y2 - bbox->y1;

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
        centerX = width * tPtr->centerX;
        centerY = height * tPtr->centerY;
        radiusX = width * tPtr->radius;
        /*radiusY = height * tPtr->radius; */
        focalX = width * tPtr->focalX;
        focalY = height * tPtr->focalY;
        if(tmPtr == NULL) {
            centerX += bbox->x1;
            centerY += bbox->y1;
            focalX += bbox->x1;
            focalY += bbox->y1;
        }
    } else {
        centerX = tPtr->centerX;
        centerY = tPtr->centerY;
        radiusX = tPtr->radius;
        /*radiusY = tPtr->radius; */
        focalX = tPtr->focalX;
        focalY = tPtr->focalY;
    }
    if(tmPtr != NULL) {
        tmPtr->tx = bbox->x1;
        tmPtr->ty = bbox->y1;
        tmPtr->b = tmPtr->c = 0.0;
        if(width > height) {
            tmPtr->a = 1.0;
            tmPtr->d = height / width;
            centerY /= tmPtr->d;
            focalY /= tmPtr->d;
        } else {
            tmPtr->a = width / height;
            tmPtr->d = 1.0;
            centerX /= tmPtr->a;
            focalX /= tmPtr->a;
        }
    }
    if(fillPtr->stopArrPtr->nstops < 2) {
        Tcl_SetResult(interp, (char *)"need two or more stops "
            "for radial gradient", TCL_STATIC);
        return TCL_ERROR;
    }
    if(fillPtr->stopArrPtr->nstops == 2) {
        stop0 = fillPtr->stopArrPtr->stops[0];
        stop1 = fillPtr->stopArrPtr->stops[fillPtr->stopArrPtr->nstops - 1];
        if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop0, stop1)
            != TCL_OK) {
            return TCL_ERROR;
        }
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    } else {
    int i;
    Tcl_DString stitchF, enc, bounds;
    char buffer[64];

        Tcl_DStringInit(&stitchF);
        Tcl_DStringInit(&enc);
        Tcl_DStringInit(&bounds);
        for(i = 1; i < fillPtr->stopArrPtr->nstops; i++) {
            stop0 = fillPtr->stopArrPtr->stops[i - 1];
            stop1 = fillPtr->stopArrPtr->stops[i];
            if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop0, stop1)
                != TCL_OK) {
                Tcl_DStringFree(&stitchF);
                Tcl_DStringFree(&enc);
                Tcl_DStringFree(&bounds);
                return TCL_ERROR;
            }
            Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
            sprintf(buffer, "%s%ld 0 R", (i > 1) ? " " : "", id);
            Tcl_DStringAppend(&stitchF, buffer, -1);
            sprintf(buffer, "%s0 1", (i > 1) ? " " : "");
            Tcl_DStringAppend(&enc, buffer, -1);
            if(i > 1) {
                Tcl_DStringAppend(&bounds, " ", 1);
            }
            PrintNumber(buffer, 3, stop1->offset);
            Tcl_DStringAppend(&bounds, buffer, -1);
        }
        stop1 = fillPtr->stopArrPtr->stops[fillPtr->stopArrPtr->nstops - 1];
        if(PathPdfGradFuncType2(interp, mkobj, isAlpha, stop1, stop1)
            != TCL_OK) {
            Tcl_DStringFree(&stitchF);
            Tcl_DStringFree(&enc);
            Tcl_DStringFree(&bounds);
            return TCL_ERROR;
        }
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
        sprintf(buffer, "%s%ld 0 R", (i > 1) ? " " : "", id);
        Tcl_DStringAppend(&stitchF, buffer, -1);
        sprintf(buffer, "%s0 1", (i > 1) ? " " : "");
        Tcl_DStringAppend(&enc, buffer, -1);
        obj = Tcl_NewObj();
        Tcl_AppendPrintfToObj(obj, "<<\n/Domain [0 1]\n"
            "/FunctionType 3\n/Bounds [%s]\n"
            "/Functions [%s]\n/Encode [%s]\n>>",
            Tcl_DStringValue(&bounds),
            Tcl_DStringValue(&stitchF), Tcl_DStringValue(&enc));
        Tcl_DStringFree(&stitchF);
        Tcl_DStringFree(&enc);
        Tcl_DStringFree(&bounds);
        cmd = Tcl_DuplicateObj(mkobj);
        Tcl_IncrRefCount(cmd);
        if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
            Tcl_DecrRefCount(cmd);
            Tcl_DecrRefCount(obj);
            return TCL_ERROR;
        }
        if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
            Tcl_DecrRefCount(cmd);
            return TCL_ERROR;
        }
        Tcl_DecrRefCount(cmd);
        Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    }
    obj = Tcl_NewObj();
    Tcl_AppendToObj(obj, "<<\n/ShadingType 3\n/Extend [true true]\n"
        "/Coords [", -1);
    TkPathPdfNumber(obj, 3, focalX, " ");
    TkPathPdfNumber(obj, 3, focalY, " 0 ");
    TkPathPdfNumber(obj, 3, centerX, " ");
    TkPathPdfNumber(obj, 3, centerY, " ");
    TkPathPdfNumber(obj, 3, radiusX, "]\n");
    Tcl_AppendPrintfToObj(obj, "/ColorSpace %s\n/Function %ld 0 R\n>>",
        isAlpha ? "/DeviceGray" : "/DeviceRGB", id);
    cmd = Tcl_DuplicateObj(mkobj);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, obj) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    Tcl_GetLongFromObj(NULL, Tcl_GetObjResult(interp), &id);
    cmd = Tcl_DuplicateObj(mkgrad);
    Tcl_IncrRefCount(cmd);
    if(Tcl_ListObjAppendElement(interp, cmd, Tcl_NewLongObj(id))
        != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        Tcl_DecrRefCount(obj);
        return TCL_ERROR;
    }
    if(Tcl_EvalObjEx(interp, cmd, TCL_EVAL_DIRECT) != TCL_OK) {
        Tcl_DecrRefCount(cmd);
        return TCL_ERROR;
    }
    Tcl_DecrRefCount(cmd);
    return TCL_OK;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathGradient.c.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathGradient.c --
 *
 *    This file implements gradient objects used when drawing paths.
 *      See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 * TODO: o Add tkwin option here and there so we can free stop colors!
 *
 */

#include "tkoPath.h"

/*
 * Per Tcl_Interp data.
 */

typedef struct {
    Tcl_HashTable gradientHash;
    Tk_OptionTable linearOptionTable;
    Tk_OptionTable radialOptionTable;
    int gradientNameUid;
} InterpData;

static const char *gradientCmds[] = {
    "cget", "configure", "create", "delete", "inuse", "names", "type",
    (char *)NULL
};

enum {
    kPathGradientCmdCget = 0L,
    kPathGradientCmdConfigure,
    kPathGradientCmdCreate,
    kPathGradientCmdDelete,
    kPathGradientCmdInUse,
    kPathGradientCmdNames,
    kPathGradientCmdType
};

static int GradientObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static void GradientInterpDeleted(
    ClientData clientData);
static int PathGradientCget(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr);
static int PathGradientConfigure(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr);
static int PathGradientCreate(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr,
    char *tokenName);
static int PathGradientDelete(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * hashTablePtr);
static int PathGradientInUse(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr);
static void PathGradientNames(
    Tcl_Interp * interp,
    Tcl_HashTable * hashTablePtr);
static int PathGradientType(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * hashTablePtr);
static void PathGradientMasterFree(
    TkPathGradientMaster * gradientPtr);

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasGradientObjCmd --
 *
 *    Implements the 'pathName gradient' command using the canvas local state.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

int
TkPathCanvasGradientObjCmd(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    int objc,
    Tcl_Obj * const objv[])
{
    int index;
    int result = TCL_OK;
    if(path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;

    /*
     * objv[2] is the subcommand: cget | configure | create | delete | names | type
     */
    if(objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[2], gradientCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {

    case kPathGradientCmdCget:{
        if(objc != 5) {
            Tcl_WrongNumArgs(interp, 3, objv, "name option");
            return TCL_ERROR;
        }
        result = PathGradientCget(interp, *(path->win), objc - 3, objv + 3,
            &path->gradientTable);
        break;
    }

    case kPathGradientCmdConfigure:{
        if(objc < 4) {
            Tcl_WrongNumArgs(interp, 3, objv,
                "name ?option? ?value option value...?");
            return TCL_ERROR;
        }
        result = PathGradientConfigure(interp, *(path->win), objc - 3, objv + 3,
            &path->gradientTable);
        break;
    }

    case kPathGradientCmdCreate:{
    char str[255];

        if(objc < 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "type ?option value...?");
            return TCL_ERROR;
        }
        sprintf(str, "%s%d", TK_PATHCMD_GRADIENT, path->gradientUid++);
        result = PathGradientCreate(interp, *(path->win), objc - 3, objv + 3,
            &path->gradientTable, str);
        break;
    }

    case kPathGradientCmdDelete:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientDelete(interp, objv[3], &path->gradientTable);
        break;
    }

    case kPathGradientCmdInUse:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientInUse(interp, objv[3], &path->gradientTable);
        break;
    }

    case kPathGradientCmdNames:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 3, objv, NULL);
            return TCL_ERROR;
        }
        PathGradientNames(interp, &path->gradientTable);
        break;
    }

    case kPathGradientCmdType:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientType(interp, objv[3], &path->gradientTable);
        break;
    }
    }
    return result;
}

/*
 * TkPathCanvasGradientsFree --
 *
 *    Used by canvas Destroy handler to clean up all gradients.
 *    Note that items clean up all their gradient instances themeselves.
 */
void
TkPathCanvasGradientsFree(
    TkPathCanvas * path)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch search;
TkPathGradientMaster *gradientPtr = NULL;

    hPtr = Tcl_FirstHashEntry(&path->gradientTable, &search);
    while(hPtr != NULL) {
        gradientPtr = (TkPathGradientMaster *) Tcl_GetHashValue(hPtr);
        Tcl_DeleteHashEntry(hPtr);
        PathGradientMasterFree(gradientPtr);
        hPtr = Tcl_NextHashEntry(&search);
    }
}

/*
 * Custom option processing code.
 */

static char *
ComputeSlotAddress(
    char *recordPtr,           /* Pointer to the start of a record. */
    int offset)
{              /* Offset of a slot within that record; may be < 0. */
    if(offset >= 0) {
        return recordPtr + offset;
    } else {
        return NULL;
    }
}

/*
 * Procedures for processing the transition option of the linear gradient fill.
 */

static int LinTransitionSet(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;
    int objEmpty = 0;
    Tcl_Obj *valuePtr;
    double z[4] = { 0.0, 0.0, 1.0, 0.0 };       /* Defaults according to SVG. */
    TkPathRect *newrc = NULL;

    valuePtr = *value;
    internalPtr = ComputeSlotAddress(recordPtr, internalOffset);
    objEmpty = TkPathObjectIsEmpty(valuePtr);

    /*
     * Important: the new value for the transition is not yet
     * stored into the style! transObj may be NULL!
     * The new value is stored in style *after* we return TCL_OK.
     */
    if((flags & TK_OPTION_NULL_OK) && objEmpty) {
        valuePtr = NULL;
    } else {
    int i, len;
    Tcl_Obj **objv;

        if(Tcl_ListObjGetElements(interp, valuePtr, &len, &objv) != TCL_OK) {
            return TCL_ERROR;
        }
        if(len != 4) {
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj("-lineartransition must have four elements",
                    -1));
            return TCL_ERROR;
        }
        for(i = 0; i < 4; i++) {
            if(Tcl_GetDoubleFromObj(interp, objv[i], z + i) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        newrc = (TkPathRect *) ckalloc(sizeof(TkPathRect));
        newrc->x1 = z[0];
        newrc->y1 = z[1];
        newrc->x2 = z[2];
        newrc->y2 = z[3];
    }
    if(internalPtr != NULL) {
        *((TkPathRect **) oldInternalPtr) = *((TkPathRect **) internalPtr);
        *((TkPathRect **) internalPtr) = newrc;
    }
    return TCL_OK;
}

static void
LinTransitionRestore(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkPathRect **) internalPtr = *(TkPathRect **) oldInternalPtr;
}

static void
LinTransitionFree(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        ckfree(*((char **)internalPtr));
        *((char **)internalPtr) = NULL;
    }
}

static Tk_ObjCustomOption linTransitionCO = {
    "lineartransition",
    LinTransitionSet,
    NULL,
    LinTransitionRestore,
    LinTransitionFree,
    (ClientData) NULL
};

static int RadTransitionSet(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;
    int objEmpty = 0;
    Tcl_Obj *valuePtr;
    double z[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 };
    TkRadialTransition *newrc = NULL;

    valuePtr = *value;
    internalPtr = ComputeSlotAddress(recordPtr, internalOffset);
    objEmpty = TkPathObjectIsEmpty(valuePtr);

    if((flags & TK_OPTION_NULL_OK) && objEmpty) {
        valuePtr = NULL;
    } else {
    int i, len;
    Tcl_Obj **objv;

        if(Tcl_ListObjGetElements(interp, valuePtr, &len, &objv) != TCL_OK) {
            return TCL_ERROR;
        }
        if((len == 1) || (len == 4) || (len > 5)) {
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj
                ("-radialtransition must be a list {cx cy ?r? ?fx fy?}", -1));
            return TCL_ERROR;
        }
        for(i = 0; i < len; i++) {
            if(Tcl_GetDoubleFromObj(interp, objv[i], z + i) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        newrc = (TkRadialTransition *) ckalloc(sizeof(TkRadialTransition));
        newrc->centerX = z[0];
        newrc->centerY = z[1];
        newrc->radius = z[2];
        newrc->focalX = z[3];
        newrc->focalY = z[4];
    }
    if(internalPtr != NULL) {
        *((TkRadialTransition **) oldInternalPtr) =
            *((TkRadialTransition **) internalPtr);
        *((TkRadialTransition **) internalPtr) = newrc;
    }
    return TCL_OK;
}

static void
RadTransitionRestore(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkRadialTransition **) internalPtr =
        *(TkRadialTransition **) oldInternalPtr;
}

static void
RadTransitionFree(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        ckfree(*((char **)internalPtr));
        *((char **)internalPtr) = NULL;
    }
}

static Tk_ObjCustomOption radTransitionCO = {
    "radialtransition",
    RadTransitionSet,
    NULL,
    RadTransitionRestore,
    RadTransitionFree,
    (ClientData) NULL
};

static TkGradientStop *
NewGradientStop(
    double offset,
    XColor * color,
    double opacity)
{
    TkGradientStop *stopPtr;

    stopPtr = (TkGradientStop *) ckalloc(sizeof(TkGradientStop));
    memset(stopPtr, '\0', sizeof(TkGradientStop));
    stopPtr->offset = offset;
    stopPtr->color = color;
    stopPtr->opacity = opacity;
    return stopPtr;
}

static TkGradientStopArray *
NewGradientStopArray(
    int nstops)
{
    TkGradientStopArray *stopArrPtr;
    TkGradientStop **stops;

    stopArrPtr = (TkGradientStopArray *) ckalloc(sizeof(TkGradientStopArray));
    memset(stopArrPtr, '\0', sizeof(TkGradientStopArray));

    /* Array of *pointers* to TkGradientStop. */
    stops = (TkGradientStop **) ckalloc(nstops * sizeof(TkGradientStop *));
    memset(stops, '\0', nstops * sizeof(TkGradientStop *));
    stopArrPtr->nstops = nstops;
    stopArrPtr->stops = stops;
    return stopArrPtr;
}

static void
FreeAllStops(
    TkGradientStop ** stops,
    int nstops)
{
    int i;
    for(i = 0; i < nstops; i++) {
        if(stops[i] != NULL) {
            /* @@@ Free color? */
            ckfree((char *)(stops[i]));
        }
    }
    ckfree((char *)stops);
}

static void
FreeStopArray(
    TkGradientStopArray * stopArrPtr)
{
    if(stopArrPtr != NULL) {
        FreeAllStops(stopArrPtr->stops, stopArrPtr->nstops);
        ckfree((char *)stopArrPtr);
    }
}

/*
 * The stops are a list of stop lists where each stop list is:
 *        {offset color ?opacity?}
 */
static int
    StopsSet(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;
    int i, nstops, stopLen;
    int objEmpty = 0;
    Tcl_Obj *valuePtr;
    double offset, lastOffset, opacity;
    Tcl_Obj **objv;
    Tcl_Obj *stopObj;
    Tcl_Obj *obj;
    XColor *color;
    TkGradientStopArray *newrc = NULL;

    valuePtr = *value;
    internalPtr = ComputeSlotAddress(recordPtr, internalOffset);
    objEmpty = TkPathObjectIsEmpty(valuePtr);

    if((flags & TK_OPTION_NULL_OK) && objEmpty) {
        valuePtr = NULL;
    } else {

        /* Deal with each stop list in turn. */
        if(Tcl_ListObjGetElements(interp, valuePtr, &nstops, &objv) != TCL_OK) {
            return TCL_ERROR;
        }
        newrc = NewGradientStopArray(nstops);
        lastOffset = 0.0;

        for(i = 0; i < nstops; i++) {
            stopObj = objv[i];
            if(Tcl_ListObjLength(interp, stopObj, &stopLen) != TCL_OK) {
                goto error;
            }
            if((stopLen == 2) || (stopLen == 3)) {
                Tcl_ListObjIndex(interp, stopObj, 0, &obj);
                if(Tcl_GetDoubleFromObj(interp, obj, &offset) != TCL_OK) {
                    goto error;
                }
                if((offset < 0.0) || (offset > 1.0)) {
                    Tcl_SetObjResult(interp,
                        Tcl_NewStringObj
                        ("stop offsets must be in the range 0.0 to 1.0", -1));
                    goto error;
                }
                if(offset < lastOffset) {
                    Tcl_SetObjResult(interp,
                        Tcl_NewStringObj("stop offsets must be ordered", -1));
                    goto error;
                }
                Tcl_ListObjIndex(interp, stopObj, 1, &obj);
                color =
                    Tk_AllocColorFromObj(interp, Tk_MainWindow(interp), obj);
                if(color == NULL) {
                    Tcl_AppendResult(interp, "color \"",
                        Tcl_GetStringFromObj(obj, NULL),
                        "\" doesn't exist", NULL);
                    goto error;
                }
                if(stopLen == 3) {
                    Tcl_ListObjIndex(interp, stopObj, 2, &obj);
                    if(Tcl_GetDoubleFromObj(interp, obj, &opacity) != TCL_OK) {
                        goto error;
                    }
                } else {
                    opacity = 1.0;
                }

                /* Make new stop. */
                newrc->stops[i] = NewGradientStop(offset, color, opacity);
                lastOffset = offset;
            } else {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("stop list not {offset color ?opacity?}",
                        -1));
                goto error;
            }
        }
    }
    if(internalPtr != NULL) {
        *((TkGradientStopArray **) oldInternalPtr) =
            *((TkGradientStopArray **) internalPtr);
        *((TkGradientStopArray **) internalPtr) = newrc;
    }
    return TCL_OK;

  error:
    if(newrc != NULL) {
        FreeStopArray(newrc);
    }
    return TCL_ERROR;
}

static void
StopsRestore(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkGradientStopArray **) internalPtr =
        *(TkGradientStopArray **) oldInternalPtr;
}

static void
StopsFree(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{
    if(*((char **)internalPtr) != NULL) {
        FreeStopArray(*(TkGradientStopArray **) internalPtr);
    }
}

static Tk_ObjCustomOption stopsCO = {
    "stops",
    StopsSet,
    NULL,
    StopsRestore,
    StopsFree,
    (ClientData) NULL
};

/*
 * The following table defines the legal values for the -method option.
 * The enum TK_PATH_GRADIENTMETHOD_Pad... MUST be kept in sync!
 */

static const char *methodST[] = {
    "pad", "repeat", "reflect", NULL
};

static const char *unitsST[] = {
    "bbox", "userspace", NULL
};

TK_PATH_STYLE_CUSTOM_OPTION_MATRIX
    static Tk_OptionSpec linGradientStyleOptionSpecs[] = {
    {TK_OPTION_STRING_TABLE, "-method", NULL, NULL,
            "pad", -1, Tk_Offset(TkPathGradientMaster, linearFill.method),
        0, (ClientData) methodST, 0},
    {TK_OPTION_STRING_TABLE, "-units", NULL, NULL,
            "bbox", -1, Tk_Offset(TkPathGradientMaster, linearFill.units),
        0, (ClientData) unitsST, 0},
    {TK_OPTION_CUSTOM, "-stops", NULL, NULL,
            NULL, Tk_Offset(TkPathGradientMaster, stopsObj),
            Tk_Offset(TkPathGradientMaster, linearFill.stopArrPtr),
        TK_OPTION_NULL_OK, (ClientData) & stopsCO, 0},
    {TK_OPTION_CUSTOM, "-lineartransition", NULL, NULL,
            NULL, Tk_Offset(TkPathGradientMaster, transObj),
            Tk_Offset(TkPathGradientMaster, linearFill.transitionPtr),
        TK_OPTION_NULL_OK, (ClientData) & linTransitionCO, 0},
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,
            NULL, -1, Tk_Offset(TkPathGradientMaster, matrixPtr),
        TK_OPTION_NULL_OK, (ClientData) & matrixCO, 0},
    {TK_OPTION_END, NULL, NULL, NULL,
        NULL, 0, -1, 0, (ClientData) NULL, 0}
};

static Tk_OptionSpec radGradientStyleOptionSpecs[] = {
    {TK_OPTION_STRING_TABLE, "-method", NULL, NULL,
            "pad", -1, Tk_Offset(TkPathGradientMaster, radialFill.method),
        0, (ClientData) methodST, 0},
    {TK_OPTION_STRING_TABLE, "-units", NULL, NULL,
            "bbox", -1, Tk_Offset(TkPathGradientMaster, radialFill.units),
        0, (ClientData) unitsST, 0},
    {TK_OPTION_CUSTOM, "-stops", NULL, NULL,
            NULL, Tk_Offset(TkPathGradientMaster, stopsObj),
            Tk_Offset(TkPathGradientMaster, radialFill.stopArrPtr),
        TK_OPTION_NULL_OK, (ClientData) & stopsCO, 0},
    {TK_OPTION_CUSTOM, "-radialtransition", NULL, NULL,
            NULL, Tk_Offset(TkPathGradientMaster, transObj),
            Tk_Offset(TkPathGradientMaster, radialFill.radialPtr),
        TK_OPTION_NULL_OK, (ClientData) & radTransitionCO, 0},
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,
            NULL, -1, Tk_Offset(TkPathGradientMaster, matrixPtr),
        TK_OPTION_NULL_OK, (ClientData) & matrixCO, 0},
    {TK_OPTION_END, NULL, NULL, NULL,
        NULL, 0, -1, 0, (ClientData) NULL, 0}
};

void
TkPathGradientPaint(
    TkPathContext ctx,
    TkPathRect * bbox,
    TkPathGradientMaster * gradientPtr,
    int fillRule,
    double fillOpacity)
{
    if(!TkPathObjectIsEmpty(gradientPtr->stopsObj)) {
        if(gradientPtr->type == TK_PATH_GRADIENTTYPE_LINEAR) {
            TkPathPaintLinearGradient(ctx, bbox, &gradientPtr->linearFill,
                fillRule, fillOpacity, gradientPtr->matrixPtr);
        } else {
            TkPathPaintRadialGradient(ctx, bbox, &gradientPtr->radialFill,
                fillRule, fillOpacity, gradientPtr->matrixPtr);
        }
    }
}

void
TkPathGradientInit(
    Tcl_Interp * interp)
{
InterpData *dataPtr =
    (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHGRADIENT, NULL);

    if(dataPtr == NULL) {
        dataPtr = (InterpData *) ckalloc(sizeof(InterpData));
        Tcl_InitHashTable(&dataPtr->gradientHash, TCL_STRING_KEYS);
        dataPtr->linearOptionTable =
            Tk_CreateOptionTable(interp, linGradientStyleOptionSpecs);
        dataPtr->radialOptionTable =
            Tk_CreateOptionTable(interp, radGradientStyleOptionSpecs);
        dataPtr->gradientNameUid = 0;
        Tcl_SetAssocData(interp, TK_PATHCMD_PATHGRADIENT,
            (Tcl_InterpDeleteProc *) GradientInterpDeleted,
            (ClientData) dataPtr);
    }
    Tcl_CreateObjCommand(interp, TK_PATHCMD_PATHGRADIENT,
        GradientObjCmd, (ClientData) dataPtr, (Tcl_CmdDeleteProc *) NULL);
}

static int
FindGradientMaster(
    Tcl_Interp * interp,
    Tcl_Obj * nameObj,
    Tcl_HashTable * tablePtr,
    TkPathGradientMaster ** g)
{
Tcl_HashEntry *hPtr;
char *name = Tcl_GetString(nameObj);
    *g = NULL;
    hPtr = Tcl_FindHashEntry(tablePtr, name);
    if(hPtr == NULL) {
Tcl_Obj *resultObj;
        resultObj = Tcl_NewStringObj("gradient \"", -1);
        Tcl_AppendStringsToObj(resultObj, name, "\" doesn't exist",
            (char *)NULL);
        Tcl_SetObjResult(interp, resultObj);
        return TCL_ERROR;
    }
    *g = (TkPathGradientMaster *) Tcl_GetHashValue(hPtr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * PathGradientCget, Configure, Create, Delete, InUse, Names, Type --
 *
 *    These functions implement gradient object commands in a generic way.
 *    The Tcl_HashTable defines the gradient namespace.
 *
 * Results:
 *    Varies: typically a standard tcl result or void.
 *
 * Side effects:
 *    Varies.
 *
 *--------------------------------------------------------------
 */

static int
PathGradientCget(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * tablePtr)
{
    TkPathGradientMaster *gradientPtr = NULL;
    Tcl_Obj *resultObj = NULL;

    if(FindGradientMaster(interp, objv[0], tablePtr, &gradientPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    resultObj = Tk_GetOptionValue(interp, (char *)gradientPtr,
        gradientPtr->optionTable, objv[1], tkwin);
    if(resultObj == NULL) {
        return TCL_ERROR;
    } else {
        Tcl_SetObjResult(interp, resultObj);
    }
    return TCL_OK;
}

static int
PathGradientConfigure(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * tablePtr)
{
    TkPathGradientMaster *gradientPtr = NULL;
    int mask;
    Tcl_Obj *resultObj = NULL;

    if(FindGradientMaster(interp, objv[0], tablePtr, &gradientPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(objc <= 2) {
        resultObj = Tk_GetOptionInfo(interp, (char *)gradientPtr,
            gradientPtr->optionTable,
            (objc == 1) ? (Tcl_Obj *) NULL : objv[1], tkwin);
        if(resultObj == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, resultObj);
    } else {
        if(Tk_SetOptions(interp, (char *)gradientPtr, gradientPtr->optionTable,
                objc - 1, objv + 1, tkwin, NULL, &mask) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    TkPathGradientChanged(gradientPtr, TK_PATH_GRADIENT_FLAG_CONFIGURE);
    return TCL_OK;
}

/* GradientCreate: objv starts with 'type' */

static int
PathGradientCreate(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr,
    char *tokenName)
{
    char *typeStr;
    int isNew;
    int type;
    int mask;
    Tcl_HashEntry *hPtr;
    TkPathGradientMaster *gradientPtr = NULL;
    InterpData *dataPtr =
        (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHGRADIENT, NULL);

    if(dataPtr == NULL) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("gradients not registered in interpreter", -1));
        return TCL_ERROR;
    }
    typeStr = Tcl_GetString(objv[0]);
    if(strcmp(typeStr, "linear") == 0) {
        type = TK_PATH_GRADIENTTYPE_LINEAR;
    } else if(strcmp(typeStr, "radial") == 0) {
        type = TK_PATH_GRADIENTTYPE_RADIAL;
    } else {
    Tcl_Obj *resultObj;
        resultObj = Tcl_NewStringObj("unrecognized type \"", -1);
        Tcl_AppendStringsToObj(resultObj, typeStr,
            "\", must be \"linear\" or \"radial\"", (char *)NULL);
        Tcl_SetObjResult(interp, resultObj);
        return TCL_ERROR;
    }
    gradientPtr =
        (TkPathGradientMaster *) ckalloc(sizeof(TkPathGradientMaster));
    memset(gradientPtr, '\0', sizeof(TkPathGradientMaster));

    /*
     * Create the option table for this class.  If it has already
     * been created, the cached pointer will be returned.
     */
    if(type == TK_PATH_GRADIENTTYPE_LINEAR) {
        gradientPtr->optionTable = dataPtr->linearOptionTable;
    } else {
        gradientPtr->optionTable = dataPtr->radialOptionTable;
    }
    gradientPtr->type = type;
    gradientPtr->name = Tk_GetUid(tokenName);
    gradientPtr->matrixPtr = NULL;
    gradientPtr->instancePtr = NULL;

    /*
     * Set default transition vector in case not set.
     */
    if(type == TK_PATH_GRADIENTTYPE_LINEAR) {
    TkPathRect *transitionPtr;

        transitionPtr = (TkPathRect *) ckalloc(sizeof(TkPathRect));
        gradientPtr->linearFill.transitionPtr = transitionPtr;
        transitionPtr->x1 = 0.0;
        transitionPtr->y1 = 0.0;
        transitionPtr->x2 = 1.0;
        transitionPtr->y2 = 0.0;
    } else {
    TkRadialTransition *tPtr;

        tPtr = (TkRadialTransition *) ckalloc(sizeof(TkRadialTransition));
        gradientPtr->radialFill.radialPtr = tPtr;
        tPtr->centerX = 0.5;
        tPtr->centerY = 0.5;
        tPtr->radius = 0.5;
        tPtr->focalX = 0.5;
        tPtr->focalY = 0.5;
    }
    if(Tk_InitOptions(interp, (char *)gradientPtr,
            gradientPtr->optionTable, tkwin) != TCL_OK) {
        ckfree((char *)gradientPtr);
        return TCL_ERROR;
    }
    if(Tk_SetOptions(interp, (char *)gradientPtr, gradientPtr->optionTable,
            objc - 1, objv + 1, tkwin, NULL, &mask) != TCL_OK) {
        Tk_FreeConfigOptions((char *)gradientPtr, gradientPtr->optionTable,
            NULL);
        ckfree((char *)gradientPtr);
        return TCL_ERROR;
    }
    hPtr = Tcl_CreateHashEntry(hashTablePtr, tokenName, &isNew);
    Tcl_SetHashValue(hPtr, gradientPtr);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(tokenName, -1));
    return TCL_OK;
}

static int
PathGradientDelete(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr)
{
TkPathGradientMaster *gradientPtr = NULL;

    if(FindGradientMaster(interp, obj, tablePtr, &gradientPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    TkPathGradientChanged(gradientPtr, TK_PATH_GRADIENT_FLAG_DELETE);
    Tcl_DeleteHashEntry(Tcl_FindHashEntry(tablePtr, Tcl_GetString(obj)));
    PathGradientMasterFree(gradientPtr);
    return TCL_OK;
}

static int
PathGradientInUse(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr)
{
TkPathGradientMaster *gradientPtr = NULL;

    if(FindGradientMaster(interp, obj, tablePtr, &gradientPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_SetBooleanObj(Tcl_GetObjResult(interp),
        gradientPtr->instancePtr != NULL);
    return TCL_OK;
}

static void
PathGradientNames(
    Tcl_Interp * interp,
    Tcl_HashTable * tablePtr)
{
char *name;
Tcl_HashEntry *hPtr;
Tcl_Obj *listObj;
Tcl_HashSearch search;

    listObj = Tcl_NewListObj(0, NULL);
    hPtr = Tcl_FirstHashEntry(tablePtr, &search);
    while(hPtr != NULL) {
        name = (char *)Tcl_GetHashKey(tablePtr, hPtr);
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(name, -1));
        hPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_SetObjResult(interp, listObj);
}

static int
PathGradientType(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr)
{
TkPathGradientMaster *gradientPtr = NULL;

    if(FindGradientMaster(interp, obj, tablePtr, &gradientPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_SetObjResult(interp, Tcl_NewStringObj(
            (gradientPtr->type ==
                TK_PATH_GRADIENTTYPE_LINEAR) ? "linear" : "radial", -1));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * GradientObjCmd --
 *
 *    Implements the path::gradient command using gGradientHashPtr.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

int
GradientObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    InterpData *dataPtr = (InterpData *) clientData;
    int index;
    Tk_Window tkwin = Tk_MainWindow(interp);    /* Should have been the canvas. */
    int result = TCL_OK;

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[1], gradientCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {

    case kPathGradientCmdCget:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "option");
            return TCL_ERROR;
        }
        result = PathGradientCget(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->gradientHash);
        break;
    }

    case kPathGradientCmdConfigure:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv,
                "name ?option? ?value option value...?");
            return TCL_ERROR;
        }
        result = PathGradientConfigure(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->gradientHash);
        break;
    }

    case kPathGradientCmdCreate:{
    char str[255];

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "type ?option value...?");
            return TCL_ERROR;
        }
        sprintf(str, "%s%d", TK_PATHCMD_PATHGRADIENT,
            dataPtr->gradientNameUid++);
        result = PathGradientCreate(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->gradientHash, str);
        break;
    }

    case kPathGradientCmdDelete:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientDelete(interp, objv[2], &dataPtr->gradientHash);
        break;
    }

    case kPathGradientCmdInUse:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientInUse(interp, objv[2], &dataPtr->gradientHash);
        break;
    }

    case kPathGradientCmdNames:{
        if(objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
        PathGradientNames(interp, &dataPtr->gradientHash);
        break;
    }

    case kPathGradientCmdType:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
        result = PathGradientType(interp, objv[2], &dataPtr->gradientHash);
        break;
    }
    }
    return result;
}

static void
GradientInterpDeleted(
    ClientData clientData)
{
InterpData *dataPtr = (InterpData *) clientData;

    Tcl_DeleteHashTable(&dataPtr->gradientHash);
    ckfree((char *)dataPtr);
}

static void
PathGradientMasterFree(
    TkPathGradientMaster * gradientPtr)
{
    Tk_FreeConfigOptions((char *)gradientPtr, gradientPtr->optionTable, NULL);
    ckfree((char *)gradientPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathGetPathColorStatic --
 *
 *    Looks up named color or gradient in the global (static) gradient
 *    hash table. Used by the surface command to parse its -fill option.
 *    Else see TkPathGetPathColor.
 *
 * Results:
 *    Pointer to a TkPathColor struct or returns NULL on error
 *      and leaves an error message.
 *
 * Side effects:
 *    TkPathColor malloced if OK.
 *
 *----------------------------------------------------------------------
 */

TkPathColor *
TkPathGetPathColorStatic(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Tcl_Obj * nameObj)
{
InterpData *dataPtr =
    (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHGRADIENT, NULL);
Tcl_HashTable *hashTablePtr = NULL;

    if(dataPtr != NULL) {
        hashTablePtr = &dataPtr->gradientHash;
    }
    return TkPathGetPathColor(interp, tkwin, nameObj, hashTablePtr, NULL, NULL);
}

/*
 * These functions are called by users of gradients, typically items,
 * that make instances of gradients from a gradient object (master).
 */

/*
 *----------------------------------------------------------------------
 *
 * TkPathGetGradient --
 *
 *    This function is invoked by an item when it wants to use a particular
 *    gradient for a particular hash table. Compare Tk_GetImage.
 *
 * Results:
 *    The return value is a token for the gradient. If there is no gradient by the
 *    given name, then NULL is returned and an error message is left in the
 *    interp's result.
 *
 * Side effects:
 *    Tk records the fact that the item is using the gradient, and it will
 *    invoke changeProc later if the item needs redisplay. The caller must
 *    eventually invoke TkPathFreeGradient when it no longer needs the gradient.
 *
 *----------------------------------------------------------------------
 */

TkPathGradientInst *
TkPathGetGradient(
    Tcl_Interp * interp,
    const char *name,
    Tcl_HashTable * tablePtr,
    TkPathGradientChangedProc * changeProc,
    ClientData clientData)
{
Tcl_HashEntry *hPtr;
TkPathGradientInst *gradientPtr;
TkPathGradientMaster *masterPtr;

    hPtr = Tcl_FindHashEntry(tablePtr, name);
    if(hPtr == NULL) {
        if(interp != NULL) {
Tcl_Obj *resultObj;
            resultObj = Tcl_NewStringObj("gradient \"", -1);
            Tcl_AppendStringsToObj(resultObj, name, "\" doesn't exist",
                (char *)NULL);
            Tcl_SetObjResult(interp, resultObj);
        }
        return NULL;
    }
    masterPtr = (TkPathGradientMaster *) Tcl_GetHashValue(hPtr);
    gradientPtr = (TkPathGradientInst *) ckalloc(sizeof(TkPathGradientInst));
    gradientPtr->masterPtr = masterPtr;
    gradientPtr->changeProc = changeProc;
    gradientPtr->clientData = clientData;
    gradientPtr->nextPtr = masterPtr->instancePtr;
    masterPtr->instancePtr = gradientPtr;
    return gradientPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathFreeGradient --
 *
 *    This function is invoked by an item when it no longer needs a gradient
 *    acquired by a previous call to TkPathGetGradient. For each call to
 *    TkPathGetGradient there must be exactly one call to TkPathFreeGradient.
 *    Compare Tk_FreeImage.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The association between the gradient and the item is removed.
 *
 *----------------------------------------------------------------------
 */

void
TkPathFreeGradient(
    TkPathGradientInst * gradientPtr)
{
TkPathGradientMaster *masterPtr = gradientPtr->masterPtr;
TkPathGradientInst *walkPtr;

    walkPtr = masterPtr->instancePtr;
    if(walkPtr == gradientPtr) {
        masterPtr->instancePtr = gradientPtr->nextPtr;
    } else {
        while(walkPtr->nextPtr != gradientPtr) {
            walkPtr = walkPtr->nextPtr;
        }
        walkPtr->nextPtr = gradientPtr->nextPtr;
    }
    ckfree((char *)gradientPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathGradientChanged --
 *
 *    This function is called by a gradient manager whenever something has
 *    happened that requires the gradient to be redrawn or it has been deleted.
 *    Compare Tk_ImageChanged,
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Any items that display the gradient are notified so that they can
 *    redisplay themselves as appropriate.
 *
 *----------------------------------------------------------------------
 */

void
TkPathGradientChanged(
    TkPathGradientMaster * masterPtr,
    int flags)
{
    TkPathGradientInst *walkPtr, *nextPtr;

    if(flags) {
        /*
         * NB: We may implicitly call TkPathFreeGradient if being deleted!
         *     Therefore cache the nextPtr before invoking changeProc.
         */
        for(walkPtr = masterPtr->instancePtr; walkPtr != NULL;) {
            nextPtr = walkPtr->nextPtr;
            if(walkPtr->changeProc != NULL) {
                (*walkPtr->changeProc) (walkPtr->clientData, flags);
            }
            walkPtr = nextPtr;
        }
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathStyle.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathStyle.c --
 *
 *    This file implements style objects used when drawing paths.
 *      See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 * Note: It would be best to have this in the canvas widget as a special
 *       object, but I see no way of doing this without touching
 *       the canvas code.
 *
 * Note: When a style object is modified or destroyed the corresponding
 *       items are not notified. They will only notice any change when
 *       they need to redisplay.
 *
 */

#include "tkoPath.h"

static const char *styleCmds[] = {
    "cget", "configure", "create", "delete", "inuse", "names",
    (char *)NULL
};

enum {
    kPathStyleCmdCget = 0L,
    kPathStyleCmdConfigure,
    kPathStyleCmdCreate,
    kPathStyleCmdDelete,
    kPathStyleCmdInUse,
    kPathStyleCmdNames
};

typedef struct {
    Tcl_HashTable styleHash;
    Tk_OptionTable styleOptionTable;
    int styleNameUid;
} InterpData;

/*
 * Declarationd for functions local to this file.
 */

static int StyleObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int PathStyleCget(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr);
static int PathStyleConfigure(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * hashTablePtr,
    Tcl_HashTable * gradTablePtr);
static int PathStyleCreate(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * styleTablePtr,
    Tcl_HashTable * gradTablePtr,
    char *tokenName);
static int PathStyleDelete(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * hashTablePtr,
    Tk_Window tkwin);
static int PathStyleInUse(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr);
static void PathStyleNames(
    Tcl_Interp * interp,
    Tcl_HashTable * hashTablePtr);

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasStyleObjCmd --
 *
 *    Implements the 'pathName style' command using the canvas local state.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

int
TkPathCanvasStyleObjCmd(
    Tcl_Interp * interp,
    TkPathCanvas * path,
    int objc,
    Tcl_Obj * const objv[])
{
    int index;
    int result = TCL_OK;
    if(path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;

    /*
     * objv[2] is the subcommand: cget | configure | create | delete | names
     */
    if(objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[2], styleCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {

    case kPathStyleCmdCget:{
        if(objc != 5) {
            Tcl_WrongNumArgs(interp, 3, objv, "name option");
            return TCL_ERROR;
        }
        result = PathStyleCget(interp, *(path->win), objc - 3, objv + 3,
            &path->styleTable);
        break;
    }

    case kPathStyleCmdConfigure:{
        if(objc < 4) {
            Tcl_WrongNumArgs(interp, 3, objv,
                "name ?option? ?value option value...?");
            return TCL_ERROR;
        }
        result = PathStyleConfigure(interp, *(path->win), objc - 3, objv + 3,
            &path->styleTable, &path->gradientTable);
        break;
    }

    case kPathStyleCmdCreate:{
    char str[255];

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "?option value...?");
            return TCL_ERROR;
        }
        sprintf(str, "%s%d", TK_PATHCMD_STYLE, path->styleUid++);
        result = PathStyleCreate(interp, *(path->win), objc - 3, objv + 3,
            &path->styleTable, &path->gradientTable, str);
        break;
    }

    case kPathStyleCmdDelete:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "name");
            return TCL_ERROR;
        }
        result = PathStyleDelete(interp, objv[3], &path->styleTable,
            *(path->win));
        break;
    }

    case kPathStyleCmdInUse:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 3, objv, "name");
            return TCL_ERROR;
        }
        result = PathStyleInUse(interp, objv[3], &path->styleTable);
        break;
    }

    case kPathStyleCmdNames:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 3, objv, NULL);
            return TCL_ERROR;
        }
        PathStyleNames(interp, &path->styleTable);
        break;
    }
    }
    return result;
}

/*
 * Custom option processing code.
 */

/*
 * The -matrix custom option.
 */

int
    TkPathMatrixSetOption(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    char *list;
    int length;
    Tcl_Obj *valuePtr;
    TkPathMatrix *newPtr;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            list = Tcl_GetStringFromObj(valuePtr, &length);
            newPtr = (TkPathMatrix *) ckalloc(sizeof(TkPathMatrix));
            if(TkPathGetTMatrix(interp, list, newPtr) != TCL_OK) {
                ckfree((char *)newPtr);
                return TCL_ERROR;
            }
        } else {
            newPtr = NULL;
        }
        *((TkPathMatrix **) oldInternalPtr) = *((TkPathMatrix **) internalPtr);
        *((TkPathMatrix **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
TkPathMatrixGetOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
char *internalPtr;
TkPathMatrix *matrixPtr;
Tcl_Obj *listObj;

    /* @@@ An alternative to this could be to have an objOffset in option table. */
    internalPtr = recordPtr + internalOffset;
    matrixPtr = *((TkPathMatrix **) internalPtr);
    TkPathGetTclObjFromTMatrix(NULL, matrixPtr, &listObj);
    return listObj;
}

void
TkPathMatrixRestoreOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkPathMatrix **) internalPtr = *(TkPathMatrix **) oldInternalPtr;
}

void
TkPathMatrixFreeOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        ckfree(*((char **)internalPtr));
        *((char **)internalPtr) = NULL;
    }
}

/* Return NULL on error and leave error message */

TkPathDash *
TkPathDashNew(
    Tcl_Interp * interp,
    Tcl_Obj * dashObjPtr)
{
TkPathDash *dashPtr;
int objc, i;
double value;
Tcl_Obj **objv;

    dashPtr = (TkPathDash *) ckalloc(sizeof(TkPathDash));
    dashPtr->number = 0;
    dashPtr->array = NULL;
    if(Tcl_ListObjGetElements(interp, dashObjPtr, &objc,
            (Tcl_Obj ***) & objv) != TCL_OK) {
        goto error;
    }
    dashPtr->number = objc;
    dashPtr->array = (float *)ckalloc(objc * sizeof(float));
    for(i = 0; i < objc; i++) {
        if(Tcl_GetDoubleFromObj(interp, objv[i], &value) != TCL_OK) {
            goto error;
        }
        dashPtr->array[i] = (float)value;
    }
    return dashPtr;

  error:
    TkPathDashFree(dashPtr);
    return NULL;
}

void
TkPathDashFree(
    TkPathDash * dashPtr)
{
    if(dashPtr->array) {
        ckfree((char *)dashPtr->array);
    }
    ckfree((char *)dashPtr);
}

/*
 * The -strokedasharray custom option.
 */

/*
 *--------------------------------------------------------------
 *
 * Tk_PathDashOptionSetProc, Tk_PathDashOptionGetProc,
 *    Tk_PathDashOptionRestoreProc, Tk_PathDashOptionRestoreProc --
 *
 *    These functions are invoked during option processing to handle
 *    "-strokedasharray" option for canvas objects.
 *
 * Results:
 *    According to the Tk_ObjCustomOption struct.
 *
 * Side effects:
 *    Memory allocated or freed.
 *
 *--------------------------------------------------------------
 */

int Tk_PathDashOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    TkPathDash *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            newPtr = TkPathDashNew(interp, valuePtr);
            if(newPtr == NULL) {
                return TCL_ERROR;
            }
        }
        *((TkPathDash **) oldInternalPtr) = *((TkPathDash **) internalPtr);
        *((TkPathDash **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
Tk_PathDashOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
TkPathDash *dashPtr = *((TkPathDash **) (recordPtr + internalOffset));
Tcl_Obj *listObj = Tcl_NewListObj(0, NULL);
int i;

    if(dashPtr != NULL) {
        for(i = 0; i < dashPtr->number; i++) {
            Tcl_ListObjAppendElement(NULL, listObj,
                Tcl_NewDoubleObj(dashPtr->array[i]));
        }
    }
    return listObj;
}

void
Tk_PathDashOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkPathDash **) internalPtr = *(TkPathDash **) oldInternalPtr;
}

void
Tk_PathDashOptionFreeProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        TkPathDashFree(*(TkPathDash **) internalPtr);
        *((char **)internalPtr) = NULL;
    }
}

/*
 * Combined XColor and gradient name in a TkPathColor record.
 */

int
    TkPathColorSetOption(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    TkPathColor *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            newPtr = TkPathNewPathColor(interp, tkwin, valuePtr);
            if(newPtr == NULL) {
                return TCL_ERROR;
            }
        } else {
            newPtr = NULL;
        }
        *((TkPathColor **) oldInternalPtr) = *((TkPathColor **) internalPtr);
        *((TkPathColor **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
TkPathColorGetOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
char *internalPtr;
Tcl_Obj *objPtr = NULL;
TkPathColor *pathColor = NULL;

    internalPtr = recordPtr + internalOffset;
    pathColor = *((TkPathColor **) internalPtr);
    if(pathColor != NULL) {
        if(pathColor->color) {
            objPtr = Tcl_NewStringObj(Tk_NameOfColor(pathColor->color), -1);
        } else if(pathColor->gradientInstPtr) {
            objPtr =
                Tcl_NewStringObj(pathColor->gradientInstPtr->masterPtr->name,
                -1);
        }
    }
    return objPtr;
}

void
TkPathColorRestoreOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(TkPathColor **) internalPtr = *(TkPathColor **) oldInternalPtr;
}

void
TkPathColorFreeOption(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        TkPathFreePathColor(*(TkPathColor **) internalPtr);
        *((char **)internalPtr) = NULL;
    }
}

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
    TK_PATH_OPTION_STRING_TABLES_FILL TK_PATH_OPTION_STRING_TABLES_STROKE
/*
 * @@@ TODO: BAD I had to duplicate this record here and in tkPathStyle.h.
 *     Else I get problems with Tk_Offset and records.
 */
static Tk_OptionSpec styleOptionSpecs[] = {
    {TK_OPTION_STRING, "-fill", NULL, NULL,
            "", Tk_Offset(Tk_PathStyle, fillObj), -1,
        TK_OPTION_NULL_OK, 0, TK_PATH_STYLE_OPTION_FILL},
    {TK_OPTION_DOUBLE, "-fillopacity", NULL, NULL,
            "1.0", -1, Tk_Offset(Tk_PathStyle, fillOpacity), 0, 0,
        TK_PATH_STYLE_OPTION_FILL_OPACITY},
    {TK_OPTION_STRING_TABLE, "-fillrule", NULL, NULL,
            "nonzero", -1, Tk_Offset(Tk_PathStyle, fillRule),
        0, (ClientData) fillRuleST, TK_PATH_STYLE_OPTION_FILL_RULE},
    {TK_OPTION_CUSTOM, "-matrix", NULL, NULL,
            NULL, -1, Tk_Offset(Tk_PathStyle, matrixPtr),
        TK_OPTION_NULL_OK, (ClientData) & matrixCO,
            TK_PATH_STYLE_OPTION_MATRIX},
    {TK_OPTION_COLOR, "-stroke", NULL, NULL,
            "black", -1, Tk_Offset(Tk_PathStyle, strokeColor),
            TK_OPTION_NULL_OK, 0,
        TK_PATH_STYLE_OPTION_STROKE},
    {TK_OPTION_CUSTOM, "-strokedasharray", NULL, NULL,
            NULL, -1, Tk_Offset(Tk_PathStyle, dashPtr),
        TK_OPTION_NULL_OK, (ClientData) & dashCO,
            TK_PATH_STYLE_OPTION_STROKE_DASHARRAY},
    {TK_OPTION_STRING_TABLE, "-strokelinecap", NULL, NULL,
            "butt", -1, Tk_Offset(Tk_PathStyle, capStyle),
        0, (ClientData) lineCapST, TK_PATH_STYLE_OPTION_STROKE_LINECAP},
    {TK_OPTION_STRING_TABLE, "-strokelinejoin", NULL, NULL,
            "round", -1, Tk_Offset(Tk_PathStyle, joinStyle),
        0, (ClientData) lineJoinST, TK_PATH_STYLE_OPTION_STROKE_LINEJOIN},
    {TK_OPTION_DOUBLE, "-strokemiterlimit", NULL, NULL,
            "4.0", -1, Tk_Offset(Tk_PathStyle, miterLimit), 0, 0,
        TK_PATH_STYLE_OPTION_STROKE_MITERLIMIT},
    {TK_OPTION_DOUBLE, "-strokeopacity", NULL, NULL,
            "1.0", -1, Tk_Offset(Tk_PathStyle, strokeOpacity), 0, 0,
        TK_PATH_STYLE_OPTION_STROKE_OPACITY},
    {TK_OPTION_DOUBLE, "-strokewidth", NULL, NULL,
            "1.0", -1, Tk_Offset(Tk_PathStyle, strokeWidth), 0, 0,
        TK_PATH_STYLE_OPTION_STROKE_WIDTH},

    /* @@@ TODO: When this comes into canvas code we should add a -tags option here??? */

    {TK_OPTION_END, NULL, NULL, NULL,
        NULL, 0, -1, 0, (ClientData) NULL, 0}
};

static void
PathStyleInterpDeleted(
    ClientData clientData)
{
InterpData *dataPtr = (InterpData *) clientData;

    Tcl_DeleteHashTable(&dataPtr->styleHash);
    ckfree((char *)dataPtr);
}

void
TkPathStyleInit(
    Tcl_Interp * interp)
{
InterpData *dataPtr =
    (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHSTYLE, NULL);

    if(dataPtr == NULL) {
        dataPtr = (InterpData *) ckalloc(sizeof(InterpData));
        Tcl_InitHashTable(&dataPtr->styleHash, TCL_STRING_KEYS);
        dataPtr->styleOptionTable =
            Tk_CreateOptionTable(interp, styleOptionSpecs);
        dataPtr->styleNameUid = 0;
        Tcl_SetAssocData(interp, TK_PATHCMD_PATHSTYLE,
            (Tcl_InterpDeleteProc *) PathStyleInterpDeleted,
            (ClientData) dataPtr);
    }
    Tcl_CreateObjCommand(interp, TK_PATHCMD_PATHSTYLE,
        StyleObjCmd, (ClientData) dataPtr, (Tcl_CmdDeleteProc *) NULL);
}

/*
 * StyleGradientProc: callback to style when gradient changes.
 */

static void
StyleGradientProc(
    ClientData clientData,
    int flags)
{
    Tk_PathStyle *stylePtr = (Tk_PathStyle *) clientData;

    if(flags) {
        if(flags & TK_PATH_GRADIENT_FLAG_DELETE) {
            TkPathFreePathColor(stylePtr->fill);
            stylePtr->fill = NULL;
            Tcl_DecrRefCount(stylePtr->fillObj);
            stylePtr->fillObj = NULL;
        }
        TkPathStyleChanged(stylePtr, flags);
    }
}

static void
PathStyleFree(
    Tk_PathStyle * stylePtr,
    Tk_Window tkwin)
{
    if(stylePtr->fill != NULL) {
        TkPathFreePathColor(stylePtr->fill);
    }
    Tk_FreeConfigOptions((char *)stylePtr, stylePtr->optionTable, tkwin);
    ckfree((char *)stylePtr);
}

static int
FindPathStyle(
    Tcl_Interp * interp,
    Tcl_Obj * nameObj,
    Tcl_HashTable * tablePtr,
    Tk_PathStyle ** s)
{
Tcl_HashEntry *hPtr;
char *name = Tcl_GetString(nameObj);
    *s = NULL;
    hPtr = Tcl_FindHashEntry(tablePtr, name);
    if(hPtr == NULL) {
Tcl_Obj *resultObj;
        resultObj = Tcl_NewStringObj("style \"", -1);
        Tcl_AppendStringsToObj(resultObj, name, "\" doesn't exist",
            (char *)NULL);
        Tcl_SetObjResult(interp, resultObj);
        return TCL_ERROR;
    }
    *s = (Tk_PathStyle *) Tcl_GetHashValue(hPtr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * PathStyleCget, Configure, Create, Delete, InUse, Names --
 *
 *    These functions implement style object commands in a generic way.
 *    The Tcl_HashTable defines the style namespace.
 *
 * Results:
 *    Varies: typically a standard tcl result or void.
 *
 * Side effects:
 *    Varies.
 *
 *--------------------------------------------------------------
 */

static int
PathStyleCget(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * tablePtr)
{
    Tk_PathStyle *stylePtr = NULL;
    Tcl_Obj *resultObj = NULL;

    if(FindPathStyle(interp, objv[0], tablePtr, &stylePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    resultObj = Tk_GetOptionValue(interp, (char *)stylePtr,
        stylePtr->optionTable, objv[1], tkwin);
    if(resultObj == NULL) {
        return TCL_ERROR;
    } else {
        Tcl_SetObjResult(interp, resultObj);
    }
    return TCL_OK;
}

static int
PathStyleConfigure(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * styleTablePtr,
    Tcl_HashTable * gradTablePtr)
{
    int mask;
    Tk_PathStyle *stylePtr = NULL;
    Tcl_Obj *resultObj = NULL;

    if(FindPathStyle(interp, objv[0], styleTablePtr, &stylePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(objc <= 2) {
        resultObj = Tk_GetOptionInfo(interp, (char *)stylePtr,
            stylePtr->optionTable,
            (objc == 1) ? (Tcl_Obj *) NULL : objv[1], tkwin);
        if(resultObj == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, resultObj);
    } else {
    TkPathColor *fillPtr = NULL;

        /* @@@ TODO: loop error to recover using savedOptions! */
        if(Tk_SetOptions(interp, (char *)stylePtr, stylePtr->optionTable,
                objc - 1, objv + 1, tkwin, NULL, &mask) != TCL_OK) {
            return TCL_ERROR;
        }
        if(stylePtr->fillObj != NULL) {
            fillPtr = TkPathGetPathColor(interp, tkwin, stylePtr->fillObj,
                gradTablePtr, StyleGradientProc, (ClientData) stylePtr);
            if(fillPtr == NULL) {
                return TCL_ERROR;
            }
        } else {
            fillPtr = NULL;
        }
        /* Free any old and store the new. */
        if(stylePtr->fill != NULL) {
            TkPathFreePathColor(stylePtr->fill);
        }
        stylePtr->fill = fillPtr;
        /*
         * Let mask be the cumalative options set.
         */
        stylePtr->mask |= mask;
    }
    TkPathStyleChanged(stylePtr, TK_PATH_STYLE_FLAG_CONFIGURE);
    return TCL_OK;
}

static int
PathStyleCreate(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    int objc,
    Tcl_Obj * const objv[],
    Tcl_HashTable * styleTablePtr,
    Tcl_HashTable * gradTablePtr,
    char *tokenName)
{
    int isNew;
    int mask;
    Tcl_HashEntry *hPtr;
    Tk_PathStyle *stylePtr = NULL;
    TkPathColor *fillPtr = NULL;
    InterpData *dataPtr =
        (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHSTYLE, NULL);

    stylePtr = (Tk_PathStyle *) ckalloc(sizeof(Tk_PathStyle));
    memset(stylePtr, '\0', sizeof(Tk_PathStyle));

    /* Fill in defaults. */
    TkPathInitStyle(stylePtr);

    /*
     * Create the option table for this class.  If it has already
     * been created, the cached pointer will be returned.
     */
    stylePtr->optionTable = dataPtr->styleOptionTable;
    stylePtr->name = Tk_GetUid(tokenName);

    if(Tk_InitOptions(interp, (char *)stylePtr,
            stylePtr->optionTable, tkwin) != TCL_OK) {
        ckfree((char *)stylePtr);
        return TCL_ERROR;
    }
    if(Tk_SetOptions(interp, (char *)stylePtr, stylePtr->optionTable,
            objc, objv, tkwin, NULL, &mask) != TCL_OK) {
        Tk_FreeConfigOptions((char *)stylePtr, stylePtr->optionTable, NULL);
        ckfree((char *)stylePtr);
        return TCL_ERROR;
    }
    if(stylePtr->fillObj != NULL) {
        fillPtr = TkPathGetPathColor(interp, tkwin, stylePtr->fillObj,
            gradTablePtr, StyleGradientProc, (ClientData) stylePtr);
        if(fillPtr == NULL) {
            Tk_FreeConfigOptions((char *)stylePtr, stylePtr->optionTable, NULL);
            ckfree((char *)stylePtr);
            return TCL_ERROR;
        }
    } else {
        fillPtr = NULL;
    }
    stylePtr->fill = fillPtr;

    /*
     * Let mask be the cumalative options set.
     */
    stylePtr->mask |= mask;
    hPtr = Tcl_CreateHashEntry(styleTablePtr, tokenName, &isNew);
    Tcl_SetHashValue(hPtr, stylePtr);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(tokenName, -1));
    return TCL_OK;
}

static int
PathStyleDelete(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr,
    Tk_Window tkwin)
{
Tk_PathStyle *stylePtr = NULL;

    if(FindPathStyle(interp, obj, tablePtr, &stylePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    TkPathStyleChanged(stylePtr, TK_PATH_STYLE_FLAG_DELETE);
    Tcl_DeleteHashEntry(Tcl_FindHashEntry(tablePtr, Tcl_GetString(obj)));
    PathStyleFree(stylePtr, tkwin);
    return TCL_OK;
}

static int
PathStyleInUse(
    Tcl_Interp * interp,
    Tcl_Obj * obj,
    Tcl_HashTable * tablePtr)
{
Tk_PathStyle *stylePtr = NULL;

    if(FindPathStyle(interp, obj, tablePtr, &stylePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    Tcl_SetBooleanObj(Tcl_GetObjResult(interp), stylePtr->instancePtr != NULL);
    return TCL_OK;
}

static void
PathStyleNames(
    Tcl_Interp * interp,
    Tcl_HashTable * tablePtr)
{
char *name;
Tcl_HashEntry *hPtr;
Tcl_Obj *listObj;
Tcl_HashSearch search;

    listObj = Tcl_NewListObj(0, NULL);
    hPtr = Tcl_FirstHashEntry(tablePtr, &search);
    while(hPtr != NULL) {
        name = (char *)Tcl_GetHashKey(tablePtr, hPtr);
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(name, -1));
        hPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_SetObjResult(interp, listObj);
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathConfigStyle --
 *
 *    Parses a list of Tcl objects to an already allocated Tk_PathStyle.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    Options allocated. Use Tk_FreeConfigOptions when finished.
 *
 *----------------------------------------------------------------------
 */

int
TkPathConfigStyle(
    Tcl_Interp * interp,
    Tk_PathStyle * stylePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_Window tkwin = Tk_MainWindow(interp);
    InterpData *dataPtr =
        (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHSTYLE, NULL);

    stylePtr->optionTable = dataPtr->styleOptionTable;
    if(Tk_InitOptions(interp, (char *)stylePtr, dataPtr->styleOptionTable,
            tkwin) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tk_SetOptions(interp, (char *)stylePtr, dataPtr->styleOptionTable,
            objc, objv, tkwin, NULL, NULL) != TCL_OK) {
        Tk_FreeConfigOptions((char *)stylePtr, dataPtr->styleOptionTable, NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StyleObjCmd --
 *
 *    This implements the standalone ::path::style command.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

static int
StyleObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    InterpData *dataPtr = (InterpData *) clientData;
    int index;
    int result = TCL_OK;
    Tk_Window tkwin = Tk_MainWindow(interp);

    /*
     * objv[1] is the subcommand: cget | configure | create | delete | names
     */
    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[1], styleCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {

    case kPathStyleCmdCget:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "name option");
            return TCL_ERROR;
        }
        result = PathStyleCget(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->styleHash);
        break;
    }

    case kPathStyleCmdConfigure:{
    Tcl_HashTable *gradientHashPtr =
        (Tcl_HashTable *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHGRADIENT,
            NULL);

        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv,
                "name ?option? ?value option value...?");
            return TCL_ERROR;
        }
        result = PathStyleConfigure(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->styleHash, gradientHashPtr);
        break;
    }

    case kPathStyleCmdCreate:{
    Tcl_HashTable *gradientHashPtr =
        (Tcl_HashTable *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHGRADIENT,
            NULL);
    char str[255];

        if(objc < 2) {
            Tcl_WrongNumArgs(interp, 1, objv, "?option value...?");
            return TCL_ERROR;
        }
        sprintf(str, "%s%d", TK_PATHCMD_PATHSTYLE, dataPtr->styleNameUid++);
        result = PathStyleCreate(interp, tkwin, objc - 2, objv + 2,
            &dataPtr->styleHash, gradientHashPtr, str);
        break;
    }

    case kPathStyleCmdDelete:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
        result = PathStyleDelete(interp, objv[2], &dataPtr->styleHash, tkwin);
        break;
    }

    case kPathStyleCmdInUse:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
        result = PathStyleInUse(interp, objv[2], &dataPtr->styleHash);
        break;
    }

    case kPathStyleCmdNames:{
        if(objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
        PathStyleNames(interp, &dataPtr->styleHash);
        break;
    }
    }
    return result;
}

void
TkPathStylesFree(
    Tk_Window tkwin,
    Tcl_HashTable * hashTablePtr)
{
Tcl_HashEntry *hPtr;
Tcl_HashSearch search;
char *recordPtr;

    hPtr = Tcl_FirstHashEntry(hashTablePtr, &search);
    while(hPtr != NULL) {
        recordPtr = (char *)Tcl_GetHashValue(hPtr);
        Tcl_DeleteHashEntry(hPtr);
        PathStyleFree((Tk_PathStyle *) recordPtr, tkwin);
        hPtr = Tcl_NextHashEntry(&search);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathStyleMergeStyleStatic --
 *
 *    Looks up the named style in styleObj in the globally defined
 *    style hash table.
 *    Overwrites values in dstStyle if set in styleObj.
 *    This is indicated by the mask of the srcStyle.
 *    This just copy pointers. For short lived style records only!
 *
 * Results:
 *    Standard Tcl result.
 *
 * Side effects:
 *    Changes *values* in dstStyle. Leaves any error string in interp.
 *
 *--------------------------------------------------------------
 */

int
TkPathStyleMergeStyleStatic(
    Tcl_Interp * interp,
    Tcl_Obj * styleObj,
    Tk_PathStyle * dstStyle,
    long flags)
{
    Tcl_HashEntry *hPtr;
    Tk_PathStyle *srcStyle;
    InterpData *dataPtr =
        (InterpData *) Tcl_GetAssocData(interp, TK_PATHCMD_PATHSTYLE, NULL);

    if(styleObj == NULL) {
        return TCL_OK;
    }
    if(dataPtr == NULL) {
        goto noStyle;
    }
    hPtr = Tcl_FindHashEntry(&dataPtr->styleHash, Tcl_GetString(styleObj));
    if(hPtr == NULL) {
      noStyle:
        Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
            "the global style \"", Tcl_GetString(styleObj),
            "\" does not exist", NULL);
        return TCL_ERROR;
    }
    srcStyle = (Tk_PathStyle *) Tcl_GetHashValue(hPtr);
    TkPathStyleMergeStyles(srcStyle, dstStyle, flags);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathStyleMergeStyles --
 *
 *    Overwrites values in dstStyle if set in srcStyle.
 *    This is indicated by the mask of the srcStyle.
 *    This just copy pointers. For short lived style records only!
 *    Be sure to NEVER free any pointers in this style since we
 *    don't own theme!
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Changes *values* in dstStyle.
 *
 *--------------------------------------------------------------
 */

void
TkPathStyleMergeStyles(
    Tk_PathStyle * srcStyle,
    Tk_PathStyle * dstStyle,
    long flags)
{
    int mask = srcStyle->mask;

    if(mask == 0) {
        return;
    }

    /*
     * Go through all options set in srcStylePtr and merge
     * these into dstStylePtr.
     */
    if(!(flags & TK_PATH_MERGESTYLE_NOTFILL)) {
        if(mask & TK_PATH_STYLE_OPTION_FILL) {
            dstStyle->fill = srcStyle->fill;
        }
        if(mask & TK_PATH_STYLE_OPTION_FILL_OFFSET) {
            /* @@@ TODO */
        }
        if(mask & TK_PATH_STYLE_OPTION_FILL_OPACITY) {
            dstStyle->fillOpacity = srcStyle->fillOpacity;
        }
        if(mask & TK_PATH_STYLE_OPTION_FILL_RULE) {
            dstStyle->fillRule = srcStyle->fillRule;
        }
        if(mask & TK_PATH_STYLE_OPTION_FILL_STIPPLE) {
            /* @@@ TODO */
        }
    }
    if(mask & TK_PATH_STYLE_OPTION_MATRIX) {
        dstStyle->matrixPtr = srcStyle->matrixPtr;
    }
    if(!(flags & TK_PATH_MERGESTYLE_NOTSTROKE)) {
        if(mask & TK_PATH_STYLE_OPTION_STROKE) {
            dstStyle->strokeColor = srcStyle->strokeColor;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_DASHARRAY) {
            dstStyle->dashPtr = srcStyle->dashPtr;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_LINECAP) {
            dstStyle->capStyle = srcStyle->capStyle;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_LINEJOIN) {
            dstStyle->joinStyle = srcStyle->joinStyle;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_MITERLIMIT) {
            dstStyle->miterLimit = srcStyle->miterLimit;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_OFFSET) {
            /* @@@ TODO */
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_OPACITY) {
            dstStyle->strokeOpacity = srcStyle->strokeOpacity;
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_STIPPLE) {
            /* @@@ TODO */
        }
        if(mask & TK_PATH_STYLE_OPTION_STROKE_WIDTH) {
            dstStyle->strokeWidth = srcStyle->strokeWidth;
        }
    }
    dstStyle->mask |= mask;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathInitStyle
 *
 *    This procedure initializes the Tk_PathStyle structure
 *    with default values.
 *
 * Results:
 *    None
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

void
TkPathInitStyle(
    Tk_PathStyle * style)
{
    memset(style, '\0', sizeof(Tk_PathStyle));

    style->mask = 0;
    style->strokeColor = NULL;
    style->strokeWidth = 1.0;
    style->strokeOpacity = 1.0;
    style->offset = 0;
    style->dashPtr = NULL;
    style->capStyle = CapButt;
    style->joinStyle = JoinRound;

    style->fillOpacity = 1.0;
    style->fillRule = WindingRule;
    style->fillObj = NULL;
    style->fill = NULL;
    style->matrixPtr = NULL;
    style->instancePtr = NULL;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathDeleteStyle
 *
 *    This procedure frees all memory in the Tk_PathStyle structure
 *    that is not freed by Tk_FreeConfigOptions.
 *
 * Results:
 *    None
 *
 * Side effects:
 *    Memory freed
 *
 *--------------------------------------------------------------
 */

void
TkPathDeleteStyle(
    Tk_PathStyle * style)
{
    if(style->fill != NULL) {
        TkPathFreePathColor(style->fill);
    }
}

/*
 * These functions are called by users of styles, typically items,
 * that make instances of styles from a style object (master).
 */

/*
 *----------------------------------------------------------------------
 *
 * TkPathGetStyle --
 *
 *    This function is invoked by an item when it wants to use a particular
 *    style for a particular hash table. Compare Tk_GetImage.
 *
 * Results:
 *    The return value is a token for the style. If there is no style by the
 *    given name, then NULL is returned and an error message is left in the
 *    interp's result.
 *
 * Side effects:
 *    Tk records the fact that the item is using the style, and it will
 *    invoke changeProc later if the item needs redisplay. The caller must
 *    eventually invoke TkPathFreeStyle when it no longer needs the style.
 *
 *----------------------------------------------------------------------
 */

TkPathStyleInst *
TkPathGetStyle(
    Tcl_Interp * interp,
    const char *name,
    Tcl_HashTable * tablePtr,
    TkPathGradientChangedProc * changeProc,
    ClientData clientData)
{
    Tcl_HashEntry *hPtr;
    TkPathStyleInst *stylePtr;
    Tk_PathStyle *masterPtr;

    hPtr = Tcl_FindHashEntry(tablePtr, name);
    if(hPtr == NULL) {
        if(interp != NULL) {
    Tcl_Obj *resultObj;
            resultObj = Tcl_NewStringObj("style \"", -1);
            Tcl_AppendStringsToObj(resultObj, name, "\" doesn't exist",
                (char *)NULL);
            Tcl_SetObjResult(interp, resultObj);
        }
        return NULL;
    }
    masterPtr = (Tk_PathStyle *) Tcl_GetHashValue(hPtr);
    stylePtr = (TkPathStyleInst *) ckalloc(sizeof(TkPathStyleInst));
    stylePtr->masterPtr = masterPtr;
    stylePtr->changeProc = changeProc;
    stylePtr->clientData = clientData;
    stylePtr->nextPtr = masterPtr->instancePtr;
    masterPtr->instancePtr = stylePtr;
    return stylePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathFreeStyle --
 *
 *    This function is invoked by an item when it no longer needs a gradient
 *    acquired by a previous call to TkPathGetGradient. For each call to
 *    TkPathGetGradient there must be exactly one call to TkPathFreeGradient.
 *    Compare Tk_FreeImage.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The association between the gradient and the item is removed.
 *
 *----------------------------------------------------------------------
 */

void
TkPathFreeStyle(
    TkPathStyleInst * stylePtr)
{
Tk_PathStyle *masterPtr = stylePtr->masterPtr;
TkPathStyleInst *walkPtr;

    walkPtr = masterPtr->instancePtr;
    if(walkPtr == stylePtr) {
        masterPtr->instancePtr = stylePtr->nextPtr;
    } else {
        while(walkPtr->nextPtr != stylePtr) {
            walkPtr = walkPtr->nextPtr;
        }
        walkPtr->nextPtr = stylePtr->nextPtr;
    }
    ckfree((char *)stylePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathStyleChanged --
 *
 *    This function is called by a style manager whenever something has
 *    happened that requires the style to be redrawn or it has been deleted.
 *    Compare Tk_ImageChanged,
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Any items that display the style are notified so that they can
 *    redisplay themselves as appropriate.
 *
 *----------------------------------------------------------------------
 */

void
TkPathStyleChanged(
    Tk_PathStyle * masterPtr,
    int flags)
{
    TkPathStyleInst *walkPtr, *nextPtr;

    if(flags) {
        /*
         * NB: We may implicitly call TkPathFreeGradient if being deleted!
         *     Therefore cache the nextPtr before invoking changeProc.
         */
        for(walkPtr = masterPtr->instancePtr; walkPtr != NULL;) {
            nextPtr = walkPtr->nextPtr;
            if(walkPtr->changeProc != NULL) {
                (*walkPtr->changeProc) (walkPtr->clientData, flags);
            }
            walkPtr = nextPtr;
        }
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathSurface.c.




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathSurface.c --
 *
 *    This file implements style objects used when drawing paths.
 *      See http://www.w3.org/TR/SVG11/.
 *
 * Copyright (c) 2007-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"

typedef struct {
    Tcl_HashTable surfaceHash;
    Tk_OptionTable optionTableCircle;
    Tk_OptionTable optionTableEllipse;
    Tk_OptionTable optionTablePath;
    Tk_OptionTable optionTablePimage;
    Tk_OptionTable optionTablePline;
    Tk_OptionTable optionTablePolyline;
    Tk_OptionTable optionTablePpolygon;
    Tk_OptionTable optionTablePrect;
    Tk_OptionTable optionTablePtext;
    int uid;
    Tk_Window tkwin;
} InterpData;

typedef struct PathSurface {
    TkPathContext ctx;
    char *token;
    ClientData clientData;
    int width;
    int height;
    Tcl_HashTable *surfaceHash;
} PathSurface;

static void StaticSurfaceEventProc(
    ClientData clientData,
    XEvent * eventPtr);
static void StaticSurfaceObjCmdDeleted(
    ClientData clientData);
static int StaticSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int NamesSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int NewSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCopyObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceDestroyObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr);
static void SurfaceDeletedProc(
    ClientData clientData);
static int SurfaceCreateObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceEraseObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreateEllipse(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int type,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePath(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePimage(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePline(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePpoly(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int type,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePrect(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);
static int SurfaceCreatePtext(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[]);

static const char *staticSurfaceCmds[] = {
    "names", "new", (char *)NULL
};

enum {
    kPathStaticSurfaceCmdNames = 0L,
    kPathStaticSurfaceCmdNew
};

static int
StaticSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    int index;
    int result = TCL_OK;

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[1], staticSurfaceCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {
    case kPathStaticSurfaceCmdNames:{
        result = NamesSurfaceObjCmd(clientData, interp, objc, objv);
        break;
    }
    case kPathStaticSurfaceCmdNew:{
        result = NewSurfaceObjCmd(clientData, interp, objc, objv);
        break;
    }
    }
    return result;
}

static void
StaticSurfaceEventProc(
    ClientData clientData,
    XEvent * eventPtr)
{
InterpData *dataPtr = (InterpData *) clientData;

    if(eventPtr->type == DestroyNotify) {
        dataPtr->tkwin = NULL;
    }
}

static void
StaticSurfaceObjCmdDeleted(
    ClientData clientData)
{
InterpData *dataPtr = (InterpData *) clientData;

    if(dataPtr->tkwin != NULL) {
        Tk_DeleteEventHandler(dataPtr->tkwin, StructureNotifyMask,
            StaticSurfaceEventProc, dataPtr);
    }
    Tcl_DeleteHashTable(&dataPtr->surfaceHash);
    Tk_DeleteOptionTable(dataPtr->optionTableCircle);
    Tk_DeleteOptionTable(dataPtr->optionTableEllipse);
    Tk_DeleteOptionTable(dataPtr->optionTablePath);
    Tk_DeleteOptionTable(dataPtr->optionTablePimage);
    Tk_DeleteOptionTable(dataPtr->optionTablePline);
    Tk_DeleteOptionTable(dataPtr->optionTablePolyline);
    Tk_DeleteOptionTable(dataPtr->optionTablePpolygon);
    Tk_DeleteOptionTable(dataPtr->optionTablePrect);
    Tk_DeleteOptionTable(dataPtr->optionTablePtext);
    ckfree((char *)dataPtr);
}

static int
NamesSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    InterpData *dataPtr = (InterpData *) clientData;
    char *name;
    Tcl_HashEntry *hPtr;
    Tcl_Obj *listObj;
    Tcl_HashSearch search;

    if(objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, NULL);
        return TCL_ERROR;
    }
    listObj = Tcl_NewListObj(0, NULL);
    hPtr = Tcl_FirstHashEntry(&dataPtr->surfaceHash, &search);
    while(hPtr != NULL) {
        name = (char *)Tcl_GetHashKey(&dataPtr->surfaceHash, hPtr);
        Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(name, -1));
        hPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_SetObjResult(interp, listObj);
    return TCL_OK;
}

static int
NewSurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    InterpData *dataPtr = (InterpData *) clientData;
    TkPathContext ctx;
    PathSurface *surfacePtr;
    Tcl_HashEntry *hPtr;
    char str[255];
    int width, height;
    int isNew;
    int result = TCL_OK;
    Display *display = NULL;

    if(objc != 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "width height");
        return TCL_ERROR;
    }
    if(Tcl_GetIntFromObj(interp, objv[2], &width) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tcl_GetIntFromObj(interp, objv[3], &height) != TCL_OK) {
        return TCL_ERROR;
    }

    if(dataPtr->tkwin == NULL) {
        dataPtr->tkwin = Tk_MainWindow(interp);
        if(dataPtr->tkwin != NULL) {
            Tk_CreateEventHandler(dataPtr->tkwin, StructureNotifyMask,
                StaticSurfaceEventProc, dataPtr);
        }
    }
    if(dataPtr->tkwin != NULL) {
        display = Tk_Display(dataPtr->tkwin);
    }
    ctx = TkPathInitSurface(display, width, height);
    if(ctx == 0) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("Failed in TkPathInitSurface", -1));
        return TCL_ERROR;
    }

    sprintf(str, "%s%d", TK_PATHCMD_PATHSURFACE, dataPtr->uid++);
    surfacePtr = (PathSurface *) ckalloc(sizeof(PathSurface));
    surfacePtr->token = (char *)ckalloc((unsigned int)strlen(str) + 1);
    strcpy(surfacePtr->token, str);
    surfacePtr->ctx = ctx;
    surfacePtr->clientData = clientData;
    surfacePtr->width = width;
    surfacePtr->height = height;
    surfacePtr->surfaceHash = &dataPtr->surfaceHash;
    Tcl_CreateObjCommand(interp, str, SurfaceObjCmd,
        (ClientData) surfacePtr, SurfaceDeletedProc);

    hPtr = Tcl_CreateHashEntry(&dataPtr->surfaceHash, str, &isNew);
    Tcl_SetHashValue(hPtr, surfacePtr);
    Tcl_SetObjResult(interp, Tcl_NewStringObj(str, -1));
    return result;
}

static const char *surfaceCmds[] = {
    "copy", "create", "destroy",
    "erase", "height", "width",
    (char *)NULL
};

enum {
    kPathSurfaceCmdCopy = 0L,
    kPathSurfaceCmdCreate,
    kPathSurfaceCmdDestroy,
    kPathSurfaceCmdErase,
    kPathSurfaceCmdHeight,
    kPathSurfaceCmdWidth
};

static int
SurfaceObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    PathSurface *surfacePtr = (PathSurface *) clientData;
    int index;
    int result = TCL_OK;

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "command ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[1], surfaceCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }
    switch (index) {
    case kPathSurfaceCmdCopy:{
        result = SurfaceCopyObjCmd(interp, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceCmdCreate:{
        result = SurfaceCreateObjCmd(surfacePtr->clientData,
            interp, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceCmdDestroy:{
        result = SurfaceDestroyObjCmd(interp, surfacePtr);
        break;
    }
    case kPathSurfaceCmdErase:{
        result = SurfaceEraseObjCmd(interp, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceCmdHeight:
    case kPathSurfaceCmdWidth:{
        if(objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp,
            Tcl_NewIntObj((index == kPathSurfaceCmdHeight) ?
                surfacePtr->height : surfacePtr->width));
        break;
    }
    }
    return result;
}

static int
SurfaceCopyObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_PhotoHandle photo;

    if(objc != 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "image");
        return TCL_ERROR;
    }
    photo = Tk_FindPhoto(interp, Tcl_GetString(objv[2]));
    if(photo == NULL) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("didn't find that image", -1));
        return TCL_ERROR;
    }
    TkPathSurfaceToPhoto(interp, surfacePtr->ctx, photo);
    Tcl_SetObjResult(interp, objv[2]);
    return TCL_OK;
}

static int
SurfaceDestroyObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr)
{
    Tcl_DeleteCommand(interp, surfacePtr->token);
    return TCL_OK;
}

static void
SurfaceDeletedProc(
    ClientData clientData)
{
PathSurface *surfacePtr = (PathSurface *) clientData;
Tcl_HashEntry *hPtr;

    hPtr = Tcl_FindHashEntry(surfacePtr->surfaceHash, surfacePtr->token);
    if(hPtr != NULL) {
        Tcl_DeleteHashEntry(hPtr);
    }
    TkPathFree(surfacePtr->ctx);
    ckfree(surfacePtr->token);
    ckfree((char *)surfacePtr);
}

/* @@@ TODO: should we have a group item? */

static const char *surfaceItemCmds[] = {
    "circle", "ellipse", "path",
    "image", "line", "polyline",
    "polygon", "rect", "text",
    (char *)NULL
};

enum {
    kPathSurfaceItemCircle = 0L,
    kPathSurfaceItemEllipse,
    kPathSurfaceItemPath,
    kPathSurfaceItemPimage,
    kPathSurfaceItemPline,
    kPathSurfaceItemPolyline,
    kPathSurfaceItemPpolygon,
    kPathSurfaceItemPrect,
    kPathSurfaceItemPtext
};

static int
SurfaceCreateObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    InterpData *dataPtr = (InterpData *) clientData;
    int index;
    int result = TCL_OK;

    if(objc < 3) {
        Tcl_WrongNumArgs(interp, 2, objv, "type ?arg arg...?");
        return TCL_ERROR;
    }
    if(Tcl_GetIndexFromObj(interp, objv[2], surfaceItemCmds, "type", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }

    switch (index) {
    case kPathSurfaceItemCircle:
    case kPathSurfaceItemEllipse:{
        result = SurfaceCreateEllipse(interp, dataPtr, surfacePtr,
            index, objc, objv);
        break;
    }
    case kPathSurfaceItemPath:{
        result = SurfaceCreatePath(interp, dataPtr, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceItemPimage:{
        result = SurfaceCreatePimage(interp, dataPtr, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceItemPline:{
        result = SurfaceCreatePline(interp, dataPtr, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceItemPolyline:
    case kPathSurfaceItemPpolygon:{
        result = SurfaceCreatePpoly(interp, dataPtr, surfacePtr,
            index, objc, objv);
        break;
    }
    case kPathSurfaceItemPrect:{
        result = SurfaceCreatePrect(interp, dataPtr, surfacePtr, objc, objv);
        break;
    }
    case kPathSurfaceItemPtext:{
        result = SurfaceCreatePtext(interp, dataPtr, surfacePtr, objc, objv);
        break;
    }
    }
    return result;
}

TK_PATH_STYLE_CUSTOM_OPTION_RECORDS
#define TK_PATH_OPTION_SPEC_R(typeName)                \
    {TK_OPTION_DOUBLE, "-r", (char *) NULL, (char *) NULL,  \
    "0.0", -1, Tk_Offset(typeName, rx), 0, 0, 0}
#define TK_PATH_OPTION_SPEC_RX(typeName)                \
    {TK_OPTION_DOUBLE, "-rx", (char *) NULL, (char *) NULL, \
    "0.0", -1, Tk_Offset(typeName, rx), 0, 0, 0}
#define TK_PATH_OPTION_SPEC_RY(typeName)                \
    {TK_OPTION_DOUBLE, "-ry", (char *) NULL, (char *) NULL, \
    "0.0", -1, Tk_Offset(typeName, ry), 0, 0, 0}
    typedef struct SurfGenericItem {
    Tcl_Obj *styleObj;
    Tk_PathStyle style;
    TkPathArrowDescr startarrow;
    TkPathArrowDescr endarrow;
} SurfGenericItem;

static int
GetPointCoords(
    Tcl_Interp * interp,
    double *pointPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    if((objc == 1) || (objc == 2)) {
    double x, y;

        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 2) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coords: expected 2", -1));
                return TCL_ERROR;
            }
        }
        if((Tcl_GetDoubleFromObj(interp, objv[0], &x) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[1], &y) != TCL_OK)) {
            return TCL_ERROR;
        }
        pointPtr[0] = x;
        pointPtr[1] = y;
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coords: expected 2", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
GetTwoPointsCoords(
    Tcl_Interp * interp,
    double *pointsPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    if((objc == 1) || (objc == 4)) {
    double x1, y1, x2, y2;

        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 4) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coords: expected 4", -1));
                return TCL_ERROR;
            }
        }
        if((Tcl_GetDoubleFromObj(interp, objv[0], &x1) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[1], &y1) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[2], &x2) != TCL_OK)
            || (Tcl_GetDoubleFromObj(interp, objv[3], &y2) != TCL_OK)) {
            return TCL_ERROR;
        }
        pointsPtr[0] = x1;
        pointsPtr[1] = y1;
        pointsPtr[2] = x2;
        pointsPtr[3] = y2;
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coords: expected 4", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

static int
MakePolyAtoms(
    Tcl_Interp * interp,
    int closed,
    int objc,
    Tcl_Obj * const objv[],
    TkPathAtom ** atomPtrPtr)
{
    TkPathAtom *atomPtr = NULL;

    if(objc == 1) {
        if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                (Tcl_Obj ***) & objv) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if(objc & 1) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coords: expected an even number", -1));
        return TCL_ERROR;
    } else if(objc < 4) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coords: expected at least 4", -1));
        return TCL_ERROR;
    } else {
    int i;
    double x, y;
    double firstX = 0.0, firstY = 0.0;
    TkPathAtom *firstAtomPtr = NULL;

        for(i = 0; i < objc; i += 2) {
            if((Tcl_GetDoubleFromObj(interp, objv[i], &x) != TCL_OK)
                || (Tcl_GetDoubleFromObj(interp, objv[i + 1], &y) != TCL_OK)) {
                TkPathFreeAtoms(atomPtr);
                return TCL_ERROR;
            }
            if(i == 0) {
                firstX = x;
                firstY = y;
                atomPtr = TkPathNewMoveToAtom(x, y);
                firstAtomPtr = atomPtr;
            } else {
                atomPtr->nextPtr = TkPathNewLineToAtom(x, y);
                atomPtr = atomPtr->nextPtr;
            }
        }
        if(closed) {
            atomPtr->nextPtr = TkPathNewCloseAtom(firstX, firstY);
        }
        *atomPtrPtr = firstAtomPtr;
    }
    return TCL_OK;
}

static int
GetFirstOptionIndex(
    int objc,
    Tcl_Obj * const objv[])
{
    int i;

    for(i = 1; i < objc; i++) {
    char *arg = Tcl_GetString(objv[i]);
        if((arg[0] == '-') && (arg[1] >= 'a') && (arg[1] <= 'z')) {
            break;
        }
    }
    return i;
}

static int
SurfaceParseOptions(
    Tcl_Interp * interp,
    char *recordPtr,
    Tk_OptionTable table,
    int objc,
    Tcl_Obj * const objv[])
{
    Tk_Window tkwin = Tk_MainWindow(interp);

    if(Tk_InitOptions(interp, recordPtr, table, tkwin) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tk_SetOptions(interp, recordPtr, table,
            objc, objv, tkwin, NULL, NULL) != TCL_OK) {
        Tk_FreeConfigOptions(recordPtr, table, tkwin);
        return TCL_ERROR;
    }
    return TCL_OK;
}

typedef struct SurfEllipseItem {
    Tcl_Obj *styleObj;
    Tk_PathStyle style;
    double rx, ry;
} SurfEllipseItem;

TK_PATH_OPTION_STRING_TABLES_FILL
    TK_PATH_OPTION_STRING_TABLES_STROKE
    static Tk_OptionSpec circleOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfEllipseItem, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfEllipseItem, "black"),
    TK_PATH_OPTION_SPEC_R(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec ellipseOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfEllipseItem, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfEllipseItem, "black"),
    TK_PATH_OPTION_SPEC_RX(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_RY(SurfEllipseItem),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreateEllipse(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int type,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    int i;
    double center[2];
    TkPathAtom *atomPtr;
    TkEllipseAtom ellAtom;
    TkPathRect bbox;
    SurfEllipseItem ellipse;
    Tk_PathStyle *style = &ellipse.style;
    Tk_PathStyle mergedStyle;
    int result = TCL_OK;

    memset(&ellipse, 0, sizeof(ellipse));
    ellipse.styleObj = NULL;
    i = GetFirstOptionIndex(objc, objv);
    TkPathInitStyle(style);
    if(GetPointCoords(interp, center, i - 3, objv + 3) != TCL_OK) {
        goto bail;
    }
    if(SurfaceParseOptions(interp, (char *)&ellipse,
            (type == kPathSurfaceItemCircle) ?
            dataPtr->optionTableCircle :
            dataPtr->optionTableEllipse, objc - i, objv + i) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(style->fillObj != NULL) {
        style->fill = TkPathGetPathColorStatic(interp,
            Tk_MainWindow(interp), style->fillObj);
        if(style->fill == NULL) {
            result = TCL_ERROR;
            goto bail;
        }
    }

    /*
     * NB: We *copy* the style for temp usage.
     *     Only values and pointers are copied so we shall not free this style.
     */
    mergedStyle = ellipse.style;
    if(TkPathStyleMergeStyleStatic(interp, ellipse.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    ellipse.rx = MAX(0.0, ellipse.rx);
    ellipse.ry = MAX(0.0, ellipse.ry);
    atomPtr = (TkPathAtom *) & ellAtom;
    atomPtr->nextPtr = NULL;
    atomPtr->type = TK_PATH_ATOM_ELLIPSE;
    ellAtom.cx = center[0];
    ellAtom.cy = center[1];
    ellAtom.rx = ellipse.rx;
    ellAtom.ry = (type == kPathSurfaceItemCircle) ? ellipse.rx : ellipse.ry;
    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    if(TkPathMakePath(context, atomPtr, &mergedStyle) != TCL_OK) {
        TkPathRestoreState(context);
        result = TCL_ERROR;
        goto bail;
    }
    bbox = TkPathGetTotalBbox(atomPtr, &mergedStyle);
    TkPathPaintPath(context, atomPtr, &mergedStyle, &bbox);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(&ellipse.style);
    Tk_FreeConfigOptions((char *)&ellipse,
        (type == kPathSurfaceItemCircle) ?
        dataPtr->optionTableCircle :
        dataPtr->optionTableEllipse, Tk_MainWindow(interp));
    return result;
}

static Tk_OptionSpec pathOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfGenericItem, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfGenericItem, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePath(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    TkPathAtom *atomPtr = NULL;
    TkPathRect bbox;
    SurfGenericItem item;
    Tk_PathStyle *style = &item.style;
    Tk_PathStyle mergedStyle;
    int len;
    int result = TCL_OK;

    memset(&item, 0, sizeof(item));
    item.styleObj = NULL;
    TkPathInitStyle(&item.style);
    TkPathArrowDescrInit(&item.startarrow);
    TkPathArrowDescrInit(&item.endarrow);
    if(TkPathParseToAtoms(interp, objv[3], &atomPtr, &len) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&item, dataPtr->optionTablePath,
            objc - 4, objv + 4) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(style->fillObj != NULL) {
        style->fill = TkPathGetPathColorStatic(interp,
            Tk_MainWindow(interp), style->fillObj);
        if(style->fill == NULL) {
            result = TCL_ERROR;
            goto bail;
        }
    }
    mergedStyle = item.style;
    if(TkPathStyleMergeStyleStatic(interp, item.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    if(TkPathMakePath(context, atomPtr, &mergedStyle) != TCL_OK) {
        TkPathRestoreState(context);
        result = TCL_ERROR;
        goto bail;
    }
    bbox = TkPathGetTotalBbox(atomPtr, &mergedStyle);
    TkPathPaintPath(context, atomPtr, &mergedStyle, &bbox);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(style);
    TkPathFreeAtoms(atomPtr);
    TkPathFreeArrow(&item.startarrow);
    TkPathFreeArrow(&item.endarrow);
    Tk_FreeConfigOptions((char *)&item, dataPtr->optionTablePath,
        Tk_MainWindow(interp));
    return result;
}

typedef struct SurfPimageItem {
    char *imageName;
    double height;
    double width;
    TkPathMatrix *matrixPtr;
    Tcl_Obj *styleObj;         /* We only use matrixPtr from style. */
} SurfPimageItem;

static Tk_OptionSpec pimageOptionSpecs[] = {
    {TK_OPTION_DOUBLE, "-height", (char *)NULL, (char *)NULL,
        "0", -1, Tk_Offset(SurfPimageItem, height), 0, 0, 0},
    {TK_OPTION_CUSTOM, "-matrix", (char *)NULL, (char *)NULL,
            (char *)NULL, -1, Tk_Offset(SurfPimageItem, matrixPtr),
        TK_OPTION_NULL_OK, (ClientData) & matrixCO, 0},
    {TK_OPTION_STRING, "-image", (char *)NULL, (char *)NULL,
        "", -1, Tk_Offset(SurfPimageItem, imageName), TK_OPTION_NULL_OK, 0,
            0},
    {TK_OPTION_STRING, "-style", (char *)NULL, (char *)NULL,
        "", Tk_Offset(SurfPimageItem, styleObj), -1, TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_DOUBLE, "-width", (char *)NULL, (char *)NULL,
        "0", -1, Tk_Offset(SurfPimageItem, width), 0, 0, 0},
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePimage(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    SurfPimageItem item;
    Tk_Image image;
    Tk_PhotoHandle photo;
    Tk_PathStyle style;
    double point[2];
    int i;
    int result = TCL_OK;

    memset(&item, 0, sizeof(item));
    item.imageName = NULL;
    item.matrixPtr = NULL;
    item.styleObj = NULL;
    TkPathInitStyle(&style);
    i = GetFirstOptionIndex(objc, objv);
    if(GetPointCoords(interp, point, i - 3, objv + 3) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&item, dataPtr->optionTablePimage,
            objc - i, objv + i) != TCL_OK) {
        return TCL_ERROR;
    }
    style.matrixPtr = item.matrixPtr;
    if(TkPathStyleMergeStyleStatic(interp, item.styleObj, &style, 0)
        != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(item.imageName != NULL) {
        photo = Tk_FindPhoto(interp, item.imageName);
        if(photo == NULL) {
            Tcl_SetObjResult(interp,
                Tcl_NewStringObj("no photo with the given name", -1));
            result = TCL_ERROR;
            goto bail;
        }
        image = Tk_GetImage(interp, Tk_MainWindow(interp),
            item.imageName, NULL, (ClientData) NULL);
        TkPathSaveState(context);
        TkPathPushTMatrix(context, style.matrixPtr);
        TkPathImage(context, image, photo, point[0], point[1],
            item.width, item.height, style.fillOpacity, NULL, 0.0, 99, NULL);
        Tk_FreeImage(image);
        TkPathRestoreState(context);
    }

  bail:
    Tk_FreeConfigOptions((char *)&item, dataPtr->optionTablePimage,
        Tk_MainWindow(interp));
    return result;
}

static Tk_OptionSpec plineOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfGenericItem, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePline(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    int i;
    TkPathRect bbox;
    SurfGenericItem item;
    TkPathAtom *atomPtr = NULL;
    Tk_PathStyle mergedStyle;
    double points[4];
    TkPathPoint pf, pl, newp;
    int result = TCL_OK;

    memset(&item, 0, sizeof(item));
    item.styleObj = NULL;
    i = GetFirstOptionIndex(objc, objv);
    TkPathInitStyle(&item.style);
    TkPathArrowDescrInit(&item.startarrow);
    TkPathArrowDescrInit(&item.endarrow);
    if(GetTwoPointsCoords(interp, points, i - 3, objv + 3) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&item, dataPtr->optionTablePline,
            objc - i, objv + i) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    mergedStyle = item.style;
    if(TkPathStyleMergeStyleStatic(interp, item.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    pf.x = points[0];
    pf.y = points[1];
    pl.x = points[2];
    pl.y = points[3];
    TkPathPreconfigureArrow(&pf, &item.startarrow);
    TkPathPreconfigureArrow(&pl, &item.endarrow);
    newp = TkPathConfigureArrow(pf, pl, &item.startarrow, &mergedStyle,
        mergedStyle.fill == NULL);
    points[0] = newp.x;
    points[1] = newp.y;
    newp = TkPathConfigureArrow(pl, pf, &item.endarrow, &mergedStyle,
        mergedStyle.fill == NULL);
    points[2] = newp.x;
    points[3] = newp.y;
    atomPtr = TkPathNewMoveToAtom(points[0], points[1]);
    atomPtr->nextPtr = TkPathNewLineToAtom(points[2], points[3]);
    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    if(TkPathMakePath(context, atomPtr, &mergedStyle) != TCL_OK) {
        TkPathRestoreState(context);
        result = TCL_ERROR;
        goto bail;
    }
    bbox = TkPathGetTotalBbox(atomPtr, &mergedStyle);
    TkPathPaintPath(context, atomPtr, &mergedStyle, &bbox);
    TkPathPaintArrow(context, &item.startarrow, &mergedStyle, &bbox);
    TkPathPaintArrow(context, &item.endarrow, &mergedStyle, &bbox);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(&item.style);
    TkPathFreeAtoms(atomPtr);
    TkPathFreeArrow(&item.startarrow);
    TkPathFreeArrow(&item.endarrow);
    Tk_FreeConfigOptions((char *)&item, dataPtr->optionTablePline,
        Tk_MainWindow(interp));
    return result;
}

static Tk_OptionSpec polylineOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfGenericItem, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_END
};

static Tk_OptionSpec ppolygonOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfGenericItem, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfGenericItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfGenericItem, "black"),
    TK_PATH_OPTION_SPEC_STARTARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_ENDARROW_GRP(SurfGenericItem),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePpoly(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int type,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    int i;
    TkPathRect bbox;
    SurfGenericItem item;
    Tk_PathStyle *style = &item.style;
    Tk_PathStyle mergedStyle;
    TkPathAtom *atomPtr = NULL;
    int result = TCL_OK;

    memset(&item, 0, sizeof(item));
    item.styleObj = NULL;
    i = GetFirstOptionIndex(objc, objv);
    TkPathInitStyle(style);
    TkPathArrowDescrInit(&item.startarrow);
    TkPathArrowDescrInit(&item.endarrow);
    if(MakePolyAtoms(interp, (type == kPathSurfaceItemPolyline) ? 0 : 1,
            i - 3, objv + 3, &atomPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&item,
            (type == kPathSurfaceItemPolyline) ?
            dataPtr->optionTablePolyline :
            dataPtr->optionTablePpolygon, objc - i, objv + i) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(style->fillObj != NULL) {
        style->fill = TkPathGetPathColorStatic(interp,
            Tk_MainWindow(interp), style->fillObj);
        if(style->fill == NULL) {
            result = TCL_ERROR;
            goto bail;
        }
    }
    mergedStyle = item.style;
    if(TkPathStyleMergeStyleStatic(interp, item.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    if(TkPathMakePath(context, atomPtr, &mergedStyle) != TCL_OK) {
        TkPathRestoreState(context);
        result = TCL_ERROR;
        goto bail;
    }
    bbox = TkPathGetTotalBbox(atomPtr, &mergedStyle);
    TkPathPaintPath(context, atomPtr, &mergedStyle, &bbox);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(style);
    TkPathFreeAtoms(atomPtr);
    TkPathFreeArrow(&item.startarrow);
    TkPathFreeArrow(&item.endarrow);
    Tk_FreeConfigOptions((char *)&item,
        (type == kPathSurfaceItemPolyline) ?
        dataPtr->optionTablePolyline :
        dataPtr->optionTablePpolygon, Tk_MainWindow(interp));
    return result;
}

typedef struct SurfPrectItem {
    Tcl_Obj *styleObj;
    Tk_PathStyle style;
    double rx, ry;
} SurfPrectItem;

static Tk_OptionSpec prectOptionSpecs[] = {
    TK_PATH_OPTION_SPEC_STYLENAME(SurfPrectItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfPrectItem, ""),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfPrectItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfPrectItem, "black"),
    TK_PATH_OPTION_SPEC_RX(SurfPrectItem),
    TK_PATH_OPTION_SPEC_RY(SurfPrectItem),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePrect(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    int i;
    SurfPrectItem prect;
    Tk_PathStyle *style = &prect.style;
    Tk_PathStyle mergedStyle;
    TkPathRect bbox;
    TkPathAtom *atomPtr = NULL;
    double points[4];
    int result = TCL_OK;

    memset(&prect, 0, sizeof(prect));
    prect.styleObj = NULL;
    i = GetFirstOptionIndex(objc, objv);
    TkPathInitStyle(style);
    if(GetTwoPointsCoords(interp, points, i - 3, objv + 3) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&prect, dataPtr->optionTablePrect,
            objc - i, objv + i) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(style->fillObj != NULL) {
        style->fill = TkPathGetPathColorStatic(interp,
            Tk_MainWindow(interp), style->fillObj);
        if(style->fill == NULL) {
            result = TCL_ERROR;
            goto bail;
        }
    }
    mergedStyle = prect.style;
    if(TkPathStyleMergeStyleStatic(interp, prect.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    prect.rx = MAX(0.0, prect.rx);
    prect.ry = MAX(0.0, prect.ry);
    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    TkPathMakePrectAtoms(points, prect.rx, prect.ry, &atomPtr);
    if(TkPathMakePath(context, atomPtr, &mergedStyle) != TCL_OK) {
        TkPathRestoreState(context);
        result = TCL_ERROR;
        goto bail;
    }
    bbox = TkPathGetTotalBbox(atomPtr, &mergedStyle);
    TkPathPaintPath(context, atomPtr, &mergedStyle, &bbox);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(&prect.style);
    TkPathFreeAtoms(atomPtr);
    Tk_FreeConfigOptions((char *)&prect, dataPtr->optionTablePrect,
        Tk_MainWindow(interp));
    return result;
}

typedef struct SurfPtextItem {
    Tcl_Obj *styleObj;
    Tk_PathStyle style;
    Tk_PathTextStyle textStyle;
    int textAnchor;
    int fillOverStroke;
    double x;
    double y;
    char *utf8;                /* The actual text to display; UTF-8 */
} SurfPtextItem;

static const char *textAnchorST[] = {
    "start", "middle", "end", "n", "w", "s", "e",
    "nw", "ne", "sw", "se", "c", (char *)NULL
};

static const char *fontWeightST[] = {
    "normal", "bold", NULL
};

static const char *fontSlantST[] = {
    "normal", "italic", "oblique", NULL
};

static Tk_OptionSpec ptextOptionSpecs[] = {
    {TK_OPTION_STRING, "-fontfamily", (char *)NULL, (char *)NULL,
            "Helvetica", -1, Tk_Offset(SurfPtextItem, textStyle.fontFamily),
        TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_DOUBLE, "-fontsize", (char *)NULL, (char *)NULL,
        "12.0", -1, Tk_Offset(SurfPtextItem, textStyle.fontSize), 0, 0, 0},
    {TK_OPTION_STRING, "-text", (char *)NULL, (char *)NULL,
            "", -1, Tk_Offset(SurfPtextItem, utf8),
        TK_OPTION_NULL_OK, 0, 0},
    {TK_OPTION_STRING_TABLE, "-textanchor", (char *)NULL, (char *)NULL,
            "start", -1, Tk_Offset(SurfPtextItem, textAnchor),
        0, (ClientData) textAnchorST, 0},
    {TK_OPTION_STRING_TABLE, "-fontweight", (char *)NULL, (char *)NULL,
            "normal", -1, Tk_Offset(SurfPtextItem, textStyle.fontWeight),
        0, (ClientData) fontWeightST, 0},
    {TK_OPTION_STRING_TABLE, "-fontslant", (char *)NULL, (char *)NULL,
            "normal", -1, Tk_Offset(SurfPtextItem, textStyle.fontSlant),
        0, (ClientData) fontSlantST, 0},
    {TK_OPTION_BOOLEAN, "-filloverstroke", (char *)NULL, (char *)NULL,
            0, -1, Tk_Offset(SurfPtextItem, fillOverStroke),
        0, 0, 0},
    TK_PATH_OPTION_SPEC_STYLENAME(SurfPtextItem),
    TK_PATH_OPTION_SPEC_STYLE_FILL(SurfPtextItem, "black"),
    TK_PATH_OPTION_SPEC_STYLE_MATRIX(SurfPtextItem),
    TK_PATH_OPTION_SPEC_STYLE_STROKE(SurfPtextItem, ""),
    TK_PATH_OPTION_SPEC_END
};

static int
SurfaceCreatePtext(
    Tcl_Interp * interp,
    InterpData * dataPtr,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    TkPathContext context = surfacePtr->ctx;
    int i;
    double point[2];
    SurfPtextItem item;
    Tk_PathStyle *style = &item.style;
    Tk_PathStyle mergedStyle;
    TkPathRect r;
    void *custom = NULL;
    int result = TCL_OK;
    double width, height, bheight;

    if(dataPtr->tkwin == NULL) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("no main window", -1));
        return TCL_ERROR;
    }
    memset(&item, 0, sizeof(item));
    item.styleObj = NULL;
    item.textAnchor = TK_PATH_TEXTANCHOR_Start;
    item.utf8 = NULL;
    item.textStyle.fontFamily = NULL;
    i = GetFirstOptionIndex(objc, objv);
    TkPathInitStyle(&item.style);
    if(GetPointCoords(interp, point, i - 3, objv + 3) != TCL_OK) {
        return TCL_ERROR;
    }
    if(SurfaceParseOptions(interp, (char *)&item, dataPtr->optionTablePtext,
            objc - i, objv + i) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(style->fillObj != NULL) {
        style->fill = TkPathGetPathColorStatic(interp, dataPtr->tkwin,
            style->fillObj);
        if(style->fill == NULL) {
            result = TCL_ERROR;
            goto bail;
        }
    }
    if(TkPathTextConfig(interp, &item.textStyle, item.utf8, &custom) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    mergedStyle = item.style;
    if(TkPathStyleMergeStyleStatic(interp, item.styleObj,
            &mergedStyle, 0) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    r = TkPathTextMeasureBbox(Tk_Display(dataPtr->tkwin), &item.textStyle,
        item.utf8, NULL, custom);
    width = r.x2 - r.x1;
    height = r.y2 - r.y1;
    bheight = r.y2 + mergedStyle.strokeWidth;

    switch (item.textAnchor) {
    case TK_PATH_TEXTANCHOR_Start:
    case TK_PATH_TEXTANCHOR_W:
    case TK_PATH_TEXTANCHOR_NW:
    case TK_PATH_TEXTANCHOR_SW:
        break;
    case TK_PATH_TEXTANCHOR_Middle:
    case TK_PATH_TEXTANCHOR_N:
    case TK_PATH_TEXTANCHOR_S:
    case TK_PATH_TEXTANCHOR_C:
        point[0] -= width / 2;
        break;
    case TK_PATH_TEXTANCHOR_End:
    case TK_PATH_TEXTANCHOR_E:
    case TK_PATH_TEXTANCHOR_NE:
    case TK_PATH_TEXTANCHOR_SE:
        point[0] -= width;
        break;
    default:
        break;
    }

    switch (item.textAnchor) {
    case TK_PATH_TEXTANCHOR_Start:
    case TK_PATH_TEXTANCHOR_Middle:
    case TK_PATH_TEXTANCHOR_End:
        point[1] += r.y1;
        break;
    case TK_PATH_TEXTANCHOR_N:
    case TK_PATH_TEXTANCHOR_NW:
    case TK_PATH_TEXTANCHOR_NE:
        break;
    case TK_PATH_TEXTANCHOR_W:
    case TK_PATH_TEXTANCHOR_E:
    case TK_PATH_TEXTANCHOR_C:
        point[1] += height / 2;
        break;
    case TK_PATH_TEXTANCHOR_S:
    case TK_PATH_TEXTANCHOR_SW:
    case TK_PATH_TEXTANCHOR_SE:
        point[1] += height;
        break;
    default:
        break;
    }

    TkPathSaveState(context);
    TkPathPushTMatrix(context, mergedStyle.matrixPtr);
    TkPathBeginPath(context, &mergedStyle);
    TkPathTextDraw(context, &mergedStyle, &item.textStyle,
        point[0], point[1] - bheight, item.fillOverStroke, item.utf8, custom);
    TkPathEndPath(context);
    TkPathTextFree(&item.textStyle, custom);
    TkPathRestoreState(context);

  bail:
    TkPathDeleteStyle(style);
    Tk_FreeConfigOptions((char *)&item, dataPtr->optionTablePtext,
        dataPtr->tkwin);
    return result;
}

static int
SurfaceEraseObjCmd(
    Tcl_Interp * interp,
    PathSurface * surfacePtr,
    int objc,
    Tcl_Obj * const objv[])
{
    double x, y, width, height;

    if(objc != 6) {
        Tcl_WrongNumArgs(interp, 2, objv, "x y width height");
        return TCL_ERROR;
    }
    if((Tcl_GetDoubleFromObj(interp, objv[2], &x) != TCL_OK) ||
        (Tcl_GetDoubleFromObj(interp, objv[3], &y) != TCL_OK) ||
        (Tcl_GetDoubleFromObj(interp, objv[4], &width) != TCL_OK) ||
        (Tcl_GetDoubleFromObj(interp, objv[5], &height) != TCL_OK)) {
        return TCL_ERROR;
    }
    TkPathSurfaceErase(surfacePtr->ctx, x, y, width, height);
    return TCL_OK;
}

int
TkPathSurfaceInit(
    Tcl_Interp * interp)
{
InterpData *dataPtr = (InterpData *) ckalloc(sizeof(InterpData));

    Tcl_InitHashTable(&dataPtr->surfaceHash, TCL_STRING_KEYS);
    dataPtr->optionTableCircle =
        Tk_CreateOptionTable(interp, circleOptionSpecs);
    dataPtr->optionTableEllipse =
        Tk_CreateOptionTable(interp, ellipseOptionSpecs);
    dataPtr->optionTablePath = Tk_CreateOptionTable(interp, pathOptionSpecs);
    dataPtr->optionTablePimage =
        Tk_CreateOptionTable(interp, pimageOptionSpecs);
    dataPtr->optionTablePline = Tk_CreateOptionTable(interp, plineOptionSpecs);
    dataPtr->optionTablePolyline =
        Tk_CreateOptionTable(interp, polylineOptionSpecs);
    dataPtr->optionTablePpolygon =
        Tk_CreateOptionTable(interp, ppolygonOptionSpecs);
    dataPtr->optionTablePrect = Tk_CreateOptionTable(interp, prectOptionSpecs);
    dataPtr->optionTablePtext = Tk_CreateOptionTable(interp, ptextOptionSpecs);
    dataPtr->uid = 0;
    dataPtr->tkwin = Tk_MainWindow(interp);
    if(dataPtr->tkwin != NULL) {
        Tk_CreateEventHandler(dataPtr->tkwin, StructureNotifyMask,
            StaticSurfaceEventProc, dataPtr);
    }
    Tcl_CreateObjCommand(interp, "::path::surface",
        StaticSurfaceObjCmd, (ClientData) dataPtr,
        (Tcl_CmdDeleteProc *) StaticSurfaceObjCmdDeleted);
    return TCL_OK;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPathUtil.c.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoPathUtil.h --
 *
 *    This file contains support functions for tkpath.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

//#include <float.h>
#include "tkoPath.h"

/*
 * For wider strokes we must make a more detailed analysis
 * when doing hit tests and area tests.
 */
#define kPathStrokeThicknessLimit     4.0

#define MAX_NUM_STATIC_SEGMENTS  2000

typedef struct CentralArcPars {
    double cx;
    double cy;
    double rx;
    double ry;
    double theta1;
    double dtheta;
    double phi;
} CentralArcPars;

static void MakeSubPathSegments(
    TkPathAtom ** atomPtrPtr,
    double *polyPtr,
    int *numPointsPtr,
    int *numStrokesPtr,
    TkPathMatrix * matrixPtr);
static int SubPathToArea(
    Tk_PathStyle * stylePtr,
    double *polyPtr,
    int numPoints,
    int numStrokes,
    double *rectPtr,
    int inside);
static void PathApplyTMatrix(
    TkPathMatrix * m,
    double *x,
    double *y);
static void PathApplyTMatrixToPoint(
    TkPathMatrix * m,
    double in[2],
    double out[2]);
static void PathInverseTMatrix(
    TkPathMatrix * m,
    TkPathMatrix * mi);
static int PathPolyLineToArea(
    double *polyPtr,
    int numPoints,
    double *rectPtr);
static double PathThickPolygonToPoint(
    int joinStyle,
    int capStyle,
    double width,
    int isclosed,
    double *polyPtr,
    int numPoints,
    double *pointPtr);
static double PathPolygonToPointEx(
    double *polyPtr,
    int numPoints,
    double *pointPtr,
    int *intersectionsPtr,
    int *nonzerorulePtr);
static int IsPathRectEmpty(
    TkPathRect * r);

/*
 *--------------------------------------------------------------
 *
 * TkPathMakePrectAtoms --
 *
 *    Makes the path atoms for a rounded rectangle, prect.
 *
 * Results:
 *    None. Path atoms in atomPtrPtr.
 *
 * Side effects:
 *    Path atom memory allocated.
 *
 *--------------------------------------------------------------
 */

void
TkPathMakePrectAtoms(
    double *pointsPtr,
    double rx,
    double ry,
    TkPathAtom ** atomPtrPtr)
{
    TkPathAtom *atomPtr = NULL;
    TkPathAtom *firstAtomPtr = NULL;
    int round = 1;
    double epsilon = 1e-6;
    double x = MIN(pointsPtr[0], pointsPtr[2]);
    double y = MIN(pointsPtr[1], pointsPtr[3]);
    double width = fabs(pointsPtr[0] - pointsPtr[2]);
    double height = fabs(pointsPtr[1] - pointsPtr[3]);

    /* If only one of rx or ry is zero this implies that both shall be nonzero. */
    if(rx < epsilon && ry < epsilon) {
        round = 0;
    } else if(rx < epsilon) {
        rx = ry;
    } else if(ry < epsilon) {
        ry = rx;
    }
    if(round) {

        /* There are certain constraints on rx and ry. */
        rx = MIN(rx, width / 2.0);
        ry = MIN(ry, height / 2.0);

        atomPtr = TkPathNewMoveToAtom(x + rx, y);
        firstAtomPtr = atomPtr;
        atomPtr->nextPtr = TkPathNewLineToAtom(x + width - rx, y);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr =
            TkPathNewArcAtom(rx, ry, 0.0, 0, 1, x + width, y + ry);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr = TkPathNewLineToAtom(x + width, y + height - ry);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr =
            TkPathNewArcAtom(rx, ry, 0.0, 0, 1, x + width - rx, y + height);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr = TkPathNewLineToAtom(x + rx, y + height);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr =
            TkPathNewArcAtom(rx, ry, 0.0, 0, 1, x, y + height - ry);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr = TkPathNewLineToAtom(x, y + ry);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr = TkPathNewArcAtom(rx, ry, 0.0, 0, 1, x + rx, y);
        atomPtr = atomPtr->nextPtr;
        atomPtr->nextPtr = TkPathNewCloseAtom(x, y);
        *atomPtrPtr = firstAtomPtr;
    } else {
        atomPtr = TkPathNewRectAtom(pointsPtr);
        *atomPtrPtr = atomPtr;
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathDrawPath --
 *
 *    This procedure is invoked to draw a line item in a given
 *    drawable.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    ItemPtr is drawn in drawable using the transformation
 *    information in canvas.
 *
 *--------------------------------------------------------------
 */

void
TkPathDrawPath(
    TkPathContext context,     /* Context. */
    TkPathAtom * atomPtr,      /* The actual path as a linked list
                                * of TkPathAtoms. */
    Tk_PathStyle * stylePtr,   /* The paths style. */
    TkPathMatrix * mPtr,       /* Typically used for canvas offsets. */
    TkPathRect * bboxPtr)
{              /* The bare (untransformed) bounding box
                * (assuming zero stroke width) */
    /*
     * Define the path in the drawable using the path drawing functions.
     * Any transform matrix need to be considered and canvas drawable
     * offset must always be taken into account. Note the order!
     */

    if(mPtr != NULL) {
        TkPathPushTMatrix(context, mPtr);
    }
    if(stylePtr->matrixPtr != NULL) {
        TkPathPushTMatrix(context, stylePtr->matrixPtr);
    }
    if(TkPathMakePath(context, atomPtr, stylePtr) != TCL_OK) {
        return;
    }
    TkPathPaintPath(context, atomPtr, stylePtr, bboxPtr);
}

/*
 *--------------------------------------------------------------
 *
 * TkPathPaintPath --
 *
 *    This procedure is invoked to paint a path in a given context.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Any path defined in the context is painted.
 *
 *--------------------------------------------------------------
 */

void
TkPathPaintPath(
    TkPathContext context,
    TkPathAtom * atomPtr,      /* The actual path as a linked list
                                * of TkPathAtoms. */
    Tk_PathStyle * stylePtr,   /* The paths style. */
    TkPathRect * bboxPtr)
{
TkPathGradientMaster *gradientPtr =
    GetGradientMasterFromPathColor(stylePtr->fill);
    if(gradientPtr != NULL) {
        TkPathClipToPath(context, stylePtr->fillRule);
        TkPathGradientPaint(context, bboxPtr, gradientPtr, stylePtr->fillRule,
            stylePtr->fillOpacity);

        /* NB: Both CoreGraphics on MacOSX and Win32 GDI (and cairo from 1.0)
         *     clear the current path when setting clipping. Need therefore
         *     to redo the path.
         */
        if(TkPathDrawingDestroysPath()) {
            TkPathMakePath(context, atomPtr, stylePtr);
        }

        /* We shall remove the path clipping here! */
        TkPathReleaseClipToPath(context);
    }

    if((stylePtr->fill != NULL) && (stylePtr->fill->color != NULL)
        && (stylePtr->strokeColor != NULL)) {
        TkPathFillAndStroke(context, stylePtr);
    } else if((stylePtr->fill != NULL) && (stylePtr->fill->color != NULL)) {
        TkPathFill(context, stylePtr);
    } else if(stylePtr->strokeColor != NULL) {
        TkPathStroke(context, stylePtr);
    }
}

TkPathRect
TkPathGetTotalBbox(
    TkPathAtom * atomPtr,
    Tk_PathStyle * stylePtr)
{
TkPathRect bare, total;

    bare = TkPathGetGenericBarePathBbox(atomPtr);
    total = TkPathGetGenericPathTotalBboxFromBare(atomPtr, stylePtr, &bare);
    return total;
}

/* Return NULL on error and leave error message */

/*
 * @@@ OBSOLETE SOON!!!
 * As a temporary mean before trashing it we ignore gradients.
 */

TkPathColor *
TkPathNewPathColor(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Tcl_Obj * nameObj)
{
char *name;
TkPathColor *colorPtr;
XColor *color = NULL;

    name = Tcl_GetStringFromObj(nameObj, NULL);
    colorPtr = (TkPathColor *) ckalloc(sizeof(TkPathColor));
    colorPtr->color = NULL;
    colorPtr->gradientInstPtr = NULL;

    color = Tk_AllocColorFromObj(interp, tkwin, nameObj);
    if(color == NULL) {
char tmp[256];
        ckfree((char *)colorPtr);
        sprintf(tmp, "unrecognized color or gradient name \"%s\"", name);
        Tcl_SetObjResult(interp, Tcl_NewStringObj(tmp, -1));
        return NULL;
    }
    colorPtr->color = color;
    return colorPtr;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathGetPathColor --
 *
 *    Parses a string in nameObj to either a valid XColor or
 *      looks up a gradient name for the hash table tablePtr.
 *      Makes a new TkPathColor struct from a string value.
 *      Like Tk_GetImage() but for TkPathColor instead of Tk_Image.
 *
 * Results:
 *    Pointer to a TkPathColor struct or returns NULL on error
 *      and leaves an error message.
 *
 * Side effects:
 *    TkPathColor malloced if OK.
 *
 *--------------------------------------------------------------
 */

TkPathColor *
TkPathGetPathColor(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    Tcl_Obj * nameObj,
    Tcl_HashTable * tablePtr,
    TkPathGradientChangedProc * changeProc,
    ClientData clientData)
{
char *name;
TkPathColor *colorPtr;
XColor *color = NULL;
TkPathGradientInst *gradientInstPtr;

    name = Tcl_GetString(nameObj);
    colorPtr = (TkPathColor *) ckalloc(sizeof(TkPathColor));

    /*
     * Only one of them can be non NULL.
     */
    colorPtr->color = NULL;
    colorPtr->gradientInstPtr = NULL;

    gradientInstPtr =
        TkPathGetGradient(interp, name, tablePtr, changeProc, clientData);
    if(gradientInstPtr != NULL) {
        colorPtr->gradientInstPtr = gradientInstPtr;
    } else {
        Tcl_ResetResult(interp);
        color = Tk_AllocColorFromObj(interp, tkwin, nameObj);
        if(color == NULL) {
Tcl_Obj *resultObj;
            ckfree((char *)colorPtr);
            resultObj =
                Tcl_NewStringObj("unrecognized color or gradient name \"", -1);
            Tcl_AppendStringsToObj(resultObj, name, "\"", (char *)NULL);
            Tcl_SetObjResult(interp, resultObj);
            return NULL;
        }
        colorPtr->color = color;
    }
    return colorPtr;
}

void
TkPathFreePathColor(
    TkPathColor * colorPtr)
{
    if(colorPtr != NULL) {
        if(colorPtr->color != NULL) {
            Tk_FreeColor(colorPtr->color);
        } else if(colorPtr->gradientInstPtr != NULL) {
            TkPathFreeGradient(colorPtr->gradientInstPtr);
        }
        ckfree((char *)colorPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCopyBitsARGB, TkPathCopyBitsBGRA --
 *
 *    Copies bitmap data from these formats to RGBA.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

void
TkPathCopyBitsARGB(
    unsigned char *from,
    unsigned char *to,
    int width,
    int height,
    int bytesPerRow)
{
    unsigned char *src, *dst;
    int i, j;

    /* Copy XRGB to RGBX in one shot, alphas in a loop. */
    memcpy(to, from + 1, height * bytesPerRow - 1);

    for(i = 0; i < height; i++) {
        src = from + i * bytesPerRow;
        dst = to + i * bytesPerRow;
        /* @@@ Keep ARGB format in photo? */
        for(j = 0; j < width; j++, src += 4, dst += 4) {
            *(dst + 3) = *src;
        }
    }
}

void
TkPathCopyBitsBGRA(
    unsigned char *from,
    unsigned char *to,
    int width,
    int height,
    int bytesPerRow)
{
    unsigned char *src, *dst;
    int i, j;

    /* Copy BGRA -> RGBA */
    for(i = 0; i < height; i++) {
        src = from + i * bytesPerRow;
        dst = to + i * bytesPerRow;
        for(j = 0; j < width; j++, src += 4) {
            /* RED */
            *dst++ = *(src + 2);
            /* GREEN */
            *dst++ = *(src + 1);
            /* BLUE */
            *dst++ = *src;
            /* ALPHA */
            *dst++ = *(src + 3);
        }
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCopyBitsPremultipliedAlphaRGBA, TkPathCopyBitsPremultipliedAlphaARGB --
 *
 *    Copies bitmap data that have alpha premultiplied into a bitmap
 *    with "true" RGB values need for Tk_Photo. The source format is
 *    either RGBA or ARGB, but destination always RGBA used for photos.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

void
TkPathCopyBitsPremultipliedAlphaRGBA(
    unsigned char *from,
    unsigned char *to,
    int width,
    int height,
    int bytesPerRow)
{
    unsigned char *src, *dst, alpha;
    int i, j;

    /* Copy src RGBA with premulitplied alpha to "plain" RGBA. */
    for(i = 0; i < height; i++) {
        src = from + i * bytesPerRow;
        dst = to + i * bytesPerRow;
        for(j = 0; j < width; j++) {
            alpha = *(src + 3);
            if(alpha == 0xFF || alpha == 0x00) {
                memcpy(dst, src, 4);
                src += 4;
                dst += 4;
            } else {
                /* dst = 255*src/alpha */
                *dst++ = (*src++ * 255) / alpha;
                *dst++ = (*src++ * 255) / alpha;
                *dst++ = (*src++ * 255) / alpha;
                *dst++ = alpha;
                src++;
            }
        }
    }
}

/* UNTESTED! */
void
TkPathCopyBitsPremultipliedAlphaARGB(
    unsigned char *from,
    unsigned char *to,
    int width,
    int height,
    int bytesPerRow)
{
    unsigned char *src, *dst, alpha;
    int i, j;

    /* Copy src ARGB with premulitplied alpha to "plain" RGBA. */
    for(i = 0; i < height; i++) {
        src = from + i * bytesPerRow;
        dst = to + i * bytesPerRow;
        for(j = 0; j < width; j++) {
            alpha = *src;
            if(alpha == 0xFF || alpha == 0x00) {
                memcpy(dst, src + 1, 3);
                *(dst + 3) = alpha;
                src += 4;
                dst += 4;
            } else {
                /* dst = 255*src/alpha */
                *(dst + 3) = alpha;
                src++;
                *dst = ((*src << 8) - *src) / alpha;
                dst++, src++;
                *dst = ((*src << 8) - *src) / alpha;
                dst++, src++;
                *dst = ((*src << 8) - *src) / alpha;
                dst++, dst++, src++;
            }
        }
    }
}

void
TkPathCopyBitsPremultipliedAlphaBGRA(
    unsigned char *from,
    unsigned char *to,
    int width,
    int height,
    int bytesPerRow)
{
    unsigned char *src, *dst, alpha;
    int i, j;

    /* Copy src BGRA with premulitplied alpha to "plain" RGBA. */
    for(i = 0; i < height; i++) {
        src = from + i * bytesPerRow;
        dst = to + i * bytesPerRow;
        for(j = 0; j < width; j++, src += 4) {
            alpha = *(src + 3);
            if(alpha == 0xFF || alpha == 0x00) {
                /* RED */
                *dst++ = *(src + 2);
                /* GREEN */
                *dst++ = *(src + 1);
                /* BLUE */
                *dst++ = *src;
                /* ALPHA */
                *dst++ = *(src + 3);
            } else {
                /* dst = 255*src/alpha */
                /* RED */
                *dst++ = (*(src + 2) * 255) / alpha;
                /* GREEN */
                *dst++ = (*(src + 1) * 255) / alpha;
                /* BLUE */
                *dst++ = (*(src + 0) * 255) / alpha;
                /* ALPHA */
                *dst++ = alpha;
            }
        }
    }
}

/* from mozilla */
static double
CalcVectorAngle(
    double ux,
    double uy,
    double vx,
    double vy)
{
    double ta = atan2(uy, ux);
    double tb = atan2(vy, vx);
    if(tb >= ta) {
        return tb - ta;
    } else {
        return 2.0 * M_PI - (ta - tb);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathEndpointToCentralArcParameters
 *
 *    Conversion from endpoint to center parameterization.
 *    All angles in radians!
 *    From: http://www.w3.org/TR/2003/REC-SVG11-20030114
 *
 * Results:
 *    Arc specific return code.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathEndpointToCentralArcParameters(
    double x1,
    double y1,
    double x2,
    double y2,                 /* The endpoints. */
    double rx,
    double ry,                 /* Radius. */
    double phi,
    char largeArcFlag,
    char sweepFlag,
    double *cxPtr,
    double *cyPtr,             /* Out. */
    double *rxPtr,
    double *ryPtr,
    double *theta1Ptr,
    double *dthetaPtr)
{
    double sinPhi, cosPhi;
    double dx, dy;
    double x1dash, y1dash;
    double cxdash, cydash;
    double cx, cy;
    double numerator, root;
    double theta1, dtheta;

    /* 1. Treat out-of-range parameters as described in
     * http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
     *
     * If the endpoints (x1, y1) and (x2, y2) are identical, then this
     * is equivalent to omitting the elliptical arc segment entirely
     */
    if(fabs(x1 - x2) < DBL_EPSILON && fabs(y1 - y2) < DBL_EPSILON) {
        return TK_PATH_ARC_Skip;
    }

    /* If rx = 0 or ry = 0 then this arc is treated as a straight line
     * segment (a "lineto") joining the endpoints.
     */
    if(rx == 0.0f || ry == 0.0f) {
        return TK_PATH_ARC_Line;
    }

    /* If rx or ry have negative signs, these are dropped; the absolute
     * value is used instead.
     */
    if(rx < 0.0)
        rx = -rx;
    if(ry < 0.0)
        ry = -ry;

    if(largeArcFlag != 0)
        largeArcFlag = 1;
    if(sweepFlag != 0)
        sweepFlag = 1;

    /* 2. convert to center parameterization as shown in
     * http://www.w3.org/TR/SVG/implnote.html
     */
    sinPhi = sin(phi);
    cosPhi = cos(phi);
    dx = (x1 - x2) / 2.0;
    dy = (y1 - y2) / 2.0;
    x1dash = cosPhi * dx + sinPhi * dy;
    y1dash = -sinPhi * dx + cosPhi * dy;

    /* Compute cx' and cy'. */
    numerator =
        rx * rx * ry * ry - rx * rx * y1dash * y1dash -
        ry * ry * x1dash * x1dash;
    if(numerator < 0.0) {

        /* If rx , ry and are such that there is no solution (basically,
         * the ellipse is not big enough to reach from (x1, y1) to (x2,
         * y2)) then the ellipse is scaled up uniformly until there is
         * exactly one solution (until the ellipse is just big enough).
         *     -> find factor s, such that numerator' with rx'=s*rx and
         *    ry'=s*ry becomes 0 :
         */
    float s = (float)sqrt(1.0 - numerator / (rx * rx * ry * ry));

        rx *= s;
        ry *= s;
        root = 0.0;
    } else {
        root = (largeArcFlag == sweepFlag ? -1.0 : 1.0) *
            sqrt(numerator / (rx * rx * y1dash * y1dash +
                ry * ry * x1dash * x1dash));
    }

    cxdash = root * rx * y1dash / ry;
    cydash = -root * ry * x1dash / rx;

    /* Compute cx and cy from cx' and cy'. */
    cx = cosPhi * cxdash - sinPhi * cydash + (x1 + x2) / 2.0;
    cy = sinPhi * cxdash + cosPhi * cydash + (y1 + y2) / 2.0;

    /* Compute start angle and extent. */
    theta1 =
        CalcVectorAngle(1.0, 0.0, (x1dash - cxdash) / rx,
        (y1dash - cydash) / ry);
    dtheta =
        CalcVectorAngle((x1dash - cxdash) / rx, (y1dash - cydash) / ry,
        (-x1dash - cxdash) / rx, (-y1dash - cydash) / ry);
    if(!sweepFlag && (dtheta > 0.0)) {
        dtheta -= 2.0 * M_PI;
    } else if(sweepFlag && (dtheta < 0.0)) {
        dtheta += 2.0 * M_PI;
    }
    *cxPtr = cx;
    *cyPtr = cy;
    *rxPtr = rx;
    *ryPtr = ry;
    *theta1Ptr = theta1;
    *dthetaPtr = dtheta;

    return TK_PATH_ARC_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathTableLooup
 *
 *    Look up an index from a statically allocated table of ints.
 *
 * Results:
 *    integer
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

int
TkPathTableLookup(
    TkLookupTable * map,
    int n,
    int from)
{
    int i = 0;

    while((i < n) && (from != map[i].from))
        i++;
    if(i == n) {
        return map[0].to;
    } else {
        return map[i].to;
    }
}

/*
 * Miscellaneous matrix utilities.
 */

static void
PathApplyTMatrix(
    TkPathMatrix * m,
    double *x,
    double *y)
{
    if(m != NULL) {
    double tmpx = *x;
    double tmpy = *y;
        *x = tmpx * m->a + tmpy * m->c + m->tx;
        *y = tmpx * m->b + tmpy * m->d + m->ty;
    }
}

static void
PathApplyTMatrixToPoint(
    TkPathMatrix * m,
    double in[2],
    double out[2])
{
    if(m == NULL) {
        out[0] = in[0];
        out[1] = in[1];
    } else {
        out[0] = in[0] * m->a + in[1] * m->c + m->tx;
        out[1] = in[0] * m->b + in[1] * m->d + m->ty;
    }
}

static void
PathInverseTMatrix(
    TkPathMatrix * m,
    TkPathMatrix * mi)
{
double det;

    /* @@@ We need error checking for det = 0 */
    det = m->a * m->d - m->b * m->c;
    mi->a = m->d / det;
    mi->b = -m->b / det;
    mi->c = -m->c / det;
    mi->d = m->a / det;
    mi->tx = (m->c * m->ty - m->d * m->tx) / det;
    mi->ty = (m->b * m->tx - m->a * m->ty) / det;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathMMulTMatrix --
 *
 *    Multiplies (concatenates) two matrices together and puts the
 *      result in m2.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    TkPathMatrix m2 modified
 *
 *----------------------------------------------------------------------
 */

void
TkPathMMulTMatrix(
    TkPathMatrix * m1,
    TkPathMatrix * m2)
{
    if(m1 == NULL) {
        return;
    }
    if(m2 == NULL) {
        /* Panic! */
    } else {
TkPathMatrix tmp = *m2;
TkPathMatrix *p = m2;

        p->a = m1->a * tmp.a + m1->b * tmp.c;
        p->b = m1->a * tmp.b + m1->b * tmp.d;
        p->c = m1->c * tmp.a + m1->d * tmp.c;
        p->d = m1->c * tmp.b + m1->d * tmp.d;
        p->tx = m1->tx * tmp.a + m1->ty * tmp.c + tmp.tx;
        p->ty = m1->tx * tmp.b + m1->ty * tmp.d + tmp.ty;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathGetTMatrix --
 *
 *    Parses a Tcl list (in string) into a TkPathMatrix record.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

int
TkPathGetTMatrix(
    Tcl_Interp * interp,
    const char *list,          /* Object containg the lists for the matrix. */
    TkPathMatrix * matrixPtr)
{              /* Where to store TkPathMatrix corresponding
                * to list. Must be allocated! */
    const char **argv = NULL;
    int i, argc;
    int result = TCL_OK;
    double tmp[6];

    /* Check matrix consistency. */
    if(Tcl_SplitList(interp, list, &argc, &argv) != TCL_OK) {
        result = TCL_ERROR;
        goto bail;
    }
    if(argc != 6) {
        Tcl_AppendResult(interp, "matrix \"", list, "\" is inconsistent",
            (char *)NULL);
        result = TCL_ERROR;
        goto bail;
    }

    /* Take arguments in turn. */
    for(i = 0; i < 6; i++) {
        if(Tcl_GetDouble(interp, argv[i], &(tmp[i])) != TCL_OK) {
            Tcl_AppendResult(interp, "matrix \"", list, "\" is inconsistent",
                (char *)NULL);
            result = TCL_ERROR;
            goto bail;
        }
    }

    /* Check that the matrix is not close to being singular. */
    if(fabs(tmp[0] * tmp[3] - tmp[1] * tmp[2]) < 1e-6) {
        Tcl_AppendResult(interp, "matrix \"", list, "\" is close to singular",
            (char *)NULL);
        result = TCL_ERROR;
        goto bail;
    }

    /* Matrix. */
    matrixPtr->a = tmp[0];
    matrixPtr->b = tmp[1];
    matrixPtr->c = tmp[2];
    matrixPtr->d = tmp[3];
    matrixPtr->tx = tmp[4];
    matrixPtr->ty = tmp[5];

  bail:
    if(argv != NULL) {
        Tcl_Free((char *)argv);
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathGetTclObjFromTMatrix --
 *
 *    Parses a TkPathMatrix record into a list object.
 *
 * Results:
 *    Standard Tcl result
 *
 * Side effects:
 *    None
 *
 *----------------------------------------------------------------------
 */

int
TkPathGetTclObjFromTMatrix(
    Tcl_Interp * interp,
    TkPathMatrix * matrixPtr,
    Tcl_Obj ** listObjPtrPtr)
{
Tcl_Obj *listObj;

    /* @@@ Error handling remains. */

    listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    if(matrixPtr != NULL) {
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->a));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->b));

        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->c));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->d));

        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->tx));
        Tcl_ListObjAppendElement(interp, listObj,
            Tcl_NewDoubleObj(matrixPtr->ty));
    }
    *listObjPtrPtr = listObj;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ObjectIsEmpty --
 *
 *    This procedure tests whether the string value of an object is
 *    empty.
 *
 * Results:
 *    The return value is 1 if the string value of objPtr has length
 *    zero, and 0 otherwise.
 *
 * Side effects:
 *    May cause object shimmering, since this function can force a
 *    conversion to a string object.
 *
 *----------------------------------------------------------------------
 */

int
TkPathObjectIsEmpty(
    Tcl_Obj * objPtr)
{              /* Object to test.  May be NULL. */
int length;

    if(objPtr == NULL) {
        return 1;
    }
    if(objPtr->bytes != NULL) {
        return (objPtr->length == 0);
    }
    Tcl_GetStringFromObj(objPtr, &length);
    return (length == 0);
}

/*
 *--------------------------------------------------------------
 *
 * TkPathIncludePoint --
 *
 *    Given a point and a generic canvas item header, expand the item's
 *    bounding box if needed to include the point.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The boudn.
 *
 *--------------------------------------------------------------
 */

    /* ARGSUSED */
void
TkPathIncludePoint(
    Tk_PathItem * itemPtr,     /* Item whose bounding box is being
                                * calculated. */
    double *pointPtr)
{              /* Address of two doubles giving x and y
                * coordinates of point. */
    int tmp;

    tmp = (int)(pointPtr[0] + 0.5);
    if(tmp < itemPtr->x1) {
        itemPtr->x1 = tmp;
    }
    if(tmp > itemPtr->x2) {
        itemPtr->x2 = tmp;
    }
    tmp = (int)(pointPtr[1] + 0.5);
    if(tmp < itemPtr->y1) {
        itemPtr->y1 = tmp;
    }
    if(tmp > itemPtr->y2) {
        itemPtr->y2 = tmp;
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathBezierScreenPoints --
 *
 *    Given four control points, create a larger set of XPoints for a Bezier
 *    curve based on the points.
 *
 * Results:
 *    The array at *xPointPtr gets filled in with numSteps XPoints
 *    corresponding to the Bezier spline defined by the four control points.
 *    Note: no output point is generated for the first input point, but an
 *    output point *is* generated for the last input point.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

void
TkPathBezierScreenPoints(
    Tk_PathCanvas canvas,      /* Canvas in which curve is to be drawn. */
    double control[],          /* Array of coordinates for four control
                                * points: x0, y0, x1, y1, ... x3 y3. */
    int numSteps,              /* Number of curve points to generate. */
    XPoint * xPointPtr)
{              /* Where to put new points. */
    int i;
    double u, u2, u3, t, t2, t3;

    for(i = 1; i <= numSteps; i++, xPointPtr++) {
        t = ((double)i) / ((double)numSteps);
        t2 = t * t;
        t3 = t2 * t;
        u = 1.0 - t;
        u2 = u * u;
        u3 = u2 * u;
        Tk_PathCanvasDrawableCoords(canvas,
            (control[0] * u3 + 3.0 * (control[2] * t * u2 + control[4] * t2 * u)
                + control[6] * t3),
            (control[1] * u3 + 3.0 * (control[3] * t * u2 + control[5] * t2 * u)
                + control[7] * t3), &xPointPtr->x, &xPointPtr->y);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathBezierPoints --
 *
 *    Given four control points, create a larger set of points for a Bezier
 *    curve based on the points.
 *
 * Results:
 *    The array at *coordPtr gets filled in with 2*numSteps coordinates,
 *    which correspond to the Bezier spline defined by the four control
 *    points. Note: no output point is generated for the first input point,
 *    but an output point *is* generated for the last input point.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

void
TkPathBezierPoints(
    double control[],          /* Array of coordinates for four control
                                * points: x0, y0, x1, y1, ... x3 y3. */
    int numSteps,              /* Number of curve points to generate. */
    double *coordPtr)
{              /* Where to put new points. */
    int i;
    double u, u2, u3, t, t2, t3;

    for(i = 1; i <= numSteps; i++, coordPtr += 2) {
        t = ((double)i) / ((double)numSteps);
        t2 = t * t;
        t3 = t2 * t;
        u = 1.0 - t;
        u2 = u * u;
        u3 = u2 * u;
        coordPtr[0] = control[0] * u3
            + 3.0 * (control[2] * t * u2 + control[4] * t2 * u) +
            control[6] * t3;
        coordPtr[1] =
            control[1] * u3 + 3.0 * (control[3] * t * u2 +
            control[5] * t2 * u) + control[7] * t3;
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathMakeBezierCurve --
 *
 *    Given a set of points, create a new set of points that fit parabolic
 *    splines to the line segments connecting the original points. Produces
 *    output points in either of two forms.
 *
 *    Note: the name of this function should *not* be taken to mean that it
 *    interprets the input points as directly defining Bezier curves.
 *    Rather, it internally computes a Bezier curve representation of each
 *    parabolic spline segment. (These Bezier curves are then flattened to
 *    produce the points filled into the output arrays.)
 *
 * Results:
 *    Either or both of the xPoints or dblPoints arrays are filled in. The
 *    return value is the number of points placed in the arrays. Note: if
 *    the first and last points are the same, then a closed curve is
 *    generated.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathMakeBezierCurve(
    Tk_PathCanvas canvas,      /* Canvas in which curve is to be drawn. */
    double *pointPtr,          /* Array of input coordinates: x0, y0, x1, y1,
                                * etc.. */
    int numPoints,             /* Number of points at pointPtr. */
    int numSteps,              /* Number of steps to use for each spline
                                * segments (determines smoothness of
                                * curve). */
    XPoint xPoints[],          /* Array of XPoints to fill in (e.g. for
                                * display). NULL means don't fill in any
                                * XPoints. */
    double dblPoints[])
{              /* Array of points to fill in as doubles, in
                * the form x0, y0, x1, y1, .... NULL means
                * don't fill in anything in this form. Caller
                * must make sure that this array has enough
                * space. */
    int closed, outputPoints, i;
    int numCoords = numPoints * 2;
    double control[8];

    /*
     * If the curve is a closed one then generate a special spline that spans
     * the last points and the first ones. Otherwise just put the first point
     * into the output.
     */

    if(!pointPtr) {
        /*
         * Of pointPtr == NULL, this function returns an upper limit of the
         * array size to store the coordinates. This can be used to allocate
         * storage, before the actual coordinates are calculated.
         */

        return 1 + numPoints * numSteps;
    }

    outputPoints = 0;
    if((pointPtr[0] == pointPtr[numCoords - 2])
        && (pointPtr[1] == pointPtr[numCoords - 1])) {
        closed = 1;
        control[0] = 0.5 * pointPtr[numCoords - 4] + 0.5 * pointPtr[0];
        control[1] = 0.5 * pointPtr[numCoords - 3] + 0.5 * pointPtr[1];
        control[2] = 0.167 * pointPtr[numCoords - 4] + 0.833 * pointPtr[0];
        control[3] = 0.167 * pointPtr[numCoords - 3] + 0.833 * pointPtr[1];
        control[4] = 0.833 * pointPtr[0] + 0.167 * pointPtr[2];
        control[5] = 0.833 * pointPtr[1] + 0.167 * pointPtr[3];
        control[6] = 0.5 * pointPtr[0] + 0.5 * pointPtr[2];
        control[7] = 0.5 * pointPtr[1] + 0.5 * pointPtr[3];
        if(xPoints != NULL) {
            Tk_PathCanvasDrawableCoords(canvas, control[0], control[1],
                &xPoints->x, &xPoints->y);
            TkPathBezierScreenPoints(canvas, control, numSteps, xPoints + 1);
            xPoints += numSteps + 1;
        }
        if(dblPoints != NULL) {
            dblPoints[0] = control[0];
            dblPoints[1] = control[1];
            TkPathBezierPoints(control, numSteps, dblPoints + 2);
            dblPoints += 2 * (numSteps + 1);
        }
        outputPoints += numSteps + 1;
    } else {
        closed = 0;
        if(xPoints != NULL) {
            Tk_PathCanvasDrawableCoords(canvas, pointPtr[0], pointPtr[1],
                &xPoints->x, &xPoints->y);
            xPoints += 1;
        }
        if(dblPoints != NULL) {
            dblPoints[0] = pointPtr[0];
            dblPoints[1] = pointPtr[1];
            dblPoints += 2;
        }
        outputPoints += 1;
    }

    for(i = 2; i < numPoints; i++, pointPtr += 2) {
        /*
         * Set up the first two control points. This is done differently for
         * the first spline of an open curve than for other cases.
         */

        if((i == 2) && !closed) {
            control[0] = pointPtr[0];
            control[1] = pointPtr[1];
            control[2] = 0.333 * pointPtr[0] + 0.667 * pointPtr[2];
            control[3] = 0.333 * pointPtr[1] + 0.667 * pointPtr[3];
        } else {
            control[0] = 0.5 * pointPtr[0] + 0.5 * pointPtr[2];
            control[1] = 0.5 * pointPtr[1] + 0.5 * pointPtr[3];
            control[2] = 0.167 * pointPtr[0] + 0.833 * pointPtr[2];
            control[3] = 0.167 * pointPtr[1] + 0.833 * pointPtr[3];
        }

        /*
         * Set up the last two control points. This is done differently for
         * the last spline of an open curve than for other cases.
         */

        if((i == (numPoints - 1)) && !closed) {
            control[4] = .667 * pointPtr[2] + .333 * pointPtr[4];
            control[5] = .667 * pointPtr[3] + .333 * pointPtr[5];
            control[6] = pointPtr[4];
            control[7] = pointPtr[5];
        } else {
            control[4] = .833 * pointPtr[2] + .167 * pointPtr[4];
            control[5] = .833 * pointPtr[3] + .167 * pointPtr[5];
            control[6] = 0.5 * pointPtr[2] + 0.5 * pointPtr[4];
            control[7] = 0.5 * pointPtr[3] + 0.5 * pointPtr[5];
        }

        /*
         * If the first two points coincide, or if the last two points
         * coincide, then generate a single straight-line segment by
         * outputting the last control point.
         */

        if(((pointPtr[0] == pointPtr[2]) && (pointPtr[1] == pointPtr[3]))
            || ((pointPtr[2] == pointPtr[4])
                && (pointPtr[3] == pointPtr[5]))) {
            if(xPoints != NULL) {
                Tk_PathCanvasDrawableCoords(canvas, control[6], control[7],
                    &xPoints[0].x, &xPoints[0].y);
                xPoints++;
            }
            if(dblPoints != NULL) {
                dblPoints[0] = control[6];
                dblPoints[1] = control[7];
                dblPoints += 2;
            }
            outputPoints += 1;
            continue;
        }

        /*
         * Generate a Bezier spline using the control points.
         */

        if(xPoints != NULL) {
            TkPathBezierScreenPoints(canvas, control, numSteps, xPoints);
            xPoints += numSteps;
        }
        if(dblPoints != NULL) {
            TkPathBezierPoints(control, numSteps, dblPoints);
            dblPoints += 2 * numSteps;
        }
        outputPoints += numSteps;
    }
    return outputPoints;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathMakeRawCurve --
 *
 *    Interpret the given set of points as the raw knots and control points
 *    defining a sequence of cubic Bezier curves. Create a new set of points
 *    that fit these Bezier curves. Output points are produced in either of
 *    two forms.
 *
 * Results:
 *    Either or both of the xPoints or dblPoints arrays are filled in. The
 *    return value is the number of points placed in the arrays.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathMakeRawCurve(
    Tk_PathCanvas canvas,      /* Canvas in which curve is to be drawn. */
    double *pointPtr,          /* Array of input coordinates: x0, y0, x1, y1,
                                * etc.. */
    int numPoints,             /* Number of points at pointPtr. */
    int numSteps,              /* Number of steps to use for each curve
                                * segment (determines smoothness of
                                * curve). */
    XPoint xPoints[],          /* Array of XPoints to fill in (e.g. for
                                * display). NULL means don't fill in any
                                * XPoints. */
    double dblPoints[])
{              /* Array of points to fill in as doubles, in
                * the form x0, y0, x1, y1, .... NULL means
                * don't fill in anything in this form.
                * Caller must make sure that this array has
                * enough space. */
    int outputPoints, i;
    int numSegments = (numPoints + 1) / 3;
    double *segPtr;

    /*
     * The input describes a curve with s Bezier curve segments if there are
     * 3s+1, 3s, or 3s-1 input points. In the last two cases, 1 or 2 initial
     * points from the first curve segment are reused as defining points also
     * for the last curve segment. In the case of 3s input points, this will
     * automatically close the curve.
     */

    if(!pointPtr) {
        /*
         * If pointPtr == NULL, this function returns an upper limit of the
         * array size to store the coordinates. This can be used to allocate
         * storage, before the actual coordinates are calculated.
         */

        return 1 + numSegments * numSteps;
    }

    outputPoints = 0;
    if(xPoints != NULL) {
        Tk_PathCanvasDrawableCoords(canvas, pointPtr[0], pointPtr[1],
            &xPoints->x, &xPoints->y);
        xPoints += 1;
    }
    if(dblPoints != NULL) {
        dblPoints[0] = pointPtr[0];
        dblPoints[1] = pointPtr[1];
        dblPoints += 2;
    }
    outputPoints += 1;

    /*
     * The next loop handles all curve segments except one that overlaps the
     * end of the list of coordinates.
     */

    for(i = numPoints, segPtr = pointPtr; i >= 4; i -= 3, segPtr += 6) {
        if(segPtr[0] == segPtr[2] && segPtr[1] == segPtr[3] &&
            segPtr[4] == segPtr[6] && segPtr[5] == segPtr[7]) {
            /*
             * The control points on this segment are equal to their
             * neighbouring knots, so this segment is just a straight line. A
             * single point is sufficient.
             */

            if(xPoints != NULL) {
                Tk_PathCanvasDrawableCoords(canvas, segPtr[6], segPtr[7],
                    &xPoints->x, &xPoints->y);
                xPoints += 1;
            }
            if(dblPoints != NULL) {
                dblPoints[0] = segPtr[6];
                dblPoints[1] = segPtr[7];
                dblPoints += 2;
            }
            outputPoints += 1;
        } else {
            /*
             * This is a generic Bezier curve segment.
             */

            if(xPoints != NULL) {
                TkPathBezierScreenPoints(canvas, segPtr, numSteps, xPoints);
                xPoints += numSteps;
            }
            if(dblPoints != NULL) {
                TkPathBezierPoints(segPtr, numSteps, dblPoints);
                dblPoints += 2 * numSteps;
            }
            outputPoints += numSteps;
        }
    }

    /*
     * If at this point i>1, then there is some point which has not yet been
     * used. Make another curve segment.
     */

    if(i > 1) {
    int j;
    double control[8];

        /*
         * Copy the relevant coordinates to control[], so that it can be
         * passed as a unit to e.g. TkPathBezierPoints.
         */

        for(j = 0; j < 2 * i; j++) {
            control[j] = segPtr[j];
        }
        for(; j < 8; j++) {
            control[j] = pointPtr[j - 2 * i];
        }

        /*
         * Then we just do the same things as above.
         */

        if(control[0] == control[2] && control[1] == control[3] &&
            control[4] == control[6] && control[5] == control[7]) {
            /*
             * The control points on this segment are equal to their
             * neighbouring knots, so this segment is just a straight line. A
             * single point is sufficient.
             */

            if(xPoints != NULL) {
                Tk_PathCanvasDrawableCoords(canvas, control[6], control[7],
                    &xPoints->x, &xPoints->y);
                xPoints += 1;
            }
            if(dblPoints != NULL) {
                dblPoints[0] = control[6];
                dblPoints[1] = control[7];
                dblPoints += 2;
            }
            outputPoints += 1;
        } else {
            /*
             * This is a generic Bezier curve segment.
             */

            if(xPoints != NULL) {
                TkPathBezierScreenPoints(canvas, control, numSteps, xPoints);
                xPoints += numSteps;
            }
            if(dblPoints != NULL) {
                TkPathBezierPoints(control, numSteps, dblPoints);
                dblPoints += 2 * numSteps;
            }
            outputPoints += numSteps;
        }
    }

    return outputPoints;
}

static int
GetOffset(
    Tcl_Interp * interp,
    ClientData clientData,
    Tcl_Obj * offsetObj,
    Tk_Window tkwin,
    Tk_TSOffset * offsetPtr)
{
char *value = Tcl_GetString(offsetObj);
Tk_TSOffset tsoffset;
const char *q, *p;
int result;

    if((value == NULL) || (*value == 0)) {
        tsoffset.flags = TK_OFFSET_CENTER | TK_OFFSET_MIDDLE;
        goto goodTSOffset;
    }
    tsoffset.flags = 0;
    p = value;

    switch (value[0]) {
    case '#':
        if(PTR2INT(clientData) & TK_OFFSET_RELATIVE) {
            tsoffset.flags = TK_OFFSET_RELATIVE;
            p++;
            break;
        }
        goto badTSOffset;
    case 'e':
        switch (value[1]) {
        case '\0':
            tsoffset.flags = TK_OFFSET_RIGHT | TK_OFFSET_MIDDLE;
            goto goodTSOffset;
        case 'n':
            if(value[2] != 'd' || value[3] != '\0') {
                goto badTSOffset;
            }
            tsoffset.flags = INT_MAX;
            goto goodTSOffset;
        }
    case 'w':
        if(value[1] != '\0') {
            goto badTSOffset;
        }
        tsoffset.flags = TK_OFFSET_LEFT | TK_OFFSET_MIDDLE;
        goto goodTSOffset;
    case 'n':
        if((value[1] != '\0') && (value[2] != '\0')) {
            goto badTSOffset;
        }
        switch (value[1]) {
        case '\0':
            tsoffset.flags = TK_OFFSET_CENTER | TK_OFFSET_TOP;
            goto goodTSOffset;
        case 'w':
            tsoffset.flags = TK_OFFSET_LEFT | TK_OFFSET_TOP;
            goto goodTSOffset;
        case 'e':
            tsoffset.flags = TK_OFFSET_RIGHT | TK_OFFSET_TOP;
            goto goodTSOffset;
        }
        goto badTSOffset;
    case 's':
        if((value[1] != '\0') && (value[2] != '\0')) {
            goto badTSOffset;
        }
        switch (value[1]) {
        case '\0':
            tsoffset.flags = TK_OFFSET_CENTER | TK_OFFSET_BOTTOM;
            goto goodTSOffset;
        case 'w':
            tsoffset.flags = TK_OFFSET_LEFT | TK_OFFSET_BOTTOM;
            goto goodTSOffset;
        case 'e':
            tsoffset.flags = TK_OFFSET_RIGHT | TK_OFFSET_BOTTOM;
            goto goodTSOffset;
        }
        goto badTSOffset;
    case 'c':
        if(strncmp(value, "center", strlen(value)) != 0) {
            goto badTSOffset;
        }
        tsoffset.flags = TK_OFFSET_CENTER | TK_OFFSET_MIDDLE;
        goto goodTSOffset;
    }
    if((q = strchr(p, ',')) == NULL) {
        if(PTR2INT(clientData) & TK_OFFSET_INDEX) {
            if(Tcl_GetInt(interp, (char *)p, &tsoffset.flags) != TCL_OK) {
                Tcl_ResetResult(interp);
                goto badTSOffset;
            }
            tsoffset.flags |= TK_OFFSET_INDEX;
            goto goodTSOffset;
        }
        goto badTSOffset;
    }
    *((char *)q) = 0;
    result = Tk_GetPixels(interp, tkwin, (char *)p, &tsoffset.xoffset);
    *((char *)q) = ',';
    if(result != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tk_GetPixels(interp, tkwin, (char *)q + 1, &tsoffset.yoffset) != TCL_OK) {
        return TCL_ERROR;
    }

  goodTSOffset:
    /*
     * Below is a hack to allow the stipple/tile offset to be stored in the
     * internal tile structure. Most of the times, offsetPtr is a pointer to
     * an already existing tile structure. However if this structure is not
     * already created, we must do it with Tk_GetTile()!!!!;
     */

    memcpy(offsetPtr, &tsoffset, sizeof(Tk_TSOffset));
    return TCL_OK;

  badTSOffset:
    Tcl_AppendResult(interp, "bad offset \"", value,
        "\": expected \"x,y\"", NULL);
    if(PTR2INT(clientData) & TK_OFFSET_RELATIVE) {
        Tcl_AppendResult(interp, ", \"#x,y\"", NULL);
    }
    if(PTR2INT(clientData) & TK_OFFSET_INDEX) {
        Tcl_AppendResult(interp, ", <index>", NULL);
    }
    Tcl_AppendResult(interp, ", n, ne, e, se, s, sw, w, nw, or center", NULL);
    return TCL_ERROR;
}

/* Return NULL on error and leave error message */

Tk_TSOffset *
TkPathOffsetNew(
    Tcl_Interp * interp,
    ClientData clientData,
    Tk_Window tkwin,
    Tcl_Obj * offsetObj)
{
Tk_TSOffset *offsetPtr;

    offsetPtr = (Tk_TSOffset *) ckalloc(sizeof(Tk_TSOffset));
    if(GetOffset(interp, clientData, offsetObj, tkwin, offsetPtr) != TCL_OK) {
        ckfree((char *)offsetPtr);
        return NULL;;
    }
    return offsetPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathOffsetOptionSetProc --
 *
 *    Converts the offset of a stipple or tile into the Tk_TSOffset
 *    structure.
 *
 *----------------------------------------------------------------------
 */

int
    TkPathOffsetOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    Tk_TSOffset *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
        newPtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            newPtr = TkPathOffsetNew(interp, clientData, tkwin, valuePtr);
            if(newPtr == NULL) {
                return TCL_ERROR;
            }
        }
        *((Tk_TSOffset **) oldInternalPtr) = *((Tk_TSOffset **) internalPtr);
        *((Tk_TSOffset **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
TkPathOffsetOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
Tk_TSOffset *offsetPtr;
char buffer[32], *p;

    offsetPtr = *((Tk_TSOffset **) (recordPtr + internalOffset));
    buffer[0] = '\0';
    if(offsetPtr->flags & TK_OFFSET_INDEX) {
        if(offsetPtr->flags >= INT_MAX) {
            strcat(buffer, "end");
        } else {
            sprintf(buffer, "%d", offsetPtr->flags & ~TK_OFFSET_INDEX);
        }
        goto end;
    }
    if(offsetPtr->flags & TK_OFFSET_TOP) {
        if(offsetPtr->flags & TK_OFFSET_LEFT) {
            strcat(buffer, "nw");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_CENTER) {
            strcat(buffer, "n");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_RIGHT) {
            strcat(buffer, "ne");
            goto end;
        }
    } else if(offsetPtr->flags & TK_OFFSET_MIDDLE) {
        if(offsetPtr->flags & TK_OFFSET_LEFT) {
            strcat(buffer, "w");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_CENTER) {
            strcat(buffer, "center");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_RIGHT) {
            strcat(buffer, "e");
            goto end;
        }
    } else if(offsetPtr->flags & TK_OFFSET_BOTTOM) {
        if(offsetPtr->flags & TK_OFFSET_LEFT) {
            strcat(buffer, "sw");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_CENTER) {
            strcat(buffer, "s");
            goto end;
        } else if(offsetPtr->flags & TK_OFFSET_RIGHT) {
            strcat(buffer, "se");
            goto end;
        }
    }
    p = buffer;
    if(offsetPtr->flags & TK_OFFSET_RELATIVE) {
        strcat(buffer, "#");
        p++;
    }
    sprintf(p, "%d,%d", offsetPtr->xoffset, offsetPtr->yoffset);

  end:
    return Tcl_NewStringObj(buffer, -1);
}

void
TkPathOffsetOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(Tk_TSOffset **) internalPtr = *(Tk_TSOffset **) oldInternalPtr;
}

void
TkPathOffsetOptionFreeProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        ckfree((char *)*((char **)internalPtr));
    }
}

/*
 *--------------------------------------------------------------
 *
 * GetDoublePixels --
 *
 *    Given a string, returns the number of pixels corresponding
 *    to that string.
 *
 * Results:
 *    The return value is a standard Tcl return result.  If
 *    TCL_OK is returned, then everything went well and the
 *    pixel distance is stored at *doublePtr;  otherwise
 *    TCL_ERROR is returned and an error message is left in
 *    interp->result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
GetDoublePixels(
    Tcl_Interp * interp,       /* Use this for error reporting. */
    Tk_Window tkwin,           /* Window whose screen determines conversion
                                * from centimeters and other absolute
                                * units. */
    const char *string,        /* String describing a number of pixels. */
    double *doublePtr)
{              /* Place to store converted result. */
    char *end;
    double d;
    int widthM, widthS;
#ifdef PLATFORM_SDL
    double dW, dH;
#endif

    d = strtod((char *)string, &end);
    if(end == string) {
      error:
        Tcl_AppendResult(interp, "bad screen distance \"", string,
            "\"", (char *)NULL);
        return TCL_ERROR;
    }
    while((*end != '\0') && isspace(UCHAR(*end))) {
        end++;
    }
#ifdef PLATFORM_SDL
    dW = WidthOfScreen(Tk_Screen(tkwin));
    dW /= WidthMMOfScreen(Tk_Screen(tkwin));
    dH = HeightOfScreen(Tk_Screen(tkwin));
    dH /= HeightMMOfScreen(Tk_Screen(tkwin));
    if(dH > dW) {
        widthS = HeightOfScreen(Tk_Screen(tkwin));
        widthM = HeightMMOfScreen(Tk_Screen(tkwin));
    } else
#endif
    {
        widthS = WidthOfScreen(Tk_Screen(tkwin));
        widthM = WidthMMOfScreen(Tk_Screen(tkwin));
    }
    switch (*end) {
    case 0:
        break;
    case 'c':
        d *= 10 * widthS;
        d /= widthM;
        end++;
        break;
    case 'i':
        d *= 25.4 * widthS;
        d /= widthM;
        end++;
        break;
    case 'm':
        d *= widthS;
        d /= widthM;
        end++;
        break;
    case 'p':
        d *= (25.4 / 72.0) * widthS;
        d /= widthM;
        end++;
        break;
    default:
        goto error;
    }
    while((*end != '\0') && isspace(UCHAR(*end))) {
        end++;
    }
    if(*end != 0) {
        goto error;
    }
    *doublePtr = d;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathPixelOptionSetProc --
 *
 *    As TK_OPTION_PIXELS but for double value instead of int.
 *
 * Results:
 *    The return value is a standard Tcl return result.  If
 *    TCL_OK is returned, then everything went well and the
 *    pixel distance is stored at *doublePtr;  otherwise
 *    TCL_ERROR is returned and an error message is left in
 *    interp->result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
    Tk_PathPixelOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    double newPixels;
    int result;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
        newPixels = 0.0;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            result =
                GetDoublePixels(interp, tkwin, Tcl_GetString(valuePtr),
                &newPixels);
            if(result != TCL_OK) {
                return TCL_ERROR;
            } else if(newPixels < 0.0) {
                Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
                    "bad screen distance \"", Tcl_GetString(valuePtr), "\"",
                    NULL);
                return TCL_ERROR;
            }
        }
        *((double *)oldInternalPtr) = *((double *)internalPtr);
        *((double *)internalPtr) = newPixels;
    }
    return TCL_OK;
}

Tcl_Obj *
Tk_PathPixelOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
    return Tcl_NewDoubleObj(*((double *)(recordPtr + internalOffset)));
}

void
Tk_PathPixelOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(double **)internalPtr = *(double **)oldInternalPtr;
}

/*
 * Structures defined only in this file.
 */

typedef struct SmoothAssocData {
    struct SmoothAssocData *nextPtr;
    /* Pointer to next SmoothAssocData. */
    Tk_PathSmoothMethod smooth; /* Name and functions associated with this
                                 * option. */
} SmoothAssocData;

Tk_PathSmoothMethod tkPathBezierSmoothMethod = {
    "true",
    TkPathMakeBezierCurve
};

static Tk_PathSmoothMethod tkPathRawSmoothMethod = {
    "raw",
    TkPathMakeRawCurve
};

/*
 * Function forward-declarations.
 */

static void SmoothMethodCleanupProc(
    ClientData clientData,
    Tcl_Interp * interp);
static SmoothAssocData *InitSmoothMethods(
    Tcl_Interp * interp);
static int FindSmoothMethod(
    Tcl_Interp * interp,
    Tcl_Obj * valueObj,
    Tk_PathSmoothMethod ** smoothPtr);
static int DashConvert(
    char *l,
    const char *p,
    int n,
    double width);
static void TranslateAndAppendCoords(
    TkPathCanvas * canvPtr,
    double x,
    double y,
    XPoint * outArr,
    int numOut);

static Tk_Dash *DashNew(
    Tcl_Interp * interp,
    Tcl_Obj * dashObj);
static void DashFree(
    Tk_Dash * dashPtr);

#ifndef ABS
#    define ABS(a)        (((a) >= 0)  ? (a) : -1*(a))
#endif

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasTkwin --
 *
 *    Given a token for a canvas, this function returns the widget that
 *    represents the canvas.
 *
 * Results:
 *    The return value is a handle for the widget.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

Tk_Window
Tk_PathCanvasTkwin(
    Tk_PathCanvas canvas)
{              /* Token for the canvas. */
TkPathCanvas *path = (TkPathCanvas *) canvas;
    if(path->win == NULL || *(path->win) == NULL)
        return NULL;
    return (*(path->win));
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasDrawableCoords --
 *
 *    Given an (x,y) coordinate pair within a canvas, this function
 *    returns the corresponding coordinates at which the point should
 *    be drawn in the drawable used for display.
 *
 * Results:
 *    There is no return value. The values at *drawableXPtr and
 *    *drawableYPtr are filled in with the coordinates at which x and y
 *    should be drawn. These coordinates are clipped to fit within a
 *    "short", since this is what X uses in most cases for drawing.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

void
Tk_PathCanvasDrawableCoords(
    Tk_PathCanvas canvas,      /* Token for the canvas. */
    double x,                  /* Coordinates in canvas space. */
    double y,
    short *drawableXPtr,       /* Screen coordinates are stored here. */
    short *drawableYPtr)
{
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    double tmp;

    tmp = x - path->drawableXOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    if(tmp > 32767) {
        *drawableXPtr = 32767;
    } else if(tmp < -32768) {
        *drawableXPtr = -32768;
    } else {
        *drawableXPtr = (short)tmp;
    }

    tmp = y - path->drawableYOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    if(tmp > 32767) {
        *drawableYPtr = 32767;
    } else if(tmp < -32768) {
        *drawableYPtr = -32768;
    } else {
        *drawableYPtr = (short)tmp;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasWindowCoords --
 *
 *    Given an (x,y) coordinate pair within a canvas, this function returns
 *    the corresponding coordinates in the canvas's window.
 *
 * Results:
 *    There is no return value. The values at *screenXPtr and *screenYPtr
 *    are filled in with the coordinates at which (x,y) appears in the
 *    canvas's window. These coordinates are clipped to fit within a
 *    "short", since this is what X uses in most cases for drawing.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

void
Tk_PathCanvasWindowCoords(
    Tk_PathCanvas canvas,      /* Token for the canvas. */
    double x,                  /* Coordinates in canvas space. */
    double y,
    short *screenXPtr,         /* Screen coordinates are stored here. */
    short *screenYPtr)
{
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    double tmp;

    tmp = x - path->xOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    if(tmp > 32767) {
        *screenXPtr = 32767;
    } else if(tmp < -32768) {
        *screenXPtr = -32768;
    } else {
        *screenXPtr = (short)tmp;
    }

    tmp = y - path->yOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    if(tmp > 32767) {
        *screenYPtr = 32767;
    } else if(tmp < -32768) {
        *screenYPtr = -32768;
    } else {
        *screenYPtr = (short)tmp;
    }
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathCanvasGetCoord --
 *
 *    Given a string, returns a floating-point canvas coordinate
 *    corresponding to that string.
 *
 * Results:
 *    The return value is a standard Tcl return result. If TCL_OK is
 *    returned, then everything went well and the canvas coordinate is
 *    stored at *doublePtr; otherwise TCL_ERROR is returned and an error
 *    message is left in the interp's result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
Tk_PathCanvasGetCoord(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas to which coordinate applies. */
    const char *string,        /* Describes coordinate (any screen coordinate
                                * form may be used here). */
    double *doublePtr)
{              /* Place to store converted coordinate. */
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    if(path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;

    if(Tk_GetScreenMM(interp, *(path->win), string, doublePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    *doublePtr *= path->pixelsPerMM;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathCanvasGetCoordFromObj --
 *
 *    Given a string, returns a floating-point canvas coordinate
 *    corresponding to that string.
 *
 * Results:
 *    The return value is a standard Tcl return result. If TCL_OK is
 *    returned, then everything went well and the canvas coordinate is
 *    stored at *doublePtr; otherwise TCL_ERROR is returned and an error
 *    message is left in interp->result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
Tk_PathCanvasGetCoordFromObj(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    Tk_PathCanvas canvas,      /* Canvas to which coordinate applies. */
    Tcl_Obj * obj,             /* Describes coordinate (any screen coordinate
                                * form may be used here). */
    double *doublePtr)
{              /* Place to store converted coordinate. */
    TkPathCanvas *path = (TkPathCanvas *) canvas;
    if(path->win == NULL || *(path->win) == NULL)
        return TCL_ERROR;
#ifndef USE_TK_STUBS
    return Tk_GetDoublePixelsFromObj(interp, *(path->win), obj, doublePtr);
#else
    int pixels;

    if(Tk_GetMMFromObj(interp, *(path->win), obj, doublePtr) != TCL_OK) {
        return TCL_ERROR;
    }
    *doublePtr *= path->pixelsPerMM;

    /*
     * Unfortunately, Tcl_GetDoublePixelsFromObj() is not a public
     * interface, so we try here to overcome rounding errors.
     */
    pixels = *doublePtr;
    Tk_GetPixelsFromObj(interp, *(path->win), obj, &pixels);
    if(fabs(*doublePtr - pixels) < 1e-9) {
        *doublePtr = pixels;
    }
    return TCL_OK;
#endif
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasSetStippleOrigin --
 *
 *    This function sets the stipple origin in a graphics context so that
 *    stipples drawn with the GC will line up with other stipples previously
 *    drawn in the canvas.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The graphics context is modified.
 *
 *----------------------------------------------------------------------
 */

void
Tk_PathCanvasSetStippleOrigin(
    Tk_PathCanvas canvas,      /* Token for a canvas. */
    GC gc)
{              /* Graphics context that is about to be used
                * to draw a stippled pattern as part of
                * redisplaying the canvas. */
TkPathCanvas *path = (TkPathCanvas *) canvas;

    XSetTSOrigin(path->display, gc, -path->drawableXOrigin,
        -path->drawableYOrigin);
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasSetOffset --
 *
 *    This function sets the stipple offset in a graphics context so that
 *    stipples drawn with the GC will line up with other stipples with the
 *    same offset.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The graphics context is modified.
 *
 *----------------------------------------------------------------------
 */

void
Tk_PathCanvasSetOffset(
    Tk_PathCanvas canvas,      /* Token for a canvas. */
    GC gc,                     /* Graphics context that is about to be used
                                * to draw a stippled pattern as part of
                                * redisplaying the canvas. */
    Tk_TSOffset * offset)
{              /* Offset (may be NULL pointer) */
TkPathCanvas *path = (TkPathCanvas *) canvas;
int flags = 0;
int x = -path->drawableXOrigin;
int y = -path->drawableYOrigin;

    if(path->win == NULL || *(path->win) == NULL)
        return;

    if(offset != NULL) {
        flags = offset->flags;
        x += offset->xoffset;
        y += offset->yoffset;
    }
    if((flags & TK_OFFSET_RELATIVE) && !(flags & TK_OFFSET_INDEX)) {
        Tk_SetTSOrigin(*(path->win), gc, x - path->xOrigin, y - path->yOrigin);
    } else {
        XSetTSOrigin(path->display, gc, x, y);
    }
}

int
TkPathCanvasGetDepth(
    Tk_PathItem * itemPtr)
{
int depth = 0;
Tk_PathItem *walkPtr = itemPtr;

    while(walkPtr->parentPtr != NULL) {
        depth++;
        walkPtr = walkPtr->parentPtr;
    }
    return depth;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasInheritStyle --
 *
 *    This function returns the style which is inherited from the
 *      parents of the itemPtr using cascading from the root item.
 *    Must use TkPathCanvasFreeInheritedStyle when done.
 *
 * Results:
 *    Tk_PathStyle.
 *
 * Side effects:
 *    May allocate memory for matrix.
 *
 *----------------------------------------------------------------------
 */

Tk_PathStyle
TkPathCanvasInheritStyle(
    Tk_PathItem * itemPtr,
    long flags)
{
int depth, i, anyMatrix = 0;
Tk_PathItem *walkPtr;
Tk_PathItemEx *itemExPtr;
Tk_PathItemEx **parents;
Tk_PathStyle style;
TkPathMatrix matrix = TK_PATH_UNIT_TMATRIX;

    depth = TkPathCanvasGetDepth(itemPtr);
    parents = (Tk_PathItemEx **) ckalloc(depth * sizeof(Tk_PathItemEx *));

    walkPtr = itemPtr, i = 0;
    while(walkPtr->parentPtr != NULL) {
        parents[i] = (Tk_PathItemEx *) walkPtr->parentPtr;
        walkPtr = walkPtr->parentPtr, i++;
    }

    /*
     * Cascade the style from the root item to the closest parent.
     * Start by just making a copy of the root's style.
     */
    itemExPtr = parents[depth - 1];
    style = itemExPtr->style;

    for(i = depth - 1; i >= 0; i--) {
        itemExPtr = parents[i];

        /* The order of these two merges decides which take precedence. */
        if(i < depth - 1) {
            TkPathStyleMergeStyles(&itemExPtr->style, &style, flags);
        }
        if(itemExPtr->styleInst != NULL) {
            TkPathStyleMergeStyles(itemExPtr->styleInst->masterPtr, &style,
                flags);
        }
        if(style.matrixPtr != NULL) {
            anyMatrix = 1;
            TkPathMMulTMatrix(style.matrixPtr, &matrix);
        }
        /*
         * We set matrix to NULL to detect if set in group.
         */
        style.matrixPtr = NULL;
    }

    /*
     * Merge the parents style with the actual items style.
     * The order of these two merges decides which take precedence.
     */
    itemExPtr = (Tk_PathItemEx *) itemPtr;
    TkPathStyleMergeStyles(&itemExPtr->style, &style, flags);
    if(itemExPtr->styleInst != NULL) {
        TkPathStyleMergeStyles(itemExPtr->styleInst->masterPtr, &style, flags);
    }
    if(style.matrixPtr != NULL) {
        anyMatrix = 1;
        TkPathMMulTMatrix(style.matrixPtr, &matrix);
    }
    if(anyMatrix) {
        style.matrixPtr = (TkPathMatrix *) ckalloc(sizeof(TkPathMatrix));
        memcpy(style.matrixPtr, &matrix, sizeof(TkPathMatrix));
    }
    ckfree((char *)parents);
    return style;
}

void
TkPathCanvasFreeInheritedStyle(
    Tk_PathStyle * stylePtr)
{
    if(stylePtr->matrixPtr != NULL) {
        ckfree((char *)stylePtr->matrixPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathCanvasInheritTMatrix --
 *
 *    Does the same job as TkPathCanvasInheritStyle but for the
 *    TkPathMatrix only. No memory allocated.
 *    Note that we don't do the last step of concatenating the items
 *    own TkPathMatrix since that depends on its specific storage.
 *
 * Results:
 *    TkPathMatrix.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

TkPathMatrix
TkPathCanvasInheritTMatrix(
    Tk_PathItem * itemPtr)
{
int depth, i;
Tk_PathItem *walkPtr;
Tk_PathItemEx *itemExPtr;
Tk_PathItemEx **parents;
Tk_PathStyle *stylePtr;
TkPathMatrix matrix = TK_PATH_UNIT_TMATRIX, *matrixPtr = NULL;

    depth = TkPathCanvasGetDepth(itemPtr);
    parents = (Tk_PathItemEx **) ckalloc(depth * sizeof(Tk_PathItemEx *));

    walkPtr = itemPtr, i = 0;
    while(walkPtr->parentPtr != NULL) {
        parents[i] = (Tk_PathItemEx *) walkPtr->parentPtr;
        walkPtr = walkPtr->parentPtr, i++;
    }

    for(i = depth - 1; i >= 0; i--) {
        itemExPtr = parents[i];

        /* The order of these two merges decides which take precedence. */
        matrixPtr = itemExPtr->style.matrixPtr;
        if(itemExPtr->styleInst != NULL) {
            stylePtr = itemExPtr->styleInst->masterPtr;
            if(stylePtr->mask & TK_PATH_STYLE_OPTION_MATRIX) {
                matrixPtr = stylePtr->matrixPtr;
            }
        }
        if(matrixPtr != NULL) {
            TkPathMMulTMatrix(matrixPtr, &matrix);
        }
    }
    ckfree((char *)parents);
    return matrix;
}

/* TkPathCanvasGradientTable etc.: this is just accessor functions to hide
   the internals of the TkPathCanvas */

Tcl_HashTable *
TkPathCanvasGradientTable(
    Tk_PathCanvas canvas)
{
    return &((TkPathCanvas *) canvas)->gradientTable;
}

Tcl_HashTable *
TkPathCanvasStyleTable(
    Tk_PathCanvas canvas)
{
    return &((TkPathCanvas *) canvas)->styleTable;
}

Tk_PathState
TkPathCanvasState(
    Tk_PathCanvas canvas)
{
    return ((TkPathCanvas *) canvas)->canvas_state;
}

Tk_PathItem *
TkPathCanvasCurrentItem(
    Tk_PathCanvas canvas)
{
    return ((TkPathCanvas *) canvas)->currentItemPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * Tk_PathCanvasGetTextInfo --
 *
 *    This function returns a pointer to a structure containing information
 *    about the selection and insertion cursor for a canvas widget. Items
 *    such as text items save the pointer and use it to share access to the
 *    information with the generic canvas code.
 *
 * Results:
 *    The return value is a pointer to the structure holding text
 *    information for the canvas. Most of the fields should not be modified
 *    outside the generic canvas code; see the user documentation for
 *    details.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

Tk_PathCanvasTextInfo *
Tk_PathCanvasGetTextInfo(
    Tk_PathCanvas canvas)
{              /* Token for the canvas widget. */
    return &((TkPathCanvas *) canvas)->textInfo;
}

/*
 *----------------------------------------------------------------------
 *
 * TkPathAllocTagsFromObj --
 *
 *    Create a new Tk_PathTags record and fill it with a tag object list.
 *
 * Results:
 *    A pointer to Tk_PathTags record or NULL if failed.
 *
 * Side effects:
 *    New Tk_PathTags possibly allocated.
 *
 *----------------------------------------------------------------------
 */

Tk_PathTags *
TkPathAllocTagsFromObj(
    Tcl_Interp * interp,
    Tcl_Obj * valuePtr)
{              /* If NULL we just create an empty Tk_PathTags struct. */
Tk_PathTags *tagsPtr;
int objc, i, len;
Tcl_Obj **objv;

    if(TkPathObjectIsEmpty(valuePtr)) {
        objc = 0;
    } else if(Tcl_ListObjGetElements(interp, valuePtr, &objc, &objv) != TCL_OK) {
        return NULL;
    }
    len = MAX(objc, TK_PATHTAG_SPACE);
    tagsPtr = (Tk_PathTags *) ckalloc(sizeof(Tk_PathTags));
    tagsPtr->tagSpace = len;
    tagsPtr->numTags = objc;
    tagsPtr->tagPtr = (Tk_Uid *) ckalloc((unsigned)(len * sizeof(Tk_Uid)));
    for(i = 0; i < objc; i++) {
        tagsPtr->tagPtr[i] = Tk_GetUid(Tcl_GetStringFromObj(objv[i], NULL));
    }
    return tagsPtr;
}

static void
PathFreeTags(
    Tk_PathTags * tagsPtr)
{
    if(tagsPtr->tagPtr != NULL) {
        ckfree((char *)tagsPtr->tagPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathCanvasTagsOptionSetProc --
 *
 *    This function is invoked during option processing to handle "-tags"
 *    options for canvas items.
 *
 * Results:
 *    A standard Tcl return value.
 *
 * Side effects:
 *    The tags for a given item get replaced by those indicated in the value
 *    argument.
 *
 *--------------------------------------------------------------
 */

int
    Tk_PathCanvasTagsOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    Tk_PathTags *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
        newPtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            newPtr = TkPathAllocTagsFromObj(interp, valuePtr);
            if(newPtr == NULL) {
                return TCL_ERROR;
            }
        }
        *((Tk_PathTags **) oldInternalPtr) = *((Tk_PathTags **) internalPtr);
        *((Tk_PathTags **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
Tk_PathCanvasTagsOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
Tk_PathTags *tagsPtr;
Tcl_Obj *listObj;
int i;

    tagsPtr = *((Tk_PathTags **) (recordPtr + internalOffset));
    listObj = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    if(tagsPtr != NULL) {
        for(i = 0; i < tagsPtr->numTags; i++) {
            Tcl_ListObjAppendElement(NULL, listObj,
                Tcl_NewStringObj((char *)tagsPtr->tagPtr[i], -1));
        }
    }
    return listObj;
}

void
Tk_PathCanvasTagsOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(Tk_PathTags **) internalPtr = *(Tk_PathTags **) oldInternalPtr;
}

void
Tk_PathCanvasTagsOptionFreeProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    Tk_PathTags *tagsPtr;

    tagsPtr = *((Tk_PathTags **) internalPtr);
    if(tagsPtr != NULL) {
        PathFreeTags(tagsPtr);
        ckfree(*((char **)internalPtr));
        *((char **)internalPtr) = NULL;
    }
}

/* Return NULL on error and leave error message */

static Tk_Dash *
DashNew(
    Tcl_Interp * interp,
    Tcl_Obj * dashObj)
{
Tk_Dash *dashPtr;

    dashPtr = (Tk_Dash *) ckalloc(sizeof(Tk_Dash));
    /*
     * NB: Tk_GetDash tries to free any existing pattern unless we zero this.
     */
    dashPtr->number = 0;
    if(Tk_GetDash(interp, Tcl_GetString(dashObj), dashPtr) != TCL_OK) {
        goto error;
    }
    return dashPtr;

  error:
    DashFree(dashPtr);
    return NULL;
}

static void
DashFree(
    Tk_Dash * dashPtr)
{
    if(dashPtr != NULL) {
        if(ABS(dashPtr->number) > sizeof(char *)) {
            ckfree((char *)dashPtr->pattern.pt);
        }
        ckfree((char *)dashPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * Tk_DashOptionSetProc, Tk_DashOptionGetProc,
 *    Tk_DashOptionRestoreProc, Tk_DashOptionRestoreProc --
 *
 *    These functions are invoked during option processing to handle
 *    "-dash", "-activedash" and "-disableddash"
 *    options for canvas objects.
 *
 * Results:
 *    According to the Tk_ObjCustomOption struct.
 *
 * Side effects:
 *    Memory allocated or freed.
 *
 *--------------------------------------------------------------
 */

int
    Tk_DashOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    Tk_Dash *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
        newPtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            newPtr = DashNew(interp, valuePtr);
            if(newPtr == NULL) {
                return TCL_ERROR;
            }
        }
        *((Tk_Dash **) oldInternalPtr) = *((Tk_Dash **) internalPtr);
        *((Tk_Dash **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
Tk_DashOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
Tk_Dash *dashPtr;
Tcl_Obj *objPtr = NULL;
char *buffer = NULL;
char *p;
int i;

    dashPtr = *((Tk_Dash **) (recordPtr + internalOffset));

    if(dashPtr != NULL) {
        i = dashPtr->number;
        if(i < 0) {
            i = -i;
            buffer = (char *)ckalloc((unsigned int)(i + 1));
            p = (i >
                (int)sizeof(char *))? dashPtr->pattern.pt : dashPtr->pattern.
                array;
            memcpy(buffer, p, (unsigned int)i);
            buffer[i] = 0;
        } else if(!i) {
            buffer = (char *)ckalloc(1);
            buffer[0] = '\0';
        } else {
            buffer = (char *)ckalloc((unsigned int)(4 * i));
            p = (i >
                (int)sizeof(char *))? dashPtr->pattern.pt : dashPtr->pattern.
                array;
            sprintf(buffer, "%d", *p++ & 0xff);
            while(--i) {
                sprintf(buffer + strlen(buffer), " %d", *p++ & 0xff);
            }
        }
        objPtr = Tcl_NewStringObj(buffer, -1);
    }
    if(buffer != NULL) {
        ckfree((char *)buffer);
    }
    return objPtr;
}

void
Tk_DashOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(Tk_Dash **) internalPtr = *(Tk_Dash **) oldInternalPtr;
}

void
Tk_DashOptionFreeProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr)
{              /* Pointer to storage for value. */
    if(*((char **)internalPtr) != NULL) {
        DashFree(*(Tk_Dash **) internalPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * InitSmoothMethods --
 *
 *    This function is invoked to set up the initial state of the list of
 *    "-smooth" methods. It should only be called when the list installed
 *    in the interpreter is NULL.
 *
 * Results:
 *    Pointer to the start of the list of default smooth methods.
 *
 * Side effects:
 *    A linked list of smooth methods is created and attached to the
 *    interpreter's association key "smoothPathMethod"
 *
 *--------------------------------------------------------------
 */

static SmoothAssocData *
InitSmoothMethods(
    Tcl_Interp * interp)
{
SmoothAssocData *methods, *ptr;

    methods = (SmoothAssocData *) ckalloc(sizeof(SmoothAssocData));
    methods->smooth.name = tkPathRawSmoothMethod.name;
    methods->smooth.coordProc = tkPathRawSmoothMethod.coordProc;
    methods->nextPtr = (SmoothAssocData *) ckalloc(sizeof(SmoothAssocData));

    ptr = methods->nextPtr;
    ptr->smooth.name = tkPathBezierSmoothMethod.name;
    ptr->smooth.coordProc = tkPathBezierSmoothMethod.coordProc;
    ptr->nextPtr = NULL;

    Tcl_SetAssocData(interp, "smoothPathMethod", SmoothMethodCleanupProc,
        (ClientData) methods);
    return methods;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathCreateSmoothMethod --
 *
 *    This function is invoked to add additional values for the "-smooth"
 *    option to the list.
 *
 * Results:
 *    A standard Tcl return value.
 *
 * Side effects:
 *    In the future "-smooth <name>" will be accepted as smooth method for
 *    the line and polygon.
 *
 *--------------------------------------------------------------
 */

void
Tk_PathCreateSmoothMethod(
    Tcl_Interp * interp,
    Tk_PathSmoothMethod * smooth)
{
SmoothAssocData *methods, *typePtr2, *prevPtr, *ptr;
    methods = (SmoothAssocData *) Tcl_GetAssocData(interp, "smoothPathMethod",
        NULL);

    /*
     * Initialize if we were not previously initialized.
     */

    if(methods == NULL) {
        methods = InitSmoothMethods(interp);
    }

    /*
     * If there's already a smooth method with the given name, remove it.
     */

    for(typePtr2 = methods, prevPtr = NULL; typePtr2 != NULL;
        prevPtr = typePtr2, typePtr2 = typePtr2->nextPtr) {
        if(!strcmp(typePtr2->smooth.name, smooth->name)) {
            if(prevPtr == NULL) {
                methods = typePtr2->nextPtr;
            } else {
                prevPtr->nextPtr = typePtr2->nextPtr;
            }
            ckfree((char *)typePtr2);
            break;
        }
    }
    ptr = (SmoothAssocData *) ckalloc(sizeof(SmoothAssocData));
    ptr->smooth.name = smooth->name;
    ptr->smooth.coordProc = smooth->coordProc;
    ptr->nextPtr = methods;
    Tcl_SetAssocData(interp, "smoothPathMethod", SmoothMethodCleanupProc,
        (ClientData) ptr);
}

/*
 *----------------------------------------------------------------------
 *
 * SmoothMethodCleanupProc --
 *
 *    This function is invoked whenever an interpreter is deleted to
 *    cleanup the smooth methods.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Smooth methods are removed.
 *
 *----------------------------------------------------------------------
 */

static void
SmoothMethodCleanupProc(
    ClientData clientData,     /* Points to "smoothPathMethod" AssocData for the
                                * interpreter. */
    Tcl_Interp * interp)
{              /* Interpreter that is being deleted. */
SmoothAssocData *ptr, *methods = (SmoothAssocData *) clientData;

    while(methods != NULL) {
        methods = (ptr = methods)->nextPtr;
        ckfree((char *)ptr);
    }
}

static int
FindSmoothMethod(
    Tcl_Interp * interp,
    Tcl_Obj * valueObj,
    Tk_PathSmoothMethod ** smoothPtr)
{              /* Place to store converted result. */
Tk_PathSmoothMethod *smooth = NULL;
int b;
char *value;
size_t length;
SmoothAssocData *methods;

    value = Tcl_GetString(valueObj);
    length = strlen(value);
    methods = (SmoothAssocData *) Tcl_GetAssocData(interp, "smoothPathMethod",
        NULL);

    /*
     * Not initialized yet; fix that now.
     */

    if(methods == NULL) {
        methods = InitSmoothMethods(interp);
    }

    /*
     * Backward compatability hack.
     */

    if(strncmp(value, "bezier", length) == 0) {
        smooth = &tkPathBezierSmoothMethod;
    }

    /*
     * Search the list of installed smooth methods.
     */

    while(methods != NULL) {
        if(strncmp(value, methods->smooth.name, length) == 0) {
            if(smooth != NULL) {
                Tcl_AppendResult(interp, "ambiguous smooth method \"", value,
                    "\"", NULL);
                return TCL_ERROR;
            }
            smooth = &methods->smooth;
        }
        methods = methods->nextPtr;
    }
    if(smooth) {
        *smoothPtr = smooth;
        return TCL_OK;
    }

    /*
     * Did not find it. Try parsing as a boolean instead.
     */

    if(Tcl_GetBooleanFromObj(interp, valueObj, &b) != TCL_OK) {
        return TCL_ERROR;
    }
    *smoothPtr = b ? &tkPathBezierSmoothMethod : NULL;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathSmoothOptionSetProc --
 *
 *    This function is invoked during option processing to handle "-smooth"
 *    options for canvas items.
 *
 * Results:
 *    A standard Tcl return value.
 *
 * Side effects:
 *    The smooth option for a given item gets replaced by the value
 *    indicated in the value argument.
 *
 *--------------------------------------------------------------
 */

int
    TkPathSmoothOptionSetProc(
    ClientData clientData,
    Tcl_Interp * interp,       /* Current interp; may be used for errors. */
    Tk_Window tkwin,           /* Window for which option is being set. */
    Tcl_Obj ** value,          /* Pointer to the pointer to the value object.
                                * We use a pointer to the pointer because
                                * we may need to return a value (NULL). */
    char *recordPtr,           /* Pointer to storage for the widget record. */
    int internalOffset,        /* Offset within *recordPtr at which the
                                * internal value is to be stored. */
    char *oldInternalPtr,      /* Pointer to storage for the old value. */
    int flags) {        /* Flags for the option, set Tk_SetOptions. */
    char *internalPtr;         /* Points to location in record where
                                * internal representation of value should
                                * be stored, or NULL. */
    Tcl_Obj *valuePtr;
    Tk_PathSmoothMethod *newPtr = NULL;

    valuePtr = *value;
    if(internalOffset >= 0) {
        internalPtr = recordPtr + internalOffset;
    } else {
        internalPtr = NULL;
    }
    if((flags & TK_OPTION_NULL_OK) && TkPathObjectIsEmpty(valuePtr)) {
        valuePtr = NULL;
        newPtr = NULL;
    }
    if(internalPtr != NULL) {
        if(valuePtr != NULL) {
            if(FindSmoothMethod(interp, valuePtr, &newPtr) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        *((Tk_PathSmoothMethod **) oldInternalPtr) =
            *((Tk_PathSmoothMethod **) internalPtr);
        *((Tk_PathSmoothMethod **) internalPtr) = newPtr;
    }
    return TCL_OK;
}

Tcl_Obj *
TkPathSmoothOptionGetProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *recordPtr,           /* Pointer to widget record. */
    int internalOffset)
{              /* Offset within *recordPtr containing the
                * value. */
Tk_PathSmoothMethod *smooth;

    smooth = *((Tk_PathSmoothMethod **) (recordPtr + internalOffset));
    return (smooth) ? Tcl_NewStringObj(smooth->name, -1) : Tcl_NewBooleanObj(0);
}

void
TkPathSmoothOptionRestoreProc(
    ClientData clientData,
    Tk_Window tkwin,
    char *internalPtr,         /* Pointer to storage for value. */
    char *oldInternalPtr)
{              /* Pointer to old value. */
    *(Tk_PathSmoothMethod **) internalPtr =
        *(Tk_PathSmoothMethod **) oldInternalPtr;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathCreateOutline
 *
 *    This function initializes the Tk_PathOutline structure with default
 *    values.
 *
 * Results:
 *    None
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

void
Tk_PathCreateOutline(
    Tk_PathOutline * outline)
{              /* Outline structure to be filled in. */
    outline->gc = None;
    outline->width = 1.0;
    outline->activeWidth = 0.0;
    outline->disabledWidth = 0.0;
    outline->offset = 0;
    outline->dashPtr = NULL;
    outline->activeDashPtr = NULL;
    outline->disabledDashPtr = NULL;
    outline->tsoffsetPtr = NULL;
    outline->color = NULL;
    outline->activeColor = NULL;
    outline->disabledColor = NULL;
    outline->stipple = None;
    outline->activeStipple = None;
    outline->disabledStipple = None;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathDeleteOutline
 *
 *    This function frees all memory that might be allocated and referenced
 *    in the Tk_PathOutline structure.
 *
 * Results:
 *    None
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

/* @@@ I don't belive this should ever be called since the memory is handled by Option! */

void
Tk_PathDeleteOutline(
    Display * display,         /* Display containing window. */
    Tk_PathOutline * outline)
{
    if(outline->gc != None) {
        Tk_FreeGC(display, outline->gc);
        outline->gc = None;
    }
    if(outline->color != NULL) {
        Tk_FreeColor(outline->color);
        outline->color = NULL;
    }
    if(outline->activeColor != NULL) {
        Tk_FreeColor(outline->activeColor);
        outline->activeColor = NULL;
    }
    if(outline->disabledColor != NULL) {
        Tk_FreeColor(outline->disabledColor);
        outline->disabledColor = NULL;
    }
    if(outline->stipple != None) {
        Tk_FreeBitmap(display, outline->stipple);
        outline->stipple = None;
    }
    if(outline->activeStipple != None) {
        Tk_FreeBitmap(display, outline->activeStipple);
        outline->activeStipple = None;
    }
    if(outline->disabledStipple != None) {
        Tk_FreeBitmap(display, outline->disabledStipple);
        outline->disabledStipple = None;
    }
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathConfigOutlineGC
 *
 *    This function should be called in the canvas object during the
 *    configure command. The graphics context description in gcValues is
 *    updated according to the information in the dash structure, as far as
 *    possible.
 *
 * Results:
 *    The return-value is a mask, indicating which elements of gcValues have
 *    been updated. 0 means there is no outline.
 *
 * Side effects:
 *    GC information in gcValues is updated.
 *
 *--------------------------------------------------------------
 */

int
Tk_PathConfigOutlineGC(
    XGCValues * gcValues,
    Tk_PathCanvas canvas,
    Tk_PathItem * item,
    Tk_PathOutline * outline)
{
int mask = 0;
double width;
Tk_Dash *dashPtr;
XColor *color;
Pixmap stipple;
Tk_PathState state = item->state;

    if(outline->width < 0.0) {
        outline->width = 0.0;
    }
    if(outline->activeWidth < 0.0) {
        outline->activeWidth = 0.0;
    }
    if(outline->disabledWidth < 0) {
        outline->disabledWidth = 0.0;
    }
    if(state == TK_PATHSTATE_HIDDEN) {
        return 0;
    }

    width = outline->width;
    if(width < 1.0) {
        width = 1.0;
    }
    dashPtr = outline->dashPtr;
    color = outline->color;
    stipple = outline->stipple;
    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(((TkPathCanvas *) canvas)->currentItemPtr == item) {
        if(outline->activeWidth > width) {
            width = outline->activeWidth;
        }
        if(outline->activeDashPtr != NULL) {
            dashPtr = outline->activeDashPtr;
        }
        if(outline->activeColor != NULL) {
            color = outline->activeColor;
        }
        if(outline->activeStipple != None) {
            stipple = outline->activeStipple;
        }
    } else if(state == TK_PATHSTATE_DISABLED) {
        if(outline->disabledWidth > 0) {
            width = outline->disabledWidth;
        }
        if(outline->disabledDashPtr != NULL) {
            dashPtr = outline->disabledDashPtr;
        }
        if(outline->disabledColor != NULL) {
            color = outline->disabledColor;
        }
        if(outline->disabledStipple != None) {
            stipple = outline->disabledStipple;
        }
    }

    if(color == NULL) {
        return 0;
    }

    gcValues->line_width = (int)(width + 0.5);
    if(color != NULL) {
        gcValues->foreground = color->pixel;
        mask = GCForeground | GCLineWidth;
        if(stipple != None) {
            gcValues->stipple = stipple;
            gcValues->fill_style = FillStippled;
            mask |= GCStipple | GCFillStyle;
        }
    }
    if(mask && (dashPtr != NULL)) {
        gcValues->line_style = LineOnOffDash;
        gcValues->dash_offset = outline->offset;
        if(dashPtr->number >= 2) {
            gcValues->dashes = 4;
        } else if(dashPtr->number > 0) {
            gcValues->dashes = dashPtr->pattern.array[0];
        } else {
            gcValues->dashes = (char)(4 * width);
        }
        mask |= GCLineStyle | GCDashList | GCDashOffset;
    }
    return mask;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathChangeOutlineGC
 *
 *    Updates the GC to represent the full information of the dash
 *    structure. Partly this is already done in Tk_PathConfigOutlineGC(). This
 *    function should be called just before drawing the dashed item.
 *
 * Results:
 *    1 if there is a stipple pattern, and 0 otherwise.
 *
 * Side effects:
 *    GC is updated.
 *
 *--------------------------------------------------------------
 */

int
Tk_PathChangeOutlineGC(
    Tk_PathCanvas canvas,
    Tk_PathItem * item,
    Tk_PathOutline * outline)
{
const char *p;
double width;
Tk_Dash *dashPtr;
XColor *color;
Pixmap stipple;
Tk_PathState state = item->state;

    width = outline->width;
    if(width < 1.0) {
        width = 1.0;
    }
    dashPtr = outline->dashPtr;
    color = outline->color;
    stipple = outline->stipple;
    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(((TkPathCanvas *) canvas)->currentItemPtr == item) {
        if(outline->activeWidth > width) {
            width = outline->activeWidth;
        }
        if(outline->activeDashPtr != NULL) {
            dashPtr = outline->activeDashPtr;
        }
        if(outline->activeColor != NULL) {
            color = outline->activeColor;
        }
        if(outline->activeStipple != None) {
            stipple = outline->activeStipple;
        }
    } else if(state == TK_PATHSTATE_DISABLED) {
        if(outline->disabledWidth > width) {
            width = outline->disabledWidth;
        }
        if(outline->disabledDashPtr != NULL) {
            dashPtr = outline->disabledDashPtr;
        }
        if(outline->disabledColor != NULL) {
            color = outline->disabledColor;
        }
        if(outline->disabledStipple != None) {
            stipple = outline->disabledStipple;
        }
    }
    if(color == NULL) {
        return 0;
    }
    if(dashPtr != NULL) {
        if((dashPtr->number < -1) ||
            ((dashPtr->number == -1) && (dashPtr->pattern.array[1] != ','))) {
char *q;
int i = -dashPtr->number;

            p = (i >
                (int)sizeof(char *))? dashPtr->pattern.pt : dashPtr->pattern.
                array;
            q = (char *)ckalloc(2 * (unsigned int)i);
            i = DashConvert(q, p, i, width);
            XSetDashes(((TkPathCanvas *) canvas)->display, outline->gc,
                outline->offset, q, i);
            ckfree(q);
        } else if(dashPtr->number > 2 || (dashPtr->number == 2 &&
                (dashPtr->pattern.array[0] != dashPtr->pattern.array[1]))) {
            p = (dashPtr->number > (int)sizeof(char *))
                ? dashPtr->pattern.pt : dashPtr->pattern.array;
            XSetDashes(((TkPathCanvas *) canvas)->display, outline->gc,
                outline->offset, p, dashPtr->number);
        }
    }
    if(stipple != None) {
int w = 0;
int h = 0;
Tk_TSOffset *tsoffset = outline->tsoffsetPtr;
int flags = tsoffset->flags;
        if(!(flags & TK_OFFSET_INDEX) &&
            (flags & (TK_OFFSET_CENTER | TK_OFFSET_MIDDLE))) {
            Tk_SizeOfBitmap(((TkPathCanvas *) canvas)->display, stipple, &w,
                &h);
            if(flags & TK_OFFSET_CENTER) {
                w /= 2;
            } else {
                w = 0;
            }
            if(flags & TK_OFFSET_MIDDLE) {
                h /= 2;
            } else {
                h = 0;
            }
        }
        tsoffset->xoffset -= w;
        tsoffset->yoffset -= h;
        Tk_PathCanvasSetOffset(canvas, outline->gc, tsoffset);
        tsoffset->xoffset += w;
        tsoffset->yoffset += h;
        return 1;
    }
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * Tk_PathResetOutlineGC
 *
 *    Restores the GC to the situation before Tk_ChangeDashGC() was called.
 *    This function should be called just after the dashed item is drawn,
 *    because the GC is supposed to be read-only.
 *
 * Results:
 *    1 if there is a stipple pattern, and 0 otherwise.
 *
 * Side effects:
 *    GC is updated.
 *
 *--------------------------------------------------------------
 */

int
Tk_PathResetOutlineGC(
    Tk_PathCanvas canvas,
    Tk_PathItem * item,
    Tk_PathOutline * outline)
{
char dashList;
double width;
Tk_Dash *dashPtr;
XColor *color;
Pixmap stipple;
Tk_PathState state = item->state;

    width = outline->width;
    if(width < 1.0) {
        width = 1.0;
    }
    dashPtr = outline->dashPtr;
    color = outline->color;
    stipple = outline->stipple;
    if(state == TK_PATHSTATE_NULL) {
        state = TkPathCanvasState(canvas);
    }
    if(((TkPathCanvas *) canvas)->currentItemPtr == item) {
        if(outline->activeWidth > width) {
            width = outline->activeWidth;
        }
        if(outline->activeDashPtr != NULL) {
            dashPtr = outline->activeDashPtr;
        }
        if(outline->activeColor != NULL) {
            color = outline->activeColor;
        }
        if(outline->activeStipple != None) {
            stipple = outline->activeStipple;
        }
    } else if(state == TK_PATHSTATE_DISABLED) {
        if(outline->disabledWidth > width) {
            width = outline->disabledWidth;
        }
        if(outline->disabledDashPtr != NULL) {
            dashPtr = outline->disabledDashPtr;
        }
        if(outline->disabledColor != NULL) {
            color = outline->disabledColor;
        }
        if(outline->disabledStipple != None) {
            stipple = outline->disabledStipple;
        }
    }
    if(color == NULL) {
        return 0;
    }

    if(dashPtr != NULL) {
        if((dashPtr->number > 2) || (dashPtr->number < -1)
            || (dashPtr->number == 2
                && (dashPtr->pattern.array[0] != dashPtr->pattern.array[1]))
            || ((dashPtr->number == -1)
                && (dashPtr->pattern.array[1] != ','))) {
            if(dashPtr->number < 0) {
                dashList = (int)(4 * width + 0.5);
            } else if(dashPtr->number < 3) {
                dashList = dashPtr->pattern.array[0];
            } else {
                dashList = 4;
            }
            XSetDashes(((TkPathCanvas *) canvas)->display, outline->gc,
                outline->offset, &dashList, 1);
        }
    }
    if(stipple != None) {
        XSetTSOrigin(((TkPathCanvas *) canvas)->display, outline->gc, 0, 0);
        return 1;
    }
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * DashConvert
 *
 *    Converts a character-like dash-list (e.g. "-..") into an X11-style. l
 *    must point to a string that holds room to at least 2*n characters. If
 *    l == NULL, this function can be used for syntax checking only.
 *
 * Results:
 *    The length of the resulting X11 compatible dash-list. -1 if failed.
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

static int
DashConvert(
    char *l,                   /* Must be at least 2*n chars long, or NULL to
                                * indicate "just check syntax". */
    const char *p,             /* String to parse. */
    int n,                     /* Length of string to parse, or -1 to
                                * indicate that strlen() should be used. */
    double width)
{              /* Width of line. */
    int result = 0;
    int size, intWidth;

    if(n < 0) {
        n = (int)strlen(p);
    }
    intWidth = (int)(width + 0.5);
    if(intWidth < 1) {
        intWidth = 1;
    }
    while(n-- && *p) {
        switch (*p++) {
        case ' ':
            if(result) {
                if(l) {
                    l[-1] += intWidth + 1;
                }
                continue;
            }
            return 0;
        case '_':
            size = 8;
            break;
        case '-':
            size = 6;
            break;
        case ',':
            size = 4;
            break;
        case '.':
            size = 2;
            break;
        default:
            return -1;
        }
        if(l) {
            *l++ = size * intWidth;
            *l++ = 4 * intWidth;
        }
        result += 2;
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TranslateAndAppendCoords --
 *
 *    This is a helper routine for TkPathCanvTranslatePath() below.
 *
 *    Given an (x,y) coordinate pair within a canvas, this function computes
 *    the corresponding coordinates at which the point should be drawn in
 *    the drawable used for display. Those coordinates are then written into
 *    outArr[numOut*2] and outArr[numOut*2+1].
 *
 * Results:
 *    There is no return value.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

static void
TranslateAndAppendCoords(
    TkPathCanvas * canvPtr,    /* The canvas. */
    double x,                  /* Coordinates in canvas space. */
    double y,
    XPoint * outArr,           /* Write results into this array */
    int numOut)
{              /* Num of prior entries in outArr[] */
    double tmp;

    tmp = x - canvPtr->drawableXOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    outArr[numOut].x = (short)tmp;

    tmp = y - canvPtr->drawableYOrigin;
    if(tmp > 0) {
        tmp += 0.5;
    } else {
        tmp -= 0.5;
    }
    outArr[numOut].y = (short)tmp;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCanvTranslatePath
 *
 *    Translate a line or polygon path so that all vertices are within a
 *    rectangle that is 1000 pixels larger than the total size of the canvas
 *    window. This will prevent pixel coordinates from overflowing the
 *    16-bit integer size limitation imposed by most windowing systems.
 *
 *    coordPtr must point to an array of doubles, two doubles per vertex.
 *    There are a total of numVertex vertices, or 2*numVertex entries in
 *    coordPtr. The result vertices written into outArr have their
 *    coordinate origin shifted to canvPtr->drawableXOrigin by
 *    canvPtr->drawableYOrigin. There might be as many as 3 times more
 *    output vertices than there are input vertices. The calling function
 *    should allocate space accordingly.
 *
 *    This routine limits the width and height of a canvas window to 31767
 *    pixels. At the highest resolution display devices available today (210
 *    ppi in Jan 2003) that's a window that is over 13 feet wide and tall.
 *    Should be enough for the near future.
 *
 * Results:
 *    Clipped and translated path vertices are written into outArr[]. There
 *    might be as many as twice the vertices in outArr[] as there are in
 *    coordPtr[]. The return value is the number of vertices actually
 *    written into outArr[].
 *
 * Side effects:
 *    None
 *
 *--------------------------------------------------------------
 */

int
TkPathCanvTranslatePath(
    TkPathCanvas * canvPtr,    /* The canvas */
    int numVertex,             /* Number of vertices specified by
                                * coordArr[] */
    double *coordArr,          /* X and Y coordinates for each vertex */
    int closedPath,            /* True if this is a closed polygon */
    XPoint * outArr)
{              /* Write results here, if not NULL */
    int numOutput = 0;         /* Number of output coordinates */
    double lft, rgh;           /* Left and right sides of the bounding box */
    double top, btm;           /* Top and bottom sizes of the bounding box */
    double *tempArr;           /* Temporary storage used by the clipper */
    double *a, *b, *t;         /* Pointers to parts of the temporary
                                * storage */
    int i, j;                  /* Loop counters */
    int maxOutput;             /* Maximum number of outputs that we will
                                * allow */
    double limit[4];           /* Boundries at which clipping occurs */
    double staticSpace[480];   /* Temp space from the stack */

    /*
     * Constrain all vertices of the path to be within a box that is no larger
     * than 32000 pixels wide or height. The top-left corner of this clipping
     * box is 1000 pixels above and to the left of the top left corner of the
     * window on which the canvas is displayed.
     *
     * This means that a canvas will not display properly on a canvas window
     * that is larger than 31000 pixels wide or high. That is not a problem
     * today, but might someday become a factor for ultra-high resolutions
     * displays.
     *
     * The X11 protocol allows us (in theory) to expand the size of the
     * clipping box to 32767 pixels. But we have found experimentally that
     * XFree86 sometimes fails to draw lines correctly if they are longer than
     * about 32500 pixels. So we have left a little margin in the size to mask
     * that bug.
     */

    lft = canvPtr->xOrigin - 1000.0;
    top = canvPtr->yOrigin - 1000.0;
    rgh = lft + 32000.0;
    btm = top + 32000.0;

    /*
     * Try the common case first - no clipping. Loop over the input
     * coordinates and translate them into appropriate output coordinates.
     * But if a vertex outside of the bounding box is seen, break out of the
     * loop.
     *
     * Most of the time, no clipping is needed, so this one loop is sufficient
     * to do the translation.
     */

    for(i = 0; i < numVertex; i++) {
    double x, y;

        x = coordArr[i * 2];
        y = coordArr[i * 2 + 1];
        if(x < lft || x > rgh || y < top || y > btm) {
            break;
        }
        TranslateAndAppendCoords(canvPtr, x, y, outArr, numOutput++);
    }
    if(i == numVertex) {
        assert(numOutput == numVertex);
        return numOutput;
    }

    /*
     * If we reach this point, it means that some clipping is required. Begin
     * by allocating some working storage - at least 6 times as much space as
     * coordArr[] requires. Divide this space into two separate arrays a[] and
     * b[]. Initialize a[] to be equal to coordArr[].
     */

    if(numVertex * 12 <= (int)(sizeof(staticSpace) / sizeof(staticSpace[0]))) {
        tempArr = staticSpace;
    } else {
        tempArr = (double *)ckalloc(numVertex * 12 * sizeof(tempArr[0]));
    }
    for(i = 0; i < numVertex * 2; i++) {
        tempArr[i] = coordArr[i];
    }
    a = tempArr;
    b = &tempArr[numVertex * 6];

    /*
     * We will make four passes through the input data. On each pass, we copy
     * the contents of a[] over into b[]. As we copy, we clip any line
     * segments that extend to the right past xClip then we rotate the
     * coordinate system 90 degrees clockwise. After each pass is complete, we
     * interchange a[] and b[] in preparation for the next pass.
     *
     * Each pass clips line segments that extend beyond a single side of the
     * bounding box, and four passes rotate the coordinate system back to its
     * original value. I'm not an expert on graphics algorithms, but I think
     * this is called Cohen-Sutherland polygon clipping.
     *
     * The limit[] array contains the xClip value used for each of the four
     * passes.
     */

    limit[0] = rgh;
    limit[1] = -top;
    limit[2] = -lft;
    limit[3] = btm;

    /*
     * This is the loop that makes the four passes through the data.
     */

    maxOutput = numVertex * 3;
    for(j = 0; j < 4; j++) {
    double xClip = limit[j];
    int inside = a[0] < xClip;
    double priorY = a[1];
        numOutput = 0;

        /*
         * Clip everything to the right of xClip. Store the results in b[]
         * rotated by 90 degrees clockwise.
         */

        for(i = 0; i < numVertex; i++) {
    double x = a[i * 2];
    double y = a[i * 2 + 1];

            if(x >= xClip) {
                /*
                 * The current vertex is to the right of xClip.
                 */

                if(inside) {
                    /*
                     * If the current vertex is to the right of xClip but the
                     * previous vertex was left of xClip, then draw a line
                     * segment from the previous vertex to until it intersects
                     * the vertical at xClip.
                     */

    double x0, y0, yN;

                    assert(i > 0);
                    x0 = a[i * 2 - 2];
                    y0 = a[i * 2 - 1];
                    yN = y0 + (y - y0) * (xClip - x0) / (x - x0);
                    b[numOutput * 2] = -yN;
                    b[numOutput * 2 + 1] = xClip;
                    numOutput++;
                    if(numOutput > maxOutput)
                        assert(0);
                    priorY = yN;
                    inside = 0;
                } else if(i == 0) {
                    /*
                     * If the first vertex is to the right of xClip, add a
                     * vertex that is the projection of the first vertex onto
                     * the vertical xClip line.
                     */

                    b[0] = -y;
                    b[1] = xClip;
                    numOutput = 1;
                    priorY = y;
                }
            } else {
                /*
                 * The current vertex is to the left of xClip
                 */
                if(!inside) {
                    /* If the current vertex is on the left of xClip and one
                     * or more prior vertices where to the right, then we have
                     * to draw a line segment along xClip that extends from
                     * the spot where we first crossed from left to right to
                     * the spot where we cross back from right to left.
                     */

    double x0, y0, yN;

                    assert(i > 0);
                    x0 = a[i * 2 - 2];
                    y0 = a[i * 2 - 1];
                    yN = y0 + (y - y0) * (xClip - x0) / (x - x0);
                    if(yN != priorY) {
                        b[numOutput * 2] = -yN;
                        b[numOutput * 2 + 1] = xClip;
                        numOutput++;
                        assert(numOutput <= maxOutput);
                    }
                    inside = 1;
                }
                b[numOutput * 2] = -y;
                b[numOutput * 2 + 1] = x;
                numOutput++;
                assert(numOutput <= maxOutput);
            }
        }

        /*
         * Interchange a[] and b[] in preparation for the next pass.
         */

        t = a;
        a = b;
        b = t;
        numVertex = numOutput;
    }

    /*
     * All clipping is now finished. Convert the coordinates from doubles into
     * XPoints and translate the origin for the drawable.
     */

    for(i = 0; i < numVertex; i++) {
        TranslateAndAppendCoords(canvPtr, a[i * 2], a[i * 2 + 1], outArr, i);
    }
    if(tempArr != staticSpace) {
        ckfree((char *)tempArr);
    }
    return numOutput;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCoordsForPointItems --
 *
 *    Used as coordProc for items that have plain single point coords.
 *
 * Results:
 *    Standard tcl result.
 *
 * Side effects:
 *    May store new coords in rectPtr.
 *
 *--------------------------------------------------------------
 */

int
TkPathCoordsForPointItems(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    double *pointPtr,          /* Sets or gets the point here. */
    int objc,
    Tcl_Obj * const objv[])
{
    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewObj();
    Tcl_Obj *subobj = Tcl_NewDoubleObj(pointPtr[0]);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(pointPtr[1]);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if((objc == 1) || (objc == 2)) {
    double x, y;

        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 2) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coordinates: expected 0 or 2",
                        -1));
                return TCL_ERROR;
            }
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0], &x) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                    &y) != TCL_OK)) {
            return TCL_ERROR;
        }
        pointPtr[0] = x;
        pointPtr[1] = y;
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coordinates: expected 0 or 2", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCoordsForRectangularItems --
 *
 *    Used as coordProc for items that have rectangular coords.
 *
 * Results:
 *    Standard tcl result.
 *
 * Side effects:
 *    May store new coords in rectPtr.
 *
 *--------------------------------------------------------------
 */

int
TkPathCoordsForRectangularItems(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    TkPathRect * rectPtr,      /* Sets or gets the box here. */
    int objc,
    Tcl_Obj * const objv[])
{
    if(objc == 0) {
    Tcl_Obj *obj = Tcl_NewObj();
    Tcl_Obj *subobj = Tcl_NewDoubleObj(rectPtr->x1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(rectPtr->y1);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(rectPtr->x2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        subobj = Tcl_NewDoubleObj(rectPtr->y2);
        Tcl_ListObjAppendElement(interp, obj, subobj);
        Tcl_SetObjResult(interp, obj);
    } else if((objc == 1) || (objc == 4)) {
    double x1, y1, x2, y2;

        if(objc == 1) {
            if(Tcl_ListObjGetElements(interp, objv[0], &objc,
                    (Tcl_Obj ***) & objv) != TCL_OK) {
                return TCL_ERROR;
            } else if(objc != 4) {
                Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("wrong # coordinates: expected 0 or 4",
                        -1));
                return TCL_ERROR;
            }
        }
        if((Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[0],
                    &x1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[1],
                    &y1) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[2],
                    &x2) != TCL_OK)
            || (Tk_PathCanvasGetCoordFromObj(interp, canvas, objv[3],
                    &y2) != TCL_OK)) {
            return TCL_ERROR;
        }

        /*
         * Get an approximation of the path's bounding box
         * assuming zero width outline (stroke).
         * Normalize the corners!
         */
        rectPtr->x1 = MIN(x1, x2);
        rectPtr->y1 = MIN(y1, y2);
        rectPtr->x2 = MAX(x1, x2);
        rectPtr->y2 = MAX(y1, y2);
    } else {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("wrong # coordinates: expected 0 or 4", -1));
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * GetBareArcBbox
 *
 *    Gets an overestimate of the bounding box rectangle of
 *     an arc defined using central parametrization assuming
 *    zero stroke width.
 *     Untransformed coordinates!
 *    Note: 1) all angles clockwise direction!
 *          2) all angles in radians.
 *
 * Results:
 *    A PathRect.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static TkPathRect
GetBareArcBbox(
    double cx,
    double cy,
    double rx,
    double ry,
    double theta1,
    double dtheta,
    double phi)
{
    TkPathRect r = { 1.0e36, 1.0e36, -1.0e36, -1.0e36 };        /* Empty rect. */
    double start, extent, stop, stop2PI;
    double cosStart, sinStart, cosStop, sinStop;

    /* Keep 0 <= start, extent < 2pi
     * and 0 <= stop < 4pi */
    if(dtheta >= 0.0) {
        start = theta1;
        extent = dtheta;
    } else {
        start = theta1 + dtheta;
        extent = -1.0 * dtheta;
    }
    if(start < 0.0) {
        start += 2.0 * M_PI;
        if(start < 0.0) {
            start += 2.0 * M_PI;
        }
    }
    if(start >= 2.0 * M_PI) {
        start -= 2.0 * M_PI;
    }
    stop = start + extent;
    stop2PI = stop - 2.0 * M_PI;
    cosStart = cos(start);
    sinStart = sin(start);
    cosStop = cos(stop);
    sinStop = sin(stop);

    /*
     * Compute bbox for phi = 0.
     * Put everything at (0,0) and shift to (cx,cy) at the end.
     * Look for extreme points of arc:
     *     1) start and stop points
     *    2) any intersections of x and y axes
     * Count both first and second "turns".
     */

    TkPathIncludePointInRect(&r, rx * cosStart, ry * sinStart);
    TkPathIncludePointInRect(&r, rx * cosStop, ry * sinStop);
    if(((start < M_PI / 2.0) && (stop > M_PI / 2.0)) || (stop2PI > M_PI / 2.0)) {
        TkPathIncludePointInRect(&r, 0.0, ry);
    }
    if(((start < M_PI) && (stop > M_PI)) || (stop2PI > M_PI)) {
        TkPathIncludePointInRect(&r, -rx, 0.0);
    }
    if(((start < 3.0 * M_PI / 2.0) && (stop > 3.0 * M_PI / 2.0))
        || (stop2PI > 3.0 * M_PI / 2.0)) {
        TkPathIncludePointInRect(&r, 0.0, -ry);
    }
    if(stop > 2.0 * M_PI) {
        TkPathIncludePointInRect(&r, rx, 0.0);
    }

    /*
     * Rotate the bbox above to get an overestimate of extremas.
     */
    if(fabs(phi) > 1e-6) {
    double cosPhi, sinPhi;
    double x, y;
    TkPathRect rrot = { 1.0e36, 1.0e36, -1.0e36, -1.0e36 };

        cosPhi = cos(phi);
        sinPhi = sin(phi);
        x = r.x1 * cosPhi - r.y1 * sinPhi;
        y = r.x1 * sinPhi + r.y1 * cosPhi;
        TkPathIncludePointInRect(&rrot, x, y);

        x = r.x2 * cosPhi - r.y1 * sinPhi;
        y = r.x2 * sinPhi + r.y1 * cosPhi;
        TkPathIncludePointInRect(&rrot, x, y);

        x = r.x1 * cosPhi - r.y2 * sinPhi;
        y = r.x1 * sinPhi + r.y2 * cosPhi;
        TkPathIncludePointInRect(&rrot, x, y);

        x = r.x2 * cosPhi - r.y2 * sinPhi;
        y = r.x2 * sinPhi + r.y2 * cosPhi;
        TkPathIncludePointInRect(&rrot, x, y);

        r = rrot;
    }

    /* Shift rect to arc center. */
    r.x1 += cx;
    r.y1 += cy;
    r.x2 += cx;
    r.y2 += cy;
    return r;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathGetGenericBarePathBbox
 *
 *    Gets an overestimate of the bounding box rectangle of
 *     a path assuming zero stroke width.
 *     Untransformed coordinates!
 *
 * Results:
 *    A TkPathRect.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

TkPathRect
TkPathGetGenericBarePathBbox(
    TkPathAtom * atomPtr)
{
double x1, y1, x2, y2, x3, y3, x4, y4, x5, y5;
double currentX, currentY;
TkPathRect r = { 1.0e36, 1.0e36, -1.0e36, -1.0e36 };

    currentX = 0.0;
    currentY = 0.0;

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

            TkPathIncludePointInRect(&r, move->x, move->y);
            currentX = move->x;
            currentY = move->y;
            break;
        }
        case TK_PATH_ATOM_L:{
TkLineToAtom *line = (TkLineToAtom *) atomPtr;

            TkPathIncludePointInRect(&r, line->x, line->y);
            currentX = line->x;
            currentY = line->y;
            break;
        }
        case TK_PATH_ATOM_A:{
TkArcAtom *arc = (TkArcAtom *) atomPtr;
int result;
double cx, cy, rx, ry;
double theta1, dtheta;

            result = TkPathEndpointToCentralArcParameters(currentX, currentY,
                arc->x, arc->y, arc->radX, arc->radY,
                DEGREES_TO_RADIANS * arc->angle,
                arc->largeArcFlag, arc->sweepFlag,
                &cx, &cy, &rx, &ry, &theta1, &dtheta);
            if(result == TK_PATH_ARC_Line) {
                TkPathIncludePointInRect(&r, arc->x, arc->y);
            } else if(result == TK_PATH_ARC_OK) {
TkPathRect arcRect;

                arcRect = GetBareArcBbox(cx, cy, rx, ry, theta1, dtheta,
                    DEGREES_TO_RADIANS * arc->angle);
                TkPathIncludePointInRect(&r, arcRect.x1, arcRect.y1);
                TkPathIncludePointInRect(&r, arcRect.x2, arcRect.y2);
            }
            currentX = arc->x;
            currentY = arc->y;
            break;
        }
        case TK_PATH_ATOM_Q:{
TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;

            x1 = (currentX + quad->ctrlX) / 2.0;
            y1 = (currentY + quad->ctrlY) / 2.0;
            x2 = (quad->ctrlX + quad->anchorX) / 2.0;
            y2 = (quad->ctrlY + quad->anchorY) / 2.0;
            TkPathIncludePointInRect(&r, x1, y1);
            TkPathIncludePointInRect(&r, x2, y2);
            currentX = quad->anchorX;
            currentY = quad->anchorY;
            TkPathIncludePointInRect(&r, currentX, currentY);
            break;
        }
        case TK_PATH_ATOM_C:{
TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            x1 = (currentX + curve->ctrlX1) / 2.0;
            y1 = (currentY + curve->ctrlY1) / 2.0;
            x2 = (curve->ctrlX1 + curve->ctrlX2) / 2.0;
            y2 = (curve->ctrlY1 + curve->ctrlY2) / 2.0;
            x3 = (curve->ctrlX2 + curve->anchorX) / 2.0;
            y3 = (curve->ctrlY2 + curve->anchorY) / 2.0;
            TkPathIncludePointInRect(&r, x1, y1);
            TkPathIncludePointInRect(&r, x3, y3);
            x4 = (x1 + x2) / 2.0;
            y4 = (y1 + y2) / 2.0;
            x5 = (x2 + x3) / 2.0;
            y5 = (y2 + y3) / 2.0;
            TkPathIncludePointInRect(&r, x4, y4);
            TkPathIncludePointInRect(&r, x5, y5);
            currentX = curve->anchorX;
            currentY = curve->anchorY;
            TkPathIncludePointInRect(&r, currentX, currentY);
            break;
        }
        case TK_PATH_ATOM_Z:{
            /* empty */
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:{
TkEllipseAtom *ell = (TkEllipseAtom *) atomPtr;
            TkPathIncludePointInRect(&r, ell->cx - ell->rx, ell->cy - ell->ry);
            TkPathIncludePointInRect(&r, ell->cx + ell->rx, ell->cy + ell->ry);
            break;
        }
        case TK_PATH_ATOM_RECT:{
TkRectAtom *rect = (TkRectAtom *) atomPtr;
            TkPathIncludePointInRect(&r, rect->x, rect->y);
            TkPathIncludePointInRect(&r, rect->x + rect->width,
                rect->y + rect->height);
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
    return r;
}

static void
CopyPoint(
    double ptSrc[2],
    double ptDst[2])
{
    ptDst[0] = ptSrc[0];
    ptDst[1] = ptSrc[1];
}

/*
 *--------------------------------------------------------------
 *
 * PathGetMiterPoint --
 *
 *    Given three points forming an angle, compute the
 *    coordinates of the outside point of the mitered corner
 *    formed by a line of a given width at that angle.
 *
 * Results:
 *    If the angle formed by the three points is less than
 *    11 degrees then 0 is returned and m isn't modified.
 *    Otherwise 1 is returned and the point of the "sharp"
 *    edge is returned.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathGetMiterPoint(
    double p1[],               /* Points to x- and y-coordinates of point
                                * before vertex. */
    double p0[],               /* Points to x- and y-coordinates of vertex
                                * for mitered joint. */
    double p2[],               /* Points to x- and y-coordinates of point
                                * after vertex. */
    double width,              /* Width of line.  */
    double sinThetaLimit,      /* Sinus of theta miter limit. */
    double m[])
{              /* The miter point; the sharp edge. */
    double n1[2], n2[2];       /* The normalized vectors. */
    double len1, len2;
    double sinTheta;

    /*
     * A little geometry:
     *          p0
     *          /\
     *     n1  /  \ n2
     *        /    \
     *       p1    p2
     *
     * n1 = (p0-p1)/|p0-p1|
     * n2 = (p0-p2)/|p0-p2|
     *
     * theta is the angle between n1 and n2 which is identical
     * to the angle of the corner. We keep 0 <= theta <= PI so
     * that sin(theta) is never negative. If you consider the triangle
     * formed by the bisection (mid line) and any of the lines,
     * then theta/2 is the angle of that triangle.
     * Define:
     *
     * n = (n1+n2)/|n1+n2|
     *
     * Simple geometry gives:
     *
     * |n1+n2| = 2cos(theta/2)
     *
     * and similar if d is the distance from p0 to the miter point:
     *
     * d = (w/2)/(sin(theta/2)
     *
     * where w is the line width.
     * For the miter point p we then get:
     *                   n1+n2            w/2
     * p = p0 + n*d = ------------- . ------------
     *                2cos(theta/2)   sin(theta/2)
     *
     * Using sin(2a) = 2sin(a)cos(a) we get:
     *
     * p = p0 + w/(2sin(theta)) * (n1 + n2)
     *
     * Use the cross product to get theta as: a x b = |a| |b| sin(angle) as:
     *
     * sin(theta) = |n1x*n2y - n1y*n2x|
     */

    /* n1 points from p1 to p0. */
    n1[0] = p0[0] - p1[0];
    n1[1] = p0[1] - p1[1];
    len1 = hypot(n1[0], n1[1]);
    if(len1 < 1e-6) {
        return 0;
    }
    n1[0] /= len1;
    n1[1] /= len1;

    /* n2 points from p2 to p0. */
    n2[0] = p0[0] - p2[0];
    n2[1] = p0[1] - p2[1];
    len2 = hypot(n2[0], n2[1]);
    if(len2 < 1e-6) {
        return 0;
    }
    n2[0] /= len2;
    n2[1] /= len2;

    sinTheta = fabs(n1[0] * n2[1] - n1[1] * n2[0]);
    if(sinTheta < sinThetaLimit) {
        return 0;
    }
    m[0] = p0[0] + width / (2.0 * sinTheta) * (n1[0] + n2[0]);
    m[1] = p0[1] + width / (2.0 * sinTheta) * (n1[1] + n2[1]);

    return 1;
}

static void
IncludeMiterPointsInRect(
    double p1[2],
    double p2[2],
    double p3[2],
    TkPathRect * bounds,
    double width,
    double sinThetaLimit)
{
    double m[2];

    if(PathGetMiterPoint(p1, p2, p3, width, sinThetaLimit, m)) {
        TkPathIncludePointInRect(bounds, m[0], m[1]);
    }
}

static TkPathRect
GetMiterBbox(
    TkPathAtom * atomPtr,
    double width,
    double miterLimit)
{
    int npts;
    double p1[2], p2[2], p3[2];
    double current[2], second[2];
    double sinThetaLimit;
    TkPathRect bounds = { 1.0e36, 1.0e36, -1.0e36, -1.0e36 };

    npts = 0;
    current[0] = 0.0;
    current[1] = 0.0;
    second[0] = 0.0;
    second[1] = 0.0;

    /* Find sin(thetaLimit) which is needed to get miter points:
     * miterLimit = 1/sin(theta/2) =approx 2/theta
     */
    if(miterLimit > 8) {
        /* theta:
         * Exact:  0.250655662336
         * Approx: 0.25
         */
        sinThetaLimit = 2.0 / miterLimit;
    } else if(miterLimit > 2) {
        sinThetaLimit = sin(2 * asin(1.0 / miterLimit));
    } else {
        return bounds;
    }

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;
            current[0] = move->x;
            current[1] = move->y;
            p1[0] = move->x;
            p1[1] = move->y;
            npts = 1;
            break;
        }
        case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;
            current[0] = line->x;
            current[1] = line->y;
            CopyPoint(p2, p3);
            CopyPoint(p1, p2);
            p1[0] = line->x;
            p1[1] = line->y;
            npts++;
            if(npts >= 3) {
                IncludeMiterPointsInRect(p1, p2, p3, &bounds, width,
                    sinThetaLimit);
            }
            break;
        }
        case TK_PATH_ATOM_A:{
    TkArcAtom *arc = (TkArcAtom *) atomPtr;
            current[0] = arc->x;
            current[1] = arc->y;
            /* @@@ TODO */
            break;
        }
        case TK_PATH_ATOM_Q:{
    TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;
            current[0] = quad->anchorX;
            current[1] = quad->anchorY;
            /* The control point(s) form the tangent lines at ends. */
            CopyPoint(p2, p3);
            CopyPoint(p1, p2);
            p1[0] = quad->ctrlX;
            p1[1] = quad->ctrlY;
            npts++;
            if(npts >= 3) {
                IncludeMiterPointsInRect(p1, p2, p3, &bounds, width,
                    sinThetaLimit);
            }
            CopyPoint(p1, p2);
            p1[0] = quad->anchorX;
            p1[1] = quad->anchorY;
            npts += 2;
            break;
        }
        case TK_PATH_ATOM_C:{
    TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;
            current[0] = curve->anchorX;
            current[1] = curve->anchorY;
            /* The control point(s) form the tangent lines at ends. */
            CopyPoint(p2, p3);
            CopyPoint(p1, p2);
            p1[0] = curve->ctrlX1;
            p1[1] = curve->ctrlY1;
            npts++;
            if(npts >= 3) {
                IncludeMiterPointsInRect(p1, p2, p3, &bounds, width,
                    sinThetaLimit);
            }
            p1[0] = curve->ctrlX2;
            p1[1] = curve->ctrlY2;
            p1[0] = curve->anchorX;
            p1[1] = curve->anchorX;
            npts += 2;
            break;
        }
        case TK_PATH_ATOM_Z:{
    TkCloseAtom *close = (TkCloseAtom *) atomPtr;
            current[0] = close->x;
            current[1] = close->y;
            CopyPoint(p2, p3);
            CopyPoint(p1, p2);
            p1[0] = close->x;
            p1[1] = close->y;
            npts++;
            if(npts >= 3) {
                IncludeMiterPointsInRect(p1, p2, p3, &bounds, width,
                    sinThetaLimit);
            }
            /* Check also the joint of first segment with the last segment. */
            CopyPoint(p2, p3);
            CopyPoint(p1, p2);
            CopyPoint(second, p1);
            if(npts >= 3) {
                IncludeMiterPointsInRect(p1, p2, p3, &bounds, width,
                    sinThetaLimit);
            }
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            /* Empty. */
            break;
        }
        }
        if(npts == 2) {
            CopyPoint(current, second);
        }
        atomPtr = atomPtr->nextPtr;
    }

    return bounds;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathGetGenericPathTotalBboxFromBare --
 *
 *    This procedure calculates the items total bbox from the
 *    bare bbox. Untransformed coords!
 *
 * Results:
 *    TkPathRect.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

TkPathRect
TkPathGetGenericPathTotalBboxFromBare(
    TkPathAtom * atomPtr,
    Tk_PathStyle * stylePtr,
    TkPathRect * bboxPtr)
{
double fudge = 1.0;
double width = 0.0;
TkPathRect rect = *bboxPtr;

    if(stylePtr->strokeColor != NULL) {
        width = stylePtr->strokeWidth;
        if(width < 1.0) {
            width = 1.0;
        }
        rect.x1 -= width;
        rect.x2 += width;
        rect.y1 -= width;
        rect.y2 += width;
    }

    /* Add the miter corners if necessary. */
    if(atomPtr && (stylePtr->joinStyle == JoinMiter)
        && (stylePtr->strokeWidth > 1.0)) {
TkPathRect miterBox;
        miterBox = GetMiterBbox(atomPtr, width, stylePtr->miterLimit);
        if(!IsPathRectEmpty(&miterBox)) {
            TkPathIncludePointInRect(&rect, miterBox.x1, miterBox.y1);
            TkPathIncludePointInRect(&rect, miterBox.x2, miterBox.y2);
        }
    }

    /*
     * Add one (or two if antialiasing) more pixel of fudge factor just to be safe
     * (e.g. X may round differently than we do).
     */

    if(Tk_PathAntiAlias) {
        fudge = 2;
    }
    rect.x1 -= fudge;
    rect.x2 += fudge;
    rect.y1 -= fudge;
    rect.y2 += fudge;

    return rect;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathSetGenericPathHeaderBbox --
 *
 *    This procedure sets the (transformed) bbox in the items header.
 *    It is a (too?) conservative measure.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    The fields x1, y1, x2, and y2 are updated in the header
 *    for itemPtr.
 *
 *--------------------------------------------------------------
 */

void
TkPathSetGenericPathHeaderBbox(
    Tk_PathItem * headerPtr,
    TkPathMatrix * mPtr,
    TkPathRect * totalBboxPtr)
{
TkPathRect rect;

    rect = *totalBboxPtr;

    if(mPtr != NULL) {
double x, y;
TkPathRect r = TkPathNewEmptyPathRect();

        /* Take each four corners in turn. */
        x = rect.x1, y = rect.y1;
        PathApplyTMatrix(mPtr, &x, &y);
        TkPathIncludePointInRect(&r, x, y);

        x = rect.x2, y = rect.y1;
        PathApplyTMatrix(mPtr, &x, &y);
        TkPathIncludePointInRect(&r, x, y);

        x = rect.x1, y = rect.y2;
        PathApplyTMatrix(mPtr, &x, &y);
        TkPathIncludePointInRect(&r, x, y);

        x = rect.x2, y = rect.y2;
        PathApplyTMatrix(mPtr, &x, &y);
        TkPathIncludePointInRect(&r, x, y);
        rect = r;
    }
    headerPtr->x1 = (int)rect.x1;
    headerPtr->x2 = (int)rect.x2;
    headerPtr->y1 = (int)rect.y1;
    headerPtr->y2 = (int)rect.y2;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathGenericPathToPoint --
 *
 *    Computes the distance from a given point to a given
 *    line, in canvas units.
 *
 * Results:
 *    The return value is 0 if the point whose x and y coordinates
 *    are pointPtr[0] and pointPtr[1] is inside the line.  If the
 *    point isn't inside the line then the return value is the
 *    distance from the point to the line.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

double
TkPathGenericPathToPoint(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against point. */
    Tk_PathStyle * stylePtr,
    TkPathAtom * atomPtr,
    int maxNumSegments,
    double *pointPtr)
{              /* Pointer to x and y coordinates. */
    int numPoints, numStrokes;
    int isclosed;
    int intersections, nonzerorule;
    int sumIntersections = 0, sumNonzerorule = 0;
    double *polyPtr;
    double bestDist, radius, width, dist;
    Tk_PathState state = itemPtr->state;
    TkPathMatrix *matrixPtr = stylePtr->matrixPtr;
    double staticSpace[2 * MAX_NUM_STATIC_SEGMENTS];

    bestDist = 1.0e36;

    if(state == TK_PATHSTATE_HIDDEN) {
        return bestDist;
    }
    if(!HaveAnyFillFromPathColor(stylePtr->fill)
        && (stylePtr->strokeColor == NULL)) {
        return bestDist;
    }
    if(atomPtr == NULL) {
        return bestDist;
    }

    /*
     * Do we need more memory or can we use static space?
     */
    if(maxNumSegments > MAX_NUM_STATIC_SEGMENTS) {
        polyPtr =
            (double *)ckalloc((unsigned)(2 * maxNumSegments * sizeof(double)));
    } else {
        polyPtr = staticSpace;
    }
    width = stylePtr->strokeWidth;
    if(width < 1.0) {
        width = 1.0;
    }
    radius = width / 2.0;

    /*
     * Loop through each subpath, creating the approximate polyline,
     * and do the *ToPoint functions.
     *
     * Note: Strokes can be treated independently for each subpath,
     *         but fills cannot since subpaths may intersect creating
     *         "holes".
     */

    while(atomPtr != NULL) {
        MakeSubPathSegments(&atomPtr, polyPtr, &numPoints, &numStrokes,
            matrixPtr);
        isclosed = 0;
        if(numStrokes == numPoints) {
            isclosed = 1;
        }

        /*
         * This gives the min distance to the *stroke* AND the
         * number of intersections of the two types.
         */
        dist = PathPolygonToPointEx(polyPtr, numPoints, pointPtr,
            &intersections, &nonzerorule);
        sumIntersections += intersections;
        sumNonzerorule += nonzerorule;
        if((stylePtr->strokeColor != NULL)
            && (stylePtr->strokeWidth <= kPathStrokeThicknessLimit)) {

            /*
             * This gives the distance to a zero width polyline.
             * Use a simple scheme to adjust for a small width.
             */
            dist -= radius;
        }
        if(dist < bestDist) {
            bestDist = dist;
        }
        if(bestDist <= 0.0) {
            bestDist = 0.0;
            goto done;
        }

        /*
         * For wider strokes we must make a more detailed analysis.
         * Yes, there is an infinitesimal overlap to the above just
         * to be on the safe side.
         */
        if((stylePtr->strokeColor != NULL)
            && (stylePtr->strokeWidth >= kPathStrokeThicknessLimit)) {
            dist =
                PathThickPolygonToPoint(stylePtr->joinStyle, stylePtr->capStyle,
                width, isclosed, polyPtr, numPoints, pointPtr);
            if(dist < bestDist) {
                bestDist = dist;
            }
            if(bestDist <= 0.0) {
                bestDist = 0.0;
                goto done;
            }
        }
    }

    /*
     * We've processed all of the points.
     * EvenOddRule: If the number of intersections is odd,
     *            the point is inside the polygon.
     * WindingRule (nonzero): If the number of directed intersections
     *            are nonzero, then inside.
     */
    if(HaveAnyFillFromPathColor(stylePtr->fill)) {
        if((stylePtr->fillRule == EvenOddRule) && (sumIntersections & 0x1)) {
            bestDist = 0.0;
        } else if((stylePtr->fillRule == WindingRule) && (sumNonzerorule != 0)) {
            bestDist = 0.0;
        }
    }

  done:
    if(polyPtr != staticSpace) {
        ckfree((char *)polyPtr);
    }
    return bestDist;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathGenericPathToArea --
 *
 *    This procedure is called to determine whether an item
 *    lies entirely inside, entirely outside, or overlapping
 *    a given rectangular area.
 *
 *    Each subpath is treated in turn. Generate straight line
 *    segments for each subpath and treat it as a polygon.
 *
 * Results:
 *    -1 is returned if the item is entirely outside the
 *    area, 0 if it overlaps, and 1 if it is entirely
 *    inside the given area.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathGenericPathToArea(
    Tk_PathCanvas canvas,      /* Canvas containing item. */
    Tk_PathItem * itemPtr,     /* Item to check against line. */
    Tk_PathStyle * stylePtr,
    TkPathAtom * atomPtr,
    int maxNumSegments,
    double *areaPtr)
{              /* Pointer to array of four coordinates
                * (x1, y1, x2, y2) describing rectangular
                * area.  */
    int inside;                /* Tentative guess about what to return,
                                * based on all points seen so far:  one
                                * means everything seen so far was
                                * inside the area;  -1 means everything
                                * was outside the area.  0 means overlap
                                * has been found. */
    int numPoints = 0;
    int numStrokes = 0;
    double *polyPtr;
    double currentT[2];
    Tk_PathState state = itemPtr->state;
    TkPathMatrix *matrixPtr = stylePtr->matrixPtr;
    double staticSpace[2 * MAX_NUM_STATIC_SEGMENTS];

    if(state == TK_PATHSTATE_HIDDEN) {
        return -1;
    }
    if(atomPtr == NULL) {
        return -1;
    }
    if((stylePtr->fill != NULL) && (stylePtr->fill->color != NULL) &&
        (stylePtr->strokeColor == NULL)) {
        if(stylePtr->fill->gradientInstPtr == NULL) {
            return -1;
        }
    }

    /*
     * Do we need more memory or can we use static space?
     */
    if(maxNumSegments > MAX_NUM_STATIC_SEGMENTS) {
        polyPtr =
            (double *)ckalloc((unsigned)(2 * maxNumSegments * sizeof(double)));
    } else {
        polyPtr = staticSpace;
    }

    /* A 'M' atom must be first, may show up later as well. */
    if(atomPtr->type == TK_PATH_ATOM_M) {
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

        PathApplyTMatrixToPoint(matrixPtr, &(move->x), currentT);
    } else if(atomPtr->type == TK_PATH_ATOM_ELLIPSE) {
    TkEllipseAtom *ellipse = (TkEllipseAtom *) atomPtr;

        PathApplyTMatrixToPoint(matrixPtr, &(ellipse->cx), currentT);
    } else if(atomPtr->type == TK_PATH_ATOM_RECT) {
    TkRectAtom *rect = (TkRectAtom *) atomPtr;

        PathApplyTMatrixToPoint(matrixPtr, &(rect->x), currentT);
    } else {
        return -1;
    }

    /*
     * This defines the starting point. It is either -1 or 1.
     * If any subseqent segment has a different 'inside'
     * then return 0 since one port (in|out)side and another
     * (out|in)side
     */
    inside = -1;
    if((currentT[0] >= areaPtr[0]) && (currentT[0] <= areaPtr[2])
        && (currentT[1] >= areaPtr[1]) && (currentT[1] <= areaPtr[3])) {
        inside = 1;
    }

    while(atomPtr != NULL) {
        MakeSubPathSegments(&atomPtr, polyPtr, &numPoints, &numStrokes,
            matrixPtr);
        if(SubPathToArea(stylePtr, polyPtr, numPoints, numStrokes, areaPtr,
                inside) != inside) {
            inside = 0;
            goto done;
        }
    }

  done:
    if(polyPtr != staticSpace) {
        ckfree((char *)polyPtr);
    }
    return inside;
}

/*
 *--------------------------------------------------------------
 *
 * ArcSegments --
 *
 *    Given the arc parameters it makes a sequence if line segments.
 *    All angles in radians!
 *    Note that segments are transformed!
 *
 * Results:
 *    The array at *coordPtr gets filled in with 2*numSteps
 *    coordinates, which correspond to the arc.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static void
ArcSegments(
    CentralArcPars * arcPars,
    TkPathMatrix * matrixPtr,
    int includeFirst,          /* Should the first point be included? */
    int numSteps,              /* Number of curve segments to
                                * generate.  */
    double *coordPtr)
{              /* Where to put new points. */
    int i;
    int istart = 1 - includeFirst;
    double cosPhi, sinPhi;
    double cosAlpha, sinAlpha;
    double alpha, dalpha, theta1;
    double cx, cy, rx, ry;

    cosPhi = cos(arcPars->phi);
    sinPhi = sin(arcPars->phi);
    cx = arcPars->cx;
    cy = arcPars->cy;
    rx = arcPars->rx;
    ry = arcPars->ry;
    theta1 = arcPars->theta1;
    dalpha = arcPars->dtheta / numSteps;

    for(i = istart; i <= numSteps; i++, coordPtr += 2) {
        alpha = theta1 + i * dalpha;
        cosAlpha = cos(alpha);
        sinAlpha = sin(alpha);
        coordPtr[0] = cx + rx * cosAlpha * cosPhi - ry * sinAlpha * sinPhi;
        coordPtr[1] = cy + rx * cosAlpha * sinPhi + ry * sinAlpha * cosPhi;
        PathApplyTMatrix(matrixPtr, coordPtr, coordPtr + 1);
    }
}

/*
 * Get maximum number of segments needed to describe path.
 * Needed to see if we can use static space or need to allocate more.
 */

static int
GetArcNumSegments(
    double currentX,
    double currentY,
    TkArcAtom * arc)
{
    int result;
    int ntheta, nlength;
    int numSteps;              /* Number of curve points to
                                * generate.  */
    double cx, cy, rx, ry;
    double theta1, dtheta;

    result = TkPathEndpointToCentralArcParameters(currentX, currentY,
        arc->x, arc->y, arc->radX, arc->radY,
        DEGREES_TO_RADIANS * arc->angle,
        arc->largeArcFlag, arc->sweepFlag,
        &cx, &cy, &rx, &ry, &theta1, &dtheta);
    if(result == TK_PATH_ARC_Line) {
        return 2;
    } else if(result == TK_PATH_ARC_Skip) {
        return 0;
    }

    /* Estimate the number of steps needed.
     * Max 10 degrees or length 50.
     */
    ntheta = (int)(dtheta / 5.0 + 0.5);
    nlength = (int)(0.5 * (rx + ry) * dtheta / 50 + 0.5);
    numSteps = MAX(4, MAX(ntheta, nlength));;
    return numSteps;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCurveSegments --
 *
 *    Given four control points, create a larger set of points
 *    for a cubic Bezier spline based on the points.
 *
 * Results:
 *    The array at *coordPtr gets filled in with 2*numSteps
 *    coordinates, which correspond to the Bezier spline defined
 *    by the four control points.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

void
TkPathCurveSegments(
    double control[],          /* Array of coordinates for four
                                * control points:  x0, y0, x1, y1,
                                * ... x3 y3. */
    int includeFirst,          /* Should the first point be included? */
    int numSteps,              /* Number of curve segments to generate. */
    double *coordPtr)
{              /* Where to put new points. */
    int i;
    int istart = 1 - includeFirst;
    double u, u2, u3, t, t2, t3;

    /*
     * We should use the 'de Castlejau' algorithm to iterate
     * line segments until a certain tolerance.
     */

    for(i = istart; i <= numSteps; i++, coordPtr += 2) {
        t = ((double)i) / ((double)numSteps);
        t2 = t * t;
        t3 = t2 * t;
        u = 1.0 - t;
        u2 = u * u;
        u3 = u2 * u;
        coordPtr[0] = control[0] * u3
            + 3.0 * (control[2] * t * u2 + control[4] * t2 * u) +
            control[6] * t3;
        coordPtr[1] =
            control[1] * u3 + 3.0 * (control[3] * t * u2 +
            control[5] * t2 * u) + control[7] * t3;
    }
}

/*
 *--------------------------------------------------------------
 *
 * QuadBezierSegments --
 *
 *    Given three control points, create a larger set of points
 *    for a quadratic Bezier spline based on the points.
 *
 * Results:
 *    The array at *coordPtr gets filled in with 2*numSteps
 *    coordinates, which correspond to the quadratic Bezier spline defined
 *    by the control points.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static void
QuadBezierSegments(
    double control[],          /* Array of coordinates for three
                                * control points:  x0, y0, x1, y1,
                                * x2, y2. */
    int includeFirst,          /* Should the first point be included? */
    int numSteps,              /* Number of curve segments to generate. */
    double *coordPtr)
{              /* Where to put new points. */
    int i;
    int istart = 1 - includeFirst;
    double u, u2, t, t2;

    for(i = istart; i <= numSteps; i++, coordPtr += 2) {
        t = ((double)i) / ((double)numSteps);
        t2 = t * t;
        u = 1.0 - t;
        u2 = u * u;
        coordPtr[0] =
            control[0] * u2 + 2.0 * control[2] * t * u + control[4] * t2;
        coordPtr[1] =
            control[1] * u2 + 2.0 * control[3] * t * u + control[5] * t2;
    }
}

static void
EllipseSegments(
    double center[],
    double rx,
    double ry,
    double angle,              /* Angle of rotated ellipse. */
    int numSteps,              /* Number of curve segments to generate. */
    double *coordPtr)
{              /* Where to put new points. */
    double phi, delta;
    double cosA, sinA;
    double cosPhi, sinPhi;

    cosA = cos(angle);
    sinA = sin(angle);
    delta = 2 * M_PI / (numSteps - 1);

    for(phi = 0.0; phi <= 2 * M_PI + 1e-6; phi += delta, coordPtr += 2) {
        cosPhi = cos(phi);
        sinPhi = sin(phi);
        coordPtr[0] = center[0] + rx * cosA * cosPhi - ry * sinA * sinPhi;
        coordPtr[1] = center[1] + rx * sinA * cosPhi + ry * cosA * sinPhi;
    }
}

/*
 *--------------------------------------------------------------
 *
 * AddArcSegments, AddQuadBezierSegments, AddCurveToSegments,
 *   AddEllipseToSegments --
 *
 *    Adds a number of points along the arc (curve) to coordPtr
 *    representing straight line segments.
 *
 * Results:
 *    Number of points added.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
AddArcSegments(
    TkPathMatrix * matrixPtr,
    double current[2],         /* Current point. */
    TkArcAtom * arc,
    double *coordPtr)
{              /* Where to put the points. */
    int result;
    int numPoints;
    CentralArcPars arcPars;
    double cx, cy, rx, ry;
    double theta1, dtheta;

    /*
     * Note: The arc parametrization used cannot generally
     * be transformed. Need to transform each line segment separately!
     */

    result = TkPathEndpointToCentralArcParameters(current[0], current[1],
        arc->x, arc->y, arc->radX, arc->radY,
        DEGREES_TO_RADIANS * arc->angle,
        arc->largeArcFlag, arc->sweepFlag,
        &cx, &cy, &rx, &ry, &theta1, &dtheta);
    if(result == TK_PATH_ARC_Line) {
    double pts[2];

        pts[0] = arc->x;
        pts[1] = arc->y;
        PathApplyTMatrix(matrixPtr, pts, pts + 1);
        coordPtr[0] = pts[0];
        coordPtr[1] = pts[1];
        return 1;
    } else if(result == TK_PATH_ARC_Skip) {
        return 0;
    }

    arcPars.cx = cx;
    arcPars.cy = cy;
    arcPars.rx = rx;
    arcPars.ry = ry;
    arcPars.theta1 = theta1;
    arcPars.dtheta = dtheta;
    arcPars.phi = arc->angle;

    numPoints = GetArcNumSegments(current[0], current[1], arc);
    ArcSegments(&arcPars, matrixPtr, 0, numPoints, coordPtr);

    return numPoints;
}

static int
AddQuadBezierSegments(
    TkPathMatrix * matrixPtr,
    double current[2],         /* Current point. */
    TkQuadBezierAtom * quad,
    double *coordPtr)
{              /* Where to put the points. */
    int numPoints;             /* Number of curve points to
                                * generate.  */
    double control[6];

    PathApplyTMatrixToPoint(matrixPtr, current, control);
    PathApplyTMatrixToPoint(matrixPtr, &(quad->ctrlX), control + 2);
    PathApplyTMatrixToPoint(matrixPtr, &(quad->anchorX), control + 4);

    numPoints = TK_PATH_NUMSEGEMENTS_QuadBezier;
    QuadBezierSegments(control, 0, numPoints, coordPtr);

    return numPoints;
}

static int
AddCurveToSegments(
    TkPathMatrix * matrixPtr,
    double current[2],         /* Current point. */
    TkCurveToAtom * curve,
    double *coordPtr)
{
    int numSteps;              /* Number of curve points to
                                * generate.  */
    double control[8];

    PathApplyTMatrixToPoint(matrixPtr, current, control);
    PathApplyTMatrixToPoint(matrixPtr, &(curve->ctrlX1), control + 2);
    PathApplyTMatrixToPoint(matrixPtr, &(curve->ctrlX2), control + 4);
    PathApplyTMatrixToPoint(matrixPtr, &(curve->anchorX), control + 6);

    numSteps = TK_PATH_NUMSEGEMENTS_CurveTo;
    TkPathCurveSegments(control, 1, numSteps, coordPtr);

    return numSteps;
}

static int
AddEllipseToSegments(
    TkPathMatrix * matrixPtr,
    TkEllipseAtom * ellipse,
    double *coordPtr)
{
    int numSteps;
    double rx, ry, angle;
    double c[2], crx[2], cry[2];
    double p[2];

    /*
     * We transform the three points: c, c+rx, c+ry
     * and then compute the parameters for the transformed ellipse.
     * This is because an affine transform of an ellipse is still an ellipse.
     */
    p[0] = ellipse->cx;
    p[1] = ellipse->cy;
    PathApplyTMatrixToPoint(matrixPtr, p, c);
    p[0] = ellipse->cx + ellipse->rx;
    p[1] = ellipse->cy;
    PathApplyTMatrixToPoint(matrixPtr, p, crx);
    p[0] = ellipse->cx;
    p[1] = ellipse->cy + ellipse->ry;
    PathApplyTMatrixToPoint(matrixPtr, p, cry);
    rx = hypot(crx[0] - c[0], crx[1] - c[1]);
    ry = hypot(cry[0] - c[0], cry[1] - c[1]);
    angle = atan2(crx[1] - c[1], crx[0] - c[0]);

    /* Note we add 1 here since we need both start and stop points.
     * Small things wont need so many segments.
     * Approximate circumference: 4(rx+ry)
     */
    if(rx + ry < 2.1) {
        numSteps = 1;
    } else if(rx + ry < 4) {
        numSteps = 3;
    } else if(rx + ry < TK_PATH_NUMSEGEMENTS_Ellipse) {
        numSteps = (int)(rx + ry + 2);
    } else {
        numSteps = TK_PATH_NUMSEGEMENTS_Ellipse + 1;
    }
    EllipseSegments(c, rx, ry, angle, numSteps, coordPtr);

    return numSteps;
}

static int
AddRectToSegments(
    TkPathMatrix * matrixPtr,
    TkRectAtom * rect,
    double *coordPtr)
{
    int i;
    double p[8];

    p[0] = rect->x;
    p[1] = rect->y;
    p[2] = rect->x + rect->width;
    p[3] = rect->y;
    p[4] = rect->x + rect->width;
    p[5] = rect->y + rect->height;
    p[6] = rect->x;
    p[7] = rect->y + rect->height;

    for(i = 0; i < 8; i += 2, coordPtr += 2) {
        PathApplyTMatrix(matrixPtr, p + i, p + i + 1);
        coordPtr[0] = p[i];
        coordPtr[1] = p[i + 1];
    }
    return 4;
}

/*
 *--------------------------------------------------------------
 *
 * MakeSubPathSegments --
 *
 *    Supposed to be a generic segment generator that can be used
 *    by both Area and Point functions.
 *
 * Results:
 *    Points filled into polyPtr...
 *
 * Side effects:
 *    Pointer *atomPtrPtr may be updated.
 *
 *--------------------------------------------------------------
 */

static void
MakeSubPathSegments(
    TkPathAtom ** atomPtrPtr,
    double *polyPtr,
    int *numPointsPtr,
    int *numStrokesPtr,
    TkPathMatrix * matrixPtr)
{
    int first = 1;
    int numPoints;
    int numStrokes;
    int numAdded;
    int isclosed = 0;
    double current[2];         /* Current untransformed point. */
    double *coordPtr;
    TkPathAtom *atomPtr;

    /* @@@     Note that for unfilled paths we could have made a progressive
     *         area (point) check which may be faster since we may stop when 0 (overlapping).
     *           For filled paths we cannot rely on this since the area rectangle
     *        may be entirely enclosed in the path and still overlapping.
     *        (Need better explanation!)
     */

    /*
     * Check each segment of the path.
     * Any transform matrix is applied at the last stage when comparing to rect.
     * 'current' is always untransformed coords.
     */

    current[0] = 0.0;
    current[1] = 0.0;
    numPoints = 0;
    numStrokes = 0;
    isclosed = 0;
    atomPtr = *atomPtrPtr;
    coordPtr = NULL;

    while(atomPtr != NULL) {

        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

            /* A 'M' atom must be first, may show up later as well. */

            if(first) {
                coordPtr = polyPtr;
                current[0] = move->x;
                current[1] = move->y;
                PathApplyTMatrixToPoint(matrixPtr, current, coordPtr);
                coordPtr += 2;
                numPoints = 1;
            } else {

                /*
                 * We have finalized a subpath.
                 */
                goto done;
            }
            first = 0;
            break;
        }
        case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;

            PathApplyTMatrixToPoint(matrixPtr, &(line->x), coordPtr);
            current[0] = line->x;
            current[1] = line->y;
            coordPtr += 2;
            numPoints++;;
            break;
        }
        case TK_PATH_ATOM_A:{
    TkArcAtom *arc = (TkArcAtom *) atomPtr;

            numAdded = AddArcSegments(matrixPtr, current, arc, coordPtr);
            coordPtr += 2 * numAdded;
            numPoints += numAdded;
            current[0] = arc->x;
            current[1] = arc->y;
            break;
        }
        case TK_PATH_ATOM_Q:{
    TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;

            numAdded = AddQuadBezierSegments(matrixPtr, current,
                quad, coordPtr);
            coordPtr += 2 * numAdded;
            numPoints += numAdded;
            current[0] = quad->anchorX;
            current[1] = quad->anchorY;
            break;
        }
        case TK_PATH_ATOM_C:{
    TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            numAdded = AddCurveToSegments(matrixPtr, current, curve, coordPtr);
            coordPtr += 2 * numAdded;
            numPoints += numAdded;
            current[0] = curve->anchorX;
            current[1] = curve->anchorY;
            break;
        }
        case TK_PATH_ATOM_Z:{
    TkCloseAtom *close = (TkCloseAtom *) atomPtr;

            /* Just add the first point to the end. */
            coordPtr[0] = polyPtr[0];
            coordPtr[1] = polyPtr[1];
            coordPtr += 2;
            numPoints++;
            current[0] = close->x;
            current[1] = close->y;
            isclosed = 1;
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:{
    TkEllipseAtom *ellipse = (TkEllipseAtom *) atomPtr;

            if(first) {
                coordPtr = polyPtr;
            }
            numAdded = AddEllipseToSegments(matrixPtr, ellipse, coordPtr);
            coordPtr += 2 * numAdded;
            numPoints += numAdded;
            if(first) {
                /* Not sure about this. Never used anyway! */
                current[0] = ellipse->cx + ellipse->rx;
                current[1] = ellipse->cy;
            }
            break;
        }
        case TK_PATH_ATOM_RECT:{
    TkRectAtom *rect = (TkRectAtom *) atomPtr;

            if(first) {
                coordPtr = polyPtr;
            }
            numAdded = AddRectToSegments(matrixPtr, rect, coordPtr);
            coordPtr += 2 * numAdded;
            numPoints += numAdded;
            current[0] = rect->x;
            current[1] = rect->y;
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }

  done:
    if(numPoints > 1) {
        if(isclosed) {
            numStrokes = numPoints;
        } else {
            numStrokes = numPoints - 1;
        }
    }
    *numPointsPtr = numPoints;
    *numStrokesPtr = numStrokes;
    *atomPtrPtr = atomPtr;

    return;
}

/*
 *--------------------------------------------------------------
 *
 * SubPathToArea --
 *
 *    This procedure is called to determine whether a subpath
 *    lies entirely inside, entirely outside, or overlapping
 *    a given rectangular area.
 *
 * Results:
 *    -1 is returned if the item is entirely outside the
 *    area, 0 if it overlaps, and 1 if it is entirely
 *    inside the given area.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
SubPathToArea(
    Tk_PathStyle * stylePtr,
    double *polyPtr,
    int numPoints,             /* Total number of points. First one
                                * is duplicated in the last. */
    int numStrokes,            /* The number of strokes which is one less
                                * than numPoints if path not closed. */
    double *rectPtr,
    int inside)
{              /* This is the current inside status. */
    double width;

    /* @@@ There is an open question how a closed unfilled polygon
     *    completely enclosing the area rect should be counted.
     *    While the tk canvas polygon item counts it as intersecting (0),
     *    the line item counts it as outside (-1).
     */

    if(HaveAnyFillFromPathColor(stylePtr->fill)) {

        /* This checks a closed polygon with zero width for inside.
         * If area rect completely enclosed it returns intersecting (0).
         */
        if(TkPolygonToArea(polyPtr, numPoints, rectPtr) != inside) {
            return 0;
        }
    }
    if(stylePtr->strokeColor != NULL) {
        width = stylePtr->strokeWidth;
        if(width < 1.0) {
            width = 1.0;
        }
        if(stylePtr->strokeWidth > kPathStrokeThicknessLimit) {
            if(TkThickPolyLineToArea(polyPtr, numPoints,
                    width, stylePtr->capStyle,
                    stylePtr->joinStyle, rectPtr) != inside) {
                return 0;
            }
        } else {
            if(PathPolyLineToArea(polyPtr, numPoints, rectPtr) != inside) {
                return 0;
            }
        }
    }
    return inside;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathTranslatePathAtoms --
 *
 *    This procedure is called to translate a linked list of path atoms.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Path atoms changed.
 *
 *--------------------------------------------------------------
 */

void
TkPathTranslatePathAtoms(
    TkPathAtom * atomPtr,
    double deltaX,             /* Amount by which item is to be */
    double deltaY)
{              /* moved. */
    while(atomPtr != NULL) {
        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

            move->x += deltaX;
            move->y += deltaY;
            break;
        }
        case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;

            line->x += deltaX;
            line->y += deltaY;
            break;
        }
        case TK_PATH_ATOM_A:{
    TkArcAtom *arc = (TkArcAtom *) atomPtr;

            arc->x += deltaX;
            arc->y += deltaY;
            break;
        }
        case TK_PATH_ATOM_Q:{
    TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;

            quad->ctrlX += deltaX;
            quad->ctrlY += deltaY;
            quad->anchorX += deltaX;
            quad->anchorY += deltaY;
            break;
        }
        case TK_PATH_ATOM_C:{
    TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            curve->ctrlX1 += deltaX;
            curve->ctrlY1 += deltaY;
            curve->ctrlX2 += deltaX;
            curve->ctrlY2 += deltaY;
            curve->anchorX += deltaX;
            curve->anchorY += deltaY;
            break;
        }
        case TK_PATH_ATOM_Z:{
    TkCloseAtom *close = (TkCloseAtom *) atomPtr;

            close->x += deltaX;
            close->y += deltaY;
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            Tcl_Panic
                ("TK_PATH_ATOM_ELLIPSE TK_PATH_ATOM_RECT are not supported for TkPathTranslatePathAtoms");
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkPathScalePathAtoms --
 *
 *    This procedure is called to scale a linked list of path atoms.
 *    The following transformation is applied to all point
 *    coordinates:
 *    x' = originX + scaleX*(x-originX)
 *    y' = originY + scaleY*(y-originY)
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Path atoms changed.
 *
 *--------------------------------------------------------------
 */

void
TkPathScalePathAtoms(
    TkPathAtom * atomPtr,
    double originX,
    double originY,            /* Origin about which to scale rect. */
    double scaleX,             /* Amount to scale in X direction. */
    double scaleY)
{              /* Amount to scale in Y direction. */
    while(atomPtr != NULL) {
        switch (atomPtr->type) {
        case TK_PATH_ATOM_M:{
    TkMoveToAtom *move = (TkMoveToAtom *) atomPtr;

            move->x = originX + scaleX * (move->x - originX);
            move->y = originY + scaleY * (move->y - originY);
            break;
        }
        case TK_PATH_ATOM_L:{
    TkLineToAtom *line = (TkLineToAtom *) atomPtr;

            line->x = originX + scaleX * (line->x - originX);
            line->y = originY + scaleY * (line->y - originY);
            break;
        }
        case TK_PATH_ATOM_A:{
    TkArcAtom *arc = (TkArcAtom *) atomPtr;
            /*
             * @@@ TODO: This is a very much simplified math which is WRONG!
             */
            if(fabs(fmod(arc->angle, 180.0)) < 0.001) {
                arc->radX = scaleX * arc->radX;
                arc->radY = scaleY * arc->radY;
            } else if(fabs(fmod(arc->angle, 90.0)) < 0.001) {
                arc->radX = scaleY * arc->radX;
                arc->radY = scaleX * arc->radY;
            } else {
    double angle;
    double nx, ny;

                if(scaleX == 0.0)
                    Tcl_Panic("singularity when scaling arc atom");
                angle =
                    atan(scaleY / scaleX * tan(arc->angle *
                        DEGREES_TO_RADIANS));
                nx = cos(arc->angle * DEGREES_TO_RADIANS);
                ny = sin(arc->angle * DEGREES_TO_RADIANS);

                arc->angle = angle * RADIANS_TO_DEGREES;
                arc->radX = arc->radX * hypot(scaleX * nx, scaleY * ny);
                arc->radY = arc->radY * hypot(-scaleX * ny, scaleY * nx);
            }
            arc->x = originX + scaleX * (arc->x - originX);
            arc->y = originY + scaleY * (arc->y - originY);
            break;
        }
        case TK_PATH_ATOM_Q:{
    TkQuadBezierAtom *quad = (TkQuadBezierAtom *) atomPtr;

            quad->ctrlX = originX + scaleX * (quad->ctrlX - originX);
            quad->ctrlY = originY + scaleY * (quad->ctrlY - originY);
            quad->anchorX = originX + scaleX * (quad->anchorX - originX);
            quad->anchorY = originY + scaleY * (quad->anchorY - originY);
            break;
        }
        case TK_PATH_ATOM_C:{
    TkCurveToAtom *curve = (TkCurveToAtom *) atomPtr;

            curve->ctrlX1 = originX + scaleX * (curve->ctrlX1 - originX);
            curve->ctrlY1 = originY + scaleY * (curve->ctrlY1 - originY);
            curve->ctrlX2 = originX + scaleX * (curve->ctrlX2 - originX);
            curve->ctrlY2 = originY + scaleY * (curve->ctrlY2 - originY);
            curve->anchorX = originX + scaleX * (curve->anchorX - originX);
            curve->anchorY = originY + scaleY * (curve->anchorY - originY);
            break;
        }
        case TK_PATH_ATOM_Z:{
    TkCloseAtom *close = (TkCloseAtom *) atomPtr;

            close->x = originX + scaleX * (close->x - originX);
            close->y = originY + scaleY * (close->y - originY);
            break;
        }
        case TK_PATH_ATOM_ELLIPSE:
        case TK_PATH_ATOM_RECT:{
            Tcl_Panic
                ("TK_PATH_ATOM_ELLIPSE TK_PATH_ATOM_RECT are not supported for TkPathScalePathAtoms");
            break;
        }
        }
        atomPtr = atomPtr->nextPtr;
    }
}

/*------------------*/

TkPathMatrix
TkPathGetCanvasTMatrix(
    Tk_PathCanvas canvas)
{
TkPathMatrix m = TK_PATH_UNIT_TMATRIX;
TkPathCanvas *path = (TkPathCanvas *) canvas;

    /* @@@ Any scaling involved as well??? */
    m.tx = -path->drawableXOrigin;
    m.ty = -path->drawableYOrigin;
    return m;
}

TkPathRect
TkPathNewEmptyPathRect(
    void)
{
TkPathRect r;

    r.x1 = 1.0e36;
    r.y1 = 1.0e36;
    r.x2 = -1.0e36;
    r.y2 = -1.0e36;
    return r;
}

static int
IsPathRectEmpty(
    TkPathRect * r)
{
    if((r->x2 >= r->x1) && (r->y2 >= r->y1)) {
        return 0;
    } else {
        return 1;
    }
}

void
TkPathIncludePointInRect(
    TkPathRect * r,
    double x,
    double y)
{
    r->x1 = MIN(r->x1, x);
    r->y1 = MIN(r->y1, y);
    r->x2 = MAX(r->x2, x);
    r->y2 = MAX(r->y2, y);
}

void
TkPathTranslatePathRect(
    TkPathRect * r,
    double deltaX,
    double deltaY)
{
    r->x1 += deltaX;
    r->x2 += deltaX;
    r->y1 += deltaY;
    r->y2 += deltaY;
}

void
TkPathScalePathRect(
    TkPathRect * r,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    r->x1 = originX + scaleX * (r->x1 - originX);
    r->x2 = originX + scaleX * (r->x2 - originX);
    r->y1 = originY + scaleY * (r->y1 - originY);
    r->y2 = originY + scaleY * (r->y2 - originY);
}

void
TkPathTranslateItemHeader(
    Tk_PathItem * itemPtr,
    double deltaX,
    double deltaY)
{
    TkPathTranslatePathRect(&itemPtr->totalBbox, deltaX, deltaY);

    /* @@@ TODO: Beware for cumulated round-off errors! */
    /* If all coords == -1 the item is hidden. */
    if((itemPtr->x1 != -1) || (itemPtr->x2 != -1) ||
        (itemPtr->y1 != -1) || (itemPtr->y2 != -1)) {
    Tk_PathStyle style;

        style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
        TkPathSetGenericPathHeaderBbox(itemPtr, style.matrixPtr,
            &itemPtr->totalBbox);
        TkPathCanvasFreeInheritedStyle(&style);
    }
}

void
TkPathScaleItemHeader(
    Tk_PathItem * itemPtr,
    double originX,
    double originY,
    double scaleX,
    double scaleY)
{
    TkPathScalePathRect(&itemPtr->totalBbox, originX, originY, scaleX, scaleY);

    /* @@@ TODO: Beware for cumulated round-off errors! */
    /* If all coords == -1 the item is hidden. */
    if((itemPtr->x1 != -1) || (itemPtr->x2 != -1) ||
        (itemPtr->y1 != -1) || (itemPtr->y2 != -1)) {
    int min, max;
    Tk_PathStyle style;

        style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
        TkPathSetGenericPathHeaderBbox(itemPtr, style.matrixPtr,
            &itemPtr->totalBbox);
        TkPathCanvasFreeInheritedStyle(&style);

        min = MIN(itemPtr->x1, itemPtr->x2);
        max = MAX(itemPtr->x1, itemPtr->x2);
        itemPtr->x1 = min;
        itemPtr->x2 = max;
        min = MIN(itemPtr->y1, itemPtr->y2);
        max = MAX(itemPtr->y1, itemPtr->y2);
        itemPtr->y1 = min;
        itemPtr->y2 = max;
    }
}

/*
 *--------------------------------------------------------------
 *
 * PathPolyLineToArea --
 *
 *    Determine whether an open polygon lies entirely inside, entirely
 *    outside, or overlapping a given rectangular area.
 *     Identical to TkPolygonToArea except that it returns outside (-1)
 *    if completely encompassing the area rect.
 *
 * Results:
 *    -1 is returned if the polygon given by polyPtr and numPoints
 *    is entirely outside the rectangle given by rectPtr.  0 is
 *    returned if the polygon overlaps the rectangle, and 1 is
 *    returned if the polygon is entirely inside the rectangle.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static int
PathPolyLineToArea(
    double *polyPtr,           /* Points to an array coordinates for
                                * closed polygon:  x0, y0, x1, y1, ...
                                * The polygon may be self-intersecting. */
    int numPoints,             /* Total number of points at *polyPtr. */
    double *rectPtr)
{              /* Points to coords for rectangle, in the
                * order x1, y1, x2, y2.  X1 and y1 must
                * be lower-left corner. */
    int state;                 /* State of all edges seen so far (-1 means
                                * outside, 1 means inside, won't ever be
                                * 0). */
    int count;
    double *pPtr;

    /*
     * Iterate over all of the edges of the polygon and test them
     * against the rectangle.  Can quit as soon as the state becomes
     * "intersecting".
     */

    state = TkLineToArea(polyPtr, polyPtr + 2, rectPtr);
    if(state == 0) {
        return 0;
    }
    for(pPtr = polyPtr + 2, count = numPoints - 1; count >= 2;
        pPtr += 2, count--) {
        if(TkLineToArea(pPtr, pPtr + 2, rectPtr) != state) {
            return 0;
        }
    }
    return state;
}

/*
 *--------------------------------------------------------------
 *
 * PathThickPolygonToPoint --
 *
 *    Computes the distance from a given point to a given
 *    thick polyline (open or closed), in canvas units.
 *
 * Results:
 *    The return value is 0 if the point whose x and y coordinates
 *    are pointPtr[0] and pointPtr[1] is inside the line.  If the
 *    point isn't inside the line then the return value is the
 *    distance from the point to the line.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static double
PathThickPolygonToPoint(
    int joinStyle,
    int capStyle,
    double width,
    int isclosed,
    double *polyPtr,           /* Points to an array coordinates for
                                * the polygon:  x0, y0, x1, y1, ...
                                * The polygon may be self-intersecting. */
    int numPoints,             /* Total number of points at *polyPtr. */
    double *pointPtr)
{              /* Points to coords for point. */
    int count;
    int project;
    int testrounding;
    int changedMiterToBevel;   /* Non-zero means that a mitered corner
                                * had to be treated as beveled after all
                                * because the angle was < 11 degrees. */
    double bestDist;           /* Closest distance between point and
                                * any edge in polygon. */
    double dist, radius;
    double *coordPtr;
    double poly[10];

    bestDist = 1.0e36;
    radius = width / 2.0;
    project = 0;
    if(!isclosed) {
        project = (capStyle == CapProjecting);
    }

    /*
     * The overall idea is to iterate through all of the edges of
     * the line, computing a polygon for each edge and testing the
     * point against that polygon.  In addition, there are additional
     * tests to deal with rounded joints and caps.
     */

    changedMiterToBevel = 0;
    for(count = numPoints, coordPtr = polyPtr; count >= 2;
        count--, coordPtr += 2) {

        /*
         * If rounding is done around the first point then compute
         * the distance between the point and the point.
         */
        testrounding = 0;
        if(isclosed) {
            testrounding = (joinStyle == JoinRound);
        } else {
            testrounding = (((capStyle == CapRound) && (count == numPoints))
                || ((joinStyle == JoinRound) && (count != numPoints)));
        }
        if(testrounding) {
            dist = hypot(coordPtr[0] - pointPtr[0], coordPtr[1] - pointPtr[1])
                - radius;
            if(dist <= 0.0) {
                bestDist = 0.0;
                goto donepoint;
            } else if(dist < bestDist) {
                bestDist = dist;
            }
        }

        /*
         * Compute the polygonal shape corresponding to this edge,
         * consisting of two points for the first point of the edge
         * and two points for the last point of the edge.
         */

        if(count == numPoints) {
            TkGetButtPoints(coordPtr + 2, coordPtr, (double)width,
                project, poly, poly + 2);
        } else if((joinStyle == JoinMiter) && !changedMiterToBevel) {
            poly[0] = poly[6];
            poly[1] = poly[7];
            poly[2] = poly[4];
            poly[3] = poly[5];
        } else {
            TkGetButtPoints(coordPtr + 2, coordPtr, (double)width, 0,
                poly, poly + 2);

            /*
             * If this line uses beveled joints, then check the distance
             * to a polygon comprising the last two points of the previous
             * polygon and the first two from this polygon;  this checks
             * the wedges that fill the mitered joint.
             */

            if((joinStyle == JoinBevel) || changedMiterToBevel) {
                poly[8] = poly[0];
                poly[9] = poly[1];
                dist = TkPolygonToPoint(poly, 5, pointPtr);
                if(dist <= 0.0) {
                    bestDist = 0.0;
                    goto donepoint;
                } else if(dist < bestDist) {
                    bestDist = dist;
                }
                changedMiterToBevel = 0;
            }
        }
        if(count == 2) {
            TkGetButtPoints(coordPtr, coordPtr + 2, (double)width,
                project, poly + 4, poly + 6);
        } else if(joinStyle == JoinMiter) {
            if(TkGetMiterPoints(coordPtr, coordPtr + 2, coordPtr + 4,
                    (double)width, poly + 4, poly + 6) == 0) {
                changedMiterToBevel = 1;
                TkGetButtPoints(coordPtr, coordPtr + 2, (double)width,
                    0, poly + 4, poly + 6);
            }
        } else {
            TkGetButtPoints(coordPtr, coordPtr + 2, (double)width, 0,
                poly + 4, poly + 6);
        }
        poly[8] = poly[0];
        poly[9] = poly[1];
        dist = TkPolygonToPoint(poly, 5, pointPtr);
        if(dist <= 0.0) {
            bestDist = 0.0;
            goto donepoint;
        } else if(dist < bestDist) {
            bestDist = dist;
        }
    }

    /*
     * If caps are rounded, check the distance to the cap around the
     * final end point of the line.
     */
    if(!isclosed && (capStyle == CapRound)) {
        dist = hypot(coordPtr[0] - pointPtr[0], coordPtr[1] - pointPtr[1])
            - width / 2.0;
        if(dist <= 0.0) {
            bestDist = 0.0;
            goto donepoint;
        } else if(dist < bestDist) {
            bestDist = dist;
        }
    }

  donepoint:

    return bestDist;
}

/*
 *--------------------------------------------------------------
 *
 * PathPolygonToPointEx --
 *
 *    Compute the distance from a point to a polygon. This is
 *    essentially identical to TkPolygonToPoint with two exceptions:
 *    1)     It returns the closest distance to the *stroke*,
 *        any fill unrecognized.
 *    2)    It returns both number of total intersections, and
 *        the number of directed crossings, nonzerorule.
 *
 * Results:
 *    The return value is 0.0 if the point referred to by
 *    pointPtr is within the polygon referred to by polyPtr
 *    and numPoints.  Otherwise the return value is the
 *    distance of the point from the polygon.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

static double
PathPolygonToPointEx(
    double *polyPtr,           /* Points to an array coordinates for
                                * the polygon:  x0, y0, x1, y1, ...
                                * The polygon may be self-intersecting.
                                * If a fillRule is used the last point
                                * must duplicate the first one. */
    int numPoints,             /* Total number of points at *polyPtr. */
    double *pointPtr,          /* Points to coords for point. */
    int *intersectionsPtr,     /* (out) The number of intersections. */
    int *nonzerorulePtr)
{              /* (out) The number of intersections
                * considering crossing direction. */
    double bestDist;           /* Closest distance between point and
                                * any edge in polygon. */
    int intersections;         /* Number of edges in the polygon that
                                * intersect a ray extending vertically
                                * upwards from the point to infinity. */
    int nonzerorule;           /* As 'intersections' except that it adds
                                * one if crossing right to left, and
                                * subtracts one if crossing left to right. */
    int count;
    double *pPtr;

    /*
     * Iterate through all of the edges in the polygon, updating
     * bestDist and intersections.
     *
     * TRICKY POINT:  when computing intersections, include left
     * x-coordinate of line within its range, but not y-coordinate.
     * Otherwise if the point lies exactly below a vertex we'll
     * count it as two intersections.
     */

    bestDist = 1.0e36;
    intersections = 0;
    nonzerorule = 0;

    for(count = numPoints, pPtr = polyPtr; count > 1; count--, pPtr += 2) {
    double x, y, dist;

        /*
         * Compute the point on the current edge closest to the point
         * and update the intersection count.  This must be done
         * separately for vertical edges, horizontal edges, and
         * other edges.
         */

        if(pPtr[2] == pPtr[0]) {

            /*
             * Vertical edge.
             */

            x = pPtr[0];
            if(pPtr[1] >= pPtr[3]) {
                y = MIN(pPtr[1], pointPtr[1]);
                y = MAX(y, pPtr[3]);
            } else {
                y = MIN(pPtr[3], pointPtr[1]);
                y = MAX(y, pPtr[1]);
            }
        } else if(pPtr[3] == pPtr[1]) {

            /*
             * Horizontal edge.
             */

            y = pPtr[1];
            if(pPtr[0] >= pPtr[2]) {
                x = MIN(pPtr[0], pointPtr[0]);
                x = MAX(x, pPtr[2]);
                if((pointPtr[1] < y) && (pointPtr[0] < pPtr[0])
                    && (pointPtr[0] >= pPtr[2])) {
                    intersections++;
                    nonzerorule++;
                }
            } else {
                x = MIN(pPtr[2], pointPtr[0]);
                x = MAX(x, pPtr[0]);
                if((pointPtr[1] < y) && (pointPtr[0] < pPtr[2])
                    && (pointPtr[0] >= pPtr[0])) {
                    intersections++;
                    nonzerorule--;
                }
            }
        } else {
    double m1, b1, m2, b2;
    int lower;                 /* Non-zero means point below line. */

            /*
             * The edge is neither horizontal nor vertical.  Convert the
             * edge to a line equation of the form y = m1*x + b1.  Then
             * compute a line perpendicular to this edge but passing
             * through the point, also in the form y = m2*x + b2.
             */

            m1 = (pPtr[3] - pPtr[1]) / (pPtr[2] - pPtr[0]);
            b1 = pPtr[1] - m1 * pPtr[0];
            m2 = -1.0 / m1;
            b2 = pointPtr[1] - m2 * pointPtr[0];
            x = (b2 - b1) / (m1 - m2);
            y = m1 * x + b1;
            if(pPtr[0] > pPtr[2]) {
                if(x > pPtr[0]) {
                    x = pPtr[0];
                    y = pPtr[1];
                } else if(x < pPtr[2]) {
                    x = pPtr[2];
                    y = pPtr[3];
                }
            } else {
                if(x > pPtr[2]) {
                    x = pPtr[2];
                    y = pPtr[3];
                } else if(x < pPtr[0]) {
                    x = pPtr[0];
                    y = pPtr[1];
                }
            }
            lower = (m1 * pointPtr[0] + b1) > pointPtr[1];
            if(lower && (pointPtr[0] >= MIN(pPtr[0], pPtr[2]))
                && (pointPtr[0] < MAX(pPtr[0], pPtr[2]))) {
                intersections++;
                if(pPtr[0] >= pPtr[2]) {
                    nonzerorule++;
                } else {
                    nonzerorule--;
                }
            }
        }

        /*
         * Compute the distance to the closest point, and see if that
         * is the best distance seen so far.
         */

        dist = hypot(pointPtr[0] - x, pointPtr[1] - y);
        if(dist < bestDist) {
            bestDist = dist;
        }
    }
    *intersectionsPtr = intersections;
    *nonzerorulePtr = nonzerorule;

    return bestDist;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathRectToPoint --
 *
 *    Computes the distance from a given point to a given
 *    rectangle, in canvas units.
 *
 * Results:
 *    The return value is 0 if the point whose x and y coordinates
 *    are pointPtr[0] and pointPtr[1] is inside the rectangle.  If the
 *    point isn't inside the rectangle then the return value is the
 *    distance from the point to the rectangle.  If item is filled,
 *    then anywhere in the interior is considered "inside"; if
 *    item isn't filled, then "inside" means only the area
 *    occupied by the outline.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

double
TkPathRectToPoint(
    double rectPtr[],          /* Bare rectangle. */
    double width,              /* Width of stroke, or 0. */
    int filled,                /* Is rectangle filled. */
    double pointPtr[])
{              /* Pointer to x and y coordinates. */
    double xDiff, yDiff, x1, y1, x2, y2, inc, tmp;

    /*
     * Generate a new larger rectangle that includes the border
     * width, if there is one.
     */

    inc = width / 2.0;
    x1 = rectPtr[0] - inc;
    y1 = rectPtr[1] - inc;
    x2 = rectPtr[2] + inc;
    y2 = rectPtr[3] + inc;

    /*
     * If the point is inside the rectangle, handle specially:
     * distance is 0 if rectangle is filled, otherwise compute
     * distance to nearest edge of rectangle and subtract width
     * of edge.
     */

    if((pointPtr[0] >= x1) && (pointPtr[0] < x2)
        && (pointPtr[1] >= y1) && (pointPtr[1] < y2)) {
        /* if (filled || (rectPtr->outline.gc == None)) */
        if(filled) {
            return 0.0;
        }
        xDiff = pointPtr[0] - x1;
        tmp = x2 - pointPtr[0];
        if(tmp < xDiff) {
            xDiff = tmp;
        }
        yDiff = pointPtr[1] - y1;
        tmp = y2 - pointPtr[1];
        if(tmp < yDiff) {
            yDiff = tmp;
        }
        if(yDiff < xDiff) {
            xDiff = yDiff;
        }
        xDiff -= width;
        if(xDiff < 0.0) {
            return 0.0;
        }
        return xDiff;
    }

    /*
     * Point is outside rectangle.
     */

    if(pointPtr[0] < x1) {
        xDiff = x1 - pointPtr[0];
    } else if(pointPtr[0] > x2) {
        xDiff = pointPtr[0] - x2;
    } else {
        xDiff = 0;
    }

    if(pointPtr[1] < y1) {
        yDiff = y1 - pointPtr[1];
    } else if(pointPtr[1] > y2) {
        yDiff = pointPtr[1] - y2;
    } else {
        yDiff = 0;
    }

    return hypot(xDiff, yDiff);
}

/*
 *--------------------------------------------------------------
 *
 * TkPathRectToArea --
 *
 *    This procedure is called to determine whether an rectangle
 *    lies entirely inside, entirely outside, or overlapping
 *    another given rectangle.
 *
 * Results:
 *    -1 is returned if the rectangle is entirely outside the area
 *    given by rectPtr, 0 if it overlaps, and 1 if it is entirely
 *    inside the given area.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathRectToArea(
    double rectPtr[],          /* Bare rectangle. */
    double width,              /* Width of stroke, or 0. */
    int filled,                /* Is rectangle filled. */
    double *areaPtr)
{              /* Pointer to array of four coordinates
                * (x1, y1, x2, y2) describing rectangular
                * area.  */
    double halfWidth = width / 2.0;

    if((areaPtr[2] <= (rectPtr[0] - halfWidth))
        || (areaPtr[0] >= (rectPtr[2] + halfWidth))
        || (areaPtr[3] <= (rectPtr[1] - halfWidth))
        || (areaPtr[1] >= (rectPtr[3] + halfWidth))) {
        return -1;
    }
    if(!filled && (width > 0.0)
        && (areaPtr[0] >= (rectPtr[0] + halfWidth))
        && (areaPtr[1] >= (rectPtr[1] + halfWidth))
        && (areaPtr[2] <= (rectPtr[2] - halfWidth))
        && (areaPtr[3] <= (rectPtr[3] - halfWidth))) {
        return -1;
    }
    if((areaPtr[0] <= (rectPtr[0] - halfWidth))
        && (areaPtr[1] <= (rectPtr[1] - halfWidth))
        && (areaPtr[2] >= (rectPtr[2] + halfWidth))
        && (areaPtr[3] >= (rectPtr[3] + halfWidth))) {
        return 1;
    }
    return 0;
}

int
TkPathRectToAreaWithMatrix(
    TkPathRect bbox,
    TkPathMatrix * mPtr,
    double *areaPtr)
{
    int rectiLinear = 0;
    double rect[4];

    if(mPtr == NULL) {
        rectiLinear = 1;
        rect[0] = bbox.x1;
        rect[1] = bbox.y1;
        rect[2] = bbox.x2;
        rect[3] = bbox.y2;
    } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
        rectiLinear = 1;
        rect[0] = mPtr->a * bbox.x1 + mPtr->tx;
        rect[1] = mPtr->d * bbox.y1 + mPtr->ty;
        rect[2] = mPtr->a * bbox.x2 + mPtr->tx;
        rect[3] = mPtr->d * bbox.y2 + mPtr->ty;
    }
    if(rectiLinear) {
        return TkPathRectToArea(rect, 0.0, 1, areaPtr);
    } else {
    double polyPtr[10];

        /* polyPtr: Points to an array coordinates for closed polygon:  x0, y0, x1, y1, ... */
        /* Construct all four corners. */
        polyPtr[0] = bbox.x1, polyPtr[1] = bbox.y1;
        polyPtr[2] = bbox.x2, polyPtr[3] = bbox.y1;
        polyPtr[4] = bbox.x2, polyPtr[5] = bbox.y2;
        polyPtr[6] = bbox.x1, polyPtr[7] = bbox.y2;
        PathApplyTMatrix(mPtr, polyPtr, polyPtr + 1);
        PathApplyTMatrix(mPtr, polyPtr + 2, polyPtr + 3);
        PathApplyTMatrix(mPtr, polyPtr + 4, polyPtr + 5);
        PathApplyTMatrix(mPtr, polyPtr + 6, polyPtr + 7);

        return TkPolygonToArea(polyPtr, 4, areaPtr);
    }
}

double
TkPathRectToPointWithMatrix(
    TkPathRect bbox,
    TkPathMatrix * mPtr,
    double *pointPtr)
{
    int rectiLinear = 0;
    double dist;
    double rect[4];

    if(mPtr == NULL) {
        rectiLinear = 1;
        rect[0] = bbox.x1;
        rect[1] = bbox.y1;
        rect[2] = bbox.x2;
        rect[3] = bbox.y2;
    } else if((fabs(mPtr->b) == 0.0) && (fabs(mPtr->c) == 0.0)) {
        rectiLinear = 1;
        rect[0] = mPtr->a * bbox.x1 + mPtr->tx;
        rect[1] = mPtr->d * bbox.y1 + mPtr->ty;
        rect[2] = mPtr->a * bbox.x2 + mPtr->tx;
        rect[3] = mPtr->d * bbox.y2 + mPtr->ty;
    }
    if(rectiLinear) {
        dist = TkPathRectToPoint(rect, 0.0, 1, pointPtr);
    } else {
    int intersections, rule;
    double polyPtr[10];

        /* Construct all four corners.
         * First and last must be identical since closed.
         */
        polyPtr[0] = bbox.x1, polyPtr[1] = bbox.y1;
        polyPtr[2] = bbox.x2, polyPtr[3] = bbox.y1;
        polyPtr[4] = bbox.x2, polyPtr[5] = bbox.y2;
        polyPtr[6] = bbox.x1, polyPtr[7] = bbox.y2;
        PathApplyTMatrix(mPtr, polyPtr, polyPtr + 1);
        PathApplyTMatrix(mPtr, polyPtr + 2, polyPtr + 3);
        PathApplyTMatrix(mPtr, polyPtr + 4, polyPtr + 5);
        PathApplyTMatrix(mPtr, polyPtr + 6, polyPtr + 7);
        polyPtr[8] = polyPtr[0], polyPtr[9] = polyPtr[1];

        dist =
            PathPolygonToPointEx(polyPtr, 5, pointPtr, &intersections, &rule);
        if(intersections % 2 == 1) {
            dist = 0.0;
        }
    }
    return dist;
}

/*
 *--------------------------------------------------------------
 *
 * TkPathCanvasItemExConfigure --
 *
 *      Takes care of the custom item configuration of the Tk_PathItemEx
 *    part of any item with style.
 *
 * Results:
 *    Standard Tcl result.
 *
 * Side effects:
 *    None.
 *
 *--------------------------------------------------------------
 */

int
TkPathCanvasItemExConfigure(
    Tcl_Interp * interp,
    Tk_PathCanvas canvas,
    Tk_PathItemEx * itemExPtr,
    int mask)
{
    Tk_Window tkwin;
    Tk_PathItem *parentPtr;
    Tk_PathItem *itemPtr = (Tk_PathItem *) itemExPtr;
    Tk_PathStyle *stylePtr = &itemExPtr->style;

    tkwin = Tk_PathCanvasTkwin(canvas);
    if(mask & TK_PATH_CORE_OPTION_PARENT) {
        if(TkPathCanvasFindGroup(interp, canvas, itemPtr->parentObj,
                &parentPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        TkPathCanvasSetParent(parentPtr, itemPtr);
    } else if((itemPtr->id != 0) && (itemPtr->parentPtr == NULL)) {
        /*
         * If item not root and parent not set we must set it to root by default.
         */
        TkPathCanvasSetParentToRoot(itemPtr);
    }

    /*
     * If we have got a style name it's options take precedence
     * over the actual path configuration options. This is how SVG does it.
     * Good or bad?
     */
    if(mask & TK_PATH_CORE_OPTION_STYLENAME) {
    TkPathStyleInst *styleInst = NULL;

        if(itemExPtr->styleObj != NULL) {
            styleInst =
                TkPathGetStyle(interp, Tcl_GetString(itemExPtr->styleObj),
                TkPathCanvasStyleTable(canvas), TkPathStyleChangedPrc,
                (ClientData) itemExPtr);
            if(styleInst == NULL) {
                return TCL_ERROR;
            }
        } else {
            styleInst = NULL;
        }
        if(itemExPtr->styleInst != NULL) {
            TkPathFreeStyle(itemExPtr->styleInst);
        }
        itemExPtr->styleInst = styleInst;
    }

    /*
     * Just translate the 'fillObj' (string) to a TkPathColor.
     * We MUST have this last in the chain of custom option checks!
     */
    if(mask & TK_PATH_STYLE_OPTION_FILL) {
    TkPathColor *fillPtr = NULL;

        if(stylePtr->fillObj != NULL) {
            fillPtr = TkPathGetPathColor(interp, tkwin, stylePtr->fillObj,
                TkPathCanvasGradientTable(canvas), TkPathGradientChangedPrc,
                (ClientData) itemExPtr);
            if(fillPtr == NULL) {
                return TCL_ERROR;
            }
        } else {
            fillPtr = NULL;
        }
        /* Free any old and store the new. */
        if(stylePtr->fill != NULL) {
            TkPathFreePathColor(stylePtr->fill);
        }
        stylePtr->fill = fillPtr;
    }
    return TCL_OK;
}

void
TkPathGradientChangedPrc(
    ClientData clientData,
    int flags)
{
    Tk_PathItemEx *itemExPtr = (Tk_PathItemEx *) clientData;
    Tk_PathItem *itemPtr = (Tk_PathItem *) itemExPtr;
    Tk_PathStyle *stylePtr = &(itemExPtr->style);

    if(flags) {
        if(flags & TK_PATH_GRADIENT_FLAG_DELETE) {
            TkPathFreePathColor(stylePtr->fill);
            stylePtr->fill = NULL;
            Tcl_DecrRefCount(stylePtr->fillObj);
            stylePtr->fillObj = NULL;
        }
        if(itemPtr->typePtr == &tkPathTypeGroup) {
            TkPathGroupItemConfigured(itemExPtr->canvas, itemPtr,
                TK_PATH_STYLE_OPTION_FILL);
        } else {
            Tk_PathCanvasEventuallyRedraw(itemExPtr->canvas,
                itemExPtr->header.x1, itemExPtr->header.y1,
                itemExPtr->header.x2, itemExPtr->header.y2);
        }
    }
}

void
TkPathStyleChangedPrc(
    ClientData clientData,
    int flags)
{
    Tk_PathItemEx *itemExPtr = (Tk_PathItemEx *) clientData;
    Tk_PathItem *itemPtr = (Tk_PathItem *) itemExPtr;

    if(flags) {
        if(flags & TK_PATH_STYLE_FLAG_DELETE) {
            TkPathFreeStyle(itemExPtr->styleInst);
            itemExPtr->styleInst = NULL;
            Tcl_DecrRefCount(itemExPtr->styleObj);
            itemExPtr->styleObj = NULL;
        }
        if(itemPtr->typePtr == &tkPathTypeGroup) {
            TkPathGroupItemConfigured(itemExPtr->canvas, itemPtr,
                TK_PATH_CORE_OPTION_STYLENAME);
            /* Not completely correct... */
        } else {
            Tk_PathCanvasEventuallyRedraw(itemExPtr->canvas,
                itemExPtr->header.x1, itemExPtr->header.y1,
                itemExPtr->header.x2, itemExPtr->header.y2);
        }
    }
}

void
TkPathCompensateScale(
    Tk_PathItem * itemPtr,
    int compensate,
    double *originX,
    double *originY,
    double *scaleX,
    double *scaleY)
{
    if(compensate) {
    Tk_PathStyle style;

        style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
        if(style.matrixPtr != NULL) {
    TkPathMatrix m;
            PathInverseTMatrix(style.matrixPtr, &m);
            PathApplyTMatrix(&m, originX, originY);
            m.tx = m.ty = 0;
            PathApplyTMatrix(&m, scaleX, scaleY);
        }
        TkPathCanvasFreeInheritedStyle(&style);
    }
}

void
TkPathCompensateTranslate(
    Tk_PathItem * itemPtr,
    int compensate,
    double *deltaX,
    double *deltaY)
{
    if(compensate) {
    Tk_PathStyle style;

        style = TkPathCanvasInheritStyle(itemPtr, TK_PATH_MERGESTYLE_NOTFILL);
        if(style.matrixPtr != NULL) {
    TkPathMatrix m;

            PathInverseTMatrix(style.matrixPtr, &m);
            m.tx = m.ty = 0;
            PathApplyTMatrix(&m, deltaX, deltaY);
        }
        TkPathCanvasFreeInheritedStyle(&style);
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoPath_MacOSX.c.












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkMacOSXPath.c --
 *
 *	This file implements path drawing API's using CoreGraphics on Mac OS X.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 *
 */

/* This should go into configure.in but don't know how. */
#ifdef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#undef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#endif

#include "tkMacOSXInt.h"
#include "tkoPath.h"

#if !__OBJC__
#error Objective-C compiler required
#endif

#import <Cocoa/Cocoa.h>

#define TINT_INT_CALCULATION

/* Seems to work for both Endians. */
#define BlueFloatFromXColorPtr(xc)   ((float) ((xc)->blue >> 8) / 255.0)
#define GreenFloatFromXColorPtr(xc)  ((float) ((xc)->green >> 8) / 255.0)
#define RedFloatFromXColorPtr(xc)    ((float) ((xc)->red >> 8) / 255.0)

#define Blue255FromXColorPtr(xc)   ((xc)->blue >> 8)
#define Green255FromXColorPtr(xc)  ((xc)->green >> 8)
#define Red255FromXColorPtr(xc)    ((xc)->red >> 8)

#ifndef FloatToFixed
#define FloatToFixed(a) ((Fixed)((float) (a) * fixed1))
#endif

extern int Tk_PathAntiAlias;
extern int Tk_PathSurfaceCopyPremultiplyAlpha;
extern int Tk_PathDepixelize;

const CGFloat kValidDomain[2] = { 0, 1 };
const CGFloat kValidRange[8] = { 0, 1, 0, 1, 0, 1, 0, 1 };

/*
 * This is used as a place holder for platform dependent stuff between each call.
 */
typedef struct TkPathContext_ {
    CGContextRef c;
    int saveCount;
    CGrafPtr port;             /* QD graphics port, NULL for bitmaps. */
    char *data;                /* bitmap data, NULL for windows. */
    int widthCode;             /* Used to depixelize the strokes:
                                * 0: not integer width
                                * 1: odd integer width
                                * 2: even integer width */

    /* fields from TK TkMacOSXDrawingContext: */
    NSView *view;
    HIShapeRef clipRgn;
    CGRect portBounds;
    int focusLocked;
    int xOff, yOff;
} TkPathContext_;

#define MAX_NL 32
typedef struct PathATSUIRecord {
    ATSUStyle atsuStyle;
    ATSUTextLayout atsuLayout;
    UniChar *buffer;           /* @@@ Not sure this needs to be cached! */
    int nlc;
    int nl[MAX_NL + 1];
    ATSUTextMeasurement dx[MAX_NL];
    ATSUTextMeasurement dy[MAX_NL];
} PathATSUIRecord;

typedef struct FillInfo {
    double fillOpacity;
    GradientStopArray *stopArrPtr;
} FillInfo;

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXDrawableView --
 *
 *      This function returns the NSView for a given X drawable.
 *
 * Results:
 *      A NSView* or nil.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */

NSView *
TkMacOSXDrawableView(
    MacDrawable * macWin)
{
NSView *result = nil;

    if(!macWin) {
        result = nil;
    } else if(!macWin->toplevel) {
        result = macWin->view;
    } else if(!(macWin->toplevel->flags & TK_EMBEDDED)) {
        result = macWin->toplevel->view;
    } else {
TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);
        if(contWinPtr) {
            result = TkMacOSXDrawableView(contWinPtr->privatePtr);
        }
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * TkpClipDrawableToRect --
 *
 *      Clip all drawing into the drawable d to the given rectangle.
 *      If width or height are negative, reset to no clipping.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Subsequent drawing into d is offset and clipped as specified.
 *
 *----------------------------------------------------------------------
 */

void
TkpClipDrawableToRect(
    Display * display,
    Drawable d,
    int x,
    int y,
    int width,
    int height)
{
    MacDrawable *macDraw = (MacDrawable *) d;
    NSView *view = TkMacOSXDrawableView(macDraw);

    if(macDraw->drawRgn) {
        CFRelease(macDraw->drawRgn);
        macDraw->drawRgn = NULL;
    }
    if(width >= 0 && height >= 0) {
    CGRect drawRect = CGRectMake(x + macDraw->xOff, y + macDraw->yOff,
            width, height);
    HIShapeRef drawRgn = HIShapeCreateWithRect(&drawRect);

        if(macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
            TkMacOSXUpdateClipRgn(macDraw->winPtr);
        }
        if(macDraw->visRgn) {
            macDraw->drawRgn = HIShapeCreateIntersection(macDraw->visRgn,
                drawRgn);
            CFRelease(drawRgn);
        } else {
            macDraw->drawRgn = drawRgn;
        }
        if(view && view !=[NSView focusView] &&[view lockFocusIfCanDraw]) {
            drawRect.origin.y =[view bounds].size.height -
                (drawRect.origin.y + drawRect.size.height);
            NSRectClip(NSRectFromCGRect(drawRect));
            macDraw->flags |= TK_FOCUSED_VIEW;
        }
    } else {
        if(view && (macDraw->flags & TK_FOCUSED_VIEW)) {
            [view unlockFocus];
            macDraw->flags &= ~TK_FOCUSED_VIEW;
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TkMacOSXGetClipRgn --
 *
 *	Get the clipping region needed to restrict drawing to the given
 *	drawable.
 *
 * Results:
 *	Clipping region. If non-NULL, CFRelease it when done.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

HIShapeRef
TkMacOSXGetClipRgn(
    Drawable drawable)
{              /* Drawable. */
MacDrawable *macDraw = (MacDrawable *) drawable;
HIShapeRef clipRgn = NULL;

    if(macDraw->winPtr && macDraw->flags & TK_CLIP_INVALID) {
        TkMacOSXUpdateClipRgn(macDraw->winPtr);
#ifdef TK_MAC_DEBUG_DRAWING
        TkMacOSXDbgMsg("%s visRgn  ", macDraw->winPtr->pathName);
        TkMacOSXDebugFlashRegion(drawable, macDraw->visRgn);
#endif /* TK_MAC_DEBUG_DRAWING */
    }

    if(macDraw->drawRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->drawRgn);
    } else if(macDraw->visRgn) {
        clipRgn = HIShapeCreateCopy(macDraw->visRgn);
    }

    return clipRgn;
}

/* copied from tk8.5.16/macosx/tkMacOSXSubwindows.c */
NSView *
TkpMacOSXDrawableView(
    MacDrawable * macWin)
{
NSView *result = nil;

    if(!macWin) {
        result = nil;
    } else if(!macWin->toplevel) {
        result = macWin->view;
    } else if(!(macWin->toplevel->flags & TK_EMBEDDED)) {
        result = macWin->toplevel->view;
    } else {
TkWindow *contWinPtr = TkpGetOtherWindow(macWin->toplevel->winPtr);
        if(contWinPtr) {
            result = TkpMacOSXDrawableView(contWinPtr->privatePtr);
        }
    }
    return result;
}

void
PathSetUpCGContext(
    Drawable d,
    TkPathContext_ * dcPtr)
{
CGrafPtr port;
MacDrawable *macDraw = (MacDrawable *) d;
int dontDraw = 0;

    dcPtr->c = NULL;
    dcPtr->view = NULL;
    dcPtr->clipRgn = NULL;
    dcPtr->focusLocked = 0;

    port = TkMacOSXGetDrawablePort(d);

    dcPtr->clipRgn = TkMacOSXGetClipRgn(d);
    if(!dontDraw) {
        dontDraw = dcPtr->clipRgn ? HIShapeIsEmpty(dcPtr->clipRgn) : 0;
    }
    if(dontDraw) {
        goto end;
    }

NSView *view = TkpMacOSXDrawableView(macDraw);
    if(view) {
NSView *fView =[NSView focusView];
        if(view != fView) {
            dcPtr->focusLocked =[view lockFocusIfCanDraw];
            dontDraw = !dcPtr->focusLocked;
        } else {
            dontDraw = ![view canDraw];
        }
        if(dontDraw) {
            goto end;
        }
        [[view window] disableFlushWindow];
        dcPtr->view = view;
NSGraphicsContext *currentGraphicsContext =[NSGraphicsContext currentContext];
        dcPtr->c = (CGContextRef)[currentGraphicsContext graphicsPort];
        dcPtr->portBounds = NSRectToCGRect([view bounds]);
        if(dcPtr->clipRgn) {
        }
    } else {
        Tcl_Panic("PathSetUpCGContext(): " "no NSView to draw into !");
    }

    /*
     * Core Graphics defines the origin to be the bottom left
     * corner of the CGContext and the positive y-axis points up.
     * Move the origin and flip the y-axis for all subsequent
     * Core Graphics drawing operations.
     */

    CGContextSaveGState(dcPtr->c);
    dcPtr->saveCount = 1;
CGRect cgbounds = CGContextGetClipBoundingBox(dcPtr->c);
    dcPtr->portBounds = NSRectToCGRect([view bounds]);
    dcPtr->portBounds.origin.x += macDraw->xOff;
    dcPtr->portBounds.origin.y += macDraw->yOff;

    dcPtr->xOff = macDraw->xOff;
    dcPtr->yOff = macDraw->yOff;

  end:
    if(dontDraw && dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

void
PathReleaseCGContext(
    TkPathContext_ * dcPtr)
{
    if(dcPtr->c) {
        CGContextSynchronize(dcPtr->c);
      [[dcPtr->view window] setViewsNeedDisplay:YES];
        [[dcPtr->view window] enableFlushWindow];
        if(dcPtr->focusLocked) {
            [dcPtr->view unlockFocus];
        }
        while(dcPtr->saveCount > 0) {
            CGContextRestoreGState(dcPtr->c);
            dcPtr->saveCount--;
        }
    }
    if(dcPtr->clipRgn) {
        CFRelease(dcPtr->clipRgn);
        dcPtr->clipRgn = NULL;
    }
}

CGColorSpaceRef
GetTheColorSpaceRef(
    void)
{
    static CGColorSpaceRef deviceRGB = NULL;
    if(deviceRGB == NULL) {
        deviceRGB = CGColorSpaceCreateDeviceRGB();
    }
    return deviceRGB;
}

static LookupTable LineCapStyleLookupTable[] = {
    {CapNotLast, kCGLineCapButt},
    {CapButt, kCGLineCapButt},
    {CapRound, kCGLineCapRound},
    {CapProjecting, kCGLineCapSquare}
};

static LookupTable LineJoinStyleLookupTable[] = {
    {JoinMiter, kCGLineJoinMiter},
    {JoinRound, kCGLineJoinRound},
    {JoinBevel, kCGLineJoinBevel}
};

void
PathSetCGContextStyle(
    CGContextRef c,
    Tk_PathStyle * style)
{
Tk_PathDash *dashPtr;
int fill = 0, stroke = 0;

    /** Drawing attribute functions. **/

    /* Set the line width in the current graphics state to `width'. */
    CGContextSetLineWidth(c, style->strokeWidth);

    /* Set the line cap in the current graphics state to `cap'. */
    CGContextSetLineCap(c,
        TkPathTableLookup(LineCapStyleLookupTable, 4, style->capStyle));

    /* Set the line join in the current graphics state to `join'. */
    CGContextSetLineJoin(c,
        TkPathTableLookup(LineJoinStyleLookupTable, 3, style->joinStyle));

    /* Set the miter limit in the current graphics state to `limit'. */
    CGContextSetMiterLimit(c, style->miterLimit);

    /* Set the line dash patttern in the current graphics state. */
    dashPtr = style->dashPtr;
    if((dashPtr != NULL) && (dashPtr->number != 0)) {
CGFloat *dashes = (CGFloat *) ckalloc(dashPtr->number * sizeof(CGFloat));
int i;

        for(i = 0; i < dashPtr->number; i++)
            dashes[i] = dashPtr->array[i] * style->strokeWidth;
        CGContextSetLineDash(c, 0.0, dashes, dashPtr->number);
        ckfree((char *)dashes);
    }

    /* Set the current fill colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current fill color to `(red, green, blue,
     * alpha)'. */
    if(GetColorFromPathColor(style->fill) != NULL) {
        fill = 1;
        CGContextSetRGBFillColor(c,
            RedFloatFromXColorPtr(style->fill->color),
            GreenFloatFromXColorPtr(style->fill->color),
            BlueFloatFromXColorPtr(style->fill->color), style->fillOpacity);
    }

    /* Set the current stroke colorspace in the context `c' to `DeviceRGB' and
     * set the components of the current stroke color to `(red, green, blue,
     * alpha)'. */
    if(style->strokeColor != NULL) {
        stroke = 1;
        CGContextSetRGBStrokeColor(c,
            RedFloatFromXColorPtr(style->strokeColor),
            GreenFloatFromXColorPtr(style->strokeColor),
            BlueFloatFromXColorPtr(style->strokeColor), style->strokeOpacity);
    }
    if(stroke && fill) {
        CGContextSetTextDrawingMode(c, kCGTextFillStroke);
    } else if(stroke) {
        CGContextSetTextDrawingMode(c, kCGTextStroke);
    } else if(fill) {
        CGContextSetTextDrawingMode(c, kCGTextFill);
    }
}

/* Various ATSUI support functions. */

static OSStatus
CreateATSUIStyle(
    const char *fontFamily,
    float fontSize,
    Boolean isBold,
    Boolean isItalic,
    ATSUStyle * atsuStylePtr)
{
    OSStatus err = noErr;
    ATSUStyle style;
    ATSUFontID atsuFont;
    Fixed atsuSize;
    Boolean isUnderline = false;
    static const ATSUAttributeTag tags[] =
        { kATSUFontTag, kATSUSizeTag, kATSUQDBoldfaceTag, kATSUQDItalicTag,
            kATSUQDUnderlineTag };
    static const ByteCount sizes[] =
        { sizeof(ATSUFontID), sizeof(Fixed), sizeof(Boolean), sizeof(Boolean),
            sizeof(Boolean) };
    const ATSUAttributeValuePtr values[] =
        { &atsuFont, &atsuSize, &isBold, &isItalic, &isUnderline };

    *atsuStylePtr = NULL;
    style = NULL;
    atsuFont = 0;
    atsuSize = FloatToFixed(fontSize);
    {
        err =
            ATSUFindFontFromName((Ptr) fontFamily, strlen(fontFamily),
            kFontFamilyName, kFontNoPlatformCode, kFontNoScriptCode,
            kFontNoLanguageCode, &atsuFont);
    }
    if(err != noErr) {
        return err;
    }
    err = ATSUCreateStyle(&style);
    if(err != noErr) {
        if(style)
            ATSUDisposeStyle(style);
        return err;
    }
    err = ATSUSetAttributes(style, sizeof(tags) / sizeof(tags[0]),
        tags, sizes, values);
    if(err != noErr) {
        if(style)
            ATSUDisposeStyle(style);
        return err;
    }
    *atsuStylePtr = style;
    return noErr;
}

static OSStatus
CreateLayoutForString(
    UniChar * buffer,
    CFIndex length,
    ATSUStyle atsuStyle,
    ATSUTextLayout * layoutPtr)
{
ATSUTextLayout layout = NULL;
OSStatus err = noErr;

    *layoutPtr = NULL;
    err = ATSUCreateTextLayoutWithTextPtr(buffer, 0,
        length, length, 1, (unsigned long *)&length, &atsuStyle, &layout);
    if(err == noErr) {
        *layoutPtr = layout;
    }
    ATSUSetTransientFontMatching(layout, true);
    return err;
}

TkPathContext
TkPathInit(
    Tk_Window tkwin,
    Drawable d)
{
TkPathContext_ *context = (TkPathContext_ *) ckalloc(sizeof(TkPathContext_));
    bzero(context, sizeof(TkPathContext_));

    PathSetUpCGContext(d, context);
    context->port = TkMacOSXGetDrawablePort(d);
    context->data = NULL;
    context->widthCode = 0;
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(
    Display * display,
    int width,
    int height)
{
CGContextRef cgContext;
TkPathContext_ *context =
    (TkPathContext_ *) ckalloc((unsigned)(sizeof(TkPathContext_)));
size_t bytesPerRow;
char *data;

    /* Move up into own function */
    bzero(context, sizeof(TkPathContext_));
    bytesPerRow = 4 * width;
    /* Round up to nearest multiple of 16 */
    bytesPerRow = (bytesPerRow + (16 - 1)) & ~(16 - 1);
    data = ckalloc(height * bytesPerRow);

    /* Make it RGBA with 32 bit depth. */
    cgContext = CGBitmapContextCreate(data, width, height, 8, bytesPerRow,
        GetTheColorSpaceRef(), kCGImageAlphaPremultipliedLast);
    if(cgContext == NULL) {
        ckfree((char *)context);
        return (TkPathContext) NULL;
    }
    CGContextClearRect(cgContext, CGRectMake(0, 0, width, height));
    CGContextTranslateCTM(cgContext, 0, height);
    CGContextScaleCTM(cgContext, 1, -1);
    context->c = cgContext;
    context->port = NULL;
    context->data = data;
    context->clipRgn = NULL;
    context->saveCount = 0;
    context->xOff = context->yOff = 0;
    return (TkPathContext) context;
}

void
TkPathPushTMatrix(
    TkPathContext ctx,
    TMatrix * mPtr)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
CGAffineTransform transform;

    if(mPtr == NULL) {
        return;
    }
    /* Return the transform [ a b c d tx ty ]. */
    transform = CGAffineTransformMake(
        (float)mPtr->a, (float)mPtr->b,
        (float)mPtr->c, (float)mPtr->d, (float)mPtr->tx, (float)mPtr->ty);
    CGContextConcatCTM(context->c, transform);
}

void
TkPathResetTMatrix(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->widthCode = 0;
    while(context->saveCount > 0) {
        CGContextRestoreGState(context->c);
        context->saveCount--;
    }
    CGContextSaveGState(context->c);
    context->saveCount++;

    if(context->data != NULL) {
        /* surface bitmap */
        return;
    }

CGAffineTransform t;
    t.a = 1.0;
    t.b = 0.0;
    t.c = 0.0;
    t.d = (-1.0);
    t.tx = 0.0;
    t.ty = context->portBounds.size.height;

    CGContextConcatCTM(context->c, t);

CGRect r;
    HIShapeGetBounds(context->clipRgn, &r);

    HIShapeReplacePathInCGContext(context->clipRgn, context->c);
    CGContextEOClip(context->c);

    CGContextTranslateCTM(context->c, context->xOff, context->yOff);

    CGContextSetShouldAntialias(context->c, Tk_PathAntiAlias);
    CGContextSetInterpolationQuality(context->c, kCGInterpolationHigh);
}

void
TkPathSaveState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextSaveGState(context->c);
    context->saveCount++;
}

void
TkPathRestoreState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(context->saveCount > 0) {
        CGContextRestoreGState(context->c);
        context->saveCount--;
    }
}

void
TkPathBeginPath(
    TkPathContext ctx,
    Tk_PathStyle * stylePtr)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
int nint;
double width;
    CGContextBeginPath(context->c);
    PathSetCGContextStyle(context->c, stylePtr);
    if(stylePtr->strokeColor == NULL) {
        context->widthCode = 0;
    } else {
        width = stylePtr->strokeWidth;
        nint = (int)(width + 0.5);
        context->widthCode = fabs(width - nint) > 0.01 ? 0 : 2 - nint % 2;
    }
}

void
TkPathMoveTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextMoveToPoint(context->c, x, y);
}

void
TkPathLineTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddLineToPoint(context->c, x, y);
}

void
TkPathLinesTo(
    TkPathContext ctx,
    double *pts,
    int n)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Add a set of lines to the context's path. */
    /* CGContextAddLines(context->c, const CGPoint points[], size_t count); */
}

void
TkPathQuadBezier(
    TkPathContext ctx,
    double ctrlX,
    double ctrlY,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddQuadCurveToPoint(context->c, ctrlX, ctrlY, x, y);
}

void
TkPathCurveTo(
    TkPathContext ctx,
    double ctrlX1,
    double ctrlY1,
    double ctrlX2,
    double ctrlY2,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    CGContextAddCurveToPoint(context->c, ctrlX1, ctrlY1, ctrlX2, ctrlY2, x, y);
}

void
TkPathArcTo(
    TkPathContext ctx,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    /* @@@ Should we try to use the native arc functions here? */
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag, sweepFlag, x,
        y);
}

void
TkPathRectangle(
    TkPathContext ctx,
    double x,
    double y,
    double width,
    double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGRect r;
    if(Tk_PathDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    r = CGRectMake(x, y, width, height);
    CGContextAddRect(context->c, r);
}

void
TkPathOval(
    TkPathContext ctx,
    double cx,
    double cy,
    double rx,
    double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    CGRect r;
    r = CGRectMake(cx - rx, cy - ry, 2 * rx, 2 * ry);
    CGContextAddEllipseInRect(context->c, r);
}

CGInterpolationQuality
convertInterpolationToCGInterpolation(
    int interpolation)
{
    switch (interpolation) {
    case kPathImageInterpolationNone:
        return kCGInterpolationNone;
    case kPathImageInterpolationFast:
        return kCGInterpolationLow;
    case kPathImageInterpolationBest:
        return kCGInterpolationHigh;
    default:
        return kCGInterpolationMedium;
    }
}

void
TkPathImage(
    TkPathContext ctx,
    Tk_Image image,
    Tk_PhotoHandle photo,
    double x,
    double y,
    double width0,
    double height0,
    double fillOpacity,
    XColor * tintColor,
    double tintAmount,
    int interpolation,
    PathRect * srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGImageRef cgImage;
    CGDataProviderRef provider;
    CGColorSpaceRef colorspace;
    CGImageAlphaInfo alphaInfo;
    size_t size;
    Tk_PhotoImageBlock block;
    unsigned char *data = NULL;
    unsigned char *ptr = NULL;
    unsigned char *srcPtr, *dstPtr;
    int srcR, srcG, srcB, srcA; /* The source pixel offsets. */
    int dstR, dstG, dstB, dstA; /* The destination pixel offsets. */
    int pitch;
    int iwidth, iheight;
    int i, j;

    /* Return value? */
    Tk_PhotoGetImage(photo, &block);
    size = block.pitch * block.height;
    iheight = block.height;
    iwidth = block.width;
    pitch = block.pitch;
    double width = (width0 == 0.0) ? (double)iwidth : width0;
    double height = (height0 == 0.0) ? (double)iheight : height0;

    /*
     * The offset array contains the offsets from the address of a pixel to
     * the addresses of the bytes containing the red, green, blue and alpha
     * (transparency) components.  These are normally 0, 1, 2 and 3.
     * @@@ There are more cases to consider than these!
     */
    srcR = dstR = block.offset[0];
    srcG = dstG = block.offset[1];
    srcB = dstB = block.offset[2];
    srcA = dstA = block.offset[3];

    if(srcA == 3) {
        alphaInfo = kCGImageAlphaLast;
    } else if(srcA == 0) {
        alphaInfo = kCGImageAlphaFirst;
    } else {
        /* @@@ What to do here? */
        return;
    }

    if(block.pixelSize == 4) {
        if((srcR == dstR) && (srcG == dstG) && (srcB == dstB) && (srcA == dstA)
            && fillOpacity >= 1.0 && (tintAmount <= 0.0 || tintColor == NULL)) {
            ptr = (unsigned char *)block.pixelPtr;
        } else {
            data = (unsigned char *)ckalloc(pitch * iheight);
            ptr = data;

            if(tintColor && tintAmount > 0.0) {
#ifdef TINT_INT_CALCULATION
    uint32_t tintR, tintG, tintB, uAmount, uRemain, uOpacity;

                if(tintAmount > 1.0)
                    tintAmount = 1.0;
                uAmount = (uint32_t) (tintAmount * 256.0);
                uRemain = 256 - uAmount;
                uOpacity = (uint32_t) (fillOpacity * 256.0);
                tintR = Red255FromXColorPtr(tintColor);
                tintG = Green255FromXColorPtr(tintColor);
                tintB = Blue255FromXColorPtr(tintColor);
                for(i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i * pitch;
                    dstPtr = ptr + i * pitch;
                    for(j = 0; j < iwidth; j++) {
                        /* extract */
    uint32_t r = *(srcPtr + srcR);
    uint32_t g = *(srcPtr + srcG);
    uint32_t b = *(srcPtr + srcB);
    uint32_t a = *(srcPtr + srcA);

                        /* transform */
    uint32_t lumAmount = ((r * 6966 + g * 23436 + b * 2366) * uAmount) >> 23;   /* 0-256 */
                        r = (uRemain * r + lumAmount * tintR);
                        g = (uRemain * g + lumAmount * tintG);
                        b = (uRemain * b + lumAmount * tintB);

                        /* fix range */
                        r = r > 0xFFFF ? 0xFFFF : r;
                        g = g > 0xFFFF ? 0xFFFF : g;
                        b = b > 0xFFFF ? 0xFFFF : b;

                        /* and put back */
                        *(dstPtr + dstR) = r >> 8;
                        *(dstPtr + dstG) = g >> 8;
                        *(dstPtr + dstB) = b >> 8;
                        *(dstPtr + dstA) = (a * uOpacity) >> 8;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#else
    float tintR, tintG, tintB;

                if(tintAmount > 1.0)
                    tintAmount = 1.0;
                tintR = RedFloatFromXColorPtr(tintColor);
                tintG = GreenFloatFromXColorPtr(tintColor);
                tintB = BlueFloatFromXColorPtr(tintColor);
                for(i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i * pitch;
                    dstPtr = ptr + i * pitch;
                    for(j = 0; j < iwidth; j++) {
                        /* extract */
    int r = *(srcPtr + srcR);
    int g = *(srcPtr + srcG);
    int b = *(srcPtr + srcB);

                        /* transform */
    int lum = (int)(0.2126 * r + 0.7152 * g + 0.0722 * b);
                        r = (int)((1.0 - tintAmount) * r +
                            tintAmount * lum * tintR);
                        g = (int)((1.0 - tintAmount) * g +
                            tintAmount * lum * tintG);
                        b = (int)((1.0 - tintAmount) * b +
                            tintAmount * lum * tintB);

                        /* fix range */
                        r = r < 0 ? 0 : r > 255 ? 255 : r;
                        g = g < 0 ? 0 : g > 255 ? 255 : g;
                        b = b < 0 ? 0 : b > 255 ? 255 : b;

                        /* and put back */
                        *(dstPtr + dstR) = r;
                        *(dstPtr + dstG) = g;
                        *(dstPtr + dstB) = b;
                        *(dstPtr + dstA) = *(srcPtr + srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
#endif
            } else {
                for(i = 0; i < iheight; i++) {
                    srcPtr = block.pixelPtr + i * pitch;
                    dstPtr = ptr + i * pitch;
                    for(j = 0; j < iwidth; j++) {
                        *(dstPtr + dstR) = *(srcPtr + srcR);
                        *(dstPtr + dstG) = *(srcPtr + srcG);
                        *(dstPtr + dstB) = *(srcPtr + srcB);
                        *(dstPtr + dstA) = *(srcPtr + srcA) * fillOpacity;
                        srcPtr += 4;
                        dstPtr += 4;
                    }
                }
            }
        }
    } else {
        ptr = (unsigned char *)block.pixelPtr;
        return;
    }
    provider = CGDataProviderCreateWithData(NULL, ptr, size, NULL);
    colorspace = CGColorSpaceCreateDeviceRGB();
    cgImage = CGImageCreate(block.width, block.height, 8,       /* bitsPerComponent */
        block.pixelSize * 8,    /* bitsPerPixel */
        block.pitch,    /* bytesPerRow */
        colorspace,     /* colorspace */
        alphaInfo,      /* alphaInfo */
        provider, NULL, interpolation > 0 ? 1 : 0,      /* shouldInterpolate */
        kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorspace);
    if(width == 0.0) {
        width = (double)block.width;
    }
    if(height == 0.0) {
        height = (double)block.height;
    }

    CGContextSaveGState(context->c);
    context->saveCount++;

    if(srcRegion != NULL) {
        width = (width0 == 0.0) ? srcRegion->x2 - srcRegion->x1 : width0;
        height = (height0 == 0.0) ? srcRegion->y2 - srcRegion->y1 : height0;
    double xscale = width / (srcRegion->x2 - srcRegion->x1);
    double yscale = height / (srcRegion->y2 - srcRegion->y1);
        CGContextSetInterpolationQuality(context->c,
            convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y + height);
        CGContextScaleCTM(context->c, xscale, -yscale);
        CGContextClipToRect(context->c, CGRectMake(0.0, 0.0, width / xscale,
                height / yscale));
        CGContextDrawTiledImage(context->c, CGRectMake(srcRegion->x1,
                fmod(srcRegion->y2, iheight), iwidth, iheight), cgImage);
    } else {
        /* Flip back to an upright coordinate system since CGContextDrawImage expect this. */
        CGContextSetInterpolationQuality(context->c,
            convertInterpolationToCGInterpolation(interpolation));
        CGContextTranslateCTM(context->c, x, y + height);
        CGContextScaleCTM(context->c, 1, -1);
        CGContextDrawImage(context->c, CGRectMake(0.0, 0.0, width, height),
            cgImage);
    }
    CGImageRelease(cgImage);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    if(data) {
        ckfree((char *)data);
    }
}

void
TkPathClosePath(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextClosePath(context->c);
}

/*
 * @@@ Problems: don't want Tcl_Interp, finding matching font not while processing options.
 * Separate font style from layout???
 */

Boolean
isItalic(
    enum FontSlant slant)
{
    switch (slant) {
    case PATH_TEXT_SLANT_NORMAL:
        return false;
    case PATH_TEXT_SLANT_ITALIC:
        return true;
    case PATH_TEXT_SLANT_OBLIQUE:
        return true;
    default:
        return false;
    }
}

Boolean
isBold(
    enum FontWeight weight)
{
    switch (weight) {
    case PATH_TEXT_WEIGHT_NORMAL:
        return false;
    case PATH_TEXT_WEIGHT_BOLD:
        return true;
    default:
        return false;
    }
}

int
TkPathTextConfig(
    Tcl_Interp * interp,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    void **customPtr)
{
    PathATSUIRecord *recordPtr;
    ATSUStyle atsuStyle = NULL;
    ATSUTextLayout atsuLayout = NULL;
    CFStringRef cf;
    UniChar *buffer;
    CFRange range;
    CFIndex length;
    OSStatus err;
    Tcl_Encoding enc;
    Tcl_DString ds;

    if(utf8 == NULL) {
        return TCL_OK;
    }
    TkPathTextFree(textStylePtr, *customPtr);

    enc = Tcl_GetEncoding(NULL, "utf-8");
    Tcl_DStringInit(&ds);
    Tcl_UtfToExternalDString(enc, utf8, -1, &ds);
    Tcl_FreeEncoding(enc);
    cf = CFStringCreateWithCString(NULL, Tcl_DStringValue(&ds),
        kCFStringEncodingUTF8);
    Tcl_DStringFree(&ds);
    length = CFStringGetLength(cf);
    if(length == 0) {
        return TCL_OK;
    }
    range = CFRangeMake(0, length);
    err =
        CreateATSUIStyle(textStylePtr->fontFamily, textStylePtr->fontSize,
        isBold(textStylePtr->fontWeight), isItalic(textStylePtr->fontSlant),
        &atsuStyle);
    if(err != noErr) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("font style couldn't be created", -1));
        return TCL_ERROR;
    }
    buffer = (UniChar *) ckalloc(length * sizeof(UniChar));
    CFStringGetCharacters(cf, range, buffer);
    err = CreateLayoutForString(buffer, length, atsuStyle, &atsuLayout);
    CFRelease(cf);
    if(err != noErr) {
        Tcl_SetObjResult(interp,
            Tcl_NewStringObj("text layout couldn't be created", -1));
        ckfree((char *)buffer);
        return TCL_ERROR;
    }
    recordPtr = (PathATSUIRecord *) ckalloc(sizeof(PathATSUIRecord));
    recordPtr->atsuStyle = atsuStyle;
    recordPtr->atsuLayout = atsuLayout;
    recordPtr->buffer = buffer;
    int i, j;
    recordPtr->nl[0] = 0;
    for(i = 0, j = 1; i < length; i++) {
        if((j < MAX_NL) && (buffer[i] == '\n')) {
            recordPtr->nl[j++] = i + 1;
            buffer[i] = 0x2028;
        }
    }
    recordPtr->nl[j] = i + 1;
    recordPtr->nlc = j;
    *customPtr = (PathATSUIRecord *) recordPtr;
    return TCL_OK;
}

static void
drawMultilineText(
    PathATSUIRecord * recordPtr)
{
int i;

    for(i = 0; i < recordPtr->nlc; i++) {
        ATSUDrawText(recordPtr->atsuLayout, recordPtr->nl[i],
            recordPtr->nl[i + 1] - recordPtr->nl[i] - 1, recordPtr->dx[i],
            recordPtr->dy[i]);
    }
}

void
TkPathTextDraw(
    TkPathContext ctx,
    Tk_PathStyle * style,
    Tk_PathTextStyle * textStylePtr,
    double x,
    double y,
    int fillOverStroke,
    char *utf8,
    void *custom)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    ByteCount iSize = sizeof(CGContextRef);
    ATSUAttributeTag iTag = kATSUCGContextTag;
    ATSUAttributeValuePtr iValuePtr = &(context->c);

    ATSUSetLayoutControls(recordPtr->atsuLayout, 1, &iTag, &iSize, &iValuePtr);
    CGContextSaveGState(context->c);
    context->saveCount++;
    CGContextTranslateCTM(context->c, x, y);
    CGContextScaleCTM(context->c, 1, -1);
    if((style->strokeColor != NULL)
        && (GetColorFromPathColor(style->fill) != NULL)) {
        CGContextSetTextDrawingMode(context->c,
            fillOverStroke ? kCGTextStroke : kCGTextFill);
        drawMultilineText(recordPtr);
        CGContextSetTextDrawingMode(context->c,
            fillOverStroke ? kCGTextFill : kCGTextStroke);
        drawMultilineText(recordPtr);
    } else {
        drawMultilineText(recordPtr);
    }
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathTextFree(
    Tk_PathTextStyle * textStylePtr,
    void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    if(recordPtr) {
        if(recordPtr->atsuStyle) {
            ATSUDisposeStyle(recordPtr->atsuStyle);
        }
        if(recordPtr->atsuLayout) {
            ATSUDisposeTextLayout(recordPtr->atsuLayout);
        }
        if(recordPtr->buffer) {
            ckfree((char *)recordPtr->buffer);
        }
    }
}

PathRect
TkPathTextMeasureBbox(
    Display * display,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    double *lineSpacing,
    void *custom)
{
    PathATSUIRecord *recordPtr = (PathATSUIRecord *) custom;
    PathRect r, ri;
    int i;
    ATSTrapezoid b;
    ItemCount numBounds;
    double x = 0.0;
    double y = 0.0;
    double baseX = 0.0;
    double lineSp = 0;

    for(i = 0; i < recordPtr->nlc; i++) {
        b.upperRight.x = b.upperLeft.x = 0;

        ATSUGetGlyphBounds(recordPtr->atsuLayout, 0, 0,
            recordPtr->nl[i], recordPtr->nl[i + 1] - recordPtr->nl[i] - 1,
            kATSUseFractionalOrigins, 1, &b, &numBounds);
        ri.x1 = MIN(Fix2X(b.upperLeft.x), Fix2X(b.lowerLeft.x));
        ri.y1 = MIN(Fix2X(b.upperLeft.y), Fix2X(b.upperRight.y));
        ri.x2 = MAX(Fix2X(b.upperRight.x), Fix2X(b.lowerRight.x));
        ri.y2 = MAX(Fix2X(b.lowerLeft.y), Fix2X(b.lowerRight.y));
        if(i == 0) {
            baseX = ri.x1;
            r.x1 = ri.x1;
            r.y1 = ri.y1;
            r.x2 = ri.x2;
            r.y2 = ri.y2;
        } else {
            x = ri.x1 - baseX;
            ri.x1 -= x;
            ri.y1 += y;
            ri.x2 -= x;
            ri.y2 += y;
            if(r.x1 > ri.x1)
                r.x1 = ri.x1;
            if(r.y1 > ri.y1)
                r.y1 = ri.y1;
            if(r.x2 < ri.x2)
                r.x2 = ri.x2;
            if(r.y2 < ri.y2)
                r.y2 = ri.y2;
        }
        recordPtr->dx[i] = X2Fix(-x);
        recordPtr->dy[i] = X2Fix(-y);
        y = r.y2 - r.y1;
        lineSp += y;
    }

    if(lineSpacing != NULL && i > 0) {
        *lineSpacing = lineSp / i;
    }

    return r;
}

void
TkPathSurfaceErase(
    TkPathContext ctx,
    double x,
    double y,
    double width,
    double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextClearRect(context->c, CGRectMake(x, y, width, height));
}

void
TkPathSurfaceToPhoto(
    Tcl_Interp * interp,
    TkPathContext ctx,
    Tk_PhotoHandle photo)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
CGContextRef c = context->c;
Tk_PhotoImageBlock block;
unsigned char *data;
unsigned char *pixel;
int width, height;
int bytesPerRow;

    width = CGBitmapContextGetWidth(c);
    height = CGBitmapContextGetHeight(c);
    data = CGBitmapContextGetData(c);
    bytesPerRow = CGBitmapContextGetBytesPerRow(c);

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *)attemptckalloc(height * bytesPerRow);
    if(pixel == NULL) {
        return;
    }
    if(Tk_PathSurfaceCopyPremultiplyAlpha) {
        TkPathCopyBitsPremultipliedAlphaRGBA(data, pixel, width, height,
            bytesPerRow);
    } else {
        memcpy(pixel, data, height * bytesPerRow);
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = bytesPerRow;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    /* Should change this to check for errors... */
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height,
        TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *)pixel);
}

void
TkPathClipToPath(
    TkPathContext ctx,
    int fillRule)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;

    /* If you need to grow the clipping path after it’s shrunk, you must save the
     * graphics state before you clip, then restore the graphics state to restore the current
     * clipping path. */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if(fillRule == WindingRule) {
        CGContextClip(context->c);
    } else if(fillRule == EvenOddRule) {
        CGContextEOClip(context->c);
    }
}

void
TkPathReleaseClipToPath(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextRestoreGState(context->c);
    context->saveCount--;
}

void
TkPathStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGContextStrokePath(context->c);
}

void
TkPathFill(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(style->fillRule == WindingRule) {
        CGContextFillPath(context->c);
    } else if(style->fillRule == EvenOddRule) {
        CGContextEOFillPath(context->c);
    }
}

void
TkPathFillAndStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(style->fillRule == WindingRule) {
        CGContextDrawPath(context->c, kCGPathFillStroke);
    } else if(style->fillRule == EvenOddRule) {
        CGContextDrawPath(context->c, kCGPathEOFillStroke);
    }
}

void
TkPathEndPath(
    TkPathContext ctx)
{
    /* TkPathContext_ *context = (TkPathContext_ *) ctx; */
    /* Empty ??? */
}

void
TkPathFree(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    PathReleaseCGContext(context);
    if(context->data) {
        ckfree(context->data);
    }
    ckfree((char *)ctx);
}

int
TkPathDrawingDestroysPath(
    void)
{
    return 1;
}

int
TkPathPixelAlign(
    void)
{
    return 0;
}

/* TkPathGetCurrentPosition --
 *
 * 		Returns the current pen position in untransformed coordinates!
 */

int
TkPathGetCurrentPosition(
    TkPathContext ctx,
    PathPoint * ptPtr)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
CGPoint cgpt;

    cgpt = CGContextGetPathCurrentPoint(context->c);
    ptPtr->x = cgpt.x;
    ptPtr->y = cgpt.y;
    return TCL_OK;
}

int
TkPathBoundingBox(
    TkPathContext ctx,
    PathRect * rPtr)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
CGRect cgRect;

    /* This one is not very useful since it includes the control points. */
    cgRect = CGContextGetPathBoundingBox(context->c);
    rPtr->x1 = cgRect.origin.x;
    rPtr->y1 = cgRect.origin.y;
    rPtr->x2 = cgRect.origin.x + cgRect.size.width;
    rPtr->y2 = cgRect.origin.y + cgRect.size.height;
    return TCL_OK;
}

/*
 * Using CGShading for fill gradients.
 */

static void
ShadeEvaluate(
    void *info,
    const CGFloat * in,
    CGFloat * out)
{
    FillInfo *fillInfo = (FillInfo *) info;
    GradientStopArray *stopArrPtr = fillInfo->stopArrPtr;
    double fillOpacity = fillInfo->fillOpacity;
    GradientStop **stopPtrPtr = stopArrPtr->stops;
    GradientStop *stop1 = NULL, *stop2 = NULL;
    int nstops = stopArrPtr->nstops;
    int i = 0;
    float par = *in;
    float f1, f2;

    /* Find the two stops for this point. Tricky! */
    while((i < nstops) && ((*stopPtrPtr)->offset < par)) {
        stopPtrPtr++, i++;
    }
    if(i == 0) {
        /* First stop > 0. */
        stop1 = *stopPtrPtr;
        stop2 = stop1;
    } else if(i == nstops) {
        /* We have stepped beyond the last stop; step back! */
        stop1 = *(stopPtrPtr - 1);
        stop2 = stop1;
    } else {
        stop1 = *(stopPtrPtr - 1);
        stop2 = *stopPtrPtr;
    }
    /* Interpolate between the two stops.
     * "If two gradient stops have the same offset value,
     * then the latter gradient stop controls the color value at the
     * overlap point."
     */
    if(fabs(stop2->offset - stop1->offset) < 1e-6) {
        *out++ = RedFloatFromXColorPtr(stop2->color);
        *out++ = GreenFloatFromXColorPtr(stop2->color);
        *out++ = BlueFloatFromXColorPtr(stop2->color);
        *out++ = stop2->opacity * fillOpacity;
    } else {
        f1 = (stop2->offset - par) / (stop2->offset - stop1->offset);
        f2 = (par - stop1->offset) / (stop2->offset - stop1->offset);
        *out++ = f1 * RedFloatFromXColorPtr(stop1->color) +
            f2 * RedFloatFromXColorPtr(stop2->color);
        *out++ = f1 * GreenFloatFromXColorPtr(stop1->color) +
            f2 * GreenFloatFromXColorPtr(stop2->color);
        *out++ = f1 * BlueFloatFromXColorPtr(stop1->color) +
            f2 * BlueFloatFromXColorPtr(stop2->color);
        *out++ = (f1 * stop1->opacity + f2 * stop2->opacity) * fillOpacity;
    }
}

static void
ShadeRelease(
    void *info)
{
    /* Not sure if anything to do here. */
}

void
TkPathPaintLinearGradient(
    TkPathContext ctx,
    PathRect * bbox,
    LinearGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TMatrix * mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef shading;
    CGPoint start, end;
    CGColorSpaceRef colorSpaceRef;
    CGFunctionRef function;
    CGFunctionCallbacks callbacks;
    PathRect *trans = fillPtr->transitionPtr;   /* The transition line. */
    FillInfo fillInfo;

    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;

    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    CGContextSaveGState(context->c);
    context->saveCount++;
    if(fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function =
        CGFunctionCreate((void *)&fillInfo, 1, kValidDomain, 4, kValidRange,
        &callbacks);
    start = CGPointMake(trans->x1, trans->y1);
    end = CGPointMake(trans->x2, trans->y2);
    shading = CGShadingCreateAxial(colorSpaceRef, start, end, function, 1, 1);
    if(mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGContextRestoreGState(context->c);
    context->saveCount--;
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
}

void
TkPathPaintRadialGradient(
    TkPathContext ctx,
    PathRect * bbox,
    RadialGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TMatrix * mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    CGShadingRef shading;
    CGPoint start, end;
    CGColorSpaceRef colorSpaceRef;
    CGFunctionRef function;
    CGFunctionCallbacks callbacks;
    RadialTransition *tPtr = fillPtr->radialPtr;
    FillInfo fillInfo;

    fillInfo.fillOpacity = fillOpacity;
    fillInfo.stopArrPtr = fillPtr->stopArrPtr;

    callbacks.version = 0;
    callbacks.evaluate = ShadeEvaluate;
    callbacks.releaseInfo = ShadeRelease;
    colorSpaceRef = CGColorSpaceCreateDeviceRGB();

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if(fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextSaveGState(context->c);
        context->saveCount++;
        CGContextTranslateCTM(context->c, bbox->x1, bbox->y1);
        CGContextScaleCTM(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    function =
        CGFunctionCreate((void *)&fillInfo, 1, kValidDomain, 4, kValidRange,
        &callbacks);
    start = CGPointMake(tPtr->focalX, tPtr->focalY);
    end = CGPointMake(tPtr->centerX, tPtr->centerY);
    shading =
        CGShadingCreateRadial(colorSpaceRef, start, 0.0, end, tPtr->radius,
        function, 1, 1);
    if(mPtr) {
        /* @@@ I'm not completely sure of the order of transforms here! */
        TkPathPushTMatrix(ctx, mPtr);
    }
    CGContextDrawShading(context->c, shading);
    CGShadingRelease(shading);
    CGFunctionRelease(function);
    CGColorSpaceRelease(colorSpaceRef);
    if(fillPtr->units == kPathGradientUnitsBoundingBox) {
        CGContextRestoreGState(context->c);
        context->saveCount--;
    }
}

int
TkPathSetup(
    Tcl_Interp * interp)
{
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
Added generic/tko/tkoPath_SDLAGG.cpp.


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkSDLAGGPath.cpp --
 *
 *        This file implements path drawing API's using SDL/Agg2D.
 *
 * Copyright (c) 2015, 2016 Christian Werner
 */

/* This should go into configure.in but don't know how. */
#ifdef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#undef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#endif

#include <tkSDLInt.h>
#include <SdlTkInt.h>

#include "tkoPath.h"

/* Avoid name clashes with Agg2D */

static const int X11_JoinMiter = JoinMiter;
static const int X11_JoinRound = JoinRound;
static const int X11_JoinBevel = JoinBevel;

#undef JoinMiter
#undef JoinRound
#undef JoinBevel

static const int X11_CapButt = CapButt;
static const int X11_CapRound = CapRound;
static const int X11_CapSquare = CapProjecting;

#undef CapButt
#undef CapRound
#undef CapProjecting
#undef CapSquare

/* XColor components to 8 bit unsigned */

#define XC_R(xc) ((xc)->red >> 8)
#define XC_G(xc) ((xc)->green >> 8)
#define XC_B(xc) ((xc)->blue >> 8)

#include "agg2d.h"

/*
 * Agg2D state for save/restore in surface.
 */

typedef struct {
    Agg2D::Color fillColor;
    Agg2D::Color lineColor;
    Agg2D::LineCap lineCap;
    Agg2D::LineJoin lineJoin;
    double lineWidth;
    bool fillEvenOdd;
        Agg2D::BlendMode blendMode;
        Agg2D::Transformations trans;
    int widthCode;             /* Used to depixelize the strokes: */
    /* 0: not integer width */
    /* 1: odd integer width */
    /* 2: even integer width */
} Agg2DState;

/*
 * This is used as a place holder for platform dependent stuff
 * between each call.
 */

typedef struct TkPathContext_ {
    Display *display;
    Agg2D *agg2d;
    double x, y;
    int width, height, widthCode;
    unsigned char *fb;         /* Frame buffer for surface or NULL. */
    int stack;                 /* State stack pointer. */
    Agg2DState states[8];      /* State stack for surface. */
} TkPathContext_;

/*
 * This is used to keep text information.
 */

typedef struct {
    char fontName[64];         /* Used as font name in Agg2D::font(). */
    const char *fontFile;      /* Used for XGetFTStream(). */
    int fontFileSize;          /* Used for XGetFTStream(). */
    int nLines;                /* Number of lines of text. */
    Tcl_DString uniString;     /* UCS-4 encoded multi-line text. */
} TextConf;

MODULE_SCOPE int gDepixelize;
MODULE_SCOPE int gSurfaceCopyPremultiplyAlpha;

static int
strlenU(
    const unsigned *string)
{
    int length = 0;
    while(*string != 0) {
        length++;
        string++;
    }
    return length;
}

/*
 * Standard tkpath interface.
 */

TkPathContext
TkPathInit(
    Tk_Window tkwin,
    Drawable d)
{
TkPathContext_ *context = (TkPathContext_ *) ckalloc(sizeof(TkPathContext_));
    context->display = Tk_Display(tkwin);
    context->agg2d = (Agg2D *) XGetAgg2D(context->display, d);
    context->x = context->y = 0;
    context->fb = NULL;
    context->stack = 0;
    context->agg2d->flipText(true);
    context->agg2d->masterAlpha(1.0);
    context->agg2d->imageResample(Agg2D::ResampleAlways);
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(
    Display * display,
    int width,
    int height)
{
    if((width <= 0) || (height <= 0)) {
        return (TkPathContext) NULL;
    }
Agg2D *agg2d = (Agg2D *) XCreateAgg2D(display);
    if(agg2d != NULL) {
TkPathContext_ *context =
    (TkPathContext_ *) attemptckalloc(sizeof(TkPathContext_));
        if(context == NULL) {
            goto error;
        }
        context->display = display;
        context->agg2d = agg2d;
        context->x = context->y = 0;
        context->width = width;
        context->height = height;
unsigned int fbsize = width * height * 4;
        context->fb = (unsigned char *)attemptckalloc(fbsize);
        if(context->fb == NULL) {
            ckfree((char *)context);
            goto error;
        }
        memset(context->fb, 0, fbsize);
        context->stack = 0;
        context->agg2d->attach(context->fb, width, height, width * 4);
        context->agg2d->flipText(true);
        context->agg2d->antiAliasGamma(1.5);
        context->agg2d->masterAlpha(0.9);
        context->agg2d->imageResample(Agg2D::ResampleAlways);
        return (TkPathContext) context;
    }
  error:
    if(agg2d != NULL) {
        XDestroyAgg2D(display, (void *)agg2d);
    }
    return (TkPathContext) NULL;
}

void
TkPathPushTMatrix(
    TkPathContext ctx,
    TMatrix * m)
{
    if(m == NULL) {
        return;
    }
TkPathContext_ *context = (TkPathContext_ *) ctx;
    Agg2D::Affine newTrans(m->a, m->b, m->c, m->d, m->tx, m->ty);
    Agg2D::Affine oldTrans(context->agg2d->transformations().affineMatrix);
    context->agg2d->resetTransformations();
    /* Order is important! */
    context->agg2d->affine(newTrans);
    context->agg2d->affine(oldTrans);
}

void
TkPathResetTMatrix(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->agg2d->resetTransformations();
}

void
TkPathSaveState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
unsigned i = context->stack;
    if(i + 1 >= sizeof(context->states) / sizeof(context->states[0])) {
        Tcl_Panic("out of path context stack space");
    }
Agg2DState *state = &context->states[i];
    state->fillColor = context->agg2d->fillColor();
    state->lineColor = context->agg2d->lineColor();
    state->lineCap = context->agg2d->lineCap();
    state->lineJoin = context->agg2d->lineJoin();
    state->lineWidth = context->agg2d->lineWidth();
    state->fillEvenOdd = context->agg2d->fillEvenOdd();
    state->blendMode = context->agg2d->blendMode();
    state->trans = context->agg2d->transformations();
    state->widthCode = context->widthCode;
    context->stack = i + 1;
}

void
TkPathRestoreState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
unsigned i = context->stack;
    if(i <= 0) {
        return;
    }
    --i;
Agg2DState *state = &context->states[i];
    context->agg2d->fillColor(state->fillColor);
    context->agg2d->lineColor(state->lineColor);
    context->agg2d->lineCap(state->lineCap);
    context->agg2d->lineJoin(state->lineJoin);
    context->agg2d->lineWidth(state->lineWidth);
    context->agg2d->fillEvenOdd(state->fillEvenOdd);
    context->agg2d->blendMode(state->blendMode);
    context->agg2d->transformations(state->trans);
    context->widthCode = state->widthCode;
    context->stack = i;
}

void
TkPathBeginPath(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
int nint;
double width;
    context->agg2d->resetPath();
    context->agg2d->fillEvenOdd(style->fillRule != WindingRule);
    if(style->strokeColor == NULL) {
        context->widthCode = 0;
    } else {
        width = style->strokeWidth;
        nint = (int)(width + 0.5);
        context->widthCode = (fabs(width - nint) > 0.01) ? 0 : (2 - nint % 2);
    }
}

void
TkPathMoveTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    context->agg2d->moveTo(x, y);
    context->x = x;
    context->y = y;
}

void
TkPathLineTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->agg2d->lineTo(x, y);
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    context->x = x;
    context->y = y;
}

void
TkPathLinesTo(
    TkPathContext ctx,
    double *pts,
    int n)
{
    /* @@@ TODO */
}

void
TkPathQuadBezier(
    TkPathContext ctx,
    double ctrlX,
    double ctrlY,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    context->agg2d->quadricCurveTo(ctrlX, ctrlY, x, y);
    context->x = x;
    context->y = y;
}

void
TkPathCurveTo(
    TkPathContext ctx,
    double ctrlX1,
    double ctrlY1,
    double ctrlX2,
    double ctrlY2,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    context->agg2d->cubicCurveTo(ctrlX1, ctrlY1, ctrlX2, ctrlY2, x, y);
    context->x = x;
    context->y = y;
}

void
TkPathArcTo(
    TkPathContext ctx,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    double phi = context->agg2d->deg2Rad(phiDegrees);
    context->agg2d->arcTo(rx, ry, phi, largeArcFlag, sweepFlag, x, y);
    context->x = x;
    context->y = y;
}

void
TkPathRectangle(
    TkPathContext ctx,
    double x,
    double y,
    double width,
    double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(gDepixelize) {
        x = PATH_DEPIXELIZE(context->widthCode, x);
        y = PATH_DEPIXELIZE(context->widthCode, y);
    }
    context->agg2d->closePolygon();
    context->agg2d->moveTo(x, y);
    context->agg2d->lineRel(width, 0);
    context->agg2d->lineRel(0, height);
    context->agg2d->lineRel(-width, 0);
    context->agg2d->closePolygon();
    context->x = x;
    context->y = y;
}

void
TkPathOval(
    TkPathContext ctx,
    double cx,
    double cy,
    double rx,
    double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->agg2d->closePolygon();
    context->agg2d->addEllipse(cx, cy, rx, ry, Agg2D::CCW);
    context->x = cx;
    context->y = cy;
}

void
TkPathImage(
    TkPathContext ctx,
    Tk_Image image,
    Tk_PhotoHandle photo,
    double x,
    double y,
    double width,
    double height,
    double fillOpacity,
    XColor * tintColor,
    double tintAmount,
    int interpolation,
    PathRect * srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    Tk_PhotoImageBlock block;
    Tk_PhotoGetImage(photo, &block);
    int srcX = (srcRegion != NULL) ? srcRegion->x1 : 0;
    int srcY = (srcRegion != NULL) ? srcRegion->y1 : 0;
    int srcWidth = (srcRegion != NULL) ?
        (srcRegion->x2 - srcRegion->x1) : block.width;
    int srcHeight = (srcRegion != NULL) ?
        (srcRegion->y2 - srcRegion->y1) : block.height;
    if(width == 0.0) {
        width = srcWidth;
    }
    if(height == 0.0) {
        height = srcHeight;
    }
    if(fillOpacity > 1.0) {
        fillOpacity = 1.0;
    } else if(fillOpacity < 0.0) {
        fillOpacity = 0.0;
    }
    double tintR, tintG, tintB;
    if((tintColor != NULL) && (tintAmount > 0.0)) {
        if(tintAmount > 1.0) {
            tintAmount = 1.0;
        }
        tintR = (double)XC_R(tintColor) / 0xFF;
        tintG = (double)XC_G(tintColor) / 0xFF;
        tintB = (double)XC_B(tintColor) / 0xFF;
    } else {
        tintAmount = 0.0;
        tintR = 0.0;
        tintG = 0.0;
        tintB = 0.0;
    }
    unsigned char *data = NULL;
    int iPitch;
    if(block.pixelSize == 4) {
    int srcR, srcG, srcB, srcA;
    int dstR, dstG, dstB, dstA;
        iPitch = block.width * 4;
        srcR = block.offset[0];
        srcG = block.offset[1];
        srcB = block.offset[2];
        srcA = block.offset[3];
        dstR = 2;
        dstG = 1;
        dstB = 0;
        dstA = 3;
        data = (unsigned char *)attemptckalloc(iPitch * block.height);
        if(data == NULL) {
            return;
        }
    int i, j;
        for(i = 0; i < block.height; i++) {
    unsigned char *srcPtr = block.pixelPtr + i * block.pitch;
    unsigned char *dstPtr = data + i * iPitch;
    unsigned char R, G, B;
            for(j = 0; j < block.width; j++) {
                R = *(srcPtr + srcR);
                G = *(srcPtr + srcG);
                B = *(srcPtr + srcB);
                if(tintAmount > 0.0) {
    int RR, GG, BB;
                    RR = (1.0 - tintAmount) * R +
                        (tintAmount * tintR * 0.2126 * R +
                        tintAmount * tintR * 0.7152 * G +
                        tintAmount * tintR * 0.0722 * B);
                    GG = (1.0 - tintAmount) * G +
                        (tintAmount * tintG * 0.2126 * R +
                        tintAmount * tintG * 0.7152 * G +
                        tintAmount * tintG * 0.0722 * B);
                    BB = (1.0 - tintAmount) * B +
                        (tintAmount * tintB * 0.2126 * R +
                        tintAmount * tintB * 0.7152 * G +
                        tintAmount * tintB * 0.0722 * B);
                    R = (RR > 0xFF) ? 0xFF : RR;
                    G = (GG > 0xFF) ? 0xFF : GG;
                    B = (BB > 0xFF) ? 0xFF : BB;
                }
                if(fillOpacity < 1.0) {
                    *(dstPtr + dstR) = R * fillOpacity;
                    *(dstPtr + dstG) = G * fillOpacity;
                    *(dstPtr + dstB) = B * fillOpacity;
                    *(dstPtr + dstA) = *(srcPtr + srcA) * fillOpacity;
                } else {
                    *(dstPtr + dstR) = R;
                    *(dstPtr + dstG) = G;
                    *(dstPtr + dstB) = B;
                    *(dstPtr + dstA) = *(srcPtr + srcA);
                }
                srcPtr += 4;
                dstPtr += 4;
            }
        }
    } else if(block.pixelSize == 3) {
    int srcR, srcG, srcB;
    int dstR, dstG, dstB, dstA;
        iPitch = block.width * 4;
        srcR = block.offset[0];
        srcG = block.offset[1];
        srcB = block.offset[2];
        dstR = 2;
        dstG = 1;
        dstB = 0;
        dstA = 3;
        data = (unsigned char *)attemptckalloc(iPitch * block.height);
        if(data == NULL) {
            return;
        }
    int i, j;
        for(i = 0; i < block.height; i++) {
    unsigned char *srcPtr = block.pixelPtr + i * block.pitch;
    unsigned char *dstPtr = data + i * iPitch;
    unsigned char R, G, B;
            for(j = 0; j < block.width; j++) {
                R = *(srcPtr + srcR);
                G = *(srcPtr + srcG);
                B = *(srcPtr + srcB);
                if(tintAmount > 0.0) {
    int RR, GG, BB;
                    RR = (1.0 - tintAmount) * R +
                        (tintAmount * tintR * 0.2126 * R +
                        tintAmount * tintR * 0.7152 * G +
                        tintAmount * tintR * 0.0722 * B);
                    GG = (1.0 - tintAmount) * G +
                        (tintAmount * tintG * 0.2126 * R +
                        tintAmount * tintG * 0.7152 * G +
                        tintAmount * tintG * 0.0722 * B);
                    BB = (1.0 - tintAmount) * B +
                        (tintAmount * tintB * 0.2126 * R +
                        tintAmount * tintB * 0.7152 * G +
                        tintAmount * tintB * 0.0722 * B);
                    R = (RR > 0xFF) ? 0xFF : RR;
                    G = (GG > 0xFF) ? 0xFF : GG;
                    B = (BB > 0xFF) ? 0xFF : BB;
                }
                if(fillOpacity < 1.0) {
                    *(dstPtr + dstR) = R * fillOpacity;
                    *(dstPtr + dstG) = G * fillOpacity;
                    *(dstPtr + dstB) = B * fillOpacity;
                    *(dstPtr + dstA) = 0xFF * fillOpacity;
                } else {
                    *(dstPtr + dstR) = R;
                    *(dstPtr + dstG) = G;
                    *(dstPtr + dstB) = B;
                    *(dstPtr + dstA) = 0xFF;
                }
                srcPtr += 3;
                dstPtr += 4;
            }
        }
    } else if(block.pixelSize == 1) {
    int srcC;
    int dstR, dstG, dstB, dstA;
        iPitch = block.width * 4;
        srcC = block.offset[0];
        dstR = 2;
        dstG = 1;
        dstB = 0;
        dstA = 3;
        data = (unsigned char *)attemptckalloc(iPitch * block.height);
        if(data == NULL) {
            return;
        }
    int i, j;
        for(i = 0; i < block.height; i++) {
    unsigned char *srcPtr = block.pixelPtr + i * block.pitch;
    unsigned char *dstPtr = data + i * iPitch;
    unsigned char R, G, B;
            for(j = 0; j < block.width; j++) {
                R = *(srcPtr + srcC);
                G = *(srcPtr + srcC);
                B = *(srcPtr + srcC);
                if(tintAmount > 0.0) {
    int RR, GG, BB;
                    RR = (1.0 - tintAmount) * R +
                        (tintAmount * tintR * 0.2126 * R +
                        tintAmount * tintR * 0.7152 * G +
                        tintAmount * tintR * 0.0722 * B);
                    GG = (1.0 - tintAmount) * G +
                        (tintAmount * tintG * 0.2126 * R +
                        tintAmount * tintG * 0.7152 * G +
                        tintAmount * tintG * 0.0722 * B);
                    BB = (1.0 - tintAmount) * B +
                        (tintAmount * tintB * 0.2126 * R +
                        tintAmount * tintB * 0.7152 * G +
                        tintAmount * tintB * 0.0722 * B);
                    R = (RR > 0xFF) ? 0xFF : RR;
                    G = (GG > 0xFF) ? 0xFF : GG;
                    B = (BB > 0xFF) ? 0xFF : BB;
                }
                if(fillOpacity < 1.0) {
                    *(dstPtr + dstR) = R * fillOpacity;
                    *(dstPtr + dstG) = G * fillOpacity;
                    *(dstPtr + dstB) = B * fillOpacity;
                    *(dstPtr + dstA) = 0xFF * fillOpacity;
                } else {
                    *(dstPtr + dstR) = R;
                    *(dstPtr + dstG) = G;
                    *(dstPtr + dstB) = B;
                    *(dstPtr + dstA) = 0xFF;
                }
                srcPtr += 1;
                dstPtr += 4;
            }
        }
    } else {
        return;
    }
    Agg2D::Image img(data, block.width, block.height, iPitch);
    Agg2D::ImageFilter filter;
    switch (interpolation) {
    default:
    case kPathImageInterpolationNone:
        filter = Agg2D::NoFilter;
        break;
    case kPathImageInterpolationFast:
        filter = Agg2D::Bilinear;
        break;
    case kPathImageInterpolationBest:
        filter = Agg2D::Bicubic;
        break;
    }
    if(srcRegion != NULL) {
        context->agg2d->imageWrapMode(Agg2D::WrapRepeat);
    }
    context->agg2d->imageFilter(filter);
    Agg2D::Affine oldTrans(context->agg2d->transformations().affineMatrix);
    context->agg2d->resetTransformations();
    context->agg2d->translate(x, y);
    context->agg2d->affine(oldTrans);
    context->agg2d->transformImage(img, srcX, srcY,
        srcX + srcWidth, srcY + srcHeight, 0, 0, width, height);
    if(data != NULL) {
        ckfree((char *)data);
    }
}

void
TkPathClosePath(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->agg2d->closePolygon();
}

int
TkPathTextConfig(
    Tcl_Interp * interp,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    void **customPtr)
{
    const char *fontFile;
    int fontFileSize;
    if(!XGetFontFile(textStylePtr->fontFamily, textStylePtr->fontSize,
            textStylePtr->fontWeight == PATH_TEXT_WEIGHT_BOLD,
            (textStylePtr->fontSlant == PATH_TEXT_SLANT_ITALIC) ||
            (textStylePtr->fontSlant == PATH_TEXT_SLANT_OBLIQUE),
            &fontFile, &fontFileSize)) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("font not found", -1));
        return TCL_ERROR;
    }
    TextConf *tconf = (TextConf *) ckalloc(sizeof(TextConf));
    sprintf(tconf->fontName, "font_%p_0x%08x", fontFile, fontFileSize);
    tconf->fontFile = fontFile;
    tconf->fontFileSize = fontFileSize;
    Tcl_DStringInit(&tconf->uniString);
    tconf->nLines = 1;
    int length = strlen(utf8);
    Tcl_DStringSetLength(&tconf->uniString, length * sizeof(unsigned));
    Tcl_DStringSetLength(&tconf->uniString, 0);
    const char *p = utf8;
    unsigned chu;
    while(p < utf8 + length) {
    Tcl_UniChar ch;
    int next = Tcl_UtfToUniChar(p, &ch);
        chu = ch;
        if(chu == '\n') {
            chu = 0;    /* end-of-line marker */
            tconf->nLines++;
        } else if(chu == '\r') {
            chu = 0;    /* end-of-line marker */
            if(p[next] == '\n') {
                ++next;
            }
            tconf->nLines++;
        } else if(chu == '\t') {
            /* two blanks */
            chu = ' ';
            Tcl_DStringAppend(&tconf->uniString, (const char *)&chu,
                sizeof(unsigned));
        } else if(chu < ' ') {
            goto skip;
        }
        Tcl_DStringAppend(&tconf->uniString, (const char *)&chu,
            sizeof(unsigned));
      skip:
        p += next;
    }
    chu = 0;   /* end-of-line marker */
    Tcl_DStringAppend(&tconf->uniString, (const char *)&chu, sizeof(unsigned));
    *customPtr = (void *)tconf;
    return TCL_OK;
}

static void
textLineU(
    Agg2D * agg2d,
    double &x,
    double &y,
    const unsigned **string)
{
    int length = strlenU(*string);
    agg2d->textU(x, y, *string, length);
    *string += length + 1;
    y += agg2d->fontAscent() - agg2d->fontDescent();
    agg2d->resetPath();
}

void
TkPathTextDraw(
    TkPathContext ctx,
    Tk_PathStyle * style,
    Tk_PathTextStyle * textStylePtr,
    double x,
    double y,
    int fillOverStroke,
    char *utf8,
    void *custom)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    TextConf *tconf = (TextConf *) custom;
    context->agg2d->font(tconf->fontName, textStylePtr->fontSize,
        textStylePtr->fontWeight == PATH_TEXT_WEIGHT_BOLD,
        (textStylePtr->fontSlant == PATH_TEXT_SLANT_ITALIC) ||
        (textStylePtr->fontSlant == PATH_TEXT_SLANT_OBLIQUE),
        Agg2D::VectorFontCache, 0.0,
        (const char *)XGetFTStream(tconf->fontFile, tconf->fontFileSize), 0);
    int hasStroke = style->strokeColor != NULL;
    int hasFill = (style->fill != NULL) && (style->fill->color != NULL);
    double opacity, tx, ty;
    const unsigned *string;
    if(fillOverStroke && hasFill && hasStroke) {
        context->agg2d->lineWidth(style->strokeWidth);
        context->agg2d->miterLimit(style->miterLimit);
        opacity = style->strokeOpacity;
        if(opacity > 1.0) {
            opacity = 1.0;
        } else if(opacity < 0.0) {
            opacity = 0.0;
        }
        context->agg2d->lineColor(XC_R(style->strokeColor),
            XC_G(style->strokeColor),
            XC_B(style->strokeColor), (unsigned)(opacity * 0xFF));
        context->agg2d->noFill();
        string = (const unsigned *)Tcl_DStringValue(&tconf->uniString);
        tx = x;
        ty = y;
        for(int i = 0; i < tconf->nLines; i++) {
            textLineU(context->agg2d, tx, ty, &string);
        }
        opacity = style->fillOpacity;
        if(opacity > 1.0) {
            opacity = 1.0;
        } else if(opacity < 0.0) {
            opacity = 0.0;
        }
        context->agg2d->fillColor(XC_R(style->fill->color),
            XC_G(style->fill->color),
            XC_B(style->fill->color), (unsigned)(opacity * 0xFF));
        context->agg2d->noLine();
        string = (const unsigned *)Tcl_DStringValue(&tconf->uniString);
        tx = x;
        ty = y;
        for(int i = 0; i < tconf->nLines; i++) {
            textLineU(context->agg2d, tx, ty, &string);
        }
    } else if(hasStroke || hasFill) {
        if(hasFill) {
            opacity = style->fillOpacity;
            if(opacity > 1.0) {
                opacity = 1.0;
            } else if(opacity < 0.0) {
                opacity = 0.0;
            }
            context->agg2d->fillColor(XC_R(style->fill->color),
                XC_G(style->fill->color),
                XC_B(style->fill->color), (unsigned)(opacity * 0xFF));
        } else {
            context->agg2d->noFill();
        }
        if(hasStroke) {
            opacity = style->strokeOpacity;
            if(opacity > 1.0) {
                opacity = 1.0;
            } else if(opacity < 0.0) {
                opacity = 0.0;
            }
            context->agg2d->lineWidth(style->strokeWidth);
            context->agg2d->miterLimit(style->miterLimit);
            context->agg2d->lineColor(XC_R(style->strokeColor),
                XC_G(style->strokeColor),
                XC_B(style->strokeColor), (unsigned)(opacity * 0xFF));
        } else {
            context->agg2d->noLine();
        }
        string = (const unsigned *)Tcl_DStringValue(&tconf->uniString);
        tx = x;
        ty = y;
        for(int i = 0; i < tconf->nLines; i++) {
            textLineU(context->agg2d, tx, ty, &string);
        }
    }
}

void
TkPathTextFree(
    Tk_PathTextStyle * textStylePtr,
    void *custom)
{
    if(custom != NULL) {
    TextConf *tconf = (TextConf *) custom;
        Tcl_DStringFree(&tconf->uniString);
        ckfree((char *)custom);
    }
}

PathRect
TkPathTextMeasureBbox(
    Display * display,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    double *lineSpacing,
    void *custom)
{
    PathRect rect = { 0.0, 0.0, 0.0, 0.0 };
    if(custom == NULL) {
        return rect;
    }
    Agg2D *agg2d = (Agg2D *) XGetAgg2D(display, None);
    if(agg2d == NULL) {
        return rect;
    }
    TextConf *tconf = (TextConf *) custom;
    agg2d->font(tconf->fontName, textStylePtr->fontSize,
        textStylePtr->fontWeight == PATH_TEXT_WEIGHT_BOLD,
        (textStylePtr->fontSlant == PATH_TEXT_SLANT_ITALIC) ||
        (textStylePtr->fontSlant == PATH_TEXT_SLANT_OBLIQUE),
        Agg2D::VectorFontCache, 0.0,
        (const char *)XGetFTStream(tconf->fontFile, tconf->fontFileSize), 0);
    rect.y1 = 0.0 - agg2d->fontAscent();
    rect.y2 = tconf->nLines * (agg2d->fontAscent() - agg2d->fontDescent())
        - agg2d->fontAscent();
    const unsigned *string =
        (const unsigned *)Tcl_DStringValue(&tconf->uniString);
    for(int i = 0; i < tconf->nLines; i++) {
    int length = strlenU(string);
    double x2 = agg2d->textWidthU(string, length);
        if(x2 > rect.x2) {
            rect.x2 = x2;
        }
        string += length + 1;
    }
    if(lineSpacing != NULL) {
        *lineSpacing = agg2d->fontAscent() - agg2d->fontDescent();
    }
    XDestroyAgg2D(display, (void *)agg2d);
    return rect;
}

void
TkPathSurfaceErase(
    TkPathContext ctx,
    double dx,
    double dy,
    double dwidth,
    double dheight)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(context->fb == NULL) {
        return;
    }
    int x = (int)(dx + 0.5);
    int y = (int)(dy + 0.5);
    int width = (int)(dwidth + 0.5);
    int height = (int)(dheight + 0.5);
    x = MAX(0, MIN(context->width, x));
    y = MAX(0, MIN(context->height, y));
    width = MAX(0, width);
    height = MAX(0, height);
    int xend = MIN(x + width, context->width);
    int yend = MIN(y + height, context->height);
    int bwidth = (xend - x) * 4;
    int stride = context->width * 4;
    for(int i = y; i < yend; i++) {
    unsigned char *dst = context->fb + i * stride + x * 4;
        memset(dst, 0, bwidth);
    }
}

void
TkPathSurfaceToPhoto(
    Tcl_Interp * interp,
    TkPathContext ctx,
    Tk_PhotoHandle photo)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(context->fb == NULL) {
        return;
    }
Tk_PhotoImageBlock block;
    Tk_PhotoGetImage(photo, &block);
unsigned char *pixel = (unsigned char *)
        attemptckalloc(context->height * context->width * 4);
    if(pixel == NULL) {
        return;
    }
    if(gSurfaceCopyPremultiplyAlpha) {
        TkPathCopyBitsPremultipliedAlphaBGRA(context->fb, pixel,
            context->width, context->height, context->width * 4);
    } else {
        TkPathCopyBitsBGRA(context->fb, pixel, context->width, context->height,
            context->width * 4);
    }
    block.pixelPtr = pixel;
    block.width = context->width;
    block.height = context->height;
    block.pitch = context->width * 4;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, context->width,
        context->height, TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *)pixel);
}

void
TkPathEndPath(
    TkPathContext ctx)
{
}

void
TkPathFree(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    XDestroyAgg2D(context->display, (void *)context->agg2d);
    if(context->fb != NULL) {
        ckfree((char *)context->fb);
    }
    ckfree((char *)context);
}

void
TkPathClipToPath(
    TkPathContext ctx,
    int fillRule)
{
}

void
TkPathReleaseClipToPath(
    TkPathContext ctx)
{
}

void
TkPathStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
Tk_PathDash *dashes = style->dashPtr;
    context->agg2d->lineWidth(style->strokeWidth);
    if(style->capStyle == X11_CapRound) {
        context->agg2d->lineCap(Agg2D::CapRound);
    } else if(style->capStyle == X11_CapSquare) {
        context->agg2d->lineCap(Agg2D::CapSquare);
    } else {
        context->agg2d->lineCap(Agg2D::CapButt);
    }
    if(style->joinStyle == X11_JoinMiter) {
        context->agg2d->lineJoin(Agg2D::JoinMiter);
    } else if(style->joinStyle == X11_JoinRound) {
        context->agg2d->lineJoin(Agg2D::JoinRound);
    } else {
        context->agg2d->lineJoin(Agg2D::JoinBevel);
    }
    context->agg2d->miterLimit(style->miterLimit);
double opacity = style->strokeOpacity;
    if(opacity > 1.0) {
        opacity = 1.0;
    } else if(opacity < 0.0) {
        opacity = 0.0;
    }
    context->agg2d->lineColor(XC_R(style->strokeColor),
        XC_G(style->strokeColor),
        XC_B(style->strokeColor), (unsigned)(opacity * 0xFF));
    context->agg2d->noFill();
    if((dashes != NULL) && (dashes->number > 0)) {
        context->agg2d->setDash(dashes->array, dashes->number, style->offset);
    }
    context->agg2d->drawPath(Agg2D::StrokeOnly);
    if((dashes != NULL) && (dashes->number > 0)) {
        context->agg2d->setDash((float *)NULL, 0);
    }
}

void
TkPathFill(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
double opacity = style->fillOpacity;
    if(opacity > 1.0) {
        opacity = 1.0;
    } else if(opacity < 0.0) {
        opacity = 0.0;
    }
    context->agg2d->fillColor(XC_R(style->fill->color),
        XC_G(style->fill->color),
        XC_B(style->fill->color), (unsigned)(opacity * 0xFF));
    context->agg2d->noLine();
    context->agg2d->drawPath(Agg2D::FillOnly);
}

void
TkPathFillAndStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
Tk_PathDash *dashes = style->dashPtr;
    context->agg2d->lineWidth(style->strokeWidth);
    if(style->capStyle == X11_CapRound) {
        context->agg2d->lineCap(Agg2D::CapRound);
    } else if(style->capStyle == X11_CapSquare) {
        context->agg2d->lineCap(Agg2D::CapSquare);
    } else {
        context->agg2d->lineCap(Agg2D::CapButt);
    }
    if(style->joinStyle == X11_JoinMiter) {
        context->agg2d->lineJoin(Agg2D::JoinMiter);
    } else if(style->joinStyle == X11_JoinRound) {
        context->agg2d->lineJoin(Agg2D::JoinRound);
    } else {
        context->agg2d->lineJoin(Agg2D::JoinBevel);
    }
    context->agg2d->miterLimit(style->miterLimit);
double opacity = style->strokeOpacity;
    if(opacity > 1.0) {
        opacity = 1.0;
    } else if(opacity < 0.0) {
        opacity = 0.0;
    }
    context->agg2d->lineColor(XC_R(style->strokeColor),
        XC_G(style->strokeColor),
        XC_B(style->strokeColor), (unsigned)(opacity * 0xFF));
    opacity = style->fillOpacity;
    if(opacity > 1.0) {
        opacity = 1.0;
    } else if(opacity < 0.0) {
        opacity = 0.0;
    }
    context->agg2d->fillColor(XC_R(style->fill->color),
        XC_G(style->fill->color),
        XC_B(style->fill->color), (unsigned)(opacity * 0xFF));
    if((dashes != NULL) && (dashes->number > 0)) {
        context->agg2d->setDash(dashes->array, dashes->number, style->offset);
    }
    context->agg2d->drawPath(Agg2D::FillAndStroke);
    if((dashes != NULL) && (dashes->number > 0)) {
        context->agg2d->setDash((float *)NULL, 0);
    }
}

int
TkPathGetCurrentPosition(
    TkPathContext ctx,
    PathPoint * ptPtr)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    ptPtr->x = context->x;
    ptPtr->y = context->y;
    return TCL_OK;
}

int
TkPathDrawingDestroysPath(
    void)
{
    return 0;
}

int
TkPathPixelAlign(
    void)
{
    return 0;
}

void
TkPathPaintLinearGradient(
    TkPathContext ctx,
    PathRect * bbox,
    LinearGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TMatrix * mPtr)
{
    if(fillOpacity > 1.0) {
        fillOpacity = 1.0;
    } else if(fillOpacity < 0.0) {
        fillOpacity = 0.0;
    }
    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    PathRect *tPtr = fillPtr->transitionPtr;
    double x1, y1, x2, y2;
    if(fillPtr->units == kPathGradientUnitsBoundingBox) {
    double x = bbox->x1;
    double y = bbox->y1;
    double width = bbox->x2 - bbox->x1;
    double height = bbox->y2 - bbox->y1;
        x1 = x + tPtr->x1 * width;
        y1 = y + tPtr->y1 * height;
        x2 = x + tPtr->x2 * width;
        y2 = y + tPtr->y2 * height;
    } else {
        x1 = tPtr->x1;
        y1 = tPtr->y1;
        x2 = tPtr->x2;
        y2 = tPtr->y2;
    }
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(fillPtr->stopArrPtr->nstops > 0) {
    int nstops = fillPtr->stopArrPtr->nstops;
    double *offsets = (double *)Tcl_Alloc(nstops * sizeof(double));
        Agg2D::Color * colors =
            (Agg2D::Color *) ckalloc(nstops * sizeof(Agg2D::Color));
        for(int i = 0; i < nstops; i++) {
    GradientStop *stop = fillPtr->stopArrPtr->stops[i];
            offsets[i] = stop->offset;
    double opacity = stop->opacity;
            if(opacity > 1.0) {
                opacity = 1.0;
            } else if(opacity < 0.0) {
                opacity = 0.0;
            }
            Agg2D::Color color(XC_R(stop->color),
                XC_G(stop->color),
                XC_B(stop->color), (unsigned)(opacity * fillOpacity * 0xFF));
            colors[i] = color;
        }
        Agg2D::GradientMode meth;
        switch (fillPtr->method) {
        default:
        case kPathGradientMethodPad:
            meth = Agg2D::GradientPad;
            break;
        case kPathGradientMethodRepeat:
            meth = Agg2D::GradientRepeat;
            break;
        case kPathGradientMethodReflect:
            meth = Agg2D::GradientReflect;
            break;
        }
        context->agg2d->fillLinearGradient(x1, y1, x2, y2,
            nstops, offsets, colors, meth);
        ckfree((char *)offsets);
        ckfree((char *)colors);
    }
    context->agg2d->fillEvenOdd(fillRule != WindingRule);
    context->agg2d->drawPath(Agg2D::FillOnly);
}

void
TkPathPaintRadialGradient(
    TkPathContext ctx,
    PathRect * bbox,
    RadialGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TMatrix * mPtr)
{
    if(fillOpacity > 1.0) {
        fillOpacity = 1.0;
    } else if(fillOpacity < 0.0) {
        fillOpacity = 0.0;
    }
    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    RadialTransition *tPtr = fillPtr->radialPtr;
    double centerX, centerY, radiusX, focalX, focalY, scaleX, scaleY;
#if 0
    double radiusY;
#endif
    double width = bbox->x2 - bbox->x1;
    double height = bbox->y2 - bbox->y1;
    if(fillPtr->units == kPathGradientUnitsBoundingBox) {
        centerX = width * tPtr->centerX;
        centerY = height * tPtr->centerY;
        radiusX = width * tPtr->radius;
#if 0
        radiusY = height * tPtr->radius;
#endif
        focalX = width * tPtr->focalX;
        focalY = height * tPtr->focalY;
    } else {
        centerX = tPtr->centerX;
        centerY = tPtr->centerY;
        radiusX = tPtr->radius;
#if 0
        radiusY = tPtr->radius;
#endif
        focalX = tPtr->focalX;
        focalY = tPtr->focalY;
    }
    if(width > height) {
        scaleX = 1.0;
        scaleY = height / width;
    } else {
        scaleX = width / height;
        scaleY = 1.0;
    }
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(fillPtr->stopArrPtr->nstops > 0) {
    int nstops = fillPtr->stopArrPtr->nstops;
    double *offsets = (double *)Tcl_Alloc(nstops * sizeof(double));
        Agg2D::Color * colors =
            (Agg2D::Color *) ckalloc(nstops * sizeof(Agg2D::Color));
        for(int i = 0; i < nstops; i++) {
    GradientStop *stop = fillPtr->stopArrPtr->stops[i];
            offsets[i] = stop->offset;
    double opacity = stop->opacity;
            if(opacity > 1.0) {
                opacity = 1.0;
            } else if(opacity < 0.0) {
                opacity = 0.0;
            }
            Agg2D::Color color(XC_R(stop->color),
                XC_G(stop->color),
                XC_B(stop->color), (unsigned)(opacity * fillOpacity * 0xFF));
            colors[i] = color;
        }
        Agg2D::GradientMode meth;
        switch (fillPtr->method) {
        default:
        case kPathGradientMethodPad:
            meth = Agg2D::GradientPad;
            break;
        case kPathGradientMethodRepeat:
            meth = Agg2D::GradientRepeat;
            break;
        case kPathGradientMethodReflect:
            meth = Agg2D::GradientReflect;
            break;
        }
        context->agg2d->fillRadialGradient(centerX + bbox->x1,
            centerY + bbox->y1,
            focalX + bbox->x1,
            focalY + bbox->y1,
            radiusX, scaleX, scaleY, nstops, offsets, colors, meth);
        ckfree((char *)offsets);
        ckfree((char *)colors);
    }
    context->agg2d->fillEvenOdd(fillRule != WindingRule);
    context->agg2d->drawPath(Agg2D::FillOnly);
}

int
TkPathSetup(
    Tcl_Interp * interp)
{
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
Added generic/tko/tkoPath_UnixCairo.c.




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkUnixCairoPath.c --
 *
 *     This file implements path drawing API's using the Cairo rendering engine.
 *
 *  TODO: implement text drawing using glyphs instead of the "toy" text API.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

/* This should go into configure.in but don't know how. */
#ifdef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#undef USE_PANIC_ON_PHOTO_ALLOC_FAILURE
#endif

#include <cairo.h>
#include <cairo-xlib.h>
#include <tkUnixInt.h>
#include "tkoPath.h"

#define TINT_INT_CALCULATION

#define Blue255FromXColorPtr(xc)   ((xc)->blue >> 8)
#define Green255FromXColorPtr(xc)  ((xc)->green >> 8)
#define Red255FromXColorPtr(xc)    ((xc)->red >> 8)

#define BlueDoubleFromXColorPtr(xc)   ((double) ((xc)->blue >> 8) / 255.0)
#define GreenDoubleFromXColorPtr(xc)  ((double) ((xc)->green >> 8) / 255.0)
#define RedDoubleFromXColorPtr(xc)    ((double) ((xc)->red >> 8) / 255.0)

MODULE_SCOPE int Tk_PathAntiAlias;
MODULE_SCOPE int Tk_PathSurfaceCopyPremultiplyAlpha;
MODULE_SCOPE int Tk_PathDepixelize;

static union {
    short set;
    char little;
} kEndianess;

/*
 * @@@ Need to use cairo_image_surface_create_for_data() here since
 *     prior to 1.2 there doesn't exist any cairo_image_surface_get_data()
 *     accessor.
 */
typedef struct PathSurfaceCairoRecord {
    unsigned char *data;
    cairo_format_t format;
    int width;
    int height;
    int stride;                /* number of bytes between the start of rows in the buffer */
} PathSurfaceCairoRecord;

/*
 * This is used as a place holder for platform dependent
 * stuff between each call.
 */
typedef struct TkPathContext_ {
    cairo_t *c;
    cairo_surface_t *surface;
    PathSurfaceCairoRecord *record;     /* NULL except for memory surfaces.
                                         * Skip when cairo 1.2 widely spread. */
    int widthCode;             /* Used to depixelize the strokes:
                                * 0: not integer width
                                * 1: odd integer width
                                * 2: even integer width */
    cairo_matrix_t def_matrix; /* For TkPathResetTMatrix() */
} TkPathContext_;

static void TkPathPrepareForStroke(
    TkPathContext ctx,
    Tk_PathStyle * style);

static void
CairoSetFill(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    /* Patch from Tim Edwards to handle color correctly on 64 bit arch. */
    cairo_set_source_rgba(context->c,
        (double)(GetColorFromPathColor(style->fill)->red) / 0xFFFF,
        (double)(GetColorFromPathColor(style->fill)->green) / 0xFFFF,
        (double)(GetColorFromPathColor(style->fill)->blue) / 0xFFFF,
        style->fillOpacity);
    cairo_set_fill_rule(context->c,
        (style->fillRule == WindingRule) ? CAIRO_FILL_RULE_WINDING :
        CAIRO_FILL_RULE_EVEN_ODD);
}

TkPathContext
TkPathInit(
    Tk_Window tkwin,
    Drawable d)
{
cairo_t *c;
cairo_surface_t *surface;
TkPathContext_ *context = (TkPathContext_ *)
        ckalloc((unsigned)(sizeof(TkPathContext_)));
Window dummy;
int x, y;
unsigned int width, height, borderWidth, depth;

    /* Find size of Drawable */
    XGetGeometry(Tk_Display(tkwin), d,
        &dummy, &x, &y, &width, &height, &borderWidth, &depth);

    surface = cairo_xlib_surface_create(Tk_Display(tkwin), d, Tk_Visual(tkwin),
        width, height);
    c = cairo_create(surface);
    context->c = c;
    context->surface = surface;
    context->record = NULL;
    context->widthCode = 0;
    cairo_get_matrix(context->c, &context->def_matrix);
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(
    Display * display,
    int width,
    int height)
{
cairo_t *c;
cairo_surface_t *surface;
unsigned char *data;
int stride;

    /*
     * @@@ Need to use cairo_image_surface_create_for_data() here since
     *     prior to 1.2 there doesn't exist any cairo_image_surface_get_data()
     *     accessor.
     */
TkPathContext_ *context = (TkPathContext_ *)
        ckalloc((unsigned)(sizeof(TkPathContext_)));
PathSurfaceCairoRecord *record = (PathSurfaceCairoRecord *)
        ckalloc((unsigned)(sizeof(PathSurfaceCairoRecord)));
    stride = 4 * width;
    /* Round up to nearest multiple of 16 */
    stride = (stride + (16 - 1)) & ~(16 - 1);
    data = (unsigned char *)ckalloc(height * stride);
    memset(data, '\0', height * stride);
    surface = cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32,
        width, height, stride);
    record->data = data;
    record->format = CAIRO_FORMAT_ARGB32;
    record->width = width;
    record->height = height;
    record->stride = stride;
    c = cairo_create(surface);
    context->c = c;
    context->surface = surface;
    context->record = record;
    context->widthCode = 0;
    cairo_get_matrix(context->c, &context->def_matrix);
    return (TkPathContext) context;
}

void
TkPathPushTMatrix(
    TkPathContext ctx,
    TkPathMatrix * m)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
cairo_matrix_t matrix;
    if(m == NULL) {
        return;
    }
    cairo_matrix_init(&matrix, m->a, m->b, m->c, m->d, m->tx, m->ty);
    cairo_transform(context->c, &matrix);
}

void
TkPathResetTMatrix(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    context->widthCode = 0;
    cairo_set_matrix(context->c, &context->def_matrix);
}

void
TkPathSaveState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_save(context->c);
}

void
TkPathRestoreState(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_restore(context->c);
}

void
TkPathBeginPath(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
int nint;
double width;
    cairo_new_path(context->c);
    if(style->strokeColor == NULL) {
        context->widthCode = 0;
    } else {
        width = style->strokeWidth;
        nint = (int)(width + 0.5);
        context->widthCode = fabs(width - nint) > 0.01 ? 0 : 2 - nint % 2;
    }
}

void
TkPathMoveTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    cairo_move_to(context->c, x, y);
}

void
TkPathLineTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    cairo_line_to(context->c, x, y);
}

void
TkPathQuadBezier(
    TkPathContext ctx,
    double ctrlX,
    double ctrlY,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    double cx, cy;
    double x31, y31, x32, y32;

    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    cairo_get_current_point(context->c, &cx, &cy);

    /*
     * Conversion of quadratic bezier curve to
     * cubic bezier curve: (mozilla/svg)
     * Unchecked! Must be an approximation!
     */
    x31 = cx + (ctrlX - cx) * 2 / 3;
    y31 = cy + (ctrlY - cy) * 2 / 3;
    x32 = ctrlX + (x - ctrlX) / 3;
    y32 = ctrlY + (y - ctrlY) / 3;

    cairo_curve_to(context->c, x31, y31, x32, y32, x, y);
}

void
TkPathCurveTo(
    TkPathContext ctx,
    double x1,
    double y1,
    double x2,
    double y2,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    cairo_curve_to(context->c, x1, y1, x2, y2, x, y);
}

void
TkPathArcTo(
    TkPathContext ctx,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag,
        sweepFlag, x, y);
}

void
TkPathRectangle(
    TkPathContext ctx,
    double x,
    double y,
    double width,
    double height)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(Tk_PathDepixelize) {
        x = TK_PATH_DEPIXELIZE(context->widthCode, x);
        y = TK_PATH_DEPIXELIZE(context->widthCode, y);
    }
    cairo_rectangle(context->c, x, y, width, height);
}

void
TkPathOval(
    TkPathContext ctx,
    double cx,
    double cy,
    double rx,
    double ry)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    if(rx == ry) {
        cairo_move_to(context->c, cx + rx, cy);
        cairo_arc(context->c, cx, cy, rx, 0.0, 2 * M_PI);
        cairo_close_path(context->c);
    } else {
        cairo_save(context->c);
        cairo_translate(context->c, cx, cy);
        cairo_scale(context->c, rx, ry);
        cairo_move_to(context->c, 1.0, 0.0);
        cairo_arc(context->c, 0.0, 0.0, 1.0, 0.0, 2 * M_PI);
        cairo_close_path(context->c);
        cairo_restore(context->c);
    }
}

static cairo_filter_t
convertInterpolationToCairoFilter(
    int interpolation)
{
    switch (interpolation) {
    case TK_PATH_IMAGEINTERPOLATION_None:
        return CAIRO_FILTER_FAST;
    case TK_PATH_IMAGEINTERPOLATION_Fast:
        return CAIRO_FILTER_GOOD;
    case TK_PATH_IMAGEINTERPOLATION_Best:
        return CAIRO_FILTER_BEST;
    }
    return CAIRO_FILTER_GOOD;
}

void
TkPathImage(
    TkPathContext ctx,
    Tk_Image image,
    Tk_PhotoHandle photo,
    double x,
    double y,
    double width0,
    double height0,
    double fillOpacity,
    XColor * tintColor,
    double tintAmount,
    int interpolation,
    TkPathRect * srcRegion)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    Tk_PhotoImageBlock block;
    cairo_surface_t *surface;
    cairo_format_t format;
    unsigned char *data = NULL;
    unsigned char *ptr = NULL;
    unsigned char *srcPtr, *dstPtr;
    int srcR, srcG, srcB, srcA; /* The source pixel offsets. */
    int dstR, dstG, dstB, dstA; /* The destination pixel offsets. */
    int pitch;
    int iwidth, iheight;
    int i, j;
    double width, height;
    cairo_filter_t filter;

    /* Return value? */
    Tk_PhotoGetImage(photo, &block);
    iwidth = block.width;
    iheight = block.height;
    pitch = block.pitch;
    width = (width0 == 0.0) ? (double)iwidth : width0;
    height = (height0 == 0.0) ? (double)iheight : height0;

    /*
     * @format: the format of pixels in the buffer
     * @width: the width of the image to be stored in the buffer
     * @height: the eight of the image to be stored in the buffer
     * @stride: the number of bytes between the start of rows
     *   in the buffer. Having this be specified separate from @width
     *   allows for padding at the end of rows, or for writing
     *   to a subportion of a larger image.
     */

    /*
     * cairo_format_t
     * @CAIRO_FORMAT_ARGB32: each pixel is a 32-bit quantity, with
     *   alpha in the upper 8 bits, then red, then green, then blue.
     *   The 32-bit quantities are stored native-endian. Pre-multiplied
     *   alpha is used. (That is, 50% transparent red is 0x80800000,
     *   not 0x80ff0000.)
     */
    if(block.pixelSize == 4) {
        format = CAIRO_FORMAT_ARGB32;

        /*
         * The offset array contains the offsets from the address of a
         * pixel to the addresses of the bytes containing the red, green,
         * blue and alpha (transparency) components.
         *
         * We need to copy pixel data from the source using the photo offsets
         * to cairos ARGB format which is in *native* endian order; Switch!
         */
        srcR = block.offset[0];
        srcG = block.offset[1];
        srcB = block.offset[2];
        srcA = block.offset[3];
        dstR = 1;
        dstG = 2;
        dstB = 3;
        dstA = 0;
        if(!kEndianess.set) {
            kEndianess.set = 1;
        }
        if(kEndianess.little) {
            dstR = 3 - dstR, dstG = 3 - dstG, dstB = 3 - dstB, dstA = 3 - dstA;
        }

        data = (unsigned char *)ckalloc(pitch * iheight);
        ptr = data;

        if(tintColor && tintAmount > 0.0) {
#ifdef TINT_INT_CALCULATION
            /* calculate with integer arithmetic */
    uint32_t tintR, tintG, tintB, uAmount, uRemain;
            if(tintAmount > 1.0)
                tintAmount = 1.0;
            uAmount = (uint32_t) (tintAmount * 256.0);
            uRemain = 256 - uAmount;
            tintR = Red255FromXColorPtr(tintColor);
            tintG = Green255FromXColorPtr(tintColor);
            tintB = Blue255FromXColorPtr(tintColor);

            for(i = 0; i < iheight; i++) {
                srcPtr = block.pixelPtr + i * pitch;
                dstPtr = ptr + i * pitch;
                for(j = 0; j < iwidth; j++) {
                    /* extract */
    uint32_t r = *(srcPtr + srcR);
    uint32_t g = *(srcPtr + srcG);
    uint32_t b = *(srcPtr + srcB);
    uint32_t a = *(srcPtr + srcA);
                    /* transform */
    uint32_t lumAmount = ((r * 6966 + g * 23436 + b * 2366)
                        * uAmount) >> 23;       /* 0-256 */

                    r = (uRemain * r + lumAmount * tintR);
                    g = (uRemain * g + lumAmount * tintG);
                    b = (uRemain * b + lumAmount * tintB);

                    if(a != 255) {
                        /* Cairo expects RGB premultiplied by alpha */
                        r = r * a / 255;
                        g = g * a / 255;
                        b = b * a / 255;
                    }

                    /* fix range */
                    r = r > 0xFFFF ? 0xFFFF : r;
                    g = g > 0xFFFF ? 0xFFFF : g;
                    b = b > 0xFFFF ? 0xFFFF : b;

                    /* and put back */
                    *(dstPtr + dstR) = r >> 8;
                    *(dstPtr + dstG) = g >> 8;
                    *(dstPtr + dstB) = b >> 8;
                    *(dstPtr + dstA) = a;
                    srcPtr += 4;
                    dstPtr += 4;
                }
            }
#else
    double tintR, tintG, tintB;
            if(tintAmount > 1.0)
                tintAmount = 1.0;
            tintR = RedDoubleFromXColorPtr(tintColor);
            tintG = GreenDoubleFromXColorPtr(tintColor);
            tintB = BlueDoubleFromXColorPtr(tintColor);

            for(i = 0; i < iheight; i++) {
                srcPtr = block.pixelPtr + i * pitch;
                dstPtr = ptr + i * pitch;
                for(j = 0; j < iwidth; j++) {
                    /* extract */
    int r = *(srcPtr + srcR);
    int g = *(srcPtr + srcG);
    int b = *(srcPtr + srcB);
    int a = *(srcPtr + srcA);
                    /* transform */
    int lum = (int)(0.2126 * r + 0.7152 * g + 0.0722 * b);

                    r = (int)((1.0 - tintAmount) * r +
                        tintAmount * lum * tintR);
                    g = (int)((1.0 - tintAmount) * g +
                        tintAmount * lum * tintG);
                    b = (int)((1.0 - tintAmount) * b +
                        tintAmount * lum * tintB);

                    if(a != 255) {
                        /* Cairo expects RGB premultiplied by alpha */
                        r = r * a / 255;
                        g = g * a / 255;
                        b = b * a / 255;
                    }

                    /* fix range */
                    r = r < 0 ? 0 : r > 255 ? 255 : r;
                    g = g < 0 ? 0 : g > 255 ? 255 : g;
                    b = b < 0 ? 0 : b > 255 ? 255 : b;

                    /* and put back */
                    *(dstPtr + dstR) = r;
                    *(dstPtr + dstG) = g;
                    *(dstPtr + dstB) = b;
                    *(dstPtr + dstA) = a;
                    srcPtr += 4;
                    dstPtr += 4;
                }
            }
#endif
        } else {
            for(i = 0; i < iheight; i++) {
                srcPtr = block.pixelPtr + i * pitch;
                dstPtr = ptr + i * pitch;
                for(j = 0; j < iwidth; j++) {
    unsigned int alpha = *(srcPtr + srcA);
                    *(dstPtr + dstA) = alpha;
                    if(alpha == 255) {
                        *(dstPtr + dstR) = *(srcPtr + srcR);
                        *(dstPtr + dstG) = *(srcPtr + srcG);
                        *(dstPtr + dstB) = *(srcPtr + srcB);
                    } else {
                        /* Cairo expects RGB premultiplied by alpha */
                        *(dstPtr + dstR) = alpha * *(srcPtr + srcR) / 255;
                        *(dstPtr + dstG) = alpha * *(srcPtr + srcG) / 255;
                        *(dstPtr + dstB) = alpha * *(srcPtr + srcB) / 255;
                    }
                    srcPtr += 4;
                    dstPtr += 4;
                }
            }
        }
    } else if(block.pixelSize == 3) {
        /* Could do something about this? */
        fprintf(stderr,
            "TkPathImage: unaccepted pixel format: 1 pixel is 3 bytes\n");
        return;
    } else {
        fprintf(stderr,
            "TkPathImage: unaccepted pixel format: 1 pixel is %d bytes\n",
            block.pixelSize);
        return;
    }
    surface = cairo_image_surface_create_for_data(ptr, format, (int)iwidth, (int)iheight, pitch);       /* stride */

    filter = convertInterpolationToCairoFilter(interpolation);
    if(width == (double)iwidth && height == (double)iheight && !srcRegion) {
        cairo_set_source_surface(context->c, surface, x, y);
        cairo_pattern_set_filter(cairo_get_source(context->c), filter);
        cairo_paint_with_alpha(context->c, fillOpacity);
    } else if(srcRegion) {
        /* crop x0, y0 positions: */
    int xcrop = srcRegion->x1;
    int ycrop = srcRegion->y1;
    double xscale, yscale, xoffs, yoffs;
    cairo_matrix_t matrix;
    cairo_pattern_t *pattern;

        width = (width0 == 0.0) ? srcRegion->x2 - srcRegion->x1 : width0;
        height = (height0 == 0.0) ? srcRegion->y2 - srcRegion->y1 : height0;
        /* scale image: */
        xscale = width / (srcRegion->x2 - srcRegion->x1);
        yscale = height / (srcRegion->y2 - srcRegion->y1);
        xoffs = xcrop * xscale;
        yoffs = ycrop * yscale;

        pattern = cairo_pattern_create_for_surface(surface);
        cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);

        cairo_translate(context->c, (x - xoffs), (y - yoffs));

        cairo_matrix_init_scale(&matrix, 1.0 / xscale, 1.0 / yscale);
        cairo_pattern_set_matrix(pattern, &matrix);

        cairo_set_source(context->c, pattern);

        cairo_pattern_set_filter(cairo_get_source(context->c), filter);
        cairo_rectangle(context->c, xoffs, yoffs, width, height);
        cairo_fill(context->c);

        cairo_pattern_destroy(pattern);
    } else {
        cairo_save(context->c);
        cairo_translate(context->c, x, y);
        cairo_scale(context->c, width / iwidth, height / iheight);
        cairo_set_source_surface(context->c, surface, 0, 0);
        cairo_pattern_set_filter(cairo_get_source(context->c), filter);
        cairo_paint_with_alpha(context->c, fillOpacity);
        cairo_restore(context->c);
    }
    cairo_surface_destroy(surface);
    if(data) {
        ckfree((char *)data);
    }
}

void
TkPathClosePath(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_close_path(context->c);
}

int
TkPathTextConfig(
    Tcl_Interp * interp,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    void **customPtr)
{
    return TCL_OK;
}

static cairo_font_slant_t
convertTkFontSlant2CairoFontSlant(
    enum TkFontSlant slant)
{
    switch (slant) {
    case TK_PATH_TEXT_SLANT_NORMAL:
        return CAIRO_FONT_SLANT_NORMAL;
    case TK_PATH_TEXT_SLANT_ITALIC:
        return CAIRO_FONT_SLANT_ITALIC;
    case TK_PATH_TEXT_SLANT_OBLIQUE:
        return CAIRO_FONT_SLANT_OBLIQUE;
    }
    return CAIRO_FONT_SLANT_NORMAL;
}

static cairo_font_weight_t
convertTkFontWeight2CairoFontWeight(
    enum TkFontWeight weight)
{
    switch (weight) {
    case TK_PATH_TEXT_WEIGHT_NORMAL:
        return CAIRO_FONT_WEIGHT_NORMAL;
    case TK_PATH_TEXT_WEIGHT_BOLD:
        return CAIRO_FONT_WEIGHT_BOLD;
    }
    return CAIRO_FONT_WEIGHT_NORMAL;
}

static char *
ckstrdup(
    const char *str)
{
    unsigned len = strlen(str);
    char *newstr = ckalloc(len + 1);

    if(newstr != NULL) {
        strcpy(newstr, str);
    }
    return newstr;
}

static char *
linebreak(
    char *str,
    char **nextp)
{
    char *ret;

    if(str == NULL) {
        str = *nextp;
    }
    str += strspn(str, "\r\n");
    if(*str == '\0') {
        return NULL;
    }
    ret = str;
    str += strcspn(str, "\r\n");
    if(*str) {
    int ch = *str;

        *str++ = '\0';
        if((ch == '\r') && (*str == '\n')) {
            str++;
        }
    }
    *nextp = str;
    return ret;
}

static void
multiline_show_text(
    TkPathContext ctx,
    double x,
    double y,
    double dy,
    char *utf8)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    char *token, *savep;
    char *str = ckstrdup(utf8);

    for(token = linebreak(str, &savep); token;
        token = linebreak(NULL, &savep), y += dy) {
        cairo_move_to(context->c, x, y);
        cairo_show_text(context->c, token);
    }
    ckfree(str);
}

static void
multiline_text_path(
    TkPathContext ctx,
    double x,
    double y,
    double dy,
    char *utf8)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    char *token, *savep;
    char *str = ckstrdup(utf8);

    for(token = linebreak(str, &savep); token;
        token = linebreak(NULL, &savep), y += dy) {
        cairo_move_to(context->c, x, y);
        cairo_text_path(context->c, token);
    }
    ckfree(str);
}

void
TkPathTextDraw(
    TkPathContext ctx,
    Tk_PathStyle * style,
    Tk_PathTextStyle * textStylePtr,
    double x,
    double y,
    int fillOverStroke,
    char *utf8,
    void *custom)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_font_extents_t fontExtents;
    int hasStroke = (style->strokeColor != NULL);
    int hasFill = (GetColorFromPathColor(style->fill) != NULL);

    cairo_select_font_face(context->c, textStylePtr->fontFamily,
        convertTkFontSlant2CairoFontSlant(textStylePtr->fontSlant),
        convertTkFontWeight2CairoFontWeight(textStylePtr->fontWeight));
    cairo_set_font_size(context->c, textStylePtr->fontSize);
    cairo_font_extents(context->c, &fontExtents);

    if(hasStroke && hasFill) {
        multiline_text_path(ctx, x, y,
            fontExtents.ascent + fontExtents.descent, utf8);
        if(fillOverStroke) {
            TkPathPrepareForStroke(ctx, style);
            cairo_stroke_preserve(context->c);
            CairoSetFill(ctx, style);
            cairo_fill(context->c);
        } else {
            TkPathFillAndStroke(ctx, style);
        }
    } else if(hasFill) {
        CairoSetFill(ctx, style);
        multiline_show_text(ctx, x, y,
            fontExtents.ascent + fontExtents.descent, utf8);
    } else if(hasStroke) {
        multiline_text_path(ctx, x, y,
            fontExtents.ascent + fontExtents.descent, utf8);
        TkPathStroke(ctx, style);
    }
}

void
TkPathTextFree(
    Tk_PathTextStyle * textStylePtr,
    void *custom)
{
    /* Empty. */
}

TkPathRect
TkPathTextMeasureBbox(
    Display * display,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    double *lineSpacing,
    void *custom)
{
    cairo_t *c;
    cairo_surface_t *surface;
    cairo_text_extents_t extents;
    cairo_font_extents_t fontExtents;
    TkPathRect r;
    int lc;
    char *token, *savep;
    double x;
    char *str = ckstrdup(utf8);

    /*
     * @@@ Not very happy about this but it seems that there is no way to
     *     measure text without having a surface (drawable) in cairo.
     */
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 10, 10);
    c = cairo_create(surface);
    cairo_select_font_face(c, textStylePtr->fontFamily,
        convertTkFontSlant2CairoFontSlant(textStylePtr->fontSlant),
        convertTkFontWeight2CairoFontWeight(textStylePtr->fontWeight));
    cairo_set_font_size(c, textStylePtr->fontSize);

    cairo_font_extents(c, &fontExtents);

    r.x2 = 0.0;
    for(lc = 0, token = linebreak(str, &savep); token;
        lc++, token = linebreak(NULL, &savep)) {
        cairo_text_extents(c, token, &extents);
        x = extents.x_bearing + extents.width;
        if(x > r.x2)
            r.x2 = x;
    }
    r.y1 = -fontExtents.ascent;
    r.x1 = 0.0;
    r.y2 = lc * (fontExtents.ascent + fontExtents.descent) - fontExtents.ascent;

    if(lineSpacing != NULL) {
        *lineSpacing = fontExtents.ascent + fontExtents.descent;
    }

    cairo_destroy(c);
    cairo_surface_destroy(surface);
    ckfree(str);

    return r;
}

void
TkPathSurfaceErase(
    TkPathContext ctx,
    double dx,
    double dy,
    double dwidth,
    double dheight)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    unsigned char *data, *dst;
    int i;
    int x, y, width, height;
    int xend, yend;
    int stride;
    int bwidth;

    /*
     * Had to do it directly on the bits. Assuming CAIRO_FORMAT_ARGB32
     * cairos ARGB format is in *native* endian order; Switch!
     * Be careful not to address the bitmap outside its limits.
     */
    data = context->record->data;
    stride = context->record->stride;
    x = (int)(dx + 0.5);
    y = (int)(dy + 0.5);
    width = (int)(dwidth + 0.5);
    height = (int)(dheight + 0.5);
    x = MAX(0, MIN(context->record->width, x));
    y = MAX(0, MIN(context->record->height, y));
    width = MAX(0, width);
    height = MAX(0, height);
    xend = MIN(x + width, context->record->width);
    yend = MIN(y + height, context->record->height);
    bwidth = 4 * (xend - x);

    for(i = y; i < yend; i++) {
        dst = data + i * stride + 4 * x;
        memset(dst, '\0', bwidth);
    }
}

void
TkPathSurfaceToPhoto(
    Tcl_Interp * interp,
    TkPathContext ctx,
    Tk_PhotoHandle photo)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
cairo_surface_t *surface = context->surface;
Tk_PhotoImageBlock block;
unsigned char *data;
unsigned char *pixel;
int width, height;
int stride;                    /* Bytes per row. */

    width = cairo_image_surface_get_width(surface);
    height = cairo_image_surface_get_height(surface);
    data = context->record->data;
    stride = context->record->stride;

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *)attemptckalloc(height * stride);
    if(pixel == NULL) {
        return;
    }

    if(Tk_PathSurfaceCopyPremultiplyAlpha) {
        if(!kEndianess.set) {
            kEndianess.set = 1;
        }
        if(kEndianess.little) {
            TkPathCopyBitsPremultipliedAlphaBGRA(data, pixel, width, height,
                stride);
        } else {
            TkPathCopyBitsPremultipliedAlphaARGB(data, pixel, width, height,
                stride);
        }
    } else {
        if(!kEndianess.set) {
            kEndianess.set = 1;
        }
        if(kEndianess.little) {
            TkPathCopyBitsBGRA(data, pixel, width, height, stride);
        } else {
            TkPathCopyBitsARGB(data, pixel, width, height, stride);
        }
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = stride;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height,
        TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *)pixel);
}

void
TkPathClipToPath(
    TkPathContext ctx,
    int fillRule)
{
    /* Clipping to path is done by default. */
    /* Note: cairo_clip does not consume the current path */
    /* cairo_clip(context->c); */
}

void
TkPathReleaseClipToPath(
    TkPathContext ctx)
{
    /* cairo_reset_clip(context->c); */
}

static void
TkPathPrepareForStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
TkPathDash *dashPtr;

    /* Patch from Tim Edwards to handle color correctly on 64 bit arch. */
    cairo_set_source_rgba(context->c,
        (double)(style->strokeColor->red) / 0xFFFF,
        (double)(style->strokeColor->green) / 0xFFFF,
        (double)(style->strokeColor->blue) / 0xFFFF, style->strokeOpacity);
    cairo_set_line_width(context->c, style->strokeWidth);

    switch (style->capStyle) {
    case CapNotLast:
    case CapButt:
        cairo_set_line_cap(context->c, CAIRO_LINE_CAP_BUTT);
        break;
    case CapRound:
        cairo_set_line_cap(context->c, CAIRO_LINE_CAP_ROUND);
        break;
    default:
        cairo_set_line_cap(context->c, CAIRO_LINE_CAP_SQUARE);
        break;
    }
    switch (style->joinStyle) {
    case JoinMiter:
        cairo_set_line_join(context->c, CAIRO_LINE_JOIN_MITER);
        break;
    case JoinRound:
        cairo_set_line_join(context->c, CAIRO_LINE_JOIN_ROUND);
        break;
    default:
        cairo_set_line_join(context->c, CAIRO_LINE_JOIN_BEVEL);
        break;
    }
    cairo_set_miter_limit(context->c, style->miterLimit);

    dashPtr = style->dashPtr;
    if((dashPtr != NULL) && (dashPtr->number != 0)) {
int i;
double *dashes = (double *)ckalloc(dashPtr->number * sizeof(double));

        for(i = 0; i < dashPtr->number; i++) {
            dashes[i] = dashPtr->array[i] * style->strokeWidth;
        }
        cairo_set_dash(context->c, dashes, dashPtr->number, style->offset);
        ckfree((char *)dashes);
    }
}

void
TkPathStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    TkPathPrepareForStroke(ctx, style);
    cairo_stroke(context->c);
}

void
TkPathFill(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CairoSetFill(ctx, style);
    cairo_fill(context->c);
}

void
TkPathFillAndStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    CairoSetFill(ctx, style);
    cairo_fill_preserve(context->c);
    TkPathStroke(ctx, style);
}

void
TkPathEndPath(
    TkPathContext ctx)
{
    /* Empty ??? */
}

void
TkPathFree(
    TkPathContext ctx)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_destroy(context->c);
    cairo_surface_destroy(context->surface);
    if(context->record) {
        ckfree((char *)context->record->data);
        ckfree((char *)context->record);
    }
    ckfree((char *)context);
}

int
TkPathDrawingDestroysPath(
    void)
{
    return 1;
}

int
TkPathPixelAlign(
    void)
{
    return 0;
}

int
TkPathGetCurrentPosition(
    TkPathContext ctx,
    TkPathPoint * pt)
{
TkPathContext_ *context = (TkPathContext_ *) ctx;
    cairo_get_current_point(context->c, &(pt->x), &(pt->y));
    return TCL_OK;
}

int
TkPathBoundingBox(
    TkPathContext ctx,
    TkPathRect * rPtr)
{
    return TCL_ERROR;
}

static int
GetCairoExtend(
    int method)
{
    cairo_extend_t extend;

    switch (method) {
    case TK_PATH_GRADIENTMETHOD_Pad:
        extend = CAIRO_EXTEND_PAD;
        break;
    case TK_PATH_GRADIENTMETHOD_Repeat:
        extend = CAIRO_EXTEND_REPEAT;
        break;
    case TK_PATH_GRADIENTMETHOD_Reflect:
        extend = CAIRO_EXTEND_REFLECT;
        break;
    default:
        extend = CAIRO_EXTEND_NONE;
        break;
    }
    return extend;
}

void
TkPathPaintLinearGradient(
    TkPathContext ctx,
    TkPathRect * bbox,
    TkLinearGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    int i;
    int nstops;
    TkPathRect *tPtr;          /* The transition line. */
    TkGradientStop *stop;
    TkGradientStopArray *stopArrPtr;
    cairo_pattern_t *pattern;

    stopArrPtr = fillPtr->stopArrPtr;
    tPtr = fillPtr->transitionPtr;
    nstops = stopArrPtr->nstops;

    /*
     * The current path is consumed by filling.
     * Need therfore to save the current context and restore after.
     */
    cairo_save(context->c);

    pattern = cairo_pattern_create_linear(tPtr->x1, tPtr->y1,
        tPtr->x2, tPtr->y2);

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
        cairo_translate(context->c, bbox->x1, bbox->y1);
        cairo_scale(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    if(mPtr) {
    cairo_matrix_t matrix;
        cairo_matrix_init(&matrix, mPtr->a, mPtr->b, mPtr->c, mPtr->d,
            mPtr->tx, mPtr->ty);
        cairo_pattern_set_matrix(pattern, &matrix);
    }

    for(i = 0; i < nstops; i++) {
        stop = stopArrPtr->stops[i];
        cairo_pattern_add_color_stop_rgba(pattern, stop->offset,
            RedDoubleFromXColorPtr(stop->color),
            GreenDoubleFromXColorPtr(stop->color),
            BlueDoubleFromXColorPtr(stop->color), stop->opacity * fillOpacity);
    }
    cairo_set_source(context->c, pattern);
    cairo_set_fill_rule(context->c,
        (fillRule == WindingRule) ? CAIRO_FILL_RULE_WINDING :
        CAIRO_FILL_RULE_EVEN_ODD);
    cairo_pattern_set_extend(pattern, GetCairoExtend(fillPtr->method));
    cairo_fill(context->c);

    cairo_pattern_destroy(pattern);
    cairo_restore(context->c);
}

void
TkPathPaintRadialGradient(
    TkPathContext ctx,
    TkPathRect * bbox,
    TkRadialGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    TkPathContext_ *context = (TkPathContext_ *) ctx;
    int i;
    int nstops;
    TkGradientStop *stop;
    cairo_pattern_t *pattern;
    TkGradientStopArray *stopArrPtr;
    TkRadialTransition *tPtr;

    stopArrPtr = fillPtr->stopArrPtr;
    nstops = stopArrPtr->nstops;
    tPtr = fillPtr->radialPtr;

    /*
     * The current path is consumed by filling.
     * Need therfore to save the current context and restore after.
     */
    cairo_save(context->c);
    pattern = cairo_pattern_create_radial(tPtr->focalX, tPtr->focalY, 0.0,
        tPtr->centerX, tPtr->centerY, tPtr->radius);

    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
        cairo_translate(context->c, bbox->x1, bbox->y1);
        cairo_scale(context->c, bbox->x2 - bbox->x1, bbox->y2 - bbox->y1);
    }
    if(mPtr) {
    cairo_matrix_t matrix;
        cairo_matrix_init(&matrix, mPtr->a, mPtr->b, mPtr->c, mPtr->d,
            mPtr->tx, mPtr->ty);
        cairo_pattern_set_matrix(pattern, &matrix);
    }

    for(i = 0; i < nstops; i++) {
        stop = stopArrPtr->stops[i];
        cairo_pattern_add_color_stop_rgba(pattern, stop->offset,
            RedDoubleFromXColorPtr(stop->color),
            GreenDoubleFromXColorPtr(stop->color),
            BlueDoubleFromXColorPtr(stop->color), stop->opacity * fillOpacity);
    }
    cairo_set_source(context->c, pattern);
    cairo_set_fill_rule(context->c,
        (fillRule == WindingRule) ? CAIRO_FILL_RULE_WINDING :
        CAIRO_FILL_RULE_EVEN_ODD);
    cairo_pattern_set_extend(pattern, GetCairoExtend(fillPtr->method));
    cairo_fill(context->c);

    cairo_pattern_destroy(pattern);
    cairo_restore(context->c);
}

int
TkPathSetup(
    Tcl_Interp * interp)
{
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */
Added generic/tko/tkoPath_WinGDIPlus.cpp.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkWinGDIPlusPath.c --
 *
 *        This file implements path drawing API's on Windows using the GDI+ lib.
 *
 * Copyright (c) 2005-2008  Mats Bengtsson
 *
 */

#include "tkoPath.h"
#include "tkWinInt.h"

#include <windows.h>

// unknwn.h is needed to build with WIN32_LEAN_AND_MEAN
#include <unknwn.h>
#include <gdiplus.h>

using namespace Gdiplus;

extern "C" int Tk_PathAntiAlias;
extern "C" int Tk_PathSurfaceCopyPremultiplyAlpha;

#define MakeGDIPlusColor(xc, opacity) \
    Color(BYTE(opacity*255),          \
          BYTE((xc)->red >> 8),      \
          BYTE((xc)->green >> 8),     \
          BYTE((xc)->blue >> 8))

static TkLookupTable LineCapStyleLookupTable[] = {
    {CapNotLast, LineCapFlat},
    {CapButt, LineCapFlat},
    {CapRound, LineCapRound},
    {CapProjecting, LineCapSquare}
};

static TkLookupTable DashCapStyleLookupTable[] = {
    {CapNotLast, DashCapFlat},
    {CapButt, DashCapFlat},
    {CapRound, DashCapRound},
    {CapProjecting, DashCapRound}
};

static TkLookupTable LineJoinStyleLookupTable[] = {
    {JoinMiter, LineJoinMiter},
    {JoinRound, LineJoinRound},
    {JoinBevel, LineJoinBevel}
};

TCL_DECLARE_MUTEX(sGdiplusMutex)

    static int sGdiplusStarted;
    static ULONG_PTR sGdiplusToken;
    static GdiplusStartupOutput sGdiplusStartupOutput;
    static void PathExit(
    ClientData clientData);

/*
 * This class is a wrapper for path drawing using GDI+
 * It keeps storage for Graphics and GraphicsPath objects etc.
 */
    class PathC {

      public:
        PathC(
            HDC hdc);
        ~PathC(
        void);

    void PushTMatrix(
            TkPathMatrix * m);
    void ResetTMatrix(
            );
    void SaveState(
            );
    void RestoreState(
            );
    void BeginPath(
            Tk_PathStyle * style);
    void MoveTo(
        float x,
        float y);
    void LineTo(
        float x,
        float y);
    void CurveTo(
        float x1,
        float y1,
        float x2,
        float y2,
        float x,
        float y);
    void AddRectangle(
        float x,
        float y,
        float width,
        float height);
    void AddEllipse(
        float cx,
        float cy,
        float rx,
        float ry);
    void DrawImage(
            Tk_PhotoHandle photo,
        float x,
        float y,
        float width,
        float height,
        double fillOpacity,
        XColor * tintColor,
        double tintAmount,
        int interpolation,
        TkPathRect * srcRegion);
    void DrawString(
            Tk_PathStyle * style,
            Tk_PathTextStyle * textStylePtr,
        float x,
        float y,
        int fillOverStroke,
        char *utf8);
    void CloseFigure(
        void);
    void Stroke(
            Tk_PathStyle * style);
    void Fill(
            Tk_PathStyle * style);
    void FillAndStroke(
            Tk_PathStyle * style);
    void GetCurrentPoint(
            PointF * pt);
    void FillLinearGradient(
            TkPathRect * bbox,
            TkLinearGradientFill * fillPtr,
        int fillRule,
        double fillOpacity,
        TkPathMatrix * mPtr);
    void FillRadialGradient(
            TkPathRect * bbox,
            TkRadialGradientFill * fillPtr,
        int fillRule,
        double fillOpacity,
        TkPathMatrix * mPtr);
    void Flush(
            );

      private:
            HDC mMemHdc;
    PointF mOrigin;
    PointF mCurrentPoint;
    Graphics *mGraphics;
    GraphicsPath *mPath;
    GraphicsContainer mContainerStack[10];
    int mCointainerTop;

    static void PathInitPen(
            Tk_PathStyle * style,
            Pen * penPtr);
    };

    typedef struct PathSurfaceGDIpRecord {
    HBITMAP bitmap;
    void *data;
    int width;
    int height;
    int bytesPerRow;           /* the number of bytes between the start of
                                * rows in the buffer */
    } PathSurfaceGDIpRecord;

/*
 * This is used as a place holder for platform dependent stuff
 * between each call.
 */
    typedef struct TkPathContext_ {
    PathC *c;
    HDC memHdc;
    PathSurfaceGDIpRecord *surface;     /* NULL unless surface. */
    } TkPathContext_;

PathC::PathC(HDC hdc)
{
    mMemHdc = hdc;
    mGraphics = new Graphics(mMemHdc);
    mPath = new GraphicsPath(FillModeWinding);
    mCointainerTop = 0;
    if(Tk_PathAntiAlias) {
        mGraphics->SetSmoothingMode(SmoothingModeAntiAlias);
        mGraphics->SetTextRenderingHint(TextRenderingHintAntiAlias);
    }
    return;
}

inline PathC::~PathC(void)
{
    if(mPath) {
        mPath->Reset();
delete
    mPath;
    }
    if(mGraphics) {
delete
    mGraphics;
    }
}

inline void
    PathC::PathInitPen(
    Tk_PathStyle * style,
    Pen * penPtr)
{
LineCap
    cap;
DashCap
    dashCap;
LineJoin
    lineJoin;
TkPathDash *
    dashPtr;

    cap = static_cast < LineCap > (TkPathTableLookup(LineCapStyleLookupTable,
            4, style->capStyle));
    dashCap =
        static_cast < DashCap > (TkPathTableLookup(DashCapStyleLookupTable, 4,
            style->capStyle));
    penPtr->SetLineCap(cap, cap, dashCap);

    lineJoin =
        static_cast < LineJoin > (TkPathTableLookup(LineJoinStyleLookupTable, 3,
            style->joinStyle));
    penPtr->SetLineJoin(lineJoin);

    penPtr->SetMiterLimit((float)style->miterLimit);

    dashPtr = style->dashPtr;
    if((dashPtr != NULL) && (dashPtr->number != 0)) {
        penPtr->SetDashPattern(dashPtr->array, dashPtr->number);
        penPtr->SetDashOffset((float)style->offset);
    }
}

inline void
    PathC::PushTMatrix(
    TkPathMatrix * tm)
{
Matrix
m(
    float (tm->a),
    float (tm->b),
    float (tm->c),
    float (tm->d),
    float (tm->tx),
    float (tm->ty));
    mGraphics->MultiplyTransform(&m);
}

inline void
    PathC::ResetTMatrix(
    )
{
    mGraphics->ResetTransform();
}

inline void
    PathC::Flush(
    )
{
    mGraphics->Flush(FlushIntentionSync);
}

inline void
    PathC::SaveState(
    )
{
    if(mCointainerTop >= 9) {
        Tcl_Panic("reached top of cointainer stack of GDI+");
    }
    mContainerStack[mCointainerTop] = mGraphics->BeginContainer();
    mCointainerTop++;
    if(Tk_PathAntiAlias) {
        mGraphics->SetSmoothingMode(SmoothingModeAntiAlias);
        mGraphics->SetTextRenderingHint(TextRenderingHintAntiAlias);
    }
}

inline void
    PathC::RestoreState(
    )
{
    mCointainerTop--;
    mGraphics->EndContainer(mContainerStack[mCointainerTop]);
}

inline void
    PathC::BeginPath(
    Tk_PathStyle * style)
{
    mPath->Reset();
    mPath->SetFillMode((style->fillRule == WindingRule) ?
        FillModeWinding : FillModeAlternate);
}

inline void
    PathC::MoveTo(
    float x,
    float y)
{
    mPath->StartFigure();
    mOrigin.X = (float)x;
    mOrigin.Y = (float)y;
    mCurrentPoint.X = (float)x;
    mCurrentPoint.Y = (float)y;
}

inline void
    PathC::LineTo(
    float x,
    float y)
{
    mPath->AddLine(mCurrentPoint.X, mCurrentPoint.Y, x, y);
    mCurrentPoint.X = x;
    mCurrentPoint.Y = y;
}

inline void
    PathC::CurveTo(
    float x1,
    float y1,
    float x2,
    float y2,
    float x,
    float y)
{
    mPath->AddBezier(mCurrentPoint.X, mCurrentPoint.Y,  // startpoint
        x1, y1, x2, y2, // controlpoints
        x, y); // endpoint
    mCurrentPoint.X = x;
    mCurrentPoint.Y = y;
}

inline void
    PathC::AddRectangle(
    float x,
    float y,
    float width,
    float height)
{
    RectF
    rect(
        x,
        y,
        width,
        height);
    mPath->AddRectangle(rect);
    // @@@ TODO: this depends
    mCurrentPoint.X = x;
    mCurrentPoint.Y = y;
}

inline void
    PathC::AddEllipse(
    float cx,
    float cy,
    float rx,
    float ry)
{
    mPath->AddEllipse(cx - rx, cy - ry, 2 * rx, 2 * ry);
    // @@@ TODO: this depends
    mCurrentPoint.X = cx + rx;
    mCurrentPoint.Y = cy;
}

inline
    InterpolationMode
canvasInterpolationToGdiPlusInterpolation(
    int interpolation)
{
    switch (interpolation) {
    case TK_PATH_IMAGEINTERPOLATION_None:
        return InterpolationModeNearestNeighbor;
    case TK_PATH_IMAGEINTERPOLATION_Fast:
        return InterpolationModeBilinear;
    case TK_PATH_IMAGEINTERPOLATION_Best:
        return InterpolationModeHighQualityBicubic;
    default:
        return InterpolationModeBilinear;
    }
}

#define RedDoubleFromXColorPtr(xc) \
    (double) (((xc)->red >> 8) / 255.0)
#define GreenDoubleFromXColorPtr(xc) \
    (double) (((xc)->green >> 8) / 255.0)
#define BlueDoubleFromXColorPtr(xc) \
    (double) (((xc)->blue >> 8) / 255.0)

inline void
    PathC::DrawImage(
    Tk_PhotoHandle photo,
    float x,
    float y,
    float width,
    float height,
    double fillOpacity,
    XColor * tintColor,
    double tintAmount,
    int interpolation,
    TkPathRect * srcRegion)
{
    Tk_PhotoImageBlock
        block;
    PixelFormat
        format;
    INT
        stride;
    int
        iwidth,
        iheight;
    int
        pitch;
    int
        smallEndian = 1;       /* Hardcoded. */
    unsigned char *
        data = NULL;
    unsigned char *
        ptr = NULL;
    unsigned char *
    srcPtr, *
        dstPtr;
    int
        srcR,
        srcG,
        srcB,
        srcA;                  /* The source pixel offsets. */
    int
        dstR,
        dstG,
        dstB,
        dstA;                  /* The destination pixel offsets. */
    int
        i,
        j;
    double
        tintR,
        tintG,
        tintB;

    Tk_PhotoGetImage(photo, &block);
    iwidth = block.width;
    iheight = block.height;
    stride = block.pitch;
    pitch = block.pitch;

    int
        srcX = srcRegion ? (int)srcRegion->x1 : 0;
    int
        srcY = srcRegion ? (int)srcRegion->y1 : 0;
    int
        srcWidth = srcRegion ?
        ((int)srcRegion->x2 - (int)srcRegion->x1) : iwidth;
    int
        srcHeight = srcRegion ?
        ((int)srcRegion->y2 - (int)srcRegion->y1) : iheight;

    if(width == 0.0) {
        width = (float)srcWidth;
    }
    if(height == 0.0) {
        height = (float)srcHeight;
    }

    if(tintColor && tintAmount > 0.0) {
        if(tintAmount > 1.0) {
            tintAmount = 1.0;
        }
        tintR = RedDoubleFromXColorPtr(tintColor);
        tintG = GreenDoubleFromXColorPtr(tintColor);
        tintB = BlueDoubleFromXColorPtr(tintColor);
    } else {
        tintAmount = 0.0;
        tintR = 0.0;
        tintG = 0.0;
        tintB = 0.0;
    }

    if(block.pixelSize * 8 == 32) {
        format = PixelFormat32bppARGB;

        srcR = block.offset[0];
        srcG = block.offset[1];
        srcB = block.offset[2];
        srcA = block.offset[3];
        dstR = 1;
        dstG = 2;
        dstB = 3;
        dstA = 0;
        if(smallEndian) {
            dstR = 3 - dstR, dstG = 3 - dstG, dstB = 3 - dstB, dstA = 3 - dstA;
        }
        if((srcR == dstR) && (srcG == dstG) && (srcB == dstB) && (srcA == dstA)) {
            ptr = (unsigned char *)block.pixelPtr;
        } else {
            data = (unsigned char *)ckalloc(pitch * iheight);
            ptr = data;

            for(i = 0; i < iheight; i++) {
                srcPtr = block.pixelPtr + i * pitch;
                dstPtr = ptr + i * pitch;
                for(j = 0; j < iwidth; j++) {
                    *(dstPtr + dstR) = *(srcPtr + srcR);
                    *(dstPtr + dstG) = *(srcPtr + srcG);
                    *(dstPtr + dstB) = *(srcPtr + srcB);
                    *(dstPtr + dstA) = *(srcPtr + srcA);
                    srcPtr += 4;
                    dstPtr += 4;
                }
            }
        }
    } else if(block.pixelSize * 8 == 24) {
        /* Could do something about this? */
        return;
    } else {
        return;
    }

    ImageAttributes
        imageAttrs;
    imageAttrs.SetWrapMode(WrapModeTile);
    if(fillOpacity < 1.0 || tintAmount > 0.0) {
    ColorMatrix
        colorMatrix;
        /*
         * int lum = (int)(0.2126*r + 0.7152*g + 0.0722*b);
         * r = (int)((1.0-tintAmount + tintAmount*tintR*0.2126) * r
         *   + tintAmount*tintR*0.7152*g + tintAmount*tintR*0.0722*b));
         * g = (int)((1.0-tintAmount)*g + (tintAmount*tintG*0.2126*r
         *   + tintAmount*tintG*0.7152*g + tintAmount*tintG*0.0722*b));
         * b = (int)((1.0-tintAmount)*b + (tintAmount*tintB*0.2126*r
         *   + tintAmount*tintB*0.7152*g + tintAmount*tintB*0.0722*b));
         */
        colorMatrix.m[0][0] =
            (float)(1.0 - tintAmount + tintAmount * tintR * 0.2126);
        colorMatrix.m[0][1] = (float)(tintAmount * tintG * 0.2126);
        colorMatrix.m[0][2] = (float)(tintAmount * tintB * 0.2126);
        colorMatrix.m[0][3] = 0.0f;
        colorMatrix.m[0][4] = 0.0f;
        colorMatrix.m[1][0] = (float)(tintAmount * tintR * 0.7152);
        colorMatrix.m[1][1] =
            (float)(1.0 - tintAmount + tintAmount * tintG * 0.7152);
        colorMatrix.m[1][2] = (float)(tintAmount * tintB * 0.7152);
        colorMatrix.m[1][3] = 0.0f;
        colorMatrix.m[1][4] = 0.0f;
        colorMatrix.m[2][0] = (float)(tintAmount * tintR * 0.0722);
        colorMatrix.m[2][1] = (float)(tintAmount * tintG * 0.0722);
        colorMatrix.m[2][2] =
            (float)(1.0 - tintAmount + tintAmount * tintB * 0.0722);
        colorMatrix.m[2][3] = 0.0f;
        colorMatrix.m[2][4] = 0.0f;
        colorMatrix.m[3][0] = 0.0f;
        colorMatrix.m[3][1] = 0.0f;
        colorMatrix.m[3][2] = 0.0f;
        colorMatrix.m[3][3] = (float)fillOpacity;
        colorMatrix.m[3][4] = 0.0f;
        colorMatrix.m[4][0] = 0.0f;
        colorMatrix.m[4][1] = 0.0f;
        colorMatrix.m[4][2] = 0.0f;
        colorMatrix.m[4][3] = 0.0f;
        colorMatrix.m[4][4] = 1.0f;
        imageAttrs.SetColorMatrix(&colorMatrix, ColorMatrixFlagsDefault,
            ColorAdjustTypeBitmap);
    }
    mGraphics->
        SetInterpolationMode(canvasInterpolationToGdiPlusInterpolation
        (interpolation));
    Bitmap
    bitmap(
        iwidth,
        iheight,
        stride,
        format,
        (BYTE *) ptr);
    mGraphics->DrawImage(&bitmap, RectF(x, y, width, height),
        (float)srcX, (float)srcY, (float)srcWidth, (float)srcHeight, UnitPixel,
        &imageAttrs);

    if(data) {
        ckfree((char *)data);
    }
}

inline int
canvasTextStyle2GdiPlusTextStyle(
    Tk_PathTextStyle * textStylePtr)
{
int
    fontStyle = 0;
    switch (textStylePtr->fontSlant) {
    case TK_PATH_TEXT_SLANT_NORMAL:
        break;
    case TK_PATH_TEXT_SLANT_ITALIC:
        fontStyle |= FontStyleItalic;
        break;
    case TK_PATH_TEXT_SLANT_OBLIQUE:
        fontStyle |= FontStyleItalic;
        break;
        /* no FontStyleOblique in GDI+ */
    default:
        break;
    }
    switch (textStylePtr->fontWeight) {
    case TK_PATH_TEXT_WEIGHT_NORMAL:
        break;
    case TK_PATH_TEXT_WEIGHT_BOLD:
        fontStyle |= FontStyleBold;
        break;
    default:
        break;
    }
    return fontStyle;
}

static WCHAR *
toWCharDS(
    const char *utf8,
    Tcl_DString * ds)
{
    int
        length = strlen(utf8);
    const char *
        p = utf8;
    while(p < utf8 + length) {
    Tcl_UniChar
        ch;
    WCHAR
        wch;
    int
        next = Tcl_UtfToUniChar(p, &ch);
#if TCL_UTF_MAX >= 4
        if(ch > 0xffff) {
            wch = (((ch - 0x10000) >> 10) & 0x3ff) | 0xd800;
            ch = ((ch - 0x10000) & 0x3ff) | 0xdc00;
            Tcl_DStringAppend(ds, (const char *)&wch, sizeof(WCHAR));
        }
#endif
        if(ch == '\n') {
            /* accept */
        } else if(ch == '\r') {
            ch = '\n';
            if(p[next] == '\n') {
                next++;
            }
        } else if(ch == '\t') {
            /* two blanks */
            ch = ' ';
            wch = ch;
            Tcl_DStringAppend(ds, (const char *)&wch, sizeof(WCHAR));
        } else if((ch >= '\0') && (ch < ' ')) {
            goto skip;
        }
        wch = ch;
        Tcl_DStringAppend(ds, (const char *)&wch, sizeof(WCHAR));
      skip:
        p += next;
    }
    return (WCHAR *) Tcl_DStringValue(ds);
}

inline void
    PathC::DrawString(
    Tk_PathStyle * style,
    Tk_PathTextStyle * textStylePtr,
    float x,
    float y,
    int fillOverStroke,
    char *utf8)
{
    Tcl_DString
        ds,
        dsFont;
    WCHAR *
    wcPtr, *
        endPtr;
    float
        ascent,
        spacing;

    Tcl_DStringInit(&dsFont);
    FontFamily
    fontFamily(
        (const WCHAR *)
        Tcl_WinUtfToTChar(textStylePtr->fontFamily,
            -1,
            &dsFont));
    if(fontFamily.GetLastStatus() != Ok) {
        fontFamily.GenericSansSerif();
    }
    int
        fontStyle = canvasTextStyle2GdiPlusTextStyle(textStylePtr);
    Gdiplus::Font font(&fontFamily, (float)textStylePtr->fontSize,
        fontStyle, UnitPixel);
    if(font.GetLastStatus() != Ok) {
        // TODO
    }
    Tcl_DStringFree(&dsFont);
    Tcl_DStringInit(&ds);
    wcPtr = toWCharDS(utf8, &ds);
    endPtr = wcPtr + Tcl_DStringLength(&ds) / sizeof(WCHAR);
    ascent = font.GetSize() *
        fontFamily.GetCellAscent(fontStyle) / fontFamily.GetEmHeight(fontStyle);
    spacing = font.GetSize() *
        (fontFamily.GetCellAscent(fontStyle) +
        fontFamily.GetCellDescent(fontStyle)) /
        fontFamily.GetEmHeight(fontStyle);
    while(wcPtr < endPtr) {
    WCHAR *
        brkPtr = wcPtr;
        while(brkPtr < endPtr) {
            if(*brkPtr == '\n') {
                break;
            }
            ++brkPtr;
        }
        /*
         * The fourth argument is a PointF object that contains the
         * coordinates of the upper-left corner of the string.
         * See GDI+ docs and the FontFamily for translating between
         * design units and pixels.
         */
    PointF
    point(
            x,
            y - ascent);
        if(!fillOverStroke && GetColorFromPathColor(style->fill) != NULL &&
            style->strokeColor == NULL) {
    SolidBrush
    brush(
                MakeGDIPlusColor(GetColorFromPathColor(style->fill),
                    style->fillOpacity));
            mGraphics->DrawString(wcPtr, brkPtr - wcPtr, &font, point,
                StringFormat::GenericTypographic(), &brush);
        }
        if(style->strokeColor != NULL) {
            mPath->AddString(wcPtr, brkPtr - wcPtr, &fontFamily, fontStyle,
                (float)textStylePtr->fontSize, point,
                StringFormat::GenericTypographic());
            if(!fillOverStroke && GetColorFromPathColor(style->fill) != NULL) {
    SolidBrush
    brush(
                    MakeGDIPlusColor(GetColorFromPathColor(style->fill),
                        style->fillOpacity));
                mGraphics->FillPath(&brush, mPath);
            }
    Pen
    pen(
                MakeGDIPlusColor(style->strokeColor,
                    style->strokeOpacity),
                (float)style->strokeWidth);
            PathInitPen(style, &pen);
            mGraphics->DrawPath(&pen, mPath);
            if(fillOverStroke && GetColorFromPathColor(style->fill) != NULL) {
    SolidBrush
    brush(
                    MakeGDIPlusColor(GetColorFromPathColor(style->fill),
                        style->fillOpacity));
                mGraphics->FillPath(&brush, mPath);
            }
        }
        y += spacing;
        wcPtr = brkPtr + 1;
    }
    Tcl_DStringFree(&ds);
}

inline void
    PathC::CloseFigure(
    )
{
    mPath->CloseFigure();
    mCurrentPoint.X = mOrigin.X;
    mCurrentPoint.Y = mOrigin.Y;
}

inline void
    PathC::Stroke(
    Tk_PathStyle * style)
{
Pen
pen(
        MakeGDIPlusColor(style->strokeColor,
            style->strokeOpacity),
        (float)style->strokeWidth);
    PathInitPen(style, &pen);
    mGraphics->DrawPath(&pen, mPath);
}

inline void
    PathC::Fill(
    Tk_PathStyle * style)
{
SolidBrush
brush(
        MakeGDIPlusColor(GetColorFromPathColor(style->fill),
            style->fillOpacity));
    mGraphics->FillPath(&brush, mPath);
}

inline void
    PathC::FillAndStroke(
    Tk_PathStyle * style)
{
Pen
pen(
        MakeGDIPlusColor(style->strokeColor,
            style->strokeOpacity),
        (float)style->strokeWidth);
    PathInitPen(style, &pen);
SolidBrush
brush(
        MakeGDIPlusColor(GetColorFromPathColor(style->fill),
            style->fillOpacity));
    mGraphics->FillPath(&brush, mPath);
    mGraphics->DrawPath(&pen, mPath);
}

inline void
    PathC::GetCurrentPoint(
    PointF * pt)
{
    *pt = mCurrentPoint;
}

void
    PathC::FillLinearGradient(
    TkPathRect * bbox,
    TkLinearGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    int
        i;
    int
        nstops;
    float
        x,
        y,
        width,
        height;
    TkGradientStop *
        stop;
    TkGradientStopArray *
        stopArrPtr;
    TkPathRect *
        tPtr;
    PointF
        p1,
        p2,
        pstart,
        pend;

    /* Trim fillOpacity to [0,1] */
    if(fillOpacity < 0.0) {
        fillOpacity = 0.0;
    }
    if(fillOpacity > 1.0) {
        fillOpacity = 1.0;
    }

    stopArrPtr = fillPtr->stopArrPtr;
    nstops = stopArrPtr->nstops;
    tPtr = fillPtr->transitionPtr;

    GraphicsContainer
        container = mGraphics->BeginContainer();
    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
    x = float (
            bbox->x1);
    y = float (
            bbox->y1);
    width = float (
            bbox->x2 - bbox->x1);
    height = float (
            bbox->y2 - bbox->y1);
    p1.X = float (
            x + tPtr->x1 * width);
    p1.Y = float (
            y + tPtr->y1 * height);
    p2.X = float (
            x + tPtr->x2 * width);
    p2.Y = float (
            y + tPtr->y2 * height);
    } else {
    p1.X = float (
            tPtr->x1);
    p1.Y = float (
            tPtr->y1);
    p2.X = float (
            tPtr->x2);
    p2.Y = float (
            tPtr->y2);
    }
    stop = stopArrPtr->stops[0];
    Color
    col1(
        MakeGDIPlusColor(stop->color,
            stop->opacity * fillOpacity));
    stop = stopArrPtr->stops[nstops - 1];
    Color
    col2(
        MakeGDIPlusColor(stop->color,
            stop->opacity * fillOpacity));
    if(fillPtr->method == TK_PATH_GRADIENTMETHOD_Pad) {
        /*
         * GDI+ seems to miss a simple way to pad with constant colors.
         * NB: This trick assumes no -matrix!
         */
    float
        length = float (
            hypot(p1.X - p2.X, p1.Y - p2.Y));
    int
        singular = 0;
        if(length < 1e-6) {
            /*
             * @@@ p1 and p2 essentially coincide.
             *     Not sure what is the standard fallback here since
             *     we get no direction. Pick the x direction and make
             *     essentially a two color painting.
             */
            singular = 1;
        }
        /*
         * We need to put up two extra points that are outside
         * the bounding rectangle so that when used for gradient
         * start and stop points it will cover the bbox.
         */
    int
        npts = nstops + 2;
    Color *
        col = new Color[npts];
    REAL *
        pos = new REAL[npts];

        /*
         * We do the painting within a rectangle which is normally
         * the bounding box but if we do padding and have a gradient
         * transform we pick a "large enough" rectangle.
         */
    PointF
        corner[4];
        if(mPtr) {
            corner[0].X = 0.0f;
            corner[0].Y = 0.0f;
            corner[1].X = 10000.0f;
            corner[1].Y = 0.0f;
            corner[2].X = 10000.0f;
            corner[2].Y = 10000.0f;
            corner[3].X = 0.0f;
            corner[3].Y = 10000.0f;
        } else {
    corner[0].X = float (
                bbox->x1);
    corner[0].Y = float (
                bbox->y1);
    corner[1].X = float (
                bbox->x2);
    corner[1].Y = float (
                bbox->y1);
    corner[2].X = float (
                bbox->x2);
    corner[2].Y = float (
                bbox->y2);
    corner[3].X = float (
                bbox->x1);
    corner[3].Y = float (
                bbox->y2);
        }
        /* The normalized transition vector as pn */
    PointF
        pn;
        if(singular) {
            pn.X = 1;
            pn.Y = 0;
        } else {
            pn = p2 - p1;
            pn.X /= length;
            pn.Y /= length;
        }

        /*
         * To find the start point we need to find the minimum
         * projection of the vector corner_i - p1 along pn.
         * Only if this is negative we need to extend the start point from p1.
         */
    PointF
        ptmp;
    float
        min = 1e+6, max = -1e6;
    float
        dist;
        for(i = 0; i < 4; i++) {
            ptmp = corner[i] - p1;
            dist = ptmp.X * pn.X + ptmp.Y * pn.Y;
            if(dist < min) {
                min = dist;
            }
        }
        if(min < 0) {
            pstart.X = p1.X + min * pn.X;
            pstart.Y = p1.Y + min * pn.Y;
        } else {
            pstart = p1;
            min = 0;
        }

        /*
         * Do the same for the end point but use p2 instead
         * of p1 and find max.
         */
        for(i = 0; i < 4; i++) {
            ptmp = corner[i] - p2;
            dist = ptmp.X * pn.X + ptmp.Y * pn.Y;
            if(dist > max) {
                max = dist;
            }
        }
        if(max > 0) {
            pend.X = p2.X + max * pn.X;
            pend.Y = p2.Y + max * pn.Y;
        } else {
            pend = p2;
            max = 0;
        }
    LinearGradientBrush
    brush(
            pstart,
            pend,
            col1,
            col2);
        col[0] = col1;
        col[npts - 1] = col2;
        pos[0] = 0.0;
        pos[npts - 1] = 1.0;

        /*
         * Since we now have artificially extended the gradient transition
         * we also need to rescale the (relative) stops values using
         * this extended transition:
         *              |min| + offset * length
         * new offset = -----------------------
         *              |min| + length + |max|
         */

    float
        den = (float)fabs(min) + length + (float)fabs(max);
        for(i = 0; i < nstops; i++) {
            stop = stopArrPtr->stops[i];
            col[i + 1] = MakeGDIPlusColor(stop->color,
                stop->opacity * fillOpacity);
            pos[i + 1] = ((float)fabs(min) + REAL(stop->offset) * length) / den;
        }
        if(mPtr) {
            /* @@@ Not sure in which coord system we should do this. */
    Matrix
    m(
        float (mPtr->a),
        float (mPtr->b),
        float (mPtr->c),
        float (mPtr->d),
        float (mPtr->tx),
        float (mPtr->ty));
            brush.MultiplyTransform(&m);
        }
        brush.SetInterpolationColors(col, pos, npts);
        mGraphics->FillPath(&brush, mPath);
        delete[]col;
        delete[]pos;
    } else {
    LinearGradientBrush
    brush(
            p1,
            p2,
            col1,
            col2);
        if(fillPtr->method == TK_PATH_GRADIENTMETHOD_Reflect) {
            brush.SetWrapMode(WrapModeTileFlipXY);
        }
        if(mPtr) {
    Matrix
    m(
        float (mPtr->a),
        float (mPtr->b),
        float (mPtr->c),
        float (mPtr->d),
        float (mPtr->tx),
        float (mPtr->ty));
            brush.MultiplyTransform(&m);
        }
    Color *
        col = new Color[nstops];
    REAL *
        pos = new REAL[nstops];
        for(i = 0; i < nstops; i++) {
            stop = stopArrPtr->stops[i];
            col[i] = MakeGDIPlusColor(stop->color, stop->opacity * fillOpacity);
            pos[i] = REAL(stop->offset);
        }
        brush.SetInterpolationColors(col, pos, nstops);
        mGraphics->FillPath(&brush, mPath);
        delete[]col;
        delete[]pos;
    }
    mGraphics->EndContainer(container);
}

void
    PathC::FillRadialGradient(
    TkPathRect * bbox,         /* The items bbox box in untransformed coords. */
    TkRadialGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    int
        i;
    int
        nstops;
    float
        width,
        height;
    TkGradientStop *
        stop;
    TkGradientStopArray *
        stopArrPtr;
    TkRadialTransition *
        tPtr;
    PointF
        center,
        radius,
        focal;

    stopArrPtr = fillPtr->stopArrPtr;
    nstops = stopArrPtr->nstops;
    tPtr = fillPtr->radialPtr;

    /* Trim fillOpacity to [0,1] */
    if(fillOpacity < 0.0) {
        fillOpacity = 0.0;
    }
    if(fillOpacity > 1.0) {
        fillOpacity = 1.0;
    }

    /*
     * We need to do like this since this is how SVG defines gradient drawing
     * in case the transition vector is in relative coordinates.
     */
    width = float (
        bbox->x2 - bbox->x1);
    height = float (
        bbox->y2 - bbox->y1);
    if(fillPtr->units == TK_PATH_GRADIENTUNITS_BoundingBox) {
    center.X = float (
            bbox->x1 + width * tPtr->centerX);
    center.Y = float (
            bbox->y1 + height * tPtr->centerY);
    radius.X = float (
            width * tPtr->radius);
    radius.Y = float (
            height * tPtr->radius);
    focal.X = float (
            bbox->x1 + width * tPtr->focalX);
    focal.Y = float (
            bbox->y1 + height * tPtr->focalY);
    } else {
    center.X = float (
            tPtr->centerX);
    center.Y = float (
            tPtr->centerY);
    radius.X = float (
            tPtr->radius);
    radius.Y = float (
            tPtr->radius);
    focal.X = float (
            tPtr->focalX);
    focal.Y = float (
            tPtr->focalY);
    }
    GraphicsContainer
        container = mGraphics->BeginContainer();
    mGraphics->SetClip(mPath);
    // @@@ Extend the transition instead like we did for liner gradients above.
    stop = stopArrPtr->stops[nstops - 1];
    SolidBrush
    solidBrush(
        MakeGDIPlusColor(stop->color,
            stop->opacity * fillOpacity));
    mGraphics->FillPath(&solidBrush, mPath);

    /*
     * This is a special trick to make a radial gradient pattern.
     * Make an ellipse and use a PathGradientBrush.
     */
    GraphicsPath
        path;
    path.AddEllipse(center.X - radius.X, center.Y - radius.Y,
        2 * radius.X, 2 * radius.Y);
    PathGradientBrush
    brush(
        &path);
    if(mPtr) {
    Matrix
    m(
        float (mPtr->a),
        float (mPtr->b),
        float (mPtr->c),
        float (mPtr->d),
        float (mPtr->tx),
        float (mPtr->ty));
        brush.MultiplyTransform(&m);
    }
    stop = stopArrPtr->stops[0];
    brush.SetCenterColor(MakeGDIPlusColor(stop->color,
            stop->opacity * fillOpacity));
    brush.SetCenterPoint(focal);
    int
        count = 1;
    stop = stopArrPtr->stops[nstops - 1];
    Color
        color = MakeGDIPlusColor(stop->color,
        stop->opacity * fillOpacity);
    brush.SetSurroundColors(&color, &count);

    /* gdi+ counts them from the border and not from the center. */
    Color *
        col = new Color[nstops];
    REAL *
        pos = new REAL[nstops];
    for(i = nstops - 1; i >= 0; i--) {
        stop = stopArrPtr->stops[i];
        col[i] = MakeGDIPlusColor(stop->color, stop->opacity * fillOpacity);
        pos[i] = REAL(1.0 - stop->offset);
    }
    brush.SetInterpolationColors(col, pos, nstops);
    mGraphics->FillPath(&brush, &path);
    mGraphics->EndContainer(container);
    delete[]col;
    delete[]pos;
}

/*
 * Init procedure for Tcl.
 */

int
TkPathSetup(
    Tcl_Interp * interp)
{
    Tcl_MutexLock(&sGdiplusMutex);
    if(!sGdiplusStarted) {
GdiplusStartupInput
    gdiplusStartupInput;

        GdiplusStartup(&sGdiplusToken, &gdiplusStartupInput,
            &sGdiplusStartupOutput);
        Tcl_CreateExitHandler(PathExit, NULL);
        sGdiplusStarted = 1;
    }
    Tcl_MutexUnlock(&sGdiplusMutex);
    return TCL_OK;
}

/*
 * Exit procedure for Tcl.
 */

void
PathExit(
    ClientData clientData)
{
    if(sGdiplusStarted) {
        GdiplusShutdown(sGdiplusToken);
    }
}

/*
 * Standard tkpath interface.
 * More or less a wrapper for the class PathC.
 * Is there a smarter way?
 */

TkPathContext
TkPathInit(
    Tk_Window tkwin,
    Drawable d)
{
TkPathContext_ *
    context = reinterpret_cast < TkPathContext_ * >(ckalloc((unsigned)
            (sizeof(TkPathContext_))));
TkWinDrawable *
    twdPtr = (TkWinDrawable *) d;
HDC
    memHdc;
    //TkWinDrawable *twdPtr = reinterpret_cast<TkWinDrawable*>(d);
    /* from tile
     * TkWinDCState dcState;
     * HDC hdc = TkWinGetDrawableDC(Tk_Display(tkwin), d, &dcState);
     * ...
     * TkWinReleaseDrawableDC(d, hdc, &dcState);
     */

    /*
     * This will only work for bitmaps; need something else!
     * TkWinGetDrawableDC()?
     */
    memHdc = CreateCompatibleDC(NULL);
    SelectObject(memHdc, twdPtr->bitmap.handle);
    context->c = new PathC(memHdc);
    context->memHdc = memHdc;
    context->surface = NULL;
    return (TkPathContext) context;
}

TkPathContext
TkPathInitSurface(
    Display * display,
    int width,
    int height)
{
TkPathContext_ *
    context = reinterpret_cast < TkPathContext_ * >(ckalloc((unsigned)
            (sizeof(TkPathContext_))));
PathSurfaceGDIpRecord *
    surface = (PathSurfaceGDIpRecord *)
        ckalloc((unsigned)(sizeof(PathSurfaceGDIpRecord)));
HBITMAP
    hbm = NULL;
HDC
    memHdc = NULL;
BITMAPINFO *
    bmInfo = NULL;
void *
    data;

    memHdc = CreateCompatibleDC(NULL);

    /* We create off-screen surfaces as DIBs */
    bmInfo = (BITMAPINFO *) ckalloc(sizeof(BITMAPINFO));
    memset(bmInfo, 0, sizeof(BITMAPINFO));
    bmInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmInfo->bmiHeader.biWidth = width;
    bmInfo->bmiHeader.biHeight = -(int)height;
    bmInfo->bmiHeader.biPlanes = 1;
    bmInfo->bmiHeader.biBitCount = 32;
    bmInfo->bmiHeader.biCompression = BI_RGB;
    bmInfo->bmiHeader.biSizeImage = 0;
    bmInfo->bmiHeader.biXPelsPerMeter = static_cast < LONG > (72. / 0.0254);    /* unused here */
    bmInfo->bmiHeader.biYPelsPerMeter = static_cast < LONG > (72. / 0.0254);    /* unused here */
    bmInfo->bmiHeader.biClrUsed = 0;
    bmInfo->bmiHeader.biClrImportant = 0;

    hbm = CreateDIBSection(memHdc, bmInfo, DIB_RGB_COLORS, &data, NULL, 0);
    if(!hbm) {
        Tcl_Panic("CreateDIBSection");
    }
    SelectObject(memHdc, hbm);

    surface->bitmap = hbm;
    surface->width = width;
    surface->data = data;
    surface->width = width;
    surface->height = height;
    /* Windows bitmaps are padded to 16-bit (word) boundaries */
    surface->bytesPerRow = 4 * width;

    context->c = new PathC(memHdc);
    context->memHdc = memHdc;
    context->surface = surface;
    if(bmInfo) {
        ckfree((char *)bmInfo);
    }
    return (TkPathContext) context;
}

void
TkPathPushTMatrix(
    TkPathContext ctx,
    TkPathMatrix * m)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    if(m == NULL) {
        return;
    }
    context->c->PushTMatrix(m);
}

void
TkPathResetTMatrix(
    TkPathContext ctx)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->ResetTMatrix();
}

void
TkPathSaveState(
    TkPathContext ctx)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->SaveState();
}

void
TkPathRestoreState(
    TkPathContext ctx)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->RestoreState();
}

void
TkPathBeginPath(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->BeginPath(style);
}

void
TkPathMoveTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->MoveTo((float)x, (float)y);
}

void
TkPathLineTo(
    TkPathContext ctx,
    double x,
    double y)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->LineTo((float)x, (float)y);
}

void
TkPathLinesTo(
    TkPathContext ctx,
    double *pts,
    int n)
{
    /* @@@ TODO */
}

void
TkPathQuadBezier(
    TkPathContext ctx,
    double ctrlX,
    double ctrlY,
    double x,
    double y)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    double
        x31,
        y31,
        x32,
        y32;
    PointF
        cp;

    context->c->GetCurrentPoint(&cp);
    /*
     * Conversion of quadratic bezier curve to cubic bezier curve: (mozilla/svg)
     * Unchecked! Must be an approximation!
     */
    x31 = cp.X + (ctrlX - cp.X) * 2 / 3;
    y31 = cp.Y + (ctrlY - cp.Y) * 2 / 3;
    x32 = ctrlX + (x - ctrlX) / 3;
    y32 = ctrlY + (y - ctrlY) / 3;
    context->c->CurveTo((float)x31, (float)y31,
        (float)x32, (float)y32, (float)x, (float)y);
}

void
TkPathCurveTo(
    TkPathContext ctx,
    double ctrlX1,
    double ctrlY1,
    double ctrlX2,
    double ctrlY2,
    double x,
    double y)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->CurveTo((float)ctrlX1, (float)ctrlY1,
        (float)ctrlX2, (float)ctrlY2, (float)x, (float)y);
}

void
TkPathArcTo(
    TkPathContext ctx,
    double rx,
    double ry,
    double phiDegrees,         /* The rotation angle in degrees! */
    char largeArcFlag,
    char sweepFlag,
    double x,
    double y)
{
    TkPathArcToUsingBezier(ctx, rx, ry, phiDegrees, largeArcFlag,
        sweepFlag, x, y);
}

void
TkPathRectangle(
    TkPathContext ctx,
    double x,
    double y,
    double width,
    double height)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->AddRectangle((float)x, (float)y, (float)width, (float)height);
}

void
TkPathOval(
    TkPathContext ctx,
    double cx,
    double cy,
    double rx,
    double ry)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->AddEllipse((float)cx, (float)cy, (float)rx, (float)ry);
}

void
TkPathImage(
    TkPathContext ctx,
    Tk_Image image,
    Tk_PhotoHandle photo,
    double x,
    double y,
    double width,
    double height,
    double fillOpacity,
    XColor * tintColor,
    double tintAmount,
    int interpolation,
    TkPathRect * srcRegion)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->DrawImage(photo, (float)x, (float)y,
        (float)width, (float)height,
        fillOpacity, tintColor, tintAmount, interpolation, srcRegion);
}

void
TkPathClosePath(
    TkPathContext ctx)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->CloseFigure();
}

int
TkPathTextConfig(
    Tcl_Interp * interp,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    void **customPtr)
{
    /*
     * @@@ We could think of having the FontFamily and
     *     Gdiplus::Font cached in custom.
     */
    return TCL_OK;
}

void
TkPathTextDraw(
    TkPathContext ctx,
    Tk_PathStyle * style,
    Tk_PathTextStyle * textStylePtr,
    double x,
    double y,
    int fillOverStroke,
    char *utf8,
    void *custom)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->DrawString(style, textStylePtr, (float)x, (float)y,
        fillOverStroke, utf8);
}

void
TkPathTextFree(
    Tk_PathTextStyle * textStylePtr,
    void *custom)
{
    /* Empty. */
}

TkPathRect
TkPathTextMeasureBbox(
    Display * display,
    Tk_PathTextStyle * textStylePtr,
    char *utf8,
    double *lineSpacing,
    void *custom)
{
    HDC
        memHdc;
    Tcl_DString
        ds,
        dsFont;
    WCHAR *
    wcPtr, *
        endPtr;
    PointF
    origin(
        0.0f,
        0.0f);
    RectF
        bounds;
    TkPathRect
    r = { -1, -1, -1, -1 };
    float
        ascent,
        spacing;
    Graphics *
        graphics = NULL;

    memHdc = CreateCompatibleDC(NULL);
    /*
     * @@@ I thought this was needed but seems not.
     *     HBITMAP bm = CreateCompatibleBitmap(memHdc, 10, 10);
     *     SelectObject(memHdc, bm);
     */
    graphics = new Graphics(memHdc);
    if(Tk_PathAntiAlias) {
        graphics->SetSmoothingMode(SmoothingModeAntiAlias);
        graphics->SetTextRenderingHint(TextRenderingHintAntiAlias);
    }

    Tcl_DStringInit(&dsFont);
    FontFamily
    fontFamily(
        (const WCHAR *)
        Tcl_WinUtfToTChar(textStylePtr->fontFamily,
            -1,
            &dsFont));
    if(fontFamily.GetLastStatus() != Ok) {
        fontFamily.GenericSansSerif();
    }
    int
        fontStyle = canvasTextStyle2GdiPlusTextStyle(textStylePtr);
    Gdiplus::Font font(&fontFamily, (float)textStylePtr->fontSize,
        fontStyle, UnitPixel);
    if(font.GetLastStatus() != Ok) {
        // TODO
    }
    Tcl_DStringFree(&dsFont);
    Tcl_DStringInit(&ds);
    wcPtr = toWCharDS(utf8, &ds);
    endPtr = wcPtr + Tcl_DStringLength(&ds) / sizeof(WCHAR);
    ascent = font.GetSize() *
        fontFamily.GetCellAscent(fontStyle) / fontFamily.GetEmHeight(fontStyle);
    spacing = font.GetSize() *
        (fontFamily.GetCellAscent(fontStyle) +
        fontFamily.GetCellDescent(fontStyle)) /
        fontFamily.GetEmHeight(fontStyle);
    r.x1 = 0.0;
    r.x2 = 0.0;
    r.y1 = -ascent;
    r.y2 = 0.0;
    while(wcPtr < endPtr) {
    WCHAR *
        brkPtr = wcPtr;
        while(brkPtr < endPtr) {
            if(*brkPtr == '\n') {
                break;
            }
            ++brkPtr;
        }
        graphics->MeasureString(wcPtr, brkPtr - wcPtr, &font, origin,
            StringFormat::GenericTypographic(), &bounds);
        if(bounds.Width > r.x2) {
            r.x2 = bounds.Width;
        }
        r.y2 += spacing;
        wcPtr = brkPtr + 1;
    }
    r.y2 -= ascent;

    if(lineSpacing != NULL) {
        *lineSpacing = spacing;
    }

    Tcl_DStringFree(&ds);
    delete
        graphics;
    // DeleteObject(bm);
    DeleteDC(memHdc);
    return r;
}

void
TkPathSurfaceErase(
    TkPathContext ctx,
    double dx,
    double dy,
    double dwidth,
    double dheight)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    PathSurfaceGDIpRecord *
        surface = context->surface;
    unsigned char *
    data, *
        dst;
    int
        i;
    int
        x,
        y,
        width,
        height;
    int
        xend,
        yend;
    int
        bytesPerRow;
    int
        bwidth;

    width = surface->width;
    height = surface->height;
    data = (unsigned char *)surface->data;
    bytesPerRow = surface->bytesPerRow;

    x = (int)(dx + 0.5);
    y = (int)(dy + 0.5);
    width = (int)(dwidth + 0.5);
    height = (int)(dheight + 0.5);
    x = MAX(0, MIN(context->surface->width, x));
    y = MAX(0, MIN(context->surface->height, y));
    width = MAX(0, width);
    height = MAX(0, height);
    xend = MIN(x + width, context->surface->width);
    yend = MIN(y + height, context->surface->height);
    bwidth = 4 * (xend - x);

    for(i = y; i < yend; i++) {
        dst = data + i * bytesPerRow + 4 * x;
        memset(dst, '\0', bwidth);
    }
}

void
TkPathSurfaceToPhoto(
    Tcl_Interp * interp,
    TkPathContext ctx,
    Tk_PhotoHandle photo)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
PathSurfaceGDIpRecord *
    surface = context->surface;
Tk_PhotoImageBlock
    block;
unsigned char *
    data;
unsigned char *
    pixel;
int
    width,
    height;
int
    bytesPerRow;

    width = surface->width;
    height = surface->height;
    data = (unsigned char *)surface->data;
    bytesPerRow = surface->bytesPerRow;

    Tk_PhotoGetImage(photo, &block);
    pixel = (unsigned char *)attemptckalloc(height * bytesPerRow);
    if(Tk_PathSurfaceCopyPremultiplyAlpha) {
        TkPathCopyBitsPremultipliedAlphaBGRA(data, pixel, width, height,
            bytesPerRow);
    } else {
        TkPathCopyBitsBGRA(data, pixel, width, height, bytesPerRow);
    }
    block.pixelPtr = pixel;
    block.width = width;
    block.height = height;
    block.pitch = bytesPerRow;
    block.pixelSize = 4;
    block.offset[0] = 0;
    block.offset[1] = 1;
    block.offset[2] = 2;
    block.offset[3] = 3;
    Tk_PhotoPutBlock(interp, photo, &block, 0, 0, width, height,
        TK_PHOTO_COMPOSITE_OVERLAY);
    ckfree((char *)pixel);
}

void
TkPathEndPath(
    TkPathContext ctx)
{
    // @@@ empty ?
}

void
TkPathFree(
    TkPathContext ctx)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    DeleteDC(context->memHdc);
    if(context->surface) {
        DeleteObject(context->surface->bitmap);
        ckfree((char *)context->surface);
    }
delete
    context->
    c;
    ckfree((char *)context);
}

void
TkPathClipToPath(
    TkPathContext ctx,
    int fillRule)
{
    /* empty */
}

void
TkPathReleaseClipToPath(
    TkPathContext ctx)
{
    /* empty */
}

void
TkPathStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->Stroke(style);
}

void
TkPathFill(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->Fill(style);
}

void
TkPathFillAndStroke(
    TkPathContext ctx,
    Tk_PathStyle * style)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
    context->c->FillAndStroke(style);
}

int
TkPathGetCurrentPosition(
    TkPathContext ctx,
    TkPathPoint * ptPtr)
{
TkPathContext_ *
    context = (TkPathContext_ *) ctx;
PointF
    pf;
    context->c->GetCurrentPoint(&pf);
    ptPtr->x = (double)pf.X;
    ptPtr->y = (double)pf.Y;
    return TCL_OK;
}

int
TkPathDrawingDestroysPath(
    void)
{
    return 0;
}

int
TkPathPixelAlign(
    void)
{
    return 1;
}

/* @@@ INCOMPLETE! We need to consider any padding as well. */

void
TkPathPaintLinearGradient(
    TkPathContext ctx,
    TkPathRect * bbox,
    TkLinearGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->FillLinearGradient(bbox, fillPtr, fillRule, fillOpacity, mPtr);
}

void
TkPathPaintRadialGradient(
    TkPathContext ctx,
    TkPathRect * bbox,
    TkRadialGradientFill * fillPtr,
    int fillRule,
    double fillOpacity,
    TkPathMatrix * mPtr)
{
    TkPathContext_ *
        context = (TkPathContext_ *) ctx;
    context->c->FillRadialGradient(bbox, fillPtr, fillRule, fillOpacity, mPtr);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcBind.c.



































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcBind.c --
 *
 *      This module implements object binding procedures for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

/*
 * Binding table procedures.
 */
#define REPICK_IN_PROGRESS (1<<0)
#define LEFT_GRABBED_ITEM  (1<<1)

#define ALL_BUTTONS_MASK \
    (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)

#ifndef VirtualEventMask
#define VirtualEventMask    (1L << 30)
#endif

#define ALL_VALID_EVENTS_MASK \
    (ButtonMotionMask | Button1MotionMask | Button2MotionMask | \
     Button3MotionMask | Button4MotionMask | Button5MotionMask | \
     ButtonPressMask | ButtonReleaseMask | EnterWindowMask | \
     LeaveWindowMask | KeyPressMask | KeyReleaseMask | \
     PointerMotionMask | VirtualEventMask)

static int buttonMasks[] = {
    0,         /* No buttons pressed */
    Button1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask,
};

/*
* Prototypes for procedures referenced only in this file:
*/

static Tk_EventProc BindProc;
static void DoEvent(
    RbcBindTable * bindPtr,
    XEvent * eventPtr,
    ClientData item,
    ClientData context);
static void PickCurrentItem(
    RbcBindTable * bindPtr,
    XEvent * eventPtr);

/*
 * How to make drag&drop work?
 *
 *  Right now we generate pseudo <Enter> <Leave> events within
 *  button grab on an object.  They're marked NotifyVirtual instead
 *  of NotifyAncestor.  A better solution: generate new-style
 *  virtual <<DragEnter>> <<DragMotion>> <<DragLeave>> events.
 *  These virtual events don't have to exist as "real" event
 *  sequences, like virtual events do now.
 */

/*
 *--------------------------------------------------------------
 *
 * DoEvent --
 *
 *      This procedure is called to invoke binding processing
 *      for a new event that is associated with the current item
 *      for a legend.
 *
 *      Sets the binding tags for a graph object. This routine is
 *      called by Tk when an event occurs in the graph.  It fills
 *      an array of pointers with bind tag addresses.
 *
 *      The object addresses are strings hashed in one of two tag
 *      tables: one for elements and the another for markers.  Note
 *      that there's only one binding table for elements and markers.
 *      [We don't want to trigger both a marker and element bind
 *      command for the same event.]  But we don't want a marker and
 *      element with the same tag name to activate the others
 *      bindings. A tag "all" for markers should mean all markers, not
 *      all markers and elements.  As a result, element and marker
 *      tags are stored in separate hash tables, which means we can't
 *      generate the same tag address for both an elements and marker,
 *      even if they have the same name.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Depends on the bindings for the legend.  A binding script
 *      could delete an entry, so callers should protect themselves
 *      with Tcl_Preserve and Tcl_Release.
 *
 *--------------------------------------------------------------
 */
static void
DoEvent(
    RbcBindTable * bindPtr,    /* Binding information for widget in
                                * which event occurred. */
    XEvent * eventPtr,         /* Real or simulated X event that
                                * is to be processed. */
    ClientData item,           /* Item picked. */
    ClientData context)
{              /* Context of item.  */
RbcElement *elemPtr;
MakeTagProc *tagProc;
RbcGraph *graphPtr;
ClientData *idArray;
ClientData tags[32];
int nIds = 2;                  /* Always add the name of the object to the tag array. */
register char **p;

    if((bindPtr->tkwin == NULL) || (bindPtr->bindingTable == NULL)) {
        return;
    }
    if((eventPtr->type == KeyPress) || (eventPtr->type == KeyRelease)) {
        item = bindPtr->focusItem;
        context = bindPtr->focusContext;
    }
    if(item == NULL) {
        return;
    }

    /*
     * Invoke the binding system.
     */
    graphPtr = (RbcGraph *) RbcGetBindingData(bindPtr);
    /*
     * Trick:   Markers, elements, and axes have the same first few
     *          fields in their structures, such as "type", "name", or
     *          "tags".  This is so we can look at graph objects
     *          interchangably.  It doesn't matter what we cast the
     *          object to.
     */
    elemPtr = (RbcElement *) item;

    if((elemPtr->classUid == rbcLineElementUid)
        || (elemPtr->classUid == rbcStripElementUid)
        || (elemPtr->classUid == rbcBarElementUid)) {
        tagProc = RbcMakeElementTag;
    } else if((elemPtr->classUid == rbcXAxisUid)
        || (elemPtr->classUid == rbcYAxisUid)) {
        tagProc = RbcMakeAxisTag;
    } else {
        tagProc = RbcMakeMarkerTag;
    }

    if(elemPtr->tags != NULL) {
        for(p = elemPtr->tags; *p != NULL; p++) {
            nIds++;
        }
    }
    if(nIds > 32) {
        idArray = (ClientData *) ckalloc(sizeof(ClientData) * nIds);
    } else {
        idArray = tags;
    }
    idArray[0] = (ClientData) (*tagProc) (graphPtr, elemPtr->name);
    idArray[1] = (ClientData) (*tagProc) (graphPtr, elemPtr->classUid);
    if(nIds > 2) {
        for(p = elemPtr->tags; *p != NULL; p++) {
            idArray[nIds++] = (ClientData) (*tagProc) (graphPtr, *p);
        }
    }
    Tk_BindEvent(bindPtr->bindingTable, eventPtr, bindPtr->tkwin, nIds,
        idArray);
    if(nIds >= 32) {
        ckfree((char *)idArray);
    }

}

/*
 *--------------------------------------------------------------
 *
 * PickCurrentItem --
 *
 *      Find the topmost item in a legend that contains a given
 *      location and mark the the current item.  If the current
 *      item has changed, generate a fake exit event on the old
 *      current item and a fake enter event on the new current
 *      item.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The current item may change.  If it does, then the commands
 *      associated with item entry and exit could do just about
 *      anything.  A binding script could delete the legend, so
 *      callers should protect themselves with Tcl_Preserve and
 *      Tcl_Release.
 *
 *--------------------------------------------------------------
 */
static void
PickCurrentItem(
    RbcBindTable * bindPtr,    /* Binding table information. */
    XEvent * eventPtr)
{              /* Event describing location of
                * mouse cursor.  Must be EnterWindow,
                * LeaveWindow, ButtonRelease, or
                * MotionNotify. */
int buttonDown;
ClientData newItem;
ClientData newContext;

    /*
     * Check whether or not a button is down.  If so, we'll log entry
     * and exit into and out of the current item, but not entry into
     * any other item.  This implements a form of grabbing equivalent
     * to what the X server does for windows.
     */
    buttonDown = (bindPtr->state & ALL_BUTTONS_MASK);
    if(!buttonDown) {
        bindPtr->flags &= ~LEFT_GRABBED_ITEM;
    }

    /*
     * Save information about this event in the widget.  The event in
     * the widget is used for two purposes:
     *
     * 1. Event bindings: if the current item changes, fake events are
     *    generated to allow item-enter and item-leave bindings to trigger.
     * 2. Reselection: if the current item gets deleted, can use the
     *    saved event to find a new current item.
     * Translate MotionNotify events into EnterNotify events, since that's
     * what gets reported to item handlers.
     */

    if(eventPtr != &bindPtr->pickEvent) {
        if((eventPtr->type == MotionNotify)
            || (eventPtr->type == ButtonRelease)) {
            bindPtr->pickEvent.xcrossing.type = EnterNotify;
            bindPtr->pickEvent.xcrossing.serial = eventPtr->xmotion.serial;
            bindPtr->pickEvent.xcrossing.send_event =
                eventPtr->xmotion.send_event;
            bindPtr->pickEvent.xcrossing.display = eventPtr->xmotion.display;
            bindPtr->pickEvent.xcrossing.window = eventPtr->xmotion.window;
            bindPtr->pickEvent.xcrossing.root = eventPtr->xmotion.root;
            bindPtr->pickEvent.xcrossing.subwindow = None;
            bindPtr->pickEvent.xcrossing.time = eventPtr->xmotion.time;
            bindPtr->pickEvent.xcrossing.x = eventPtr->xmotion.x;
            bindPtr->pickEvent.xcrossing.y = eventPtr->xmotion.y;
            bindPtr->pickEvent.xcrossing.x_root = eventPtr->xmotion.x_root;
            bindPtr->pickEvent.xcrossing.y_root = eventPtr->xmotion.y_root;
            bindPtr->pickEvent.xcrossing.mode = NotifyNormal;
            bindPtr->pickEvent.xcrossing.detail = NotifyNonlinear;
            bindPtr->pickEvent.xcrossing.same_screen =
                eventPtr->xmotion.same_screen;
            bindPtr->pickEvent.xcrossing.focus = False;
            bindPtr->pickEvent.xcrossing.state = eventPtr->xmotion.state;
        } else {
            bindPtr->pickEvent = *eventPtr;
        }
    }
    bindPtr->activePick = TRUE;

    /*
     * If this is a recursive call (there's already a partially completed
     * call pending on the stack;  it's in the middle of processing a
     * Leave event handler for the old current item) then just return;
     * the pending call will do everything that's needed.
     */
    if(bindPtr->flags & REPICK_IN_PROGRESS) {
        return;
    }

    /*
     * A LeaveNotify event automatically means that there's no current
     * item, so the check for closest item can be skipped.
     */
    newContext = NULL;
    if(bindPtr->pickEvent.type != LeaveNotify) {
int x, y;

        x = bindPtr->pickEvent.xcrossing.x;
        y = bindPtr->pickEvent.xcrossing.y;
        newItem = (*bindPtr->pickProc) (bindPtr->clientData, x, y, &newContext);
    } else {
        newItem = NULL;
    }

    if(((newItem == bindPtr->currentItem)
            && (newContext == bindPtr->currentContext))
        && (!(bindPtr->flags & LEFT_GRABBED_ITEM))) {
        /*
         * Nothing to do:  the current item hasn't changed.
         */
        return;
    }
#ifndef FULLY_SIMULATE_GRAB
    if(((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext)) && (buttonDown)) {
        bindPtr->flags |= LEFT_GRABBED_ITEM;
        return;
    }
#endif
    /*
     * Simulate a LeaveNotify event on the previous current item and
     * an EnterNotify event on the new current item.  Remove the "current"
     * tag from the previous current item and place it on the new current
     * item.
     */
    if((bindPtr->currentItem != NULL) && ((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext))
        && !(bindPtr->flags & LEFT_GRABBED_ITEM)) {
XEvent event;

        event = bindPtr->pickEvent;
        event.type = LeaveNotify;

        /*
         * If the event's detail happens to be NotifyInferior the
         * binding mechanism will discard the event.  To be consistent,
         * always use NotifyAncestor.
         */
        event.xcrossing.detail = NotifyAncestor;

        bindPtr->flags |= REPICK_IN_PROGRESS;
        DoEvent(bindPtr, &event, bindPtr->currentItem, bindPtr->currentContext);
        bindPtr->flags &= ~REPICK_IN_PROGRESS;

        /*
         * Note:  during DoEvent above, it's possible that
         * bindPtr->newItem got reset to NULL because the
         * item was deleted.
         */
    }
    if(((newItem != bindPtr->currentItem)
            || (newContext != bindPtr->currentContext)) && (buttonDown)) {
XEvent event;

        bindPtr->flags |= LEFT_GRABBED_ITEM;
        event = bindPtr->pickEvent;
        if((newItem != bindPtr->newItem)
            || (newContext != bindPtr->newContext)) {
ClientData savedItem;
ClientData savedContext;

            /*
             * Generate <Enter> and <Leave> events for objects during
             * button grabs.  This isn't standard. But for example, it
             * allows one to provide balloon help on the individual
             * entries of the Hierbox widget.
             */
            savedItem = bindPtr->currentItem;
            savedContext = bindPtr->currentContext;
            if(bindPtr->newItem != NULL) {
                event.type = LeaveNotify;
                event.xcrossing.detail = NotifyVirtual /* Ancestor */ ;
                bindPtr->currentItem = bindPtr->newItem;
                DoEvent(bindPtr, &event, bindPtr->newItem, bindPtr->newContext);
            }
            bindPtr->newItem = newItem;
            bindPtr->newContext = newContext;
            if(newItem != NULL) {
                event.type = EnterNotify;
                event.xcrossing.detail = NotifyVirtual /* Ancestor */ ;
                bindPtr->currentItem = newItem;
                DoEvent(bindPtr, &event, newItem, newContext);
            }
            bindPtr->currentItem = savedItem;
            bindPtr->currentContext = savedContext;
        }
        return;
    }
    /*
     * Special note:  it's possible that
     *   bindPtr->newItem == bindPtr->currentItem
     * here.  This can happen, for example, if LEFT_GRABBED_ITEM was set.
     */

    bindPtr->flags &= ~LEFT_GRABBED_ITEM;
    bindPtr->currentItem = bindPtr->newItem = newItem;
    bindPtr->currentContext = bindPtr->newContext = newContext;
    if(bindPtr->currentItem != NULL) {
XEvent event;

        event = bindPtr->pickEvent;
        event.type = EnterNotify;
        event.xcrossing.detail = NotifyAncestor;
        DoEvent(bindPtr, &event, newItem, newContext);
    }
}

/*
 *--------------------------------------------------------------
 *
 * BindProc --
 *
 *      This procedure is invoked by the Tk dispatcher to handle
 *      events associated with bindings on items.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Depends on the command invoked as part of the binding
 *      (if there was any).
 *
 *--------------------------------------------------------------
 */
static void
BindProc(
    ClientData clientData,     /* Pointer to widget structure. */
    XEvent * eventPtr)
{              /* Pointer to X event that just
                * happened. */
RbcBindTable *bindPtr = clientData;
int mask;

    Tcl_Preserve(bindPtr->clientData);

    /*
     * This code below keeps track of the current modifier state in
     * bindPtr->state.  This information is used to defer repicks of
     * the current item while buttons are down.
     */
    switch (eventPtr->type) {
    case ButtonPress:
    case ButtonRelease:
        mask = 0;
        if((eventPtr->xbutton.button >= Button1)
            && (eventPtr->xbutton.button <= Button5)) {
            mask = buttonMasks[eventPtr->xbutton.button];
        }

        /*
         * For button press events, repick the current item using the
         * button state before the event, then process the event.  For
         * button release events, first process the event, then repick
         * the current item using the button state *after* the event
         * (the button has logically gone up before we change the
         * current item).
         */
        if(eventPtr->type == ButtonPress) {
            /*
             * On a button press, first repick the current item using
             * the button state before the event, the process the event.
             */
            bindPtr->state = eventPtr->xbutton.state;
            PickCurrentItem(bindPtr, eventPtr);
            bindPtr->state ^= mask;
            DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
                bindPtr->currentContext);
        } else {
            /*
             * Button release: first process the event, with the button
             * still considered to be down.  Then repick the current
             * item under the assumption that the button is no longer down.
             */
            bindPtr->state = eventPtr->xbutton.state;
            DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
                bindPtr->currentContext);
            eventPtr->xbutton.state ^= mask;
            bindPtr->state = eventPtr->xbutton.state;
            PickCurrentItem(bindPtr, eventPtr);
            eventPtr->xbutton.state ^= mask;
        }
        break;

    case EnterNotify:
    case LeaveNotify:
        bindPtr->state = eventPtr->xcrossing.state;
        PickCurrentItem(bindPtr, eventPtr);
        break;

    case MotionNotify:
        bindPtr->state = eventPtr->xmotion.state;
        PickCurrentItem(bindPtr, eventPtr);
        DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
            bindPtr->currentContext);
        break;

    case KeyPress:
    case KeyRelease:
        bindPtr->state = eventPtr->xkey.state;
        PickCurrentItem(bindPtr, eventPtr);
        DoEvent(bindPtr, eventPtr, bindPtr->currentItem,
            bindPtr->currentContext);
        break;
    }
    Tcl_Release(bindPtr->clientData);
}

/*
 *--------------------------------------------------------------
 *
 * RbcConfigureBindings --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcConfigureBindings(
    Tcl_Interp * interp,
    RbcBindTable * bindPtr,
    ClientData item,
    int argc,
    const char **argv)
{
    const char *command;
    unsigned long mask;
    const char *seq;

    if(argc == 0) {
        Tk_GetAllBindings(interp, bindPtr->bindingTable, item);
        return TCL_OK;
    }
    if(argc == 1) {
        command = Tk_GetBinding(interp, bindPtr->bindingTable, item, argv[0]);
        if(command == NULL) {
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewStringObj(command, -1));
        return TCL_OK;
    }

    seq = argv[0];
    command = argv[1];

    if(command[0] == '\0') {
        return Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
    }

    if(command[0] == '+') {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq,
            command + 1, TRUE);
    } else {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq, command,
            FALSE);
    }
    if(mask == 0) {
        return TCL_ERROR;
    }
    if(mask & (unsigned)~ALL_VALID_EVENTS_MASK) {
        Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
        Tcl_ResetResult(interp);
        Tcl_AppendResult(interp, "requested illegal events; ",
            "only key, button, motion, enter, leave, and virtual ",
            "events may be used", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}

#if (TCL_MAJOR_VERSION >= 8)

/*
 *--------------------------------------------------------------
 *
 * RbcConfigureBindingsFromObj --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcConfigureBindingsFromObj(
    Tcl_Interp * interp,
    RbcBindTable * bindPtr,
    ClientData item,
    int objc,
    Tcl_Obj * const *objv)
{
    const char *command;
    unsigned long mask;
    char *seq;
    char *string;

    if(objc == 0) {
        Tk_GetAllBindings(interp, bindPtr->bindingTable, item);
        return TCL_OK;
    }
    string = Tcl_GetString(objv[0]);
    if(objc == 1) {
        command = Tk_GetBinding(interp, bindPtr->bindingTable, item, string);
        if(command == NULL) {
            Tcl_ResetResult(interp);
            Tcl_AppendResult(interp, "invalid binding event \"", string, "\"",
                (char *)NULL);
            return TCL_ERROR;
        }
        Tcl_SetObjResult(interp, Tcl_NewStringObj(command, -1));
        return TCL_OK;
    }

    seq = string;
    command = Tcl_GetString(objv[1]);

    if(command[0] == '\0') {
        return Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
    }

    if(command[0] == '+') {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq,
            command + 1, TRUE);
    } else {
        mask =
            Tk_CreateBinding(interp, bindPtr->bindingTable, item, seq, command,
            FALSE);
    }
    if(mask == 0) {
        return TCL_ERROR;
    }
    if(mask & (unsigned)~ALL_VALID_EVENTS_MASK) {
        Tk_DeleteBinding(interp, bindPtr->bindingTable, item, seq);
        Tcl_ResetResult(interp);
        Tcl_AppendResult(interp, "requested illegal events; ",
            "only key, button, motion, enter, leave, and virtual ",
            "events may be used", (char *)NULL);
        return TCL_ERROR;
    }
    return TCL_OK;
}
#endif

/*
 *--------------------------------------------------------------
 *
 * RbcCreateBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcBindTable *
RbcCreateBindingTable(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    ClientData clientData,
    RbcBindPickProc * pickProc)
{
unsigned int mask;
RbcBindTable *bindPtr;

    bindPtr = RbcCalloc(1, sizeof(RbcBindTable));
    assert(bindPtr);
    bindPtr->clientData = clientData;
    bindPtr->pickProc = pickProc;
    bindPtr->tkwin = tkwin;
    bindPtr->bindingTable = Tk_CreateBindingTable(interp);
    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    Tk_CreateEventHandler(tkwin, mask, BindProc, bindPtr);
    return bindPtr;
}

/*
 *--------------------------------------------------------------
 *
 * RbcDestroyBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDestroyBindingTable(
    RbcBindTable * bindPtr)
{
unsigned int mask;

    Tk_DeleteBindingTable(bindPtr->bindingTable);
    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    Tk_DeleteEventHandler(bindPtr->tkwin, mask, BindProc, bindPtr);
    ckfree((char *)bindPtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcPickCurrentItem --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcPickCurrentItem(
    RbcBindTable * bindPtr)
{
    if(bindPtr->activePick) {
        PickCurrentItem(bindPtr, &(bindPtr->pickEvent));
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcDeleteBindings --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDeleteBindings(
    RbcBindTable * bindPtr,
    ClientData object)
{
    Tk_DeleteAllBindings(bindPtr->bindingTable, object);

    /*
     * If this is the object currently picked, we need to repick one.
     */
    if(bindPtr->currentItem == object) {
        bindPtr->currentItem = NULL;
        bindPtr->currentContext = NULL;
    }
    if(bindPtr->newItem == object) {
        bindPtr->newItem = NULL;
        bindPtr->newContext = NULL;
    }
    if(bindPtr->focusItem == object) {
        bindPtr->focusItem = NULL;
        bindPtr->focusContext = NULL;
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcMoveBindingTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcMoveBindingTable(
    RbcBindTable * bindPtr,
    Tk_Window tkwin)
{
unsigned int mask;

    mask =
        (KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
        EnterWindowMask | LeaveWindowMask | PointerMotionMask);
    if(bindPtr->tkwin != NULL) {
        Tk_DeleteEventHandler(bindPtr->tkwin, mask, BindProc, bindPtr);
    }
    Tk_CreateEventHandler(tkwin, mask, BindProc, bindPtr);
    bindPtr->tkwin = tkwin;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcChain.c.

























































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcChain.c --
 *
 * The module implements a generic linked list package.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#ifndef ALIGN
#define ALIGN(a) \
    (((size_t)a + (sizeof(double) - 1)) & (~(sizeof(double) - 1)))
#endif /* ALIGN */

/*
 *----------------------------------------------------------------------
 *
 * RbcChainCreate --
 *
 *      Creates a new linked list (chain) structure and initializes
 *      its pointers;
 *
 * Results:
 *      Returns a pointer to the newly created chain structure.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChain *
RbcChainCreate(
    )
{
RbcChain *chainPtr;

    chainPtr = (RbcChain *) ckalloc(sizeof(RbcChain));
    if(chainPtr != NULL) {
        RbcChainInit(chainPtr);
    }
    return chainPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainInit --
 *
 *      Initializes a linked list.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainInit(
    RbcChain * chainPtr)
{              /* The chain to initialize */
    chainPtr->nLinks = 0;
    chainPtr->headPtr = chainPtr->tailPtr = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainLinkAfter --
 *
 *      Inserts an entry following a given entry.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainLinkAfter(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr,
    RbcChainLink * afterPtr)
{
    if(chainPtr->headPtr == NULL) {
        chainPtr->tailPtr = chainPtr->headPtr = linkPtr;
    } else {
        if(afterPtr == NULL) {
            /* Prepend to the front of the chain */
            linkPtr->nextPtr = chainPtr->headPtr;
            linkPtr->prevPtr = NULL;
            chainPtr->headPtr->prevPtr = linkPtr;
            chainPtr->headPtr = linkPtr;
        } else {
            linkPtr->nextPtr = afterPtr->nextPtr;
            linkPtr->prevPtr = afterPtr;
            if(afterPtr == chainPtr->tailPtr) {
                chainPtr->tailPtr = linkPtr;
            } else {
                afterPtr->nextPtr->prevPtr = linkPtr;
            }
            afterPtr->nextPtr = linkPtr;
        }
    }
    chainPtr->nLinks++;
}

/*----------------------------------------------------------------------
 *
 * RbcChainLinkBefore --
 *
 *      Inserts a link preceding a given link.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainLinkBefore(
    RbcChain * chainPtr,       /* Chain to contain new entry */
    RbcChainLink * linkPtr,    /* New entry to be inserted */
    RbcChainLink * beforePtr)
{              /* Entry to link before */
    if(chainPtr->headPtr == NULL) {
        chainPtr->tailPtr = chainPtr->headPtr = linkPtr;
    } else {
        if(beforePtr == NULL) {
            /* Append to the end of the chain. */
            linkPtr->nextPtr = NULL;
            linkPtr->prevPtr = chainPtr->tailPtr;
            chainPtr->tailPtr->nextPtr = linkPtr;
            chainPtr->tailPtr = linkPtr;
        } else {
            linkPtr->prevPtr = beforePtr->prevPtr;
            linkPtr->nextPtr = beforePtr;
            if(beforePtr == chainPtr->headPtr) {
                chainPtr->headPtr = linkPtr;
            } else {
                beforePtr->prevPtr->nextPtr = linkPtr;
            }
            beforePtr->prevPtr = linkPtr;
        }
    }
    chainPtr->nLinks++;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainNewLink --
 *
 *      Creates a new link.
 *
 * Results:
 *      The return value is the pointer to the newly created link.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink *
RbcChainNewLink(
    )
{
RbcChainLink *linkPtr;

    linkPtr = (RbcChainLink *) ckalloc(sizeof(RbcChainLink));
    assert(linkPtr);
    linkPtr->clientData = NULL;
    linkPtr->nextPtr = linkPtr->prevPtr = NULL;
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainReset --
 *
 *      Removes all the links from the chain, freeing the memory for
 *      each link.  Memory pointed to by the link (clientData) is not
 *      freed.  It's the caller's responsibility to deallocate it.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainReset(
    RbcChain * chainPtr)
{              /* Chain to clear */
    if(chainPtr != NULL) {
RbcChainLink *oldPtr;
RbcChainLink *linkPtr = chainPtr->headPtr;

        while(linkPtr != NULL) {
            oldPtr = linkPtr;
            linkPtr = linkPtr->nextPtr;
            ckfree((char *)oldPtr);
        }
        RbcChainInit(chainPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainDestroy
 *
 *      Frees all the nodes from the chain and deallocates the memory
 *      allocated for the chain structure itself.  It's assumed that
 *      the chain was previous allocated by RbcChainCreate.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
void
RbcChainDestroy(
    RbcChain * chainPtr)
{              /* The chain to destroy. */
    if(chainPtr != NULL) {
        RbcChainReset(chainPtr);
        ckfree((char *)chainPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainUnlinkLink --
 *
 *      Unlinks a link from the chain. The link is not deallocated,
 *      but only removed from the chain.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainUnlinkLink(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr)
{
    /* Indicates if the link is actually removed from the chain. */
int unlinked;

    unlinked = FALSE;
    if(chainPtr->headPtr == linkPtr) {
        chainPtr->headPtr = linkPtr->nextPtr;
        unlinked = TRUE;
    }
    if(chainPtr->tailPtr == linkPtr) {
        chainPtr->tailPtr = linkPtr->prevPtr;
        unlinked = TRUE;
    }
    if(linkPtr->nextPtr != NULL) {
        linkPtr->nextPtr->prevPtr = linkPtr->prevPtr;
        unlinked = TRUE;
    }
    if(linkPtr->prevPtr != NULL) {
        linkPtr->prevPtr->nextPtr = linkPtr->nextPtr;
        unlinked = TRUE;
    }
    if(unlinked) {
        chainPtr->nLinks--;
    }
    linkPtr->prevPtr = linkPtr->nextPtr = NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainDeleteLink --
 *
 *      Unlinks and also frees the given link.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcChainDeleteLink(
    RbcChain * chainPtr,
    RbcChainLink * linkPtr)
{
    RbcChainUnlinkLink(chainPtr, linkPtr);
    ckfree((char *)linkPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainAppend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink *
RbcChainAppend(
    RbcChain * chainPtr,
    ClientData clientData)
{
RbcChainLink *linkPtr;

    linkPtr = RbcChainNewLink();
    RbcChainLinkBefore(chainPtr, linkPtr, (RbcChainLink *) NULL);
    RbcChainSetValue(linkPtr, clientData);
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainPrepend --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink *
RbcChainPrepend(
    RbcChain * chainPtr,
    ClientData clientData)
{
RbcChainLink *linkPtr;

    linkPtr = RbcChainNewLink();
    RbcChainLinkAfter(chainPtr, linkPtr, (RbcChainLink *) NULL);
    RbcChainSetValue(linkPtr, clientData);
    return linkPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcChainAllocLink --
 *
 *      Creates a new chain link.  Unlink RbcChainNewLink, this
 *      routine also allocates extra memory in the node for data.
 *
 * Results:
 *      The return value is the pointer to the newly created entry.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcChainLink *
RbcChainAllocLink(
    unsigned int extraSize)
{
RbcChainLink *linkPtr;
unsigned int linkSize;

    linkSize = ALIGN(sizeof(RbcChainLink));
    linkPtr = RbcCalloc(1, linkSize + extraSize);
    assert(linkPtr);
    if(extraSize > 0) {
        /* Point clientData at the memory beyond the normal structure. */
        linkPtr->clientData = (ClientData) ((char *)linkPtr + linkSize);
    }
    return linkPtr;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcImage.c.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcImage.c --
 *
 *      This module implements image processing procedures for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define NC		256
enum ColorIndices { RED, GREEN, BLUE };

#define R0	(cubePtr->r0)
#define R1	(cubePtr->r1)
#define G0	(cubePtr->g0)
#define G1	(cubePtr->g1)
#define B0	(cubePtr->b0)
#define B1	(cubePtr->b1)

typedef struct {
    int r0, r1;                /* min, max values:
                                * min exclusive max inclusive */
    int g0, g1;
    int b0, b1;
    int vol;
} Cube;

/*
 *----------------------------------------------------------------------
 *
 * Histogram is in elements 1..HISTSIZE along each axis,
 * element 0 is for base or marginal value
 * NB: these must start out 0!
 *----------------------------------------------------------------------
 */
typedef struct {
    long int wt[33][33][33];   /* # pixels in voxel */
    long int mR[33][33][33];   /* Sum over voxel of red pixel values */
    long int mG[33][33][33];   /* Sum over voxel of green pixel values */
    long int mB[33][33][33];   /* Sum over voxel of blue pixel values */
    long int gm2[33][33][33];  /* Variance */
} ColorImageStatistics;

static void ZoomImageVertically(
    RbcColorImage * src,
    RbcColorImage * dest,
    RbcResampleFilter * filterPtr);
static void ZoomImageHorizontally(
    RbcColorImage * src,
    RbcColorImage * dest,
    RbcResampleFilter * filterPtr);
static void ShearY(
    RbcColorImage * src,
    RbcColorImage * dest,
    int y,
    int offset,
    double frac,
    RbcPix32 bgColor);
static void ShearX(
    RbcColorImage * src,
    RbcColorImage * dest,
    int x,
    int offset,
    double frac,
    RbcPix32 bgColor);
static RbcColorImage *Rotate45(
    RbcColorImage * src,
    double theta,
    RbcPix32 bgColor);
static RbcColorImage *CopyColorImage(
    RbcColorImage * src);
static RbcColorImage *Rotate180(
    RbcColorImage * src);
static RbcColorImage *Rotate270(
    RbcColorImage * src);
static ColorImageStatistics *GetColorImageStatistics(
    RbcColorImage * image);
static void M3d(
    ColorImageStatistics * s);
static long int Volume(
    Cube * cubePtr,
    long int m[33][33][33]);
static long int Bottom(
    Cube * cubePtr,
    unsigned char dir,
    long int m[33][33][33]);
static long int Top(
    Cube * cubePtr,
    unsigned char dir,
    int pos,
    long int m[33][33][33]);
static double Variance(
    Cube * cubePtr,
    ColorImageStatistics * s);
static double Maximize(
    Cube * cubePtr,
    unsigned char dir,
    int first,
    int last,
    int *cut,
    long int rWhole,
    long int gWhole,
    long int bWhole,
    long int wWhole,
    ColorImageStatistics * s);
static int Cut(
    Cube * set1,
    Cube * set2,
    ColorImageStatistics * s);
static int SplitColorSpace(
    ColorImageStatistics * s,
    Cube * cubes,
    int nColors);
static void Mark(
    Cube * cubePtr,
    int label,
    unsigned int lut[33][33][33]);
static void CreateColorLookupTable(
    ColorImageStatistics * s,
    Cube * cubes,
    int nColors,
    unsigned int lut[33][33][33]);
static void MapColors(
    RbcColorImage * src,
    RbcColorImage * dest,
    unsigned int lut[33][33][33]);
static RbcPix32 *ColorImagePixel(
    RbcColorImage * imagePtr,
    int x,
    int y);

RbcResampleFilter *rbcBoxFilterPtr;     /* The ubiquitous box filter */

/*
 *----------------------------------------------------------------------
 *
 * RbcCreateColorImage --
 *
 *      Allocates a color image of a designated height and width.
 *
 *      This routine will be augmented with other types of information
 *      such as a color table, etc.
 *
 * Results:
 *      Returns the new color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcCreateColorImage(
    int width,                 /* Dimensions of new image */
    int height)
{              /* Dimensions of new image */
    RbcColorImage *imagePtr;
    size_t size;

    size = width * height;
    imagePtr = (RbcColorImage *) ckalloc(sizeof(RbcColorImage));
    assert(imagePtr);
    imagePtr->bits = (RbcPix32 *) ckalloc(sizeof(RbcPix32) * size);
    assert(imagePtr->bits);

    imagePtr->width = width;
    imagePtr->height = height;
    return imagePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreeColorImage --
 *
 *      Deallocates the given color image.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcFreeColorImage(
    RbcColorImage * imagePtr)
{
    ckfree((char *)imagePtr->bits);
    ckfree((char *)imagePtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcGammaCorrectColorImage --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcGammaCorrectColorImage(
    RbcColorImage * src,
    double newGamma)
{
    unsigned int nPixels;
    register RbcPix32 *srcPtr, *endPtr;
    register unsigned int i;
    double value;
    unsigned char lut[256];
    double invGamma;

    invGamma = 1.0 / newGamma;
    for(i = 0; i < 256; i++) {
        value = 255.0 * pow((double)i / 255.0, invGamma);
        lut[i] = CLAMP((unsigned char)value, 0, 255);
    }
    nPixels = src->width * src->height;
    srcPtr = src->bits;
    for(endPtr = srcPtr + nPixels; srcPtr < endPtr; srcPtr++) {
        srcPtr->rgba.red = lut[srcPtr->rgba.red];
        srcPtr->rgba.green = lut[srcPtr->rgba.green];
        srcPtr->rgba.blue = lut[srcPtr->rgba.blue];
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcColorImageToGreyscale --
 *
 *      Converts a color image to PostScript grey scale (1 component)
 *      output.  Luminosity isn't computed using the old NTSC formula,
 *
 *        Y = 0.299 * Red + 0.587 * Green + 0.114 * Blue
 *
 *      but the following
 *
 *        Y = 0.212671 * Red + 0.715160 * Green + 0.072169 * Blue
 *
 *      which better represents contemporary monitors.
 *
 * Results:
 *      The color image is converted to greyscale.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcColorImageToGreyscale(
    RbcColorImage * image)
{
register RbcPix32 *srcPtr, *endPtr;
double Y;
int nPixels;
int width, height;

    width = image->width;
    height = image->height;
    nPixels = width * height;
    srcPtr = image->bits;
    for(endPtr = srcPtr + nPixels; srcPtr < endPtr; srcPtr++) {
        Y = ((0.212671 * (double)srcPtr->rgba.red) +
            (0.715160 * (double)srcPtr->rgba.green) +
            (0.072169 * (double)srcPtr->rgba.blue));
        srcPtr->rgba.red = srcPtr->rgba.green = srcPtr->rgba.blue =
            (unsigned char)CLAMP((unsigned char)Y, 0, 255);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcColorImageToPhoto --
 *
 *      Translates a color image into a Tk photo.
 *
 * Results:
 *      The photo is re-written with the new color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcColorImageToPhoto(
    Tcl_Interp * interp,
    RbcColorImage * src,       /* Image to use as source */
    Tk_PhotoHandle photo)
{              /* Photo to write color image into */
Tk_PhotoImageBlock dest;
int width, height;

    width = src->width;
    height = src->height;

    Tk_PhotoGetImage(photo, &dest);
    dest.pixelSize = sizeof(RbcPix32);
    dest.pitch = sizeof(RbcPix32) * width;
    dest.width = width;
    dest.height = height;
    dest.offset[0] = Tk_Offset(RbcPix32, rgba.red);
    dest.offset[1] = Tk_Offset(RbcPix32, rgba.green);
    dest.offset[2] = Tk_Offset(RbcPix32, rgba.blue);
    dest.offset[3] = Tk_Offset(RbcPix32, rgba.alpha);
    dest.pixelPtr = (unsigned char *)src->bits;
    Tk_PhotoSetSize(interp, photo, width, height);
    Tk_PhotoPutBlock(interp, photo, &dest, 0, 0, width, height,
        TK_PHOTO_COMPOSITE_OVERLAY);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcPhotoRegionToColorImage --
 *
 *      Create a photo to a color image.
 *
 * Results:
 *      The new color image is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcPhotoRegionToColorImage(
    Tk_PhotoHandle photo,      /* Source photo image to scale */
    int x,
    int y,
    int width,
    int height)
{
    Tk_PhotoImageBlock src;
    RbcColorImage *image;
    register RbcPix32 *destPtr;
    register unsigned char *srcData;
    register int offset;
    unsigned int offR, offG, offB, offA;

    Tk_PhotoGetImage(photo, &src);
    if(x < 0) {
        x = 0;
    }
    if(y < 0) {
        y = 0;
    }
    if(width < 0) {
        width = src.width;
    }
    if(height < 0) {
        height = src.height;
    }
    if((x + width) > src.width) {
        width = src.width - x;
    }
    if((height + y) > src.height) {
        height = src.width - y;
    }
    image = RbcCreateColorImage(width, height);
    destPtr = image->bits;

    offset = (x * src.pixelSize) + (y * src.pitch);

    offR = src.offset[0];
    offG = src.offset[1];
    offB = src.offset[2];
    offA = src.offset[3];

    if(src.pixelSize == 4) {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = srcData[offR];
                destPtr->rgba.green = srcData[offG];
                destPtr->rgba.blue = srcData[offB];
                destPtr->rgba.alpha = srcData[offA];
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    } else if(src.pixelSize == 3) {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = srcData[offR];
                destPtr->rgba.green = srcData[offG];
                destPtr->rgba.blue = srcData[offB];
                /* No transparency information */
                destPtr->rgba.alpha = (unsigned char)-1;
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    } else {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = destPtr->rgba.green = destPtr->rgba.blue =
                    srcData[offA];
                /* No transparency information */
                destPtr->rgba.alpha = (unsigned char)-1;
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    }
    return image;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcPhotoToColorImage --
 *
 *      Create a photo to a color image.
 *
 * Results:
 *      The new color image is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcPhotoToColorImage(
    Tk_PhotoHandle photo)
{              /* Source photo image to scale */
RbcColorImage *image;
Tk_PhotoImageBlock src;
int width, height;
register RbcPix32 *destPtr;
register int offset;
register int x, y;
register unsigned char *srcData;

    Tk_PhotoGetImage(photo, &src);
    width = src.width;
    height = src.height;
    image = RbcCreateColorImage(width, height);
    destPtr = image->bits;
    offset = 0;
    if(src.pixelSize == 4) {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = srcData[src.offset[0]];
                destPtr->rgba.green = srcData[src.offset[1]];
                destPtr->rgba.blue = srcData[src.offset[2]];
                destPtr->rgba.alpha = srcData[src.offset[3]];
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    } else if(src.pixelSize == 3) {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = srcData[src.offset[0]];
                destPtr->rgba.green = srcData[src.offset[1]];
                destPtr->rgba.blue = srcData[src.offset[2]];
                /* No transparency information */
                destPtr->rgba.alpha = (unsigned char)-1;
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    } else {
        for(y = 0; y < height; y++) {
            srcData = src.pixelPtr + offset;
            for(x = 0; x < width; x++) {
                destPtr->rgba.red = destPtr->rgba.green = destPtr->rgba.blue =
                    srcData[src.offset[0]];
                /* No transparency information */
                destPtr->rgba.alpha = (unsigned char)-1;
                srcData += src.pixelSize;
                destPtr++;
            }
            offset += src.pitch;
        }
    }
    return image;
}

/*
 *	filter function definitions
 */

static ResampleFilterProc DefaultFilter;
static ResampleFilterProc BellFilter;
static ResampleFilterProc BesselFilter;
static ResampleFilterProc BoxFilter;
static ResampleFilterProc BSplineFilter;
static ResampleFilterProc CatRomFilter;
static ResampleFilterProc DummyFilter;
static ResampleFilterProc GaussianFilter;
static ResampleFilterProc GiFilter;
static ResampleFilterProc Lanczos3Filter;
static ResampleFilterProc MitchellFilter;
static ResampleFilterProc SincFilter;
static ResampleFilterProc TriangleFilter;
static Tk_ImageChangedProc TempImageChangedProc;

/*
 *--------------------------------------------------------------
 *
 * DefaultFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
DefaultFilter(
    double x)
{
    if(x < 0.0) {
        x = -x;
    }
    if(x < 1.0) {
        /* f(x) = 2x^3 - 3x^2 + 1, -1 <= x <= 1 */
        return (2.0 * x - 3.0) * x * x + 1.0;
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * DummyFilter --
 *
 *      Just for testing...
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
DummyFilter(
    double x)
{
    return FABS(x);
}

/*
 *
 * Finite filters in increasing order:
 *
 *      Box (constant)
 *      Triangle (linear)
 *      Bell
 *      BSpline (cubic)
 *
 */

/*
 *--------------------------------------------------------------
 *
 * BoxFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
BoxFilter(
    double x)
{
    if((x < -0.5) || (x > 0.5)) {
        return 0.0;
    }
    return 1.0;
}

/*
 *--------------------------------------------------------------
 *
 * TriangleFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
TriangleFilter(
    double x)
{
    if(x < 0.0) {
        x = -x;
    }
    if(x < 1.0) {
        return (1.0 - x);
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * BellFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
BellFilter(
    double x)
{
    if(x < 0.0) {
        x = -x;
    }
    if(x < 0.5) {
        return (0.75 - (x * x));
    }
    if(x < 1.5) {
        x = (x - 1.5);
        return (0.5 * (x * x));
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * BSplineFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
BSplineFilter(
    double x)
{
    double x2;

    if(x < 0.0) {
        x = -x;
    }
    if(x < 1) {
        x2 = x * x;
        return ((.5 * x2 * x) - x2 + (2.0 / 3.0));
    } else if(x < 2) {
        x = 2 - x;
        return ((x * x * x) / 6.0);
    }
    return 0.0;
}

/*
 *
 * Infinite Filters:
 *      Sinc		perfect lowpass filter
 *      Bessel		circularly symmetric 2-D filter
 *      Gaussian
 *      Lanczos3
 *      Mitchell
 */

/*
 *--------------------------------------------------------------
 *
 * SincFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
SincFilter(
    double x)
{
    x *= M_PI;
    if(x == 0.0) {
        return 1.0;
    }
    return (sin(x) / x);
}

/*
 *--------------------------------------------------------------
 *
 * BesselFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
BesselFilter(
    double x)
{
    /*
     * See Pratt "Digital Image Processing" p. 97 for Bessel functions
     * zeros are at approx x=1.2197, 2.2331, 3.2383, 4.2411, 5.2428, 6.2439,
     * 7.2448, 8.2454
     */
#ifdef __BORLANDC__
    return 0.0;
#else
    return (x == 0.0) ? M_PI / 4.0 : j1(M_PI * x) / (x + x);
#endif
}

#define SQRT_2PI	0.79788456080286541     /* sqrt(2.0 / M_PI) */

/*
 *--------------------------------------------------------------
 *
 * GaussianFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
GaussianFilter(
    double x)
{
    return exp(-2.0 * x * x) * SQRT_2PI;
}

/*
 *--------------------------------------------------------------
 *
 * Lanczos3Filter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Lanczos3Filter(
    double x)
{
    if(x < 0) {
        x = -x;
    }
    if(x < 3.0) {
        return (SincFilter(x) * SincFilter(x / 3.0));
    }
    return 0.0;
}

#define	B		0.3333333333333333      /* (1.0 / 3.0) */
#define	C		0.3333333333333333      /* (1.0 / 3.0) */

/*
 *--------------------------------------------------------------
 *
 * MitchellFilter --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
MitchellFilter(
    double x)
{
    double x2;

    x2 = x * x;
    if(x < 0) {
        x = -x;
    }
    if(x < 1.0) {
        x = (((12.0 - 9.0 * B - 6.0 * C) * (x * x2)) +
            ((-18.0 + 12.0 * B + 6.0 * C) * x2) + (6.0 - 2 * B));
        return (x / 6.0);
    } else if(x < 2.0) {
        x = (((-1.0 * B - 6.0 * C) * (x * x2)) + ((6.0 * B + 30.0 * C) * x2) +
            ((-12.0 * B - 48.0 * C) * x) + (8.0 * B + 24 * C));
        return (x / 6.0);
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * CatRomFilter --
 *
 *      Catmull-Rom spline
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
CatRomFilter(
    double x)
{
    if(x < -2.) {
        return 0.0;
    }
    if(x < -1.0) {
        return 0.5 * (4.0 + x * (8.0 + x * (5.0 + x)));
    }
    if(x < 0.0) {
        return 0.5 * (2.0 + x * x * (-5.0 + x * -3.0));
    }
    if(x < 1.0) {
        return 0.5 * (2.0 + x * x * (-5.0 + x * 3.0));
    }
    if(x < 2.0) {
        return 0.5 * (4.0 + x * (-8.0 + x * (5.0 - x)));
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * GiFilter --
 *
 *      Approximation to the gaussian integral [x, inf)
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
GiFilter(
    double x)
{
    if(x > 1.5) {
        return 0.0;
    } else if(x < -1.5) {
        return 1.0;
    } else {
#define I6 0.166666666666667
#define I4 0.25
#define I3 0.333333333333333
    double x2 = x * x;
    double x3 = x2 * x;

        if(x > 0.5) {
            return .5625 - (x3 * I6 - 3 * x2 * I4 + 1.125 * x);
        } else if(x > -0.5) {
            return 0.5 - (0.75 * x - x3 * I3);
        } else {
            return 0.4375 + (-x3 * I6 - 3 * x2 * I4 - 1.125 * x);
        }
    }
}

static RbcResampleFilter filterTable[] = {
    /* name,     function,              support */
    {"bell", BellFilter, 1.5},
    {"bessel", BesselFilter, 3.2383},
    {"box", BoxFilter, 0.5},
    {"bspline", BSplineFilter, 2.0},
    {"catrom", CatRomFilter, 2.0},
    {"default", DefaultFilter, 1.0},
    {"dummy", DummyFilter, 0.5},
    {"gauss8", GaussianFilter, 8.0},
    {"gaussian", GaussianFilter, 1.25},
    {"gi", GiFilter, 1.25},
    {"lanczos3", Lanczos3Filter, 3.0},
    {"mitchell", MitchellFilter, 2.0},
    {"none", (ResampleFilterProc *) NULL, 0.0},
    {"sinc", SincFilter, 4.0},
    {"triangle", TriangleFilter, 1.0},
};

static int nFilters = sizeof(filterTable) / sizeof(RbcResampleFilter);

RbcResampleFilter *rbcBoxFilterPtr = &(filterTable[1]);

/*
 *----------------------------------------------------------------------
 *
 * RbcGetResampleFilter --
 *
 *      Finds a 1-D filter associated by the given filter name.
 *
 * Results:
 *      A standard Tcl result.  Returns TCL_OK is the filter was
 *      found.  The filter information (proc and support) is returned
 *      via filterPtrPtr. Otherwise TCL_ERROR is returned and an error
 *      message is left in interp->result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetResampleFilter(
    Tcl_Interp * interp,
    char *name,
    RbcResampleFilter ** filterPtrPtr)
{
    RbcResampleFilter *filterPtr, *endPtr;

    endPtr = filterTable + nFilters;
    for(filterPtr = filterTable; filterPtr < endPtr; filterPtr++) {
        if(strcmp(name, filterPtr->name) == 0) {
            *filterPtrPtr = (filterPtr->proc == NULL) ? NULL : filterPtr;
            return TCL_OK;
        }
    }
    Tcl_AppendResult(interp, "can't find filter \"", name, "\"", (char *)NULL);
    return TCL_ERROR;
}

/*
 * Scaled integers are fixed point values.  The upper 18 bits is the integer
 * portion, the lower 14 bits the fractional remainder.  Must be careful
 * not to overflow the values (especially during multiplication).
 *
 * The following operations are defined:
 *
 *	S * n		Scaled integer times an integer.
 *	S1 + S2		Scaled integer plus another scaled integer.
 *
 */

#define float2si(f)	(int)((f) * 16384.0 + 0.5)
#define uchar2si(b)	(((int)(b)) << 14)
#define si2int(s)	(((s) + 8192) >> 14)

typedef union {
    int i;                     /* Fixed point, scaled integer. */
    float f;
} Weight;

typedef struct {
    int count;                 /* Number of samples. */
    int start;
    Weight weights[1];         /* Array of weights. */
} Sample;

/*
 *--------------------------------------------------------------
 *
 * ComputeWeights --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static size_t
ComputeWeights(
    int srcWidth,
    int destWidth,
    RbcResampleFilter * filterPtr,
    Sample ** samplePtrPtr)
{
    Sample *samples;
    double scale;
    int filterSize;
    double center;
    register Sample *s;
    register Weight *weight;
    register int x, i;
    register int left, right;  /* filter bounds */
    double factor, sum;
    size_t size;

    /* Pre-calculate filter contributions for a row */
    scale = (double)destWidth / (double)srcWidth;

    if(scale < 1.0) {
    double radius, fscale;

        /* Downsample */

        radius = filterPtr->support / scale;
        fscale = 1.0 / scale;
        filterSize = (int)(radius * 2 + 2);

        size = sizeof(Sample) + (filterSize - 1) * sizeof(Weight);
        samples = RbcCalloc(destWidth, size);
        assert(samples);

        s = samples;
        for(x = 0; x < destWidth; x++) {
    center = (double)x *fscale;

            /* Determine bounds of filter and its density */
            left = (int)(center - radius + 0.5);
            if(left < 0) {
                left = 0;
            }
            right = (int)(center + radius + 0.5);
            if(right >= srcWidth) {
                right = srcWidth - 1;
            }
            sum = 0.0;
            s->start = left;
            for(weight = s->weights, i = left; i <= right; i++, weight++) {
                weight->f = (float)
                    (*filterPtr->proc) (((double)i + 0.5 - center) * scale);
                sum += weight->f;
            }
            s->count = right - left + 1;

            factor = (sum == 0.0) ? 1.0 : (1.0 / sum);
            for(weight = s->weights, i = left; i <= right; i++, weight++) {
                weight->f = (float)(weight->f * factor);
                weight->i = float2si(weight->f);
            }
            s = (Sample *) ((char *)s + size);
        }
    } else {
    double fscale;
        /* Upsample */

        filterSize = (int)(filterPtr->support * 2 + 2);
        size = sizeof(Sample) + (filterSize - 1) * sizeof(Weight);
        samples = RbcCalloc(destWidth, size);
        assert(samples);

        fscale = 1.0 / scale;

        s = samples;
        for(x = 0; x < destWidth; x++) {
    center = (double)x *fscale;
            left = (int)(center - filterPtr->support + 0.5);
            if(left < 0) {
                left = 0;
            }
            right = (int)(center + filterPtr->support + 0.5);
            if(right >= srcWidth) {
                right = srcWidth - 1;
            }
            sum = 0.0;
            s->start = left;
            for(weight = s->weights, i = left; i <= right; i++, weight++) {
                weight->f = (float)
                    (*filterPtr->proc) ((double)i - center + 0.5);
                sum += weight->f;
            }
            s->count = right - left + 1;
            factor = (sum == 0.0) ? 1.0 : (1.0 / sum);
            for(weight = s->weights, i = left; i <= right; i++, weight++) {
                weight->f = (float)(weight->f * factor);
                weight->i = float2si(weight->f);
            }
            s = (Sample *) ((char *)s + size);
        }
    }
    *samplePtrPtr = samples;
    return size;
}

/*
 * The following macro converts a fixed-point scaled integer to a
 * byte, clamping the value between 0 and 255.
 */
#define SICLAMP(s) \
    (unsigned char)(((s) < 0) ? 0 : ((s) > 4177920) ? 255 : (si2int(s)))

/*
 *--------------------------------------------------------------
 *
 * ZoomImageVertically --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
ZoomImageVertically(
    RbcColorImage * src,
    RbcColorImage * dest,
    RbcResampleFilter * filterPtr)
{
Sample *samples, *s, *endPtr;
int destWidth, destHeight;
int red, green, blue, alpha;
int srcWidth, srcHeight;
register RbcPix32 *srcColumnPtr;
register RbcPix32 *srcPtr, *destPtr;
register Weight *weight;
int x, i;
size_t size;                   /* Size of sample. */

    srcWidth = src->width;
    srcHeight = src->height;
    destWidth = dest->width;
    destHeight = dest->height;

    /* Pre-calculate filter contributions for a row */
    size = ComputeWeights(srcHeight, destHeight, filterPtr, &samples);
    endPtr = (Sample *) ((char *)samples + (destHeight * size));

    /* Apply filter to zoom vertically from tmp to destination */
    for(x = 0; x < srcWidth; x++) {
        srcColumnPtr = src->bits + x;
        destPtr = dest->bits + x;
        for(s = samples; s < endPtr; s = (Sample *) ((char *)s + size)) {
            red = green = blue = alpha = 0;
            srcPtr = srcColumnPtr + (s->start * srcWidth);
            for(weight = s->weights, i = 0; i < s->count; i++, weight++) {
                red += srcPtr->rgba.red * weight->i;
                green += srcPtr->rgba.green * weight->i;
                blue += srcPtr->rgba.blue * weight->i;
                alpha += srcPtr->rgba.alpha * weight->i;
                srcPtr += srcWidth;
            }
            destPtr->rgba.red = SICLAMP(red);
            destPtr->rgba.green = SICLAMP(green);
            destPtr->rgba.blue = SICLAMP(blue);
            destPtr->rgba.alpha = SICLAMP(alpha);
            destPtr += destWidth;

        }
    }
    /* Free the memory allocated for filter weights */
    ckfree((char *)samples);
}

/*
 *--------------------------------------------------------------
 *
 * ZoomImageHorizontally --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
ZoomImageHorizontally(
    RbcColorImage * src,
    RbcColorImage * dest,
    RbcResampleFilter * filterPtr)
{
Sample *samples, *s, *endPtr;
Weight *weight;
int destWidth;
int red, green, blue, alpha;
int srcWidth, srcHeight;
int y, i;
register RbcPix32 *srcPtr, *destPtr;
register RbcPix32 *srcRowPtr;
size_t size;                   /* Size of sample. */

    srcWidth = src->width;
    srcHeight = src->height;
    destWidth = dest->width;

    /* Pre-calculate filter contributions for a row */
    size = ComputeWeights(srcWidth, destWidth, filterPtr, &samples);
    endPtr = (Sample *) ((char *)samples + (destWidth * size));

    /* Apply filter to zoom horizontally from srcPtr to tmpPixels */
    srcRowPtr = src->bits;
    destPtr = dest->bits;
    for(y = 0; y < srcHeight; y++) {
        for(s = samples; s < endPtr; s = (Sample *) ((char *)s + size)) {
            red = green = blue = alpha = 0;
            srcPtr = srcRowPtr + s->start;
            for(weight = s->weights, i = 0; i < s->count; i++, weight++) {
                red += srcPtr->rgba.red * weight->i;
                green += srcPtr->rgba.green * weight->i;
                blue += srcPtr->rgba.blue * weight->i;
                alpha += srcPtr->rgba.alpha * weight->i;
                srcPtr++;
            }
            destPtr->rgba.red = SICLAMP(red);
            destPtr->rgba.green = SICLAMP(green);
            destPtr->rgba.blue = SICLAMP(blue);
            destPtr->rgba.alpha = SICLAMP(alpha);
            destPtr++;
        }
        srcRowPtr += srcWidth;
    }
    /* free the memory allocated for horizontal filter weights */
    ckfree((char *)samples);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResampleColorImage --
 *
 *      Resamples a given color image using 1-D filters and returns
 *      a new color image of the designated size.
 *
 * Results:
 *      Returns the resampled color image. The original color image
 *      is left intact.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcResampleColorImage(
    RbcColorImage * src,
    int width,
    int height,
    RbcResampleFilter * horzFilterPtr,
    RbcResampleFilter * vertFilterPtr)
{
    RbcColorImage *tmp, *dest;

    /*
     * It's usually faster to zoom vertically last.  This has to do
     * with the fact that images are stored in contiguous rows.
     */

    tmp = RbcCreateColorImage(width, src->height);
    ZoomImageHorizontally(src, tmp, horzFilterPtr);
    dest = RbcCreateColorImage(width, height);
    ZoomImageVertically(tmp, dest, vertFilterPtr);
    RbcFreeColorImage(tmp);
    return dest;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResamplePhoto --
 *
 *      Resamples a Tk photo image using 1-D filters and writes the
 *      image into another Tk photo.  It is possible for the
 *      source and destination to be the same photo.
 *
 * Results:
 *      The designated destination photo will contain the resampled
 *      color image. The original photo is left intact.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcResamplePhoto(
    Tcl_Interp * interp,
    Tk_PhotoHandle srcPhoto,   /* Source photo image to scale */
    int x,
    int y,
    int width,
    int height,
    Tk_PhotoHandle destPhoto,  /* Resulting scaled photo image */
    RbcResampleFilter * horzFilterPtr,
    RbcResampleFilter * vertFilterPtr)
{
    RbcColorImage *srcImage, *destImage;
    Tk_PhotoImageBlock dest;

    Tk_PhotoGetImage(destPhoto, &dest);
    srcImage = RbcPhotoRegionToColorImage(srcPhoto, x, y, width, height);
    destImage = RbcResampleColorImage(srcImage, dest.width, dest.height,
        horzFilterPtr, vertFilterPtr);
    RbcFreeColorImage(srcImage);
    RbcColorImageToPhoto(interp, destImage, destPhoto);
    RbcFreeColorImage(destImage);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResizePhoto --
 *
 *      Scales the region of the source image to the size of the
 *      destination image.  This routine performs raw scaling of
 *      the image and unlike RbcResamplePhoto does not handle
 *      aliasing effects from subpixel sampling. It is possible
 *      for the source and destination to be the same photo.
 *
 * Results:
 *      The designated destination photo will contain the resampled
 *      color image. The original photo is left intact.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcResizePhoto(
    Tcl_Interp * interp,
    Tk_PhotoHandle srcPhoto,   /* Source photo image to scaled. */
    register int x,            /* Region of source photo to be * scaled. */
    register int y,            /* Region of source photo to be * scaled. */
    int width,
    int height,
    Tk_PhotoHandle destPhoto)
{              /* (out) Resulting scaled photo image.
                * Scaling factors are derived from
                * the destination photo's
                * dimensions. */
    double xScale, yScale;
    RbcColorImage *destImage;
    RbcPix32 *destPtr;
    Tk_PhotoImageBlock src, dest;
    unsigned char *srcPtr, *srcRowPtr;
    int *mapX, *mapY;
    register int sx, sy;
    int left, right, top, bottom;

    Tk_PhotoGetImage(srcPhoto, &src);
    Tk_PhotoGetImage(destPhoto, &dest);

    left = x, top = y, right = x + width - 1, bottom = y + height - 1;
    destImage = RbcCreateColorImage(dest.width, dest.height);
    xScale = (double)width / (double)dest.width;
    yScale = (double)height / (double)dest.height;
    mapX = (int *)ckalloc(sizeof(int) * dest.width);
    mapY = (int *)ckalloc(sizeof(int) * dest.height);
    for(x = 0; x < dest.width; x++) {
        sx = (int)(xScale * (double)(x + left));
        if(sx > right) {
            sx = right;
        }
        mapX[x] = sx;
    }
    for(y = 0; y < dest.height; y++) {
        sy = (int)(yScale * (double)(y + top));
        if(sy > bottom) {
            sy = bottom;
        }
        mapY[y] = sy;
    }
    destPtr = destImage->bits;
    if(src.pixelSize == 4) {
        for(y = 0; y < dest.height; y++) {
            srcRowPtr = src.pixelPtr + (mapY[y] * src.pitch);
            for(x = 0; x < dest.width; x++) {
                srcPtr = srcRowPtr + (mapX[x] * src.pixelSize);
                destPtr->rgba.red = srcPtr[src.offset[0]];
                destPtr->rgba.green = srcPtr[src.offset[1]];
                destPtr->rgba.blue = srcPtr[src.offset[2]];
                destPtr->rgba.alpha = srcPtr[src.offset[3]];
                destPtr++;
            }
        }
    } else if(src.pixelSize == 3) {
        for(y = 0; y < dest.height; y++) {
            srcRowPtr = src.pixelPtr + (mapY[y] * src.pitch);
            for(x = 0; x < dest.width; x++) {
                srcPtr = srcRowPtr + (mapX[x] * src.pixelSize);
                destPtr->rgba.red = srcPtr[src.offset[0]];
                destPtr->rgba.green = srcPtr[src.offset[1]];
                destPtr->rgba.blue = srcPtr[src.offset[2]];
                destPtr->rgba.alpha = (unsigned char)-1;
                destPtr++;
            }
        }
    } else {
        for(y = 0; y < dest.height; y++) {
            srcRowPtr = src.pixelPtr + (mapY[y] * src.pitch);
            for(x = 0; x < dest.width; x++) {
                srcPtr = srcRowPtr + (mapX[x] * src.pixelSize);
                destPtr->rgba.red = destPtr->rgba.green = destPtr->rgba.blue =
                    srcPtr[src.offset[0]];
                destPtr->rgba.alpha = (unsigned char)-1;
                destPtr++;
            }
        }
    }
    ckfree((char *)mapX);
    ckfree((char *)mapY);
    RbcColorImageToPhoto(interp, destImage, destPhoto);
    RbcFreeColorImage(destImage);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResizeColorImage --
 *
 *      Scales the region of the source image to the size of the
 *      destination image.  This routine performs raw scaling of
 *      the image and unlike RbcResamplePhoto does not perform
 *      any antialiasing.
 *
 * Results:
 *      Returns the new resized color image.  The original image
 *      is left intact.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcResizeColorImage(
    RbcColorImage * src,       /* Source color image to be scaled. */
    register int x,            /* Region of source image to scaled. */
    register int y,            /* Region of source image to scaled. */
    int width,
    int height,
    int destWidth,             /* Requested dimensions of the scaled image. */
    int destHeight)
{              /* Requested dimensions of the scaled image. */
    register int sx, sy;
    double xScale, yScale;
    RbcColorImage *dest;
    RbcPix32 *srcPtr, *srcRowPtr, *destPtr;
    int *mapX, *mapY;
    int left, right, top, bottom;

    left = x, top = y;
    right = x + width - 1, bottom = y + height - 1;

    dest = RbcCreateColorImage(destWidth, destHeight);
    xScale = (double)width / (double)destWidth;
    yScale = (double)height / (double)destHeight;
    mapX = (int *)ckalloc(sizeof(int) * destWidth);
    mapY = (int *)ckalloc(sizeof(int) * destHeight);
    for(x = 0; x < destWidth; x++) {
        sx = (int)(xScale * (double)(x + left));
        if(sx > right) {
            sx = right;
        }
        mapX[x] = sx;
    }
    for(y = 0; y < destHeight; y++) {
        sy = (int)(yScale * (double)(y + top));
        if(sy > bottom) {
            sy = bottom;
        }
        mapY[y] = sy;
    }
    destPtr = dest->bits;
    for(y = 0; y < destHeight; y++) {
        srcRowPtr = src->bits + (src->width * mapY[y]);
        for(x = 0; x < destWidth; x++) {
            srcPtr = srcRowPtr + mapX[x];
            destPtr->value = srcPtr->value;     /* Copy the pixel. */
            destPtr++;
        }
    }
    ckfree((char *)mapX);
    ckfree((char *)mapY);
    return dest;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcResizeColorSubimage --
 *
 *      Scales the region of the source image to the size of the
 *      destination image.  This routine performs raw scaling of
 *      the image and unlike RbcResamplePhoto does not perform
 *      any antialiasing.
 *
 * Results:
 *      Returns the new resized color image.  The original image
 *      is left intact.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcResizeColorSubimage(
    RbcColorImage * src,       /* Source color image to be scaled. */
    int regionX,
    int regionY,               /* Offset of subimage in destination. */
    int regionWidth,           /* Dimension of subimage. */
    int regionHeight,          /* Dimension of subimage. */
    int destWidth,             /* Dimensions of the entire scaled image. */
    int destHeight)
{              /* Dimensions of the entire scaled image. */
RbcColorImage *dest;
RbcPix32 *srcPtr, *srcRowPtr, *destPtr;
double xScale, yScale;
int *mapX, *mapY;
int srcWidth, srcHeight;
register int sx, sy;
register int x, y;

    srcWidth = src->width;
    srcHeight = src->height;

    xScale = (double)srcWidth / (double)destWidth;
    yScale = (double)srcHeight / (double)destHeight;
    mapX = (int *)ckalloc(sizeof(int) * regionWidth);
    mapY = (int *)ckalloc(sizeof(int) * regionHeight);

    /* Precompute scaling factors for each row and column. */
    for(x = 0; x < regionWidth; x++) {
        sx = (int)(xScale * (double)(x + regionX));
        if(sx >= srcWidth) {
            sx = srcWidth - 1;
        }
        mapX[x] = sx;
    }
    for(y = 0; y < regionHeight; y++) {
        sy = (int)(yScale * (double)(y + regionY));
        if(sy > srcHeight) {
            sy = srcHeight - 1;
        }
        mapY[y] = sy;
    }

    dest = RbcCreateColorImage(regionWidth, regionHeight);
    destPtr = dest->bits;
    for(y = 0; y < regionHeight; y++) {
        srcRowPtr = src->bits + (src->width * mapY[y]);
        for(x = 0; x < regionWidth; x++) {
            srcPtr = srcRowPtr + mapX[x];
            destPtr->value = srcPtr->value;     /* Copy the pixel. */
            destPtr++;
        }
    }
    ckfree((char *)mapX);
    ckfree((char *)mapY);
    return dest;
}

/*
 *--------------------------------------------------------------
 *
 * RbcConvolveColorImage --
 *
 *      FIXME: Boundary handling could be better (pixels
 *             are replicated). It's slow. Take boundary
 *             tests out of inner loop.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcColorImage *
RbcConvolveColorImage(
    RbcColorImage * src,
    RbcFilter2D * filterPtr)
{
RbcColorImage *dest;
register RbcPix32 *srcPtr, *destPtr;
#define MAXROWS	24
register int sx, sy, dx, dy;
register int x, y;
double red, green, blue;
int width, height;
int radius;
register double *valuePtr;

    width = src->width;
    height = src->height;

    dest = RbcCreateColorImage(width, height);
    radius = (int)filterPtr->support;
    if(radius < 1) {
        radius = 1;
    }
    destPtr = dest->bits;
    for(dy = 0; dy < height; dy++) {
        for(dx = 0; dx < width; dx++) {
            red = green = blue = 0.0;
            valuePtr = filterPtr->kernel;
            for(sy = (dy - radius); sy <= (dy + radius); sy++) {
                y = sy;
                if(y < 0) {
                    y = 0;
                } else if(y >= height) {
                    y = height - 1;
                }
                for(sx = (dx - radius); sx <= (dx + radius); sx++) {
                    x = sx;
                    if(x < 0) {
                        x = 0;
                    } else if(sx >= width) {
                        x = width - 1;
                    }
                    srcPtr = ColorImagePixel(src, x, y);
                    red += *valuePtr * (double)srcPtr->rgba.red;
                    green += *valuePtr * (double)srcPtr->rgba.green;
                    blue += *valuePtr * (double)srcPtr->rgba.blue;
                    valuePtr++;
                }
            }
            red /= filterPtr->sum;
            green /= filterPtr->sum;
            blue /= filterPtr->sum;
            destPtr->rgba.red = CLAMP((unsigned char)red, 0, 255);
            destPtr->rgba.green = CLAMP((unsigned char)green, 0, 255);
            destPtr->rgba.blue = CLAMP((unsigned char)blue, 0, 255);
            destPtr->rgba.alpha = (unsigned char)-1;
            destPtr++;
        }
    }
    return dest;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSnapPhoto --
 *
 *      Takes a snapshot of an X drawable (pixmap or window) and
 *      writes it to an existing Tk photo image.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side Effects:
 *      The named Tk photo is updated with the snapshot.
 *
 *----------------------------------------------------------------------
 */
int
RbcSnapPhoto(
    Tcl_Interp * interp,       /* Interpreter to report errors back to */
    Tk_Window tkwin,
    Drawable drawable,         /* Window or pixmap to be snapped */
    int x,                     /* Offset of image from drawable origin. */
    int y,                     /* Offset of image from drawable origin. */
    int width,                 /* Dimension of the drawable */
    int height,                /* Dimension of the drawable */
    int destWidth,             /* Desired size of the Tk photo */
    int destHeight,            /* Desired size of the Tk photo */
    const char *photoName,     /* Name of an existing Tk photo image. */
    double inputGamma)
{
    Tk_PhotoHandle photo;      /* The photo image to write into. */
    RbcColorImage *image;

    photo = Tk_FindPhoto(interp, photoName);
    if(photo == NULL) {
        Tcl_AppendResult(interp, "can't find photo \"", photoName, "\"",
            (char *)NULL);
        return TCL_ERROR;
    }
    image =
        RbcDrawableToColorImage(tkwin, drawable, x, y, width, height,
        inputGamma);
    if(image == NULL) {
        Tcl_AppendResult(interp,
            "can't grab window or pixmap (possibly obscured?)", (char *)NULL);
        return TCL_ERROR;       /* Can't grab window image */
    }
    if((destWidth != width) || (destHeight != height)) {
    RbcColorImage *destImage;

        /*
         * The requested size for the destination image is different than
         * that of the source snapshot.  Resample the image as necessary.
         * We'll use a cheap box filter. I'm assuming that the destination
         * image will typically be smaller than the original.
         */
        destImage = RbcResampleColorImage(image, destWidth, destHeight,
            rbcBoxFilterPtr, rbcBoxFilterPtr);
        RbcFreeColorImage(image);
        image = destImage;
    }
    RbcColorImageToPhoto(interp, image, photo);
    RbcFreeColorImage(image);
    return TCL_OK;
}

/*
 * --------------------------------------------------------------------------
 *
 * ShearY --
 *
 *      Shears a row horizontally. Antialiasing limited to filtering
 *      two adjacent pixels.  So the shear angle must be between +-45
 *      degrees.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The sheared image is drawn into the destination color image.
 *
 * --------------------------------------------------------------------------
 */
static void
ShearY(
    RbcColorImage * src,
    RbcColorImage * dest,
    int y,                     /* Designates the row to be sheared */
    int offset,                /* Difference between  of  */
    double frac,
    RbcPix32 bgColor)
{
    RbcPix32 *srcPtr, *destPtr;
    RbcPix32 *srcRowPtr, *destRowPtr;
    register int x, dx;
    int destWidth;
    int srcWidth;
    int red, blue, green, alpha;
    int leftRed, leftGreen, leftBlue, leftAlpha;
    int oldLeftRed, oldLeftGreen, oldLeftBlue, oldLeftAlpha;
    int ifrac;

    srcWidth = src->width;
    destWidth = dest->width;

    destRowPtr = dest->bits + (y * destWidth);
    srcRowPtr = src->bits + (y * srcWidth);

    destPtr = destRowPtr;
    for(x = 0; x < offset; x++) {
        *destPtr++ = bgColor;
    }
    destPtr = destRowPtr + offset;
    srcPtr = srcRowPtr;
    dx = offset;

    oldLeftRed = uchar2si(bgColor.rgba.red);
    oldLeftGreen = uchar2si(bgColor.rgba.green);
    oldLeftBlue = uchar2si(bgColor.rgba.blue);
    oldLeftAlpha = uchar2si(bgColor.rgba.alpha);

    ifrac = float2si(frac);
    for(x = 0; x < srcWidth; x++, dx++) {       /* Loop through row pixels */
        leftRed = srcPtr->rgba.red * ifrac;
        leftGreen = srcPtr->rgba.green * ifrac;
        leftBlue = srcPtr->rgba.blue * ifrac;
        leftAlpha = srcPtr->rgba.alpha * ifrac;
        if((dx >= 0) && (dx < destWidth)) {
            red = uchar2si(srcPtr->rgba.red) - (leftRed - oldLeftRed);
            green = uchar2si(srcPtr->rgba.green) - (leftGreen - oldLeftGreen);
            blue = uchar2si(srcPtr->rgba.blue) - (leftBlue - oldLeftBlue);
            alpha = uchar2si(srcPtr->rgba.alpha) - (leftAlpha - oldLeftAlpha);
            destPtr->rgba.red = SICLAMP(red);
            destPtr->rgba.green = SICLAMP(green);
            destPtr->rgba.blue = SICLAMP(blue);
            destPtr->rgba.alpha = SICLAMP(alpha);
        }
        oldLeftRed = leftRed;
        oldLeftGreen = leftGreen;
        oldLeftBlue = leftBlue;
        oldLeftAlpha = leftAlpha;
        srcPtr++, destPtr++;
    }
    x = srcWidth + offset;
    destPtr = dest->bits + (y * destWidth) + x;
    if(x < destWidth) {
        leftRed = uchar2si(bgColor.rgba.red);
        leftGreen = uchar2si(bgColor.rgba.green);
        leftBlue = uchar2si(bgColor.rgba.blue);
        leftAlpha = uchar2si(bgColor.rgba.alpha);

        red = leftRed + oldLeftRed - (bgColor.rgba.red * ifrac);
        green = leftGreen + oldLeftGreen - (bgColor.rgba.green * ifrac);
        blue = leftBlue + oldLeftBlue - (bgColor.rgba.blue * ifrac);
        alpha = leftAlpha + oldLeftAlpha - (bgColor.rgba.alpha * ifrac);
        destPtr->rgba.red = SICLAMP(red);
        destPtr->rgba.green = SICLAMP(green);
        destPtr->rgba.blue = SICLAMP(blue);
        destPtr->rgba.alpha = SICLAMP(alpha);
        destPtr++;
    }
    for(x++; x < destWidth; x++) {
        *destPtr++ = bgColor;
    }
}

/*
 * --------------------------------------------------------------------------
 *
 * ShearX --
 *
 *      Shears a column. Antialiasing is limited to filtering two
 *      adjacent pixels.  So the shear angle must be between +-45
 *      degrees.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The sheared image is drawn into the destination color image.
 *
 * --------------------------------------------------------------------------
 */
static void
ShearX(
    RbcColorImage * src,
    RbcColorImage * dest,
    int x,                     /* Column in source image to be sheared. */
    int offset,                /* Offset of */
    double frac,               /* Fraction of subpixel. */
    RbcPix32 bgColor)
{
    RbcPix32 *srcPtr, *destPtr;
    register int y, dy;
    int destHeight;
    int srcHeight;
    int red, blue, green, alpha;
    int leftRed, leftGreen, leftBlue, leftAlpha;
    int oldLeftRed, oldLeftGreen, oldLeftBlue, oldLeftAlpha;
    int ifrac;

    srcHeight = src->height;
    destHeight = dest->height;
    for(y = 0; y < offset; y++) {
        destPtr = ColorImagePixel(dest, x, y);
        *destPtr = bgColor;
    }

    oldLeftRed = uchar2si(bgColor.rgba.red);
    oldLeftGreen = uchar2si(bgColor.rgba.green);
    oldLeftBlue = uchar2si(bgColor.rgba.blue);
    oldLeftAlpha = uchar2si(bgColor.rgba.alpha);
    dy = offset;
    ifrac = float2si(frac);
    for(y = 0; y < srcHeight; y++, dy++) {
        srcPtr = ColorImagePixel(src, x, y);
        leftRed = srcPtr->rgba.red * ifrac;
        leftGreen = srcPtr->rgba.green * ifrac;
        leftBlue = srcPtr->rgba.blue * ifrac;
        leftAlpha = srcPtr->rgba.alpha * ifrac;
        if((dy >= 0) && (dy < destHeight)) {
            destPtr = ColorImagePixel(dest, x, dy);
            red = uchar2si(srcPtr->rgba.red) - (leftRed - oldLeftRed);
            green = uchar2si(srcPtr->rgba.green) - (leftGreen - oldLeftGreen);
            blue = uchar2si(srcPtr->rgba.blue) - (leftBlue - oldLeftBlue);
            alpha = uchar2si(srcPtr->rgba.alpha) - (leftAlpha - oldLeftAlpha);
            destPtr->rgba.red = SICLAMP(red);
            destPtr->rgba.green = SICLAMP(green);
            destPtr->rgba.blue = SICLAMP(blue);
            destPtr->rgba.alpha = SICLAMP(alpha);
        }
        oldLeftRed = leftRed;
        oldLeftGreen = leftGreen;
        oldLeftBlue = leftBlue;
        oldLeftAlpha = leftAlpha;
    }
    y = srcHeight + offset;
    if(y < destHeight) {
        leftRed = uchar2si(bgColor.rgba.red);
        leftGreen = uchar2si(bgColor.rgba.green);
        leftBlue = uchar2si(bgColor.rgba.blue);
        leftAlpha = uchar2si(bgColor.rgba.alpha);

        destPtr = ColorImagePixel(dest, x, y);
        red = leftRed + oldLeftRed - (bgColor.rgba.red * ifrac);
        green = leftGreen + oldLeftGreen - (bgColor.rgba.green * ifrac);
        blue = leftBlue + oldLeftBlue - (bgColor.rgba.blue * ifrac);
        alpha = leftAlpha + oldLeftAlpha - (bgColor.rgba.alpha * ifrac);
        destPtr->rgba.red = SICLAMP(red);
        destPtr->rgba.green = SICLAMP(green);
        destPtr->rgba.blue = SICLAMP(blue);
        destPtr->rgba.alpha = SICLAMP(alpha);
    }

    for(y++; y < destHeight; y++) {
        destPtr = ColorImagePixel(dest, x, y);
        *destPtr = bgColor;
    }
}

/*
 * ---------------------------------------------------------------------------
 *
 * Rotate45 --
 *
 *      Rotates an image by a given angle.  The angle must be in the
 *      range -45.0 to 45.0 inclusive.  Anti-aliasing filtering is
 *      performed on two adjacent pixels, so the angle can't be so
 *      great as to force a sheared pixel to occupy 3 destination
 *      pixels.  Performs a three shear rotation described below.
 *
 *      Reference: Alan W. Paeth, "A Fast Algorithm for General Raster
 *               Rotation", Graphics Gems, pp 179-195.
 *
 *
 * Results:
 *      Returns a newly allocated rotated image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------------
 */
static RbcColorImage *
Rotate45(
    RbcColorImage * src,
    double theta,
    RbcPix32 bgColor)
{
    int tmpWidth, tmpHeight;
    int srcWidth, srcHeight;
    double sinTheta, cosTheta, tanTheta;
    double skewf;
    int skewi;
    RbcColorImage *tmp1, *tmp2, *dest;
    register int x, y;

    sinTheta = sin(theta);
    cosTheta = cos(theta);
    tanTheta = tan(theta * 0.5);

    srcWidth = src->width;
    srcHeight = src->height;

    tmpWidth = srcWidth + (int)(srcHeight * FABS(tanTheta));
    tmpHeight = srcHeight;

    /* 1st shear */

    tmp1 = RbcCreateColorImage(tmpWidth, tmpHeight);
    assert(tmp1);

    if(tanTheta >= 0.0) {       /* Positive angle */
        for(y = 0; y < tmpHeight; y++) {
            skewf = (y + 0.5) * tanTheta;
            skewi = (int)floor(skewf);
            ShearY(src, tmp1, y, skewi, skewf - skewi, bgColor);
        }
    } else {   /* Negative angle */
        for(y = 0; y < tmpHeight; y++) {
            skewf = ((y - srcHeight) + 0.5) * tanTheta;
            skewi = (int)floor(skewf);
            ShearY(src, tmp1, y, skewi, skewf - skewi, bgColor);
        }
    }
    tmpHeight = (int)(srcWidth * FABS(sinTheta) + srcHeight * cosTheta) + 1;

    tmp2 = RbcCreateColorImage(tmpWidth, tmpHeight);
    assert(tmp2);

    /* 2nd shear */

    if(sinTheta > 0.0) {        /* Positive angle */
        skewf = (srcWidth - 1) * sinTheta;
    } else {   /* Negative angle */
        skewf = (srcWidth - tmpWidth) * -sinTheta;
    }
    for(x = 0; x < tmpWidth; x++) {
        skewi = (int)floor(skewf);
        ShearX(tmp1, tmp2, x, skewi, skewf - skewi, bgColor);
        skewf -= sinTheta;
    }

    RbcFreeColorImage(tmp1);

    /* 3rd shear */

    tmpWidth = (int)(srcHeight * FABS(sinTheta) + srcWidth * cosTheta) + 1;

    dest = RbcCreateColorImage(tmpWidth, tmpHeight);
    assert(dest);

    if(sinTheta >= 0.0) {       /* Positive angle */
        skewf = (srcWidth - 1) * sinTheta * -tanTheta;
    } else {   /* Negative angle */
        skewf = tanTheta * ((srcWidth - 1) * -sinTheta - (tmpHeight - 1));
    }
    for(y = 0; y < tmpHeight; y++) {
        skewi = (int)floor(skewf);
        ShearY(tmp2, dest, y, skewi, skewf - skewi, bgColor);
        skewf += tanTheta;
    }
    RbcFreeColorImage(tmp2);
    return dest;
}

/*
 * ---------------------------------------------------------------------------
 *
 * CopyColorImage --
 *
 *      Creates a copy of the given color image.
 *
 * Results:
 *      Returns the new copy.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------------
 */
static RbcColorImage *
CopyColorImage(
    RbcColorImage * src)
{
unsigned int width, height;
RbcPix32 *srcPtr, *destPtr;
RbcColorImage *dest;

    width = src->width;
    height = src->height;
    dest = RbcCreateColorImage(width, height);
    srcPtr = src->bits;
    destPtr = dest->bits;
    memcpy(destPtr, srcPtr, width * height * sizeof(RbcPix32));
    return dest;
}

/*
 * ---------------------------------------------------------------------------
 *
 * Rotate90 --
 *
 *      Rotates the given color image by 90 degrees.  This is part
 *      of the special case right-angle rotations that do not create
 *      subpixel aliasing.
 *
 * Results:
 *      Returns a newly allocated, rotated color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------------
 */
static RbcColorImage *
Rotate90(
    RbcColorImage * src)
{
int width, height, offset;
RbcPix32 *srcPtr, *destPtr;
RbcColorImage *dest;
register int x, y;

    height = src->width;
    width = src->height;

    srcPtr = src->bits;
    dest = RbcCreateColorImage(width, height);
    offset = (height - 1) * width;

    for(x = 0; x < width; x++) {
        destPtr = dest->bits + offset + x;
        for(y = 0; y < height; y++) {
            *destPtr = *srcPtr++;
            destPtr -= width;
        }
    }
    return dest;
}

/*
 * ---------------------------------------------------------------------------
 *
 * Rotate180 --
 *
 *      Rotates the given color image by 180 degrees.  This is one of
 *      the special case orthogonal rotations that do not create
 *      subpixel aliasing.
 *
 * Results:
 *      Returns a newly allocated, rotated color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------------
 */
static RbcColorImage *
Rotate180(
    RbcColorImage * src)
{
int width, height, offset;
RbcPix32 *srcPtr, *destPtr;
RbcColorImage *dest;
register int x, y;

    width = src->width;
    height = src->height;
    dest = RbcCreateColorImage(width, height);

    srcPtr = src->bits;
    offset = (height - 1) * width;
    for(y = 0; y < height; y++) {
        destPtr = dest->bits + offset + width - 1;
        for(x = 0; x < width; x++) {
            *destPtr-- = *srcPtr++;
        }
        offset -= width;
    }
    return dest;
}

/*
 * ---------------------------------------------------------------------------
 *
 * Rotate270 --
 *
 *      Rotates the given color image by 270 degrees.  This is part
 *      of the special case right-angle rotations that do not create
 *      subpixel aliasing.
 *
 * Results:
 *      Returns a newly allocated, rotated color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ---------------------------------------------------------------------------
 */
static RbcColorImage *
Rotate270(
    RbcColorImage * src)
{
int width, height;
RbcPix32 *srcPtr, *destPtr;
RbcColorImage *dest;
register int x, y;

    height = src->width;
    width = src->height;
    dest = RbcCreateColorImage(width, height);

    srcPtr = src->bits;
    for(x = width - 1; x >= 0; x--) {
        destPtr = dest->bits + x;
        for(y = 0; y < height; y++) {
            *destPtr = *srcPtr++;
            destPtr += width;
        }
    }
    return dest;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcRotateColorImage --
 *
 *      Rotates a color image by a given # of degrees.
 *
 * Results:
 *      Returns a newly allocated, rotated color image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcRotateColorImage(
    RbcColorImage * src,
    double angle)
{
RbcColorImage *dest, *tmp;
int quadrant;

    tmp = src; /* Suppress compiler warning. */

    /* Make the angle positive between 0 and 360 degrees. */
    angle = FMOD(angle, 360.0);
    if(angle < 0.0) {
        angle += 360.0;
    }
    quadrant = RBC_ROTATE_0;
    if((angle > 45.0) && (angle <= 135.0)) {
        quadrant = RBC_ROTATE_90;
        angle -= 90.0;
    } else if((angle > 135.0) && (angle <= 225.0)) {
        quadrant = RBC_ROTATE_180;
        angle -= 180.0;
    } else if((angle > 225.0) && (angle <= 315.0)) {
        quadrant = RBC_ROTATE_270;
        angle -= 270.0;
    } else if(angle > 315.0) {
        angle -= 360.0;
    }
    /*
     * If necessary, create a temporary image that's been rotated
     * by a right-angle.  We'll then rotate this color image between
     * -45 to 45 degrees to arrive at its final angle.
     */
    switch (quadrant) {
    case RBC_ROTATE_270:       /* 270 degrees */
        tmp = Rotate270(src);
        break;

    case RBC_ROTATE_90:        /* 90 degrees */
        tmp = Rotate90(src);
        break;

    case RBC_ROTATE_180:       /* 180 degrees */
        tmp = Rotate180(src);
        break;

    case RBC_ROTATE_0: /* 0 degrees */
        if(angle == 0.0) {
            tmp = CopyColorImage(src);  /* Make a copy of the source. */
        }
        break;
    }

    assert((angle >= -45.0) && (angle <= 45.0));

    dest = tmp;
    if(angle != 0.0) {
double theta;
RbcPix32 *srcPtr;
RbcPix32 bgColor;

        /* FIXME: pick up background blending color from somewhere */
        srcPtr = src->bits;
        bgColor = *srcPtr;
        bgColor.rgba.red = bgColor.rgba.green = bgColor.rgba.blue = 0xFF;
        bgColor.rgba.alpha = 0x00;      /* Transparent background */
        theta = (angle / 180.0) * M_PI;
        dest = Rotate45(tmp, theta, bgColor);
        if(tmp != src) {
            RbcFreeColorImage(tmp);
        }
    }
    return dest;
}

/*
 *--------------------------------------------------------------
 *
 * GetColorImageStatistics --
 *
 *      Build 3-D color histogram of counts, R/G/B, c^2
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static ColorImageStatistics *
GetColorImageStatistics(
    RbcColorImage * image)
{
register int r, g, b;
#define MAX_INTENSITIES	256
unsigned int sqr[MAX_INTENSITIES];
int numPixels;
RbcPix32 *srcPtr, *endPtr;
register int i;
ColorImageStatistics *s;

    s = RbcCalloc(1, sizeof(ColorImageStatistics));
    assert(s);

    /* Precompute table of squares. */
    for(i = 0; i < MAX_INTENSITIES; i++) {
        sqr[i] = i * i;
    }
    numPixels = image->width * image->height;

    for(srcPtr = image->bits, endPtr = srcPtr + numPixels;
        srcPtr < endPtr; srcPtr++) {
        /*
         * Reduce the number of bits (5) per color component. This
         * will keep the table size (2^15) reasonable without perceptually
         * affecting the final image.
         */
        r = (srcPtr->rgba.red >> 3) + 1;
        g = (srcPtr->rgba.green >> 3) + 1;
        b = (srcPtr->rgba.blue >> 3) + 1;
        s->wt[r][g][b] += 1;
        s->mR[r][g][b] += srcPtr->rgba.red;
        s->mG[r][g][b] += srcPtr->rgba.green;
        s->mB[r][g][b] += srcPtr->rgba.blue;
        s->gm2[r][g][b] += sqr[srcPtr->rgba.red] + sqr[srcPtr->rgba.green] +
            sqr[srcPtr->rgba.blue];
    }
    return s;
}

/*
 *----------------------------------------------------------------------
 * At conclusion of the histogram step, we can interpret
 *   wt[r][g][b] = sum over voxel of P(c)
 *   mR[r][g][b] = sum over voxel of r*P(c)  ,  similarly for mG, mB
 *   m2[r][g][b] = sum over voxel of c^2*P(c)
 * Actually each of these should be divided by 'size' to give the usual
 * interpretation of P() as ranging from 0 to 1, but we needn't do that here.
 *----------------------------------------------------------------------
 */

/*
 *--------------------------------------------------------------
 *
 * M3d --
 *
 *      We now convert histogram into moments so that we
 *      can rapidly calculate the sums of the above
 *      quantities over any desired box.
 *
 *      compute cumulative moments
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
M3d(
    ColorImageStatistics * s)
{
register unsigned char i, r, g, b, r0;
long int line, rLine, gLine, bLine;
long int area[33], rArea[33], gArea[33], bArea[33];
unsigned int line2, area2[33];

    for(r = 1, r0 = 0; r <= 32; r++, r0++) {
        for(i = 0; i <= 32; ++i) {
            area2[i] = area[i] = rArea[i] = gArea[i] = bArea[i] = 0;
        }
        for(g = 1; g <= 32; g++) {
            line2 = line = rLine = gLine = bLine = 0;
            for(b = 1; b <= 32; b++) {
                /* ind1 = RGBIndex(r, g, b); */

                line += s->wt[r][g][b];
                rLine += s->mR[r][g][b];
                gLine += s->mG[r][g][b];
                bLine += s->mB[r][g][b];
                line2 += s->gm2[r][g][b];

                area[b] += line;
                rArea[b] += rLine;
                gArea[b] += gLine;
                bArea[b] += bLine;
                area2[b] += line2;

                /* ind2 = ind1 - 1089; [r0][g][b] */
                s->wt[r][g][b] = s->wt[r0][g][b] + area[b];
                s->mR[r][g][b] = s->mR[r0][g][b] + rArea[b];
                s->mG[r][g][b] = s->mG[r0][g][b] + gArea[b];
                s->mB[r][g][b] = s->mB[r0][g][b] + bArea[b];
                s->gm2[r][g][b] = s->gm2[r0][g][b] + area2[b];
            }
        }
    }
}

/*
 *--------------------------------------------------------------
 *
 * Volume --
 *
 *      Compute sum over a box of any given statistic
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static long int
Volume(
    Cube * cubePtr,
    long int m[33][33][33])
{
    return (m[R1][G1][B1] - m[R1][G1][B0] - m[R1][G0][B1] + m[R1][G0][B0] -
        m[R0][G1][B1] + m[R0][G1][B0] + m[R0][G0][B1] - m[R0][G0][B0]);
}

/*
 *----------------------------------------------------------------------
 *
 *      The next two routines allow a slightly more efficient
 *      calculation of Volume() for a proposed subbox of a given box.
 *      The sum of Top() and Bottom() is the Volume() of a subbox split
 *      in the given direction and with the specified new upper
 *      bound.
 *
 *----------------------------------------------------------------------
 */

/*
 *--------------------------------------------------------------
 *
 * Bottom --
 *
 *      Compute part of Volume(cubePtr, mmt) that doesn't
 *      depend on r1, g1, or b1 (depending on dir)
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static long int
Bottom(
    Cube * cubePtr,
    unsigned char dir,
    long int m[33][33][33])
{              /* Moment */
    switch (dir) {
    case RED:
        return -m[R0][G1][B1] + m[R0][G1][B0] + m[R0][G0][B1] - m[R0][G0][B0];
    case GREEN:
        return -m[R1][G0][B1] + m[R1][G0][B0] + m[R0][G0][B1] - m[R0][G0][B0];
    case BLUE:
        return -m[R1][G1][B0] + m[R1][G0][B0] + m[R0][G1][B0] - m[R0][G0][B0];
    }
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * Top --
 *
 *      Compute remainder of Volume(cubePtr, mmt),
 *      substituting pos for r1, g1, or b1 (depending on dir)
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static long int
Top(
    Cube * cubePtr,
    unsigned char dir,
    int pos,
    long int m[33][33][33])
{
    switch (dir) {
    case RED:
        return (m[pos][G1][B1] - m[pos][G1][B0] -
            m[pos][G0][B1] + m[pos][G0][B0]);

    case GREEN:
        return (m[R1][pos][B1] - m[R1][pos][B0] -
            m[R0][pos][B1] + m[R0][pos][B0]);

    case BLUE:
        return (m[R1][G1][pos] - m[R1][G0][pos] -
            m[R0][G1][pos] + m[R0][G0][pos]);
    }
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * Variance --
 *
 *      Compute the weighted variance of a box NB: as with
 *      the raw statistics, this is really the (variance * size)
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Variance(
    Cube * cubePtr,
    ColorImageStatistics * s)
{
double dR, dG, dB, xx;

    dR = Volume(cubePtr, s->mR);
    dG = Volume(cubePtr, s->mG);
    dB = Volume(cubePtr, s->mB);
    xx = (s->gm2[R1][G1][B1] - s->gm2[R1][G1][B0] -
        s->gm2[R1][G0][B1] + s->gm2[R1][G0][B0] -
        s->gm2[R0][G1][B1] + s->gm2[R0][G1][B0] +
        s->gm2[R0][G0][B1] - s->gm2[R0][G0][B0]);
    return (xx - (dR * dR + dG * dG + dB * dB) / Volume(cubePtr, s->wt));
}

/*
 *--------------------------------------------------------------
 *
 * Maximize --
 *
 *      We want to minimize the sum of the variances of two
 *      subboxes. The sum(c^2) terms can be ignored since
 *      their sum over both subboxes is the same (the sum
 *      for the whole box) no matter where we split.  The
 *      remaining terms have a minus sign in the variance
 *      formula, so we drop the minus sign and MAXIMIZE the
 *      sum of the two terms.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Maximize(
    Cube * cubePtr,
    unsigned char dir,
    int first,
    int last,
    int *cut,
    long int rWhole,
    long int gWhole,
    long int bWhole,
    long int wWhole,
    ColorImageStatistics * s)
{
    register long int rHalf, gHalf, bHalf, wHalf;
    long int rBase, gBase, bBase, wBase;
    register int i;
    register double temp, max;

    rBase = Bottom(cubePtr, dir, s->mR);
    gBase = Bottom(cubePtr, dir, s->mG);
    bBase = Bottom(cubePtr, dir, s->mB);
    wBase = Bottom(cubePtr, dir, s->wt);
    max = 0.0;
    *cut = -1;
    for(i = first; i < last; i++) {
        rHalf = rBase + Top(cubePtr, dir, i, s->mR);
        gHalf = gBase + Top(cubePtr, dir, i, s->mG);
        bHalf = bBase + Top(cubePtr, dir, i, s->mB);
        wHalf = wBase + Top(cubePtr, dir, i, s->wt);

        /* Now half_x is sum over lower half of box, if split at i */
        if(wHalf == 0) {        /* subbox could be empty of pixels! */
            continue;   /* never split into an empty box */
        } else {
            temp = ((double)rHalf * rHalf + (float)gHalf * gHalf +
                (double)bHalf * bHalf) / wHalf;
        }
        rHalf = rWhole - rHalf;
        gHalf = gWhole - gHalf;
        bHalf = bWhole - bHalf;
        wHalf = wWhole - wHalf;
        if(wHalf == 0) {        /* Subbox could be empty of pixels! */
            continue;   /* never split into an empty box */
        } else {
            temp += ((double)rHalf * rHalf + (float)gHalf * gHalf +
                (double)bHalf * bHalf) / wHalf;
        }
        if(temp > max) {
            max = temp;
            *cut = i;
        }
    }
    return max;
}

/*
 *--------------------------------------------------------------
 *
 * Cut --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
Cut(
    Cube * set1,
    Cube * set2,
    ColorImageStatistics * s)
{
unsigned char dir;
int rCut, gCut, bCut;
double rMax, gMax, bMax;
long int rWhole, gWhole, bWhole, wWhole;

    rWhole = Volume(set1, s->mR);
    gWhole = Volume(set1, s->mG);
    bWhole = Volume(set1, s->mB);
    wWhole = Volume(set1, s->wt);

    rMax = Maximize(set1, RED, set1->r0 + 1, set1->r1, &rCut,
        rWhole, gWhole, bWhole, wWhole, s);
    gMax = Maximize(set1, GREEN, set1->g0 + 1, set1->g1, &gCut,
        rWhole, gWhole, bWhole, wWhole, s);
    bMax = Maximize(set1, BLUE, set1->b0 + 1, set1->b1, &bCut,
        rWhole, gWhole, bWhole, wWhole, s);

    if((rMax >= gMax) && (rMax >= bMax)) {
        dir = RED;
        if(rCut < 0) {
            return 0;   /* can't split the box */
        }
    } else {
        dir = ((gMax >= rMax) && (gMax >= bMax)) ? GREEN : BLUE;
    }
    set2->r1 = set1->r1;
    set2->g1 = set1->g1;
    set2->b1 = set1->b1;

    switch (dir) {
    case RED:
        set2->r0 = set1->r1 = rCut;
        set2->g0 = set1->g0;
        set2->b0 = set1->b0;
        break;

    case GREEN:
        set2->g0 = set1->g1 = gCut;
        set2->r0 = set1->r0;
        set2->b0 = set1->b0;
        break;

    case BLUE:
        set2->b0 = set1->b1 = bCut;
        set2->r0 = set1->r0;
        set2->g0 = set1->g0;
        break;
    }
    set1->vol = (set1->r1 - set1->r0) * (set1->g1 - set1->g0) *
        (set1->b1 - set1->b0);
    set2->vol = (set2->r1 - set2->r0) * (set2->g1 - set2->g0) *
        (set2->b1 - set2->b0);
    return 1;
}

/*
 *--------------------------------------------------------------
 *
 * SplitColorSpace --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
SplitColorSpace(
    ColorImageStatistics * s,
    Cube * cubes,
    int nColors)
{
    double *vv, temp;
    register int i;
    register int n, k;

    vv = (double *)ckalloc(sizeof(double) * nColors);
    assert(vv);

    cubes[0].r0 = cubes[0].g0 = cubes[0].b0 = 0;
    cubes[0].r1 = cubes[0].g1 = cubes[0].b1 = 32;
    for(i = 1, n = 0; i < nColors; i++) {
        if(Cut(cubes + n, cubes + i, s)) {
            /*
             * Volume test ensures we won't try to cut one-cell box
             */
            vv[n] = vv[i] = 0.0;
            if(cubes[n].vol > 1) {
                vv[n] = Variance(cubes + n, s);
            }
            if(cubes[i].vol > 1) {
                vv[i] = Variance(cubes + i, s);
            }
        } else {
            vv[n] = 0.0;        /* don't try to split this box again */
            i--;        /* didn't create box i */
        }

        n = 0;
        temp = vv[0];
        for(k = 1; k <= i; k++) {
            if(vv[k] > temp) {
                temp = vv[k];
                n = k;
            }
        }
        if(temp <= 0.0) {
            i++;
            fprintf(stderr, "Only got %d boxes\n", i);
            break;
        }
    }
    ckfree((char *)vv);
    return i;
}

/*
 *--------------------------------------------------------------
 *
 * Mark --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
Mark(
    Cube * cubePtr,
    int label,
    unsigned int tag[33][33][33])
{
    register int r, g, b;

    for(r = R0 + 1; r <= R1; r++) {
        for(g = G0 + 1; g <= G1; g++) {
            for(b = B0 + 1; b <= B1; b++) {
                tag[r][g][b] = label;
            }
        }
    }
}

/*
 *--------------------------------------------------------------
 *
 * CreateColorLookupTable --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
CreateColorLookupTable(
    ColorImageStatistics * s,
    Cube * cubes,
    int nColors,
    unsigned int lut[33][33][33])
{
    RbcPix32 color;
    unsigned int red, green, blue;
    unsigned int weight;
    register Cube *cubePtr;
    register int i;

    color.rgba.alpha = (unsigned char)-1;
    for(cubePtr = cubes, i = 0; i < nColors; i++, cubePtr++) {
        weight = Volume(cubePtr, s->wt);
        if(weight) {
            red = (Volume(cubePtr, s->mR) / weight) * (NC + 1);
            green = (Volume(cubePtr, s->mG) / weight) * (NC + 1);
            blue = (Volume(cubePtr, s->mB) / weight) * (NC + 1);
        } else {
            fprintf(stderr, "bogus box %d\n", i);
            red = green = blue = 0;
        }
        color.rgba.red = red >> 8;
        color.rgba.green = green >> 8;
        color.rgba.blue = blue >> 8;
        Mark(cubePtr, color.value, lut);
    }
}

/*
 *--------------------------------------------------------------
 *
 * MapColors --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
MapColors(
    RbcColorImage * src,
    RbcColorImage * dest,
    unsigned int lut[33][33][33])
{
    /* Apply the color lookup table against the original image */
    int width, height;
    int count;
    RbcPix32 *srcPtr, *destPtr, *endPtr;
    unsigned char alpha;

    width = src->width;
    height = src->height;
    count = width * height;

    srcPtr = src->bits;
    destPtr = dest->bits;
    for(endPtr = destPtr + count; destPtr < endPtr; srcPtr++, destPtr++) {
        alpha = srcPtr->rgba.alpha;
        destPtr->value =
            lut[srcPtr->rgba.red >> 3][srcPtr->rgba.green >> 3][srcPtr->rgba.
            blue >> 3];
        destPtr->rgba.alpha = alpha;
    }
}

/*
 *--------------------------------------------------------------
 *
 * ColorImagePixel --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static RbcPix32 *
ColorImagePixel(
    RbcColorImage * imagePtr,
    int x,
    int y)
{
    return (imagePtr->bits + (imagePtr->width * y) + x);
}

/*
 *--------------------------------------------------------------
 *
 * RbcQuantizeColorImage --
 *
 *      C Implementation of Wu's Color Quantizer (v. 2) (see Graphics Gems
 *      vol. II, pp. 126-133)
 *
 *      Author: Xiaolin Wu
 *            Dept. of Computer Science Univ. of Western
 *            Ontario London, Ontario
 *            N6A 5B7
 *            [email protected]
 *
 *      Algorithm:
 *            Greedy orthogonal bipartition of RGB space for variance
 *            minimization aided by inclusion-exclusion tricks.  For
 *            speed no nearest neighbor search is done. Slightly
 *            better performance can be expected by more
 *            sophisticated but more expensive versions.
 *
 *      The author thanks Tom Lane at [email protected] for much of
 *      additional documentation and a cure to a previous bug.
 *
 *      Free to distribute, comments and suggestions are appreciated.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcQuantizeColorImage(
    RbcColorImage * src,       /* Source and destination images. */
    RbcColorImage * dest,      /* Source and destination images. */
    int reduceColors)
{              /* Reduced number of colors. */
    Cube *cubes;
    ColorImageStatistics *statistics;
    int nColors;
    unsigned int lut[33][33][33];
    /*
     * Allocated a structure to hold color statistics.
     */
    statistics = GetColorImageStatistics(src);
    M3d(statistics);

    cubes = (Cube *) ckalloc(sizeof(Cube) * reduceColors);
    assert(cubes);

    nColors = SplitColorSpace(statistics, cubes, reduceColors);
    assert(nColors <= reduceColors);

    CreateColorLookupTable(statistics, cubes, nColors, lut);
    ckfree((char *)statistics);
    ckfree((char *)cubes);
    MapColors(src, dest, lut);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetRegion --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcRegion2D *
RbcSetRegion(
    int x,
    int y,
    int width,
    int height,
    RbcRegion2D * regionPtr)
{
    regionPtr->left = x;
    regionPtr->top = y;
    regionPtr->right = x + width - 1;
    regionPtr->bottom = y + height - 1;
    return regionPtr;
}

/*
 * Each call to Tk_GetImage returns a pointer to one of the following
 * structures, which is used as a token by clients (widgets) that
 * display images.
 */
typedef struct TkImageStruct {
    Tk_Window tkwin;           /* Window passed to Tk_GetImage (needed to
                                * "re-get" the image later if the manager
                                * changes). */
    Display *display;          /* Display for tkwin.  Needed because when
                                * the image is eventually freed tkwin may
                                * not exist anymore. */
    struct TkImageMasterStruct *masterPtr;
    /* Master for this image (identifiers image
     * manager, for example). */
    ClientData instanceData;
    /* One word argument to pass to image manager
     * when dealing with this image instance. */
    Tk_ImageChangedProc *changeProc;
    /* Code in widget to call when image changes
     * in a way that affects redisplay. */
    ClientData widgetClientData;
    /* Argument to pass to changeProc. */
    struct Image *nextPtr;     /* Next in list of all image instances
                                * associated with the same name. */

} TkImage;

/*
 * For each image master there is one of the following structures,
 * which represents a name in the image table and all of the images
 * instantiated from it.  Entries in mainPtr->imageTable point to
 * these structures.
 */
typedef struct TkImageMasterStruct {
    Tk_ImageType *typePtr;     /* Information about image type.  NULL means
                                * that no image manager owns this image:  the
                                * image was deleted. */
    ClientData masterData;     /* One-word argument to pass to image mgr
                                * when dealing with the master, as opposed
                                * to instances. */
    int width, height;         /* Last known dimensions for image. */
    Tcl_HashTable *tablePtr;   /* Pointer to hash table containing image
                                * (the imageTable field in some TkMainInfo
                                * structure). */
    Tcl_HashEntry *hPtr;       /* Hash entry in mainPtr->imageTable for
                                * this structure (used to delete the hash
                                * entry). */
    TkImage *instancePtr;      /* Pointer to first in list of instances
                                * derived from this name. */
} TkImageMaster;

typedef struct TkPhotoMasterStruct TkPhotoMaster;
typedef struct TkColorTableStruct TkColorTable;

typedef struct TkPhotoInstanceStruct {
    TkPhotoMaster *masterPtr;  /* Pointer to master for image. */
    Display *display;          /* Display for windows using this instance. */
    Colormap colormap;         /* The image may only be used in windows with
                                * this particular colormap. */
    struct TkPhotoInstanceStruct *nextPtr;
    /* Pointer to the next instance in the list
     * of instances associated with this master. */
    int refCount;              /* Number of instances using this structure. */
    Tk_Uid palette;            /* Palette for these particular instances. */
    double outputGamma;        /* Gamma value for these instances. */
    Tk_Uid defaultPalette;     /* Default palette to use if a palette
                                * is not specified for the master. */
    TkColorTable *colorTablePtr;        /* Pointer to information about colors
                                         * allocated for image display in windows
                                         * like this one. */
    Pixmap pixels;             /* X pixmap containing dithered image. */
    int width, height;         /* Dimensions of the pixmap. */
    char *error;               /* Error image, used in dithering. */
    XImage *imagePtr;          /* Image structure for converted pixels. */
    XVisualInfo visualInfo;    /* Information about the visual that these
                                * windows are using. */
    GC  gc;                    /* Graphics context for writing images
                                * to the pixmap. */
} TkPhotoInstance;

/*
 *----------------------------------------------------------------------
 *
 * TempImageChangedProc
 *
 *      The image is over-written each time it's resized.  We always
 *      resample from the color image we saved when the photo image
 *      was specified (-image option). So we only worry if the image
 *      is deleted.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
TempImageChangedProc(
    ClientData clientData,
    int x,                     /* Not used. */
    int y,                     /* Not used. */
    int width,                 /* Not used. */
    int height,                /* Not used. */
    int imageWidth,            /* Not used. */
    int imageHeight)
{              /* Not used. */
}

/*
 *--------------------------------------------------------------
 *
 * RbcCreateTemporaryImage --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
Tk_Image
RbcCreateTemporaryImage(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    ClientData clientData)
{
Tk_Image token;
char *name;                    /* Contains image name. */

    if(Tcl_Eval(interp, "image create photo") != TCL_OK) {
        return NULL;
    }
    name = (char *)Tcl_GetStringResult(interp);
    token = Tk_GetImage(interp, tkwin, name, TempImageChangedProc, clientData);
    if(token == NULL) {
        return NULL;
    }
    return token;
}

/*
 *--------------------------------------------------------------
 *
 * RbcDestroyTemporaryImage --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcDestroyTemporaryImage(
    Tcl_Interp * interp,
    Tk_Image tkImage)
{
    if(tkImage != NULL) {
        if(Tcl_VarEval(interp, "image delete ", RbcNameOfImage(tkImage),
                (char *)NULL) != TCL_OK) {
            return TCL_ERROR;
        }
        Tk_FreeImage(tkImage);
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcNameOfImage --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
const char *
RbcNameOfImage(
    Tk_Image tkImage)
{
TkImage *imagePtr = (TkImage *) tkImage;
    return Tk_NameOfImage((Tk_ImageMaster) imagePtr->masterPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcImageDeleted --
 *
 *      Is there any other way to determine if an image has been
 *      deleted?
 *
 * Results:
 *      Returns 1 if the image has been deleted, 0 otherwise.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
int
RbcImageIsDeleted(
    Tk_Image tkImage)
{              /* Token for image. */
TkImage *imagePtr = (TkImage *) tkImage;

    if(imagePtr->masterPtr == NULL) {
        return TRUE;
    }
    return (imagePtr->masterPtr->typePtr == NULL);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcParse.c.





































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcParse.c --
 *
 *      TODO: Description
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#ifndef TCL_RESULT_SIZE
#define TCL_RESULT_SIZE		200
#endif

#define TCL_BRACKET_TERM	  1

/*
 * A table used to classify input characters to assist in parsing
 * Tcl commands.  The table should be indexed with a signed character
 * using the CHAR_TYPE macro.  The character may have a negative
 * value.  The CHAR_TYPE macro takes a pointer to a signed character
 * and a pointer to the last character in the source string.  If the
 * src pointer is pointing at the terminating null of the string,
 * CHAR_TYPE returns TCL_COMMAND_END.
 */

#define TCL_NORMAL		0x01
#define TCL_SPACE		0x02
#define TCL_COMMAND_END		0x04
#define TCL_QUOTE		0x08
#define TCL_OPEN_BRACKET	0x10
#define TCL_OPEN_BRACE		0x20
#define TCL_CLOSE_BRACE		0x40
#define TCL_BACKSLASH		0x80
#define TCL_DOLLAR		0x00

static unsigned char tclTypeTable[] = {
    /*
     * Negative character values, from -128 to -1:
     */

    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,

    /*
     * Positive character values, from 0-127:
     */

    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_SPACE, TCL_COMMAND_END, TCL_SPACE,
    TCL_SPACE, TCL_SPACE, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_SPACE, TCL_NORMAL, TCL_QUOTE, TCL_NORMAL,
    TCL_DOLLAR, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_COMMAND_END,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_OPEN_BRACKET,
    TCL_BACKSLASH, TCL_COMMAND_END, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_OPEN_BRACE,
    TCL_NORMAL, TCL_CLOSE_BRACE, TCL_NORMAL, TCL_NORMAL,

    /*
     * Large unsigned character values, from 128-255:
     */

    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
    TCL_NORMAL, TCL_NORMAL, TCL_NORMAL, TCL_NORMAL,
};

#define CHAR_TYPE(src,last) \
	(((src)==(last))?TCL_COMMAND_END:(tclTypeTable+128)[(int)*(src)])

/*
 *--------------------------------------------------------------
 *
 * RbcExpandParseValue --
 *
 *      This procedure is commonly used as the value of the
 *      expandProc in a ParseValue.  It uses malloc to allocate
 *      more space for the result of a parse.
 *
 * Results:
 *      The buffer space in *parsePtr is reallocated to something
 *      larger, and if parsePtr->clientData is non-zero the old
 *      buffer is freed.  Information is copied from the old
 *      buffer to the new one.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
void
RbcExpandParseValue(
    RbcParseValue * parsePtr,  /* Information about buffer that
                                * must be expanded.  If the clientData
                                * in the structure is non-zero, it
                                * means that the current buffer is
                                * dynamically allocated. */
    int needed)
{              /* Minimum amount of additional space
                * to allocate. */
    int size;
    char *buffer;

    /*
     * Either double the size of the buffer or add enough new space
     * to meet the demand, whichever produces a larger new buffer.
     */
    size = (parsePtr->end - parsePtr->buffer) + 1;
    if(size < needed) {
        size += needed;
    } else {
        size += size;
    }
    buffer = (char *)ckalloc((unsigned int)size);

    /*
     * Copy from old buffer to new, free old buffer if needed, and
     * mark new buffer as malloc-ed.
     */
    memcpy((void *)buffer, (void *)parsePtr->buffer,
        (size_t) (parsePtr->next - parsePtr->buffer));
    parsePtr->next = buffer + (parsePtr->next - parsePtr->buffer);
    if(parsePtr->clientData != 0) {
        ckfree((char *)parsePtr->buffer);
    }
    parsePtr->buffer = buffer;
    parsePtr->end = buffer + size - 1;
    parsePtr->clientData = (ClientData) 1;
}

/*
 *--------------------------------------------------------------
 *
 * RbcParseNestedCmd --
 *
 *      This procedure parses a nested Tcl command between
 *      brackets, returning the result of the command.
 *
 * Results:
 *      The return value is a standard Tcl result, which is
 *      TCL_OK unless there was an error while executing the
 *      nested command.  If an error occurs then interp->result
 *      contains a standard error message.  *TermPtr is filled
 *      in with the address of the character just after the
 *      last one processed;  this is usually the character just
 *      after the matching close-bracket, or the null character
 *      at the end of the string if the close-bracket was missing
 *      (a missing close bracket is an error).  The result returned
 *      by the command is stored in standard fashion in *parsePtr,
 *      null-terminated, with parsePtr->next pointing to the null
 *      character.
 *
 * Side effects:
 *      The storage space at *parsePtr may be expanded.
 *--------------------------------------------------------------
 */
int
RbcParseNestedCmd(
    Tcl_Interp * interp,       /* Interpreter to use for nested command
                                * evaluations and error messages. */
    char *string,              /* Character just after opening bracket. */
    int flags,                 /* Flags to pass to nested Tcl_Eval. */
    char **termPtr,            /* Store address of terminating character
                                * here. */
    RbcParseValue * parsePtr)
{              /* Information about where to place
                * result of command. */
    int level;
    register char *src, *dest, *end;
    register char c;
    char *lastChar = string + strlen(string);
    int length, shortfall;

    src = string;
    dest = parsePtr->next;
    end = parsePtr->end;
    level = 1;

    /*
     * Copy the characters one at a time to the result area, stopping
     * when the matching close-bracket is found.
     */

    for(;;) {
        c = *src;
        src++;

        if(dest == end) {
            parsePtr->next = dest;
            (*parsePtr->expandProc) (parsePtr, 20);
            dest = parsePtr->next;
            end = parsePtr->end;
        }
        *dest = c;
        dest++;

        if(CHAR_TYPE(src - 1, lastChar) == TCL_NORMAL) {
            continue;
        } else if(c == '[') {
            level++;
        } else if(c == ']') {
            level--;
            if(level == 0) {
                dest--; /* Don't copy the last close bracket. */
                break;
            }
        } else if(c == '\\') {
    int count;

            /*
             * Must always squish out backslash-newlines, even when in
             * braces.  This is needed so that this sequence can appear
             * anywhere in a command, such as the middle of an expression.
             */

            if(*src == '\n') {
                dest[-1] = Tcl_Backslash(src - 1, &count);
                src += count - 1;
            } else {
                Tcl_Backslash(src - 1, &count);
                while(count > 1) {
                    if(dest == end) {
                        parsePtr->next = dest;
                        (*parsePtr->expandProc) (parsePtr, 20);
                        dest = parsePtr->next;
                        end = parsePtr->end;
                    }
                    *dest = *src;
                    dest++;
                    src++;
                    count--;
                }
            }
        } else if(c == '\0') {
            Tcl_AppendResult(interp, "missing close-bracket", (char *)NULL);
            *termPtr = string - 1;
            return TCL_ERROR;
        }
    }

    *dest = '\0';
    /*
     * *dest contain the command. Now we call the command and get the result.
     */
    if(Tcl_Eval(interp, dest) != TCL_OK) {
        Tcl_AppendResult(interp, "command error: ", Tcl_GetStringResult(interp),
            (char *)NULL);
        return TCL_ERROR;
    }
    dest = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &length);
    shortfall = length + 1 - (parsePtr->end - parsePtr->next);
    if(shortfall > 0) {
        (*parsePtr->expandProc) (parsePtr, shortfall);
    }
    strcpy(parsePtr->next, dest);
    parsePtr->next += length;
    *termPtr = src;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcParseBraces --
 *
 *      This procedure scans the information between matching
 *      curly braces.
 *
 * Results:
 *      The return value is a standard Tcl result, which is
 *      TCL_OK unless there was an error while parsing string.
 *      If an error occurs then interp->result contains a
 *      standard error message.  *TermPtr is filled
 *      in with the address of the character just after the
 *      last one successfully processed;  this is usually the
 *      character just after the matching close-brace.  The
 *      information between curly braces is stored in standard
 *      fashion in *parsePtr, null-terminated with parsePtr->next
 *      pointing to the terminating null character.
 *
 * Side effects:
 *      The storage space at *parsePtr may be expanded.
 *
 *--------------------------------------------------------------
 */
int
RbcParseBraces(
    Tcl_Interp * interp,       /* Interpreter to use for nested command
                                * evaluations and error messages. */
    char *string,              /* Character just after opening bracket. */
    char **termPtr,            /* Store address of terminating character here. */
    RbcParseValue * parsePtr)
{              /* Information about where to place
                * result of command. */
    int level;
    register char *src, *dest, *end;
    register char c;
    char *lastChar = string + strlen(string);

    src = string;
    dest = parsePtr->next;
    end = parsePtr->end;
    level = 1;

    /*
     * Copy the characters one at a time to the result area, stopping
     * when the matching close-brace is found.
     */

    for(;;) {
        c = *src;
        src++;

        if(dest == end) {
            parsePtr->next = dest;
            (*parsePtr->expandProc) (parsePtr, 20);
            dest = parsePtr->next;
            end = parsePtr->end;
        }
        *dest = c;
        dest++;

        if(CHAR_TYPE(src - 1, lastChar) == TCL_NORMAL) {
            continue;
        } else if(c == '{') {
            level++;
        } else if(c == '}') {
            level--;
            if(level == 0) {
                dest--; /* Don't copy the last close brace. */
                break;
            }
        } else if(c == '\\') {
    int count;

            /*
             * Must always squish out backslash-newlines, even when in
             * braces.  This is needed so that this sequence can appear
             * anywhere in a command, such as the middle of an expression.
             */

            if(*src == '\n') {
                dest[-1] = Tcl_Backslash(src - 1, &count);
                src += count - 1;
            } else {
                Tcl_Backslash(src - 1, &count);
                while(count > 1) {
                    if(dest == end) {
                        parsePtr->next = dest;
                        (*parsePtr->expandProc) (parsePtr, 20);
                        dest = parsePtr->next;
                        end = parsePtr->end;
                    }
                    *dest = *src;
                    dest++;
                    src++;
                    count--;
                }
            }
        } else if(c == '\0') {
            Tcl_AppendResult(interp, "missing close-brace", (char *)NULL);
            *termPtr = string - 1;
            return TCL_ERROR;
        }
    }

    *dest = '\0';
    parsePtr->next = dest;
    *termPtr = src;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcParseQuotes --
 *
 *      This procedure parses a double-quoted string such as a
 *      quoted Tcl command argument or a quoted value in a Tcl
 *      expression.  This procedure is also used to parse array
 *      element names within parentheses, or anything else that
 *      needs all the substitutions that happen in quotes.
 *
 * Results:
 *      The return value is a standard Tcl result, which is
 *      TCL_OK unless there was an error while parsing the
 *      quoted string.  If an error occurs then interp->result
 *      contains a standard error message.  *TermPtr is filled
 *      in with the address of the character just after the
 *      last one successfully processed;  this is usually the
 *      character just after the matching close-quote.  The
 *      fully-substituted contents of the quotes are stored in
 *      standard fashion in *parsePtr, null-terminated with
 *      parsePtr->next pointing to the terminating null character.
 *
 * Side effects:
 *      The buffer space in parsePtr may be enlarged by calling its
 *      expandProc.
 *
 *--------------------------------------------------------------
 */
int
RbcParseQuotes(
    Tcl_Interp * interp,       /* Interpreter to use for nested command
                                * evaluations and error messages. */
    char *string,              /* Character just after opening double-
                                * quote. */
    int termChar,              /* Character that terminates "quoted" string
                                * (usually double-quote, but sometimes
                                * right-paren or something else). */
    int flags,                 /* Flags to pass to nested Tcl_Eval calls. */
    char **termPtr,            /* Store address of terminating character
                                * here. */
    RbcParseValue * parsePtr)
{              /* Information about where to place
                * fully-substituted result of parse. */
    register char *src, *dest, c;
    char *lastChar = string + strlen(string);

    src = string;
    dest = parsePtr->next;

    for(;;) {
        if(dest == parsePtr->end) {
            /*
             * Target buffer space is about to run out.  Make more space.
             */
            parsePtr->next = dest;
            (*parsePtr->expandProc) (parsePtr, 1);
            dest = parsePtr->next;
        }
        c = *src;
        src++;
        if(c == termChar) {
            *dest = '\0';
            parsePtr->next = dest;
            *termPtr = src;
            return TCL_OK;
        } else if(CHAR_TYPE(src - 1, lastChar) == TCL_NORMAL) {
          copy:
            *dest = c;
            dest++;
            continue;
        } else if(c == '$') {
    int length;
    const char *value;
            value = Tcl_ParseVar(interp, src - 1, (const char **)termPtr);
            if(value == NULL) {
                return TCL_ERROR;
            }
            src = *termPtr;
            length = strlen(value);
            if((parsePtr->end - dest) <= length) {
                parsePtr->next = dest;
                (*parsePtr->expandProc) (parsePtr, length);
                dest = parsePtr->next;
            }
            strcpy(dest, value);
            dest += length;
            continue;
        } else if(c == '[') {
    int result;

            parsePtr->next = dest;
            result = RbcParseNestedCmd(interp, src, flags, termPtr, parsePtr);
            if(result != TCL_OK) {
                return result;
            }
            src = *termPtr;
            dest = parsePtr->next;
            continue;
        } else if(c == '\\') {
    int nRead;

            src--;
            *dest = Tcl_Backslash(src, &nRead);
            dest++;
            src += nRead;
            continue;
        } else if(c == '\0') {
    char buf[30];

            Tcl_ResetResult(interp);
            sprintf(buf, "missing %c", termChar);
            Tcl_SetObjResult(interp, Tcl_NewStringObj(buf, -1));
            *termPtr = string - 1;
            return TCL_ERROR;
        } else {
            goto copy;
        }
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcPs.c.












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcPs.c --
 *
 *      This module implements general PostScript conversion routines.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#include <X11/Xatom.h>

#define PS_MAXPATH	1500    /* Maximum number of components in a PostScript
                                 * (level 1) path. */

static void XColorToPostScript(
    RbcPsToken * tokenPtr,
    XColor * colorPtr);
static unsigned char ReverseBits(
    register unsigned char byte);
static void ByteToHex(
    register unsigned char byte,
    char *string);
#ifndef  _WIN32
static const char *NameOfAtom(
    Tk_Window tkwin,
    Atom atom);
#endif
static void TextLayoutToPostScript(
    RbcPsToken * tokenPtr,
    int x,
    int y,
    RbcTextLayout * textPtr);

/*
 *--------------------------------------------------------------
 *
 * RbcGetPsToken --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcPsToken *
RbcGetPsToken(
    Tcl_Interp * interp,
    Tk_Window tkwin)
{
RbcPsToken *tokenPtr;

    tokenPtr = (RbcPsToken *) ckalloc(sizeof(RbcPsToken));
    assert(tokenPtr);

    tokenPtr->fontVarName = tokenPtr->colorVarName = NULL;
    tokenPtr->interp = interp;
    tokenPtr->tkwin = tkwin;
    tokenPtr->colorMode = PS_MODE_COLOR;
    Tcl_DStringInit(&(tokenPtr->dString));
    return tokenPtr;
}

/*
 *--------------------------------------------------------------
 *
 * RbcReleasePsToken --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcReleasePsToken(
    RbcPsToken * tokenPtr)
{
    Tcl_DStringFree(&(tokenPtr->dString));
    ckfree((char *)tokenPtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcPostScriptFromToken --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
char *
RbcPostScriptFromToken(
    RbcPsToken * tokenPtr)
{
    return Tcl_DStringValue(&(tokenPtr->dString));
}

/*
 *--------------------------------------------------------------
 *
 * RbcScratchBufferFromToken --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
char *
RbcScratchBufferFromToken(
    RbcPsToken * tokenPtr)
{
    return tokenPtr->scratchArr;
}

/*
 *--------------------------------------------------------------
 *
 * RbcAppendToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcAppendToPostScript(
    RbcPsToken * psToken,
    ...)
{
    va_list argList;
    RbcPsToken *tokenPtr;
    char *string;

    tokenPtr = psToken;
    va_start(argList, psToken);
    for(;;) {
    string = va_arg(argList, char *);
        if(string == NULL) {
            break;
        }
        Tcl_DStringAppend(&(tokenPtr->dString), string, -1);
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcFormatToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcFormatToPostScript(
    RbcPsToken * psToken,
    ...)
{
    va_list argList;
    RbcPsToken *tokenPtr;
    char *fmt;

    tokenPtr = psToken;
    va_start(argList, psToken);
    fmt = va_arg(argList, char *);
    vsprintf(tokenPtr->scratchArr, fmt, argList);
    va_end(argList);
    Tcl_DStringAppend(&(tokenPtr->dString), tokenPtr->scratchArr, -1);
}

/*
 *----------------------------------------------------------------------
 *
 * XColorToPostScript --
 *
 *      Convert the a XColor (from its RGB values) to a PostScript
 *      command.  If a Tk color map variable exists, it will be
 *      consulted for a PostScript translation based upon the color
 *      name.
 *
 *      Maps an X color intensity (0 to 2^16-1) to a floating point
 *      value [0..1].  Many versions of Tk don't properly handle the
 *      the lower 8 bits of the color intensity, so we can only
 *      consider the upper 8 bits.
 *
 * Results:
 *      The string representing the color mode is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
XColorToPostScript(
    RbcPsToken * tokenPtr,
    XColor * colorPtr)
{              /* Color value to be converted */
    /*
     * Shift off the lower byte before dividing because some versions
     * of Tk don't fill the lower byte correctly.
     */
    RbcFormatToPostScript(tokenPtr, "%g %g %g",
        ((double)(colorPtr->red >> 8) / 255.0),
        ((double)(colorPtr->green >> 8) / 255.0),
        ((double)(colorPtr->blue >> 8) / 255.0));
}

/*
 *--------------------------------------------------------------
 *
 * RbcBackgroundToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcBackgroundToPostScript(
    RbcPsToken * tokenPtr,
    XColor * colorPtr)
{
    /* If the color name exists in Tcl array variable, use that translation */
    if(tokenPtr->colorVarName != NULL) {
const char *psColor;

        psColor = Tcl_GetVar2(tokenPtr->interp, tokenPtr->colorVarName,
            Tk_NameOfColor(colorPtr), 0);
        if(psColor != NULL) {
            RbcAppendToPostScript(tokenPtr, " ", psColor, "\n", (char *)NULL);
            return;
        }
    }
    XColorToPostScript(tokenPtr, colorPtr);
    RbcAppendToPostScript(tokenPtr, " SetBgColor\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * RbcForegroundToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcForegroundToPostScript(
    RbcPsToken * tokenPtr,
    XColor * colorPtr)
{
    /* If the color name exists in Tcl array variable, use that translation */
    if(tokenPtr->colorVarName != NULL) {
const char *psColor;

        psColor = Tcl_GetVar2(tokenPtr->interp, tokenPtr->colorVarName,
            Tk_NameOfColor(colorPtr), 0);
        if(psColor != NULL) {
            RbcAppendToPostScript(tokenPtr, " ", psColor, "\n", (char *)NULL);
            return;
        }
    }
    XColorToPostScript(tokenPtr, colorPtr);
    RbcAppendToPostScript(tokenPtr, " SetFgColor\n", (char *)NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * ReverseBits --
 *
 *      Convert a byte from a X image into PostScript image order.
 *      This requires not only the nybbles to be reversed but also
 *      their bit values.
 *
 * Results:
 *      The converted byte is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static unsigned char
ReverseBits(
    register unsigned char byte)
{
    byte = ((byte >> 1) & 0x55) | ((byte << 1) & 0xaa);
    byte = ((byte >> 2) & 0x33) | ((byte << 2) & 0xcc);
    byte = ((byte >> 4) & 0x0f) | ((byte << 4) & 0xf0);
    return byte;
}

/*
 *----------------------------------------------------------------------
 *
 * ByteToHex --
 *
 *      Convert a byte to its ASCII hexidecimal equivalent.
 *
 * Results:
 *      The converted 2 ASCII character string is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ByteToHex(
    register unsigned char byte,
    char *string)
{
    static char hexDigits[] = "0123456789ABCDEF";

    string[0] = hexDigits[byte >> 4];
    string[1] = hexDigits[byte & 0x0F];
}

#ifdef _WIN32

/*
 * -------------------------------------------------------------------------
 *
 * RbcBitmapDataToPostScript --
 *
 *      Output a PostScript image string of the given bitmap image.
 *      It is assumed the image is one bit deep and a zero value
 *      indicates an off-pixel.  To convert to PostScript, the bits
 *      need to be reversed from the X11 image order.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The PostScript image string is appended.
 *
 * -------------------------------------------------------------------------
 */
void
RbcBitmapDataToPostScript(
    RbcPsToken * tokenPtr,
    Display * display,
    Pixmap bitmap,
    int width,
    int height)
{
    register unsigned char byte;
    register int x, y, bitPos;
    unsigned long pixel;
    int byteCount;
    char string[10];
    unsigned char *srcBits, *srcPtr;
    int bytesPerRow;

    srcBits = RbcGetBitmapData(display, bitmap, width, height, &bytesPerRow);
    if(srcBits == NULL) {
        OutputDebugStringA("Can't get bitmap data");
        return;
    }
    RbcAppendToPostScript(tokenPtr, "\t<", (char *)NULL);
    byteCount = bitPos = 0;     /* Suppress compiler warning */
    for(y = height - 1; y >= 0; y--) {
        srcPtr = srcBits + (bytesPerRow * y);
        byte = 0;
        for(x = 0; x < width; x++) {
            bitPos = x % 8;
            pixel = (*srcPtr & (0x80 >> bitPos));
            if(pixel) {
                byte |= (unsigned char)(1 << bitPos);
            }
            if(bitPos == 7) {
                byte = ReverseBits(byte);
                ByteToHex(byte, string);
                string[2] = '\0';
                byteCount++;
                srcPtr++;
                byte = 0;
                if(byteCount >= 30) {
                    string[2] = '\n';
                    string[3] = '\t';
                    string[4] = '\0';
                    byteCount = 0;
                }
                RbcAppendToPostScript(tokenPtr, string, (char *)NULL);
            }
        }      /* x */
        if(bitPos != 7) {
            byte = ReverseBits(byte);
            ByteToHex(byte, string);
            string[2] = '\0';
            RbcAppendToPostScript(tokenPtr, string, (char *)NULL);
            byteCount++;
        }
    }          /* y */
    ckfree((char *)srcBits);
    RbcAppendToPostScript(tokenPtr, ">\n", (char *)NULL);
}

#else

/*
 * -------------------------------------------------------------------------
 *
 * RbcBitmapDataToPostScript --
 *
 *      Output a PostScript image string of the given bitmap image.
 *      It is assumed the image is one bit deep and a zero value
 *      indicates an off-pixel.  To convert to PostScript, the bits
 *      need to be reversed from the X11 image order.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The PostScript image string is appended to interp->result.
 *
 * -------------------------------------------------------------------------
 */
void
RbcBitmapDataToPostScript(
    RbcPsToken * psToken,
    Display * display,
    Pixmap bitmap,
    int width,
    int height)
{
    register unsigned char byte = 0;
    register int x, y, bitPos;
    unsigned long pixel;
    XImage *imagePtr;
    int byteCount;
    char string[10];

    imagePtr = XGetImage(display, bitmap, 0, 0, width, height, 1, ZPixmap);
    RbcAppendToPostScript(psToken, "\t<", (char *)NULL);
    byteCount = bitPos = 0;     /* Suppress compiler warning */
    for(y = 0; y < height; y++) {
        byte = 0;
        for(x = 0; x < width; x++) {
            pixel = XGetPixel(imagePtr, x, y);
            bitPos = x % 8;
            byte |= (unsigned char)(pixel << bitPos);
            if(bitPos == 7) {
                byte = ReverseBits(byte);
                ByteToHex(byte, string);
                string[2] = '\0';
                byteCount++;
                byte = 0;
                if(byteCount >= 30) {
                    string[2] = '\n';
                    string[3] = '\t';
                    string[4] = '\0';
                    byteCount = 0;
                }
                RbcAppendToPostScript(psToken, string, (char *)NULL);
            }
        }      /* x */
        if(bitPos != 7) {
            byte = ReverseBits(byte);
            ByteToHex(byte, string);
            string[2] = '\0';
            RbcAppendToPostScript(psToken, string, (char *)NULL);
            byteCount++;
        }
    }          /* y */
    RbcAppendToPostScript(psToken, ">\n", (char *)NULL);
    XDestroyImage(imagePtr);
}

#endif /* _WIN32 */

/*
 *----------------------------------------------------------------------
 *
 * RbcColorImageToPsData --
 *
 *      Converts a color image to PostScript RGB (3 components)
 *      or Greyscale (1 component) output.  With 3 components, we
 *      assume the "colorimage" operator is available.
 *
 *      Note that the image converted from bottom to top, to conform
 *      to the PostScript coordinate system.
 *
 * Results:
 *      The PostScript data comprising the color image is written
 *      into the dynamic string.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcColorImageToPsData(
    RbcColorImage * image,
    int nComponents,
    Tcl_DString * resultPtr,
    const char *prefix)
{
    char string[10];
    register int count;
    register int x, y;
    register RbcPix32 *pixelPtr;
    unsigned char byte;
    int width, height;
    int offset;
    int nLines;
    width = image->width;
    height = image->height;

    nLines = 0;
    count = 0;
    offset = (height - 1) * width;
    if(nComponents == 3) {
        for(y = (height - 1); y >= 0; y--) {
            pixelPtr = image->bits + offset;
            for(x = 0; x < width; x++, pixelPtr++) {
                if(count == 0) {
                    Tcl_DStringAppend(resultPtr, prefix, -1);
                    Tcl_DStringAppend(resultPtr, " ", -1);
                }
                count += 6;
                ByteToHex(pixelPtr->rgba.red, string);
                ByteToHex(pixelPtr->rgba.green, string + 2);
                ByteToHex(pixelPtr->rgba.blue, string + 4);
                string[6] = '\0';
                if(count >= 60) {
                    string[6] = '\n';
                    string[7] = '\0';
                    count = 0;
                    nLines++;
                }
                Tcl_DStringAppend(resultPtr, string, -1);
            }
            offset -= width;
        }
    } else if(nComponents == 1) {
        for(y = (height - 1); y >= 0; y--) {
            pixelPtr = image->bits + offset;
            for(x = 0; x < width; x++, pixelPtr++) {
                if(count == 0) {
                    Tcl_DStringAppend(resultPtr, prefix, -1);
                    Tcl_DStringAppend(resultPtr, " ", -1);
                }
                count += 2;
                byte = ~(pixelPtr->rgba.red);
                ByteToHex(byte, string);
                string[2] = '\0';
                if(count >= 60) {
                    string[2] = '\n';
                    string[3] = '\0';
                    count = 0;
                    nLines++;
                }
                Tcl_DStringAppend(resultPtr, string, -1);
            }
            offset -= width;
        }
    }
    if(count != 0) {
        Tcl_DStringAppend(resultPtr, "\n", -1);
        nLines++;
    }
    return nLines;
}

#ifndef  _WIN32

/*
 *----------------------------------------------------------------------
 *
 * NameOfAtom --
 *
 *      Wrapper routine for Tk_GetAtomName.  Returns NULL instead of
 *      "?bad atom?" if the atom can't be found.
 *
 * Results:
 *      The name of the atom is returned if found. Otherwise NULL.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static const char *
NameOfAtom(
    Tk_Window tkwin,
    Atom atom)
{
char *result;

    result = Tk_GetAtomName(tkwin, atom);
    if((result[0] == '?') && (strcmp(result, "?bad atom?") == 0)) {
        return NULL;
    }
    return result;
}
#endif

typedef struct {
    const char *alias;
    const char *fontName;
} FontMap;

static FontMap psFontMap[] = {
    {"Arial", "Helvetica",},
    {"AvantGarde", "AvantGarde",},
    {"Courier New", "Courier",},
    {"Courier", "Courier",},
    {"Geneva", "Helvetica",},
    {"Helvetica", "Helvetica",},
    {"Monaco", "Courier",},
    {"New Century Schoolbook", "NewCenturySchlbk",},
    {"New York", "Times",},
    {"Palatino", "Palatino",},
    {"Symbol", "Symbol",},
    {"Times New Roman", "Times",},
    {"Times Roman", "Times",},
    {"Times", "Times",},
    {"Utopia", "Utopia",},
    {"ZapfChancery", "ZapfChancery",},
    {"ZapfDingbats", "ZapfDingbats",},
};

static int nFontNames = (sizeof(psFontMap) / sizeof(FontMap));

#ifndef  _WIN32

/*
 * -----------------------------------------------------------------
 *
 * XFontStructToPostScript --
 *
 *      Map X11 font to a PostScript font. Currently, only fonts whose
 *      FOUNDRY property are "Adobe" are converted. Simply gets the
 *      XA_FULL_NAME and XA_FAMILY properties and pieces together a
 *      PostScript fontname.
 *
 * Results:
 *      Returns the mapped PostScript font name if one is possible.
 *      Otherwise returns NULL.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
static char *
XFontStructToPostScript(
    Tk_Window tkwin,           /* Window to query for atoms */
    XFontStruct * fontPtr)
{              /* Font structure to map to name */
Atom atom;
char *fullName, *family, *foundry;
register char *src, *dest;
int familyLen;
char *start;
static char string[200];       /* What size? */

    if(XGetFontProperty(fontPtr, XA_FULL_NAME, &atom) == False) {
        return NULL;
    }
    fullName = NameOfAtom(tkwin, atom);
    if(fullName == NULL) {
        return NULL;
    }
    family = foundry = NULL;
    if(XGetFontProperty(fontPtr, Tk_InternAtom(tkwin, "FOUNDRY"), &atom)) {
        foundry = NameOfAtom(tkwin, atom);
    }
    if(XGetFontProperty(fontPtr, XA_FAMILY_NAME, &atom)) {
        family = NameOfAtom(tkwin, atom);
    }
    /*
     * Try to map the font only if the foundry is Adobe
     */
    if((foundry == NULL) || (family == NULL)) {
        return NULL;
    }
    src = NULL;
    familyLen = strlen(family);
    if(strncasecmp(fullName, family, familyLen) == 0) {
        src = fullName + familyLen;
    }
    if(strcmp(foundry, "Adobe") != 0) {
register int i;

        if(strncasecmp(family, "itc ", 4) == 0) {
            family += 4;        /* Throw out the "itc" prefix */
        }
        for(i = 0; i < nFontNames; i++) {
            if(strcasecmp(family, psFontMap[i].alias) == 0) {
                family = psFontMap[i].fontName;
            }
        }
        if(i == nFontNames) {
            family = "Helvetica";       /* Default to a known font */
        }
    }
    /*
     * PostScript font name is in the form <family>-<type face>
     */
    sprintf(string, "%s-", family);
    dest = start = string + strlen(string);

    /*
     * Append the type face (part of the full name trailing the family name)
     * to the the PostScript font name, removing any spaces or dashes
     *
     * ex. " Bold Italic" ==> "BoldItalic"
     */
    if(src != NULL) {
        while(*src != '\0') {
            if((*src != ' ') && (*src != '-')) {
                *dest++ = *src;
            }
            src++;
        }
    }
    if(dest == start) {
        --dest; /* Remove '-' to leave just the family name */
    }
    *dest = '\0';       /* Make a valid string */
    return string;
}

#endif /* !_WIN32 */

/*
 * -------------------------------------------------------------------
 * Routines to convert X drawing functions to PostScript commands.
 * -------------------------------------------------------------------
 */

/*
 *--------------------------------------------------------------
 *
 * RbcClearBackgroundToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcClearBackgroundToPostScript(
    RbcPsToken * tokenPtr)
{
    RbcAppendToPostScript(tokenPtr, " 1.0 1.0 1.0 SetBgColor\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * CapStyleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
CapStyleToPostScript(
    RbcPsToken * tokenPtr,
    int capStyle)
{
    /*
     * X11:not last = 0, butt = 1, round = 2, projecting = 3
     * PS: butt = 0, round = 1, projecting = 2
     */
    if(capStyle > 0) {
        capStyle--;
    }
    RbcFormatToPostScript(tokenPtr, "%d setlinecap\n", capStyle);
}

/*
 *--------------------------------------------------------------
 *
 * JoinStyleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
JoinStyleToPostScript(
    RbcPsToken * tokenPtr,
    int joinStyle)
{
    /*
     * miter = 0, round = 1, bevel = 2
     */
    RbcFormatToPostScript(tokenPtr, "%d setlinejoin\n", joinStyle);
}

/*
 *--------------------------------------------------------------
 *
 * RbcLineWidthToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcLineWidthToPostScript(
    RbcPsToken * tokenPtr,
    int lineWidth)
{
    if(lineWidth < 1) {
        lineWidth = 1;
    }
    RbcFormatToPostScript(tokenPtr, "%d setlinewidth\n", lineWidth);
}

/*
 *--------------------------------------------------------------
 *
 * RbcLineDashesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcLineDashesToPostScript(
    RbcPsToken * tokenPtr,
    RbcDashes * dashesPtr)
{

    RbcAppendToPostScript(tokenPtr, "[ ", (char *)NULL);
    if(dashesPtr != NULL) {
char *p;

        for(p = dashesPtr->values; *p != 0; p++) {
            RbcFormatToPostScript(tokenPtr, " %d", *p);
        }
    }
    RbcAppendToPostScript(tokenPtr, "] 0 setdash\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * RbcLineAttributesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcLineAttributesToPostScript(
    RbcPsToken * tokenPtr,
    XColor * colorPtr,
    int lineWidth,
    RbcDashes * dashesPtr,
    int capStyle,
    int joinStyle)
{
    JoinStyleToPostScript(tokenPtr, joinStyle);
    CapStyleToPostScript(tokenPtr, capStyle);
    RbcForegroundToPostScript(tokenPtr, colorPtr);
    RbcLineWidthToPostScript(tokenPtr, lineWidth);
    RbcLineDashesToPostScript(tokenPtr, dashesPtr);
    RbcAppendToPostScript(tokenPtr, "/DashesProc {} def\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * RbcRectangleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcRectangleToPostScript(
    RbcPsToken * tokenPtr,
    double x,
    double y,
    int width,
    int height)
{
    RbcFormatToPostScript(tokenPtr,
        "%g %g %d %d Box fill\n\n", x, y, width, height);
}

/*
 *--------------------------------------------------------------
 *
 * RbcRegionToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcRegionToPostScript(
    RbcPsToken * tokenPtr,
    double x,
    double y,
    int width,
    int height)
{
    RbcFormatToPostScript(tokenPtr, "%g %g %d %d Box\n\n", x, y, width, height);
}

/*
 *--------------------------------------------------------------
 *
 * RbcPathToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcPathToPostScript(
    RbcPsToken * tokenPtr,
    register RbcPoint2D * screenPts,
    int nScreenPts)
{
    register RbcPoint2D *pointPtr, *endPtr;

    pointPtr = screenPts;
    RbcFormatToPostScript(tokenPtr, "newpath %g %g moveto\n",
        pointPtr->x, pointPtr->y);
    pointPtr++;
    endPtr = screenPts + nScreenPts;
    while(pointPtr < endPtr) {
        RbcFormatToPostScript(tokenPtr, "%g %g lineto\n",
            pointPtr->x, pointPtr->y);
        pointPtr++;
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcPolygonToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcPolygonToPostScript(
    RbcPsToken * tokenPtr,
    RbcPoint2D * screenPts,
    int nScreenPts)
{
    RbcPathToPostScript(tokenPtr, screenPts, nScreenPts);
    RbcFormatToPostScript(tokenPtr, "%g %g ", screenPts[0].x, screenPts[0].y);
    RbcAppendToPostScript(tokenPtr, " lineto closepath Fill\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * RbcSegmentsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSegmentsToPostScript(
    RbcPsToken * tokenPtr,
    register XSegment * segPtr,
    int nSegments)
{
    register int i;

    for(i = 0; i < nSegments; i++, segPtr++) {
        RbcFormatToPostScript(tokenPtr, "%d %d moveto\n",
            segPtr->x1, segPtr->y1);
        RbcFormatToPostScript(tokenPtr, " %d %d lineto\n",
            segPtr->x2, segPtr->y2);
        RbcAppendToPostScript(tokenPtr, "DashesProc stroke\n", (char *)NULL);
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcRectanglesToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcRectanglesToPostScript(
    RbcPsToken * tokenPtr,
    XRectangle rectArr[],
    int nRects)
{
    register int i;

    for(i = 0; i < nRects; i++) {
        RbcRectangleToPostScript(tokenPtr,
            (double)rectArr[i].x, (double)rectArr[i].y,
            (int)rectArr[i].width, (int)rectArr[i].height);
    }
}

#ifndef TK_RELIEF_SOLID
#define TK_RELIEF_SOLID		-1      /* Set the an impossible value. */
#endif /* TK_RELIEF_SOLID */

/*
 *--------------------------------------------------------------
 *
 * RbcDraw3DRectangleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDraw3DRectangleToPostScript(
    RbcPsToken * tokenPtr,
    Tk_3DBorder border,        /* Token for border to draw. */
    double x,                  /* Coordinates of rectangle */
    double y,                  /* Coordinates of rectangle */
    int width,                 /* Region to be drawn. */
    int height,                /* Region to be drawn. */
    int borderWidth,           /* Desired width for border, in pixels. */
    int relief)
{              /* Should be either TK_RELIEF_RAISED or
                * TK_RELIEF_SUNKEN;  indicates position of
                * interior of window relative to exterior. */
    TkBorder *borderPtr = (TkBorder *) border;
    XColor lightColor, darkColor;
    XColor *lightColorPtr, *darkColorPtr;
    XColor *topColor, *bottomColor;
    RbcPoint2D points[7];
    int twiceWidth = (borderWidth * 2);

    if((width < twiceWidth) || (height < twiceWidth)) {
        return;
    }
    if((relief == TK_RELIEF_SOLID) || (borderPtr->lightColorPtr == NULL)
        || (borderPtr->darkColorPtr == NULL)) {
        if(relief == TK_RELIEF_SOLID) {
            darkColor.red = darkColor.blue = darkColor.green = 0x00;
            lightColor.red = lightColor.blue = lightColor.green = 0x00;
            relief = TK_RELIEF_SUNKEN;
        } else {
    Screen *screenPtr;

            lightColor = *borderPtr->bgColorPtr;
            screenPtr = Tk_Screen(tokenPtr->tkwin);
            if(lightColor.pixel == WhitePixelOfScreen(screenPtr)) {
                darkColor.red = darkColor.blue = darkColor.green = 0x00;
            } else {
                darkColor.red = darkColor.blue = darkColor.green = 0xFF;
            }
        }
        lightColorPtr = &lightColor;
        darkColorPtr = &darkColor;
    } else {
        lightColorPtr = borderPtr->lightColorPtr;
        darkColorPtr = borderPtr->darkColorPtr;
    }

    /*
     * Handle grooves and ridges with recursive calls.
     */

    if((relief == TK_RELIEF_GROOVE) || (relief == TK_RELIEF_RIDGE)) {
    int halfWidth, insideOffset;

        halfWidth = borderWidth / 2;
        insideOffset = borderWidth - halfWidth;
        RbcDraw3DRectangleToPostScript(tokenPtr, border, (double)x, (double)y,
            width, height, halfWidth,
            (relief == TK_RELIEF_GROOVE) ? TK_RELIEF_SUNKEN : TK_RELIEF_RAISED);
        RbcDraw3DRectangleToPostScript(tokenPtr, border,
            (double)(x + insideOffset), (double)(y + insideOffset),
            width - insideOffset * 2, height - insideOffset * 2, halfWidth,
            (relief == TK_RELIEF_GROOVE) ? TK_RELIEF_RAISED : TK_RELIEF_SUNKEN);
        return;
    }
    if(relief == TK_RELIEF_RAISED) {
        topColor = lightColorPtr;
        bottomColor = darkColorPtr;
    } else if(relief == TK_RELIEF_SUNKEN) {
        topColor = darkColorPtr;
        bottomColor = lightColorPtr;
    } else {
        topColor = bottomColor = borderPtr->bgColorPtr;
    }
    RbcBackgroundToPostScript(tokenPtr, bottomColor);
    RbcRectangleToPostScript(tokenPtr, x, y + height - borderWidth, width,
        borderWidth);
    RbcRectangleToPostScript(tokenPtr, x + width - borderWidth, y,
        borderWidth, height);
    points[0].x = points[1].x = points[6].x = x;
    points[0].y = points[6].y = y + height;
    points[1].y = points[2].y = y;
    points[2].x = x + width;
    points[3].x = x + width - borderWidth;
    points[3].y = points[4].y = y + borderWidth;
    points[4].x = points[5].x = x + borderWidth;
    points[5].y = y + height - borderWidth;
    if(relief != TK_RELIEF_FLAT) {
        RbcBackgroundToPostScript(tokenPtr, topColor);
    }
    RbcPolygonToPostScript(tokenPtr, points, 7);
}

/*
 *--------------------------------------------------------------
 *
 * RbcFill3DRectangleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcFill3DRectangleToPostScript(
    RbcPsToken * tokenPtr,
    Tk_3DBorder border,        /* Token for border to draw. */
    double x,                  /* Coordinates of top-left of border area */
    double y,                  /* Coordinates of top-left of border area */
    int width,                 /* Dimension of border to be drawn. */
    int height,                /* Dimension of border to be drawn. */
    int borderWidth,           /* Desired width for border, in pixels. */
    int relief)
{              /* Should be either TK_RELIEF_RAISED or
                * TK_RELIEF_SUNKEN;  indicates position of
                * interior of window relative to exterior. */
    TkBorder *borderPtr = (TkBorder *) border;

    /*
     * I'm assuming that the rectangle is to be drawn as a background.
     * Setting the pen color as foreground or background only affects
     * the plot when the colormode option is "monochrome".
     */
    RbcBackgroundToPostScript(tokenPtr, borderPtr->bgColorPtr);
    RbcRectangleToPostScript(tokenPtr, x, y, width, height);
    RbcDraw3DRectangleToPostScript(tokenPtr, border, x, y, width, height,
        borderWidth, relief);
}

/*
 *--------------------------------------------------------------
 *
 * RbcStippleToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcStippleToPostScript(
    RbcPsToken * tokenPtr,
    Display * display,
    Pixmap bitmap)
{
int width, height;

    Tk_SizeOfBitmap(display, bitmap, &width, &height);
    RbcFormatToPostScript(tokenPtr, "gsave\n  clip\n  %d %d\n", width, height);
    RbcBitmapDataToPostScript(tokenPtr, display, bitmap, width, height);
    RbcAppendToPostScript(tokenPtr, "  StippleFill\ngrestore\n", (char *)NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcColorImageToPostScript --
 *
 *      Translates a color image into 3 component RGB PostScript output.
 *      Uses PS Language Level 2 operator "colorimage".
 *
 * Results:
 *      The dynamic string will contain the PostScript output.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcColorImageToPostScript(
    RbcPsToken * tokenPtr,
    RbcColorImage * image,
    double x,
    double y)
{
    int width, height;
    int tmpSize;

    width = image->width;
    height = image->height;

    tmpSize = width;
    if(tokenPtr->colorMode == PS_MODE_COLOR) {
        tmpSize *= 3;
    }
    RbcFormatToPostScript(tokenPtr, "\n/tmpStr %d string def\n", tmpSize);
    RbcAppendToPostScript(tokenPtr, "gsave\n", (char *)NULL);
    RbcFormatToPostScript(tokenPtr, "  %g %g translate\n", x, y);
    RbcFormatToPostScript(tokenPtr, "  %d %d scale\n", width, height);
    RbcFormatToPostScript(tokenPtr, "  %d %d 8\n", width, height);
    RbcFormatToPostScript(tokenPtr, "  [%d 0 0 %d 0 %d] ", width, -height,
        height);
    RbcAppendToPostScript(tokenPtr,
        "{\n    currentfile tmpStr readhexstring pop\n  } ", (char *)NULL);
    if(tokenPtr->colorMode != PS_MODE_COLOR) {
        RbcAppendToPostScript(tokenPtr, "image\n", (char *)NULL);
        RbcColorImageToGreyscale(image);
        RbcColorImageToPsData(image, 1, &(tokenPtr->dString), " ");
    } else {
        RbcAppendToPostScript(tokenPtr, "false 3 colorimage\n", (char *)NULL);
        RbcColorImageToPsData(image, 3, &(tokenPtr->dString), " ");
    }
    RbcAppendToPostScript(tokenPtr, "\ngrestore\n\n", (char *)NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcWindowToPostScript --
 *
 *      Converts a Tk window to PostScript.  If the window could not
 *      be "snapped", then a grey rectangle is drawn in its place.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcWindowToPostScript(
    RbcPsToken * tokenPtr,
    Tk_Window tkwin,
    double x,
    double y)
{
    RbcColorImage *image;
    int width, height;

    width = Tk_Width(tkwin);
    height = Tk_Height(tkwin);
    image =
        RbcDrawableToColorImage(tkwin, Tk_WindowId(tkwin), 0, 0, width, height,
        1.0 /*gamma */ );
    if(image == NULL) {
        /* Can't grab window image so paint the window area grey */
        RbcAppendToPostScript(tokenPtr, "% Can't grab window \"",
            Tk_PathName(tkwin), "\"\n", (char *)NULL);
        RbcAppendToPostScript(tokenPtr, "0.5 0.5 0.5 SetBgColor\n",
            (char *)NULL);
        RbcRectangleToPostScript(tokenPtr, x, y, width, height);
        return;
    }
    RbcColorImageToPostScript(tokenPtr, image, x, y);
    RbcFreeColorImage(image);
}

/*
 * -------------------------------------------------------------------------
 *
 * RbcPhotoToPostScript --
 *
 *      Output a PostScript image string of the given photo image.
 *      The photo is first converted into a color image and then
 *      translated into PostScript.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The PostScript output representing the photo is appended to
 *      the tokenPtr's dynamic string.
 *
 * -------------------------------------------------------------------------
 */
void
RbcPhotoToPostScript(
    RbcPsToken * tokenPtr,
    Tk_PhotoHandle photo,
    double x,                  /* Origin of photo image */
    double y)
{              /* Origin of photo image */
    RbcColorImage *image;

    image = RbcPhotoToColorImage(photo);
    RbcColorImageToPostScript(tokenPtr, image, x, y);
    RbcFreeColorImage(image);
}

/*
 * -----------------------------------------------------------------
 *
 * RbcFontToPostScript --
 *
 *      Map the Tk font to a PostScript font and point size.
 *
 *      If a Tcl array variable was specified, each element should be
 *      indexed by the X11 font name and contain a list of 1-2
 *      elements; the PostScript font name and the desired point size.
 *      The point size may be omitted and the X font point size will
 *      be used.
 *
 *      Otherwise, if the foundry is "Adobe", we try to do a plausible
 *      mapping looking at the full name of the font and building a
 *      string in the form of "Family-TypeFace".
 *
 * Returns:
 *      None.
 *
 * Side Effects:
 *      PostScript commands are output to change the type and the
 *      point size of the current font.
 *
 * -----------------------------------------------------------------
 */
void
RbcFontToPostScript(
    RbcPsToken * tokenPtr,
    Tk_Font font)
{              /* Tk font to query about */
XFontStruct *fontPtr = (XFontStruct *) font;
Tcl_Interp *interp = tokenPtr->interp;
const char *fontName;
double pointSize;
Tk_Uid family;
register int i;

    fontName = Tk_NameOfFont(font);
    pointSize = 12.0;
    /*
     * Use the font variable information if it exists.
     */
    if(tokenPtr->fontVarName != NULL) {
char *fontInfo;

        fontInfo = (char *)Tcl_GetVar2(interp, tokenPtr->fontVarName, fontName,
            0);
        if(fontInfo != NULL) {
int nProps;
const char **propArr = NULL;

            if(Tcl_SplitList(interp, fontInfo, &nProps, &propArr) == TCL_OK) {
int newSize;

                fontName = propArr[0];
                if((nProps == 2) &&
                    (Tcl_GetInt(interp, propArr[1], &newSize) == TCL_OK)) {
                    pointSize = (double)newSize;
                }
            }
            RbcFormatToPostScript(tokenPtr,
                "%g /%s SetFont\n", pointSize, fontName);
            if(propArr != (const char **)NULL) {
                ckfree((char *)propArr);        /*TODO really delete here? */
            }
            return;
        }
    }

    /*
     * Otherwise do a quick test to see if it's a PostScript font.
     * Tk_PostScriptFontName will silently generate a bogus PostScript
     * font description, so we have to check to see if this is really a
     * PostScript font.
     */
    family = ((TkFont *) fontPtr)->fa.family;
    for(i = 0; i < nFontNames; i++) {
        if(strncasecmp(psFontMap[i].alias, family, strlen(psFontMap[i].alias))
            == 0) {
Tcl_DString dString;

            Tcl_DStringInit(&dString);
            pointSize = (double)Tk_PostscriptFontName(font, &dString);
            fontName = Tcl_DStringValue(&dString);
            RbcFormatToPostScript(tokenPtr, "%g /%s SetFont\n", pointSize,
                fontName);
            Tcl_DStringFree(&dString);
            return;
        }
    }

    /*
     * Can't find it. Try to use the current point size.
     */
    fontName = NULL;
    pointSize = 12.0;

#ifndef  _WIN32
    /* Can you believe what I have to go through to get an XFontStruct? */
    fontPtr = XLoadQueryFont(Tk_Display(tokenPtr->tkwin), Tk_NameOfFont(font));
    if(fontPtr != NULL) {
unsigned long fontProp;

        if(XGetFontProperty(fontPtr, XA_POINT_SIZE, &fontProp) != False) {
            pointSize = (double)fontProp / 10.0;
        }
        fontName = XFontStructToPostScript(tokenPtr->tkwin, fontPtr);
        XFreeFont(Tk_Display(tokenPtr->tkwin), fontPtr);
    }
#endif /* !_WIN32 */
    if((fontName == NULL) || (fontName[0] == '\0')) {
        fontName = "Helvetica-Bold";    /* Defaulting to a known PS font */
    }
    RbcFormatToPostScript(tokenPtr, "%g /%s SetFont\n", pointSize, fontName);
}

/*
 *--------------------------------------------------------------
 *
 * TextLayoutToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
TextLayoutToPostScript(
    RbcPsToken * tokenPtr,
    int x,
    int y,
    RbcTextLayout * textPtr)
{
    char *src, *dst, *end;
    int count;                 /* Counts the # of bytes written to
                                * the intermediate scratch buffer. */
    RbcTextFragment *fragPtr;
    int i;
    unsigned char c;
#if HAVE_UTF
    Tcl_UniChar ch;
#endif
    int limit;

    limit = (BUFSIZ * 2) - 5;   /* High water mark for the scratch
                                 * buffer. */
    fragPtr = textPtr->fragArr;
    for(i = 0; i < textPtr->nFrags; i++, fragPtr++) {
        if(fragPtr->count < 1) {
            continue;
        }
        RbcAppendToPostScript(tokenPtr, "(", (char *)NULL);
        count = 0;
        dst = tokenPtr->scratchArr;
        src = fragPtr->text;
        end = fragPtr->text + fragPtr->count;
        while(src < end) {
            if(count > limit) {
                /* Don't let the scatch buffer overflow */
                dst = tokenPtr->scratchArr;
                dst[count] = '\0';
                RbcAppendToPostScript(tokenPtr, dst, (char *)NULL);
                count = 0;
            }
#if HAVE_UTF
            /*
             * INTL: For now we just treat the characters as binary
             * data and display the lower byte.  Eventually this should
             * be revised to handle international postscript fonts.
             */
            src += Tcl_UtfToUniChar(src, &ch);
            c = (unsigned char)(ch & 0xff);
#else
            c = *src++;
#endif

            if((c == '\\') || (c == '(') || (c == ')')) {
                /*
                 * If special PostScript characters characters "\", "(",
                 * and ")" are contained in the text string, prepend
                 * backslashes to them.
                 */
                *dst++ = '\\';
                *dst++ = c;
                count += 2;
            } else if((c < ' ') || (c > '~')) {
                /*
                 * Present non-printable characters in their octal
                 * representation.
                 */
                sprintf(dst, "\\%03o", c);
                dst += 4;
                count += 4;
            } else {
                *dst++ = c;
                count++;
            }
        }
        tokenPtr->scratchArr[count] = '\0';
        RbcAppendToPostScript(tokenPtr, tokenPtr->scratchArr, (char *)NULL);
        RbcFormatToPostScript(tokenPtr, ") %d %d %d DrawAdjText\n",
            fragPtr->width, x + fragPtr->x, y + fragPtr->y);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcTextToPostScript --
 *
 *      Output PostScript commands to print a text string. The string
 *      may be rotated at any arbitrary angle, and placed according
 *      the anchor type given. The anchor indicates how to interpret
 *      the window coordinates as an anchor for the text bounding box.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Text string is drawn using the given font and GC on the graph
 *      window at the given coordinates, anchor, and rotation
 *
 * -----------------------------------------------------------------
 */
void
RbcTextToPostScript(
    RbcPsToken * tokenPtr,
    char *string,              /* String to convert to PostScript */
    RbcTextStyle * tsPtr,      /* Text attribute information */
    double x,                  /* Window coordinates where to print text */
    double y)
{              /* Window coordinates where to print text */
    double theta;
    double rotWidth, rotHeight;
    RbcTextLayout *textPtr;
    RbcPoint2D anchorPos;

    if((string == NULL) || (*string == '\0')) { /* Empty string, do nothing */
        return;
    }
    theta = FMOD(tsPtr->theta, (double)360.0);
    textPtr = RbcGetTextLayout(string, tsPtr);
    RbcGetBoundingBox(textPtr->width, textPtr->height, theta, &rotWidth,
        &rotHeight, (RbcPoint2D *) NULL);
    /*
     * Find the center of the bounding box
     */
    anchorPos.x = x, anchorPos.y = y;
    anchorPos =
        RbcTranslatePoint(&anchorPos, ROUND(rotWidth), ROUND(rotHeight),
        tsPtr->anchor);
    anchorPos.x += (rotWidth * 0.5);
    anchorPos.y += (rotHeight * 0.5);

    /* Initialize text (sets translation and rotation) */
    RbcFormatToPostScript(tokenPtr, "%d %d %g %g %g BeginText\n",
        textPtr->width, textPtr->height, tsPtr->theta, anchorPos.x,
        anchorPos.y);

    RbcFontToPostScript(tokenPtr, tsPtr->font);

    /* All coordinates are now relative to what was set by BeginText */
    if((tsPtr->shadow.offset > 0) && (tsPtr->shadow.color != NULL)) {
        RbcForegroundToPostScript(tokenPtr, tsPtr->shadow.color);
        TextLayoutToPostScript(tokenPtr, tsPtr->shadow.offset,
            tsPtr->shadow.offset, textPtr);
    }
    RbcForegroundToPostScript(tokenPtr,
        (tsPtr->state & RBC_STATE_ACTIVE) ? tsPtr->activeColor : tsPtr->color);
    TextLayoutToPostScript(tokenPtr, 0, 0, textPtr);
    ckfree((char *)textPtr);
    RbcAppendToPostScript(tokenPtr, "EndText\n", (char *)NULL);
}

/*
 * -----------------------------------------------------------------
 *
 * RbcLineToPostScript --
 *
 *      Outputs PostScript commands to print a multi-segmented line.
 *      It assumes a procedure DashesProc was previously defined.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Segmented line is printed.
 *
 * -----------------------------------------------------------------
 */
void
RbcLineToPostScript(
    RbcPsToken * tokenPtr,
    register XPoint * pointPtr,
    int nPoints)
{
    register int i;

    if(nPoints <= 0) {
        return;
    }
    RbcFormatToPostScript(tokenPtr, " newpath %d %d moveto\n",
        pointPtr->x, pointPtr->y);
    pointPtr++;
    for(i = 1; i < (nPoints - 1); i++, pointPtr++) {
        RbcFormatToPostScript(tokenPtr, " %d %d lineto\n",
            pointPtr->x, pointPtr->y);
        if((i % PS_MAXPATH) == 0) {
            RbcFormatToPostScript(tokenPtr,
                "DashesProc stroke\n newpath  %d %d moveto\n",
                pointPtr->x, pointPtr->y);
        }
    }
    RbcFormatToPostScript(tokenPtr, " %d %d lineto\n",
        pointPtr->x, pointPtr->y);
    RbcAppendToPostScript(tokenPtr, "DashesProc stroke\n", (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * RbcBitmapToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcBitmapToPostScript(
    RbcPsToken * tokenPtr,
    Display * display,
    Pixmap bitmap,             /* Bitmap to be converted to PostScript */
    double scaleX,
    double scaleY)
{
    int width, height;
    double scaledWidth, scaledHeight;

    Tk_SizeOfBitmap(display, bitmap, &width, &height);
    scaledWidth = (double)width *scaleX;
    scaledHeight = (double)height *scaleY;
    RbcAppendToPostScript(tokenPtr, "  gsave\n", (char *)NULL);
    RbcFormatToPostScript(tokenPtr, "    %g %g translate\n",
        scaledWidth * -0.5, scaledHeight * 0.5);
    RbcFormatToPostScript(tokenPtr, "    %g %g scale\n",
        scaledWidth, -scaledHeight);
    RbcFormatToPostScript(tokenPtr, "    %d %d true [%d 0 0 %d 0 %d] {",
        width, height, width, -height, height);
    RbcBitmapDataToPostScript(tokenPtr, display, bitmap, width, height);
    RbcAppendToPostScript(tokenPtr, "    } imagemask\n  grestore\n",
        (char *)NULL);
}

/*
 *--------------------------------------------------------------
 *
 * Rbc2DSegmentsToPostScript --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
Rbc2DSegmentsToPostScript(
    RbcPsToken * psToken,
    register RbcSegment2D * segPtr,
    int nSegments)
{
    register RbcSegment2D *endPtr;

    for(endPtr = segPtr + nSegments; segPtr < endPtr; segPtr++) {
        RbcFormatToPostScript(psToken, "%g %g moveto\n",
            segPtr->p.x, segPtr->p.y);
        RbcFormatToPostScript(psToken, " %g %g lineto\n",
            segPtr->q.x, segPtr->q.y);
        RbcAppendToPostScript(psToken, "DashesProc stroke\n", (char *)NULL);
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcSpline.c.








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcSpline.c --
 *
 *      TODO: Description
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

typedef double TriDiagonalMatrix[3];
typedef struct {
    double b, c, d;
} RbcCubic2D;

typedef struct {
    double b, c, d, e, f;
} RbcQuint2D;

typedef struct {
    double t;                  /* Arc length of interval. */
    double x;                  /* 2nd derivative of X with respect to T */
    double y;                  /* 2nd derivative of Y with respect to T */
} CubicSpline;

#define SQR(x)	((x)*(x))

/*
 * Quadratic spline parameters
 */
#define E1	param[0]
#define E2	param[1]
#define V1	param[2]
#define V2	param[3]
#define W1	param[4]
#define W2	param[5]
#define Z1	param[6]
#define Z2	param[7]
#define Y1	param[8]
#define Y2	param[9]

static Tcl_CmdProc SplineCmd;
static int Search(
    RbcPoint2D points[],
    int nPoints,
    double key,
    int *foundPtr);
static int QuadChoose(
    RbcPoint2D * p,
    RbcPoint2D * q,
    double m1,
    double m2,
    double epsilon);
static void QuadCases(
    RbcPoint2D * p,
    RbcPoint2D * q,
    double m1,
    double m2,
    double param[],
    int which);
static int QuadSelect(
    RbcPoint2D * p,
    RbcPoint2D * q,
    double m1,
    double m2,
    double epsilon,
    double param[]);
static double QuadGetImage(
    double p1,
    double p2,
    double p3,
    double x1,
    double x2,
    double x3);
static void QuadSpline(
    RbcPoint2D * intp,
    RbcPoint2D * left,
    RbcPoint2D * right,
    double param[],
    int ncase);
static void QuadSlopes(
    RbcPoint2D points[],
    double *m,
    int nPoints);
static int QuadEval(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts,
    double *m,
    double epsilon);
static int SolveCubic1(
    TriDiagonalMatrix A[],
    int n);
static void SolveCubic2(
    TriDiagonalMatrix A[],
    CubicSpline spline[],
    int nIntervals);
static CubicSpline *CubicSlopes(
    RbcPoint2D points[],
    int nPoints,
    int isClosed,
    double unitX,
    double unitY);
static int CubicEval(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts,
    CubicSpline spline[]);
static void CatromCoeffs(
    RbcPoint2D * p,
    RbcPoint2D * a,
    RbcPoint2D * b,
    RbcPoint2D * c,
    RbcPoint2D * d);

/*
 * -----------------------------------------------------------------------
 *
 * Search --
 *
 *      Conducts a binary search for a value.  This routine is called
 *      only if key is between x(0) and x(len - 1).
 *
 * Results:
 *      Returns the index of the largest value in xtab for which
 *      x[i] < key.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static int
Search(
    RbcPoint2D points[],       /* Contains the abscissas of the data
                                * points of interpolation. */
    int nPoints,               /* Dimension of x. */
    double key,                /* Value whose relative position in
                                * x is to be located. */
    int *foundPtr)
{              /* (out) Returns 1 if s is found in
                * x and 0 otherwise. */
    int high, low, mid;

    low = 0;
    high = nPoints - 1;

    while(high >= low) {
        mid = (high + low) / 2;
        if(key > points[mid].x) {
            low = mid + 1;
        } else if(key < points[mid].x) {
            high = mid - 1;
        } else {
            *foundPtr = 1;
            return mid;
        }
    }
    *foundPtr = 0;
    return low;
}

/*
 *-----------------------------------------------------------------------
 *
 * QuadChoose --
 *
 *      Determines the case needed for the computation of the parame-
 *      ters of the quadratic spline.
 *
 * Results:
 *      Returns a case number (1-4) which controls how the parameters
 *      of the quadratic spline are evaluated.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *-----------------------------------------------------------------------
 */
static int
QuadChoose(
    RbcPoint2D * p,            /* Coordinates of one of the points of
                                * interpolation */
    RbcPoint2D * q,            /* Coordinates of one of the points of
                                * interpolation */
    double m1,                 /* Derivative condition at point P */
    double m2,                 /* Derivative condition at point Q */
    double epsilon)
{              /* Error tolerance used to distinguish
                * cases when m1 or m2 is relatively
                * close to the slope or twice the
                * slope of the line segment joining
                * the points P and Q.  If
                * epsilon is not 0.0, then epsilon
                * should be greater than or equal to
                * machine epsilon.  */
    double slope;

    /* Calculate the slope of the line joining P and Q. */
    slope = (q->y - p->y) / (q->x - p->x);

    if(slope != 0.0) {
    double relerr;
    double mref, mref1, mref2, prod1, prod2;

        prod1 = slope * m1;
        prod2 = slope * m2;

        /* Find the absolute values of the slopes slope, m1, and m2. */
        mref = FABS(slope);
        mref1 = FABS(m1);
        mref2 = FABS(m2);

        /*
         * If the relative deviation of m1 or m2 from slope is less than
         * epsilon, then choose case 2 or case 3.
         */
        relerr = epsilon * mref;
        if((FABS(slope - m1) > relerr) && (FABS(slope - m2) > relerr) &&
            (prod1 >= 0.0) && (prod2 >= 0.0)) {
    double prod;

            prod = (mref - mref1) * (mref - mref2);
            if(prod < 0.0) {
                /*
                 * l1, the line through (x1,y1) with slope m1, and l2,
                 * the line through (x2,y2) with slope m2, intersect
                 * at a point whose abscissa is between x1 and x2.
                 * The abscissa becomes a knot of the spline.
                 */
                return 1;
            }
            if(mref1 > (mref * 2.0)) {
                if(mref2 <= ((2.0 - epsilon) * mref)) {
                    return 3;
                }
            } else if(mref2 <= (mref * 2.0)) {
                /*
                 * Both l1 and l2 cross the line through
                 * (x1+x2)/2.0,y1 and (x1+x2)/2.0,y2, which is the
                 * midline of the rectangle formed by P and Q or both
                 * m1 and m2 have signs different than the sign of
                 * slope, or one of m1 and m2 has opposite sign from
                 * slope and l1 and l2 intersect to the left of x1 or
                 * to the right of x2.  The point (x1+x2)/2. is a knot
                 * of the spline.
                 */
                return 2;
            } else if(mref1 <= ((2.0 - epsilon) * mref)) {
                /*
                 * In cases 3 and 4, sign(m1)=sign(m2)=sign(slope).
                 * Either l1 or l2 crosses the midline, but not both.
                 * Choose case 4 if mref1 is greater than
                 * (2.-epsilon)*mref; otherwise, choose case 3.
                 */
                return 3;
            }
            /*
             * If neither l1 nor l2 crosses the midline, the spline
             * requires two knots between x1 and x2.
             */
            return 4;
        } else {
            /*
             * The sign of at least one of the slopes m1 or m2 does not
             * agree with the sign of *slope*.
             */
            if((prod1 < 0.0) && (prod2 < 0.0)) {
                return 2;
            } else if(prod1 < 0.0) {
                if(mref2 > ((epsilon + 1.0) * mref)) {
                    return 1;
                } else {
                    return 2;
                }
            } else if(mref1 > ((epsilon + 1.0) * mref)) {
                return 1;
            } else {
                return 2;
            }
        }
    } else if((m1 * m2) >= 0.0) {
        return 2;
    } else {
        return 1;
    }
}

/*
 * -----------------------------------------------------------------------
 *
 * QuadCases --
 *
 *       Computes the knots and other parameters of the spline on the
 *       interval PQ.
 *
 *
 *       On input--
 *
 *         P and Q    the coordinates of the points of interpolation.
 *         m1         the slope at P.
 *         m2         the slope at Q.
 *         ncase      controls the number and location of the knots.
 *
 *
 *      On output--
 *
 *        (v1,v2),(w1,w2),(z1,z2), (e1,e2)    the coordinates of the
 *                                            knots and other
 *                                            parameters of the spline
 *                                            on P.  (e1,e2) and Q
 *                                            are used only if ncase=4.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static void
QuadCases(
    RbcPoint2D * p,
    RbcPoint2D * q,
    double m1,
    double m2,
    double param[],
    int which)
{
    if((which == 3) || (which == 4)) {  /* Parameters used in both 3 and 4 */
    double mbar1, mbar2, mbar3, c1, d1, h1, j1, k1;

        c1 = p->x + (q->y - p->y) / m1;
        d1 = q->x + (p->y - q->y) / m2;
        h1 = c1 * 2.0 - p->x;
        j1 = d1 * 2.0 - q->x;
        mbar1 = (q->y - p->y) / (h1 - p->x);
        mbar2 = (p->y - q->y) / (j1 - q->x);

        if(which == 4) {        /* Case 4. */
            Y1 = (p->x + c1) / 2.0;
            V1 = (p->x + Y1) / 2.0;
            V2 = m1 * (V1 - p->x) + p->y;
            Z1 = (d1 + q->x) / 2.0;
            W1 = (q->x + Z1) / 2.0;
            W2 = m2 * (W1 - q->x) + q->y;
            mbar3 = (W2 - V2) / (W1 - V1);
            Y2 = mbar3 * (Y1 - V1) + V2;
            Z2 = mbar3 * (Z1 - V1) + V2;
            E1 = (Y1 + Z1) / 2.0;
            E2 = mbar3 * (E1 - V1) + V2;
        } else {        /* Case 3. */
            k1 = (p->y - q->y + q->x * mbar2 - p->x * mbar1) / (mbar2 - mbar1);
            if(FABS(m1) > FABS(m2)) {
                Z1 = (k1 + p->x) / 2.0;
            } else {
                Z1 = (k1 + q->x) / 2.0;
            }
            V1 = (p->x + Z1) / 2.0;
            V2 = p->y + m1 * (V1 - p->x);
            W1 = (q->x + Z1) / 2.0;
            W2 = q->y + m2 * (W1 - q->x);
            Z2 = V2 + (W2 - V2) / (W1 - V1) * (Z1 - V1);
        }
    } else if(which == 2) {     /* Case 2. */
        Z1 = (p->x + q->x) / 2.0;
        V1 = (p->x + Z1) / 2.0;
        V2 = p->y + m1 * (V1 - p->x);
        W1 = (Z1 + q->x) / 2.0;
        W2 = q->y + m2 * (W1 - q->x);
        Z2 = (V2 + W2) / 2.0;
    } else {   /* Case 1. */
    double ztwo;

        Z1 = (p->y - q->y + m2 * q->x - m1 * p->x) / (m2 - m1);
        ztwo = p->y + m1 * (Z1 - p->x);
        V1 = (p->x + Z1) / 2.0;
        V2 = (p->y + ztwo) / 2.0;
        W1 = (Z1 + q->x) / 2.0;
        W2 = (ztwo + q->y) / 2.0;
        Z2 = V2 + (W2 - V2) / (W1 - V1) * (Z1 - V1);
    }
}

/*
 *--------------------------------------------------------------
 *
 * QuadSelect --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
QuadSelect(
    RbcPoint2D * p,
    RbcPoint2D * q,
    double m1,
    double m2,
    double epsilon,
    double param[])
{
    int ncase;

    ncase = QuadChoose(p, q, m1, m2, epsilon);
    QuadCases(p, q, m1, m2, param, ncase);
    return ncase;
}

/*
 *--------------------------------------------------------------
 *
 * QuadGetImage --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
QuadGetImage(
    double p1,
    double p2,
    double p3,
    double x1,
    double x2,
    double x3)
{
    double A, B, C;
    double y;

    A = x1 - x2;
    B = x2 - x3;
    C = x1 - x3;

    y = (p1 * (A * A) + p2 * 2.0 * B * A + p3 * (B * B)) / (C * C);
    return y;
}

/*
 * -----------------------------------------------------------------------
 *
 * QuadSpline --
 *
 *      Finds the image of a point in x.
 *
 *      On input
 *
 *        x                             Contains the value at which
 *                                      the spline is evaluated.
 *        leftX, leftY                  Coordinates of the left-hand
 *                                      data point used in the
 *                                      evaluation of x values.
 *        rightX, rightY                Coordinates of the right-hand
 *                                      data point used in the
 *                                      evaluation of x values.
 *        Z1, Z2, Y1, Y2, E2, W2, V2    Parameters of the spline.
 *        ncase                         Controls the evaluation of
 *                                      the spline by indicating
 *                                      whether one or two knots
 *                                      were placed in the interval
 *                                      (xtabs,xtabs1).
 *
 * Results:
 *      The image of the spline at x.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static void
QuadSpline(
    RbcPoint2D * intp,         /* Value at which spline is evaluated */
    RbcPoint2D * left,         /* Point to the left of the data point to
                                * be evaluated */
    RbcPoint2D * right,        /* Point to the right of the data point to
                                * be evaluated */
    double param[],            /* Parameters of the spline */
    int ncase)
{              /* Controls the evaluation of the
                * spline by indicating whether one or
                * two knots were placed in the
                * interval (leftX,rightX) */
    double y;

    if(ncase == 4) {
        /*
         * Case 4:  More than one knot was placed in the interval.
         */

        /*
         * Determine the location of data point relative to the 1st knot.
         */
        if(Y1 > intp->x) {
            y = QuadGetImage(left->y, V2, Y2, Y1, intp->x, left->x);
        } else if(Y1 < intp->x) {
            /*
             * Determine the location of the data point relative to
             * the 2nd knot.
             */
            if(Z1 > intp->x) {
                y = QuadGetImage(Y2, E2, Z2, Z1, intp->x, Y1);
            } else if(Z1 < intp->x) {
                y = QuadGetImage(Z2, W2, right->y, right->x, intp->x, Z1);
            } else {
                y = Z2;
            }
        } else {
            y = Y2;
        }
    } else {

        /*
         * Cases 1, 2, or 3:
         *
         * Determine the location of the data point relative to the
         * knot.
         */
        if(Z1 < intp->x) {
            y = QuadGetImage(Z2, W2, right->y, right->x, intp->x, Z1);
        } else if(Z1 > intp->x) {
            y = QuadGetImage(left->y, V2, Z2, Z1, intp->x, left->x);
        } else {
            y = Z2;
        }
    }
    intp->y = y;
}

/*
 * -----------------------------------------------------------------------
 *
 * QuadSlopes --
 *
 *       Calculates the derivative at each of the data points.  The
 *       slopes computed will insure that an osculatory quadratic
 *       spline will have one additional knot between two adjacent
 *       points of interpolation.  Convexity and monotonicity are
 *       preserved wherever these conditions are compatible with the
 *       data.
 *
 * Results:
 *      The output array "m" is filled with the derivates at each
 *      data point.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static void
QuadSlopes(
    RbcPoint2D points[],
    double *m,                 /* (out) To be filled with the first
                                * derivative at each data point. */
    int nPoints)
{              /* Number of data points (dimension of
                * x, y, and m). */
    double xbar, xmid, xhat, ydif1, ydif2;
    double yxmid;
    double m1, m2;
    double m1s, m2s;
    register int i, n, l;

    m1s = m2s = m1 = m2 = 0;
    for(l = 0, i = 1, n = 2; i < (nPoints - 1); l++, i++, n++) {
        /*
         * Calculate the slopes of the two lines joining three
         * consecutive data points.
         */
        ydif1 = points[i].y - points[l].y;
        ydif2 = points[n].y - points[i].y;
        m1 = ydif1 / (points[i].x - points[l].x);
        m2 = ydif2 / (points[n].x - points[i].x);
        if(i == 1) {
            m1s = m1, m2s = m2; /* Save slopes of starting point */
        }
        /*
         * If one of the preceding slopes is zero or if they have opposite
         * sign, assign the value zero to the derivative at the middle
         * point.
         */
        if((m1 == 0.0) || (m2 == 0.0) || ((m1 * m2) <= 0.0)) {
            m[i] = 0.0;
        } else if(FABS(m1) > FABS(m2)) {
            /*
             * Calculate the slope by extending the line with slope m1.
             */
            xbar = ydif2 / m1 + points[i].x;
            xhat = (xbar + points[n].x) / 2.0;
            m[i] = ydif2 / (xhat - points[i].x);
        } else {
            /*
             * Calculate the slope by extending the line with slope m2.
             */
            xbar = -ydif1 / m2 + points[i].x;
            xhat = (points[l].x + xbar) / 2.0;
            m[i] = ydif1 / (points[i].x - xhat);
        }
    }

    /* Calculate the slope at the last point, x(n). */
    i = nPoints - 2;
    n = nPoints - 1;
    if((m1 * m2) < 0.0) {
        m[n] = m2 * 2.0;
    } else {
        xmid = (points[i].x + points[n].x) / 2.0;
        yxmid = m[i] * (xmid - points[i].x) + points[i].y;
        m[n] = (points[n].y - yxmid) / (points[n].x - xmid);
        if((m[n] * m2) < 0.0) {
            m[n] = 0.0;
        }
    }

    /* Calculate the slope at the first point, x(0). */
    if((m1s * m2s) < 0.0) {
        m[0] = m1s * 2.0;
    } else {
        xmid = (points[0].x + points[1].x) / 2.0;
        yxmid = m[1] * (xmid - points[1].x) + points[1].y;
        m[0] = (yxmid - points[0].y) / (xmid - points[0].x);
        if((m[0] * m1s) < 0.0) {
            m[0] = 0.0;
        }
    }

}

/*
 *--------------------------------------------------------------
 *
 * QuadEval --
 *
 *      QuadEval controls the evaluation of an osculatory
 *      quadratic spline.  The user may provide his own
 *      slopes at the points of interpolation or use the
 *      subroutine 'QuadSlopes' to calculate slopes which
 *      are consistent with the shape of the data.
 *
 *      ON INPUT--
 *
 *        intpPts      must be a nondecreasing vector of
 *                     points at which the spline will be
 *                     evaluated.
 *        origPts      contains the abscissas of the data
 *                     points to be interpolated. xtab must
 *                     be increasing.
 *        y            contains the ordinates of the data
 *                     points to be interpolated.
 *        m            contains the slope of the spline at
 *                     each point of interpolation.
 *        nPoints      number of data points (dimension of
 *                     xtab and y).
 *        numEval      the number of points of evaluation
 *                     (dimension of xval and yval).
 *        epsilon      a relative error tolerance used in
 *                     subroutine 'QuadChoose' to distinguish
 *                     the situation m(i) or m(i+1) is
 *                     relatively close to the slope or twice
 *                     the slope of the linear segment
 *                     between xtab(i) and xtab(i+1).  If
 *                     this situation occurs, roundoff may
 *                     cause a change in convexity or
 *                     monotonicity of the resulting spline
 *                     and a change in the case number
 *                     provided by 'QuadChoose'.  If epsilon
 *                     is not equal to zero, then epsilon
 *                     should be greater than or equal to
 *                     machine epsilon.
 *
 *      ON OUTPUT--
 *        yval         contains the images of the points in
 *                     xval.
 *        err          one of the following error codes:
 *                       0 - QuadEval ran normally.
 *                       1 - xval(i) is less than xtab(1)
 *                           for at least one i or xval(i)
 *                           is greater than xtab(num) for
 *                           at least one i. QuadEval will
 *                           extrapolate to provide function
 *                           values for these abscissas.
 *                       2 - xval(i+1) < xval(i) for some i.
 *
 *      QuadEval calls the following subroutines or functions:
 *
 *        Search
 *        QuadCases
 *        QuadChoose
 *        QuadSpline
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
QuadEval(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts,
    double *m,                 /* Slope of the spline at each point
                                * of interpolation. */
    double epsilon)
{              /* Relative error tolerance (see choose) */
    int error;
    register int i, j;
    double param[10];
    int ncase;
    int start, end;
    int l, p;
    register int n;
    int found;

    /* Initialize indices and set error result */
    error = 0;
    l = nOrigPts - 1;
    p = l - 1;
    ncase = 1;

    /*
     * Determine if abscissas of new vector are non-decreasing.
     */
    for(j = 1; j < nIntpPts; j++) {
        if(intpPts[j].x < intpPts[j - 1].x) {
            return 2;
        }
    }
    /*
     * Determine if any of the points in xval are LESS than the
     * abscissa of the first data point.
     */
    for(start = 0; start < nIntpPts; start++) {
        if(intpPts[start].x >= origPts[0].x) {
            break;
        }
    }
    /*
     * Determine if any of the points in xval are GREATER than the
     * abscissa of the l data point.
     */
    for(end = nIntpPts - 1; end >= 0; end--) {
        if(intpPts[end].x <= origPts[l].x) {
            break;
        }
    }

    if(start > 0) {
        error = 1;      /* Set error value to indicate that
                         * extrapolation has occurred. */
        /*
         * Calculate the images of points of evaluation whose abscissas
         * are less than the abscissa of the first data point.
         */
        ncase = QuadSelect(origPts, origPts + 1, m[0], m[1], epsilon, param);
        for(j = 0; j < (start - 1); j++) {
            QuadSpline(intpPts + j, origPts, origPts + 1, param, ncase);
        }
        if(nIntpPts == 1) {
            return error;
        }
    }
    if((nIntpPts == 1) && (end != (nIntpPts - 1))) {
        goto noExtrapolation;
    }

    /*
     * Search locates the interval in which the first in-range
     * point of evaluation lies.
     */

    i = Search(origPts, nOrigPts, intpPts[start].x, &found);

    n = i + 1;
    if(n >= nOrigPts) {
        n = nOrigPts - 1;
        i = nOrigPts - 2;
    }
    /*
     * If the first in-range point of evaluation is equal to one
     * of the data points, assign the appropriate value from y.
     * Continue until a point of evaluation is found which is not
     * equal to a data point.
     */
    if(found) {
        do {
            intpPts[start].y = origPts[i].y;
            start++;
            if(start >= nIntpPts) {
                return error;
            }
        } while(intpPts[start - 1].x == intpPts[start].x);

        for(;;) {
            if(intpPts[start].x < origPts[n].x) {
                break;  /* Break out of for-loop */
            }
            if(intpPts[start].x == origPts[n].x) {
                do {
                    intpPts[start].y = origPts[n].y;
                    start++;
                    if(start >= nIntpPts) {
                        return error;
                    }
                } while(intpPts[start].x == intpPts[start - 1].x);
            }
            i++;
            n++;
        }
    }
    /*
     * Calculate the images of all the points which lie within
     * range of the data.
     */
    if((i > 0) || (error != 1)) {
        ncase = QuadSelect(origPts + i, origPts + n, m[i], m[n],
            epsilon, param);
    }
    for(j = start; j <= end; j++) {
        /*
         * If xx(j) - x(n) is negative, do not recalculate
         * the parameters for this section of the spline since
         * they are already known.
         */
        if(intpPts[j].x == origPts[n].x) {
            intpPts[j].y = origPts[n].y;
            continue;
        } else if(intpPts[j].x > origPts[n].x) {
    double delta;

            /* Determine that the routine is in the correct part of
             * the spline. */
            do {
                i++, n++;
                delta = intpPts[j].x - origPts[n].x;
            } while(delta > 0.0);

            if(delta < 0.0) {
                ncase = QuadSelect(origPts + i, origPts + n, m[i],
                    m[n], epsilon, param);
            } else if(delta == 0.0) {
                intpPts[j].y = origPts[n].y;
                continue;
            }
        }
        QuadSpline(intpPts + j, origPts + i, origPts + n, param, ncase);
    }

    if(end == (nIntpPts - 1)) {
        return error;
    }
    if((n == l) && (intpPts[end].x != origPts[l].x)) {
        goto noExtrapolation;
    }

    error = 1; /* Set error value to indicate that
                * extrapolation has occurred. */
    ncase = QuadSelect(origPts + p, origPts + l, m[p], m[l], epsilon, param);

  noExtrapolation:
    /*
     * Calculate the images of the points of evaluation whose
     * abscissas are greater than the abscissa of the last data point.
     */
    for(j = (end + 1); j < nIntpPts; j++) {
        QuadSpline(intpPts + j, origPts + p, origPts + l, param, ncase);
    }
    return error;
}

/*
 * -----------------------------------------------------------------------
 *
 *		  Shape preserving quadratic splines
 *		   by D.F.Mcallister & J.A.Roulier
 *		    Coded by S.L.Dodd & M.Roulier
 *			 N.C.State University
 *
 * -----------------------------------------------------------------------
 */

/*
 *--------------------------------------------------------------
 *
 * RbcQuadraticSpline --
 *
 *      Driver routine for quadratic spline package
 *
 *      On input--
 *
 *        X,Y    Contain n-long arrays of data (x is
 *               increasing)
 *        XM     Contains m-long array of x values
 *               (increasing)
 *        eps    Relative error tolerance
 *        n      Number of input data points
 *        m      Number of output data points
 *
 *      On output--
 *
 *        work   Contains the value of the first derivative
 *               at each data point
 *        ym     Contains the interpolated spline value at
 *               each data point
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcQuadraticSpline(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts)
{
    double epsilon;
    double *work;
    int result;

    work = (double *)ckalloc(nOrigPts * sizeof(double));
    assert(work);

    epsilon = 0.0;      /* TBA: adjust error via command-line option */
    /* allocate space for vectors used in calculation */
    QuadSlopes(origPts, work, nOrigPts);
    result = QuadEval(origPts, nOrigPts, intpPts, nIntpPts, work, epsilon);
    ckfree((char *)work);
    if(result > 1) {
        return FALSE;
    }
    return TRUE;
}

/*
 *--------------------------------------------------------------
 *
 * RbcNaturalSpline --
 *
 *      Reference:
 *
 *        Numerical Analysis, R. Burden, J. Faires
 *          and A. Reynolds.
 *        Prindle, Weber & Schmidt 1981 pp 112
 *
 *      Parameters:
 *
 *        origPts - vector of points, assumed to be
 *                  sorted along x.
 *        intpPts - vector of new points.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcNaturalSpline(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts)
{
    RbcCubic2D *eq;
    RbcPoint2D *iPtr, *endPtr;
    TriDiagonalMatrix *A;
    double *dx;                /* vector of deltas in x */
    double x, dy, alpha;
    int isKnot;
    register int i, j, n;

    dx = (double *)ckalloc(sizeof(double) * nOrigPts);
    /* Calculate vector of differences */
    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        dx[i] = origPts[j].x - origPts[i].x;
        if(dx[i] < 0.0) {
            return 0;
        }
    }
    n = nOrigPts - 1;   /* Number of intervals. */
    A = (TriDiagonalMatrix *) ckalloc(sizeof(TriDiagonalMatrix) * nOrigPts);
    if(A == NULL) {
        ckfree((char *)dx);
        return 0;
    }
    /* Vectors to solve the tridiagonal matrix */
    A[0][0] = A[n][0] = 1.0;
    A[0][1] = A[n][1] = 0.0;
    A[0][2] = A[n][2] = 0.0;

    /* Calculate the intermediate results */
    for(i = 0, j = 1; j < n; j++, i++) {
        alpha = 3.0 * ((origPts[j + 1].y / dx[j]) - (origPts[j].y / dx[i]) -
            (origPts[j].y / dx[j]) + (origPts[i].y / dx[i]));
        A[j][0] = 2 * (dx[j] + dx[i]) - dx[i] * A[i][1];
        A[j][1] = dx[j] / A[j][0];
        A[j][2] = (alpha - dx[i] * A[i][2]) / A[j][0];
    }
    eq = (RbcCubic2D *) ckalloc(sizeof(RbcCubic2D) * nOrigPts);

    if(eq == NULL) {
        ckfree((char *)A);
        ckfree((char *)dx);
        return FALSE;
    }
    eq[0].c = eq[n].c = 0.0;
    for(j = n, i = n - 1; i >= 0; i--, j--) {
        eq[i].c = A[i][2] - A[i][1] * eq[j].c;
        dy = origPts[i + 1].y - origPts[i].y;
        eq[i].b = (dy) / dx[i] - dx[i] * (eq[j].c + 2.0 * eq[i].c) / 3.0;
        eq[i].d = (eq[j].c - eq[i].c) / (3.0 * dx[i]);
    }
    ckfree((char *)A);
    ckfree((char *)dx);

    endPtr = intpPts + nIntpPts;
    /* Now calculate the new values */
    for(iPtr = intpPts; iPtr < endPtr; iPtr++) {
        iPtr->y = 0.0;
        x = iPtr->x;

        /* Is it outside the interval? */
        if((x < origPts[0].x) || (x > origPts[n].x)) {
            continue;
        }
        /* Search for the interval containing x in the point array */
        i = Search(origPts, nOrigPts, x, &isKnot);
        if(isKnot) {
            iPtr->y = origPts[i].y;
        } else {
            i--;
            x -= origPts[i].x;
            iPtr->y = origPts[i].y +
                x * (eq[i].b + x * (eq[i].c + x * eq[i].d));
        }
    }
    ckfree((char *)eq);
    return TRUE;
}

static RbcOpSpec splineOps[] = {
    {"natural", 1, (RbcOp) RbcNaturalSpline, 6, 6, "x y splx sply",},
    {"quadratic", 1, (RbcOp) RbcQuadraticSpline, 6, 6, "x y splx sply",},
};

static int nSplineOps = sizeof(splineOps) / sizeof(RbcOpSpec);

/*
 *--------------------------------------------------------------
 *
 * SplineCmd --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
SplineCmd(
    ClientData clientData,     /* Not used. */
    Tcl_Interp * interp,
    int argc,
    const char *argv[])
{
    RbcOp proc;
    Rbc_Vector *x, *y, *splX, *splY;
    double *xArr, *yArr;
    register int i;
    RbcPoint2D *origPts, *intpPts;
    int nOrigPts, nIntpPts;

    proc = RbcGetOp(interp, nSplineOps, splineOps, RBC_OP_ARG1, argc, argv, 0);
    if(proc == NULL) {
        return TCL_ERROR;
    }
    if((Rbc_GetVector(interp, argv[2], &x) != TCL_OK) ||
        (Rbc_GetVector(interp, argv[3], &y) != TCL_OK) ||
        (Rbc_GetVector(interp, argv[4], &splX) != TCL_OK)) {
        return TCL_ERROR;
    }
    nOrigPts = x->numValues;
    if(nOrigPts < 3) {
        Tcl_AppendResult(interp, "length of vector \"", argv[2], "\" is < 3",
            (char *)NULL);
        return TCL_ERROR;
    }
    for(i = 1; i < nOrigPts; i++) {
        if(x->valueArr[i] < x->valueArr[i - 1]) {
            Tcl_AppendResult(interp, "x vector \"", argv[2],
                "\" must be monotonically increasing", (char *)NULL);
            return TCL_ERROR;
        }
    }
    /* Check that all the data points aren't the same. */
    if(x->valueArr[i - 1] <= x->valueArr[0]) {
        Tcl_AppendResult(interp, "x vector \"", argv[2],
            "\" must be monotonically increasing", (char *)NULL);
        return TCL_ERROR;
    }
    if(nOrigPts != y->numValues) {
        Tcl_AppendResult(interp, "vectors \"", argv[2], "\" and \"", argv[3],
            " have different lengths", (char *)NULL);
        return TCL_ERROR;
    }
    nIntpPts = splX->numValues;
    if(Rbc_GetVector(interp, argv[5], &splY) != TCL_OK) {
        /*
         * If the named vector to hold the ordinates of the spline
         * doesn't exist, create one the same size as the vector
         * containing the abscissas.
         */
        if(Rbc_CreateVector(interp, argv[5], nIntpPts, &splY) != TCL_OK) {
            return TCL_ERROR;
        }
    } else if(nIntpPts != splY->numValues) {
        /*
         * The x and y vectors differ in size. Make the number of ordinates
         * the same as the number of abscissas.
         */
        if(Rbc_ResizeVector(splY, nIntpPts) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    origPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * nOrigPts);
    if(origPts == NULL) {
        Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
            "can't allocate \"%d\" points", nOrigPts);
        return TCL_ERROR;
    }
    intpPts = (RbcPoint2D *) ckalloc(sizeof(RbcPoint2D) * nIntpPts);
    if(intpPts == NULL) {
        Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
            "can't allocate \"%d\" points", nIntpPts);
        ckfree((char *)origPts);
        return TCL_ERROR;
    }
    xArr = x->valueArr;
    yArr = y->valueArr;
    for(i = 0; i < nOrigPts; i++) {
        origPts[i].x = xArr[i];
        origPts[i].y = yArr[i];
    }
    xArr = splX->valueArr;
    yArr = splY->valueArr;
    for(i = 0; i < nIntpPts; i++) {
        intpPts[i].x = xArr[i];
        intpPts[i].y = yArr[i];
    }
    if(!(*proc) (origPts, nOrigPts, intpPts, nIntpPts)) {
        Tcl_AppendResult(interp, "error generating spline for \"",
            RbcNameOfVector(splY), "\"", (char *)NULL);
        ckfree((char *)origPts);
        ckfree((char *)intpPts);
        return TCL_ERROR;
    }
    yArr = splY->valueArr;
    for(i = 0; i < nIntpPts; i++) {
        yArr[i] = intpPts[i].y;
    }
    ckfree((char *)origPts);
    ckfree((char *)intpPts);

    /* Finally update the vector. The size of the vector hasn't
     * changed, just the data. Reset the vector using TCL_STATIC to
     * indicate this. */
    if(Rbc_ResetVector(splY, splY->valueArr, splY->numValues,
            splY->arraySize, TCL_STATIC) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSplineInit --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcSplineInit(
    Tcl_Interp * interp)
{
    Tcl_CreateCommand(interp, "spline", SplineCmd, (ClientData) NULL,
        (Tcl_CmdDeleteProc *) NULL);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * SolveCubic1 --
 *
 *      The Cholesky decomposition A = C^T * D * C (C is
 *      upper triangle with unit diagonal, D is diagonal)
 *      is calculated.
 *
 *      If x is assumed cyclic ( x[i]=x[n+i] ) the
 *      equations can be written as (i=0,1,...,n-1):
 *
 *        m[i][0] * x[i-1] + m[i][1] * x[i] + m[i][2] *
 *        x[i+1] = b[i] .
 *
 *      In matrix notation one gets A * x = b, where the
 *      matrix A is tridiagonal with additional elements
 *      in the upper right and lower left position:
 *
 *        A[i][0] = A_{i,i-1}  for i=1,2,...,n-1
 *          and    m[0][0] = A_{0,n-1} ,
 *
 *        A[i][1] = A_{i, i }  for i=0,1,...,n-1
 *
 *        A[i][2] = A_{i,i+1}  for i=0,1,...,n-2
 *          and    m[n-1][2] = A_{n-1,0}.
 *
 *      A should be symmetric (A[i+1][0] == A[i][2]) and positive definite.
 *      The size of the system is given in n (n>=1).
 *
 * Results:
 *      Return TRUE if decomposition exist.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
SolveCubic1(
    TriDiagonalMatrix A[],
    int n)
{
    int i;
    double m_ij, m_n, m_nn, d;

    if(n < 1) {
        return FALSE;   /* Dimension should be at least 1 */
    }
    d = A[0][1];        /* D_{0,0} = A_{0,0} */
    if(d <= 0.0) {
        return FALSE;   /* A (or D) should be positive definite */
    }
    m_n = A[0][0];      /*  A_{0,n-1}  */
    m_nn = A[n - 1][1]; /* A_{n-1,n-1} */
    for(i = 0; i < n - 2; i++) {
        m_ij = A[i][2]; /*  A_{i,1}  */
        A[i][2] = m_ij / d;     /* C_{i,i+1} */
        A[i][0] = m_n / d;      /* C_{i,n-1} */
        m_nn -= A[i][0] * m_n;  /* to get C_{n-1,n-1} */
        m_n = -A[i][2] * m_n;   /* to get C_{i+1,n-1} */
        d = A[i + 1][1] - A[i][2] * m_ij;       /* D_{i+1,i+1} */
        if(d <= 0.0) {
            return FALSE;       /* Elements of D should be positive */
        }
        A[i + 1][1] = d;
    }
    if(n >= 2) {        /* Complete last column */
        m_n += A[n - 2][2];     /* add A_{n-2,n-1} */
        A[n - 2][0] = m_n / d;  /* C_{n-2,n-1} */
        A[n - 1][1] = d = m_nn - A[n - 2][0] * m_n;     /* D_{n-1,n-1} */
        if(d <= 0.0) {
            return FALSE;
        }
    }
    return TRUE;
}

/*
 *--------------------------------------------------------------
 *
 * SolveCubic2 --
 *
 *      The second procedure solves the linear system, with
 *      the Cholesky decomposition calculated above (in m[][])
 *      and the right side b given in x[]. The solution x
 *      overwrites the right side in x[].
 *
 *      If x is assumed cyclic ( x[i]=x[n+i] ) the
 *      equations can be written as (i=0,1,...,n-1):
 *
 *        m[i][0] * x[i-1] + m[i][1] * x[i] + m[i][2] *
 *        x[i+1] = b[i] .
 *
 *      In matrix notation one gets A * x = b, where the
 *      matrix A is tridiagonal with additional elements
 *      in the upper right and lower left position:
 *
 *        A[i][0] = A_{i,i-1}  for i=1,2,...,n-1
 *          and    m[0][0] = A_{0,n-1} ,
 *
 *        A[i][1] = A_{i, i }  for i=0,1,...,n-1
 *
 *        A[i][2] = A_{i,i+1}  for i=0,1,...,n-2
 *          and    m[n-1][2] = A_{n-1,0}.
 *
 *      A should be symmetric (A[i+1][0] == A[i][2]) and positive definite.
 *      The size of the system is given in n (n>=1).
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
SolveCubic2(
    TriDiagonalMatrix A[],
    CubicSpline spline[],
    int nIntervals)
{
    int i;
    double x, y;
    int n, m;

    n = nIntervals - 2;
    m = nIntervals - 1;

    /* Division by transpose of C : b = C^{-T} * b */
    x = spline[m].x;
    y = spline[m].y;
    for(i = 0; i < n; i++) {
        spline[i + 1].x -= A[i][2] * spline[i].x;       /* C_{i,i+1} * x(i) */
        spline[i + 1].y -= A[i][2] * spline[i].y;       /* C_{i,i+1} * x(i) */
        x -= A[i][0] * spline[i].x;     /* C_{i,n-1} * x(i) */
        y -= A[i][0] * spline[i].y;     /* C_{i,n-1} * x(i) */
    }
    if(n >= 0) {
        /* C_{n-2,n-1} * x_{n-1} */
        spline[m].x = x - A[n][0] * spline[n].x;
        spline[m].y = y - A[n][0] * spline[n].y;
    }
    /* Division by D: b = D^{-1} * b */
    for(i = 0; i < nIntervals; i++) {
        spline[i].x /= A[i][1];
        spline[i].y /= A[i][1];
    }

    /* Division by C: b = C^{-1} * b */
    x = spline[m].x;
    y = spline[m].y;
    if(n >= 0) {
        /* C_{n-2,n-1} * x_{n-1} */
        spline[n].x -= A[n][0] * x;
        spline[n].y -= A[n][0] * y;
    }
    for(i = (n - 1); i >= 0; i--) {
        /* C_{i,i+1} * x_{i+1} + C_{i,n-1} * x_{n-1} */
        spline[i].x -= A[i][2] * spline[i + 1].x + A[i][0] * x;
        spline[i].y -= A[i][2] * spline[i + 1].y + A[i][0] * y;
    }
}

/*
 *--------------------------------------------------------------
 *
 * CubicSlopes --
 *
 *      Find second derivatives (x''(t_i),y''(t_i)) of cubic
 *      spline interpolation through list of points (x_i,y_i).
 *      The parameter t is calculated as the length of the
 *      linear stroke. The number of points must be at least 3.
 *
 *      Note: For CLOSED_CONTOURs the first and last point
 *      must be equal.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static CubicSpline *
CubicSlopes(
    RbcPoint2D points[],
    int nPoints,               /* Number of points (nPoints>=3) */
    int isClosed,              /* CLOSED_CONTOUR or OPEN_CONTOUR  */
    double unitX,              /* Unit length in x and y (norm=1) */
    double unitY)
{              /* Unit length in x and y (norm=1) */
    CubicSpline *spline;
    register CubicSpline *s1, *s2;
    int n, i;
    double norm, dx, dy;
    TriDiagonalMatrix *A;      /* The tri-diagonal matrix is saved here. */

    spline = (CubicSpline *) ckalloc(sizeof(CubicSpline) * nPoints);
    if(spline == NULL) {
        return NULL;
    }
    A = (TriDiagonalMatrix *) ckalloc(sizeof(TriDiagonalMatrix) * nPoints);
    if(A == NULL) {
        ckfree((char *)spline);
        return NULL;
    }
    /*
     * Calculate first differences in (dxdt2[i], y[i]) and interval lengths
     * in dist[i]:
     */
    s1 = spline;
    for(i = 0; i < nPoints - 1; i++) {
        s1->x = points[i + 1].x - points[i].x;
        s1->y = points[i + 1].y - points[i].y;

        /*
         * The Norm of a linear stroke is calculated in "normal coordinates"
         * and used as interval length:
         */
        dx = s1->x / unitX;
        dy = s1->y / unitY;
        s1->t = sqrt(dx * dx + dy * dy);

        s1->x /= s1->t; /* first difference, with unit norm: */
        s1->y /= s1->t; /*   || (dxdt2[i], y[i]) || = 1      */
        s1++;
    }

    /*
     * Setup linear System:  Ax = b
     */
    n = nPoints - 2;    /* Without first and last point */
    if(isClosed) {
        /* First and last points must be equal for CLOSED_CONTOURs */
        spline[nPoints - 1].t = spline[0].t;
        spline[nPoints - 1].x = spline[0].x;
        spline[nPoints - 1].y = spline[0].y;
        n++;   /* Add last point (= first point) */
    }
    s1 = spline, s2 = s1 + 1;
    for(i = 0; i < n; i++) {
        /* Matrix A, mainly tridiagonal with cyclic second index
         * ("j = j+n mod n")
         */
        A[i][0] = s1->t;        /* Off-diagonal element A_{i,i-1} */
        A[i][1] = 2.0 * (s1->t + s2->t);        /* A_{i,i} */
        A[i][2] = s2->t;        /* Off-diagonal element A_{i,i+1} */

        /* Right side b_x and b_y */
        s1->x = (s2->x - s1->x) * 6.0;
        s1->y = (s2->y - s1->y) * 6.0;

        /*
         * If the linear stroke shows a cusp of more than 90 degree,
         * the right side is reduced to avoid oscillations in the
         * spline:
         */
        /*
         * The Norm of a linear stroke is calculated in "normal coordinates"
         * and used as interval length:
         */
        dx = s1->x / unitX;
        dy = s1->y / unitY;
        norm = sqrt(dx * dx + dy * dy) / 8.5;
        if(norm > 1.0) {
            /* The first derivative will not be continuous */
            s1->x /= norm;
            s1->y /= norm;
        }
        s1++, s2++;
    }

    if(!isClosed) {
        /* Third derivative is set to zero at both ends */
        A[0][1] += A[0][0];     /* A_{0,0}     */
        A[0][0] = 0.0;  /* A_{0,n-1}   */
        A[n - 1][1] += A[n - 1][2];     /* A_{n-1,n-1} */
        A[n - 1][2] = 0.0;      /* A_{n-1,0}   */
    }
    /* Solve linear systems for dxdt2[] and y[] */

    if(SolveCubic1(A, n)) {     /* Cholesky decomposition */
        SolveCubic2(A, spline, n);      /* A * dxdt2 = b_x */
    } else {   /* Should not happen, but who knows ... */
        ckfree((char *)A);
        ckfree((char *)spline);
        return NULL;
    }
    /* Shift all second derivatives one place right and update the ends. */
    s2 = spline + n, s1 = s2 - 1;
    for( /* empty */ ; s2 > spline; s2--, s1--) {
        s2->x = s1->x;
        s2->y = s1->y;
    }
    if(isClosed) {
        spline[0].x = spline[n].x;
        spline[0].y = spline[n].y;
    } else {
        /* Third derivative is 0.0 for the first and last interval. */
        spline[0].x = spline[1].x;
        spline[0].y = spline[1].y;
        spline[n + 1].x = spline[n].x;
        spline[n + 1].y = spline[n].y;
    }
    ckfree((char *)A);
    return spline;
}

/*
 *--------------------------------------------------------------
 *
 * CubicEval --
 *
 *      Calculate interpolated values of the spline function
 *      (defined via p_cntr and the second derivatives
 *      dxdt2[] and dydt2[]). The number of tabulated values
 *      is n. On an equidistant grid n_intpol values are
 *      calculated.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
CubicEval(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcPoint2D intpPts[],
    int nIntpPts,
    CubicSpline spline[])
{
    double t, tSkip, tMax;
    RbcPoint2D p, q;
    double d, hx, dx0, dx01, hy, dy0, dy01;
    register int i, j, count;

    /* Sum the lengths of all the segments (intervals). */
    tMax = 0.0;
    for(i = 0; i < nOrigPts - 1; i++) {
        tMax += spline[i].t;
    }

    /* Need a better way of doing this... */

    /* The distance between interpolated points */
    tSkip = (1. - 1e-7) * tMax / (nIntpPts - 1);

    t = 0.0;   /* Spline parameter value. */
    q = origPts[0];
    count = 0;

    intpPts[count++] = q;       /* First point. */
    t += tSkip;

    for(i = 0, j = 1; j < nOrigPts; i++, j++) {
        d = spline[i].t;        /* Interval length */
        p = q;
        q = origPts[i + 1];
        hx = (q.x - p.x) / d;
        hy = (q.y - p.y) / d;
        dx0 = (spline[j].x + 2 * spline[i].x) / 6.0;
        dy0 = (spline[j].y + 2 * spline[i].y) / 6.0;
        dx01 = (spline[j].x - spline[i].x) / (6.0 * d);
        dy01 = (spline[j].y - spline[i].y) / (6.0 * d);
        while(t <= spline[i].t) {       /* t in current interval ? */
            p.x += t * (hx + (t - d) * (dx0 + t * dx01));
            p.y += t * (hy + (t - d) * (dy0 + t * dy01));
            intpPts[count++] = p;
            t += tSkip;
        }
        /* Parameter t relative to start of next interval */
        t -= spline[i].t;
    }
    return count;
}

/*
 *--------------------------------------------------------------
 *
 * RbcNaturalParametricSpline --
 *
 *      Generate a cubic spline curve through the points
 *      (x_i,y_i) which are stored in the linked list
 *      p_cntr.
 *
 *      The spline is defined as a 2d-function
 *      s(t) = (x(t),y(t)), where the parameter t is the
 *      length of the linear stroke.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcNaturalParametricSpline(
    RbcPoint2D origPts[],
    int nOrigPts,
    RbcExtents2D * extsPtr,
    int isClosed,
    RbcPoint2D * intpPts,
    int nIntpPts)
{
    double unitX, unitY;       /* To define norm (x,y)-plane */
    CubicSpline *spline;
    int result;

    if(nOrigPts < 3) {
        return 0;
    }
    if(isClosed) {
        origPts[nOrigPts].x = origPts[0].x;
        origPts[nOrigPts].y = origPts[0].y;
        nOrigPts++;
    }
    /* Width and height of the grid is used at unit length (2d-norm) */
    unitX = extsPtr->right - extsPtr->left;
    unitY = extsPtr->bottom - extsPtr->top;

    if(unitX < FLT_EPSILON) {
        unitX = FLT_EPSILON;
    }
    if(unitY < FLT_EPSILON) {
        unitY = FLT_EPSILON;
    }
    /* Calculate parameters for cubic spline:
     *          t     = arc length of interval.
     *          dxdt2 = second derivatives of x with respect to t,
     *          dydt2 = second derivatives of y with respect to t,
     */
    spline = CubicSlopes(origPts, nOrigPts, isClosed, unitX, unitY);
    if(spline == NULL) {
        return 0;
    }
    result = CubicEval(origPts, nOrigPts, intpPts, nIntpPts, spline);
    ckfree((char *)spline);
    return result;
}

/*
 *--------------------------------------------------------------
 *
 * CatromCoeffs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
CatromCoeffs(
    RbcPoint2D * p,
    RbcPoint2D * a,
    RbcPoint2D * b,
    RbcPoint2D * c,
    RbcPoint2D * d)
{
    a->x = -p[0].x + 3.0 * p[1].x - 3.0 * p[2].x + p[3].x;
    b->x = 2.0 * p[0].x - 5.0 * p[1].x + 4.0 * p[2].x - p[3].x;
    c->x = -p[0].x + p[2].x;
    d->x = 2.0 * p[1].x;
    a->y = -p[0].y + 3.0 * p[1].y - 3.0 * p[2].y + p[3].y;
    b->y = 2.0 * p[0].y - 5.0 * p[1].y + 4.0 * p[2].y - p[3].y;
    c->y = -p[0].y + p[2].y;
    d->y = 2.0 * p[1].y;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcCatromParametricSpline --
 *
 *      Computes a spline based upon the data points, returning a new
 *      (larger) coordinate array or points.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcCatromParametricSpline(
    RbcPoint2D * points,
    int nPoints,
    RbcPoint2D * intpPts,
    int nIntpPts)
{
    register int i;
    RbcPoint2D *origPts;
    double t;
    int interval;
    RbcPoint2D a, b, c, d;

    assert(nPoints > 0);
    /*
     * The spline is computed in screen coordinates instead of data
     * points so that we can select the abscissas of the interpolated
     * points from each pixel horizontally across the plotting area.
     */
    origPts = (RbcPoint2D *) ckalloc((nPoints + 4) * sizeof(RbcPoint2D));
    memcpy(origPts + 1, points, sizeof(RbcPoint2D) * nPoints);

    origPts[0] = origPts[1];
    origPts[nPoints + 2] = origPts[nPoints + 1] = origPts[nPoints];

    for(i = 0; i < nIntpPts; i++) {
        interval = (int)intpPts[i].x;
        t = intpPts[i].y;
        assert(interval < nPoints);
        CatromCoeffs(origPts + interval, &a, &b, &c, &d);
        intpPts[i].x = (d.x + t * (c.x + t * (b.x + t * a.x))) / 2.0;
        intpPts[i].y = (d.y + t * (c.y + t * (b.y + t * a.y))) / 2.0;
    }
    ckfree((char *)origPts);
    return 1;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcSwitch.c.















































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcSwitch.c --
 *
 *      This module implements command/argument switch parsing
 *      procedures for the rbc toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

static RbcSwitchSpec *FindSwitchSpec(
    Tcl_Interp * interp,
    RbcSwitchSpec * specs,
    const char *name,
    int needFlags,
    int hateFlags);
static int DoSwitch(
    Tcl_Interp * interp,
    RbcSwitchSpec * specPtr,
    const char *string,
    ClientData record);

/*
 *--------------------------------------------------------------
 *
 * FindSwitchSpec --
 *
 *      Search through a table of configuration specs, looking for
 *      one that matches a given argvName.
 *
 * Results:
 *      The return value is a pointer to the matching entry, or NULL
 *      if nothing matched.  In that case an error message is left
 *      in the interp's result.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
static RbcSwitchSpec *
FindSwitchSpec(
    Tcl_Interp * interp,       /* Used for reporting errors. */
    RbcSwitchSpec * specs,     /* Pointer to table of configuration
                                * specifications for a widget. */
    const char *name,          /* Name (suitable for use in a "switch"
                                * command) identifying particular option. */
    int needFlags,             /* Flags that must be present in matching
                                * entry. */
    int hateFlags)
{              /* Flags that must NOT be present in
                * matching entry. */
    register RbcSwitchSpec *specPtr;
    register char c;           /* First character of current argument. */
    RbcSwitchSpec *matchPtr;   /* Matching spec, or NULL. */
    size_t length;

    c = name[1];
    length = strlen(name);
    matchPtr = NULL;

    for(specPtr = specs; specPtr->type != RBC_SWITCH_END; specPtr++) {
        if(specPtr->switchName == NULL) {
            continue;
        }
        if((specPtr->switchName[1] != c)
            || (strncmp(specPtr->switchName, name, length) != 0)) {
            continue;
        }
        if(((specPtr->flags & needFlags) != needFlags)
            || (specPtr->flags & hateFlags)) {
            continue;
        }
        if(specPtr->switchName[length] == 0) {
            return specPtr;     /* Stop on a perfect match. */
        }
        if(matchPtr != NULL) {
            Tcl_AppendResult(interp, "ambiguous option \"", name, "\"",
                (char *)NULL);
            return (RbcSwitchSpec *) NULL;
        }
        matchPtr = specPtr;
    }

    if(matchPtr == NULL) {
        Tcl_AppendResult(interp, "unknown option \"", name, "\"", (char *)NULL);
        return (RbcSwitchSpec *) NULL;
    }
    return matchPtr;
}

/*
 *--------------------------------------------------------------
 *
 * DoSwitch --
 *
 *      This procedure applies a single configuration option
 *      to a widget record.
 *
 * Results:
 *      A standard Tcl return value.
 *
 * Side effects:
 *      WidgRec is modified as indicated by specPtr and value.
 *      The old value is recycled, if that is appropriate for
 *      the value type.
 *
 *--------------------------------------------------------------
 */
static int
DoSwitch(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    RbcSwitchSpec * specPtr,   /* Specifier to apply. */
    const char *string,        /* Value to use to fill in widgRec. */
    ClientData record)
{              /* Record whose fields are to be
                * modified.  Values must be properly
                * initialized. */
    char *ptr;
    int isNull;
    int count;

    isNull = ((*string == '\0') && (specPtr->flags & RBC_SWITCH_NULL_OK));
    do {
        ptr = (char *)record + specPtr->offset;
        switch (specPtr->type) {
        case RBC_SWITCH_BOOLEAN:
            if(Tcl_GetBoolean(interp, string, (int *)ptr) != TCL_OK) {
                return TCL_ERROR;
            }
            break;

        case RBC_SWITCH_INT:
            if(Tcl_GetInt(interp, string, (int *)ptr) != TCL_OK) {
                return TCL_ERROR;
            }
            break;

        case RBC_SWITCH_INT_NONNEGATIVE:
            if(Tcl_GetInt(interp, string, &count) != TCL_OK) {
                return TCL_ERROR;
            }
            if(count < 0) {
                Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                    "can't be negative", (char *)NULL);
                return TCL_ERROR;
            }
            *((int *)ptr) = count;
            break;

        case RBC_SWITCH_INT_POSITIVE:
            if(Tcl_GetInt(interp, string, &count) != TCL_OK) {
                return TCL_ERROR;
            }
            if(count <= 0) {
                Tcl_AppendResult(interp, "bad value \"", string, "\": ",
                    "must be positive", (char *)NULL);
                return TCL_ERROR;
            }
            *((int *)ptr) = count;
            break;

        case RBC_SWITCH_DOUBLE:
            if(Tcl_GetDouble(interp, string, (double *)ptr) != TCL_OK) {
                return TCL_ERROR;
            }
            break;

        case RBC_SWITCH_STRING:{
    char *old, *new, **strPtr;

            strPtr = (char **)ptr;
            if(isNull) {
                new = NULL;
            } else {
                new = RbcStrdup(string);
            }
            old = *strPtr;
            if(old != NULL) {
                ckfree((char *)old);
            }
            *strPtr = new;
        }
            break;

        case RBC_SWITCH_LIST:
            if(Tcl_SplitList(interp, string, &count, (const char ***)ptr)
                != TCL_OK) {
                return TCL_ERROR;
            }
            break;

        case RBC_SWITCH_CUSTOM:
            if((*specPtr->customPtr->parseProc)
                (specPtr->customPtr->clientData, interp,
                    (char *)specPtr->switchName, (char *)string, record,
                    specPtr->offset) != TCL_OK) {
                return TCL_ERROR;
            }
            break;

        default:
            Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
                "bad switch table: unknown type \"%d\"", specPtr->type);
            return TCL_ERROR;
        }
        specPtr++;
    } while((specPtr->switchName == NULL) && (specPtr->type != RBC_SWITCH_END));
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcProcessSwitches --
 *
 *      Process command-line options and database options to
 *      fill in fields of a widget record with resources and
 *      other parameters.
 *
 * Results:
 *      Returns the number of arguments comsumed by parsing the
 *      command line.  If an error occurred, -1 will be returned
 *      and an error messages can be found as the interpreter
 *      result.
 *
 * Side effects:
 *      The fields of widgRec get filled in with information
 *      from argc/argv and the option database.  Old information
 *      in widgRec's fields gets recycled.
 *
 *--------------------------------------------------------------
 */
int
RbcProcessSwitches(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    RbcSwitchSpec * specs,     /* Describes legal options. */
    int argc,                  /* Number of elements in argv. */
    const char **argv,         /* Command-line options. */
    char *record,              /* Record whose fields are to be
                                * modified.  Values must be properly
                                * initialized. */
    int flags)
{              /* Used to specify additional flags
                * that must be present in switch specs
                * for them to be considered.  Also,
                * may have RBC_SWITCH_ARGV_ONLY set. */
    register int count;
    const char *arg;
    register RbcSwitchSpec *specPtr;
    int needFlags;             /* Specs must contain this set of flags
                                * or else they are not considered. */
    int hateFlags;             /* If a spec contains any bits here, it's
                                * not considered. */

    needFlags = flags & ~(RBC_SWITCH_USER_BIT - 1);
    hateFlags = 0;

    /*
     * Pass 1:  Clear the change flags on all the specs so that we
     *          can check it later.
     */
    for(specPtr = specs; specPtr->type != RBC_SWITCH_END; specPtr++) {
        specPtr->flags &= ~RBC_SWITCH_SPECIFIED;
    }
    /*
     * Pass 2:  Process the arguments that match entries in the specs.
     *          It's an error if the argument doesn't match anything.
     */
    for(count = 0; count < argc; count++) {
        arg = argv[count];
        if(flags & RBC_SWITCH_OBJV_PARTIAL) {
            if((arg[0] != '-') || ((arg[1] == '-') && (argv[2] == '\0'))) {
                /*
                 * If the argument doesn't start with a '-' (not a switch)
                 * or is '--', stop processing and return the number of
                 * arguments comsumed.
                 */
                return count;
            }
        }
        specPtr = FindSwitchSpec(interp, specs, arg, needFlags, hateFlags);
        if(specPtr == NULL) {
            return -1;
        }
        if(specPtr->type == RBC_SWITCH_FLAG) {
    char *ptr;

            ptr = record + specPtr->offset;
            *((int *)ptr) |= specPtr->value;
        } else if(specPtr->type == RBC_SWITCH_VALUE) {
    char *ptr;

            ptr = record + specPtr->offset;
            *((int *)ptr) = specPtr->value;
        } else {
            if((count + 1) == argc) {
                Tcl_AppendResult(interp, "value for \"", arg, "\" missing",
                    (char *)NULL);
                return -1;
            }
            count++;
            if(DoSwitch(interp, specPtr, argv[count], record) != TCL_OK) {
    char msg[100];

                sprintf(msg, "\n    (processing \"%.40s\" option)",
                    specPtr->switchName);
                Tcl_AddErrorInfo(interp, msg);
                return -1;
            }
        }
        specPtr->flags |= RBC_SWITCH_SPECIFIED;
    }
    return count;
}

/*
 *--------------------------------------------------------------
 *
 * RbcProcessObjSwitches --
 *
 *      Process command-line options and database options to
 *      fill in fields of a widget record with resources and
 *      other parameters.
 *
 * Results:
 *      Returns the number of arguments comsumed by parsing the
 *      command line.  If an error occurred, -1 will be returned
 *      and an error messages can be found as the interpreter
 *      result.
 *
 * Side effects:
 *      The fields of widgRec get filled in with information
 *      from argc/argv and the option database.  Old information
 *      in widgRec's fields gets recycled.
 *
 *--------------------------------------------------------------
 */
int
RbcProcessObjSwitches(
    Tcl_Interp * interp,       /* Interpreter for error reporting. */
    RbcSwitchSpec * specs,     /* Describes legal options. */
    int objc,                  /* Number of elements in argv. */
    Tcl_Obj * const *objv,     /* Command-line options. */
    char *record,              /* Record whose fields are to be
                                * modified.  Values must be properly
                                * initialized. */
    int flags)
{              /* Used to specify additional flags
                * that must be present in switch specs
                * for them to be considered.  Also,
                * may have RBC_SWITCH_ARGV_ONLY set. */
    register RbcSwitchSpec *specPtr;
    register int count;
    int needFlags;             /* Specs must contain this set of flags
                                * or else they are not considered. */
    int hateFlags;             /* If a spec contains any bits here, it's
                                * not considered. */

    needFlags = flags & ~(RBC_SWITCH_USER_BIT - 1);
    hateFlags = 0;

    /*
     * Pass 1:  Clear the change flags on all the specs so that we
     *          can check it later.
     */
    for(specPtr = specs; specPtr->type != RBC_SWITCH_END; specPtr++) {
        specPtr->flags &= ~RBC_SWITCH_SPECIFIED;
    }
    /*
     * Pass 2:  Process the arguments that match entries in the specs.
     *          It's an error if the argument doesn't match anything.
     */
    for(count = 0; count < objc; count++) {
    char *arg;

        arg = Tcl_GetString(objv[count]);
        if(flags & RBC_SWITCH_OBJV_PARTIAL) {
            if((arg[0] != '-') || ((arg[1] == '-') && (arg[2] == '\0'))) {
                /*
                 * If the argument doesn't start with a '-' (not a switch)
                 * or is '--', stop processing and return the number of
                 * arguments comsumed.
                 */
                return count;
            }
        }
        specPtr = FindSwitchSpec(interp, specs, arg, needFlags, hateFlags);
        if(specPtr == NULL) {
            return -1;
        }
        if(specPtr->type == RBC_SWITCH_FLAG) {
    char *ptr;

            ptr = record + specPtr->offset;
            *((int *)ptr) |= specPtr->value;
        } else if(specPtr->type == RBC_SWITCH_VALUE) {
    char *ptr;

            ptr = record + specPtr->offset;
            *((int *)ptr) = specPtr->value;
        } else {
            count++;
            if(count == objc) {
                Tcl_AppendResult(interp, "value for \"", arg, "\" missing",
                    (char *)NULL);
                return -1;
            }
            arg = Tcl_GetString(objv[count]);
            if(DoSwitch(interp, specPtr, arg, record) != TCL_OK) {
    char msg[100];

                sprintf(msg, "\n    (processing \"%.40s\" option)",
                    specPtr->switchName);
                Tcl_AddErrorInfo(interp, msg);
                return -1;
            }
        }
        specPtr->flags |= RBC_SWITCH_SPECIFIED;
    }
    return count;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreeSwitches --
 *
 *      Free up all resources associated with switch options.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */

/* ARGSUSED */
void
RbcFreeSwitches(
    RbcSwitchSpec * specs,     /* Describes legal options. */
    char *record,              /* Record whose fields contain current
                                * values for options. */
    int needFlags)
{              /* Used to specify additional flags
                * that must be present in config specs
                * for them to be considered. */
    register RbcSwitchSpec *specPtr;

    for(specPtr = specs; specPtr->type != RBC_SWITCH_END; specPtr++) {
        if((specPtr->flags & needFlags) == needFlags) {
    char *ptr;

            ptr = record + specPtr->offset;
            switch (specPtr->type) {
            case RBC_SWITCH_STRING:
            case RBC_SWITCH_LIST:
                if(*((char **)ptr) != NULL) {
                    ckfree((char *)*((char **)ptr));
                    *((char **)ptr) = NULL;
                }
                break;

            case RBC_SWITCH_CUSTOM:
                if((*(char **)ptr != NULL) &&
                    (specPtr->customPtr->freeProc != NULL)) {
                    (*specPtr->customPtr->freeProc) (*(char **)ptr);
                    *((char **)ptr) = NULL;
                }
                break;

            default:
                break;
            }
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSwitchChanged --
 *
 *      Given the configuration specifications and one or more option
 *      patterns (terminated by a NULL), indicate if any of the matching
 *      configuration options has been reset.
 *
 * Results:
 *      Returns 1 if one of the options has changed, 0 otherwise.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcSwitchChanged(
    RbcSwitchSpec * specs,
    ...)
{
    va_list argList;
    register RbcSwitchSpec *specPtr;
    register char *switchName;

    va_start(argList, specs);
    while((switchName = va_arg(argList, char *)) != NULL) {
        for(specPtr = specs; specPtr->type != RBC_SWITCH_END; specPtr++) {
            if((Tcl_StringMatch(specPtr->switchName, switchName)) &&
                (specPtr->flags & RBC_SWITCH_SPECIFIED)) {
                va_end(argList);
                return 1;
            }
        }
    }
    va_end(argList);
    return 0;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcText.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcText.c --
 *
 *      This module implements multi-line, rotate-able text for the rbc toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define WINDEBUG	0

static Tcl_HashTable bitmapGCTable;
static int initialized;

static void DrawTextLayout(
    Display * display,
    Drawable drawable,
    GC gc,
    Tk_Font font,
    register int x,
    register int y,
    RbcTextLayout * textPtr);
static Pixmap CreateTextBitmap(
    Tk_Window tkwin,
    RbcTextLayout * textPtr,
    RbcTextStyle * stylePtr,
    int *widthPtr,
    int *heightPtr);

/*
 *--------------------------------------------------------------
 *
 * DrawTextLayout --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
DrawTextLayout(
    Display * display,
    Drawable drawable,
    GC gc,
    Tk_Font font,
    register int x,            /* Origin of text */
    register int y,            /* Origin of text */
    RbcTextLayout * textPtr)
{
    register RbcTextFragment *fragPtr;
    register int i;

    fragPtr = textPtr->fragArr;
    for(i = 0; i < textPtr->nFrags; i++, fragPtr++) {
        Tk_DrawChars(display, drawable, gc, font, fragPtr->text, fragPtr->count,
            x + fragPtr->x, y + fragPtr->y);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * RbcGetTextLayout --
 *
 *      Get the extents of a possibly multiple-lined text string.
 *
 * Results:
 *      Returns via *widthPtr* and *heightPtr* the dimensions of
 *      the text string.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
RbcTextLayout *
RbcGetTextLayout(
    char string[],
    RbcTextStyle * tsPtr)
{
    int maxHeight, maxWidth;
    int count;                 /* Count # of characters on each line */
    int nFrags;
    int width;                 /* Running dimensions of the text */
    RbcTextFragment *fragPtr;
    RbcTextLayout *textPtr;
    int lineHeight;
    int size;
    register char *p;
    register int i;
    Tk_FontMetrics fontMetrics;

    Tk_GetFontMetrics(tsPtr->font, &fontMetrics);
    lineHeight = fontMetrics.linespace + tsPtr->leader + tsPtr->shadow.offset;
    nFrags = 0;
    for(p = string; *p != '\0'; p++) {
        if(*p == '\n') {
            nFrags++;
        }
    }
    if((p != string) && (*(p - 1) != '\n')) {
        nFrags++;
    }
    size = sizeof(RbcTextLayout) + (sizeof(RbcTextFragment) * (nFrags - 1));
    textPtr = RbcCalloc(1, size);
    textPtr->nFrags = nFrags;
    nFrags = count = 0;
    width = maxWidth = 0;
    maxHeight = tsPtr->padY.side1;
    fragPtr = textPtr->fragArr;
    for(p = string; *p != '\0'; p++) {
        if(*p == '\n') {
            if(count > 0) {
                width = Tk_TextWidth(tsPtr->font, string, count) +
                    tsPtr->shadow.offset;
                if(width > maxWidth) {
                    maxWidth = width;
                }
            }
            fragPtr->width = width;
            fragPtr->count = count;
            fragPtr->y = maxHeight + fontMetrics.ascent;
            fragPtr->text = string;
            fragPtr++;
            nFrags++;
            maxHeight += lineHeight;
            string = p + 1;     /* Start the string on the next line */
            count = 0;  /* Reset to indicate the start of a new line */
            continue;
        }
        count++;
    }
    if(nFrags < textPtr->nFrags) {
        width = Tk_TextWidth(tsPtr->font, string, count) + tsPtr->shadow.offset;
        if(width > maxWidth) {
            maxWidth = width;
        }
        fragPtr->width = width;
        fragPtr->count = count;
        fragPtr->y = maxHeight + fontMetrics.ascent;
        fragPtr->text = string;
        maxHeight += lineHeight;
        nFrags++;
    }
    maxHeight += tsPtr->padY.side2;
    maxWidth += RbcPadding(tsPtr->padX);
    fragPtr = textPtr->fragArr;
    for(i = 0; i < nFrags; i++, fragPtr++) {
        switch (tsPtr->justify) {
        default:
        case TK_JUSTIFY_LEFT:
            /* No offset for left justified text strings */
            fragPtr->x = tsPtr->padX.side1;
            break;
        case TK_JUSTIFY_RIGHT:
            fragPtr->x = (maxWidth - fragPtr->width) - tsPtr->padX.side2;
            break;
        case TK_JUSTIFY_CENTER:
            fragPtr->x = (maxWidth - fragPtr->width) / 2;
            break;
        }
    }
    textPtr->width = maxWidth;
    textPtr->height = maxHeight - tsPtr->leader;
    return textPtr;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcGetTextExtents --
 *
 *      Get the extents of a possibly multiple-lined text string.
 *
 * Results:
 *      Returns via *widthPtr* and *heightPtr* the dimensions of
 *      the text string.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcGetTextExtents(
    RbcTextStyle * tsPtr,
    char *string,
    int *widthPtr,
    int *heightPtr)
{
    int count;                 /* Count # of characters on each line */
    int width, height;
    int w, lineHeight;
    register char *p;
    Tk_FontMetrics fontMetrics;

    if(string == NULL) {
        return; /* NULL string? */
    }
    Tk_GetFontMetrics(tsPtr->font, &fontMetrics);
    lineHeight = fontMetrics.linespace + tsPtr->leader + tsPtr->shadow.offset;
    count = 0;
    width = height = 0;
    for(p = string; *p != '\0'; p++) {
        if(*p == '\n') {
            if(count > 0) {
                w = Tk_TextWidth(tsPtr->font, string, count) +
                    tsPtr->shadow.offset;
                if(w > width) {
                    width = w;
                }
            }
            height += lineHeight;
            string = p + 1;     /* Start the string on the next line */
            count = 0;  /* Reset to indicate the start of a new line */
            continue;
        }
        count++;
    }
    if((count > 0) && (*(p - 1) != '\n')) {
        height += lineHeight;
        w = Tk_TextWidth(tsPtr->font, string, count) + tsPtr->shadow.offset;
        if(w > width) {
            width = w;
        }
    }
    *widthPtr = width + RbcPadding(tsPtr->padX);
    *heightPtr = height + RbcPadding(tsPtr->padY);
}

/*
 * -----------------------------------------------------------------
 *
 * RbcGetBoundingBox
 *
 *      Computes the dimensions of the bounding box surrounding a
 *      rectangle rotated about its center.  If pointArr isn't NULL,
 *      the coordinates of the rotated rectangle are also returned.
 *
 *      The dimensions are determined by rotating the rectangle, and
 *      doubling the maximum x-coordinate and y-coordinate.
 *
 *        w = 2 * maxX,  h = 2 * maxY
 *
 *      Since the rectangle is centered at 0,0, the coordinates of
 *      the bounding box are (-w/2,-h/2 w/2,-h/2, w/2,h/2 -w/2,h/2).
 *
 *        0 ------- 1
 *        |         |
 *        |    x    |
 *        |         |
 *        3 ------- 2
 *
 * Results:
 *      The width and height of the bounding box containing the
 *      rotated rectangle are returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcGetBoundingBox(
    int width,                 /* Unrotated region */
    int height,                /* Unrotated region */
    double theta,              /* Rotation of box */
    double *rotWidthPtr,       /* (out) Bounding box region */
    double *rotHeightPtr,      /* (out) Bounding box region */
    RbcPoint2D * bbox)
{              /* (out) Points of the rotated box */
    register int i;
    double sinTheta, cosTheta;
    double xMax, yMax;
    register double x, y;
    RbcPoint2D corner[4];

    theta = FMOD(theta, 360.0);
    if(FMOD(theta, (double)90.0) == 0.0) {
    int ll, ur, ul, lr;
    double rotWidth, rotHeight;
    int quadrant;

        /* Handle right-angle rotations specifically */

        quadrant = (int)(theta / 90.0);
        switch (quadrant) {
        case RBC_ROTATE_270:   /* 270 degrees */
            ul = 3, ur = 0, lr = 1, ll = 2;
            rotWidth = (double)height;
            rotHeight = (double)width;
            break;
        case RBC_ROTATE_90:    /* 90 degrees */
            ul = 1, ur = 2, lr = 3, ll = 0;
            rotWidth = (double)height;
            rotHeight = (double)width;
            break;
        case RBC_ROTATE_180:   /* 180 degrees */
            ul = 2, ur = 3, lr = 0, ll = 1;
            rotWidth = (double)width;
            rotHeight = (double)height;
            break;
        default:
        case RBC_ROTATE_0:     /* 0 degrees */
            ul = 0, ur = 1, lr = 2, ll = 3;
            rotWidth = (double)width;
            rotHeight = (double)height;
            break;
        }
        if(bbox != NULL) {
            x = rotWidth * 0.5;
            y = rotHeight * 0.5;
            bbox[ll].x = bbox[ul].x = -x;
            bbox[ur].y = bbox[ul].y = -y;
            bbox[lr].x = bbox[ur].x = x;
            bbox[ll].y = bbox[lr].y = y;
        }
        *rotWidthPtr = rotWidth;
        *rotHeightPtr = rotHeight;
        return;
    }
    /* Set the four corners of the rectangle whose center is the origin */

    corner[1].x = corner[2].x = (double)width *0.5;
    corner[0].x = corner[3].x = -corner[1].x;
    corner[2].y = corner[3].y = (double)height *0.5;
    corner[0].y = corner[1].y = -corner[2].y;

    theta = (-theta / 180.0) * M_PI;
    sinTheta = sin(theta), cosTheta = cos(theta);
    xMax = yMax = 0.0;

    /* Rotate the four corners and find the maximum X and Y coordinates */

    for(i = 0; i < 4; i++) {
        x = (corner[i].x * cosTheta) - (corner[i].y * sinTheta);
        y = (corner[i].x * sinTheta) + (corner[i].y * cosTheta);
        if(x > xMax) {
            xMax = x;
        }
        if(y > yMax) {
            yMax = y;
        }
        if(bbox != NULL) {
            bbox[i].x = x;
            bbox[i].y = y;
        }
    }

    /*
     * By symmetry, the width and height of the bounding box are
     * twice the maximum x and y coordinates.
     */
    *rotWidthPtr = xMax + xMax;
    *rotHeightPtr = yMax + yMax;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcTranslateAnchor --
 *
 *      Translate the coordinates of a given bounding box based
 *      upon the anchor specified.  The anchor indicates where
 *      the given xy position is in relation to the bounding box.
 *
 *        nw --- n --- ne
 *        |            |
 *        w   center   e
 *        |            |
 *        sw --- s --- se
 *
 *      The coordinates returned are translated to the origin of the
 *      bounding box (suitable for giving to XCopyArea, XCopyPlane, etc.)
 *
 * Results:
 *      The translated coordinates of the bounding box are returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
void
RbcTranslateAnchor(
    int x,                     /* Window coordinates of anchor */
    int y,                     /* Window coordinates of anchor */
    int width,                 /* Extents of the bounding box */
    int height,                /* Extents of the bounding box */
    Tk_Anchor anchor,          /* Direction of the anchor */
    int *transXPtr,
    int *transYPtr)
{
    switch (anchor) {
    case TK_ANCHOR_NW: /* Upper left corner */
        break;
    case TK_ANCHOR_W:  /* Left center */
        y -= (height / 2);
        break;
    case TK_ANCHOR_SW: /* Lower left corner */
        y -= height;
        break;
    case TK_ANCHOR_N:  /* Top center */
        x -= (width / 2);
        break;
    case TK_ANCHOR_CENTER:     /* Center */
        x -= (width / 2);
        y -= (height / 2);
        break;
    case TK_ANCHOR_S:  /* Bottom center */
        x -= (width / 2);
        y -= height;
        break;
    case TK_ANCHOR_NE: /* Upper right corner */
        x -= width;
        break;
    case TK_ANCHOR_E:  /* Right center */
        x -= width;
        y -= (height / 2);
        break;
    case TK_ANCHOR_SE: /* Lower right corner */
        x -= width;
        y -= height;
        break;
    }
    *transXPtr = x;
    *transYPtr = y;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcTranslatePoint --
 *
 *      Translate the coordinates of a given bounding box based
 *      upon the anchor specified.  The anchor indicates where
 *      the given xy position is in relation to the bounding box.
 *
 *        nw --- n --- ne
 *        |            |
 *        w   center   e
 *        |            |
 *        sw --- s --- se
 *
 *      The coordinates returned are translated to the origin of the
 *      bounding box (suitable for giving to XCopyArea, XCopyPlane, etc.)
 *
 * Results:
 *      The translated coordinates of the bounding box are returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------
 */
RbcPoint2D
RbcTranslatePoint(
    RbcPoint2D * pointPtr,     /* Window coordinates of anchor */
    int width,                 /* Extents of the bounding box */
    int height,                /* Extents of the bounding box */
    Tk_Anchor anchor)
{              /* Direction of the anchor */
    RbcPoint2D trans;

    trans = *pointPtr;
    switch (anchor) {
    case TK_ANCHOR_NW: /* Upper left corner */
        break;
    case TK_ANCHOR_W:  /* Left center */
        trans.y -= (height * 0.5);
        break;
    case TK_ANCHOR_SW: /* Lower left corner */
        trans.y -= height;
        break;
    case TK_ANCHOR_N:  /* Top center */
        trans.x -= (width * 0.5);
        break;
    case TK_ANCHOR_CENTER:     /* Center */
        trans.x -= (width * 0.5);
        trans.y -= (height * 0.5);
        break;
    case TK_ANCHOR_S:  /* Bottom center */
        trans.x -= (width * 0.5);
        trans.y -= height;
        break;
    case TK_ANCHOR_NE: /* Upper right corner */
        trans.x -= width;
        break;
    case TK_ANCHOR_E:  /* Right center */
        trans.x -= width;
        trans.y -= (height * 0.5);
        break;
    case TK_ANCHOR_SE: /* Lower right corner */
        trans.x -= width;
        trans.y -= height;
        break;
    }
    return trans;
}

/*
 * -----------------------------------------------------------------
 *
 * CreateTextBitmap --
 *
 *      Draw a bitmap, using the the given window coordinates
 *      as an anchor for the text bounding box.
 *
 * Results:
 *      Returns the bitmap representing the text string.
 *
 * Side Effects:
 *      Bitmap is drawn using the given font and GC in the
 *      drawable at the given coordinates, anchor, and rotation.
 *
 * -----------------------------------------------------------------
 */
static Pixmap
CreateTextBitmap(
    Tk_Window tkwin,
    RbcTextLayout * textPtr,   /* Text string to draw */
    RbcTextStyle * tsPtr,      /* Text attributes: rotation, color, font,
                                * linespacing, justification, etc. */
    int *bmWidthPtr,
    int *bmHeightPtr)
{              /* Extents of rotated text string */
    int width, height;
    Pixmap bitmap;
    Display *display;
    Window root;
    GC  gc;
#ifdef _WIN32
    HDC hDC;
    TkWinDCState state;
#endif
    display = Tk_Display(tkwin);

    width = textPtr->width;
    height = textPtr->height;

    /* Create a temporary bitmap to contain the text string */
    root = RootWindow(display, Tk_ScreenNumber(tkwin));
    bitmap = Tk_GetPixmap(display, root, width, height, 1);
    assert(bitmap != None);
    if(bitmap == None) {
        return None;    /* Can't allocate pixmap. */
    }
    /* Clear the pixmap and draw the text string into it */
    gc = RbcGetBitmapGC(tkwin);
#ifdef _WIN32
    hDC = TkWinGetDrawableDC(display, bitmap, &state);
    PatBlt(hDC, 0, 0, width, height, WHITENESS);
    TkWinReleaseDrawableDC(bitmap, hDC, &state);
#else
    XSetForeground(display, gc, 0);
    XFillRectangle(display, bitmap, gc, 0, 0, width, height);
#endif /* _WIN32 */

    XSetFont(display, gc, Tk_FontId(tsPtr->font));
    XSetForeground(display, gc, 1);
    DrawTextLayout(display, bitmap, gc, tsPtr->font, 0, 0, textPtr);

#ifdef _WIN32
    /*
     * Under Win32 when drawing into a bitmap, the bits are
     * reversed. Which is why we are inverting the bitmap here.
     */
    hDC = TkWinGetDrawableDC(display, bitmap, &state);
    PatBlt(hDC, 0, 0, width, height, DSTINVERT);
    TkWinReleaseDrawableDC(bitmap, hDC, &state);
#endif
    if(tsPtr->theta != 0.0) {
    Pixmap rotBitmap;

        /* Replace the text pixmap with a rotated one */

        rotBitmap = RbcRotateBitmap(tkwin, bitmap, width, height,
            tsPtr->theta, bmWidthPtr, bmHeightPtr);
        assert(rotBitmap);
        if(rotBitmap != None) {
            Tk_FreePixmap(display, bitmap);
            return rotBitmap;
        }
    }
    *bmWidthPtr = textPtr->width, *bmHeightPtr = textPtr->height;
    return bitmap;
}

/*
 *--------------------------------------------------------------
 *
 * RbcInitTextStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcInitTextStyle(
    RbcTextStyle * tsPtr)
{
    /* Initialize these attributes to zero */
    tsPtr->activeColor = (XColor *) NULL;
    tsPtr->anchor = TK_ANCHOR_CENTER;
    tsPtr->color = (XColor *) NULL;
    tsPtr->font = NULL;
    tsPtr->justify = TK_JUSTIFY_CENTER;
    tsPtr->leader = 0;
    tsPtr->padX.side1 = tsPtr->padX.side2 = 0;  /*x-padding */
    tsPtr->padY.side1 = tsPtr->padY.side2 = 0;  /*y-padding */
    tsPtr->shadow.color = (XColor *) NULL;
    tsPtr->shadow.offset = 0;
    tsPtr->state = 0;
    tsPtr->theta = 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetDrawTextStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetDrawTextStyle(
    RbcTextStyle * tsPtr,
    Tk_Font font,
    GC gc,
    XColor * normalColor,
    XColor * activeColor,
    XColor * shadowColor,
    double theta,
    Tk_Anchor anchor,
    Tk_Justify justify,
    int leader,
    int shadowOffset)
{
    RbcInitTextStyle(tsPtr);
    tsPtr->activeColor = activeColor;
    tsPtr->anchor = anchor;
    tsPtr->color = normalColor;
    tsPtr->font = font;
    tsPtr->gc = gc;
    tsPtr->justify = justify;
    tsPtr->leader = leader;
    tsPtr->shadow.color = shadowColor;
    tsPtr->shadow.offset = shadowOffset;
    tsPtr->theta = theta;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetPrintTextStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetPrintTextStyle(
    RbcTextStyle * tsPtr,
    Tk_Font font,
    XColor * fgColor,
    XColor * activeColor,
    XColor * shadowColor,
    double theta,
    Tk_Anchor anchor,
    Tk_Justify justify,
    int leader,
    int shadowOffset)
{
    RbcInitTextStyle(tsPtr);
    tsPtr->color = fgColor;
    tsPtr->activeColor = activeColor;
    tsPtr->shadow.color = shadowColor;
    tsPtr->font = font;
    tsPtr->theta = theta;
    tsPtr->anchor = anchor;
    tsPtr->justify = justify;
    tsPtr->leader = leader;
    tsPtr->shadow.offset = shadowOffset;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcDrawTextLayout --
 *
 *      Draw a text string, possibly rotated, using the the given
 *      window coordinates as an anchor for the text bounding box.
 *      If the text is not rotated, simply use the X text drawing
 *      routines. Otherwise, generate a bitmap of the rotated text.
 *
 * Results:
 *      Returns the x-coordinate to the right of the text.
 *
 * Side Effects:
 *      Text string is drawn using the given font and GC at the
 *      the given window coordinates.
 *
 *      The Stipple, FillStyle, and TSOrigin fields of the GC are
 *      modified for rotated text.  This assumes the GC is private,
 *      *not* shared (via Tk_GetGC)
 *
 * -----------------------------------------------------------------
 */
void
RbcDrawTextLayout(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTextLayout * textPtr,
    RbcTextStyle * tsPtr,      /* Text attribute information */
    int x,                     /* Window coordinates to draw text */
    int y)
{              /* Window coordinates to draw text */
    int width, height;
    double theta;
    Display *display;
    Pixmap bitmap;
    int active;

    display = Tk_Display(tkwin);
    theta = FMOD(tsPtr->theta, (double)360.0);
    if(theta < 0.0) {
        theta += 360.0;
    }
    active = tsPtr->state & RBC_STATE_ACTIVE;
    if(theta == 0.0) {

        /*
         * This is the easy case of no rotation. Simply draw the text
         * using the standard drawing routines.  Handle offset printing
         * for engraved (disabled) and shadowed text.
         */
        width = textPtr->width, height = textPtr->height;
        RbcTranslateAnchor(x, y, width, height, tsPtr->anchor, &x, &y);
        if(tsPtr->state & (RBC_STATE_DISABLED | RBC_STATE_EMPHASIS)) {
    TkBorder *borderPtr = (TkBorder *) tsPtr->border;
    XColor *color1, *color2;

            color1 = borderPtr->lightColorPtr, color2 = borderPtr->darkColorPtr;
            if(tsPtr->state & RBC_STATE_EMPHASIS) {
    XColor *hold;

                hold = color1, color1 = color2, color2 = hold;
            }
            if(color1 != NULL) {
                XSetForeground(display, tsPtr->gc, color1->pixel);
            }
            DrawTextLayout(display, drawable, tsPtr->gc, tsPtr->font, x + 1,
                y + 1, textPtr);
            if(color2 != NULL) {
                XSetForeground(display, tsPtr->gc, color2->pixel);
            }
            DrawTextLayout(display, drawable, tsPtr->gc, tsPtr->font, x, y,
                textPtr);

            /* Reset the foreground color back to its original setting,
             * so not to invalidate the GC cache. */
            XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);

            return;     /* Done */
        }
        if((tsPtr->shadow.offset > 0) && (tsPtr->shadow.color != NULL)) {
            XSetForeground(display, tsPtr->gc, tsPtr->shadow.color->pixel);
            DrawTextLayout(display, drawable, tsPtr->gc, tsPtr->font,
                x + tsPtr->shadow.offset, y + tsPtr->shadow.offset, textPtr);
            XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);
        }
        if(active) {
            XSetForeground(display, tsPtr->gc, tsPtr->activeColor->pixel);
        }
        DrawTextLayout(display, drawable, tsPtr->gc, tsPtr->font, x, y,
            textPtr);
        if(active) {
            XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);
        }
        return; /* Done */
    }
#ifdef _WIN32
    if(RbcDrawRotatedText(display, drawable, x, y, theta, tsPtr, textPtr)) {
        return;
    }
#endif
    /*
     * Rotate the text by writing the text into a bitmap and rotating
     * the bitmap.  Set the clip mask and origin in the GC first.  And
     * make sure we restore the GC because it may be shared.
     */
    tsPtr->theta = theta;
    bitmap = CreateTextBitmap(tkwin, textPtr, tsPtr, &width, &height);
    if(bitmap == None) {
        return;
    }
    RbcTranslateAnchor(x, y, width, height, tsPtr->anchor, &x, &y);
#ifdef notdef
    theta = FMOD(theta, (double)90.0);
#endif
    XSetClipMask(display, tsPtr->gc, bitmap);

    if(tsPtr->state & (RBC_STATE_DISABLED | RBC_STATE_EMPHASIS)) {
    TkBorder *borderPtr = (TkBorder *) tsPtr->border;
    XColor *color1, *color2;

        color1 = borderPtr->lightColorPtr, color2 = borderPtr->darkColorPtr;
        if(tsPtr->state & RBC_STATE_EMPHASIS) {
    XColor *hold;

            hold = color1, color1 = color2, color2 = hold;
        }
        if(color1 != NULL) {
            XSetForeground(display, tsPtr->gc, color1->pixel);
        }
        XSetClipOrigin(display, tsPtr->gc, x + 1, y + 1);
        XCopyPlane(display, bitmap, drawable, tsPtr->gc, 0, 0, width,
            height, x + 1, y + 1, 1);
        if(color2 != NULL) {
            XSetForeground(display, tsPtr->gc, color2->pixel);
        }
        XSetClipOrigin(display, tsPtr->gc, x, y);
        XCopyPlane(display, bitmap, drawable, tsPtr->gc, 0, 0, width,
            height, x, y, 1);
        XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);
    } else {
        if((tsPtr->shadow.offset > 0) && (tsPtr->shadow.color != NULL)) {
            XSetClipOrigin(display, tsPtr->gc, x + tsPtr->shadow.offset,
                y + tsPtr->shadow.offset);
            XSetForeground(display, tsPtr->gc, tsPtr->shadow.color->pixel);
            XCopyPlane(display, bitmap, drawable, tsPtr->gc, 0, 0, width,
                height, x + tsPtr->shadow.offset, y + tsPtr->shadow.offset, 1);
            XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);
        }
        if(active) {
            XSetForeground(display, tsPtr->gc, tsPtr->activeColor->pixel);
        }
        XSetClipOrigin(display, tsPtr->gc, x, y);
        XCopyPlane(display, bitmap, drawable, tsPtr->gc, 0, 0, width, height,
            x, y, 1);
        if(active) {
            XSetForeground(display, tsPtr->gc, tsPtr->color->pixel);
        }
    }
    XSetClipMask(display, tsPtr->gc, None);
    Tk_FreePixmap(display, bitmap);
}

/*
 *--------------------------------------------------------------
 *
 * RbcDrawText2 --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDrawText2(
    Tk_Window tkwin,
    Drawable drawable,
    char string[],
    RbcTextStyle * tsPtr,      /* Text attribute information */
    int x,                     /* Window coordinates to draw text */
    int y,                     /* Window coordinates to draw text */
    RbcDim2D * areaPtr)
{
    RbcTextLayout *textPtr;
    int width, height;
    double theta;

    if((string == NULL) || (*string == '\0')) {
        return; /* Empty string, do nothing */
    }
    textPtr = RbcGetTextLayout(string, tsPtr);
    RbcDrawTextLayout(tkwin, drawable, textPtr, tsPtr, x, y);
    theta = FMOD(tsPtr->theta, (double)360.0);
    if(theta < 0.0) {
        theta += 360.0;
    }
    width = textPtr->width;
    height = textPtr->height;
    if(theta != 0.0) {
    double rotWidth, rotHeight;

        RbcGetBoundingBox(width, height, theta, &rotWidth, &rotHeight,
            (RbcPoint2D *) NULL);
        width = ROUND(rotWidth);
        height = ROUND(rotHeight);
    }
    areaPtr->width = width;
    areaPtr->height = height;
    ckfree((char *)textPtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcDrawText --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDrawText(
    Tk_Window tkwin,
    Drawable drawable,
    char string[],
    RbcTextStyle * tsPtr,      /* Text attribute information */
    int x,                     /* Window coordinates to draw text */
    int y)
{              /* Window coordinates to draw text */
    RbcTextLayout *textPtr;

    if((string == NULL) || (*string == '\0')) {
        return; /* Empty string, do nothing */
    }
    textPtr = RbcGetTextLayout(string, tsPtr);
    RbcDrawTextLayout(tkwin, drawable, textPtr, tsPtr, x, y);
    ckfree((char *)textPtr);
}

/*
 *--------------------------------------------------------------
 *
 * RbcGetBitmapGC --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
GC
RbcGetBitmapGC(
    Tk_Window tkwin)
{
int isNew;
GC  gc;
Display *display;
Tcl_HashEntry *hPtr;

    if(!initialized) {
        Tcl_InitHashTable(&bitmapGCTable, TCL_ONE_WORD_KEYS);
        initialized = TRUE;
    }
    display = Tk_Display(tkwin);
    hPtr = Tcl_CreateHashEntry(&bitmapGCTable, (char *)display, &isNew);
    if(isNew) {
Pixmap bitmap;
XGCValues gcValues;
unsigned long gcMask;
Window root;

        root = RootWindow(display, Tk_ScreenNumber(tkwin));
        bitmap = Tk_GetPixmap(display, root, 1, 1, 1);
        gcValues.foreground = gcValues.background = 0;
        gcMask = (GCForeground | GCBackground);
        gc = RbcGetPrivateGCFromDrawable(display, bitmap, gcMask, &gcValues);
        Tk_FreePixmap(display, bitmap);
        Tcl_SetHashValue(hPtr, gc);
    } else {
        gc = (GC) Tcl_GetHashValue(hPtr);
    }
    return gc;
}

/*
 *--------------------------------------------------------------
 *
 * RbcResetTextStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcResetTextStyle(
    Tk_Window tkwin,
    RbcTextStyle * tsPtr)
{
GC  newGC;
XGCValues gcValues;
unsigned long gcMask;

    gcMask = GCFont;
    gcValues.font = Tk_FontId(tsPtr->font);
    if(tsPtr->color != NULL) {
        gcMask |= GCForeground;
        gcValues.foreground = tsPtr->color->pixel;
    }
    newGC = Tk_GetGC(tkwin, gcMask, &gcValues);
    if(tsPtr->gc != NULL) {
        Tk_FreeGC(Tk_Display(tkwin), tsPtr->gc);
    }
    tsPtr->gc = newGC;
}

/*
 *--------------------------------------------------------------
 *
 * RbcFreeTextStyle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcFreeTextStyle(
    Display * display,
    RbcTextStyle * tsPtr)
{
    if(tsPtr->gc != NULL) {
        Tk_FreeGC(display, tsPtr->gc);
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcTile.c.










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcTile.c --
 *
 *      This module manages images for tiled backgrounds for the rbc toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define TILE_THREAD_KEY	"Rbc Tile Data"
#define TILE_MAGIC ((unsigned int) 0x46170277)
typedef struct {
    Tcl_HashTable tileTable;   /* Hash table of tile structures keyed by
                                * the name of the image. */
    Tcl_Interp *interp;
} TileInterpData;
typedef struct {
    char *name;                /* Name of image used to generate the pixmap. */
    Display *display;          /* Display where pixmap was created. */
    int flags;                 /* See definitions below. */
    Tcl_Interp *interp;
    Tcl_HashEntry *hashPtr;    /* Pointer to hash table location */
    Tcl_HashTable *tablePtr;
    Pixmap pixmap;             /* Pixmap generated from image. */
    Pixmap mask;               /* Monochrome pixmap used as
                                * transparency mask. */
    GC  gc;                    /* GC */
    Tk_Image tkImage;          /* Tk image token. */
    RbcChain *clients;         /* Chain of clients sharing this tile. */
    int width, height;
} Tile;
/* If set, indicates that the image
* associated with the tile has been
* updated or deleted.  The tile pixmap
* will be changed and the clients of the
* tile will be notified (if they supplied
* a TileChangedProc routine. */
#define TILE_NOTIFY_PENDING	1
typedef struct RbcTileClient {
    unsigned int magic;
    Tk_Window tkwin;           /* Client window. */
    int xOrigin, yOrigin;      /* Tiling origin in relation to the
                                * client window. */
    RbcTileChangedProc *notifyProc;     /* If non-NULL, routine to
                                         * call to when tile image changes. */
    ClientData clientData;     /* Data to pass to when calling the above
                                * routine. */
    Tile *tilePtr;             /* Pointer to actual tile information */
    RbcChainLink *linkPtr;     /* Pointer to client entry in the server's
                                * client list.  Used to delete the client */
} RbcTileClient;
typedef struct {
    Display *display;
    Tk_Uid nameId;
    int depth;
} TileKey;
static Tcl_IdleProc UpdateTile;
static Tk_ImageChangedProc ImageChangedProc;
static Tcl_InterpDeleteProc TileInterpDeleteProc;
static TileInterpData *GetTileInterpData(
    Tcl_Interp * interp);
static void DestroyClient(
    RbcTileClient * clientPtr);
static void DestroyTile(
    Tile * tilePtr);
static void RedrawTile(
    Tk_Window tkwin,
    Tile * tilePtr);
static Tile *CreateTile(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *imageName);
static RbcTileClient *CreateClient(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *name);
#ifdef _WIN32
static void TileRegion(
    HDC srcDC,
    HDC destDC,
    HDC maskDC,
    RbcTileClient * clientPtr,
    int x,
    int y,
    int width,
    int height);
#endif
/*
 *--------------------------------------------------------------
 *
 * RedrawTile --
 *
 *      Generates a pixmap and draws the tile image into it.  Also
 *      a tranparency mask is possibly generated from the image.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
RedrawTile(
    Tk_Window tkwin,
    Tile * tilePtr)
{
GC  newGC;
Tk_PhotoHandle photo;
XGCValues gcValues;
int width, height;
unsigned int gcMask;
    Tk_SizeOfImage(tilePtr->tkImage, &width, &height);
    Tk_MakeWindowExist(tkwin);
    if((width != tilePtr->width) || (height != tilePtr->height)) {
Pixmap pixmap;
        /*
         * Create the new pixmap *before* destroying the old one.  I don't
         * why this happens, but if you delete the old pixmap first, the
         * old pixmap sometimes gets used in the client's GCs.  I suspect
         * it has something to do with the way Tk reallocates X resource
         * identifiers.
         */
        pixmap = Tk_GetPixmap(Tk_Display(tkwin), Tk_WindowId(tkwin), width,
            height, Tk_Depth(tkwin));
        if(tilePtr->pixmap != None) {
            Tk_FreePixmap(Tk_Display(tkwin), tilePtr->pixmap);
        }
        tilePtr->pixmap = pixmap;
    }
    Tk_RedrawImage(tilePtr->tkImage, 0, 0, width, height, tilePtr->pixmap,
        0, 0);
    gcMask = (GCTile | GCFillStyle);
    gcValues.fill_style = FillTiled;
    gcValues.tile = tilePtr->pixmap;
    newGC = Tk_GetGC(tkwin, gcMask, &gcValues);
    if(tilePtr->gc != NULL) {
        Tk_FreeGC(Tk_Display(tkwin), tilePtr->gc);
    }
    tilePtr->gc = newGC;
    tilePtr->width = width;
    tilePtr->height = height;
    if(tilePtr->mask != None) {
#ifdef _WIN32
        Tk_FreePixmap(Tk_Display(tkwin), tilePtr->mask);
#else
        XFreePixmap(Tk_Display(tkwin), tilePtr->mask);
#endif /* _WIN32 */
        tilePtr->mask = None;
    }
    photo = Tk_FindPhoto(tilePtr->interp, RbcNameOfImage(tilePtr->tkImage));
    if(photo != NULL) {
Tk_PhotoImageBlock src;
        Tk_PhotoGetImage(photo, &src);
        if((src.offset[3] < src.pixelSize) && (src.offset[3] >= 0)) {
            tilePtr->mask = RbcPhotoImageMask(tkwin, src);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * UpdateTile --
 *
 *      It would be better if Tk checked for NULL proc pointers.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
UpdateTile(
    ClientData clientData)
{
Tile *tilePtr = (Tile *) clientData;
RbcTileClient *clientPtr;
RbcChainLink *linkPtr;
    tilePtr->flags &= ~TILE_NOTIFY_PENDING;
    if(RbcImageIsDeleted(tilePtr->tkImage)) {
        if(tilePtr->pixmap != None) {
            Tk_FreePixmap(tilePtr->display, tilePtr->pixmap);
        }
        tilePtr->pixmap = None;
    } else {
        /* Pick any client window to generate the new pixmap. */
        linkPtr = RbcChainFirstLink(tilePtr->clients);
        clientPtr = RbcChainGetValue(linkPtr);
        RedrawTile(clientPtr->tkwin, tilePtr);
    }
    /* Notify each of the tile's clients that the pixmap has changed. */
    for(linkPtr = RbcChainFirstLink(tilePtr->clients); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        clientPtr = RbcChainGetValue(linkPtr);
        if(clientPtr->notifyProc != NULL) {
            (*clientPtr->notifyProc) (clientPtr->clientData, clientPtr);
        }
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ImageChangedProc
 *
 *      The Tk image has changed or been deleted, redraw the pixmap
 *      tile.
 *
 *      Note: As of Tk 4.2 (rechecked in 8.3), if you redraw Tk
 *      images from a Tk_ImageChangedProc you'll get a
 *      coredump.  As a workaround, we have to simulate
 *      how the Tk widgets use images and redraw within
 *      an idle event.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
ImageChangedProc(
    ClientData clientData,
    int x,                     /* Not used. */
    int y,                     /* Not used. */
    int width,                 /* Not used. */
    int height,                /* Not used. */
    int imageWidth,            /* Not used. */
    int imageHeight)
{              /* Not used. */
    Tile *tilePtr = (Tile *) clientData;
    if(!(tilePtr->flags & TILE_NOTIFY_PENDING)) {
        Tcl_DoWhenIdle(UpdateTile, tilePtr);
        tilePtr->flags |= TILE_NOTIFY_PENDING;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyTile --
 *
 *      Deletes the core tile structure, including the pixmap
 *      representing the tile.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyTile(
    Tile * tilePtr)
{
RbcChainLink *linkPtr;
RbcTileClient *clientPtr;
    if(tilePtr->flags & TILE_NOTIFY_PENDING) {
        Tcl_CancelIdleCall(UpdateTile, tilePtr);
    }
    for(linkPtr = RbcChainFirstLink(tilePtr->clients); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        clientPtr = RbcChainGetValue(linkPtr);
        ckfree((char *)clientPtr);
    }
    RbcChainDestroy(tilePtr->clients);
    if(tilePtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(tilePtr->hashPtr);
    }
    if(tilePtr->pixmap != None) {
        Tk_FreePixmap(tilePtr->display, tilePtr->pixmap);
    }
    Tk_FreeImage(tilePtr->tkImage);
    if(tilePtr->gc != NULL) {
        Tk_FreeGC(tilePtr->display, tilePtr->gc);
    }
    if(tilePtr->name != NULL) {
        ckfree((char *)tilePtr->name);
    }
    ckfree((char *)tilePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateTile --
 *
 *      Creates a tile server.  A tile server manages a single image,
 *      possibly shared by several clients.  Clients will be updated
 *      (if requested) by the server if the image changes, so they
 *      know to redraw themselves.  For X11 the image is drawn into a
 *      pixmap that is used in a new GC as its tile.  For Windows we
 *      have to do the tiling ourselves by redrawing the image across
 *      the drawing area (see RbcTileRectangle and RbcTilePolygon).
 *
 * Results:
 *      Returns a pointer to the new tile server.  If the image name
 *      does not represent a Tk image, NULL is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static Tile *
CreateTile(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *imageName)
{
    Tile *tilePtr;
    Tk_Image tkImage;
    tilePtr = RbcCalloc(1, sizeof(Tile));
    assert(tilePtr);
    /*
     * Get the image. Funnel all change notifications to a single routine.
     */
    tkImage = Tk_GetImage(interp, tkwin, imageName, ImageChangedProc, tilePtr);
    if(tkImage == NULL) {
        ckfree((char *)tilePtr);
        return NULL;
    }
    /*
     * Initialize the tile server.
     */
    tilePtr->display = Tk_Display(tkwin);
    tilePtr->interp = interp;
    tilePtr->name = RbcStrdup(imageName);
    tilePtr->clients = RbcChainCreate();
    tilePtr->tkImage = tkImage;
    RedrawTile(tkwin, tilePtr);
    return tilePtr;
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyClient --
 *
 *      Removes the client from the servers's list of clients and
 *      memory used by the client token is released.  When the last
 *      client is deleted, the server is also removed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static void
DestroyClient(
    RbcTileClient * clientPtr)
{
Tile *tilePtr;
    tilePtr = clientPtr->tilePtr;
    /* Remove the client from the server's list */
    if(clientPtr->linkPtr != NULL) {
        RbcChainDeleteLink(tilePtr->clients, clientPtr->linkPtr);
    }
    if(RbcChainGetLength(tilePtr->clients) == 0) {
        /*
         * If there are no more clients of the tile, then remove the
         * pixmap, image, and the server record.
         */
        DestroyTile(tilePtr);
    }
    ckfree((char *)clientPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * CreateClient --
 *
 *      Returns a token to a tile (possibly shared by many clients).
 *      A client uses the token to query or display the tile.  Clients
 *      request tiles by their image names.  Each tile is known by its
 *      display, screen depth, and image name.  The tile server tracks
 *      what clients are using the tile and notifies them (via a
 *      callback) whenever the tile changes. If no server exists
 *      already, one is created on-the-fly.
 *
 * Results:
 *      A pointer to the newly created client (i.e. tile).
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static RbcTileClient *
CreateClient(
    Tcl_Interp * interp,
    Tk_Window tkwin,
    const char *name)
{
    RbcTileClient *clientPtr;
    Tile *tilePtr;
    TileInterpData *dataPtr;
    Tcl_HashEntry *hPtr;
    int isNew;
    TileKey key;
    dataPtr = GetTileInterpData(interp);
    key.nameId = Tk_GetUid(name);
    key.display = Tk_Display(tkwin);
    key.depth = Tk_Depth(tkwin);
    hPtr = Tcl_CreateHashEntry(&dataPtr->tileTable, (char *)&key, &isNew);
    if(isNew) {
        tilePtr = CreateTile(interp, tkwin, name);
        if(tilePtr == NULL) {
            Tcl_DeleteHashEntry(hPtr);
            return NULL;
        }
        tilePtr->hashPtr = hPtr;
        tilePtr->tablePtr = &(dataPtr->tileTable);
        Tcl_SetHashValue(hPtr, tilePtr);
    } else {
        tilePtr = Tcl_GetHashValue(hPtr);
    }
    clientPtr = RbcCalloc(1, sizeof(RbcTileClient));
    assert(clientPtr);
    /* Initialize client information. */
    clientPtr->magic = TILE_MAGIC;
    clientPtr->tkwin = tkwin;
    clientPtr->linkPtr = RbcChainAppend(tilePtr->clients, clientPtr);
    clientPtr->tilePtr = tilePtr;
    return clientPtr;
}

/*
 * -----------------------------------------------------------------------
 *
 * TileInterpDeleteProc --
 *
 *      This is called when the interpreter is deleted. All the tiles
 *      are specific to that interpreter are destroyed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Destroys the tile table.
 *
 * ------------------------------------------------------------------------
 */
static void
TileInterpDeleteProc(
    ClientData clientData,     /* Thread-specific data. */
    Tcl_Interp * interp)
{
TileInterpData *dataPtr = clientData;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
Tile *tilePtr;
    for(hPtr = Tcl_FirstHashEntry(&(dataPtr->tileTable), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        tilePtr = Tcl_GetHashValue(hPtr);
        tilePtr->hashPtr = NULL;
        DestroyTile(tilePtr);
    }
    Tcl_DeleteHashTable(&(dataPtr->tileTable));
    Tcl_DeleteAssocData(interp, TILE_THREAD_KEY);
    ckfree((char *)dataPtr);
}

/*
 *--------------------------------------------------------------
 *
 * GetTileInterpData --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static TileInterpData *
GetTileInterpData(
    Tcl_Interp * interp)
{
TileInterpData *dataPtr;
Tcl_InterpDeleteProc *proc;
    dataPtr = (TileInterpData *)
        Tcl_GetAssocData(interp, TILE_THREAD_KEY, &proc);
    if(dataPtr == NULL) {
        dataPtr = (TileInterpData *) ckalloc(sizeof(TileInterpData));
        assert(dataPtr);
        dataPtr->interp = interp;
        Tcl_SetAssocData(interp, TILE_THREAD_KEY, TileInterpDeleteProc,
            dataPtr);
        Tcl_InitHashTable(&(dataPtr->tileTable), sizeof(TileKey) / sizeof(int));
    }
    return dataPtr;
}

/* Public API for tiles. */
/*
 *----------------------------------------------------------------------
 *
 * RbcGetTile
 *
 *      Convert the named image into a tile.
 *
 * Results:
 *      If the image is valid, a new tile is returned.  If the name
 *      does not represent a proper image, an error message is left in
 *      Tcl_GetString(Tcl_GetObjResult(interp)).
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcGetTile(
    Tcl_Interp * interp,       /* Interpreter to report results back to */
    Tk_Window tkwin,           /* Window on the same display as tile */
    const char *imageName,     /* Name of image */
    RbcTile * tokenPtr)
{              /* (out) Returns the allocated tile token. */
    RbcTileClient *clientPtr;
    clientPtr = CreateClient(interp, tkwin, imageName);
    if(clientPtr == NULL) {
        return TCL_ERROR;
    }
    *tokenPtr = clientPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcFreeTile
 *
 *      Release the resources associated with the tile.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Memory and X resources are freed.  Bookkeeping information
 *      about the tile (i.e. width, height, and name) is discarded.
 *
 *----------------------------------------------------------------------
 */
void
RbcFreeTile(
    RbcTileClient * clientPtr)
{              /* Tile to be deleted */
    if((clientPtr == NULL) || (clientPtr->magic != TILE_MAGIC)) {
        return; /* No tile */
    }
    DestroyClient(clientPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcNameOfTile
 *
 *      Returns the name of the image from which the tile was
 *      generated.
 *
 * Results:
 *      The name of the image is returned.  The name is not unique.
 *      Many tiles may use the same image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
const char *
RbcNameOfTile(
    RbcTileClient * clientPtr)
{              /* Tile to query */
    if(clientPtr == NULL) {
        return "";
    }
    if(clientPtr->magic != TILE_MAGIC) {
        return "not a tile";
    }
    return clientPtr->tilePtr->name;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcPixmapOfTile
 *
 *      Returns the pixmap of the tile.
 *
 * Results:
 *      The X pixmap used as the tile is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
Pixmap
RbcPixmapOfTile(
    RbcTileClient * clientPtr)
{              /* Tile to query */
    if((clientPtr == NULL) || (clientPtr->magic != TILE_MAGIC)) {
        return None;
    }
    return clientPtr->tilePtr->pixmap;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSizeOfTile
 *
 *      Returns the width and height of the tile.
 *
 * Results:
 *      The width and height of the tile are returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void
RbcSizeOfTile(
    RbcTileClient * clientPtr, /* Tile to query */
    int *widthPtr,
    int *heightPtr)
{              /* Returned dimensions of the tile (out) */
    if((clientPtr == NULL) || (clientPtr->magic != TILE_MAGIC)) {
        *widthPtr = *heightPtr = 0;
        return; /* No tile given. */
    }
    *widthPtr = clientPtr->tilePtr->width;
    *heightPtr = clientPtr->tilePtr->height;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSetTileChangedProc
 *
 *      Sets the routine to called when an image changes.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The designated routine will be called the next time the
 *      image associated with the tile changes.
 *
 *----------------------------------------------------------------------
 */
void
RbcSetTileChangedProc(
    RbcTileClient * clientPtr, /* Tile to query */
    RbcTileChangedProc * notifyProc,
    ClientData clientData)
{
    if((clientPtr != NULL) && (clientPtr->magic == TILE_MAGIC)) {
        clientPtr->notifyProc = notifyProc;
        clientPtr->clientData = clientData;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcSetTileOrigin --
 *
 *      Set the pattern origin of the tile to a common point (i.e. the
 *      origin (0,0) of the top level window) so that tiles from two
 *      different widgets will match up.  This done by setting the
 *      GCTileStipOrigin field is set to the translated origin of the
 *      toplevel window in the hierarchy.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The GCTileStipOrigin is reset in the GC.  This will cause the
 *      tile origin to change when the GC is used for drawing.
 *
 *----------------------------------------------------------------------
 */
void
RbcSetTileOrigin(
    Tk_Window tkwin,
    RbcTileClient * clientPtr,
    int x,
    int y)
{
    while(!Tk_IsTopLevel(tkwin)) {
        x += Tk_X(tkwin) + Tk_Changes(tkwin)->border_width;
        y += Tk_Y(tkwin) + Tk_Changes(tkwin)->border_width;
        tkwin = Tk_Parent(tkwin);
    }
    XSetTSOrigin(Tk_Display(tkwin), clientPtr->tilePtr->gc, -x, -y);
    clientPtr->xOrigin = -x;
    clientPtr->yOrigin = -y;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetTSOrigin --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetTSOrigin(
    Tk_Window tkwin,
    RbcTileClient * clientPtr,
    int x,
    int y)
{
    XSetTSOrigin(Tk_Display(tkwin), clientPtr->tilePtr->gc, x, y);
    clientPtr->xOrigin = x;
    clientPtr->yOrigin = y;
}

#ifdef _WIN32
#define MASKPAT		0x00E20746      /* dest = (src & pat) | (!src & dst) */
#define COPYFG		0x00CA0749      /* dest = (pat & src) | (!pat & dst) */
#define COPYBG		0x00AC0744      /* dest = (!pat & src) | (pat & dst) */
/*
 *--------------------------------------------------------------
 *
 * TileRegion --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static void
TileRegion(
    HDC srcDC,                 /* Source device context. */
    HDC destDC,                /* Destination device context. */
    HDC maskDC,                /* If non-NULL, device context of the
                                * mask tile mask. */
    RbcTileClient * clientPtr,
    int x,
    int y,
    int width,
    int height)
{
    Tile *tilePtr = clientPtr->tilePtr;
    int destX, destY;
    int destWidth, destHeight;
    int srcX, srcY;
    int startX, startY;        /* Starting upper left corner of region. */
    int delta;
    int left, top, right, bottom;
    startX = x;
    if(x < clientPtr->xOrigin) {
        delta = (clientPtr->xOrigin - x) % tilePtr->width;
        if(delta > 0) {
            startX -= (tilePtr->width - delta);
        }
    } else if(x > clientPtr->xOrigin) {
        delta = (x - clientPtr->xOrigin) % tilePtr->width;
        if(delta > 0) {
            startX -= delta;
        }
    }
    startY = y;
    if(y < clientPtr->yOrigin) {
        delta = (clientPtr->yOrigin - y) % tilePtr->height;
        if(delta > 0) {
            startY -= (tilePtr->height - delta);
        }
    } else if(y >= clientPtr->yOrigin) {
        delta = (y - clientPtr->yOrigin) % tilePtr->height;
        if(delta > 0) {
            startY -= delta;
        }
    }
#ifdef notdef
    PurifyPrintf("tile is (%d,%d,%d,%d)\n",
        clientPtr->xOrigin, clientPtr->yOrigin,
        tilePtr->width, tilePtr->height);
    PurifyPrintf("region is (%d,%d,%d,%d)\n", x, y, width, height);
    PurifyPrintf("starting at %d,%d\n", startX, startY);
#endif
    left = x;
    right = x + width;
    top = y;
    bottom = y + height;
    for(y = startY; y < bottom; y += tilePtr->height) {
        srcY = 0;
        destY = y;
        destHeight = tilePtr->height;
        if(y < top) {
            srcY = (top - y);
            destHeight = tilePtr->height - srcY;
            destY = top;
        }
        if((destY + destHeight) > bottom) {
            destHeight = (bottom - destY);
        }
        for(x = startX; x < right; x += tilePtr->width) {
            srcX = 0;
            destX = x;
            destWidth = tilePtr->width;
            if(x < left) {
                srcX = (left - x);
                destWidth = tilePtr->width - srcX;
                destX = left;
            }
            if((destX + destWidth) > right) {
                destWidth = (right - destX);
            }
#ifdef notdef
            PurifyPrintf("drawing pattern (%d,%d,%d,%d) at %d,%d\n",
                srcX, srcY, destWidth, destHeight, destX, destY);
#endif
            if(tilePtr->mask != None) { /* With transparency. */
#ifdef notdef
    HDC maskDC;
    TkWinDCState maskState;
                maskDC = TkWinGetDrawableDC(tilePtr->display,
                    tilePtr->mask, &maskState);
                SetBkColor(destDC, RGB(255, 255, 255));
                SetTextColor(destDC, RGB(0, 0, 0));
#endif
                BitBlt(destDC, destX, destY, destWidth, destHeight, maskDC,
                    0, 0, SRCAND);
                BitBlt(destDC, destX, destY, destWidth, destHeight, srcDC,
                    srcX, srcY, SRCPAINT);
#ifdef notdef
                TkWinReleaseDrawableDC(tilePtr->mask, maskDC, &maskState);
#endif
            } else {    /* Opaque tile. */
                BitBlt(destDC, destX, destY, destWidth, destHeight,
                    srcDC, srcX, srcY, SRCCOPY);
            }
        }
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcTilePolygon --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcTilePolygon(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    XPoint pointArr[],
    int nPoints)
{
    HBITMAP oldBitmap;
    HDC hDC, memDC;
    HRGN hRgn;
    POINT *p, *winPts;
    RbcRegion2D bbox;
    Tile *tilePtr;
    TkWinDCState state;
    TkWinDrawable *twdPtr;
    XPoint *endPtr, *pointPtr;
    int fillMode;
    int width, height;
    if(drawable == None) {
        return;
    }
    tilePtr = clientPtr->tilePtr;
    /* Determine the bounding box of the polygon. */
    bbox.left = bbox.right = pointArr[0].x;
    bbox.top = bbox.bottom = pointArr[0].y;
    endPtr = pointArr + nPoints;
    for(pointPtr = pointArr; pointPtr < endPtr; pointPtr++) {
        if(pointPtr->x < bbox.left) {
            bbox.left = pointPtr->x;
        }
        if(pointPtr->x > bbox.right) {
            bbox.right = pointPtr->x;
        }
        if(pointPtr->y < bbox.top) {
            bbox.top = pointPtr->y;
        }
        if(pointPtr->y > bbox.bottom) {
            bbox.bottom = pointPtr->y;
        }
    }
    width = bbox.right - bbox.left + 1;
    height = bbox.bottom - bbox.top + 1;
    /* Allocate and fill an array of POINTS to create the polygon path. */
    p = winPts = (POINT *) ckalloc(sizeof(POINT) * nPoints);
    for(pointPtr = pointArr; pointPtr < endPtr; pointPtr++) {
        p->x = pointPtr->x - bbox.left;
        p->y = pointPtr->y - bbox.top;
        p++;
    }
    hDC = TkWinGetDrawableDC(Tk_Display(tkwin), drawable, &state);
    RbcSetROP2(hDC, tilePtr->gc->function);
    fillMode = (tilePtr->gc->fill_rule == EvenOddRule) ? ALTERNATE : WINDING;
    /* Use the polygon as a clip path. */
    LPtoDP(hDC, winPts, nPoints);
    hRgn = CreatePolygonRgn(winPts, nPoints, fillMode);
    SelectClipRgn(hDC, hRgn);
    OffsetClipRgn(hDC, bbox.left, bbox.top);
    ckfree((char *)winPts);
    twdPtr = (TkWinDrawable *) tilePtr->pixmap;
    memDC = CreateCompatibleDC(hDC);
    oldBitmap = SelectBitmap(memDC, twdPtr->bitmap.handle);
    /* Tile the bounding box. */
    if(tilePtr->mask != None) {
    TkWinDCState maskState;
    HDC maskDC;
        maskDC = TkWinGetDrawableDC(tilePtr->display, tilePtr->mask,
            &maskState);
        SetBkColor(hDC, RGB(255, 255, 255));
        SetTextColor(hDC, RGB(0, 0, 0));
        TileRegion(memDC, hDC, maskDC, clientPtr, bbox.left, bbox.top, width,
            height);
        TkWinReleaseDrawableDC(tilePtr->mask, maskDC, &maskState);
    } else {
        TileRegion(memDC, hDC, NULL, clientPtr, bbox.left, bbox.top, width,
            height);
    }
    SelectBitmap(memDC, oldBitmap);
    DeleteDC(memDC);
    SelectClipRgn(hDC, NULL);
    DeleteRgn(hRgn);
    TkWinReleaseDrawableDC(drawable, hDC, &state);
}

/*
 *--------------------------------------------------------------
 *
 * RbcTileRectangle --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcTileRectangle(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    int x,
    int y,
    unsigned int width,
    unsigned int height)
{
    HBITMAP oldBitmap;
    HDC hDC, memDC;
    Tile *tilePtr;
    TkWinDCState state;
    TkWinDrawable *twdPtr;
    if(drawable == None) {
        return;
    }
    tilePtr = clientPtr->tilePtr;
    hDC = TkWinGetDrawableDC(Tk_Display(tkwin), drawable, &state);
    RbcSetROP2(hDC, tilePtr->gc->function);
    twdPtr = (TkWinDrawable *) tilePtr->pixmap;
    memDC = CreateCompatibleDC(hDC);
    oldBitmap = SelectBitmap(memDC, twdPtr->bitmap.handle);
    /* Tile the bounding box. */
    if(tilePtr->mask != None) {
    TkWinDCState maskState;
    HDC maskDC;
        maskDC = TkWinGetDrawableDC(tilePtr->display, tilePtr->mask,
            &maskState);
        SetBkColor(hDC, RGB(255, 255, 255));
        SetTextColor(hDC, RGB(0, 0, 0));
        TileRegion(memDC, hDC, maskDC, clientPtr, x, y, width, height);
        TkWinReleaseDrawableDC(tilePtr->mask, maskDC, &maskState);
    } else {
        TileRegion(memDC, hDC, NULL, clientPtr, x, y, width, height);
    }
    SelectBitmap(memDC, oldBitmap);
    DeleteDC(memDC);
    TkWinReleaseDrawableDC(drawable, hDC, &state);
}

/*
 *--------------------------------------------------------------
 *
 * RbcTileRectangles --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcTileRectangles(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    XRectangle rectArr[],
    int nRectangles)
{
    HBITMAP oldBitmap;
    HDC hDC, memDC;
    Tile *tilePtr;
    TkWinDCState state;
    TkWinDrawable *twdPtr;
    XRectangle *rectPtr, *endPtr;
    if(drawable == None) {
        return;
    }
    tilePtr = clientPtr->tilePtr;
    hDC = TkWinGetDrawableDC(Tk_Display(tkwin), drawable, &state);
    RbcSetROP2(hDC, tilePtr->gc->function);
    twdPtr = (TkWinDrawable *) tilePtr->pixmap;
    memDC = CreateCompatibleDC(hDC);
    oldBitmap = SelectBitmap(memDC, twdPtr->bitmap.handle);
    endPtr = rectArr + nRectangles;
    /* Tile the bounding box. */
    if(tilePtr->mask != None) {
    TkWinDCState maskState;
    HDC maskDC;
        maskDC = TkWinGetDrawableDC(tilePtr->display, tilePtr->mask,
            &maskState);
        SetBkColor(hDC, RGB(255, 255, 255));
        SetTextColor(hDC, RGB(0, 0, 0));
        for(rectPtr = rectArr; rectPtr < endPtr; rectPtr++) {
            TileRegion(memDC, hDC, maskDC, clientPtr, (int)rectPtr->x,
                (int)rectPtr->y, (int)rectPtr->width, (int)rectPtr->height);
        }
        TkWinReleaseDrawableDC(tilePtr->mask, maskDC, &maskState);
    } else {
        for(rectPtr = rectArr; rectPtr < endPtr; rectPtr++) {
            TileRegion(memDC, hDC, NULL, clientPtr, (int)rectPtr->x,
                (int)rectPtr->y, (int)rectPtr->width, (int)rectPtr->height);
        }
    }
    SelectBitmap(memDC, oldBitmap);
    DeleteDC(memDC);
    TkWinReleaseDrawableDC(drawable, hDC, &state);
}
#else
/*
 *----------------------------------------------------------------------
 *
 * RectangleMask --
 *
 *      Creates a rectangular mask also stippled by the mask of the
 *      tile.  This is used to draw the tiled polygon images with
 *      transparent areas.
 *
 * Results:
 *      A bitmap mask is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static Pixmap
RectangleMask(
    Display * display,
    Drawable drawable,
    int x,
    int y,
    unsigned int width,
    unsigned int height,
    Pixmap mask,
    int xOrigin,
    int yOrigin)
{
    GC  gc;
    Pixmap bitmap;
    XGCValues gcValues;
    unsigned long gcMask;
    bitmap = Tk_GetPixmap(display, drawable, width, height, 1);
    gcMask = (GCForeground | GCBackground | GCFillStyle |
        GCTileStipXOrigin | GCTileStipYOrigin | GCStipple);
    gcValues.foreground = 0x1;
    gcValues.background = 0x0;
    gcValues.fill_style = FillOpaqueStippled;
    gcValues.ts_x_origin = xOrigin - x;
    gcValues.ts_y_origin = yOrigin - y;
    gcValues.stipple = mask;
    gc = XCreateGC(display, bitmap, gcMask, &gcValues);
    XFillRectangle(display, bitmap, gc, 0, 0, width, height);
    RbcFreePrivateGC(display, gc);
    return bitmap;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcTileRectangle --
 *
 *      Draws a rectangle filled by a tiled image.  This differs from
 *      the normal XFillRectangle call in that we also try to handle
 *      a transparency mask.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws the rectangle.
 *
 *----------------------------------------------------------------------
 */
void
RbcTileRectangle(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    int x,
    int y,
    unsigned int width,
    unsigned int height)
{
    Tile *tilePtr;
    Display *display;
    display = Tk_Display(tkwin);
    tilePtr = clientPtr->tilePtr;
    if(clientPtr->tilePtr->mask != None) {
    Pixmap mask;
        mask = RectangleMask(display, drawable, x, y, width, height,
            tilePtr->mask, clientPtr->xOrigin, clientPtr->yOrigin);
        XSetClipMask(display, tilePtr->gc, mask);
        XSetClipOrigin(display, tilePtr->gc, x, y);
        XFillRectangle(display, drawable, tilePtr->gc, x, y, width, height);
        XSetClipMask(display, tilePtr->gc, None);
        XSetClipOrigin(display, tilePtr->gc, 0, 0);
        Tk_FreePixmap(display, mask);
    } else {
        XFillRectangle(display, drawable, tilePtr->gc, x, y, width, height);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcTileRectangles --
 *
 *      Draws rectangles filled by a tiled image.  This differs from
 *      the normal XFillRectangles call in that we also try to handle
 *      a transparency mask.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws the given rectangles.
 *
 *----------------------------------------------------------------------
 */
void
RbcTileRectangles(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    XRectangle rectArr[],
    int nRectangles)
{
    Tile *tilePtr;
    tilePtr = clientPtr->tilePtr;
    if(tilePtr->mask != None) {
    XRectangle *rectPtr, *endPtr;
        endPtr = rectArr + nRectangles;
        for(rectPtr = rectArr; rectPtr < endPtr; rectPtr++) {
            RbcTileRectangle(tkwin, drawable, clientPtr, rectPtr->x,
                rectPtr->y, rectPtr->width, rectPtr->height);
        }
    } else {
        XFillRectangles(Tk_Display(tkwin), drawable, tilePtr->gc, rectArr,
            nRectangles);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * PolygonMask --
 *
 *      Creates a polygon shaped mask also stippled by the mask
 *      of the tile.  This is used to draw the tiled polygon images
 *      with transparent areas.
 *
 * Results:
 *      A bitmap mask is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static Pixmap
PolygonMask(
    Display * display,
    XPoint * pointArr,
    int nPoints,
    RbcRegion2D * regionPtr,
    Pixmap mask,
    int xOrigin,
    int yOrigin)
{
    unsigned int width, height;
    Pixmap bitmap;
    GC  gc;
    XPoint *destArr;
    register XPoint *srcPtr, *destPtr, *endPtr;
    width = regionPtr->right - regionPtr->left + 1;
    height = regionPtr->bottom - regionPtr->top + 1;
    bitmap =
        Tk_GetPixmap(display, DefaultRootWindow(display), width, height, 1);
    destArr = (XPoint *) ckalloc(sizeof(XPoint) * nPoints);
    endPtr = destArr + nPoints;
    srcPtr = pointArr;
    for(destPtr = destArr; destPtr < endPtr; destPtr++) {
        destPtr->x = srcPtr->x - regionPtr->left;
        destPtr->y = srcPtr->y - regionPtr->top;
        srcPtr++;
    }
    gc = XCreateGC(display, bitmap, 0, NULL);
    XFillRectangle(display, bitmap, gc, 0, 0, width, height);
    XSetForeground(display, gc, 0x01);
    XSetFillStyle(display, gc, FillStippled);
    XSetTSOrigin(display, gc, xOrigin - regionPtr->left,
        yOrigin - regionPtr->top);
    XSetStipple(display, gc, mask);
    XFillPolygon(display, bitmap, gc, destArr, nPoints, Complex,
        CoordModeOrigin);
    XFreeGC(display, gc);
    ckfree((char *)destArr);
    return bitmap;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcTilePolygon --
 *
 *      Draws a polygon filled by a tiled image.  This differs from
 *      the normal XFillPolygon call in that we also try to handle
 *      a transparency mask.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Draws the polygon.
 *
 *----------------------------------------------------------------------
 */
void
RbcTilePolygon(
    Tk_Window tkwin,
    Drawable drawable,
    RbcTileClient * clientPtr,
    XPoint pointArr[],
    int nPoints)
{
    Tile *tilePtr;
    Display *display;
    display = Tk_Display(tkwin);
    tilePtr = clientPtr->tilePtr;
    if(tilePtr->mask != None) {
    XPoint *pointPtr, *endPtr;
    RbcRegion2D region;
    Pixmap mask;
        /* Determine the bounding box of the polygon. */
        pointPtr = pointArr;
        region.left = region.right = pointPtr->x;
        region.top = region.bottom = pointPtr->y;
        endPtr = pointArr + nPoints;
        for(pointPtr = pointArr; pointPtr < endPtr; pointPtr++) {
            if(region.left > pointPtr->x) {
                region.left = pointPtr->x;
            } else if(region.right < pointPtr->x) {
                region.right = pointPtr->x;
            }
            if(region.top > pointPtr->y) {
                region.top = pointPtr->y;
            } else if(region.bottom < pointPtr->y) {
                region.bottom = pointPtr->y;
            }
        }
        mask = PolygonMask(display, pointArr, nPoints, &region,
            tilePtr->mask, clientPtr->xOrigin, clientPtr->yOrigin);
        XSetClipMask(display, tilePtr->gc, mask);
        XSetClipOrigin(display, tilePtr->gc, region.left, region.top);
        XFillPolygon(display, drawable, tilePtr->gc, pointArr,
            nPoints, Complex, CoordModeOrigin);
        XSetClipMask(display, tilePtr->gc, None);
        XSetClipOrigin(display, tilePtr->gc, 0, 0);
        Tk_FreePixmap(display, mask);
    } else {
        XFillPolygon(display, drawable, tilePtr->gc, pointArr,
            nPoints, Complex, CoordModeOrigin);
    }
}
#endif
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcUnixImage.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcUnixImage.c --
 *
 *	This module implements image processing procedures for the rbc
 *	toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define RGBIndex(r,g,b) (((r)<<10) + ((r)<<6) + (r) + ((g) << 5) + (g) + (b))

/* Defined rbcColor.c TODO
extern int redAdjust, greenAdjust, blueAdjust;
extern int redMaskShift, greenMaskShift, blueMaskShift;
*/
int redAdjust, greenAdjust, blueAdjust;
int redMaskShift, greenMaskShift, blueMaskShift;

/*
 *----------------------------------------------------------------------
 *
 * ShiftCount --
 *
 *	Returns the position of the least significant (low) bit in
 *	the given mask.
 *
 *	For TrueColor and DirectColor visuals, a pixel value is
 *	formed by OR-ing the red, green, and blue colormap indices
 *	into a single 32-bit word.  The visual's color masks tell
 *	you where in the word the indices are supposed to be.  The
 *	masks contain bits only where the index is found.  By counting
 *	the leading zeros in the mask, we know how many bits to shift
 *	to the individual red, green, and blue values to form a pixel.
 *
 * Results:
 *      The number of the least significant bit.
 *
 *----------------------------------------------------------------------
 */
static int
ShiftCount(
    register unsigned int mask)
{
    register int count;

    for(count = 0; count < 32; count++) {
        if(mask & 0x01) {
            break;
        }
        mask >>= 1;
    }
    return count;
}

/*
 *----------------------------------------------------------------------
 *
 * CountBits --
 *
 *	Returns the number of bits set in the given mask.
 *
 *	Reference: Graphics Gems Volume 2.
 *
 * Results:
 *      The number of bits to set in the mask.
 *
 *
 *----------------------------------------------------------------------
 */
static int
CountBits(
    register unsigned long mask)
{              /* 32  1-bit tallies */
    /* 16  2-bit tallies */
    mask = (mask & 0x55555555) + ((mask >> 1) & (0x55555555));
    /* 8  4-bit tallies */
    mask = (mask & 0x33333333) + ((mask >> 2) & (0x33333333));
    /* 4  8-bit tallies */
    mask = (mask & 0x07070707) + ((mask >> 4) & (0x07070707));
    /* 2 16-bit tallies */
    mask = (mask & 0x000F000F) + ((mask >> 8) & (0x000F000F));
    /* 1 32-bit tally */
    mask = (mask & 0x0000001F) + ((mask >> 16) & (0x0000001F));
    return mask;
}

static void
ComputeMasks(
    Visual * visualPtr)
{
int count;

    redMaskShift = ShiftCount((unsigned int)visualPtr->red_mask);
    greenMaskShift = ShiftCount((unsigned int)visualPtr->green_mask);
    blueMaskShift = ShiftCount((unsigned int)visualPtr->blue_mask);

    redAdjust = greenAdjust = blueAdjust = 0;
    count = CountBits((unsigned long)visualPtr->red_mask);
    if(count < 8) {
        redAdjust = 8 - count;
    }
    count = CountBits((unsigned long)visualPtr->green_mask);
    if(count < 8) {
        greenAdjust = 8 - count;
    }
    count = CountBits((unsigned long)visualPtr->blue_mask);
    if(count < 8) {
        blueAdjust = 8 - count;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TrueColorPixel --
 *
 *      Computes a pixel index from the 3 component RGB values.
 *
 * Results:
 *      The pixel index is returned.
 *
 *----------------------------------------------------------------------
 */
static unsigned int
TrueColorPixel(
    Visual * visualPtr,
    RbcPix32 * pixelPtr)
{
unsigned int red, green, blue;

    /*
     * The number of bits per color may be less than eight. For example,
     * 15/16 bit displays (hi-color) use only 5 bits, 8-bit displays
     * use 2 or 3 bits (don't ask me why you'd have an 8-bit TrueColor
     * display). So shift off the least significant bits.
     */
    red = ((unsigned int)pixelPtr->rgba.red >> redAdjust);
    green = ((unsigned int)pixelPtr->rgba.green >> greenAdjust);
    blue = ((unsigned int)pixelPtr->rgba.blue >> blueAdjust);

    /* Shift each color into the proper location of the pixel index. */
    red = (red << redMaskShift) & visualPtr->red_mask;
    green = (green << greenMaskShift) & visualPtr->green_mask;
    blue = (blue << blueMaskShift) & visualPtr->blue_mask;
    return (red | green | blue);
}

/*
 *----------------------------------------------------------------------
 *
 * DirectColorPixel --
 *
 *      Translates the 3 component RGB values into a pixel index.
 *      This differs from TrueColor only in that it first translates
 *	the RGB values through a color table.
 *
 * Results:
 *      The pixel index is returned.
 *
 *----------------------------------------------------------------------
 */

/*TODO
static unsigned int
DirectColorPixel(
    struct ColorTableStruct *colorTabPtr,
    RbcPix32 *pixelPtr)
{
    unsigned int red, green, blue;

    red = colorTabPtr->red[pixelPtr->Red];
    green = colorTabPtr->green[pixelPtr->Green];
    blue = colorTabPtr->blue[pixelPtr->Blue];
    return (red | green | blue);
}
*/

/*
 *----------------------------------------------------------------------
 *
 * PseudoColorPixel --
 *
 *      Translates the 3 component RGB values into a pixel index.
 *      This differs from TrueColor only in that it first translates
 *	the RGB values through a color table.
 *
 * Results:
 *      The pixel index is returned.
 *
 *----------------------------------------------------------------------
 */
static unsigned int
PseudoColorPixel(
    RbcPix32 * pixelPtr,
    unsigned int *lut)
{
    int red, green, blue;
    int pixel;

    red = (pixelPtr->rgba.red >> 3) + 1;
    green = (pixelPtr->rgba.green >> 3) + 1;
    blue = (pixelPtr->rgba.blue >> 3) + 1;
    pixel = RGBIndex(red, green, blue);
    return lut[pixel];
}

static int
XGetImageErrorProc(
    ClientData clientData,
    XErrorEvent * errEventPtr)
{
int *errorPtr = clientData;

    *errorPtr = TCL_ERROR;
    return 0;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawableToColorImage --
 *
 *      Takes a snapshot of an X drawable (pixmap or window) and
 *	converts it to a color image.
 *
 *	The trick here is to efficiently convert the pixel values
 *	(indices into the color table) into RGB color values.  In the
 *	days of 8-bit displays, it was simpler to get RGB values for
 *	all 256 indices into the colormap.  Instead we'll build a
 *	hashtable of unique pixels and from that an array of pixels to
 *	pass to XQueryColors.  For TrueColor visuals, we'll simple
 *	compute the colors from the pixel.
 *
 *	[I don't know how much faster it would be to take advantage
 *	of all the different visual types.  This pretty much depends
 *	on the size of the image and the number of colors it uses.]
 *
 * Results:
 *      Returns a color image of the drawable.  If an error occurred,
 *	NULL is returned.
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcDrawableToColorImage(
    Tk_Window tkwin,
    Drawable drawable,
    register int x,            /* Offset of image from the drawable's origin. */
    register int y,            /* Offset of image from the drawable's origin. */
    int width,                 /* Dimension of the image.  Image must
                                * be completely contained by the
                                * drawable. */
    int height,                /* Dimension of the image.  Image must
                                * be completely contained by the
                                * drawable. */
    double inputGamma)
{
XImage *imagePtr;
RbcColorImage *image;
register RbcPix32 *destPtr;
unsigned long pixel;
int result = TCL_OK;
Tk_ErrorHandler errHandler;
Visual *visualPtr;
unsigned char lut[256];

    errHandler =
        Tk_CreateErrorHandler(Tk_Display(tkwin), BadMatch, X_GetImage, -1,
        XGetImageErrorProc, &result);
    imagePtr =
        XGetImage(Tk_Display(tkwin), drawable, x, y, width, height, AllPlanes,
        ZPixmap);
    Tk_DeleteErrorHandler(errHandler);
    XSync(Tk_Display(tkwin), False);
    if(result != TCL_OK) {
        return NULL;
    }

    {
register int i;
double value;

        for(i = 0; i < 256; i++) {
            value = pow(i / 255.0, inputGamma) * 255.0 + 0.5;
            lut[i] = CLAMP((unsigned char)value, 0, 255);
        }
    }
    /*
     * First allocate a color image to hold the screen snapshot.
     */
    image = RbcCreateColorImage(width, height);
    visualPtr = Tk_Visual(tkwin);
    if(visualPtr->class == TrueColor) {
unsigned int red, green, blue;
        /*
         * Directly compute the RGB color values from the pixel index
         * rather than of going through XQueryColors.
         */
        ComputeMasks(visualPtr);
        destPtr = image->bits;
        for(y = 0; y < height; y++) {
            for(x = 0; x < width; x++) {
                pixel = XGetPixel(imagePtr, x, y);

                red =
                    ((pixel & visualPtr->red_mask) >> redMaskShift) <<
                    redAdjust;
                green =
                    ((pixel & visualPtr->green_mask) >> greenMaskShift) <<
                    greenAdjust;
                blue =
                    ((pixel & visualPtr->blue_mask) >> blueMaskShift) <<
                    blueAdjust;

                /*
                 * The number of bits per color in the pixel may be
                 * less than eight. For example, 15/16 bit displays
                 * (hi-color) use only 5 bits, 8-bit displays use 2 or
                 * 3 bits (don't ask me why you'd have an 8-bit
                 * TrueColor display). So shift back the least
                 * significant bits.
                 */
                destPtr->rgba.red = lut[red];
                destPtr->rgba.green = lut[green];
                destPtr->rgba.blue = lut[blue];
                destPtr->rgba.alpha = (unsigned char)-1;
                destPtr++;
            }
        }
        XDestroyImage(imagePtr);
    } else {
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
Tcl_HashTable pixelTable;
XColor *colorPtr, *colorArr;
RbcPix32 *endPtr;
int nPixels;
int nColors;
int isNew;

        /*
         * Fill the array with each pixel of the image. At the same time, build
         * up a hashtable of the pixels used.
         */
        nPixels = width * height;
        Tcl_InitHashTable(&pixelTable, TCL_ONE_WORD_KEYS);
        destPtr = image->bits;
        for(y = 0; y < height; y++) {
            for(x = 0; x < width; x++) {
                pixel = XGetPixel(imagePtr, x, y);
                hPtr = Tcl_CreateHashEntry(&pixelTable, (char *)pixel, &isNew);
                if(isNew) {
                    Tcl_SetHashValue(hPtr, (char *)pixel);
                }
                destPtr->value = pixel;
                destPtr++;
            }
        }
        XDestroyImage(imagePtr);

        /*
         * Convert the hashtable of pixels into an array of XColors so
         * that we can call XQueryColors with it. XQueryColors will
         * convert the pixels into their RGB values.
         */
        nColors = pixelTable.numEntries;
        colorArr = (XColor *) ckalloc(sizeof(XColor) * nColors);
        assert(colorArr);

        colorPtr = colorArr;
        for(hPtr = Tcl_FirstHashEntry(&pixelTable, &cursor); hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&cursor)) {
            colorPtr->pixel = (unsigned long)Tcl_GetHashValue(hPtr);
            Tcl_SetHashValue(hPtr, (char *)colorPtr);
            colorPtr++;
        }
        XQueryColors(Tk_Display(tkwin), Tk_Colormap(tkwin), colorArr, nColors);

        /*
         * Go again through the array of pixels, replacing each pixel
         * of the image with its RGB value.
         */
        destPtr = image->bits;
        endPtr = destPtr + nPixels;
        for( /* empty */ ; destPtr < endPtr; destPtr++) {
            hPtr = Tcl_FindHashEntry(&pixelTable, (char *)destPtr->value);
            colorPtr = (XColor *) Tcl_GetHashValue(hPtr);
            destPtr->rgba.red = lut[colorPtr->red >> 8];
            destPtr->rgba.green = lut[colorPtr->green >> 8];
            destPtr->rgba.blue = lut[colorPtr->blue >> 8];
            destPtr->rgba.alpha = (unsigned char)-1;
        }
        ckfree((char *)colorArr);
        Tcl_DeleteHashTable(&pixelTable);
    }
    return image;
}

Pixmap
RbcPhotoImageMask(
    Tk_Window tkwin,
    Tk_PhotoImageBlock src)
{
Pixmap bitmap;
int arraySize, bytes_per_line;
int offset, count;
int value, bitMask;
register int x, y;
unsigned char *bits;
unsigned char *srcPtr;
unsigned char *destPtr;
unsigned long pixel;

    bytes_per_line = (src.width + 7) / 8;
    arraySize = src.height * bytes_per_line;
    bits = (unsigned char *)ckalloc(sizeof(unsigned char) * arraySize);
    assert(bits);
    destPtr = bits;
    offset = count = 0;
    for(y = 0; y < src.height; y++) {
        value = 0, bitMask = 1;
        srcPtr = src.pixelPtr + offset;
        for(x = 0; x < src.width; /*empty */ ) {
            pixel = (srcPtr[src.offset[3]] != 0x00);
            if(pixel) {
                value |= bitMask;
            } else {
                count++;        /* Count the number of transparent pixels. */
            }
            bitMask <<= 1;
            x++;
            if(!(x & 7)) {
                *destPtr++ = (unsigned char)value;
                value = 0, bitMask = 1;
            }
            srcPtr += src.pixelSize;
        }
        if(x & 7) {
            *destPtr++ = (unsigned char)value;
        }
        offset += src.pitch;
    }
    if(count > 0) {
        Tk_MakeWindowExist(tkwin);
        bitmap = XCreateBitmapFromData(Tk_Display(tkwin), Tk_WindowId(tkwin),
            (char *)bits, (unsigned int)src.width, (unsigned int)src.height);
    } else {
        bitmap = None;  /* Image is opaque. */
    }
    ckfree((char *)bits);
    return bitmap;
}

/*
 * -----------------------------------------------------------------
 *
 * RbcRotateBitmap --
 *
 *	Creates a new bitmap containing the rotated image of the given
 *	bitmap.  We also need a special GC of depth 1, so that we do
 *	not need to rotate more than one plane of the bitmap.
 *
 * Results:
 *	Returns a new bitmap containing the rotated image.
 *
 * -----------------------------------------------------------------
 */
Pixmap
RbcRotateBitmap(
    Tk_Window tkwin,
    Pixmap srcBitmap,          /* Source bitmap to be rotated */
    int srcWidth,              /* Width of the source bitmap */
    int srcHeight,             /* Height of the source bitmap */
    double theta,              /* Right angle rotation to perform */
    int *destWidthPtr,
    int *destHeightPtr)
{
Display *display;              /* X display */
Window root;                   /* Root window drawable */
Pixmap destBitmap;
int destWidth, destHeight;
XImage *src, *dest;
register int x, y;             /* Destination bitmap coordinates */
register int sx, sy;           /* Source bitmap coordinates */
unsigned long pixel;
GC  bitmapGC;
double rotWidth, rotHeight;

    display = Tk_Display(tkwin);
    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));

    /* Create a bitmap and image big enough to contain the rotated text */
    RbcGetBoundingBox(srcWidth, srcHeight, theta, &rotWidth, &rotHeight,
        (RbcPoint2D *) NULL);
    destWidth = ROUND(rotWidth);
    destHeight = ROUND(rotHeight);
    destBitmap = Tk_GetPixmap(display, root, destWidth, destHeight, 1);
    bitmapGC = RbcGetBitmapGC(tkwin);
    XSetForeground(display, bitmapGC, 0x0);
    XFillRectangle(display, destBitmap, bitmapGC, 0, 0, destWidth, destHeight);

    src = XGetImage(display, srcBitmap, 0, 0, srcWidth, srcHeight, 1, ZPixmap);
    dest = XGetImage(display, destBitmap, 0, 0, destWidth, destHeight, 1,
        ZPixmap);
    theta = FMOD(theta, 360.0);
    if(FMOD(theta, (double)90.0) == 0.0) {
int quadrant;

        /* Handle right-angle rotations specifically */

        quadrant = (int)(theta / 90.0);
        switch (quadrant) {
        case RBC_ROTATE_270:   /* 270 degrees */
            for(y = 0; y < destHeight; y++) {
                sx = y;
                for(x = 0; x < destWidth; x++) {
                    sy = destWidth - x - 1;
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_180:   /* 180 degrees */
            for(y = 0; y < destHeight; y++) {
                sy = destHeight - y - 1;
                for(x = 0; x < destWidth; x++) {
                    sx = destWidth - x - 1, pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_90:    /* 90 degrees */
            for(y = 0; y < destHeight; y++) {
                sx = destHeight - y - 1;
                for(x = 0; x < destWidth; x++) {
                    sy = x;
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_0:     /* 0 degrees */
            for(y = 0; y < destHeight; y++) {
                for(x = 0; x < destWidth; x++) {
                    pixel = XGetPixel(src, x, y);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        default:
            /* The calling routine should never let this happen. */
            break;
        }
    } else {
double radians, sinTheta, cosTheta;
double sox, soy;               /* Offset from the center of
                                * the source rectangle. */
double destCX, destCY;         /* Offset to the center of the destination
                                * rectangle. */
double tx, ty;                 /* Translated coordinates from center */
double rx, ry;                 /* Angle of rotation for x and y coordinates */

        radians = (theta / 180.0) * M_PI;
        sinTheta = sin(radians), cosTheta = cos(radians);

        /*
         * Coordinates of the centers of the source and destination rectangles
         */
        sox = srcWidth * 0.5;
        soy = srcHeight * 0.5;
        destCX = destWidth * 0.5;
        destCY = destHeight * 0.5;

        /* For each pixel of the destination image, transform back to the
         * associated pixel in the source image. */

        for(y = 0; y < destHeight; y++) {
            ty = y - destCY;
            for(x = 0; x < destWidth; x++) {

                /* Translate origin to center of destination image. */
                tx = x - destCX;

                /* Rotate the coordinates about the origin. */
                rx = (tx * cosTheta) - (ty * sinTheta);
                ry = (tx * sinTheta) + (ty * cosTheta);

                /* Translate back to the center of the source image. */
                rx += sox;
                ry += soy;

                sx = ROUND(rx);
                sy = ROUND(ry);

                /*
                 * Verify the coordinates, since the destination image can be
                 * bigger than the source.
                 */

                if((sx >= srcWidth) || (sx < 0) || (sy >= srcHeight) ||
                    (sy < 0)) {
                    continue;
                }
                pixel = XGetPixel(src, sx, sy);
                if(pixel) {
                    XPutPixel(dest, x, y, pixel);
                }
            }
        }
    }
    /* Write the rotated image into the destination bitmap. */
    XPutImage(display, destBitmap, bitmapGC, dest, 0, 0, 0, 0, destWidth,
        destHeight);

    /* Clean up the temporary resources used. */
    XDestroyImage(src), XDestroyImage(dest);
    *destWidthPtr = destWidth;
    *destHeightPtr = destHeight;
    return destBitmap;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcScaleBitmap --
 *
 *	Creates a new scaled bitmap from another bitmap. The new bitmap
 *	is bounded by a specified region. Only this portion of the bitmap
 *	is scaled from the original bitmap.
 *
 *	By bounding scaling to a region we can generate a new bitmap
 *	which is no bigger than the specified viewport.
 *
 * Results:
 *	The new scaled bitmap is returned.
 *
 * Side Effects:
 *	A new pixmap is allocated. The caller must release this.
 *
 * -----------------------------------------------------------------------
 */
Pixmap
RbcScaleBitmap(
    Tk_Window tkwin,
    Pixmap srcBitmap,
    int srcWidth,
    int srcHeight,
    int destWidth,
    int destHeight)
{
Display *display;
GC  bitmapGC;
Pixmap destBitmap;
Window root;
XImage *src, *dest;
double xScale, yScale;
register int sx, sy;           /* Source bitmap coordinates */
register int x, y;             /* Destination bitmap coordinates */
unsigned long pixel;

    /* Create a new bitmap the size of the region and clear it */

    display = Tk_Display(tkwin);

    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));
    destBitmap = Tk_GetPixmap(display, root, destWidth, destHeight, 1);
    bitmapGC = RbcGetBitmapGC(tkwin);
    XSetForeground(display, bitmapGC, 0x0);
    XFillRectangle(display, destBitmap, bitmapGC, 0, 0, destWidth, destHeight);

    src = XGetImage(display, srcBitmap, 0, 0, srcWidth, srcHeight, 1, ZPixmap);
    dest = XGetImage(display, destBitmap, 0, 0, destWidth, destHeight, 1,
        ZPixmap);

    /*
     * Scale each pixel of destination image from results of source
     * image. Verify the coordinates, since the destination image can
     * be bigger than the source
     */
    xScale = (double)srcWidth / (double)destWidth;
    yScale = (double)srcHeight / (double)destHeight;

    /* Map each pixel in the destination image back to the source. */
    for(y = 0; y < destHeight; y++) {
        sy = (int)(yScale * (double)y);
        for(x = 0; x < destWidth; x++) {
            sx = (int)(xScale * (double)x);
            pixel = XGetPixel(src, sx, sy);
            if(pixel) {
                XPutPixel(dest, x, y, pixel);
            }
        }
    }
    /* Write the scaled image into the destination bitmap */

    XPutImage(display, destBitmap, bitmapGC, dest, 0, 0, 0, 0,
        destWidth, destHeight);
    XDestroyImage(src), XDestroyImage(dest);
    return destBitmap;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcRotateScaleBitmapRegion --
 *
 *	Creates a scaled and rotated bitmap from a given bitmap.  The
 *	caller also provides (offsets and dimensions) the region of
 *	interest in the destination bitmap.  This saves having to
 *	process the entire destination bitmap is only part of it is
 *	showing in the viewport.
 *
 *	This uses a simple rotation/scaling of each pixel in the
 *	destination image.  For each pixel, the corresponding
 *	pixel in the source bitmap is used.  This means that
 *	destination coordinates are first scaled to the size of
 *	the rotated source bitmap.  These coordinates are then
 *	rotated back to their original orientation in the source.
 *
 * Results:
 *	The new rotated and scaled bitmap is returned.
 *
 * Side Effects:
 *	A new pixmap is allocated. The caller must release this.
 *
 * -----------------------------------------------------------------------
 */
Pixmap
RbcScaleRotateBitmapRegion(
    Tk_Window tkwin,
    Pixmap srcBitmap,          /* Source bitmap. */
    unsigned int srcWidth,
    unsigned int srcHeight,    /* Size of source bitmap */
    int regionX,
    int regionY,               /* Offset of region in virtual
                                * destination bitmap. */
    unsigned int regionWidth,
    unsigned int regionHeight, /* Desire size of bitmap region. */
    unsigned int destWidth,
    unsigned int destHeight,   /* Virtual size of destination bitmap. */
    double theta)
{              /* Angle to rotate bitmap.  */
Display *display;              /* X display */
Window root;                   /* Root window drawable */
Pixmap destBitmap;
XImage *src, *dest;
register int x, y;             /* Destination bitmap coordinates */
register int sx, sy;           /* Source bitmap coordinates */
unsigned long pixel;
double xScale, yScale;
double rotWidth, rotHeight;
GC  bitmapGC;

    display = Tk_Display(tkwin);
    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));

    /* Create a bitmap and image big enough to contain the rotated text */
    bitmapGC = RbcGetBitmapGC(tkwin);
    destBitmap = Tk_GetPixmap(display, root, regionWidth, regionHeight, 1);
    XSetForeground(display, bitmapGC, 0x0);
    XFillRectangle(display, destBitmap, bitmapGC, 0, 0, regionWidth,
        regionHeight);

    src = XGetImage(display, srcBitmap, 0, 0, srcWidth, srcHeight, 1, ZPixmap);
    dest = XGetImage(display, destBitmap, 0, 0, regionWidth, regionHeight, 1,
        ZPixmap);
    theta = FMOD(theta, 360.0);

    RbcGetBoundingBox(srcWidth, srcHeight, theta, &rotWidth, &rotHeight,
        (RbcPoint2D *) NULL);
    xScale = rotWidth / (double)destWidth;
    yScale = rotHeight / (double)destHeight;

    if(FMOD(theta, (double)90.0) == 0.0) {
int quadrant;

        /* Handle right-angle rotations specifically */

        quadrant = (int)(theta / 90.0);
        switch (quadrant) {
        case RBC_ROTATE_270:   /* 270 degrees */
            for(y = 0; y < regionHeight; y++) {
                sx = (int)(yScale * (double)(y + regionY));
                for(x = 0; x < regionWidth; x++) {
                    sy = (int)(xScale * (double)(destWidth - (x + regionX) -
                            1));
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_180:   /* 180 degrees */
            for(y = 0; y < regionHeight; y++) {
                sy = (int)(yScale * (double)(destHeight - (y + regionY) - 1));
                for(x = 0; x < regionWidth; x++) {
                    sx = (int)(xScale * (double)(destWidth - (x + regionX) -
                            1));
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_90:    /* 90 degrees */
            for(y = 0; y < regionHeight; y++) {
                sx = (int)(yScale * (double)(destHeight - (y + regionY) - 1));
                for(x = 0; x < regionWidth; x++) {
                    sy = (int)(xScale * (double)(x + regionX));
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        case RBC_ROTATE_0:     /* 0 degrees */
            for(y = 0; y < regionHeight; y++) {
                sy = (int)(yScale * (double)(y + regionY));
                for(x = 0; x < regionWidth; x++) {
                    sx = (int)(xScale * (double)(x + regionX));
                    pixel = XGetPixel(src, sx, sy);
                    if(pixel) {
                        XPutPixel(dest, x, y, pixel);
                    }
                }
            }
            break;

        default:
            /* The calling routine should never let this happen. */
            break;
        }
    } else {
double radians, sinTheta, cosTheta;
double sox, soy;               /* Offset from the center of the
                                * source rectangle. */
double rox, roy;               /* Offset to the center of the
                                * rotated rectangle. */
double tx, ty;                 /* Translated coordinates from center */
double rx, ry;                 /* Angle of rotation for x and y coordinates */

        radians = (theta / 180.0) * M_PI;
        sinTheta = sin(radians), cosTheta = cos(radians);

        /*
         * Coordinates of the centers of the source and destination rectangles
         */
        sox = srcWidth * 0.5;
        soy = srcHeight * 0.5;
        rox = rotWidth * 0.5;
        roy = rotHeight * 0.5;

        /* For each pixel of the destination image, transform back to the
         * associated pixel in the source image. */

        for(y = 0; y < regionHeight; y++) {
            ty = (yScale * (double)(y + regionY)) - roy;
            for(x = 0; x < regionWidth; x++) {

                /* Translate origin to center of destination image. */
                tx = (xScale * (double)(x + regionX)) - rox;

                /* Rotate the coordinates about the origin. */
                rx = (tx * cosTheta) - (ty * sinTheta);
                ry = (tx * sinTheta) + (ty * cosTheta);

                /* Translate back to the center of the source image. */
                rx += sox;
                ry += soy;

                sx = ROUND(rx);
                sy = ROUND(ry);

                /*
                 * Verify the coordinates, since the destination image can be
                 * bigger than the source.
                 */

                if((sx >= srcWidth) || (sx < 0) || (sy >= srcHeight) ||
                    (sy < 0)) {
                    continue;
                }
                pixel = XGetPixel(src, sx, sy);
                if(pixel) {
                    XPutPixel(dest, x, y, pixel);
                }
            }
        }
    }
    /* Write the rotated image into the destination bitmap. */
    XPutImage(display, destBitmap, bitmapGC, dest, 0, 0, 0, 0, regionWidth,
        regionHeight);

    /* Clean up the temporary resources used. */
    XDestroyImage(src), XDestroyImage(dest);
    return destBitmap;

}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcUtil.c.

























































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcUtil.c --
 *
 *      This module implements utility procedures for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

static int BinaryOpSearch(
    RbcOpSpec specArr[],
    int nSpecs,
    const char *string);
static int LinearOpSearch(
    RbcOpSpec specArr[],
    int nSpecs,
    const char *string);

/*
 *----------------------------------------------------------------------
 *
 * RbcCalloc --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
void *
RbcCalloc(
    unsigned int nElems,
    size_t sizeOfElem)
{
    char *allocPtr;
    size_t size;

    size = nElems * sizeOfElem;
    allocPtr = ckalloc(size);
    if(allocPtr != NULL) {
        memset(allocPtr, 0, size);
    }
    return allocPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcStrdup --
 *
 *      Create a copy of the string from heap storage.
 *
 * Results:
 *      Returns a pointer to the need string copy.
 *
 * Side Effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
char *
RbcStrdup(
    const char *string)
{
    size_t size;
    char *allocPtr;

    size = strlen(string) + 1;
    allocPtr = ckalloc(size * sizeof(char));
    if(allocPtr != NULL) {
        strcpy(allocPtr, string);
    }
    return allocPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * BinaryOpSearch --
 *
 *      Performs a binary search on the array of command operation
 *      specifications to find a partial, anchored match for the
 *      given operation string.
 *
 * Results:
 *      If the string matches unambiguously the index of the
 *      specification in the array is returned.  If the string does
 *      not match, even as an abbreviation, any operation, -1 is
 *      returned.  If the string matches, but ambiguously -2 is
 *      returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
BinaryOpSearch(
    RbcOpSpec specArr[],
    int nSpecs,
    const char *string)
{              /* Name of minor operation to search for */
    RbcOpSpec *specPtr;
    char c;
    register int high, low, median;
    register int compare, length;

    low = 0;
    high = nSpecs - 1;
    c = string[0];
    length = strlen(string);
    while(low <= high) {
        median = (low + high) >> 1;
        specPtr = specArr + median;

        /* Test the first character */
        compare = c - specPtr->name[0];
        if(compare == 0) {
            /* Now test the entire string */
            compare = strncmp(string, specPtr->name, length);
            if(compare == 0) {
                if(length < specPtr->minChars) {
                    return -2;  /* Ambiguous operation name */
                }
            }
        }
        if(compare < 0) {
            high = median - 1;
        } else if(compare > 0) {
            low = median + 1;
        } else {
            return median;      /* Op found. */
        }
    }
    return -1; /* Can't find operation */
}

/*
 *----------------------------------------------------------------------
 *
 * LinearOpSearch --
 *
 *      Performs a binary search on the array of command operation
 *      specifications to find a partial, anchored match for the
 *      given operation string.
 *
 * Results:
 *      If the string matches unambiguously the index of the
 *      specification in the array is returned.  If the string does
 *      not match, even as an abbreviation, any operation, -1 is
 *      returned.  If the string matches, but ambiguously -2 is
 *      returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
LinearOpSearch(
    RbcOpSpec specArr[],
    int nSpecs,
    const char *string)
{              /* Name of minor operation to search for */
    RbcOpSpec *specPtr;
    char c;
    int length, nMatches, last;
    register int i;

    c = string[0];
    length = strlen(string);
    nMatches = 0;
    last = -1;
    for(specPtr = specArr, i = 0; i < nSpecs; i++, specPtr++) {
        if((c == specPtr->name[0]) &&
            (strncmp(string, specPtr->name, length) == 0)) {
            last = i;
            nMatches++;
            if(length == specPtr->minChars) {
                break;
            }
        }
    }
    if(nMatches > 1) {
        return -2;      /* Ambiguous operation name */
    }
    if(nMatches == 0) {
        return -1;      /* Can't find operation */
    }
    return last;        /* Op found. */
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetOp --
 *
 *      Find the command operation given a string name.  This is
 *      useful where a group of command operations have the same
 *      argument signature.
 *
 * Results:
 *      If found, a pointer to the procedure (function pointer) is
 *      returned.  Otherwise NULL is returned and an error message
 *      containing a list of the possible commands is returned in
 *      interp->result.
 *
 *
 * Side effects:
 *      TODO: Side Effects
 *----------------------------------------------------------------------
 */
RbcOp
RbcGetOp(
    Tcl_Interp * interp,       /* Interpreter to report errors to */
    int nSpecs,                /* Number of specifications in array */
    RbcOpSpec specArr[],       /* Op specification array */
    int operPos,               /* Index of the operation name argument */
    int argc,                  /* Number of arguments in the argument vector.
                                * This includes any prefixed arguments */
    const char **argv,         /* Argument vector */
    int flags)
{              /*  */
RbcOpSpec *specPtr;
const char *string;
register int i;
register int n;

    if(argc <= operPos) {       /* No operation argument */
        Tcl_AppendResult(interp, "wrong # args: ", (char *)NULL);
      usage:
        Tcl_AppendResult(interp, "should be one of...", (char *)NULL);
        for(n = 0; n < nSpecs; n++) {
            Tcl_AppendResult(interp, "\n  ", (char *)NULL);
            for(i = 0; i < operPos; i++) {
                Tcl_AppendResult(interp, argv[i], " ", (char *)NULL);
            }
            specPtr = specArr + n;
            Tcl_AppendResult(interp, specPtr->name, " ", specPtr->usage,
                (char *)NULL);
        }
        return NULL;
    }
    string = argv[operPos];
    if(flags & RBC_OP_LINEAR_SEARCH) {
        n = LinearOpSearch(specArr, nSpecs, string);
    } else {
        n = BinaryOpSearch(specArr, nSpecs, string);
    }
    if(n == -2) {
char c;
int length;

        Tcl_AppendResult(interp, "ambiguous", (char *)NULL);
        if(operPos > 2) {
            Tcl_AppendResult(interp, " ", argv[operPos - 1], (char *)NULL);
        }
        Tcl_AppendResult(interp, " operation \"", string, "\" matches:",
            (char *)NULL);

        c = string[0];
        length = strlen(string);
        for(n = 0; n < nSpecs; n++) {
            specPtr = specArr + n;
            if((c == specPtr->name[0]) &&
                (strncmp(string, specPtr->name, length) == 0)) {
                Tcl_AppendResult(interp, " ", specPtr->name, (char *)NULL);
            }
        }
        return NULL;

    } else if(n == -1) {        /* Can't find operation, display help */
        Tcl_AppendResult(interp, "bad", (char *)NULL);
        if(operPos > 2) {
            Tcl_AppendResult(interp, " ", argv[operPos - 1], (char *)NULL);
        }
        Tcl_AppendResult(interp, " operation \"", string, "\": ", (char *)NULL);
        goto usage;
    }
    specPtr = specArr + n;
    if((argc < specPtr->minArgs) || ((specPtr->maxArgs > 0) &&
            (argc > specPtr->maxArgs))) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", (char *)NULL);
        for(i = 0; i < operPos; i++) {
            Tcl_AppendResult(interp, argv[i], " ", (char *)NULL);
        }
        Tcl_AppendResult(interp, specPtr->name, " ", specPtr->usage, "\"",
            (char *)NULL);
        return NULL;
    }
    return specPtr->proc;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetOpFromObj --
 *
 *      Find the command operation given a string name.  This is
 *      useful where a group of command operations have the same
 *      argument signature.
 *
 * Results:
 *      If found, a pointer to the procedure (function pointer) is
 *      returned.  Otherwise NULL is returned and an error message
 *      containing a list of the possible commands is returned in
 *      interp->result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcOp
RbcGetOpFromObj(
    Tcl_Interp * interp,       /* Interpreter to report errors to */
    int nSpecs,                /* Number of specifications in array */
    RbcOpSpec specArr[],       /* Op specification array */
    int operPos,               /* Position of operation in argument list. */
    int objc,                  /* Number of arguments in the argument vector.
                                * This includes any prefixed arguments */
    Tcl_Obj * const objv[],    /* Argument vector */
    int flags)
{
RbcOpSpec *specPtr;
char *string;
register int i;
register int n;

    if(objc <= operPos) {       /* No operation argument */
        Tcl_AppendResult(interp, "wrong # args: ", (char *)NULL);
      usage:
        Tcl_AppendResult(interp, "should be one of...", (char *)NULL);
        for(n = 0; n < nSpecs; n++) {
            Tcl_AppendResult(interp, "\n  ", (char *)NULL);
            for(i = 0; i < operPos; i++) {
                Tcl_AppendResult(interp, Tcl_GetString(objv[i]), " ",
                    (char *)NULL);
            }
            specPtr = specArr + n;
            Tcl_AppendResult(interp, specPtr->name, " ", specPtr->usage,
                (char *)NULL);
        }
        return NULL;
    }
    string = Tcl_GetString(objv[operPos]);
    if(flags & RBC_OP_LINEAR_SEARCH) {
        n = LinearOpSearch(specArr, nSpecs, string);
    } else {
        n = BinaryOpSearch(specArr, nSpecs, string);
    }
    if(n == -2) {
char c;
int length;

        Tcl_AppendResult(interp, "ambiguous", (char *)NULL);
        if(operPos > 2) {
            Tcl_AppendResult(interp, " ", Tcl_GetString(objv[operPos - 1]),
                (char *)NULL);
        }
        Tcl_AppendResult(interp, " operation \"", string, "\" matches:",
            (char *)NULL);

        c = string[0];
        length = strlen(string);
        for(n = 0; n < nSpecs; n++) {
            specPtr = specArr + n;
            if((c == specPtr->name[0]) &&
                (strncmp(string, specPtr->name, length) == 0)) {
                Tcl_AppendResult(interp, " ", specPtr->name, (char *)NULL);
            }
        }
        return NULL;

    } else if(n == -1) {        /* Can't find operation, display help */
        Tcl_AppendResult(interp, "bad", (char *)NULL);
        if(operPos > 2) {
            Tcl_AppendResult(interp, " ", Tcl_GetString(objv[operPos - 1]),
                (char *)NULL);
        }
        Tcl_AppendResult(interp, " operation \"", string, "\": ", (char *)NULL);
        goto usage;
    }
    specPtr = specArr + n;
    if((objc < specPtr->minArgs) ||
        ((specPtr->maxArgs > 0) && (objc > specPtr->maxArgs))) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", (char *)NULL);
        for(i = 0; i < operPos; i++) {
            Tcl_AppendResult(interp, Tcl_GetString(objv[i]), " ", (char *)NULL);
        }
        Tcl_AppendResult(interp, specPtr->name, " ", specPtr->usage, "\"",
            (char *)NULL);
        return NULL;
    }
    return specPtr->proc;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcWin.h.
















































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoRbcWin.h --
 *
 *      TODO: Description
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#ifndef _TKORBCWIN_H
#define _TKORBCWIN_H

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#include <windowsx.h>

/* DOS Encapsulated PostScript File Header */
#pragma pack(2)
typedef struct {
    BYTE magic[4];             /* Magic number for a DOS EPS file
                                * C5,D0,D3,C6 */
    DWORD psStart;             /* Offset of PostScript section. */
    DWORD psLength;            /* Length of the PostScript section. */
    DWORD wmfStart;            /* Offset of Windows Meta File section. */
    DWORD wmfLength;           /* Length of Meta file section. */
    DWORD tiffStart;           /* Offset of TIFF section. */
    DWORD tiffLength;          /* Length of TIFF section. */
    WORD checksum;             /* Checksum of header. If FFFF, ignore. */
} DOSEPSHEADER;
#pragma pack()

/* Aldus Portable Metafile Header */
#pragma pack(2)
typedef struct {
    DWORD key;                 /* Type of metafile */
    WORD hmf;                  /* Unused. Must be NULL. */
    SMALL_RECT bbox;           /* Bounding rectangle */
    WORD inch;                 /* Units per inch. */
    DWORD reserved;            /* Unused. */
    WORD checksum;             /* XOR of previous fields (10 32-bit words). */
} APMHEADER;
#pragma pack()

MODULE_SCOPE void RbcSetROP2(
    HDC dc,
    int function);

#ifdef __GNUC__
#include <wingdi.h>
#include <windowsx.h>
#undef Status
#include <winspool.h>
#define Status int

#endif /* __GNUC__ */
/*
 * Add definitions missing from windgi.h, windowsx.h, and winspool.h
 */
#define XDrawSegments		RbcEmulateXDrawSegments

/* rbcWinDraw.c */
MODULE_SCOPE char *RbcLastError(
    );
MODULE_SCOPE HPALETTE RbcGetSystemPalette(
    );
MODULE_SCOPE unsigned char *RbcGetBitmapData(
    Display * display,
    Pixmap bitmap,
    int width,
    int height,
    int *pitchPtr);
MODULE_SCOPE void RbcSetROP2(
    HDC dc,
    int function);
MODULE_SCOPE GC RbcEmulateXCreateGC(
    Display * display,
    Drawable drawable,
    unsigned long mask,
    XGCValues * srcPtr);
MODULE_SCOPE HPEN RbcGCToPen(
    HDC dc,
    GC gc);
MODULE_SCOPE int RbcDrawRotatedText(
    Display * display,
    Drawable drawable,
    int x,
    int y,
    double theta,
    RbcTextStyle * stylePtr,
    RbcTextLayout * textPtr);
MODULE_SCOPE void RbcEmulateXDrawSegments(
    Display * display,
    Drawable drawable,
    GC gc,
    XSegment * segArr,
    int nSegments);

/* Already defined in rbcInt.h:
void RbcSetDashes(Display *display,
    GC gc,
    RbcDashes *dashesPtr);

*/

#endif /*_TKORBCWIN_H */

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcWinDraw.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcWinDraw.c --
 *
 *      This module contains WIN32 routines not included in the Tcl/Tk
 *      libraries.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"
#include <X11/Xlib.h>

/*
 * Data structure for setting graphics context.
 */
typedef struct {
    int function;              /* logical operation */
    unsigned long plane_mask;  /* plane mask */
    unsigned long foreground;  /* foreground pixel */
    unsigned long background;  /* background pixel */
    int line_width;            /* line width */
    int line_style;            /* LineSolid, LineOnOffDash, LineDoubleDash */
    int cap_style;             /* CapNotLast, CapButt,
                                * CapRound, CapProjecting */
    int join_style;            /* JoinMiter, JoinRound, JoinBevel */
    int fill_style;            /* FillSolid, FillTiled,
                                * FillStippled, FillOpaeueStippled */
    int fill_rule;             /* EvenOddRule, WindingRule */
    int arc_mode;              /* ArcChord, ArcPieSlice */
    Pixmap tile;               /* tile pixmap for tiling operations */
    Pixmap stipple;            /* stipple 1 plane pixmap for stipping */
    int ts_x_origin;           /* offset for tile or stipple operations */
    int ts_y_origin;
    Font font;                 /* default text font for text operations */
    int subwindow_mode;        /* ClipByChildren, IncludeInferiors */
    Bool graphics_exposures;   /* boolean, should exposures be generated */
    int clip_x_origin;         /* origin for clipping */
    int clip_y_origin;
    Pixmap clip_mask;          /* bitmap clipping; other calls for rects */
    int dash_offset;           /* patterned/dashed line information */
    char dashes;               /* If -1, indicates that the extended
                                * information below is available. */
    int nDashValues;
    char dashValues[12];
} XGCValuesEx;

typedef struct {
    HDC dc;
    int count;
    COLORREF color;
    int offset, nBits;
} DashInfo;

static Tcl_Encoding systemEncoding = NULL;

static HFONT CreateRotatedFont(
    unsigned long fontId,
    double theta);
static XGCValuesEx *CreateGC(
    );
static BOOL DrawChars(
    HDC dc,
    int x,
    int y,
    char *string,
    int length);
static int GetDashInfo(
    HDC dc,
    GC gc,
    DashInfo * infoPtr);
static void CALLBACK DrawDot(
    int x,
    int y,
    LPARAM clientData);
static int GetPlatformId(
    );

/*
 *--------------------------------------------------------------
 *
 * GetPlatformId --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
GetPlatformId(
    )
{
static int platformId = 0;

    if(platformId == 0) {
OSVERSIONINFO opsysInfo;

        opsysInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        if(GetVersionEx(&opsysInfo)) {
            platformId = opsysInfo.dwPlatformId;
        }
    }
    return platformId;
}

/*
 *--------------------------------------------------------------
 *
 * RbcLastError --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
char *
RbcLastError(
    )
{
static char buffer[1024];
int length;

    FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
        buffer, 1024, NULL);
    length = strlen(buffer);
    if(buffer[length - 2] == '\r') {
        buffer[length - 2] = '\0';
    }
    return buffer;
}

/*
 *--------------------------------------------------------------
 *
 * RbcGetSystemPalette --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
HPALETTE
RbcGetSystemPalette(
    )
{
HDC hDC;
HPALETTE hPalette;
DWORD flags;
    hPalette = NULL;
    hDC = GetDC(NULL);  /* Get the desktop device context */
    flags = GetDeviceCaps(hDC, RASTERCAPS);
    if(flags & RC_PALETTE) {
LOGPALETTE *palettePtr;
        palettePtr = (LOGPALETTE *)
            GlobalAlloc(GPTR, sizeof(LOGPALETTE) + 256 * sizeof(PALETTEENTRY));
        palettePtr->palVersion = 0x300;
        palettePtr->palNumEntries = 256;
        GetSystemPaletteEntries(hDC, 0, 256, palettePtr->palPalEntry);
        hPalette = CreatePalette(palettePtr);
        GlobalFree(palettePtr);
    }
    ReleaseDC(NULL, hDC);
    return hPalette;
}

/*
 *--------------------------------------------------------------
 *
 * RbcGetBitmapData --
 *
 *      Returns the DIB bits from a bitmap.
 *
 * Results:
 *      Returns a byte array of bitmap data or NULL if an error
 *      occurred.  The parameter pitchPtr returns the number
 *      of bytes per row.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
unsigned char *
RbcGetBitmapData(
    Display * display,         /* Display of bitmap */
    Pixmap bitmap,             /* Bitmap to query */
    int width,                 /* Width of bitmap */
    int height,                /* Height of bitmap */
    int *pitchPtr)
{              /* (out) Number of bytes per row */
    TkWinDCState state;
    HDC dc;
    int result;
    unsigned char *bits;
    unsigned int size;
    HBITMAP hBitmap;
    BITMAPINFOHEADER *bmiPtr;
    HANDLE hMem, hMem2;
    int bytesPerRow, imageSize;
    size = sizeof(BITMAPINFOHEADER) + 2 * sizeof(RGBQUAD);
    hMem = GlobalAlloc(GHND, size);
    bmiPtr = (BITMAPINFOHEADER *) GlobalLock(hMem);
    bmiPtr->biSize = sizeof(BITMAPINFOHEADER);
    bmiPtr->biPlanes = 1;
    bmiPtr->biBitCount = 1;
    bmiPtr->biCompression = BI_RGB;
    bmiPtr->biWidth = width;
    bmiPtr->biHeight = height;
    hBitmap = ((TkWinDrawable *) bitmap)->bitmap.handle;
    dc = TkWinGetDrawableDC(display, bitmap, &state);
    result = GetDIBits(dc, hBitmap, 0, height, (LPVOID) NULL,
        (BITMAPINFO *) bmiPtr, DIB_RGB_COLORS);
    TkWinReleaseDrawableDC(bitmap, dc, &state);
    if(!result) {
        GlobalUnlock(hMem);
        GlobalFree(hMem);
        return NULL;
    }
    imageSize = bmiPtr->biSizeImage;
    GlobalUnlock(hMem);
    bytesPerRow = ((width + 31) & ~31) / 8;
    if(imageSize == 0) {
        imageSize = bytesPerRow * height;
    }
    hMem2 = GlobalReAlloc(hMem, size + imageSize, 0);
    if(hMem2 == NULL) {
        GlobalFree(hMem);
        return NULL;
    }
    hMem = hMem2;
    bmiPtr = (LPBITMAPINFOHEADER) GlobalLock(hMem);
    dc = TkWinGetDrawableDC(display, bitmap, &state);
    result = GetDIBits(dc, hBitmap, 0, height, (unsigned char *)bmiPtr + size,
        (BITMAPINFO *) bmiPtr, DIB_RGB_COLORS);
    TkWinReleaseDrawableDC(bitmap, dc, &state);
    bits = NULL;
    if(!result) {
        OutputDebugStringA("GetDIBits failed\n");
    } else {
        bits = (unsigned char *)ckalloc(imageSize);
        if(bits != NULL) {
            memcpy(bits, (unsigned char *)bmiPtr + size, imageSize);
        }
    }
    *pitchPtr = bytesPerRow;
    GlobalUnlock(hMem);
    GlobalFree(hMem);
    return bits;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetROP2 --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetROP2(
    HDC dc,
    int function)
{
    static int WinRop2Mode[] = {
        R2_BLACK,       /* GXclear */
        R2_MASKPEN,     /* GXand */
        R2_MASKPENNOT,  /* GXandReverse */
        R2_COPYPEN,     /* GXcopy */
        R2_MASKNOTPEN,  /* GXandInverted */
        R2_NOT, /* GXnoop */
        R2_XORPEN,      /* GXxor */
        R2_MERGEPEN,    /* GXor */
        R2_NOTMERGEPEN, /* GXnor */
        R2_NOTXORPEN,   /* GXequiv */
        R2_NOT, /* GXinvert */
        R2_MERGEPENNOT, /* GXorReverse */
        R2_NOTCOPYPEN,  /* GXcopyInverted */
        R2_MERGENOTPEN, /* GXorInverted */
        R2_NOTMASKPEN,  /* GXnand */
        R2_WHITE        /* GXset */
    };
    if(function < 0 || function > 15)
        return;
    SetROP2(dc, WinRop2Mode[function]);
}

/*
 *----------------------------------------------------------------------
 *
 * RbcEmulateXCreateGC --
 *
 *      Allocate a new extended GC, and initialize the specified fields.
 *
 * Results:
 *      Returns a newly allocated GC.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
GC
RbcEmulateXCreateGC(
    Display * display,
    Drawable drawable,
    unsigned long mask,
    XGCValues * srcPtr)
{
XGCValuesEx *destPtr;
    destPtr = CreateGC();
    if(destPtr == NULL) {
        return None;
    }
    if(mask & GCFunction) {
        destPtr->function = srcPtr->function;
    }
    if(mask & GCPlaneMask) {
        destPtr->plane_mask = srcPtr->plane_mask;
    }
    if(mask & GCForeground) {
        destPtr->foreground = srcPtr->foreground;
    }
    if(mask & GCBackground) {
        destPtr->background = srcPtr->background;
    }
    if(mask & GCLineWidth) {
        destPtr->line_width = srcPtr->line_width;
    }
    if(mask & GCLineStyle) {
        destPtr->line_style = srcPtr->line_style;
    }
    if(mask & GCCapStyle) {
        destPtr->cap_style = srcPtr->cap_style;
    }
    if(mask & GCJoinStyle) {
        destPtr->join_style = srcPtr->join_style;
    }
    if(mask & GCFillStyle) {
        destPtr->fill_style = srcPtr->fill_style;
    }
    if(mask & GCFillRule) {
        destPtr->fill_rule = srcPtr->fill_rule;
    }
    if(mask & GCArcMode) {
        destPtr->arc_mode = srcPtr->arc_mode;
    }
    if(mask & GCTile) {
        destPtr->tile = srcPtr->tile;
    }
    if(mask & GCStipple) {
        destPtr->stipple = srcPtr->stipple;
    }
    if(mask & GCTileStipXOrigin) {
        destPtr->ts_x_origin = srcPtr->ts_x_origin;
    }
    if(mask & GCTileStipXOrigin) {
        destPtr->ts_y_origin = srcPtr->ts_y_origin;
    }
    if(mask & GCFont) {
        destPtr->font = srcPtr->font;
    }
    if(mask & GCSubwindowMode) {
        destPtr->subwindow_mode = srcPtr->subwindow_mode;
    }
    if(mask & GCGraphicsExposures) {
        destPtr->graphics_exposures = srcPtr->graphics_exposures;
    }
    if(mask & GCClipXOrigin) {
        destPtr->clip_x_origin = srcPtr->clip_x_origin;
    }
    if(mask & GCClipYOrigin) {
        destPtr->clip_y_origin = srcPtr->clip_y_origin;
    }
    if(mask & GCDashOffset) {
        destPtr->dash_offset = srcPtr->dash_offset;
    }
    if(mask & GCDashList) {
        destPtr->dashes = srcPtr->dashes;
    }
    if(mask & GCClipMask) {
struct ClipMask {
    int type;                  /* TKP_CLIP_PIXMAP or TKP_CLIP_REGION */
    Pixmap pixmap;
}  *clipPtr;
        clipPtr = (struct ClipMask *)ckalloc(sizeof(struct ClipMask));
#define TKP_CLIP_PIXMAP 0
        clipPtr->type = TKP_CLIP_PIXMAP;
        clipPtr->pixmap = srcPtr->clip_mask;
        destPtr->clip_mask = (Pixmap) clipPtr;
    }
    return (GC) destPtr;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGCToPen --
 *
 *      Set up the graphics port from the given GC.
 *
 *      Geometric and cosmetic pens available under both 95 and NT.
 *      Geometric pens differ from cosmetic pens in that they can
 *        1. Draw in world units (can have thick lines: line width > 1).
 *        2. Under NT, allow arbitrary line style.
 *        3. Can have caps and join (needed for thick lines).
 *        4. Draw very, very slowly.
 *
 *      Cosmetic pens are single line width only.
 *
 *                       95   98   NT
 *        PS_SOLID      c,g  c,g  c,g
 *        PS_DASH       c,g  c,g  c,g
 *        PS_DOT          c    c  c,g
 *        PS_DASHDOT      c    -  c,g
 *        PS_DASHDOTDOT   c    -  c,g
 *        PS_USERSTYLE    -    -  c,g
 *        PS_ALTERNATE    -    -    c
 *
 *      Geometric only for 95/98
 *
 *        PS_ENDCAP_ROUND
 *        PS_ENDCAP_SQUARE
 *        PS_ENDCAP_FLAT
 *        PS_JOIN_BEVEL
 *        PS_JOIN_ROUND
 *        PS_JOIN_MITER
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The current port is adjusted.
 *
 *----------------------------------------------------------------------
 */
HPEN
RbcGCToPen(
    HDC dc,
    GC gc)
{
DWORD lineAttrs, lineStyle;
DWORD dashArr[12];
DWORD *dashPtr;
int nValues, lineWidth;
LOGBRUSH lBrush;
HPEN pen;
    nValues = 0;
    lineWidth = (gc->line_width < 1) ? 1 : gc->line_width;
    if((gc->line_style == LineOnOffDash) || (gc->line_style == LineDoubleDash)) {
XGCValuesEx *gcPtr = (XGCValuesEx *) gc;
        if((int)gc->dashes == -1) {
register int i;
            nValues = strlen(gcPtr->dashValues);
            for(i = 0; i < nValues; i++) {
                dashArr[i] = (DWORD) gcPtr->dashValues[i];
            }
            if(nValues == 1) {
                dashArr[1] = dashArr[0];
                nValues = 2;
            }
        } else {
            dashArr[1] = dashArr[0] = (DWORD) gc->dashes;
            nValues = 2;
            gc->dashes = -1;
        }
    }
    switch (nValues) {
    case 0:
        lineStyle = PS_SOLID;
        break;
    case 3:
        lineStyle = PS_DASHDOT;
        break;
    case 4:
        lineStyle = PS_DASHDOTDOT;
        break;
    case 2:
    default:
        /* PS_DASH style dash length is too long. */
        lineStyle = PS_DOT;
        break;
    }
    lBrush.lbStyle = BS_SOLID;
    lBrush.lbColor = gc->foreground;
    lBrush.lbHatch = 0; /* Value is ignored when style is BS_SOLID. */
    lineAttrs = 0;
    switch (gc->cap_style) {
    case CapNotLast:
    case CapButt:
        lineAttrs |= PS_ENDCAP_FLAT;
        break;
    case CapRound:
        lineAttrs |= PS_ENDCAP_ROUND;
        break;
    default:
        lineAttrs |= PS_ENDCAP_SQUARE;
        break;
    }
    switch (gc->join_style) {
    case JoinMiter:
        lineAttrs |= PS_JOIN_MITER;
        break;
    case JoinBevel:
        lineAttrs |= PS_JOIN_BEVEL;
        break;
    case JoinRound:
    default:
        lineAttrs |= PS_JOIN_ROUND;
        break;
    }
    SetBkMode(dc, TRANSPARENT);
    if(GetPlatformId() == VER_PLATFORM_WIN32_NT) {
        /* Windows NT/2000/XP. */
        if(nValues > 0) {
            lineStyle = PS_USERSTYLE;
            dashPtr = dashArr;
        } else {
            dashPtr = NULL;
        }
        if(lineWidth > 1) {
            /* Limit the use of geometric pens to thick lines. */
            pen = ExtCreatePen(PS_GEOMETRIC | lineAttrs | lineStyle, lineWidth,
                &lBrush, nValues, dashPtr);
        } else {
            /* Cosmetic pens are much faster. */
            pen = ExtCreatePen(PS_COSMETIC | lineAttrs | lineStyle, 1, &lBrush,
                nValues, dashPtr);
        }
    } else {
        /* Windows 95/98. */
        if((lineStyle == PS_SOLID) && (lineWidth > 1)) {
            /* Use geometric pens with solid, thick lines only. */
            pen = ExtCreatePen(PS_GEOMETRIC | lineAttrs | lineStyle, lineWidth,
                &lBrush, 0, NULL);
        } else {
            /* Otherwise sacrifice thick lines for dashes. */
            pen = ExtCreatePen(PS_COSMETIC | lineStyle, 1, &lBrush, 0, NULL);
        }
    }
    assert(pen != NULL);
    return pen;
}

/*
 *--------------------------------------------------------------
 *
 * RbcDrawRotatedText --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcDrawRotatedText(
    Display * display,
    Drawable drawable,
    int x,
    int y,
    double theta,
    RbcTextStyle * tsPtr,
    RbcTextLayout * textPtr)
{
    HFONT hFont, oldFont;
    TkWinDCState state;
    HDC hDC;
    int isActive;
    int bbWidth, bbHeight;
    double rotWidth, rotHeight;
    double sinTheta, cosTheta;
    RbcPoint2D p, q, center;
    register RbcTextFragment *fragPtr, *endPtr;
    static int initialized = 0;
    if(!initialized) {
        if(GetPlatformId() == VER_PLATFORM_WIN32_NT) {
            /*
             * If running NT, then we will be calling some Unicode functions
             * explictly.  So, even if the Tcl system encoding isn't Unicode,
             * make sure we convert to/from the Unicode char set.
             */
            systemEncoding = Tcl_GetEncoding(NULL, "unicode");
        }
        initialized = 1;
    }
    hFont = CreateRotatedFont(tsPtr->gc->font, theta);
    if(hFont == NULL) {
        return FALSE;
    }
    isActive = (tsPtr->state & RBC_STATE_ACTIVE);
    hDC = TkWinGetDrawableDC(display, drawable, &state);
    RbcSetROP2(hDC, tsPtr->gc->function);
    oldFont = SelectFont(hDC, hFont);
    RbcGetBoundingBox(textPtr->width, textPtr->height, theta, &rotWidth,
        &rotHeight, (RbcPoint2D *) NULL);
    bbWidth = ROUND(rotWidth);
    bbHeight = ROUND(rotHeight);
    RbcTranslateAnchor(x, y, bbWidth, bbHeight, tsPtr->anchor, &x, &y);
    center.x = (double)textPtr->width * -0.5;
    center.y = (double)textPtr->height * -0.5;
    theta = (-theta / 180.0) * M_PI;
    sinTheta = sin(theta), cosTheta = cos(theta);
    endPtr = textPtr->fragArr + textPtr->nFrags;
    for(fragPtr = textPtr->fragArr; fragPtr < endPtr; fragPtr++) {
        p.x = center.x + (double)fragPtr->x;
        p.y = center.y + (double)fragPtr->y;
        q.x = x + (p.x * cosTheta) - (p.y * sinTheta) + (bbWidth * 0.5);
        q.y = y + (p.x * sinTheta) + (p.y * cosTheta) + (bbHeight * 0.5);
        fragPtr->sx = ROUND(q.x);
        fragPtr->sy = ROUND(q.y);
    }
    SetBkMode(hDC, TRANSPARENT);
    SetTextAlign(hDC, TA_LEFT | TA_BASELINE);
    if(tsPtr->state & (RBC_STATE_DISABLED | RBC_STATE_EMPHASIS)) {
    TkBorder *borderPtr = (TkBorder *) tsPtr->border;
    XColor *color1, *color2;
        color1 = borderPtr->lightColorPtr, color2 = borderPtr->darkColorPtr;
        if(tsPtr->state & RBC_STATE_EMPHASIS) {
    XColor *hold;
            hold = color1, color1 = color2, color2 = hold;
        }
        if(color1 != NULL) {
            SetTextColor(hDC, color1->pixel);
            for(fragPtr = textPtr->fragArr; fragPtr < endPtr; fragPtr++) {
                DrawChars(hDC, fragPtr->sx, fragPtr->sy, fragPtr->text,
                    fragPtr->count);
            }
        }
        if(color2 != NULL) {
            SetTextColor(hDC, color2->pixel);
            for(fragPtr = textPtr->fragArr; fragPtr < endPtr; fragPtr++) {
                DrawChars(hDC, fragPtr->sx + 1, fragPtr->sy + 1, fragPtr->text,
                    fragPtr->count);
            }
        }
        goto done;      /* Done */
    }
    SetBkMode(hDC, TRANSPARENT);
    if((tsPtr->shadow.offset > 0) && (tsPtr->shadow.color != NULL)) {
        SetTextColor(hDC, tsPtr->shadow.color->pixel);
        for(fragPtr = textPtr->fragArr; fragPtr < endPtr; fragPtr++) {
            DrawChars(hDC, fragPtr->sx + tsPtr->shadow.offset,
                fragPtr->sy + tsPtr->shadow.offset, fragPtr->text,
                fragPtr->count);
        }
    }
    if(isActive) {
        SetTextColor(hDC, tsPtr->activeColor->pixel);
    } else {
        SetTextColor(hDC, tsPtr->color->pixel);
    }
    for(fragPtr = textPtr->fragArr; fragPtr < endPtr; fragPtr++) {
        DrawChars(hDC, fragPtr->sx, fragPtr->sy, fragPtr->text, fragPtr->count);
    }
    if(isActive) {
        SetTextColor(hDC, tsPtr->color->pixel);
    }
  done:
    SelectFont(hDC, oldFont);
    DeleteFont(hFont);
    TkWinReleaseDrawableDC(drawable, hDC, &state);
    return TRUE;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetDashes --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetDashes(
    Display * display,
    GC gc,
    RbcDashes * dashesPtr)
{
XGCValuesEx *gcPtr = (XGCValuesEx *) gc;
    /* This must be used only with a privately created GC */
    assert((int)gcPtr->dashes == -1);
    gcPtr->nDashValues = strlen(dashesPtr->values);
    gcPtr->dash_offset = dashesPtr->offset;
    strcpy(gcPtr->dashValues, dashesPtr->values);
}

/*
 *--------------------------------------------------------------
 *
 * CreateRotatedFont --
 *
 *      Creates a rotated copy of the given font.  This only works
 *      for TrueType fonts.
 *
 * Results:
 *      Returns the newly create font or NULL if the font could not
 *      be created.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static HFONT
CreateRotatedFont(
    unsigned long fontId,      /* Font identifier (actually a Tk_Font) */
    double theta)
{              /* Number of degrees to rotate font */
    TkFontAttributes *faPtr;   /* Set of attributes to match. */
    TkFont *fontPtr;
    HFONT hFont;
    LOGFONTW lf;
    fontPtr = (TkFont *) fontId;
    faPtr = &fontPtr->fa;
    ZeroMemory(&lf, sizeof(LOGFONT));
    lf.lfHeight = (LONG) - faPtr->size;
    if(lf.lfHeight < 0) {
    HDC dc;
        dc = GetDC(NULL);
        lf.lfHeight = -MulDiv((int)faPtr->size,
            GetDeviceCaps(dc, LOGPIXELSY), 72);
        ReleaseDC(NULL, dc);
    }
    lf.lfWidth = 0;
    lf.lfEscapement = lf.lfOrientation = ROUND(theta * 10.0);
#define TK_FW_NORMAL	0
    lf.lfWeight = (faPtr->weight == TK_FW_NORMAL) ? FW_NORMAL : FW_BOLD;
    lf.lfItalic = faPtr->slant;
    lf.lfUnderline = faPtr->underline;
    lf.lfStrikeOut = faPtr->overstrike;
    lf.lfCharSet = DEFAULT_CHARSET;
    lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
    lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    lf.lfQuality = DEFAULT_QUALITY;
    lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
    hFont = NULL;
    if(faPtr->family == NULL) {
        lf.lfFaceName[0] = '\0';
    } else {
    Tcl_DString dString;
        Tcl_UtfToExternalDString(systemEncoding, faPtr->family, -1, &dString);
        if(GetPlatformId() == VER_PLATFORM_WIN32_NT) {
    Tcl_UniChar *src, *dst;
            /*
             * We can only store up to LF_FACESIZE wide characters
             */
            if(Tcl_DStringLength(&dString) >=
                (int)(LF_FACESIZE * sizeof(WCHAR))) {
                Tcl_DStringSetLength(&dString, LF_FACESIZE);
            }
            src = (Tcl_UniChar *) Tcl_DStringValue(&dString);
            dst = (Tcl_UniChar *) lf.lfFaceName;
            while(*src != '\0') {
                *dst++ = *src++;
            }
            *dst = '\0';
            hFont = CreateFontIndirectW((LOGFONTW *) & lf);
        } else {
            /*
             * We can only store up to LF_FACESIZE characters
             */
            if(Tcl_DStringLength(&dString) >= LF_FACESIZE) {
                Tcl_DStringSetLength(&dString, LF_FACESIZE);
            }
            strcpy((char *)lf.lfFaceName, Tcl_DStringValue(&dString));
            hFont = CreateFontIndirectA((LOGFONTA *) & lf);
        }
        Tcl_DStringFree(&dString);
    }
    if(hFont == NULL) {
    } else {
    HFONT oldFont;
    TEXTMETRIC tm;
    HDC hRefDC;
    int result;
        /* Check if the rotated font is really a TrueType font. */
        hRefDC = GetDC(NULL);   /* Get the desktop device context */
        oldFont = SelectFont(hRefDC, hFont);
        result = ((GetTextMetrics(hRefDC, &tm)) &&
            (tm.tmPitchAndFamily & TMPF_TRUETYPE));
        SelectFont(hRefDC, oldFont);
        ReleaseDC(NULL, hRefDC);
        if(!result) {
            DeleteFont(hFont);
            return NULL;
        }
    }
    return hFont;
}

/*
 *--------------------------------------------------------------
 *
 * CreateGC --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static XGCValuesEx *
CreateGC(
    )
{
XGCValuesEx *gcPtr;
    gcPtr = (XGCValuesEx *) ckalloc(sizeof(XGCValuesEx));
    if(gcPtr == NULL) {
        return NULL;
    }
    gcPtr->arc_mode = ArcPieSlice;
    gcPtr->background = 0xffffff;
    gcPtr->cap_style = CapNotLast;
    gcPtr->clip_mask = None;
    gcPtr->clip_x_origin = gcPtr->clip_y_origin = 0;
    gcPtr->dash_offset = 0;
    gcPtr->fill_rule = WindingRule;
    gcPtr->fill_style = FillSolid;
    gcPtr->font = None;
    gcPtr->foreground = 0;
    gcPtr->function = GXcopy;
    gcPtr->graphics_exposures = True;
    gcPtr->join_style = JoinMiter;
    gcPtr->line_style = LineSolid;
    gcPtr->line_width = 0;
    gcPtr->plane_mask = ~0;
    gcPtr->stipple = None;
    gcPtr->subwindow_mode = ClipByChildren;
    gcPtr->tile = None;
    gcPtr->ts_x_origin = gcPtr->ts_y_origin = 0;
    gcPtr->dashes = -1; /* Mark that this an extended GC */
    gcPtr->nDashValues = 0;
    return gcPtr;
}

/*
 *--------------------------------------------------------------
 *
 * DrawChars --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static BOOL
DrawChars(
    HDC dc,
    int x,
    int y,
    char *string,
    int length)
{
    BOOL result;
    if(systemEncoding == NULL) {
        result = TextOutA(dc, x, y, string, length);
    } else {
    const unsigned short *wstring;
    Tcl_DString dString;
        Tcl_DStringInit(&dString);
        Tcl_UtfToExternalDString(systemEncoding, string, length, &dString);
        length = Tcl_NumUtfChars(string, -1);
        wstring = (const unsigned short *)Tcl_DStringValue(&dString);
        result = TextOutW(dc, x, y, wstring, length);
        Tcl_DStringFree(&dString);
    }
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcEmulateXDrawSegments --
 *
 *      Draws multiple, unconnected lines. For each segment, draws a
 *      line between (x1, y1) and (x2, y2).  It draws the lines in the
 *      order listed in the array of XSegment structures and does not
 *      perform joining at coincident endpoints.  For any given line,
 *      does not draw a pixel more than once. If lines intersect, the
 *      intersecting pixels are drawn multiple times.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Draws unconnected line segments on the specified drawable.
 *
 *----------------------------------------------------------------------
 */
void
RbcEmulateXDrawSegments(
    Display * display,
    Drawable drawable,
    GC gc,
    XSegment * segArr,
    int nSegments)
{
    HDC dc;
    register XSegment *segPtr, *endPtr;
    TkWinDCState state;

    display->request++;
    if(drawable == None) {
        return;
    }
    dc = TkWinGetDrawableDC(display, drawable, &state);
    RbcSetROP2(dc, gc->function);
    if(gc->line_style != LineSolid) {
        /* Handle dotted lines specially */
    DashInfo info;

        if(!GetDashInfo(dc, gc, &info)) {
            goto solidLine;
        }
        endPtr = segArr + nSegments;
        for(segPtr = segArr; segPtr < endPtr; segPtr++) {
            info.count = 0;     /* Reset dash counter after every segment. */
            LineDDA(segPtr->x1, segPtr->y1, segPtr->x2, segPtr->y2, DrawDot,
                (LPARAM) & info);
        }
    } else {
    HPEN pen, oldPen;

      solidLine:
        pen = RbcGCToPen(dc, gc);
        oldPen = SelectPen(dc, pen);
        endPtr = segArr + nSegments;
        for(segPtr = segArr; segPtr < endPtr; segPtr++) {
            MoveToEx(dc, segPtr->x1, segPtr->y1, (LPPOINT) NULL);
            LineTo(dc, segPtr->x2, segPtr->y2);
        }
        DeletePen(SelectPen(dc, oldPen));
    }
    TkWinReleaseDrawableDC(drawable, dc, &state);
}

/*
 *--------------------------------------------------------------
 *
 * GetDashInfo --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
GetDashInfo(
    HDC dc,
    GC gc,
    DashInfo * infoPtr)
{
int dashOffset, dashValue;

    dashValue = 0;
    dashOffset = gc->dash_offset;
    if((int)gc->dashes == -1) {
XGCValuesEx *gcPtr = (XGCValuesEx *) gc;

        if(gcPtr->nDashValues == 1) {
            dashValue = gcPtr->dashValues[0];
        }
    } else if(gc->dashes > 0) {
        dashValue = (int)gc->dashes;
    }
    if(dashValue == 0) {
        return FALSE;
    }
    infoPtr->dc = dc;
    infoPtr->nBits = dashValue;
    infoPtr->offset = dashOffset;
    infoPtr->count = 0;
    infoPtr->color = gc->foreground;
    return TRUE;
}

/*
 *----------------------------------------------------------------------
 *
 * DrawDot --
 *
 *      Draws a dot.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Renders a dot.
 *
 *----------------------------------------------------------------------
 */
static void CALLBACK
DrawDot(
    int x,                     /* y-coordinates of point */
    int y,                     /* y-coordinates of point */
    LPARAM clientData)
{              /* Line information */
    DashInfo *infoPtr = (DashInfo *) clientData;
    int count;

    infoPtr->count++;
    count = (infoPtr->count + infoPtr->offset) / infoPtr->nBits;
    if(count & 0x1) {
        SetPixelV(infoPtr->dc, x, y, infoPtr->color);
    }
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcWinImage.c.
















































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

/*
 * rbcWinImage.c --
 *
 *      This module implements image processing procedures for the rbc
 *      toolkit.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define GetBit(x, y) \
   srcBits[(srcBytesPerRow * (srcHeight - y - 1)) + (x>>3)] & (0x80 >> (x&7))
#define SetBit(x, y) \
   destBits[(destBytesPerRow * (destHeight - y - 1)) + (x>>3)] |= (0x80 >>(x&7))

/*
 *----------------------------------------------------------------------
 *
 * RbcDrawableToColorImage --
 *
 *      Takes a snapshot of an X drawable (pixmap or window) and
 *      converts it to a color image.
 *
 * Results:
 *      Returns a color image of the drawable.  If an error occurred,
 *      NULL is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
RbcColorImage *
RbcDrawableToColorImage(
    Tk_Window tkwin,
    Drawable drawable,
    int x,
    int y,
    int width,
    int height,                /* Dimension of the drawable. */
    double inputGamma)
{
    void *data;
    BITMAPINFO info;
    DIBSECTION ds;
    HBITMAP hBitmap, oldBitmap;
    HPALETTE hPalette;
    HDC memDC;
    unsigned char *srcArr;
    register unsigned char *srcPtr;
    HDC hDC;
    TkWinDCState state;
    register RbcPix32 *destPtr;
    RbcColorImage *image;
    unsigned char lut[256];

    hDC = TkWinGetDrawableDC(Tk_Display(tkwin), drawable, &state);

    /* Create the intermediate drawing surface at window resolution. */
    ZeroMemory(&info, sizeof(info));
    info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info.bmiHeader.biWidth = width;
    info.bmiHeader.biHeight = height;
    info.bmiHeader.biPlanes = 1;
    info.bmiHeader.biBitCount = 32;
    info.bmiHeader.biCompression = BI_RGB;
    hBitmap = CreateDIBSection(hDC, &info, DIB_RGB_COLORS, &data, NULL, 0);
    memDC = CreateCompatibleDC(hDC);
    oldBitmap = SelectBitmap(memDC, hBitmap);

    hPalette = RbcGetSystemPalette();
    if(hPalette != NULL) {
        SelectPalette(hDC, hPalette, FALSE);
        RealizePalette(hDC);
        SelectPalette(memDC, hPalette, FALSE);
        RealizePalette(memDC);
    }
    image = NULL;
    /* Copy the window contents to the memory surface. */
    if(!BitBlt(memDC, 0, 0, width, height, hDC, x, y, SRCCOPY)) {
        goto done;
    }
    if(GetObject(hBitmap, sizeof(DIBSECTION), &ds) == 0) {
        goto done;
    }
    srcArr = (unsigned char *)ds.dsBm.bmBits;
    image = RbcCreateColorImage(width, height);
    destPtr = image->bits;

    {
    register int i;
    double value;

        for(i = 0; i < 256; i++) {
            value = pow(i / 255.0, inputGamma) * 255.0 + 0.5;
            lut[i] = CLAMP((unsigned char)value, 0, 255);
        }
    }

    /*
     * Copy the DIB RGB data into the color image. The DIB scanlines
     * are stored bottom-to-top and the order of the RGB color
     * components is BGR. Who says Win32 GDI programming isn't
     * backwards?
     */

    for(y = height - 1; y >= 0; y--) {
        srcPtr = srcArr + (y * ds.dsBm.bmWidthBytes);
        for(x = 0; x < width; x++) {
            destPtr->rgba.blue = lut[*srcPtr++];
            destPtr->rgba.green = lut[*srcPtr++];
            destPtr->rgba.red = lut[*srcPtr++];
            destPtr->rgba.alpha = (unsigned char)-1;
            destPtr++;
            srcPtr++;
        }
    }
  done:
    DeleteBitmap(SelectBitmap(memDC, oldBitmap));
    DeleteDC(memDC);
    TkWinReleaseDrawableDC(drawable, hDC, &state);
    if(hPalette != NULL) {
        DeletePalette(hPalette);
    }
    return image;
}

/*
 *--------------------------------------------------------------
 *
 * RbcPhotoImageMask --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
Pixmap
RbcPhotoImageMask(
    Tk_Window tkwin,
    Tk_PhotoImageBlock src)
{
TkWinBitmap *twdPtr;
int offset, count;
register int x, y;
unsigned char *srcPtr;
int destBytesPerRow;
int destHeight;
unsigned char *destBits;

    destBytesPerRow = ((src.width + 31) & ~31) / 8;
    destBits = RbcCalloc(src.height, destBytesPerRow);
    destHeight = src.height;

    offset = count = 0;
    /* FIXME: figure out why this is so! */
    for(y = src.height - 1; y >= 0; y--) {
        srcPtr = src.pixelPtr + offset;
        for(x = 0; x < src.width; x++) {
            if(srcPtr[src.offset[3]] == 0x00) {
                SetBit(x, y);
                count++;
            }
            srcPtr += src.pixelSize;
        }
        offset += src.pitch;
    }
    if(count > 0) {
HBITMAP hBitmap;
BITMAP bm;

        bm.bmType = 0;
        bm.bmWidth = src.width;
        bm.bmHeight = src.height;
        bm.bmWidthBytes = destBytesPerRow;
        bm.bmPlanes = 1;
        bm.bmBitsPixel = 1;
        bm.bmBits = destBits;
        hBitmap = CreateBitmapIndirect(&bm);

        twdPtr = (TkWinBitmap *) ckalloc(sizeof(TkWinBitmap));
        assert(twdPtr);
        twdPtr->type = TWD_BITMAP;
        twdPtr->handle = hBitmap;
        twdPtr->depth = 1;
        if(Tk_WindowId(tkwin) == None) {
            twdPtr->colormap = DefaultColormap(Tk_Display(tkwin),
                DefaultScreen(Tk_Display(tkwin)));
        } else {
            twdPtr->colormap = Tk_Colormap(tkwin);
        }
    } else {
        twdPtr = NULL;
    }
    if(destBits != NULL) {
        ckfree((char *)destBits);
    }
    return (Pixmap) twdPtr;
}

/*
 *--------------------------------------------------------------
 *
 * RbcRotateBitmap --
 *
 *      Creates a new bitmap containing the rotated image
 *      of the given bitmap.  We also need a special GC of
 *      depth 1, so that we do not need to rotate more than
 *      one plane of the bitmap.
 *
 *      Note that under Windows, monochrome bitmaps are
 *      stored bottom-to-top.  This is why the right angle
 *      rotations 0/180 and 90/270 look reversed.
 *
 * Results:
 *      Returns a new bitmap containing the rotated image.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
Pixmap
RbcRotateBitmap(
    Tk_Window tkwin,
    Pixmap srcBitmap,          /* Source bitmap to be rotated */
    int srcWidth,
    int srcHeight,             /* Width and height of the source bitmap */
    double theta,              /* Right angle rotation to perform */
    int *destWidthPtr,
    int *destHeightPtr)
{
Display *display;              /* X display */
Window root;                   /* Root window drawable */
Pixmap destBitmap;
double rotWidth, rotHeight;
HDC hDC;
TkWinDCState state;
register int x, y;             /* Destination bitmap coordinates */
register int sx, sy;           /* Source bitmap coordinates */
unsigned long pixel;
HBITMAP hBitmap;
int result;
struct MonoBitmap {
    BITMAPINFOHEADER bi;
    RGBQUAD colors[2];
} mb;
int srcBytesPerRow, destBytesPerRow;
int destWidth, destHeight;
unsigned char *srcBits, *destBits;

    display = Tk_Display(tkwin);
    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));
    RbcGetBoundingBox(srcWidth, srcHeight, theta, &rotWidth, &rotHeight,
        (RbcPoint2D *) NULL);

    destWidth = (int)ceil(rotWidth);
    destHeight = (int)ceil(rotHeight);
    destBitmap = Tk_GetPixmap(display, root, destWidth, destHeight, 1);
    if(destBitmap == None) {
        return None;    /* Can't allocate pixmap. */
    }
    srcBits = RbcGetBitmapData(display, srcBitmap, srcWidth, srcHeight,
        &srcBytesPerRow);
    if(srcBits == NULL) {
        OutputDebugStringA("RbcGetBitmapData failed");
        return None;
    }
    destBytesPerRow = ((destWidth + 31) & ~31) / 8;
    destBits = RbcCalloc(destHeight, destBytesPerRow);

    theta = FMOD(theta, 360.0);
    if(FMOD(theta, (double)90.0) == 0.0) {
int quadrant;

        /* Handle right-angle rotations specially. */

        quadrant = (int)(theta / 90.0);
        switch (quadrant) {
        case RBC_ROTATE_270:   /* 270 degrees */
            for(y = 0; y < destHeight; y++) {
                sx = y;
                for(x = 0; x < destWidth; x++) {
                    sy = destWidth - x - 1;
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_180:   /* 180 degrees */
            for(y = 0; y < destHeight; y++) {
                sy = destHeight - y - 1;
                for(x = 0; x < destWidth; x++) {
                    sx = destWidth - x - 1;
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_90:    /* 90 degrees */
            for(y = 0; y < destHeight; y++) {
                sx = destHeight - y - 1;
                for(x = 0; x < destWidth; x++) {
                    sy = x;
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_0:     /* 0 degrees */
            for(y = 0; y < destHeight; y++) {
                for(x = 0; x < destWidth; x++) {
                    pixel = GetBit(x, y);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        default:
            /* The calling routine should never let this happen. */
            break;
        }
    } else {
double radians, sinTheta, cosTheta;
double srcCX, srcCY;           /* Center of source rectangle */
double destCX, destCY;         /* Center of destination rectangle */
double tx, ty;
double rx, ry;                 /* Angle of rotation for x and y coordinates */

        radians = (theta / 180.0) * M_PI;
        sinTheta = sin(radians), cosTheta = cos(radians);

        /*
         * Coordinates of the centers of the source and destination rectangles
         */
        srcCX = srcWidth * 0.5;
        srcCY = srcHeight * 0.5;
        destCX = destWidth * 0.5;
        destCY = destHeight * 0.5;

        /* Rotate each pixel of dest image, placing results in source image */

        for(y = 0; y < destHeight; y++) {
            ty = y - destCY;
            for(x = 0; x < destWidth; x++) {

                /* Translate origin to center of destination image */
                tx = x - destCX;

                /* Rotate the coordinates about the origin */
                rx = (tx * cosTheta) - (ty * sinTheta);
                ry = (tx * sinTheta) + (ty * cosTheta);

                /* Translate back to the center of the source image */
                rx += srcCX;
                ry += srcCY;

                sx = ROUND(rx);
                sy = ROUND(ry);

                /*
                 * Verify the coordinates, since the destination image can be
                 * bigger than the source
                 */

                if((sx >= srcWidth) || (sx < 0) || (sy >= srcHeight) ||
                    (sy < 0)) {
                    continue;
                }
                pixel = GetBit(sx, sy);
                if(pixel) {
                    SetBit(x, y);
                }
            }
        }
    }
    hBitmap = ((TkWinDrawable *) destBitmap)->bitmap.handle;
    ZeroMemory(&mb, sizeof(mb));
    mb.bi.biSize = sizeof(BITMAPINFOHEADER);
    mb.bi.biPlanes = 1;
    mb.bi.biBitCount = 1;
    mb.bi.biCompression = BI_RGB;
    mb.bi.biWidth = destWidth;
    mb.bi.biHeight = destHeight;
    mb.bi.biSizeImage = destBytesPerRow * destHeight;
    mb.colors[0].rgbBlue = mb.colors[0].rgbRed = mb.colors[0].rgbGreen = 0x0;
    mb.colors[1].rgbBlue = mb.colors[1].rgbRed = mb.colors[1].rgbGreen = 0xFF;
    hDC = TkWinGetDrawableDC(display, destBitmap, &state);
    result = SetDIBits(hDC, hBitmap, 0, destHeight, (LPVOID) destBits,
        (BITMAPINFO *) & mb, DIB_RGB_COLORS);
    TkWinReleaseDrawableDC(destBitmap, hDC, &state);
    if(!result) {
#if WINDEBUG
        PurifyPrintf("can't setDIBits: %s\n", RbcLastError());
#endif
        destBitmap = None;
    }
    if(destBits != NULL) {
        ckfree((char *)destBits);
    }
    if(srcBits != NULL) {
        ckfree((char *)srcBits);
    }

    *destWidthPtr = destWidth;
    *destHeightPtr = destHeight;
    return destBitmap;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcScaleBitmap --
 *
 *      Creates a new scaled bitmap from another bitmap.
 *
 * Results:
 *      The new scaled bitmap is returned.
 *
 * Side Effects:
 *      A new pixmap is allocated. The caller must release this.
 *
 * -----------------------------------------------------------------------
 */
Pixmap
RbcScaleBitmap(
    Tk_Window tkwin,
    Pixmap srcBitmap,
    int srcWidth,
    int srcHeight,
    int destWidth,
    int destHeight)
{
TkWinDCState srcState, destState;
HDC src, dest;
Pixmap destBitmap;
Window root;
Display *display;

    /* Create a new bitmap the size of the region and clear it */

    display = Tk_Display(tkwin);
    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));
    destBitmap = Tk_GetPixmap(display, root, destWidth, destHeight, 1);
    if(destBitmap == None) {
        return None;
    }
    src = TkWinGetDrawableDC(display, srcBitmap, &srcState);
    dest = TkWinGetDrawableDC(display, destBitmap, &destState);

    StretchBlt(dest, 0, 0, destWidth, destHeight, src, 0, 0,
        srcWidth, srcHeight, SRCCOPY);

    TkWinReleaseDrawableDC(srcBitmap, src, &srcState);
    TkWinReleaseDrawableDC(destBitmap, dest, &destState);
    return destBitmap;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcScaleRotateBitmapRegion --
 *
 *      Creates a scaled and rotated bitmap from a given bitmap.  The
 *      caller also provides (offsets and dimensions) the region of
 *      interest in the destination bitmap.  This saves having to
 *      process the entire destination bitmap is only part of it is
 *      showing in the viewport.
 *
 *      This uses a simple rotation/scaling of each pixel in the
 *      destination image.  For each pixel, the corresponding
 *      pixel in the source bitmap is used.  This means that
 *      destination coordinates are first scaled to the size of
 *      the rotated source bitmap.  These coordinates are then
 *      rotated back to their original orientation in the source.
 *
 * Results:
 *      The new rotated and scaled bitmap is returned.
 *
 * Side Effects:
 *      A new pixmap is allocated. The caller must release this.
 *
 * -----------------------------------------------------------------------
 */
Pixmap
RbcScaleRotateBitmapRegion(
    Tk_Window tkwin,
    Pixmap srcBitmap,          /* Source bitmap. */
    unsigned int srcWidth,
    unsigned int srcHeight,    /* Size of source bitmap */
    int regionX,
    int regionY,               /* Offset of region in virtual
                                * destination bitmap. */
    unsigned int regionWidth,
    unsigned int regionHeight, /* Desire size of bitmap region. */
    unsigned int virtWidth,
    unsigned int virtHeight,   /* Virtual size of destination bitmap. */
    double theta)
{              /* Angle to rotate bitmap. */
Display *display;              /* X display */
HBITMAP hBitmap;
HDC hDC;
Pixmap destBitmap;
TkWinDCState state;
Window root;                   /* Root window drawable */
double rotWidth, rotHeight;
double xScale, yScale;
int srcBytesPerRow, destBytesPerRow;
int destHeight;
int result;
register int sx, sy;           /* Source bitmap coordinates */
register int x, y;             /* Destination bitmap coordinates */
unsigned char *srcBits, *destBits;
unsigned long pixel;
struct MonoBitmap {
    BITMAPINFOHEADER bi;
    RGBQUAD colors[2];
} mb;

    display = Tk_Display(tkwin);
    root = RootWindow(Tk_Display(tkwin), Tk_ScreenNumber(tkwin));

    /* Create a bitmap and image big enough to contain the rotated text */
    destBitmap = Tk_GetPixmap(display, root, regionWidth, regionHeight, 1);
    if(destBitmap == None) {
        return None;    /* Can't allocate pixmap. */
    }
    srcBits = RbcGetBitmapData(display, srcBitmap, srcWidth, srcHeight,
        &srcBytesPerRow);
    if(srcBits == NULL) {
        OutputDebugStringA("RbcGetBitmapData failed");
        return None;
    }
    destBytesPerRow = ((regionWidth + 31) & ~31) / 8;
    destBits = RbcCalloc(regionHeight, destBytesPerRow);
    destHeight = regionHeight;

    theta = FMOD(theta, 360.0);
    RbcGetBoundingBox(srcWidth, srcHeight, theta, &rotWidth, &rotHeight,
        (RbcPoint2D *) NULL);
    xScale = rotWidth / (double)virtWidth;
    yScale = rotHeight / (double)virtHeight;

    if(FMOD(theta, (double)90.0) == 0.0) {
int quadrant;

        /* Handle right-angle rotations specifically */

        quadrant = (int)(theta / 90.0);
        switch (quadrant) {
        case RBC_ROTATE_270:   /* 270 degrees */
            for(y = 0; y < (int)regionHeight; y++) {
                sx = (int)(yScale * (double)(y + regionY));
                for(x = 0; x < (int)regionWidth; x++) {
                    sy = (int)(xScale * (double)(virtWidth - (x + regionX) -
                            1));
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_180:   /* 180 degrees */
            for(y = 0; y < (int)regionHeight; y++) {
                sy = (int)(yScale * (double)(virtHeight - (y + regionY) - 1));
                for(x = 0; x < (int)regionWidth; x++) {
                    sx = (int)(xScale * (double)(virtWidth - (x + regionX) -
                            1));
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_90:    /* 90 degrees */
            for(y = 0; y < (int)regionHeight; y++) {
                sx = (int)(yScale * (double)(virtHeight - (y + regionY) - 1));
                for(x = 0; x < (int)regionWidth; x++) {
                    sy = (int)(xScale * (double)(x + regionX));
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        case RBC_ROTATE_0:     /* 0 degrees */
            for(y = 0; y < (int)regionHeight; y++) {
                sy = (int)(yScale * (double)(y + regionY));
                for(x = 0; x < (int)regionWidth; x++) {
                    sx = (int)(xScale * (double)(x + regionX));
                    pixel = GetBit(sx, sy);
                    if(pixel) {
                        SetBit(x, y);
                    }
                }
            }
            break;

        default:
            /* The calling routine should never let this happen. */
            break;
        }
    } else {
double radians, sinTheta, cosTheta;
double scx, scy;               /* Offset from the center of the
                                * source rectangle. */
double rcx, rcy;               /* Offset to the center of the
                                * rotated rectangle. */
double tx, ty;                 /* Translated coordinates from center */
double rx, ry;                 /* Angle of rotation for x and y coordinates */

        radians = (theta / 180.0) * M_PI;
        sinTheta = sin(radians), cosTheta = cos(radians);

        /*
         * Coordinates of the centers of the source and destination rectangles
         */
        scx = srcWidth * 0.5;
        scy = srcHeight * 0.5;
        rcx = rotWidth * 0.5;
        rcy = rotHeight * 0.5;

        /* For each pixel of the destination image, transform back to the
         * associated pixel in the source image. */

        for(y = 0; y < (int)regionHeight; y++) {
            ty = (yScale * (double)(y + regionY)) - rcy;
            for(x = 0; x < (int)regionWidth; x++) {

                /* Translate origin to center of destination image. */
                tx = (xScale * (double)(x + regionX)) - rcx;

                /* Rotate the coordinates about the origin. */
                rx = (tx * cosTheta) - (ty * sinTheta);
                ry = (tx * sinTheta) + (ty * cosTheta);

                /* Translate back to the center of the source image. */
                rx += scx;
                ry += scy;

                sx = ROUND(rx);
                sy = ROUND(ry);

                /*
                 * Verify the coordinates, since the destination image can be
                 * bigger than the source.
                 */

                if((sx >= (int)srcWidth) || (sx < 0) ||
                    (sy >= (int)srcHeight) || (sy < 0)) {
                    continue;
                }
                pixel = GetBit(sx, sy);
                if(pixel) {
                    SetBit(x, y);
                }
            }
        }
    }
    /* Write the rotated image into the destination bitmap. */
    hBitmap = ((TkWinDrawable *) destBitmap)->bitmap.handle;
    ZeroMemory(&mb, sizeof(mb));
    mb.bi.biSize = sizeof(BITMAPINFOHEADER);
    mb.bi.biPlanes = 1;
    mb.bi.biBitCount = 1;
    mb.bi.biCompression = BI_RGB;
    mb.bi.biWidth = regionWidth;
    mb.bi.biHeight = regionHeight;
    mb.bi.biSizeImage = destBytesPerRow * regionHeight;
    mb.colors[0].rgbBlue = mb.colors[0].rgbRed = mb.colors[0].rgbGreen = 0x0;
    mb.colors[1].rgbBlue = mb.colors[1].rgbRed = mb.colors[1].rgbGreen = 0xFF;
    hDC = TkWinGetDrawableDC(display, destBitmap, &state);
    result = SetDIBits(hDC, hBitmap, 0, regionHeight, (LPVOID) destBits,
        (BITMAPINFO *) & mb, DIB_RGB_COLORS);
    TkWinReleaseDrawableDC(destBitmap, hDC, &state);
    if(!result) {
#if WINDEBUG
        PurifyPrintf("can't setDIBits: %s\n", RbcLastError());
#endif
        destBitmap = None;
    }
    if(destBits != NULL) {
        ckfree((char *)destBits);
    }
    if(srcBits != NULL) {
        ckfree((char *)srcBits);
    }
    return destBitmap;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoRbcWindow.c.

























































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcWindow.c --
 *
 *      This module implements additional window functionality for
 *      the rbc toolkit, such as transparent Tk windows,
 *      and reparenting Tk windows.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#include <X11/Xlib.h>

typedef struct TkIdStackStruct TkIdStack;
typedef struct TkSelectionInfoStruct TkSelectionInfo;
typedef struct TkClipboardTargetStruct TkClipboardTarget;

typedef struct TkWindowEventStruct TkWindowEvent;
typedef struct TkSelHandlerStruct TkSelHandler;
typedef struct TkWinInfoStruct TkWinInfo;
typedef struct TkClassProcsStruct TkClassProcs;
typedef struct TkWindowPrivateStruct TkWindowPrivate;
typedef struct TkWmInfoStruct TkWmInfo;

#ifdef XNQueryInputStyle
#define TK_USE_INPUT_METHODS
#endif

/*
 * This defines whether we should try to use XIM over-the-spot style
 * input.  Allow users to override it.  It is a much more elegant use
 * of XIM, but uses a bit more memory.
 */
#ifndef TK_XIM_SPOT
#   define TK_XIM_SPOT	1
#endif

#ifndef TK_REPARENTED
#define TK_REPARENTED 	0
#endif

struct TkWindowStruct {
    Display *display;
    TkDisplay *dispPtr;
    int screenNum;
    Visual *visual;
    int depth;
    Window window;
    TkWindow *childList;
    TkWindow *lastChildPtr;
    TkWindow *parentPtr;
    TkWindow *nextPtr;
    TkMainInfo *infoPtr;
    char *pathName;
    Tk_Uid nameUid;
    Tk_Uid classUid;
    XWindowChanges changes;
    unsigned int dirtyChanges;
    XSetWindowAttributes atts;
    unsigned long dirtyAtts;
    unsigned int flags;
    TkEventHandler *handlerList;
#ifdef TK_USE_INPUT_METHODS
    XIC inputContext;
#endif                         /* TK_USE_INPUT_METHODS */
    ClientData *tagPtr;
    int nTags;
    int optionLevel;
    TkSelHandler *selHandlerList;
    Tk_GeomMgr *geomMgrPtr;
    ClientData geomData;
    int reqWidth, reqHeight;
    int internalBorderWidth;
    TkWinInfo *wmInfoPtr;
    TkClassProcs *classProcsPtr;
    ClientData instanceData;
    TkWindowPrivate *privatePtr;
};

static int GetWindowSize(
    Tcl_Interp * interp,
    Window window,
    int *widthPtr,
    int *heightPtr);

/*
 *----------------------------------------------------------------------
 *
 * RbcFindChild --
 *
 *      Performs a linear search for the named child window in a given
 *      parent window.
 *
 *      This can be done via Tcl, but not through Tk's C API.  It's
 *      simple enough, if you peek into the Tk_Window structure.
 *
 * Results:
 *      The child Tk_Window. If the named child can't be found, NULL
 *      is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
Tk_Window
RbcFindChild(
    Tk_Window parent,
    char *name)
{
    register TkWindow *winPtr;
    TkWindow *parentPtr = (TkWindow *) parent;

    for(winPtr = parentPtr->childList; winPtr != NULL; winPtr = winPtr->nextPtr) {
        if(strcmp(name, winPtr->nameUid) == 0) {
            return (Tk_Window) winPtr;
        }
    }
    return NULL;
}

/*
 *--------------------------------------------------------------
 *
 * RbcSetWindowInstanceData --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcSetWindowInstanceData(
    Tk_Window tkwin,
    ClientData instanceData)
{
TkWindow *winPtr = (TkWindow *) tkwin;

    winPtr->instanceData = instanceData;
}

/*
 *--------------------------------------------------------------
 *
 * RbcGetWindowInstanceData --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
ClientData
RbcGetWindowInstanceData(
    Tk_Window tkwin)
{
TkWindow *winPtr = (TkWindow *) tkwin;

    return winPtr->instanceData;
}

/*
 *--------------------------------------------------------------
 *
 * RbcDeleteWindowInstanceData --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
void
RbcDeleteWindowInstanceData(
    Tk_Window tkwin)
{
}

/*
 *--------------------------------------------------------------
 *
 * Rbc_SnapWindow --
 *
 *      Snaps a picture of a window and stores it in a
 *      designated photo image.  The window must be completely
 *      visible or the snap will fail.
 *
 * Results:
 *      Returns a standard Tcl result.  interp->result contains
 *      the list of the graph coordinates. If an error occurred
 *      while parsing the window positions, TCL_ERROR is
 *      returned, then interp->result will contain an error
 *      message.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
Rbc_SnapWindow(
    Tcl_Interp * interp,       /* Current interpreter. */
    Tk_Window tkmain,          /* Window of topelevel window */
    const char *pathName,      /* Window path of window to snap */
    const char *photoImage,    /* Name of exisiting photo image to save to */
    int destWidth,             /* used if >0 */
    int destHeight)
{              /* used if >0 */
    Tk_Window tkwin;
    int width, height;
    Window window;

    tkwin = Tk_NameToWindow(interp, pathName, tkmain);
    if(tkwin == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("window \"%s\" not found",
                pathName));
        return TCL_ERROR;
    }
    if(Tk_WindowId(tkwin) == None) {
        Tk_MakeWindowExist(tkwin);
    }

    if(Tk_IsTopLevel(tkwin)) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("window \"%s\" is not supported toplvel", pathName));
        return TCL_ERROR;
    } else {
        window = Tk_WindowId(tkwin);
    }

    if(GetWindowSize(interp, window, &width, &height) != TCL_OK) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("can't get window geometry of \"%s\"", pathName));
        return TCL_ERROR;
    }
    if(destWidth <= 0) {
        destWidth = width;
    }
    if(destHeight <= 0) {
        destHeight = height;
    }
    return RbcSnapPhoto(interp, tkwin, window, 0, 0, width, height, destWidth,
        destHeight, photoImage, 1.0);
}

#ifdef WIN32

/*
 *--------------------------------------------------------------
 *
 * GetWindowSize --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
GetWindowSize(
    Tcl_Interp * interp,
    Window window,
    int *widthPtr,
    int *heightPtr)
{
    int result;
    RECT region;
    TkWinWindow *winPtr = (TkWinWindow *) window;

    result = GetWindowRect(winPtr->handle, &region);
    if(result) {
        *widthPtr = region.right - region.left;
        *heightPtr = region.bottom - region.top;
        return TCL_OK;
    }
    return TCL_ERROR;
}
#else

/*
 *----------------------------------------------------------------------
 *
 * XGeometryErrorProc --
 *
 *	Flags errors generated from XGetGeometry calls to the X server.
 *
 * Results:
 *	Always returns 0.
 *
 * Side Effects:
 *	Sets a flag, indicating an error occurred.
 *
 *----------------------------------------------------------------------
 */

/* ARGSUSED */
static int
XGeometryErrorProc(
    clientData,
    errEventPtr)
    ClientData clientData;
    XErrorEvent *errEventPtr;
{
int *errorPtr = clientData;

    *errorPtr = TCL_ERROR;
    return 0;
}

/*
 *--------------------------------------------------------------
 *
 * GetWindowSize --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
GetWindowSize(
    Tcl_Interp * interp,
    Window window,
    int *widthPtr,
    int *heightPtr)
{
    int result;
    int any = -1;
    int x, y, borderWidth, depth;
    Window root;
    Tk_ErrorHandler handler;
    Tk_Window tkwin;

    tkwin = Tk_MainWindow(interp);
    handler = Tk_CreateErrorHandler(Tk_Display(tkwin), any, X_GetGeometry,
        any, XGeometryErrorProc, &result);
    result = XGetGeometry(Tk_Display(tkwin), window, &root, &x, &y,
        (unsigned int *)widthPtr, (unsigned int *)heightPtr,
        (unsigned int *)&borderWidth, (unsigned int *)&depth);
    Tk_DeleteErrorHandler(handler);
    XSync(Tk_Display(tkwin), False);
    if(result) {
        return TCL_OK;
    }
    return TCL_ERROR;
}
#endif

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoVector.c.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcVector.c --
 *
 *      TODO: Description
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define VECTOR_THREAD_KEY	"Rbc Vector Data"
#define VECTOR_MAGIC		((unsigned int) 0x46170277)
#define MAX_ERR_MSG	1023
#define DEF_ARRAY_SIZE		64

#define TRACE_ALL  (TCL_TRACE_WRITES | TCL_TRACE_READS | TCL_TRACE_UNSETS)

/* These defines allow parsing of different types of indices */

/* Never notify clients of updates to the vector */
#define NOTIFY_NEVER		(1<<3)

/* Notify clients after each update of the vector is made */
#define NOTIFY_ALWAYS		(1<<4)

/* Notify clients at the next idle point that the vector has been updated. */
#define NOTIFY_WHENIDLE		(1<<5)

/* A do-when-idle notification of the vector's clients is pending. */
#define NOTIFY_PENDING		(1<<6)
#define NOTIFY_UPDATED		((int) RBC_VECTOR_NOTIFY_UPDATE)
#define NOTIFY_DESTROYED	((int) RBC_VECTOR_NOTIFY_DESTROY)

#define VECTOR_CHAR(c)	((isalnum(UCHAR(c))) || \
	(c == '_') || (c == ':') || (c == '@') || (c == '.'))

static const char *subCmds[] =
    { "*", "+", "-", "/", "append", "binread", "clear", "delete", "dup",
    "expr", "index", "length", "merge", "normalize", "offset", "populate",
    "random", "range", "search", "seq", "set", "sort", "split", "variable",
    NULL
};

enum cmdIdx {
    multIdx,
    plusIdx,
    minusIdx,
    divisionIdx,
    appendIdx,
    binreadIdx,
    clearIdx,
    deleteIdx,
    dupIdx,
    exprIdx,
    indexIdx,
    lengthIdx,
    mergeIdx,
    normalizeIdx,
    offsetIdx,
    populateIdx,
    randomIdx,
    rangeIdx,
    searchIdx,
    seqIdx,
    setIdx,
    sortIdx,
    splitIdx,
    variableIdx
};

/*
 *	A vector can be shared by several clients.  Each client
 *	allocates this structure that acts as its key for using the
 *	vector.  Clients can also designate a callback routine that is
 *	executed whenever the vector is updated or destroyed.
 *
 */
typedef struct {
    unsigned int magic;        /* Magic value designating whether this
                                * really is a vector token or not */
    RbcVectorObject *serverPtr; /* Pointer to the master record of the
                                 * vector.  If NULL, indicates that the
                                 * vector has been destroyed but as of
                                 * yet, this client hasn't recognized
                                 * it. */
    RbcVectorChangedProc *proc; /* Routine to call when the contents
                                 * of the vector change or the vector
                                 * is deleted. */
    ClientData clientData;     /* Data passed whenever the vector
                                * change procedure is called. */
    RbcChainLink *linkPtr;     /* Used to quickly remove this entry from
                                * its server's client chain. */
} VectorClient;

static int VectorObjCmd(
    ClientData dataPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int VectorInstanceCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int VectorCreateObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int VectorDestroyObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int VectorExprObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static int VectorNamesObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[]);
static void VectorInterpDeleteProc(
    ClientData clientData,
    Tcl_Interp * interp);
static void VectorInstDeleteProc(
    ClientData clientData);
static void VectorNotifyClients(
    ClientData clientData);
static void VectorFlushCache(
    RbcVectorObject * vPtr);
static const char *VectorVarTrace(
    ClientData clientData,
    Tcl_Interp * interp,
    const char *part1,
    const char *part2,
    int flags);
static const char *BuildQualifiedName(
    Tcl_Interp * interp,
    const char *name,
    Tcl_DString * fullName);
static int ParseQualifiedName(
    Tcl_Interp * interp,
    const char *qualName,
    Tcl_Namespace ** nsPtrPtr,
    const char **namePtrPtr);
static const char *GetQualifiedName(
    Tcl_Namespace * nsPtr,
    const char *name,
    Tcl_DString * resultPtr);
static RbcVectorObject *GetVectorObject(
    RbcVectorInterpData * dataPtr,
    const char *name,
    int flags);
static RbcVectorObject *FindVectorInNamespace(
    RbcVectorInterpData * dataPtr,
    Tcl_Namespace * nsPtr,
    const char *vecName);
static void DeleteCommand(
    RbcVectorObject * vPtr);
static void UnmapVariable(
    RbcVectorObject * vPtr);

double rbcNaN;

/*
 * -----------------------------------------------------------------------
 *
 * Rbcdrand48 --
 *
 *      TODO
 *
 * Results:
 *      TODO
 *
 * Side effects:
 *      TODO
 *
 * ------------------------------------------------------------------------
 */
double
Rbcdrand48(
    )
{
    return ((double)rand() / (double)RAND_MAX);
}

/*
 * -----------------------------------------------------------------------
 *
 * Tko_VectorInit --
 *
 *      This procedure is invoked to initialize the "vector" command.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Creates the new command and adds a new entry into a global Tcl
 *      associative array.
 *
 * ------------------------------------------------------------------------
 */
int
Tko_VectorInit(
    Tcl_Interp * interp)
{
RbcVectorInterpData *dataPtr;  /* Interpreter-specific data. */
#ifdef __BORLANDC__
union Real {
    struct DoubleWord {
        int lo, hi;
    } doubleWord;
    double number;
} real;
    real.doubleWord.lo = real.doubleWord.hi = 0x7FFFFFFF;
    rbcNaN = real.number;
#endif /* __BORLANDC__ */

#ifdef _MSC_VER
    rbcNaN = sqrt(-1.0);        /* Generate IEEE 754 Quiet Not-A-Number. */
#endif /* _MSC_VER */

#if !defined(__BORLANDC__) && !defined(_MSC_VER)
    rbcNaN = 0.0 / 0.0; /* Generate IEEE 754 Not-A-Number. */
#endif /* !__BORLANDC__  && !_MSC_VER */

    /*
     * Create and export our public API.
     */
    dataPtr = RbcVectorGetInterpData(interp);
    Tcl_CreateObjCommand(interp, "::graph::vector", VectorObjCmd, dataPtr,
        NULL);

    return TCL_OK;
}

/*
 * ------------------------------------------------------------------------
 *
 * VectorObjCmd --
 *
 *      This implements the Tcl vector command from the rbc package.
 *      See the user documentation on what is does.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      Do some user action.
 *
 * ------------------------------------------------------------------------
 */
static int
VectorObjCmd(
    ClientData dataPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    int index;
    const char *subCmds[] = { "create", "destroy", "expr", "names", NULL };
    enum RecodeIndex {
        createIndex, destroyIndex, exprIndex, namesIndex
    };

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "command ?args?");
        return TCL_ERROR;
    }

    if(Tcl_GetIndexFromObj(interp, objv[1], subCmds, "command", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }

    switch (index) {
    case createIndex:{
        return VectorCreateObjCmd((ClientData) dataPtr, interp, objc, objv);
    }
    case destroyIndex:{
        return VectorDestroyObjCmd((ClientData) dataPtr, interp, objc, objv);
    }
    case exprIndex:{
        return VectorExprObjCmd((ClientData) dataPtr, interp, objc, objv);
    }
    case namesIndex:{
        return VectorNamesObjCmd((ClientData) dataPtr, interp, objc, objv);
    }
    }

    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * VectorInstanceCmd --
 *
 *      Instance command for the vector. This command
 *      is registered via Tcl_CreatObjCommand for each new vector
 *      and is called when the Tcl vector instance command is called
 *
 * Results:
 *      Returns the result from the operation called on the command or
 *      TCL_ERROR if the operation was unknown or a wrong number of
 *      arguments was specified
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
VectorInstanceCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorObject *vPtr = clientData;
    int index;

    if(objc < 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "option ?args?");
        return TCL_ERROR;
    }

    if(Tcl_GetIndexFromObj(interp, objv[1], subCmds, "option", 0,
            &index) != TCL_OK) {
        return TCL_ERROR;
    }

    vPtr->first = 0;
    vPtr->last = vPtr->length - 1;

    switch (index) {
    case multIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "list");
            return TCL_ERROR;
        } else {
            return RbcArithOp(vPtr, interp, objc, objv);
        }
    }
    case plusIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "list");
            return TCL_ERROR;
        } else {
            return RbcArithOp(vPtr, interp, objc, objv);
        }
    }
    case minusIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "list");
            return TCL_ERROR;
        } else {
            return RbcArithOp(vPtr, interp, objc, objv);
        }
    }
    case divisionIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "list");
            return TCL_ERROR;
        } else {
            return RbcArithOp(vPtr, interp, objc, objv);
        }
    }
    case appendIdx:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "item ?item...?");
            return TCL_ERROR;
        } else {
            return RbcAppendOp(vPtr, interp, objc, objv);
        }
    }
    case binreadIdx:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "channel ?numValues? ?flags?");
            return TCL_ERROR;
        } else {
            return RbcBinreadOp(vPtr, interp, objc, objv);
        }
    }
    case clearIdx:{
        if(objc > 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "");
            return TCL_ERROR;
        } else {
            return RbcClearOp(vPtr, interp, objc, objv);
        }
    }
    case deleteIdx:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "index ?index...?");
            return TCL_ERROR;
        } else {
            return RbcDeleteOp(vPtr, interp, objc, objv);
        }
    }
    case dupIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "vecName");
            return TCL_ERROR;
        } else {
            return RbcDupOp(vPtr, interp, objc, objv);
        }
    }
    case exprIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "expression");
            return TCL_ERROR;
        } else {
            return RbcExprOp(vPtr, interp, objc, objv);
        }
    }
    case indexIdx:{
        if((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "index ?value?");
            return TCL_ERROR;
        } else {
            return RbcIndexOp(vPtr, interp, objc, objv);
        }
    }
    case lengthIdx:{
        if((objc < 2) || (objc > 3)) {
            Tcl_WrongNumArgs(interp, 2, objv, "?newSize?");
            return TCL_ERROR;
        } else {
            return RbcLengthOp(vPtr, interp, objc, objv);
        }
    }
    case mergeIdx:{
        if(objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "vecName ?vecName...?");
            return TCL_ERROR;
        } else {
            return RbcMergeOp(vPtr, interp, objc, objv);
        }
    }
    case normalizeIdx:{
        if((objc < 2) || (objc > 3)) {
            Tcl_WrongNumArgs(interp, 2, objv, "?vecName?");
            return TCL_ERROR;
        } else {
            return RbcNormalizeOp(vPtr, interp, objc, objv);
        }
    }
    case offsetIdx:{
        if((objc < 2) || (objc > 3)) {
            Tcl_WrongNumArgs(interp, 2, objv, "?offset?");
            return TCL_ERROR;
        } else {
            return RbcOffsetOp(vPtr, interp, objc, objv);
        }
    }
    case randomIdx:{
        if(objc > 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "");
            return TCL_ERROR;
        } else {
            return RbcRandomOp(vPtr, interp, objc, objv);
        }
    }
    case populateIdx:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "vecName density");
            return TCL_ERROR;
        } else {
            return RbcPopulateOp(vPtr, interp, objc, objv);
        }
    }
    case rangeIdx:{
        if(objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "first last");
            return TCL_ERROR;
        } else {
            return RbcRangeOp(vPtr, interp, objc, objv);
        }
    }
    case searchIdx:{
        if((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "?-value? value ?value?");
            return TCL_ERROR;
        } else {
            return RbcSearchOp(vPtr, interp, objc, objv);
        }
    }
    case seqIdx:{
        if((objc < 4) || (objc > 5)) {
            Tcl_WrongNumArgs(interp, 2, objv, "start end ?step?");
            return TCL_ERROR;
        } else {
            return RbcSeqOp(vPtr, interp, objc, objv);
        }
    }
    case setIdx:{
        if(objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "list");
            return TCL_ERROR;
        } else {
            return RbcSetOp(vPtr, interp, objc, objv);
        }
    }
    case sortIdx:{
        if(objc < 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "?-reverse? ?vecName...?");
            return TCL_ERROR;
        } else {
            return RbcSortOp(vPtr, interp, objc, objv);
        }
    }
    case splitIdx:{
        if(objc < 2) {
            Tcl_WrongNumArgs(interp, 2, objv, "?vecName...?");
            return TCL_ERROR;
        } else {
            return RbcSplitOp(vPtr, interp, objc, objv);
        }
    }
    case variableIdx:{
        if((objc < 2) || (objc > 3)) {
            Tcl_WrongNumArgs(interp, 2, objv, "?varName?");
            return TCL_ERROR;
        } else {
            return RbcVariableOp(vPtr, interp, objc, objv);
        }
    }
    }
    /* we should never reach this point: */
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * VectorCreateObjCmd --
 *
 *      processes the Tcl 'vector create' command, and calls
 *      vectorCreate to actually create the vector
 *
 *        vector create a
 *        vector create b(20)
 *        vector create c(-5:14)
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      See the user documentation.
 *
 *----------------------------------------------------------------------
 */
static int
VectorCreateObjCmd(
    ClientData clientData,     /* Vector interp data */
    Tcl_Interp * interp,       /* Interp to return results to */
    int objc,                  /* argument count */
    Tcl_Obj * const objv[])
{              /* arguments to the command */
    RbcVectorInterpData *dataPtr = clientData;
    RbcVectorObject *vPtr;
    Tcl_Obj *resultPtr;        /* for the result of this function */
    char *leftParen, *rightParen;       /* positions of left and right parens in vector specification */
    int isNew, size, first, last;
    char *cmdName, *varName, *switchName;
    int length;
    int freeOnUnset, flush;
    char **nameArr;            /* holds all vector names specified */
    int count;
    register int i;

    resultPtr = Tcl_NewStringObj("", -1);

    /*
     * Handle switches to the vector command and collect the vector
     * name arguments into an array.
     */
    varName = NULL;     /* name of Tcl variable to link to the vector */
    cmdName = NULL;     /* name of Tcl command to link to vector */
    freeOnUnset = 0;    /* value of the user level '-watchunset' switch */
    flush = FALSE;
    nameArr = (char **)ckalloc(sizeof(char *) * objc);

    /***    assert(nameArr); */
    count = 0;
    vPtr = NULL;
    for(i = 2; i < objc; i++) {
        /* collect all arguments: */
        if(Tcl_GetStringFromObj(objv[i], NULL)[0] == '-') {
            /* found a switch: */
            switchName = Tcl_GetStringFromObj(objv[i], &length);
            if((length > 1) && (strncmp(switchName, "-variable", length) == 0)) {
                /* process -variable switch: */
                if((i + 1) == objc) {
                    Tcl_AppendStringsToObj(resultPtr,
                        "no variable name supplied with \"-variable\" switch",
                        NULL);
                    Tcl_SetObjResult(interp, resultPtr);
                    goto error;
                }
                i++;
                varName = Tcl_GetStringFromObj(objv[i], NULL);
            } else if((length > 1)
                && (strncmp(switchName, "-command", length) == 0)) {
                /* process -command switch: */
                if((i + 1) == objc) {
                    Tcl_AppendStringsToObj(resultPtr,
                        "no command name supplied with \"-command\" switch",
                        NULL);
                    Tcl_SetObjResult(interp, resultPtr);
                    goto error;
                }
                i++;
                cmdName = Tcl_GetStringFromObj(objv[i], NULL);
            } else if((length > 1)
                && (strncmp(switchName, "-watchunset", length) == 0)) {
                /* process -watchunset switch: */
    int bool;

                if((i + 1) == objc) {
                    Tcl_AppendStringsToObj(resultPtr,
                        "no value name supplied with \"-watchunset\" switch",
                        NULL);
                    Tcl_SetObjResult(interp, resultPtr);
                    goto error;
                }
                i++;
                if(Tcl_GetBooleanFromObj(interp, objv[i], &bool) != TCL_OK) {
                    goto error;
                }
                freeOnUnset = bool;
            } else if((length > 1)
                && (strncmp(switchName, "-flush", length) == 0)) {
                /* process -flush switch: */
    int bool;

                if((i + 1) == objc) {
                    Tcl_AppendStringsToObj(resultPtr,
                        "no value name supplied with \"-flush\" switch", NULL);
                    Tcl_SetObjResult(interp, resultPtr);
                    goto error;
                }
                i++;
                if(Tcl_GetBooleanFromObj(interp, objv[i], &bool) != TCL_OK) {
                    goto error;
                }
                flush = bool;
            } else {
                Tcl_AppendStringsToObj(resultPtr,
                    "bad vector switch \"",
                    switchName,
                    "\": must be -command, -flush, -variable, or -watchunset",
                    NULL);
                Tcl_SetObjResult(interp, resultPtr);
                goto error;
            }
        } else {
            /* found a vector name: */
            nameArr[count++] = Tcl_GetStringFromObj(objv[i], NULL);
        }
    }
    /* finished parsing arguments -> do some sanity checks: */
    if(count == 0) {
        Tcl_AppendStringsToObj(resultPtr, "no vector names supplied", NULL);
        Tcl_SetObjResult(interp, resultPtr);
        goto error;
    }

    if(count > 1) {
        if((cmdName != NULL) && (cmdName[0] != '\0')) {
            Tcl_AppendStringsToObj(resultPtr,
                "can't specify more than one vector with \"-command\" switch",
                NULL);
            Tcl_SetObjResult(interp, resultPtr);
            goto error;
        }
        if((varName != NULL) && (varName[0] != '\0')) {
            Tcl_AppendStringsToObj(resultPtr,
                "can't specify more than one vector with \"-variable\" switch",
                NULL);
            Tcl_SetObjResult(interp, resultPtr);
            goto error;
        }
    }

    /* now process the vector names and check their validity: */
    for(i = 0; i < count; i++) {
        size = first = last = 0;
        leftParen = strchr(nameArr[i], '(');
        rightParen = strchr(nameArr[i], ')');
        if(((leftParen != NULL) && (rightParen == NULL)) || ((leftParen
                    == NULL) && (rightParen != NULL))
            || (leftParen > rightParen)) {
            Tcl_AppendStringsToObj(resultPtr, "bad vector specification \"",
                nameArr[i], "\"", NULL);
            Tcl_SetObjResult(interp, resultPtr);
            goto error;
        }
        if(leftParen != NULL) {
    int result;
    char *colon;

            *rightParen = '\0';
            colon = strchr(leftParen + 1, ':');
            if(colon != NULL) {
                /* Specification is in the form vecName(first:last) */
                *colon = '\0';
                result = Tcl_GetInt(interp, leftParen + 1, &first);
                if((*(colon + 1) != '\0') && (result == TCL_OK)) {
                    result = Tcl_GetInt(interp, colon + 1, &last);
                    if(first > last) {
                        Tcl_AppendStringsToObj(resultPtr,
                            "bad vector range \"", nameArr[i], "\"", NULL);
                        Tcl_SetObjResult(interp, resultPtr);
                        result = TCL_ERROR;
                    }
                    size = (last - first) + 1;
                }
                *colon = ':';
            } else {
                /* Specification is in the form vecName(size) */
                result = Tcl_GetInt(interp, leftParen + 1, &size);
            }
            *rightParen = ')';
            if(result != TCL_OK) {
                goto error;
            }
            if(size < 0) {
                Tcl_AppendStringsToObj(resultPtr, "bad vector size \"",
                    nameArr[i], "\"", NULL);
                Tcl_AppendResult(interp, resultPtr);
                goto error;
            }
        }
        if(leftParen != NULL) {
            *leftParen = '\0';
        }

        /*
         * actually create the vector:
         */
        vPtr = RbcVectorCreate(dataPtr, nameArr[i],
            (cmdName == NULL) ? nameArr[i] : cmdName,
            (varName == NULL) ? nameArr[i] : varName, &isNew);

        if(leftParen != NULL) {
            *leftParen = '(';
        }
        if(vPtr == NULL) {
            goto error;
        }
        vPtr->freeOnUnset = freeOnUnset;
        vPtr->flush = flush;
        vPtr->offset = first;
        if(size > 0) {
            if(RbcVectorChangeLength(vPtr, size) != TCL_OK) {
                goto error;
            }
        }
        if(!isNew) {
            if(vPtr->flush) {
                VectorFlushCache(vPtr);
            }
            RbcVectorUpdateClients(vPtr);
        }
    }
    ckfree((char *)nameArr);
    if(vPtr != NULL) {
        /* Return the name of the last vector created  */
        Tcl_SetObjResult(interp, Tcl_NewStringObj(vPtr->name, -1));
    }
    return TCL_OK;
  error:
    ckfree((char *)nameArr);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * VectorDestroyObjCmd --
 *
 *      processes the Tcl 'vector destroy' command, and calls vectorCreate
 *      to actually create the vector
 *
 *        vector create a
 *        vector create b(20)
 *        vector create c(-5:14)
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      See the user documentation.
 *
 *----------------------------------------------------------------------
 */
static int
VectorDestroyObjCmd(
    ClientData clientData,     /* Interpreter-specific data. */
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    /* Not Implemented Correctly */

    RbcVectorInterpData *dataPtr = clientData;
    RbcVectorObject *vPtr;
    register int i;
    for(i = 2; i < objc; i++) {
        if(RbcVectorLookupName(dataPtr, Tcl_GetStringFromObj(objv[i], NULL),
                &vPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        Rbc_VectorFree(vPtr);
    }

    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * VectorExprObjCmd --
 *
 *      Computes the result of the expression which may be
 *      either a scalar (single value) or vector (list of values).
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
VectorExprObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    return RbcExprVector(interp, Tcl_GetString(objv[2]), (Rbc_Vector *) NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * VectorNamesObjCmd --
 *
 *      Reports the names of all the current vectors in the
 *      interpreter.
 *
 * Results:
 *      A standard Tcl result.  interp->result will contain a
 *      list of all the names of the vector instances.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
static int
VectorNamesObjCmd(
    ClientData clientData,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorInterpData *dataPtr = clientData;
    Tcl_HashEntry *hPtr;
    const char *name;
    Tcl_HashSearch cursor;
    Tcl_Obj *resultPtr;

    resultPtr = Tcl_NewListObj(0, NULL);
    for(hPtr = Tcl_FirstHashEntry(&(dataPtr->vectorTable), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        name = Tcl_GetHashKey(&(dataPtr->vectorTable), hPtr);
        if((objc == 2) || (Tcl_StringMatch(name, Tcl_GetString(objv[2])))) {
            Tcl_ListObjAppendElement(interp, resultPtr, Tcl_NewStringObj(name,
                    -1));
        }
    }
    Tcl_SetObjResult(interp, resultPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 *RbcVectorGetInterpData --
 *
 *      Gathers the data need for the vector interpreter to function.
 *      It then stores it into the vector interpreter.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Creates the new command and adds a new entry into a global Tcl
 *      associative array.
 *
 * ------------------------------------------------------------------------
 */

RbcVectorInterpData *
RbcVectorGetInterpData(
    Tcl_Interp * interp)
{              /* Base interpreter to wrap. */
RbcVectorInterpData *dataPtr;
Tcl_InterpDeleteProc *proc;

    dataPtr =
        (RbcVectorInterpData *) Tcl_GetAssocData(interp, VECTOR_THREAD_KEY,
        &proc);
    if(dataPtr == NULL) {
        dataPtr = (RbcVectorInterpData *) ckalloc(sizeof(RbcVectorInterpData));

        /***	assert(dataPtr); */
        dataPtr->interp = interp;
        dataPtr->nextId = 0;
        Tcl_SetAssocData(interp, VECTOR_THREAD_KEY, VectorInterpDeleteProc,
            dataPtr);
        Tcl_InitHashTable(&(dataPtr->vectorTable), TCL_STRING_KEYS);
        Tcl_InitHashTable(&(dataPtr->mathProcTable), TCL_STRING_KEYS);
        Tcl_InitHashTable(&(dataPtr->indexProcTable), TCL_STRING_KEYS);
        RbcVectorInstallMathFunctions(&(dataPtr->mathProcTable));
        RbcVectorInstallSpecialIndices(&(dataPtr->indexProcTable));

/* ???        srand(time((time_t *) NULL)); */
    }
    return dataPtr;
}

/*
 * -----------------------------------------------------------------------
 *
 * VectorInterpDeleteProc --
 *
 *      This is called when the interpreter hosting the "vector"
 *      command is deleted.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Destroys the math and index hash tables.  In addition removes
 *      the hash table managing all vector names.
 *
 * ------------------------------------------------------------------------
 */
static void
VectorInterpDeleteProc(
    ClientData clientData,     /* Interpreter Specific */
    Tcl_Interp * interp)
{
RbcVectorInterpData *dataPtr = clientData;
Tcl_HashEntry *hPtr;
Tcl_HashSearch cursor;
RbcVectorObject *vPtr;

    for(hPtr = Tcl_FirstHashEntry(&(dataPtr->vectorTable), &cursor);
        hPtr != NULL; hPtr = Tcl_NextHashEntry(&cursor)) {
        vPtr = (RbcVectorObject *) Tcl_GetHashValue(hPtr);
        vPtr->hashPtr = NULL;
        Rbc_VectorFree(vPtr);
    }
    Tcl_DeleteHashTable(&(dataPtr->vectorTable));

    /* If any user-defined math functions were installed, remove them.  */
    Tcl_DeleteHashTable(&(dataPtr->mathProcTable));

    Tcl_DeleteHashTable(&(dataPtr->indexProcTable));
    Tcl_DeleteAssocData(interp, VECTOR_THREAD_KEY);
    ckfree((char *)dataPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorNew --
 *
 *      Creates a new vector object and populates with the needed data.
 *
 * Results:
 *      A pointer to the new vector object
 *
 * Side effects:
 *      None
 *
 * ---------------------------------------------------------------------- */
RbcVectorObject *
RbcVectorNew(
    RbcVectorInterpData * dataPtr)
{              /* Interpreter-specific data. */
RbcVectorObject *vPtr;

    vPtr = RbcCalloc(1, sizeof(RbcVectorObject));

    /***    assert(vPtr); */
    vPtr->notifyFlags = NOTIFY_WHENIDLE;
    vPtr->freeProc = TCL_STATIC;
    vPtr->dataPtr = dataPtr;
    vPtr->valueArr = NULL;
    vPtr->length = vPtr->size = 0;
    vPtr->interp = dataPtr->interp;
    vPtr->hashPtr = NULL;
    vPtr->chainPtr = RbcChainCreate();
    vPtr->flush = FALSE;
    vPtr->min = vPtr->max = rbcNaN;
    return vPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorCreate --
 *
 *      Actually creates a vector structure and the following items:
 *
 *        o Tcl command
 *        o Tcl array variable and establishes traces on the variable
 *        o Adds a  new entry in the vector hash table
 *
 * Results:
 *      A pointer to the new vector structure.  If an error occurred
 *      NULL is returned and an error message is left in
 *      interp->result.
 *
 * Side effects:
 *      A new Tcl command and array variable is added to the
 *      interpreter.
 *
 * ---------------------------------------------------------------------- */
RbcVectorObject *RbcVectorCreate(
    RbcVectorInterpData * dataPtr,      /* Interpreter-specific data (clientData). */
    const char *vecName,       /* Name of the vector */
    const char *cmdName,       /* Name of the Tcl command mapped to the vector; if NULL (actually '\0') then do not create a command */
    const char *varName,       /* Name of the Tcl array mapped to the vector; if NULL (actually '\0') then do not create a variable */
    int *newPtr) {      /* pointer to the vector created */
Tcl_Obj *resultPtr = Tcl_NewStringObj("", -1);
RbcVectorObject *vPtr;
int isNew;
int isAutoName = 0;            /* is the name autmatically generated? */
const char *qualVecName = NULL; /* qualified name of the vector */
const char *vecNameTail;       /* the name of the vector without namespace */
Tcl_Namespace *nsPtr;          /* namespace of the vector name */
Tcl_HashEntry *hPtr;
Tcl_Interp *interp = dataPtr->interp;
Tcl_DString qualVecNamePtr;

    isNew = 0;
    nsPtr = NULL;
    vPtr = NULL;

    /* process the vector name: */
    vecName = BuildQualifiedName(interp, vecName, &qualVecNamePtr);
    if(ParseQualifiedName(interp, vecName, &nsPtr, &vecNameTail) != TCL_OK) {
        Tcl_AppendStringsToObj(resultPtr, "unknown namespace in \"", vecName,
            "\"", NULL);
        Tcl_SetObjResult(interp, resultPtr);
        return NULL;
    }

    if((vecNameTail[0] == '#') && (strcmp(vecNameTail, "#auto") == 0)) {
        /* generate a unique automatic name for the vector: */
char string[200];

        do {
            sprintf(string, "vector%d", dataPtr->nextId++);
            qualVecName = GetQualifiedName(nsPtr, string, &qualVecNamePtr);
            hPtr = Tcl_FindHashEntry(&(dataPtr->vectorTable), qualVecName);
        } while(hPtr != NULL);
        isAutoName = 1;
    } else {
        /* check correct vector name syntax: */
register const char *p;

        for(p = vecNameTail; *p != '\0'; p++) {
            if(!VECTOR_CHAR(*p)) {
                Tcl_AppendStringsToObj(resultPtr,
                    "bad vector name \"",
                    vecName,
                    "\": must contain digits, letters, underscore, or period",
                    NULL);
                Tcl_SetObjResult(interp, resultPtr);
                goto error;
            }
        }
        qualVecName = (char *)vecName;
        vPtr =
            RbcVectorParseElement((Tcl_Interp *) NULL, dataPtr, qualVecName,
            (char **)NULL, RBC_NS_SEARCH_CURRENT);
    }

    if(vPtr == NULL) {
        hPtr =
            Tcl_CreateHashEntry(&(dataPtr->vectorTable), qualVecName, &isNew);
        vPtr = RbcVectorNew(dataPtr);
        vPtr->hashPtr = hPtr;

        vPtr->name = Tcl_GetHashKey(&(dataPtr->vectorTable), hPtr);

#ifdef NAMESPACE_DELETE_NOTIFY
        /* Not Implemented Yet */

        /***	RbcCreateNsDeleteNotify(interp, nsPtr, vPtr, VectorInstDeleteProc); */
#endif /* NAMESPACE_DELETE_NOTIFY */

        Tcl_SetHashValue(hPtr, vPtr);
    }

    /* process the command name: */
    if(cmdName != NULL) {
Tcl_CmdInfo cmdInfo;

        if(isAutoName) {
            cmdName = qualVecName;
        } else {
            cmdName = BuildQualifiedName(interp, cmdName, &qualVecNamePtr);
        }
        nsPtr = NULL;
        vecNameTail = NULL;
        if(ParseQualifiedName(interp, cmdName, &nsPtr, &vecNameTail) != TCL_OK) {
            Tcl_AppendStringsToObj(resultPtr, "unknown namespace in \"",
                cmdName, "\"", NULL);
            Tcl_SetObjResult(interp, resultPtr);
            return NULL;
        }

        if(Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) {
            if(vPtr != cmdInfo.objClientData) {
                Tcl_AppendStringsToObj(resultPtr, "command \"", cmdName,
                    "\" already exists", NULL);
                Tcl_SetObjResult(interp, resultPtr);
                goto error;
            }
        }
    }

    if(vPtr->cmdToken != 0) {
        DeleteCommand(vPtr);    /* Command already exists, delete old first */
    }

    if(cmdName != NULL) {
        vPtr->cmdToken =
            Tcl_CreateObjCommand(interp, cmdName, VectorInstanceCmd, vPtr,
            VectorInstDeleteProc);
    }

    /* process array variable: */
    if(varName != NULL) {
        if((varName[0] == '#') && (strcmp(varName, "#auto") == 0)) {
            varName = vPtr->name;
        } else {
            varName = BuildQualifiedName(interp, varName, &qualVecNamePtr);
        }
        if(RbcVectorMapVariable(interp, vPtr, varName) != TCL_OK) {
            goto error;
        }
    }

    *newPtr = isNew;
    Tcl_DStringFree(&qualVecNamePtr);
    return vPtr;

  error:
    if(vPtr != NULL) {
        Rbc_VectorFree(vPtr);
    }
    Tcl_DStringFree(&qualVecNamePtr);
    return NULL;
}

/*
 * ----------------------------------------------------------------------
 *
 * VectorInstDeleteProc --
 *
 *     Deletes the command associated with the vector.  This is
 *     called only when the command associated with the vector is
 *     destroyed.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
VectorInstDeleteProc(
    ClientData clientData)
{              /* Vector object to delete */
RbcVectorObject *vPtr = clientData;

    vPtr->cmdToken = 0;
    Rbc_VectorFree(vPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * Rbc_VectorFree --
 *
 *     Removes the memory and frees resources associated with the
 *     vector.
 *
 *        o Removes the trace and the Tcl array variable and unsets
 *          the variable.
 *        o Notifies clients of the vector that the vector is being
 *          destroyed.
 *        o Removes any clients that are left after notification.
 *        o Frees the memory (if necessary) allocated for the array.
 *        o Removes the entry from the hash table of vectors.
 *        o Frees the memory allocated for the name.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
void
Rbc_VectorFree(
    RbcVectorObject * vPtr)
{              /* The vector to free */
RbcChainLink *linkPtr;
VectorClient *clientPtr;

    if(vPtr->cmdToken != 0) {
        DeleteCommand(vPtr);
    }

    if(vPtr->arrayName != NULL) {
        UnmapVariable(vPtr);
    }
    vPtr->length = 0;

    /* Immediately notify clients that vector is going away */
    if(vPtr->notifyFlags & NOTIFY_PENDING) {
        vPtr->notifyFlags &= ~NOTIFY_PENDING;
        Tcl_CancelIdleCall(VectorNotifyClients, vPtr);
    }
    vPtr->notifyFlags |= NOTIFY_DESTROYED;
    VectorNotifyClients(vPtr);

    for(linkPtr = RbcChainFirstLink(vPtr->chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        clientPtr = RbcChainGetValue(linkPtr);
        ckfree((char *)clientPtr);
    }
    RbcChainDestroy(vPtr->chainPtr);
    if((vPtr->valueArr != NULL) && (vPtr->freeProc != TCL_STATIC)) {
        if(vPtr->freeProc == TCL_DYNAMIC) {
            ckfree((char *)vPtr->valueArr);
        } else {
            (*vPtr->freeProc) ((char *)vPtr->valueArr);
        }
    }
    if(vPtr->hashPtr != NULL) {
        Tcl_DeleteHashEntry(vPtr->hashPtr);
    }
#ifdef NAMESPACE_DELETE_NOTIFY
    if(vPtr->nsPtr != NULL) {
        /* Not Implemented Yet */

        /*** RbcDestroyNsDeleteNotify(vPtr->interp, vPtr->nsPtr, vPtr); */
    }
#endif /* NAMESPACE_DELETE_NOTIFY */
    ckfree((char *)vPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorDuplicate --
 *
 *      Duplicates all elements of a vector.
 *
 * Results:
 *      Standard Tcl result.
 *
 * Side effects:
 *      New vector is created.
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorDuplicate(
    RbcVectorObject * destPtr,
    RbcVectorObject * srcPtr)
{
int nBytes;
int length;

    length = srcPtr->last - srcPtr->first + 1;
    if(RbcVectorChangeLength(destPtr, length) != TCL_OK) {
        return TCL_ERROR;
    }
    nBytes = length * sizeof(double);
    memcpy(destPtr->valueArr, srcPtr->valueArr + srcPtr->first, nBytes);
    destPtr->offset = srcPtr->offset;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorFlushCache --
 *
 *      Unsets all the elements of the Tcl array variable associated
 *      with the vector, freeing memory associated with the variable.
 *      This includes both the hash table and the hash keys.  The down
 *      side is that this effectively flushes the caching of vector
 *      elements in the array.  This means that the subsequent reads
 *      of the array will require a decimal to string conversion.
 *
 *      This is needed when the vector changes its values, making
 *      the array variable out-of-sync.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      All elements of array variable (except one) are unset, freeing
 *      the memory associated with the variable.
 *
 * ----------------------------------------------------------------------
 */
void
RbcVectorFlushCache(
    RbcVectorObject * vPtr)
{
Tcl_Interp *interp = vPtr->interp;

    if(vPtr->arrayName == NULL) {
        return; /* Doesn't use the variable API */
    }

    /* Turn off the trace temporarily so that we can unset all the
     * elements in the array.  */

    Tcl_UntraceVar2(interp, vPtr->arrayName, (char *)NULL,
        TRACE_ALL | vPtr->varFlags, (Tcl_VarTraceProc *) VectorVarTrace, vPtr);

    /* Clear all the element entries from the entire array */
    Tcl_UnsetVar2(interp, vPtr->arrayName, (char *)NULL, vPtr->varFlags);

    /* Restore the "end" index by default and the trace on the entire array */
    Tcl_SetVar2(interp, vPtr->arrayName, "end", "", vPtr->varFlags);
    Tcl_TraceVar2(interp, vPtr->arrayName, (char *)NULL,
        TRACE_ALL | vPtr->varFlags, (Tcl_VarTraceProc *) VectorVarTrace, vPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorMapVariable --
 *
 *      Sets up traces on a Tcl variable to access the vector.
 *
 *      If another variable is already mapped, it's first untraced and
 *      removed.  Don't do anything else for variables named "" (even
 *      though Tcl allows this pathology). Saves the name of the new
 *      array variable.
 *
 * Results:
 *      A standard Tcl result. If an error occurs setting the variable
 *      TCL_ERROR is returned and an error message is left in the
 *      interpreter.
 *
 * Side effects:
 *      Traces are set for the new variable. The new variable name is
 *	    saved in a malloc'ed string in vPtr->arrayName.  If this
 *	    variable is non-NULL, it indicates that a Tcl variable has
 *      been mapped to this vector.
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorMapVariable(
    Tcl_Interp * interp,
    RbcVectorObject * vPtr,
    const char *name)
{              /* name of array variable to map to vector */
    const char *result;
    Tcl_Namespace *varNsPtr;

    if(vPtr->arrayName != NULL) {
        UnmapVariable(vPtr);
    }
    if((name == NULL) || (name[0] == '\0')) {
        /* If the variable name is the empty string, simply return after removing any existing variable. */
        return TCL_OK;
    }

    /*
     * To play it safe, delete the variable first.  This has
     * side-effect of unmapping the variable from any vector that may
     * be currently using it.
     */
    Tcl_UnsetVar2(interp, name, NULL, 0);

    /* Set the index "end" in the array.  This will create the
     * variable immediately so that we can check its namespace
     * context.
     */
    result = Tcl_SetVar2(interp, name, "end", "", TCL_LEAVE_ERR_MSG);

    /* Determine if the variable is global or not.  If there wasn't a
     * namespace qualifier, it still may be global.  We need to look
     * inside the Var structure to see what it's namespace field says.
     * NULL indicates that it's local.
     */
    varNsPtr = Tcl_FindNamespace(interp, name, NULL, 0);
    vPtr->varFlags =
        (varNsPtr != NULL) ? (TCL_NAMESPACE_ONLY | TCL_GLOBAL_ONLY) : 0;

    if(result != NULL) {
        /* Trace the array on reads, writes, and unsets */
        /*printf("trace on %s with variable %s\n",vPtr->name,name); */
        Tcl_TraceVar2(interp, name, NULL, (TRACE_ALL | vPtr->varFlags),
            (Tcl_VarTraceProc *) VectorVarTrace, vPtr);
    }

    vPtr->arrayName = RbcStrdup(name);
    return (result == NULL) ? TCL_ERROR : TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcVectorReset --
 *
 *      Resets the vector data.  This is called by a client to
 *      indicate that the vector data has changed.  The vector does
 *      not need to point to different memory.  Any clients of the
 *      vector will be notified of the change.
 *
 * Results:
 *      A standard Tcl result.  If the new array size is invalid,
 *      TCL_ERROR is returned.  Otherwise TCL_OK is returned and the
 *      new vector data is recorded.
 *
 * Side Effects:
 *      Any client designated callbacks will be posted.  Memory may
 *      be changed for the vector array.
 *
 * -----------------------------------------------------------------------
 */
int
RbcVectorReset(
    RbcVectorObject * vPtr,
    double *valueArr,          /* Array containing the elements of th
                                * vector. If NULL, indicates to reset the
                                * vector.*/
    int length,                /* The number of elements that the vector currently holds. */
    int size,                  /* The maximum number of elements that the  array can hold. */
    Tcl_FreeProc * freeProc)
{              /* Address of memory deallocation routine
                * for the array of values.  Can also be
                * TCL_STATIC, TCL_DYNAMIC, or TCL_VOLATILE. */
    if(vPtr->valueArr != valueArr) {    /* New array of values resides
                                         * in different memory than
                                         * the current vector.  */
        if((valueArr == NULL) || (size == 0)) {
            /* Empty array. Set up default values */
            freeProc = TCL_STATIC;
            valueArr = NULL;
            size = length = 0;
        } else if(freeProc == TCL_VOLATILE) {
    double *newArr;
            /* Data is volatile. Make a copy of the value array.  */
            newArr = (double *)ckalloc(size * sizeof(double));
            if(newArr == NULL) {
                Tcl_AppendPrintfToObj(Tcl_GetObjResult(vPtr->interp),
                    "can't allocate %d elements for vector \"%s\"",
                    size, vPtr->name);
                return TCL_ERROR;
            }
            memcpy((char *)newArr, (char *)valueArr, sizeof(double) * length);
            valueArr = newArr;
            freeProc = TCL_DYNAMIC;
        }

        if(vPtr->freeProc != TCL_STATIC) {
            /* Old data was dynamically allocated. Free it before
             * attaching new data.  */
            if(vPtr->freeProc == TCL_DYNAMIC) {
                ckfree((char *)vPtr->valueArr);
            } else {
                (*freeProc) ((char *)vPtr->valueArr);
            }
        }
        vPtr->freeProc = freeProc;
        vPtr->valueArr = valueArr;
        vPtr->size = size;
    }

    vPtr->length = length;
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * VectorNotifyClients --
 *
 *      Notifies each client of the vector that the vector has changed
 *      (updated or destroyed) by calling the provided function back.
 *      The function pointer may be NULL, in that case the client is
 *      not notified.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The results depend upon what actions the client callbacks
 *      take.
 *
 * ----------------------------------------------------------------------
 */
static void
VectorNotifyClients(
    ClientData clientData)
{
RbcVectorObject *vPtr = clientData;
RbcChainLink *linkPtr;
VectorClient *clientPtr;
RbcVectorNotify notify;

    notify = (vPtr->notifyFlags & NOTIFY_DESTROYED) ? RBC_VECTOR_NOTIFY_DESTROY
        : RBC_VECTOR_NOTIFY_UPDATE;
    vPtr->notifyFlags &= ~(NOTIFY_UPDATED | NOTIFY_DESTROYED | NOTIFY_PENDING);

    for(linkPtr = RbcChainFirstLink(vPtr->chainPtr); linkPtr != NULL;
        linkPtr = RbcChainNextLink(linkPtr)) {
        clientPtr = RbcChainGetValue(linkPtr);
        if(clientPtr->proc != NULL) {
            (*clientPtr->proc) (vPtr->interp, clientPtr->clientData, notify);
        }
    }
    /*
     * Some clients may not handle the "destroy" callback properly
     * (they should call Rbc_FreeVectorId to release the client
     * identifier), so mark any remaining clients to indicate that
     * vector's server has gone away.
     */
    if(notify == RBC_VECTOR_NOTIFY_DESTROY) {
        for(linkPtr = RbcChainFirstLink(vPtr->chainPtr); linkPtr != NULL;
            linkPtr = RbcChainNextLink(linkPtr)) {
            clientPtr = RbcChainGetValue(linkPtr);
            clientPtr->serverPtr = NULL;
        }
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcVectorNotifyPending --
 *
 *      Returns the name of the vector (and array variable).
 *
 * Results:
 *      The name of the array variable is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
RbcVectorNotifyPending(
    RbcVectorId clientId)
{              /* Client token identifying the vector */
VectorClient *clientPtr = (VectorClient *) clientId;

    if((clientPtr == NULL) || (clientPtr->magic != VECTOR_MAGIC)
        || (clientPtr->serverPtr == NULL)) {
        return 0;
    }
    return (clientPtr->serverPtr->notifyFlags & NOTIFY_PENDING);
}

/*
 * ----------------------------------------------------------------------
 *
 * VectorFlushCache --
 *
 *      Unsets all the elements of the Tcl array variable associated
 *      with the vector, freeing memory associated with the variable.
 *      This includes both the hash table and the hash keys.  The down
 *      side is that this effectively flushes the caching of vector
 *      elements in the array.  This means that the subsequent reads
 *      of the array will require a decimal to string conversion.
 *
 *      This is needed when the vector changes its values, making
 *      the array variable out-of-sync.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      All elements of array variable (except one) are unset, freeing
 *      the memory associated with the variable.
 *
 * ----------------------------------------------------------------------
 */
static void
VectorFlushCache(
    RbcVectorObject * vPtr)
{              /* The vector to flush */
Tcl_Interp *interp = vPtr->interp;

    if(vPtr->arrayName == NULL) {
        return; /* Doesn't use the variable API */
    }

    /* Turn off the trace temporarily so that we can unset all the
     * elements in the array.  */
    /* TODO I added a cast to Tcl_VarTraceProc * which might cause issues. */
    Tcl_UntraceVar2(interp, vPtr->arrayName, (char *)NULL,
        TRACE_ALL | vPtr->varFlags, (Tcl_VarTraceProc *) VectorVarTrace, vPtr);

    /* Clear all the element entries from the entire array */
    Tcl_UnsetVar2(interp, vPtr->arrayName, (char *)NULL, vPtr->varFlags);

    /* Restore the "end" index by default and the trace on the entire array */
    Tcl_SetVar2(interp, vPtr->arrayName, "end", "", vPtr->varFlags);
    /* TODO I added a cast to Tcl_VarTraceProc * which might cause issues. */
    Tcl_TraceVar2(interp, vPtr->arrayName, (char *)NULL,
        TRACE_ALL | vPtr->varFlags, (Tcl_VarTraceProc *) VectorVarTrace, vPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorChangeLength --
 *
 *      Resizes the vector to the new size.
 *
 *      The new size of the vector is computed by doubling the
 *      size of the vector until it fits the number of slots needed
 *      (designated by *length*).
 *
 *      If the new size is the same as the old, simply adjust the
 *      length of the vector.  Otherwise we're copying the data from
 *      one memory location to another. The trailing elements of the
 *      vector need to be reset to zero.
 *
 *      If the storage changed memory locations, free up the old
 *      location if it was dynamically allocated.
 *
 * Results:
 *      A standard Tcl result.  If the reallocation is successful,
 *      TCL_OK is returned, otherwise TCL_ERROR.
 *
 * Side effects:
 *      Memory for the array is reallocated.
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorChangeLength(
    RbcVectorObject * vPtr,    /* The vector to change lengths */
    int length)
{              /* The new size of the vector */
    int newSize;               /* Size of array in elements */
    double *newArr;
    Tcl_FreeProc *freeProc;

    newArr = NULL;
    newSize = 0;
    freeProc = TCL_STATIC;

    if(length > 0) {
    int wanted, used;

        wanted = length;
        used = vPtr->length;

        /* Compute the new size by doubling old size until it's big enough */
        newSize = DEF_ARRAY_SIZE;
        if(wanted > DEF_ARRAY_SIZE) {
            while(newSize < wanted) {
                newSize += newSize;
            }
        }
        freeProc = vPtr->freeProc;
        if(newSize == vPtr->size) {
            /* Same size, use current array. */
            newArr = vPtr->valueArr;
        } else {
            /* Dynamically allocate memory for the new array. */
            newArr = (double *)ckalloc(newSize * sizeof(double));
            if(newArr == NULL) {
                Tcl_SetObjResult(vPtr->interp,
                    Tcl_ObjPrintf
                    ("can't allocate %d elements for vector \"%s\"", newSize,
                        vPtr->name));
                return TCL_ERROR;
            }
            if(used > wanted) {
                used = wanted;
            }
            /* Copy any previous data */
            if(used > 0) {
                memcpy(newArr, vPtr->valueArr, used * sizeof(double));
            }
            freeProc = TCL_DYNAMIC;
        }
        /* Clear any new slots that we're now using in the array */
        if(wanted > used) {
            memset(newArr + used, 0, (wanted - used) * sizeof(double));
        }
    }
    if((newArr != vPtr->valueArr) && (vPtr->valueArr != NULL)) {
        /*
         * We're not using the old storage anymore, so free it if it's
         * not static.  It's static because the user previously reset
         * the vector with a statically allocated array (setting freeProc
         * to TCL_STATIC).
         */
        if(vPtr->freeProc != TCL_STATIC) {
            if(vPtr->freeProc == TCL_DYNAMIC) {
                ckfree((char *)vPtr->valueArr);
            } else {
                (*vPtr->freeProc) ((char *)vPtr->valueArr);
            }
        }
    }
    vPtr->valueArr = newArr;
    vPtr->size = newSize;
    vPtr->length = length;
    vPtr->first = 0;
    vPtr->last = length - 1;
    vPtr->freeProc = freeProc;  /* Set the type of the new storage */
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorLookupName --
 *
 *      Searches for the vector associated with the name given.  Allow
 *      for a range specification.
 *
 * Results:
 *      Returns a pointer to the vector if found, otherwise NULL.
 *      If the name is not associated with a vector and the
 *      TCL_LEAVE_ERR_MSG flag is set, and interp->result will contain
 *      an error message.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorLookupName(
    RbcVectorInterpData * dataPtr,      /* Interpreter-specific data. */
    const char *vecName,
    RbcVectorObject ** vPtrPtr)
{
    RbcVectorObject *vPtr;
    char *endPtr;

    vPtr =
        RbcVectorParseElement(dataPtr->interp, dataPtr, vecName, &endPtr,
        RBC_NS_SEARCH_BOTH);
    if(vPtr == NULL) {
        return TCL_ERROR;
    }
    if(*endPtr != '\0') {
        Tcl_AppendResult(dataPtr->interp, "extra characters after vector name",
            (char *)NULL);
        return TCL_ERROR;
    }
    *vPtrPtr = vPtr;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorUpdateRange --
 *
 *      TODO: Description
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
void
RbcVectorUpdateRange(
    RbcVectorObject * vPtr)
{
double min, max;
register int i;

    min = DBL_MAX, max = -DBL_MAX;
    for(i = 0; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            min = max = vPtr->valueArr[i];
            break;
        }
    }
    for( /* empty */ ; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            if(min > vPtr->valueArr[i]) {
                min = vPtr->valueArr[i];
            } else if(max < vPtr->valueArr[i]) {
                max = vPtr->valueArr[i];
            }
        }
    }
    vPtr->min = min;
    vPtr->max = max;
    vPtr->notifyFlags &= ~RBC_UPDATE_RANGE;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorGetIndex --
 *
 *      Converts the string representing an index in the vector to
 *      its numeric value.  A valid index may be an numeric string or
 *      the string "end" (indicating the last element in the string).
 *
 * Results:
 *      A standard Tcl result.  If the string is a valid index, TCL_OK
 *      is returned.  Otherwise TCL_ERROR is returned and interp->result
 *      will contain an error message.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorGetIndex(
    Tcl_Interp * interp,
    RbcVectorObject * vPtr,
    const char *string,
    int *indexPtr,             /* index to convert */
    int flags,
    Rbc_VectorIndexProc ** procPtrPtr)
{
    char c;
    int value;

    c = string[0];

    /* Treat the index "end" like a numeric index.  */

    if((c == 'e') && (strcmp(string, "end") == 0)) {
        if(vPtr->length < 1) {
            if(interp != NULL) {
                Tcl_AppendResult(interp, "bad index \"end\": vector is empty",
                    (char *)NULL);
            }
            return TCL_ERROR;
        }
        *indexPtr = vPtr->length - 1;
        return TCL_OK;
    } else if((c == '+') && (strcmp(string, "++end") == 0)) {
        *indexPtr = vPtr->length;
        return TCL_OK;
    }
    if(procPtrPtr != NULL) {
    Tcl_HashEntry *hPtr;

        hPtr = Tcl_FindHashEntry(&(vPtr->dataPtr->indexProcTable), string);
        if(hPtr != NULL) {
            *indexPtr = RBC_SPECIAL_INDEX;
            *procPtrPtr = (Rbc_VectorIndexProc *) Tcl_GetHashValue(hPtr);
            return TCL_OK;
        }
    }
    if(Tcl_GetInt(interp, (char *)string, &value) != TCL_OK) {
    long int lvalue;
        /*
         * Unlike Tcl_GetInt, Tcl_ExprLong needs a valid interpreter,
         * but the interp passed in may be NULL.  So we have to use
         * vPtr->interp and then reset the result.
         */
        if(Tcl_ExprLong(vPtr->interp, (char *)string, &lvalue) != TCL_OK) {
            Tcl_ResetResult(vPtr->interp);
            if(interp != NULL) {
                Tcl_AppendResult(interp, "bad index \"", string, "\"",
                    (char *)NULL);
            }
            return TCL_ERROR;
        }
        value = lvalue;
    }
    /*
     * Correct the index by the current value of the offset. This makes
     * all the numeric indices non-negative, which is how we distinguish
     * the special non-numeric indices.
     */
    value -= vPtr->offset;

    if((value < 0) || ((flags & RBC_INDEX_CHECK) && (value >= vPtr->length))) {
        if(interp != NULL) {
            Tcl_AppendResult(interp, "index \"", string, "\" is out of range",
                (char *)NULL);
        }
        return TCL_ERROR;
    }
    *indexPtr = (int)value;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorGetIndexRange --
 *
 *      Converts the string representing of an index in the vector to
 *      its numeric value.  A valid index may be an numeric string or
 *      the string "end" (indicating the last element in the string).
 *
 * Results:
 *      A standard Tcl result.  If the string is a valid index, TCL_OK
 *      is returned.  Otherwise TCL_ERROR is returned and interp->result
 *      will contain an error message.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
int
RbcVectorGetIndexRange(
    Tcl_Interp * interp,       /* The interpreter to return results to */
    RbcVectorObject * vPtr,    /* The vector object to get the range from */
    const char *string,        /* The index in the vector to convert */
    int flags,                 /* The flags for special cases */
    Rbc_VectorIndexProc ** procPtrPtr)
{              /* The index procedure */
    int ielem;
    char *colon;

    colon = NULL;
    if(flags & RBC_INDEX_COLON) {
        colon = strchr(string, ':');
    }
    if(colon != NULL) {
        /* there is a colon in the index specification */
        if(string == colon) {
            vPtr->first = 0;    /* Default to the first index */
        } else {
    int result;

            *colon = '\0';
            result =
                RbcVectorGetIndex(interp, vPtr, string, &ielem, flags,
                (Rbc_VectorIndexProc **) NULL);
            *colon = ':';
            if(result != TCL_OK) {
                return TCL_ERROR;
            }
            vPtr->first = ielem;
        }
        if(*(colon + 1) == '\0') {
            /* Default to the last index */
            vPtr->last = (vPtr->length > 0) ? vPtr->length - 1 : 0;
        } else {
            if(RbcVectorGetIndex(interp, vPtr, colon + 1, &ielem, flags,
                    (Rbc_VectorIndexProc **) NULL) != TCL_OK) {
                return TCL_ERROR;
            }
            vPtr->last = ielem;
        }
        if(vPtr->first > vPtr->last) {
            if(interp != NULL) {
                Tcl_AppendResult(interp, "bad range \"", string,
                    "\" (first > last)", (char *)NULL);
            }
            return TCL_ERROR;
        }
    } else {
        /* there is no colon in the index */
        if(RbcVectorGetIndex(interp, vPtr, string, &ielem, flags,
                procPtrPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        vPtr->last = vPtr->first = ielem;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorParseElement --
 *
 *      TODO: Description
 *
 * Results:
 *      A vector object
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
RbcVectorObject *
RbcVectorParseElement(
    Tcl_Interp * interp,
    RbcVectorInterpData * dataPtr,      /* Interpreter-specific data. */
    const char *start,         /* name of the vector */
    char **endPtr,             /* ? */
    int flags)
{              /* RBC_NS_SEARCH_CURRENT nd such ... */
register char *p;
char saved;
RbcVectorObject *vPtr;

    p = (char *)start;
    /* Find the end of the vector name */
    while(VECTOR_CHAR(*p)) {
        p++;
    }
    saved = *p;
    *p = '\0';

    vPtr = GetVectorObject(dataPtr, start, flags);
    if(vPtr == NULL) {
        if(interp != NULL) {
            Tcl_AppendResult(interp, "can't find vector \"", start, "\"",
                (char *)NULL);
        }
        *p = saved;
        return NULL;
    }
    *p = saved;
    vPtr->first = 0;
    vPtr->last = vPtr->length - 1;
    if(*p == '(') {
int count, result;

        start = p + 1;
        p++;

        /* Find the matching right parenthesis */
        count = 1;
        while(*p != '\0') {
            if(*p == ')') {
                count--;
                if(count == 0) {
                    break;
                }
            } else if(*p == '(') {
                count++;
            }
            p++;
        }
        if(count > 0) {
            if(interp != NULL) {
                Tcl_AppendResult(interp, "unbalanced parentheses \"", start,
                    "\"", (char *)NULL);
            }
            return NULL;
        }
        *p = '\0';
        result =
            RbcVectorGetIndexRange(interp, vPtr, start,
            (RBC_INDEX_COLON | RBC_INDEX_CHECK), (Rbc_VectorIndexProc **) NULL);
        *p = ')';
        if(result != TCL_OK) {
            return NULL;
        }
        p++;
    }
    if(endPtr != NULL) {
        *endPtr = p;
    }
    return vPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcVectorUpdateClients --
 *
 *      Notifies each client of the vector that the vector has changed
 *      (updated or destroyed) by calling the provided function back.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      The individual client callbacks are eventually invoked.
 *
 * ----------------------------------------------------------------------
 */
void
RbcVectorUpdateClients(
    RbcVectorObject * vPtr)
{              /* The vector to update clients for */
    vPtr->max = vPtr->min = rbcNaN;
    if(vPtr->notifyFlags & NOTIFY_NEVER) {
        return;
    }
    vPtr->notifyFlags |= NOTIFY_UPDATED;
    if(vPtr->notifyFlags & NOTIFY_ALWAYS) {
        VectorNotifyClients(vPtr);
        return;
    }
    if(!(vPtr->notifyFlags & NOTIFY_PENDING)) {
        vPtr->notifyFlags |= NOTIFY_PENDING;
        Tcl_DoWhenIdle(VectorNotifyClients, vPtr);
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * VectorVarTrace --
 *
 *      Procedure invoked when a vector variable is read, written or unset
 *
 * Results:
 *      Returns NULL on success.  Returns an error message on failure.
 *      Only called from a variable trace.
 *
 * Side effects:
 *       may be several, like deleting a vector, etc.
 *
 * ----------------------------------------------------------------------
 */
static const char *
VectorVarTrace(
    ClientData clientData,     /* Vector object. */
    Tcl_Interp * interp,       /* Interpreter of the vector */
    const char *part1,         /* name of array variable accessed */
    const char *part2,         /* name of array element accessed */
    int flags)
{
    Rbc_VectorIndexProc *indexProc;
    RbcVectorObject *vPtr = clientData;
    int first, last;
    int varFlags;

    static char message[MAX_ERR_MSG + 1];

    if(part2 == NULL) {
        if(flags & TCL_TRACE_UNSETS) {
            /* vector is deleted via an unset on the whole array variable */
            ckfree((char *)vPtr->arrayName);
            vPtr->arrayName = NULL;
            if(vPtr->freeOnUnset) {
                Rbc_VectorFree(vPtr);
            }
        }
        return NULL;
    }
    if(RbcVectorGetIndexRange(interp, vPtr, part2, RBC_INDEX_ALL_FLAGS,
            &indexProc) != TCL_OK) {
        goto error;
    }
    first = vPtr->first;
    last = vPtr->last;
    varFlags = TCL_LEAVE_ERR_MSG | (TCL_GLOBAL_ONLY & flags);
    if(flags & TCL_TRACE_WRITES) {
    double value;
    Tcl_Obj *objPtr;

        if(first == RBC_SPECIAL_INDEX) {
            /* Tried to set "min" or "max" */
            return "read-only index";
        }
        objPtr = Tcl_GetVar2Ex(interp, part1, part2, varFlags);
        if(objPtr == NULL) {
            goto error;
        }
        if(RbcGetDouble(interp, objPtr, &value) != TCL_OK) {
            if((last == first) && (first >= 0)) {
                /* Single numeric index. Reset the array element to
                 * its old value on errors */
                Tcl_SetVar2Ex(interp, part1, part2, objPtr, varFlags);
            }
            goto error;
        }
        if(first == vPtr->length) {
            if(RbcVectorChangeLength(vPtr, vPtr->length + 1) != TCL_OK) {
                return "error resizing vector";
            }
        }
        /* Set possibly an entire range of values */
        RbcReplicateValue(vPtr, first, last, value);
    } else if(flags & TCL_TRACE_READS) {
    double value;
    Tcl_Obj *objPtr;

        if(vPtr->length == 0) {
            if(Tcl_SetVar2(interp, part1, part2, "", varFlags) == NULL) {
                goto error;
            }
            return NULL;
        }
        if(first == vPtr->length) {
            return "write-only index";
        }
        if(first == last) {
            if(first >= 0) {
                value = vPtr->valueArr[first];
            } else {
                vPtr->first = 0, vPtr->last = vPtr->length - 1;
                value = (*indexProc) ((Rbc_Vector *) vPtr);
            }
            objPtr = Tcl_NewDoubleObj(value);
            if(Tcl_SetVar2Ex(interp, part1, part2, objPtr, varFlags) == NULL) {
                Tcl_DecrRefCount(objPtr);
                goto error;
            }
        } else {
            objPtr = RbcGetValues(vPtr, first, last);
            if(Tcl_SetVar2Ex(interp, part1, part2, objPtr, varFlags) == NULL) {
                Tcl_DecrRefCount(objPtr);
                goto error;
            }
        }
    } else if(flags & TCL_TRACE_UNSETS) {
    register int i, j;

        if((first == vPtr->length) || (first == RBC_SPECIAL_INDEX)) {
            return "special vector index";
        }
        /*
         * Collapse the vector from the point of the first unset element.
         * Also flush any array variable entries so that the shift is
         * reflected when the array variable is read.
         */
        for(i = first, j = last + 1; j < vPtr->length; i++, j++) {
            vPtr->valueArr[i] = vPtr->valueArr[j];
        }
        vPtr->length -= ((last - first) + 1);
        if(vPtr->flush) {
            VectorFlushCache(vPtr);
        }
    } else {
        return "unknown variable trace flag";
    }
    if(flags & (TCL_TRACE_UNSETS | TCL_TRACE_WRITES)) {
        RbcVectorUpdateClients(vPtr);
    }
    Tcl_ResetResult(interp);
    return NULL;

  error:
    strncpy(message, Tcl_GetStringResult(interp), MAX_ERR_MSG);
    message[MAX_ERR_MSG] = '\0';
    return message;
}

/*
 * ----------------------------------------------------------------------
 *
 * BuildQualifiedName --
 *
 *      Builds a fully qualified name from a given name depending on the current namespace
 *
 *        - lookup current namespace
 *        - if name starts with :: -> do nothing
 *        - if name does not start with :: -> set name relative to current namespace
 *
 *      (used in VectorCreate)
 *
 * Results:
 *      Returns the qualified name
 *
 * Side effects:
 *      fullName is filled with the qualified name
 *
 * ----------------------------------------------------------------------
 */
static const char *
BuildQualifiedName(
    Tcl_Interp * interp,       /* the interpreter in which to lookup the variable or command */
    const char *name,          /* the name of a variable, or command to build the qualified name for */
    Tcl_DString * fullName)
{              /* string pointer to save the qualified name into
                * (free or uninitialized DString) */
    Tcl_Namespace *nsPtr;

    if(name == NULL) {
        return NULL;
    }

    Tcl_DStringInit(fullName);
    /* FIXME: Doesn't work in Tcl 8.4 */
    nsPtr = Tcl_GetCurrentNamespace(interp);

    if((name[0] == ':') && (name[1] == ':')) {
        /* we have a fully qualified name already -> just return the given name */
        Tcl_DStringAppend(fullName, name, -1);
        return Tcl_DStringValue(fullName);
    }

    /* build a qualified name */
    Tcl_DStringAppend(fullName, nsPtr->fullName, -1);
    if(Tcl_DStringLength(fullName) > 2) {
        /* namespace is not the root namespace, so we need a separator */
        Tcl_DStringAppend(fullName, "::", -1);
    }
    Tcl_DStringAppend(fullName, name, -1);
    return Tcl_DStringValue(fullName);
}

/*
 * ----------------------------------------------------------------------
 *
 * ParseQualifiedName --
 *
 *      Parses a possibly namespaced (variable) name
 *      and checkes whether the corresponding namespace
 *      exists or not. Splits the name into its components
 *      as the namespace part and the name itself
 *
 *      This function is the counterpart of GetQualifiedName
 *
 * Results:
 *      A standard Tcl result. Returns TCL_ERROR if the namespace does
 *      not exist yet, else returns TCL_OK
 *
 * Side effects:
 *      If TCL_OK is returned, the nsPtr contains the namespace
 *      and namePtr contains the name of the vector in that namespace
 *
 * ----------------------------------------------------------------------
 */
static int
ParseQualifiedName(
    Tcl_Interp * interp,       /* the interpreter, where the name is found in */
    const char *qualName,      /* the qualified name to parse */
    Tcl_Namespace ** nsPtrPtr, /* pointer to store the namespace part into */
    const char **namePtrPtr)
{              /* pointer to store the name itself into */
    register char *p, *colon;
    Tcl_Namespace *nsPtr;

    colon = NULL;
    p = (char *)(qualName + strlen(qualName));
    while(--p > qualName) {
        if((*p == ':') && (*(p - 1) == ':')) {
            p++;        /* just after the last "::" */
            colon = p - 2;
            break;
        }
    }
    if(colon == NULL) {
        *nsPtrPtr = NULL;
        *namePtrPtr = (char *)qualName;
        return TCL_OK;
    }
    *colon = '\0';
    if(qualName[0] == '\0') {
        nsPtr = Tcl_GetGlobalNamespace(interp);
    } else {
        nsPtr = Tcl_FindNamespace(interp, (char *)qualName,
            (Tcl_Namespace *) NULL, 0);
    }
    *colon = ':';
    if(nsPtr == NULL) {
        return TCL_ERROR;
    }
    *nsPtrPtr = nsPtr;
    *namePtrPtr = p;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * GetQualifiedName --
 *
 *      Builds a namespaced variable name
 *      from a namespace and a variable name specification
 *
 *      This function is the counterpart of ParseQualifiedName
 *
 * Results:
 *      A namespaced Tcl name
 *
 * Side effects:
 *      fills the supplied DString with the qualified name
 *
 * ----------------------------------------------------------------------
 */
static const char *
GetQualifiedName(
    Tcl_Namespace * nsPtr,
    const char *name,
    Tcl_DString * resultPtr)
{
    Tcl_DStringInit(resultPtr);
    if((nsPtr->fullName[0] != ':') || (nsPtr->fullName[1] != ':')
        || (nsPtr->fullName[2] != '\0')) {
        Tcl_DStringAppend(resultPtr, nsPtr->fullName, -1);
    }
    Tcl_DStringAppend(resultPtr, "::", -1);
    Tcl_DStringAppend(resultPtr, (char *)name, -1);
    return Tcl_DStringValue(resultPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * GetVectorObject --
 *
 *      Searches for the vector associated with the name given.
 *      Allow for a range specification.
 *
 * Results:
 *      Returns a pointer to the vector if found, otherwise NULL.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static RbcVectorObject *
GetVectorObject(
    RbcVectorInterpData * dataPtr,      /* Interpreter-specific data. */
    const char *name,
    int flags)
{
    const char *vecName;
    Tcl_Namespace *nsPtr;
    RbcVectorObject *vPtr;

    nsPtr = NULL;
    vecName = name;
    if(ParseQualifiedName(dataPtr->interp, name, &nsPtr, &vecName) != TCL_OK) {
        return NULL;    /* Can't find namespace. */
    }
    vPtr = NULL;
    if(nsPtr != NULL) {
        vPtr = FindVectorInNamespace(dataPtr, nsPtr, vecName);
    } else {
        if(flags & RBC_NS_SEARCH_CURRENT) {
            nsPtr = Tcl_GetCurrentNamespace(dataPtr->interp);
            vPtr = FindVectorInNamespace(dataPtr, nsPtr, vecName);
        }
        if((vPtr == NULL) && (flags & RBC_NS_SEARCH_GLOBAL)) {
            nsPtr = Tcl_GetGlobalNamespace(dataPtr->interp);
            vPtr = FindVectorInNamespace(dataPtr, nsPtr, vecName);
        }
    }
    return vPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * FindVectorInNamespace --
 *
 *      Retrieves the vector indicated when it is located in
 *      a certain namespace.
 *
 * Results:
 *      Returns a pointer to the vector if found, otherwise NULL.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static RbcVectorObject *
FindVectorInNamespace(
    RbcVectorInterpData * dataPtr,      /* Interpreter-specific data. */
    Tcl_Namespace * nsPtr,     /* Namespace pointer */
    const char *vecName)
{              /* Name of the vector to find */
    Tcl_DString dString;
    const char *name;
    Tcl_HashEntry *hPtr;

    name = GetQualifiedName(nsPtr, vecName, &dString);
    hPtr = Tcl_FindHashEntry(&(dataPtr->vectorTable), name);
    Tcl_DStringFree(&dString);
    if(hPtr != NULL) {
        return (RbcVectorObject *) Tcl_GetHashValue(hPtr);
    }
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcGetValues --
 *
 *      Return a list containing the values of the vector
 *
 * Results:
 *      Returns a Tcl_Obj pointer to a list of doubles
 *      representing the values of the vector.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
Tcl_Obj *
RbcGetValues(
    RbcVectorObject * vPtr,
    int first,
    int last)
{
register int i;
Tcl_Obj *listObjPtr;

    listObjPtr = Tcl_NewListObj(0, NULL);
    for(i = first; i <= last; i++) {
        Tcl_ListObjAppendElement(vPtr->interp, listObjPtr,
            Tcl_NewDoubleObj(vPtr->valueArr[i]));
    }
    return listObjPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcReplicateValue --
 *
 *      Sets the value into the array from the first to last index.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *       Sets new value for vector from first to last.
 *
 * ----------------------------------------------------------------------
 */
void
RbcReplicateValue(
    RbcVectorObject * vPtr,    /* The vector to replicate values on */
    int first,                 /* The start index to replicate into */
    int last,                  /* The end index to replicate into */
    double value)
{              /* The value to replicate */
    register int i;

    for(i = first; i <= last; i++) {
        vPtr->valueArr[i] = value;
    }
    vPtr->notifyFlags |= RBC_UPDATE_RANGE;
}

/*
 * ----------------------------------------------------------------------
 *
 * DeleteCommand --
 *
 *      Deletes the Tcl command associated with the vector, without
 *      triggering a callback to "VectorInstDeleteProc".
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 * ----------------------------------------------------------------------
 */
static void
DeleteCommand(
    RbcVectorObject * vPtr)
{              /* Vector associated with the Tcl command. */
Tcl_Interp *interp = vPtr->interp;
Tcl_CmdInfo cmdInfo;
const char *cmdName;

    cmdName = Tcl_GetCommandName(interp, vPtr->cmdToken);

    if(Tcl_GetCommandInfo(interp, cmdName, &cmdInfo)) {
        /* Disable the callback before deleting the Tcl command. */
        cmdInfo.deleteProc = NULL;
        Tcl_SetCommandInfo(interp, cmdName, &cmdInfo);
        Tcl_DeleteCommand(interp, cmdName);
    }
    vPtr->cmdToken = 0;
}

/*
 * ----------------------------------------------------------------------
 *
 * UnmapVariable --
 *
 *      Destroys the trace on the current Tcl variable designated
 *      to access the vector.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static void
UnmapVariable(
    RbcVectorObject * vPtr)
{              /* Vector to unmap */
Tcl_Interp *interp = vPtr->interp;

    if(vPtr->arrayName == NULL) {
        return;
    }

    /* Unset the entire array */
    Tcl_UntraceVar2(interp, vPtr->arrayName, NULL,
        (TRACE_ALL | vPtr->varFlags), (Tcl_VarTraceProc *) VectorVarTrace,
        vPtr);
    Tcl_UnsetVar2(interp, vPtr->arrayName, (char *)NULL, vPtr->varFlags);

    /* free the space */
    ckfree((char *)vPtr->arrayName);
    vPtr->arrayName = NULL;
}

/*
 * ----------------------------------------------------------------------
 *
 * RbcGetDouble --
 *
 *      Returns a double from the Tcl_Obj provided.
 *
 * Results:
 *      Success of failure and the value object.
 *
 * Side effects:
 *       None.
 *
 * ----------------------------------------------------------------------
 */

int
RbcGetDouble(
    Tcl_Interp * interp,       /* Tcl Interp to use for extracting. */
    Tcl_Obj * objPtr,          /* The object holding the double value */
    double *valuePtr)
{              /* Return value for the double */
    /* First try to extract the value as a double precision number. */
    if(Tcl_GetDoubleFromObj(interp, objPtr, valuePtr) == TCL_OK) {
        return TCL_OK;
    }
    Tcl_ResetResult(interp);

    /* Then try to parse it as an expression. */
    if(Tcl_ExprDouble(interp, Tcl_GetString(objPtr), valuePtr) == TCL_OK) {
        return TCL_OK;
    }
    return TCL_ERROR;
}

/*
 *--------------------------------------------------------------
 *
 * Rbc_FreeVectorId --
 *
 *      Releases the token for an existing vector.  This
 *      indicates that the client is no longer interested
 *      the vector.  Any previously specified callback
 *      routine will no longer be invoked when (and if) the
 *      vector changes.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      Any previously specified callback routine will no
 *      longer be invoked when (and if) the vector changes.
 *
 *--------------------------------------------------------------
 */
void
Rbc_FreeVectorId(
    RbcVectorId clientId)
{              /* Client token identifying the vector */
VectorClient *clientPtr = (VectorClient *) clientId;

    if(clientPtr->magic != VECTOR_MAGIC) {
        return; /* Not a valid token */
    }
    if(clientPtr->serverPtr != NULL) {
        /* Remove the client from the server's list */
        RbcChainDeleteLink(clientPtr->serverPtr->chainPtr, clientPtr->linkPtr);
    }
    ckfree((char *)clientPtr);
}

/*
 * -----------------------------------------------------------------------
 *
 * Rbc_GetVectorById --
 *
 *      Returns a pointer to the vector associated with the client
 *      token.
 *
 * Results:
 *      A standard Tcl result.  If the client token is not associated
 *      with a vector any longer, TCL_ERROR is returned. Otherwise,
 *      TCL_OK is returned and vecPtrPtr will point to vector.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
Rbc_GetVectorById(
    Tcl_Interp * interp,
    RbcVectorId clientId,      /* Client token identifying the vector */
    Rbc_Vector ** vecPtrPtr)
{
VectorClient *clientPtr = (VectorClient *) clientId;

    if(clientPtr->magic != VECTOR_MAGIC) {
        Tcl_AppendResult(interp, "bad vector token", (char *)NULL);
        return TCL_ERROR;
    }
    if(clientPtr->serverPtr == NULL) {
        Tcl_AppendResult(interp, "vector no longer exists", (char *)NULL);
        return TCL_ERROR;
    }
    RbcVectorUpdateRange(clientPtr->serverPtr);
    *vecPtrPtr = (Rbc_Vector *) clientPtr->serverPtr;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * Rbc_VectorExists --
 *
 *      Returns whether the vector associated with the client token
 *      still exists.
 *
 * Results:
 *      Returns 1 is the vector still exists, 0 otherwise.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
int
Rbc_VectorExists(
    Tcl_Interp * interp,
    const char *vecName)
{
    RbcVectorInterpData *dataPtr;       /* Interpreter-specific data. */

    dataPtr = RbcVectorGetInterpData(interp);
    if(GetVectorObject(dataPtr, vecName, RBC_NS_SEARCH_BOTH) != NULL) {
        return TRUE;
    }
    return FALSE;
}

/*
 *--------------------------------------------------------------
 *
 * RbcAllocVectorId --
 *
 *      Creates an identifier token for an existing vector.
 *      The identifier is used by the client routines to get
 *      call backs when (and if) the vector changes.
 *
 * Results:
 *      A standard Tcl result.  If "vecName" is not associated
 *      with a vector, TCL_ERROR is returned and interp->result
 *      is filled with an error message.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
RbcVectorId
RbcAllocVectorId(
    Tcl_Interp * interp,
    const char *name)
{
RbcVectorInterpData *dataPtr;  /* Interpreter-specific data. */
RbcVectorObject *vPtr;
VectorClient *clientPtr;
RbcVectorId clientId;
int result;
char *nameCopy;

    dataPtr = RbcVectorGetInterpData(interp);
    /*
     * If the vector name was passed via a read-only string (e.g. "x"),
     * the VectorParseName routine will segfault when it tries to write
     * into the string.  Therefore make a writable copy and free it
     * when we're done.
     */
    nameCopy = RbcStrdup(name);
    result = RbcVectorLookupName(dataPtr, nameCopy, &vPtr);
    ckfree((char *)nameCopy);

    if(result != TCL_OK) {
        return (RbcVectorId) 0;
    }
    /* Allocate a new client structure */
    clientPtr = RbcCalloc(1, sizeof(VectorClient));
    assert(clientPtr);
    clientPtr->magic = VECTOR_MAGIC;

    /* Add the new client to the server's list of clients */
    clientPtr->linkPtr = RbcChainAppend(vPtr->chainPtr, clientPtr);
    clientPtr->serverPtr = vPtr;
    clientId = (RbcVectorId) clientPtr;
    return clientId;
}

/*
 * -----------------------------------------------------------------------
 *
 * Rbc_SetVectorChangedProc --
 *
 *      Sets the routine to be called back when the vector is changed
 *      or deleted.  *clientData* will be provided as an argument. If
 *      *proc* is NULL, no callback will be made.
 *
 * Results:
 *      None.
 *
 * Side Effects:
 *      The designated routine will be called when the vector is changed
 *      or deleted.
 *
 * -----------------------------------------------------------------------
 */
void
Rbc_SetVectorChangedProc(
    RbcVectorId clientId,      /* Client token identifying the vector */
    RbcVectorChangedProc * proc,        /* Address of routine to call when the contents
                                         * of the vector change. If NULL, no routine
                                         * will be called */
    ClientData clientData)
{              /* One word of information to pass along when
                * the above routine is called */
VectorClient *clientPtr = (VectorClient *) clientId;

    if(clientPtr->magic != VECTOR_MAGIC) {
        return; /* Not a valid token */
    }
    clientPtr->clientData = clientData;
    clientPtr->proc = proc;
}

/*
 *--------------------------------------------------------------
 *
 * Rbc_NameOfVectorId --
 *
 *      Returns the name of the vector (and array variable).
 *
 * Results:
 *      The name of the array variable is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
char *
Rbc_NameOfVectorId(
    RbcVectorId clientId)
{              /* Client token identifying the vector */
VectorClient *clientPtr = (VectorClient *) clientId;

    if((clientPtr->magic != VECTOR_MAGIC) || (clientPtr->serverPtr == NULL)) {
        return NULL;
    }
    return clientPtr->serverPtr->name;
}

/*
 * -----------------------------------------------------------------------
 *
 * Rbc_GetVector --
 *
 *      Returns a pointer to the vector associated with the given name.
 *
 * Results:
 *      A standard Tcl result.  If there is no vector "name", TCL_ERROR
 *      is returned.  Otherwise TCL_OK is returned and vecPtrPtr will
 *      point to the vector.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
Rbc_GetVector(
    Tcl_Interp * interp,
    const char *name,
    Rbc_Vector ** vecPtrPtr)
{
    RbcVectorInterpData *dataPtr;       /* Interpreter-specific data. */
    RbcVectorObject *vPtr;
    char *nameCopy;
    int result;

    dataPtr = RbcVectorGetInterpData(interp);
    /*
     * If the vector name was passed via a read-only string (e.g. "x"),
     * the VectorParseName routine will segfault when it tries to write
     * into the string.  Therefore make a writable copy and free it
     * when we're done.
     */
    nameCopy = RbcStrdup(name);
    result = RbcVectorLookupName(dataPtr, nameCopy, &vPtr);
    ckfree((char *)nameCopy);
    if(result != TCL_OK) {
        return TCL_ERROR;
    }
    RbcVectorUpdateRange(vPtr);
    *vecPtrPtr = (Rbc_Vector *) vPtr;
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcCreateVector --
 *
 *      Creates a new vector by the name and size.
 *
 * Results:
 *      A standard Tcl result.  If the new array size is invalid or a
 *      vector already exists by that name, TCL_ERROR is returned.
 *      Otherwise TCL_OK is returned and the new vector is created.
 *
 * Side Effects:
 *      Memory will be allocated for the new vector.  A new Tcl command
 *      and Tcl array variable will be created.
 *
 * -----------------------------------------------------------------------
 */
int
RbcCreateVector2(
    Tcl_Interp * interp,
    const char *vecName,
    const char *cmdName,
    const char *varName,
    int initialSize,
    Rbc_Vector ** vecPtrPtr)
{
    RbcVectorInterpData *dataPtr;       /* Interpreter-specific data. */
    RbcVectorObject *vPtr;
    int isNew;
    char *nameCopy;

    if(initialSize < 0) {
        Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
            "bad vector size \"%d\"", initialSize);
        return TCL_ERROR;
    }
    dataPtr = RbcVectorGetInterpData(interp);

    nameCopy = RbcStrdup(vecName);
    vPtr = RbcVectorCreate(dataPtr, nameCopy, cmdName, varName, &isNew);
    ckfree((char *)nameCopy);

    if(vPtr == NULL) {
        return TCL_ERROR;
    }
    if(initialSize > 0) {
        if(RbcVectorChangeLength(vPtr, initialSize) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if(vecPtrPtr != NULL) {
        *vecPtrPtr = (Rbc_Vector *) vPtr;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * Rbc_CreateVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int
Rbc_CreateVector(
    Tcl_Interp * interp,
    const char *name,
    int size,
    Rbc_Vector ** vecPtrPtr)
{
    return RbcCreateVector2(interp, name, name, name, size, vecPtrPtr);
}

/*
 * -----------------------------------------------------------------------
 *
 * Rbc_ResizeVector --
 *
 *      Changes the size of the vector.  All clients with designated
 *      callback routines will be notified of the size change.
 *
 * Results:
 *      A standard Tcl result.  If no vector exists by that name,
 *      TCL_ERROR is returned.  Otherwise TCL_OK is returned and
 *      vector is resized.
 *
 * Side Effects:
 *      Memory may be reallocated for the new vector size.  All clients
 *      which set call back procedures will be notified.
 *
 * -----------------------------------------------------------------------
 */
int
Rbc_ResizeVector(
    Rbc_Vector * vecPtr,
    int length)
{
    RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;

    if(RbcVectorChangeLength(vPtr, length) != TCL_OK) {
        Tcl_AppendResult(vPtr->interp, "can't resize vector \"", vPtr->name,
            "\"", (char *)NULL);
        return TCL_ERROR;
    }
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcNameOfVector --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
char *
RbcNameOfVector(
    Rbc_Vector * vecPtr)
{              /* Vector to query. */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
    return vPtr->name;
}

/*
 * -----------------------------------------------------------------------
 *
 * Rbc_ResetVector --
 *
 *      Resets the vector data.  This is called by a client to
 *      indicate that the vector data has changed.  The vector does
 *      not need to point to different memory.  Any clients of the
 *      vector will be notified of the change.
 *
 * Results:
 *      A standard Tcl result.  If the new array size is invalid,
 *      TCL_ERROR is returned.  Otherwise TCL_OK is returned and the
 *      new vector data is recorded.
 *
 * Side Effects:
 *      Any client designated callbacks will be posted.  Memory may
 *      be changed for the vector array.
 *
 * -----------------------------------------------------------------------
 */
int
Rbc_ResetVector(
    Rbc_Vector * vecPtr,
    double *valueArr,          /* Array containing the elements of the
                                * vector. If NULL, indicates to reset the
                                * vector.*/
    int length,                /* The number of elements that the vector
                                * currently holds. */
    int size,                  /* The maximum number of elements that the
                                * array can hold. */
    Tcl_FreeProc * freeProc)
{              /* Address of memory deallocation routine
                * for the array of values.  Can also be
                * TCL_STATIC, TCL_DYNAMIC, or TCL_VOLATILE. */
    RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;

    if(size < 0) {
        Tcl_AppendResult(vPtr->interp, "bad array size", (char *)NULL);
        return TCL_ERROR;
    }
    return RbcVectorReset(vPtr, valueArr, length, size, freeProc);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoVectorMath.c.














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * rbcVecMath.c --
 *
 *      Collections of procedures and structures to perform
 *      math functions on vector objects.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */
#include "tkoGraph.h"

typedef int (
    GenericMathProc) (
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr);                                                                      /*** how to get rid of this here? */

/*
 * Token --
 *
 *	The token types are defined below.  In addition, there is a
 *	table associating a precedence with each operator.  The order
 *	of types is important.  Consult the code before changing it.
 */
typedef enum {
    VALUE,
    OPEN_PAREN,
    CLOSE_PAREN,
    COMMA,
    END,
    UNKNOWN,
    MULT = 8,
    DIVIDE,
    MOD,
    PLUS,
    MINUS,
    LEFT_SHIFT,
    RIGHT_SHIFT,
    LESS,
    GREATER,
    LEQ,
    GEQ,
    EQUAL,
    NEQ,
    OLD_BIT_AND,
    EXPONENT,
    OLD_BIT_OR,
    OLD_QUESTY,
    OLD_COLON,
    AND,
    OR,
    UNARY_MINUS,
    OLD_UNARY_PLUS,
    NOT,
    OLD_BIT_NOT
} Token;

/*
 *	Contains information about math functions that can be called
 *	for vectors.  The table of math functions is global within the
 *	application.  So you can't define two different "sqrt"
 *	functions.
 */
typedef struct {
    const char *name;          /* Name of built-in math function.  If
                                * NULL, indicates that the function
                                * was user-defined and dynamically
                                * allocated.  Function names are
                                * global across all interpreters. */
    GenericMathProc *proc;     /* Procedure that implements this math
                                * function. */
    ClientData clientData;     /* Argument to pass when invoking the
                                * function. */
} MathFunction;
/*
 *	The data structure below describes the state of parsing an
 *	expression.  It's passed among the routines in this module.
 */
typedef struct {
    char *expr;                /* The entire right-hand side of the
                                * expression, as originally passed to
                                * RbcExprVector. */
    char *nextPtr;             /* Position of the next character to
                                * be scanned from the expression
                                * string. */
    Token token;               /* Type of the last token to be parsed
                                * from nextPtr.  See below for
                                * definitions.  Corresponds to the
                                * characters just before nextPtr. */
} ParseInfo;
#ifdef DBL_MAX
#   define IS_INF(v) (((v) > DBL_MAX) || ((v) < -DBL_MAX))
#else
#   define IS_INF(v) 0
#endif
static int precTable[] = {
    0, 0, 0, 0, 0, 0, 0, 0,
    12, 12, 12, /* MULT, DIVIDE, MOD */
    11, 11,    /* PLUS, MINUS */
    10, 10,    /* LEFT_SHIFT, RIGHT_SHIFT */
    9, 9, 9, 9, /* LESS, GREATER, LEQ, GEQ */
    8, 8,      /* EQUAL, NEQ */
    7,         /* OLD_BIT_AND */
    13,        /* EXPONENTIATION */
    5,         /* OLD_BIT_OR */
    4,         /* AND */
    3,         /* OR */
    2,         /* OLD_QUESTY */
    1,         /* OLD_COLON */
    14, 14, 14, 14      /* UNARY_MINUS, OLD_UNARY_PLUS, NOT, OLD_BIT_NOT */
};

typedef double (
    ComponentProc) (
    double value);
typedef int (
    VectorProc) (
    RbcVectorObject * vPtr);
typedef double (
    ScalarProc) (
    RbcVectorObject * vPtr);

static void InstallIndexProc(
    Tcl_HashTable * tablePtr,
    const char *string,
    Rbc_VectorIndexProc * procPtr);
static int First(
    RbcVectorObject * vPtr);
static int Next(
    RbcVectorObject * vPtr,
    int current);
static double Mean(
    Rbc_Vector * vecPtr);
static double Sum(
    Rbc_Vector * vecPtr);
static double Product(
    Rbc_Vector * vecPtr);
static double Fabs(
    double value);
static double AvgDeviation(
    Rbc_Vector * vecPtr);
static double Kurtosis(
    Rbc_Vector * vecPtr);
static double Length(
    Rbc_Vector * vecPtr);
static double Median(
    Rbc_Vector * vecPtr);
static int Norm(
    Rbc_Vector * vecPtr);
static double Nonzeros(
    Rbc_Vector * vecPtr);
static double Q1(
    Rbc_Vector * vecPtr);
static double Q3(
    Rbc_Vector * vecPtr);
static double Round(
    double value);
static double StdDeviation(
    Rbc_Vector * vecPtr);
static double Skew(
    Rbc_Vector * vecPtr);
static int Sort(
    RbcVectorObject * vPtr);
static double Sum(
    Rbc_Vector * vecPtr);
static double Variance(
    Rbc_Vector * vecPtr);
static int EvaluateExpression(
    Tcl_Interp * interp,
    char *string,
    RbcParseVector * valuePtr);
static int NextValue(
    Tcl_Interp * interp,
    ParseInfo * parsePtr,
    int prec,
    RbcParseVector * valuePtr);
static void MathError(
    Tcl_Interp * interp,
    double value);
static int NextToken(
    Tcl_Interp * interp,
    ParseInfo * parsePtr,
    RbcParseVector * valuePtr);
static double Fmod(
    double x,
    double y);
static int ParseString(
    Tcl_Interp * interp,
    const char *string,
    RbcParseVector * valuePtr);
static int ParseMathFunction(
    Tcl_Interp * interp,
    char *start,
    ParseInfo * parsePtr,
    RbcParseVector * valuePtr);
static int ComponentFunc(
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr);
static int ScalarFunc(
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr);
static int VectorFunc(
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr);
static MathFunction mathFunctions[] = {
    {"abs", (GenericMathProc *) ComponentFunc, (ClientData) Fabs},
    {"acos", (GenericMathProc *) ComponentFunc, (ClientData) acos},
    {"asin", (GenericMathProc *) ComponentFunc, (ClientData) asin},
    {"atan", (GenericMathProc *) ComponentFunc, (ClientData) atan},
    {"adev", (GenericMathProc *) ScalarFunc, (ClientData) AvgDeviation},
    {"ceil", (GenericMathProc *) ComponentFunc, (ClientData) ceil},
    {"cos", (GenericMathProc *) ComponentFunc, (ClientData) cos},
    {"cosh", (GenericMathProc *) ComponentFunc, (ClientData) cosh},
    {"exp", (GenericMathProc *) ComponentFunc, (ClientData) exp},
    {"floor", (GenericMathProc *) ComponentFunc, (ClientData) floor},
    {"kurtosis", (GenericMathProc *) ScalarFunc, (ClientData) Kurtosis},
    {"length", (GenericMathProc *) ScalarFunc, (ClientData) Length},
    {"log", (GenericMathProc *) ComponentFunc, (ClientData) log},
    {"log10", (GenericMathProc *) ComponentFunc, (ClientData) log10},
    {"max", (GenericMathProc *) ScalarFunc, (ClientData) RbcVecMax},
    {"mean", (GenericMathProc *) ScalarFunc, (ClientData) Mean},
    {"median", (GenericMathProc *) ScalarFunc, (ClientData) Median},
    {"min", (GenericMathProc *) ScalarFunc, (ClientData) RbcVecMin},
    {"norm", (GenericMathProc *) VectorFunc, (ClientData) Norm},
    {"nz", (GenericMathProc *) ScalarFunc, (ClientData) Nonzeros},
    {"q1", (GenericMathProc *) ScalarFunc, (ClientData) Q1},
    {"q3", (GenericMathProc *) ScalarFunc, (ClientData) Q3},
    {"prod", (GenericMathProc *) ScalarFunc, (ClientData) Product},
    {"random", (GenericMathProc *) ComponentFunc, (ClientData) Rbcdrand48},
    {"round", (GenericMathProc *) ComponentFunc, (ClientData) Round},
    {"sdev", (GenericMathProc *) ScalarFunc, (ClientData) StdDeviation},
    {"sin", (GenericMathProc *) ComponentFunc, (ClientData) sin},
    {"sinh", (GenericMathProc *) ComponentFunc, (ClientData) sinh},
    {"skew", (GenericMathProc *) ScalarFunc, (ClientData) Skew},
    {"sort", (GenericMathProc *) VectorFunc, (ClientData) Sort},
    {"sqrt", (GenericMathProc *) ComponentFunc, (ClientData) sqrt},
    {"sum", (GenericMathProc *) ScalarFunc, (ClientData) Sum},
    {"tan", (GenericMathProc *) ComponentFunc, (ClientData) tan},
    {"tanh", (GenericMathProc *) ComponentFunc, (ClientData) tanh},
    {"var", (GenericMathProc *) ScalarFunc, (ClientData) Variance},
    {(char *)NULL,},
};

/*
 *----------------------------------------------------------------------
 *
 * RbcVectorInstallMathFunctions --
 *
 *      Creates a hash entry for every math function
 *      and sets the value to the function.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Adds to the hash entry the math functions.
 *
 *----------------------------------------------------------------------
 */
void
RbcVectorInstallMathFunctions(
    Tcl_HashTable * tablePtr)
{              /* Pointer to the hash where
                * the math functions should
                * be installed to. */
Tcl_HashEntry *hPtr;
register MathFunction *mathPtr;
int isNew;
    for(mathPtr = mathFunctions; mathPtr->name != NULL; mathPtr++) {
        hPtr = Tcl_CreateHashEntry(tablePtr, mathPtr->name, &isNew);
        Tcl_SetHashValue(hPtr, (ClientData) mathPtr);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * RbcVectorInstallSpecialIndices --
 *
 *      Creates a hash entry for every index
 *      and sets the value to the function.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Adds to the hash entry the special indicies
 *
 *----------------------------------------------------------------------
 */
void
RbcVectorInstallSpecialIndices(
    Tcl_HashTable * tablePtr)
{              /* Pointer to the hash where
                * the special indices should
                * be added to. */
    InstallIndexProc(tablePtr, "min", RbcVecMin);
    InstallIndexProc(tablePtr, "max", RbcVecMax);
    InstallIndexProc(tablePtr, "mean", Mean);
    InstallIndexProc(tablePtr, "sum", Sum);
    InstallIndexProc(tablePtr, "prod", Product);
}

/*
 *----------------------------------------------------------------------
 *
 * InstallIndexProc --
 *
 *      Creates a hash entry for every index
 *      and sets the value to the function.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Adds to the hash entry the special indicies
 *
 *----------------------------------------------------------------------
 */
static void
InstallIndexProc(
    Tcl_HashTable * tablePtr,
    const char *string,
    Rbc_VectorIndexProc * procPtr)
{              /* Pointer to function to be called
                * when the vector finds the named index.
                * If NULL, this indicates to remove
                * the index from the table.
                */
    Tcl_HashEntry *hPtr;
    int dummy;
    hPtr = Tcl_CreateHashEntry(tablePtr, string, &dummy);
    if(procPtr == NULL) {
        Tcl_DeleteHashEntry(hPtr);
    } else {
        Tcl_SetHashValue(hPtr, (ClientData) procPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * First --
 *
 *      Gets the first index of the designated interval.  The interval
 *      is between vPtr->first and vPtr->last.  But the range may
 *      NaN or Inf values that should be ignored.
 *
 * Results:
 *      Returns the index of the first finite value in the designated
 *      interval.  If no finite values exists in the range, then -1 is
 *      returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
First(
    RbcVectorObject * vPtr)
{              /* The vector to retrieve the first index from */
register int i;
    for(i = vPtr->first; i <= vPtr->last; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            return i;
        }
    }
    return -1;
}

/*
 *--------------------------------------------------------------
 *
 * Next --
 *
 *      Gets the next index of the designated interval.  The interval
 *      is between vPtr->first and vPtr->last.  Ignore NaN or Inf
 *      values.
 *
 * Results:
 *      Returns the index of the next finite value in the designated
 *      interval.  If no more finite values exists in the range,
 *      then -1 is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
Next(
    RbcVectorObject * vPtr,    /* The vector to retrieve the next index for */
    int current)
{              /* The current index */
    register int i;
    for(i = current + 1; i <= vPtr->last; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            return i;
        }
    }
    return -1;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcVecMin --
 *
 *      Calculates the minimum value of all the indexes in the
 *      vector.
 *
 * Results:
 *      The minimum value in the vector
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
double
RbcVecMin(
    Rbc_Vector * vecPtr)
{              /* The vector to calculate the min for */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
double min;
register int i;
    min = rbcNaN;
    for(i = 0; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            min = vPtr->valueArr[i];
            break;
        }
    }
    for( /* empty */ ; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            if(min > vPtr->valueArr[i]) {
                min = vPtr->valueArr[i];
            }
        }
    }
    vPtr->min = min;
    return vPtr->min;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcVecMax --
 *
 *      Calculates the minimum value of all the indexes in the
 *      vector.
 *
 * Results:
 *      The minimum value in the vector
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
double
RbcVecMax(
    Rbc_Vector * vecPtr)
{              /* The vector to calculate the max for */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
double max;
register int i;
    max = rbcNaN;
    for(i = 0; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            max = vPtr->valueArr[i];
            break;
        }
    }
    for( /* empty */ ; i < vPtr->length; i++) {
        if(!TclIsInfinite(vPtr->valueArr[i])) {
            if(max < vPtr->valueArr[i]) {
                max = vPtr->valueArr[i];
            }
        }
    }
    vPtr->max = max;
    return vPtr->max;
}

/*
 *----------------------------------------------------------------------
 *
 * Mean --
 *
 *      Calculates the mean of all the value in the
 *      vector.
 *
 * Results:
 *      The mean value of the vector
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static double
Mean(
    Rbc_Vector * vecPtr)
{              /* The vector to calculate the mean of */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register int i;
int count;
double sum;
    sum = 0.0;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        sum += vPtr->valueArr[i];
        count++;
    }
    return sum / (double)count;
}

/*
 *----------------------------------------------------------------------
 *
 * Sum --
 *
 *      Calculates the sum of all the value in the
 *      vector.
 *
 * Results:
 *      The sum value of the vector
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static double
Sum(
    Rbc_Vector * vecPtr)
{              /* The vector to calculate the sum for */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register int i;
double sum;
    sum = 0.0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        sum += vPtr->valueArr[i];
    }
    return sum;
}

/*
 *----------------------------------------------------------------------
 *
 * Product --
 *
 *      Calculates the product of all the value in the
 *      vector.
 *
 * Results:
 *      The product value of the vector
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static double
Product(
    Rbc_Vector * vecPtr)
{              /* The Vector to calculate product for */
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register int i;
register double prod;
    prod = 1.0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        prod *= vPtr->valueArr[i];
    }
    return prod;
}

/*
 *--------------------------------------------------------------
 *
 * Sort --
 *
 *      A vector math function.  Sorts the values of the given
 *      vector.
 *
 * Results:
 *      Always TCL_OK.
 *
 * Side Effects:
 *      The vector is sorted.
 *
 *--------------------------------------------------------------
 */
static int
Sort(
    RbcVectorObject * vPtr)
{
int *indexArr;
double *tempArr;
register int i;
    indexArr = RbcVectorSortIndex(&vPtr, 1);
    tempArr = (double *)ckalloc(sizeof(double) * vPtr->length);
    for(i = vPtr->first; i <= vPtr->last; i++) {
        tempArr[i] = vPtr->valueArr[indexArr[i]];
    }
    ckfree((char *)indexArr);
    for(i = vPtr->first; i <= vPtr->last; i++) {
        vPtr->valueArr[i] = tempArr[i];
    }
    ckfree((char *)tempArr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * Length --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Length(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
int count;
register int i;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        count++;
    }
    return (double)count;
}

/*
 *--------------------------------------------------------------
 *
 * Median --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Median(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
int *iArr;
double q2;
int mid;
    if(vPtr->length == 0) {
        return -DBL_MAX;
    }
    iArr = RbcVectorSortIndex(&vPtr, 1);
    mid = (vPtr->length - 1) / 2;
    /*
     * Determine Q2 by checking if the number of elements [0..n-1] is
     * odd or even.  If even, we must take the average of the two
     * middle values.
     */
    if(vPtr->length & 1) {      /* Odd */
        q2 = vPtr->valueArr[iArr[mid]];
    } else {   /* Even */
        q2 = (vPtr->valueArr[iArr[mid]] + vPtr->valueArr[iArr[mid + 1]]) * 0.5;
    }
    ckfree((char *)iArr);
    return q2;
}

/*
 *--------------------------------------------------------------
 *
 * Variance --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Variance(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register double dx, var, mean;
register int i;
int count;
    mean = Mean(vecPtr);
    var = 0.0;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        dx = vPtr->valueArr[i] - mean;
        var += dx * dx;
        count++;
    }
    if(count < 2) {
        return 0.0;
    }
    var /= (double)(count - 1);
    return var;
}

/*
 *--------------------------------------------------------------
 *
 * Skew --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Skew(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register double diff, var, skew, mean, diffsq;
register int i;
int count;
    mean = Mean(vecPtr);
    var = skew = 0.0;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        diff = vPtr->valueArr[i] - mean;
        diff = FABS(diff);
        diffsq = diff * diff;
        var += diffsq;
        skew += diffsq * diff;
        count++;
    }
    if(count < 2) {
        return 0.0;
    }
    var /= (double)(count - 1);
    skew /= count * var * sqrt(var);
    return skew;
}

/*
 *--------------------------------------------------------------
 *
 * StdDeviation --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
StdDeviation(
    Rbc_Vector * vecPtr)
{
double var;
    var = Variance(vecPtr);
    if(var > 0.0) {
        return sqrt(var);
    }
    return 0.0;
}

/*
 *--------------------------------------------------------------
 *
 * AvgDeviation --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
AvgDeviation(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register double diff, avg, mean;
register int i;
int count;
    mean = Mean(vecPtr);
    avg = 0.0;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        diff = vPtr->valueArr[i] - mean;
        avg += FABS(diff);
        count++;
    }
    if(count < 2) {
        return 0.0;
    }
    avg /= (double)count;
    return avg;
}

/*
 *--------------------------------------------------------------
 *
 * Kurtosis --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Kurtosis(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register double diff, diffsq, kurt, var, mean;
register int i;
int count;
    mean = Mean(vecPtr);
    var = kurt = 0.0;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        diff = vPtr->valueArr[i] - mean;
        diffsq = diff * diff;
        var += diffsq;
        kurt += diffsq * diffsq;
        count++;
    }
    if(count < 2) {
        return 0.0;
    }
    var /= (double)(count - 1);
    if(var == 0.0) {
        return 0.0;
    }
    kurt /= (count * var * var);
    return kurt - 3.0;  /* Fisher Kurtosis */
}

/*
 *--------------------------------------------------------------
 *
 * Q1 --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Q1(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
double q1;
int *iArr;
    if(vPtr->length == 0) {
        return -DBL_MAX;
    }
    iArr = RbcVectorSortIndex(&vPtr, 1);
    if(vPtr->length < 4) {
        q1 = vPtr->valueArr[iArr[0]];
    } else {
int mid, q;
        mid = (vPtr->length - 1) / 2;
        q = mid / 2;
        /*
         * Determine Q1 by checking if the number of elements in the
         * bottom half [0..mid) is odd or even.   If even, we must
         * take the average of the two middle values.
         */
        if(mid & 1) {   /* Odd */
            q1 = vPtr->valueArr[iArr[q]];
        } else {        /* Even */
            q1 = (vPtr->valueArr[iArr[q]] + vPtr->valueArr[iArr[q + 1]]) * 0.5;
        }
    }
    ckfree((char *)iArr);
    return q1;
}

/*
 *--------------------------------------------------------------
 *
 * Q3 --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Q3(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
double q3;
int *iArr;
    if(vPtr->length == 0) {
        return -DBL_MAX;
    }
    iArr = RbcVectorSortIndex(&vPtr, 1);
    if(vPtr->length < 4) {
        q3 = vPtr->valueArr[iArr[vPtr->length - 1]];
    } else {
int mid, q;
        mid = (vPtr->length - 1) / 2;
        q = (vPtr->length + mid) / 2;
        /*
         * Determine Q3 by checking if the number of elements in the
         * upper half (mid..n-1] is odd or even.   If even, we must
         * take the average of the two middle values.
         */
        if(mid & 1) {   /* Odd */
            q3 = vPtr->valueArr[iArr[q]];
        } else {        /* Even */
            q3 = (vPtr->valueArr[iArr[q]] + vPtr->valueArr[iArr[q + 1]]) * 0.5;
        }
    }
    ckfree((char *)iArr);
    return q3;
}

/*
 *--------------------------------------------------------------
 *
 * Norm --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
Norm(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
double norm, range, min, max;
register int i;
    min = RbcVecMin(vecPtr);
    max = RbcVecMax(vecPtr);
    range = max - min;
    for(i = 0; i < vPtr->length; i++) {
        norm = (vPtr->valueArr[i] - min) / range;
        vPtr->valueArr[i] = norm;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * Nonzeros --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Nonzeros(
    Rbc_Vector * vecPtr)
{
RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
register int i;
int count;
    count = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        if(vPtr->valueArr[i] == 0.0) {
            count++;
        }
    }
    return (double)count;
}

/*
 *--------------------------------------------------------------
 *
 * Fabs --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Fabs(
    double value)
{
    if(value < 0.0) {
        return -value;
    }
    return value;
}

/*
 *--------------------------------------------------------------
 *
 * Round --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Round(
    double value)
{
    if(value < 0.0) {
        return ceil(value - 0.5);
    } else {
        return floor(value + 0.5);
    }
}

/*
 *--------------------------------------------------------------
 *
 * RbcExprVector --
 *
 *      Evaluates an vector expression and returns its value(s).
 *
 * Results:
 *      Each of the procedures below returns a standard Tcl result.
 *      If an error occurs then an error message is left in
 *      Tcl_GetString(Tcl_GetObjResult(interp)).  Otherwise the value of the expression,
 *      in the appropriate form, is stored at *resultPtr.  If
 *      the expression had a result that was incompatible with the
 *      desired form then an error is returned.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
int
RbcExprVector(
    Tcl_Interp * interp,
    char *string,
    Rbc_Vector * vecPtr)
{
    RbcVectorInterpData *dataPtr;       /* Interpreter-specific data. */
    RbcVectorObject *vPtr = (RbcVectorObject *) vecPtr;
    RbcParseVector value;
    char stringDouble[TCL_DOUBLE_SPACE];

    dataPtr = (vecPtr != NULL) ? vPtr->dataPtr : RbcVectorGetInterpData(interp);
    value.vPtr = RbcVectorNew(dataPtr);
    if(EvaluateExpression(interp, string, &value) != TCL_OK) {
        Rbc_VectorFree(value.vPtr);
        return TCL_ERROR;
    }
    if(vPtr != NULL) {
        RbcVectorDuplicate(vPtr, value.vPtr);
    } else {
    register int i;
        /* No result vector.  Put values in Tcl_GetString(Tcl_GetObjResult(interp)).  */
        for(i = 0; i < value.vPtr->length; i++) {
            Tcl_PrintDouble(NULL, value.vPtr->valueArr[i], stringDouble);
            Tcl_AppendElement(interp, stringDouble);
        }
    }
    Rbc_VectorFree(value.vPtr);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * EvaluateExpression --
 *
 *      This procedure provides top-level functionality shared by
 *      procedures like Tcl_ExprInt, Tcl_ExprDouble, etc.
 *
 * Results:
 *      The result is a standard Tcl return value.  If an error
 *      occurs then an error message is left in Tcl_GetString(Tcl_GetObjResult(interp)).
 *      The value of the expression is returned in *valuePtr, in
 *      whatever form it ends up in (could be string or integer
 *      or double).  Caller may need to convert result.  Caller
 *      is also responsible for freeing string memory in *valuePtr,
 *      if any was allocated.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
static int
EvaluateExpression(
    Tcl_Interp * interp,       /* Context in which to evaluate the
                                * expression. */
    char *string,              /* Expression to evaluate. */
    RbcParseVector * valuePtr)
{              /* Where to store result.  Should
                * not be initialized by caller. */
    ParseInfo info;
    int result;
    RbcVectorObject *vPtr;
    register int i;
    info.expr = info.nextPtr = string;
    valuePtr->pv.buffer = valuePtr->pv.next = valuePtr->staticSpace;
    valuePtr->pv.end = valuePtr->pv.buffer + RBC_STATIC_STRING_SPACE - 1;
    valuePtr->pv.expandProc = RbcExpandParseValue;
    valuePtr->pv.clientData = NULL;
    result = NextValue(interp, &info, -1, valuePtr);
    if(result != TCL_OK) {
        return result;
    }
    if(info.token != END) {
        Tcl_AppendResult(interp, ": syntax error in expression \"", string,
            "\"", (char *)NULL);
        return TCL_ERROR;
    }
    vPtr = valuePtr->vPtr;
    /* Check for NaN's and overflows. */
    for(i = 0; i < vPtr->length; i++) {
        if(TclIsInfinite(vPtr->valueArr[i])) {
            /*
             * IEEE floating-point error.
             */
            MathError(interp, vPtr->valueArr[i]);
            return TCL_ERROR;
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * NextValue --
 *
 *      Parse a "value" from the remainder of the expression in parsePtr.
 *
 * Results:
 *      Normally TCL_OK is returned.  The value of the expression is
 *      returned in *valuePtr.  If an error occurred, then Tcl_GetString(Tcl_GetObjResult(interp))
 *      contains an error message and TCL_ERROR is returned.
 *      InfoPtr->token will be left pointing to the token AFTER the
 *      expression, and parsePtr->nextPtr will point to the character just
 *      after the terminating token.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static int
NextValue(
    Tcl_Interp * interp,       /* Interpreter to use for error reporting. */
    ParseInfo * parsePtr,      /* Describes the state of the parse
                                * just before the value (i.e. NextToken will
                                * be called to get first token of value). */
    int prec,                  /* Treat any un-parenthesized operator
                                * with precedence <= this as the end
                                * of the expression. */
    RbcParseVector * valuePtr)
{              /* Where to store the value of the expression.
                * Caller must have initialized pv field. */
    RbcParseVector value2;     /* Second operand for current operator.  */
    int operator;              /* Current operator (either unary or binary). */
    /* Non-zero means already lexed the operator
     * (while picking up value for unary operator).
     * Don't lex again. */
    int gotOp;
    int result;
    RbcVectorObject *vPtr, *v2Ptr;
    register int i;
    /*
     * There are two phases to this procedure.  First, pick off an initial
     * value.  Then, parse (binary operator, value) pairs until done.
     */
    vPtr = valuePtr->vPtr;
    v2Ptr = RbcVectorNew(vPtr->dataPtr);
    gotOp = FALSE;
    value2.vPtr = v2Ptr;
    value2.pv.buffer = value2.pv.next = value2.staticSpace;
    value2.pv.end = value2.pv.buffer + RBC_STATIC_STRING_SPACE - 1;
    value2.pv.expandProc = RbcExpandParseValue;
    value2.pv.clientData = NULL;
    result = NextToken(interp, parsePtr, valuePtr);
    if(result != TCL_OK) {
        goto done;
    }
    if(parsePtr->token == OPEN_PAREN) {
        /* Parenthesized sub-expression. */
        result = NextValue(interp, parsePtr, -1, valuePtr);
        if(result != TCL_OK) {
            goto done;
        }
        if(parsePtr->token != CLOSE_PAREN) {
            Tcl_AppendResult(interp, "unmatched parentheses in expression \"",
                parsePtr->expr, "\"", (char *)NULL);
            result = TCL_ERROR;
            goto done;
        }
    } else {
        if(parsePtr->token == MINUS) {
            parsePtr->token = UNARY_MINUS;
        }
        if(parsePtr->token >= UNARY_MINUS) {
    operator = parsePtr->token;
            result = NextValue(interp, parsePtr, precTable[operator], valuePtr);
            if(result != TCL_OK) {
                goto done;
            }
            gotOp = TRUE;
            /* Process unary operators. */
            switch (operator) {
            case UNARY_MINUS:
                for(i = 0; i < vPtr->length; i++) {
                    vPtr->valueArr[i] = -(vPtr->valueArr[i]);
                }
                break;
            case NOT:
                for(i = 0; i < vPtr->length; i++) {
                    vPtr->valueArr[i] = (double)(!vPtr->valueArr[i]);
                }
                break;
            default:
                Tcl_AppendResult(interp, "unknown operator", (char *)NULL);
                goto error;
            }
        } else if(parsePtr->token != VALUE) {
            Tcl_AppendResult(interp, "missing operand", (char *)NULL);
            goto error;
        }
    }
    if(!gotOp) {
        result = NextToken(interp, parsePtr, &value2);
        if(result != TCL_OK) {
            goto done;
        }
    }
    /*
     * Got the first operand.  Now fetch (operator, operand) pairs.
     */
    for(;;) {
    operator = parsePtr->token;
        value2.pv.next = value2.pv.buffer;
        if((operator < MULT) || (operator >= UNARY_MINUS)) {
            if((operator == END) || (operator == CLOSE_PAREN)
                || (operator == COMMA)) {
                result = TCL_OK;
                goto done;
            } else {
                Tcl_AppendResult(interp, "bad operator", (char *)NULL);
                goto error;
            }
        }
        if(precTable[operator] <= prec) {
            result = TCL_OK;
            goto done;
        }
        result = NextValue(interp, parsePtr, precTable[operator], &value2);
        if(result != TCL_OK) {
            goto done;
        }
        if((parsePtr->token < MULT) && (parsePtr->token != VALUE)
            && (parsePtr->token != END) && (parsePtr->token != CLOSE_PAREN)
            && (parsePtr->token != COMMA)) {
            Tcl_AppendResult(interp, "unexpected token in expression",
                (char *)NULL);
            goto error;
        }
        /*
         * At this point we have two vectors and an operator.
         */
        if(v2Ptr->length == 1) {
    register double *opnd;
    register double scalar;
            /*
             * 2nd operand is a scalar.
             */
            scalar = v2Ptr->valueArr[0];
            opnd = vPtr->valueArr;
            switch (operator) {
            case MULT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] *= scalar;
                }
                break;
            case DIVIDE:
                if(scalar == 0.0) {
                    Tcl_AppendResult(interp, "divide by zero", (char *)NULL);
                    goto error;
                }
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] /= scalar;
                }
                break;
            case PLUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] += scalar;
                }
                break;
            case MINUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] -= scalar;
                }
                break;
            case EXPONENT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = pow(opnd[i], scalar);
                }
                break;
            case MOD:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = Fmod(opnd[i], scalar);
                }
                break;
            case LESS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] < scalar);
                }
                break;
            case GREATER:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] > scalar);
                }
                break;
            case LEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] <= scalar);
                }
                break;
            case GEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] >= scalar);
                }
                break;
            case EQUAL:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] == scalar);
                }
                break;
            case NEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] != scalar);
                }
                break;
            case AND:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] && scalar);
                }
                break;
            case OR:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] || scalar);
                }
                break;
            case LEFT_SHIFT:{
    int offset;
                offset = (int)scalar % vPtr->length;
                if(offset > 0) {
    double *hold;
    register int j;
                    hold = (double *)ckalloc(sizeof(double) * offset);
                    for(i = 0; i < offset; i++) {
                        hold[i] = opnd[i];
                    }
                    for(i = offset, j = 0; i < vPtr->length; i++, j++) {
                        opnd[j] = opnd[i];
                    }
                    for(i = 0, j = vPtr->length - offset; j < vPtr->length;
                        i++, j++) {
                        opnd[j] = hold[i];
                    }
                    ckfree((char *)hold);
                }
            }
                break;
            case RIGHT_SHIFT:{
    int offset;
                offset = (int)scalar % vPtr->length;
                if(offset > 0) {
    double *hold;
    register int j;
                    hold = (double *)ckalloc(sizeof(double) * offset);
                    for(i = vPtr->length - offset, j = 0; i < vPtr->length;
                        i++, j++) {
                        hold[j] = opnd[i];
                    }
                    for(i = vPtr->length - offset - 1, j = vPtr->length - 1; i
                        >= 0; i--, j--) {
                        opnd[j] = opnd[i];
                    }
                    for(i = 0; i < offset; i++) {
                        opnd[i] = hold[i];
                    }
                    ckfree((char *)hold);
                }
            }
                break;
            default:
                Tcl_AppendResult(interp, "unknown operator in expression",
                    (char *)NULL);
                goto error;
            }
        } else if(vPtr->length == 1) {
    register double *opnd;
    register double scalar;
            /*
             * 1st operand is a scalar.
             */
            scalar = vPtr->valueArr[0];
            RbcVectorDuplicate(vPtr, v2Ptr);
            opnd = vPtr->valueArr;
            switch (operator) {
            case MULT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] *= scalar;
                }
                break;
            case PLUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] += scalar;
                }
                break;
            case DIVIDE:
                for(i = 0; i < vPtr->length; i++) {
                    if(opnd[i] == 0.0) {
                        Tcl_AppendResult(interp, "divide by zero",
                            (char *)NULL);
                        goto error;
                    }
                    opnd[i] = (scalar / opnd[i]);
                }
                break;
            case MINUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = scalar - opnd[i];
                }
                break;
            case EXPONENT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = pow(scalar, opnd[i]);
                }
                break;
            case MOD:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = Fmod(scalar, opnd[i]);
                }
                break;
            case LESS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(scalar < opnd[i]);
                }
                break;
            case GREATER:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(scalar > opnd[i]);
                }
                break;
            case LEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(scalar >= opnd[i]);
                }
                break;
            case GEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(scalar <= opnd[i]);
                }
                break;
            case EQUAL:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] == scalar);
                }
                break;
            case NEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] != scalar);
                }
                break;
            case AND:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] && scalar);
                }
                break;
            case OR:
                for(i = 0; i < vPtr->length; i++) {
                    opnd[i] = (double)(opnd[i] || scalar);
                }
                break;
            case LEFT_SHIFT:
            case RIGHT_SHIFT:
                Tcl_AppendResult(interp, "second shift operand must be scalar",
                    (char *)NULL);
                goto error;
            default:
                Tcl_AppendResult(interp, "unknown operator in expression",
                    (char *)NULL);
                goto error;
            }
        } else {
    register double *opnd1, *opnd2;
            /*
             * Carry out the function of the specified operator.
             */
            if(vPtr->length != v2Ptr->length) {
                Tcl_AppendResult(interp, "vectors are different lengths",
                    (char *)NULL);
                goto error;
            }
            opnd1 = vPtr->valueArr, opnd2 = v2Ptr->valueArr;
            switch (operator) {
            case MULT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] *= opnd2[i];
                }
                break;
            case DIVIDE:
                for(i = 0; i < vPtr->length; i++) {
                    if(opnd2[i] == 0.0) {
                        Tcl_AppendResult(interp,
                            "can't divide by 0.0 vector component",
                            (char *)NULL);
                        goto error;
                    }
                    opnd1[i] /= opnd2[i];
                }
                break;
            case PLUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] += opnd2[i];
                }
                break;
            case MINUS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] -= opnd2[i];
                }
                break;
            case MOD:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = Fmod(opnd1[i], opnd2[i]);
                }
                break;
            case EXPONENT:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = pow(opnd1[i], opnd2[i]);
                }
                break;
            case LESS:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] < opnd2[i]);
                }
                break;
            case GREATER:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] > opnd2[i]);
                }
                break;
            case LEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] <= opnd2[i]);
                }
                break;
            case GEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] >= opnd2[i]);
                }
                break;
            case EQUAL:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] == opnd2[i]);
                }
                break;
            case NEQ:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] != opnd2[i]);
                }
                break;
            case AND:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] && opnd2[i]);
                }
                break;
            case OR:
                for(i = 0; i < vPtr->length; i++) {
                    opnd1[i] = (double)(opnd1[i] || opnd2[i]);
                }
                break;
            case LEFT_SHIFT:
            case RIGHT_SHIFT:
                Tcl_AppendResult(interp, "second shift operand must be scalar",
                    (char *)NULL);
                goto error;
            default:
                Tcl_AppendResult(interp, "unknown operator in expression",
                    (char *)NULL);
                goto error;
            }
        }
    }
  done:
    if(value2.pv.buffer != value2.staticSpace) {
        ckfree((char *)value2.pv.buffer);
    }
    Rbc_VectorFree(v2Ptr);
    return result;
  error:
    if(value2.pv.buffer != value2.staticSpace) {
        ckfree((char *)value2.pv.buffer);
    }
    Rbc_VectorFree(v2Ptr);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * MathError --
 *
 *      This procedure is called when an error occurs during a
 *      floating-point operation.  It reads errno and sets
 *      Tcl_GetString(Tcl_GetObjResult(interp)) accordingly.
 *
 * Results:
 *      Interp->result is set to hold an error message.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static void
MathError(
    Tcl_Interp * interp,       /* Where to store error message. */
    double value)
{              /* Value returned after error;  used to
                * distinguish underflows from overflows. */
    if((errno == EDOM) || (value != value)) {
        Tcl_AppendResult(interp, "domain error: argument not in valid range",
            (char *)NULL);
        Tcl_SetErrorCode(interp, "ARITH", "DOMAIN",
            Tcl_GetString(Tcl_GetObjResult(interp)), (char *)NULL);
    } else if((errno == ERANGE) || IS_INF(value)) {
        if(value == 0.0) {
            Tcl_AppendResult(interp,
                "floating-point value too small to represent", (char *)NULL);
            Tcl_SetErrorCode(interp, "ARITH", "UNDERFLOW",
                Tcl_GetString(Tcl_GetObjResult(interp)), (char *)NULL);
        } else {
            Tcl_AppendResult(interp,
                "floating-point value too large to represent", (char *)NULL);
            Tcl_SetErrorCode(interp, "ARITH", "OVERFLOW",
                Tcl_GetString(Tcl_GetObjResult(interp)), (char *)NULL);
        }
    } else {
    char buf[20];
        sprintf(buf, "%d", errno);
        Tcl_AppendResult(interp, "unknown floating-point error, ", "errno = ",
            buf, (char *)NULL);
        Tcl_SetErrorCode(interp, "ARITH", "UNKNOWN",
            Tcl_GetString(Tcl_GetObjResult(interp)), (char *)NULL);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * NextToken --
 *
 *      Lexical analyzer for expression parser:  parses a single value,
 *      operator, or other syntactic element from an expression string.
 *
 * Results:
 *      TCL_OK is returned unless an error occurred while doing lexical
 *      analysis or executing an embedded command.  In that case a
 *      standard Tcl error is returned, using Tcl_GetString(Tcl_GetObjResult(interp)) to hold
 *      an error message.  In the event of a successful return, the token
 *      and field in parsePtr is updated to refer to the next symbol in
 *      the expression string, and the expr field is advanced past that
 *      token;  if the token is a value, then the value is stored at
 *      valuePtr.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static int
NextToken(
    Tcl_Interp * interp,       /* Interpreter to use for error reporting. */
    ParseInfo * parsePtr,      /* Describes the state of the parse. */
    RbcParseVector * valuePtr)
{              /* Where to store value, if that is
                * what's parsed from string.  Caller
                * must have initialized pv field
                * correctly. */
register char *p;
char *endPtr;
const char *var;
int result;
    p = parsePtr->nextPtr;
    while(isspace(UCHAR(*p))) {
        p++;
    }
    if(*p == '\0') {
        parsePtr->token = END;
        parsePtr->nextPtr = p;
        return TCL_OK;
    }
    /*
     * Try to parse the token as a floating-point number. But check
     * that the first character isn't a "-" or "+", which "strtod"
     * will happily accept as an unary operator.  Otherwise, we might
     * accidently treat a binary operator as unary by mistake, which
     * will eventually cause a syntax error.
     */
    if((*p != '-') && (*p != '+')) {
double value;
        errno = 0;
        value = strtod(p, &endPtr);
        if(endPtr != p) {
            if(errno != 0) {
                MathError(interp, value);
                return TCL_ERROR;
            }
            parsePtr->token = VALUE;
            parsePtr->nextPtr = endPtr;
            /*
             * Save the single floating-point value as an 1-component vector.
             */
            if(RbcVectorChangeLength(valuePtr->vPtr, 1) != TCL_OK) {
                return TCL_ERROR;
            }
            valuePtr->vPtr->valueArr[0] = value;
            return TCL_OK;
        }
    }
    parsePtr->nextPtr = p + 1;
    switch (*p) {
    case '$':
        parsePtr->token = VALUE;
        var = Tcl_ParseVar(interp, p, (const char **)&endPtr);
        if(var == NULL) {
            return TCL_ERROR;
        }
        parsePtr->nextPtr = endPtr;
        Tcl_ResetResult(interp);
        result = ParseString(interp, var, valuePtr);
        return result;
    case '[':
        parsePtr->token = VALUE;
        result = RbcParseNestedCmd(interp, p + 1, 0, &endPtr, &(valuePtr->pv));
        if(result != TCL_OK) {
            return result;
        }
        parsePtr->nextPtr = endPtr;
        Tcl_ResetResult(interp);
        result = ParseString(interp, valuePtr->pv.buffer, valuePtr);
        return result;
    case '"':
        parsePtr->token = VALUE;
        result =
            RbcParseQuotes(interp, p + 1, '"', 0, &endPtr, &(valuePtr->pv));
        if(result != TCL_OK) {
            return result;
        }
        parsePtr->nextPtr = endPtr;
        Tcl_ResetResult(interp);
        result = ParseString(interp, valuePtr->pv.buffer, valuePtr);
        return result;
    case '{':
        parsePtr->token = VALUE;
        result = RbcParseBraces(interp, p + 1, &endPtr, &valuePtr->pv);
        if(result != TCL_OK) {
            return result;
        }
        parsePtr->nextPtr = endPtr;
        Tcl_ResetResult(interp);
        result = ParseString(interp, valuePtr->pv.buffer, valuePtr);
        return result;
    case '(':
        parsePtr->token = OPEN_PAREN;
        break;
    case ')':
        parsePtr->token = CLOSE_PAREN;
        break;
    case ',':
        parsePtr->token = COMMA;
        break;
    case '*':
        parsePtr->token = MULT;
        break;
    case '/':
        parsePtr->token = DIVIDE;
        break;
    case '%':
        parsePtr->token = MOD;
        break;
    case '+':
        parsePtr->token = PLUS;
        break;
    case '-':
        parsePtr->token = MINUS;
        break;
    case '^':
        parsePtr->token = EXPONENT;
        break;
    case '<':
        switch (*(p + 1)) {
        case '<':
            parsePtr->nextPtr = p + 2;
            parsePtr->token = LEFT_SHIFT;
            break;
        case '=':
            parsePtr->nextPtr = p + 2;
            parsePtr->token = LEQ;
            break;
        default:
            parsePtr->token = LESS;
            break;
        }
        break;
    case '>':
        switch (*(p + 1)) {
        case '>':
            parsePtr->nextPtr = p + 2;
            parsePtr->token = RIGHT_SHIFT;
            break;
        case '=':
            parsePtr->nextPtr = p + 2;
            parsePtr->token = GEQ;
            break;
        default:
            parsePtr->token = GREATER;
            break;
        }
        break;
    case '=':
        if(*(p + 1) == '=') {
            parsePtr->nextPtr = p + 2;
            parsePtr->token = EQUAL;
        } else {
            parsePtr->token = UNKNOWN;
        }
        break;
    case '&':
        if(*(p + 1) == '&') {
            parsePtr->nextPtr = p + 2;
            parsePtr->token = AND;
        } else {
            parsePtr->token = UNKNOWN;
        }
        break;
    case '|':
        if(*(p + 1) == '|') {
            parsePtr->nextPtr = p + 2;
            parsePtr->token = OR;
        } else {
            parsePtr->token = UNKNOWN;
        }
        break;
    case '!':
        if(*(p + 1) == '=') {
            parsePtr->nextPtr = p + 2;
            parsePtr->token = NEQ;
        } else {
            parsePtr->token = NOT;
        }
        break;
    default:
        parsePtr->token = VALUE;
        result = ParseMathFunction(interp, p, parsePtr, valuePtr);
        if((result == TCL_OK) || (result == TCL_ERROR)) {
            return result;
        } else {
RbcVectorObject *vPtr;
            while(isspace(UCHAR(*p))) {
                p++;    /* Skip spaces leading the vector name. */
            }
            vPtr = RbcVectorParseElement(interp, valuePtr->vPtr->dataPtr, p,
                &endPtr, RBC_NS_SEARCH_BOTH);
            if(vPtr == NULL) {
                return TCL_ERROR;
            }
            RbcVectorDuplicate(valuePtr->vPtr, vPtr);
            parsePtr->nextPtr = endPtr;
        }
    }
    return TCL_OK;
}

/*
 * Fmod --
 * 	Returns x mod y
 */
/*
 *--------------------------------------------------------------
 *
 * Fmod --
 *
 *      Returns the remainder after performing x divided by y.
 *
 * Results:
 *      x mod y
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static double
Fmod(
    double x,
    double y)
{
    if(y == 0.0) {
        return 0.0;
    }
    return x - (floor(x / y) * y);
}

/*
 *--------------------------------------------------------------
 *
 * ParseString --
 *
 *      Given a string (such as one coming from command or variable
 *      substitution), make a Value based on the string.  The value
 *      will be a floating-point or integer, if possible, or else it
 *      will just be a copy of the string.
 *
 * Results:
 *      TCL_OK is returned under normal circumstances, and TCL_ERROR
 *      is returned if a floating-point overflow or underflow occurred
 *      while reading in a number.  The value at *valuePtr is modified
 *      to hold a number, if possible.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
static int
ParseString(
    Tcl_Interp * interp,       /* Where to store error message. */
    const char *string,        /* String to turn into value. */
    RbcParseVector * valuePtr)
{              /* Where to store value information.
                * Caller must have initialized pv field. */
    char *endPtr;
    double value;
    errno = 0;
    /*
     * The string can be either a number or a vector.  First try to
     * convert the string to a number.  If that fails then see if
     * we can find a vector by that name.
     */
    value = strtod(string, &endPtr);
    if((endPtr != string) && (*endPtr == '\0')) {
        if(errno != 0) {
            Tcl_ResetResult(interp);
            MathError(interp, value);
            return TCL_ERROR;
        }
        /* Numbers are stored as single element vectors. */
        if(RbcVectorChangeLength(valuePtr->vPtr, 1) != TCL_OK) {
            return TCL_ERROR;
        }
        valuePtr->vPtr->valueArr[0] = value;
        return TCL_OK;
    } else {
    RbcVectorObject *vPtr;
        while(isspace(UCHAR(*string))) {
            string++;   /* Skip spaces leading the vector name. */
        }
        vPtr =
            RbcVectorParseElement(interp, valuePtr->vPtr->dataPtr, string,
            &endPtr, RBC_NS_SEARCH_BOTH);
        if(vPtr == NULL) {
            return TCL_ERROR;
        }
        if(*endPtr != '\0') {
            Tcl_AppendResult(interp, "extra characters after vector",
                (char *)NULL);
            return TCL_ERROR;
        }
        /* Copy the designated vector to our temporary. */
        RbcVectorDuplicate(valuePtr->vPtr, vPtr);
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ParseMathFunction --
 *
 *      This procedure is invoked to parse a math function from an
 *      expression string, carry out the function, and return the
 *      value computed.
 *
 * Results:
 *      TCL_OK is returned if all went well and the function's value
 *      was computed successfully.  If the name doesn't match any
 *      known math function, returns TCL_RETURN. And if a format error
 *      was found, TCL_ERROR is returned and an error message is left
 *      in Tcl_GetString(Tcl_GetObjResult(interp)).
 *
 *      After a successful return parsePtr will be updated to point to
 *      the character just after the function call, the token is set
 *      to VALUE, and the value is stored in valuePtr.
 *
 * Side effects:
 *      Embedded commands could have arbitrary side-effects.
 *
 *----------------------------------------------------------------------
 */
static int
ParseMathFunction(
    Tcl_Interp * interp,       /* Interpreter to use for error reporting. */
    char *start,               /* Start of string to parse */
    ParseInfo * parsePtr,      /* Describes the state of the parse.
                                * parsePtr->nextPtr must point to the
                                * first character of the function's
                                * name. */
    RbcParseVector * valuePtr)
{              /* Where to store value, if that is
                * what's parsed from string.  Caller
                * must have initialized pv field
                * correctly. */
    Tcl_HashEntry *hPtr;
    MathFunction *mathPtr;     /* Info about math function. */
    register char *p;
    RbcVectorInterpData *dataPtr;       /* Interpreter-specific data. */
    /*
     * Find the end of the math function's name and lookup the
     * record for the function.
     */
    p = start;
    while(isspace(UCHAR(*p))) {
        p++;
    }
    parsePtr->nextPtr = p;
    while(isalnum(UCHAR(*p)) || (*p == '_')) {
        p++;
    }
    if(*p != '(') {
        return TCL_RETURN;      /* Must start with open parenthesis */
    }
    dataPtr = valuePtr->vPtr->dataPtr;
    *p = '\0';
    hPtr = Tcl_FindHashEntry(&(dataPtr->mathProcTable), parsePtr->nextPtr);
    *p = '(';
    if(hPtr == NULL) {
        return TCL_RETURN;      /* Name doesn't match any known function */
    }
    /* Pick up the single value as the argument to the function */
    parsePtr->token = OPEN_PAREN;
    parsePtr->nextPtr = p + 1;
    valuePtr->pv.next = valuePtr->pv.buffer;
    if(NextValue(interp, parsePtr, -1, valuePtr) != TCL_OK) {
        return TCL_ERROR;       /* Parse error */
    }
    if(parsePtr->token != CLOSE_PAREN) {
        Tcl_AppendResult(interp, "unmatched parentheses in expression \"",
            parsePtr->expr, "\"", (char *)NULL);
        return TCL_ERROR;       /* Missing right parenthesis */
    }
    mathPtr = (MathFunction *) Tcl_GetHashValue(hPtr);
    if((*mathPtr->proc) (mathPtr->clientData, interp, valuePtr->vPtr) != TCL_OK) {
        return TCL_ERROR;       /* Function invocation error */
    }
    parsePtr->token = VALUE;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * Math Functions --
 *
 *      This page contains the procedures that implement all of the
 *      built-in math functions for expressions.
 *
 * Results:
 *      Each procedure returns TCL_OK if it succeeds and places result
 *      information at *resultPtr.  If it fails it returns TCL_ERROR
 *      and leaves an error message in Tcl_GetString(Tcl_GetObjResult(interp)).
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------
 */
static int
ComponentFunc(
    ClientData clientData,     /* Contains address of procedure that
                                * takes one double argument and
                                * returns a double result. */
    Tcl_Interp * interp,
    RbcVectorObject * vPtr)
{
ComponentProc *procPtr = (ComponentProc *) clientData;
register int i;
    errno = 0;
    for(i = First(vPtr); i >= 0; i = Next(vPtr, i)) {
        vPtr->valueArr[i] = (*procPtr) (vPtr->valueArr[i]);
        if(errno != 0) {
            MathError(interp, vPtr->valueArr[i]);
            return TCL_ERROR;
        }
        if(TclIsInfinite(vPtr->valueArr[i])) {
            /*
             * IEEE floating-point error.
             */
            MathError(interp, vPtr->valueArr[i]);
            return TCL_ERROR;
        }
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * ScalarFunc --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
ScalarFunc(
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr)
{
double value;
ScalarProc *procPtr = (ScalarProc *) clientData;
    errno = 0;
    value = (*procPtr) (vPtr);
    if(errno != 0) {
        MathError(interp, value);
        return TCL_ERROR;
    }
    if(RbcVectorChangeLength(vPtr, 1) != TCL_OK) {
        return TCL_ERROR;
    }
    vPtr->valueArr[0] = value;
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * VectorFunc --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
VectorFunc(
    ClientData clientData,
    Tcl_Interp * interp,
    RbcVectorObject * vPtr)
{
VectorProc *procPtr = (VectorProc *) clientData;
    return (*procPtr) (vPtr);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoVectorObjCmd.c.














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

/*
 * rbcVecObjCmd.c --
 *
 *      This file contains all commands to process the operations
 *      on instances of a vector.
 *
 * Copyright (c) 2001 BLT was created by George Howlett.
 * Copyright (c) 2009 RBC was created by Samuel Green, Nicholas Hudson, Stanton Sievers, Jarrod Stormo
 * Copyright (c) 2018 Rene Zaumseil

 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkoGraph.h"

#define BUFFER_SIZE 1024

enum NativeFormats {
    FMT_UNKNOWN = -1,
    FMT_UCHAR,
    FMT_CHAR,
    FMT_USHORT,
    FMT_SHORT,
    FMT_UINT,
    FMT_INT,
    FMT_ULONG,
    FMT_LONG,
    FMT_FLOAT,
    FMT_DOUBLE
};

/* Pointer to the array of values currently being sorted. */
static RbcVectorObject **sortVectorArr;
static int nSortVectors;
static int reverse;

static int AppendVector(
    RbcVectorObject * destPtr,
    RbcVectorObject * srcPtr);
static int AppendList(
    RbcVectorObject * vPtr,
    int objc,
    Tcl_Obj * const objv[]);
static enum NativeFormats GetBinaryFormat(
    Tcl_Interp * interp,
    char *string,
    int *sizePtr);
static int CopyValues(
    RbcVectorObject * vPtr,
    char *byteArr,
    enum NativeFormats fmt,
    int size,
    int length,
    int swap,
    int *indexPtr);
static int InRange(
    double value,
    double min,
    double max);
static int CopyList(
    RbcVectorObject * vPtr,
    int objc,
    Tcl_Obj * const objv[]);
static int *SortVectors(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const *objv);
static int CompareVectors(
    void *a,
    void *b);

/*
 * -----------------------------------------------------------------------
 *
 * RbcAppendOp --
 *
 *      Appends one of more Tcl lists of values, or vector objects
 *      onto the end of the current vector object.
 *
 * Results:
 *      A standard Tcl result.  If a current vector can't be created,
 *      resized, any of the named vectors can't be found, or one of
 *      lists of values is invalid, TCL_ERROR is returned.
 *
 * Side Effects:
 *      Clients of current vector will be notified of the change.
 *
 * -----------------------------------------------------------------------
 */
int
RbcAppendOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    register int i;
    int result;
    RbcVectorObject *v2Ptr;

    for(i = 2; i < objc; i++) {
        v2Ptr = RbcVectorParseElement((Tcl_Interp *) NULL, vPtr->dataPtr,
            Tcl_GetStringFromObj(objv[i], NULL), (char **)NULL,
            RBC_NS_SEARCH_BOTH);
        if(v2Ptr != NULL) {
            result = AppendVector(vPtr, v2Ptr);
        } else {
    int nElem;
    Tcl_Obj **elemObjArr;

            if(Tcl_ListObjGetElements(interp, objv[i], &nElem,
                    &elemObjArr) != TCL_OK) {
                return TCL_ERROR;
            }
            result = AppendList(vPtr, nElem, elemObjArr);
        }
        if(result != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if(objc > 2) {
        if(vPtr->flush) {
            RbcVectorFlushCache(vPtr);
        }
        RbcVectorUpdateClients(vPtr);
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcArithOp --
 *
 *     TODO: Description
 *
 * Results:
 *      A standard Tcl result.  If the source vector doesn't exist
 *      or the source list is not a valid list of numbers, TCL_ERROR
 *      returned.  Otherwise TCL_OK is returned.
 *
 * Side Effects:
 *      The vector data is reset.  Clients of the vector are notified.
 *      Any cached array indices are flushed.
 *
 * -----------------------------------------------------------------------
 */
int
RbcArithOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const *objv)
{
    register double value;
    register int i;
    RbcVectorObject *v2Ptr;
    double scalar;
    Tcl_Obj *listObjPtr;
    char *string;

    v2Ptr =
        RbcVectorParseElement((Tcl_Interp *) NULL, vPtr->dataPtr,
        Tcl_GetString(objv[2]), (char **)NULL, RBC_NS_SEARCH_BOTH);
    if(v2Ptr != NULL) {
    register int j;
    int length;

        length = v2Ptr->last - v2Ptr->first + 1;
        if(length != vPtr->length) {
            Tcl_AppendResult(interp, "vectors \"", Tcl_GetString(objv[0]),
                "\" and \"", Tcl_GetString(objv[2]),
                "\" are not the same length", (char *)NULL);
            return TCL_ERROR;
        }
        string = Tcl_GetString(objv[1]);
        listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
        switch (string[0]) {
        case '*':
            for(i = 0, j = v2Ptr->first; i < vPtr->length; i++, j++) {
                value = vPtr->valueArr[i] * v2Ptr->valueArr[j];
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '/':
            for(i = 0, j = v2Ptr->first; i < vPtr->length; i++, j++) {
                value = vPtr->valueArr[i] / v2Ptr->valueArr[j];
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '-':
            for(i = 0, j = v2Ptr->first; i < vPtr->length; i++, j++) {
                value = vPtr->valueArr[i] - v2Ptr->valueArr[j];
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '+':
            for(i = 0, j = v2Ptr->first; i < vPtr->length; i++, j++) {
                value = vPtr->valueArr[i] + v2Ptr->valueArr[j];
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        }
        Tcl_SetObjResult(interp, listObjPtr);
    } else if(RbcGetDouble(interp, objv[2], &scalar) == TCL_OK) {
        listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
        string = Tcl_GetString(objv[1]);
        switch (string[0]) {
        case '*':
            for(i = 0; i < vPtr->length; i++) {
                value = vPtr->valueArr[i] * scalar;
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '/':
            for(i = 0; i < vPtr->length; i++) {
                value = vPtr->valueArr[i] / scalar;
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '-':
            for(i = 0; i < vPtr->length; i++) {
                value = vPtr->valueArr[i] - scalar;
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        case '+':
            for(i = 0; i < vPtr->length; i++) {
                value = vPtr->valueArr[i] + scalar;
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(value));
            }
            break;
        }
        Tcl_SetObjResult(interp, listObjPtr);
    } else {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcBinreadOp --
 *
 *      Reads binary values from a Tcl channel. Values are either appended
 *      to the end of the vector or placed at a given index (using the
 *      "-at" option), overwriting existing values.  Data is read until EOF
 *      is found on the channel or a specified number of values are read.
 *      (note that this is not necessarily the same as the number of bytes).
 *
 *      The following flags are supported:
 *        -swap          Swap bytes
 *        -at index      Start writing data at the index.
 *        -format fmt    Specifies the format of the data.
 *
 *      This binary reader was created by Harald Kirsch ([email protected]).
 *
 * Results:
 *      Returns a standard Tcl result. The interpreter result will contain
 *      the number of values (not the number of bytes) read.
 *
 * Caveats:
 *      Channel reads must end on an element boundary.
 *
 * -----------------------------------------------------------------------
 */
int
RbcBinreadOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Channel channel;
    char *byteArr;
    char *string;
    enum NativeFormats fmt;
    int arraySize, bytesRead;
    int count, total;
    int first;
    int size, length, mode;
    int swap;
    register int i;

    string = Tcl_GetStringFromObj(objv[2], NULL);
    channel = Tcl_GetChannel(interp, string, &mode);
    if(channel == NULL) {
        return TCL_ERROR;
    }
    if((mode & TCL_READABLE) == 0) {
        Tcl_AppendResult(interp, "channel \"", string,
            "\" wasn't opened for reading", (char *)NULL);
        return TCL_ERROR;
    }
    first = vPtr->length;
    fmt = FMT_DOUBLE;
    size = sizeof(double);
    swap = FALSE;
    count = 0;

    if(objc > 3) {
        string = Tcl_GetStringFromObj(objv[3], NULL);
        if(string[0] != '-') {
    long int value;
            /* Get the number of values to read.  */
            if(Tcl_GetLongFromObj(interp, objv[3], &value) != TCL_OK) {
                return TCL_ERROR;
            }
            if(value < 0) {
                Tcl_AppendResult(interp, "count can't be negative",
                    (char *)NULL);
                return TCL_ERROR;
            }
            count = (int)value;
            objc--;
            objv++;
        }
    }

    /* Process any option-value pairs that remain.  */
    for(i = 3; i < objc; i++) {
        string = Tcl_GetStringFromObj(objv[i], NULL);
        if(strcmp(string, "-swap") == 0) {
            swap = TRUE;
        } else if(strcmp(string, "-format") == 0) {
            i++;
            if(i >= objc) {
                Tcl_AppendResult(interp, "missing arg after \"", string, "\"",
                    (char *)NULL);
                return TCL_ERROR;
            }
            string = Tcl_GetStringFromObj(objv[i], NULL);
            fmt = GetBinaryFormat(interp, string, &size);
            if(fmt == FMT_UNKNOWN) {
                return TCL_ERROR;
            }
        } else if(strcmp(string, "-at") == 0) {
            i++;
            if(i >= objc) {
                Tcl_AppendResult(interp, "missing arg after \"", string, "\"",
                    (char *)NULL);
                return TCL_ERROR;
            }
            string = Tcl_GetString(objv[i]);
            if(RbcVectorGetIndex(interp, vPtr, string, &first, 0,
                    (Rbc_VectorIndexProc **) NULL) != TCL_OK) {
                return TCL_ERROR;
            }
            if(first > vPtr->length) {
                Tcl_AppendResult(interp, "index \"", string,
                    "\" is out of range", (char *)NULL);
                return TCL_ERROR;
            }
        }
    }

    if(count == 0) {
        arraySize = BUFFER_SIZE * size;
    } else {
        arraySize = count * size;
    }

    byteArr = (char *)ckalloc(arraySize);

    /* FIXME: restore old channel translation later? */
    if(Tcl_SetChannelOption(interp, channel, "-translation",
            "binary") != TCL_OK) {
        return TCL_ERROR;
    }
    total = 0;
    while(!Tcl_Eof(channel)) {
        bytesRead = Tcl_Read(channel, byteArr, arraySize);
        if(bytesRead < 0) {
            Tcl_AppendResult(interp, "error reading channel: ",
                Tcl_PosixError(interp), (char *)NULL);
            return TCL_ERROR;
        }
        if((bytesRead % size) != 0) {
            Tcl_AppendResult(interp, "error reading channel: short read",
                (char *)NULL);
            return TCL_ERROR;
        }
        length = bytesRead / size;
        if(CopyValues(vPtr, byteArr, fmt, size, length, swap, &first) != TCL_OK) {
            return TCL_ERROR;
        }
        total += length;
        if(count > 0) {
            break;
        }
    }
    ckfree((char *)byteArr);

    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);

    /* Set the result as the number of values read.  */
    Tcl_SetObjResult(interp, Tcl_NewIntObj(total));
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcClearOp --
 *
 *      Deletes all the accumulated array indices for the Tcl array
 *      associated will the vector.  This routine can be used to
 *      free excess memory from a large vector.
 *
 * Results:
 *      Always returns TCL_OK.
 *
 * Side Effects:
 *      Memory used for the entries of the Tcl array variable is freed.
 *
 * -----------------------------------------------------------------------
 */
int
RbcClearOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorFlushCache(vPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcDeleteOp --
 *
 *      Deletes the given indices from the vector.  If no indices are
 *      provided the entire vector is deleted.
 *
 * Results:
 *      A standard Tcl result.  If any of the given indices is invalid,
 *      interp->result will an error message and TCL_ERROR is returned.
 *
 * Side Effects:
 *      The clients of the vector will be notified of the vector
 *      deletions.
 *
 * -----------------------------------------------------------------------
 */
int
RbcDeleteOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    unsigned char *unsetArr;
    register int i, j;
    register int count;
    char *string;

    /* FIXME: Don't delete vector with no indices.  */
    if(objc == 2) {
        Rbc_VectorFree(vPtr);
        return TCL_OK;
    }
    /*
     * Allocate an "unset" bitmap the size of the vector.
     */
    unsetArr = (unsigned char *)RbcCalloc(sizeof(unsigned char),
        (vPtr->length + 7) / 8);

    /***    assert(unsetArr); */

#define SetBit(i) \
    unsetArr[(i) >> 3] |= (1 << ((i) & 0x07))
#define GetBit(i) \
    (unsetArr[(i) >> 3] & (1 << ((i) & 0x07)))

    for(i = 2; i < objc; i++) {
        string = Tcl_GetStringFromObj(objv[i], NULL);
        if(RbcVectorGetIndexRange(interp, vPtr, string,
                (RBC_INDEX_COLON | RBC_INDEX_CHECK),
                (Rbc_VectorIndexProc **) NULL) != TCL_OK) {
            ckfree((char *)unsetArr);
            return TCL_ERROR;
        }
        for(j = vPtr->first; j <= vPtr->last; j++) {
            SetBit(j);  /* Mark the range of elements for deletion. */
        }
    }
    count = 0;
    for(i = 0; i < vPtr->length; i++) {
        if(GetBit(i)) {
            continue;   /* Skip elements marked for deletion. */
        }
        if(count < i) {
            vPtr->valueArr[count] = vPtr->valueArr[i];
        }
        count++;
    }
    ckfree((char *)unsetArr);
    vPtr->length = count;
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcDupOp --
 *
 *      Creates one or more duplicates of the vector object.
 *
 * Results:
 *      A standard Tcl result.  If a new vector can't be created,
 *      or and existing vector resized, TCL_ERROR is returned.
 *
 * Side Effects:
 *      Clients of existing vectors will be notified of the change.
 *
 * -----------------------------------------------------------------------
 */
int
RbcDupOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorObject *v2Ptr;
    int isNew;
    register int i;
    char *string;

    for(i = 2; i < objc; i++) {
        string = Tcl_GetStringFromObj(objv[i], NULL);
        v2Ptr = RbcVectorCreate(vPtr->dataPtr, string, string, string, &isNew);
        if(v2Ptr == NULL) {
            return TCL_ERROR;
        }
        if(v2Ptr == vPtr) {
            continue;
        }
        if(RbcVectorDuplicate(v2Ptr, vPtr) != TCL_OK) {
            return TCL_ERROR;
        }
        if(!isNew) {
            if(v2Ptr->flush) {
                RbcVectorFlushCache(v2Ptr);
            }
            RbcVectorUpdateClients(v2Ptr);
        }
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * RbcExprOp --
 *
 *      Computes the result of the expression which may be
 *      either a scalar (single value) or vector (list of values).
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *----------------------------------------------------------------------
 */
int
RbcExprOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    if(RbcExprVector(interp, Tcl_GetStringFromObj(objv[2], NULL),
            (Rbc_Vector *) vPtr) != TCL_OK) {
        return TCL_ERROR;
    }
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcIndexOp --
 *
 *      Sets or reads the value of the index.  This simulates what the
 *      vector's variable does.
 *
 * Results:
 *      A standard Tcl result.  If the index is invalid,
 *      interp->result will an error message and TCL_ERROR is returned.
 *      Otherwise interp->result will contain the values.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcIndexOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    int first, last;
    char *string;

    string = Tcl_GetStringFromObj(objv[2], NULL);
    if(RbcVectorGetIndexRange(interp, vPtr, string, RBC_INDEX_ALL_FLAGS,
            (Rbc_VectorIndexProc **) NULL) != TCL_OK) {
        return TCL_ERROR;
    }
    first = vPtr->first, last = vPtr->last;
    if(objc == 3) {
    Tcl_Obj *listObjPtr;

        if(first == vPtr->length) {
            Tcl_AppendResult(interp, "can't get index \"", string, "\"",
                (char *)NULL);
            return TCL_ERROR;   /* Can't read from index "++end" */
        }
        listObjPtr = RbcGetValues(vPtr, first, last);
        Tcl_SetObjResult(interp, listObjPtr);
    } else {
    double value;

        /* FIXME: huh? Why set values here?.  */
        if(first == RBC_SPECIAL_INDEX) {
            Tcl_AppendResult(interp, "can't set index \"", string, "\"",
                (char *)NULL);
            return TCL_ERROR;   /* Tried to set "min" or "max" */
        }
        if(RbcGetDouble(vPtr->interp, objv[3], &value) != TCL_OK) {
            return TCL_ERROR;
        }
        if(first == vPtr->length) {
            if(RbcVectorChangeLength(vPtr, vPtr->length + 1) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        RbcReplicateValue(vPtr, first, last, value);
        Tcl_SetObjResult(interp, objv[3]);
        if(vPtr->flush) {
            RbcVectorFlushCache(vPtr);
        }
        RbcVectorUpdateClients(vPtr);
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcLengthOp --
 *
 *      Returns the length of the vector.  If a new size is given, the
 *      vector is resized to the new vector.
 *
 * Results:
 *      A standard Tcl result.  If the new length is invalid,
 *      interp->result will an error message and TCL_ERROR is returned.
 *      Otherwise interp->result will contain the length of the vector.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcLengthOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    if(objc == 3) {
    int size;

        if(Tcl_GetIntFromObj(interp, objv[2], &size) != TCL_OK) {
            return TCL_ERROR;
        }
        if(size < 0) {
            Tcl_AppendResult(interp, "bad vector size \"",
                Tcl_GetString(objv[2]), "\"", (char *)NULL);
            return TCL_ERROR;
        }
        if(RbcVectorChangeLength(vPtr, size) != TCL_OK) {
            return TCL_ERROR;
        }
        if(vPtr->flush) {
            RbcVectorFlushCache(vPtr);
        }
        RbcVectorUpdateClients(vPtr);
    }
    Tcl_SetObjResult(interp, Tcl_NewIntObj(vPtr->length));
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcMergeOp --
 *
 *      Merges the values from the given vectors to the current vector.
 *
 * Results:
 *      A standard Tcl result.  If any of the given vectors differ in size,
 *      TCL_ERROR is returned.  Otherwise TCL_OK is returned and the
 *      vector data will contain merged values of the given vectors.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcMergeOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorObject *v2Ptr;
    RbcVectorObject **vecArr;
    register RbcVectorObject **vPtrPtr;
    int refSize, length, nElem;
    register int i;
    double *valuePtr, *valueArr;

    /* Allocate an array of vector pointers of each vector to be
     * merged in the current vector.  */
    vecArr = (RbcVectorObject **) ckalloc(sizeof(RbcVectorObject *) * objc);

    /***    assert(vecArr); */
    vPtrPtr = vecArr;

    refSize = -1;
    nElem = 0;
    for(i = 2; i < objc; i++) {
        if(RbcVectorLookupName(vPtr->dataPtr, Tcl_GetStringFromObj(objv[i],
                    NULL), &v2Ptr) != TCL_OK) {
            ckfree((char *)vecArr);
            return TCL_ERROR;
        }
        /* Check that all the vectors are the same length */
        length = v2Ptr->last - v2Ptr->first + 1;
        if(refSize < 0) {
            refSize = length;
        } else if(length != refSize) {
            Tcl_AppendResult(vPtr->interp, "vectors \"", vPtr->name,
                "\" and \"", v2Ptr->name, "\" differ in length", (char *)NULL);
            ckfree((char *)vecArr);
            return TCL_ERROR;
        }
        *vPtrPtr++ = v2Ptr;
        nElem += refSize;
    }
    *vPtrPtr = NULL;

    valueArr = (double *)ckalloc(sizeof(double) * nElem);
    if(valueArr == NULL) {
        Tcl_AppendPrintfToObj(Tcl_GetObjResult(vPtr->interp),
            "not enough memory to allocate %d vector elements", nElem);
        return TCL_ERROR;
    }
    /* Merge the values from each of the vectors into the current vector */
    valuePtr = valueArr;
    for(i = 0; i < refSize; i++) {
        for(vPtrPtr = vecArr; *vPtrPtr != NULL; vPtrPtr++) {
            *valuePtr++ = (*vPtrPtr)->valueArr[i + (*vPtrPtr)->first];
        }
    }
    ckfree((char *)vecArr);
    RbcVectorReset(vPtr, valueArr, nElem, nElem, TCL_DYNAMIC);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcNormalizeOp --
 *
 *      Normalizes the vector.
 *
 * Results:
 *      A standard Tcl result.  If the density is invalid, TCL_ERROR
 *      is returned.  Otherwise TCL_OK is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcNormalizeOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    register int i;
    double range;

    RbcVectorUpdateRange(vPtr);
    range = vPtr->max - vPtr->min;
    if(objc > 2) {
    RbcVectorObject *v2Ptr;
    int isNew;
    char *string;

        string = Tcl_GetStringFromObj(objv[2], NULL);
        v2Ptr = RbcVectorCreate(vPtr->dataPtr, string, string, string, &isNew);
        if(v2Ptr == NULL) {
            return TCL_ERROR;
        }
        if(RbcVectorChangeLength(v2Ptr, vPtr->length) != TCL_OK) {
            return TCL_ERROR;
        }
        for(i = 0; i < vPtr->length; i++) {
            v2Ptr->valueArr[i] = (vPtr->valueArr[i] - vPtr->min) / range;
        }
        RbcVectorUpdateRange(v2Ptr);
        if(!isNew) {
            if(v2Ptr->flush) {
                RbcVectorFlushCache(v2Ptr);
            }
            RbcVectorUpdateClients(v2Ptr);
        }
    } else {
    double norm;
    Tcl_Obj *listObjPtr;

        listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
        for(i = 0; i < vPtr->length; i++) {
            norm = (vPtr->valueArr[i] - vPtr->min) / range;
            Tcl_ListObjAppendElement(interp, listObjPtr,
                Tcl_NewDoubleObj(norm));
        }
        Tcl_SetObjResult(interp, listObjPtr);
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcOffsetOp --
 *
 *      Queries or sets the offset of the array index from the base
 *      address of the data array of values.
 *
 * Results:
 *      A standard Tcl result.  If the source vector doesn't exist
 *      or the source list is not a valid list of numbers, TCL_ERROR
 *      returned.  Otherwise TCL_OK is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcOffsetOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    if(objc == 3) {
    int newOffset;

        if(Tcl_GetIntFromObj(interp, objv[2], &newOffset) != TCL_OK) {
            return TCL_ERROR;
        }
        vPtr->offset = newOffset;
    }
    Tcl_SetObjResult(interp, Tcl_NewIntObj(vPtr->offset));
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcPopulateOp --
 *
 *      Creates or resizes a new vector based upon the density specified.
 *
 * Results:
 *      A standard Tcl result.  If the density is invalid, TCL_ERROR
 *      is returned.  Otherwise TCL_OK is returned.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcPopulateOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorObject *v2Ptr;
    int size, density;
    int isNew;
    register int i, j;
    double slice, range;
    register double *valuePtr;
    int count;
    char *string;

    string = Tcl_GetStringFromObj(objv[2], NULL);
    v2Ptr = RbcVectorCreate(vPtr->dataPtr, string, string, string, &isNew);
    if(v2Ptr == NULL) {
        return TCL_ERROR;
    }
    if(vPtr->length == 0) {
        return TCL_OK;  /* Source vector is empty. */
    }
    if(Tcl_GetIntFromObj(interp, objv[3], &density) != TCL_OK) {
        return TCL_ERROR;
    }
    if(density < 1) {
        Tcl_AppendResult(interp, "bad density \"", Tcl_GetStringFromObj(objv[3],
                NULL), "\"", (char *)NULL);
        return TCL_ERROR;
    }
    size = (vPtr->length - 1) * (density + 1) + 1;
    if(RbcVectorChangeLength(v2Ptr, size) != TCL_OK) {
        return TCL_ERROR;
    }
    count = 0;
    valuePtr = v2Ptr->valueArr;
    for(i = 0; i < (vPtr->length - 1); i++) {
        range = vPtr->valueArr[i + 1] - vPtr->valueArr[i];
        slice = range / (double)(density + 1);
        for(j = 0; j <= density; j++) {
            *valuePtr = vPtr->valueArr[i] + (slice * (double)j);
            valuePtr++;
            count++;
        }
    }
    count++;
    *valuePtr = vPtr->valueArr[i];

    /*** assert(count == v2Ptr->length); */
    if(!isNew) {
        if(v2Ptr->flush) {
            RbcVectorFlushCache(v2Ptr);
        }
        RbcVectorUpdateClients(v2Ptr);
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcRandomOp --
 *
 *      Generates random values for the length of the vector.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcRandomOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    register int i;

    for(i = 0; i < vPtr->length; i++) {
        vPtr->valueArr[i] = Rbcdrand48();
    }
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcRangeOp --
 *
 *      Returns a Tcl list of the range of vector values specified.
 *
 * Results:
 *      A standard Tcl result.  If the given range is invalid, TCL_ERROR
 *      is returned.  Otherwise TCL_OK is returned and interp->result
 *      will contain the list of values.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcRangeOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Obj *listObjPtr;
    int first, last;
    register int i;

    if((RbcVectorGetIndex(interp, vPtr, Tcl_GetStringFromObj(objv[2], NULL),
                &first, RBC_INDEX_CHECK,
                (Rbc_VectorIndexProc **) NULL) != TCL_OK)
        || (RbcVectorGetIndex(interp, vPtr, Tcl_GetStringFromObj(objv[3], NULL),
                &last, RBC_INDEX_CHECK,
                (Rbc_VectorIndexProc **) NULL) != TCL_OK)) {
        return TCL_ERROR;
    }
    listObjPtr = Tcl_NewListObj(0, NULL);
    if(first > last) {
        /* Return the list reversed */
        for(i = last; i <= first; i++) {
            Tcl_ListObjAppendElement(interp, listObjPtr,
                Tcl_NewDoubleObj(vPtr->valueArr[i]));
        }
    } else {
        for(i = first; i <= last; i++) {
            Tcl_ListObjAppendElement(interp, listObjPtr,
                Tcl_NewDoubleObj(vPtr->valueArr[i]));
        }
    }
    Tcl_SetObjResult(interp, listObjPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcSearchOp --
 *
 *      Searchs for a value in the vector. Returns the indices of all
 *      vector elements matching a particular value.
 *
 * Results:
 *      Always returns TCL_OK.  interp->result will contain a list of
 *      the indices of array elements matching value. If no elements
 *      match, interp->result will contain the empty string.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcSearchOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    double min, max;
    register int i;
    int wantValue;
    char *string;
    Tcl_Obj *listObjPtr;

    wantValue = FALSE;
    string = Tcl_GetStringFromObj(objv[2], NULL);
    if((string[0] == '-') && (strcmp(string, "-value") == 0)) {
        wantValue = TRUE;
        objv++, objc--;
    }
    if(RbcGetDouble(interp, objv[2], &min) != TCL_OK) {
        return TCL_ERROR;
    }
    max = min;
    if((objc > 3) && (RbcGetDouble(interp, objv[3], &max) != TCL_OK)) {
        return TCL_ERROR;
    }
    if((min - max) >= DBL_EPSILON) {
        return TCL_OK;  /* Bogus range. Don't bother looking. */
    }
    listObjPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
    if(wantValue) {
        for(i = 0; i < vPtr->length; i++) {
            if(InRange(vPtr->valueArr[i], min, max)) {
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewDoubleObj(vPtr->valueArr[i]));
            }
        }
    } else {
        for(i = 0; i < vPtr->length; i++) {
            if(InRange(vPtr->valueArr[i], min, max)) {
                Tcl_ListObjAppendElement(interp, listObjPtr,
                    Tcl_NewIntObj(i + vPtr->offset));
            }
        }
    }
    Tcl_SetObjResult(interp, listObjPtr);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcSeqOp --
 *
 *      Generates a sequence of values in the vector.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcSeqOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    register int i;
    double start, finish, step;
    int fillVector;
    int nSteps;
    char *string;

    if(RbcGetDouble(interp, objv[2], &start) != TCL_OK) {
        return TCL_ERROR;
    }
    fillVector = FALSE;
    string = Tcl_GetStringFromObj(objv[3], NULL);
    if((string[0] == 'e') && (strcmp(string, "end") == 0)) {
        fillVector = TRUE;
    } else if(RbcGetDouble(interp, objv[3], &finish) != TCL_OK) {
        return TCL_ERROR;
    }
    step = 1.0;
    if((objc > 4) && (RbcGetDouble(interp, objv[4], &step) != TCL_OK)) {
        return TCL_ERROR;
    }
    if(fillVector) {
        nSteps = vPtr->length;
    } else {
        nSteps = (int)((finish - start) / step) + 1;
    }
    if(nSteps > 0) {
        if(RbcVectorChangeLength(vPtr, nSteps) != TCL_OK) {
            return TCL_ERROR;
        }
        for(i = 0; i < nSteps; i++) {
            vPtr->valueArr[i] = start + (step * (double)i);
        }
        if(vPtr->flush) {
            RbcVectorFlushCache(vPtr);
        }
        RbcVectorUpdateClients(vPtr);
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcSetOp --
 *
 *      Sets the data of the vector object from a list of values.
 *
 * Results:
 *      A standard Tcl result.  If the source vector doesn't exist
 *      or the source list is not a valid list of numbers, TCL_ERROR
 *      returned.  Otherwise TCL_OK is returned.
 *
 * Side Effects:
 *      The vector data is reset.  Clients of the vector are notified.
 *      Any cached array indices are flushed.
 *
 * -----------------------------------------------------------------------
 */
int
RbcSetOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    int result;
    RbcVectorObject *v2Ptr;
    int nElem;
    Tcl_Obj **elemObjArr;

    /* The source can be either a list of numbers or another vector.  */

    v2Ptr =
        RbcVectorParseElement((Tcl_Interp *) NULL, vPtr->dataPtr,
        Tcl_GetStringFromObj(objv[2], NULL), NULL, RBC_NS_SEARCH_BOTH);
    if(v2Ptr != NULL) {
        if(vPtr == v2Ptr) {
    RbcVectorObject *tmpPtr;
            /*
             * Source and destination vectors are the same.  Copy the
             * source first into a temporary vector to avoid memory
             * overlaps.
             */
            tmpPtr = RbcVectorNew(vPtr->dataPtr);
            result = RbcVectorDuplicate(tmpPtr, v2Ptr);
            if(result == TCL_OK) {
                result = RbcVectorDuplicate(vPtr, tmpPtr);
            }
            Rbc_VectorFree(tmpPtr);
        } else {
            result = RbcVectorDuplicate(vPtr, v2Ptr);
        }
    } else if(Tcl_ListObjGetElements(interp, objv[2], &nElem,
            &elemObjArr) == TCL_OK) {
        result = CopyList(vPtr, nElem, elemObjArr);
    } else {
        return TCL_ERROR;
    }

    if(result == TCL_OK) {
        /*
         * The vector has changed; so flush the array indices (they're
         * wrong now), find the new range of the data, and notify
         * the vector's clients that it's been modified.
         */
        if(vPtr->flush) {
            RbcVectorFlushCache(vPtr);
        }
        RbcVectorUpdateClients(vPtr);
    }
    return result;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcSortOp --
 *
 *      Sorts the vector object and any other vectors according to
 *      sorting order of the vector object.
 *
 * Results:
 *      A standard Tcl result.  If any of the auxiliary vectors are
 *      a different size than the sorted vector object, TCL_ERROR is
 *      returned.  Otherwise TCL_OK is returned.
 *
 * Side Effects:
 *      The vectors are sorted.
 *
 * -----------------------------------------------------------------------
 */
int
RbcSortOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    RbcVectorObject *v2Ptr;
    char *string;
    double *mergeArr;
    int *iArr;
    int refSize, nBytes;
    int result;
    register int i, n;

    reverse = FALSE;
    if(objc > 2) {
    int length;
        string = Tcl_GetStringFromObj(objv[2], &length);
        if(string[0] == '-') {
            if((length > 1) && (strncmp(string, "-reverse", length) == 0)) {
                reverse = TRUE;
            } else {
                Tcl_AppendResult(interp, "unknown flag \"", string,
                    "\": should be \"-reverse\"", (char *)NULL);
                return TCL_ERROR;
            }
            objc--;
            objv++;
        }
    }
    if(objc > 2) {
        iArr = SortVectors(vPtr, interp, objc - 2, objv + 2);
    } else {
        iArr = RbcVectorSortIndex(&vPtr, 1);
    }
    if(iArr == NULL) {
        return TCL_ERROR;
    }
    refSize = vPtr->length;

    /*
     * Create an array to store a copy of the current values of the
     * vector. We'll merge the values back into the vector based upon
     * the indices found in the index array.
     */
    nBytes = sizeof(double) * refSize;
    mergeArr = (double *)ckalloc(nBytes);
    memcpy((char *)mergeArr, (char *)vPtr->valueArr, nBytes);
    for(n = 0; n < refSize; n++) {
        vPtr->valueArr[n] = mergeArr[iArr[n]];
    }
    if(vPtr->flush) {
        RbcVectorFlushCache(vPtr);
    }
    RbcVectorUpdateClients(vPtr);

    /* Now sort any other vectors in the same fashion.  The vectors
     * must be the same size as the iArr though.  */
    result = TCL_ERROR;
    for(i = 2; i < objc; i++) {
        if(RbcVectorLookupName(vPtr->dataPtr, Tcl_GetString(objv[i]),
                &v2Ptr) != TCL_OK) {
            goto error;
        }
        if(v2Ptr->length != refSize) {
            Tcl_AppendResult(interp, "vector \"", v2Ptr->name,
                "\" is not the same size as \"", vPtr->name, "\"",
                (char *)NULL);
            goto error;
        }
        memcpy((char *)mergeArr, (char *)v2Ptr->valueArr, nBytes);
        for(n = 0; n < refSize; n++) {
            v2Ptr->valueArr[n] = mergeArr[iArr[n]];
        }
        RbcVectorUpdateClients(v2Ptr);
        if(v2Ptr->flush) {
            RbcVectorFlushCache(v2Ptr);
        }
    }
    result = TCL_OK;
  error:
    ckfree((char *)mergeArr);
    ckfree((char *)iArr);
    return result;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcSplitOp --
 *
 *      Copies the values from the vector evens into one of more
 *      vectors.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcSplitOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    int nVectors;

    nVectors = objc - 2;
    if((vPtr->length % nVectors) != 0) {
        Tcl_AppendPrintfToObj(Tcl_GetObjResult(interp),
            "can't split vector \"%s\" into %d even parts.",
            vPtr->name, nVectors);
        return TCL_ERROR;
    }
    if(nVectors > 0) {
    RbcVectorObject *v2Ptr;
    char *string;              /* Name of vector. */
    int i, j, k;
    int oldSize, newSize, extra, isNew;

        extra = vPtr->length / nVectors;
        for(i = 0; i < nVectors; i++) {
            string = Tcl_GetStringFromObj(objv[i + 2], NULL);
            v2Ptr =
                RbcVectorCreate(vPtr->dataPtr, string, string, string, &isNew);
            oldSize = v2Ptr->length;
            newSize = oldSize + extra;
            if(RbcVectorChangeLength(v2Ptr, newSize) != TCL_OK) {
                return TCL_ERROR;
            }
            for(j = i, k = oldSize; j < vPtr->length; j += nVectors, k++) {
                v2Ptr->valueArr[k] = vPtr->valueArr[j];
            }
            RbcVectorUpdateClients(v2Ptr);
            if(v2Ptr->flush) {
                RbcVectorFlushCache(v2Ptr);
            }
        }
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * RbcVariableOp --
 *
 *      Renames the variable associated with the vector
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
int
RbcVariableOp(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const objv[])
{
    if(objc > 2) {
        if(RbcVectorMapVariable(interp, vPtr, Tcl_GetString(objv[2])) != TCL_OK) {
            return TCL_ERROR;
        }
    }
    if(vPtr->arrayName != NULL) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(vPtr->arrayName, -1));
    }
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * AppendVector --
 *
 *      Appends a vector to the end of another vector
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static int
AppendVector(
    RbcVectorObject * destPtr,
    RbcVectorObject * srcPtr)
{
int nBytes;
int oldSize, newSize;

    oldSize = destPtr->length;
    newSize = oldSize + srcPtr->last - srcPtr->first + 1;
    if(RbcVectorChangeLength(destPtr, newSize) != TCL_OK) {
        return TCL_ERROR;
    }
    nBytes = (newSize - oldSize) * sizeof(double);
    memcpy((char *)(destPtr->valueArr + oldSize), (srcPtr->valueArr
            + srcPtr->first), nBytes);
    destPtr->notifyFlags |= RBC_UPDATE_RANGE;
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * AppendList --
 *
 *      Appends a list to the end of another list
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static int
AppendList(
    RbcVectorObject * vPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    int count;
    register int i;
    double value;
    int oldSize;

    oldSize = vPtr->length;
    if(RbcVectorChangeLength(vPtr, vPtr->length + objc) != TCL_OK) {
        return TCL_ERROR;
    }
    count = oldSize;
    for(i = 0; i < objc; i++) {
        if(RbcGetDouble(vPtr->interp, objv[i], &value) != TCL_OK) {
            RbcVectorChangeLength(vPtr, count);
            return TCL_ERROR;
        }
        vPtr->valueArr[count++] = value;
    }
    vPtr->notifyFlags |= RBC_UPDATE_RANGE;
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------------
 *
 * GetBinaryFormat
 *
 *      Translates a format string into a native type.  Formats may be
 *      as follows.
 *
 *            signed     i1, i2, i4, i8
 *            unsigned   u1, u2, u4, u8
 *            real       r4, r8, r16
 *
 *      But there must be a corresponding native type.  For example,
 *      this for reading 2-byte binary integers from an instrument and
 *      converting them to unsigned shorts or ints.
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * -----------------------------------------------------------------------
 */
static enum NativeFormats
GetBinaryFormat(
    Tcl_Interp * interp,
    char *string,
    int *sizePtr)
{
    char c;

    c = tolower(string[0]);
    if(Tcl_GetInt(interp, string + 1, sizePtr) != TCL_OK) {
        Tcl_AppendResult(interp, "unknown binary format \"", string,
            "\": incorrect byte size", (char *)NULL);
        return FMT_UNKNOWN;
    }
    switch (c) {
    case 'r':
        if(*sizePtr == sizeof(double)) {
            return FMT_DOUBLE;
        } else if(*sizePtr == sizeof(float)) {
            return FMT_FLOAT;
        }
        break;

    case 'i':
        if(*sizePtr == sizeof(char)) {
            return FMT_CHAR;
        } else if(*sizePtr == sizeof(int)) {
            return FMT_INT;
        } else if(*sizePtr == sizeof(long)) {
            return FMT_LONG;
        } else if(*sizePtr == sizeof(short)) {
            return FMT_SHORT;
        }
        break;

    case 'u':
        if(*sizePtr == sizeof(unsigned char)) {
            return FMT_UCHAR;
        } else if(*sizePtr == sizeof(unsigned int)) {
            return FMT_UINT;
        } else if(*sizePtr == sizeof(unsigned long)) {
            return FMT_ULONG;
        } else if(*sizePtr == sizeof(unsigned short)) {
            return FMT_USHORT;
        }
        break;

    default:
        Tcl_AppendResult(interp, "unknown binary format \"", string,
            "\": should be either i#, r#, u# (where # is size in bytes)",
            (char *)NULL);
        return FMT_UNKNOWN;
    }
    Tcl_AppendResult(interp, "can't handle format \"", string, "\"",
        (char *)NULL);
    return FMT_UNKNOWN;
}

/*
 *--------------------------------------------------------------
 *
 * CopyValues --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
CopyValues(
    RbcVectorObject * vPtr,
    char *byteArr,
    enum NativeFormats fmt,
    int size,
    int length,
    int swap,
    int *indexPtr)
{
    register int i, n;
    int newSize;

    if((swap) && (size > 1)) {
    int nBytes = size * length;
    register unsigned char *p;
    register int left, right;

        for(i = 0; i < nBytes; i += size) {
            p = (unsigned char *)(byteArr + i);
            for(left = 0, right = size - 1; left < right; left++, right--) {
                p[left] ^= p[right];
                p[right] ^= p[left];
                p[left] ^= p[right];
            }
        }
    }
    newSize = *indexPtr + length;
    if(newSize > vPtr->length) {
        if(RbcVectorChangeLength(vPtr, newSize) != TCL_OK) {
            return TCL_ERROR;
        }
    }
#define CopyArrayToVector(vPtr, arr) \
	    for (i = 0, n = *indexPtr; i < length; i++, n++) { \
		(vPtr)->valueArr[n] = (double)(arr)[i]; \
	    }

    switch (fmt) {
    case FMT_CHAR:
        CopyArrayToVector(vPtr, (char *)byteArr);
        break;

    case FMT_UCHAR:
        CopyArrayToVector(vPtr, (unsigned char *)byteArr);
        break;

    case FMT_INT:
        CopyArrayToVector(vPtr, (int *)byteArr);
        break;

    case FMT_UINT:
        CopyArrayToVector(vPtr, (unsigned int *)byteArr);
        break;

    case FMT_LONG:
        CopyArrayToVector(vPtr, (long *)byteArr);
        break;

    case FMT_ULONG:
        CopyArrayToVector(vPtr, (unsigned long *)byteArr);
        break;

    case FMT_SHORT:
        CopyArrayToVector(vPtr, (short int *)byteArr);
        break;

    case FMT_USHORT:
        CopyArrayToVector(vPtr, (unsigned short int *)byteArr);
        break;

    case FMT_FLOAT:
        CopyArrayToVector(vPtr, (float *)byteArr);
        break;

    case FMT_DOUBLE:
        CopyArrayToVector(vPtr, (double *)byteArr);
        break;

    case FMT_UNKNOWN:
        break;
    }
    *indexPtr += length;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InRange --
 *
 *      Determines if a value lies within a given range.
 *
 *      The value is normalized and compared against the interval
 *      [0..1], where 0.0 is the minimum and 1.0 is the maximum.
 *      DBL_EPSILON is the smallest number that can be represented
 *      on the host machine, such that (1.0 + epsilon) != 1.0.
 *
 *      Please note, min cannot be greater than max.
 *
 * Results:
 *      If the value is within of the interval [min..max], 1 is
 *      returned; 0 otherwise.
 *
 * Side effects:
 *      TODO: Side Effects
 *
 * ----------------------------------------------------------------------
 */
static int
InRange(
    double value,
    double min,
    double max)
{
    double range;

    range = max - min;
    if(range < DBL_EPSILON) {
        return (FABS(max - value) < DBL_EPSILON);
    } else {
    double norm;

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

/*
 *--------------------------------------------------------------
 *
 * CopyList --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
CopyList(
    RbcVectorObject * vPtr,
    int objc,
    Tcl_Obj * const objv[])
{
    register int i;
    double value;

    if(RbcVectorChangeLength(vPtr, objc) != TCL_OK) {
        return TCL_ERROR;
    }
    for(i = 0; i < objc; i++) {
        if(RbcGetDouble(vPtr->interp, objv[i], &value) != TCL_OK) {
            RbcVectorChangeLength(vPtr, i);
            return TCL_ERROR;
        }
        vPtr->valueArr[i] = value;
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RbcVectorSortIndex --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
int *
RbcVectorSortIndex(
    RbcVectorObject ** vPtrPtr,
    int nVectors)
{
    int *indexArr;
    register int i;
    RbcVectorObject *vPtr = *vPtrPtr;
    int length;

    length = vPtr->last - vPtr->first + 1;
    indexArr = (int *)ckalloc(sizeof(int) * length);
    for(i = vPtr->first; i <= vPtr->last; i++) {
        indexArr[i] = i;
    }
    sortVectorArr = vPtrPtr;
    nSortVectors = nVectors;
    qsort((char *)indexArr, length, sizeof(int),
        (QSortCompareProc *) CompareVectors);
    return indexArr;
}

/*
 *--------------------------------------------------------------
 *
 * SortVectors --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int *
SortVectors(
    RbcVectorObject * vPtr,
    Tcl_Interp * interp,
    int objc,
    Tcl_Obj * const *objv)
{
    RbcVectorObject **vPtrArray, *v2Ptr;
    int *iArr;
    register int i;

    vPtrArray =
        (RbcVectorObject **) ckalloc(sizeof(RbcVectorObject *) * (objc + 1));
    vPtrArray[0] = vPtr;
    iArr = NULL;
    for(i = 0; i < objc; i++) {
        if(RbcVectorLookupName(vPtr->dataPtr, Tcl_GetStringFromObj(objv[i],
                    NULL), &v2Ptr) != TCL_OK) {
            goto error;
        }
        if(v2Ptr->length != vPtr->length) {
            Tcl_AppendResult(interp, "vector \"", v2Ptr->name,
                "\" is not the same size as \"", vPtr->name, "\"",
                (char *)NULL);
            goto error;
        }
        vPtrArray[i + 1] = v2Ptr;
    }
    iArr = RbcVectorSortIndex(vPtrArray, objc + 1);
  error:
    ckfree((char *)vPtrArray);
    return iArr;
}

/*
 *--------------------------------------------------------------
 *
 * CompareVectors --
 *
 *      TODO: Description
 *
 * Results:
 *      TODO: Results
 *
 * Side effects:
 *      TODO: Side Effects
 *
 *--------------------------------------------------------------
 */
static int
CompareVectors(
    void *a,
    void *b)
{
    double delta;
    int i;
    int sign;
    register RbcVectorObject *vPtr;

    sign = (reverse) ? -1 : 1;
    for(i = 0; i < nSortVectors; i++) {
        vPtr = sortVectorArr[i];
        delta = vPtr->valueArr[*(int *)a] - vPtr->valueArr[*(int *)b];
        if(delta < 0.0) {
            return (-1 * sign);
        } else if(delta > 0.0) {
            return (1 * sign);
        }
    }
    return 0;
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoWidget.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
* tkoWidget.h --
*
*    This file contains the tko widget class.
*
* Copyright (c) 2019 Rene Zaumseil
*
*/
#include "tcl.h"
#include "tclOO.h"
#include "tk.h"
#include "tkInt.h"

#include "tkoWidget.h"

/*
* Widget structure data used in objects.
*/
typedef struct tkoWidget {
    Tcl_Interp *interp;        /* Interpreter associated with widget. */
    Tcl_Object object;         /* our own object */
    Tk_Window tkWin;           /* Window that embodies the canvas. NULL means
                                * that the window has been destroyed but the
                                * data structures haven't yet been cleaned
                                * up.*/
    Tcl_Obj *myCmd;            /* Objects "my" command. Needed to call internal methods. */
    Tcl_Command widgetCmd;     /* Token for canvas's widget command. */
    Tcl_Obj *optionsArray;     /* Name of option array variable */
    Tcl_HashTable optionsTable; /* Hash table containing all used options */
} tkoWidget;

/*
 * Widget option.
 */
typedef struct WidgetOption {
    Tcl_Obj *option;           /* Name of option */
    Tcl_Obj *dbname;           /* Database name or name of synonym option */
    Tcl_Obj *dbclass;          /* Class name or NULL for synonym options */
    Tcl_Obj *defvalue;         /* Default value from initialization */
    Tcl_Obj *value;            /* Contain last known value of option */
    int flags;				   /* see flags in struct tkoWidgetOptionDefine */
} WidgetOption;

/*
 * Static tcl objects.
 */
Tk_Uid TkoUid_class = NULL;
tkoObj TkoObj =
    { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
/*
* Methods
*/
static int WidgetConstructor(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int WidgetDestructor(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int WidgetMethod_cget(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int WidgetMethod_configure(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);
static int WidgetMethod_tko_configure(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);

/*
 * Functions
 */
static char *WidgetOptionTrace(
    ClientData clientData,
    Tcl_Interp * interp,
    const char *name1,
    const char *name2,
    int flags);
static void WidgetOptionDelEntry(
    Tcl_HashEntry * entry);
static void WidgetEventProc(
    ClientData clientData,
    XEvent * eventPtr);
static int WidgetOptionAdd(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option,
    Tcl_Obj * dbname,
    Tcl_Obj * dbclass,
    Tcl_Obj * defvalue,
    Tcl_Obj * flags,
    Tcl_Obj * value,
    int initmode);
static int WidgetOptionConfigure(
    Tcl_Interp * interp,
    tkoWidget * widget,
    int objc,
    Tcl_Obj * const objv[]);
static int WidgetOptionDel(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option);
static int WidgetOptionGet(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option);
static int WidgetOptionSet(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option,
    Tcl_Obj * value);
static void WidgetMetaDestroy(
    tkoWidget * widget);
static void WidgetMetaDelete(
	ClientData clientData);
static int WidgetMethod_(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[]);

/*
 * tkoWidgetMeta --
 */
Tcl_ObjectMetadataType tkoWidgetMeta = {
    TCL_OO_METADATA_VERSION_CURRENT,
    "tkoWidgetMeta",
    WidgetMetaDelete,
    NULL
};

/*
 * widgetMethods --
 *
 */
static Tcl_MethodType widgetMethods[] = {
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, WidgetConstructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, NULL, WidgetDestructor, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "cget", WidgetMethod_cget, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "configure", WidgetMethod_configure, NULL,
            NULL},
    {-1, NULL, NULL, NULL, NULL},
    {TCL_OO_METHOD_VERSION_CURRENT, "_tko_configure",
            WidgetMethod_tko_configure, NULL, NULL},
    {-1, NULL, NULL, NULL, NULL}
};

/*
 * TkoWidgetWindow --
 *
 * Results:
 *
 * Side effects:
 */
Tk_Window *
TkoWidgetWindow(
    Tcl_Object object)
{
tkoWidget *widget = (tkoWidget *) Tcl_ObjectGetMetadata(object, &tkoWidgetMeta);
    if(widget)
        return &widget->tkWin;
    return NULL;
}

/*
 * TkoWidgetOptionVar --
 *
 * Results:
 *
 * Side effects:
 */
Tcl_Obj *
TkoWidgetOptionVar(
    Tcl_Object object)
{
tkoWidget *widget = (tkoWidget *) Tcl_ObjectGetMetadata(object, &tkoWidgetMeta);
    if(widget)
        return widget->optionsArray;
    return NULL;
}

/*
 * TkoWidgetClassDefine --
 *
 * Results:
 *
 * Side effects:
 */
int
TkoWidgetClassDefine(
    Tcl_Interp * interp,
    Tcl_Class clazz,
    Tcl_Obj * classname,
    const Tcl_MethodType * methods,
    tkoWidgetOptionDefine * options)
{
    Tcl_Obj *listPtr;
    int i;
    Tcl_Obj *option;
    Tcl_MethodType *methodPtr;
    Tcl_Obj *myObjv[6];
    Tcl_Obj *retPtr;
    Tcl_Obj *tmpObj;

    if(classname == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("missing class name"));
        return TCL_ERROR;
    }
    /*
     * Add methods
     */
    if(methods) {
		/* constructor */
        if(methods[0].name == NULL && methods[0].callProc) {
            Tcl_ClassSetConstructor(interp, clazz,
                Tcl_NewMethod(interp, clazz, NULL, 1, &methods[0], NULL));
        }
		/* destructor */
        if(methods[1].name == NULL && methods[1].callProc) {
            Tcl_ClassSetDestructor(interp, clazz,
                Tcl_NewMethod(interp, clazz, NULL, 1, &methods[1], NULL));
        }
		/* public */
        for(i = 2; methods[i].name != NULL; i++) {
            tmpObj = Tcl_NewStringObj(methods[i].name, -1);
            Tcl_IncrRefCount(tmpObj);
            Tcl_NewMethod(interp, clazz, tmpObj, 1, &methods[i], NULL);
            Tcl_DecrRefCount(tmpObj);
        }
        i++;
		/* private */
        for(; methods[i].name != NULL; i++) {
            tmpObj = Tcl_NewStringObj(methods[i].name, -1);
            Tcl_IncrRefCount(tmpObj);
            Tcl_NewMethod(interp, clazz, tmpObj, 0, &methods[i], NULL);
            Tcl_DecrRefCount(tmpObj);
        }
    }
    /*
     *Add options
     */
    if(options) {
		/*
		 * Option definitions will be saved in the tko::options array variable.
		 * All options of a class are saved as a list under tko::option(classname)
		 * Here we ensure this variable exists and is a proper list.
		 */
        retPtr =
            Tcl_ObjGetVar2(interp, TkoObj.tko_options, classname,
            TCL_GLOBAL_ONLY);
        if(retPtr == NULL) {
            retPtr = Tcl_NewObj();
			Tcl_IncrRefCount(retPtr);
        } else {
            if(Tcl_ListObjLength(interp, retPtr, &i) != TCL_OK) {
                Tcl_SetObjResult(interp,
                    Tcl_ObjPrintf("::tko::options(%s) variable is not list",
                        Tcl_GetString(classname)));
                return TCL_ERROR;
            }
			retPtr = Tcl_DuplicateObj(retPtr);
			Tcl_IncrRefCount(retPtr);
        }
		/* Loop over all option definitions */
        for(i = 0;; i++) {
            if(options[i].option == NULL)
                break;  /* end of options */
            if(options[i].dbname == NULL) {
                Tcl_SetObjResult(interp,
                    Tcl_ObjPrintf("wrong option definition: %d", i));
                goto error;
            }
            listPtr = Tcl_NewObj();
            option = Tcl_NewStringObj(options[i].option, -1);
            Tcl_IncrRefCount(option);
            Tcl_ListObjAppendElement(interp, listPtr, option);
            Tcl_ListObjAppendElement(interp, listPtr,
                Tcl_NewStringObj(options[i].dbname, -1));
            /* synonym option, ignore rest */
            if(options[i].dbclass == NULL) {
                Tcl_ListObjAppendElement(interp, retPtr, listPtr);
				Tcl_DecrRefCount(option);
                continue;
            }
            /* normal option */
            Tcl_ListObjAppendElement(interp, listPtr,
                Tcl_NewStringObj(options[i].dbclass, -1));
            if(options[i].defvalue == NULL) {
                Tcl_ListObjAppendElement(interp, listPtr, TkoObj.empty);
            } else {
                Tcl_ListObjAppendElement(interp, listPtr,
                    Tcl_NewStringObj(options[i].defvalue, -1));
            }
            Tcl_ListObjAppendElement(interp, listPtr,
                Tcl_NewIntObj(options[i].flags));
            Tcl_ListObjAppendElement(interp, retPtr, listPtr);
			/*
			 * Now we create the necessary -option method if provided.
			 * If given we use the code provided in the proc body.
			 * Or we create the -option method with the given method.
			 * Or we use the internal implementation of a given type.
			 * If none of the above are provided it is up to the caller
			 * to create the necessary -option method.
			 */
            if(options[i].proc != NULL) {
                myObjv[0] = TkoObj.oo_define;
                myObjv[1] = classname;
                myObjv[2] = TkoObj.method;
                myObjv[3] = option;
                myObjv[4] = TkoObj.empty;
                myObjv[5] = Tcl_NewStringObj(options[i].proc, -1);
                Tcl_IncrRefCount(myObjv[5]);
                if(Tcl_EvalObjv(interp, 6, myObjv, TCL_EVAL_GLOBAL) != TCL_OK) {
                    Tcl_DecrRefCount(myObjv[5]);
					Tcl_DecrRefCount(option);
                    goto error;
                }
                Tcl_DecrRefCount(myObjv[5]);
            } else if(options[i].method != NULL) {
                methodPtr = (Tcl_MethodType *) ckalloc(sizeof(Tcl_MethodType));
                methodPtr->version = TCL_OO_METHOD_VERSION_CURRENT;
                methodPtr->name = options[i].option;
                methodPtr->callProc = options[i].method;
                methodPtr->deleteProc = NULL;
                methodPtr->cloneProc = NULL;
                Tcl_NewMethod(interp, clazz, option, 0, methodPtr, NULL);
            } else if(options[i].type >= 0) {
				if (options[i].optionPtr == NULL) {
					options[i].optionPtr = option;
					Tcl_IncrRefCount(option);
				}
                methodPtr = (Tcl_MethodType *) ckalloc(sizeof(Tcl_MethodType));
                methodPtr->version = TCL_OO_METHOD_VERSION_CURRENT;
                methodPtr->name = options[i].option;
                methodPtr->callProc = WidgetMethod_;
                methodPtr->deleteProc = NULL;
                methodPtr->cloneProc = NULL;
                Tcl_NewMethod(interp, clazz, option, 0, methodPtr,
                    (ClientData) & options[i]);
            }
			Tcl_DecrRefCount(option);
        }
        Tcl_ObjSetVar2(interp, TkoObj.tko_options, classname, retPtr,
            TCL_GLOBAL_ONLY);
        Tcl_SetObjResult(interp, retPtr);
    }
    return TCL_OK;
  error:
    Tcl_DecrRefCount(retPtr);
    return TCL_ERROR;
}

/*
 * Tko_Init --
 *
 * Results:
 *
 * Side effects:
 */
int
Tko_Init(
    Tcl_Interp * interp /* Tcl interpreter. */)
{             
    /* Needed oo extension */
    if(Tcl_OOInitStubs(interp) == NULL) {
        return TCL_ERROR;
    }

    if(Tko_WidgetInit(interp) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tko_FrameInit(interp) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tko_VectorInit(interp) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tko_GraphInit(interp) != TCL_OK) {
        return TCL_ERROR;
    }
    if(Tko_PathInit(interp) != TCL_OK) {
        return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * Tko_WidgetInit --
 *
 * Results:
 *
 * Side effects:
 */
int
Tko_WidgetInit(
    Tcl_Interp * interp /* Tcl interpreter. */)
{             
Tcl_Class clazz;
Tcl_Object object;

    /* Create class like tk command and remove oo functions from widget commands */
static const char *initScript =
    "namespace eval ::tko {variable options}\n"
    "array set ::tko::options {}\n"
    "::oo::class create ::tko::widget {\n"
    " variable tko\n"
    " self unexport new destroy\n"
    " unexport new create destroy\n"
    "}\n"
	"set ::tko::unknown [list self method unknown args {\n"
    " if {[set w [lindex $args 0]] eq {}} {return -code error \"wrong # args: should be \\\"[self] pathName ?-option value ...?\\\"\"}\n"
    " uplevel #0 [list [self] create $w {} [lrange $args 1 end]]\n"
    " $w configure init\n"
    " return $w\n"
    "}]";
    /*
     * Internal variables and constants.
     */
    TkoUid_class = Tk_GetUid("-class");
    if(TkoObj.empty == NULL) {
        Tcl_IncrRefCount((TkoObj.empty = Tcl_NewStringObj("", -1)));
        Tcl_IncrRefCount((TkoObj.point = Tcl_NewStringObj(".", -1)));
        Tcl_IncrRefCount((TkoObj.next = Tcl_NewStringObj("next", -1)));
        Tcl_IncrRefCount((TkoObj.uplevel = Tcl_NewStringObj("::uplevel", -1)));
        Tcl_IncrRefCount((TkoObj.oo_define =
                Tcl_NewStringObj("::oo::define", -1)));
        Tcl_IncrRefCount((TkoObj.oo_objdefine =
                Tcl_NewStringObj("::oo::objdefine", -1)));
        Tcl_IncrRefCount((TkoObj.method = Tcl_NewStringObj("method", -1)));
        Tcl_IncrRefCount((TkoObj._tko_configure =
                Tcl_NewStringObj("_tko_configure", -1)));
        Tcl_IncrRefCount((TkoObj.tko = Tcl_NewStringObj("::tko", -1)));
        Tcl_IncrRefCount((TkoObj.tko_options =
                Tcl_NewStringObj("::tko::options", -1)));
        Tcl_IncrRefCount((TkoObj.lsort = Tcl_NewStringObj("::lsort", -1)));
        Tcl_IncrRefCount((TkoObj.tko_widget =
                Tcl_NewStringObj("::tko::widget", -1)));
        Tcl_IncrRefCount((TkoObj.tko_frame =
                Tcl_NewStringObj("::tko::frame", -1)));
        Tcl_IncrRefCount((TkoObj.tko_labelframe =
                Tcl_NewStringObj("::tko::labelframe", -1)));
        Tcl_IncrRefCount((TkoObj.tko_toplevel =
                Tcl_NewStringObj("::tko::toplevel", -1)));
        Tcl_IncrRefCount((TkoObj.path = Tcl_NewStringObj("::path", -1)));
        Tcl_IncrRefCount((TkoObj.graph = Tcl_NewStringObj("::graph", -1)));
        Tcl_IncrRefCount((TkoObj._screen = Tcl_NewStringObj("-screen", -1)));
        Tcl_IncrRefCount((TkoObj._labelwidget =
                Tcl_NewStringObj("-labelwidget", -1)));
        Tcl_IncrRefCount((TkoObj._0 = Tcl_NewIntObj(0)));
        Tcl_IncrRefCount((TkoObj._1 = Tcl_NewIntObj(1)));
    }

    /* Create widget class. */
    if(Tcl_Eval(interp, initScript) != TCL_OK) {
        return TCL_ERROR;
    }
    /* Get class object */
    if((object = Tcl_GetObjectFromObj(interp, TkoObj.tko_widget)) == NULL
        || (clazz = Tcl_GetObjectAsClass(object)) == NULL) {
        return TCL_ERROR;
    }
    /*
     * Add methods and options
     */
    if(TkoWidgetClassDefine(interp, clazz, Tcl_GetObjectName(interp, object),
            widgetMethods, NULL) != TCL_OK) {
        return TCL_ERROR;
    }

    return TCL_OK;
}

/*
 * WidgetConstructor --
 *
 * class create path optiondefs optionargs
 * -screen ""	-- special arg to place toplevel widgets
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetConstructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    tkoWidget *widget;
    Tk_Window tkWin;
    Tcl_Namespace *nsPtr;
    Tcl_Obj *argPtr;
    int argSize;
    Tcl_Obj **optionObjv;
    int optionObjc;
    Tcl_Obj **argObjv;
    int argObjc;
    int i;
    Tcl_Obj *dbclass;
    Tcl_Obj *defvalue;
    Tcl_Obj *flags;
    Tcl_Obj *value;
    const char *screenName = NULL;
    Tcl_Obj *win;
    char *ch = NULL;
    int length;

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL) {
        return TCL_ERROR;
    }
    /* Check objv[] arguments: ... optionlist arglist */
    if(objc - Tcl_ObjectContextSkippedArgs(context) != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "optionlist arglist");
        return TCL_ERROR;
    }
    /* check arguments */
    if(Tcl_ListObjGetElements(interp, objv[objc - 2], &optionObjc,
            &optionObjv) != TCL_OK) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("could not get list of options"));
        return TCL_ERROR;
    }
    argPtr = objv[objc - 1];
    if(Tcl_DictObjSize(interp, argPtr, &argSize) != TCL_OK) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("could not get arglist"));
        return TCL_ERROR;
    }
    /* Check on -screen option indicating creation of toplevel window
     */
    Tcl_DictObjGet(interp, argPtr, TkoObj._screen, &value);
    if(value) {
        for(i = 0; i < optionObjc; i++) {
            Tcl_ListObjGetElements(interp, optionObjv[i], &argObjc, &argObjv);
            if(strcmp(Tcl_GetString(argObjv[0]), "-screen") == 0) {
                screenName = Tcl_GetString(value);
                break;
            }
        }
    }
    /* check widget name */
    if((win = Tcl_GetObjectName(interp, object)) == NULL
        || (ch = TclGetStringFromObj(win, &length)) == NULL
        || length < 4 || ch[0] != ':' || ch[1] != ':' || ch[2] != '.') {
		if (ch) {
			Tcl_SetObjResult(interp, Tcl_ObjPrintf("no pathName"));
		}
		else {
			Tcl_SetObjResult(interp, Tcl_ObjPrintf("wrong pathName: %s", ch));
		}
        return TCL_ERROR;
    }
    tkWin =
        Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp), &ch[2],
        screenName);
    if(tkWin == NULL) {
        return TCL_ERROR;
    }
    Tk_MakeWindowExist(tkWin);
    widget = (tkoWidget *)ckalloc(sizeof(tkoWidget));
    widget->interp = interp;
    widget->object = object;
    widget->tkWin = tkWin;
    widget->widgetCmd = Tcl_GetObjectCommand(object);
    Tcl_InitHashTable(&widget->optionsTable, TCL_ONE_WORD_KEYS);
    widget->optionsArray = NULL;
    /* Create option array variable */
    nsPtr = Tcl_GetObjectNamespace(object);
    widget->optionsArray = Tcl_NewStringObj(nsPtr->fullName, -1);
    Tcl_IncrRefCount(widget->optionsArray);
    Tcl_AppendToObj(widget->optionsArray, "::tko", -1);
    /* set tko(.) to name of widget */
    win = Tcl_NewStringObj(&ch[2], length - 2);
    Tcl_IncrRefCount(win);
    if(Tcl_ObjSetVar2(interp, widget->optionsArray, TkoObj.point, win,
            TCL_GLOBAL_ONLY) == NULL) {
        Tcl_DecrRefCount(win);
        goto error;
    }
    Tcl_DecrRefCount(win);
    /* Create my command */
    widget->myCmd = Tcl_NewStringObj(nsPtr->fullName, -1);
    Tcl_IncrRefCount(widget->myCmd);
    Tcl_AppendToObj(widget->myCmd, "::my", -1);

    Tcl_ObjectSetMetadata(object, &tkoWidgetMeta, (ClientData) widget);
    /*
     * Add options
     */
    for(i = 0; i < optionObjc; i++) {
        Tcl_ListObjGetElements(interp, optionObjv[i], &argObjc, &argObjv);
        dbclass = defvalue = flags = value = NULL;
        switch (argObjc) {
        case 2:
            break;
        case 3:
            dbclass = argObjv[2];
            break;
        case 4:
            dbclass = argObjv[2];
            defvalue = argObjv[3];
            break;
        case 5:
            dbclass = argObjv[2];
            defvalue = argObjv[3];
            flags = argObjv[4];
            break;
        default:
            Tcl_SetObjResult(interp, Tcl_ObjPrintf("wrong option def: %s",
                    Tcl_GetString(optionObjv[i])));
            goto error;
        }
        Tcl_DictObjGet(interp, argPtr, argObjv[0], &value);
        if(value) {
            Tcl_IncrRefCount(value);
            Tcl_DictObjRemove(interp, argPtr, argObjv[0]);
            argSize--;
        }
        if(WidgetOptionAdd(interp, widget, argObjv[0], argObjv[1],
                dbclass, defvalue, flags, value, 1) != TCL_OK) {
            goto error;
        }
    }
    if(argSize) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("unknown options: %s",
                Tcl_GetString(argPtr)));
        goto error;
    }

    Tcl_TraceVar2(interp, Tcl_GetString(widget->optionsArray), NULL,
        TCL_TRACE_WRITES | TCL_TRACE_RESULT_OBJECT, WidgetOptionTrace, widget);

    Tk_CreateEventHandler(tkWin, StructureNotifyMask,
        WidgetEventProc, (ClientData) widget);

    return TCL_OK;

  error:
    Tcl_DeleteCommandFromToken(interp, Tcl_GetObjectCommand(object));
    return TCL_ERROR;
}

/*
 * WidgetDestructor --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetDestructor(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    tkoWidget *widget;

    /* Get current object. Should not fail? */
    if((object = Tcl_ObjectContextObject(context)) == NULL)
        return TCL_ERROR;
    if((widget =
            (tkoWidget *) Tcl_ObjectGetMetadata(object,
                &tkoWidgetMeta)) == NULL)
        return TCL_ERROR;
    Tcl_Preserve(widget);
    if(widget->tkWin) {
        Tk_DeleteEventHandler(widget->tkWin, StructureNotifyMask,
            WidgetEventProc, (ClientData) widget);
        Tk_DestroyWindow(widget->tkWin);
        widget->tkWin = NULL;
    }
    Tcl_ObjectSetMetadata(object, &tkoWidgetMeta, NULL);
    Tcl_Release(widget);
    return TCL_OK;
}

/*
 * WidgetMetaDestroy --
 *
 * Results:
 *
 * Side effects:
 */
static void
WidgetMetaDestroy(
    tkoWidget * widget)
{
Tcl_HashSearch search;
Tcl_HashEntry *entryPtr;

    entryPtr = Tcl_FirstHashEntry(&widget->optionsTable, &search);
    while(entryPtr != NULL) {
        WidgetOptionDelEntry(entryPtr);
        entryPtr = Tcl_NextHashEntry(&search);
    }
    Tcl_DeleteHashTable(&widget->optionsTable);
    if(widget->optionsArray != NULL) {
        Tcl_DecrRefCount((widget->optionsArray));
        widget->optionsArray = NULL;
    }
    if(widget->myCmd) {
        Tcl_DecrRefCount(widget->myCmd);
        widget->myCmd = NULL;
    }
    ckfree(widget);
}

/*
* WidgetEventProc --
*
*    This function is invoked by the Tk dispatcher for various events on
*    canvases.
*
* Results:
*    None.
*
* Side effects:
*    When the window gets deleted, internal structures get cleaned up.
*    When it gets exposed, it is redisplayed.
*/
static void
WidgetEventProc(
    ClientData clientData,     /* Information about window. */
    XEvent * eventPtr)
{              /* Information about event. */
tkoWidget *widget = (tkoWidget *) clientData;

    if(eventPtr->type == DestroyNotify) {
        if(widget->tkWin) {
            Tk_DeleteEventHandler(widget->tkWin, StructureNotifyMask,
                WidgetEventProc, widget);
            Tk_DestroyWindow(widget->tkWin);
            widget->tkWin = NULL;
            Tcl_DeleteCommandFromToken(widget->interp, widget->widgetCmd);
        }
    }
}

/*
 * WidgetMethod_cget --
 *
 * cget "-option"
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetMethod_cget(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    Tcl_Object object;
    tkoWidget *widget;         /* widget. */
    int skip;

    if((object = Tcl_ObjectContextObject(context)) == NULL)
        return TCL_ERROR;
    if((widget =
            (tkoWidget *) Tcl_ObjectGetMetadata(object,
                &tkoWidgetMeta)) == NULL)
        return TCL_ERROR;
    skip = Tcl_ObjectContextSkippedArgs(context);

    if(objc - skip != 1) {
        Tcl_WrongNumArgs(interp, skip, objv, "option");
        return TCL_ERROR;
    }
    return WidgetOptionGet(interp, widget, objv[skip]);
}

/*
 * WidgetMethod_configure --
 *
 * configure
 * configure "-option"
 * configure "-option value .."
 * configure "add option dbname dbclass ?default?"
 * configure "del option"
 * configure "after"
 *
 * set tk(-option) -> WidgetTraceOption() -> my -option $v ..
 * Results:
 *
 * Side effects:
 */
static int
WidgetMethod_configure(
    ClientData clientData,
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    int objc,
    Tcl_Obj * const objv[])
{
    int result, index;
    Tcl_Object object;
    tkoWidget *widget;         /* widget. */
    int skip;
    Tcl_Obj *myObjv[2];
	static const char *const commandNames[] =
	{ "init", "optionadd", "optiondel", "optionhide", "optionshow", "optionvar", NULL };
	enum command {
		COMMAND_INIT, COMMAND_OPTIONADD, COMMAND_OPTIONDEL,
		COMMAND_OPTIONHIDE, COMMAND_OPTIONSHOW,
		COMMAND_OPTIONVAR
	};
    Tcl_Obj *dbclass = NULL;
    Tcl_Obj *defvalue = NULL;
    Tcl_Obj *flags = NULL;
	Tcl_HashSearch search;
	Tcl_HashEntry *entryPtr;
	WidgetOption *optionPtr;
	Tcl_Obj *retPtr;
	Tcl_Obj *listPtr;

    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (widget = (tkoWidget *)Tcl_ObjectGetMetadata(object,
		&tkoWidgetMeta)) == NULL) {
		return TCL_ERROR;
	}
    skip = Tcl_ObjectContextSkippedArgs(context);

    if(widget->tkWin == NULL) {
        return TCL_ERROR;
    }
    /* configure */
    if(objc - skip == 0) {
	    retPtr = Tcl_NewObj();
        entryPtr = Tcl_FirstHashEntry(&widget->optionsTable, &search);
        while(entryPtr != NULL) {       /* TODO Tcl_DuplicateObj()? */
            optionPtr = (WidgetOption *) Tcl_GetHashValue(entryPtr);
            entryPtr = Tcl_NextHashEntry(&search);
			/* hidden option, not visible in configure method */
			if (optionPtr->flags&TKO_OPTION_HIDE) continue;
			listPtr = Tcl_NewObj();
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->option);
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->dbname);
            if(optionPtr->dbclass != NULL) {
                Tcl_ListObjAppendElement(interp, listPtr, optionPtr->dbclass);
                Tcl_ListObjAppendElement(interp, listPtr, optionPtr->defvalue);
                Tcl_ListObjAppendElement(interp, listPtr, optionPtr->value);
            }
            Tcl_ListObjAppendElement(interp, retPtr, listPtr);
        }
        /* Return sorted list */
        myObjv[0] = TkoObj.lsort;
        myObjv[1] = retPtr;
        return (Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL));
    }
    /* configure "-option ?value? .." */
    if(Tcl_GetString(objv[skip])[0] == '-') {
        if(objc - skip == 1) {  /* configure -option */
            entryPtr =
                Tcl_FindHashEntry(&widget->optionsTable,
                Tk_GetUid(Tcl_GetString(objv[skip])));
            if(entryPtr == NULL) {
                Tcl_SetObjResult(interp, Tcl_ObjPrintf("unknown option \"%s\"",
                        Tcl_GetString(objv[skip])));
                return TCL_ERROR;
            }
            optionPtr = (WidgetOption *) Tcl_GetHashValue(entryPtr);
			/* hidden option, not visible in configure method */
			if (optionPtr->flags&TKO_OPTION_HIDE) {
				Tcl_SetObjResult(interp, Tcl_ObjPrintf("hidden option \"%s\"",
					Tcl_GetString(objv[skip])));
				return TCL_ERROR;
			}
			if(optionPtr->dbclass == NULL) {
                entryPtr =
                    Tcl_FindHashEntry(&widget->optionsTable,
                    Tk_GetUid(Tcl_GetString(optionPtr->dbname)));
                if(entryPtr == NULL) {
                    Tcl_SetObjResult(interp,
                        Tcl_ObjPrintf("unknown option \"%s\"",
                            Tcl_GetString(objv[skip])));
                    return TCL_ERROR;
                }
                optionPtr = (WidgetOption *) Tcl_GetHashValue(entryPtr);
                if(optionPtr->dbclass == NULL) {
                    Tcl_SetObjResult(interp,
                        Tcl_ObjPrintf("unknown option \"%s\"",
                            Tcl_GetString(objv[skip])));
                    return TCL_ERROR;
                }
            }
            listPtr = Tcl_NewObj();
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->option);
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->dbname);
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->dbclass);
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->defvalue);
            Tcl_ListObjAppendElement(interp, listPtr, optionPtr->value);
            Tcl_SetObjResult(interp, listPtr);
            return TCL_OK;
        }
        if((objc - skip) % 2 == 0) {    /* configure "-option value .." */
            return WidgetOptionConfigure(interp, widget, objc - skip,
                &objv[skip]);
        }
        Tcl_WrongNumArgs(interp, skip, objv, "?-option value ..?");
        return TCL_ERROR;
    }
    /* configure "command .." */
    result =
        Tcl_GetIndexFromObj(interp, objv[skip], commandNames, "option", 0,
        &index);
    if(result != TCL_OK) {
        return result;
    }
    switch (index) {
	case COMMAND_INIT:
		// collect all not readonly options and configure
		Tcl_Preserve(widget);
		myObjv[0] = widget->myCmd;
		entryPtr = Tcl_FirstHashEntry(&widget->optionsTable, &search);
		while (entryPtr != NULL) {
			optionPtr = Tcl_GetHashValue(entryPtr);
			entryPtr = Tcl_NextHashEntry(&search);
			if (optionPtr->dbclass == NULL) {    /* synonym option */
				if (optionPtr->value) {
					Tcl_ObjSetVar2(interp, widget->optionsArray,
						optionPtr->dbname, optionPtr->value, TCL_GLOBAL_ONLY);
					Tcl_DecrRefCount(optionPtr->value);
					optionPtr->value = NULL;
				}
			}
			else {    /* normal option */
				if ((optionPtr->flags & TKO_OPTION_READONLY) == 0) {
					myObjv[1] = optionPtr->option;
					if (Tcl_EvalObjv(interp, 2, myObjv,
						TCL_EVAL_GLOBAL) != TCL_OK) {
						retPtr = Tcl_GetObjResult(interp);
						Tcl_IncrRefCount(retPtr);
						Tcl_Release(widget);
						Tcl_DeleteCommandFromToken(interp, widget->widgetCmd);
						Tcl_SetObjResult(interp, retPtr);
						Tcl_DecrRefCount(retPtr);
						return TCL_ERROR;
					}
				}
			}
		}
		myObjv[1] = TkoObj._tko_configure;
		if (Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL) != TCL_OK) {
			retPtr = Tcl_GetObjResult(interp);
			Tcl_IncrRefCount(retPtr);
			Tcl_Release(widget);
			Tcl_DeleteCommandFromToken(interp, widget->widgetCmd);
			Tcl_SetObjResult(interp, retPtr);
			Tcl_DecrRefCount(retPtr);
			return TCL_ERROR;
		}
		Tcl_Release(widget);
		return TCL_OK;
	case COMMAND_OPTIONADD:
        dbclass = NULL;
        defvalue = NULL;
        flags = NULL;
        if(objc - skip == 3) {  /* configure add option dbname */
            ;
        } else if(objc - skip == 4) {   /* configure add option dbname dbclass */
            dbclass = objv[skip + 3];
        } else if(objc - skip == 5) {   /* configure add option dbname dbclass defvalue */
            dbclass = objv[skip + 3];
            defvalue = objv[skip + 4];
        } else if(objc - skip == 6) {   /* configure add option dbname dbclass defvalue flags */
            dbclass = objv[skip + 3];
            defvalue = objv[skip + 4];
            flags = objv[skip + 5];
        } else {
            Tcl_WrongNumArgs(interp, skip + 1, objv,
                "option ?synonym?|?dbname dbclass ?default? ?flags??");
            return TCL_ERROR;
        }
        return (WidgetOptionAdd(interp, widget, objv[skip + 1], objv[skip + 2],
                dbclass, defvalue, flags, NULL, 0));
    case COMMAND_OPTIONDEL:
        if(objc - skip == 2) {
            return (WidgetOptionDel(interp, widget, objv[skip + 1]));
        }
        Tcl_WrongNumArgs(interp, skip + 1, objv, "option");
        return TCL_ERROR;
	case COMMAND_OPTIONHIDE:
		/* no further args, return hidden options */
		if (objc - skip == 1) {
			retPtr = Tcl_NewObj();
			entryPtr = Tcl_FirstHashEntry(&widget->optionsTable, &search);
			while (entryPtr != NULL) {
				optionPtr = Tcl_GetHashValue(entryPtr);
				entryPtr = Tcl_NextHashEntry(&search);
				if (optionPtr->flags&TKO_OPTION_HIDE) {
					Tcl_ListObjAppendElement(interp, retPtr, optionPtr->option);
				}
			}
			/* Return sorted list */
			myObjv[0] = TkoObj.lsort;
			myObjv[1] = retPtr;
			return (Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL));
		/* hide given options */
		} else {
			skip++;
			while (skip < objc) {
				entryPtr = Tcl_FindHashEntry(&widget->optionsTable,
						Tk_GetUid(Tcl_GetString(objv[skip])));
				if (entryPtr == NULL) {
					Tcl_SetObjResult(interp,
						Tcl_ObjPrintf("unknown option \"%s\"", Tcl_GetString(objv[skip])));
					return TCL_ERROR;
				}
				optionPtr = Tcl_GetHashValue(entryPtr);
				optionPtr->flags |= TKO_OPTION_HIDE;
				skip++;
			}
			return TCL_OK;
		}
	case COMMAND_OPTIONSHOW:
		/* no further args, return configure'able options */
		if (objc - skip == 1) {
			retPtr = Tcl_NewObj();
			entryPtr = Tcl_FirstHashEntry(&widget->optionsTable, &search);
			while (entryPtr != NULL) {
				optionPtr = Tcl_GetHashValue(entryPtr);
				entryPtr = Tcl_NextHashEntry(&search);
				if ((optionPtr->flags & TKO_OPTION_HIDE) == 0) {
					Tcl_ListObjAppendElement(interp, retPtr, optionPtr->option);
				}
			}
			/* Return sorted list */
			myObjv[0] = TkoObj.lsort;
			myObjv[1] = retPtr;
			return (Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL));
		/* make given options configure'able */
		} else {
			skip++;
			while (skip < objc) {
				entryPtr = Tcl_FindHashEntry(&widget->optionsTable,
					Tk_GetUid(Tcl_GetString(objv[skip])));
				if (entryPtr == NULL) {
					Tcl_SetObjResult(interp,
						Tcl_ObjPrintf("unknown option \"%s\"", Tcl_GetString(objv[skip])));
					return TCL_ERROR;
				}
				optionPtr = Tcl_GetHashValue(entryPtr);
				optionPtr->flags &= ~TKO_OPTION_HIDE;
				skip++;
			}
			return TCL_OK;
		}
	case COMMAND_OPTIONVAR:
        if(objc - skip == 1) {
            Tcl_SetObjResult(interp, widget->optionsArray);
            return TCL_OK;
        }
        Tcl_WrongNumArgs(interp, skip + 1, objv, "");
        return TCL_ERROR;
    }
    return TCL_ERROR;   /* supress compiler warning */
}

/*
 * WidgetOptionAdd --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetOptionAdd(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option,
    Tcl_Obj * dbname,
    Tcl_Obj * dbclass,
    Tcl_Obj * defvalue,
    Tcl_Obj * flags,
    Tcl_Obj * value,
    int initmode)
{
    Tcl_HashEntry *entryPtr;
    WidgetOption *optionPtr;
    Tk_Uid valueUid;
    int isNew;
    Tk_Uid optionUid;
    Tk_Uid dbnameUid;
    Tk_Uid dbclassUid;
    int intFlags;
	int readonly;
    Tcl_Obj *myObjv[2];
    const char *ch;
	int traceadd = 0; /* if not 0 then readd trace on array variable */

    if(option == NULL || (ch = Tcl_GetString(option))[0] != '-') {
        Tcl_SetObjResult(interp, Tcl_NewStringObj("missing or wrong option",
                -1));
        return TCL_ERROR;
    }
    if(dbname == NULL) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("missing dbname for option \"%s\"", ch));
        return TCL_ERROR;
    }
    /* synonym option check */
    if(dbclass == NULL) {
        if(Tcl_GetString(dbname)[0] != '-') {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("wrong synonym name for option \"%s\"", ch));
            return TCL_ERROR;
        }
    }
    /* int flag */
    intFlags = 0;
    if(flags != NULL && Tcl_GetIntFromObj(interp, flags, &intFlags) != TCL_OK) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("wrong flags \"%s\" for option \"%s\"",
                Tcl_GetString(flags), ch));
        return TCL_ERROR;
    }
	if (intFlags & TKO_OPTION_READONLY) {
		intFlags &= ~TKO_OPTION_READONLY;
		readonly = TKO_OPTION_READONLY;
	}
	else {
		readonly = 0;
	}
    /* return if no widget given, all class checks are done */
    if(widget == NULL) {
        return TCL_OK;
    }
    optionUid = Tk_GetUid(ch);
    dbnameUid = Tk_GetUid(Tcl_GetString(dbname));
    entryPtr = Tcl_CreateHashEntry(&widget->optionsTable, optionUid, &isNew);
    if(isNew == 0) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("option \"%s\" exists", ch));
        return TCL_ERROR;
    }
    /* create option */
    optionPtr = (WidgetOption *) ckalloc(sizeof(WidgetOption));
    optionPtr->option = option;
    Tcl_IncrRefCount(optionPtr->option);
    optionPtr->dbname = dbname;
    Tcl_IncrRefCount(optionPtr->dbname);
    optionPtr->dbclass = NULL;
    optionPtr->defvalue = NULL;
    optionPtr->value = NULL;
    optionPtr->flags = intFlags;
    Tcl_SetHashValue(entryPtr, (char *)optionPtr);
    /* synonym options can have init value */
    if(dbclass == NULL) {
        if(value) {
            optionPtr->value = value;
            Tcl_IncrRefCount(optionPtr->value);
        }
        /* normal option */
    } else {
        dbclassUid = Tk_GetUid(Tcl_GetString(dbclass));
        optionPtr->dbclass = dbclass;
        Tcl_IncrRefCount(optionPtr->dbclass);
        if(defvalue) {
            optionPtr->defvalue = defvalue;
        } else {
            optionPtr->defvalue = TkoObj.empty;
        }
        Tcl_IncrRefCount(optionPtr->defvalue);
        /*
         * If value is given use it.
         */
        if(value) {
            optionPtr->value = value;
        } else {
            /*
             * Get value from option database
             */
            if(optionPtr->value == NULL) {
                valueUid = Tk_GetOption(widget->tkWin, dbnameUid, dbclassUid);
                if(valueUid != NULL) {
                    optionPtr->value = Tcl_NewStringObj(valueUid, -1);
                }
            }
            /*
             * Check for a system-specific default value.
             * Do not for -class because Tcl_SetClass was not called.
             * When -class is not first option (after -screen) we get a crash!
             */
            if(optionPtr->value == NULL && optionUid != TkoUid_class) {
                optionPtr->value =
                    TkpGetSystemDefault(widget->tkWin, dbnameUid, dbclassUid);
            }
            /*
             * Use default value.
             */
            if(optionPtr->value == NULL) {
                optionPtr->value = defvalue;
            }
        }
        /*
         * No given value defaults to empty string.
         */
        if(optionPtr->value == NULL) {
            optionPtr->value = TkoObj.empty;
        }
        Tcl_IncrRefCount(optionPtr->value);
		/*
		 * Outside initmode the trace on the array variable needs to be disabled.
		 */
		if (initmode == 0) {
			Tcl_UntraceVar2(interp, Tcl_GetString(widget->optionsArray), NULL,
				TCL_TRACE_WRITES | TCL_TRACE_RESULT_OBJECT, WidgetOptionTrace, widget);
			traceadd = 1;
		}
		/*
		 *Set option array variable
		 */
		if (Tcl_ObjSetVar2(interp, widget->optionsArray, option,
			optionPtr->value, TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG) == NULL) {
			goto error;
		}
		/*
		 * Do initialization with -option method.
		 */
		if (readonly || initmode == 0) {
			myObjv[0] = widget->myCmd;
			myObjv[1] = option;
			if (Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL) != TCL_OK) {
				goto error;
			}
			/*
			* We set the value again because the -option method may have changed it.
			*/
			if (optionPtr->value) {
				Tcl_DecrRefCount(optionPtr->value);
			}
			optionPtr->value = Tcl_ObjGetVar2(interp, widget->optionsArray, option, TCL_GLOBAL_ONLY);   /*TODO flags? */
			Tcl_IncrRefCount(optionPtr->value);
			/* Now we are ready to set the readonly bit */
			if (readonly) {
				optionPtr->flags |= TKO_OPTION_READONLY;
			}
		}
    }
	if (traceadd) {
		Tcl_TraceVar2(interp, Tcl_GetString(widget->optionsArray), NULL,
			TCL_TRACE_WRITES | TCL_TRACE_RESULT_OBJECT, WidgetOptionTrace, widget);
	}
    return TCL_OK;
error:
	if (traceadd) {
		/* There should be no error and thus we don't need to save the result. */
		Tcl_TraceVar2(interp, Tcl_GetString(widget->optionsArray), NULL,
			TCL_TRACE_WRITES | TCL_TRACE_RESULT_OBJECT, WidgetOptionTrace, widget);
	}
	WidgetOptionDelEntry(entryPtr);
    return TCL_ERROR;
}

/*
 * WidgetOptionConfigure --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetOptionConfigure(
    Tcl_Interp * interp,
    tkoWidget * widget,
    int objc,
    Tcl_Obj * const objv[])
{
    int i;
    Tcl_Obj *myObjv[2];

    if(objc % 2) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("missing value"));
        return TCL_ERROR;
    }
    Tcl_Preserve(widget);
    for(i = 0; i < objc; i = i + 2) {
        if(WidgetOptionSet(interp, widget, objv[i], objv[i + 1]) != TCL_OK) {
            Tcl_Release(widget);
            return TCL_ERROR;
        }
    }
    myObjv[0] = widget->myCmd;
    myObjv[1] = TkoObj._tko_configure;
    if(Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL) != TCL_OK) {
        Tcl_Release(widget);
        return TCL_ERROR;
    }
    Tcl_Release(widget);
    return TCL_OK;
}

/*
 * WidgetOptionDel --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetOptionDel(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option)
{
Tcl_HashEntry *entryPtr;

    if(option == NULL) {
        return TCL_ERROR;
    }
    /* delete single option */
    entryPtr =
        Tcl_FindHashEntry(&widget->optionsTable,
        Tk_GetUid(Tcl_GetString(option)));
    if(entryPtr == NULL) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("unknown option \"%s\"", Tcl_GetString(option)));
        return TCL_ERROR;
    }
    /* delete with no additional check on synonym option */
    Tcl_UnsetVar2(interp, Tcl_GetString(widget->optionsArray),
        Tcl_GetString(option), TCL_GLOBAL_ONLY);
    WidgetOptionDelEntry(entryPtr);

    return TCL_OK;
}

/*
 * WidgetOptionGet --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetOptionGet(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option)
{
Tcl_Obj *retPtr;
Tcl_HashEntry *entryPtr;
WidgetOption *optionPtr;

    if(option == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("no option given"));
        return TCL_ERROR;
    }
    entryPtr =
        Tcl_FindHashEntry(&widget->optionsTable,
        Tk_GetUid(Tcl_GetString(option)));
    if(entryPtr == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("unknown option \"%s\"",
                Tcl_GetString(option)));
        return TCL_ERROR;
    }
    optionPtr = Tcl_GetHashValue(entryPtr);
	/* hidden option, not visible in cget method */
	if (optionPtr->flags&TKO_OPTION_HIDE) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("hidden option \"%s\"",
			Tcl_GetString(option)));
        return TCL_ERROR;
	}
    /* synonym option */
    if(optionPtr->dbclass == NULL) {
        entryPtr =
            Tcl_FindHashEntry(&widget->optionsTable,
            Tk_GetUid(Tcl_GetString(optionPtr->dbname)));
        if(entryPtr == NULL) {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("unknown synonym option \"%s\"",
                    Tcl_GetString(option)));
            return TCL_ERROR;
        }
        optionPtr = Tcl_GetHashValue(entryPtr);
        if(optionPtr->dbclass == NULL) {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("synonym option is synonym \"%s\"",
                    Tcl_GetString(option)));
            return TCL_ERROR;
        }
    }
    retPtr = optionPtr->value;
    Tcl_SetObjResult(interp, retPtr);
    return TCL_OK;
}

/*
 * WidgetOptionSet --
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetOptionSet(
    Tcl_Interp * interp,
    tkoWidget * widget,
    Tcl_Obj * option,
    Tcl_Obj * value)
{
    Tcl_HashEntry *entryPtr;
    WidgetOption *optionPtr;

    if(option == NULL || value == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf("missing option and/or value"));
        return TCL_ERROR;
    }
    entryPtr =
        Tcl_FindHashEntry(&widget->optionsTable,
        Tk_GetUid(Tcl_GetString(option)));
    if(entryPtr == NULL) {
        Tcl_SetObjResult(interp,
            Tcl_ObjPrintf("unknown option \"%s\"", Tcl_GetString(option)));
        return TCL_ERROR;
    }
    optionPtr = Tcl_GetHashValue(entryPtr);
	/* hidden option, not visible in cget method */
	if (optionPtr->flags&TKO_OPTION_HIDE) {
		Tcl_SetObjResult(interp, Tcl_ObjPrintf("hidden option \"%s\"",
			Tcl_GetString(option)));
		return TCL_ERROR;
	}
	/* synonym option */
    if(optionPtr->dbclass == NULL) {
        entryPtr =
            Tcl_FindHashEntry(&widget->optionsTable,
            Tk_GetUid(Tcl_GetString(optionPtr->dbname)));
        if(entryPtr == NULL) {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("unknown synonym option \"%s\"",
                    Tcl_GetString(option)));
            return TCL_ERROR;
        }
        optionPtr = Tcl_GetHashValue(entryPtr);
        if(optionPtr->dbclass == NULL) {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("synonym option is synonym \"%s\"",
                    Tcl_GetString(option)));
            return TCL_ERROR;
        }
        if(Tcl_ObjSetVar2(interp, widget->optionsArray, optionPtr->option,
                value, TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG) == NULL) {
            return TCL_ERROR;
        }
    } else {
        if(Tcl_ObjSetVar2(interp, widget->optionsArray, option, value,
                TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG) == NULL) {
            return TCL_ERROR;
        }
    }
    return TCL_OK;
}

/*
 * TkoWidgetOptionGet --
 *
 * Results:
 *
 * Side effects:
 */
Tcl_Obj *
TkoWidgetOptionGet(
    Tcl_Interp * interp,
    Tcl_Object object,
    Tcl_Obj * option)
{
    tkoWidget *widget = (tkoWidget *) Tcl_ObjectGetMetadata(object, &tkoWidgetMeta);

    if(widget == NULL) {
        return NULL;
    }
    return Tcl_ObjGetVar2(interp, widget->optionsArray, option,
        TCL_GLOBAL_ONLY);
}

/*
 * TkoWidgetOptionSet --
 *
 * Results:
 *
 * Side effects:
 */
int
TkoWidgetOptionSet(
    Tcl_Interp * interp,
    Tcl_ObjectContext context,
    Tcl_Obj * option,
    tkoWidgetOptionType type,
    Tcl_ObjectMetadataType * meta,
    size_t offset)
{
    Tcl_Object object;
    tkoWidget *widget;
    Tcl_Obj *value;
    char *address = NULL;
    int intVal;
    double dblVal;
    Colormap colormap;
    int *intPtr;
    const char *str;
    int length;
    int pixels[4] = { 0, 0, 0, 0 };
    int objc;
    Tcl_Obj **objv;
    Visual * visual;
	XColor * color;
    Tk_3DBorder border;
    Tk_Anchor anchor;
    Tk_Cursor cursor;
    Tk_Window newWin;
    Tk_Font newFont;
    Tk_Justify justify;

    if((object = Tcl_ObjectContextObject(context)) == NULL
        || (widget =
            (tkoWidget *) Tcl_ObjectGetMetadata(object, &tkoWidgetMeta)) == NULL
        || (value =
            Tcl_ObjGetVar2(interp, widget->optionsArray, option,
                TCL_GLOBAL_ONLY)) == NULL || widget->tkWin == NULL) {
        return TCL_ERROR;
    }
    if(meta) {
        if((address = Tcl_ObjectGetMetadata(object, meta)) == NULL) {
            return TCL_ERROR;
        }
        address += offset;
    }

    switch (type) {
    case TKO_SET_CLASS:        /* (Tcl_Obj **)address */
        Tk_SetClass(widget->tkWin, Tcl_GetString(value));
        if(address) {
            if(*((Tcl_Obj **) address) != NULL)
                Tcl_DecrRefCount(*((Tcl_Obj **) address));
            *((Tcl_Obj **) address) = value;
            Tcl_IncrRefCount(value);
        }
        return TCL_OK;
    case TKO_SET_VISUAL:       /* (Tcl_Obj **)address */
        visual =
            Tk_GetVisual(interp, widget->tkWin, Tcl_GetString(value), &intVal,
            &colormap);
        if(visual == NULL)
            return TCL_ERROR;
        Tk_SetWindowVisual(widget->tkWin, visual, intVal, colormap);
        if(address) {
            if(*((Tcl_Obj **) address) != NULL)
                Tcl_DecrRefCount(*((Tcl_Obj **) address));
            *((Tcl_Obj **) address) = value;
            Tcl_IncrRefCount(value);
        }
        return TCL_OK;
    case TKO_SET_COLORMAP:     /* (Tcl_Obj **)address */
        str = Tcl_GetStringFromObj(value, &length);
        if(str && length) {
            colormap = Tk_GetColormap(interp, widget->tkWin, str);
            if(colormap == None)
                return TCL_ERROR;
            Tk_SetWindowColormap(widget->tkWin, colormap);
        }
        if(address) {
            if(*((Tcl_Obj **) address) != NULL)
                Tcl_DecrRefCount(*((Tcl_Obj **) address));
            *((Tcl_Obj **) address) = value;
            Tcl_IncrRefCount(value);
        }
        return TCL_OK;
    case TKO_SET_USENULL:      /* (Tcl_Obj **)address */
        str = Tcl_GetStringFromObj(value, &length);
        if(str && length) {
            if(TkpUseWindow(interp, widget->tkWin, str) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        if(address) {
            if(*((Tcl_Obj **) address) != NULL)
                Tcl_DecrRefCount(*((Tcl_Obj **) address));
            if(length) {
                *((Tcl_Obj **) address) = value;
                Tcl_IncrRefCount(value);
            } else {
                *((Tcl_Obj **) address) = NULL;
            }
        }
        return TCL_OK;
    case TKO_SET_CONTAINER:    /* (int *)address */
        if(Tcl_GetBooleanFromObj(interp, value, &intVal) != TCL_OK)
            return TCL_ERROR;
        if(intVal) {
            TkpMakeContainer(widget->tkWin);
            Tcl_ObjSetVar2(interp, widget->optionsArray, option, TkoObj._1,
                TCL_GLOBAL_ONLY);
        } else {
            Tcl_ObjSetVar2(interp, widget->optionsArray, option, TkoObj._0,
                TCL_GLOBAL_ONLY);
        }
        if(address) {
            *(int *)address = intVal;
        }
        return TCL_OK;
    case TKO_SET_TCLOBJ:       /* (Tcl_Obj **)address */
        if(address) {
            if(*((Tcl_Obj **) address) != NULL)
                Tcl_DecrRefCount(*((Tcl_Obj **) address));
            *((Tcl_Obj **) address) = value;
            Tcl_IncrRefCount(value);
        }
        return TCL_OK;
    case TKO_SET_XCOLOR:       /* (Xcolor **)address */
        color = Tk_AllocColorFromObj(interp, widget->tkWin, value);
        if(color == NULL)
            return TCL_ERROR;
        if(address) {
            if(*((XColor **) address) != NULL) {
                Tk_FreeColor(*((XColor **) address));
            }
            *((XColor **) address) = color;
        } else {
            Tk_FreeColor(color);
        }
        return TCL_OK;
    case TKO_SET_3DBORDER:     /* (Tk_3DBorder *)address */
        border = Tk_Alloc3DBorderFromObj(interp, widget->tkWin, value);
        if(border == NULL)
            return TCL_ERROR;
        if(address) {
            if(*(Tk_3DBorder *) address != NULL) {
                Tk_Free3DBorder(*(Tk_3DBorder *) address);
            }
            *(Tk_3DBorder *) address = border;
        } else {
            Tk_Free3DBorder(border);
        }
        return TCL_OK;
    case TKO_SET_PIXEL:        /* (int *)address */
        if(Tk_GetPixelsFromObj(interp, widget->tkWin, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(int *)address = intVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewIntObj(intVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_PIXELNONEGATIV:       /* (int *)address */
        if(Tk_GetPixelsFromObj(interp, widget->tkWin, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(intVal >= SHRT_MAX) {
            Tcl_AppendResult(interp, "bad distance \"", Tcl_GetString(value),
                "\": ", "too big to represent", (char *)NULL);
            return TCL_ERROR;
        }
        if(intVal < 0) {
            Tcl_AppendResult(interp, "bad distance \"", Tcl_GetString(value),
                "\": ", "can't be negative", (char *)NULL);
            return TCL_ERROR;
        }
        if(address) {
            *(int *)address = intVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewIntObj(intVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_PIXELPOSITIV: /* (int *)address */
        if(Tk_GetPixelsFromObj(interp, widget->tkWin, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(intVal >= SHRT_MAX) {
            Tcl_AppendResult(interp, "bad distance \"", Tcl_GetString(value),
                "\": ", "too big to represent", (char *)NULL);
            return TCL_ERROR;
        }
        if(intVal <= 0) {
            Tcl_AppendResult(interp, "bad distance \"", Tcl_GetString(value),
                "\": ", "must be positive", (char *)NULL);
            return TCL_ERROR;
        }
        if(address) {
            *(int *)address = intVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewIntObj(intVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_DOUBLE:       /* (double *)address */
        if(Tcl_GetDoubleFromObj(interp, value, &dblVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(double *)address = dblVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewDoubleObj(dblVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_BOOLEAN:      /* (int *)address */
        if(Tcl_GetBooleanFromObj(interp, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(intVal) {
            Tcl_ObjSetVar2(interp, widget->optionsArray, option, TkoObj._1,
                TCL_GLOBAL_ONLY);
        } else {
            Tcl_ObjSetVar2(interp, widget->optionsArray, option, TkoObj._0,
                TCL_GLOBAL_ONLY);
        }
        if(address) {
            *(int *)address = intVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewIntObj(intVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_CURSOR:       /* (Tk_Cursor *)address */
        cursor = None;
        if(Tcl_GetString(value)[0] != '\0') {
            cursor = Tk_AllocCursorFromObj(interp, widget->tkWin, value);
            if(cursor == None) {
                return TCL_ERROR;
            }
            Tk_DefineCursor(widget->tkWin, cursor);
        }
        if(address) {
            if(*(Tk_Cursor *) address != None) {
                Tk_FreeCursor(Tk_Display(widget->tkWin),
                    *(Tk_Cursor *) address);
            }
            *(Tk_Cursor *) address = cursor;
        } else {
            if(cursor != None) {
                Tk_FreeCursor(Tk_Display(widget->tkWin), cursor);       /*TODO necessary? */
            }
        }
        return TCL_OK;
    case TKO_SET_INT:  /* (int *)address */
        if(Tcl_GetIntFromObj(interp, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(int *)address = intVal;
        }
        Tcl_ObjSetVar2(interp, widget->optionsArray, option,
            Tcl_NewIntObj(intVal), TCL_GLOBAL_ONLY);
        return TCL_OK;
    case TKO_SET_RELIEF:       /* (int *)address */
        if(Tk_GetReliefFromObj(interp, value, &intVal) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(int *)address = intVal;
        }
        return TCL_OK;
    case TKO_SET_ANCHOR:       /* (Tk_Anchor *)address */
        if(Tk_GetAnchorFromObj(interp, value, &anchor) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(Tk_Anchor *) address = anchor;
        }
        return TCL_OK;
    case TKO_SET_WINDOW:       /* (Tk_Window *)address */
        if(value == NULL || Tcl_GetCharLength(value) == 0) {
            newWin = None;
        } else {
            if(TkGetWindowFromObj(interp, widget->tkWin, value,
                    &newWin) != TCL_OK) {
                return TCL_ERROR;
            }
        }
        if(address) {
            *(Tk_Window *) address = newWin;
        }
        return TCL_OK;
    case TKO_SET_FONT: /* (Tk_Font *)address */
        newFont = Tk_AllocFontFromObj(interp, widget->tkWin, value);
        if(newFont == NULL) {
            return TCL_ERROR;
        }
        if(address) {
            if(*(Tk_Font *) address != NULL) {
                Tk_FreeFont(*(Tk_Font *) address);
            }
            *(Tk_Font *) address = newFont;
        } else {
            Tk_FreeFont(newFont);
        }
        return TCL_OK;
    case TKO_SET_STRING:       /* (char **)address */
        if(address) {
            str = Tcl_GetStringFromObj(value, &length);
            if(*(char **)address != NULL) {
                ckfree(*(char **)address);
            }
            *(char **)address = ckalloc(length + 1);
            memcpy(*(char **)address, str, length + 1);
        }
        return TCL_OK;
    case TKO_SET_STRINGNULL:   /* (char **)address */
        if(address) {
            str = Tcl_GetStringFromObj(value, &length);
            if(*(char **)address != NULL) {
                ckfree(*(char **)address);
            }
            if(length == 0) {
                *(char **)address = NULL;
            } else {
                *(char **)address = ckalloc(length + 1);
                memcpy(*(char **)address, str, length + 1);
            }
        }
        return TCL_OK;
    case TKO_SET_SCROLLREGION: /* (int *[4])address */
        if(Tcl_ListObjGetElements(interp, value, &objc, &objv) != TCL_OK) {
            return TCL_ERROR;
        }
        if(objc == 4) {
            if(Tk_GetPixelsFromObj(interp, widget->tkWin, objv[0],
                    &pixels[0]) != TCL_OK
                || Tk_GetPixelsFromObj(interp, widget->tkWin, objv[1],
                    &pixels[1]) != TCL_OK
                || Tk_GetPixelsFromObj(interp, widget->tkWin, objv[2],
                    &pixels[2]) != TCL_OK
                || Tk_GetPixelsFromObj(interp, widget->tkWin, objv[3],
                    &pixels[3]) != TCL_OK) {
                return TCL_ERROR;
            }
        } else if(objc != 0) {
            Tcl_SetObjResult(interp,
                Tcl_ObjPrintf("found %d instead of 4 values", objc));
            return TCL_ERROR;
        }
        if(address) {
            intPtr = (int *)address;
            intPtr[0] = pixels[0];
            intPtr[1] = pixels[1];
            intPtr[2] = pixels[2];
            intPtr[3] = pixels[3];
        }
        return TCL_OK;
    case TKO_SET_JUSTIFY:      /* (Tk_Justify *)address */
        if(Tk_GetJustify(interp, Tk_GetUid(Tcl_GetString(value)),
                &justify) != TCL_OK) {
            return TCL_ERROR;
        }
        if(address) {
            *(Tk_Justify *) address = justify;
        }
        return TCL_OK;
    }

    Tcl_SetObjResult(interp, Tcl_ObjPrintf("unknown type \"%d\"", type));
    return TCL_ERROR;
}

/*
 * WidgetOptionTrace --
 *
 * Write trace on option array variable
 *
 * Results:
 *
 * Side effects:
 */
static char *
WidgetOptionTrace(
    ClientData clientData,
    Tcl_Interp * interp,
    const char *name1,
    const char *name2,
    int flags)
{
    tkoWidget *widget = (tkoWidget *) clientData;
    Tcl_HashEntry *entryPtr;
    Tcl_Obj *valuePtr;
    //    const char *result;
    WidgetOption *optionPtr;
    Tcl_Obj *myObjv[2];
    Tcl_Obj *myRet;

    /* get new value */
    entryPtr = Tcl_FindHashEntry(&widget->optionsTable, Tk_GetUid(name2));
    if(entryPtr == NULL) {
        myRet = Tcl_ObjPrintf("option \"%s\" not found", name2);
        Tcl_IncrRefCount(myRet);
        return (char *)myRet;
    }
    optionPtr = (WidgetOption *) Tcl_GetHashValue(entryPtr);
    if(optionPtr->flags & TKO_OPTION_READONLY) {
        myRet = Tcl_ObjPrintf("option \"%s\" is readonly", name2);
        Tcl_IncrRefCount(myRet);
        return (char *)myRet;
    }
    myObjv[0] = widget->myCmd;
    myObjv[1] = optionPtr->option;
    if(Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL) != TCL_OK) {
        myRet = Tcl_GetObjResult(interp);
        Tcl_IncrRefCount(myRet);
        /* reset to old value TODO checks? */
        if(optionPtr->value != NULL) {
            Tcl_ObjSetVar2(interp, widget->optionsArray, optionPtr->option,
                optionPtr->value, TCL_GLOBAL_ONLY);
            Tcl_EvalObjv(interp, 2, myObjv, TCL_EVAL_GLOBAL);
        }
        return (char *)myRet;
    }
    if(optionPtr->value != NULL) {
        Tcl_DecrRefCount(optionPtr->value);
    }
    valuePtr = Tcl_ObjGetVar2(interp, widget->optionsArray, optionPtr->option, TCL_GLOBAL_ONLY);        /*TODO flags? */
    optionPtr->value = valuePtr;
    Tcl_IncrRefCount(optionPtr->value);
    return NULL;
}

/*
 * WidgetOptionDelEntry --
 *
 * Results:
 *
 * Side effects:
 */
static void
WidgetOptionDelEntry(
    Tcl_HashEntry * entry)
{
WidgetOption *optionPtr = Tcl_GetHashValue(entry);
    if(optionPtr->option)
        Tcl_DecrRefCount(optionPtr->option);
    if(optionPtr->dbname)
        Tcl_DecrRefCount(optionPtr->dbname);
    if(optionPtr->dbclass)
        Tcl_DecrRefCount(optionPtr->dbclass);
    if(optionPtr->defvalue)
        Tcl_DecrRefCount(optionPtr->defvalue);
    if(optionPtr->value)
        Tcl_DecrRefCount(optionPtr->value);
    ckfree(optionPtr);
    Tcl_DeleteHashEntry(entry);
}

/*
 * WidgetMethod_tko_configure --
 *	Virtual method called after configuring options.
 *	Should be implemented in derived classes.
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetMethod_tko_configure(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[])
{              /* virtual method */
	return TCL_OK;
}

/*
 * WidgetMetaDelete --
 *	Delete widget meta data when all preserve calls done.
 *
 * Results:
 *
 * Side effects:
 */
static void
WidgetMetaDelete(
	ClientData clientData)
{
	Tcl_EventuallyFree(clientData, (Tcl_FreeProc *)WidgetMetaDestroy);
}

/*
 * WidgetMethod_ --
 *	Call standard option set method.
 *
 * Results:
 *
 * Side effects:
 */
static int
WidgetMethod_(
	ClientData clientData,
	Tcl_Interp * interp,
	Tcl_ObjectContext context,
	int objc,
	Tcl_Obj * const objv[])
{              /* common option set method */
	tkoWidgetOptionDefine *define = (tkoWidgetOptionDefine *)clientData;
	return TkoWidgetOptionSet(interp, context, define->optionPtr,
		define->type, define->meta, define->offset);
}

/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added generic/tko/tkoWidget.h.































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
 * tkoWidget.h --
 *
 *    Header file for the internals of the tko widget package.
 *
 * Copyright (c) 2019 Rene zaumseil
 *
 */

#ifndef _TKOWIDGET_H
#define _TKOWIDGET_H

#include "tcl.h"
#include "tclInt.h"     /* TclIsInfinite() */

#include "tclOO.h"

#include "tk.h"
#include "default.h"
#include "tk3d.h"
#include "tkFont.h"

#ifndef _WIN32
#include <X11/Xproto.h>
#endif

#if defined(_WIN32)
#include "tkWinInt.h"
#elif defined(MAC_OSX_TK)
#include "tkMacOSXInt.h"
#else
#include "tkUnixInt.h"
#endif

#define _USE_MATH_DEFINES
#include <math.h>       /* VC math constants M_PI, M_SQRT1_2 */
#include <float.h>      /* DBL_MAX,.. */
#include <assert.h>

/*
 * For C++ compilers, use extern "C"
 */
#ifdef __cplusplus
extern "C" {
#endif

/*
 * Mathematical functions
 */
#undef ABS
#define ABS(x)		(((x)<0)?(-(x)):(x))

#undef EXP10
#define EXP10(x)	(pow(10.0,(x)))

#undef FABS
#define FABS(x) 	(((x)<0.0)?(-(x)):(x))

#undef SIGN
#define SIGN(x)		(((x) < 0.0) ? -1 : 1)

#undef MIN
#define MIN(a,b)	(((a)<(b))?(a):(b))

#undef MAX
#define MAX(a,b)	(((a)>(b))?(a):(b))

#undef MIN3
#define MIN3(a,b,c)	(((a)<(b))?(((a)<(c))?(a):(c)):(((b)<(c))?(b):(c)))

#undef MAX3
#define MAX3(a,b,c)	(((a)>(b))?(((a)>(c))?(a):(c)):(((b)>(c))?(b):(c)))

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

    /*
     * Be careful when using the next two macros.  They both assume the floating
     * point number is less than the size of an int.  That means, for example, you
     * can't use these macros with numbers bigger than than 2^31-1.
     */
#undef FMOD
#define FMOD(x,y) 	((x)-(((int)((x)/(y)))*y))

#undef ROUND
#define ROUND(x) 	((int)((x) + (((x)<0.0) ? -0.5 : 0.5)))

#define DEGREES_TO_RADIANS (M_PI/180.0)
#define RADIANS_TO_DEGREES (180.0/M_PI)

/*
* Static tcl objects.
*/
    typedef struct tkoObj {
        Tcl_Obj *empty;
        Tcl_Obj *point;
        Tcl_Obj *next;
        Tcl_Obj *uplevel;
        Tcl_Obj *oo_define;
        Tcl_Obj *oo_objdefine;
        Tcl_Obj *method;
        Tcl_Obj *_tko_configure;
        Tcl_Obj *tko;
        Tcl_Obj *tko_options;
        Tcl_Obj *lsort;
        Tcl_Obj *tko_widget;
        Tcl_Obj *tko_frame;
        Tcl_Obj *tko_labelframe;
        Tcl_Obj *tko_toplevel;
        Tcl_Obj *path;
        Tcl_Obj *graph;
        Tcl_Obj *_screen;
        Tcl_Obj *_labelwidget;
        Tcl_Obj *_0;
        Tcl_Obj *_1;
    } tkoObj;
    MODULE_SCOPE tkoObj TkoObj;

/*
 * tkoWidgetOptionType --
 *
 * Suported type in the TkowidgetOptinSet() function.
 * In comments is the type of the address pointer.
 */
    typedef enum tkoWidgetOptionType {
        TKO_SET_CLASS = 1,     /* (Tcl_Obj **)address */
        TKO_SET_VISUAL, /* (Tcl_Obj **)address */
        TKO_SET_COLORMAP,       /* (Tcl_Obj **)address */
        TKO_SET_USENULL,        /* (Tcl_Obj **)address */
        TKO_SET_CONTAINER,      /* (int *)address */
        TKO_SET_TCLOBJ, /* (Tcl_Obj **)address */
        TKO_SET_XCOLOR, /* (Xcolor **)address */
        TKO_SET_3DBORDER,       /* (Tk_3DBorder *)address */
        TKO_SET_PIXEL,  /* (int *)address */
        TKO_SET_PIXELNONEGATIV, /* (int *)address */
        TKO_SET_PIXELPOSITIV,   /* (int *)address */
        TKO_SET_DOUBLE, /* (double *)address */
        TKO_SET_BOOLEAN,        /* (int *)address */
        TKO_SET_CURSOR, /* (Tk_Cursor *)address */
        TKO_SET_INT,    /* (int *)address */
        TKO_SET_RELIEF, /* (int *)address */
        TKO_SET_ANCHOR, /* (int *)address */
        TKO_SET_WINDOW, /* (Tk_Window *)address */
        TKO_SET_FONT,   /* (Tk_Font *)address */
        TKO_SET_STRING, /* (char **)address */
        TKO_SET_STRINGNULL,     /* (char **)address */
        TKO_SET_SCROLLREGION,   /* (int *[4])address */
        TKO_SET_JUSTIFY /* (Tk_Justify *)address */
    } tkoWidgetOptionType;

/*
 * tkoWidgetOptionDefine --
 *
 * Widget definition data used in class.
 " An option set method "-option" is created in the following order:
 * - If "proc" is given it will be used as option set method.
 * - If "method" is given it will be used as option set method.
 * - If "type" is greater 0 a common option set method will be used.
 *   In this case "type", "meta" and "offset" are used as parameters for
 *   the TkoWidgetOptionSet() function call.
 */
    typedef struct tkoWidgetOptionDefine {
        const char *option;    /* Name of option. Starts with "-" minus sign */
        const char *dbname;    /* Option DB name or synonym option if dbclass is NULL */
        const char *dbclass;   /* Option DB class name or NULL for synonym options. */
        const char *defvalue;  /* Default value. */
        int flags;             /* bit array of TKO_OPTION_* values to configure option behaviour */
		Tcl_Obj *optionPtr;    /* tko internally used, always init with NULL! */
        const char *proc;      /* If not NULL it is the body of the newly created -option method */
        Tcl_MethodCallProc *method;     /* If not NULL it is the function name of the -option method */
        tkoWidgetOptionType type;       /* if greater 0 then option type used in common option set method */
        Tcl_ObjectMetadataType *meta;   /* meta data address used in common option set method */
        int offset;            /* offset in meta data struct */
    } tkoWidgetOptionDefine;
#define TKO_OPTION_READONLY 0x1 /* option is only setable at creation time */
#define TKO_OPTION_HIDE     0x2 /* option is hidden in configure method */      

/* tkoFrame.c */
    MODULE_SCOPE int Tko_FrameInit(
        Tcl_Interp * interp);
/* tkoVector.c */
    MODULE_SCOPE int Tko_VectorInit(
        Tcl_Interp * interp);
/* tkoGraph.c */
    MODULE_SCOPE int Tko_GraphInit(
        Tcl_Interp * interp);
/* tkoPath.c */
    MODULE_SCOPE int Tko_PathInit(
        Tcl_Interp * interp);
/* tkoWidget.c */
    MODULE_SCOPE int Tko_WidgetInit(
        Tcl_Interp * interp);
    MODULE_SCOPE Tk_Window *TkoWidgetWindow(
        Tcl_Object object);
    MODULE_SCOPE Tcl_Obj *TkoWidgetOptionVar(
        Tcl_Object object);
    MODULE_SCOPE Tcl_Obj *TkoWidgetOptionGet(
        Tcl_Interp * interp,
        Tcl_Object object,
        Tcl_Obj * option);
    MODULE_SCOPE int TkoWidgetOptionSet(
        Tcl_Interp * interp,
        Tcl_ObjectContext context,
        Tcl_Obj * option,
        tkoWidgetOptionType type,
        Tcl_ObjectMetadataType * meta,
        size_t offset);
    MODULE_SCOPE int TkoWidgetClassDefine(
        Tcl_Interp * interp,
        Tcl_Class clazz,
        Tcl_Obj * classname,
        const Tcl_MethodType * methods,
        tkoWidgetOptionDefine * options);

/*
 * end block for C++
 */

#ifdef __cplusplus
}
#endif
#endif                         /* _TKOWIDGET_H */
/* vim: set ts=4 sw=4 sts=4 ff=unix et : */
Added library/graph.tcl.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# graph.tcl --
#
# This file defines the default bindings for Tk graph widgets and provides
# procedures that help in implementing those bindings.
#

## Used namespace.
namespace eval ::graph {
    variable _zoom
    array set _zoom {}
}

## ::graph binding --
#
#   Enable and disable default bindings for specified elements.
#
# Arguments:
# args -    list of entries for which to enable default bindings.
#           For not given entries bindings will be disabled.
#           Possible names are:
#               legend, crosshairs, zoom, findelement
#
::oo::define ::graph method bindings {args} {
    array set myArgs {legend 0 crosshairs 0 zoom 0 findelement 0}
    foreach myName $args {
        if {![info exists myArgs($myName)]} {
            return -code error "wrong or double name '$myName' in given list"
        }
        set myArgs($myName) 1
    }
    set my  [namespace which my]
    if {$myArgs(legend)} {
        my legend bind all <Enter> [list $my _legend activate]
	    my legend bind all <Leave> [list $my _legend deactivate]
	    my legend bind all <ButtonPress-1> [list $my _legend select]
    } else {
        my legend bind all <Enter> {}
	    my legend bind all <Leave> {}
	    my legend bind all <ButtonPress-1> {}
    }
    if {$myArgs(crosshairs)} {
        my crosshairs on
        my _bindtag bind cross <Any-Motion> {%W crosshairs configure -position @%x,%y}
        my _bindtag bind cross <Leave> {%W crosshairs off}
        my _bindtag bind cross <Enter> {%W crosshairs on}
	    my _bindtag add cross
    } else {
        my crosshairs off
	    my _bindtag remove cross
    }
    if {$myArgs(zoom)} {
        my _zoom init
        my _bindtag bind zoom <ButtonPress-1> [list $my _zoom setpoint %x %y]
        my _bindtag bind zoom <ButtonPress-3> [list $my _zoom reset]
        my _bindtag add zoom
    } else {
        my _zoom remove
	    my _bindtag remove zoom
    }
    if {$myArgs(findelement)} {
        my _bindtag bind find <Control-ButtonPress-2> [list $my _findelement %x %y]
        my _bindtag bind find <Control-ButtonRelease-2> [list $my _findelement {} {}]
        my _bindtag add find
    } else {
        my _findelement {} {}
        my _bindtag remove find
    }
}

#
# Private functions.
#

# ::graph _legend --
#
#   Helper function for legend bindings.
#
# Arguments:
# mode -    Indicate what to do
#   - activate "w"
#   - deactivate "w"
#   - select "w"
::oo::define ::graph method _legend {mode} {
    set elem [my legend get current]
    switch -- $mode {
        activate {
            my legend activate $elem
        }
        deactivate {
            my legend deactivate $elem
        }
        select {
            set relief [my element cget $elem -labelrelief]
            if { $relief eq "flat" } {
        	    my element configure $elem -labelrelief raised
        	    my element activate $elem
            } else {
        	    my element configure $elem -labelrelief flat
        	    my element deactivate $elem
            }
        }
    }
}

# ::graph _bindtag --
#
#   Helper function to add/remove of bindtags.
#
# Arguments:
# mode -    Indicate what to do
#   - add "widget" "tag"
#   - remove "widget" "tag"
# tag -     Tag to add or remove
::oo::define ::graph method _bindtag {mode tag args} {
    set w   [string range [self] 2 end]
    set oldTagList [bindtags $w]
    append tag $w;#add window path name to make it unique
    switch -- $mode {
        add {
            if {$tag ni $oldTagList} {
	            bindtags $w [linsert $oldTagList 0 $tag]
            }
        }
        remove {
            set index [lsearch $oldTagList $tag]
            if { $index >= 0 } {
	            bindtags $w [lreplace $oldTagList $index $index]
            }
        }
        bind {
            puts "bind $tag {*}$args"
            bind $tag {*}$args
        }
    }
}

option add *_graph_findelelementText.font	  -*-helvetica-medium-R-*-*-10-*-*-*-*-*-*-* 

# ::graph _findelement --
#
#   Helper function to flash nearest elemnt.
#
# Arguments:
# graph -   Name of graph widget
# x -       x coordinate
# y -       y coordinate
::oo::define ::graph method _findelement {x y} {
	my marker delete _graph_findelementText _graph_findelementLine
    if {$x eq {} || $y eq {} || ![my element closest $x $y my -halo 50]} {
	    return
    }
    # my(name)		- element Id
    # my(index)		- index of closest point
    # my(x) my(y)	- coordinates of closest point
    # my(dist)		- distance from sample coordinate
    lassign [my invtransform $x $y] x y
    if {$x > $my(x)} {
        if {$y > $my(y)} {
            set myAnchor sw
        } else {
            set myAnchor nw
        }
    } else {
        if {$y > $my(y)} {
            set myAnchor se
        } else {
            set myAnchor ne
        }
    }
    my marker create text \
        -coords [list $x $y] \
	    -name   _graph_findelementText \
	    -text   "$my(name)($my(index))=$my(x),$my(y)" \
	    -anchor $myAnchor\
        -bg     {} 
    my marker create line\
        -coords     [list $x $y $my(x) $my(y)]\
        -linewidth  2\
	    -name _graph_findelementLine

    my element activate $my(name) $my(index)
    after 2000 [self] element deactivate $my(name)
}

option add *_graph_zoomOutline.dashes		4	
option add *_graph_zoomTitle.anchor		    nw
option add *_graph_zoomOutline.lineWidth	2
option add *_graph_zoomOutline.xor		    yes
option add *_graph_zoomTitle.shadow	        yellow4
option add *_graph_zoomTitle.foreground     yellow1
option add *_graph_zoomTitle.coords	        [list -Inf Inf]

# ::graph _zoom --
#
#   Helper function for zooming.
#
# Arguments:
# mode    - indicate what to do
#   - init
#   - destroy
#   - titledestroy
#   - titlenext
#   - titlelast
#   - pop
#   - push
#   - reset
#   - setpoint "x" "y"
#   - box "x" "y"
#   - marchingants
# w -   Name of graph widget
#       
::oo::define ::graph method _zoom {mode args} {
    variable _zoom

    switch -- $mode {
    init {;# initialize zooming data
        set _zoom(interval) 100
        set _zoom(afterId) 0
        set _zoom(A,x) {}
        set _zoom(A,y) {}
        set _zoom(B,x) {}
        set _zoom(B,y) {}
        set _zoom(stack) {}
        set _zoom(corner) A
        set _zoom(ants) 0
    }
    titledestroy {
        if { $_zoom(corner) eq "A" } {
	        catch { my marker delete "_graph_zoomTitle" }
        }
    }
    titlenext {
        set level [expr {[llength $_zoom(stack)] + 1}]
        if { [my cget -invertxy] } {
	        set coords [list -Inf -Inf]
        } else {
	        set coords [list -Inf Inf]
        }
        my marker create text\
        -name       "_graph_zoomTitle"\
        -text       "Zoom #$level"\
	    -coords     $coords\
        -bindtags   ""\
        -anchor     nw

    }
    titlelast {
        set level [llength $_zoom(stack)]
        if { $level > 0 } {
     	    my marker create text\
            -name   "_graph_zoomTitle"\
            -anchor nw\
	        -text   "Zoom #$level" 
        }
    }
    pop {
        if { [llength $_zoom(stack)] > 0 } {
	        set _zoom(stack) [lassign $_zoom(stack) cmd]
	        uplevel #0 $cmd
	        my _zoom titlelast
            # get window from self
	        event generate [string range [self] 2 end] <Configure>
	        update idletasks
	        after 2000 [list [namespace which my] _zoom titledestroy]
        } else {
	        catch { my marker delete "_graph_zoomTitle" }
        }
    }
    push {
        my marker delete {*}[my marker names "_graph_zoom*"]
        if { [info exists _zoom(afterId)] } {
	        after cancel $_zoom(afterId)
        }
        set x1 $_zoom(A,x)
        set y1 $_zoom(A,y)
        set x2 $_zoom(B,x)
        set y2 $_zoom(B,y)

	    # No delta, revert to start
        if { ($x1 == $x2) || ($y1 == $y2) } return
        set cmd {}
        foreach margin { xaxis yaxis x2axis y2axis } {
	        foreach axis [my $margin use] {
	            set min [my axis cget $axis -min] 
	            set max [my axis cget $axis -max]
	            append cmd [list [self] axis configure $axis -min $min -max $max] \
		        "\n"
	        }
        }
        set _zoom(stack) [linsert $_zoom(stack) 0 $cmd]

        foreach margin { xaxis x2axis } {
	        foreach axis [my $margin use] {
	            set min [my axis invtransform $axis $x1]
	            set max [my axis invtransform $axis $x2]
	            if { $min > $max } { 
		            my axis configure $axis -min $max -max $min
	            } else {
		            my axis configure $axis -min $min -max $max
	            }
	        }
        }
        foreach margin { yaxis y2axis } {
	        foreach axis [my $margin use] {
	            set min [my axis invtransform $axis $y1]
	            set max [my axis invtransform $axis $y2]
	            if { $min > $max } { 
		            my axis configure $axis -min $max -max $min
	            } else {
		            my axis configure $axis -min $min -max $max
	            }
	        }
        }
        # get window from self
        event generate [string range [self] 2 end] <Configure>
        update idletasks
    }
    reset {
        # This routine terminates either an existing zoom, or pops back to
        # the previous zoom level (if no zoom is in progress).
        if { ![info exists _zoom(corner)] } {
	        my _zoom init
        }
        my marker delete {*}[my marker names "_graph_zoom*"]

        if { $_zoom(corner) eq "A" } {
	        # Reset the whole axis
	        my _zoom pop
        } else {
	        set _zoom(corner) A
	        my _bindtag remove select-region
        }
    }
    remove {;# reset to very first level
        if {[info exists _zoom(stack)]} {
            if { [llength $_zoom(stack)] > 0 } {
	            uplevel #0 [lindex $_zoom(stack) 0]
	            event generate [string range [self] 2 end] <Configure>
            }
            my marker delete {*}[my marker names "_graph_zoom*"]
        }
        my _zoom init
    }
    setpoint {;# 
        lassign $args x y
        if { ![info exists _zoom(corner)] } {
		    my _zoom init
        }
        my _bindtag bind zoomregion <Any-Motion>\
            [list [namespace which my] _zoom box %x %y]
        if { $_zoom(corner) eq {A} } {
		    if { ![my inside $x $y] } return
            if { [my cget -invertxy] } {
		        set _zoom(A,x) $y
		        set _zoom(A,y) $x
            } else {
		        set _zoom(A,x) $x
		        set _zoom(A,y) $y
            }
		    # First corner selected, start watching motion events
		    my _zoom titlenext 
		    my _bindtag add zoomregion
		    set _zoom(corner) B
        } else {
            if { [my cget -invertxy] } {
		        set _zoom(B,x) $y
		        set _zoom(B,y) $x
            } else {
		        set _zoom(B,x) $x
		        set _zoom(B,y) $y
            }
		    # Delete the modal binding
		    my _bindtag remove zoomregion
		    my _zoom push
		    set _zoom(corner) A
        }
    }
    box {;#
        lassign $args x y;# coords of second point
        if { [my cget -invertxy] } {
	        set _zoom(B,x) $y
	        set _zoom(B,y) $x
        } else {
	        set _zoom(B,x) $x
	        set _zoom(B,y) $y
        }
        if { $_zoom(A,x) > $_zoom(B,x) } { 
	        set x1 [my xaxis invtransform $_zoom(B,x)]
	        set y1 [my yaxis invtransform $_zoom(B,y)]
	        set x2 [my xaxis invtransform $_zoom(A,x)]
	        set y2 [my yaxis invtransform $_zoom(A,y)]
        } else {
	        set x1 [my xaxis invtransform $_zoom(A,x)]
	        set y1 [my yaxis invtransform $_zoom(A,y)]
	        set x2 [my xaxis invtransform $_zoom(B,x)]
	        set y2 [my yaxis invtransform $_zoom(B,y)]
        }
        set coords { $x1 $y1 $x2 $y1 $x2 $y2 $x1 $y2 $x1 $y1 }
        if { [my marker exists "_graph_zoomOutline"] } {
	        my marker configure "_graph_zoomOutline" -coords $coords 
        } else {
	        set X [lindex [my xaxis use] 0]
	        set Y [lindex [my yaxis use] 0]
	        my marker create line\
            -coords $coords\
            -name   "_graph_zoomOutline"\
	        -mapx   $X\
            -mapy   $Y
	        set interval $_zoom(interval)
            set _zoom(ants) 0
	        set id [after $interval [list [namespace which my] _zoom marchingants]]
	        set _zoom(afterId) $id
        }
    }
    marchingants {
        incr _zoom(ants)
        if {[my marker exists _graph_zoomOutline]} {
	        my marker configure _graph_zoomOutline -dashoffset $_zoom(ants)
	        set interval $_zoom(interval)
	        set id [after $interval [list [namespace which my] _zoom marchingants]]
	        set _zoom(afterId) $id
        }
    }
    default {}
    }
}

# TODO Check if ::tk::ps_preamble can be used instead.
# It is used be the graph postscript method.
set ::::graph::ps_preamble\
{%%BeginProlog
%
% PostScript prolog file of the rbc graph widget.
%
% Copyright 1989-1992 Regents of the University of California.
% Permission to use, copy, modify, and distribute this
% software and its documentation for any purpose and without
% fee is hereby granted, provided that the above copyright
% notice appear in all copies.  The University of California
% makes no representations about the suitability of this
% software for any purpose.  It is provided "as is" without
% express or implied warranty.
%
% Copyright 1991-1997 Bell Labs Innovations for Lucent Technologies.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for any purpose and without fee is hereby granted, provided
% that the above copyright notice appear in all copies and that both that the
% copyright notice and warranty disclaimer appear in supporting documentation,
% and that the names of Lucent Technologies any of their entities not be used
% in advertising or publicity pertaining to distribution of the software
% without specific, written prior permission.
%
% Lucent Technologies disclaims all warranties with regard to this software,
% including all implied warranties of merchantability and fitness.  In no event
% shall Lucent Technologies be liable for any special, indirect or
% consequential damages or any damages whatsoever resulting from loss of use,
% data or profits, whether in an action of contract, negligence or other
% tortuous action, arising out of or in connection with the use or performance
% of this software.
%

200 dict begin

/BaseRatio 1.3467736870885982 def	% Ratio triangle base / symbol size
/BgColorProc 0 def			% Background color routine (symbols)
/DrawSymbolProc 0 def			% Routine to draw symbol outline/fill
/StippleProc 0 def			% Stipple routine (bar segments)
/DashesProc 0 def			% Dashes routine (line segments)
  
% Define the array ISOLatin1Encoding (which specifies how characters are 
% encoded for ISO-8859-1 fonts), if it isn't already present (Postscript 
% level 2 is supposed to define it, but level 1 doesn't). 
 
systemdict /ISOLatin1Encoding known not { 
  /ISOLatin1Encoding [ 
    /space /space /space /space /space /space /space /space 
    /space /space /space /space /space /space /space /space 
    /space /space /space /space /space /space /space /space 
    /space /space /space /space /space /space /space /space 
    /space /exclam /quotedbl /numbersign /dollar /percent /ampersand 
    /quoteright 
    /parenleft /parenright /asterisk /plus /comma /minus /period /slash 
    /zero /one /two /three /four /five /six /seven 
    /eight /nine /colon /semicolon /less /equal /greater /question 
    /at /A /B /C /D /E /F /G 
    /H /I /J /K /L /M /N /O 
    /P /Q /R /S /T /U /V /W 
    /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore 
    /quoteleft /a /b /c /d /e /f /g 
    /h /i /j /k /l /m /n /o 
    /p /q /r /s /t /u /v /w 
    /x /y /z /braceleft /bar /braceright /asciitilde /space 
    /space /space /space /space /space /space /space /space 
    /space /space /space /space /space /space /space /space 
    /dotlessi /grave /acute /circumflex /tilde /macron /breve /dotaccent 
    /dieresis /space /ring /cedilla /space /hungarumlaut /ogonek /caron 
    /space /exclamdown /cent /sterling /currency /yen /brokenbar /section 
    /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen 
    /registered /macron 
    /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph 
    /periodcentered 
    /cedillar /onesuperior /ordmasculine /guillemotright /onequarter 
    /onehalf /threequarters /questiondown 
    /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla 
    /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex 
    /Idieresis 
    /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply 
    /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn 
    /germandbls 
    /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla 
    /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex 
    /idieresis 
    /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide 
    /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn 
    /ydieresis 
  ] def 
} if 

% font ISOEncode font 
% This procedure changes the encoding of a font from the default 
% Postscript encoding to ISOLatin1.  It is typically invoked just 
% before invoking "setfont".  The body of this procedure comes from 
% Section 5.6.1 of the Postscript book. 

/ISOEncode { 
  dup length dict
  begin 
    {1 index /FID ne {def} {pop pop} ifelse} forall 
    /Encoding ISOLatin1Encoding def 
    currentdict 
  end 

  % I'm not sure why it's necessary to use "definefont" on this new 
  % font, but it seems to be important; just use the name "Temporary" 
  % for the font. 

  /Temporary exch definefont 
} bind def 

/Stroke {
  gsave
    stroke
  grestore
} def

/Fill {
  gsave
    fill
  grestore
} def

/SetFont { 	
  % Stack: pointSize fontName
  findfont exch scalefont ISOEncode setfont
} def

/Box {
  % Stack: x y width height
  newpath
  exch 4 2 roll moveto
  dup 0 rlineto
  exch 0 exch rlineto
  neg 0 rlineto
  closepath
} def

/SetFgColor {
  % Stack: red green blue
  CL 0 eq { 
    pop pop pop 0 0 0 
  } if
  setrgbcolor
  CL 1 eq { 
    currentgray setgray 
  } if
} def

/SetBgColor {
  % Stack: red green blue
  CL 0 eq { 
    pop pop pop 1 1 1 
  } if
  setrgbcolor
  CL 1 eq { 
    currentgray setgray 
  } if
} def

% The next two definitions are taken from "$tk_library/prolog.ps"

% desiredSize EvenPixels closestSize
%
% The procedure below is used for stippling.  Given the optimal size
% of a dot in a stipple pattern in the current user coordinate system,
% compute the closest size that is an exact multiple of the device's
% pixel size.  This allows stipple patterns to be displayed without
% aliasing effects.

/EvenPixels {
  % Compute exact number of device pixels per stipple dot.
  dup 0 matrix currentmatrix dtransform
  dup mul exch dup mul add sqrt

  % Round to an integer, make sure the number is at least 1, and compute
  % user coord distance corresponding to this.
  dup round dup 1 lt {pop 1} if
  exch div mul
} bind def

% width height string filled StippleFill --
%
% Given a path and other graphics information already set up, this
% procedure will fill the current path in a stippled fashion.  "String"
% contains a proper image description of the stipple pattern and
% "width" and "height" give its dimensions.  If "filled" is true then
% it means that the area to be stippled is gotten by filling the
% current path (e.g. the interior of a polygon); if it's false, the
% area is gotten by stroking the current path (e.g. a wide line).
% Each stipple dot is assumed to be about one unit across in the
% current user coordinate system.

% width height string StippleFill --
%
% Given a path already set up and a clipping region generated from
% it, this procedure will fill the clipping region with a stipple
% pattern.  "String" contains a proper image description of the
% stipple pattern and "width" and "height" give its dimensions.  Each
% stipple dot is assumed to be about one unit across in the current
% user coordinate system.  This procedure trashes the graphics state.

/StippleFill {
    % The following code is needed to work around a NeWSprint bug.

    /tmpstip 1 index def

    % Change the scaling so that one user unit in user coordinates
    % corresponds to the size of one stipple dot.
    1 EvenPixels dup scale

    % Compute the bounding box occupied by the path (which is now
    % the clipping region), and round the lower coordinates down
    % to the nearest starting point for the stipple pattern.  Be
    % careful about negative numbers, since the rounding works
    % differently on them.

    pathbbox
    4 2 roll
    5 index div dup 0 lt {1 sub} if cvi 5 index mul 4 1 roll
    6 index div dup 0 lt {1 sub} if cvi 6 index mul 3 2 roll

    % Stack now: width height string y1 y2 x1 x2
    % Below is a doubly-nested for loop to iterate across this area
    % in units of the stipple pattern size, going up columns then
    % across rows, blasting out a stipple-pattern-sized rectangle at
    % each position

    6 index exch {
	2 index 5 index 3 index {
	    % Stack now: width height string y1 y2 x y

	    gsave
	    1 index exch translate
	    5 index 5 index true matrix tmpstip imagemask
	    grestore
	} for
	pop
    } for
    pop pop pop pop pop
} bind def


/LS {	% Stack: x1 y1 x2 y2
  newpath 4 2 roll moveto lineto stroke
} def

/EndText {
  %Stack :
  grestore
} def

/BeginText {
  %Stack :  w h theta centerX centerY
  gsave
    % Translate the origin to the center of bounding box and rotate
    translate neg rotate
    % Translate back to the origin of the text region
    -0.5 mul exch -0.5 mul exch translate
} def

/DrawAdjText {
  %Stack : str strWidth x y
  moveto				% Go to the text position
  exch dup dup 4 2 roll

  % Adjust character widths to get desired overall string width
  % adjust X = (desired width - real width)/#chars

  stringwidth pop sub exch
  length div
  0 3 -1 roll

  % Flip back the scale so that the string is not drawn in reverse

  gsave
    1 -1 scale
    ashow
  grestore
} def

/DrawBitmap {
  % Stack: ?bgColorProc? boolean centerX centerY width height theta imageStr
  gsave
    6 -2 roll translate			% Translate to center of bounding box
    4 1 roll neg rotate			% Rotate by theta
    
    % Find upperleft corner of bounding box
    
    2 copy -.5 mul exch -.5 mul exch translate
    2 copy scale			% Make pixel unit scale
    newpath
    0 0 moveto 0 1 lineto 1 1 lineto 1 0 lineto
    closepath
    
    % Fill rectangle with background color
    
    4 -1 roll { 
      gsave 
	4 -1 roll exec fill 
      grestore 
    } if
    
    % Paint the image string into the unit rectangle
    
    2 copy true 3 -1 roll 0 0 5 -1 roll 0 0 6 array astore 5 -1 roll
    imagemask
  grestore
} def

% Symbols:

% Skinny-cross
/Sc {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate 45 rotate
    0 0 3 -1 roll Sp
  grestore
} def

% Skinny-plus
/Sp {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate
    2 idiv
    dup 2 copy
    newpath neg 0 moveto 0 lineto
    DrawSymbolProc
    newpath neg 0 exch moveto 0 exch lineto
    DrawSymbolProc
  grestore
} def

% Cross
/Cr {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate 45 rotate
    0 0 3 -1 roll Pl
  grestore
} def

% Plus
/Pl {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate
    dup 2 idiv
    exch 6 idiv

    %
    %          2   3		The plus/cross symbol is a
    %				closed polygon of 12 points.
    %      0   1   4    5	The diagram to the left
    %           x,y		represents the positions of
    %     11  10   7    6	the points which are computed
    %				below.
    %          9   8
    %

    newpath
    2 copy exch neg exch neg moveto dup neg dup lineto
    2 copy neg exch neg lineto 2 copy exch neg lineto
    dup dup neg lineto 2 copy neg lineto 2 copy lineto
    dup dup lineto 2 copy exch lineto 2 copy neg exch lineto
    dup dup neg exch lineto exch neg exch lineto
    closepath
    DrawSymbolProc
  grestore
} def

% Circle
/Ci {
  % Stack: x y symbolSize
  gsave
    3 copy pop
    moveto newpath
    2 div 0 360 arc
    closepath DrawSymbolProc
  grestore
} def

% Square
/Sq {
  % Stack: x y symbolSize
  gsave
    dup dup 2 div dup
    6 -1 roll exch sub exch
    5 -1 roll exch sub 4 -2 roll Box
    DrawSymbolProc
  grestore
} def

% Line
/Li {
  % Stack: x y symbolSize
  gsave
    3 1 roll exch 3 -1 roll 2 div 3 copy
    newpath
    sub exch moveto add exch lineto
    stroke
  grestore
} def

% Diamond
/Di {
  % Stack: x y symbolSize
  gsave
    3 1 roll translate 45 rotate 0 0 3 -1 roll Sq
  grestore
} def
    
% Triangle
/Tr {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate
    BaseRatio mul 0.5 mul		% Calculate 1/2 base
    dup 0 exch 30 cos mul		% h1 = height above center point
    neg					% b2 0 -h1
    newpath moveto			% point 1;  b2
    dup 30 sin 30 cos div mul		% h2 = height below center point
    2 copy lineto			% point 2;  b2 h2
    exch neg exch lineto		% 
    closepath
    DrawSymbolProc
  grestore
} def

% Arrow
/Ar {
  % Stack: x y symbolSize
  gsave
    3 -2 roll translate
    BaseRatio mul 0.5 mul		% Calculate 1/2 base
    dup 0 exch 30 cos mul		% h1 = height above center point
					% b2 0 h1
    newpath moveto			% point 1;  b2
    dup 30 sin 30 cos div mul		% h2 = height below center point
    neg					% -h2 b2
    2 copy lineto			% point 2;  b2 h2
    exch neg exch lineto		% 
    closepath
    DrawSymbolProc
  grestore
} def

% Bitmap
/Bm {
  % Stack: x y symbolSize
  gsave
    3 1 roll translate pop DrawSymbolProc
  grestore
} def

%%EndProlog

%%BeginSetup
gsave					% Save the graphics state

% Default line/text style parameters

1 setlinewidth				% width
1 setlinejoin				% join
0 setlinecap				% cap
[] 0 setdash				% dashes

/CL 0 def				% Set color level mode
0 0 0 setrgbcolor			% color
}
# vim: set ts=4 sw=4 sts=4 ff=unix et :
Added library/path.tcl.
















































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# path.tcl --
#
#       Various support procedures for the path widget.
#
#  Copyright (c) 2018 [email protected]
#

namespace eval ::path {
    # All functions inside this namespace return a transormation matrix.
    namespace eval matrix {
	namespace export *
	namespace ensemble create
    }
    # All functions inside this namespace return a path description.
    namespace eval path {
	namespace export *
	namespace ensemble create
    }
}

# ::path::matrix::rotate --
# Arguments:
#   angle   Angle in grad
#   cx      X-center coordinate
#   cy      Y-center coordinate
# Results:
#       The transformation matrix.
proc ::path::matrix::rotate {angle {cx 0} {cy 0}} {
    set myCos [expr {cos($angle)}]
    set mySin [expr {sin($angle)}]
    if {$cx == 0 && $cy == 0} {
        return [list $myCos $mySin [expr {-1.*$mySin}] $myCos 0 0]
    }
    return [list $myCos $mySin [expr {-1.*$mySin}] $myCos \
        [expr {$cx - $myCos*$cx + $mySin*$cy}] \
        [expr {$cy - $mySin*$cx - $myCos*$cy}]]
}

# ::path::matrix::scale --
# Arguments:
#   sx  Scaling factor x-coordinate
#   sy  Scaling factor y-coordinate
# Results:
#       The transformation matrix.
proc ::path::matrix::scale {sx {sy {}}} {
    if {$sy eq {}} {set sy $sx}
    return [list $sx 0 0 $sy 0 0]
}

# ::path::matrix::flip --
# Arguments:
#   fx  1 no flip, -1 horizontal flip
#   fy  1 no flip, -1 vertical flip
# Results:
#       The transformation matrix.
proc ::path::matrix::flip {{cx 0} {cy 0} {fx 1} {fy 1}} {
    return [list $fx 0 0 $fy [expr {$cx*(1-$fx)}] [expr {$cy*($fy-1)}]]
}

# ::path::matrix::rotateflip --
# Arguments:
#   angle   Angle in grad
#   cx      X-center coordinate
#   cy      Y-center coordinate
#   fx      1 no flip, -1 horizontal flip
#   fy      1 no flip, -1 vertical flip
# Results:
#       The transformation matrix.
proc ::path::matrix::rotateflip {{angle 0} {cx 0} {cy 0} {fx 1} {fy 1}} {
    set myCos [expr {cos($angle)}]
    set mySin [expr {sin($angle)}]
    if {$cx == 0 && $cy == 0} {
    return [list [expr {$fx*$myCos}] [expr {$fx*$mySin}] \
        [expr {-1.*$mySin*$fy}] [expr {$myCos*$fy}] 0 0]
    }
    return [list [expr {$fx*$myCos}] [expr {$fx*$mySin}] \
        [expr {-1.*$mySin*$fy}] [expr {$myCos*$fy}] \
        [expr {$myCos*$cx*(1.-$fx) - $mySin*$cy*($fy-1.) + $cx - $myCos*$cx + $mySin*$cy}] \
        [expr {$mySin*$cx*(1.-$fx) + $myCos*$cy*($fy-1.) + $cy - $mySin*$cx - $myCos*$cy}] \
    ]

}

# ::path::matrixs::kewx --
# Arguments:
#   angle   Angle in grad
# Results:
#       The transformation matrix.
proc ::path::matrix::skewx {angle} {
    return [list 1 0 [expr {tan($angle)}] 1 0 0]
}

# ::path::matrix::skewy --
# Arguments:
#   angle   Angle in grad
# Results:
#       The transformation matrix.
proc ::path::matrix::skewy {angle} {
    return [list 1 [expr {tan($angle)}] 0 1 0 0]
}

# ::path::matrix::move --
# Arguments:
#   dx  Difference in x direction
#   dy  Difference in y direction
# Results:
#       The transformation matrix.
proc ::path::matrix::move {dx dy} {
    return [list 1 0 0 1 $dx $dy]
}

# ::path::matrix::mult --
# Arguments:
#   ma  First matrix
#   mb  Second matrix
# Results:
#       Product of transformation matrices.
proc ::path::matrix::mult {ma mb} {
    lassign $ma a1 b1 c1 d1 x1 y1
    lassign $mb a2 b2 c2 d2 x2 y2
    return [list \
        [expr {$a1*$a2 + $c1*$b2}] [expr {$b1*$a2 + $d1*$b2}] \
        [expr {$a1*$c2 + $c1*$d2}] [expr {$b1*$c2 + $d1*$d2}] \
        [expr {$a1*$x2 + $c1*$y2 + $x1}] [expr {$b1*$x2 + $d1*$y2 + $y1}]]
}

# ::path::path::ellipse --
# Arguments:
#   x   Start x coordinate
#   y   Start y coordinate
#   rx  Radius in x direction
#   ry  Radius in y direction
# Results:
#   The path definition.
proc ::path::path::ellipse {x y rx ry} {
    return [list M $x $y a $rx $ry 0 1 1 0 [expr {2*$ry}] a $rx $ry 0 1 1 0 [expr {-2*$ry}] Z]
}

# ::path::path::circle --
# Arguments:
#   x   Start x coordinate
#   y   Start y coordinate
#   r   Radius of circle
# Results:
#       The path definition.
proc ::path::path::circle {x y r} {
    return [list M $x $y a $r $r 0 1 1 0 [expr {2*$r}] a $r $r 0 1 1 0 [expr {-2*$r}] Z]
}

# ::path::gradientstopsstyle --
#       Utility function to create named example gradient definitions.
# Arguments:
#       name      the name of the gradient
#       args
# Results:
#       The stops list.
proc ::path::gradientstopsstyle {name args} {
    switch -- $name {
    rainbow {
        return {
            {0.00 "#ff0000"}
            {0.15 "#ff7f00"}
            {0.30 "#ffff00"}
            {0.45 "#00ff00"}
            {0.65 "#0000ff"}
            {0.90 "#7f00ff"}
            {1.00 "#7f007f"}
        }
    }
    default {
        return -code error "the named gradient '$name' is unknown"
    }
    }
}

# vim: set ts=4 sw=4 sts=4 ff=unix et :
Changes to library/tk.tcl.
506
507
508
509
510
511
512


513
514
515
516
517
518
519
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521







+
+







	SourceLibFile listbox
	SourceLibFile menu
	SourceLibFile panedwindow
	SourceLibFile scale
	SourceLibFile scrlbar
	SourceLibFile spinbox
	SourceLibFile text
	SourceLibFile graph
	SourceLibFile path
    }
}

# ----------------------------------------------------------------------
# Default bindings for keyboard traversal.
# ----------------------------------------------------------------------

684
685
686
687
688
689
690

691
692
693
694
695
686
687
688
689
690
691
692
693
694
695
696
697
698







+





    }
}

# Run the Ttk themed widget set initialization
if {$::ttk::library ne ""} {
    uplevel \#0 [list source $::ttk::library/ttk.tcl]
}


# Local Variables:
# mode: tcl
# fill-column: 78
# End:
Changes to tests/tk.test.
13
14
15
16
17
18
19
20

21
22
23
24
25
26
27
13
14
15
16
17
18
19

20
21
22
23
24
25
26
27







-
+







testConstraint testprintf [llength [info command testprintf]]

test tk-1.1 {tk command: general} -body {
    tk
} -returnCodes error -result {wrong # args: should be "tk subcommand ?arg ...?"}
test tk-1.2 {tk command: general} -body {
    tk xyz
} -returnCodes error -result {unknown or ambiguous subcommand "xyz": must be appname, busy, caret, fontchooser, inactive, scaling, useinputmethods, or windowingsystem}
} -returnCodes error -result {unknown or ambiguous subcommand "xyz": must be appname, busy, caret, fontchooser, inactive, scaling, snap, useinputmethods, or windowingsystem}

# Value stored to restore default settings after 2.* tests
set appname [tk appname]
test tk-2.1 {tk command: appname} -body {
    tk appname xyz abc
} -returnCodes error -result {wrong # args: should be "tk appname ?newName?"}
test tk-2.2 {tk command: appname} -body {
Added tests/tko/all.tcl.

















1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# all.tcl --
#
# This file contains a top-level script to run all of the Tcl
# tests.  Execute it by invoking "make test" 
#

# restart using tclsh \
exec tclsh "$0" "$@"

package require Tk ;# This is for a Tk Widget; fail early if no Tk!
package require tcltest 2

tcltest::configure {*}$argv
tcltest::configure -testdir [file normalize [file dirname [info script]]]
tcltest::configure -singleproc 1
tcltest::runAllTests

Added tests/tko/binReadTestFile.txt.

cannot compute difference between binary files

Added tests/tko/greenback.xbm.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#define greenback_width 499
#define greenback_height 210
static char greenback_bits[] = {
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x44,
 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21,0x09,0x10,0x00,0x00,0x00,
 0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,
 0x20,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x22,0x00,0x40,0x00,
 0x08,0x20,0x20,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x10,
 0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x02,0x00,
 0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x08,0x11,0x00,0x00,0x01,0x00,
 0x00,0x00,0x48,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x20,0x02,0x04,
 0x48,0x10,0x02,0x01,0x01,0x09,0x00,0x00,0x80,0x00,0x80,0x00,0x00,0x00,0x00,
 0x22,0x90,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x04,0x04,0x48,0x10,0x01,
 0x41,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x02,0x04,0x10,0x40,0x00,0x00,0x00,
 0x40,0x00,0x02,0x08,0x48,0x00,0x02,0x80,0x20,0x00,0x00,0x80,0x04,0x00,0x00,
 0x01,0x40,0x00,0x00,0x04,0x10,0x00,0x44,0x00,0x00,0x00,0x10,0x14,0x22,0x54,
 0xa4,0xb6,0xf7,0xfe,0x6f,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0x9f,0xaa,0xd9,
 0x95,0xef,0xfe,0xba,0xda,0xd7,0x56,0x77,0xaf,0x56,0x7d,0x81,0x50,0x45,0x15,
 0xc9,0x00,0x00,0x00,0x6d,0xb5,0xd3,0x95,0xab,0xaa,0x35,0xad,0xaa,0x4a,0x29,
 0x40,0x92,0x40,0x80,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x20,0x11,0x22,0x12,0x00,0x21,0x25,0x55,0xa8,0xa4,0x54,0xa9,0xaa,0x92,0x7e,
 0x6f,0x7b,0xed,0xbe,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x88,0x00,0x42,0xa4,0x00,0x08,
 0x41,0x00,0x00,0x01,0x00,0x81,0x80,0xa4,0x54,0x5b,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xbf,0x08,0x00,0x10,0xfd,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe7,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3f,0xbb,0xf7,0x80,0x84,
 0x28,0x22,0x00,0x06,0x14,0x0c,0x68,0x04,0x08,0x80,0xf7,0xf7,0xfd,0xff,0xbf,
 0xfb,0xff,0xf3,0xff,0xff,0xbb,0xea,0xef,0xbb,0xbf,0x00,0x00,0x00,0xdd,0xbf,
 0xfe,0xbf,0xfe,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xef,0xe7,0x8a,0x5a,
 0x82,0x92,0xb4,0x40,0x48,0x40,0x7f,0x7b,0x54,0x3e,0x02,0x06,0x00,0x07,0x00,
 0x00,0x0c,0x06,0x03,0x23,0x08,0x1e,0x30,0x8e,0xe1,0x84,0x08,0x0e,0xe7,0xbf,
 0xbe,0xef,0x7b,0xf5,0xda,0xb5,0xbd,0x5f,0xbf,0xff,0xee,0xae,0xbf,0x00,0x00,
 0x00,0xf5,0x5d,0x9f,0xdf,0xdf,0xff,0xff,0xef,0xbf,0x63,0xeb,0xfe,0xbf,0xd6,
 0xe5,0xc0,0x18,0x1c,0x83,0xc1,0xe0,0x38,0x1a,0x3c,0xf0,0x81,0x3f,0x18,0x18,
 0x1c,0x83,0x7f,0xf0,0x1c,0x06,0x02,0x77,0x78,0x3e,0x61,0x83,0x43,0x82,0x19,
 0x2c,0x67,0xd5,0x6f,0x53,0xb7,0xdd,0xff,0xe5,0x67,0xed,0xee,0xae,0xe7,0x7d,
 0xab,0x08,0x00,0x00,0xbd,0xdf,0xaf,0x7f,0xbb,0xfd,0xee,0xcf,0xfb,0xdf,0xbf,
 0xff,0xfd,0xfb,0xe7,0xc1,0x19,0x2c,0x87,0xc1,0x61,0x3b,0x1c,0x1c,0xf0,0xc1,
 0x7f,0x38,0x38,0x6c,0x01,0xf0,0xa0,0x1d,0x06,0x06,0x7f,0xc8,0x7f,0xc0,0x83,
 0xc3,0x96,0x9b,0xf0,0xe7,0xfe,0xdd,0xdd,0xfd,0xdf,0xae,0xa4,0xbb,0xba,0xbf,
 0xdd,0x77,0xff,0xbb,0x00,0x00,0x00,0xf5,0x6e,0xaf,0x6f,0xfe,0x5f,0xfb,0xd7,
 0xbf,0x7b,0xff,0x4e,0x77,0xef,0xe5,0x01,0x1e,0xe2,0x87,0xc3,0x21,0x3f,0x80,
 0xdf,0xe0,0xe1,0xff,0x00,0x3e,0xe4,0x03,0x60,0x10,0x3f,0x82,0x0f,0x7a,0xd0,
 0xfe,0x01,0x83,0xc3,0x87,0x1f,0x6c,0xe7,0x5b,0x7f,0xbf,0xb7,0xad,0x7b,0xe6,
 0xad,0x6a,0xd7,0xfb,0xcd,0xbe,0xbd,0x20,0x00,0x24,0x5d,0xbf,0xb6,0x5f,0xdd,
 0x57,0xfd,0x95,0xff,0xf7,0xdb,0xbd,0xbf,0xde,0xe7,0xc1,0x9e,0x6c,0x87,0xc1,
 0x61,0x3b,0x08,0x2e,0xe0,0xe1,0x7f,0x18,0x3c,0x6c,0x17,0x60,0xa2,0x1d,0x06,
 0x0f,0x3c,0x78,0x7e,0x03,0x83,0xc3,0x03,0x1f,0x3c,0xf7,0xfe,0xdb,0xfb,0xee,
 0xff,0x7f,0xe6,0xdf,0xf7,0xf6,0x76,0xcb,0xbe,0xbd,0x02,0x00,0x00,0xf5,0x7b,
 0x33,0xb5,0x5e,0xeb,0x57,0x97,0xdf,0xb5,0x7f,0xff,0xb5,0x5f,0xe3,0xc0,0x1f,
 0x1c,0x83,0xc1,0xe0,0x38,0x18,0xe6,0xc0,0x61,0x3c,0x10,0x18,0x0c,0xf3,0x70,
 0x30,0x0c,0x24,0x1e,0x1e,0x08,0x1e,0x46,0x8f,0xf1,0x03,0x86,0x04,0xa7,0xdd,
 0xb6,0xfe,0xba,0xaf,0x7f,0x67,0xf7,0xdf,0xbf,0xdb,0xdb,0x7f,0xbe,0x00,0x00,
 0x00,0xdd,0xfc,0xaa,0x2e,0xff,0xfa,0xff,0x27,0x7f,0x7b,0xb3,0x77,0x7b,0xdb,
 0x67,0x10,0x06,0x00,0x49,0xba,0x2a,0x08,0x25,0x80,0x00,0x84,0x2c,0x64,0x00,
 0x50,0x57,0xbf,0xdf,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xe7,0xfe,0xea,0xff,0xb3,0xff,0x6f,0xd7,0xfa,0xb5,0xf6,0xeb,0x9a,0x9f,
 0xb6,0x20,0x00,0x00,0xbd,0x79,0x3b,0xb6,0xde,0xde,0xdb,0x35,0xef,0xf6,0x5d,
 0xf7,0xdb,0x7e,0xe7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xe7,0xff,0xff,0xff,0xff,0xff,0xbf,0x47,0x6d,0xff,0xba,
 0xff,0xdb,0x97,0xbe,0x08,0x00,0x00,0xcd,0xf6,0xb6,0xae,0xad,0xf7,0x76,0x35,
 0xfe,0xff,0xff,0xff,0xff,0xff,0xa7,0x56,0x7b,0x55,0x92,0x52,0x40,0x22,0x01,
 0x08,0xa4,0x54,0x4a,0x01,0x12,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0xe0,0xe7,
 0xd6,0xef,0xe7,0x91,0x35,0x57,0xbe,0x00,0x00,0x00,0xfd,0xe6,0x3c,0xf7,0x5a,
 0xfc,0xcf,0x32,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x10,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x01,
 0x00,0x00,0x42,0x04,0xb5,0xd2,0xaa,0xfa,0xef,0xff,0xf7,0xf7,0xbd,0x55,0xdd,
 0xb6,0xad,0xc7,0xf3,0xfe,0xfe,0xe3,0x9d,0x6b,0xbe,0x00,0x00,0x40,0xdd,0xde,
 0x77,0x8e,0xc5,0x7f,0xaf,0x5f,0xf2,0xff,0xff,0xff,0xff,0xbf,0xed,0x75,0xab,
 0xd6,0x5a,0x55,0x8b,0x54,0x55,0xa9,0xab,0xaa,0xaa,0xaa,0x00,0x02,0x08,0x80,
 0x10,0x10,0x00,0x84,0x20,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0xa2,0xd3,0xfd,0x4b,0x49,0x40,0x77,0x7f,0xbe,0x02,0x00,
 0x00,0xfd,0xd6,0xbd,0x81,0xb6,0xfd,0xaf,0x3b,0x02,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x04,0x20,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x92,0xe7,0x74,0x01,0x00,0x04,0x00,0x20,
 0xbe,0x00,0x00,0x08,0xed,0xaa,0x7d,0x48,0x1d,0xee,0x6f,0x7e,0x36,0x40,0x80,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x04,0x00,0x00,0x00,0x41,0x20,0x84,0x00,0x02,0x00,0x00,0x08,0x10,0x00,0x20,
 0x42,0x02,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xa0,0x55,0xf7,0xa7,0xad,
 0xfe,0x6d,0x79,0xbf,0x40,0x00,0x00,0xfd,0x96,0x3d,0x82,0xeb,0xba,0x7f,0x2b,
 0x15,0x02,0x21,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x24,0x22,0x00,
 0x00,0x00,0x00,0x28,0x00,0x42,0x00,0x00,0x02,0x00,0x00,0x00,0x11,0x00,0x00,
 0x00,0x44,0x08,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x00,0x21,0xb0,0x67,
 0xa7,0xe7,0xff,0xf7,0xff,0x1b,0xbf,0x00,0x00,0x00,0xed,0xb4,0x0d,0xfc,0x14,
 0xf4,0xed,0x7c,0x82,0x10,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80,0x80,0x24,
 0x00,0x00,0x04,0x01,0x00,0x20,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x40,0x00,
 0x00,0x02,0x00,0x08,0x00,0x02,0x80,0x10,0x80,0x40,0x04,0x11,0x20,0x40,0x10,
 0x08,0xa9,0xad,0xe5,0xb7,0xff,0x7b,0xff,0x5a,0xb3,0x08,0x00,0x00,0xdd,0x2a,
 0x01,0x7f,0xff,0xe9,0xef,0xb8,0x0a,0x00,0x00,0x20,0x00,0x00,0x04,0x00,0x08,
 0x20,0x08,0x80,0x08,0x00,0x40,0x00,0x40,0x00,0x00,0x09,0x01,0x20,0x00,0x00,
 0x10,0x00,0x00,0xc0,0x40,0x42,0x02,0x0a,0xa8,0x60,0xeb,0x7f,0x5a,0x1b,0xd5,
 0xa1,0x0a,0x0c,0x00,0xa5,0xaf,0x53,0xb3,0xde,0xfa,0x57,0xdb,0xbf,0x00,0x00,
 0x20,0xfd,0x4a,0x93,0x6f,0xf7,0xc9,0xaf,0x78,0x03,0x40,0x24,0x8a,0x02,0x40,
 0x01,0x25,0x21,0x15,0xa5,0x02,0x52,0x49,0x05,0xad,0x00,0x80,0x11,0x52,0x42,
 0x41,0xb5,0xfd,0x17,0xbd,0x07,0x10,0x45,0x95,0x00,0x10,0x00,0x49,0x55,0xd1,
 0xea,0x4a,0xfd,0xc8,0x16,0x28,0x00,0xda,0x7d,0xe5,0x52,0xff,0xb3,0x7f,0xd2,
 0xbb,0x00,0x00,0x08,0xad,0x1a,0xc8,0xdb,0xef,0x87,0xaf,0xb8,0x2e,0xf8,0xff,
 0x3f,0x3f,0x3f,0x17,0xf0,0x79,0x5e,0xcf,0xf7,0xff,0xbc,0x9e,0xdf,0x04,0x68,
 0xfe,0xff,0x87,0xe1,0xef,0x78,0x5c,0x8c,0x0b,0x34,0x16,0x8e,0x0b,0x5c,0xf6,
 0xf2,0xc0,0xe1,0xf2,0x78,0x79,0x74,0x5c,0x5c,0x00,0xe5,0xff,0xe2,0x79,0xdf,
 0xcc,0xb7,0xe7,0xbf,0x00,0x00,0x00,0xfd,0x65,0xe4,0x7f,0xfe,0x1e,0xaf,0x7d,
 0x0b,0x78,0x67,0x3c,0x1e,0x3e,0x07,0xf8,0x60,0xbe,0x86,0xf7,0xef,0x38,0x5c,
 0x1e,0x0b,0x70,0x9c,0xbb,0xc7,0xe5,0xde,0x71,0x9c,0x07,0x03,0x3d,0xae,0x8e,
 0x43,0x98,0xf8,0xe5,0xd9,0xe9,0xf4,0x78,0x7a,0x7a,0x4a,0x1c,0x00,0x6d,0x3f,
 0x13,0x38,0xa9,0xf9,0xad,0x85,0xb6,0x09,0x00,0x00,0x5d,0x69,0x75,0xb3,0xd4,
 0x9b,0x0e,0xbb,0x01,0xb8,0xef,0xbc,0x9e,0x9c,0x6e,0xf0,0x29,0x3d,0xa1,0x77,
 0xce,0x38,0x1b,0x1e,0x2f,0x3c,0xb1,0x79,0xd3,0x73,0xce,0x70,0x3e,0xe7,0x36,
 0x9c,0x5e,0x4f,0x13,0x3e,0xe2,0xe9,0xf4,0xe9,0xf4,0xfe,0x7a,0x3a,0x95,0xbe,
 0x41,0xb9,0x5d,0x30,0xdf,0x76,0xb7,0xd7,0x1f,0xf6,0x00,0x00,0x04,0xad,0x12,
 0xb2,0x7e,0xbe,0x39,0xae,0x71,0x08,0x10,0xe7,0x3e,0x9e,0x9c,0xa6,0xf0,0x34,
 0x7d,0x94,0x33,0xcf,0x38,0x5c,0x9f,0x4f,0x78,0xbd,0x39,0xd6,0x63,0x9e,0x79,
 0x18,0x4f,0x27,0x1d,0x9f,0x8e,0x12,0x3e,0xf1,0xe9,0xec,0xd9,0xfc,0x7c,0x3a,
 0x3e,0xcb,0x3d,0x02,0x7a,0x5b,0xa5,0xff,0xfc,0x08,0x4e,0x7f,0xbf,0x00,0x00,
 0x00,0xbd,0x37,0xb9,0xda,0x5e,0xea,0x4c,0x73,0x05,0x99,0x67,0xbc,0x9f,0x9e,
 0x26,0xf0,0x8c,0xfa,0xb0,0x37,0xcf,0x3c,0x8b,0x1e,0xcf,0xfc,0x85,0x78,0xd7,
 0x73,0x4f,0x71,0x0a,0xff,0x10,0x9e,0x3f,0x4e,0x33,0x39,0xd3,0xe3,0xc5,0x59,
 0xf8,0x7a,0x7e,0x3d,0x41,0x78,0x02,0xe6,0xbe,0xe2,0xb7,0x70,0xa5,0xe6,0xbb,
 0xb7,0x00,0x00,0x00,0xdd,0x2d,0x3d,0xb7,0xfa,0x79,0xcd,0xb3,0x28,0x54,0x6f,
 0x3e,0x9e,0xdc,0x6a,0xf0,0x2e,0xf1,0xd0,0x27,0xcf,0x3c,0x4b,0x9f,0x8f,0xf8,
 0x9f,0x3c,0xa5,0x27,0xdf,0x78,0x83,0xff,0x33,0x3e,0x9f,0x7e,0x10,0x78,0xd2,
 0xeb,0xec,0x1f,0xfb,0x3e,0x79,0x7c,0xd3,0x78,0x06,0x6a,0x5d,0x62,0xfa,0x6c,
 0x00,0xb6,0x97,0xbf,0x00,0x00,0x00,0xbd,0x9b,0x5c,0x7a,0x5f,0xf6,0x5a,0x33,
 0x0d,0x40,0x47,0xbc,0x9e,0xdc,0x24,0xf0,0x84,0xe2,0x93,0x93,0x9e,0xb8,0x53,
 0x1f,0x5f,0xf0,0xff,0x7a,0x05,0xa7,0x8e,0x74,0xd3,0xfe,0x17,0x9f,0x3e,0x6f,
 0xae,0xf1,0x8d,0xe7,0xc4,0xd9,0xf4,0x9c,0x7d,0x3d,0xb5,0x7c,0x04,0xec,0x59,
 0x73,0x9f,0x39,0x00,0xd7,0x9d,0xbd,0x10,0x00,0x08,0xad,0x4e,0xbe,0x1d,0x50,
 0xdd,0xb1,0x5b,0x06,0xa0,0x2f,0x3f,0x9e,0x9c,0x28,0xf0,0x24,0xdb,0xb3,0x77,
 0x4f,0x3a,0x21,0x9e,0xcf,0x88,0x3f,0x3a,0x89,0xaf,0xce,0x75,0x3a,0xa0,0x07,
 0x9e,0x9e,0x4e,0x81,0xfa,0x94,0xf7,0xec,0x89,0xf0,0x78,0x38,0x3e,0x19,0xf0,
 0x04,0x54,0x57,0x33,0xfd,0x06,0x00,0xeb,0xaf,0xbb,0x04,0x00,0x00,0xfd,0x4f,
 0xce,0xd5,0xcb,0xfa,0x35,0x13,0x0d,0x81,0x47,0x3c,0x9f,0x3c,0x0c,0xf2,0x24,
 0xe1,0xd3,0xa7,0xce,0x3c,0x14,0x9e,0x8e,0x04,0x3c,0x79,0x52,0x2f,0x0f,0x79,
 0x00,0x82,0x27,0x3d,0x9f,0x4e,0x86,0xf0,0xcc,0xe7,0xcd,0xc9,0xf2,0x7a,0x7b,
 0x39,0x91,0xe1,0x09,0x95,0xa7,0xb6,0xfb,0x11,0x10,0x6e,0x47,0xbf,0x00,0x00,
 0x00,0x5d,0xa3,0xdf,0x09,0xc0,0xad,0x77,0xab,0x06,0x88,0x67,0xbe,0x9e,0x9e,
 0x4e,0xf0,0x8d,0x92,0xab,0x17,0x4f,0x38,0x39,0x1f,0x4f,0xd8,0x3a,0x3d,0x0d,
 0x5e,0xde,0x70,0xba,0x79,0x66,0x9e,0x9e,0xce,0xc3,0xe4,0x99,0xf3,0xc4,0xfb,
 0xf4,0x7a,0x7e,0x7a,0xc6,0xfc,0x09,0xd8,0x6a,0xbd,0x5e,0x0f,0x01,0xdf,0x65,
 0xbf,0x00,0x00,0x00,0xfd,0x27,0xd7,0x06,0xd0,0xf7,0xeb,0x0a,0x2a,0x85,0x27,
 0xbc,0x1e,0xbd,0x4e,0xf0,0x24,0xb3,0xd3,0x13,0xcf,0x3c,0x9f,0x9e,0xcf,0x98,
 0x32,0x7b,0xca,0x9e,0x9e,0x75,0x1e,0x53,0x47,0x3c,0x8f,0x8e,0xa2,0xee,0x91,
 0xea,0xd5,0xe9,0xf8,0x7c,0x79,0x76,0xca,0xf0,0x09,0x30,0x75,0x9b,0xfa,0x1e,
 0x80,0xb6,0x57,0xbb,0x00,0x00,0x00,0xbd,0x65,0xfb,0x09,0xd0,0x5d,0xf7,0x62,
 0x07,0xa0,0x6f,0x3d,0x9f,0x1e,0x4f,0xe0,0x09,0x47,0xd3,0xb7,0x9f,0xba,0x3c,
 0x1e,0xa3,0x38,0x3b,0x7d,0x1a,0x9d,0x1f,0x79,0xbe,0xcf,0x31,0x34,0xe7,0x7f,
 0xf8,0xf5,0x7b,0xf9,0xfa,0xab,0x74,0xf5,0xac,0xec,0xb1,0x96,0x32,0x60,0xaf,
 0xed,0x54,0xbf,0x00,0xdf,0xd2,0xbf,0x12,0x00,0x00,0xed,0x96,0x6b,0x82,0xc0,
 0xb7,0x4e,0xa2,0x85,0xa0,0x1f,0xff,0xbf,0xbf,0x8f,0xd0,0x8b,0x1f,0xe6,0xaf,
 0xbf,0x7e,0x9f,0xdf,0x51,0xfc,0x8c,0xfd,0x5e,0x7f,0x7f,0xfd,0x1a,0xbf,0x28,
 0xa4,0x21,0x84,0x00,0x09,0x80,0x01,0x00,0x00,0x00,0x04,0x00,0x12,0x00,0x00,
 0x10,0x61,0x9a,0x7d,0xb6,0x2d,0x10,0x77,0x99,0xbb,0x00,0x00,0x08,0xad,0x93,
 0xd6,0x24,0xd8,0xfd,0xf5,0xd5,0x25,0x20,0x40,0x00,0x00,0x00,0x40,0x00,0x60,
 0x40,0x10,0x00,0x00,0x02,0x80,0x00,0x2c,0x00,0x20,0x02,0x80,0x00,0x00,0x02,
 0x00,0x01,0x14,0x10,0xd0,0x28,0x61,0x50,0x55,0xbe,0xaf,0xba,0xae,0x95,0xb6,
 0x4d,0x7e,0x6b,0x37,0x40,0x6a,0x9f,0xed,0xbd,0x00,0xbf,0xeb,0xb7,0x00,0x00,
 0x00,0xfd,0x92,0xfd,0x01,0xe0,0x1f,0x6d,0x97,0x05,0x44,0xa5,0x2a,0xa0,0xaa,
 0x52,0xc0,0xa0,0x52,0xb4,0x52,0x4a,0x69,0x55,0x15,0x29,0x20,0x68,0x00,0x84,
 0x24,0xa9,0x55,0xf7,0x4a,0x0b,0x90,0x2c,0x57,0x81,0x47,0x55,0x61,0x55,0xeb,
 0x52,0xeb,0xda,0xa6,0x45,0xad,0xea,0x80,0x59,0x8c,0x6a,0x37,0x00,0xfb,0x7b,
 0xbe,0x10,0x00,0x00,0xfd,0xa9,0xb3,0x0f,0xd0,0xab,0xdd,0xe9,0x0a,0x00,0x5b,
 0xd5,0xaf,0x5a,0xad,0x00,0x5d,0xac,0x28,0x6d,0xb4,0x52,0x55,0x55,0x0b,0xc0,
 0x17,0xf8,0xb5,0xea,0x6a,0x53,0x4d,0xb9,0x02,0x40,0x05,0x54,0x02,0x95,0xaa,
 0x4a,0xad,0x2a,0x45,0x15,0xa5,0x0a,0x02,0x83,0x04,0x08,0xff,0x4d,0xb1,0x9f,
 0x00,0x5e,0x41,0xbd,0x00,0x00,0x00,0xad,0xd9,0xcf,0x06,0xf2,0x53,0xee,0x6d,
 0x01,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0xa8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xb8,
 0x4e,0x6a,0x3d,0x88,0xab,0x35,0xb6,0x00,0x00,0x00,0x7d,0xa9,0xbd,0x13,0xc0,
 0x09,0xd3,0x7a,0x03,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x02,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x10,0x00,
 0x10,0x05,0x78,0x35,0x6d,0xb7,0x00,0x1e,0x2d,0xb7,0x08,0x00,0x00,0x9d,0xa9,
 0x3f,0x06,0xd0,0x7c,0xa2,0x6b,0x10,0x90,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x20,
 0x08,0x00,0x00,0x00,0x80,0x42,0x00,0x00,0x00,0x20,0x00,0x00,0x80,0x00,0x00,
 0x00,0x00,0x20,0x00,0x18,0x62,0xfd,0xf2,0xb0,0x80,0xe2,0xc9,0xbb,0x00,0x00,
 0x20,0xdd,0xa8,0xb6,0x15,0xf2,0x1d,0xf2,0xbe,0x82,0x00,0x20,0x00,0x00,0x00,
 0x00,0x80,0x00,0x00,0x02,0x00,0x04,0x00,0x40,0x40,0x00,0x00,0x00,0x00,0x00,
 0x00,0x10,0x00,0x02,0x02,0x80,0x10,0x08,0x00,0x00,0x11,0x00,0x04,0x41,0x00,
 0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x90,0xc8,0xec,0xf5,0x35,0x20,0xf7,0xe9,
 0xbd,0x00,0x00,0x04,0xbd,0xa9,0xaf,0x85,0xc0,0x35,0xd4,0x54,0x28,0x80,0x00,
 0x10,0x11,0x01,0x04,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x09,0x00,0x00,0x00,
 0x00,0x04,0x00,0x00,0x00,0x10,0x40,0x20,0x22,0x80,0x00,0x00,0x40,0x00,0x21,
 0x01,0x00,0x00,0x08,0x20,0x04,0x88,0x08,0x02,0x00,0xbc,0xe5,0x1f,0xf1,0xbd,
 0x08,0x6b,0xe9,0xbf,0x22,0x00,0x00,0xdc,0x98,0xb7,0x17,0xd8,0x7d,0xae,0xad,
 0x02,0x20,0x00,0x04,0x00,0x20,0x01,0x10,0x00,0x00,0x00,0x24,0x00,0x49,0x00,
 0x00,0x00,0x22,0x04,0x80,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x40,
 0x10,0x00,0x00,0x00,0x20,0x84,0x80,0x00,0x80,0x00,0x00,0x20,0x04,0x64,0x92,
 0x1d,0x65,0x2d,0x00,0xde,0x65,0xb5,0x00,0x00,0x00,0xdd,0x28,0xfb,0x07,0xc0,
 0xfb,0x6c,0x23,0x5a,0x08,0x20,0x00,0x00,0x00,0x00,0x00,0x20,0x01,0x00,0x00,
 0x10,0x00,0x00,0x10,0x20,0x00,0x20,0x02,0x10,0x00,0x40,0x80,0x08,0x00,0x00,
 0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x40,0xb8,0xa7,0xdb,0xf3,0xb6,0x80,0x66,0xf1,0xbb,0x08,0x00,0x00,0x7d,0x4c,
 0x5f,0x17,0xd0,0x5b,0xe4,0x00,0x20,0x01,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
 0x20,0x02,0x00,0x00,0x00,0x84,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x10,0x00,
 0x00,0x44,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x40,0x10,
 0x00,0x00,0x00,0x00,0x68,0x55,0xda,0xe3,0x1e,0x00,0xdf,0xf5,0xbd,0x00,0x00,
 0x00,0x9d,0x58,0xf7,0x82,0xd0,0x9f,0x2d,0x9f,0x97,0x06,0x00,0x00,0x38,0x15,
 0x62,0x1f,0x9f,0xfc,0x8a,0xcb,0xbe,0x87,0x20,0x00,0x00,0x00,0x00,0x40,0x00,
 0x00,0x00,0x10,0x90,0x00,0x22,0x0a,0x09,0x92,0x10,0x84,0x20,0x00,0x80,0x10,
 0x00,0x04,0x00,0x20,0x82,0x08,0x00,0xc0,0x75,0xeb,0x62,0xbd,0x00,0x5a,0x75,
 0xb7,0x02,0x00,0x00,0xed,0xc8,0x94,0x15,0xe4,0x55,0xc9,0x3c,0x10,0x8c,0x00,
 0x00,0x90,0x35,0x0e,0x09,0x8d,0xd4,0x0b,0xe9,0xaa,0x23,0x00,0xa0,0x2a,0xad,
 0x57,0x09,0x8a,0x00,0x02,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,
 0x00,0x24,0x04,0x44,0x00,0x00,0x08,0x20,0x00,0x02,0x00,0xde,0xae,0xe7,0x3a,
 0x88,0xd7,0x9b,0xbf,0x10,0x00,0x00,0x7d,0xd8,0x2c,0x04,0xd0,0x58,0xab,0x77,
 0xa0,0x0c,0x00,0x00,0x41,0x00,0x26,0x2b,0x89,0x71,0x0d,0x81,0x9a,0x13,0x00,
 0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x84,0x48,0xa5,0xa2,0x4a,0x45,0x00,
 0x84,0x00,0x00,0x04,0x00,0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x20,0x70,
 0xcd,0x62,0xad,0x00,0x4b,0xb5,0xbb,0x0a,0x00,0x00,0x9d,0xa8,0xb1,0x07,0xe0,
 0xbb,0xca,0x99,0xd2,0x11,0x04,0x10,0x00,0x14,0x00,0x10,0x00,0x00,0x40,0x00,
 0x00,0x00,0x01,0x40,0xc7,0x9f,0x7c,0xef,0x87,0xff,0xff,0xe3,0x97,0xbd,0xfc,
 0xe5,0x02,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x40,
 0x00,0x42,0xa0,0xff,0xe3,0x1d,0x00,0xb6,0x5b,0xbd,0x00,0x00,0x00,0x6c,0x1c,
 0xdb,0x15,0xd1,0xbb,0xd1,0xf6,0x85,0x3b,0x00,0x01,0x00,0x80,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x50,0x00,0x00,0x33,0x1f,0x34,0xeb,0xf1,0xff,0xff,0x8f,
 0x77,0x5d,0xfd,0xd0,0x05,0x00,0x00,0x00,0x80,0x40,0x00,0x00,0x00,0x01,0x80,
 0x00,0x00,0x02,0x40,0x80,0x6a,0xbb,0x73,0xb6,0x90,0xae,0xf3,0xbf,0x00,0x00,
 0x00,0xfd,0x88,0xea,0x07,0xd0,0xfb,0xe9,0xa9,0xa2,0x6e,0x00,0x10,0x11,0x01,
 0x08,0x25,0x00,0x02,0x42,0x10,0x2a,0x09,0x0c,0x40,0xfd,0xe0,0xb7,0x7f,0xfe,
 0xff,0xff,0x7f,0xfc,0xcb,0x27,0xbf,0x04,0x80,0x10,0x04,0x20,0x00,0x08,0x00,
 0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0xd6,0xee,0xf3,0x3d,0x00,0xab,0x93,
 0xbf,0x00,0x00,0x00,0x6d,0x58,0xd8,0x05,0xc4,0xdd,0xab,0xe2,0x4f,0x7f,0x02,
 0xb7,0xa5,0xc4,0xed,0x37,0x3e,0xd6,0x67,0x72,0x6c,0xab,0x0f,0x49,0xeb,0xe5,
 0xd7,0x1b,0xff,0xff,0xff,0xff,0xd1,0xeb,0xcf,0xbf,0x05,0x00,0x00,0x00,0x04,
 0x00,0x80,0x10,0x10,0x00,0x00,0x08,0x08,0x00,0x00,0x00,0xb8,0x5d,0x73,0x97,
 0x00,0xde,0x73,0xb5,0x02,0x00,0x40,0x6d,0x32,0x7f,0x97,0xd0,0x7b,0xeb,0xcd,
 0xf2,0x5a,0x00,0x8e,0x61,0xc4,0xed,0x32,0x9e,0x52,0xa1,0x56,0x7c,0x2d,0x0d,
 0x00,0x3f,0xeb,0xf9,0xe7,0xff,0xff,0xff,0xff,0x47,0xdf,0xaa,0xee,0x02,0x00,
 0x44,0x80,0x00,0x40,0x20,0x00,0x02,0x20,0x00,0x80,0x00,0x20,0x00,0x00,0x42,
 0xb7,0xf9,0xbe,0x90,0xee,0xf3,0xbf,0x20,0x00,0x10,0x7c,0x30,0xbe,0x07,0xd2,
 0xff,0xd3,0xc2,0xc7,0xf5,0x20,0xab,0x71,0x44,0xa5,0x02,0x24,0x96,0x65,0x54,
 0x42,0x65,0x05,0x40,0xc3,0xee,0xf7,0xe2,0xff,0x7f,0xf5,0xff,0x9f,0xb5,0xab,
 0x83,0x01,0x09,0x00,0x20,0x00,0x08,0x04,0x10,0x40,0x02,0x00,0x00,0x40,0x08,
 0x00,0x10,0xa0,0xfb,0xd9,0x2a,0x04,0xf7,0xa2,0xbd,0x08,0x00,0x00,0xfd,0x5a,
 0xbc,0x04,0xf0,0xda,0xeb,0x94,0x0d,0x68,0x00,0x22,0x08,0xca,0x64,0xb2,0x66,
 0x52,0x82,0x14,0x40,0x14,0x04,0x00,0x3c,0x6b,0xbd,0xfc,0xff,0x02,0x80,0xff,
 0x3f,0xbe,0xcd,0x3c,0x02,0x80,0x40,0x08,0x00,0x02,0x00,0x00,0x00,0x80,0x88,
 0x00,0x08,0x00,0x08,0x00,0xb4,0xee,0xf9,0xb6,0xa0,0xea,0xe7,0xb7,0x02,0x00,
 0x00,0xcd,0x30,0xbd,0x17,0xd1,0x2c,0xaa,0xe5,0x27,0x80,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x43,0x77,0x3d,0xff,0x0b,
 0x0a,0x21,0xfc,0xff,0x68,0xef,0x80,0x00,0x00,0x10,0x00,0x80,0x80,0x00,0x08,
 0x42,0x08,0x00,0x08,0x00,0x01,0x00,0x01,0x51,0xfb,0xf9,0xb1,0x00,0xd6,0xe7,
 0xbe,0x00,0x00,0x00,0xfd,0x68,0xcc,0x06,0xd0,0xfd,0xeb,0x8c,0x0d,0x00,0x08,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x40,0x80,0xb6,
 0x16,0xff,0xf5,0x00,0x00,0xf1,0xff,0xf1,0x7a,0x02,0x20,0x00,0x00,0x08,0x20,
 0x02,0x00,0x20,0x10,0x00,0x01,0x05,0x00,0x28,0x40,0x10,0x8c,0xb5,0x59,0x39,
 0x90,0x66,0xe5,0xbb,0x00,0x00,0x00,0xad,0xd8,0xbe,0x13,0xd0,0xe7,0xdb,0xe4,
 0x06,0x12,0x00,0x00,0x09,0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x80,0x00,0x00,
 0x88,0x01,0x7a,0xc7,0x7f,0x83,0x90,0x44,0x82,0xff,0xcf,0x6f,0xc3,0x03,0x00,
 0x00,0xfa,0x80,0x8f,0x3e,0x3e,0xe4,0xd1,0xc7,0x9d,0x3e,0x78,0xc1,0x10,0x60,
 0xbd,0x6c,0x36,0x82,0xbe,0xcf,0xb5,0x40,0x00,0x04,0xed,0xe8,0xf6,0x07,0xe2,
 0x4b,0xd9,0xb4,0x87,0x80,0x00,0x00,0x00,0x01,0x00,0x00,0x01,0x00,0x00,0x00,
 0x11,0x00,0x10,0x40,0x85,0xd6,0xe3,0xbf,0x14,0x00,0x42,0xc0,0xff,0xcf,0x7c,
 0x23,0x06,0x20,0x10,0xa4,0x80,0x19,0x3a,0x20,0x30,0x43,0x84,0x00,0x22,0xca,
 0xc0,0x10,0xc5,0xda,0xbc,0x5d,0x00,0x6a,0xdb,0xbb,0x00,0x00,0x20,0x99,0x31,
 0x57,0x07,0xd0,0xbb,0xee,0xaa,0x0b,0x00,0x08,0x00,0x00,0x00,0x08,0x40,0x20,
 0x42,0x00,0x10,0x00,0x04,0x00,0x60,0x09,0xfa,0xf8,0xbf,0x89,0x42,0x00,0x01,
 0xff,0xbf,0x6b,0xd3,0x0a,0x02,0x00,0x09,0x81,0x10,0x03,0x10,0x10,0x22,0x84,
 0x00,0x60,0x84,0x40,0x10,0x22,0x2c,0x56,0x47,0xad,0xf8,0x9c,0xbd,0x20,0x00,
 0x00,0xfd,0x32,0xff,0x91,0xd0,0x7f,0x56,0xd8,0x0b,0x00,0x00,0x81,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x01,0x44,0x02,0xde,0xfd,0x9f,0x02,
 0x04,0x48,0x24,0xff,0x3f,0x7f,0x51,0x8d,0x00,0x00,0x88,0x00,0x18,0x23,0xa0,
 0x00,0x40,0x86,0x00,0x20,0x48,0xc0,0x18,0x62,0x4a,0xf6,0x03,0x00,0xd0,0x9b,
 0xbf,0x04,0x00,0x00,0xdc,0xf1,0x75,0x0f,0xd0,0x9f,0x7a,0xb5,0x05,0x10,0x41,
 0x00,0x40,0x10,0x01,0x08,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x90,0x08,0x7a,
 0xfe,0x77,0x5c,0x11,0x02,0x01,0xf8,0x7f,0x4e,0x23,0x0d,0x00,0x08,0xd4,0x10,
 0x0e,0x3c,0x30,0x00,0xc3,0x91,0x1f,0x1c,0x7c,0x40,0x4f,0x08,0x6d,0xab,0xfe,
 0xff,0xff,0x2a,0xb7,0x00,0x00,0x00,0xfd,0xf1,0xf6,0x03,0xe4,0x66,0x55,0xa0,
 0x07,0x00,0x00,0x00,0x02,0x00,0x40,0x00,0x00,0x10,0x08,0x00,0x00,0x00,0x80,
 0xa0,0x88,0x6a,0xfe,0x6b,0x05,0x00,0x40,0x00,0xf4,0x7f,0x5c,0x23,0x09,0x00,
 0x00,0xf8,0x04,0x16,0x36,0x24,0xc4,0x91,0x86,0x10,0x38,0xd9,0xc0,0x10,0x12,
 0x15,0xeb,0xff,0xff,0xbf,0x35,0xbf,0x40,0x00,0x00,0xfd,0xa5,0xaf,0x44,0x01,
 0xef,0x39,0x42,0x05,0x02,0x10,0x40,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x02,
 0x81,0x00,0x20,0xc0,0x98,0x9e,0xff,0x5a,0x05,0x90,0x10,0x90,0xf0,0xff,0xf9,
 0x12,0x06,0x00,0x01,0x84,0x80,0x18,0x23,0x20,0x70,0x60,0x04,0x10,0x60,0x84,
 0xc2,0x10,0x81,0xab,0x5f,0xff,0xff,0xff,0x5e,0xbe,0x00,0x00,0x40,0xac,0xe1,
 0x6e,0x10,0x80,0xfa,0x3e,0x80,0x03,0x00,0x04,0x00,0x40,0x00,0x00,0x00,0x04,
 0x02,0x00,0x40,0x00,0x10,0x00,0x00,0x88,0xda,0xbf,0x55,0x50,0x00,0x04,0x22,
 0xc4,0xff,0xb3,0x32,0x00,0x00,0x00,0x08,0x01,0x10,0x41,0x20,0x10,0x64,0x0c,
 0x08,0x00,0x84,0x40,0x10,0xd3,0x90,0x7b,0x45,0xa1,0xdd,0x77,0xbe,0x40,0x00,
 0x08,0x7d,0xe9,0xdf,0xff,0xff,0xff,0x36,0x80,0x01,0x80,0x00,0x00,0x10,0x00,
 0x00,0x04,0x00,0x00,0x00,0x00,0x20,0x00,0x04,0x00,0x48,0xcf,0x7f,0xc6,0x0a,
 0x14,0x41,0x08,0xc1,0xff,0xe7,0x10,0x00,0x00,0x80,0x88,0x00,0x18,0x23,0x30,
 0x12,0x20,0x04,0x18,0x61,0xcc,0xc0,0x10,0x75,0x34,0xdf,0x7e,0x55,0xdd,0x3f,
 0xbe,0x04,0x00,0x02,0xdd,0xe2,0xd7,0xff,0xff,0x6f,0x9d,0x10,0x00,0x20,0x00,
 0x20,0x00,0x40,0x10,0x40,0x20,0x00,0x24,0x00,0x00,0x00,0x00,0x10,0x48,0xe7,
 0xaf,0x35,0x05,0x10,0x88,0x41,0x94,0xff,0xcf,0x34,0x80,0x10,0x00,0x7c,0x80,
 0x0f,0x3e,0xae,0xf0,0xc3,0x83,0x07,0x1e,0x38,0xc0,0x10,0x0b,0x40,0xd4,0xf5,
 0xfb,0xf7,0x8c,0xbf,0x10,0x00,0x00,0xfa,0xcb,0x3d,0xad,0x7f,0x79,0x0d,0x00,
 0x00,0x01,0x00,0x00,0x02,0x00,0x02,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
 0x04,0x0c,0xf3,0x9f,0x0a,0x01,0x40,0x20,0x04,0x01,0xff,0xcf,0x14,0x00,0x00,
 0x08,0x68,0x80,0x02,0x0c,0xfc,0xd8,0x02,0x41,0x05,0x14,0x40,0x00,0x00,0x05,
 0x80,0xc9,0xea,0xde,0xda,0xc0,0xb7,0x00,0x00,0x00,0x9d,0xca,0xaf,0x7e,0xeb,
 0xba,0x0f,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0xa4,0xf9,0x55,0xa1,0x08,0x0d,0x00,0x00,0x24,0xdf,0x9f,
 0x2d,0x20,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x11,
 0x10,0x40,0x02,0x40,0xa2,0x7a,0xf3,0x67,0xf2,0xbf,0x00,0x00,0x00,0xfc,0x97,
 0x37,0x6b,0x6f,0xbd,0x06,0x00,0x00,0x00,0x20,0x00,0x00,0x40,0x00,0x00,0x42,
 0x00,0x00,0x82,0x00,0x04,0x00,0x00,0xa8,0xf9,0x37,0x54,0x10,0x90,0x20,0xa8,
 0x00,0xfc,0x1f,0x2b,0x00,0x00,0x00,0x00,0x08,0x80,0x00,0x00,0x00,0x08,0x10,
 0x20,0x00,0x00,0x00,0x10,0x90,0x00,0x96,0xea,0xfd,0x57,0x7b,0xbf,0x44,0x00,
 0x00,0xad,0x57,0xcf,0x7d,0xfd,0x4c,0x83,0x00,0x42,0x00,0x02,0x40,0x20,0x08,
 0x00,0x92,0x00,0x04,0x00,0x20,0x20,0x80,0x00,0x01,0xd6,0xfc,0x6b,0xa9,0x84,
 0x04,0x14,0x48,0xa0,0xfc,0x7f,0x4b,0x00,0x00,0x81,0x00,0x00,0x24,0x40,0x00,
 0x80,0x40,0x04,0x04,0x04,0x00,0x00,0x00,0x04,0x08,0x88,0xdd,0xbb,0x6d,0xde,
 0xb9,0x00,0x00,0x00,0xf9,0x06,0x5b,0x3f,0xef,0xd9,0x0b,0x00,0x00,0x20,0x00,
 0x04,0x08,0x02,0x80,0x00,0x00,0x00,0x80,0x00,0x08,0x00,0x20,0x00,0xc2,0xfe,
 0xa7,0x5c,0x0e,0xaa,0x00,0x15,0x09,0xfc,0x7f,0x53,0x00,0x04,0x20,0x00,0x00,
 0x00,0x01,0x80,0x24,0x00,0x00,0x01,0x41,0x02,0x00,0x00,0x00,0x80,0x94,0xf4,
 0xf3,0xa7,0x7c,0xbb,0x00,0x00,0x00,0x7c,0x4b,0xcf,0x6d,0xba,0xa9,0x01,0x00,
 0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x80,0x80,0x08,0x00,0x00,0x00,0x08,
 0x80,0x62,0xfe,0x8d,0xb2,0x20,0x0a,0xa1,0x00,0x50,0xf9,0xff,0xf4,0x08,0x01,
 0x00,0x00,0x00,0x01,0x00,0x02,0x00,0x00,0x00,0x40,0x00,0x80,0x08,0x11,0x00,
 0x00,0x92,0xf5,0x6a,0xef,0xfe,0xb7,0x08,0x00,0x40,0xad,0x2f,0xf4,0x7e,0x6f,
 0xf5,0x05,0x40,0x00,0x08,0x24,0x00,0x00,0x00,0x40,0x00,0x08,0x10,0x00,0x00,
 0x00,0x00,0x00,0x00,0x2b,0xff,0xb7,0xaa,0x14,0x56,0x48,0x55,0x00,0xf2,0xff,
 0xac,0x00,0x00,0x00,0x00,0x04,0xdb,0x10,0x00,0x00,0x04,0x40,0xa8,0xc2,0x12,
 0x00,0x00,0x02,0x40,0x88,0xdb,0xed,0xb5,0xfe,0xbf,0x00,0x00,0x00,0xdd,0x0d,
 0xff,0x5b,0xfb,0xdb,0x00,0x11,0x00,0x02,0x00,0x20,0x40,0x00,0x08,0x00,0x00,
 0x00,0x00,0x00,0x00,0x04,0x01,0x10,0x35,0xff,0x2d,0x65,0x81,0x08,0x11,0x00,
 0x95,0xf9,0xfb,0x2d,0x00,0x00,0x04,0x00,0x41,0x5a,0x40,0xa9,0x55,0x55,0x4c,
 0x47,0x44,0x04,0x00,0x00,0x10,0x09,0x8a,0x7f,0x5b,0x7f,0xb6,0xbb,0x40,0x00,
 0x00,0xae,0x7a,0xb2,0xff,0xde,0x6d,0x40,0x00,0x80,0x00,0x00,0x00,0x00,0x00,
 0x02,0x80,0x80,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0xd0,0xff,0xd5,0x9a,0xa7,
 0x52,0x02,0x0a,0x28,0x62,0xff,0x4b,0x01,0x80,0x80,0x40,0x00,0x16,0x33,0x24,
 0x8c,0x50,0xb3,0x41,0xc4,0x00,0x40,0x80,0x00,0x00,0x30,0xdf,0xea,0x2f,0x6f,
 0xae,0x08,0x00,0x08,0xfd,0xdf,0xfa,0x7e,0xff,0x7e,0x08,0x00,0x08,0x00,0x82,
 0x04,0x00,0x90,0x00,0x08,0x00,0x00,0x52,0x08,0x91,0x00,0x00,0x84,0xd8,0xff,
 0x9a,0xed,0x2a,0x25,0x24,0xd1,0x44,0xf1,0xff,0x53,0x81,0x00,0x00,0x10,0x00,
 0x36,0xf4,0xbd,0xb1,0x40,0xb2,0x45,0x56,0x84,0x10,0x08,0x00,0x80,0x74,0xff,
 0xfb,0x37,0xfb,0xbf,0x00,0x00,0x00,0xda,0xdf,0xd4,0x5f,0x3f,0x1f,0x02,0x00,
 0x00,0x40,0x00,0x00,0x12,0x02,0x60,0x06,0x24,0x40,0x00,0x00,0x00,0x00,0x10,
 0x80,0xca,0xff,0xf5,0xab,0x4b,0x4d,0x45,0x00,0x00,0xc2,0xff,0xb3,0x00,0x08,
 0x20,0x00,0x00,0x24,0x94,0x06,0xa5,0x66,0xb2,0x9a,0xd4,0x18,0x04,0x20,0x48,
 0x12,0x80,0x7c,0xfb,0x9e,0x97,0xbe,0x00,0x00,0x00,0xbd,0xad,0x94,0x7b,0xf5,
 0x8d,0x00,0x00,0x00,0x04,0x08,0x00,0x80,0x00,0x61,0x0c,0x01,0x12,0x00,0x00,
 0x00,0x00,0x01,0x00,0xca,0x7f,0x7d,0x55,0xbd,0x96,0x10,0x49,0x49,0xd1,0xff,
 0xb7,0x20,0x00,0x04,0x04,0x00,0xa4,0xbd,0xb4,0x2c,0x65,0xda,0xde,0x92,0x0a,
 0x00,0x00,0x02,0x00,0xd2,0xfc,0xb3,0xcf,0xdf,0xbe,0x44,0x00,0x00,0xfd,0xb7,
 0xb3,0x7c,0xbd,0x03,0x00,0x44,0x90,0x00,0x00,0x80,0x00,0x50,0xff,0xff,0x00,
 0x00,0x00,0x02,0x00,0x10,0x40,0x42,0xe5,0xff,0x6b,0xbb,0x53,0x2b,0xaa,0x80,
 0x90,0xca,0xbb,0x2f,0x03,0x40,0x00,0x01,0x20,0x10,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xa0,0xf3,0xf5,0xf3,0x7f,0xbe,0x00,0x00,
 0x10,0xaa,0x2a,0x63,0x43,0xde,0x09,0x00,0x00,0x04,0x00,0x00,0x04,0x00,0x00,
 0xdf,0xf2,0x01,0x00,0x84,0x00,0x00,0x00,0x00,0x50,0xf4,0x7f,0xd7,0xea,0x96,
 0xcc,0x3e,0x12,0x04,0xc2,0xff,0x0f,0x01,0x00,0x40,0x00,0x00,0x04,0x00,0x00,
 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x42,0x00,0x00,0x14,0xc3,0xca,0xfc,0xac,
 0xae,0x00,0x00,0x00,0x6d,0x57,0x8f,0xb8,0xf3,0x02,0x40,0x00,0x00,0x88,0x80,
 0x00,0x20,0xf8,0xbe,0xff,0x9e,0x42,0x00,0x80,0x44,0x00,0x40,0x80,0xf2,0xff,
 0xbd,0xbe,0xaa,0xb3,0xf4,0xa7,0xf9,0x92,0xff,0x4f,0x05,0x08,0x02,0x80,0x00,
 0x01,0x00,0x02,0x42,0x82,0x00,0x90,0x80,0x00,0x40,0x00,0x00,0x41,0xd0,0x1e,
 0x3f,0xe4,0x77,0xbc,0x24,0x00,0x00,0xbc,0x77,0x14,0x0b,0x5d,0x00,0x04,0x00,
 0x00,0x00,0x10,0x00,0x08,0xdc,0x99,0x93,0x1b,0x00,0x00,0x00,0x00,0x80,0x00,
 0xa0,0xfb,0x7f,0x6d,0xa9,0x4a,0xaf,0xe6,0x05,0x7e,0xa5,0xff,0xdf,0x02,0x02,
 0x10,0x00,0x40,0x00,0x05,0x80,0x00,0x20,0x40,0x00,0x10,0x00,0x01,0x00,0x00,
 0x10,0xa0,0xef,0x8c,0xcb,0x5a,0xbe,0x00,0x00,0x00,0xfd,0xea,0xba,0x74,0x9f,
 0x88,0x00,0x10,0x49,0x00,0x00,0x42,0x80,0xec,0x9b,0xe3,0x2e,0x10,0x20,0x00,
 0x00,0x08,0x10,0x08,0xfb,0xdf,0xde,0x5a,0xe3,0xfa,0xcd,0xab,0xe7,0x87,0xfb,
 0x9f,0x82,0x80,0x00,0x02,0x10,0x40,0x88,0xb0,0x1a,0x50,0xbf,0xbf,0x6f,0x1f,
 0x00,0x00,0x00,0x00,0xe8,0xbf,0xc0,0x8b,0xbb,0xbc,0x00,0x00,0x10,0xfa,0xad,
 0x7e,0xa4,0x30,0x80,0x04,0x04,0x00,0x42,0x00,0x10,0xc0,0xfb,0xff,0xdf,0xda,
 0x03,0x02,0x00,0x00,0x00,0x00,0x42,0xfd,0x77,0x69,0x69,0x88,0x55,0x21,0x8f,
 0x0b,0xa5,0xff,0x3f,0x06,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x22,0x00,0x22,
 0x40,0x80,0x04,0x00,0x80,0x20,0x02,0xf2,0x7f,0xeb,0x1b,0x2f,0xbc,0x04,0x00,
 0x00,0xbe,0xf4,0xae,0x0a,0xd2,0x40,0x80,0x00,0x00,0x00,0x44,0x00,0x82,0x6f,
 0xbf,0x7a,0xff,0x01,0x00,0x08,0x08,0x00,0x40,0x40,0xfd,0x6f,0x5f,0xcb,0x65,
 0xff,0xbf,0x57,0xb7,0x25,0xfe,0x3f,0x05,0x30,0x80,0x20,0x02,0x10,0x20,0x80,
 0x04,0x01,0x15,0x34,0x81,0x02,0x00,0x08,0x00,0x00,0x40,0x7d,0xf6,0x95,0x5f,
 0xbd,0x40,0x00,0x00,0xf8,0xfe,0xf7,0x43,0xe0,0xc8,0x30,0x00,0x80,0x08,0x00,
 0x00,0x90,0x9f,0xc7,0xf4,0xe5,0x21,0x08,0x02,0x00,0x00,0x01,0xc0,0xfc,0xd5,
 0xd0,0x28,0xb2,0xcd,0xc7,0x96,0xfd,0x02,0xff,0x3e,0x05,0x00,0x00,0x02,0x00,
 0x20,0x80,0x10,0x18,0x90,0x0a,0x50,0x00,0x04,0x08,0x00,0x00,0x00,0x81,0xf2,
 0xf9,0x18,0x1b,0xb6,0x00,0x00,0x00,0x3f,0xff,0xb6,0x0e,0xb0,0xc0,0x40,0x00,
 0x22,0x00,0x00,0x04,0x80,0xcd,0x9e,0x32,0xaf,0x02,0x00,0x00,0x01,0x02,0x00,
 0xa0,0xfc,0x7b,0xd5,0x82,0x45,0x57,0xcd,0x2e,0xbe,0x2b,0xfc,0x7f,0x05,0x00,
 0x10,0x08,0x80,0x14,0x04,0x01,0x25,0x00,0x12,0x60,0x01,0x15,0x02,0x00,0x00,
 0x51,0x00,0xc5,0x70,0x15,0x9f,0xbe,0x00,0x00,0x00,0xd8,0x7f,0xb3,0xfd,0xda,
 0x80,0x31,0x00,0xc0,0x03,0x00,0x00,0xf8,0xf6,0xfc,0x3f,0xdd,0x9d,0x80,0x00,
 0x00,0x00,0x00,0x82,0xde,0xa5,0x16,0xd0,0x78,0xe0,0x11,0x9d,0x40,0x42,0xfa,
 0x7f,0x08,0x00,0x00,0x00,0x22,0x02,0x80,0x00,0x48,0x66,0x0a,0x90,0x40,0x04,
 0x00,0x01,0x78,0x04,0x08,0xd7,0x67,0x59,0x1f,0xbe,0x00,0x00,0x40,0xfa,0x75,
 0x72,0xb7,0xbb,0x00,0x01,0x10,0xf0,0x83,0x10,0x00,0xb1,0xfc,0xff,0x7b,0x7d,
 0x0f,0x00,0x00,0x48,0x20,0x24,0xa0,0xfe,0xdb,0xf5,0x93,0x83,0x95,0x26,0x1b,
 0x69,0xdd,0xfc,0xf7,0x0a,0x10,0x80,0x80,0x00,0x00,0x00,0x22,0x6a,0x56,0x83,
 0x60,0x10,0x0a,0x00,0x80,0xf8,0x00,0x40,0x09,0xe9,0x15,0x5f,0xb6,0x10,0x00,
 0x00,0xda,0x3f,0xf3,0x7a,0xf8,0x00,0x00,0x04,0x39,0x0e,0x00,0x22,0xf0,0x6f,
 0x0b,0xb0,0x27,0x0d,0x04,0x00,0x02,0x00,0x00,0x40,0xff,0x6d,0x05,0xa4,0x75,
 0xa2,0x00,0x2a,0x21,0x22,0xba,0xfd,0x1a,0x00,0x20,0x24,0x00,0x0c,0x80,0x04,
 0xd4,0xff,0x3f,0x90,0x00,0x00,0x00,0x00,0x8e,0x03,0x04,0x16,0x86,0x3b,0x0e,
 0xb6,0x00,0x00,0x08,0x5e,0x27,0x73,0x4d,0xa8,0x08,0x48,0x00,0x00,0x2c,0x80,
 0x00,0x38,0xf3,0x01,0x80,0xf3,0x0f,0x01,0x00,0x00,0x08,0x00,0x50,0xff,0xf7,
 0x3e,0x79,0xb9,0x23,0x52,0x15,0x44,0xac,0xf4,0xef,0x14,0x01,0x01,0x00,0x00,
 0x01,0x40,0x01,0xfc,0x68,0xf9,0x29,0x01,0x84,0x00,0x00,0x02,0x03,0x10,0x04,
 0xba,0x9d,0x5e,0xbf,0x00,0x00,0x00,0xf9,0x3d,0x6b,0x10,0xf9,0x00,0x00,0x00,
 0x10,0x0c,0x00,0x00,0xfe,0x67,0x00,0x00,0xaf,0x3a,0x40,0x00,0x00,0x00,0x01,
 0x70,0xff,0xff,0xf5,0x6e,0xe5,0x54,0x44,0xb5,0xa4,0x2a,0xeb,0x7b,0x15,0x10,
 0x00,0x08,0x80,0x0a,0x42,0x80,0x3c,0xff,0xcf,0x61,0x01,0x24,0x20,0x08,0x00,
 0x03,0x80,0x94,0xda,0x35,0x16,0xbb,0x44,0x00,0x00,0x1a,0x3b,0xe2,0x5a,0x2e,
 0x00,0x00,0x00,0x82,0x07,0x22,0x80,0x9e,0x7f,0x10,0x10,0xfe,0x69,0x00,0x20,
 0x01,0x00,0x00,0x68,0x7f,0xff,0x5a,0xbb,0xf5,0x09,0x21,0x54,0x02,0x94,0x77,
 0xdf,0x05,0x00,0x00,0x01,0x10,0x04,0x80,0x83,0xf7,0xbd,0x24,0x5f,0x20,0x00,
 0x00,0x02,0xc0,0x81,0x00,0x08,0x34,0xbd,0x8e,0xbf,0x00,0x00,0x00,0x7d,0x39,
 0xeb,0xb1,0x3d,0x80,0x44,0x90,0xc0,0x27,0x00,0x08,0x9e,0x3f,0x00,0x01,0xfc,
 0x7d,0x00,0x02,0x08,0x12,0x10,0xa9,0xdf,0xff,0xef,0x75,0x75,0x57,0x44,0x25,
 0xd4,0x5a,0xca,0xf7,0x35,0x00,0x08,0x00,0x80,0x02,0x40,0x8a,0xbb,0xfb,0xfa,
 0x5e,0x01,0x08,0x00,0x00,0xf0,0x00,0x48,0x32,0x68,0x3f,0xae,0xbb,0x20,0x00,
 0x00,0xfa,0xa0,0x73,0xde,0x0f,0x10,0x00,0x00,0xf0,0x00,0x00,0x01,0xfc,0x1f,
 0x7f,0x9e,0xf8,0x17,0x08,0x00,0x00,0x00,0x04,0xa8,0xff,0xfb,0xff,0xdd,0xf5,
 0x57,0x84,0x58,0x2a,0xda,0xf6,0xff,0x21,0x00,0x02,0x10,0x01,0x4c,0x44,0xf5,
 0xec,0xd4,0xfb,0x5a,0x80,0x08,0x00,0x40,0x3c,0x00,0x00,0xd0,0xa0,0xba,0xd2,
 0xbd,0x00,0x00,0x10,0xfd,0x29,0x63,0xad,0x8f,0x00,0x10,0x04,0x30,0x00,0x41,
 0x40,0xee,0x1f,0x7c,0x3c,0xe8,0xbb,0x40,0x00,0x00,0x00,0x00,0xa8,0xfd,0xdf,
 0xfd,0xfb,0xaa,0xad,0x18,0x95,0x88,0x7a,0xe9,0xfd,0x29,0x88,0x00,0x04,0x80,
 0x13,0x40,0x72,0xbf,0x2f,0xdf,0xf6,0x11,0x08,0x08,0x10,0x0c,0x20,0x40,0x70,
 0x65,0x3e,0x96,0xb7,0x14,0x00,0x00,0xba,0xed,0x75,0xda,0x00,0x04,0x82,0x00,
 0x18,0x20,0x00,0x80,0xbb,0x07,0x38,0x3c,0xf0,0xef,0x00,0x00,0x00,0x00,0x00,
 0xa0,0xef,0xef,0xff,0xaf,0x55,0x2b,0x51,0x5a,0xa4,0xfa,0xee,0xff,0x69,0x00,
 0x40,0x00,0x10,0x04,0x80,0xb4,0xeb,0xfe,0x75,0x59,0x00,0x00,0x00,0x00,0x06,
 0x08,0x08,0x82,0x83,0x35,0xd7,0xbe,0x00,0x00,0x00,0xed,0xd1,0x73,0x7e,0x01,
 0x00,0x00,0x00,0x19,0x00,0x00,0x88,0xe7,0x0e,0xbc,0x3c,0x72,0xe6,0x01,0x20,
 0x01,0x80,0x80,0x84,0xff,0xfe,0x7e,0xa6,0xf6,0x5b,0x26,0x25,0x88,0x7a,0xe9,
 0xf7,0x29,0x20,0x00,0x00,0x41,0x05,0x40,0x9f,0xb6,0x7b,0xc7,0xf5,0x01,0x00,
 0x00,0x04,0x06,0x00,0x40,0xa0,0x0e,0xad,0xea,0xb5,0x04,0x00,0x00,0xda,0x8c,
 0xf9,0x3c,0x04,0x01,0x04,0x40,0xf8,0x0f,0x04,0x02,0x5d,0x0b,0x78,0xbc,0xc0,
 0xb3,0x00,0x04,0x00,0x10,0x10,0x90,0xff,0xff,0xdf,0x9f,0xab,0x5e,0x14,0x5b,
 0x52,0xdb,0x7b,0xbf,0x69,0x00,0x00,0x00,0x40,0x11,0x44,0xfd,0xee,0xef,0x3f,
 0xbb,0x93,0x00,0x80,0x00,0xfe,0x03,0x01,0x04,0x71,0xbe,0xed,0xb6,0x00,0x00,
 0x00,0xbf,0x39,0xb3,0xdf,0x41,0x90,0x40,0x08,0x00,0x89,0x40,0x00,0x76,0x47,
 0x3c,0x3c,0xe0,0xbe,0x08,0x01,0x20,0x04,0x04,0x94,0xef,0xad,0xff,0xbf,0xf5,
 0x59,0x83,0xff,0xaa,0x7a,0xfb,0xff,0x5b,0x04,0x00,0x08,0x40,0x06,0x41,0x27,
 0xfb,0xde,0xfe,0x66,0x02,0x08,0x11,0x00,0x20,0x04,0x08,0x48,0xe0,0x1d,0xfb,
 0xbf,0x00,0x00,0x00,0xea,0x28,0xb3,0x6f,0x08,0x00,0x00,0x00,0x40,0x00,0x00,
 0x00,0x6e,0x07,0x3c,0x3c,0xe0,0xde,0x40,0x00,0x00,0x00,0x01,0x94,0x7b,0xff,
 0xf7,0xaf,0xf7,0xb7,0xa4,0xdd,0x46,0xdd,0xff,0xff,0x5b,0x00,0x42,0x00,0x49,
 0x11,0x40,0xf5,0xbf,0x9f,0xdf,0xb7,0x43,0x00,0x00,0x00,0x01,0x00,0x02,0x41,
 0xe1,0xbb,0xda,0xbd,0x20,0x00,0x20,0xfa,0x9c,0xeb,0xe3,0x00,0x00,0x00,0x02,
 0x02,0x20,0x08,0x80,0xef,0x07,0xf8,0x07,0xa0,0xa2,0x00,0x00,0x00,0x00,0x00,
 0xdc,0xff,0xb7,0xfe,0xff,0x6c,0x6d,0x91,0xfe,0xa9,0xba,0xff,0xfd,0x4b,0x10,
 0x00,0x40,0x80,0x16,0x40,0xaf,0x0c,0x44,0x84,0xf9,0x8d,0x00,0x00,0x40,0x10,
 0x11,0x40,0x10,0xf4,0xba,0x7d,0xbb,0x00,0x00,0x00,0x7e,0x7a,0xff,0x65,0x00,
 0x80,0x00,0x40,0x00,0x00,0x00,0xe0,0x67,0x47,0xf8,0x07,0xe0,0xde,0x03,0x01,
 0x00,0x22,0x00,0x94,0xdf,0xfd,0xfb,0xff,0xef,0xab,0x26,0xbd,0x89,0xdd,0x7f,
 0xdf,0x57,0x81,0x00,0x04,0x40,0x05,0x10,0xcb,0x46,0x37,0x22,0xef,0x0d,0x00,
 0x00,0x02,0x00,0x04,0x01,0x83,0x10,0xf7,0xfe,0xb7,0x08,0x00,0x00,0xd9,0x54,
 0xd5,0xb0,0x20,0x02,0x10,0x00,0x00,0x04,0x82,0x04,0x7d,0x0f,0x3a,0xbc,0xa8,
 0x96,0x10,0x00,0x84,0x00,0x20,0xdd,0x77,0xdf,0xae,0xef,0xd5,0xb5,0x11,0x01,
 0x52,0xfe,0xdf,0xff,0x53,0x20,0x10,0x01,0xa0,0x92,0xc0,0x3d,0x47,0xfa,0x05,
 0xb6,0xa6,0x90,0x40,0x00,0x00,0x01,0x08,0x1f,0xed,0xb5,0xff,0xbe,0x00,0x00,
 0x00,0xfa,0x32,0xbb,0x92,0x04,0x00,0x00,0x02,0x40,0x00,0x20,0x00,0xfd,0x07,
 0x38,0x3c,0xe0,0xbe,0x00,0x00,0x01,0x00,0x04,0xdc,0xfd,0xff,0xf7,0xdd,0x55,
 0x6f,0x64,0x52,0x88,0xd5,0xfe,0xdb,0x57,0x10,0x00,0x80,0x88,0x14,0xc0,0xcf,
 0x93,0xff,0x4f,0xee,0x1e,0x00,0x00,0x00,0x40,0x00,0x00,0x2d,0xa9,0xd7,0x6b,
 0xbb,0x00,0x00,0x40,0xfe,0xd4,0x6a,0x19,0x00,0x00,0x02,0x00,0x10,0x80,0x00,
 0x00,0x7e,0x07,0x78,0x78,0xe0,0xbe,0x88,0x00,0x00,0x04,0x00,0xea,0xff,0xff,
 0xdf,0xbe,0xef,0x5f,0x8a,0x04,0x56,0xfd,0xf7,0xff,0x17,0x00,0x00,0x00,0x20,
 0x05,0x80,0xaf,0xc7,0x62,0x30,0xfa,0xab,0x00,0x08,0x00,0x00,0x40,0x00,0xff,
 0x70,0x2f,0x8f,0xb5,0x00,0x00,0x04,0xda,0xaa,0x7e,0x9a,0x00,0x00,0x00,0x41,
 0x04,0x00,0x00,0x00,0xfc,0x0f,0x3a,0x78,0xc0,0xbf,0x00,0x10,0x00,0x40,0x08,
 0xda,0xff,0xb7,0xfd,0xd7,0xfb,0xd4,0x24,0x89,0x28,0xbe,0x7f,0xbd,0xd7,0x00,
 0x00,0x04,0x80,0x12,0xc0,0xaa,0x47,0x6e,0x12,0xde,0x1d,0x00,0x00,0x00,0x08,
 0x08,0x84,0xac,0x81,0x7b,0x87,0xbf,0x20,0x00,0x00,0xfb,0x6d,0xab,0x7c,0x00,
 0x20,0x00,0x10,0x00,0x44,0x08,0x84,0xef,0x0b,0x78,0x78,0xf2,0xf7,0x01,0x00,
 0x80,0x00,0x00,0xea,0xbf,0xff,0xef,0xfd,0x56,0x57,0xed,0xff,0x5f,0xfa,0xff,
 0xf7,0x06,0x20,0x02,0x81,0x20,0x15,0xc0,0xaa,0xa5,0x35,0xbc,0xde,0xb2,0x88,
 0x00,0x20,0x00,0x00,0x00,0x7b,0xf5,0xbf,0xf7,0xbf,0x08,0x00,0x00,0xba,0xb1,
 0x3d,0x8d,0x80,0x08,0x00,0x00,0x00,0x00,0x40,0x00,0xfa,0x4f,0x3c,0x7c,0xf0,
 0xf7,0x08,0x02,0x00,0x10,0x80,0xea,0xef,0xff,0x7b,0xaf,0xff,0xaf,0x09,0x40,
 0x02,0xff,0xdd,0xfe,0x97,0x00,0x40,0x00,0x80,0x14,0x68,0xdf,0x67,0x6d,0x4a,
 0x36,0x77,0x00,0x40,0x00,0x02,0x00,0x01,0x71,0xe3,0xea,0x8b,0xb5,0x00,0x00,
 0x00,0xfa,0x7b,0x35,0x5e,0x04,0x00,0x40,0x00,0x00,0x00,0x00,0x01,0xde,0x1f,
 0x38,0x3c,0xe8,0x73,0x80,0x80,0x00,0x02,0x00,0xea,0xff,0xfd,0xff,0xdf,0xfb,
 0x5b,0x13,0x08,0x28,0xdd,0xff,0xd7,0x87,0x10,0x10,0x00,0x90,0x05,0xc2,0xdd,
 0x56,0x7d,0x6e,0xfe,0x35,0x00,0x00,0x00,0x40,0x42,0x00,0xe6,0x66,0xf7,0x7e,
 0xb7,0x00,0x00,0x00,0xda,0xa7,0xad,0x9f,0x00,0x00,0x04,0x04,0x41,0x00,0x08,
 0x00,0xfe,0x39,0x7f,0x0f,0xf0,0x1b,0x00,0x00,0x80,0x00,0x22,0xea,0x7e,0xdf,
 0xee,0xb6,0x5e,0xbf,0xd4,0x22,0x49,0xff,0xf7,0xfd,0xa6,0x00,0x02,0x80,0xa4,
 0x12,0x40,0xf7,0x6b,0xd9,0x59,0xbe,0x57,0x10,0x04,0x00,0x00,0x10,0x10,0x00,
 0x97,0xbd,0xdf,0xbb,0x00,0x00,0x00,0xfa,0x37,0x4b,0xcf,0x40,0x00,0x01,0x00,
 0x04,0x48,0x42,0x10,0xbe,0x2e,0xff,0x03,0x3e,0x1f,0x08,0x00,0x04,0x00,0x00,
 0xea,0xf7,0xff,0xbb,0xdf,0xf6,0x6d,0x25,0x4b,0x12,0xed,0xbd,0xff,0x87,0x00,
 0x00,0x00,0x80,0x14,0x40,0xdf,0xc7,0xbe,0x35,0x36,0xb5,0x04,0x00,0x80,0x08,
 0x00,0x00,0x95,0x8b,0x7f,0xff,0xbf,0x20,0x00,0x40,0xfa,0x4e,0x8b,0x5f,0x00,
 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0xf6,0x7b,0x00,0x40,0xee,0x6d,0x00,0x00,
 0x00,0x00,0x00,0xea,0xff,0xdf,0xff,0xaf,0xbe,0x5f,0xd5,0xd4,0x44,0xff,0xff,
 0xb7,0xa7,0x80,0x00,0x10,0x20,0x93,0x70,0x77,0x03,0x77,0x27,0xfe,0x76,0x80,
 0x40,0x20,0x00,0x00,0x02,0x4c,0xbd,0xfe,0x7b,0xbd,0x00,0x00,0x10,0xfe,0xef,
 0xcd,0x5b,0x10,0x00,0x00,0x40,0x00,0x02,0x00,0x00,0xfe,0xfb,0x00,0x00,0xc5,
 0x7f,0x00,0x20,0x00,0x04,0x04,0xaa,0xbf,0xf7,0x5a,0xbd,0xed,0xfb,0x2a,0xa9,
 0x55,0xff,0xee,0xfe,0x87,0x08,0x00,0x00,0x80,0x14,0xc0,0xdb,0x47,0xfb,0x0e,
 0xae,0x7d,0x00,0x00,0x08,0x00,0x00,0x00,0x48,0x5d,0xb7,0x95,0xbf,0x00,0x00,
 0x00,0xda,0x95,0xf5,0x4c,0x00,0x00,0x00,0x10,0x04,0x00,0x00,0x41,0xf8,0xcf,
 0x01,0xc0,0xdb,0x0f,0x00,0x01,0x01,0x81,0x00,0xea,0xed,0xfd,0xef,0x6f,0xfb,
 0xae,0xa5,0x50,0xb4,0xdf,0xff,0xff,0x87,0x00,0x00,0x00,0x40,0x13,0x48,0xff,
 0xc5,0xde,0xbd,0x7e,0x17,0x00,0x00,0x00,0x40,0x20,0x00,0x30,0xf5,0xef,0xea,
 0xb2,0x10,0x00,0x00,0xfa,0xbf,0xfd,0xb9,0x00,0x21,0x80,0x00,0x00,0x00,0x21,
 0x08,0xf0,0xed,0x07,0x60,0xf9,0x07,0x08,0x00,0x40,0x00,0x40,0xea,0xff,0xbf,
 0xba,0x5f,0xdd,0xff,0x4d,0x85,0xca,0xff,0xef,0xdd,0xa7,0x00,0x00,0x04,0x41,
 0x15,0xc0,0xdf,0xf3,0xee,0x2b,0xbe,0x17,0x00,0x10,0x00,0x04,0x00,0x48,0xb0,
 0x7c,0xbd,0xfd,0xbf,0x00,0x00,0x00,0xfa,0xa9,0x1d,0x4c,0x10,0x00,0x12,0x00,
 0x00,0x21,0x00,0x00,0x50,0xfd,0xfe,0xff,0x56,0x0e,0x40,0x10,0x10,0x00,0x00,
 0xea,0xff,0xdd,0xef,0x7f,0x6b,0xfb,0x2a,0x5a,0xf2,0xb7,0x7d,0xf7,0x87,0x00,
 0x81,0x40,0x50,0x05,0xf0,0xde,0x3e,0x33,0xef,0xf6,0x35,0x02,0x04,0x00,0x00,
 0x84,0x00,0x84,0xd5,0xd7,0x03,0xba,0x20,0x00,0x00,0x5a,0x2f,0x6d,0x5a,0x04,
 0x00,0x00,0x10,0x40,0x00,0x00,0x80,0xf8,0xf7,0xfa,0xdf,0x9c,0x1d,0x01,0x00,
 0x00,0x00,0x01,0x62,0x7b,0xaf,0xbd,0xdf,0xec,0xfe,0x7f,0x45,0xfa,0xfd,0xdf,
 0x7f,0x97,0x00,0x20,0x00,0x40,0x11,0x82,0x87,0xcf,0xa8,0xac,0x5f,0x11,0x90,
 0x00,0x02,0x10,0x00,0x00,0x40,0xee,0xdf,0xc9,0xbd,0x00,0x00,0x00,0xfe,0xdd,
 0x3e,0x58,0x01,0x08,0x00,0x04,0x09,0x00,0x80,0x04,0x6a,0xed,0x78,0xb7,0xbe,
 0x43,0x10,0x00,0x01,0x20,0x00,0xca,0xff,0xbf,0xff,0x7f,0xdb,0xbf,0x6e,0x55,
 0xbd,0xef,0xff,0xfb,0xa7,0x88,0x00,0x00,0x80,0x96,0xc0,0xba,0xb7,0x6e,0x7b,
 0x7b,0x8b,0x08,0x00,0x20,0x01,0x00,0x08,0x90,0xd8,0xee,0x74,0xb7,0x08,0x00,
 0x00,0x5a,0x73,0xbc,0x5a,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x00,0x80,0xcf,
 0x7b,0xf3,0x7f,0x01,0x00,0x40,0x00,0x00,0x40,0xea,0xff,0xfb,0xbf,0xbd,0x6e,
 0xfb,0xfb,0xcb,0xfa,0xba,0xfb,0xde,0x97,0x00,0x00,0x00,0x40,0x11,0xc0,0xf7,
 0x3f,0xc9,0xce,0xef,0x1b,0x08,0x80,0x00,0x00,0x41,0x82,0x00,0x61,0x77,0xa5,
 0x9a,0x00,0x00,0x00,0xde,0x73,0x2d,0x5d,0x00,0x40,0x00,0x00,0x00,0x48,0x00,
 0x40,0x80,0x4f,0x7f,0xd7,0xe6,0x09,0x00,0x10,0x00,0x01,0x10,0xca,0xbf,0xbf,
 0xef,0xff,0xbd,0xef,0xdf,0x7e,0xef,0xff,0xaf,0xff,0x86,0x00,0x00,0x10,0x04,
 0x56,0xd0,0x7b,0x2d,0xb8,0xe5,0x7e,0x3f,0x00,0x08,0x00,0x04,0x10,0x00,0x44,
 0x60,0xbd,0x10,0xa5,0x00,0x00,0x80,0x5a,0x99,0x3e,0x4c,0x00,0x04,0x40,0x20,
 0x00,0x01,0x80,0x00,0x80,0xff,0xf5,0x2f,0xd9,0x01,0x00,0x00,0x00,0x20,0x00,
 0xda,0xff,0xfb,0xfe,0xff,0xd2,0xbc,0xff,0xfb,0x7e,0xeb,0xfe,0xdb,0x57,0x40,
 0x08,0x00,0x00,0x05,0x84,0x4d,0xcf,0xff,0x13,0x53,0x05,0x04,0x02,0x20,0x21,
 0x00,0x00,0x00,0xc1,0x52,0x40,0xb9,0x40,0x00,0x00,0xda,0x6f,0x3d,0x5e,0x80,
 0x00,0x00,0x04,0x20,0x00,0x00,0x00,0xa0,0xbc,0x75,0x6e,0x2d,0x00,0x00,0x02,
 0x20,0x00,0x00,0xd8,0xfb,0xbf,0x5f,0x7f,0xed,0xfb,0xfa,0x3f,0xff,0xbf,0x77,
 0x7f,0x13,0x00,0x00,0x00,0x01,0x15,0x40,0xcb,0x6f,0x82,0x12,0x77,0x05,0x8c,
 0x00,0x00,0x00,0x02,0x08,0x08,0xf0,0xd7,0x27,0xbc,0x00,0x00,0x00,0xfa,0xdf,
 0x96,0x5c,0x20,0x00,0x08,0x00,0x04,0x00,0x00,0x00,0x00,0xf8,0xf7,0xa6,0x1b,
 0x24,0x40,0x00,0x00,0x08,0x22,0xda,0xff,0xf7,0xff,0xdf,0xab,0xdd,0xdf,0x6f,
 0x6f,0xf7,0xff,0xed,0x57,0x00,0x00,0x02,0x40,0x12,0xd0,0xbb,0xde,0xab,0xce,
 0xbb,0x0d,0x20,0x00,0x20,0x00,0x00,0x80,0x42,0xe5,0xfc,0xff,0xbf,0x00,0x00,
 0x00,0x7a,0xbf,0x0d,0xce,0x00,0x00,0x00,0x00,0x00,0x20,0x10,0x42,0x08,0xf8,
 0xff,0xfc,0x1f,0x00,0x02,0x00,0x08,0x00,0x00,0x9c,0x7f,0xef,0xee,0xf7,0x77,
 0x7f,0xfb,0x1a,0xfb,0xfd,0xed,0xbf,0x53,0x10,0x00,0x00,0x90,0x02,0x82,0xbe,
 0x3a,0xa0,0xc1,0xf0,0x0f,0x08,0x00,0x09,0x00,0x00,0x01,0x00,0xe0,0xbb,0xf7,
 0xbf,0x00,0x00,0x00,0xba,0x6f,0xab,0x5d,0x00,0x20,0x00,0x01,0x20,0x04,0x04,
 0x00,0x00,0x00,0xfb,0xcf,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xd4,0xf7,0xbf,
 0x7f,0xff,0xab,0xf6,0xb7,0x17,0xff,0xdf,0x7f,0xff,0x5b,0x00,0x00,0x40,0x00,
 0x14,0x40,0xc7,0xb7,0xa5,0xfe,0x5e,0x02,0x06,0x00,0x00,0x80,0x10,0x00,0x40,
 0x62,0x5e,0xdf,0xaf,0x10,0x00,0x00,0xfa,0x87,0x83,0x5f,0x00,0x00,0x02,0x10,
 0x01,0x00,0x00,0x00,0x00,0x00,0xf1,0xcf,0x00,0x00,0x00,0x80,0x00,0x00,0x20,
 0x94,0xfd,0xda,0xf7,0xff,0xdf,0xed,0xfe,0x05,0x7f,0xfb,0xde,0xfb,0x53,0x04,
 0x22,0x00,0x00,0x09,0x40,0xed,0xef,0xcf,0x37,0xff,0x01,0x09,0x00,0x00,0x02,
 0x00,0x40,0x20,0xe5,0xbe,0xbd,0xba,0x00,0x00,0x00,0x5a,0x82,0xa1,0x5e,0x00,
 0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x61,0x0e,0x00,0x10,0x00,0x00,
 0x00,0x01,0x09,0x94,0xbf,0xff,0xdb,0xef,0xd7,0xbf,0xff,0x83,0xff,0xbf,0xf7,
 0xff,0x69,0x00,0x00,0x00,0x00,0x02,0x80,0xde,0xde,0x9b,0x9e,0xdb,0x03,0x0d,
 0x40,0x40,0x08,0x0f,0x11,0x00,0x70,0xf7,0xab,0xad,0x00,0x00,0x00,0x7a,0xe9,
 0x4a,0x4f,0x04,0x00,0x20,0x00,0x84,0x08,0x00,0x11,0x01,0x00,0x20,0x00,0x00,
 0x05,0x00,0x00,0x40,0x40,0x00,0x90,0xf7,0xd7,0xfe,0xff,0xaf,0xea,0xb6,0x20,
 0xbf,0xed,0xff,0xdf,0x69,0x00,0x00,0x02,0x04,0x08,0x91,0xb0,0x6f,0xfe,0xf3,
 0x7f,0x00,0x00,0x10,0x00,0x00,0x01,0x00,0x08,0xa0,0x9b,0xde,0xba,0x00,0x00,
 0x00,0xda,0x63,0xe2,0x5f,0x40,0x08,0x01,0x08,0x00,0x02,0x04,0x00,0x20,0x80,
 0x04,0x00,0x00,0x00,0x40,0x40,0x08,0x04,0x00,0x90,0xbe,0xff,0xff,0xff,0xbf,
 0xff,0x5f,0x04,0xfe,0xff,0xfb,0xf6,0x69,0x00,0x00,0x20,0x00,0x42,0x00,0xb0,
 0xbb,0x51,0x7d,0x6b,0x41,0x8e,0x04,0x00,0x89,0x01,0x00,0x40,0xea,0x77,0xb5,
 0xbf,0x20,0x00,0x80,0xfa,0xf9,0xff,0x5f,0x00,0x00,0x00,0x40,0x88,0x00,0x40,
 0x00,0x00,0x22,0x00,0x10,0x10,0x00,0x11,0x00,0x00,0x00,0x00,0xa0,0xef,0x6d,
 0xb5,0xfa,0xff,0x6a,0x17,0xa0,0xee,0x7b,0xff,0xff,0x29,0x00,0x01,0x00,0x80,
 0x04,0x40,0xc9,0xfe,0xfa,0xff,0x7b,0x81,0x04,0x00,0x24,0x80,0x40,0x4b,0x01,
 0xe0,0xb7,0x6f,0xaf,0x08,0x00,0x00,0xfa,0x62,0xb5,0x4f,0x01,0x41,0x00,0x01,
 0x00,0x20,0x00,0x04,0x04,0x00,0x00,0x00,0x02,0x40,0x00,0x10,0x00,0x00,0x00,
 0xa9,0xff,0xfb,0xef,0xdf,0xbf,0xbd,0x2d,0x00,0x7b,0xdf,0xdf,0xff,0x21,0x08,
 0x00,0x00,0x02,0x20,0x90,0xc0,0xfd,0x46,0xea,0x18,0x81,0x01,0x00,0x00,0x08,
 0x51,0xab,0x88,0xf0,0xdf,0xbb,0xbc,0x00,0x00,0x00,0xba,0x2e,0xee,0x5b,0x10,
 0x10,0x14,0x10,0x02,0x04,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x12,0x00,0x00,
 0x00,0x00,0x00,0x28,0x77,0xdf,0xf7,0xff,0x3b,0x56,0x00,0xa1,0xcf,0xfb,0x7b,
 0xff,0x25,0x00,0x00,0x04,0x00,0x10,0x20,0xa0,0xd7,0xde,0x3b,0x6f,0x41,0x06,
 0x00,0x80,0x00,0x47,0x93,0x00,0x42,0x7f,0xff,0xbf,0x08,0x00,0x00,0xfa,0xd6,
 0xfb,0x5d,0x00,0x00,0x00,0x00,0x20,0x01,0x00,0x00,0x00,0x00,0x42,0x00,0x00,
 0x00,0x00,0x00,0x00,0x10,0x40,0x68,0xff,0x7f,0xfe,0x6f,0xff,0xbf,0x11,0x80,
 0xdf,0xde,0xfe,0xfb,0x14,0x02,0x00,0x01,0x00,0x20,0x14,0xa4,0xae,0x7b,0x3d,
 0x1b,0x01,0x20,0x04,0x01,0x00,0x00,0x00,0x00,0xe0,0x7e,0xf7,0xba,0x00,0x00,
 0x20,0x3a,0x7f,0xfb,0x4e,0x00,0x00,0x80,0x00,0x08,0x00,0x02,0x40,0x40,0x04,
 0x00,0x84,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x69,0xff,0xef,0xdb,0xfe,0x3f,
 0xa5,0x00,0xe9,0xdf,0xf7,0xef,0xdf,0x16,0x01,0x40,0x40,0x40,0x00,0x03,0xa8,
 0xfe,0xaa,0xd2,0x55,0x2a,0x09,0x20,0x00,0x08,0x00,0x00,0x20,0xb8,0xb5,0xbf,
 0xb7,0x00,0x00,0x00,0xba,0xf7,0xbf,0x5d,0x00,0x00,0x01,0x00,0x00,0x82,0x80,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x40,0x00,0x80,0x52,0x7f,0x77,
 0xff,0xff,0xbe,0x2d,0x40,0xd0,0xdd,0x7a,0x7f,0xf7,0x92,0x00,0x10,0x00,0x10,
 0x00,0x00,0x00,0xc0,0xff,0x3f,0x00,0x00,0x00,0x00,0x84,0x00,0x00,0x00,0x04,
 0x66,0xc2,0xef,0xbd,0x40,0x00,0x00,0x7a,0xbf,0xdf,0x4e,0x00,0x09,0x00,0x08,
 0x01,0x20,0x20,0x10,0x08,0x40,0x04,0x00,0x80,0x00,0x00,0x04,0x04,0x00,0x84,
 0x59,0xef,0xdd,0xfb,0xef,0xbf,0x2a,0x2a,0xd4,0xff,0xdf,0xff,0xff,0x9e,0x00,
 0x01,0x00,0x04,0x88,0x00,0x01,0x40,0xf6,0x33,0x00,0x00,0x00,0x00,0x20,0x90,
 0x40,0x04,0x01,0xce,0xef,0xf6,0xbb,0x00,0x00,0x00,0xba,0xef,0xab,0x7d,0x04,
 0x80,0x10,0x40,0xf8,0x00,0x0c,0x10,0x78,0x10,0x41,0x12,0x37,0x34,0x68,0x00,
 0x21,0x00,0x80,0x06,0xfe,0xbf,0x7f,0xfd,0xff,0xaa,0x02,0xf0,0x7f,0xf7,0x7b,
 0xff,0x58,0x41,0x00,0x00,0x00,0x02,0x40,0x00,0x00,0x22,0x00,0x10,0x00,0x00,
 0x01,0x04,0x04,0x00,0x02,0x00,0xe5,0xb9,0xff,0xb7,0x10,0x00,0x00,0x7a,0xff,
 0xfe,0x82,0x43,0x00,0x80,0x00,0xd0,0x01,0x1e,0x7c,0x58,0xc0,0x01,0x07,0x6f,
 0x28,0xd0,0x01,0x21,0x00,0x20,0x8b,0xfe,0xf7,0xfa,0xdf,0xbf,0xaa,0x00,0xe8,
 0xbd,0xfc,0xde,0x6b,0x9a,0x01,0x00,0x00,0x00,0x80,0x10,0x10,0x00,0x20,0x00,
 0x00,0x00,0x02,0x00,0x00,0x00,0x10,0x80,0x40,0x81,0xff,0x6f,0xbd,0x00,0x00,
 0x00,0xba,0xbf,0x1f,0x04,0x08,0x20,0x00,0x00,0x08,0x03,0x21,0x4c,0x20,0x60,
 0x86,0x0c,0x01,0xcc,0x98,0x21,0x21,0x00,0x80,0xba,0xfc,0xef,0xef,0xff,0x3f,
 0x44,0x00,0x75,0xff,0xcb,0xff,0x7f,0xe9,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x04,0x80,0x00,0x00,0x01,0x00,0x04,0x01,0x28,0x27,0xbd,0xbe,
 0xb5,0x00,0x00,0x00,0xfa,0xfa,0xaf,0x95,0x30,0x08,0x02,0x08,0x08,0x03,0x23,
 0x44,0x40,0x22,0x86,0x08,0x01,0xc4,0x18,0x01,0x21,0x00,0x42,0xac,0xfc,0xbb,
 0xff,0xbf,0x7d,0xa8,0x40,0x52,0xbd,0xf2,0xff,0x7f,0xac,0x05,0x00,0x84,0x40,
 0x20,0x00,0x00,0x80,0x02,0x00,0x00,0x12,0x00,0x48,0x88,0x10,0x00,0x00,0x04,
 0x03,0xed,0xdd,0xbd,0x00,0x00,0x00,0x7a,0x7d,0x91,0x5e,0xc4,0x00,0x08,0x80,
 0x18,0x21,0x30,0x4d,0x60,0x00,0x84,0x08,0x01,0xc0,0x88,0x01,0x29,0x10,0xc0,
 0xb9,0x7c,0xef,0xf7,0x6f,0x7f,0x01,0x06,0x74,0xbd,0x4e,0xff,0x3f,0xed,0x07,
 0x88,0x00,0x10,0x00,0x02,0x00,0x20,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,
 0x40,0x80,0x08,0xee,0xb2,0x7b,0xb6,0x00,0x00,0x00,0xfa,0xed,0x6b,0xc7,0x01,
 0x00,0x20,0x20,0x90,0x03,0x18,0x54,0x60,0x00,0x86,0x0d,0x1d,0x50,0xf0,0x00,
 0x3f,0x04,0x40,0x69,0xfc,0xff,0xbb,0xfa,0xf5,0x22,0x43,0xc8,0x7e,0xdb,0xf4,
 0x3f,0xa7,0x45,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x80,0x40,0x00,0x00,
 0x01,0x00,0x08,0x01,0x00,0x2c,0x6b,0xf1,0x56,0x3f,0x20,0x00,0x10,0xfa,0xba,
 0xb5,0x1e,0x97,0x82,0x08,0x01,0x78,0x01,0x1c,0x5c,0x60,0xc0,0x81,0x0b,0x23,
 0x70,0x98,0x01,0x21,0x00,0x88,0x49,0xfd,0xfd,0xff,0xff,0xfd,0x41,0x2e,0x81,
 0xf6,0xae,0x4f,0xaf,0xd6,0x25,0x00,0x20,0x04,0x02,0x20,0x00,0x01,0x00,0x10,
 0x10,0x00,0x00,0x00,0x40,0x00,0x20,0x80,0xb0,0xff,0x0d,0x95,0xbf,0x00,0x00,
 0x00,0xba,0x53,0xfd,0xe5,0x7f,0x08,0x00,0x00,0x08,0x03,0x20,0xc4,0x60,0x60,
 0x40,0x18,0x60,0xc0,0x18,0x09,0x21,0x01,0xc1,0x1b,0x73,0x77,0xe7,0xbb,0xef,
 0x57,0x25,0x24,0xf8,0xd5,0xbd,0x9f,0xa2,0x09,0x00,0x08,0x41,0x20,0x08,0x08,
 0x00,0x08,0x00,0x00,0x20,0x21,0x10,0x04,0x00,0x24,0x60,0xe7,0x85,0x47,0xbc,
 0xba,0x08,0x00,0x00,0xda,0xa6,0x59,0x00,0xfe,0x08,0x05,0x10,0x09,0x03,0x20,
 0x86,0x20,0x20,0x80,0x10,0x60,0xc0,0x08,0x03,0x21,0x00,0xd0,0xcb,0xfa,0xdf,
 0xfb,0xfe,0xfb,0x23,0x4b,0x08,0xea,0x5d,0xef,0xda,0xea,0x15,0x02,0x00,0x10,
 0x00,0x01,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x42,0x50,0x10,0xe3,
 0x00,0xce,0xa8,0xb7,0x00,0x00,0x00,0xba,0x57,0x37,0xde,0xd0,0x93,0x80,0x00,
 0x58,0x43,0x33,0x44,0x60,0x28,0x80,0x08,0x30,0xc6,0xd8,0x41,0x21,0x00,0x40,
 0xa7,0xb2,0xff,0xdf,0xf7,0xb7,0x47,0x1e,0x80,0xf5,0xfd,0xbb,0x4f,0x4d,0x35,
 0x40,0x08,0x00,0x04,0x00,0x08,0x00,0x00,0x82,0x00,0x04,0x00,0x40,0x20,0x00,
 0x02,0x92,0x33,0xfe,0x80,0xdb,0xbd,0x00,0x00,0x00,0xea,0xf5,0x8f,0x55,0xe1,
 0x07,0x00,0x00,0xb8,0x81,0x2f,0x7c,0xf8,0xd3,0x87,0x0d,0x1f,0xdc,0x78,0x01,
 0x21,0x00,0x50,0x27,0xf4,0xeb,0xfd,0xef,0xff,0xc7,0x0a,0x51,0xee,0xaf,0xfe,
 0x0a,0xc1,0x06,0x00,0x02,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,
 0x08,0x00,0x20,0x28,0xd8,0x0b,0xff,0xf3,0xb3,0x2e,0x00,0x00,0x00,0xfa,0xc3,
 0x47,0xed,0xcf,0x67,0x90,0x20,0x20,0x00,0x08,0x10,0x08,0xa0,0x04,0x07,0x05,
 0x10,0x00,0x00,0x00,0x20,0xa8,0xf5,0xe5,0xbb,0xfb,0xfb,0xfb,0x9f,0x1a,0xa4,
 0xd0,0xbf,0xeb,0xa7,0xd7,0x11,0x00,0x40,0x10,0x41,0x00,0x00,0x02,0x80,0x00,
 0x00,0x80,0x00,0x00,0x00,0x08,0x21,0xe0,0xc3,0x13,0xcb,0xe7,0xb5,0x20,0x00,
 0x00,0xfa,0x65,0x71,0xab,0x95,0x5e,0x02,0x04,0x02,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x22,0xa5,0xcd,0xfe,0x7f,0xbf,0xef,
 0x5e,0x2a,0x69,0xda,0x7b,0xbd,0xb3,0xd5,0x04,0x01,0x00,0x04,0x00,0x20,0x80,
 0x00,0x10,0x10,0x08,0x00,0x04,0x42,0x90,0x00,0x14,0xe4,0xb3,0xee,0xcd,0xaf,
 0xbf,0x00,0x00,0x00,0x7a,0x13,0x91,0x7e,0x29,0x9f,0x20,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x57,0xcb,0xf7,
 0xd7,0xef,0xbf,0x8f,0x3a,0x85,0xa2,0xbb,0xdf,0xd3,0xd7,0x4c,0x00,0x08,0x00,
 0x00,0x00,0x00,0x40,0x00,0x00,0x40,0x10,0x80,0x00,0x02,0x42,0x02,0x72,0x59,
 0x7f,0x3b,0x9d,0x37,0x00,0x00,0x80,0xea,0xf8,0xfc,0x04,0x35,0xba,0x22,0x00,
 0x00,0x00,0x00,0x00,0x00,0x01,0x20,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x40,
 0x6e,0xc2,0xbf,0xfc,0xf5,0xfb,0x2f,0x6a,0xad,0xa9,0xeb,0xf6,0xd3,0x76,0x15,
 0x20,0x40,0x80,0x10,0x01,0x02,0x00,0x00,0x00,0x01,0x04,0x00,0x20,0x00,0x00,
 0x0c,0xfa,0xdc,0x81,0x3a,0x97,0xb7,0x10,0x00,0x00,0xda,0xf9,0xa4,0x03,0xef,
 0x6e,0x01,0x40,0x04,0x08,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x11,
 0x04,0x20,0x88,0xd8,0x93,0xf7,0x6b,0xef,0xd7,0x9f,0xad,0x12,0x85,0xf6,0xbd,
 0xc9,0xb7,0x02,0x08,0xfa,0xff,0x0e,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,
 0x00,0x91,0x88,0x10,0xbc,0xb8,0x81,0x7d,0xb8,0xba,0x00,0x00,0x00,0xba,0x7c,
 0x56,0x80,0xdb,0x6c,0x00,0x15,0x00,0x81,0xe0,0x00,0x01,0x14,0x00,0x08,0x40,
 0x10,0x10,0x00,0x80,0x08,0x44,0x7f,0x2e,0xfd,0xff,0xbf,0xff,0x5f,0x35,0x50,
 0xa5,0x6e,0xff,0x64,0xd7,0x4b,0x04,0xf8,0xce,0x0e,0x00,0x10,0x00,0x00,0x04,
 0x00,0x40,0x00,0x10,0x00,0x00,0x0d,0x7d,0xe6,0x80,0xdb,0x3c,0x33,0x04,0x00,
 0x00,0xea,0x5c,0x6e,0x00,0x6f,0x79,0x00,0x00,0x40,0x00,0x18,0x10,0xc0,0x3f,
 0x04,0x80,0x88,0x04,0x04,0x00,0x00,0x80,0x82,0xd4,0x2a,0xff,0xdf,0xf7,0xfe,
 0xbf,0xa6,0x6a,0xca,0xff,0xb7,0xf4,0xbf,0xaa,0x93,0x68,0x5a,0x28,0x01,0x00,
 0x00,0x40,0x00,0x08,0x00,0x12,0x04,0x0a,0x42,0x02,0x6d,0x3d,0x80,0xbf,0x5c,
 0xbb,0x00,0x00,0x00,0xba,0x3e,0xfd,0x80,0xfd,0xe8,0x13,0x00,0x02,0x00,0x04,
 0x0c,0x30,0x01,0xc0,0x00,0xe0,0x03,0xc1,0x87,0x00,0x80,0x7d,0xfa,0xcd,0xee,
 0xf6,0xde,0xef,0xbe,0xde,0x06,0x51,0xcf,0x7e,0xb2,0xca,0x7a,0x04,0x00,0x00,
 0x00,0x08,0x00,0x78,0x00,0x00,0x80,0x19,0x00,0x00,0xc1,0x20,0x85,0x3e,0x7b,
 0x80,0xb5,0x79,0x3e,0x10,0x00,0x00,0x7a,0x3e,0x7b,0x81,0xdb,0xf9,0x02,0x10,
 0x2c,0x00,0x26,0x00,0x90,0x00,0xe0,0x00,0xe0,0x8e,0xc0,0x0d,0x00,0x64,0xab,
 0xe2,0xdf,0xfe,0xff,0x7f,0xff,0x7f,0xa9,0xac,0xc8,0xfd,0x7b,0xbb,0xf7,0x4e,
 0x05,0x40,0xb3,0x05,0x10,0x80,0x44,0x01,0x00,0x01,0x09,0x60,0x00,0x10,0x48,
 0x83,0x2e,0xd7,0x80,0xef,0x69,0xbe,0x00,0x00,0x00,0x7a,0x16,0xb5,0x91,0xb5,
 0xda,0x01,0x01,0x7f,0x20,0x90,0x00,0x38,0x11,0x60,0xa0,0x42,0x0a,0x42,0x00,
 0x04,0x81,0xfc,0x0f,0x3e,0xdd,0x6d,0xef,0x5f,0xff,0xae,0x22,0x42,0xef,0x3f,
 0xf9,0xc6,0x17,0x01,0x40,0x8d,0x41,0x02,0x40,0x02,0x01,0x00,0x41,0x09,0x20,
 0x00,0x00,0xe0,0x8b,0x9e,0xbd,0x91,0x7b,0xba,0x36,0x00,0x00,0x00,0x7a,0xbe,
 0xf7,0x01,0x77,0x73,0x01,0x80,0xe3,0x08,0xd1,0x20,0x08,0x19,0x25,0xcf,0x30,
 0x65,0x67,0x22,0x00,0x20,0xd1,0x95,0x3c,0xf9,0xdf,0xfb,0xfb,0x7b,0x93,0x20,
 0xc1,0x5d,0x9f,0xbc,0xa3,0x8d,0x44,0x44,0x97,0x00,0x00,0x00,0x02,0x01,0x00,
 0xc5,0x3f,0x00,0x00,0x00,0xe8,0x8f,0x16,0xdb,0x80,0xaf,0xdb,0xbe,0x24,0x00,
 0x00,0x5a,0x96,0xda,0x80,0xff,0xb2,0x11,0x80,0xc1,0x80,0xdd,0x28,0x80,0xd4,
 0xdf,0x29,0x98,0x3c,0xb8,0xb3,0x41,0x88,0xf6,0x57,0x77,0xf1,0xff,0xff,0xfd,
 0xdf,0x5e,0x2b,0xb0,0xfe,0x97,0x5e,0xf8,0xe7,0x93,0x40,0x93,0x20,0x00,0x00,
 0x02,0x4d,0x99,0x07,0xcb,0x93,0x8d,0x01,0x31,0x09,0x8e,0xdd,0x81,0xfb,0xf2,
 0x3a,0x00,0x00,0x20,0x7a,0x8e,0x5a,0x89,0x55,0xd3,0x81,0x08,0xd0,0x00,0xe7,
 0x1b,0x80,0xbc,0x33,0x3c,0x04,0x36,0xe4,0xe9,0x00,0x62,0x2f,0xbf,0xee,0xf2,
 0xfd,0xbf,0xff,0x7d,0x2b,0x63,0x60,0xf7,0x4f,0x46,0xbd,0xfa,0x2d,0x00,0x08,
 0x08,0x00,0x03,0x46,0x6b,0x4d,0x03,0x4d,0x59,0x4b,0x01,0xa4,0x2a,0x9f,0xb7,
 0x80,0x53,0xb3,0xbe,0x04,0x00,0x00,0x7a,0xdb,0xbe,0x21,0xff,0x76,0x05,0x00,
 0xe5,0x10,0xc0,0x20,0x08,0x40,0x01,0x00,0x80,0x00,0x00,0x00,0x00,0xe8,0xcd,
 0x65,0xfc,0xe4,0x77,0xf7,0x77,0xff,0x5a,0x54,0xa2,0xb6,0x67,0x7f,0x7a,0x0b,
 0x77,0x11,0x0c,0x00,0x01,0x20,0x3c,0xd9,0x3b,0x0d,0xc9,0x37,0xb9,0x07,0x48,
 0x4a,0x92,0x6c,0x81,0xf5,0xb2,0x3c,0x00,0x00,0x00,0x7a,0xcb,0xdd,0x81,0xed,
 0xe7,0x05,0x02,0x3e,0x00,0x60,0x00,0x00,0x90,0x00,0x01,0x00,0x00,0x00,0x00,
 0x08,0x11,0xb5,0xde,0xb8,0xc9,0xff,0xff,0xfd,0xff,0xd5,0x90,0xb0,0xba,0x93,
 0xdb,0x8d,0xbf,0x42,0x02,0x1e,0x42,0x00,0x22,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x40,0x65,0x4f,0x9f,0xbf,0x91,0x7f,0xd7,0xbd,0x00,0x00,0x80,0x7a,0x5d,
 0x6f,0x21,0xe7,0x66,0x83,0x00,0x0f,0x02,0x40,0x80,0x20,0xd2,0x00,0x00,0x00,
 0x00,0x00,0x20,0x00,0xae,0xae,0xd3,0xf3,0x9b,0xd7,0xef,0xbf,0xff,0x1f,0x2c,
 0x2d,0xdd,0x99,0x7f,0x57,0x4a,0xac,0x41,0x14,0x08,0x10,0x00,0x00,0x20,0x00,
 0x00,0x10,0x00,0x00,0x00,0xe8,0x47,0xd3,0x6d,0x81,0xf7,0x75,0x35,0x04,0x00,
 0x00,0x3a,0xd7,0xdc,0x89,0xef,0xe5,0x22,0xa0,0x83,0x00,0x10,0x00,0x00,0x20,
 0x00,0x00,0x80,0xc0,0x08,0x00,0x00,0x61,0x11,0xea,0xce,0x36,0x7f,0xbf,0xff,
 0xfe,0x69,0x0b,0x4d,0xf7,0xe4,0xca,0xb5,0x8e,0x2b,0x04,0x88,0x00,0x0b,0x08,
 0x00,0x00,0x10,0x20,0x00,0x00,0x84,0x00,0x72,0x40,0x8b,0xef,0x81,0x55,0xd3,
 0xbd,0x00,0x00,0x10,0x78,0xd5,0xdf,0x81,0x7b,0xa7,0x05,0x01,0x09,0x90,0x00,
 0x10,0x04,0x38,0x80,0x00,0x00,0x30,0x01,0x82,0x20,0x40,0xc4,0xb0,0xbf,0x27,
 0xfe,0xfb,0xaf,0xff,0x5b,0x93,0x4a,0x75,0xe4,0xfb,0x4a,0x3d,0x29,0x81,0x00,
 0xa0,0x34,0x00,0x08,0x08,0x00,0x00,0x02,0x04,0x00,0x50,0xa8,0x00,0xdb,0xad,
 0xa0,0xef,0xf7,0xbc,0x00,0x00,0x00,0x7a,0xdb,0xde,0x81,0xed,0xf6,0x22,0x88,
 0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x0c,0x02,0x20,0x00,0xa8,0x7f,
 0xaf,0xb6,0x6d,0xee,0xbf,0xfb,0x00,0x00,0x0c,0x54,0xfd,0xec,0xb7,0xfd,0xfd,
 0x5f,0x10,0x24,0x04,0x3e,0x00,0x00,0x01,0x04,0x01,0x80,0x80,0x00,0x04,0x32,
 0x40,0x95,0xcf,0x81,0x73,0x55,0x2d,0x00,0x00,0x04,0x7a,0xc5,0x5b,0x11,0xff,
 0xe5,0x09,0x80,0xff,0x00,0x04,0x02,0x80,0x00,0x00,0x00,0x40,0xe0,0x40,0x00,
 0x08,0xe9,0xff,0x7e,0x7d,0x27,0xfe,0xf7,0x8f,0x0b,0xee,0xe3,0x49,0xed,0xd9,
 0xff,0x77,0xd7,0xb6,0xef,0xdf,0xfb,0x57,0x40,0x40,0x80,0x00,0x70,0x04,0x00,
 0x00,0x80,0x68,0x0d,0x9b,0x7e,0x81,0x7f,0xf3,0xbd,0x20,0x00,0x00,0x5a,0x97,
 0xde,0x81,0x6d,0xb7,0x00,0x02,0x20,0x22,0x89,0x80,0x00,0x20,0x10,0x18,0x02,
 0x94,0x03,0x04,0x00,0x00,0x00,0x00,0x00,0x90,0x61,0x3f,0x34,0xaa,0xea,0x60,
 0xd9,0x16,0x22,0x00,0x89,0x2a,0x55,0xb5,0x6a,0xad,0x56,0x48,0x04,0x00,0x74,
 0x10,0x90,0x10,0x44,0x00,0xf6,0x4f,0x96,0xeb,0x88,0xf7,0x5a,0x37,0x00,0x00,
 0x00,0x6a,0x8a,0xb9,0x80,0x73,0xd3,0x01,0x20,0x09,0x00,0x04,0x20,0xa0,0x42,
 0x00,0x0a,0x02,0xb0,0xef,0xfb,0x77,0x7f,0xf7,0xb7,0xef,0x9f,0xcd,0x57,0x9b,
 0x03,0x00,0x52,0xa5,0x7e,0xe6,0xff,0xfe,0xdd,0xfb,0xdd,0xff,0xf7,0x71,0x00,
 0xd5,0x3e,0xe5,0xd2,0x96,0x0f,0x00,0x20,0x01,0x00,0x95,0xde,0x81,0xb9,0x73,
 0xae,0x04,0x00,0x00,0x58,0xb6,0xf7,0x00,0xbb,0xba,0x4a,0x00,0x00,0x91,0xba,
 0x86,0x9a,0xa9,0xf2,0xe1,0x1c,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,
 0xd3,0x84,0xf0,0xff,0xff,0x1f,0x06,0xb1,0x0f,0x00,0x00,0x00,0x00,0x12,0x12,
 0x24,0x2a,0xc0,0x58,0xa1,0x92,0x28,0x65,0x10,0x00,0x21,0x34,0x84,0x86,0xb9,
 0xa0,0x7f,0xdb,0xb6,0x10,0x00,0x00,0xaa,0x26,0x3d,0x91,0xbd,0x59,0x03,0x00,
 0x00,0x00,0xa5,0x6a,0x05,0x46,0x24,0x49,0x45,0xdc,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0x69,0x82,0xff,0xff,0xff,0xff,0x87,0xce,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0x27,0x03,0x00,0x10,0x00,0x00,0x00,0x02,0x44,0x88,0x00,
 0xa1,0x36,0x7f,0x81,0xcd,0x19,0xbe,0x00,0x00,0x08,0xfa,0x2e,0x7b,0x01,0x7b,
 0xb9,0x43,0x04,0x48,0x94,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xb3,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xf3,0xf8,0xff,0xfd,0xff,0xff,0xbf,0x8e,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdb,0x02,0x04,0x00,0x00,0x00,0x00,0x02,
 0x01,0x40,0x2a,0x80,0x36,0xb3,0x80,0xbd,0x79,0xbe,0x00,0x00,0x00,0xba,0x5b,
 0x6f,0x00,0xcd,0x49,0x00,0x21,0x04,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
 0xd5,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfa,0xff,0x5f,0x95,0x00,0xf0,
 0xff,0xff,0xe7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x25,0x1a,0x42,0x48,0x41,
 0x08,0x00,0x48,0x21,0xad,0x31,0x14,0x65,0xef,0x08,0xef,0x0c,0x31,0x10,0x00,
 0x80,0xea,0x55,0x0a,0x04,0x58,0xac,0x54,0x00,0x00,0x08,0x00,0x00,0x01,0x00,
 0x00,0x00,0x10,0x15,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd5,0xee,0xb7,
 0xad,0xfe,0x8b,0xfe,0xf7,0xa9,0xda,0xff,0xff,0xff,0xff,0xff,0xff,0x95,0xc6,
 0x90,0x5a,0x1d,0x73,0x6f,0x27,0x94,0x5a,0xce,0x51,0x55,0x1d,0x40,0xbc,0x5c,
 0xbf,0x00,0x00,0x00,0xf8,0xc5,0xfc,0xff,0xbf,0x56,0x9b,0x73,0x6b,0xe7,0xac,
 0xbd,0xae,0x95,0xb3,0x56,0x4b,0xe5,0x49,0x0a,0x00,0x02,0x40,0x00,0x00,0x00,
 0x3e,0x00,0x00,0x2b,0x20,0x30,0x00,0x70,0x01,0xe0,0x88,0xc0,0x06,0x40,0x80,
 0x85,0x84,0x88,0xb4,0x56,0x45,0xa5,0x52,0x6a,0xa9,0xb5,0xab,0xb4,0x68,0xf6,
 0xff,0xf7,0xb4,0xbf,0x04,0x00,0x00,0x9a,0xb9,0xd4,0xff,0x97,0x26,0x2d,0x55,
 0x6d,0x55,0x1a,0x63,0x4a,0x90,0x54,0x2d,0x2a,0x95,0x56,0x05,0x07,0x06,0xc0,
 0x61,0x00,0x00,0xe2,0x00,0x03,0x2f,0x70,0xe0,0x01,0xfc,0x03,0xf0,0x7f,0xc0,
 0x1d,0xc0,0x00,0xb7,0x2b,0x53,0x6a,0xd7,0x56,0x49,0x0c,0x2b,0x2d,0xdf,0x67,
 0xb5,0x88,0xd8,0xff,0x57,0xae,0xb5,0x00,0x00,0x00,0xda,0x1b,0xb9,0xb6,0x2e,
 0xcb,0x4e,0x4b,0x0c,0xa9,0xb5,0xba,0xb7,0xb5,0x96,0xb2,0x57,0xb1,0xed,0x00,
 0x0f,0x18,0x80,0xf7,0x00,0x07,0xae,0x09,0x07,0x0c,0x70,0x80,0x03,0xfc,0x07,
 0xf8,0x2b,0x80,0x7f,0xc0,0x01,0x5f,0x72,0xb6,0xdf,0xfa,0xbd,0xf7,0xfb,0xea,
 0xd6,0x6a,0xda,0x4b,0xdb,0xbd,0xfe,0x3d,0x93,0xbb,0x00,0x00,0x10,0xfa,0xaa,
 0xe3,0xba,0x3c,0xab,0xfd,0xf7,0xf7,0xf7,0x6e,0x77,0xad,0x77,0xf7,0xfd,0xd6,
 0x4e,0x5f,0x01,0x0f,0x38,0x04,0xf7,0x00,0x17,0x5e,0x81,0x97,0x0c,0x70,0x80,
 0x03,0xbe,0x05,0xfc,0x5f,0x08,0x77,0xc0,0x20,0xbe,0x35,0x0a,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x04,0x20,0x56,0xd1,0x2e,0x16,0x47,0x3d,0x00,0x00,
 0x00,0xe8,0x27,0xa6,0xb5,0x87,0x41,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x80,0x78,0xb7,0x00,0x0f,0xb8,0x00,0xf6,0x00,0xe1,0xdf,0x00,0x07,
 0x08,0x70,0x80,0x01,0x6e,0x02,0xbc,0xb0,0x01,0x5f,0xe0,0x80,0x9f,0xca,0xf1,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x87,0x63,0x5b,0xc5,0x69,
 0xae,0x40,0x00,0x00,0xfa,0x2c,0x8d,0xaf,0xe3,0xe8,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xaf,0xb7,0x5a,0x08,0x0f,0xb8,0x01,0xf0,0x04,0xf1,
 0xb7,0x01,0x07,0x08,0x70,0xc0,0x03,0x3e,0x06,0x6c,0x8d,0x01,0x5e,0x40,0xc8,
 0xbf,0xfc,0xc7,0xd5,0xbe,0xc5,0xba,0xea,0xff,0xdd,0xff,0xf7,0xff,0x6f,0x8c,
 0x57,0x63,0xe4,0xbb,0x10,0x00,0x00,0xba,0x5c,0x1c,0xd6,0x70,0xe4,0xff,0xfd,
 0xf7,0xee,0xfd,0xff,0xff,0x6f,0xfb,0xee,0xd7,0x6d,0xdd,0x00,0x07,0xb8,0x21,
 0xb0,0x00,0xe3,0x5c,0x13,0x07,0x08,0xf0,0x80,0x23,0x5e,0x06,0xfc,0xdc,0x21,
 0x3e,0xd0,0x80,0xaf,0xae,0xae,0xff,0xff,0xaa,0xfe,0xde,0xdf,0xf7,0xfd,0x55,
 0xbf,0x9d,0x0e,0xdd,0xf1,0xb2,0xbd,0x00,0x00,0x00,0xea,0x9e,0x71,0x00,0x1c,
 0xf5,0xfa,0x2b,0xfd,0xb7,0xbf,0xcf,0xf5,0xad,0xde,0x7f,0x6b,0x7f,0xbe,0x40,
 0x0f,0xb8,0x07,0xf0,0x00,0x37,0x56,0x04,0x47,0x0e,0x71,0x80,0x03,0x1e,0x86,
 0x38,0xec,0x01,0x7c,0xe0,0x80,0xb7,0xfa,0xcd,0xdf,0xdd,0x75,0xb7,0x55,0xf7,
 0xbd,0xff,0xd5,0xbf,0x2f,0x71,0x00,0x1c,0xf9,0xb9,0x00,0x00,0x40,0x7a,0x3f,
 0xe5,0x01,0x2f,0xda,0xdb,0x55,0x5f,0xef,0xed,0xfb,0xbe,0x6d,0xeb,0xaa,0xe3,
 0xfb,0x7a,0x01,0x8f,0x18,0x0f,0xf0,0x00,0x0f,0xde,0x01,0x07,0x1c,0x70,0xc0,
 0x01,0x0f,0x06,0x3c,0xcc,0x03,0x38,0xc4,0x04,0xaf,0xad,0xaa,0x97,0xfb,0xcd,
 0xdb,0xff,0x3a,0xd7,0xfd,0xba,0xfd,0x7f,0xf5,0x21,0xaf,0x7c,0xb7,0x00,0x00,
 0x00,0x48,0xfb,0x92,0xff,0xa3,0xfd,0xf6,0xe7,0xfe,0xd6,0x77,0xdf,0xf7,0xa7,
 0x7e,0xf3,0x74,0x77,0xaf,0x00,0x07,0x1e,0x1b,0xf0,0x20,0x03,0xae,0x00,0x03,
 0x1e,0x30,0xe0,0x00,0x02,0x02,0x08,0x84,0x01,0x18,0xc0,0x00,0x6f,0xbe,0x4d,
 0x1c,0xfb,0xba,0xbe,0x55,0xef,0x7b,0xbb,0xad,0xdb,0xad,0x04,0xef,0x25,0xfe,
 0xbb,0x20,0x00,0x00,0xfa,0xff,0x84,0x7c,0x80,0xee,0x7b,0x37,0xfb,0xbf,0xfb,
 0xeb,0x6d,0x5b,0xfd,0xf1,0x6a,0x5d,0x7d,0x06,0x07,0x0e,0x2c,0x30,0x08,0x00,
 0x1e,0x00,0x41,0x7f,0x20,0x38,0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x01,0x83,
 0xd8,0xfd,0xae,0xa5,0xbd,0x5d,0xef,0xef,0xef,0xfe,0x7e,0x5a,0xef,0xbb,0x28,
 0xd6,0x12,0xf7,0x3d,0x00,0x00,0x00,0x9a,0xb5,0x33,0x02,0x2a,0xdb,0xf6,0xd5,
 0x6a,0xdd,0xde,0xdf,0xd7,0xf5,0xba,0x2d,0x60,0xb4,0xde,0xfd,0xfa,0xff,0xdf,
 0xff,0xff,0xff,0xf7,0xff,0xff,0xdf,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0x5f,0x5a,0x2a,0x3b,0xf7,0xbe,0xaf,0x5b,0xf7,0xeb,0x73,0xfd,
 0x5e,0xcf,0x03,0x20,0xc9,0xbd,0xbb,0x08,0x00,0x00,0x7a,0xf7,0x62,0x01,0x88,
 0x75,0xef,0x73,0xfd,0xdb,0xbf,0xef,0xef,0x5b,0x7d,0xcb,0xe5,0x75,0xbf,0xfe,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x75,0x57,0xac,0x75,0xba,0x7c,0xaf,0xe7,
 0xfb,0xae,0xad,0xd5,0xbf,0x07,0x50,0x60,0x6f,0xb5,0x00,0x00,0x00,0xba,0x7d,
 0x1f,0xfe,0x71,0xb7,0xdf,0xdc,0xb6,0x7d,0xcf,0xbb,0xfb,0xf2,0xd7,0x51,0x51,
 0x8f,0x77,0xfb,0xff,0xff,0x7f,0xff,0xff,0xff,0xdf,0xff,0xff,0x6f,0xff,0xaf,
 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3f,0xdd,0x1e,0xc7,0xaf,0x7d,
 0xa7,0xff,0xdf,0xbf,0xdb,0xfa,0xfe,0xfb,0xff,0xa0,0xfe,0xef,0x3f,0x00,0x00,
 0x40,0x72,0xdf,0xff,0x00,0xce,0xdf,0xb7,0x7b,0xef,0x77,0x7f,0xff,0xde,0xff,
 0xff,0xff,0xff,0xfb,0x5d,0xea,0xff,0xe5,0xef,0xfe,0xff,0xff,0x37,0xff,0xff,
 0xdb,0xee,0x7b,0xff,0xff,0xff,0xdd,0xf7,0xff,0x7b,0xab,0xaa,0x2a,0x85,0x54,
 0x55,0x54,0x52,0x52,0x51,0x04,0x84,0x14,0x02,0x08,0x04,0x00,0x12,0x09,0x00,
 0x80,0x00,0x00,0x10,0xf8,0xff,0xff,0xd7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xbf,0xff,0xde,0x56,0xad,0xaa,0x56,0x53,0x15,0x04,0x0a,0x11,0x01,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,
 0x00,0x00,0x20,0x80,0x24,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x22,0x22,0x91,0xac,0xea,0x6a,0x7b,0xed,
 0xbe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfb,0xff,0xff,0xff,0xff,0xb7,
 0xde,0xff,0xf7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
 0xff,0xff,0xff,0xff,0x20,0x04,0x01,0x00,0x00,0x00,0x4a,0xca,0xaa,0xbe,0xdd,
 0x76,0xff,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xef,0xfd,0x6d,0x6d,0xab,0xaa,
 0x9a,0x4a,0x81,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x40,0x02,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x01,0x00,0x20,0x80,0x00,0x00,0x00,
 0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x01,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x44,0x10,0xa4,0x08,0x80,0x80,0x00,0x08,
 0x80,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x02,0x21,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,
 0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x00,0x00,
 0x20,0x00,0x00,0x10,0x10,0x00,0x80,0x40,0x00,0x80,0x00,0x00,0x00,0x00,0x00,
 0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x08,0x00,0x00,0x42,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x10,
 0x41,0x00,0x02,0x04,0x00,0x10,0x00,0x00,0x08,0x00,0x00,0x40,0x04,0x00,0x80,
 0x00,0x00,0x20,0x00,0x10,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x22,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x04,0x02,
 0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x10,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x02,0x10,0x02,0x80,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x10,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x22,0x02,0x00,0x00,0x01,0x00,
 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x84,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x10,0x00,0x00,0x00,0x20,0x04,0x00,
 0x08,0x00,0x04,0x80,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x02,0x00,
 0x00,0x00,0x40,0x24,0x84,0x20,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x80,0x00,0x80,0x00,0x00,0x00,0x02,0x00,0x01,0x20,0x10,0x84,
 0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x08,0x20,0x00,0x01,0x00,0x00,0x00,
 0x00,0x00,0x00,0x02,0x80,0x00,0x00,0x00,0x20,0x00,0x00,0x01,0x00,0x00,0x01,
 0x00,0x00,0x00,0x24,0x02,0x01,0x00,0x00,0x00,0x00,0x20,0x00,0x14,0x88,0x10,
 0x00,0x00,0x84,0x00,0x00,0x00,0x04,0x10,0x00,0x40,0x00,0x40,0x00,0x42,0x00,
 0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x21,0x00,0x08,0x04,0x01,0x08,0x00,0x48,
 0x00,0x00,0x04,0x08,0x00,0x80,0x00,0x10,0x00,0x20,0x00,0x08,0x00,0x40,0x00,
 0x00,0x00,0x00,0x08,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
Added tests/tko/rain.gif.

cannot compute difference between binary files

Added tests/tko/sample.gif.

cannot compute difference between binary files

Added tests/tko/stopsign.gif.

cannot compute difference between binary files

Added tests/tko/test.JPG.

cannot compute difference between binary files

Added tests/tko/tkoFrame.test.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# This file is a Tcl script to test out the "frame" and "toplevel"
# commands of Tko. It is organized in the standard fashion for Tcl
# tests.
#
# Copyright (c) 1994 The Regents of the University of California.
# Copyright (c) 1994-1996 Sun Microsystems, Inc.
# Copyright (c) 1998-1999 by Scriptics Corporation.
# All rights reserved.

package require tcltest
namespace import ::tcltest::*
namespace eval ::TEST {

proc ::TEST::deleteWindows {} {
    destroy {*}[winfo children .]
}

# ::TEST::eatColors --
# Creates a toplevel window and allocates enough colors in it to
# use up all the slots in the colormap.
#
# Arguments:
# w -		Name of toplevel window to create.

proc ::TEST::eatColors {w} {
    catch {destroy $w}
    ::tko::toplevel $w
    wm geom $w +0+0
    canvas $w.c -width 400 -height 200 -bd 0
    pack $w.c
    for {set y 0} {$y < 8} {incr y} {
	for {set x 0} {$x < 40} {incr x} {
	    set color [format #%02x%02x%02x [expr $x*6] [expr $y*30] 0]
	    $w.c create rectangle [expr 10*$x] [expr 20*$y] \
		    [expr 10*$x + 10] [expr 20*$y + 20] -outline {} \
		    -fill $color
	}
    }
    update
}

# ::TEST::colorsFree --
#
# Returns 1 if there appear to be free colormap entries in a window,
# 0 otherwise.
#
# Arguments:
# w -			Name of window in which to check.
# red, green, blue -	Intensities to use in a trial color allocation
#			to see if there are colormap entries free.

proc ::TEST::colorsFree {w {red 31} {green 245} {blue 192}} {
    set vals [winfo rgb $w [format #%02x%02x%02x $red $green $blue]]
    expr ([lindex $vals 0]/256 == $red) && ([lindex $vals 1]/256 == $green) \
	    && ([lindex $vals 2]/256 == $blue)
}

#
# Test ::tko::frame configuration options
#
test frame-1.1 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -class NewFrame
    .f configure -class
} -cleanup {
    deleteWindows
} -result {-class class Class TkoFrame NewFrame}

test frame-1.2 {frame configuration options} -setup {
    deleteWindows
} -body {
    ::tko::frame .f -class NewFrame
    .f configure -class Different
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-class" is readonly}

test frame-1.3 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -colormap new
    .f configure -colormap
} -cleanup {
    deleteWindows
} -result {-colormap colormap Colormap {} new}

test frame-1.4 {frame configuration options} -setup {
    deleteWindows
} -body {
    ::tko::frame .f -colormap new
    .f configure -colormap .
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-colormap" is readonly}

test frame-1.5 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -visual default
    .f configure -visual
} -cleanup {
    deleteWindows
} -result {-visual visual Visual {} default}

test frame-1.6 {frame configuration options} -setup {
    deleteWindows
} -body {
    ::tko::frame .f -visual default
    .f configure -visual best
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-visual" is readonly}

test frame-1.7 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -screen bogus
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {unknown options: -screen bogus}

test frame-1.8 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -container true
} -cleanup {
    deleteWindows
} -result {.f}

test frame-1.9 {frame configuration options} -setup {
    deleteWindows
} -body {
    ::tko::frame .f -container true
    .f configure -container
} -cleanup {
    deleteWindows
} -result {-container container Container 0 1}

test frame-1.10 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -container bogus
} -cleanup {
    deleteWindows
} -returnCodes error -result {expected boolean value but got "bogus"}

test frame-1.11 {frame configuration options} -setup {
	deleteWindows
} -body {
    ::tko::frame .f
    .f configure -container 1
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-container" is readonly}

test frame-1.12 {frame configuration options} -setup {
	deleteWindows
} -body {
    # Make sure all options can be set to the default value
    ::tko::frame .f
    set opts {}
    foreach opt [.f configure] {
        if {[llength $opt] == 5} {
            lappend opts [lindex $opt 0] [lindex $opt 4]
        }
    }
    eval ::tko::frame .g $opts
    destroy .f .g
} -cleanup {
    deleteWindows
} -result {}

destroy .f
::tko::frame .f
test frame-1.13 {frame configuration options} -body {
    .f configure -background #ff0000
    lindex [.f configure -background] 4
} -cleanup {
    .f configure -background [lindex [.f configure -background] 3]
} -result {#ff0000}

test frame-1.14 {frame configuration options} -body {
    .f configure -background non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-1.15 {frame configuration options} -body {
    .f configure -bd 4
    lindex [.f configure -bd] 4
} -cleanup {
    .f configure -bd [lindex [.f configure -bd] 3]
} -result {4}

test frame-1.16 {frame configuration options} -body {
    .f configure -bd badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-1.17 {frame configuration options} -body {
    .f configure -bg #00ff00
    lindex [.f configure -bg] 4
} -cleanup {
    .f configure -bg [lindex [.f configure -bg] 3]
} -result {#00ff00}

test frame-1.18 {frame configuration options} -body {
    .f configure -bg non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-1.19 {frame configuration options} -body {
    .f configure -borderwidth 1.3
    lindex [.f configure -borderwidth] 4
} -cleanup {
    .f configure -borderwidth [lindex [.f configure -borderwidth] 3]
} -result {1}

test frame-1.20 {frame configuration options} -body {
    .f configure -borderwidth badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-1.21 {frame configuration options} -body {
    .f configure -cursor arrow
    lindex [.f configure -cursor] 4
} -cleanup {
    .f configure -cursor [lindex [.f configure -cursor] 3]
} -result {arrow}

test frame-1.22 {frame configuration options} -body {
    .f configure -cursor badValue
} -returnCodes error -match glob -result {*: bad cursor spec "badValue"}

test frame-1.23 {frame configuration options} -body {
    .f configure -height 100
    lindex [.f configure -height] 4
} -cleanup {
    .f configure -height [lindex [.f configure -height] 3]
} -result {100}

test frame-1.24 {frame configuration options} -body {
    .f configure -height not_a_number
} -returnCodes error -match glob -result {*: bad screen distance "not_a_number"}

test frame-1.25 {frame configuration options} -body {
    .f configure -highlightbackground #112233
    lindex [.f configure -highlightbackground] 4
} -cleanup {
    .f configure -highlightbackground [lindex [.f configure -highlightbackground] 3]
} -result {#112233}

test frame-1.26 {frame configuration options} -body {
    .f configure -highlightbackground ugly
} -returnCodes error -match glob -result {*: unknown color name "ugly"}

test frame-1.27 {frame configuration options} -body {
    .f configure -highlightcolor #123456
    lindex [.f configure -highlightcolor] 4
} -cleanup {
    .f configure -highlightcolor [lindex [.f configure -highlightcolor] 3]
} -result {#123456}

test frame-1.28 {frame configuration options} -body {
    .f configure -highlightcolor non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-1.29 {frame configuration options} -body {
    .f configure -highlightthickness 6
    lindex [.f configure -highlightthickness] 4
} -cleanup {
    .f configure -highlightthickness [lindex [.f configure -highlightthickness] 3]
} -result {6}

test frame-1.30 {frame configuration options} -body {
    .f configure -highlightthickness badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-1.31 {frame configuration options} -body {
    .f configure -padx 3
    lindex [.f configure -padx] 4
} -cleanup {
    .f configure -padx [lindex [.f configure -padx] 3]
} -result {3}

test frame-1.32 {frame configuration options} -body {
    .f configure -padx badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-1.33 {frame configuration options} -body {
    .f configure -pady 4
    lindex [.f configure -pady] 4
} -cleanup {
    .f configure -pady [lindex [.f configure -pady] 3]
} -result {4}

test frame-1.34 {frame configuration options} -body {
    .f configure -pady badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-1.35 {frame configuration options} -body {
    .f configure -relief ridge
    lindex [.f configure -relief] 4
} -cleanup {
    .f configure -relief [lindex [.f configure -relief] 3]
} -result {ridge}

test frame-1.36 {frame configuration options} -body {
    .f configure -relief badValue
} -returnCodes error -match glob -result {*: bad relief "badValue": must be flat, groove, raised, ridge, solid, or sunken}

test frame-1.37 {frame configuration options} -body {
    .f configure -takefocus {any string}
    lindex [.f configure -takefocus] 4
} -cleanup {
    .f configure -takefocus [lindex [.f configure -takefocus] 3]
} -result {any string}

test frame-1.38 {frame configuration options} -body {
    .f configure -width 32
    lindex [.f configure -width] 4
} -cleanup {
    .f configure -width [lindex [.f configure -width] 3]
} -result {32}

test frame-1.39 {frame configuration options} -body {
    .f configure -width badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}
destroy .f

#
# Test ::tko::toplevel configuration options
#

test frame-2.1 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -class NewClass
    wm geometry .t +0+0
    .t configure -class
} -cleanup {
    deleteWindows
} -result {-class class Class TkoToplevel NewClass}

test frame-2.2 {toplevel configuration options} -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -class NewClass
    wm geometry .t +0+0
    .t configure -class Another
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-class" is readonly}

test frame-2.3 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -colormap new
    wm geometry .t +0+0
    .t configure -colormap
} -cleanup {
    deleteWindows
} -result {-colormap colormap Colormap {} new}

test frame-2.4 {toplevel configuration options} -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -colormap new
    wm geometry .t +0+0
    .t configure -colormap .
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-colormap" is readonly}

test frame-2.5 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100
    wm geometry .t +0+0
    .t configure -container 1
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-container" is readonly}

test frame-2.6 {toplevel configuration options} -setup {
    deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100
    wm geometry .t +0+0
    catch {.t configure -container 1}
    .t configure -container
} -cleanup {
    deleteWindows
} -result {-container container Container 0 0}

test frame-2.7 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -colormap bogus
} -cleanup {
    deleteWindows
} -returnCodes error -result {bad window path name "bogus"}

test frame-2.8 {toplevel configuration options} -constraints {
    win
} -setup {
	deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100 -use 0x44022
#    wm geometry .t +0+0
#    .t configure -use 0x44022
} -cleanup {
    deleteWindows
} -returnCodes error -result {window "0x44022" doesn't exist}

test frame-2.9 {toplevel configuration options} -constraints {
    win
} -setup {
    deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100
    wm geometry .t +0+0
    catch {.t configure -use 0x44022}
    .t configure -use
} -cleanup {
    deleteWindows
} -result {-use use Use {} {}}

test frame-2.10 {toplevel configuration options} -constraints {
    nonwin
} -setup {
    deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100
    wm geometry .t +0+0
    .t configure -use 0x44022
} -cleanup {
    deleteWindows
} -returnCodes error -result {can't modify -use option after widget is created}

test frame-2.11 {toplevel configuration options} -constraints {
    nonwin
} -setup {
	deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100
    wm geometry .t +0+0
    catch {.t configure -use 0x44022}
    .t configure -use
} -cleanup {
    deleteWindows
} -result {-use use Use {} {}}

test frame-2.12 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100 -visual default
    wm geometry .t +0+0
    .t configure -visual
} -cleanup {
    deleteWindows
} -result {-visual visual Visual {} default}

test frame-2.13 {toplevel configuration options} -setup {
    deleteWindows
} -body {
    catch {destroy .t}
    ::tko::toplevel .t -width 200 -height 100 -visual default
    wm geometry .t +0+0
    .t configure -visual best
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-visual" is readonly}

test frame-2.14 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -visual who_knows?
} -cleanup {
    deleteWindows
} -returnCodes error -result {unknown or ambiguous visual name "who_knows?": class must be best, directcolor, grayscale, greyscale, pseudocolor, staticcolor, staticgray, staticgrey, truecolor, or default}

test frame-2.15 {toplevel configuration options} -constraints haveDISPLAY -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -screen $env(DISPLAY)
    wm geometry .t +0+0
    string compare [.t configure -screen] "-screen screen Screen {} $env(DISPLAY)"
} -cleanup {
    deleteWindows
} -result {0}

test frame-2.16 {toplevel configuration options} -constraints haveDISPLAY -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -screen $env(DISPLAY)
    wm geometry .t +0+0
    .t configure -screen another
} -cleanup {
    deleteWindows
} -returnCodes error -result {can't modify -screen option after widget is created}

test frame-2.17 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 200 -height 100 -screen bogus
} -cleanup {
    deleteWindows
} -returnCodes error -result {couldn't connect to display "bogus"}


test frame-2.18 {toplevel configuration options} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -container 1 -width 300 -height 120
    wm geometry .t +0+0
    ::tko::toplevel .x -container 1 -use [winfo id .t]
} -cleanup {
    deleteWindows
} -returnCodes error -result {windows cannot have both the -use and the -container option set}

test frame-2.19 {toplevel configuration options} -setup {
	deleteWindows
    set opts {}
} -body {
    # Make sure all options can be set to the default value
    ::tko::toplevel .f
    foreach opt [.f configure] {
        if {[llength $opt] == 5} {
            lappend opts [lindex $opt 0] [lindex $opt 4]
        }
    }
    eval ::tko::toplevel .g $opts
    destroy .f .g
} -cleanup {
    deleteWindows
} -result {}

destroy .t
::tko::toplevel .t -width 300 -height 150
wm geometry .t +0+0
update
test frame-2.20 {toplevel configuration options} -body {
    .t configure -background #ff0000
    lindex [.t configure -background] 4
} -result {#ff0000}

test frame-2.21 {toplevel configuration options} -body {
    .t configure -background non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-2.22 {toplevel configuration options} -body {
    .t configure -bd 4
    lindex [.t configure -bd] 4
} -result {4}

test frame-2.23 {toplevel configuration options} -body {
    .t configure -bd badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-2.24 {toplevel configuration options} -body {
    .t configure -bg #00ff00
    lindex [.t configure -bg] 4
} -result {#00ff00}

test frame-2.25 {toplevel configuration options} -body {
    .t configure -bg non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-2.26 {toplevel configuration options} -body {
    .t configure -borderwidth 1.3
    lindex [.t configure -borderwidth] 4
} -result {1}

test frame-2.27 {toplevel configuration options} -body {
    .t configure -borderwidth badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-2.28 {toplevel configuration options} -body {
    .t configure -cursor arrow
    lindex [.t configure -cursor] 4
} -result {arrow}

test frame-2.29 {toplevel configuration options} -body {
    .t configure -cursor badValue
} -returnCodes error -match glob -result {*: bad cursor spec "badValue"}

test frame-2.30 {toplevel configuration options} -body {
    .t configure -height 100
    lindex [.t configure -height] 4
} -result {100}

test frame-2.31 {toplevel configuration options} -body {
    .t configure -height not_a_number
} -returnCodes error -match glob -result {*: bad screen distance "not_a_number"}

test frame-2.32 {toplevel configuration options} -body {
    .t configure -highlightcolor #123456
    lindex [.t configure -highlightcolor] 4
} -result {#123456}

test frame-2.33 {toplevel configuration options} -body {
    .t configure -highlightcolor non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-2.34 {toplevel configuration options} -body {
    .t configure -highlightthickness 3
    lindex [.t configure -highlightthickness] 4
} -result {3}

test frame-2.35 {toplevel configuration options} -body {
    .t configure -highlightthickness badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-2.36 {toplevel configuration options} -body {
    .t configure -padx 3
    lindex [.t configure -padx] 4
} -result {3}

test frame-2.37 {toplevel configuration options} -body {
    .t configure -padx badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-2.38 {toplevel configuration options} -body {
    .t configure -pady 4
    lindex [.t configure -pady] 4
} -result {4}

test frame-2.39 {toplevel configuration options} -body {
    .t configure -pady badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-2.40 {toplevel configuration options} -body {
    .t configure -relief ridge
    lindex [.t configure -relief] 4
} -result {ridge}

test frame-2.41 {toplevel configuration options} -body {
    .t configure -relief badValue
} -returnCodes error -match glob -result {*: bad relief "badValue": must be flat, groove, raised, ridge, solid, or sunken}

test frame-2.42 {toplevel configuration options} -body {
    .t configure -width 32
    lindex [.t configure -width] 4
} -result {32}

test frame-2.43 {toplevel configuration options} -body {
    .t configure -width badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}
destroy .t

#
# Test ::tko::labelframe configuration options
#
test frame-3.1 {TkCreateFrame procedure} -body {
    ::tko::frame
} -returnCodes error -result {wrong # args: should be "::tko::frame pathName ?-option value ...?"}

test frame-3.2 {TkCreateFrame procedure} -setup {
	deleteWindows
    ::tko::frame .f
} -body {
    .f configure -class
} -cleanup {
    deleteWindows
} -result {-class class Class TkoFrame TkoFrame}

test frame-3.3 {TkCreateFrame procedure} -setup {
	deleteWindows
    ::tko::toplevel .t
    wm geometry .t +0+0
} -body {
    .t configure -class
} -cleanup {
    deleteWindows
} -result {-class class Class TkoToplevel TkoToplevel}

test frame-3.4 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 350 -class NewClass -bg black -visual default -height 90
    wm geometry .t +0+0
    update
    list [lindex [.t configure -width] 4] \
	    [lindex [.t configure -background] 4] \
	    [lindex [.t configure -height] 4]
} -cleanup {
    deleteWindows
} -result {350 black 90}

# Be sure that the -class, -colormap, and -visual options are processed
# before configuring the widget.

test frame-3.5 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    option add *NewFrame.background #123456
    ::tko::frame .f -class NewFrame
    lindex [.f configure -background] 4
} -cleanup {
    deleteWindows
    option clear
} -result {#123456}

test frame-3.6 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    option add *NewFrame.background #123456
    ::tko::frame .f -class NewFrame
    lindex [.f configure -background] 4
} -cleanup {
    deleteWindows
    option clear
} -result {#123456}

test frame-3.7 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    option add *NewFrame.background #332211
    option add *f.class NewFrame
    ::tko::frame .f
    list [lindex [.f configure -class] 4] [lindex [.f configure -background] 4]
} -cleanup {
    deleteWindows
    option clear
} -result {NewFrame #332211}

test frame-3.8 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    option add *Silly.background #122334
    option add *f.Class Silly
    ::tko::frame .f
    list [lindex [.f configure -class] 4] [lindex [.f configure -background] 4]
} -cleanup {
    deleteWindows
    option clear
} -result {Silly #122334}

test frame-3.9 {TkCreateFrame procedure, -use option} -constraints {
    unix
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -container 1 -width 300 -height 120
    wm geometry .t +0+0
    ::tko::toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green
    tkwait visibility .x
    list [expr {[winfo rootx .x] - [winfo rootx .t]}] \
	    [expr {[winfo rooty .x] - [winfo rooty .t]}] \
	    [winfo width .t] [winfo height .t]
} -cleanup {
    deleteWindows
} -result {0 0 140 300}

test frame-3.10 {TkCreateFrame procedure, -use option} -constraints {
    unix
} -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -container 1 -width 300 -height 120
    wm geometry .t +0+0
    option add *x.use [winfo id .t]
    ::tko::toplevel .x -width 140 -height 300 -bg green
    tkwait visibility .x
    list [expr {[winfo rootx .x] - [winfo rootx .t]}] \
	    [expr {[winfo rooty .x] - [winfo rooty .t]}] \
	    [winfo width .t] [winfo height .t]
} -cleanup {
    destroy .t
    option clear
} -result {0 0 140 300}

# The tests below require specific display characteristics (i.e. that
# they are run on a pseudocolor display of depth 8).  Even so, they
# are non-portable: some machines don't seem to ever run out of
# colors.
if {[testConstraint defaultPseudocolor8]} {
    ::TEST::eatColors .t1
}
test frame-3.11 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 300 -height 200 -bg #475601
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {0}

test frame-3.12 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 300 -height 200 -bg #475601 -colormap new
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {1}

test frame-3.13 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    option add *t.class Toplevel2
    option add *Toplevel2.colormap new
    ::tko::toplevel .t -width 300 -height 200 -bg #475601
    wm geometry .t +0+0
    update
    option clear
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {1}

test frame-3.14 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    option add *t.class Toplevel3
    option add *Toplevel3.Colormap new
    ::tko::toplevel .t -width 300 -height 200 -bg #475601 -colormap new
    wm geometry .t +0+0
    update
    option clear
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {1}

test frame-3.15 {TkCreateFrame procedure, -use and -colormap} -constraints {
    defaultPseudocolor8 unix nonPortable
} -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -container 1 -width 300 -height 120
    wm geometry .t +0+0
    ::tko::toplevel .x -width 140 -height 300 -use [winfo id .t] -bg green -colormap new
    tkwait visibility .x
    list [::TEST::colorsFree .t] [::TEST::colorsFree .x]
} -cleanup {
    destroy .t
} -result {0 1}

test frame-3.16 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 300 -height 200 -bg #475601 -visual default
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {0}

test frame-3.17 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 nonPortable
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 300 -height 200 -bg #475601 -visual default \
	    -colormap new
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t
} -cleanup {
    deleteWindows
} -result {1}

test frame-3.18 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 haveGrayscale8 nonPortable
} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -visual {grayscale 8} -width 300 -height 200 -bg #434343
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t 131 131 131
} -cleanup {
    deleteWindows
} -result {1}

test frame-3.19 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 haveGrayscale8 nonPortable
} -setup {
	deleteWindows
} -body {
    option add *t.class T4
    option add *T4.visual {grayscale 8}
    ::tko::toplevel .t -width 300 -height 200 -bg #434343
    wm geometry .t +0+0
    update
    option clear
    list [::TEST::colorsFree .t 131 131 131] [lindex [.t configure -visual] 4]
} -cleanup {
    deleteWindows
} -result {1 {grayscale 8}}

test frame-3.20 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 haveGrayscale8 nonPortable
} -setup {
	deleteWindows
} -body {
    set x ok
    option add *t.class T5
    option add *T5.Visual {grayscale 8}
    ::tko::toplevel .t -width 300 -height 200 -bg #434343
    wm geometry .t +0+0
    update
    option clear
    list [::TEST::colorsFree .t 131 131 131] [lindex [.t configure -visual] 4]
} -cleanup {
    deleteWindows
} -result {1 {grayscale 8}}

test frame-3.21 {TkCreateFrame procedure} -constraints {
	defaultPseudocolor8 haveGrayscale8 nonPortable
} -setup {
	deleteWindows
} -body {
    set x ok
    ::tko::toplevel .t -visual {grayscale 8} -width 300 -height 200 -bg #434343
    wm geometry .t +0+0
    update
    ::TEST::colorsFree .t 131 131 131
} -cleanup {
    deleteWindows
} -result {1}
if {[testConstraint defaultPseudocolor8]} {
    destroy .t1
}

test frame-3.22 {TkCreateFrame procedure, default dimensions} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t
    wm geometry .t +0+0
    update
    set result "[winfo reqwidth .t] [winfo reqheight .t]"
    ::tko::frame .t.f -bg red
    pack .t.f
    update
    lappend result [winfo reqwidth .t.f] [winfo reqheight .t.f]
} -cleanup {
    deleteWindows
} -result {200 200 1 1}

test frame-3.23 {TkCreateFrame procedure} -setup {
    deleteWindows
} -body {
    ::tko::frame .f -gorp glob
} -returnCodes error -result {unknown options: -gorp glob}

test frame-3.24 {TkCreateFrame procedure} -setup {
    deleteWindows
} -body {
    ::tko::toplevel .t -width 300 -height 200 -colormap new -bogus option
    wm geometry .t +0+0
} -returnCodes error -result {unknown options: -bogus option}


test frame-4.1 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    catch {::tko::frame .f -gorp glob}
    winfo exists .f
} -result 0

test frame-4.2 {TkCreateFrame procedure} -setup {
	deleteWindows
} -body {
    list [::tko::frame .f -width 200 -height 100] [winfo exists .f]
} -cleanup {
    deleteWindows
} -result {.f 1}


::tko::frame .f -highlightcolor black

test frame-5.1 {FrameWidgetCommand procedure} -body {
    .f
} -returnCodes error -result {wrong # args: should be ".f method ?arg ...?"}

test frame-5.2 {FrameWidgetCommand procedure, cget option} -body {
    .f cget
} -returnCodes error -result {wrong # args: should be ".f cget option"}

test frame-5.3 {FrameWidgetCommand procedure, cget option} -body {
    .f cget a b
} -returnCodes error -result {wrong # args: should be ".f cget option"}

test frame-5.4 {FrameWidgetCommand procedure, cget option} -body {
    .f cget -gorp
} -returnCodes error -result {unknown option "-gorp"}

test frame-5.5 {FrameWidgetCommand procedure, cget option} -body {
    .f cget -highlightcolor
} -result {black}

test frame-5.6 {FrameWidgetCommand procedure, cget option} -body {
    .f cget -screen
} -returnCodes error -result {unknown option "-screen"}

test frame-5.7 {FrameWidgetCommand procedure, cget option} -setup {
    destroy .t
} -body {
    ::tko::toplevel .t
    .t cget -screen
} -cleanup {
    destroy .t
} -returnCodes ok -match glob -result *

test frame-5.8 {FrameWidgetCommand procedure, configure option} -body {
    llength [.f configure]
} -result {18}

test frame-5.9 {FrameWidgetCommand procedure, configure option} -body {
    .f configure -gorp
} -returnCodes error -result {unknown option "-gorp"}

test frame-5.10 {FrameWidgetCommand procedure, configure option} -body {
    .f configure -gorp bogus
} -returnCodes error -result {unknown option "-gorp"}

test frame-5.11 {FrameWidgetCommand procedure, configure option} -body {
    .f configure -width 200 -height
} -returnCodes error -result {wrong # args: should be ".f configure ?-option value ..?"}

test frame-5.12 {FrameWidgetCommand procedure} -body {
    .f swizzle
} -returnCodes error -result {unknown method "swizzle": must be cget or configure}

test frame-5.13 {FrameWidgetCommand procedure, configure option} -body {
    llength [. configure]
} -result {21}
destroy .f

test frame-6.1 {ConfigureFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -width 150
    list [winfo reqwidth .f] [winfo reqheight .f]
} -cleanup {
    deleteWindows
} -result {150 1}

test frame-6.2 {ConfigureFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::frame .f -height 97
    list [winfo reqwidth .f] [winfo reqheight .f]
} -cleanup {
    deleteWindows
} -result {1 97}

test frame-6.3 {ConfigureFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::frame .f
    set result {}
    lappend result [winfo reqwidth .f] [winfo reqheight .f]
    .f configure -width 100 -height 180
    lappend result [winfo reqwidth .f] [winfo reqheight .f]
    .f configure -width 0 -height 0
    lappend result [winfo reqwidth .f] [winfo reqheight .f]
} -cleanup {
    deleteWindows
} -result {1 1 100 180 100 180}

test frame-7.1 {FrameEventProc procedure} -setup {
	deleteWindows
} -body {
    ::tko::frame .frame2
    set result [info commands .frame2]
    destroy .frame2
    lappend result [info commands .frame2]
} -result {.frame2 {}}

test frame-7.2 {FrameEventProc procedure} -setup {
	deleteWindows
    set x {}
} -body {
    frame .f1 -bg #543210
    rename .f1 .f2
    lappend x [winfo children .]
    lappend x [.f2 cget -bg]
    destroy .f1
    lappend x [info command .f*] [winfo children .]
} -cleanup {
    deleteWindows
} -result {.f1 #543210 {} {}}

test frame-8.1 {FrameCmdDeletedProc procedure} -setup {
	deleteWindows
} -body {
    ::tko::frame .f1
    rename .f1 {}
    list [info command .f*] [winfo children .]
} -cleanup {
    deleteWindows
} -result {{} {}}

test frame-8.2 {FrameCmdDeletedProc procedure} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .f1 -menu .m
    wm geometry .f1 +0+0
    update
    rename .f1 {}
    update
    list [info command .f*] [winfo children .]
} -cleanup {
    deleteWindows
} -result {{} {}}
#
# This one fails with the dash-patch!!!! Still don't know why  :-(
#
#test frame-8.3 {FrameCmdDeletedProc procedure} -setup {
#    eval destroy [winfo children .]
#    deleteWindows
#} -body {
#    ::tko::toplevel .f1 -menu .m
#    wm geometry .f1 +0+0
#    menu .m
#    update
#    rename .f1 {}
#    update
#    list [info command .f*] [winfo children .]
#} -cleanup {
#    eval destroy [winfo children .]
#    deleteWindows
#} -result {{} .m}

test frame-9.1 {MapFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 100 -height 400
    wm geometry .t +0+0
    set result [winfo ismapped .t]
    update idletasks
    lappend result [winfo ismapped .t]
} -cleanup {
    deleteWindows
} -result {0 1}

test frame-9.2 {MapFrame procedure} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t -width 100 -height 400
    wm geometry .t +0+0
    destroy .t
    update
    winfo exists .t
} -result {0}

test frame-9.3 {MapFrame procedure, window deleted while mapping} -setup {
	deleteWindows
} -body {
    ::tko::toplevel .t2 -width 200 -height 200
    wm geometry .t2 +0+0
    tkwait visibility .t2
    ::tko::toplevel .t -width 100 -height 400
    wm geometry .t +0+0
    ::tko::frame .t2.f -width 50 -height 50
    bind .t2.f <Configure> {destroy .t}
    pack .t2.f -side top
    update idletasks
    winfo exists .t
} -cleanup {
    deleteWindows
} -result {0}


test frame-10.1 {frame widget vs hidden commands} -setup {
	deleteWindows
} -body {
    set l [interp hidden]
    ::tko::frame .t
    interp hide {} .t
    destroy .t
    set res1 [list [winfo children .] [interp hidden]]
    set res2 [list {} $l]
    expr {$res1 eq $res2}
} -result 1


test frame-11.1 {TkInstallFrameMenu} -setup {
	deleteWindows
} -body {
    menu .m1
    .m1 add cascade -menu .m1.system
    menu .m1.system -tearoff 0
    .m1.system add command -label foo
    ::tko::toplevel .t -menu .m1
} -cleanup {
    deleteWindows
} -result {.t}

test frame-11.2 {TkInstallFrameMenu - frame renamed} -setup {
	deleteWindows
} -body {
    catch {rename foo {}}
    menu .m1
    .m1 add cascade -menu .m1.system
    menu .m1.system -tearoff 0
    .m1.system add command -label foo
    ::tko::toplevel .t
    rename .t foo
} -cleanup {
    deleteWindows
} -result {}


test frame-12.1 {FrameWorldChanged procedure} -setup {
	deleteWindows
} -body {
    # Test -bd -padx and -pady
    ::tko::frame .f -borderwidth 2 -padx 3 -pady 4
    place .f -x 0 -y 0 -width 40 -height 40
    pack [::tko::frame .f.f] -fill both -expand 1
    update
    list [winfo x .f.f] [winfo y .f.f] [winfo width .f.f] [winfo height .f.f]
} -cleanup {
    deleteWindows
} -result {5 6 30 28}

test frame-12.2 {FrameWorldChanged procedure} -setup {
	deleteWindows
} -body {
    # Test all -labelanchor positions
    set font {helvetica 12}
    ::tko::labelframe .f -highlightthickness 1 -bd 3 -padx 1 -pady 2 -font $font \
            -text "Mupp"
    set fh [expr {[font metrics $font -linespace] + 2 - 3}]
    set fw [expr {[font measure $font "Mupp"] + 2 - 3}]
    if {$fw < 0} {set fw 0}
    if {$fh < 0} {set fh 0}
    place .f -x 0 -y 0 -width 100 -height 100
    pack [::tko::frame .f.f] -fill both -expand 1

    set result {}
    foreach lp {nw n ne en e es se s sw ws w wn} {
        .f configure -labelanchor $lp
        update
        set expx 5
        set expy 6
        set expw 90
        set exph 88
        switch -glob $lp {
            n* {incr expy $fh ; incr exph -$fh}
            s* {incr exph -$fh}
            w* {incr expx $fw ; incr expw -$fw}
            e* {incr expw -$fw}
        }
        lappend result [expr {\
                [winfo x .f.f] == $expx && [winfo y .f.f] == $expy &&\
                [winfo width .f.f] == $expw && [winfo height .f.f] == $exph}]
    }
    return $result
} -cleanup {
    deleteWindows
} -result {1 1 1 1 1 1 1 1 1 1 1 1}

test frame-12.3 {FrameWorldChanged procedure} -setup {
	deleteWindows
} -body {
    # Check reaction on font change
    font create myfont -family courier -size 10
    ::tko::labelframe .f -font myfont -text Mupp
    place .f -x 0 -y 0 -width 40 -height 40
    pack [::tko::frame .f.f] -fill both -expand 1
    update
    set h1 [font metrics myfont -linespace]
    set y1 [winfo y .f.f]
    font configure myfont -size 20
    update
    set h2 [font metrics myfont -linespace]
    set y2 [winfo y .f.f]
    expr {($h2 - $h1) - ($y2 - $y1)}
} -cleanup {
    deleteWindows
    font delete myfont
} -result {0}


test frame-13.1 {labelframe configuration options} -setup {
	deleteWindows
} -body {
    ::tko::labelframe .f -class NewFrame
    .f configure -class
} -cleanup {
    deleteWindows
} -result {-class class Class TkoLabelframe NewFrame}

test frame-13.2 {labelframe configuration options} -setup {
    deleteWindows
} -body {
    ::tko::labelframe .f -class NewFrame
    .f configure -class Different
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {*: option "-class" is readonly}

test frame-13.3 {labelframe configuration options} -setup {
	deleteWindows
} -body {
    ::tko::labelframe .f -colormap new
} -cleanup {
    deleteWindows
} -result {.f}

test frame-13.4 {labelframe configuration options} -setup {
	deleteWindows
} -body {
    ::tko::labelframe .f -visual default
} -cleanup {
    deleteWindows
} -result {.f}

test frame-13.5 {labelframe configuration options} -setup {
	deleteWindows
} -body {
    ::tko::labelframe .f -screen bogus
} -cleanup {
    deleteWindows
} -returnCodes error -result {unknown options: -screen bogus}

test frame-13.6 {labelframe configuration options} -setup {
	deleteWindows
} -body {
    labelframe .f -container true
} -cleanup {
    deleteWindows
} -result {.f}

# Removed. Should be deprectaed in frame too.
#test frame-13.7 {labelframe configuration options} -setup {
#    deleteWindows
#} -body {
#    ::tko::labelframe .f -container true
#    .f configure -container
#} -cleanup {
#    deleteWindows
#} -result {-container container Container 0 1}
#
#test frame-13.8 {labelframe configuration options} -setup {
#	deleteWindows
#} -body {
#     ::tko::labelframe .f -container bogus
#} -cleanup {
#    deleteWindows
#} -returnCodes error -result {expected boolean value but got "bogus"}
#
#test frame-13.9 {labelframe configuration options} -setup {
#	deleteWindows
#} -body {
#    ::tko::labelframe .f
#    .f configure -container 1
#} -cleanup {
#    deleteWindows
#} -returnCodes error -result {can't modify -container option after widget is created}

destroy .f
::tko::labelframe .f
test frame-13.10 {labelframe configuration options} -body {
    .f configure -background #ff0000
    lindex [.f configure -background] 4
} -cleanup {
    .f configure -background [lindex [.f configure -background] 3]
} -result {#ff0000}

test frame-13.11 {labelframe configuration options} -body {
        .f configure -background non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-13.12 {labelframe configuration options} -body {
    .f configure -bd 4
    lindex [.f configure -bd] 4
} -cleanup {
    .f configure -bd [lindex [.f configure -bd] 3]
} -result {4}

test frame-13.13 {labelframe configuration options} -body {
        .f configure -bd badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-13.14 {labelframe configuration options} -body {
    .f configure -bg #00ff00
    lindex [.f configure -bg] 4
} -cleanup {
    .f configure -bg [lindex [.f configure -bg] 3]
} -result {#00ff00}

test frame-13.15 {labelframe configuration options} -body {
        .f configure -bg non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-13.16 {labelframe configuration options} -body {
    .f configure -borderwidth 1.3
    lindex [.f configure -borderwidth] 4
} -cleanup {
    .f configure -borderwidth [lindex [.f configure -borderwidth] 3]
} -result {1}

test frame-13.17 {labelframe configuration options} -body {
        .f configure -borderwidth badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-13.18 {labelframe configuration options} -body {
    .f configure -cursor arrow
    lindex [.f configure -cursor] 4
} -cleanup {
    .f configure -cursor [lindex [.f configure -cursor] 3]
} -result {arrow}

test frame-13.19 {labelframe configuration options} -body {
        .f configure -cursor badValue
} -returnCodes error -match glob -result {*: bad cursor spec "badValue"}

test frame-13.20 {labelframe configuration options} -body {
    .f configure -fg #0000ff
    lindex [.f configure -fg] 4
} -cleanup {
    .f configure -fg [lindex [.f configure -fg] 3]
} -result {#0000ff}

test frame-13.21 {labelframe configuration options} -body {
        .f configure -fg non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-13.22 {labelframe configuration options} -body {
    .f configure -font {courier 8}
    lindex [.f configure -font] 4
} -cleanup {
    .f configure -font [lindex [.f configure -font] 3]
} -result {courier 8}

test frame-13.23 {labelframe configuration options} -body {
    .f configure -foreground #ff0000
    lindex [.f configure -foreground] 4
} -cleanup {
    .f configure -foreground [lindex [.f configure -foreground] 3]
} -result {#ff0000}

test frame-13.24 {labelframe configuration options} -body {
        .f configure -foreground non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-13.25 {labelframe configuration options} -body {
    .f configure -height 100
    lindex [.f configure -height] 4
} -cleanup {
    .f configure -height [lindex [.f configure -height] 3]
} -result {100}

test frame-13.26 {labelframe configuration options} -body {
        .f configure -height not_a_number
} -returnCodes error -match glob -result {*: bad screen distance "not_a_number"}

test frame-13.27 {labelframe configuration options} -body {
    .f configure -highlightbackground #112233
    lindex [.f configure -highlightbackground] 4
} -cleanup {
    .f configure -highlightbackground [lindex [.f configure -highlightbackground] 3]
} -result {#112233}

test frame-13.28 {labelframe configuration options} -body {
        .f configure -highlightbackground ugly
} -returnCodes error -match glob -result {*: unknown color name "ugly"}

test frame-13.29 {labelframe configuration options} -body {
    .f configure -highlightcolor #123456
    lindex [.f configure -highlightcolor] 4
} -cleanup {
    .f configure -highlightcolor [lindex [.f configure -highlightcolor] 3]
} -result {#123456}

test frame-13.30 {labelframe configuration options} -body {
        .f configure -highlightcolor non-existent
} -returnCodes error -match glob -result {*: unknown color name "non-existent"}

test frame-13.31 {labelframe configuration options} -body {
    .f configure -highlightthickness 6
    lindex [.f configure -highlightthickness] 4
} -cleanup {
    .f configure -highlightthickness [lindex [.f configure -highlightthickness] 3]
} -result {6}

test frame-13.32 {labelframe configuration options} -body {
        .f configure -highlightthickness badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-13.33 {labelframe configuration options} -body {
    .f configure -labelanchor se
    lindex [.f configure -labelanchor] 4
} -cleanup {
    .f configure -labelanchor [lindex [.f configure -labelanchor] 3]
} -result {se}

test frame-13.34 {labelframe configuration options} -body {
        .f configure -labelanchor badValue
} -returnCodes error -match glob -result {*: bad labelanchor "badValue": must be e, en, es, n, ne, nw, s, se, sw, w, wn, or ws}

test frame-13.35 {labelframe configuration options} -body {
    .f configure -padx 3
    lindex [.f configure -padx] 4
} -cleanup {
    .f configure -padx [lindex [.f configure -padx] 3]
} -result {3}

test frame-13.36 {labelframe configuration options} -body {
        .f configure -padx badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-13.37 {labelframe configuration options} -body {
    .f configure -pady 4
    lindex [.f configure -pady] 4
} -cleanup {
    .f configure -pady [lindex [.f configure -pady] 3]
} -result {4}

test frame-13.38 {labelframe configuration options} -body {
        .f configure -pady badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}

test frame-13.39 {labelframe configuration options} -body {
    .f configure -relief ridge
    lindex [.f configure -relief] 4
} -cleanup {
    .f configure -relief [lindex [.f configure -relief] 3]
} -result {ridge}

test frame-13.40 {labelframe configuration options} -body {
        .f configure -relief badValue
} -returnCodes error -match glob -result {*: bad relief "badValue": must be flat, groove, raised, ridge, solid, or sunken}

test frame-13.41 {labelframe configuration options} -body {
    .f configure -takefocus {any string}
    lindex [.f configure -takefocus] 4
} -cleanup {
    .f configure -takefocus [lindex [.f configure -takefocus] 3]
} -result {any string}

test frame-13.42 {labelframe configuration options} -body {
    .f configure -text {any string}
    lindex [.f configure -text] 4
} -cleanup {
    .f configure -text [lindex [.f configure -text] 3]
} -result {any string}

test frame-13.43 {labelframe configuration options} -body {
    .f configure -width 32
    lindex [.f configure -width] 4
} -cleanup {
    .f configure -width [lindex [.f configure -width] 3]
} -result {32}

test frame-13.44 {labelframe configuration options} -body {
        .f configure -width badValue
} -returnCodes error -match glob -result {*: bad screen distance "badValue"}
destroy .f

test frame-14.1 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Test that label is moved in stacking order
    label .l -text Mupp -font {helvetica 8}
    ::tko::labelframe .f -labelwidget .l
    pack .f
    ::tko::frame .f.f -width 50 -height 50
    pack .f.f
    update
    list [winfo children .] [winfo width .f] \
        [expr {[winfo height .f] - [winfo height .l]}]
} -cleanup {
    deleteWindows
} -result {{.f .l} 54 52}

test frame-14.2 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Test the labelframe's reaction if the label is destroyed
    label .l -text Aratherlonglabel
    ::tko::labelframe .f -labelwidget .l
    pack .f
    label .f.l -text Mupp
    pack .f.l
    update
    set res [list [.f cget -labelwidget]]
    lappend res [expr {[winfo width .f] - [winfo width .l]}]
    destroy .l
    lappend res [.f cget -labelwidget]
    update
    lappend res [expr {[winfo width .f] - [winfo width .f.l]}]
} -cleanup {
    deleteWindows
} -result {.l 12 {} 4}

test frame-14.3 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Test the labelframe's reaction if the label is stolen
    label .l -text Aratherlonglabel
    ::tko::labelframe .f -labelwidget .l
    pack .f
    label .f.l -text Mupp
    pack .f.l
    update
    set res [list [.f cget -labelwidget]]
    lappend res [expr {[winfo width .f] - [winfo width .l]}]
    pack .l
    lappend res [.f cget -labelwidget]
    update
    lappend res [expr {[winfo width .f] - [winfo width .f.l]}]
} -cleanup {
    deleteWindows
} -result {.l 12 {} 4}

test frame-14.4 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Test the label's reaction if the labelframe is destroyed
    label .l -text Mupp
    ::tko::labelframe .f -labelwidget .l
    pack .f
    update
    set res [list [winfo manager .l]]
    destroy .f
    lappend res [winfo manager .l]
} -cleanup {
    deleteWindows
} -result {labelframe {}}

test frame-14.5 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Test that the labelframe reacts on changes in label
    label .l -text Aratherlonglabel
    ::tko::labelframe .f -labelwidget .l
    pack .f
    label .f.l -text Mupp
    pack .f.l
    update
    set first [winfo width .f]
    set res [expr {[winfo width .f] - [winfo width .l]}]
    .l configure -text Shorter
    update
    lappend res [expr {[winfo width .f] - [winfo width .l]}]
    lappend res [expr {[winfo width .f] < $first}]
    .l configure -text Alotlongerthananytimebefore
    update
    lappend res [expr {[winfo width .f] - [winfo width .l]}]
    lappend res [expr {[winfo width .f] > $first}]
} -cleanup {
    deleteWindows
} -result {12 12 1 12 1}

test frame-14.6 {labelframe labelwidget option} -setup {
	deleteWindows
} -body {
    # Destroying a labelframe with a child label caused a crash
    # when not handling mapping of the label correctly.
    # This test does not test anything directly, it's just ment
    # to catch if the same mistake is made again.
    ::tko::labelframe .f
    pack .f
    label .f.l -text Mupp
    .f configure -labelwidget .f.l
    update
} -cleanup {
    deleteWindows
} -result {}

test frame-20.1 {configure optionadd wrong args} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    .f configure optionadd
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {wrong # args: *}

test frame-20.2 {configure optionadd wrong args} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    .f configure optionadd -option
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {wrong # args: *}

test frame-20.3 {configure optionadd wrong synonym} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    .f configure optionadd -option mmm
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {wrong synonym name for option*}

test frame-20.3 {configure optionadd missing command} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    .f configure optionadd -option option Option value
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {unknown method "-option": must be*}

test frame-20.4 {configure optionadd} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {}
    .f configure optionadd -option option Option value
    .f cget -option
} -cleanup {
    deleteWindows
} -result {value}

test frame-20.5 {configure optionadd modify} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {my variable tko; set tko(-option) new}
    .f configure optionadd -option option Option value
    .f cget -option
} -cleanup {
    deleteWindows
} -result {new}

test frame-20.6 {configure optiondel} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    .f configure optiondel -notexist
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {unknown option "-notexist"}

test frame-20.7 {configure optionaddand optiondel} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {}
    set ret [llength [.f configure]]
    .f configure optionadd -option option Option value
    lappend ret [llength [.f configure]]
    .f cget -option
    .f configure optiondel -option
    lappend ret [llength [.f configure]]
} -cleanup {
    deleteWindows
} -result {18 19 18}

test frame-20.8 {configure optionadd readonly} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {}
    set ret [llength [.f configure]]
    .f configure optionadd -option option Option value 1
    if {[.f cget -option] ne {value}} {error "option not set"}
    .f configure -option test
} -cleanup {
    deleteWindows
} -returnCodes error -match glob -result {* is readonly}

test frame-20.9 {configure optionvar get} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {}
    .f configure optionadd -option option Option value
    set [.f configure optionvar](-option)
} -cleanup {
    deleteWindows
} -result {value}

test frame-20.10 {configure optionvar set} -setup {
    deleteWindows
} -body {
    ::tko::frame .f
    ::oo::objdefine .f method -option {} {}
    .f configure optionadd -option option Option value
    set [.f configure optionvar](-option) other
    .f cget -option
} -cleanup {
    deleteWindows
} -result {other}

deleteWindows
rename ::TEST::eatColors {}
rename ::TEST::colorsFree {}

# cleanup
cleanupTests
}
catch {namespace delete ::TEST}

# vim: set ts=4 sw=4 sts=4 ff=unix et :
Added tests/tko/tkoGraph.test.

more than 10,000 changes

Added tests/tko/tkoGraph_vector.test.


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# vector.test --
#
package require tcltest
namespace import tcltest::*

namespace eval ::TEST {

#===============================================================================
# This part tests the append function of the vector rbc component.
# Append is an instance function of vector.
#

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector append command works correctly when given a list of 
# numbers.
# ------------------------------------------------------------------------------
test vector.append-1.1 {
	::graph::vector set: list of numbers
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0}
} -body {
	foo append {3.0 4.0} 
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector append command works correctly when given another vector.
# ------------------------------------------------------------------------------
test vector.append-1.2 {
	::graph::vector append: another vector
} -setup {
	::graph::vector create foo
	::graph::vector create goo
	foo set {1.0 2.0}
	goo set {3.0 4.0}
} -body {
	foo append goo
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector append command works correctly when given a list  
# containing characters.
# ------------------------------------------------------------------------------
test vector.append-1.3 {
	::graph::vector append: list with characters
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0}
} -body {
	if {[catch {foo append {3.0 a}}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector append command works correctly when given a non-existent 
# vector reference.
# ------------------------------------------------------------------------------
test vector.append-1.4 {
	::graph::vector append: non-existent vector
} -setup {
	::graph::vector create foo
} -body {
	if {[catch {foo append goo}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

#===============================================================================
# This part tests the different arithmetic operators for 
# the vector RBC component.
#

# ------------------------------------------------------------------------------
#  Test Constraints
#  Some machines treat floating point numbers differently, so we set some
#  constraints here for various vector related routines
# ------------------------------------------------------------------------------
tcltest::testConstraint twoDigitExponent   [expr {[format %1.0e 1e-20] eq "1e-20"}]
tcltest::testConstraint threeDigitExponent [expr {[format %1.0e 1e-20] eq "1e-020"}]
set tcl_precision 12

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of vector addition
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.1 {
    Test vector addition
} -setup {
	::graph::vector create VectorX
	::graph::vector create VectorY
	VectorX set {2 4 -1 2.4 4}
	VectorY set {5 -2 7 8 9.2}
} -body {
    VectorX + VectorY
} -cleanup {
	::graph::vector destroy VectorX
	::graph::vector destroy VectorY
} -result {7.0 2.0 6.0 10.4 13.2}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of addition using a scalar
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.2 {
    Test scalar addition
} -setup {
	::graph::vector create VectorX
	VectorX set {2 4 -1 2.4 4}
} -body {
    VectorX + 3.1
} -cleanup {
	::graph::vector destroy VectorX
} -result {5.1 7.1 2.1 5.5 7.1}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of vector subtraction
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.3 {
    Test vector subtraction
} -setup {
	::graph::vector create VectorX
	::graph::vector create VectorY
	VectorX set {0 5 4 2 -8 -8}
	VectorY set {5 0 2 4 4 -4}
} -body {
    VectorX - VectorY
} -cleanup {
	::graph::vector destroy VectorX
	::graph::vector destroy VectorY
} -result {-5.0 5.0 2.0 -2.0 -12.0 -4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of subtraction using a scalar
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.4 {
    Test scalar subtraction
} -setup {
	::graph::vector create VectorX
	VectorX set {0 5 4 2 -8}
} -body {
    VectorX - 3.1
} -cleanup {
	::graph::vector destroy VectorX
} -result {-3.1 1.9 0.9 -1.1 -11.1}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of vector multiplication
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.5 {
    Test vector multiplication
} -setup {
	::graph::vector create VectorX
	::graph::vector create VectorY
	VectorX set {0 1 2 2.4 -4 -4}
	VectorY set {5 5 5 2 2 -4}
} -body {
    VectorX * VectorY
} -cleanup {
	::graph::vector destroy VectorX
	::graph::vector destroy VectorY
} -result {0.0 5.0 10.0 4.8 -8.0 16.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of multiplication using a scalar
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.7 {
    Test scalar multiplication
} -setup {
	::graph::vector create VectorX
	VectorX set {0 1 2 2.4 -4}
} -body {
    VectorX * 2
} -cleanup {
	::graph::vector destroy VectorX
} -result {0.0 2.0 4.0 4.8 -8.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of vector division
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.8 {
    Test vector division
} -setup {
	::graph::vector create VectorX
	::graph::vector create VectorY
	VectorX set {0 1 5 -4 -8}
	VectorY set {5 5 1 2 -4}
} -body {
    VectorX / VectorY
} -cleanup {
	::graph::vector destroy VectorX
	::graph::vector destroy VectorY
} -result {0.0 0.2 5.0 -2.0 2.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the correct functioning of division using a scalar
# ------------------------------------------------------------------------------ 
test vector.arithmetic-1.6 {
    Test scalar division
} -setup {
	::graph::vector create VectorX
	VectorX set {0 1 5 -10 10}
} -body {
    VectorX / 5
} -cleanup {
	::graph::vector destroy VectorX
} -result {0.0 0.2 1.0 -2.0 2.0}

#===============================================================================
# This part tests the binread function of the vector rbc component.
# binread is an instance function of vector.
#

# ------------------------------------------------------------------------------
#  Test Constraints
#  Some machines treat floating point numbers differently, so we set some
#  constraints here for various vector related routines
# ------------------------------------------------------------------------------
tcltest::testConstraint twoDigitExponent   [expr {[format %1.0e 1e-20] eq "1e-20"}]
tcltest::testConstraint threeDigitExponent [expr {[format %1.0e 1e-20] eq "1e-020"}]

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command reads the entire contents of a file when 
# given no length parameter 
# ------------------------------------------------------------------------------ 
test vector.binread-1.1 {
	::graph::vector binread entire file
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 4.67887034632e+163}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command reads length number of items from the 
# channel 
# ------------------------------------------------------------------------------ 
test vector.binread-1.2 {
	::graph::vector binread length items
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel 1
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command reads the entire contents of a file in 
# the default endianess of the host machine 
# ------------------------------------------------------------------------------ 
test vector.binread-2.1 {
	::graph::vector binread default endianess
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 4.67887034632e+163}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command reads the entire contents of a file in 
# the opposite endianess of the host machine 
# ------------------------------------------------------------------------------ 
test vector.binread-2.2 {
	::graph::vector binread opposite endianess
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -swap
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 2.96444328161e-319}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command reads the entire contents of a file into 
# the vector starting at index# Purpose: 
# ------------------------------------------------------------------------------ 
test vector.binread-3.1 {
	::graph::vector binread at index
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2}
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -at 1
    expr {$Vector1(1:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 4.67887034632e+163}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command leaves all items preceding index 
# unchanged 
# ------------------------------------------------------------------------------ 
test vector.binread-3.2 {
	::graph::vector binread at index
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2}    
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -at 1
    expr {$Vector1(0)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {1.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the i1 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.1 {
	::graph::vector binread format i1
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format i1
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -22.0 97.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the i2 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.2 {
	::graph::vector binread format i2
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format i2
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 0.0 0.0 0.0 0.0 25066.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the i4 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.3 {
	::graph::vector binread format i4
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format i4
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 1642725376.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the u1 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.4 {
	::graph::vector binread format u1
} -setup {
	::graph::vector create Vector1
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format u1
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 234.0 97.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the u2 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.5 {
	::graph::vector binread format u2
} -setup {
	::graph::vector create Vector1 
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format u2
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 0.0 0.0 0.0 0.0 25066.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the u4 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.6 {
	::graph::vector binread format u4
} -setup {
	::graph::vector create Vector1 
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format u4
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 1642725376.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the r4 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.7-00 {
	::graph::vector binread format r4
} -constraints twoDigitExponent -setup {
	::graph::vector create Vector1   
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format r4
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 5.39567264156e+20}

test vector.binread-4.7-000 {
	::graph::vector binread format r4
} -constraints threeDigitExponent -setup {
	::graph::vector create Vector1   
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format r4
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 0.0 0.0 5.39567264156e+020}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector binread command can read the r8 format 
# ------------------------------------------------------------------------------ 
test vector.binread-4.8 {
	::graph::vector binread format r8
} -setup {
	::graph::vector create Vector1  
    set Channel [open [file join [file dirname [info script]] binReadTestFile.txt] r]
} -body {
    Vector1 binread $Channel -format r8
    expr {$Vector1(:)}
} -cleanup {
	::graph::vector destroy Vector1
    close $Channel
    unset Channel
} -result {0.0 4.67887034632e+163}

#===============================================================================
# This part tests the clear function of the vector rbc component.
# Clear is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector clear command works correctly.
# ------------------------------------------------------------------------------
test vector.clear-1.1 {
	::graph::vector clear: 
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
	expr $foo(0)
	expr $foo(1)
} -body {
	foo clear
	array size foo
} -cleanup {
	::graph::vector destroy foo
} -result {1}
	
#===============================================================================
# This part tests the different constructs for the create function of 
# the vector rbc component when no switches are used.

# ------------------------------------------------------------------------------
# Purpose: Ensure that creating a vector with no size parameter creates a new vector
# with zero elements (i.e. a length of zero)
# ------------------------------------------------------------------------------ 
test vector.create-1.1 {
    Test default vector length
} -body {
	::graph::vector create Vector1
    Vector1 length
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure that creating a vector with a size parameter create a new vector
# with the size parameter number of elements
# ------------------------------------------------------------------------------ 
test vector.create-1.2 {
    Test vector size
} -body {
	::graph::vector create Vector1(5)
    Vector1 length
} -cleanup {
	::graph::vector destroy Vector1
} -result {5}

# ------------------------------------------------------------------------------
# Purpose: Ensure that creating a vector with a size parameter of zero creates a new
# vector with zero elements
# ------------------------------------------------------------------------------ 
test vector.create-1.3 {
    Test vector size
} -body {
	::graph::vector create Vector1(0)
    Vector1 length
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with a size parameter greater than zero
# creates a new vector with size components all initialized to 0
# ------------------------------------------------------------------------------ 
test vector.create-1.4 {
    Test vector component initialization  
} -body {
	::graph::vector create Vector1(5)
    for {set i 0} {$i < [Vector1 length]} {incr i} {
        if {[Vector1 index $i]} {
            return 1
        }
    }
    return 0
} -cleanup {
	::graph::vector destroy Vector1
    unset i
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with identical range parameters creates a 
# new vector with 1 element
# ------------------------------------------------------------------------------ 
test vector.create-1.5 {
    Test vector indexing size
} -body {
	::graph::vector create Vector1(4:4)
    Vector1 length
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with firstIndex and lastIndex range 
# parameters creates a new vector with lastIndex-firstIndex+1 items
# ------------------------------------------------------------------------------ 
test vector.create-1.6 {
    Test vector indexing size
} -body {
	::graph::vector create Vector1(6:10)
    Vector1 length
} -cleanup {
	::graph::vector destroy Vector1
} -result {5}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with firstIndex and lastIndex range 
# parameters creates a new vector whose index starts at firstIndex
# ------------------------------------------------------------------------------ 
test vector.create-1.7 {
    Test vector indexing 
} -body {
	::graph::vector create Vector1(6:10)
    Vector1 offset
} -cleanup {
	::graph::vector destroy Vector1
} -result {6}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with firstIndex and lastIndex range 
# parameters creates a new vector with with lastIndex-firstIndex+1 components, all of
# which are initialized to 0
# ------------------------------------------------------------------------------ 
test vector.create-1.8 {
    Test vector indexing component initialization
} -body {
	::graph::vector create Vector1(6:10)
    for {set i [expr {[Vector1 offset]}]} {$i < [expr {[Vector1 offset] + [Vector1 length]}]} {incr i} {
        if {[Vector1 index $i]} {
            return 1
        }
    }
    return 0    
} -cleanup {
	::graph::vector destroy Vector1
    unset i
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector also creates a command with the same name
# as the vector
# ------------------------------------------------------------------------------
test vector.create-1.9 {
    Test default command creation
} -body {
	::graph::vector create Vector1
    expr {[info commands Vector1] == "Vector1"}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector also creates a variable with the same name
# as the vector
# ------------------------------------------------------------------------------
test vector.create-1.10 {
    Test default variable creation
} -body {
	::graph::vector create Vector1
    expr {[info vars Vector1] == "Vector1"}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that newly created vector shows up in the vector names command
# ------------------------------------------------------------------------------
test vector.create-1.11 {
    Test default vector creation
} -body {
	::graph::vector create Vector1
    expr {[::graph::vector names ::TEST::Vector1] == [list ::TEST::Vector1]}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the variable switch creates a variable
# ------------------------------------------------------------------------------ 
test vector.create-2.1 {
    Test vector variable switch
} -body {
	::graph::vector create Vector1 -variable Foo
    info exists Foo
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the variable switch causes the vector
# name to not also be a variable reference
# ------------------------------------------------------------------------------ 
test vector.create-2.2 {
    Test vector variable switch
} -body {
	::graph::vector create Vector1 -variable Foo
    info exists Vector1
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the command switch does not remove
# the variable reference that exists with the vector name
# ------------------------------------------------------------------------------ 
test vector.create-3.1 {
    Test vector command switch
} -body {
	::graph::vector create Vector1 -command Foo
    info exists Vector1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the command switch does not create
# a variable reference
# ------------------------------------------------------------------------------ 
test vector.create-3.2 {
    Test vector command switch
} -body {
	::graph::vector create Vector1 -command Foo
    info exists Foo
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the command switch creates a Tcl 
# command
# ------------------------------------------------------------------------------ 
test vector.create-3.3 {
    Test vector command switch 
} -body {
	::graph::vector create Vector1 -command Foo
    info commands Foo
} -cleanup {
	::graph::vector destroy Vector1
} -result {Foo}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the watchunset switch set to true
# causes the vector to be destoyed when the variable name (in this case the same as
# the vector name) is unset
# ------------------------------------------------------------------------------ 
test vector.create-4.1 {
    Test vector watchunset true switch  
} -body {
	::graph::vector create Vector1 -watchunset true
    unset Vector1
    expr -1 != [lsearch -glob [::graph::vector names] *Vector1]
} -cleanup {
    # vector destroy Vector1
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensures that creating a vector with the watchunset switch set to false
# does not destroy the vector when the variable name (in this case the same as the 
# vector name) is unset
# ------------------------------------------------------------------------------ 
test vector.create-4.2 {
    Test vector watchunset false switch
} -body {
	::graph::vector create Vector1 -watchunset false
    unset Vector1
    expr -1 != [lsearch -glob [::graph::vector names] *Vector1]
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}
	
#===============================================================================
# This part tests the delete function of the vector rbc component.
# Delete is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector delete command works correctly when given a single vector 
# index.
# ------------------------------------------------------------------------------
test vector.delete-1.1 {
	::graph::vector delete: single index
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo delete 2
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector delete command works correctly when given multiple vector 
# indices.
# ------------------------------------------------------------------------------
test vector.delete-1.2 {
	::graph::vector delete: multiple indices
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo delete 0 2
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
} -result {2.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector delete command works correctly when given an invalid 
# vector index.
# ------------------------------------------------------------------------------
test vector.delete-1.3 {
	::graph::vector delete: invalid index
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo delete 4}] || [foo length] != 4} {
		expr {$foo(:)}
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector delete command works correctly when given both a valid 
# and an invalid vector index.
# ------------------------------------------------------------------------------
test vector.delete-1.4 {
	::graph::vector delete: valid and invalid indices
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo delete 0 4}] || [foo length] != 4 || [lsearch $foo(:) 1.0] == -1} {
		expr {$foo(:)}
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

#===============================================================================
# This part tests the destroy function of the vector rbc component.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector destroy command works correctly when given a single
# existing vector name and no command has been assigned during the vector create.
# ------------------------------------------------------------------------------
test vector.destroy-1.1 {
	::graph::vector destroy: single vector name, no command
} -setup {
	::graph::vector create foo
	foo set 3
} -body {
	::graph::vector destroy foo
	
	if {[catch {$foo(0)}] && [catch {foo length}]} {
		return 0
	} else {
		return 1
	}
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector destroy command works correctly when given a multiple 
# existing vector names and no commands have been assigned during the vector create.
# ------------------------------------------------------------------------------
test vector.destroy-1.2 {
	::graph::vector destroy: multiple vector names, no command
} -setup {
	::graph::vector create foo
	foo set 3
	::graph::vector create bar
	bar set 5
} -body {
	::graph::vector destroy foo bar
	
	if {[catch {$foo(0)}] && [catch {foo length}]&& [catch {$bar(0)}] && [catch {bar length}]} {
		return 0
	} else {
		return 1
	}
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector destroy command works correctly when given a single 
# existing vector name and a command has been assigned during the vector create.
# ------------------------------------------------------------------------------
test vector.destroy-1.3 {
	::graph::vector destroy: single vector name, with command
} -setup {
	::graph::vector create foo -command bar
	bar set 3
} -body {
	::graph::vector destroy foo
	
	if {[catch {$foo(0)}] && [catch {bar length}]} {
		return 0
	} else {
		return 1
	}
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector destroy command works correctly when given a multiple 
# existing vector names and a commands have been assigned during the vector create.
# ------------------------------------------------------------------------------
test vector.destroy-1.4 {
	::graph::vector destroy: multiple vector names, with command
} -setup {
	::graph::vector create foo -command bar
	bar set 3
	::graph::vector create moo -command nar
	nar set 5
} -body {
	::graph::vector destroy foo moo
	
	if {[catch {$foo(0)}] && [catch {bar length}] && [catch {$moo(0)}] && [catch {nar length}]} {
		return 0
	} else {
		return 1
	}
} -result {0}

#===============================================================================
# This part tests the dup function of an instance of the vector
# rbc component.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector dup command overwrites the contents of an existing 
# destName vector with the contents of the instance vector 
# ------------------------------------------------------------------------------ 
test vector.dup-1.1 {
    Test vector dup with overwriting
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 7 8 9}       
	::graph::vector create Vector2
    Vector2 set {1 2}
} -body {
    Vector1 dup Vector2
    expr {$Vector2(:)}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector dup command creates a new vector with the contents of 
# the instance vector when destName does not exist. 
# ------------------------------------------------------------------------------ 
test vector.dup-1.2 {
    Test vector dup with vector creation
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 7 8 9}       
} -body {
    Vector1 dup Vector2
    expr {$Vector2(:)}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0}

#===============================================================================
# This part tests the different operators of the expression feature
# in the vector package.

# ------------------------------------------------------------------------------
#  Test Constraints
#  Some machines treat floating point numbers differently, so we set some
#  constraints here for various vector related routines
# ------------------------------------------------------------------------------
tcltest::testConstraint twoDigitExponent   [expr {[format %1.0e 1e-20] eq "1e-20"}]
tcltest::testConstraint threeDigitExponent [expr {[format %1.0e 1e-20] eq "1e-020"}]
set tcl_precision 12

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating unary minus
# ------------------------------------------------------------------------------ 
test vector.expr-1.1 {
	Test unary minus
} -setup {
	::graph::vector create Vector1(5)
	
	Vector1 set {2 0 -1 2.4 -4.3}
} -body {
	::graph::vector expr {-Vector1}
} -cleanup {
	::graph::vector destroy Vector1
} -result {-2.0 0.0 1.0 -2.4 4.3}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating logical not
# ------------------------------------------------------------------------------
test vector.expr-1.2 {
	Test logical not
} -setup {
	::graph::vector create Vector1(5)
	
	Vector1 set {2 0 -2 2.4 -4.4}
} -body {
	::graph::vector expr {!Vector1}
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 1.0 0.0 0.0 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating exponentation
# ------------------------------------------------------------------------------
test vector.expr-1.3 {
	Test exponentiation
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 1 12 4 2 -2 -2}
	Vector2 set {5 5 0 0.5 3 3 4}
} -body {
	::graph::vector expr {Vector1 ^ Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 1.0 1.0 2.0 8.0 -8.0 16.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating multiplication
# ------------------------------------------------------------------------------
test vector.expr-1.4 {
	Test multiplication
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 1 2 2.4 -4 -4}
	Vector2 set {5 5 5 2 2 -4}
} -body {
	::graph::vector expr {Vector1 * Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 5.0 10.0 4.8 -8.0 16.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating division
# ------------------------------------------------------------------------------
test vector.expr-1.5 {
	Test Division
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 1 5 -4 -8}
	Vector2 set {5 5 1 2 -4}
} -body {
	::graph::vector expr {Vector1 / Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 0.2 5.0 -2.0 2.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating Modulo
# ------------------------------------------------------------------------------
test vector.expr-1.6 {
	Test Modulo
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {38 12 -3 5}
	Vector2 set {12 24 5 -3}
} -body {
	::graph::vector expr {Vector1 % Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {2.0 12.0 2.0 -1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating Subtraction
# ------------------------------------------------------------------------------
test vector.expr-1.7 {
	Test Subtraction
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 5 4 2 -8 -8}
	Vector2 set {5 0 2 4 4 -4}
} -body {
	::graph::vector expr {Vector1 - Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {-5.0 5.0 2.0 -2.0 -12.0 -4.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating addition
# ------------------------------------------------------------------------------
test vector.expr-1.8 {
	Test Addition
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {2 4 -1 2.4 4}
	Vector2 set {5 -2 7 8 9.2}
} -body {
	::graph::vector expr {Vector1 + Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {7.0 2.0 6.0 10.4 13.2}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating vector shift left
# ------------------------------------------------------------------------------
test vector.expr-1.9 {
	Test shift left
} -setup {
	::graph::vector create Vector1(5)
	
	Vector1 set {0 1 5 -4 -8}
} -body {
	::graph::vector expr {Vector1 << 1}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.0 5.0 -4.0 -8.0 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating vector shift right
# ------------------------------------------------------------------------------
test vector.expr-1.10 {
	Test Shift Right
} -setup {
	::graph::vector create Vector1(5)
	
	Vector1 set {0 1 5 -4 -8}
} -body {
	::graph::vector expr {Vector1 >> 1}
} -cleanup {
	::graph::vector destroy Vector1
} -result {-8.0 0.0 1.0 5.0 -4.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating less than
# ------------------------------------------------------------------------------
test vector.expr-1.11 {
	Test less than
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {2 4 -2 4 4 5}
	Vector2 set {5 2 5 -2 4.4 5}
} -body {
	::graph::vector expr {Vector1 < Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 0.0 1.0 0.0 1.0 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating greater than
# ------------------------------------------------------------------------------
test vector.expr-1.12 {
	Test Greater Than
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {2 4 -2 4 4 5}
	Vector2 set {5 2 5 -2 4.4 5}
} -body {
	::graph::vector expr {Vector1 > Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 1.0 0.0 1.0 0.0 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating less than or equal
# ------------------------------------------------------------------------------
test vector.expr-1.13 {
	Test Less than or equal
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {2 4 -2 4 4 5}
	Vector2 set {5 2 5 -2 4.4 5}
} -body {
	::graph::vector expr {Vector1 <= Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 0.0 1.0 0.0 1.0 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating greater than or equal
# ------------------------------------------------------------------------------
test vector.expr-1.14 {
	Test Greater than or equal
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {2 4 -2 4 4 5}
	Vector2 set {5 2 5 -2 4.4 5}
} -body {
	::graph::vector expr {Vector1 >= Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 1.0 0.0 1.0 0.0 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating logical and
# ------------------------------------------------------------------------------
test vector.expr-1.15 {
	Test logical and
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 5 0 5.5}
	Vector2 set {0 0 5.2 6.0}
} -body {
	::graph::vector expr {Vector1 && Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 0.0 0.0 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating logical or
# ------------------------------------------------------------------------------
test vector.expr-1.16 {
	Test logical or
} -setup {
	::graph::vector create Vector1(5)
	::graph::vector create Vector2(5)
	
	Vector1 set {0 5 0 5.5}
	Vector2 set {0 0 5.2 6.0}
} -body {
	::graph::vector expr {Vector1 || Vector2}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {0.0 1.0 1.0 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating acos (inverse cosine)
# ------------------------------------------------------------------------------ 
test vector.expr-1.17 {
	Test acos
} -setup {
	::graph::vector create Vector1
	Vector1 set {1 0 0.5 -1}
} -body {
	::graph::vector expr {acos(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 1.57079632679 1.0471975512 3.14159265359}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating asin (inverse sine)
# ------------------------------------------------------------------------------ 
test vector.expr-1.18 {
	Test asin
} -setup {
	::graph::vector create Vector1
	Vector1 set {1 0 0.5 -1}
} -body {
	::graph::vector expr {asin(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.57079632679 0.0 0.523598775598 -1.57079632679}
	
# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating atan (inverse tangent)
# ------------------------------------------------------------------------------ 
test vector.expr-1.19 {
	Test atan
} -setup {
	::graph::vector create Vector1
	Vector1 set {1 0 0.5 -1}
} -body {
	::graph::vector expr {atan(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.785398163397 0.0 0.463647609001 -0.785398163397}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating ceil (ceiling)
# ------------------------------------------------------------------------------ 
test vector.expr-1.20- {
	Test ceil
} -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 4.5 8.4 .1 -0.1 -0.5 -2.1}
} -body {
	::graph::vector expr {ceil(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {4.0 5.0 9.0 1.0 0.0 0.0 -2.0}

test vector.expr-1.20+ {
	Test ceil
} -constraints threeDigitExponent -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 4.5 8.4 .1 -0.1 -0.5 -2.1}
} -body {
	::graph::vector expr {ceil(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {4.0 5.0 9.0 1.0 0.0 0.0 -2.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating cos
# ------------------------------------------------------------------------------ 
test vector.expr-1.21 {
	Test cosine
} -setup {
	::graph::vector create Vector1
	Vector1 set {0 3.14159 6.28318 -3.14159}
} -body {
	::graph::vector expr {cos(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.0 -0.999999999996 0.999999999986 -0.999999999996}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating cosh
# ------------------------------------------------------------------------------ 
test vector.expr-1.22 {
	Test cosh
} -setup {
	::graph::vector create Vector1
	Vector1 set {0 3.14159 6.28318 -3.14159}
} -body {
	::graph::vector expr {cosh(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.0 11.5919226299 267.745340517 11.5919226299}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating exp
# ------------------------------------------------------------------------------ 
test vector.expr-1.23 {
	Test exp
} -setup {
	::graph::vector create Vector1
	Vector1 set {2 -2 1.3 0}
} -body {
	::graph::vector expr {exp(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {7.38905609893 0.135335283237 3.66929666762 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating floor
# ------------------------------------------------------------------------------ 
test vector.expr-1.24 {
	Test floor
} -setup {
	::graph::vector create Vector1
	Vector1 set {2.1 3.9 -0.1 -1.5}
} -body {
	::graph::vector expr {floor(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.0 3.0 -1.0 -2.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating log
# ------------------------------------------------------------------------------ 
test vector.expr-1.25 {
	Test log
} -setup {
	::graph::vector create Vector1
	Vector1 set {12 2 3 5}
} -body {
	::graph::vector expr {log(Vector1)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.48490664979 0.69314718056 1.09861228867 1.60943791243}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating log10
# ------------------------------------------------------------------------------ 
test vector.expr-1.26 {
	Test log10
} -setup {
	::graph::vector create Vector1
	Vector1 set {1 10 2.1 19} 
} -body {
	::graph::vector expr {log10(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 1.0 0.322219294734 1.27875360095}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating abs
# ------------------------------------------------------------------------------ 
test vector.expr-1.27 {
	Test abs
} -setup {
	::graph::vector create Vector1
	Vector1 set {2 3 -3 5 4 -1.1 3.2}
} -body {
	::graph::vector expr {abs(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.0 3.0 3.0 5.0 4.0 1.1 3.2}	

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sin
# ------------------------------------------------------------------------------ 
test vector.expr-1.28-00 {
	Test sin
} -constraints twoDigitExponent -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {sin(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.65358979335e-06 0.999999999999 0.0 -2.65358979335e-06 -0.846220404175 0.841470984808 -0.841470984808}
test vector.expr-1.28-000 {
	Test sin
} -constraints threeDigitExponent -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {sin(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.65358979335e-006 0.999999999999 0.0 -2.65358979335e-006 -0.846220404175 0.841470984808 -0.841470984808}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sinh
# ------------------------------------------------------------------------------ 
test vector.expr-1.29 {
	Test sinh
} -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {sinh(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {11.548708597 2.30129557314 0.0 -11.548708597 4872401723.12 1.17520119364 -1.17520119364}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sqrt
# ------------------------------------------------------------------------------ 
test vector.expr-1.30 {
	Test sqrt
} -setup {
	::graph::vector create Vector1
	Vector1 set {0 2 4 144 3.14159}
} -body {
	::graph::vector expr {sqrt(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 1.41421356237 2.0 12.0 1.77245310234}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating tan
# ------------------------------------------------------------------------------ 
test vector.expr-1.31-00 {
	Test tan
} -constraints twoDigitExponent -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {tan(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-2.65358979336e-06 753695.995141 0.0 2.65358979336e-06 1.58815308339 1.55740772465 -1.55740772465}
test vector.expr-1.31-000 {
	Test tan
} -constraints threeDigitExponent -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {tan(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-2.65358979336e-006 753695.995141 0.0 2.65358979336e-006 1.58815308339 1.55740772465 -1.55740772465}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating tanh
# ------------------------------------------------------------------------------ 
test vector.expr-1.32 {
	Test tanh
} -setup {
	::graph::vector create Vector1
	Vector1 set {3.14159 1.570795 0 -3.14159 23 1 -1}
} -body {
	::graph::vector expr {tanh(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.996272056473 0.91715212493 0.0 -0.996272056473 1.0 0.761594155956 -0.761594155956}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating round
# ------------------------------------------------------------------------------ 
test vector.expr-1.33 {
	Test round
} -setup {
	::graph::vector create Vector1
	Vector1 set {-3.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {round(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-3.0 -2.0 7.0 10.0 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating adev
# ------------------------------------------------------------------------------ 
test vector.expr-1.34 {
	Test adev
} -setup {
	::graph::vector create Vector1
	Vector1 set {-3.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {adev(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {4.7696}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating kurtosis (degree of peakedness)
# ------------------------------------------------------------------------------ 
test vector.expr-1.35 {
	Test kurtosis
} -setup {
	::graph::vector create Vector1
	Vector1 set {-3.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {kurtosis(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-2.13595720694}

# ------------------------------------------------------------------------------
# Purpose: Tests length with a vector containing elements (see 1.52 for no elements)
# ------------------------------------------------------------------------------ 
test vector.expr-1.36 {
	Test length with elements
} -setup {
	::graph::vector create Vector1
	Vector1 set {-3.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {length(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {5.0}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating max
# ------------------------------------------------------------------------------ 
test vector.expr-1.37 {
	Test max
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {max(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {9.5}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating mean
# ------------------------------------------------------------------------------ 
test vector.expr-1.38 {
	Test mean
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 0}
} -body {
	::graph::vector expr {mean(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.438}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating median
# ------------------------------------------------------------------------------ 
test vector.expr-1.39 {
	Test median
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {median(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.05}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating min
# ------------------------------------------------------------------------------ 
test vector.expr-1.40 {
	Test min
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {min(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-13.11}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating q1
# ------------------------------------------------------------------------------ 
test vector.expr-1.41 {
	Test q1
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {q1(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-1.3}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating q3
# ------------------------------------------------------------------------------ 
test vector.expr-1.42 {
	Test q3
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {q3(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {8.4}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating prod
# ------------------------------------------------------------------------------ 
test vector.expr-1.43 {
	Test prod
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {prod(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-1800.17343}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sdev (standard deviation)
# ------------------------------------------------------------------------------ 
test vector.expr-1.44 {
	Test sdev
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {sdev(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {7.99297295546}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating skew (skewedness)
# ------------------------------------------------------------------------------ 
test vector.expr-1.45 {
	Test skew
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {skew(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.16046217734}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sum
# ------------------------------------------------------------------------------ 
test vector.expr-1.46 {
	Test sum
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {sum(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {2.29}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating var (variance)
# ------------------------------------------------------------------------------ 
test vector.expr-1.47 {
	Test var
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {var(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {63.8876166667}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating norm
# ------------------------------------------------------------------------------ 
test vector.expr-1.48 {
	Test norm
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {norm(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 0.513489606369 0.902697921274 1.0 0.53118089341 0.632905793897}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating sort (ascending by default)
# ------------------------------------------------------------------------------ 
test vector.expr-1.49 {
	Test sort
} -setup {
	::graph::vector create Vector1
	Vector1 set {-13.11 -1.5 7.3 9.5 -1.1 1.2}
} -body {
	::graph::vector expr {sort(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {-13.11 -1.5 -1.1 1.2 7.3 9.5}

# ------------------------------------------------------------------------------
# Purpose: Tests different conditions when evaluating random (produces vector)
# ------------------------------------------------------------------------------ 
test vector.expr-1.50 {
	Test random
} -setup {
	::graph::vector create Vector1(5)
} -body {
	::graph::vector expr {random(Vector1)}
	for {set i 0} {$i < [Vector1 length]} {incr i} {
        if {[Vector1 index $i] < 0 || [Vector1 index $i] > 1} {
            return 0
        }
    }
    return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Tests length when vector has no elements
# ------------------------------------------------------------------------------ 
test vector.expr-1.51 {
	Test length no elements
} -setup {
	::graph::vector create Vector1(0)
} -body {
	::graph::vector expr {length(Vector1)} 
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0}

#===============================================================================
# This part tests the index function of the vector rbc component when only 
# an index is given.
# Index is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector index command works correctly when given a valid vector 
# index.
# ------------------------------------------------------------------------------
test vector.index-1.1 {
	::graph::vector index: valid index
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo index 2
} -cleanup {
	::graph::vector destroy foo
} -result {3.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector index command works correctly when given an invalid 
# vector index.
# ------------------------------------------------------------------------------
test vector.index-1.2 {
	::graph::vector index: invalid index
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo index 4}]} {
		expr {$foo(:)}
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector index command works correctly when given a valid vector 
# index and a valid value.
# ------------------------------------------------------------------------------
test vector.index-2.1 {
	::graph::vector index: valid index, valid value
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo index 2 5.0
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 5.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector index command works correctly when given an invalid 
# vector index.
# ------------------------------------------------------------------------------
test vector.index-2.2 {
	::graph::vector index: invalid index, valid value
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo index 4 5.0}]} {
		expr {$foo(:)}
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector index command works correctly when given a valid vector 
# index and an invalid value.
# ------------------------------------------------------------------------------
test vector.index-2.3 {
	::graph::vector index: valid index, invalid value
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo index 2 a}]} {
		expr {$foo(:)}
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

#===============================================================================
# This part tests the different constructs for the length function of 
# the vector rbc component using no arguments.

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will return the correct length
# ------------------------------------------------------------------------------ 
test vector.length-1.1 {
    Test default vector length
} -setup {
	::graph::vector create TestVector(5)
} -body {
    TestVector length
} -cleanup {
	::graph::vector destroy TestVector
} -result {5}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will return the correct length when the vector
#	has been offset
# ------------------------------------------------------------------------------ 
test vector.length-1.2 {
    Test default vector length
} -setup {
	::graph::vector create TestVector(2:5)
} -body {
    TestVector length
} -cleanup {
	::graph::vector destroy TestVector
} -result {4}

	# ------------------------------------------------------------------------------
# Purpose: Ensure that length which resizes returns the correct value
# ------------------------------------------------------------------------------ 
test vector.length-2.1 {
    Test length resizing
} -setup {
	::graph::vector create TestVector(5)
} -body {
	TestVector length 10
} -cleanup {
	::graph::vector destroy TestVector
} -result {10}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will keep its offset after adjusted to the desired length
# ------------------------------------------------------------------------------ 
test vector.length-2.2 {
    Test length resizing keeps offset
} -setup {
	::graph::vector create TestVector(2:5)
} -body {
	TestVector length 10
    TestVector offset
} -cleanup {
	::graph::vector destroy TestVector
} -result {2}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will expand to the desired length
# ------------------------------------------------------------------------------ 
test vector.length-2.3 {
    Test length resizing
} -setup {
	::graph::vector create TestVector(5)
} -body {
	TestVector length 10
    TestVector length
} -cleanup {
	::graph::vector destroy TestVector
} -result {10}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will keep the data in the vector after resizing
# ------------------------------------------------------------------------------ 
test vector.length-2.4 {
    Test length resizing keeps data
} -setup {
	::graph::vector create TestVector(5)
	TestVector set {0 1 2 3 4}
} -body {
	TestVector length 10
    for {set i 0} {$i < 5} {incr i} {
		if {$i != [TestVector index $i]} {
			return 0
		}
    }
	
	for {set i 5} {$i < 10} {incr i} {
		if {0 != [TestVector index $i]} {
			return 0
		}
	}
	return 1
} -cleanup {
	::graph::vector destroy TestVector
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will expand to the desired length
# ------------------------------------------------------------------------------ 
test vector.length-2.5 {
    Test length resizing
} -setup {
	::graph::vector create TestVector(5)
} -body {
	TestVector length 3
    TestVector length
} -cleanup {
	::graph::vector destroy TestVector
} -result {3}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will keep the data in the vector after resizing
# ------------------------------------------------------------------------------ 
test vector.length-2.6 {
    Test length resizing keeps data
} -setup {
	::graph::vector create TestVector(5)
	TestVector set {0 1 2 3 4}
} -body {
	TestVector length 3
    for {set i 0} {$i < 3} {incr i} {
		if {$i != [TestVector index $i]} {
			return 0
		}
    }
	return 1
} -cleanup {
	::graph::vector destroy TestVector
} -result {1}

#===============================================================================
# This part tests the merge function of the vector rbc
# component by merging different permutations of vectors

# ------------------------------------------------------------------------------
# Purpose: Ensure that a single vector merge will overite data
# ------------------------------------------------------------------------------ 
test vector.merge-1.1 {
    Test single vector merge
} -setup {
	::graph::vector create Foobar
	::graph::vector create Foo
    Foobar set {1 2 3 4 5}
	Foo set {3 4}
} -body {
	Foobar merge Foo
	Foobar range [Foobar offset] end
} -cleanup {
	::graph::vector destroy Foobar
	::graph::vector destroy Foo
} -result {3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a multiple vector merge merges index by index
# ------------------------------------------------------------------------------ 
test vector.merge-1.1 {
    Test multiple vector merge
} -setup {
	::graph::vector create Foobar
	::graph::vector create Foo
	::graph::vector create Bar
	Foo set {1 3 5 7 9}
	Bar set {2 4 6 8 10}
} -body {
	Foobar merge Foo Bar
	Foobar range [Foobar offset] end
} -cleanup {
	::graph::vector destroy Foobar
	::graph::vector destroy Foo
	::graph::vector destroy Bar
} -result {1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0}

#===============================================================================
# This part tests the names function of the vector rbc component.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector names command works correctly when no pattern is given.
# ------------------------------------------------------------------------------
test vector.names-1.1 {
	::graph::vector names: no pattern
} -setup {
	::graph::vector create foo
	::graph::vector create goo
} -body {
	::graph::vector names
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
} -result {::TEST::foo ::TEST::goo}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector names command works correctly when an exact pattern is 
# given.
# ------------------------------------------------------------------------------
test vector.names-1.2 {
	::graph::vector names: exact pattern
} -setup {
	::graph::vector create foo
	::graph::vector create goo
} -body {
	::graph::vector names ::TEST::goo
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
} -result {::TEST::goo}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector names command works correctly when a wildcard pattern is 
# given.
# ------------------------------------------------------------------------------
test vector.names-1.3 {
	::graph::vector names: wildcard pattern
} -setup {
	::graph::vector create foo
	::graph::vector create food
} -body {
	::graph::vector names *f*
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy food
} -result {::TEST::food ::TEST::foo}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector names command works correctly when an incorrect pattern 
# is given.
# ------------------------------------------------------------------------------
test vector.names-1.4 {
	::graph::vector names: incorrect pattern
} -setup {
	::graph::vector create foo
	::graph::vector create food
} -body {
	::graph::vector names foo
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy food
} -result {}

#===============================================================================
# This part tests the different constructs for the normalize function of 
# the vector rbc component.

# ------------------------------------------------------------------------------
# Purpose: Tests normalize to verify a vector of whole numbers is normalized properly
# ------------------------------------------------------------------------------ 
test vector.normalize-1.1 {
    Test normalize ints
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 3 7 11 13 17 19 23 29}
} -body {
    Vector1 normalize
} -cleanup {
	::graph::vector destroy Vector1
} -result {0.0 0.0714285714286 0.214285714286 0.357142857143 0.428571428571 0.571428571429 0.642857142857 0.785714285714 1.0}

# ------------------------------------------------------------------------------
# Purpose: Tests normalize to verify a vector of negative numbers is normalized properly
# ------------------------------------------------------------------------------ 
test vector.normalize-1.2 {
    Test normalize ints
} -setup {
	::graph::vector create Vector1
    Vector1 set {-1 -3 -7 -11 -13 -17 -19 -23 -29}
} -body {
    Vector1 normalize
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.0 0.928571428571 0.785714285714 0.642857142857 0.571428571429 0.428571428571 0.357142857143 0.214285714286 0.0}

# ------------------------------------------------------------------------------
# Purpose: Tests normalize to verify a vector of negative numbers is normalized properly
# ------------------------------------------------------------------------------ 
test vector.normalize-1.3 {
    Test normalize ints
} -setup {
	::graph::vector create Vector1
} -body {
    Vector1 normalize
} -cleanup {
	::graph::vector destroy Vector1
} -result {}	

#===============================================================================
# This part tests the offset function of 
# the vector rbc component using no arguments.

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will return the correct offset
# ------------------------------------------------------------------------------ 
test vector.offset-1.1 {
    Test default vector offset
} -setup {
	::graph::vector create TestVector(5:10)
} -body {
    TestVector offset
} -cleanup {
	::graph::vector destroy TestVector
} -result {5}

	# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector will shift to correct offset
# ------------------------------------------------------------------------------ 
test vector.offset-2.1 {
    Test vector offset shift
} -setup {
	::graph::vector create TestVector(5:10)
} -body {
    TestVector offset 4
	TestVector offset
} -cleanup {
	::graph::vector destroy TestVector
} -result {4}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a vector's data will shift to correct offset
# ------------------------------------------------------------------------------ 
test vector.offset-2.1 {
    Test vector offset shift
} -setup {
	::graph::vector create TestVector(5:10)
	TestVector set {4 5 6 7 8}
} -body {
    TestVector offset 4
	
	for {set i 4} {$i < 5} {incr i} {
		if {$i != [TestVector index $i]} {
			return 0
		}
	}
	return 1
} -cleanup {
	::graph::vector destroy TestVector
} -result {1}

#===============================================================================
# This part tests the populate function of an instance of the vector
# rbc component.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector populate command overwrites the contents of an existing
# destName vector with the contents of the instance vector and density new components
# between each pre-existing component 
# ------------------------------------------------------------------------------ 
test vector.populate-1.1 {
    Test vector populate with overwriting
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 7 8 9}       
	::graph::vector create Vector2
Vector2 set {1 2}
} -body {
    Vector1 populate Vector2 1
    expr {$Vector2(:)}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector populate command creates a new destName vector with the 
# contents of the instance vector and density number of new components between each 
# pre-existing component 
# ------------------------------------------------------------------------------ 
test vector.populate-1.2 {
    Test vector populate with creation
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 7 8 9}
} -body {
    Vector1 populate Vector2 1
    expr {$Vector2(:)}
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0}

#===============================================================================
# This part tests the different constructs for the random function of 
# the vector rbc component.

# ------------------------------------------------------------------------------
# Purpose: Tests random to verify it creates a random vector given an empty vector 
# of set length
# ------------------------------------------------------------------------------ 
test vector.random-1.1 {
    Test random
} -setup {
	::graph::vector create Vector1(5)
} -body {
	Vector1 random
	for {set i 0} {$i < [Vector1 length]} {incr i} {
        if {[Vector1 index $i] < 0 || [Vector1 index $i] > 1} {
            return 0
        }
    }
    return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Tests random to verify it creates a random vector given an already 
# initialized vector
# ------------------------------------------------------------------------------ 
test vector.random-1.2 {
    Test random
} -setup {
	::graph::vector create Vector1(5)
	Vector1 set {1 2 3 4 5}
} -body {
	Vector1 random
	for {set i 0} {$i < [Vector1 length]} {incr i} {
        if {[Vector1 index $i] < 0 || [Vector1 index $i] > 1} {
            return 0
        }
    }
    return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}	

#===============================================================================
# This part tests the range function of the vector rbc component.
# Range is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector range command works correctly when given two valid vector 
# indices where the last index is greater than the first index.
# ------------------------------------------------------------------------------
test vector.range-1.1 {
	::graph::vector range: valid indices
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo range 1 2
} -cleanup {
	::graph::vector destroy foo
} -result {2.0 3.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector range command works correctly when given an invalid 
# vector index.
# ------------------------------------------------------------------------------
test vector.range-1.2 {
	::graph::vector range: invalid index
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo range 1 4}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector range command works correctly when given two valid vector 
# indices where the last index is less than the first index.
# ------------------------------------------------------------------------------
test vector.range-1.3 {
	::graph::vector range: valid indices, reversed
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo range 2 1
} -cleanup {
	::graph::vector destroy foo
} -result {2.0 3.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector range command works correctly when given a valid vector 
# index and the end keyword.
# ------------------------------------------------------------------------------
test vector.range-1.4 {
	::graph::vector range: keyword
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo range 1 end
} -cleanup {
	::graph::vector destroy foo
} -result {2.0 3.0 4.0}

#===============================================================================
# This part tests the different constructs for the search function of 
# the vector rbc component.

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it finds the locations of an element that occurs twice
# ------------------------------------------------------------------------------ 
test vector.search-1.1 {
    Test search multipe instances
} -setup {
	::graph::vector create Vector1
    Vector1 set {3 1 2 -3 4 1}
} -body {
    Vector1 search 1 
} -cleanup {
	::graph::vector destroy Vector1
} -result {1 5}

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it finds the locations of an element that occurs once
# ------------------------------------------------------------------------------ 	
test vector.search-1.2 {
    Test search single instance
} -setup {
	::graph::vector create Vector1
    Vector1 set {3 1 2 -3 4 1}
} -body {
    Vector1 search 3
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}	

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it returns nothing for an element that does not exist
# ------------------------------------------------------------------------------ 	
test vector.search-1.3 {
    Test search zero instances
} -setup {
	::graph::vector create Vector1
    Vector1 set {3 1 2 -3 4 1}
} -body {
    Vector1 search 7
} -cleanup {
	::graph::vector destroy Vector1
} -result {}

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it finds the locations of elements within a given
# range where the numbers with in the range are included in the elements
# ------------------------------------------------------------------------------ 	
test vector.search-1.4 {
    Test search
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 5 4 3 2 1 0}
} -body {
    Vector1 search 2 5
} -cleanup {
	::graph::vector destroy Vector1
} -result {1 2 3 4 6 7 8 9}

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it finds the locations of elements within a given
# range where the numbers provided are not included in the elements
# ------------------------------------------------------------------------------ 	
test vector.search-1.5 {
    Test search
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 5 4 3 2 1 0}
} -body {
    Vector1 search -1 10
} -cleanup {
	::graph::vector destroy Vector1
} -result {0 1 2 3 4 5 6 7 8 9 10 11}

# ------------------------------------------------------------------------------
# Purpose: Tests search to verify it returns nothing when given a range where no
# elements exist
# ------------------------------------------------------------------------------ 	
test vector.search-1.6 {
    Test search
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 5 4 3 2 1 0}
} -body {
    Vector1 search 1.1 1.9
} -cleanup {
	::graph::vector destroy Vector1
} -result {}	

#===============================================================================
# This part tests the different constructs for the sequence (seq) function of 
# the vector rbc component using no arguments.

# ------------------------------------------------------------------------------
# Purpose: Ensure that a sequence will be generated from start to finish
# ------------------------------------------------------------------------------ 
test vector.seq-1.1 {
    Test sequence generation without step
} -setup {
	::graph::vector create TestVector
} -body {
	TestVector seq 2 5
	TestVector range 0 end
} -cleanup {
	::graph::vector destroy TestVector
} -result {2.0 3.0 4.0 5.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a sequence will be generated from start to finish with a step
# ------------------------------------------------------------------------------ 
test vector.seq-1.2 {
    Test sequence generation with step
} -setup {
	::graph::vector create TestVector
} -body {
	TestVector seq 2 5 2
	TestVector range 0 end
} -cleanup {
	::graph::vector destroy TestVector
} -result {2.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure that a sequence will be generated when given a negative step
# ------------------------------------------------------------------------------ 
test vector.seq-1.3 {
    Test sequence generation with negative step
} -setup {
	::graph::vector create TestVector
} -body {
	TestVector seq 5 0 -1
	TestVector range 0 end
} -cleanup {
	::graph::vector destroy TestVector
} -result {5.0 4.0 3.0 2.0 1.0 0.0}

#===============================================================================
# This part tests the set function of the vector rbc component.
# Set is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector set command works correctly when given a list of 
# numbers.
# ------------------------------------------------------------------------------
test vector.set-1.1 {
	::graph::vector set: list of numbers
} -setup {
	::graph::vector create foo
} -body {
	foo set {1.0 2.0 3.0 4.0} 
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector set command works correctly when given another vector.
# ------------------------------------------------------------------------------
test vector.set-1.2 {
	::graph::vector set: another vector
} -setup {
	::graph::vector create foo
	::graph::vector create goo
} -body {
	goo set {1.0 2.0 3.0 4.0}
	foo set goo
	expr {$foo(:)}
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
} -result {1.0 2.0 3.0 4.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector set command works correctly when given a list containing 
# characters.
# ------------------------------------------------------------------------------
test vector.set-1.3 {
	::graph::vector set: list with characters
} -setup {
	::graph::vector create foo
} -body {
	if {[catch {foo set {1.0 2.0 3.0 a}}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector set command works correctly when given a non-existent 
# vector reference.
# ------------------------------------------------------------------------------
test vector.set-1.4 {
	::graph::vector set: non-existent vector
} -setup {
	::graph::vector create foo
} -body {
	if {[catch {foo set goo}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

#===============================================================================
# This part tests the different constructs for the sort function of 
# the vector rbc component when one vector is given.

# ------------------------------------------------------------------------------
# Purpose: Tests sort to verify a vector of numbers is sorted properly
# ------------------------------------------------------------------------------ 
test vector.sort-1.1 {
    Test sort basic
} -setup {
	::graph::vector create Vector1
    Vector1 set {10 9 8 7 6 5 4 3 2 1}
} -body {
    Vector1 sort
	for {set i 0} {$i < [Vector1 length] - 1} {incr i} {
    if {[Vector1 index $i] > [Vector1 index $i+1]} {
        return 0
    }
}
    return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Tests sort to verify a vector of numbers is sorted properly in reverse
# ------------------------------------------------------------------------------ 
test vector.sort-1.2 {
    Test sort reverse
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5 6 7 8 9 10}
} -body {
    Vector1 sort -reverse
for {set i 0} {$i < [Vector1 length] - 1} {incr i} {
    if {[Vector1 index $i] < [Vector1 index $i+1]} {
        return 0
    }
}
	return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Tests sort to verify a vector of numbers is sorted properly along with 
# the associated vector
# ------------------------------------------------------------------------------ 
test vector.sort-2.1 {
    Test sort vector and an associated vector
} -setup {
	::graph::vector create Vector1
	::graph::vector create Vector2
    Vector1 set {5 4 3 2 1}
	Vector2 set {10 9 8 7 6}
} -body {
	Vector1 sort Vector2
    Vector1 append Vector2
	for {set i 0} {$i < [Vector1 length] - 1} {incr i} {
    if {[Vector1 index $i] > [Vector1 index $i+1]} {
        return 0
    }
}
    return 1
} -cleanup {
	::graph::vector destroy Vector1
} -result {1}

# ------------------------------------------------------------------------------
# Purpose: Tests sort to verify a vector of numbers is sorted properly along with 
# the associated vector using the reverse flag
# ------------------------------------------------------------------------------ 	
test vector.sort-2.2 {
    Test sort vector and an associated vector -reverse
} -setup {
	::graph::vector create Vector1
	::graph::vector create Vector2
    Vector1 set {1 2 3 4 5}
	Vector2 set {6 7 8 9 10}
} -body {
	Vector1 sort -reverse Vector2
    Vector2 append Vector1
	for {set i 0} {$i < [Vector2 length] - 1} {incr i} {
    if {[Vector2 index $i] < [Vector2 index $i+1]} {
        return 0
    }
}
	return 1
} -cleanup {
	::graph::vector destroy Vector1
	::graph::vector destroy Vector2
} -result {1}

#===============================================================================
# This part tests the split function of the vector rbc component.
# Split is an instance function of vector.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector split command works correctly when given a single vector 
# name.
# ------------------------------------------------------------------------------
test vector.split-1.1 {
	::graph::vector split: one vector name
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	foo split goo
	if {[expr {$goo(:)}] != {1.0 2.0 3.0 4.0}} {
		return 1
	} elseif {[expr {$foo(:)}] != {1.0 2.0 3.0 4.0}} {
		return 2
	} else {
		return 0
	}
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector split command works correctly when given multiple vector 
# names.
# ------------------------------------------------------------------------------
test vector.split-1.2 {
	::graph::vector split: multiple vector names
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0 5.0 6.0}
} -body {
	foo split goo moo too 
	if {[expr {$goo(:)}] != {1.0 4.0} && [expr {$moo(:)}] != {2.0 5.0} && [expr {$too(:)}] != {3.0 6.0}} {
		return 1
	} elseif {[expr {$foo(:)}] != {1.0 2.0 3.0 4.0 5.0 6.0}} {
		return 2
	} else {
		return 0
	}
} -cleanup {
	::graph::vector destroy foo
	::graph::vector destroy goo
	::graph::vector destroy moo
	::graph::vector destroy too
} -result {0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector split command works correctly when the components of the 
# vector cannot be evenly split into the given number of vector names.
# ------------------------------------------------------------------------------
test vector.split-1.3 {
	::graph::vector split: incorrect number of vector names
} -setup {
	::graph::vector create foo
	foo set {1.0 2.0 3.0 4.0}
} -body {
	if {[catch {foo split goo moo too}]} {
		return 0
	} else {
		return 1
	}
} -cleanup {
	::graph::vector destroy foo
} -result {0}

#===============================================================================
# This part tests the variable function of an instance of the vector
# rbc component.

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector variable command creates a new Tcl variable reference to
# the vector instance 
# ------------------------------------------------------------------------------ 
test vector.variable-1.1 {
    Test vector variable's variable creation
} -setup {
	::graph::vector create Vector1
Vector1 set {1 2 3 4 5}
} -body {
    Vector1 variable VarName 
    expr {$VarName(:)}
} -cleanup {
	::graph::vector destroy Vector1
} -result {1.0 2.0 3.0 4.0 5.0}

# ------------------------------------------------------------------------------
# Purpose: Ensure the vector variable command removes any old Tcl variable reference 
# to the vector instance 
# ------------------------------------------------------------------------------ 
test vector.variable-1.2 {
    Test vector variable existing variable destruction
} -setup {
	::graph::vector create Vector1
    Vector1 set {1 2 3 4 5}
} -body {
    Vector1 variable VarName 
    info exists Vector1
} -cleanup {
	::graph::vector destroy Vector1
} -result {0}

	
cleanupTests
}
catch {namespace delete ::TEST}
# vim: set ts=4 sw=4 sts=4 ff=unix et :
Added tests/tko/tkoPath.test.








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# path.test --
#
package require tcltest
namespace import tcltest::*

namespace eval ::TEST {

proc ::TEST::_setup {} {
    catch {destroy {*}[winfo children .]}
    pack [::path .c -width 60 -height 40 -bd 0 -highlightthickness 0]
    update
}

test path.canvWind-1.1 {
    DisplayWinItem, windows off-screen vertically
} {
    catch {destroy .t}
    toplevel .t
    ::path .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \
	    -relief sunken -xscrollincrement 1 -yscrollincrement 1 \
	    -highlightthickness 1
    pack .t.c -fill both -expand 1 -padx 20 -pady 20
    wm geometry .t +0+0
    set f .t.f
    frame $f -width 80 -height 50 -bg red
    .t.c create window 300 400 -window $f -anchor nw
    .t.c xview moveto .3
    .t.c yview moveto .50
    update
    set x [list [list [winfo ismapped $f] [winfo y $f]]]
    .t.c yview scroll 52 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll 1 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll -255 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll -1 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
} {{1 23} {1 -29} {0 -29} {1 225} {0 225}}

test path.canvWind-1.2 {
    DisplayWinItem, windows off-screen vertically
} {
    catch {destroy .t}
    toplevel .t
    ::path .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \
	    -relief sunken -xscrollincrement 1 -yscrollincrement 1 \
	    -highlightthickness 1
    pack .t.c -fill both -expand 1 -padx 20 -pady 20
    wm geometry .t +0+0
    set f .t.c.f
    frame $f -width 80 -height 50 -bg red
    .t.c create window 300 400 -window $f -anchor nw
    .t.c xview moveto .3
    .t.c yview moveto .50
    update
    set x [list [list [winfo ismapped $f] [winfo y $f]]]
    .t.c yview scroll 52 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll 1 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll -255 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
    .t.c yview scroll -1 units
    update
    lappend x [list [winfo ismapped $f] [winfo y $f]]
} {{1 3} {1 -49} {0 -49} {1 205} {0 205}}

test path.canvWind-1.3 {
    DisplayWinItem, windows off-screen horizontally
} {
    catch {destroy .t}
    toplevel .t
    ::path .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \
	    -relief sunken -xscrollincrement 1 -yscrollincrement 1 \
	    -highlightthickness 1
    pack .t.c -fill both -expand 1 -padx 20 -pady 20
    wm geometry .t +0+0
    set f .t.f
    frame $f -width 80 -height 50 -bg red
    .t.c create window 300 400 -window $f -anchor nw
    .t.c xview moveto .3
    .t.c yview moveto .50
    update
    set x [list [list [winfo ismapped $f] [winfo x $f]]]
    .t.c xview scroll 82 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll 1 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll -335 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll -1 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
} {{1 23} {1 -59} {0 -59} {1 275} {0 275}}

test path.canvWind-1.4 {
    DisplayWinItem, windows off-screen horizontally
} {
    catch {destroy .t}
    toplevel .t
    ::path .t.c -scrollregion {0 0 1000 800} -width 250 -height 200 -bd 2 \
	    -relief sunken -xscrollincrement 1 -yscrollincrement 1 \
	    -highlightthickness 1
    pack .t.c -fill both -expand 1 -padx 20 -pady 20
    wm geometry .t +0+0
    set f .t.c.f
    frame $f -width 80 -height 50 -bg red
    .t.c create window 300 400 -window $f -anchor nw
    .t.c xview moveto .3
    .t.c yview moveto .50
    update
    set x [list [list [winfo ismapped $f] [winfo x $f]]]
    .t.c xview scroll 82 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll 1 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll -335 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
    .t.c xview scroll -1 units
    update
    lappend x [list [winfo ismapped $f] [winfo x $f]]
} {{1 3} {1 -79} {0 -79} {1 255} {0 255}}
catch {destroy .t}

test path.canvas-1.1 {
    configuration options: good value for -background
} -setup {
    ::TEST::_setup
} -body {
	.c configure -background #ff0000
	lindex [.c configure -background] 4
} -result #ff0000

test path.canvas-1.2 {
    configuration options: bad value for -background
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -background non-existent
} -result {*: unknown color name "non-existent"}

test path.canvas-1.3 {
    configuration options: good value for -bg
} -setup {
    ::TEST::_setup
} -body {
	.c configure -bg #ff0000
	lindex [.c configure -bg] 4
} -result #ff0000

test path.canvas-1.4 {
    configuration options: bad value for -bg
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -bg non-existent
} -result {*: unknown color name "non-existent"}

test path.canvas-1.5 {
    configuration options: good value for -borderwidth
} -setup {
    ::TEST::_setup
} -body {
	.c configure -borderwidth 5
	lindex [.c configure -borderwidth] 4
} -result 5

test path.canvas-1.6 {
    configuration options: bad value for -borderwidth
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -borderwidth badValue
} -result {*: bad screen distance "badValue"}

test path.canvas-1.7 {
    configuration options: good value for -bd
} -setup {
    ::TEST::_setup
} -body {
	.c configure -bd 5
	lindex [.c configure -bd] 4
} -result 5

test path.canvas-1.8 {
    configuration options: bad value for -bd
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -bd badValue
} -result {*: bad screen distance "badValue"}

test path.canvas-1.9 {
    configuration options: good value for -closeenough
} -setup {
    ::TEST::_setup
} -body {
	.c configure -closeenough 24
	lindex [.c configure -closeenough] 4
} -result 24.0

test path.canvas-1.10 {
    configuration options: bad value for -closeenough
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -closeenough bogus
} -result {*: expected floating-point number but got "bogus"}

test path.canvas-1.11 {
    configuration options: good value for -confine
} -setup {
    ::TEST::_setup
} -body {
	.c configure -confine true
	lindex [.c configure -confine] 4
} -result 1

test path.canvas-1.12 {
    configuration options: bad value for -confine
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -confine silly
} -result {*: expected boolean value but got "silly"}

test path.canvas-1.13 {
    configuration options: good value for -cursor
} -setup {
    ::TEST::_setup
} -body {
	.c configure -cursor arrow
	lindex [.c configure -cursor] 4
} -result arrow

test path.canvas-1.14 {
    configuration options: bad value for -cursor
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -cursor badValue
} -result {*: bad cursor spec "badValue"}

test path.canvas-1.15 {
    configuration options: good value for -height
} -setup {
    ::TEST::_setup
} -body {
	.c configure -height 2.1
	lindex [.c configure -height] 4
} -result 2

test path.canvas-1.16 {
    configuration options: bad value for -height
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -height x42
} -result {*: bad screen distance "x42"}

test path.canvas-1.17 {
    configuration options: good value for -highlightbackground
} -setup {
    ::TEST::_setup
} -body {
	.c configure -highlightbackground #112233
	lindex [.c configure -highlightbackground] 4
} -result #112233

test path.canvas-1.18 {
    configuration options: bad value for -highlightbackground
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -highlightbackground ugly
} -result {*: unknown color name "ugly"}

test path.canvas-1.19 {
    configuration options: good value for -highlightcolor
} -setup {
    ::TEST::_setup
} -body {
	.c configure -highlightcolor #110022
	lindex [.c configure -highlightcolor] 4
} -result #110022

test path.canvas-1.20 {
    configuration options: bad value for -highlightcolor
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -highlightcolor bogus
} -result {*: unknown color name "bogus"}

test path.canvas-1.21 {
    configuration options: good value for -highlightthickness
} -setup {
    ::TEST::_setup
} -body {
	.c configure -highlightthickness 18
	lindex [.c configure -highlightthickness] 4
} -result 18

test path.canvas-1.22 {
configuration options: bad value for -highlightthickness
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -highlightthickness badValue
} -result {*: bad screen distance "badValue"}

test path.canvas-1.23 {
    configuration options: good value for -insertbackground
} -setup {
    ::TEST::_setup
} -body {
	.c configure -insertbackground #110022
	lindex [.c configure -insertbackground] 4
} -result #110022

test path.canvas-1.24 {
    configuration options: bad value for -insertbackground
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -insertbackground bogus
} -result {*: unknown color name "bogus"}

test path.canvas-1.25 {
    configuration options: good value for -insertborderwidth
} -setup {
    ::TEST::_setup
} -body {
	.c configure -insertborderwidth 1.3
	lindex [.c configure -insertborderwidth] 4
} -result 1

test path.canvas-1.26 {
    configuration options: bad value for -insertborderwidth
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -insertborderwidth 2.6x
} -result {*: bad screen distance "2.6x"}

test path.canvas-1.27 {
    configuration options: good value for -insertofftime
} -setup {
    ::TEST::_setup
} -body {
	.c configure -insertofftime 100
	lindex [.c configure -insertofftime] 4
} -result 100

test path.canvas-1.28 {
    configuration options: bad value for -insertofftime
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -insertofftime 3.2
} -result {*: expected integer but got "3.2"}

test path.canvas-1.29 {
    configuration options: good value for -insertontime
} -setup {
    ::TEST::_setup
} -body {
	.c configure -insertofftime 10
	lindex [.c configure -insertofftime] 4
} -result 10

test path.canvas-1.30 {
    configuration options: bad value for -insertontime
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -insertofftime 3.5
} -result {*: expected integer but got "3.5"}

test path.canvas-1.31 {
    configuration options: good value for -insertwidth
} -setup {
    ::TEST::_setup
} -body {
	.c configure -insertwidth 1.3
	lindex [.c configure -insertwidth] 4
} -result 1

test path.canvas-1.32 {
    configuration options: bad value for -insertwidth
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -insertwidth 6x
} -result {*: bad screen distance "6x"}

test path.canvas-1.33 {
    configuration options: good value for -relief
} -setup {
    ::TEST::_setup
} -body {
	.c configure -relief groove
	lindex [.c configure -relief] 4
} -result groove

test path.canvas-1.34 {
    configuration options: bad value for -relief
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -relief 1.5
} -result {*: bad relief "1.5": must be flat, groove, raised, ridge, solid, or sunken}

test path.canvas-1.35 {
    configuration options: good value for -selectbackground
} -setup {
    ::TEST::_setup
} -body {
	.c configure -selectbackground #110022
	lindex [.c configure -selectbackground] 4
} -result #110022

test path.canvas-1.36 {
    configuration options: bad value for -selectbackground
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -selectbackground bogus
} -result {*: unknown color name "bogus"}

test path.canvas-1.37 {
    configuration options: good value for -selectborderwidth
} -setup {
    ::TEST::_setup
} -body {
	.c configure -selectborderwidth 1.3
	lindex [.c configure -selectborderwidth] 4
} -result 1

test path.canvas-1.38 {
    configuration options: bad value for -selectborderwidth
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -selectborderwidth badValue
} -result {*: bad screen distance "badValue"}

test path.canvas-1.39 {
    configuration options: good value for -selectforeground
} -setup {
    ::TEST::_setup
} -body {
	.c configure -selectforeground #654321
	lindex [.c configure -selectforeground] 4
} -result #654321

test path.canvas-1.40 {
    configuration options: bad value for -selectforeground
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -selectforeground bogus
} -result {*: unknown color name "bogus"}

test path.canvas-1.41 {
    configuration options: good value for -takefocus
} -setup {
    ::TEST::_setup
} -body {
	.c configure -takefocus "any string"
	lindex [.c configure -takefocus] 4
} -result "any string"

test path.canvas-1.42 {
    configuration options: good value for -width
} -setup {
    ::TEST::_setup
} -body {
	.c configure -width 402
	lindex [.c configure -width] 4
} -result 402

test path.canvas-1.43 {
    configuration options: bad value for -width
} -returnCodes error -match glob -setup {
    ::TEST::_setup
} -body {
    .c configure -width xyz
} -result {*: bad screen distance "xyz"}

test path.canvas-1.44 {
    configuration options: good value for -xscrollcommand
} -setup {
    ::TEST::_setup
} -body {
	.c configure -xscrollcommand "some command"
	lindex [.c configure -xscrollcommand] 4
} -result "some command"

test path.canvas-1.45 {
    configuration options: good value for -yscrollcommand
} -setup {
    ::TEST::_setup
} -body {
	.c configure -yscrollcommand "other command"
	lindex [.c configure -yscrollcommand] 4
} -result "other command"

test path.canvas-1.46 {
    configure throws error on bad option
} -setup {
    ::TEST::_setup
} -body {
    set res [list [catch {.c configure -gorp foo}]]
    .c create rect 10 10 100 100
    lappend res [catch {.c configure -gorp foo}]
    set res
} -result [list 1 1]

#
# Path widget commands
#

test path.canvas-2.1 {
    CanvasWidgetCmd, bind option
} -setup {
    ::TEST::_setup
} -body {
    set i [.c create rect 10 10 100 100]
    list [catch {.c bind $i <a>} msg] $msg
} -result {0 {}}

test path.canvas-2.2 {
    CanvasWidgetCmd, bind option
} -setup {
    ::TEST::_setup
} -body {
    set i [.c create rect 10 10 100 100]
    list [catch {.c bind $i <} msg] $msg
} -result {1 {no event type or button # or keysym}}

test path.canvas-2.3 {
    CanvasWidgetCmd, xview option
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 60 -height 40 -scrollregion {0 0 200 150} -bd 0 \
	-highlightthickness 0
    .c configure -xscrollincrement 40 -yscrollincrement 5
    .c xview moveto 0
    update
    set x [list [.c xview]]
    .c xview scroll 2 units
    update
    lappend x [.c xview]
} -result {{0.0 0.3} {0.4 0.7}}

test path.canvas-2.4 {
    CanvasWidgetCmd, xview option
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 60 -height 40 -scrollregion {0 0 200 150} -bd 0 \
	-highlightthickness 0
    # This test gives slightly different results on platforms such
    # as NetBSD.  I don't know why...
    .c configure -xscrollincrement 0 -yscrollincrement 5
    .c xview moveto 0.6
    update
    set x [list [.c xview]]
    .c xview scroll 2 units
    update
    lappend x [.c xview]
} -result {{0.6 0.9} {0.66 0.96}}

test path.canvas-3.1 {
    CanvasWidgetCmd, yview option
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 60 -height 40 -scrollregion {0 0 200 80} \
	-borderwidth 0 -highlightthickness 0
    .c configure -xscrollincrement 40 -yscrollincrement 5
    .c yview moveto 0
    update
    set x [list [.c yview]]
    .c yview scroll 3 units
    update
    lappend x [.c yview]
} -result {{0.0 0.5} {0.1875 0.6875}}

test path.canvas-3.2 {
    CanvasWidgetCmd, yview option
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 60 -height 40 -scrollregion {0 0 200 80} \
	-borderwidth 0 -highlightthickness 0
    .c configure -xscrollincrement 40 -yscrollincrement 0
    .c yview moveto 0
    update
    set x [list [.c yview]]
    .c yview scroll 2 units
    update
    lappend x [.c yview]
} -result {{0.0 0.5} {0.1 0.6}}

test path.canvas-4.1 {
    ButtonEventProc procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -bg #543210
    rename .c .c2
    set x {}
    lappend x [winfo children .]
    lappend x [.c2 cget -bg]
    destroy .c
    lappend x [info command .c*] [winfo children .]
} -result {.c #543210 {} {}}

test path.canvas-5.1 {
    ButtonCmdDeletedProc procedure
} -setup {
    ::TEST::_setup
} -body {
    rename .c {}
    list [info command .c*] [winfo children .]
} -result {{} {}}

test path.canvas-6.1 {
    CanvasSetOrigin procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    .c configure -xscrollincrement 0 -yscrollincrement 0 \
	-width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    update
    .c xview moveto 0
    .c yview moveto 0
    update
    list [.c canvasx 0] [.c canvasy 0]
} -result {-205.0 -105.0}

test path.canvas-6.2 {
    CanvasSetOrigin procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    .c configure -xscrollincrement 20 -yscrollincrement 10
    set x ""
    foreach i {.08 .10 .48 .50} {
	.c xview moveto $i
	update
	lappend x [.c canvasx 0]
    }
    set x
} -result {-165.0 -145.0 35.0 55.0}

test path.canvas-6.3 {
    CanvasSetOrigin procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    .c configure -xscrollincrement 20 -yscrollincrement 10
    set x ""
    foreach i {.06 .08 .70 .72} {
	.c yview moveto $i
	update
	lappend x [.c canvasy 0]
    }
    set x
} -result {-95.0 -85.0 35.0 45.0}

test path.canvas-6.4 {
    CanvasSetOrigin procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    .c configure -xscrollincrement 20 -yscrollincrement 10
    update
    .c xview moveto 1.0
    .c canvasx 0
} -result {215.0}

test path.canvas-6.5 {
    CanvasSetOrigin procedure
} -setup {
    ::TEST::_setup
} -body {
    .c configure -width 100 -height 50 -scrollregion {-200 -100 305 102} \
	-borderwidth 2 -highlightthickness 3
    .c configure -xscrollincrement 20 -yscrollincrement 10
    update
    .c yview moveto 1.0
    .c canvasy 0
} -result {55.0}

test path.canvas-7.1 {
    canvas widget vs hidden commands
} -setup {
    ::TEST::_setup
} -body {
    set l [lsort [interp hidden]]
    interp hide {} .c
    destroy .c
    list [winfo children .] [string compare [lsort [interp hidden]] $l]
} -result [list {} 0]

test path.canvas-9.1 {
    canvas id creation and deletion
} -setup {
    ::TEST::_setup
} -body {
    # With Tk 8.0.4 the ids are now stored in a hash table.  You
    # can use this test as a performance test with older versions
    # by changing the value of size.
    set size 15
    for {set i 0} {$i < $size} {incr i} {
	set x [expr {-10 + 3*$i}]
	for {set j 0; set y -10} {$j < 10} {incr j; incr y 3} {
	    .c create rect ${x}c ${y}c [expr $x+2]c [expr $y+2]c \
		    -stroke black -fill blue -tags rect
	    .c create text [expr $x+1]c [expr $y+1]c -text "$i,$j" \
		    -textanchor middle -tags text
	}
    }
    # The actual bench mark - this code also exercises all the hash
    # table changes.
    set time [lindex [time {
	foreach id [.c find withtag all] {
	    .c lower $id
	    .c raise $id
	    .c find withtag $id
	    .c bind <Return> $id {}
	    .c delete $id
	}
    }] 0]
    set x ""
} -result {}

test path.canvas-10.1 {
    find items using tag expressions
} -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 60 -r 10 -fill yellow -tag [list b a]
    .c create circle 20 100 -r 10 -fill green -tag [list c b]
    .c create circle 20 140 -r 10 -fill blue -tag [list b]
    .c create circle 20 180 -r 10 -fill bisque -tag [list a d e]
    .c create circle 20 220 -r 10 -fill bisque -tag b
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    set res {}
    lappend res [.c find withtag {!a}]
    lappend res [.c find withtag {b&&c}]
    lappend res [.c find withtag {b||c}]
    lappend res [.c find withtag {a&&!b}]
    lappend res [.c find withtag {!b&&!c}]
    lappend res [.c find withtag {d&&a&&c&&b}]
    lappend res [.c find withtag {b^a}]
    lappend res [.c find withtag {(a&&!b)||(!a&&b)}]
    lappend res [.c find withtag { ( a && ! b ) || ( ! a && b ) }]
    lappend res [.c find withtag {a&&!(c||d)}]
    lappend res [.c find withtag {d&&"tag with spaces"}]
    lappend res [.c find withtag "tag with spaces"]
} -result {{0 3 4 6 7} {1 3} {1 2 3 4 6} 5 {0 5 7} 1 {3 4 5 6} {3 4 5 6} {3 4 5 6} 2 7 7}

test path.canvas-10.2 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {&&c}
} -result {Unexpected operator in tag search expression}

test path.canvas-10.3 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {!!c}
} -result {Too many '!' in tag search expression} \

test path.canvas-10.4 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {b||}
} -result {Missing tag in tag search expression}

test path.canvas-10.5 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {b&&(c||)}
} -result {Unexpected operator in tag search expression}

test path.canvas-10.6 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {d&&""}
} -result {Null quoted tag string in tag search expression}

test path.canvas-10.7 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag "d&&\"tag with spaces"
} -result {Missing endquote in tag search expression} \

test path.canvas-10.8 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {a&&"tag with spaces"z}
} -result {Invalid boolean operator in tag search expression}

test path.canvas-10.9 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {a&&b&c}
} -result {Singleton '&' in tag search expression}

test path.canvas-10.10 {
    check errors from tag expressions
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list a b c d]
    .c create circle 20 260 -r 10 -fill bisque -tag [list d "tag with spaces"]
    .c find withtag {a||b|c}
} -result {Singleton '|' in tag search expression}

test path.canvas-10.11 {
    backward compatility, strange tags that are not expressions
} -setup {
    ::TEST::_setup
} -body {
    .c create circle 20 20 -r 10 -fill red -tag [list { strange tag(xxx&yyy|zzz) " && \" || ! ^ " }]
    .c find withtag { strange tag(xxx&yyy|zzz) " && \" || ! ^ " }
} -result 1

test path.canvas-10.12 {
    multple events bound to same tag expr
} -setup {
    ::TEST::_setup
} -body {
    .c bind {a && b} <Enter> {puts Enter}
    .c bind {a && b} <Leave> {puts Leave}
} -result {}

test path.canvas-11.2 {
    canvas polygon overlap fill check, bug 226357
} -setup {
    ::TEST::_setup
} -body {
    set result {}
    set id [.c create polygon 30 30 90 90 30 90 90 30 -fill black]
    lappend result [.c find over 40 40 45 45]; # rect region inc. edge
    lappend result [.c find over 60 40 60 40]; # top-center point
    lappend result [.c find over 0 0 0 0]; # not on poly
    lappend result [.c find over 60 60 60 60]; # center-point
    lappend result [.c find over 45 50 45 50]; # outside poly
    .c itemconfigure $id -fill "" -stroke black
    lappend result [.c find over 40 40 45 45]; # rect region inc. edge
    lappend result [.c find over 60 40 60 40]; # top-center point
    lappend result [.c find over 0 0 0 0]; # not on poly
    lappend result [.c find over 60 60 60 60]; # center-point
    lappend result [.c find over 45 50 45 50]; # outside poly
    .c itemconfigure $id -strokewidth 8
    lappend result [.c find over 45 50 45 50]; # outside poly
} -result {1 1 {} 1 {} 1 {} {} 1 {} 1}

test path.canvas-12.1 {
    canvas mm obj, patch SF-403327, 102471
} -setup {
    ::TEST::_setup
} -body {
    set qx [expr {1.+1.}] 
    # qx has type double and no string representation 
    .c scale all $qx 0 1. 1.
    # qx has now type MMRep and no string representation 
    list $qx [string length $qx]
} -result {2.0 3}

test path.canvas-12.2 {
    canvas mm obj, patch SF-403327, 102471
} -setup {
    ::TEST::_setup
} -body {
    set val 10
    incr val
    # qx has type double and no string representation 
    .c scale all $val 0 1 1
    # qx has now type MMRep and no string representation 
    incr val
} -result 12 

test path.canvas-13.1 {
    canvas delete during event, SF bug-228024
} -setup {
    ::TEST::_setup
} -body {
    proc ::TEST::_kill_canvas {w} {
        destroy $w
        pack [::path $w -height 200 -width 200] -fill both -expand yes
        update idle
        $w create rect 80 80 120 120 -fill blue -tags blue
        # bind a button press to re-build the canvas
        $w bind blue <ButtonRelease-1> [subst {
	        [lindex [info level 0] 0] $w
	        append ::x ok
        }]
    }
    ::TEST::_kill_canvas .c
    set ::x {}
    # do this many times to improve chances of triggering the crash
    for {set i 0} {$i < 30} {incr i} {
	    event generate .c <1> -x 100 -y 100
	    event generate .c <ButtonRelease-1> -x 100 -y 100
    }
    rename ::TEST::_kill_canvas {}
    set ::x
} -result okokokokokokokokokokokokokokokokokokokokokokokokokokokokokok

test path.canvas-14.1 {
    canvas scan SF bug 581560
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c scan
} -result {wrong # args: should be ".c scan mark|dragto x y ?dragGain?"}

test path.canvas-14.2 {
    canvas scan
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c scan bogus
} -result {wrong # args: should be ".c scan mark|dragto x y ?dragGain?"}

test path.canvas-14.3 {
    canvas scan
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c scan mark
} -result {wrong # args: should be ".c scan mark|dragto x y ?dragGain?"}

test path.canvas-14.4 {
    canvas scan
} -setup {
    ::TEST::_setup
} -body {
    .c scan mark 10 10
} -result {}

test path.canvas-14.5 {
    canvas scan
} -returnCodes error -setup {
    ::TEST::_setup
} -body {
    .c scan mark 10 10 5
} -result {wrong # args: should be ".c scan mark x y"}

test path.canvas-14.6 {
    canvas scan
} -setup {
    ::TEST::_setup
} -body {
    .c scan dragto 10 10 5
} -result {}

set i 0
foreach type {image line circle ellipse polygon rect text window} {
    incr i
    test path.canvas-15.$i "basic types check: $type requires coords" \
-setup ::TEST::_setup \
-returnCodes error \
-result "wrong # args: should be \".c create $type coords ?arg arg ...?\"" \
-body {
    .c create $type
}
    incr i
    test path.canvas-15.$i "basic coords check: $type coords are paired" \
-setup ::TEST::_setup \
-match glob \
-returnCodes error \
-result "wrong # coordinates: expected*" \
-body {
    .c create $type 0
}
}

test path.gradientslave-1.1 {
    Destroy slave
} -body {
    interp create slavei
    slavei eval {
        package require Tk
    }
    interp delete slavei
} -result {}

test path.gradientslave-1.2 {
    Shared gradients inside slave
} -body {
    set masterg [path::gradient create radial \
                -stops [list \
                           {0 white 0.9}  [list 1 red4 0.4]] \
                -radialtransition {
                    0.477551020408 0.540983606557
                    1.00918367347 0.898979591837
                    0.139344262295}]
    interp create slavei
    slavei eval {
        package require Tk
    }
    set myRet [string compare [path::gradient names] $masterg]
    interp delete slavei
    set myRet
} -result 0

# Testcase for image "move".
# ----------------------------------------------------------------
# Author : Arndt Roger Schneider
# Date   : 09/22/2007
# License: Tcl-License (aka BSD)
#
# Copyright © 2007 Arndt Roger Schneider
# ----------------------------------------------------------------
image create photo _oval -data {
R0lGODlhIQAZAPcAMf//////////////9///9//39//39//39/f///f///f/
9/f/9/f3//f3//f39/f39/f37/f37/fv9/fv9/fv7/fv7/fv7/fv3vfv3vfv
3u/39+/39+/v9+/v9+/v7+/v7+/v5+/v5+/v3u/v3u/v3u/v1u/v1u/vzu/v
zu/n7+/n7+/n7+/n5+/n5+/nve/nve/eve/eve/Wre/Wrefv7+fv7+fv5+fv
5+fn7+fn7+fn5+fn5+fn5+fWxufWxufWxufWvefWvefWvefOpefOpefGlOfG
lOfGlOe9jOe9jOe9jN7v997v997v797v79bW1tbW1tala9ala9ala87n787n
787n587n587Ozs7Ozs7Ozs7Oxs7Oxs7Gxs7Gxs6tjM6tjM6lY86lY8bn98bn
98bOzsbOzsbOxsbOxsbGzsbGzsbGzsbGxsbGxsbGvcbGvcbGvcale8ale73n
973n973n773n773Gxr3Gxr29vb29vb29vb2le72le72le72MUr2MUr2MUrW1
tbW1tbW1rbW1rbWcjLWcjLWMY7WMY7WMY63e763e763e7621ta21ta1zKa1z
Ka1zKaW9zqW9zqW9zqWttaWttaWlpaWlpaWlpZzO55zO55ycnJycnJyUe5yU
e5yEa5yEa5yEa5TO55TO55S1xpS1xpSUlJSUlJRKAJRKAJQ5AJQ5AIS954S9
54S93oS93oRjSoRjSoRjSoQpAIQpAHO11nO11nOt1nOt1nOt1nMAAHMAAGuE
nGuEnGuEnGOUxmOUxmOUxmMAAGMAAGMAAFpzjFpzjFpzjFo5AFo5AFo5AFKM
vVKMvVKMvUp7pUp7pUpje0pje0oAAEoAADlrlDlrlDlrlDkpADkpADkAKTkA
KTkAKTkAADkAACl7vSl7vSlrrSlrrSlrrSljjCljjCljjCkAACkAACkAAABj
pQBjpQBKlABKlABKlAA5cwA5cwA5WgA5WgAAawAAawAAawAAUgAAUgAAKQAA
KQAAKQAAAAAAAAAAAAAAACwAAAAAIQAZAAAI/wABAPCApaDBgwgTJvQgEACm
TnmwuLkzsSLFixYzUsyTp1MnAFg+AuDQUELDkygBmEzpoVPBPAAolJxpsqbK
mzhJCoyIBaaGmAJNMgTwc+BNCDiHMpQgkaIGmQyjCmRIwYOHJlaJImUIQSpP
mBygDuzK0I2sf2j/ybOkQUNUoQPv9MSS1aoHCQw1/PmXz5cjS1+U/YNXZ6AE
CmQBfPXQlUNXCBw8QPoHzTHJJhC+/LtXx7EHyx6+Rmbswa0HJP+aCrRrV4a3
dXbJhn7J2q6IWu0gYK1tNcq/TbwX83bhChZv1heI5QpOmzcMdIuO22YFjjVW
jhytPvEgAquLbXWwdtTnLr6JCOra7Qonz90KNeNPIo/vLqIHsVt2t892k8fD
dvEeUKAKPLvNt1sYv/mX31dPUKDfdiIUQRkH5ZH3hTfgGGgVR3f0lx97iPxj
Cl0QNhHHP/RgUR59DCp4lYt8oHWMJZh8Qo2IVJA33nYc8acghA960MMn2aQl
zSRYPWFeE+b5J9x2QUKZnoI7cidlHnJh8mN6UroIpXlRXsVTJ1KGWSZ3VCq5
5TFuSOARJhxhASd2HBFCpyV5uIFnndh18kVDIrwkKE9yzeUGFoVGdOhcTZgU
EAA7LA==} -gamma 1.0

# The TestCase itself:
test path.image-1.1 {
    move 10 10
} -setup {
    ::TEST::_setup
} -body {
    set id [.c create image 100 100 -image _oval]
    .c move $id 10 10
    .c coords $id
} -result {110.0 110.0}

test path.image-1.2 {
    coords 10 10
} -setup {
    ::TEST::_setup
} -body {
    set id [.c create image 100 100 -image _oval]
    .c coords $id 110.0 110.0
    .c coords $id
} -result {110.0 110.0}

test path.line-1.1 {
    line coords
} -setup {
    ::TEST::_setup
} -body {
    lassign [.c coords [.c create line 200 201 250 202]] l t r b
    return [list \
               [expr { round($l) }] \
               [expr { round($t) }] \
               [expr { round($r) }] \
               [expr { round($b) }]]

} -result {200 201 250 202}

test path.line-1.2 {
    line {coords after move}
} -setup {
    ::TEST::_setup
} -body {
    set line [.c create line 200 201 250 202]
    .c move $line 20 20
    lassign [.c coords $line] l t r b
    return [list \
               [expr { round($l) }] \
               [expr { round($t) }] \
               [expr { round($r) }] \
               [expr { round($b) }]]

} -result {220 221 270 222}

test path.line-1.3 {
    line {Strokedash as .}
} -setup {
    ::TEST::_setup
} -body {
    set line [.c create line 200 201 250 202 -strokedash {0.1 0.2}]
    return {}
} -result {}

test path.polyline-1.1 {
    polyline coords
} -setup {
    ::TEST::_setup
} -body { 
    .c coords [.c create polyline 12 20 34 5 90 56] 
} -result {12.0 20.0 34.0 5.0 90.0 56.0}

test path.polygon-1.1 {
    polygon coords
} -setup {
    ::TEST::_setup
} -body { 
    .c coords [.c create polygon 12 20 34 5 90 56 -fill red] 
} -result {12.0 20.0 34.0 5.0 90.0 56.0}

# cleanup
::tcltest::cleanupTests
catch {destroy {*}[winfo children .]}
}
catch {namespace delete ::TEST}
# vim: set ts=4 sw=4 sts=4 ff=unix et :
Changes to unix/Makefile.in.
144
145
146
147
148
149
150

151

152
153
154
155
156
157

158

159
160
161
162
163
164
165
144
145
146
147
148
149
150
151

152
153
154
155
156
157
158
159

160
161
162
163
164
165
166
167







+
-
+






+
-
+







LDFLAGS_OPTIMIZE	= @LDFLAGS_OPTIMIZE@
LDFLAGS			= @LDFLAGS_DEFAULT@ @LDFLAGS@

# A "-I" switch that can be used when compiling to make all of the
# X11 include files accessible (the configure script will try to
# set this value, and will cause it to be an empty string if the
# include files are accessible via /usr/include).
#RZ TODO add search for cairo lib to configure
X11_INCLUDES		= @XINCLUDES@
X11_INCLUDES		= @XINCLUDES@ -I/usr/include/cairo

AQUA_INCLUDES		= -I$(MAC_OSX_DIR) -I$(XLIB_DIR)

# Linker switch(es) to use to link with the X11 library archive (the
# configure script will try to set this value automatically, but you
# can override it).
#RZ TODO add search for cairo lib to configure
X11_LIB_SWITCHES	= $(XFT_LIBS) @XLIBSW@
X11_LIB_SWITCHES	= $(XFT_LIBS) @XLIBSW@ -lcairo


# To turn off the security checks that disallow incoming sends when
# the X server appears to be insecure, reverse the comments on the
# following lines:
SECURITY_FLAGS		=
#SECURITY_FLAGS		= -DTK_NO_SECURITY
304
305
306
307
308
309
310

311
312
313
314
315
316
317
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320







+







AC_FLAGS		= @DEFS@
AR			= @AR@
RANLIB			= @RANLIB@
SRC_DIR			= @srcdir@
TOP_DIR			= $(SRC_DIR)/..
GENERIC_DIR		= $(TOP_DIR)/generic
TTK_DIR			= $(GENERIC_DIR)/ttk
TKO_DIR			= $(GENERIC_DIR)/tko
UNIX_DIR		= $(TOP_DIR)/unix
BMAP_DIR		= $(TOP_DIR)/bitmaps
TOOL_DIR		= @TCL_SRC_DIR@/tools
TEST_DIR		= $(TOP_DIR)/tests
MAC_OSX_DIR		= $(TOP_DIR)/macosx
XLIB_DIR		= $(TOP_DIR)/xlib

377
378
379
380
381
382
383

















































384
385
386
387
388
389
390
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







	ttkDefaultTheme.o ttkElements.o ttkEntry.o ttkFrame.o ttkImage.o \
	ttkInit.o ttkLabel.o ttkLayout.o ttkManager.o ttkNotebook.o \
	ttkPanedwindow.o ttkProgress.o ttkScale.o ttkScrollbar.o ttkScroll.o \
	ttkSeparator.o ttkSquare.o ttkState.o \
	ttkTagSet.o ttkTheme.o ttkTrace.o ttkTrack.o ttkTreeview.o \
	ttkWidget.o ttkStubInit.o

TKO_OBJS = \
	tkoWidget.o \
	tkoFrame.o \
	tkoRbcBind.o \
	tkoRbcChain.o \
	tkoRbcImage.o \
	tkoRbcParse.o \
	tkoRbcPs.o \
	tkoRbcSpline.o \
	tkoRbcSwitch.o \
	tkoRbcText.o \
	tkoRbcTile.o \
	tkoRbcUtil.o \
	tkoRbcWindow.o \
	tkoRbcUnixImage.o \
	tkoVectorMath.o \
	tkoVectorObjCmd.o \
	tkoVector.o \
	tkoGraph.o \
	tkoGraphConfig.o \
	tkoGraphAxis.o \
	tkoGraphBar.o \
	tkoGraphElem.o \
	tkoGraphGrid.o \
	tkoGraphHairs.o \
	tkoGraphLegd.o \
	tkoGraphLine.o \
	tkoGraphMarker.o \
	tkoGraphMisc.o \
	tkoGraphPen.o \
	tkoGraphPs.o \
	tkoPath.o \
	tkoPathCanvArrow.o \
	tkoPathCanvEllipse.o \
	tkoPathCanvGroup.o \
	tkoPathCanvImage.o \
	tkoPathCanvLine.o \
	tkoPathCanvPath.o \
	tkoPathCanvPoly.o \
	tkoPathCanvRect.o \
	tkoPathCanvText.o \
	tkoPathCanvWindow.o \
	tkoPathGeneric.o \
	tkoPathGradient.o \
	tkoPathStyle.o \
	tkoPathSurface.o \
	tkoPathUtil.o \
	tkoPath_UnixCairo.o \

STUB_OBJS = tkStubInit.o

STUB_LIB_OBJS = tkStubLib.o ttkStubLib.o

X11_OBJS = tkUnix.o tkUnix3d.o tkUnixButton.o tkUnixColor.o tkUnixConfig.o \
	tkUnixCursor.o tkUnixDraw.o tkUnixEmbed.o tkUnixEvent.o \
	tkUnixFocus.o  $(FONT_OBJS) tkUnixInit.o tkUnixKey.o tkUnixMenu.o \
403
404
405
406
407
408
409
410

411
412
413
414
415
416
417
455
456
457
458
459
460
461

462
463
464
465
466
467
468
469







-
+







	tkFileFilter.o tkMacWinMenu.o tkPointer.o tkUnix3d.o tkUnixScale.o \
	xcolors.o xdraw.o xgc.o ximage.o xutil.o \
	ttkMacOSXTheme.o

AQUA_TKTEST_OBJS = tkMacOSXTest.o

OBJS =  $(GENERIC_OBJS) $(WIDG_OBJS) $(CANV_OBJS) $(IMAGE_OBJS) $(TEXT_OBJS) \
	$(STUB_OBJS) $(TTK_OBJS) \
	$(STUB_OBJS) $(TTK_OBJS) $(TKO_OBJS) \
	$(@TK_WINDOWINGSYSTEM@_OBJS) @PLAT_OBJS@

TK_DECLS = \
	$(GENERIC_DIR)/tk.decls \
	$(GENERIC_DIR)/tkInt.decls

TTK_DECLS = \
489
490
491
492
493
494
495

















































496
497
498
499
500
501
502
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







	$(TTK_DIR)/ttkTrack.c \
	$(TTK_DIR)/ttkTreeview.c \
	$(TTK_DIR)/ttkWidget.c

TTK_STUB_SRCS = \
	$(TTK_DIR)/ttkStubInit.c $(TTK_DIR)/ttkStubLib.c

TKO_SRCS = \
	$(TKO_DIR)\tkoWidget.c \
	$(TKO_DIR)\tkoFrame.c \
	$(TKO_DIR)\tkoRbcBind.c \
	$(TKO_DIR)\tkoRbcChain.c \
	$(TKO_DIR)\tkoRbcImage.c \
	$(TKO_DIR)\tkoRbcParse.c \
	$(TKO_DIR)\tkoRbcPs.c \
	$(TKO_DIR)\tkoRbcSpline.c \
	$(TKO_DIR)\tkoRbcSwitch.c \
	$(TKO_DIR)\tkoRbcText.c \
	$(TKO_DIR)\tkoRbcTile.c \
	$(TKO_DIR)\tkoRbcUtil.c \
	$(TKO_DIR)\tkoRbcWindow.c \
	$(TKO_DIR)\tkoRbcUnixImage.c \
	$(TKO_DIR)\tkoVectorMath.c \
	$(TKO_DIR)\tkoVectorObjCmd.c \
	$(TKO_DIR)\tkoVector.c \
	$(TKO_DIR)\tkoGraph.c \
	$(TKO_DIR)\tkoGraphConfig.c \
	$(TKO_DIR)\tkoGraphAxis.c \
	$(TKO_DIR)\tkoGraphBar.c \
	$(TKO_DIR)\tkoGraphElem.c \
	$(TKO_DIR)\tkoGraphGrid.c \
	$(TKO_DIR)\tkoGraphHairs.c \
	$(TKO_DIR)\tkoGraphLegd.c \
	$(TKO_DIR)\tkoGraphLine.c \
	$(TKO_DIR)\tkoGraphMarker.c \
	$(TKO_DIR)\tkoGraphMisc.c \
	$(TKO_DIR)\tkoGraphPen.c \
	$(TKO_DIR)\tkoGraphPs.c \
	$(TKO_DIR)\tkoPath.c \
	$(TKO_DIR)\tkoPathCanvArrow.c \
	$(TKO_DIR)\tkoPathCanvEllipse.c \
	$(TKO_DIR)\tkoPathCanvGroup.c \
	$(TKO_DIR)\tkoPathCanvImage.c \
	$(TKO_DIR)\tkoPathCanvLine.c \
	$(TKO_DIR)\tkoPathCanvPath.c \
	$(TKO_DIR)\tkoPathCanvPoly.c \
	$(TKO_DIR)\tkoPathCanvRect.c \
	$(TKO_DIR)\tkoPathCanvText.c \
	$(TKO_DIR)\tkoPathCanvWindow.c \
	$(TKO_DIR)\tkoPathGeneric.c \
	$(TKO_DIR)\tkoPathGradient.c \
	$(TKO_DIR)\tkoPathStyle.c \
	$(TKO_DIR)\tkoPathSurface.c \
	$(TKO_DIR)\tkoPathUtil.c \
	$(TKO_DIR)\tkoPath_WinGDIPlus.c \

X11_SRCS = \
	$(UNIX_DIR)/tkAppInit.c $(UNIX_DIR)/tkUnix.c \
	$(UNIX_DIR)/tkUnix3d.c \
	$(UNIX_DIR)/tkUnixButton.c $(UNIX_DIR)/tkUnixColor.c \
	$(UNIX_DIR)/tkUnixConfig.c \
	$(UNIX_DIR)/tkUnixCursor.c \
	$(UNIX_DIR)/tkUnixDraw.c \
644
645
646
647
648
649
650
651

652
653
654
655
656
657
658




659
660
661
662
663
664
665
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







-
+







+
+
+
+







# Note, in the target below TCL_LIBRARY needs to be set or else
# "make test" won't work in the case where the compilation directory
# isn't the same as the source directory.
# Specifying TESTFLAGS on the command line is the standard way to pass
# args to tcltest, ie:
#	% make test TESTFLAGS="-verbose bps -file fileName.test"

test: test-classic test-ttk
test: test-classic test-ttk test-tko

test-classic: $(TKTEST_EXE)
	$(SHELL_ENV) ./$(TKTEST_EXE) $(TEST_DIR)/all.tcl -geometry +0+0 $(TESTFLAGS)

test-ttk: $(TKTEST_EXE)
	$(SHELL_ENV) ./$(TKTEST_EXE) $(TEST_DIR)/ttk/all.tcl -geometry +0+0 \
	$(TESTFLAGS)

test-tko: $(TKTEST_EXE)
	$(SHELL_ENV) ./$(TKTEST_EXE) $(TEST_DIR)/tko/all.tcl -geometry +0+0 \
	$(TESTFLAGS)

# Tests with different languages
testlang: $(TKTEST_EXE)
	$(SHELL_ENV) \
	for lang in $(LOCALES) ;  \
	do \
	LANG=$(lang); export LANG; \
758
759
760
761
762
763
764
765

766
767
768
769
770
771
772
863
864
865
866
867
868
869

870
871
872
873
874
875
876
877







-
+







	@EXTRA_INSTALL_BINARIES@
	@echo "Installing pkg-config file to $(LIB_INSTALL_DIR)/pkgconfig/"
	@$(INSTALL_DATA_DIR) $(LIB_INSTALL_DIR)/pkgconfig
	@$(INSTALL_DATA) tk.pc $(LIB_INSTALL_DIR)/pkgconfig/tk.pc

install-libraries: libraries
	@for i in "$(SCRIPT_INSTALL_DIR)" "$(SCRIPT_INSTALL_DIR)/images" \
		"$(SCRIPT_INSTALL_DIR)/msgs" "$(SCRIPT_INSTALL_DIR)/ttk"; \
		"$(SCRIPT_INSTALL_DIR)/msgs" "$(SCRIPT_INSTALL_DIR)/ttk" ; \
	    do \
	    if [ -n "$$i" -a ! -d "$$i" ] ; then \
		echo "Making directory $$i"; \
		$(INSTALL_DATA_DIR) "$$i"; \
		else true; \
		fi; \
	    done;
1446
1447
1448
1449
1450
1451
1452














































































































































1453
1454
1455
1456
1457
1458
1459
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







	$(CC) -c $(CC_SWITCHES) $(TTK_DIR)/ttkTreeview.c

ttkWidget.o: $(TTK_DIR)/ttkWidget.c
	$(CC) -c $(CC_SWITCHES) $(TTK_DIR)/ttkWidget.c

ttkMacOSXTheme.o: $(MAC_OSX_DIR)/ttkMacOSXTheme.c
	$(CC) -c $(CC_SWITCHES) $(MAC_OSX_DIR)/ttkMacOSXTheme.c

tkoWidget.o: $(TKO_DIR)/tkoWidget.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoWidget.c

tkoFrame.o: $(TKO_DIR)/tkoFrame.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoFrame.c

tkoRbcBind.o: $(TKO_DIR)/tkoRbcBind.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcBind.c

tkoRbcChain.o: $(TKO_DIR)/tkoRbcChain.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcChain.c

tkoRbcImage.o: $(TKO_DIR)/tkoRbcImage.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcImage.c

tkoRbcParse.o: $(TKO_DIR)/tkoRbcParse.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcParse.c

tkoRbcPs.o: $(TKO_DIR)/tkoRbcPs.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcPs.c

tkoRbcSpline.o: $(TKO_DIR)/tkoRbcSpline.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcSpline.c

tkoRbcSwitch.o: $(TKO_DIR)/tkoRbcSwitch.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcSwitch.c

tkoRbcText.o: $(TKO_DIR)/tkoRbcText.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcText.c

tkoRbcTile.o: $(TKO_DIR)/tkoRbcTile.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcTile.c

tkoRbcUtil.o: $(TKO_DIR)/tkoRbcUtil.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcUtil.c

tkoRbcWindow.o: $(TKO_DIR)/tkoRbcWindow.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcWindow.c

tkoRbcUnixImage.o: $(TKO_DIR)/tkoRbcUnixImage.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoRbcUnixImage.c

tkoVectorMath.o: $(TKO_DIR)/tkoVectorMath.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoVectorMath.c

tkoVectorObjCmd.o: $(TKO_DIR)/tkoVectorObjCmd.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoVectorObjCmd.c

tkoVector.o: $(TKO_DIR)/tkoVector.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoVector.c

tkoGraph.o: $(TKO_DIR)/tkoGraph.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraph.c

tkoGraphConfig.o: $(TKO_DIR)/tkoGraphConfig.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphConfig.c

tkoGraphAxis.o: $(TKO_DIR)/tkoGraphAxis.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphAxis.c

tkoGraphBar.o: $(TKO_DIR)/tkoGraphBar.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphBar.c

tkoGraphElem.o: $(TKO_DIR)/tkoGraphElem.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphElem.c

tkoGraphGrid.o: $(TKO_DIR)/tkoGraphGrid.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphGrid.c

tkoGraphHairs.o: $(TKO_DIR)/tkoGraphHairs.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphHairs.c

tkoGraphLegd.o: $(TKO_DIR)/tkoGraphLegd.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphLegd.c

tkoGraphLine.o: $(TKO_DIR)/tkoGraphLine.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphLine.c

tkoGraphMarker.o: $(TKO_DIR)/tkoGraphMarker.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphMarker.c

tkoGraphMisc.o: $(TKO_DIR)/tkoGraphMisc.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphMisc.c

tkoGraphPen.o: $(TKO_DIR)/tkoGraphPen.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphPen.c

tkoGraphPs.o: $(TKO_DIR)/tkoGraphPs.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoGraphPs.c

tkoPath.o: $(TKO_DIR)/tkoPath.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPath.c

tkoPathCanvArrow.o: $(TKO_DIR)/tkoPathCanvArrow.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvArrow.c

tkoPathCanvEllipse.o: $(TKO_DIR)/tkoPathCanvEllipse.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvEllipse.c

tkoPathCanvGroup.o: $(TKO_DIR)/tkoPathCanvGroup.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvGroup.c

tkoPathCanvImage.o: $(TKO_DIR)/tkoPathCanvImage.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvImage.c

tkoPathCanvLine.o: $(TKO_DIR)/tkoPathCanvLine.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvLine.c

tkoPathCanvPath.o: $(TKO_DIR)/tkoPathCanvPath.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvPath.c

tkoPathCanvPoly.o: $(TKO_DIR)/tkoPathCanvPoly.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvPoly.c

tkoPathCanvRect.o: $(TKO_DIR)/tkoPathCanvRect.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvRect.c

tkoPathCanvText.o: $(TKO_DIR)/tkoPathCanvText.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvText.c

tkoPathCanvWindow.o: $(TKO_DIR)/tkoPathCanvWindow.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathCanvWindow.c

tkoPathGeneric.o: $(TKO_DIR)/tkoPathGeneric.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathGeneric.c

tkoPathGradient.o: $(TKO_DIR)/tkoPathGradient.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathGradient.c

tkoPathStyle.o: $(TKO_DIR)/tkoPathStyle.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathStyle.c

tkoPathSurface.o: $(TKO_DIR)/tkoPathSurface.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathSurface.c

tkoPathUtil.o: $(TKO_DIR)/tkoPathUtil.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPathUtil.c

tkoPath_UnixCairo.o: $(TKO_DIR)/tkoPath_UnixCairo.c
	$(CC) -c $(CC_SWITCHES) $(TKO_DIR)/tkoPath_UnixCairo.c


.c.o:
	$(CC) -c $(CC_SWITCHES) $<

#
# Target to regenerate header files and stub files from the *.decls tables.
#
Changes to win/Makefile.in.
110
111
112
113
114
115
116

117
118
119
120
121
122
123
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124







+








SRC_DIR			= @srcdir@
ROOT_DIR		= $(SRC_DIR)/..
WIN_DIR			= $(SRC_DIR)
UNIX_DIR		= $(SRC_DIR)/../unix
GENERIC_DIR		= $(SRC_DIR)/../generic
TTK_DIR			= $(GENERIC_DIR)/ttk
TKO_DIR			= $(GENERIC_DIR)/tko
BITMAP_DIR		= $(ROOT_DIR)/bitmaps
XLIB_DIR		= $(ROOT_DIR)/xlib
RC_DIR			= $(WIN_DIR)/rc

ROOT_DIR_NATIVE	   	= $(shell $(CYGPATH) '$(ROOT_DIR)' | sed 's!\\!/!g')
WIN_DIR_NATIVE	   	= $(shell $(CYGPATH) '$(WIN_DIR)' | sed 's!\\!/!g')
GENERIC_DIR_NATIVE 	= $(shell $(CYGPATH) '$(GENERIC_DIR)' | sed 's!\\!/!g')
148
149
150
151
152
153
154
155

156
157
158
159
160
161
162
149
150
151
152
153
154
155

156
157
158
159
160
161
162
163







-
+








@SET_MAKE@

# Setting the VPATH variable to a list of paths will cause the
# makefile to look into these paths when resolving .c to .obj
# dependencies.

VPATH = $(GENERIC_DIR):$(TTK_DIR):$(WIN_DIR):$(UNIX_DIR):$(XLIB_DIR):$(RC_DIR)
VPATH = $(GENERIC_DIR):$(TTK_DIR):$(TKO_DIR):$(WIN_DIR):$(UNIX_DIR):$(XLIB_DIR):$(RC_DIR)

# warning flags
CFLAGS_WARNING	= @CFLAGS_WARNING@

# The default switches for optimization or debugging
CFLAGS_DEBUG    = @CFLAGS_DEBUG@
CFLAGS_OPTIMIZE	= @CFLAGS_OPTIMIZE@
185
186
187
188
189
190
191

192


193
194
195
196
197

198

199
200
201
202
203
204
205
186
187
188
189
190
191
192
193

194
195
196
197
198
199
200
201

202
203
204
205
206
207
208
209







+
-
+
+





+
-
+







CPPFLAGS	= @CPPFLAGS@
LDFLAGS		= @LDFLAGS@ @LDFLAGS_DEFAULT@
LDFLAGS_CONSOLE	= @LDFLAGS_CONSOLE@
LDFLAGS_WINDOW	= @LDFLAGS_WINDOW@
EXEEXT		= @EXEEXT@
OBJEXT		= @OBJEXT@
STLIB_LD	= @STLIB_LD@
#RZ TODO search for C++ compiler in configure AC_PROG_CC
SHLIB_LD	= @SHLIB_LD@
#RZ SHLIB_LD	= @SHLIB_LD@
SHLIB_LD	= g++ -shared
SHLIB_LD_LIBS	= @SHLIB_LD_LIBS@
SHLIB_CFLAGS	= @SHLIB_CFLAGS@
SHLIB_SUFFIX	= @SHLIB_SUFFIX@
VER		= @TK_MAJOR_VERSION@@TK_MINOR_VERSION@
DOTVER		= @TK_MAJOR_VERSION@.@TK_MINOR_VERSION@
#RZ TODO add -lgdiplus in configure
LIBS		= $(TCL_STUB_LIB_FILE) @LIBS@ @LIBS_GUI@
LIBS		= $(TCL_STUB_LIB_FILE) @LIBS@ @LIBS_GUI@ -lgdiplus
RMDIR		= rm -rf
MKDIR		= mkdir -p
SHELL		= @SHELL@
RM		= rm -f
COPY		= cp

BUILD_TCLSH	= @BUILD_TCLSH@
354
355
356
357
358
359
360
361


362
363
364
365
366
367
368
358
359
360
361
362
363
364

365
366
367
368
369
370
371
372
373







-
+
+







	tkTextWind.$(OBJEXT) \
	tkTrig.$(OBJEXT) \
	tkUndo.$(OBJEXT) \
	tkUtil.$(OBJEXT) \
	tkVisual.$(OBJEXT) \
	tkStubInit.$(OBJEXT) \
	tkWindow.$(OBJEXT) \
	$(TTK_OBJS)
	$(TTK_OBJS) \
	$(TKO_OBJS)

TTK_OBJS = \
	ttkWinMonitor.$(OBJEXT) \
	ttkWinTheme.$(OBJEXT) \
	ttkWinXPTheme.$(OBJEXT) \
	ttkBlink.$(OBJEXT) \
	ttkButton.$(OBJEXT) \
391
392
393
394
395
396
397


















































398
399
400
401
402
403
404
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







	ttkTheme.$(OBJEXT) \
	ttkTrace.$(OBJEXT) \
	ttkTrack.$(OBJEXT) \
	ttkTreeview.$(OBJEXT) \
	ttkWidget.$(OBJEXT) \
	ttkStubInit.$(OBJEXT)

TKO_OBJS = \
	tkoWidget.$(OBJEXT) \
	tkoFrame.$(OBJEXT) \
	tkoRbcBind.$(OBJEXT) \
	tkoRbcChain.$(OBJEXT) \
	tkoRbcImage.$(OBJEXT) \
	tkoRbcParse.$(OBJEXT) \
	tkoRbcPs.$(OBJEXT) \
	tkoRbcSpline.$(OBJEXT) \
	tkoRbcSwitch.$(OBJEXT) \
	tkoRbcText.$(OBJEXT) \
	tkoRbcTile.$(OBJEXT) \
	tkoRbcUtil.$(OBJEXT) \
	tkoRbcWindow.$(OBJEXT) \
	tkoRbcWinDraw.$(OBJEXT) \
	tkoRbcWinImage.$(OBJEXT) \
	tkoVectorMath.$(OBJEXT) \
	tkoVectorObjCmd.$(OBJEXT) \
	tkoVector.$(OBJEXT) \
	tkoGraph.$(OBJEXT) \
	tkoGraphConfig.$(OBJEXT) \
	tkoGraphAxis.$(OBJEXT) \
	tkoGraphBar.$(OBJEXT) \
	tkoGraphElem.$(OBJEXT) \
	tkoGraphGrid.$(OBJEXT) \
	tkoGraphHairs.$(OBJEXT) \
	tkoGraphLegd.$(OBJEXT) \
	tkoGraphLine.$(OBJEXT) \
	tkoGraphMarker.$(OBJEXT) \
	tkoGraphMisc.$(OBJEXT) \
	tkoGraphPen.$(OBJEXT) \
	tkoGraphPs.$(OBJEXT) \
	tkoPath.$(OBJEXT) \
	tkoPathCanvArrow.$(OBJEXT) \
	tkoPathCanvEllipse.$(OBJEXT) \
	tkoPathCanvGroup.$(OBJEXT) \
	tkoPathCanvImage.$(OBJEXT) \
	tkoPathCanvLine.$(OBJEXT) \
	tkoPathCanvPath.$(OBJEXT) \
	tkoPathCanvPoly.$(OBJEXT) \
	tkoPathCanvRect.$(OBJEXT) \
	tkoPathCanvText.$(OBJEXT) \
	tkoPathCanvWindow.$(OBJEXT) \
	tkoPathGeneric.$(OBJEXT) \
	tkoPathGradient.$(OBJEXT) \
	tkoPathStyle.$(OBJEXT) \
	tkoPathSurface.$(OBJEXT) \
	tkoPathUtil.$(OBJEXT) \
	tkoPath_WinGDIPlus.$(OBJEXT) \

STUB_OBJS = \
	tkStubLib.$(OBJEXT) \
	ttkStubLib.$(OBJEXT)

TCL_DOCS = "$(TCL_SRC_DIR_NATIVE)/doc/*.[13n]"
TK_DOCS = "$(ROOT_DIR_NATIVE)/doc/*.[13n]"
CORE_DOCS = $(TCL_DOCS) $(TK_DOCS)
433
434
435
436
437
438
439
440

441
442
443
444
445
446
447
448




449
450
451
452
453
454
455
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







-
+








+
+
+
+







$(MAN2TCL): $(TCL_SRC_DIR)/tools/man2tcl.c
	$(CC) $(CFLAGS_OPTIMIZE) $(MAN2TCLFLAGS) -o $(MAN2TCL) "$(TCL_SRC_DIR_NATIVE)/tools/man2tcl.c"

# Specifying TESTFLAGS on the command line is the standard way to pass
# args to tcltest, ie:
#	% make test TESTFLAGS="-verbose bps -file fileName.test"

test: test-classic test-ttk
test: test-classic test-ttk test-tko

test-classic: binaries $(TKTEST) $(TEST_DLL_FILE) $(CAT32)
	$(SHELL_ENV) ./$(TKTEST) "$(ROOT_DIR_NATIVE)/tests/all.tcl" \
	$(TESTFLAGS) | ./$(CAT32)

test-ttk: binaries $(TKTEST) $(TEST_DLL_FILE) $(CAT32)
	$(SHELL_ENV) ./$(TKTEST) "$(ROOT_DIR_NATIVE)/tests/ttk/all.tcl" \
	$(TESTFLAGS) | ./$(CAT32)

test-tko: binaries $(TKTEST) $(TEST_DLL_FILE) $(CAT32)
	$(SHELL_ENV) ./$(TKTEST) "$(ROOT_DIR_NATIVE)/tests/tko/all.tcl" \
	$(TESTFLAGS) | ./$(CAT32)

runtest: binaries $(TKTEST) $(TEST_DLL_FILE)
	$(SHELL_ENV) ./$(TKTEST) $(TESTFLAGS) $(SCRIPT)

# This target can be used to run wish from the build directory
# via `make shell` or `make shell SCRIPT=foo.tcl`
shell: binaries
504
505
506
507
508
509
510
511

512
513
514
515
516
517
518
563
564
565
566
567
568
569

570
571
572
573
574
575
576
577







-
+







	    fi; \
	    done

install-libraries: libraries
	@for i in $(INSTALL_ROOT)$(prefix)/lib \
		$(INCLUDE_INSTALL_DIR) $(INCLUDE_INSTALL_DIR)/X11 \
		$(SCRIPT_INSTALL_DIR) $(SCRIPT_INSTALL_DIR)/images \
		$(SCRIPT_INSTALL_DIR)/msgs $(SCRIPT_INSTALL_DIR)/ttk; \
		$(SCRIPT_INSTALL_DIR)/msgs $(SCRIPT_INSTALL_DIR)/ttk ; \
	    do \
	    if [ ! -d $$i ] ; then \
		echo "Making directory $$i"; \
		$(MKDIR) $$i; \
		chmod 755 $$i; \
		else true; \
		fi; \
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
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







+

-
+


















+


-
+








$(TKTEST): testMain.$(OBJEXT) $(TEST_DLL_FILE) @LIBRARIES@ $(TK_STUB_LIB_FILE) wish.$(RES)
	$(CC) $(CFLAGS) testMain.$(OBJEXT) $(TEST_LIB_FILE) $(TK_LIB_FILE) \
	$(TK_STUB_LIB_FILE) $(TCL_LIB_FILE) $(LIBS) \
	wish.$(RES) $(CC_EXENAME) $(LDFLAGS_WINDOW)
	@VC_MANIFEST_EMBED_EXE@

#RZ TODO configure should add -static-libstdc++
${TEST_DLL_FILE}: ${TKTEST_OBJS} ${TK_STUB_LIB_FILE}
	@MAKE_DLL@ ${TKTEST_OBJS} $(TK_STUB_LIB_FILE) $(SHLIB_LD_LIBS)
	@MAKE_DLL@ -static-libstdc++ ${TKTEST_OBJS} $(TK_STUB_LIB_FILE) $(SHLIB_LD_LIBS)

# Msys make requires this next rule for some reason.
$(TCL_SRC_DIR)/win/cat.c:

cat32.${OBJEXT}: $(TCL_SRC_DIR)/win/cat.c
	$(CC) -c $(CC_SWITCHES) "$(TCL_SRC_DIR)/win/cat.c" $(CC_OBJNAME)

$(CAT32): cat32.${OBJEXT}
	$(CC) $(CFLAGS) cat32.$(OBJEXT) $(CC_EXENAME) $(LIBS) $(LDFLAGS_CONSOLE)

# The following targets are configured by autoconf to generate either
# a shared library or static library

${TK_STUB_LIB_FILE}: ${STUB_OBJS}
	@$(RM) ${TK_STUB_LIB_FILE}
	@MAKE_STUB_LIB@ ${STUB_OBJS}
	@POST_MAKE_LIB@

#RZ TODO configure should add -static-libstdc++
${TK_DLL_FILE}: ${TK_OBJS} $(TK_RES)
	@$(RM) ${TK_DLL_FILE}
	@MAKE_DLL@ ${TK_OBJS} $(TK_RES) $(SHLIB_LD_LIBS)
	@MAKE_DLL@ -static-libstdc++ ${TK_OBJS} $(TK_RES) $(SHLIB_LD_LIBS)
	@VC_MANIFEST_EMBED_DLL@

${TK_LIB_FILE}: ${TK_OBJS}
	@$(RM) ${TK_LIB_FILE}
	@MAKE_LIB@ ${TK_OBJS}
	@POST_MAKE_LIB@

692
693
694
695
696
697
698



699
700
701
702
703
704
705
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769







+
+
+







.SUFFIXES: .rc

# Implicit rule for all object files that will end up in the Tk library

%.$(OBJEXT): %.c
	$(CC) -c $(CC_SWITCHES) -DBUILD_tk -DBUILD_ttk @DEPARG@ $(CC_OBJNAME)

%.$(OBJEXT): %.cpp
	$(CXX) -c $(CC_SWITCHES) -DBUILD_tk -DBUILD_ttk @DEPARG@ $(CC_OBJNAME)

.rc.$(RES):
	$(RC) @RC_OUT@ $@ @RC_TYPE@ @RC_DEFINES@ @RC_INCLUDE@ "$(GENERIC_DIR_NATIVE)" @RC_INCLUDE@ "$(TCL_GENERIC_NATIVE)" @RC_INCLUDE@ "$(RC_DIR_NATIVE)" @DEPARG@

depend:

cleanhelp:
	$(RM) *.hlp *.cnt *.hpj *.GID *.rtf man2tcl${EXEEXT}
Changes to win/makefile.vc.
253
254
255
256
257
258
259

260
261
262
263
264
265
266
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267







+







	$(TMP_DIR)\tkTrig.obj \
	$(TMP_DIR)\tkUndo.obj \
	$(TMP_DIR)\tkUtil.obj \
	$(TMP_DIR)\tkVisual.obj \
	$(TMP_DIR)\tkStubInit.obj \
	$(TMP_DIR)\tkWindow.obj \
	$(TTK_OBJS) \
	$(TKO_OBJS) \
!if !$(STATIC_BUILD)
	$(TMP_DIR)\tk.res
!endif

TTK_OBJS = \
        $(TMP_DIR)\ttkWinMonitor.obj \
        $(TMP_DIR)\ttkWinTheme.obj \
292
293
294
295
296
297
298


















































299
300
301
302
303
304
305
306

307
308
309
310
311
312
313
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+








+







        $(TMP_DIR)\ttkTheme.obj \
        $(TMP_DIR)\ttkTrace.obj \
        $(TMP_DIR)\ttkTrack.obj \
        $(TMP_DIR)\ttkTreeview.obj \
        $(TMP_DIR)\ttkWidget.obj \
        $(TMP_DIR)\ttkStubInit.obj

TKO_OBJS = \
	$(TMP_DIR)\tkoWidget.obj \
	$(TMP_DIR)\tkoFrame.obj \
	$(TMP_DIR)\tkoRbcBind.obj \
	$(TMP_DIR)\tkoRbcChain.obj \
	$(TMP_DIR)\tkoRbcImage.obj \
	$(TMP_DIR)\tkoRbcParse.obj \
	$(TMP_DIR)\tkoRbcPs.obj \
	$(TMP_DIR)\tkoRbcSpline.obj \
	$(TMP_DIR)\tkoRbcSwitch.obj \
	$(TMP_DIR)\tkoRbcText.obj \
	$(TMP_DIR)\tkoRbcTile.obj \
	$(TMP_DIR)\tkoRbcUtil.obj \
	$(TMP_DIR)\tkoRbcWindow.obj \
	$(TMP_DIR)\tkoRbcWinDraw.obj \
	$(TMP_DIR)\tkoRbcWinImage.obj \
	$(TMP_DIR)\tkoVectorMath.obj \
	$(TMP_DIR)\tkoVectorObjCmd.obj \
	$(TMP_DIR)\tkoVector.obj \
	$(TMP_DIR)\tkoGraph.obj \
	$(TMP_DIR)\tkoGraphConfig.obj \
	$(TMP_DIR)\tkoGraphAxis.obj \
	$(TMP_DIR)\tkoGraphBar.obj \
	$(TMP_DIR)\tkoGraphElem.obj \
	$(TMP_DIR)\tkoGraphGrid.obj \
	$(TMP_DIR)\tkoGraphHairs.obj \
	$(TMP_DIR)\tkoGraphLegd.obj \
	$(TMP_DIR)\tkoGraphLine.obj \
	$(TMP_DIR)\tkoGraphMarker.obj \
	$(TMP_DIR)\tkoGraphMisc.obj \
	$(TMP_DIR)\tkoGraphPen.obj \
	$(TMP_DIR)\tkoGraphPs.obj \
	$(TMP_DIR)\tkoPath.obj \
	$(TMP_DIR)\tkoPathCanvArrow.obj \
	$(TMP_DIR)\tkoPathCanvEllipse.obj \
	$(TMP_DIR)\tkoPathCanvGroup.obj \
	$(TMP_DIR)\tkoPathCanvImage.obj \
	$(TMP_DIR)\tkoPathCanvLine.obj \
	$(TMP_DIR)\tkoPathCanvPath.obj \
	$(TMP_DIR)\tkoPathCanvPoly.obj \
	$(TMP_DIR)\tkoPathCanvRect.obj \
	$(TMP_DIR)\tkoPathCanvText.obj \
	$(TMP_DIR)\tkoPathCanvWindow.obj \
	$(TMP_DIR)\tkoPathGeneric.obj \
	$(TMP_DIR)\tkoPathGradient.obj \
	$(TMP_DIR)\tkoPathStyle.obj \
	$(TMP_DIR)\tkoPathSurface.obj \
	$(TMP_DIR)\tkoPathUtil.obj \
	$(TMP_DIR)\tkoPath_WinGDIPlus.obj \

TKSTUBOBJS = \
	$(TMP_DIR)\tkStubLib.obj \
	$(TMP_DIR)\ttkStubLib.obj

### The following paths CANNOT have spaces in them as they appear on
### the left side of implicit rules.
XLIBDIR		= $(ROOT)\xlib
TTKDIR		= $(ROOT)\generic\ttk
TKODIR		= $(ROOT)\generic\tko
BITMAPDIR	= $(ROOT)\bitmaps

# Additional include and C macro definitions for the implicit rules
# defined in rules.vc
PRJ_INCLUDES	= -I"$(BITMAPDIR)" -I"$(XLIBDIR)"

CONFIG_DEFS     =-DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 \
323
324
325
326
327
328
329
330

331
332
333
334
335
336
337
375
376
377
378
379
380
381

382
383
384
385
386
387
388
389







-
+







!if $(TK_NO_DEPRECATED)
		 -DTK_NO_DEPRECATED=1
!endif

PRJ_DEFINES	= -DBUILD_ttk $(CONFIG_DEFS) -Dinline=__inline -D _CRT_SECURE_NO_DEPRECATE -D _CRT_NONSTDC_NO_DEPRECATE

# Additional Link libraries needed beyond those in rules.vc
PRJ_LIBS   = netapi32.lib gdi32.lib user32.lib userenv.lib
PRJ_LIBS   = netapi32.lib gdiplus.lib gdi32.lib user32.lib userenv.lib


#---------------------------------------------------------------------
# TkTest flags
#---------------------------------------------------------------------

!if "$(TESTPAT)" != ""
551
552
553
554
555
556
557




558
559
560
561
562
563
564
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620







+
+
+
+







$(TMP_DIR)\winMain.obj: $(WINDIR)\winMain.c
	$(cc32) $(appcflags_nostubs) \
	    -DTCL_USE_STATIC_PACKAGES=$(TCL_USE_STATIC_PACKAGES) \
	    -Fo$@ $?

$(TMP_DIR)\tkMain2.obj: $(GENERICDIR)\tkMain.c
	$(cc32) $(pkgcflags) -DTK_ASCII_MAIN -Fo$@ $?

$(TMP_DIR)\tkoPath_WinGDIPlus.obj: $(TKODIR)\tkoPath_WinGDIPlus.cpp
	$(cc32) $(pkgcflags) -DTK_ASCII_MAIN -Fo$@ $?


# The following objects are part of the stub library and should not
# be built as DLL objects but none of the symbols should be exported
# and no reference made to a C runtime.

$(TMP_DIR)\tkStubLib.obj : $(GENERICDIR)\tkStubLib.c
	$(cc32) $(stubscflags) -Fo$@ $?
582
583
584
585
586
587
588
589

590
591
592
593
594
595
596
638
639
640
641
642
643
644

645
646
647
648
649
650
651
652







-
+







!if !exist($(TCLSH))
	@echo Build tclsh first!
!else
	set TCL_LIBRARY=$(TCL_LIBRARY)
	$(TCLSH) $(TCLTOOLSDIR:\=/)/mkdepend.tcl -vc32 -out:"$(OUT_DIR)\depend.mk" \
		-passthru:"-DBUILD_tk $(TK_INCLUDES)" $(GENERICDIR),$$(GENERICDIR) \
		$(WINDIR),$$(WINDIR) $(TTKDIR),$$(TTKDIR) $(XLIBDIR),$$(XLIBDIR) \
		$(BITMAPDIR),$$(BITMAPDIR) @<<
		$(TKODIR),$$(TKODIR) $(BITMAPDIR),$$(BITMAPDIR) @<<
$(TKOBJS)
<<
!endif

#---------------------------------------------------------------------
# Dependency rules
#---------------------------------------------------------------------
619
620
621
622
623
624
625





626
627
628
629
630
631
632
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693







+
+
+
+
+







$<
<<

{$(TTKDIR)}.c{$(TMP_DIR)}.obj::
	$(CCPKGCMD) @<<
$<
<<

{$(TKODIR)}.c{$(TMP_DIR)}.obj::
	$(CCPKGCMD) @<<
$<
<<

{$(ROOT)\unix}.c{$(TMP_DIR)}.obj::
	$(CCPKGCMD) @<<
$<
<<

$(TMP_DIR)\tk.res: $(TMP_DIR)\wish.exe.manifest