File: tkdiff.tcl

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

###############################################################################
#
# TkDiff -- A graphical front-end to diff for Unix and NT.
# Copyright (C) 1994-1998 by John M. Klassa.
#
# TkDiff Home Page: http://www.accurev.com/free/tkdiff
# Mailing list, mail archive, etc.
#
# Usage:
#	  To interactively pick files:
#	      tkdiff
#
#	  Plain files:
#	      tkdiff <file1> <file2>
#
#	  Plain file with conflict markers:
#	      tkdiff -conflict <file>
#
#	  Source control AccuRev/CVS/RCS/Perforce/PVCS/SCCS:
#	      tkdiff <file> (same as -r)
#	      tkdiff -r <file>
#	      tkdiff -r<rev> <file>
#	      tkdiff -r<rev> -r <file>
#	      tkdiff -r<rev1> -r<rev2> <file>
#
#	  Options:
#	      -a <ancestor_file>
#	      -o <merge output file>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# THINGS TO DO:
#
# the code that parses the command line ought to be separated from the
# code that reads in the files. That way we can parse the command line
# right up front and display potential problems on stdout instead of
# waiting until the window display.
###############################################################################


# get this out of the way -- we want to draw the whole user interface
# behind the scenes, then pop up in all of its well-laid-out glory
wm withdraw .

# set a couple o' globals that we might need sooner than later
set g(name) "TkDiff"
set g(version) "3.08"
set g(nativeMenus) 1
set g(started) 0

# ok, I'll admit -- this is a personal preference. I suppose I ought to
# move this into the preferences or remove it entirely. Sue me. :-)
option add "*TearOff" false 100

###############################################################################
# determine the name of the temporary directory and the name of
# the rc file, both of which are dependent on the platform.
###############################################################################
switch $tcl_platform(platform) {
    windows {
	    if {[info exists env(TEMP)]} {
		set opts(tmpdir) $env(TEMP)
	    } else {
		set opts(tmpdir) C:/temp
	    }
	    set basercfile "_tkdiff.rc"
	}
    default {
	    # Make menus and buttons prettier
	    option add *Font -*-Helvetica-Medium-R-Normal-*-12-*

	    if {[info exists env(TMPDIR)]} {
		set opts(tmpdir) $env(TMPDIR)
	    } else {
		set opts(tmpdir) /tmp
	    }
	    set basercfile ".tkdiffrc"
	}
}

###############################################################################
# compute preferences file location. Note that TKDIFFRC can hold either
# a directory or a file, though we document it as being a file name
###############################################################################
if {[info exists env(TKDIFFRC)]} {
    set rcfile $env(TKDIFFRC)
    if {[file isdirectory $rcfile]} {
	set rcfile [file join $rcfile $basercfile]
    }

} elseif {[info exists env(HOME)]} {
    set rcfile [file join $env(HOME) $basercfile]

} else {
    set rcfile [file join "/" $basercfile]
}

###############################################################################
# Fonts are selected based on platform.	 Can anyone clean this
# up by finding one set of fonts that looks good everywhere?
# bdo - probably not; fonts are probably best left platform-specific
# For windows I personally recommend Monotype.com, free from Microsoft
# (not that I like Microsoft, but Monotype is a decent fixed width
# font).
###############################################################################

if {$tcl_platform(platform) == "windows"} {
    if {$tk_version >= 8.0} {
	set font "{{Lucida Console} 7}"
	# Breaks if you're running
	set bold "{{Lucida Console} 7}"
	# Windows with a mono display.
    } else {
	# These XFDs are from Sun's font alias file
	# Also known as 6x13
	set font -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1
	# Also known as 6x13bold
	set bold -misc-fixed-bold-r-semicondensed--13-120-75-75-c-60-iso8859-1
    }
} else {
    set font 6x13
    set bold 6x13bold
}

###############################################################################
# more initialization...
###############################################################################

array set g {
    ancfileset 0
    changefile	    "tkdiff-change-bars.out"
    destroy	    ""
    ignore_event,1  0
    ignore_event,2  0
    ignore_hevent,1 0
    ignore_hevent,2 0
    initOK	    0
    mapborder	    0
    mapheight	    0
    mergefile	    "tkdiff-merge.out"
    returnValue	    0
    showmerge	    0
    started	    0
    mergefileset    0
    tempfiles	    ""
    thumbMinHeight  10
    thumbHeight	    10
}

array set finfo {
    pth,1	""
    pth,2	""
    title	{}
    tmp,1	0
    tmp,2	0
}

###############################################################################
# These options may be changed at runtime
###############################################################################

array set opts {
    autocenter	1
    autoselect	0
    colorcbs	0
    customCode	{}
    diffcmd	"diff"
    editor	""
    geometry	"80x30"
    showcbs	1
    showln	1
    showmap	1
    showlineview 0
    syncscroll	1
    toolbarIcons 1
    tagcbs	0
    tagln	0
    tagtext	1
    tabstops    8
}

if {$tcl_platform(platform) == "windows"} {
    set opts(fancyButtons) 1
} else {
    set opts(fancyButtons) 0
}

# reporting options
array set report {
    doSideLeft		 0
    doLineNumbersLeft	 1
    doChangeMarkersLeft	 1
    doTextLeft		 1
    doSideRight		 1
    doLineNumbersRight	 1
    doChangeMarkersRight 1
    doTextRight		 1
    filename		 "tkdiff.out"
}


if {[string first "color" [winfo visual .]] >= 0} {
    # We have color
    # (but, let's not go crazy...)
    array set opts [subst {
	textopt "-background white -foreground black  -font $font"
	currtag "-background blue -foreground white"
	difftag "-background gray -foreground black  -font $bold"
	deltag	"-background red1 -foreground black"
	instag	"-background green3 -foreground black"
	chgtag	"-background DodgerBlue1 -foreground black"
	overlaptag	"-background yellow -foreground black"
	bytetag "-underline 1 -foreground white -background black"
	-	"-background red1 -foreground red1"
	+	"-background green -foreground green"
	!	"-background blue -foreground blue"
	?	"-background yellow -foreground yellow"
    }]

} else {
    # Assume only black and white
    set bg "black"
    array set opts [subst {
	textopt "-background white -foreground black -font $font"
	currtag "-background black -foreground white"
	difftag "-background white -foreground black -font $bold"
	deltag	"-background black -foreground white"
	instag	"-background black -foreground white"
	chgtag	"-background black -foreground white"
	overlaptag "-background black -foreground white"
	bytetag "-underline 1"
	-	"-background black -foreground white"
	+	"-background black -foreground white"
	!	"-background black -foreground white"
	?	"-background black -foreground white"
    }]
}

# make sure wrapping is turned off. This might piss off a few people,
# but it would screw up the display to have things wrap
set opts(textopt) "$opts(textopt) -wrap none"

###############################################################################
# Source the rc file, which may override some of the defaults
# Any errors will be reported. Before doing so, we need to define the 
# "define" proc, which lets the rc file have a slightly more human-friendly 
# interface. Old-style .rc files should still load just fine for now, though
# it ought to be noted new .rc files won't be able to be processed by older
# versions of TkDiff. That shouldn't be a problem.
###############################################################################

proc define {name value} {
    global opts
    set opts($name) $value
}

if {[file exists $rcfile]} {

    if {[catch {source $rcfile} error]} {
	set startupError [join [list "There was an error in processing your startup file." "\n$g(name) will still run, but some of your preferences" "\nmay not be in effect." "\n\nFile: $rcfile"\
	  "\nError: $error"] " "]
    }
}


# a hack to handle older preferences files...
# if the user has a diffopt defined in their rc file, we'll magically
# convert that to diffcmd...
if {[info exists opts(diffopt)]} {
    set opts(diffcmd) "diff $opts(diffopt)"
}

###############################################################################
# Work-around for bad font approximations,
# as suggested by Don Libes (libes@nist.gov).
###############################################################################
catch {tk scaling [expr 100.0 / 72]}

proc do-exit {{returncode {}}} {
    global g

    # we don't particularly care if del-tmp fails.
    catch {del-tmp}

    if {$returncode == ""} {
	set returncode $g(returnValue)
    }

    # exit with an appropriate return value
    exit $returncode
}


###############################################################################
# Throw up a modal error dialog.
###############################################################################

proc do-error {msg} {
    global argv0
    tk_messageBox\
        -message "$msg"\
        -title "$argv0: Error"\
        -icon error\
        -type ok
}

###############################################################################
# Throw up a modal error dialog or print a message to stderr.  For
# Unix we print to stderr and exit if the main window hasn't been
# created, otherwise put up a dialog and throw an exception.
###############################################################################

proc fatal-error {msg} {
    global g tcl_platform

    if {$tcl_platform(platform) == "windows" || $g(started)} {
	tk_messageBox\
	    -title "Error"\
	    -icon error\
	    -type ok\
	    -message $msg
	error "Fatal"
    } else {
	puts stderr $msg
	del-tmp
	do-exit 2
    }
}

###############################################################################
# Return user name.  Credit to Warren Jones (wjones@tc.fluke.com).
###############################################################################

proc whoami {} {
    global env
    if {[info exists env(USER)]} {
	return $env(USER)
    }
    if {[info exists env(LOGNAME)]} {
	return $env(LOGNAME)
    }
    if {[info exists env(USERNAME)]} {
	return $env(USERNAME)
    }
    if {[info exists env(VCSID)]} {
	return $env(VCSID)
    }
    if {[catch {exec whoami} whoami]} {
	return nobody
    }
    return $whoami
}

###############################################################################
# Return the name of a temporary file
###############################################################################

proc tmpfile {n} {
    global opts
    file join $opts(tmpdir) "[whoami][pid]-$n"
}

###############################################################################
# Execute a command.
# Returns "$stdout $stderr $exitcode" if exit code != 0
###############################################################################

proc run-command {cmd} {
    global opts errorCode

    set stderr ""
    set exitcode 0
    set errfile [tmpfile "r"]

    set failed [catch "$cmd 2>$errfile" stdout]
    # Read stderr output
    catch {
	set hndl [open "$errfile" r]
	set stderr [read $hndl]
	close $hndl
    }
    if {$failed} {
	switch [lindex $errorCode 0] {
	    "CHILDSTATUS" {
		    set exitcode [lindex $errorCode 2]
		}
	    "POSIX" {
		    if {$stderr == ""} {
			set stderr $stdout
		    }
		    set exitcode -1
		}
	    default {
		    set exitcode -1
		}
	}
    }

    catch {file delete $errfile}
    return [list "$stdout" "$stderr" "$exitcode"]
}

###############################################################################
# Execute a command.  Die if unsuccessful.
###############################################################################

proc die-unless {cmd file} {
    global opts errorCode

    set result [run-command "$cmd >$file"]
    set stdout [lindex $result 0]
    set stderr [lindex $result 1]
    set exitcode [lindex $result 2]

    if {$exitcode != 0} {
	fatal-error "$stderr\n$stdout"
    }
}

###############################################################################
# Filter PVCS output files that have CR-CR-LF end-of-lines
###############################################################################

proc filterCRCRLF {file} {
    set outfile [tmpfile 9]
    set inp [open $file r]
    set out [open $outfile w]
    fconfigure $inp\
        -translation binary
    fconfigure $out\
        -translation binary
    set CR [format %c 13]
    while {![eof $inp]} {
	set line [gets $inp]
	if {[string length $line] && ![eof $inp]} {
	    regsub\
	        -all "$CR$CR" $line $CR line
	    puts $out $line
	}
    }
    close $inp
    close $out
    file rename\
        -force $outfile $file
}


###############################################################################
# Return the smallest of two values
###############################################################################

proc min {a b} {
    return [expr {$a < $b ? $a : $b}]
}

###############################################################################
# Return the largest of two values
###############################################################################

proc max {a b} {
    return [expr {$a > $b ? $a : $b}]
}

###############################################################################
# Toggle change bars
###############################################################################
proc do-show-changebars {{show {}}} {
    global opts
    global w

    if {$show != {}} {
	set opts(showcbs) $show
    }

    if {$opts(showcbs)} {
	grid $w(LeftCB)\
	    -row 0\
	    -column 2\
	    -sticky ns
	grid $w(RightCB)\
	    -row 0\
	    -column 1\
	    -sticky ns
    } else {
	grid forget $w(LeftCB)
	grid forget $w(RightCB)
    }
}


###############################################################################
# Toggle line numbers.
###############################################################################
proc do-show-linenumbers {{showLn {}}} {
    global opts
    global w

    if {$showLn != {}} {
	set opts(showln) $showLn
    }

    if {$opts(showln)} {
	grid $w(LeftInfo)\
	    -row 0\
	    -column 1\
	    -sticky nsew
	grid $w(RightInfo)\
	    -row 0\
	    -column 0\
	    -sticky nsew
    } else {
	grid forget $w(LeftInfo)
	grid forget $w(RightInfo)
    }
}


###############################################################################
# Show line numbers in info windows
###############################################################################

proc draw-line-numbers {} {
    global g
    global w

    $w(LeftInfo) configure\
        -state normal
    $w(RightInfo) configure\
        -state normal
    $w(LeftCB) configure\
        -state normal
    $w(RightCB) configure\
        -state normal

    set lines(Left) [lindex [split [$w(LeftText) index end-1lines] .] 0]
    set lines(Right) [lindex [split [$w(RightText) index end-1lines] .] 0]

    # Smallest line count
    set minlines [min $lines(Left) $lines(Right)]

    # cache all the blank lines for the info and cb windows, and do
    # one big insert after we're done. This seems to be much quicker
    # than inserting them in the widgets one line at a time.
    set linestuff {}
    set cbstuff {}
    for {set i 1} {$i < $minlines} {incr i} {
	append linestuff "$i\n"
	append cbstuff " \n" ;# for now, just put in place holders...
    }

    $w(LeftInfo) insert end $linestuff
    $w(RightInfo) insert end $linestuff
    $w(LeftCB) insert end $cbstuff
    $w(RightCB) insert end $cbstuff

    # Insert remaining line numbers. We'll cache the stuff to be
    # inserted so we can do just one call in to the widget. This
    # should be much faster, relatively speaking, then inserting
    # data one line at a time.
    foreach mod {Left Right} {
	set linestuff {}
	set cbstuff {}
	for {set i $minlines} {$i < $lines($mod)} {incr i} {
	    append linestuff "$i\n"
	    append cbstuff " \n" ;# for now, just put in place holders...
	}
	$w(${mod}Info) insert end $linestuff
	$w(${mod}CB) insert end $cbstuff
    }

    $w(LeftCB) configure\
        -state disabled
    $w(RightCB) configure\
        -state disabled

    $w(LeftInfo) configure\
        -state disabled
    $w(RightInfo) configure\
        -state disabled
}

###############################################################################
# Pop up a window for file merge.
###############################################################################

proc popup-merge {{writeproc merge-write-file}} {
    global g
    global w

    if {$g(mergefileset)} {
	$writeproc
	return
    }

    set types {
	{{Text Files}	 {.txt}}
	{{All Files}	 {*}}
    }

    set path [tk_getSaveFile\
        -defaultextension ""\
        -filetypes $types\
        -initialfile [file nativename $g(mergefile)]]

    if {[string length $path] > 0} {
	set g(mergefile) $path
	$writeproc
    }
}



###############################################################################
# Split a file containing CVS conflict markers into two temporary files
#    name	Name of file containing conflict markers
# Returns the names of the two temporary files and the names of the
# files that were merged
###############################################################################

proc split-cvs-conflicts {name} {
    global g opts

    set first ${name}.1
    set second ${name}.2

    set temp1 [tmpfile 1]
    set temp2 [tmpfile 2]

    if {[catch {set input [open $name r]}]} {
	fatal-error "Couldn't open file '$name'."
    }
    set first [open $temp1 w]
    lappend g(tempfiles) $temp1
    set second [open $temp2 w]
    lappend g(tempfiles) $temp2

    set firstname ""
    set secondname ""
    set output 3

    set firstMatch ""
    set secondMatch ""
    set thirdMatch ""

    while {[gets $input line] >= 0} {
	if {$firstMatch == ""} {
	    if {[regexp {^<<<<<<<* +(.*)} $line]} {
		set firstMatch {^<<<<<<<* +(.*)}
		set secondMatch {^=======*}
		set thirdMatch {^>>>>>>>* +(.*)}
	    } elseif {[regexp {^>>>>>>>* +(.*)} $line]} {
		set firstMatch {^>>>>>>>* +(.*)}
		set secondMatch {^<<<<<<<* +(.*)}
		set thirdMatch {^=======*}
	    }
	}
	if {$firstMatch != ""} {
	    if {[regexp $firstMatch $line]} {
		set output 2
		if {$secondname == ""} {
		    regexp $firstMatch $line all secondname
		}
	    } elseif {[regexp $secondMatch $line]} {
		set output 1
		if {$firstname == ""} {
		    regexp $secondMatch $line all firstname
		}
	    } elseif {[regexp $thirdMatch $line]} {
		set output 3
		if {$firstname == ""} {
		    regexp $thirdMatch $line all firstname
		}
	    } else {
		if {$output & 1} {
		    puts $first $line
		}
		if {$output & 2} {
		    puts $second $line
		}
	    }
	} else {
	    puts $first $line
	    puts $second $line
	}
    }
    close $input
    close $first
    close $second

    if {$firstname == ""} {
	set firstname "old"
    }
    if {$secondname == ""} {
	set secondname "new"
    }

    return "{$temp1} {$temp2} {$firstname} {$secondname}"
}

###############################################################################
# Get a revision of a file
#   f	    file name
#   index   index in finfo array
#   r	    revision, "" for head revision
###############################################################################

proc get-file-rev {f index {r ""}} {
    global finfo
    global opts
    global tcl_platform

    if {"$r" == ""} {
	set rev "HEAD"
	set acrev "HEAD"
	set acopt ""
	set cvsopt ""
	set rcsopt ""
	set sccsopt ""
	set pvcsopt ""
	set p4file "$f"
    } else {
	set rev "r$r"
	set acrev "\"$r\""
	set acopt "-v \"$r\""
	set cvsopt "-r $r"
	set rcsopt "$r"
	set sccsopt "-r$r"
	set pvcsopt "-r$r"
	set p4file "$f#$r"
    }

    set finfo(pth,$index) [tmpfile $index]
    set finfo(tmp,$index) 1

    # NB: it would probably be a Good Thing to move the definition
    # of the various command to exec, to the preferences dialog.

    set dirname [file dirname $f]
    set tailname [file tail $f]

    # For CVS, if it isn't checked out there is neither a CVS nor RCS
    # directory.  It will however have a ,v suffix just like rcs.
    # There is not necessarily a RCS directory for RCS, either.	 The file
    # always has a ,v suffix.

    if {[file isdirectory [file join $dirname CVS]]} {
	set cmd "cvs"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (CVS $rev)"
	die-unless "exec $cmd update -p $cvsopt $f" $finfo(pth,$index)

    } elseif {[file isdirectory [file join $dirname SCCS]]} {
	set cmd "sccs"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (SCCS $rev)"
	die-unless "exec $cmd get -p $sccsopt $f" $finfo(pth,$index)


    } elseif {[file isdirectory [file join $dirname RCS]]} {
	set cmd "co"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (RCS $rev)"
	die-unless "exec $cmd -p$rcsopt $f" $finfo(pth,$index)

    } elseif {[regexp {,v$} $tailname]} {
	set cmd "co"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (RCS $rev)"
	die-unless "exec $cmd -p$rcsopt $f" $finfo(pth,$index)

    } elseif {[file exists [file join $dirname vcs.cfg]]} {
	set cmd "get"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (PVCS $rev)"
	die-unless "exec $cmd -p $pvcsopt $f" $finfo(pth,$index)
	filterCRCRLF $finfo(pth,$index)

    } elseif {[info exists ::env(P4CLIENT)]} {
	set cmd "p4"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f (Perforce $rev)"
	die-unless "exec $cmd print -q $p4file" $finfo(pth,$index)

    } elseif {[info exists ::env(ACCUREV_BIN)]} {
	set cmd "accurev"
	if {$tcl_platform(platform) == "windows"} {
	    append cmd ".exe"
	}
	set finfo(lbl,$index) "$f ($acrev)"
	die-unless "exec $cmd cat $acopt \"$f\"" $finfo(pth,$index)
    } else {
	fatal-error "File '$f' is not part of a revision control system."
    }
}

###############################################################################
# Setup ordinary file
#   f	    file name
#   index   index in finfo array
###############################################################################

proc get-file {f index} {
    global finfo

    if {[file exists $f] != 1} {
	fatal-error "File '$f' does not exist."
    }
    if {[file isdirectory $f]} {
	fatal-error "'$f' is a directory."
    }

    set finfo(lbl,$index) "$f"
    set finfo(pth,$index) "$f"
    set finfo(tmp,$index) 0
}

###############################################################################
# Initialize file variables.
###############################################################################

proc init-files {} {
    global argc argv
    global finfo
    global opts
    global g

    set g(initOK) 0
    set argindex 0
    set revs 0
    set pths 0
    set conflict 0

    # Loop through argv, storing revision args in rev and file args in
    # finfo. revs and pths are counters.
    while {$argindex < $argc} {
	set arg [lindex $argv $argindex]
	switch -regexp -- $arg {
	    "^-a$" {
		    incr argindex
		    set g(ancfile) [lindex $argv $argindex]
		    set g(ancfileset) 1
		}
	    "^-a.*" {
		    set g(ancfile) [string range $arg 2 end]
		    set g(ancfileset) 1
		}
	    "^-r$" {
		    incr argindex
		    incr revs
		    set rev($revs) [lindex $argv $argindex]
		}
	    "^-r.*" {
		    incr revs
		    set rev($revs) [string range $arg 2 end]
		}
	    "^-v$" {
		    incr argindex
		    incr revs
		    set rev($revs) [lindex $argv $argindex]
		}
	    "^-v.*" {
		    incr revs
		    set rev($revs) [string range $arg 2 end]
		}
	    "^-conflict$" {
		    set conflict 1
		}
	    "^-o$" {
		    incr argindex
		    set g(mergefile) [lindex $argv $argindex]
		    set g(mergefileset) 1
		}
	    "^-o.*" {
		    set g(mergefile) [string range $arg 2 end]
		    set g(mergefileset) 1
		}
	    "^-" {
		    append opts(diffcmd) " $arg "
		}
	    default {
		    incr pths
		    set finfo(pth,$pths) $arg
		}
	}
	incr argindex
    }

    # Now check how many revision and file args we have.
    if {$conflict} {
	if {$revs == 0 && $pths == 1} {
	    ############################################################
	    # tkdiff -conflict FILE
	    ############################################################
	    set files [split-cvs-conflicts "$finfo(pth,1)"]
	    get-file [lindex "$files" 0] 1
	    get-file [lindex "$files" 1] 2
	    set finfo(lbl,1) [lindex "$files" 2]
	    set finfo(lbl,2) [lindex "$files" 3]
	} else {
	    fatal-error "Usage: tkdiff -conflict FILE"
	}
    } else {
	if {$revs == 2 && $pths == 1} {
	    ############################################################
	    #  tkdiff -rREV1 -rREV2 FILE
	    ############################################################
	    set f $finfo(pth,1)
	    get-file-rev "$f" 1 "$rev(1)"
	    get-file-rev "$f" 2 "$rev(2)"

	} elseif {$revs == 2 && $pths == 0} {
	    ############################################################
	    #  tkdiff -rREV -r FILE
	    ############################################################
	    set f $rev(2)
	    get-file-rev "$f" 1 "$rev(1)"
	    get-file-rev "$f" 2

	} elseif {$revs == 1 && $pths == 1} {
	    ############################################################
	    #  tkdiff -rREV FILE
	    ############################################################
	    set f $finfo(pth,1)
	    get-file-rev "$f" 1 "$rev(1)"
	    get-file "$f" 2

	} elseif {$revs == 1 && $pths == 0} {
	    ############################################################
	    # tkdiff -r FILE
	    ############################################################
	    set f $rev(1)
	    get-file-rev "$f" 1
	    get-file "$f" 2

	} elseif {$revs == 0 && $pths == 2} {
	    ############################################################
	    #  tkdiff FILE1 FILE2
	    ############################################################
	    set f1 $finfo(pth,1)
	    set f2 $finfo(pth,2)
	    if {[file isdirectory $f1] && [file isdirectory $f2]} {
		fatal-error "Either <file1> or <file2> must be a plain file."
	    }

	    if {[file isdirectory $f1]} {
		set f1 [file join $f1 [file tail $f2]]
	    } elseif {[file isdirectory $f2]} {
		set f2 [file join $f2 [file tail $f1]]
	    }

	    get-file "$f1" 1
	    get-file "$f2" 2

	} elseif {$revs == 0 && $pths == 1} {
	    ############################################################
	    #  tkdiff FILE
	    ############################################################
	    set f $finfo(pth,1)
	    get-file-rev "$f" 1
	    get-file "$f" 2

	} else {
	    do-error "Invalid command line!\n	 $argv\nSee the help for valid command line parameters."
	    do-usage
	    tkwait window .usage
	    destroy .
	    error "Fatal"
	}
    }

    set finfo(title) "[file tail $finfo(lbl,1)] vs. [file tail $finfo(lbl,2)]"
    set rootname [file rootname $finfo(pth,1)]
    #    set path	  [file dirname	  $finfo(pth,1)]
    set path [pwd]
    set suffix [file extension $finfo(pth,1)]
    if {! $g(mergefileset)} {
	set g(mergefile) [file join $path "${rootname}-merge$suffix"]
    }
    set g(initOK) 1

    wm title . "$finfo(title) - $g(name) $g(version)"
}

###############################################################################
# Set up the display...
###############################################################################
proc create-display {} {

    global g opts bg tk_version
    global w
    global tmpopts

    # these are the four major areas of the GUI:
    # menubar - the menubar (duh)
    # toolbar - the toolbar (duh, again)
    # client  - the area with the text widgets and the graphical map
    # status us	 - a bottom status line

    # this block of destroys is only for stand-alone testing of
    # the GUI code, and can be blown away (or not, if we want to
    # be able to call this routine to recreate the display...)
    catch {
	destroy .menubar
	destroy .toolbar
	destroy .client
	destroy .map
	destroy .status
    }

    # create the top level frames and store them in a global
    # array..
    set w(client) .client
    set w(menubar) .menubar
    set w(toolbar) .toolbar
    set w(status) .status

    # other random windows...
    set w(preferences) .pref
    set w(findDialog) .findDialog
    set w(popupMenu) .popupMenu

    # now, simply build all the pieces
    build-menubar
    build-toolbar
    build-client
    build-status
    build-popupMenu

    # ... and fit it all together...
    if {$g(nativeMenus)} {
	. configure\
	    -menu $w(menubar)
    } else {
	pack $w(menubar)\
	    -side top\
	    -fill x\
	    -expand n
    }
    pack $w(toolbar)\
        -side top\
        -fill x\
        -expand n
    pack $w(client)\
        -side top\
        -fill both\
        -expand y
    pack $w(status)\
        -side bottom\
        -fill x\
        -expand n

    # apply user preferences by calling the proc that gets
    # called when the user presses "Apply" from the preferences
    # window. That proc uses a global variable named "tmpopts"
    # which should have the values from the dialog. Since we
    # aren't using the dialog, we need to populate this array
    # manually
    foreach key [array names opts] {
	set ::tmpopts($key) $opts($key)
    }
    apply 0

    # Make sure temporary files get deleted
    bind . <Destroy> {del-tmp}

    # other misc. bindings
    common-navigation $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)

    # normally, keyboard traversal using tab and shift-tab isn't
    # enabled for text widgets, since the default binding for these
    # keys is to actually insert the tab charater. Because all of
    # our text widgets are for display only, let's redefine the
    # default binding so the global <Tab> and <Shift-Tab> bindings
    # are used.
    bind Text <Tab> {continue}
    bind Text <Shift-Tab> {continue}

    # if the user toggles scrollbar syncing, we want to make sure 
    # they sync up immediately
    trace variable opts(syncscroll) w toggleSyncScroll
    wm deiconify .
    focus\
        -force $w(RightText)
    update idletasks

    set g(started) 1
}

###############################################################################
# when the user changes the "sync scrollbars" option, we want to 
# sync up the left scrollbar with the right if they turn the option
# on
###############################################################################
proc toggleSyncScroll {args} {
    global opts
    global w

    if {$opts(syncscroll) == 1} {
	eval vscroll-sync {{}} 2 [$w(RightText) yview]
    }
}

###############################################################################
# show the popup menu, optionally changing some of the entries based on
# where the user clicked
###############################################################################

proc show-popupMenu {x y} {
    global w
    global g

    set window [winfo containing $x $y]
    if {[winfo class $window] == "Text"} {
	$w(popupMenu) entryconfigure "Find..."\
	    -state normal
	$w(popupMenu) entryconfigure "Find Nearest*"\
	    -state normal
	$w(popupMenu) entryconfigure "Edit*"\
	    -state normal

	if {$window == $w(LeftText) || $window == $w(LeftInfo) || $window == $w(LeftCB)} {
	    $w(popupMenu) configure\
	        -title "File 1"
	    set g(activeWindow) $w(LeftText)
	} else {
	    $w(popupMenu) configure\
	        -title "File 2"
	    set g(activeWindow) $w(RightText)
	}

    } else {
	$w(popupMenu) entryconfigure "Find..."\
	    -state disabled
	$w(popupMenu) entryconfigure "Find Nearest*"\
	    -state disabled
	$w(popupMenu) entryconfigure "Edit*"\
	    -state disabled
    }
    tk_popup $w(popupMenu) $x $y
}


###############################################################################
# build the right-click popup menu
###############################################################################

proc build-popupMenu {} {
    global w g

    # this routine assumes the other windows already exist...
    menu $w(popupMenu)
    foreach win [list LeftText RightText LeftInfo RightInfo LeftCB RightCB mapCanvas] {
	bind $w($win) <3> {show-popupMenu %X %Y}
    }

    set m $w(popupMenu)
    $m add command\
        -label "First Diff"\
        -underline 0\
        -command [list popupMenu first]\
        -accelerator "F"
    $m add command\
        -label "Previous Diff"\
        -underline 0\
        -command [list popupMenu previous]\
        -accelerator "P"
    $m add command\
        -label "Center Current Diff"\
        -underline 0\
        -command [list popupMenu center]\
        -accelerator "C"
    $m add command\
        -label "Next Diff"\
        -underline 0\
        -command [list popupMenu next]\
        -accelerator "N"
    $m add command\
        -label "Last Diff"\
        -underline 0\
        -command [list popupMenu last]\
        -accelerator "L"
    $m add separator
    $m add command\
        -label "Find Nearest Diff"\
        -underline 0\
        -command [list popupMenu nearest]\
        -accelerator "Double-Click"
    $m add separator
    $m add command\
        -label "Find..."\
        -underline 0\
        -command [list popupMenu find]
    $m add command\
        -label "Edit"\
        -underline 0\
        -command [list popupMenu edit]
}

###############################################################################
# handle popup menu commands
###############################################################################
proc popupMenu {command args} {
    global g
    global w

    switch $command {
	center {
		$w(centerDiffs) invoke
	    }
	edit {
		do-edit
	    }
	find {
		$w(find) invoke
	    }
	first {
		$w(firstDiff) invoke
	    }
	last {
		$w(lastDiff) invoke
	    }
	next {
		$w(nextDiff) invoke
	    }
	previous {
		$w(prevDiff) invoke
	    }
	nearest {
		moveNearest $g(activeWindow) xy [winfo pointerx $g(activeWindow)] [winfo pointery $g(activeWindow)]
	    }
    }
}

###############################################################################
# build the main client display (the text widgets, scrollbars, that
# sort of fluff)
###############################################################################

proc build-client {} {
    global g
    global w
    global opts
    global map

    frame $w(client)\
        -bd 2\
        -relief flat

    # set up global variables to reference the widgets, so
    # we don't have to use hardcoded widget paths elsewhere
    # in the code
    #
    # Text  - holds the text of the file
    # Info  - sort-of "invisible" text widget which is kept in sync
    #	      with the text widget and holds line numbers
    # CB    - contains changebars or status or something like that...
    # VSB   - vertical scrollbar
    # HSB   - horizontal scrollbar
    # Label - label to hold the name of the file
    set w(LeftText) $w(client).left.text
    set w(LeftInfo) $w(client).left.info
    set w(LeftCB) $w(client).left.changeBars
    set w(LeftVSB) $w(client).left.vsb
    set w(LeftHSB) $w(client).left.hsb
    set w(LeftLabel) $w(client).leftlabel

    set w(RightText) $w(client).right.text
    set w(RightInfo) $w(client).right.info
    set w(RightCB) $w(client).right.changeBars
    set w(RightVSB) $w(client).right.vsb
    set w(RightHSB) $w(client).right.hsb
    set w(RightLabel) $w(client).rightlabel

    set w(BottomText) $w(client).bottomtext

    set w(map) $w(client).map
    set w(mapCanvas) $w(map).canvas

    # these don't need to be global...
    set leftFrame $w(client).left
    set rightFrame $w(client).right

    # we'll create each widget twice; once for the left side
    # and once for the right.
    label $w(LeftLabel)\
        -bd 1\
        -relief flat\
        -textvariable finfo(lbl,1)

    label $w(RightLabel)\
        -bd 1\
        -relief flat\
        -textvariable finfo(lbl,2)

    # this holds the text widgets and the scrollbars. The reason
    # for the frame is purely for aesthetics. It just looks
    # nicer, IMHO, to "embed" the scrollbars within the text
    # widget
    frame $leftFrame\
        -bd 1\
        -relief sunken

    frame $rightFrame\
        -bd 1\
        -relief sunken

    scrollbar $w(LeftHSB)\
        -borderwidth 1\
        -orient horizontal\
        -command [list $w(LeftText) xview]

    scrollbar $w(RightHSB)\
        -borderwidth 1\
        -orient horizontal\
        -command [list $w(RightText) xview]

    scrollbar $w(LeftVSB)\
        -borderwidth 1\
        -orient vertical\
        -command [list $w(LeftText) yview]

    scrollbar $w(RightVSB)\
        -borderwidth 1\
        -orient vertical\
        -command [list $w(RightText) yview]

    scan $opts(geometry) "%dx%d" width height

    text $w(LeftText)\
        -padx 4\
        -wrap none\
        -width $width\
        -height $height\
        -borderwidth 0\
        -setgrid 1\
        -yscrollcommand [list vscroll-sync "$w(LeftInfo) $w(LeftCB)" 1]\
        -xscrollcommand [list hscroll-sync 1]

    text $w(RightText)\
        -padx 4\
        -wrap none\
        -width $width\
        -height $height\
        -borderwidth 0\
        -setgrid 1\
        -yscrollcommand [list vscroll-sync "$w(RightInfo) $w(RightCB)" 2]\
        -xscrollcommand [list hscroll-sync 2]

    text $w(LeftInfo)\
        -height 0\
        -padx 0\
        -width 6\
        -borderwidth 0\
        -setgrid 1\
        -yscrollcommand [list vscroll-sync "$w(LeftCB) $w(LeftText)" 1]

    text $w(RightInfo)\
        -height 0\
        -padx 0\
        -width 6\
        -borderwidth 0\
        -setgrid 1\
        -yscrollcommand [list vscroll-sync "$w(RightCB) $w(RightText)" 2]

    # each and every line in a text window will have a corresponding line
    # in this widget. And each line in this widget will be composed of
    # a single character (either "+", "-" or "!" for insertion, deletion
    # or change, respectively
    text $w(LeftCB)\
        -height 0\
        -padx 0\
        -highlightthickness 0\
        -wrap none\
        -foreground white\
        -width 1\
        -borderwidth 0\
        -yscrollcommand [list vscroll-sync "$w(LeftInfo) $w(LeftText)" 1]

    text $w(RightCB)\
        -height 0\
        -padx 0\
        -highlightthickness 0\
        -wrap none\
        -background white\
        -foreground white\
        -width 1\
        -borderwidth 0\
        -yscrollcommand [list vscroll-sync "$w(RightInfo) $w(RightText)" 2]

    # this widget is the two line display showing the current line, so
    # one can compare character by character if necessary.
    text $w(BottomText)\
        -wrap none\
        -borderwidth 1\
        -height 2\
        -width 0

    # this is how we highlight bytes that are different...
    # the bottom window (lineview) uses reverse video to highlight 
    # diffs, so we need to figure out what reverse video is, and
    # define the tag appropriately
    eval $w(BottomText) tag configure diff $opts(bytetag)

    # Set up text tags for the 'current diff' (the one chosen by the 'next'
    # and 'prev' buttons) and any ol' diff region.  All diff regions are
    # given the 'diff' tag initially...	 As 'next' and 'prev' are pressed,
    # to scroll through the differences, one particular diff region is
    # always chosen as the 'current diff', and is set off from the others
    # via the 'diff' tag -- in particular, so that it's obvious which diffs
    # in the left and right-hand text widgets match.

    foreach widget [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)] {
	eval "$widget configure $opts(textopt)"
	foreach tag {difftag currtag deltag instag chgtag overlaptag + - ! ?} {
	    eval "$widget tag configure $tag $opts($tag)"
	}
    }

    # adjust the tag priorities a bit...
    foreach window [list LeftText RightText LeftCB RightCB LeftInfo RightInfo] {
	$w($window) tag raise deltag currtag
	$w($window) tag raise chgtag currtag
	$w($window) tag raise instag currtag
	$w($window) tag raise currtag difftag
    }

    # these tags are specific to change bars
    foreach widget [list $w(LeftCB) $w(RightCB)] {
	eval "$widget tag configure + $opts(+)"
	eval "$widget tag configure - $opts(-)"
	eval "$widget tag configure ! $opts(!)"
	eval "$widget tag configure ? $opts(?)"
    }

    # build the map...
    # we want the map to be the same width as a scrollbar, so we'll
    # steal some information from one of the scrollbars we just
    # created...
    set cwidth [winfo reqwidth $w(LeftVSB)]
    set color [$w(LeftVSB) cget -troughcolor]

    set map [frame $w(client).map\
        -bd 1\
        -relief sunken\
        -takefocus 0\
        -highlightthickness 0]

    # now for the real map...
    image create photo map

    canvas $w(mapCanvas)\
        -width [expr {$cwidth + 1}]\
        -yscrollcommand map-resize\
        -background $color\
        -borderwidth 0\
        -relief sunken\
        -highlightthickness 0
    $w(mapCanvas) create image 1 1\
        -image map\
        -anchor nw
    pack $w(mapCanvas)\
        -side top\
        -fill both\
        -expand y

    # I'm not too pleased with these bindings -- it results in a rather
    # jerky, cpu-intensive maneuver since with each move of the mouse
    # we are finding and tagging the nearest diff. But, what *should*
    # it do?
    #
    # I think what I *want* it to do is update the combobox and status
    # bar so the user can see where in the scheme of things they are,
    # but not actually select anything until they release the mouse.
    bind $w(mapCanvas) <ButtonPress-1> [list handleMapEvent B1-Press %y]
    bind $w(mapCanvas) <Button1-Motion> [list handleMapEvent B1-Motion %y]
    bind $w(mapCanvas) <ButtonRelease-1> [list handleMapEvent B1-Release %y]

    # this is a dummy frame we're going to create that's the
    # same height as a horizontal scrollbar.
    frame $w(client).dummyFrame\
        -borderwidth 0\
        -height [winfo reqheight $w(LeftHSB)]

    # use grid to manage the widgets in the left side frame
    grid $w(LeftVSB)\
        -row 0\
        -column 0\
        -sticky ns
    grid $w(LeftInfo)\
        -row 0\
        -column 1\
        -sticky nsew
    grid $w(LeftCB)\
        -row 0\
        -column 2\
        -sticky ns
    grid $w(LeftText)\
        -row 0\
        -column 3\
        -sticky nsew
    grid $w(LeftHSB)\
        -row 1\
        -column 1\
        -sticky ew\
        -columnspan 3

    grid rowconfigure $leftFrame 0\
        -weight 1
    grid rowconfigure $leftFrame 1\
        -weight 0

    grid columnconfigure $leftFrame 0\
        -weight 0
    grid columnconfigure $leftFrame 1\
        -weight 0
    grid columnconfigure $leftFrame 2\
        -weight 0
    grid columnconfigure $leftFrame 3\
        -weight 1

    # likewise for the right...
    grid $w(RightVSB)\
        -row 0\
        -column 3\
        -sticky ns
    grid $w(RightInfo)\
        -row 0\
        -column 0\
        -sticky nsew
    grid $w(RightCB)\
        -row 0\
        -column 1\
        -sticky ns
    grid $w(RightText)\
        -row 0\
        -column 2\
        -sticky nsew
    grid $w(RightHSB)\
        -row 1\
        -column 0\
        -sticky ew\
        -columnspan 3

    grid rowconfigure $rightFrame 0\
        -weight 1
    grid rowconfigure $rightFrame 1\
        -weight 0

    grid columnconfigure $rightFrame 0\
        -weight 0
    grid columnconfigure $rightFrame 1\
        -weight 0
    grid columnconfigure $rightFrame 2\
        -weight 1
    grid columnconfigure $rightFrame 3\
        -weight 0

    # use grid to manage the labels, frames and map. We're going to
    # toss in an extra row just for the benefit of our dummy frame.
    # the intent is that the dummy frame will match the height of
    # the horizontal scrollbars so the map stops at the right place...
    grid $w(LeftLabel)\
        -row 0\
        -column 0\
        -sticky ew
    grid $w(RightLabel)\
        -row 0\
        -column 2\
        -sticky ew
    grid $leftFrame\
        -row 1\
        -column 0\
        -sticky nsew\
        -rowspan 2
    grid $map\
        -row 1\
        -column 1\
        -stick ns
    grid $w(client).dummyFrame\
        -row 2\
        -column 1
    grid $rightFrame\
        -row 1\
        -column 2\
        -sticky nsew\
        -rowspan 2

    grid rowconfigure $w(client) 0\
        -weight 0
    grid rowconfigure $w(client) 1\
        -weight 1
    grid rowconfigure $w(client) 2\
        -weight 0
    grid rowconfigure $w(client) 3\
        -weight 0

    grid columnconfigure $w(client) 0\
        -weight 1
    grid columnconfigure $w(client) 1\
        -weight 0
    grid columnconfigure $w(client) 2\
        -weight 1

    # this adjusts the variable g(activeWindow) to be whatever text
    # widget has the focus...
    bind $w(LeftText) <1> {set g(activeWindow) $w(LeftText)}
    bind $w(RightText) <1> {set g(activeWindow) $w(RightText)}

    set g(activeWindow) $w(LeftText) ;# establish a default

    rename $w(RightText) $w(RightText)_
    rename $w(LeftText) $w(LeftText)_

    proc $w(RightText) {command args} $::text_widget_proc
    proc $w(LeftText) {command args} $::text_widget_proc

}

###############################################################################
# the following code is used as the replacement body for the left and 
# right widget procs. The purpose is to catch when the insertion point 
# changes so we can update the line comparison window
###############################################################################

set text_widget_proc {
    global w
    set real "[lindex [info level [info level]] 0]_"
    set result [eval $real $command $args]
    if {$command == "mark"} {
	if {[lindex $args 0] == "set" && [lindex $args 1] == "insert"} {
	    set i [lindex $args 2]
	    set i0 "$i linestart"
	    set i1 "$i lineend"
	    set left [$w(LeftText)_ get $i0 $i1]
	    set right [$w(RightText)_ get $i0 $i1]
	    $w(BottomText) delete 1.0 end
	    $w(BottomText) insert end "< $left\n> $right"
	    # find characters that are different, and underline them
	    if {$left != $right} {
		set left [split $left {}]
		set right [split $right {}]
		# n.b. we set c to an offset equal to whatever we have
		# prepended to the data...
		set c 2
		foreach l $left r $right {
		    if {[string compare $l $r] != 0} {
			$w(BottomText) tag add diff 1.$c "1.$c+1c"
			$w(BottomText) tag add diff 2.$c "2.$c+1c"
		    }
		    incr c
		}
		$w(BottomText) tag remove diff "1.0 lineend"
		$w(BottomText) tag remove diff "2.0 lineend"
	    }
	}
    }
    return $result
}

###############################################################################
# create (if necessary) and show the find dialog
###############################################################################

proc show-find {} {
    global w g

    if {![winfo exists $w(findDialog)]} {
	toplevel $w(findDialog)
	wm group $w(findDialog) .
	wm transient $w(findDialog) .
	wm title $w(findDialog) "$g(name) Find"

	# we don't want the window to be deleted, just hidden from view
	wm protocol $w(findDialog) WM_DELETE_WINDOW [list wm withdraw $w(findDialog)]

	wm withdraw $w(findDialog)
	update idletasks

	frame $w(findDialog).content\
	    -bd 2\
	    -relief groove
	pack $w(findDialog).content\
	    -side top\
	    -fill both\
	    -expand y\
	    -padx 5\
	    -pady 5

	frame $w(findDialog).buttons
	pack $w(findDialog).buttons\
	    -side bottom\
	    -fill x\
	    -expand n

	button $w(findDialog).buttons.doit\
	    -text "Find Next"\
	    -command do-find
	button $w(findDialog).buttons.dismiss\
	    -text "Dismiss"\
	    -command "wm withdraw $w(findDialog)"
	pack $w(findDialog).buttons.dismiss\
	    -side right\
	    -pady 5\
	    -padx 5
	pack $w(findDialog).buttons.doit\
	    -side right\
	    -pady 5\
	    -padx 1

	set ff $w(findDialog).content.findFrame
	frame $ff\
	    -height 100\
	    -bd 2\
	    -relief flat
	pack $ff\
	    -side top\
	    -fill x\
	    -expand n\
	    -padx 5\
	    -pady 5

	label $ff.label\
	    -text "Find what:"\
	    -underline 2

	entry $ff.entry\
	    -textvariable g(findString)

	checkbutton $ff.searchCase\
	    -text "Ignore Case"\
	    -offvalue 0\
	    -onvalue 1\
	    -indicatoron true\
	    -variable g(findIgnoreCase)

	grid $ff.label\
	    -row 0\
	    -column 0\
	    -sticky e
	grid $ff.entry\
	    -row 0\
	    -column 1\
	    -sticky ew
	grid $ff.searchCase\
	    -row 0\
	    -column 2\
	    -sticky w
	grid columnconfigure $ff 0\
	    -weight 0
	grid columnconfigure $ff 1\
	    -weight 1
	grid columnconfigure $ff 2\
	    -weight 0

	# we need this in other places...
	set w(findEntry) $ff.entry

	bind $ff.entry <Return> do-find

	set of $w(findDialog).content.optionsFrame
	frame $of\
	    -bd 2\
	    -relief flat
	pack $of\
	    -side top\
	    -fill y\
	    -expand y\
	    -padx 10\
	    -pady 10

	label $of.directionLabel\
	    -text "Search Direction:"\
	    -anchor e
	radiobutton $of.directionForward\
	    -indicatoron true\
	    -text "Down"\
	    -value "-forward"\
	    -variable g(findDirection)
	radiobutton $of.directionBackward\
	    -text "Up"\
	    -value "-backward"\
	    -indicatoron true\
	    -variable g(findDirection)


	label $of.windowLabel\
	    -text "Window:"\
	    -anchor e
	radiobutton $of.windowLeft\
	    -indicatoron true\
	    -text "Left"\
	    -value $w(LeftText)\
	    -variable g(activeWindow)
	radiobutton $of.windowRight\
	    -indicatoron true\
	    -text "Right"\
	    -value $w(RightText)\
	    -variable g(activeWindow)


	label $of.searchLabel\
	    -text "Search Type:"\
	    -anchor e
	radiobutton $of.searchExact\
	    -indicatoron true\
	    -text "Exact"\
	    -value "-exact"\
	    -variable g(findType)
	radiobutton $of.searchRegexp\
	    -text "Regexp"\
	    -value "-regexp"\
	    -indicatoron true\
	    -variable g(findType)

	grid $of.directionLabel\
	    -row 1\
	    -column 0\
	    -sticky w
	grid $of.directionForward\
	    -row 1\
	    -column 1\
	    -sticky w
	grid $of.directionBackward\
	    -row 1\
	    -column 2\
	    -sticky w

	grid $of.windowLabel\
	    -row 0\
	    -column 0\
	    -sticky w
	grid $of.windowLeft\
	    -row 0\
	    -column 1\
	    -sticky w
	grid $of.windowRight\
	    -row 0\
	    -column 2\
	    -sticky w

	grid $of.searchLabel\
	    -row 2\
	    -column 0\
	    -sticky w
	grid $of.searchExact\
	    -row 2\
	    -column 1\
	    -sticky w
	grid $of.searchRegexp\
	    -row 2\
	    -column 2\
	    -sticky w

	grid columnconfigure $of 0\
	    -weight 0
	grid columnconfigure $of 1\
	    -weight 0
	grid columnconfigure $of 2\
	    -weight 1

	set g(findDirection) "-forward"
	set g(findType) "-exact"
	set g(findIgnoreCase) 1
	set g(lastSearch) ""
	if {$g(activeWindow) == ""} {
	    set g(activeWindow) [focus]
	    if {$g(activeWindow) != $w(LeftText) && $g(activeWindow) != $w(RightText)} {
		set g(activeWindow) $w(LeftText)
	    }
	}
    }

    centerWindow $w(findDialog)
    wm deiconify $w(findDialog)
    after idle focus $w(findEntry)

}

###############################################################################
# do the "Edit->Copy" functionality, by copying the current selection
# to the clipboard
###############################################################################

proc do-copy {} {
    clipboard clear\
        -displayof .
    # figure out which window has the selection...
    catch {
	clipboard append [selection get\
	    -displayof .]
    }
}

###############################################################################
# search for the text in the find dialog
###############################################################################

proc do-find {} {
    global g
    global w

    if {![winfo exists $w(findDialog)] || ![winfo ismapped $w(findDialog)]} {
	show-find
	return
    }

    set win $g(activeWindow)
    if {$win == ""} {
	set win $w(LeftText)
    }
    if {$g(lastSearch) != ""} {
	if {$g(findDirection) == "-forward"} {
	    set start [$win index "insert +1c"]
	} else {
	    set start insert
	}
    } else {
	set start 1.0
    }

    if {$g(findIgnoreCase)} {
	set result [$win search $g(findDirection) $g(findType)\
	    -nocase -- $g(findString) $start]
    } else {
	set result [$win search $g(findDirection) $g(findType)\
	    -- $g(findString) $start]
    }
    if {[string length $result] > 0} {
	# if this is a regular expression search, get the whole line and try
	# to figure out exactly what matched; otherwise we know we must
	# have matched the whole string...
	if {$g(findType) == "-regexp"} {
	    set line [$win get $result "$result lineend"]
	    regexp $g(findString) $line matchVar
	    set length [string length $matchVar]
	} else {
	    set length [string length $g(findString)]
	}
	set g(lastSearch) $result
	$win mark set insert $result
	$win tag remove sel 1.0 end
	$win tag add sel $result "$result + ${length}c"
	$win see $result
	focus $win
	# should I somehow snap to the nearest diff? Probably not...
    } else {
	bell

    }
}
proc build-menubar {} {
    global tooltip
    global w
    global g

    if {$g(nativeMenus)} {
	menu $w(menubar)
    } else {
	frame $w(menubar)\
	    -bd 2\
	    -relief flat
    }

    # this is just temporary shorthand ...
    set menubar $w(menubar)


    # First, the menu buttons...

    if {$g(nativeMenus)} {

	set fileMenu $w(menubar).file
	set viewMenu $w(menubar).view
	set helpMenu $w(menubar).help
	set editMenu $w(menubar).edit
	set mergeMenu $w(menubar).window
	set markMenu $w(menubar).marks

	$w(menubar) add cascade\
	    -label "File"\
	    -menu $fileMenu\
	    -underline 0
	$w(menubar) add cascade\
	    -label "Edit"\
	    -menu $editMenu\
	    -underline 0
	$w(menubar) add cascade\
	    -label "View"\
	    -menu $viewMenu\
	    -underline 0
	$w(menubar) add cascade\
	    -label "Mark"\
	    -menu $markMenu\
	    -underline 3
	$w(menubar) add cascade\
	    -label "Merge"\
	    -menu $mergeMenu\
	    -underline 0
	$w(menubar) add cascade\
	    -label "Help"\
	    -menu $helpMenu\
	    -underline 0

    } else {
	# these are shorthand used only in this routine...
	set fileButton $menubar.fileButton
	set viewButton $menubar.viewButton
	set helpButton $menubar.helpButton
	set editButton $menubar.editButton
	set mergeButton $menubar.mergeButton
	set markButton $menubar.markButton

	set fileMenu $fileButton.file
	set viewMenu $viewButton.view
	set helpMenu $helpButton.help
	set editMenu $editButton.edit
	set mergeMenu $mergeButton.window
	set markMenu $markButton.marks

	menubutton $fileButton\
	    -text "File"\
	    -menu $fileMenu\
	    -underline 0
	menubutton $editButton\
	    -text "Edit"\
	    -menu $editMenu\
	    -underline 0
	menubutton $viewButton\
	    -text "View"\
	    -menu $viewMenu\
	    -underline 0
	menubutton $helpButton\
	    -text "Help"\
	    -menu $helpMenu\
	    -underline 0
	menubutton $mergeButton\
	    -text "Merge"\
	    -menu $mergeMenu\
	    -underline 0
	menubutton $markButton\
	    -text "Mark"\
	    -menu $markMenu\
	    -underline 3

	pack $fileButton $editButton $viewButton $markButton $mergeButton\
	    -side left\
	    -fill none\
	    -expand n
	if {$::tcl_platform(platform) == "windows"} {
	    pack $helpButton\
	        -side left\
	        -fill none\
	        -expand n
	} else {
	    pack $helpButton\
	        -side right\
	        -fill none\
	        -expand n
	}
    }

    # these, however, are used in other places..
    set w(fileMenu) $fileMenu
    set w(viewMenu) $viewMenu
    set w(helpMenu) $helpMenu
    set w(editMenu) $editMenu
    set w(mergeMenu) $mergeMenu
    set w(markMenu) $markMenu

    # Now, the menus...

    # Mark menu...
    menu $markMenu
    $markMenu add command\
        -label "Mark Current Diff"\
        -command [list diffmark set]\
        -underline 0
    $markMenu add command\
        -label "Clear Current Diff Mark"\
        -command [list diffmark clear]\
        -underline 0

    set "g(tooltip,Mark Current Diff)" "Create a marker for the current difference record"
    set "g(tooltip,Clear Current Diff Mark)" "Clear the marker for the current difference record"

    # File menu...
    menu $fileMenu
    $fileMenu add command\
        -label "New..."\
        -underline 0\
        -command [list do-new-diff]
    $fileMenu add separator
    $fileMenu add command\
        -label "Recompute Diffs"\
        -underline 0\
        -command recompute-diff
    $fileMenu add command\
        -label "Write Report..."\
        -command [list write-report popup]\
        -underline 0
    $fileMenu add separator
    $fileMenu add command\
        -label "Exit"\
        -underline 1\
        -accelerator Q\
        -command do-exit

    set "g(tooltip,Exit)" "Exit $g(name)"
    set "g(tooltip,Recompute Diffs)" "Recompute and redisplay the difference records."
    set "g(tooltip,Write Report...)" "Write the diff records to a file"

    # Edit menu...  If you change, add or remove labels, be sure and
    # update the tooltips.
    menu $editMenu
    $editMenu add command\
        -label "Copy"\
        -underline 0\
        -command do-copy
    $editMenu add separator
    $editMenu add command\
        -label "Find..."\
        -underline 0\
        -command show-find
    $editMenu add separator
    $editMenu add command\
        -label "Edit File 1"\
        -command {
	    global g w
	    set g(activeWindow) $w(LeftText)
	    do-edit
	}\
        -underline 10
    $editMenu add command\
        -label "Edit File 2"\
        -command {
	    global g w
	    set g(activeWindow) $w(RightText)
	    do-edit
	}\
        -underline 10
    $editMenu add separator
    $editMenu add command\
        -label "Preferences..."\
        -underline 3\
        -command customize

    set "g(tooltip,Copy)" "Copy the currently selected text to the clipboard."
    set "g(tooltip,Find...)" "Pop up a dialog to search for a string within either file."
    set "g(tooltip,Edit File 1)" "Launch an editor on the file on the left side of the window."
    set "g(tooltip,Edit File 2)" "Launch an editor on the file on the right side of the window."
    set "g(tooltip,Preferences...)" "Pop up a window to customize $g(name)."

    # View menu...  If you change, add or remove labels, be sure and
    # update the tooltips.
    menu $viewMenu
    $viewMenu add checkbutton\
        -label "Show Line Numbers"\
        -underline 12\
        -variable opts(showln)\
        -command do-show-linenumbers

    $viewMenu add checkbutton\
        -label "Show Change Bars"\
        -underline 12\
        -variable opts(showcbs)\
        -command do-show-changebars

    $viewMenu add checkbutton\
        -label "Show Diff Map"\
        -underline 5\
        -variable opts(showmap)\
        -command do-show-map

    $viewMenu add checkbutton\
        -label "Show Line Comparison"\
        -underline 11\
        -variable opts(showlineview)\
        -command do-show-lineview

    $viewMenu add separator

    $viewMenu add checkbutton\
        -label "Synchronize Scrollbars"\
        -underline 0\
        -variable opts(syncscroll)
    $viewMenu add checkbutton\
        -label "Auto Center"\
        -underline 0\
        -variable opts(autocenter)\
        -command {if {$opts(autocenter)} {center}}
    $viewMenu add checkbutton\
        -label "Auto Select"\
        -underline 1\
        -variable opts(autoselect)

    $viewMenu add separator

    $viewMenu add command\
        -label "First Diff"\
        -underline 0\
        -command {move first}\
        -accelerator "F"
    $viewMenu add command\
        -label "Previous Diff"\
        -underline 0\
        -command {move -1}\
        -accelerator "P"
    $viewMenu add command\
        -label "Center Current Diff"\
        -underline 0\
        -command {center}\
        -accelerator "C"
    $viewMenu add command\
        -label "Next Diff"\
        -underline 0\
        -command {move 1}\
        -accelerator "N"
    $viewMenu add command\
        -label "Last Diff"\
        -underline 0\
        -command {move last}\
        -accelerator "L"

    set "g(tooltip,Show Line Comparison)" "If set, show the current line comparison window"
    set "g(tooltip,Show Change Bars)" "If set, show the changebar column for each line of each file"
    set "g(tooltip,Show Line Numbers)" "If set, show line numbers beside each line of each file"
    set "g(tooltip,Synchronize Scrollbars)" "If set, scrolling either window will scroll both windows."
    set "g(tooltip,Diff Map)" "If set, display the graphical \"Difference Map\" in the center of the display."
    set "g(tooltip,Auto Select)" "If set, automatically selects the nearest diff record while scrolling"
    set "g(tooltip,Auto Center)" "If set, moving to another diff record will center the diff on the screen."
    set "g(tooltip,Center Current Diff)" "Center the display around the current diff record."
    set "g(tooltip,First Diff)" "Go to the first difference."
    set "g(tooltip,Last Diff)" "Go to the last difference."
    set "g(tooltip,Previous Diff)" "Go to the diff record just prior to the current diff record."
    set "g(tooltip,Next Diff)" "Go to the diff record just after the current diff record."

    # Merge menu. If you change, add or remove labels, be sure and
    # update the tooltips.
    menu $mergeMenu
    $mergeMenu add checkbutton\
        -label "Show Merge Window"\
        -underline 9\
        -variable g(showmerge)\
        -command do-show-merge
    $mergeMenu add command\
        -label "Write Merge File..."\
        -underline 6\
        -command popup-merge
    set "g(tooltip,Show Merge Window)" "Pops up a window showing the current merge results."
    set "g(tooltip,Write Merge File)" "Write the merge file to disk. You will be prompted for a filename."

    # Help menu. If you change, add or remove labels, be sure and
    # update the tooltips.
    menu $helpMenu
    $helpMenu add command\
        -label "On GUI"\
        -underline 3\
        -command do-help
    $helpMenu add command\
        -label "On Command Line"\
        -underline 3\
        -command do-usage
    $helpMenu add command\
        -label "On Preferences"\
        -underline 3\
        -command do-help-preferences
    $helpMenu add separator
    $helpMenu add command\
        -label "About $g(name)"\
        -underline 0\
        -command do-about

    bind $fileMenu <<MenuSelect>> {showTooltip menu %W}
    bind $editMenu <<MenuSelect>> {showTooltip menu %W}
    bind $viewMenu <<MenuSelect>> {showTooltip menu %W}
    bind $markMenu <<MenuSelect>> {showTooltip menu %W}
    bind $mergeMenu <<MenuSelect>> {showTooltip menu %W}
    bind $helpMenu <<MenuSelect>> {showTooltip menu %W}

    set "g(tooltip,On Preferences)" "Show help on the user-settable preferences"
    set "g(tooltip,On GUI)" "Show help on how to use the Graphical User Interface"
    set "g(tooltip,On Command Line)" "Show help on the command line arguments"
    set "g(tooltip,About $g(name))" "Show information about this application"
}

proc showTooltip {which w} {
    global tooltip
    global g
    switch $which {
	menu {
		if {[catch {$w entrycget active -label} label]} {
		    set label ""
		}
		if {[info exists g(tooltip,$label)]} {
		    set g(statusInfo) $g(tooltip,$label)
		} else {
		    set g(statusInfo) $label
		}
		update idletasks
	    }
	button {
		if {[info exists g(tooltip,$w)]} {
		    set g(statusInfo) $g(tooltip,$w)
		} else {
		    set g(statusInfo) ""
		}
		update idletasks
	    }
    }
}

proc build-toolbar {} {
    global w g

    frame $w(toolbar)\
        -bd 2\
        -relief groove
    set toolbar $w(toolbar)

    # these are shorthand used only in this routine...
    set find $toolbar.find
    set prevDiff $toolbar.prev
    set firstDiff $toolbar.first
    set lastDiff $toolbar.last
    set nextDiff $toolbar.next
    set centerDiffs $toolbar.center
    set mergeChoice1 $toolbar.m1
    set mergeChoice2 $toolbar.m2
    set mergeChoice12 $toolbar.m12
    set mergeChoice21 $toolbar.m21
    set mergeChoiceLbl $toolbar.mlabel
    set currentPos $toolbar.cp
    set combo $toolbar.combo
    set rediff $toolbar.rediff
    set markclear $toolbar.clearMark
    set markset $toolbar.setMark

    # these, however, are used in other places..
    set w(find) $find
    set w(prevDiff) $prevDiff
    set w(firstDiff) $firstDiff
    set w(lastDiff) $lastDiff
    set w(nextDiff) $nextDiff
    set w(centerDiffs) $centerDiffs
    set w(mergeChoice1) $mergeChoice1
    set w(mergeChoice2) $mergeChoice2
    set w(mergeChoice12) $mergeChoice12
    set w(mergeChoice21) $mergeChoice21
    set w(currentPos) $currentPos
    set w(combo) $combo
    set w(mergeChoiceLabel) $mergeChoiceLbl
    set w(rediff) $rediff
    set w(markSet) $markset
    set w(markClear) $markclear

    label $currentPos\
        -textvariable g(pos)

    # some separators we'll use in other places
    toolsep $toolbar.sep1
    toolsep $toolbar.sep2
    toolsep $toolbar.sep3
    toolsep $toolbar.sep4
    toolsep $toolbar.sep5
    toolsep $toolbar.sep6
    toolsep $toolbar.sep7
    toolsep $toolbar.sep8

    # rediff...
    toolbutton $rediff\
        -text "Rediff"\
        -width 6\
        -command recompute-diff

    # find...
    toolbutton $find\
        -text "Find"\
        -width 5\
        -command do-find\
        -bd 1

    # navigation widgets
    toolbutton $prevDiff\
        -text "Prev"\
        -width 5\
        -command [list move -1]\
        -bd 1
    toolbutton $nextDiff\
        -text "Next"\
        -width 5\
        -command [list move 1]\
        -bd 1
    toolbutton $firstDiff\
        -text "First"\
        -width 5\
        -command [list move first]\
        -bd 1
    toolbutton $lastDiff\
        -text "Last"\
        -width 5\
        -command [list move last]\
        -bd 1
    toolbutton $centerDiffs\
        -text "Center"\
        -width 5\
        -command center\
        -bd 1

    toolbutton $markset\
        -text "Set Mark"\
        -width 10\
        -command [list diffmark set]\
        -bd 1
    toolbutton $markclear\
        -text "Clear Mark"\
        -width 10\
        -command [list diffmark clear]\
        -bd 1

    ::combobox::combobox $combo\
        -editable false\
        -width 30\
        -command moveTo

    # the merge widgets
    radiobutton $mergeChoice2\
        -borderwidth 1\
        -indicatoron true\
        -text Right\
        -value 2\
        -variable g(toggle)\
        -command [list do-merge-choice 2]\
        -takefocus 0
    radiobutton $mergeChoice1\
        -borderwidth 1\
        -indicatoron true\
        -text Left\
        -value 1\
        -variable g(toggle)\
        -command [list do-merge-choice 1]\
        -takefocus 0
    radiobutton $mergeChoice12\
        -borderwidth 1\
        -indicatoron true\
        -text Left\
        -value 12\
        -variable g(toggle)\
        -command [list do-merge-choice 12]\
        -takefocus 0
    radiobutton $mergeChoice21\
        -borderwidth 1\
        -indicatoron true\
        -text Left\
        -value 21\
        -variable g(toggle)\
        -command [list do-merge-choice 21]\
        -takefocus 0

    # this is gross. We want the label next to the radiobuttons to
    # be disabled if the radiobuttons are disabled. But, labels can't
    # be disabled, so we'll use a "dead" button
    button $mergeChoiceLbl\
        -text "Merge Choice:"\
        -borderwidth 0\
        -command {}\
        -highlightthickness 0

    pack $combo\
        -side left\
        -padx 2
    pack $toolbar.sep1\
        -side left\
        -fill y\
        -pady 2\
        -padx 2
    pack $rediff\
        -side left\
        -padx 2
    pack $toolbar.sep6\
        -side left\
        -fill y\
        -pady 2\
        -padx 2
    pack $find\
        -side left\
        -padx 2
    pack $toolbar.sep2\
        -side left\
        -fill y\
        -pady 2\
        -padx 2
    pack $mergeChoiceLbl $mergeChoice12 $mergeChoice1 $mergeChoice2 $mergeChoice21\
        -side left\
        -padx 2
    pack $toolbar.sep5\
        -side left\
        -fill y\
        -pady 2\
        -padx 3
    pack $firstDiff $lastDiff $prevDiff $nextDiff\
        -side left\
        -pady 2\
        -padx 0
    pack $toolbar.sep3\
        -side left\
        -fill y\
        -pady 2\
        -padx 2
    pack $centerDiffs\
        -side left\
        -pady 2\
        -padx 0
    pack $toolbar.sep7\
        -side left\
        -fill y\
        -pady 2\
        -padx 2
    pack $markset $markclear\
        -side left\
        -padx 2
    pack $toolbar.sep8\
        -side left\
        -fill y\
        -pady 2\
        -padx 2

    # these bindings provide pseudo-tooltips. Note that if some menu
    # items change, these references need to be updated... Also, we
    # assume the menubar tooltips have already been defined....
    set g(tooltip,$markset) $g(tooltip,Mark Current Diff)
    set g(tooltip,$markclear) $g(tooltip,Clear Current Diff Mark)

    set g(tooltip,$combo) "Shows current difference record; allows you to go to a specific difference."
    set g(tooltip,$prevDiff) $g(tooltip,Previous Diff)

    set g(tooltip,$nextDiff) $g(tooltip,Next Diff)

    set g(tooltip,$firstDiff) $g(tooltip,First Diff)

    set g(tooltip,$lastDiff) $g(tooltip,Last Diff)

    set g(tooltip,$centerDiffs) $g(tooltip,Center Current Diff)

    set g(tooltip,$find) $g(tooltip,Find...)

    set g(tooltip,$rediff) $g(tooltip,Recompute Diffs)

    set g(tooltip,$mergeChoice1) "select the diff record on the left for merging"
    set g(tooltip,$mergeChoice2) "select the diff record on the right for merging"
    set g(tooltip,$mergeChoice12) "select the diff record on the left then right for merging"
    set g(tooltip,$mergeChoice21) "select the diff record on the right then left for merging"

    # the toolbuttons have support for tooltips, the combobox and
    # radiobuttons do not. But, we can use the same callback.
    foreach widget [list $combo $mergeChoice1 $mergeChoice2 $mergeChoice12 $mergeChoice21] {
	bind $widget <Enter> +[list toolbutton:handleEvent <Enter> %W 0]
	bind $widget <Leave> +[list toolbutton:handleEvent <Leave> %W 0]
	bind $widget <FocusIn> +[list toolbutton:handleEvent <FocusIn> %W 0]
	bind $widget <FocusOut> +[list toolbutton:handleEvent <FocusOut> %W 0]
    }

    # this adjusts the image or label on the buttons according to the
    # user preferences
    reconfigure-toolbar
}

proc reconfigure-toolbar {} {
    global opts
    global w

    # standard button reliefs
    foreach button [list prevDiff nextDiff firstDiff lastDiff centerDiffs find markSet markClear rediff] {
	if {$opts(fancyButtons)} {
	    $w($button) configure\
	        -relief flat
	} else {
	    $w($button) configure\
	        -relief raised
	}
    }

    # diff mark buttons relief
    foreach widget [info commands $w(toolbar).mark*] {
	if {$opts(fancyButtons)} {
	    $widget configure\
	        -relief flat
	} else {
	    $widget configure\
	        -relief raised
	}
    }

    # standard button images and labels
    foreach button [list prevDiff nextDiff firstDiff lastDiff centerDiffs find markSet markClear rediff] {
	if {$opts(toolbarIcons)} {
	    $w($button) configure\
	        -width 20\
	        -image ${button}Image
	} else {
	    if {$button == "markSet" || $button == "markClear"} {
		$w($button) configure\
		    -width 10\
		    -image {}
	    } else {
		$w($button) configure\
		    -width 5\
		    -image {}
	    }
	}
    }

    # merge choice buttons images and labels
    if {$opts(toolbarIcons)} {
	foreach button [list mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21] {
	    $w($button) configure\
	        -indicatoron false\
	        -image ${button}Image
	}
	# this, in effect, hides the text of the label without
	# actually destroying it
	$w(mergeChoiceLabel) configure\
	    -image nullImage

    } else {
	$w(mergeChoiceLabel) configure\
	    -image {}
	foreach button [list mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21] {
	    $w($button) configure\
	        -indicatoron true\
	        -image {}
	}
    }
}

proc build-status {} {
    global w
    global g

    frame $w(status)\
        -bd 1\
        -relief flat

    set w(statusLabel) $w(status).label
    set w(statusCurrent) $w(status).current

    label $w(statusCurrent)\
        -textvariable g(statusCurrent)\
        -anchor e\
        -width 14\
        -borderwidth 1\
        -relief sunken\
        -padx 4\
        -pady 2
    label $w(statusLabel)\
        -textvariable g(statusInfo)\
        -anchor w\
        -width 1\
        -borderwidth 1\
        -relief sunken\
        -pady 2
    pack $w(statusCurrent)\
        -side right\
        -fill y\
        -expand n
    pack $w(statusLabel)\
        -side left\
        -fill both\
        -expand y
}

###############################################################################
# handles events over the map
###############################################################################
proc handleMapEvent {event y} {
    global opts
    global w
    global g

    switch $event {
	B1-Press {
		set ty1 [lindex $g(thumbBbox) 1]
		set ty2 [lindex $g(thumbBbox) 3]
		if {$y >= $ty1 && $y <= $ty2} {
		    set g(mapScrolling) 1
		}
	    }
	B1-Motion {
		if {[info exists g(mapScrolling)]} {
		    map-seek $y
		}
	    }
	B1-Release {
		show-info ""
		set ty1 [lindex $g(thumbBbox) 1]
		set ty2 [lindex $g(thumbBbox) 3]
		# if we release over the trough (actually, *not* over the thumb),
		# just scroll by the size of the thumb
		if {$y < $ty1 || $y > $ty2} {
		    if {$y < $ty1} {
			# if vertical scrollbar syncing is turned on,
			# all the other windows should toe the line
			# appropriately...
			$w(RightText) yview scroll\
			    -1 pages
		    } else {
			$w(RightText) yview scroll 1 pages
		    }

		} else {
		    # do nothing
		}

		catch {unset g(mapScrolling)}
	    }
    }
}

# makes a toolbar "separator"
proc toolsep {w} {
    label $w\
        -image [image create photo]\
        -highlightthickness 0\
        -bd 1\
        -width 0\
        -relief groove
    return $w
}

proc toolbutton {w args} {
    global tcl_platform
    global opts

    # create the button
    eval button $w $args

    # add minimal tooltip-like support
    bind $w <Enter> [list toolbutton:handleEvent <Enter> %W]
    bind $w <Leave> [list toolbutton:handleEvent <Leave> %W]
    bind $w <FocusIn> [list toolbutton:handleEvent <FocusIn> %W]
    bind $w <FocusOut> [list toolbutton:handleEvent <FocusOut> %W]

    # give a taste of the MS Windows "look and feel"
    if {$opts(fancyButtons)} {
	$w configure\
	    -relief flat
    }

    return $w
}

# handle events in our fancy toolbuttons...
proc toolbutton:handleEvent {event w {isToolbutton 1}} {
    global g
    global opts

    switch $event {
	"<Enter>" {
		showTooltip button $w
		if {$opts(fancyButtons) && $isToolbutton && [$w cget -state] == "normal"} {
		    $w configure\
		        -relief raised
		}
	    }
	"<Leave>" {
		set g(statusInfo) ""
		if {$opts(fancyButtons) && $isToolbutton} {
		    $w configure\
		        -relief flat
		}
	    }
	"<FocusIn>" {
		showTooltip button $w
		if {$opts(fancyButtons) && $isToolbutton && [$w cget -state] == "normal"} {
		    $w configure\
		        -relief raised
		}
	    }
	"<FocusOut>" {
		set g(statusInfo) ""
		if {$opts(fancyButtons) && $isToolbutton} {
		    $w configure\
		        -relief flat
		}
	    }
    }
}

###############################################################################
# move the map thumb to correspond to current shown merge...
###############################################################################
proc map-move-thumb {y1 y2} {
    global g
    global w

    set thumbheight [expr {($y2 - $y1) * $g(mapheight)}]
    if {$thumbheight < $g(thumbMinHeight)} {
	set thumbheight $g(thumbMinHeight)
    }

    if {![info exists g(mapwidth)]} {
	set g(mapwidth) 0
    }
    set x1 1
    set x2 [expr {$g(mapwidth) - 3}]

    # why -2? it's the thickness of our border...
    set y1 [expr {int(($y1 * $g(mapheight)) - 2)}]
    if {$y1 < 0} {
	set y1 0
    }

    set y2 [expr {$y1 + $thumbheight}]
    if {$y2 > $g(mapheight)} {
	set y2 $g(mapheight)
	set y1 [expr {$y2 - $thumbheight}]
    }

    set dx1 [expr {$x1 + 1}]
    set dx2 [expr {$x2 - 1}]
    set dy1 [expr {$y1 + 1}]
    set dy2 [expr {$y2 - 1}]

    $w(mapCanvas) coords thumbUL $x1 $y2 $x1 $y1 $x2 $y1 $dx2 $dy1 $dx1 $dy1 $dx1 $dy2
    $w(mapCanvas) coords thumbLR $dx1 $y2 $x2 $y2 $x2 $dy1 $dx2 $dy1 $dx2 $dy2 $dx1 $dy2

    set g(thumbBbox) [list $x1 $y1 $x2 $y2]
    set g(thumbHeight) $thumbheight
}

###############################################################################
# Bind keys for Next, Prev, Center, Merge choices 1 and 2
#
# N.B. This is GROSS! It might have been necessary in earlier versions,
# but now I think it needs a serious rewriite. We are now overriding
# the text widget, so we can probably just disable the insert and delete
# commands, and use something like insert_ and delete_ internally.
###############################################################################
proc common-navigation {args} {
    global w

    bind . <Control-f> do-find

    foreach widget $args {
	# this effectively disables the widget, without having to
	# resort to actually disabling the widget (the latter which
	# has some annoying side effects). What we really want is to
	# only disable keys that get inserted, but that's difficult
	# to do, and this works almost as well...
	bind $widget <KeyPress> {break}

	bind $widget <Alt-KeyPress> {continue}

	bind $widget <<Paste>> {break}


	# ... but now we need to restore some navigation key bindings
	# which got lost because we disable all keys. Since we are 
	# attaching bindings that duplicate class bindings, we need
	# to be sure and include the break, so the events don't fire
	# twice (once for the widget, once for the class). There is
	# probably a much better way to do all this, but I'm too 
	# lazy to figure it out...
	foreach event [list Next Prior Up Down Left Right Home End] {
	    foreach modifier [list {} Shift Control Shift-Control] {
		set binding [bind Text <${modifier}${event}>]
		if {[string length $binding] > 0} {
		    bind $widget "<${modifier}${event}>" "
			${binding}
			break
		    "
		}
	    }
	}

	# these bindings allow control-f, tab and shift-tab to work
	# in spite of the fact we bound Any-KeyPress to a null action
	bind $widget <Control-f> continue

	bind $widget <Tab> continue

	bind $widget <Shift-Tab> continue


	bind $widget <c> "
	    $w(centerDiffs) invoke
	    break
	"
	bind $widget <n> "
	    $w(nextDiff) invoke
	    break
	"
	bind $widget <p> "
	    $w(prevDiff) invoke
	    break
	"
	bind $widget <f> "
	    $w(firstDiff) invoke
	    break
	"
	bind $widget <l> "
	    $w(lastDiff) invoke
	    break
	"
	bind $widget <q> "
	    do-exit
	    break
	"
	bind $widget <Return> "
	    moveNearest $widget mark insert
	    break
	"

	# these bindings keep Alt- modified keys from triggering
	# the above actions. This way, any Alt combinations that
	# should open a menu will...
	foreach key [list c n p f l] {
	    bind $widget <Alt-$key> {continue}
	}

	bind $widget <Double-1> "
	    moveNearest $widget xy %x %y
	    break
	"

	bind $widget <Key-1> "
	    $w(mergeChoice1) invoke
	    break
	"
	bind $widget <Key-2> "
	    $w(mergeChoice2) invoke
	    break
	"
	bind $widget <Key-3> "
	    $w(mergeChoice12) invoke
	    break
	"
	bind $widget <Key-4> "
	    $w(mergeChoice21) invoke
	    break
	"
    }
}

###############################################################################
# set or clear a "diff mark" -- a hot button to move to a particular diff
###############################################################################

proc diffmark {option {diff -1}} {
    global g
    global w

    if {$diff == -1} {
	set diff $g(pos)
    }

    set widget $w(toolbar).mark$diff

    switch $option {
	activate {
		move $diff 0 1
	    }
	set {
		if {![winfo exists $widget]} {
		    toolbutton $widget\
		        -text "\[$diff\]"\
		        -command [list diffmark activate $diff]\
		        -bd 1
		    pack $widget\
		        -side left\
		        -padx 2
		    set g(tooltip,$widget) "Diff Marker: Jump to diff record number $diff"
		}
		update-display
	    }
	clear {
		if {[winfo exists $widget]} {
		    destroy $widget
		    catch {unset g(tooltip,$widget)}
		}
		update-display
	    }
	clearall {
		foreach widget [info commands $w(toolbar).mark*] {
		    destroy $widget
		    catch {unset g(tooltip,$widget)}
		}
		update-display
	    }
    }
}

###############################################################################
# Customize the display (among other things).
###############################################################################

proc customize {} {
    global pref
    global g
    global w
    global opts
    global tmpopts

    catch {destroy $w(preferences)}
    toplevel $w(preferences)

    wm title $w(preferences) "$g(name) Preferences"
    wm transient $w(preferences) .
    wm group $w(preferences) .

    wm withdraw $w(preferences)

    # the button frame...
    frame $w(preferences).buttons\
        -bd 0
    button $w(preferences).buttons.dismiss\
        -width 8\
        -text "Dismiss"\
        -command {destroy $w(preferences)}
    button $w(preferences).buttons.apply\
        -width 8\
        -text "Apply"\
        -command apply
    button $w(preferences).buttons.save\
        -width 8\
        -text "Save"\
        -command save

    button $w(preferences).buttons.help\
        -width 8\
        -text "Help"\
        -command do-help-preferences

    pack $w(preferences).buttons\
        -side bottom\
        -fill x
    pack $w(preferences).buttons.dismiss\
        -side right\
        -padx 10\
        -pady 5
    pack $w(preferences).buttons.help\
        -side right\
        -padx 10\
        -pady 5
    pack $w(preferences).buttons.save\
        -side right\
        -padx 1\
        -pady 5
    pack $w(preferences).buttons.apply\
        -side right\
        -padx 1\
        -pady 5

    # a series of checkbuttons to act as a poor mans notebook tab
    frame $w(preferences).notebook\
        -bd 0
    pack $w(preferences).notebook\
        -side top\
        -fill x\
        -pady 4
    set pagelist {}
    foreach page [list General Display Appearance] {
	set frame $w(preferences).f$page
	lappend pagelist $frame
	set rb $w(preferences).notebook.f$page
	radiobutton $rb\
	    -command "customize-selectPage $frame"\
	    -variable g(prefPage)\
	    -value $frame\
	    -text $page\
	    -indicatoron false\
	    -width 10\
	    -borderwidth 1

	pack $rb\
	    -side left

	frame $frame\
	    -bd 2\
	    -relief groove\
	    -width 400\
	    -height 300
    }
    set g(prefPage) $w(preferences).fGeneral

    # make sure our labels are defined
    customize-initLabels

    # this is an option that we support internally, but don't give
    # the user a way to directly edit (right now, anyway). But we 
    # need to make sure tmpopts knows about it
    set tmpopts(customCode) $opts(customCode)

    # General
    set count 0
    set frame $w(preferences).fGeneral
    foreach key {diffcmd tmpdir editor geometry} {
	label $frame.l$count\
	    -text "$pref($key): "\
	    -anchor w
	set tmpopts($key) $opts($key)
	entry $frame.e$count\
	    -textvariable tmpopts($key)\
	    -width 50\
	    -bd 2\
	    -relief sunken

	grid $frame.l$count\
	    -row $count\
	    -column 0\
	    -sticky w\
	    -padx 5\
	    -pady 2
	grid $frame.e$count\
	    -row $count\
	    -column 1\
	    -sticky ew\
	    -padx 5\
	    -pady 2

	incr count
    }

    # this is just for filler...
    label $frame.filler\
        -text {}
    grid $frame.filler\
        -row $count
    incr count

    foreach key {fancyButtons toolbarIcons autocenter syncscroll autoselect} {
	label $frame.l$count\
	    -text "$pref($key): "\
	    -anchor w
	set tmpopts($key) $opts($key)
	checkbutton $frame.c$count\
	    -indicatoron true\
	    -text "$pref($key)"\
	    -justify left\
	    -onvalue 1\
	    -offvalue 0\
	    -variable tmpopts($key)

	set tmpopts($key) $opts($key)

	grid $frame.c$count\
	    -row $count\
	    -column 0\
	    -sticky w\
	    -padx 5\
	    -columnspan 2

	incr count
    }

    grid columnconfigure $frame 0\
        -weight 0
    grid columnconfigure $frame 1\
        -weight 1

    # this, in effect, adds a hidden row at the bottom which takes
    # up any extra room

    grid rowconfigure $frame $count\
        -weight 1

    # pack this window for a brief moment, and compute the window
    # size. We'll do this for each "page" and find the largest
    # size to be the size of the dialog
    pack $frame\
        -side right\
        -fill both\
        -expand y
    update idletasks
    set maxwidth [winfo reqwidth $w(preferences)]
    set maxheight [winfo reqheight $w(preferences)]
    pack forget $frame

    # Appearance
    set frame $w(preferences).fAppearance
    set count 0
    foreach key {textopt difftag deltag instag chgtag currtag bytetag overlaptag} {
	label $frame.l$count\
	    -text "$pref($key): "\
	    -anchor w
	set tmpopts($key) $opts($key)
	entry $frame.e$count\
	    -textvariable tmpopts($key)\
	    -bd 2\
	    -relief sunken

	grid $frame.l$count\
	    -row $count\
	    -column 0\
	    -sticky w\
	    -padx 5\
	    -pady 2
	grid $frame.e$count\
	    -row $count\
	    -column 1\
	    -sticky ew\
	    -padx 5\
	    -pady 2

	incr count
    }
    grid columnconfigure $frame 0\
        -weight 0
    grid columnconfigure $frame 1\
        -weight 1

    # tabstops are placed after a little extra whitespace, since it is
    # slightly different than all of the other options (ie: it's not
    # a list of widget options)
    frame $frame.sep$count\
        -bd 0\
        -height 4
    grid $frame.sep$count\
        -row $count\
        -column 0\
        -stick ew\
        -columnspan 2\
        -padx 5\
        -pady 2
    incr count

    set key "tabstops"
    set tmpopts($key) $opts($key)
    label $frame.l$count\
        -text "$pref($key):"\
        -anchor w
    set tmpopts($key) $opts($key)
    entry $frame.e$count\
        -textvariable tmpopts($key)\
        -bd 2\
        -relief sunken\
        -width 3
    grid $frame.l$count\
        -row $count\
        -column 0\
        -sticky w\
        -padx 5\
        -pady 2
    grid $frame.e$count\
        -row $count\
        -column 1\
        -sticky w\
        -padx 5\
        -pady 2
    incr count

    # add a tiny bit of validation, so the user can only enter numbers
    trace variable tmpopts($key) w [list validate integer]

    # this, in effect, adds a hidden row at the bottom which takes
    # up any extra room

    grid rowconfigure $frame $count\
        -weight 1

    pack $frame\
        -side right\
        -fill both\
        -expand y
    update idletasks
    set maxwidth [max $maxwidth [winfo reqwidth $w(preferences)]]
    set maxheight [max $maxheight [winfo reqheight $w(preferences)]]
    pack forget $frame

    # Display
    set frame $w(preferences).fDisplay
    set row 0

    # Option fields
    # Note that the order of the list is used to determine
    # the layout. So, if you add something to the list pay
    # attention to how it affects things.
    #
    # an x means an empty column; a - means an empty row
    set col 0
    foreach key [list showln tagln showcbs tagcbs showmap colorcbs showlineview tagtext -] {

	if {$key == "x"} {
	    set col [expr {$col ? 0 : 1}]
	    if {$col == 0} {
		incr row
	    }
	    continue
	}

	if {$key == "-"} {
	    frame $frame.f${row}\
	        -bd 0\
	        -height 4
	    grid $frame.f${row}\
	        -row $row\
	        -column 0\
	        -columnspan 2\
	        -padx 20\
	        -pady 4\
	        -sticky nsew
	    set col 1 ;# will force next column to zero and incr row

	} else {

	    checkbutton $frame.c${row}${col}\
	        -indicatoron true\
	        -text "$pref($key)"\
	        -onvalue 1\
	        -offvalue 0\
	        -variable tmpopts($key)

	    set tmpopts($key) $opts($key)

	    grid $frame.c${row}$col\
	        -row $row\
	        -column $col\
	        -sticky w\
	        -padx 5
	}

	set col [expr {$col ? 0 : 1}]
	if {$col == 0} {
	    incr row
	}
    }

    grid columnconfigure $frame 0\
        -weight 0
    grid columnconfigure $frame 1\
        -weight 0
    grid columnconfigure $frame 2\
        -weight 0
    grid columnconfigure $frame 3\
        -weight 0
    grid columnconfigure $frame 4\
        -weight 1

    # this, in effect, adds a hidden row at the bottom which takes
    # up any extra room

    grid rowconfigure $frame $row\
        -weight 1

    pack $frame\
        -side right\
        -fill both\
        -expand y
    update idletasks
    set maxwidth [max $maxwidth [winfo reqwidth $w(preferences)]]
    set maxheight [max $maxheight [winfo reqheight $w(preferences)]]
    pack forget $frame

    customize-selectPage

    # compute a reasonable location for the window...
    centerWindow $w(preferences) [list $maxwidth $maxheight]

    wm deiconify $w(preferences)
}

proc validate {type name index op} {
    global tmpopts

    # if we fail the check, attempt to do something clever
    if {![string is $type $tmpopts($index)]} {
	bell

	switch -- $type {
	    integer {
		    regsub\
		        -all {[^0-9]} $tmpopts($index) {} tmpopts($index)
		}
	    default {
		    # this should never happen. If you use this routine, 
		    # make sure you add cases to handle all possible 
		    # values of $type used by this program.
		    set tmpopts($index) ""
		}
	}
    }
}

proc customize-selectPage {{frame {}}} {
    global g w

    if {$frame == ""} {
	set frame $g(prefPage)
    }

    pack forget $w(preferences).fGeneral
    pack forget $w(preferences).fAppearance
    pack forget $w(preferences).fDisplay
    pack forget $w(preferences).fBehavior
    pack $frame\
        -side right\
        -fill both\
        -expand y
}

###############################################################################
# define the labels for the preferences. This is done outside of
# the customize proc since the labels are used in the help text.
###############################################################################
proc customize-initLabels {} {
    global pref

    set pref(diffcmd) {diff command}
    set pref(textopt) {Text widget options}
    set pref(bytetag) {Tag options for characters in line view}
    set pref(difftag) {Tag options for diff regions}
    set pref(currtag) {Tag options for the current diff region}
    set pref(deltag) {Tag options for deleted diff region}
    set pref(instag) {Tag options for inserted diff region}
    set pref(chgtag) {Tag options for changed diff region}
    set pref(overlaptag) {Tag options for overlap diff region}
    set pref(geometry) {Text window size}
    set pref(tmpdir) {Directory for scratch files}
    set pref(editor) {Program for editing files}

    set pref(fancyButtons) {Fancy toolbar buttons}
    set pref(showlineview) {Show current line comparison window}
    set pref(showmap) {Show graphical map of diffs}
    set pref(showln) {Show line numbers}
    set pref(showcbs) {Show change bars}
    set pref(autocenter) {Automatically center current diff region}
    set pref(syncscroll) {Synchronize scrollbars}
    set pref(toolbarIcons) {Use icons instead of labels in the toolbar}

    set pref(colorcbs) {Color change bars to match the diff map}
    set pref(tagtext) {Highlight file contents}
    set pref(tagcbs) {Highlight change bars}
    set pref(tagln) {Highlight line numbers}
    set pref(tabstops) {Tab stops}

    set pref(autoselect) "Automaticallly select the nearest diff region while scrolling"

}

###############################################################################
# Apply customization changes.
###############################################################################

proc apply {{remark 0}} {
    global opts
    global tmpopts
    global w
    global pref

    if {! [file isdirectory $tmpopts(tmpdir)]} {
	do-error "Invalid temporary directory $tmpopts(tmpdir)"
    }

    if {[catch "
	$w(LeftText) configure $tmpopts(textopt)
	$w(RightText) configure $tmpopts(textopt)
	$w(BottomText) configure $tmpopts(textopt)
    "]} {
	do-error "Invalid text widget setting: \n\n'$tmpopts(textopt)'"
	eval "$w(LeftText)   configure $opts(textopt)"
	eval "$w(RightText)  configure $opts(textopt)"
	eval "$w(BottomText) configure $opts(textopt)"
	return
    }

    # the text options must be ok. Configure the other text widgets
    # similarly
    eval "$w(LeftCB)	configure $tmpopts(textopt)"
    eval "$w(LeftInfo)	configure $tmpopts(textopt)"
    eval "$w(RightCB)	configure $tmpopts(textopt)"
    eval "$w(RightInfo) configure $tmpopts(textopt)"

    if {$tmpopts(geometry) == "" || [catch {scan $tmpopts(geometry) "%dx%d" width height} result]} {
	do-error "invalid geometry setting: $tmpopts(geometry)"
	return
    }
    if {[catch {$w(LeftText) configure\
	    -width $width\
	    -height $height} result]} {
	do-error "invalid geometry setting: $tmpopts(geometry)"
	return
    }
    $w(RightText) configure\
        -width $width\
        -height $height


    foreach tag {difftag currtag deltag instag chgtag overlaptag} {
	foreach win [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)] {
	    if {[catch "$win tag configure $tag $tmpopts($tag)"]} {
		do-error "Invalid settings for \"$pref($tag)\": \n\n'$tmpopts($tag)' is not a valid option string"
		eval "$win tag configure $tag $opts($tag)"
		return
	    }
	}
    }

    if {[catch "$w(BottomText) tag configure diff $tmpopts(bytetag)"]} {
	do-error "Invalid settings for \"$pref(bytetag)\":  \n\n'$tmpopts(bytetag)' is not a valid option string"
	eval "$w(BottomText) tag configure diff $opts(bytetag)"
	return
    }

    # tabstops require a little extra work. We need to figure out 
    # the width of an "m" in the widget's font, then multiply that
    # by the tab stop width. For the bottom text widget the first tabstop 
    # is adjusted by two to take into consideration the fact that we
    # add two bytes to each line (ie: "< " or "> ").
    set cwidth [font measure [$w(LeftText) cget -font] "m"]
    set tabstops [expr {$cwidth * $tmpopts(tabstops)}]
    $w(LeftText) configure\
        -tabs $tabstops
    $w(RightText) configure\
        -tabs $tabstops

    $w(BottomText) configure\
        -tabs [list [expr {$tabstops +($cwidth * 2)}] $tabstops]

    if {[info exists w(mergeText)] && [winfo exists $w(mergeText)]} {
	$w(mergeText) configure\
	    -tabs $tabstops
    }

    # set opts to the values from tmpopts
    foreach key {diffcmd textopt difftag currtag deltag instag chgtag overlaptag tmpdir editor showmap showln showcbs showlineview autocenter syncscroll tagln tagcbs tagtext autoselect toolbarIcons geometry\
      fancyButtons colorcbs tabstops} {
	set opts($key) $tmpopts($key)
    }

    # reconfigure the toolbar buttons
    reconfigure-toolbar

    # remark all the diff regions, show (or hide) the line numbers,
    # change bars and diff map, and we are done.
    if {$remark} {
	remark-diffs
    }

    do-show-linenumbers
    do-show-changebars
    do-show-map
    do-show-lineview
}

###############################################################################
# Save customization changes.
###############################################################################

proc save {} {
    global g
    global tmpopts rcfile tcl_platform
    global pref

    if {[file exists $rcfile]} {
	file rename\
	    -force $rcfile "$rcfile~"
    }

    # Need to quote backslashes, replace single \ with double \\
    regsub\
        -all {\\} $tmpopts(tmpdir) {\\\\} tmpdir

    set fid [open $rcfile w]

    # put the tkdiff version in the file. It might be handy later
    puts $fid "# This file was generated by $g(name) $g(version)"
    puts $fid "# [clock format [clock seconds]]\n"
    puts $fid "set prefsFileVersion {$g(version)}\n"

    # now, put all of the preferences in the file
    foreach key {diffcmd textopt difftag currtag deltag instag bytetag overlaptag tabstops chgtag showmap showln showcbs showlineview autocenter syncscroll fancyButtons geometry editor colorcbs autoselect\
      tagln tagcbs tagtext toolbarIcons} {
	regsub "\n" $pref($key) "\n# " comment
	puts $fid "# $comment"
	puts $fid "define $key {$tmpopts($key)}\n"
    }

    # Seems we can't use {$tmpdir} here or embedded \\ don't translate to  
    puts $fid "# $pref(tmpdir)"
    puts $fid "define tmpdir \"$tmpdir\"\n"

    # ... and any custom code
    puts $fid "# custom code"
    puts $fid "# put any custom code you want to be executed in the"
    puts $fid "# following block. This code will be automatically executed"
    puts $fid "# after the GUI has been set up but before the diff is "
    puts $fid "# performed. Use this code to customize the interface if"
    puts $fid "# you so desire."
    puts $fid "#  "
    puts $fid "# Even though you can't (as of version 3.08) edit this "
    puts $fid "# code via the preferences dialog, it will be automatically"
    puts $fid "# saved and restored if you do a SAVE from that dialog."
    puts $fid ""
    puts $fid "# Unless you really know what you are doing, it is probably"
    puts $fid "# wise to leave this unmodified."
    puts $fid ""
    puts $fid "define customCode {\n[string trim $tmpopts(customCode) \n]\n}\n"

    close $fid

    if {$tcl_platform(platform) == "windows"} {
	file attribute $rcfile\
	    -hidden 1
    }
}

###############################################################################
# Text has scrolled, update scrollbars and synchronize windows
###############################################################################

proc hscroll-sync {id args} {
    global g opts
    global w

    # If ignore_event is true, we've already taken care of scrolling.
    # We're only interested in the first event.
    if {$g(ignore_hevent,$id)} {
	return
    }

    # Scrollbar sizes
    set size1 [expr {[lindex [$w(LeftText) xview] 1] - [lindex [$w(LeftText) xview] 0]}]
    set size2 [expr {[lindex [$w(RightText) xview] 1] - [lindex [$w(RightText) xview] 0]}]

    if {$opts(syncscroll) || $id == 1} {
	set start [lindex $args 0]

	if {$id != 1} {
	    set start [expr {$start * $size2 / $size1}]
	}
	$w(LeftHSB) set $start [expr {$start + $size1}]
	$w(LeftText) xview moveto $start
	set g(ignore_hevent,1) 1
    }
    if {$opts(syncscroll) || $id == 2} {
	set start [lindex $args 0]
	if {$id != 2} {
	    set start [expr {$start * $size1 / $size2}]
	}
	$w(RightHSB) set $start [expr {$start + $size2}]
	$w(RightText) xview moveto $start
	set g(ignore_hevent,2) 1
    }

    # This forces all the event handlers for the view alterations
    # above to trigger, and we lock out the recursive (redundant)
    # events using ignore_event.
    update idletasks
    # Restore to normal
    set g(ignore_hevent,1) 0
    set g(ignore_hevent,2) 0
}

###############################################################################
# Text has scrolled, update scrollbars and synchronize windows
###############################################################################

proc vscroll-sync {windowlist id y0 y1} {
    global g opts
    global w

    if {$id == 1} {
	$w(LeftVSB) set $y0 $y1
    } else {
	$w(RightVSB) set $y0 $y1
    }

    # if syncing is disabled, we're done. This prevents a nasty
    # set of recursive calls
    if {[info exists g(disableSyncing)]} {
	return
    }

    # set the flag; this makes sure we only get called once
    set g(disableSyncing) 1

    # scroll the other windows on the same side as this window
    foreach window $windowlist {
	$window yview moveto $y0
    }

    eval map-move-thumb $y0 $y1

    # Select nearest visible diff region, if the appropriate
    # options are set
    if {$opts(syncscroll) && $opts(autoselect) && $g(count) > 0} {
	set winhalf [expr {[winfo height $w(RightText)] / 2}]
	set result [find-diff [expr {int([$w(RightText) index @1,$winhalf])}]]
	set i [lindex $result 0]

	# have we found a diff other than the current diff?
	if {$i != $g(pos)} {
	    # Also, make sure the diff is visible. If not, we won't
	    # change the current diff region...
	    set topline [$w(RightText) index @0,0]
	    set bottomline [$w(RightText) index @0,10000]
	    foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { }
	    if {$s1 >= $topline && $s1 <= $bottomline} {
		move $i 0 1
	    }
	}
    }

    # if syncing is turned on, scroll other windows.
    # Annoyingly, sometimes the *Text windows won't scroll properly,
    # at least under windows. And I can't for the life of me figure
    # out why. Maybe a bug in tk?
    if {$opts(syncscroll)} {
	if {$id == 1} {

	    $w(RightText) yview moveto $y0
	    $w(RightInfo) yview moveto $y0
	    $w(RightCB) yview moveto $y0
	    $w(RightVSB) set $y0 $y1

	} else {

	    $w(LeftText) yview moveto $y0
	    $w(LeftInfo) yview moveto $y0
	    $w(LeftCB) yview moveto $y0
	    $w(LeftVSB) set $y0 $y1
	}
    }

    # we apparently automatically process idle events after this
    # proc is called. Once that is done we'll unset our flag 
    after idle {catch {unset g(disableSyncing)}}

}

###############################################################################
# Make a miniature map of the diff regions
###############################################################################

proc create-map {name mapwidth mapheight} {
    global g
    global w
    global map

    set map $name

    # Text widget always contains blank line at the end
    set lines [expr {double([$w(LeftText) index end]) - 2}]
    set factor [expr {$mapheight / $lines}]

    # We add some transparent stuff to make the map fill the canvas
    # in order to receive mouse events at the very bottom.
    $map blank
    $map put \#000\
        -to 0 $mapheight $mapwidth $mapheight

    # Line numbers start at 1, not at 0.
    for {set i 1} {$i <= $g(count)} {incr i} {
	#	 scan $g(scrdiff,$i) "%s %d %d %d %d %s" line s1 e1 s2 e2 type
	foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { }

	set y [expr {int(($s2 - 1) * $factor) + $g(mapborder)}]
	set size [expr {round(($e2 - $s2 + 1) * $factor)}]
	if {$size < 1} {
	    set size 1
	}
	switch $type {
	    "d" {
		    set color red1
		}
	    "a" {
		    set color green
		}
	    "c" {
		    set color blue
		}
	}
	if { [info exists g(overlap$i) ] } {
	  set color yellow
	}

	$map put $color\
	    -to 0 $y $mapwidth [expr {$y + $size}]

    }

    # let's draw a rectangle to simulate a scrollbar thumb. The size
    # isn't important since it will get resized when map-move-thumb
    # is called...
    $w(mapCanvas) create line 0 0 0 0\
        -tags thumbUL\
        -fill white
    $w(mapCanvas) create line 1 1 1 1\
        -tags thumbLR\
        -fill black
    $w(mapCanvas) raise thumb

    # now, move the thumb
    eval map-move-thumb [$w(LeftText) yview]

}

###############################################################################
# Resize map to fit window size
###############################################################################

proc map-resize {args} {
    global g opts
    global w

    set mapwidth [winfo width $w(map)]
    set g(mapborder) [expr {[$w(map) cget -borderwidth] + [$w(map) cget -highlightthickness]}]
    set mapheight [expr {[winfo height $w(map)] - $g(mapborder) * 2}]

    # We'll get a couple of "resize" events, so don't draw a map
    # unless we've got the diffs and the map size has changed
    if {$g(count) == 0 || $mapheight == $g(mapheight)} {
	return
    }

    # If we don't have a map and don't want one, don't make one
    if {$g(mapheight) == 0 && $opts(showmap) == 0} {
	return
    }

    # This seems to happen on Windows!? _After_ the map is drawn the first time
    # another event triggers and [winfo height $w(map)] is then 0...
    if {$mapheight < 1} {
	return
    }

    set g(mapheight) $mapheight
    set g(mapwidth) $mapwidth
    create-map map $mapwidth $mapheight
}

###############################################################################
# scroll to diff region nearest to y
###############################################################################

proc map-scroll {y} {
    global g
    global w
    global opts

    set yview [expr {double($y) / double($g(mapheight))}]
    # Show text corresponding to map
    catch {$w(RightText) yview moveto $yview} result
    update idletasks

    # Select the diff region closest to the middle of the screen
    set winhalf [expr {[winfo height $w(RightText)] / 2}]
    set result [find-diff [expr {int([$w(RightText) index @1,$winhalf])}]]
    move [lindex $result 0] 0 0

    if {$opts(autocenter)} {
	center
    }

    if {$g(showmerge)} {
	merge-center
    }
}

###############################################################################
# Toggle showing the line comparison window
###############################################################################

proc do-show-lineview {{showLineview {}}} {
    global opts
    global w

    if {$showLineview != {}} {
	set opts(showlineview) $showLineview
    }

    if {$opts(showlineview)} {
	grid $w(BottomText)\
	    -row 3\
	    -column 0\
	    -sticky ew\
	    -columnspan 4
    } else {
	grid forget $w(BottomText)
    }
}

###############################################################################
# Toggle showing map or not
###############################################################################

proc do-show-map {{showMap {}}} {
    global opts
    global w

    if {$showMap != {}} {
	set opts(showmap) $showMap
    }

    if {$opts(showmap)} {
	grid $w(map)\
	    -row 1\
	    -column 1\
	    -stick ns
    } else {
	grid forget $w(map)
    }
}

###############################################################################
# Find the diff nearest to $line.
# Returns "$i $newtop" where $i is the index of the diff region
# and $newtop is the new top line in the window to the right.
###############################################################################

proc find-diff {line} {
    global g
    global w

    set top $line
    set newtop [expr {$top - int([$w(LeftText) index end]) + int([$w(RightText) index end])}]

    for {set low 1; set high $g(count); set i [expr {($low + $high) / 2}]} {$i >= $low} {set i [expr {($low + $high) / 2}]} {

	foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { }

	if {$s1 > $top} {
	    set newtop [expr {$top - $s1 + $s2}]
	    set high [expr {$i-1}]
	} else {
	    set low [expr {$i+1}]
	}
    }

    # do some range checking...
    set i [max 1 [min $i $g(count)]]

    # If next diff is closer than the one found, use it instead
    if {$i > 0 && $i < $g(count)} {
	set nexts1 [lindex $g(scrdiff,[expr {$i + 1}]) 1]
	set e1 [lindex $g(scrdiff,$i) 2]
	if {$nexts1 - $top < $top - $e1} {
	    incr i
	}
    }

    return [list $i $newtop]
}

###############################################################################
# Calculate number of lines in diff region
# pos	    Diff number
# version   1 or 2, left or right window version
# screen    1 for screen size, 0 for original diff size
###############################################################################

proc diff-size {pos version {screen 0}} {
    global g

    if {$screen} {
	set diff scrdiff
    } else {
	set diff pdiff
    }
    #    scan $g($diff,$pos) "%s %d %d %d %d %s"  #	 thisdiff s(1) e(1) s(2) e(2) type
    foreach {thisdiff s(1) e(1) s(2) e(2) type} $g($diff,$pos) { }

    switch $version {
	1 {
		set lines [expr {$e(1) - $s(1) + 1}]
		if {$type == "a"} {
		    incr lines -1
		}
	    }
	2 {
		set lines [expr {$e(2) - $s(2) + 1}]
		if {$type == "d"} {
		    incr lines -1
		}
	    }
	12 -
	21 {
		set lines [expr {$e(1) - $s(1) + $e(2) - $s(2) + 1}]
	    }
    }
    return $lines
}

###############################################################################
# Toggle showing merge preview or not
###############################################################################

proc do-show-merge {{showMerge ""}} {
    global g
    global w

    if {$showMerge != ""} {
	set g(showmerge) $showMerge
    }

    if {$g(showmerge)} {
	set-cursor
	wm deiconify $w(merge)
	$w(mergeText) configure\
	    -state disabled
	focus\
	    -force $w(mergeText)
	merge-center
	restore-cursor
    } else {
	wm withdraw $w(merge)
	restore-cursor
    }
}

###############################################################################
# Create Merge preview window
###############################################################################

proc merge-create-window {} {
    global opts
    global w
    global g

    set top .merge
    set w(merge) $top

    catch {destroy $top}

    toplevel $top
    set x [expr {[winfo rootx .] + 0}]
    set y [expr {[winfo rooty .] + 0}]
    wm geometry $top "+${x}+${y}"

    wm group $top .
    wm transient $top .

    wm title $top "$g(name) Merge Preview"

    frame $top.frame\
        -bd 1\
        -relief sunken
    pack $top.frame\
        -side top\
        -fill both\
        -expand y\
        -padx 10\
        -pady 10

    set w(mergeText) $top.frame.text
    set w(mergeVSB) $top.frame.vsb
    set w(mergeHSB) $top.frame.hsb
    set w(mergeDismiss) $top.dismiss
    set w(mergeWrite) $top.mergeWrite
    set w(mergeWriteAndExit) $top.mergeWriteAndExit
    set w(mergeExit) $top.mergeExit
    set w(mergeRecenter) $top.mergeRecenter

    # Window and scrollbars
    scrollbar $w(mergeHSB)\
        -orient horizontal\
        -command [list $w(mergeText) xview]
    scrollbar $w(mergeVSB)\
        -orient vertical\
        -command [list $w(mergeText) yview]

    text $w(mergeText)\
        -bd 0\
        -takefocus 1\
        -yscrollcommand [list $w(mergeVSB) set]\
        -xscrollcommand [list $w(mergeHSB) set]

    grid $w(mergeText)\
        -row 0\
        -column 0\
        -sticky nsew
    grid $w(mergeVSB)\
        -row 0\
        -column 1\
        -sticky ns
    grid $w(mergeHSB)\
        -row 1\
        -column 0\
        -sticky ew

    grid rowconfigure $top.frame 0\
        -weight 1
    grid rowconfigure $top.frame 1\
        -weight 0

    grid columnconfigure $top.frame 0\
        -weight 1
    grid columnconfigure $top.frame 1\
        -weight 0

    # buttons
    button $w(mergeRecenter)\
        -width 8\
        -text "ReCenter"\
        -underline 0\
        -command merge-center

    button $w(mergeDismiss)\
        -width 8\
        -text "Dismiss"\
        -underline 0\
        -command [list do-show-merge 0]

    button $w(mergeWrite)\
        -width 8\
        -text "Save"\
        -underline 0\
        -command [list popup-merge merge-write-file]

    button $w(mergeWriteAndExit)\
        -width 8\
        -text "Save & Exit"\
        -underline 8\
        -command { popup-merge merge-write-file ; exit }

    button $w(mergeExit)\
        -width 8\
        -text "Exit TkDiff"\
        -underline 0\
        -command { exit }

    pack $w(mergeDismiss)\
        -side right\
        -pady 5\
        -padx 10
    pack $w(mergeRecenter)\
        -side right\
        -pady 5\
        -padx 1
    pack $w(mergeWrite)\
        -side right\
        -pady 5\
        -padx 1
    pack $w(mergeWriteAndExit)\
        -side right\
        -pady 5\
        -padx 1
    pack $w(mergeExit)\
        -side right\
        -pady 5\
        -padx 1

    eval $w(mergeText) configure $opts(textopt)
    foreach tag {difftag currtag} {
	eval $w(mergeText) tag configure $tag $opts($tag)
    }

    # adjust the tabstops
    set cwidth [font measure [$w(mergeText) cget -font] "m"]
    set tabstops [expr {$cwidth * $opts(tabstops)}]
    $w(mergeText) configure\
        -tabs $tabstops

    wm protocol $w(merge) WM_DELETE_WINDOW {do-show-merge 0}

    # adjust the tag priorities a bit...
    $w(mergeText) tag raise sel
    $w(mergeText) tag raise currtag difftag

    common-navigation $w(mergeText)


    wm withdraw $w(merge)
}

###############################################################################
# Read original file (Left window file) into merge preview window.
# Not so good if it has changed.
###############################################################################

proc merge-read-file {} {
    global finfo
    global w

    # hack; need to find a cleaner way...
    catch {destroy .merge}
    merge-create-window

    set hndl [open "$finfo(pth,1)" r]
    $w(mergeText) configure\
        -state normal
    $w(mergeText) delete 1.0 end
    $w(mergeText) insert 1.0 [read $hndl]
    close $hndl

    # If last line doesn't end with a newline, add one. Important when
    # writing out the merge preview.
    if {![regexp {\.0$} [$w(mergeText) index "end-1lines lineend"]]} {
	$w(mergeText) insert end "\n"
    }
    $w(mergeText) configure\
        -state disabled
}

###############################################################################
# Write merge preview to file
###############################################################################

proc merge-write-file {} {
    global g
    global w

    set hndl [open "$g(mergefile)" w]
    set text [$w(mergeText) get 1.0 end-1lines]
    puts\
        -nonewline $hndl $text
    close $hndl
}

###############################################################################
# Add a mark where each diff begins and tag diff regions so they are visible.
# Assumes text is initially the bare original (Left) version.
###############################################################################
proc merge-add-marks {} {
    global g
    global w

    # mark all lines first, so selection won't mess up line numbers
    for {set i 1} {$i <= $g(count)} {incr i} {
	foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$i) { }
	#	set delta [expr {$type == "a" ? 1 : 0}]
	#	$w(mergeText) mark set mark$i $s1.0+${delta}lines
	if {$type == "a"} {
	    incr s1
	}
	$w(mergeText) mark set mark$i $s1.0
	$w(mergeText) mark gravity mark$i left
    }

    # if a 3-way merge, select right window as needed
    if {$g(ancfileset) && $g(count) > 0} { 
	#
	# By default, select the right window
	#
	for {set i 1} {$i <= $g(count)} {incr i} {
	    set g(merge$i) 2
	}
	#
	# If there was something different between file1
	# and the ancestor, pick the left window, but...
	#
	set i 1
	set s1 [lindex $g(pdiff,$i) 1]
	foreach as1 $g(diff3l) {
	    while {$as1 >= $s1} {
		if {$as1 == $s1} {
		    set g(merge$i) 1
		}
		if {$i >= $g(count)} break
		incr i
		set s1 [lindex $g(pdiff,$i) 1]
	    }
	}
	#
	# ... if there was also a diff between file2 and the ancestor,
	# then file2 takes precedence
	#
	set i 1
	set s1 [lindex $g(pdiff,$i) 1]
	foreach as1 $g(diff3r) {
	    while {$as1 >= $s1} {
		if {$as1 == $s1} {
		    set g(merge$i) 2
		}
		if {$i >= $g(count)} break
		incr i
		set s1 [lindex $g(pdiff,$i) 1]
	    }
	}
    }

    # select merged lines
    for {set i 1} {$i <= $g(count)} {incr i} {
	foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$i) { }

	if {$g(merge$i) == 1} {
	    # (If it's an insert it's not visible)
	    if {$type != "a"} {
		set lines [expr {$e1 - $s1 + 1}]
		$w(mergeText) tag add difftag mark$i mark$i+${lines}lines
	    }
	} else {
	    # Insert right window version
	    merge-select-version $i 1 2
	}
    }

    # Tag current
    if {$g(count) > 0} {
	set pos $g(pos)
	set lines [diff-size $pos $g(merge$pos)]
	$w(mergeText) tag add currtag mark$pos "mark$pos+${lines}lines"
    }
}

###############################################################################
# Add a mark where each diff begins
# pos	       diff index
# oldversion   1 or 2, previous merge choice
# newversion   1 or 2, new merge choice
###############################################################################

proc merge-select-version {pos oldversion newversion} {
    global g
    global w

    catch {
	switch $oldversion {
	    1 -
	    2 {set oldlines [diff-size $pos $oldversion]}
	    12 -
	    21 {set oldlines [expr {[diff-size $pos 1] + [diff-size $pos 2]}]}
	}
	$w(mergeText) configure\
	    -state normal
	$w(mergeText) delete mark$pos "mark${pos}+${oldlines}lines"
	$w(mergeText) configure\
	    -state disabled
    }

    # Screen coordinates
    foreach {thisdiff s(1) e(1) s(2) e(2) type} $g(scrdiff,$pos) { }

    # Get the text directly from window
    switch $newversion {
	1 {
		set newlines [diff-size $pos 1]
		set newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines]
	    }
	2 {
		set newlines [diff-size $pos 2]
		set newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines]
	    }
	12 {
		set newlines [diff-size $pos 1]
		set newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines]
		set newlines [diff-size $pos 2]
		append newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines]
		incr newlines [diff-size $pos 1]
	    }
	21 {
		set newlines [diff-size $pos 2]
		set newtext [$w(RightText) get $s(2).0 $s(2).0+${newlines}lines]
		set newlines [diff-size $pos 1]
		append newtext [$w(LeftText) get $s(1).0 $s(1).0+${newlines}lines]
		incr newlines [diff-size $pos 2]
	    }
    }

    # Insert it
    $w(mergeText) configure\
        -state normal
    $w(mergeText) insert mark$pos $newtext diff
    $w(mergeText) configure\
        -state disabled
    if {$pos == $g(pos)} {
	$w(mergeText) tag add currtag mark$pos "mark${pos}+${newlines}lines"
    }
}

###############################################################################
# Center the merge region in the merge window
###############################################################################

proc merge-center {} {
    global g
    global w

    # bail if there are no diffs
    if { $g(count) == 0 } {
	return
    }
    # Size of diff in lines of text
    set difflines [diff-size $g(pos) $g(merge$g(pos))]
    set yview [$w(mergeText) yview]
    # Window height in percent
    set ywindow [expr {[lindex $yview 1] - [lindex $yview 0]}]
    # First line of diff
    set firstline [$w(mergeText) index mark$g(pos)]
    # Total number of lines in window
    set totallines [$w(mergeText) index end]

    if {$difflines / $totallines < $ywindow} {
	# Diff fits in window, center it
	$w(mergeText) yview moveto [expr {($firstline + $difflines / 2) / $totallines - $ywindow / 2}]
    } else {
	# Diff too big, show top part
	$w(mergeText) yview moveto [expr {($firstline - 1) / $totallines}]
    }
}

###############################################################################
# Update the merge preview window with the current merge choice
# newversion   1 or 2, new merge choice
###############################################################################

proc do-merge-choice {newversion} {
    global g opts
    global w

    $w(mergeText) configure\
        -state normal
    merge-select-version $g(pos) $g(merge$g(pos)) $newversion
    $w(mergeText) configure\
        -state disabled

    set g(merge$g(pos)) $newversion
    if {$g(showmerge) && $opts(autocenter)} {
	merge-center
    }
}

###############################################################################
# Extract the start and end lines for file1 and file2 from the diff
# stored in "line".
###############################################################################

proc extract {line} {
    # the line darn well better be of the form <range><op><range>,
    # where op is one of "a","c" or "d". range will either be a
    # single number or two numbers separated by a comma.

    # is this a cool regular expression, or what? :-)
    regexp {([0-9]*)(,([0-9]*))?([a-z])([0-9]*)(,([0-9]*))?} $line matchvar s1 x e1 op s2 x e2
    if {[string length $e1] == 0} {
	set e1 $s1
    }
    if {[string length $e2] == 0} {
	set e2 $s2
    }

    if {[info exists s1] && [info exists s2]} {
	#	 return "$line $s1 $e1 $s2 $e2 $op"
	return [list $line $s1 $e1 $s2 $e2 $op]
    } else {
	fatal-error "Cannot parse output from diff:\n$line"
    }

}

###############################################################################
# Insert blank lines to match added/deleted lines in other file
###############################################################################

proc add-lines {pos} {
    global g
    global w

    # Figure out which lines we need to address...
    foreach [list thisdiff s1 e1 s2 e2 type] $g(pdiff,$pos) { }

    set size(1) [expr {$e1 - $s1}]
    set size(2) [expr {$e2 - $s2}]

    incr s1 $g(delta,1)
    incr s2 $g(delta,2)

    # Figure out what kind of diff we're dealing with
    switch $type {
	"a" {
		set lefttext " " ;# insert
		set righttext "+"
		set idx 1
		set count [expr {$size(2) + 1}]

		incr s1
		incr size(2)
	    }
	"d" {
		set lefttext "-" ;# delete
		set righttext " "
		set idx 2
		set count [expr {$size(1) + 1}]

		incr s2
		incr size(1)
	    }
	"c" {
		set lefttext "!" ;# change
		set righttext "!" ;# change
		if { $g(ancfileset) } {
		  set change $g(pdiff,$g(count))
		  set leftBegin [lindex $change 1]
		  set leftEnd [lindex $change 2]
		  set rightBegin [lindex $change 3]
		  set rightEnd [lindex $change 4]

		  set changeLeft 0
		  set changeRight 0
		  for {set i $leftBegin} {$i <= $leftEnd} {incr i} {
		    if { [info exists g(diff3l$i) ] } {
		      set changeLeft 1
		      break
		    }
		  }
		  if { $changeLeft } {
		    for {set i $rightBegin} {$i <= $rightEnd} {incr i} {
		      if { [info exists g(diff3r$i) ] } {
		        set changeRight 1
		        break
		      }
		    }
		  }
	          if { $changeLeft && $changeRight } {
			set lefttext "?" ;# overlap
			set righttext "?" ;# overlap
			set g(overlap$pos) 1
		  }
		}
		set idx [expr {$size(1) < $size(2) ? 1 : 2}]
		set count [expr {abs($size(1) - $size(2))}]

		incr size(1)
		incr size(2)
	    }
    }

    # Put plus signs in left info column
    if {$idx == 1} {
	set textWidget $w(LeftText)
	set infoWidget $w(LeftInfo)
	set cbWidget $w(LeftCB)
	#	set blank "++++++\n"
	set blank "	 \n"
    } else {
	set textWidget $w(RightText)
	set infoWidget $w(RightInfo)
	set cbWidget $w(RightCB)
	set blank "	 \n"
    }

    # Insert blank lines to match other window
    set line [expr {$s1 + $size($idx)}]
    for {set i 0} {$i < $count} {incr i} {
	$textWidget insert $line.0 "\n"
	$infoWidget insert $line.0 $blank
	$cbWidget insert $line.0 "\n"
    }

    incr size($idx) $count
    set e1 [expr {$s1 + $size(1) - 1}]
    set e2 [expr {$s2 + $size(2) - 1}]
    incr g(delta,$idx) $count

    # Insert change bars or text to show what has changed.
    $w(RightCB) configure\
        -state normal
    $w(LeftCB) configure\
        -state normal
    for {set i $s1} {$i <= $e1} {incr i} {
	$w(LeftCB) insert $i.0 $lefttext
	$w(RightCB) insert $i.0 $righttext
    }

    # Save the diff block in window coordinates
    set g(scrdiff,$g(count)) [list $thisdiff $s1 $e1 $s2 $e2 $type]
}

###############################################################################
# Add a tag to a region.
###############################################################################

proc add-tag {wgt tag start end type new {exact 0}} {
    global g

    $wgt tag add $tag $start.0 [expr {$end + 1}].0

}

###############################################################################
# Change the tag for a diff region.
# 'pos' is the index in the diff array
# If 'oldtag' is present, first remove it from the region
# If 'setpos' is non-zero, make sure the region is visible.
# Returns the diff expression.
###############################################################################

proc set-tag {pos newtag {oldtag ""} {setpos 0}} {
    global g opts
    global w

    # Figure out which lines we need to address...
    if {![info exists g(scrdiff,$pos)]} {
	return
    }
    foreach {thisdiff s1 e1 s2 e2 dt} $g(scrdiff,$pos) { }

    # Remove old tag
    if {"$oldtag" != ""} {
	set e1next "[expr {$e1 + 1}].0"
	set e2next "[expr {$e2 + 1}].0"
	$w(LeftText) tag remove $oldtag $s1.0 $e1next
	$w(LeftInfo) tag remove $oldtag $s1.0 $e1next
	$w(RightText) tag remove $oldtag $s2.0 $e2next
	$w(RightInfo) tag remove $oldtag $s2.0 $e2next
	$w(LeftCB) tag remove $oldtag $s1.0 $e1next
	$w(RightCB) tag remove $oldtag $s2.0 $e2next
	catch {
	    set lines [diff-size $pos $g(merge$pos)]
	    $w(mergeText) tag remove $oldtag mark$pos "mark${pos}+${lines}lines"
	}
    }

    switch $dt {
	"d" {
		set coltag deltag
		set rcbtag " "
		set lcbtag "-"
	    }
	"a" {
		set coltag instag
		set rcbtag "+"
		set lcbtag " "
	    }
	"c" {
		set coltag chgtag
		set rcbtag "!"
		set lcbtag "!"
	    }
    }
    if { [ info exists g(overlap$pos) ] } {
		set coltag overlaptag
		set rcbtag "?"
		set lcbtag "?"
    }
    # Add new tag
    if {$opts(tagtext)} {
	add-tag $w(LeftText) $newtag $s1 $e1 $dt 1
	add-tag $w(RightText) $newtag $s2 $e2 $dt 1
	add-tag $w(RightText) $coltag $s2 $e2 $dt 1
    }
    if {$opts(tagcbs)} {
	if {$opts(colorcbs)} {
	    add-tag $w(LeftCB) $lcbtag $s1 $e1 $dt 1
	    add-tag $w(RightCB) $rcbtag $s2 $e2 $dt 1
	} else {
	    add-tag $w(LeftCB) $newtag $s1 $e1 $dt 1
	    add-tag $w(RightCB) $newtag $s2 $e2 $dt 1
	    add-tag $w(RightCB) $coltag $s2 $e2 $dt 1
	}

    }
    if {$opts(tagln)} {
	add-tag $w(LeftInfo) $newtag $s1 $e1 $dt 1
	add-tag $w(RightInfo) $newtag $s2 $e2 $dt 1
	add-tag $w(RightInfo) $coltag $s2 $e2 $dt 1
    }

    catch {
	set lines [diff-size $pos $g(merge$pos)]
	$w(mergeText) tag add $newtag mark$pos "mark${pos}+${lines}lines"
    }

    # Move the view on both text widgets so that the new region is
    # visible.
    if {$setpos} {
	if {$opts(autocenter)} {
	    center
	} else {
	    $w(LeftText) see $s1.0
	    $w(RightText) see $s2.0
	    $w(LeftText) mark set insert $s1.0
	    $w(RightText) mark set insert $s2.0

	    if {$g(showmerge)} {
		$w(mergeText) see mark$pos
	    }
	}
    }

    # make sure the sel tag has the highest priority
    foreach window [list LeftText RightText LeftCB RightCB LeftInfo RightInfo] {
	$w($window) tag raise sel
    }

    return $thisdiff
}

###############################################################################
# moves to the diff nearest the insertion cursor or the mouse click,
# depending on $mode (which should be either "xy" or "mark")
###############################################################################

proc moveNearest {window mode args} {
    switch $mode {
	"xy" {
		set x [lindex $args 0]
		set y [lindex $args 1]
		set index [$window index @$x,$y]

		set line [expr {int($index)}]
		set diff [find-diff $line]
	    }
	"mark" {
		set index [$window index [lindex $args 0]]
		set line [expr {int($index)}]
		set diff [find-diff $line]
	    }
    }

    # ok, we have an index
    move [lindex $diff 0] 0 1
}

###############################################################################
###############################################################################

proc moveTo {window value} {
    global w
    global g
    # we know that the value is prefixed by the nunber/index of
    # the diff the user wants. So, just grab that out of the string
    regexp {([0-9]+) *:} $value matchVar index
    move $index 0 1
}

###############################################################################
# this is called when the user scrolls the map thumb interactively.
###############################################################################
proc map-seek {y} {
    global g
    global w

    incr y -2
    set yview [expr {(double($y) / double($g(mapheight)))}]

    # Show text corresponding to map;
    $w(RightText) yview moveto $yview
}

###############################################################################
# Move the "current" diff indicator (i.e. go to the next or previous diff
# region if "relative" is 1; go to an absolute diff number if "relative"
# is 0).
###############################################################################

proc move {value {relative 1} {setpos 1}} {
    global g
    global w

    if {$value == "first"} {
	set value 1
	set relative 0
    }
    if {$value == "last"} {
	set value $g(count)
	set relative 0
    }

    # Remove old 'curr' tag
    set-tag $g(pos) difftag currtag

    # Bump 'pos' (one way or the other).
    if {$relative} {
	set g(pos) [expr {$g(pos) + $value}]
    } else {
	set g(pos) $value
    }

    # Range check 'pos'.
    set g(pos) [max $g(pos) 1]
    set g(pos) [min $g(pos) $g(count)]

    # Set new 'curr' tag
    set g(currdiff) [set-tag $g(pos) currtag "" $setpos]

    # update the buttons..
    update-display

}

proc update-display {} {
    global g
    global w

    if {!$g(initOK)} {
	# disable darn near everything
	foreach widget [list combo prevDiff firstDiff nextDiff lastDiff centerDiffs mergeChoice1 mergeChoice2 mergeChoice12 mergeChoice21 find mergeChoiceLabel combo] {
	    $w($widget) configure\
	        -state disabled
	}
	foreach menu [list $w(popupMenu) $w(viewMenu)] {
	    $menu entryconfigure "Previous*"\
	        -state disabled
	    $menu entryconfigure "First*"\
	        -state disabled
	    $menu entryconfigure "Next*"\
	        -state disabled
	    $menu entryconfigure "Last*"\
	        -state disabled
	    $menu entryconfigure "Center*"\
	        -state disabled
	}
	$w(popupMenu) entryconfigure "Find..."\
	    -state disabled
	$w(popupMenu) entryconfigure "Find Nearest*"\
	    -state disabled
	$w(popupMenu) entryconfigure "Edit*"\
	    -state disabled

	$w(editMenu) entryconfigure "Find*"\
	    -state disabled
	$w(editMenu) entryconfigure "Edit File 1"\
	    -state disabled
	$w(editMenu) entryconfigure "Edit File 2"\
	    -state disabled

	$w(fileMenu) entryconfigure "Write*"\
	    -state disabled
	$w(fileMenu) entryconfigure "Recompute*"\
	    -state disabled

	$w(mergeMenu) entryconfigure "Show*"\
	    -state disabled
	$w(mergeMenu) entryconfigure "Write*"\
	    -state disabled

	$w(markMenu) entryconfigure "Mark*"\
	    -state disabled
	$w(markMenu) entryconfigure "Clear*"\
	    -state disabled

    } else {
	# these are always enabled, assuming we have properly
	# diffed a couple of files
	$w(popupMenu) entryconfigure "Find..."\
	    -state normal
	$w(popupMenu) entryconfigure "Find Nearest*"\
	    -state normal
	$w(popupMenu) entryconfigure "Edit*"\
	    -state normal

	$w(mergeChoice1) configure\
	    -state normal
	$w(mergeChoice2) configure\
	    -state normal
	$w(mergeChoice12) configure\
	    -state normal
	$w(mergeChoice21) configure\
	    -state normal
	$w(mergeChoiceLabel) configure\
	    -state normal

	$w(editMenu) entryconfigure "Find*"\
	    -state normal
	$w(editMenu) entryconfigure "Edit File 1"\
	    -state normal
	$w(editMenu) entryconfigure "Edit File 2"\
	    -state normal

	$w(fileMenu) entryconfigure "Write*"\
	    -state normal
	$w(fileMenu) entryconfigure "Recompute*"\
	    -state normal

	$w(mergeMenu) entryconfigure "Show*"\
	    -state normal
	$w(mergeMenu) entryconfigure "Write*"\
	    -state normal

	$w(find) configure\
	    -state normal
	$w(combo) configure\
	    -state normal
    }

    # Update the toggles.
    if {$g(count)} {
	set g(toggle) $g(merge$g(pos))
    }

    # update the status line
    set g(statusCurrent) "$g(pos) of $g(count)"

    # update the combobox. We don't want it's command to fire, so
    # we'll disable it temporarily
    $w(combo) configure\
        -commandstate "disabled"
    set i [expr {$g(pos) - 1}]
    $w(combo) configure\
        -value [lindex [$w(combo) list get 0 end] $i]
    $w(combo) selection clear
    $w(combo) configure\
        -commandstate "normal"

    # update the widgets
    if {$g(pos) <= 1} {
	$w(prevDiff) configure\
	    -state disabled
	$w(firstDiff) configure\
	    -state disabled
	$w(popupMenu) entryconfigure "Previous*"\
	    -state disabled
	$w(popupMenu) entryconfigure "First*"\
	    -state disabled
	$w(viewMenu) entryconfigure "Previous*"\
	    -state disabled
	$w(viewMenu) entryconfigure "First*"\
	    -state disabled
    } else {
	$w(prevDiff) configure\
	    -state normal
	$w(firstDiff) configure\
	    -state normal
	$w(popupMenu) entryconfigure "Previous*"\
	    -state normal
	$w(popupMenu) entryconfigure "First*"\
	    -state normal
	$w(viewMenu) entryconfigure "Previous*"\
	    -state normal
	$w(viewMenu) entryconfigure "First*"\
	    -state normal
    }

    if {$g(pos) >= $g(count)} {
	$w(nextDiff) configure\
	    -state disabled
	$w(lastDiff) configure\
	    -state disabled
	$w(popupMenu) entryconfigure "Next*"\
	    -state disabled
	$w(popupMenu) entryconfigure "Last*"\
	    -state disabled
	$w(viewMenu) entryconfigure "Next*"\
	    -state disabled
	$w(viewMenu) entryconfigure "Last*"\
	    -state disabled
    } else {
	$w(nextDiff) configure\
	    -state normal
	$w(lastDiff) configure\
	    -state normal
	$w(popupMenu) entryconfigure "Next*"\
	    -state normal
	$w(popupMenu) entryconfigure "Last*"\
	    -state normal
	$w(viewMenu) entryconfigure "Next*"\
	    -state normal
	$w(viewMenu) entryconfigure "Last*"\
	    -state normal
    }

    if {$g(count) > 0} {
	$w(centerDiffs) configure\
	    -state normal
	$w(popupMenu) entryconfigure "Center*"\
	    -state normal
	$w(viewMenu) entryconfigure "Center*"\
	    -state normal

	$w(mergeChoice1) configure\
	    -state normal
	$w(mergeChoice2) configure\
	    -state normal
	$w(mergeChoice12) configure\
	    -state normal
	$w(mergeChoice21) configure\
	    -state normal
	$w(mergeChoiceLabel) configure\
	    -state normal

	$w(markMenu) entryconfigure "Mark*"\
	    -state normal

    } else {
	$w(centerDiffs) configure\
	    -state disabled
	$w(popupMenu) entryconfigure "Center*"\
	    -state disabled
	$w(viewMenu) entryconfigure "Center*"\
	    -state disabled

	$w(mergeChoice1) configure\
	    -state disabled
	$w(mergeChoice2) configure\
	    -state disabled
	$w(mergeChoice12) configure\
	    -state disabled
	$w(mergeChoice21) configure\
	    -state disabled
	$w(mergeChoiceLabel) configure\
	    -state disabled

	$w(markMenu) entryconfigure "Mark*"\
	    -state disabled
    }

    # the mark clear button should only be enabled if there is 
    # presently a mark at the current diff record
    set widget $w(toolbar).mark$g(pos)
    if {[winfo exists $widget]} {
	$w(markMenu) entryconfigure "Clear*"\
	    -state normal
	$w(markMenu) entryconfigure "Mark*"\
	    -state disabled
	$w(markClear) configure\
	    -state normal
	$w(markSet) configure\
	    -state disabled
    } else {
	$w(markMenu) entryconfigure "Clear*"\
	    -state disabled
	$w(markMenu) entryconfigure "Mark*"\
	    -state normal
	$w(markClear) configure\
	    -state disabled
	$w(markSet) configure\
	    -state normal
    }

}

###############################################################################
# Center the top line of the CDR in each window.
###############################################################################

proc center {} {
    global g
    global w

    #    scan $g(scrdiff,$g(pos)) "%s %d %d %d %d %s" dummy s1 e1 s2 e2 dt
    foreach {dummy s1 e1 s2 e2 dt} $g(scrdiff,$g(pos)) { }

    # Window requested height in pixels
    set opix [winfo reqheight $w(LeftText)]
    # Window requested lines
    set olin [$w(LeftText) cget -height]
    # Current window height in pixels
    set npix [winfo height $w(LeftText)]

    # Visible lines
    set winlines [expr {$npix * $olin / $opix}]
    # Lines in diff
    set diffsize [max [expr {$e1 - $s1 + 1}] [expr {$e2 - $s2 + 1}]]

    if {$diffsize < $winlines} {
	set h [expr {($winlines - $diffsize) / 2}]
    } else {
	set h 2
    }

    set o [expr {$s1 - $h}]
    if {$o < 0} {
	set o 0
    }
    set n [expr {$s2 - $h}]
    if {$n < 0} {
	set n 0
    }

    $w(LeftText) mark set insert $s1.0
    $w(RightText) mark set insert $s2.0
    $w(LeftText) yview $o
    $w(RightText) yview $n

    if {$g(showmerge)} {
	merge-center
    }
}

###############################################################################
# Change the state on all of the diff-sensitive buttons.
###############################################################################

proc buttons {{newstate "normal"}} {
    global w
    $w(combo) configure\
        -state $newstate
    $w(prevDiff) configure\
        -state $newstate
    $w(nextDiff) configure\
        -state $newstate
    $w(firstDiff) configure\
        -state $newstate
    $w(lastDiff) configure\
        -state $newstate
    $w(centerDiffs) configure\
        -state $newstate
}

###############################################################################
# Wipe the slate clean...
###############################################################################

proc wipe {} {
    global g

    set g(pos) 0
    set g(count) 0
    set g(diff) ""
    set g(currdiff) ""

    set g(delta,1) 0
    set g(delta,2) 0
}

###############################################################################
# Wipe all data and all windows
###############################################################################

proc wipe-window {} {
    global g
    global w

    wipe

    foreach mod {Left Right} {
	$w(${mod}Text) configure\
	    -state normal
	$w(${mod}Text) tag remove difftag 1.0 end
	$w(${mod}Text) tag remove currtag 1.0 end
	$w(${mod}Text) delete 1.0 end

	$w(${mod}Info) configure\
	    -state normal
	$w(${mod}Info) delete 1.0 end
	$w(${mod}CB) configure\
	    -state normal
	$w(${mod}CB) delete 1.0 end
    }

    catch {
	$w(mergeText) configure\
	    -state normal
	$w(mergeText) delete 1.0 end
	eval $w(mergeText) tag delete [$w(mergeText) tag names]
	$w(mergeText) configure\
	    -state disabled
    }

    if {[string length $g(destroy)] > 0} {
	eval $g(destroy)
	set g(destroy) ""
    }

    $w(combo) list delete 0 end
    buttons disabled

    diffmark clearall
}

###############################################################################
# Mark difference regions and build up the combobox
###############################################################################

proc mark-diffs {} {
    global g
    global w

    set numdiff [llength "$g(diff)"]

    set g(count) 0


    # ain't this clever? We want to update the display as soon as
    # we've marked enough diffs to fill the display so the user will
    # have the impression we're fast. But, we don't want this
    # want this code to slow us down too much, so we'll put the
    # code in a variable and delete it when its no longer needed.
    set hack {
	# for now, just pick a number out of thin air. Ideally
	# we'd compute the number of lines that are visible and
	# use that, but I'm too lazy today...
	if {$g(count) > 25} {
	    update idletasks
	    set hack {}
	}
    }

    foreach d $g(diff) {
	set result [extract $d]
	if {$result != ""} {
	    incr g(count)
	    set g(merge$g(count)) 1

	    set g(pdiff,$g(count)) "$result"
	    add-lines $g(count)

	    #	     set-tag $g(count) difftag

	    $w(combo) list insert end [format "%-6d: %s" $g(count) $d]

	    eval $hack
	}

    }

    remark-diffs
    return $g(count)
}

###############################################################################
# start a new diff
###############################################################################
proc do-new-diff {args} {
    global argv argc
    global g

    if {[llength $args] == 0} {
	set args [newDiff popup]
	if {[llength $args] == 0} {
	    return 0
	}
	set argv $args
	set argc [llength $args]
    }

    set-cursor
    set g(disableSyncing) 1 ;# turn off syncing until things settle down

    # remove all evidence of previous diff
    wipe-window
    update idletasks

    set result [catch init-files output]
    check-error $result $output
    if {$result} {
	# drat! Probably ought to display the newDiff dialog
	# or something.
	set ret 0

    } else {

	# do the diff
	do-diff

	move first 1 1

	set ret 1
    }

    restore-cursor

    update-display
    catch {unset g(disableSyncing)}

    return $ret
}

###############################################################################
# Remark difference regions...
###############################################################################

proc remark-diffs {} {
    global g
    global w
    global opts
    global pref

    # delete all known tags.
    foreach window [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB) $w(mergeText)] {
	eval $window tag delete [$window tag names]
    }

    # reconfigure all the tags based on the current options
    # first, the common tags:
    foreach tag {difftag currtag deltag instag chgtag overlaptag } {
	foreach win [list $w(LeftText) $w(LeftInfo) $w(LeftCB) $w(RightText) $w(RightInfo) $w(RightCB)] {
	    if {[catch "$win tag configure $tag $opts($tag)"]} {
		do-error "Invalid settings for \"$pref($tag)\": \n\n'$opts($tag)' is not a valid option string."
		eval "$win tag configure $tag $opts($tag)"
		return
	    }
	}
    }

    # next, changebar-specific tags
    foreach widget [list $w(LeftCB) $w(RightCB)] {
	eval $widget tag configure + $opts(+)
	eval $widget tag configure\
	    - $opts(-)
	eval $widget tag configure ! $opts(!)
	eval $widget tag configure ? $opts(?)
    }

    # ... and the merge text window
    foreach tag {difftag currtag} {
	eval $w(mergeText) tag configure $tag $opts($tag)
    }


    # now, reapply the tags to all the diff regions
    for {set i 1} {$i <= $g(count)} {incr i} {
	set-tag $i difftag
    }

    # finally, reset the current diff
    set-tag $g(pos) currtag "" 0

}


###############################################################################
# Put up some informational text.
###############################################################################

proc show-info {message} {
    global g

    #    set g(currdiff) $message
    set g(statusInfo) $message
    update idletasks
}

###############################################################################
# Compute differences (start over, basically).
###############################################################################

proc rediff {} {
    global g
    global opts
    global finfo
    global tcl_platform
    global w

    buttons disabled

    # Read the files into their respective widgets & add line numbers.
    foreach mod {1 2} {
	if {$mod == 1} {
	    set text $w(LeftText)
	} else {
	    set text $w(RightText)
	}
	show-info "reading $finfo(pth,$mod)..."
	if {[catch {set hndl [open "$finfo(pth,$mod)" r]}]} {
	    fatal-error "Failed to open file: $finfo(pth,$mod)"
	}
	$text insert 1.0 [read $hndl]
	close $hndl

    }

    # Diff the two files and store the summary lines into 'g(diff)'.
    set diffcmd "$opts(diffcmd) {$finfo(pth,1)} {$finfo(pth,2)}"
    show-info "Executing \"$diffcmd\""

    set result [run-command "exec $diffcmd"]
    set stdout [lindex $result 0]
    set stderr [lindex $result 1]
    set exitcode [lindex $result 2]
    set g(returnValue) $exitcode

    # The exit code is 0 if there are no differences and 1 if there
    # are differences. Any other exit code means trouble and we abort.
    if {$exitcode < 0 || $exitcode > 1 || $stderr != ""} {
	fatal-error "diff failed:\n$stderr"
    }

    set g(diff) {}
    set lines [split $stdout "\n"]

    # If there is no output and we got this far the files are equal,
    # otherwise check if the first line begins with a line number. If
    # not there was trouble and we abort. For instance, using a binary
    # file results in the message "Binary files ..." etc on stdout,
    # exit code 1. The message may wary depending on locale.
    if {$lines != "" && [string match {[0-9]*} $lines] != 1} {
	fatal-error "diff failed:\n$stdout"
    }

    # Collect all lines containing line numbers
    foreach line $lines {
	if {[string match {[0-9]*} $line]} {
	    lappend g(diff) $line
	}
    }

    if {$g(ancfileset)} {

	# 3-way merge - compare 1st file (left: diff3l) with ancestor
	set diffcmd "$opts(diffcmd) {$finfo(pth,1)} {$g(ancfile)}"
	show-info "Executing \"$diffcmd\""
	set result [run-command "exec $diffcmd"]
	set stdout [lindex $result 0]
	set stderr [lindex $result 1]
	set exitcode [lindex $result 2]
	if {$exitcode < 0 || $exitcode > 1 || $stderr != ""} {
	    fatal-error "diff3 failed:\n$stderr"
	}
	set lines [split $stdout "\n"]
	set g(diff3l) {}
	foreach line $lines {
	    if {[string match {[0-9]*} $line]} {
		if {[regexp {^[0-9]*,} $line match ] } {
		  regexp {([0-9]*),([0-9]*).*} $line matchvar s1 s2
		} else {
		  regexp {([0-9]*).*} $line matchvar s1
		  set s2 $s1
		}

		lappend g(diff3l) $s1
		for {set i $s1} {$i <= $s2} {incr i} {
		  set g(diff3l$i) 1
		}
	    }
	}

	# 3-way merge - compare 2nd file (right: diff3r) with ancestor
	set diffcmd "$opts(diffcmd) {$finfo(pth,2)} {$g(ancfile)}"
	show-info "Executing \"$diffcmd\""
	set result [run-command "exec $diffcmd"]
	set stdout [lindex $result 0]
	set stderr [lindex $result 1]
	set exitcode [lindex $result 2]
	if {$exitcode < 0 || $exitcode > 1 || $stderr != ""} {
	    fatal-error "diff3 failed:\n$stderr"
	}
	set lines [split $stdout "\n"]
	set g(diff3r) {}
	foreach line $lines {
	    if {[string match {[0-9]*} $line]} {
		if {[regexp {^[0-9]*,} $line match ] } {
		  regexp {([0-9]*),([0-9]*).*} $line matchvar s1 s2
		} else {
		  regexp {([0-9]*).*} $line matchvar s1
		  set s2 $s1
		}

		lappend g(diff3r) $s1
		for {set i $s1} {$i <= $s2} {incr i} {
		  set g(diff3r$i) 1
		}
	    }
	}
    }

    # Mark up the two text widgets and go to the first diff (if there
    # is one).

    draw-line-numbers

    show-info "Marking differences..."

    $w(LeftInfo) configure\
        -state normal
    $w(RightInfo) configure\
        -state normal
    $w(LeftCB) configure\
        -state normal
    $w(RightCB) configure\
        -state normal

    if {[mark-diffs]} {
	set g(pos) 1
	move 1 0 1
	buttons normal
    } else {
	after idle {show-info "Files are identical."}
	buttons disabled
    }

    # Prevent tampering in the line number widgets. The text
    # widgets are already taken care of
    $w(LeftInfo) configure\
        -state disabled
    $w(RightInfo) configure\
        -state disabled
    $w(LeftCB) configure\
        -state disabled
    $w(RightCB) configure\
        -state disabled
}

###############################################################################
# Set the X cursor to "watch" for a window and all of its descendants.
###############################################################################

proc set-cursor {args} {
    global current
    global w

    . configure\
        -cursor watch
    $w(LeftText) configure\
        -cursor watch
    $w(RightText) configure\
        -cursor watch
    $w(combo) configure\
        -cursor watch
    update idletasks

}

###############################################################################
# Restore the X cursor for a window and all of its descendants.
###############################################################################

proc restore-cursor {args} {
    global current
    global w

    . configure\
        -cursor {}
    $w(LeftText) configure\
        -cursor {}
    $w(RightText) configure\
        -cursor {}
    $w(combo) configure\
        -cursor {}
    show-info ""
    update idletasks
}

###############################################################################
# Check if error was thrown by us or unexpected
###############################################################################

proc check-error {result output} {
    global g errorInfo

    if {$result && $output != "Fatal"} {
	error $result $errorInfo
    }
}


###############################################################################
# redo the current diff. Attempt to return to the same diff region,
# numerically speaking.
###############################################################################
proc recompute-diff {} {
    global g
    set current $g(pos)

    do-diff
    move $current 0 1

    update-display
}


###############################################################################
# Flash the "rediff" button and then kick off a rediff.
###############################################################################

proc do-diff {} {
    global g map errorInfo
    global opts

    set-cursor
    update idletasks

    wipe-window
    update idletasks
    set result [catch {
	if {$g(mapheight)} {
	    ## FIXME this could better a catch
	    catch { $map blank }  
	}
	init-files
	rediff
	merge-read-file
	merge-add-marks

	# If a map exists, recreate it
	if {$opts(showmap)} {
	    set g(mapheight) -1
	    map-resize
	}

    } output]

    check-error $result $output

    if {$g(mergefileset)} {
	do-show-merge 1
    }

    restore-cursor
}

###############################################################################
# Get things going...
###############################################################################

proc main {} {
    global argv
    global w
    global g errorInfo
    global startupError
    global opts

    wm withdraw .
    wm protocol . WM_DELETE_WINDOW do-exit
    wm title . "$g(name) $g(version)"

    wipe

    create-display

    update-display

    update

    merge-create-window

    do-show-linenumbers
    do-show-map

    # evaluate any custom code the user has
    if {[info exists opts(customCode)]} {
	if {[catch [list uplevel \#0 $opts(customCode)] error]} {
	    set startupError "Error in custom code: \n\n$error"
	} else {
	    update
	}
    }

    eval do-new-diff $argv

    move first 1 1

    # this forces all of the various scrolling windows (line numbers,
    # change bars, etc) to get in sync.
    set yview [$w(RightText) yview]
    vscroll-sync [list $w(RightInfo) $w(LeftInfo)] 2 [lindex $yview 0] [lindex $yview 1]

    wm deiconify .
    update idletasks

    if {[info exists startupError]} {
	tk_messageBox\
	    -icon warning\
	    -type ok\
	    -title "$g(name) - Error in Startup File"\
	    -message $startupError
    }
}


###############################################################################
# Erase tmp files (if necessary) and destroy the application.
###############################################################################

proc del-tmp {} {
    global g finfo

    if {$finfo(tmp,1)} {
	file delete $finfo(pth,1)
    }
    if {$finfo(tmp,2)} {
	file delete $finfo(pth,2)
    }
    foreach f $g(tempfiles) {
	file delete $f
    }
}

###############################################################################
# Throw up a window with formatted text
###############################################################################

proc do-text-info {w title text} {
    global g

    catch "destroy $w"
    toplevel $w
    wm title $w "$g(name) Help - $title"
    set x [expr {[winfo rootx .] + 0}]
    set y [expr {[winfo rooty .] + 0}]

    wm geometry $w "=55x29+${x}+${y}"
    wm group $w .
    wm transient $w .

    frame $w.f\
        -bd 1\
        -relief sunken
    pack $w.f\
        -side top\
        -fill both\
        -expand y

    text $w.f.title\
        -highlightthickness 0\
        -bd 0\
        -height 2\
        -wrap word\
        -width 50\
        -background white\
        -foreground black

    text $w.f.text\
        -wrap word\
        -setgrid true\
        -padx 20\
        -highlightthickness 0\
        -bd 0\
        -width 50\
        -height 20\
        -yscroll [list $w.f.vsb set]\
        -background white\
        -foreground black
    scrollbar $w.f.vsb\
        -command [list $w.f.text yview]\
        -orient vertical

    pack $w.f.vsb\
        -side right\
        -fill y\
        -expand n
    pack $w.f.title\
        -side top\
        -fill x\
        -expand n
    pack $w.f.text\
        -side left\
        -fill both\
        -expand y

    focus $w.f.text

    button $w.done\
        -text Dismiss\
        -command "destroy $w"
    pack $w.done\
        -side right\
        -fill none\
        -pady 5\
        -padx 5

    put-text $w.f.title "<ttl>$title</ttl>"
    put-text $w.f.text $text
    $w.f.text configure\
        -state disabled
}


###############################################################################
# centers window w over parent
###############################################################################
proc centerWindow {w {size {}}} {
    update
    set parent .

    if {[llength $size] > 0} {
	set wWidth [lindex $size 0]
	set wHeight [lindex $size 1]
    } else {
	set wWidth [winfo reqwidth $w]
	set wHeight [winfo reqheight $w]
    }

    set pWidth [winfo reqwidth $parent]
    set pHeight [winfo reqheight $parent]
    set pX [winfo rootx $parent]
    set pY [winfo rooty $parent]

    set centerX [expr {$pX +($pWidth / 2)}]
    set centerY [expr {$pY +($pHeight / 2)}]

    set x [expr {$centerX -($wWidth / 2)}]
    set y [expr {$centerY -($wHeight / 2)}]

    wm geometry $w "=${wWidth}x${wHeight}+${x}+${y}"
    update

}

###############################################################################
# all the code to handle the "New Diff" dialog
###############################################################################
proc newDiff {command args} {
    global g w
    global finfo

    set w(newDiffPopup) .newDiffPopup

    switch $command {
	"popup" {
		if {![winfo exists $w(newDiffPopup)]} {
		    newDiff build
		    centerWindow $w(newDiffPopup)
		}

		wm deiconify $w(newDiffPopup)
		raise $w(newDiffPopup)
		focus $w(newDiffPopup,entry1)
		tkwait variable g(newDiffArgs)
		wm withdraw $w(newDiffPopup)

		# handle result...
		return $g(newDiffArgs)
	    }
	"ok" {
		# normally we would retrieve the switch value based
		# on a radio button or option menu or some such on
		# the dialog, but for now we only support one type of
		# diff from the dialog...

		# handle the various permutations...
		switch 1 {
		    1 {
			    set f1 [file nativename $g(newDiff,simple,original)]
			    set f2 [file nativename $g(newDiff,simple,revision)]
			    if {![file exists $f1]} {
				tk_messageBox\
				    -icon warning\
				    -title "File does not exist"\
				    -message "The original file '$f1' does not exist"\
				    -type ok
				focus $w(newDiffPopup,entry1)
				return
			    }
			    if {![file exists $f2]} {
				tk_messageBox\
				    -icon warning\
				    -title "File does not exist"\
				    -message "The revised file '$f2' does not exist"\
				    -type ok
				focus $w(newDiffPopup,entry2)
				return
			    }
			    # setting this variable will cause popup
			    # to close the window...
			    set g(newDiffArgs) [list $f1 $f2]
			}
		}
	    }
	"cancel" {
		set g(newDiffArgs) {}
		return
	    }
	"browse" {
		# n.b.: args(0) is dialog title; args(1) is entry widget
		set title [lindex $args 0]
		set widget [lindex $args 1]
		set foo [$widget get]
		set initialdir [file dirname $foo]
		set initialfile [file tail $foo]
		set filename [tk_getOpenFile\
		    -title $title\
		    -initialfile $initialfile\
		    -initialdir $initialdir]
		if {[string length $filename] > 0} {
		    $widget delete 0 end
		    $widget insert 0 $filename
		    $widget selection range 0 end
		    $widget xview end
		    focus $widget
		    return 1
		} else {
		    after idle {raise $w(newDiffPopup)}
		    return 0
		}
	    }
	"build" {

		catch {destroy $w(newDiffPopup)}
		toplevel $w(newDiffPopup)

		wm group $w(newDiffPopup) .
		wm transient $w(newDiffPopup) .
		wm title $w(newDiffPopup) "New Diff"

		wm protocol $w(newDiffPopup) WM_DELETE_WINDOW {newDiff cancel}

		wm withdraw $w(newDiffPopup)

		set x [expr {[winfo rootx .] + 0}]
		set y [expr {[winfo rooty .] + 0}]

		# ultimately it might be nice to support all the
		# modes even though for now all we'll support is the
		# two-file mode. But, to make the transition easier
		# we'll put all of the widgets for this mode in its own
		# frame which can ultimately be controlled by a notebook
		# widget
		set simple [frame $w(newDiffPopup).simple\
		    -borderwidth 2\
		    -relief groove]
		label $simple.l1\
		    -text "Original File:"
		label $simple.l2\
		    -text "Revised File:"

		entry $simple.e1\
		    -textvariable g(newDiff,simple,original)
		entry $simple.e2\
		    -textvariable g(newDiff,simple,revision)

		set w(newDiffPopup,entry1) $simple.e1
		set w(newDiffPopup,entry2) $simple.e2

		set g(newDiff,simple,original) $finfo(pth,1)
		set g(newDiff,simple,revision) $finfo(pth,2)

		# we want these buttons to be the same height as
		# the entry, so we'll try to force the issue...
		button $simple.b1\
		    -borderwidth 1\
		    -highlightthickness 0\
		    -text "Browse..."\
		    -command [list newDiff browse "Original File" $simple.e1]
		button $simple.b2\
		    -borderwidth 1\
		    -highlightthickness 0\
		    -text "Browse..."\
		    -command [list newDiff browse "Revised File" $simple.e2]

		# we'll use the grid geometry manager to get things lined up right...
		grid $simple.l1\
		    -row 0\
		    -column 0\
		    -sticky e
		grid $simple.e1\
		    -row 0\
		    -column 1\
		    -sticky nsew
		grid $simple.b1\
		    -row 0\
		    -column 2\
		    -sticky nsew\
		    -pad 4

		grid $simple.l2\
		    -row 1\
		    -column 0\
		    -sticky e
		grid $simple.e2\
		    -row 1\
		    -column 1\
		    -sticky nsew
		grid $simple.b2\
		    -row 1\
		    -column 2\
		    -sticky nsew\
		    -pad 4

		grid columnconfigure $simple 0\
		    -weight 0
		grid columnconfigure $simple 1\
		    -weight 1
		grid columnconfigure $simple 2\
		    -weight 0

		# here are the buttons for this dialog...
		set commands [frame $w(newDiffPopup).buttons]
		button $commands.ok\
		    -text "Ok"\
		    -width 5\
		    -command [list newDiff ok]\
		    -default active
		button $commands.cancel\
		    -text "Cancel"\
		    -width 5\
		    -command [list newDiff cancel]\
		    -default normal

		pack $commands.ok $commands.cancel\
		    -side left\
		    -fill none\
		    -expand y\
		    -pady 4

		catch {$commands.ok\
		        -default 1}

		# pack this crud in...
		pack $simple\
		    -side top\
		    -fill both\
		    -expand y\
		    -ipady 20\
		    -ipadx 20\
		    -padx 5\
		    -pady 5
		pack $commands\
		    -side bottom\
		    -fill x\
		    -expand n

		bind $w(newDiffPopup) <Return> [list $commands.ok invoke]
		bind $w(newDiffPopup) <Escape> [list $commands.cancel invoke]
	    }
    }

}


###############################################################################
# all the code to handle the report writing dialog.
###############################################################################

proc write-report {command args} {
    global g
    global w
    global report
    global finfo

    set w(reportPopup) .reportPopup
    switch $command {
	popup {
		if {![winfo exists $w(reportPopup)]} {
		    write-report build
		}
		set report(filename) [file join [pwd] $report(filename)]
		write-report update

		centerWindow $w(reportPopup)
		wm deiconify $w(reportPopup)
		raise $w(reportPopup)
	    }
	cancel {
		wm withdraw $w(reportPopup)
	    }
	update {

		set stateLeft "disabled"
		set stateRight "disabled"
		if {$report(doSideLeft)} {
		    set stateLeft "normal"
		}
		if {$report(doSideRight)} {
		    set stateRight "normal"
		}

		$w(reportLinenumLeft) configure\
		    -state $stateLeft
		$w(reportCMLeft) configure\
		    -state $stateLeft
		$w(reportTextLeft) configure\
		    -state $stateLeft

		$w(reportLinenumRight) configure\
		    -state $stateRight
		$w(reportCMRight) configure\
		    -state $stateRight
		$w(reportTextRight) configure\
		    -state $stateRight

	    }
	save {
		set leftLines [lindex [split [$w(LeftText) index end-1lines] .] 0]
		set rightLines [lindex [split [$w(RightText) index end-1lines] .] 0]

		# number of lines of the largest window...
		set maxlines [max $leftLines $rightLines]

		# probably ought to catch this, in case it fails. Maybe later...
		set handle [open $report(filename) w]

		puts $handle "$g(name) $g(version) report"

		# write the file names
		if {$report(doSideLeft) == 1 && $report(doSideRight) == 1} {
		    puts $handle "\nFile A: $finfo(lbl,1)\nFile B: $finfo(lbl,2)\n"
		} elseif {$report(doSideLeft) == 1} {
		    puts $handle "\nFile: $finfo(lbl,1)"
		} else {
		    puts $handle "\nFile: $finfo(lbl,2)"
		}

		puts $handle "number of diffs: $g(count)"

		set acount [set ccount [set dcount 0]]
		for {set i 1} {$i <= $g(count)} {incr i} {
		    foreach {line s1 e1 s2 e2 type} $g(scrdiff,$i) { }
		    switch $type {
			"d" {
				incr dcount
			    }
			"a" {
				incr acount
			    }
			"c" {
				incr ccount
			    }
		    }
		}

		puts $handle [format "    %6d regions were deleted" $dcount]
		puts $handle [format "    %6d regions were added" $acount]
		puts $handle [format "    %6d regions were changed" $ccount]

		puts $handle "\n"
		for {set i 1} {$i <= $maxlines} {incr i} {
		    set out(Left) [set out(Right) ""]
		    foreach side {Left Right} {

			if {$side == "Left" && $i > $leftLines} break

			if {$side == "Right" && $i > $rightLines} break


			if {$report(doLineNumbers$side)} {
			    set widget $w(${side}Info)
			    set number [string trimright [$widget get "$i.0" "$i.0 lineend"]]

			    append out($side) [format "%6s " $number]
			}

			if {$report(doChangeMarkers$side)} {
			    set widget $w(${side}CB)
			    set data [$widget get "$i.0" "$i.1"]
			    append out($side) "$data "
			}

			if {$report(doText$side)} {
			    set widget $w(${side}Text)
			    append out($side) [string trimright [$widget get "$i.0" "$i.0 lineend"]]
			}
		    }

		    if {$report(doSideLeft) == 1 && $report(doSideRight) == 1} {
			set output [format "%-90s%-90s" $out(Left) $out(Right)]

		    } elseif {$report(doSideRight) == 1} {
			set output $out(Right)

		    } elseif {$report(doSideLeft) == 1} {
			set output $out(Left)

		    } else {
			# what a wasted effort!
			set output ""
		    }
		    puts $handle [string trimright $output]
		}
		close $handle

		wm withdraw $w(reportPopup)
	    }
	browse {
		set types {
		{{All Files}	 {*}}
	    }

		set path [tk_getSaveFile\
		    -defaultextension ""\
		    -filetypes $types\
		    -initialfile $report(filename)]

		if {[string length $path] > 0} {
		    set report(filename) $path
		}
	    }
	build {
		catch {destroy $w(reportPopup)}
		toplevel $w(reportPopup)
		wm group $w(reportPopup) .
		wm transient $w(reportPopup) .
		wm title $w(reportPopup) "$g(name) - Generate Report"
		wm protocol $w(reportPopup) WM_DELETE_WINDOW [list write-report cancel]
		wm withdraw $w(reportPopup)

		set cf [frame $w(reportPopup).clientFrame\
		    -bd 2\
		    -relief groove]
		set bf [frame $w(reportPopup).buttonFrame\
		    -bd 0]
		pack $cf\
		    -side top\
		    -fill both\
		    -expand y\
		    -padx 5\
		    -pady 5
		pack $bf\
		    -side bottom\
		    -fill x\
		    -expand n

		# buttons...
		set w(reportSave) $bf.save
		set w(reportCancel) $bf.cancel

		button $w(reportSave)\
		    -text "Save"\
		    -underline 0\
		    -command [list write-report save]\
		    -width 6
		button $w(reportCancel)\
		    -text "Cancel"\
		    -underline 0\
		    -command [list write-report cancel]\
		    -width 6

		pack $w(reportCancel)\
		    -side right\
		    -pady 5\
		    -padx 5
		pack $w(reportSave)\
		    -side right\
		    -pady 5

		# client area.
		set col(Left) 0
		set col(Right) 1
		foreach side [list Left Right] {
		    set choose [checkbutton $cf.choose$side]
		    set linenum [checkbutton $cf.linenum$side]
		    set cm [checkbutton $cf.changemarkers$side]
		    set text [checkbutton $cf.text$side]

		    $choose configure\
		        -text "$side Side"\
		        -variable report(doSide$side)\
		        -command [list write-report update]

		    $linenum configure\
		        -text "Line Numbers"\
		        -variable report(doLineNumbers$side)
		    $cm configure\
		        -text "Change Markers"\
		        -variable report(doChangeMarkers$side)
		    $text configure\
		        -text "Text"\
		        -variable report(doText$side)

		    grid $choose\
		        -row 0\
		        -column $col($side)\
		        -sticky w
		    grid $linenum\
		        -row 1\
		        -column $col($side)\
		        -sticky w\
		        -padx 10
		    grid $cm\
		        -row 2\
		        -column $col($side)\
		        -sticky w\
		        -padx 10
		    grid $text\
		        -row 3\
		        -column $col($side)\
		        -sticky w\
		        -padx 10

		    # save the widget paths for later use...
		    set w(reportChoose$side) $choose
		    set w(reportLinenum$side) $linenum
		    set w(reportCM$side) $cm
		    set w(reportText$side) $text
		}

		# the entry, label and button for the filename will get
		# stuffed into a frame for convenience...
		frame $cf.fileFrame\
		    -bd 0
		grid $cf.fileFrame\
		    -row 4\
		    -columnspan 2\
		    -sticky ew\
		    -padx 5

		label $cf.fileFrame.l\
		    -text "File:"
		entry $cf.fileFrame.e\
		    -textvariable report(filename)\
		    -width 30
		button $cf.fileFrame.b\
		    -text "Browse..."\
		    -pady 0\
		    -highlightthickness 0\
		    -borderwidth 1\
		    -command [list write-report browse]

		pack $cf.fileFrame.l\
		    -side left\
		    -pady 4
		pack $cf.fileFrame.b\
		    -side right\
		    -pady 4\
		    -padx 2
		pack $cf.fileFrame.e\
		    -side left\
		    -fill x\
		    -expand y\
		    -pady 4

		grid rowconfigure $cf 0\
		    -weight 0
		grid rowconfigure $cf 1\
		    -weight 0
		grid rowconfigure $cf 2\
		    -weight 0
		grid rowconfigure $cf 3\
		    -weight 0

		grid columnconfigure $cf 0\
		    -weight 1
		grid columnconfigure $cf 1\
		    -weight 1

		# make sure the widgets are in the proper state
		write-report update
	    }
    }
}

###############################################################################
# Throw up an "about" window.
###############################################################################

proc do-about {} {
    global g

    set title "About $g(name)"
    set text {
<hdr>$g(name) $g(version)</hdr>
<itl>$g(name)</itl> is a Tcl/Tk front-end to <itl>diff</itl> for Unix and NT, and is Copyright (C) 1994-1998 by John M. Klassa.

Many of the toolbar icons were created by Dean S. Jones and used with his permission. The icons have the following copyright:

Copyright(C) 1998 by Dean S. Jones
dean@gallant.com
http://www.gallant.com/icons.htm 
http://www.javalobby.org/jfa/projects/icons/

<bld>This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</bld>
    }

    set text [subst\
        -nobackslashes -nocommands $text]
    do-text-info .about $title $text
}

###############################################################################
# Throw up a "command line usage" window.
###############################################################################

proc do-usage {} {
    global g

    set title "The $g(name) Command Line"
    set text {
<hdr>Startup</hdr>
<itl>$g(name)</itl> may be started in any of the following ways:

    Interactive selection of files to compare:
<cmp>	tkdiff</cmp>

    Plain files:
<cmp>	tkdiff FILE1 FILE2</cmp>

    Plain file with conflict markers:
<cmp>	tkdiff -conflict FILE</cmp>

    Source control AccuRev/RCS/CVS/SCCS/PVCS/Perforce:
<cmp>	tkdiff FILE	</cmp>(same as -r)
<cmp>	tkdiff -r FILE
	tkdiff -rREV FILE
	tkdiff -rREV -r FILE
	tkdiff -rREV1 -rREV2 FILE</cmp>

    Additional optional parameters:
	<cmp>-a ANCESTORFILE </cmp>
	<cmp>-o MERGEOUTPUTFILE </cmp>

$g(name) detects and supports RCS, CVS and SCCS by looking for a directory with the same name.	It detects and supports PVCS by looking for a vcs.cfg file. It detects and supports AccuRev and Perforce by looking for the environment variables named ACCUREV_BIN and P4CLIENT respectively.

In the first form, tkdiff will present a dialog to allow you to choose the files to diff interactively. At present this dialog only supports a diff between two files that already exist. There is no way to do a diff against a file under souce code control (unless the previous versions can be found on disk via a standard file selection dialog).

In the second form, at least one of the arguments must be the name of a plain text file.  Symbolic links are acceptable, but at least one of the filename arguments must point to a real file rather than to a directory.

In the remaining forms, <cmp>REV</cmp> (or <cmp>REV1</cmp> and <cmp>REV2</cmp>) must be a valid revision number for <cmp>FILE</cmp>.  Where AccuRev, RCS, CVS, SCCS, PVCS or Perforce is implied but no revision number is specified, <cmp>FILE</cmp> is compared with the the revision most recently checked in.

To merge a file with conflict markers generated by "<cmp>merge</cmp>", "<cmp>cvs</cmp>", or "<cmp>vmrg</cmp>", use "<cmp>tkdiff -conflict FILE</cmp>". The file is split into two temporary files which you can merge as usual (see below).

Note that "<cmp>tkdiff FILE</cmp>" is the same as "<cmp>tkdiff -r FILE</cmp>".	The CVS version has priority, followed by the SCCS version -- i.e. if a CVS directory is present, CVS; if not and an SCCS directory is present, SCCS is assumed; otherwise, if a CVS.CFG file is found, PVCS is assumed; otherwise RCS is assumed. If none of the above apply and the AccuRev environment variable ACCUREV_BIN is found, AccuRev is used. If P4CLIENT is found, Perforce is used.

Note also that the "<cmp>tkdiff -rREV -r FILE</cmp>" form results in a comparison between revision <cmp>REV</cmp> and the head of the AccuRev, RCS, CVS, SCCS, PVCS or Perforce revision tree.

If the merge output filename is not specified, tkdiff will present a dialog to allow you to choose the name of the merge output file.

Note further that anything with a leading dash that isn't recognized as a $g(name) option is passed through to diff.  This permits you to temporarily alter the way diff is called, without resorting to a change in your preferences file.
}

    set text [subst\
        -nobackslashes -nocommands $text]
    do-text-info .usage $title $text
}

###############################################################################
# Throw up a help window.
###############################################################################

proc do-help {} {
    global g

    set title "How to use the $g(name) GUI"
    set text {
<hdr>Layout</hdr>

The top row contains the File, Edit, View, Mark, Merge and Help menus. The second row contains the labels which identify the contents of each text window. Below that is a toolbar which contains\
      navigation and merge selection tools.

The left-most text widget displays the contents of <cmp>FILE1</cmp>, the most recently checked-in revision, <cmp>REV</cmp> or <cmp>REV1</cmp>, respectively (as per the startup options described in\
      the "On Command Line" help). The right-most widget displays the contents of <cmp>FILE2</cmp>, <cmp>FILE</cmp> or <cmp>REV2</cmp>, respectively. Clicking the right mouse button over either of\
      these windows will give you a context sensitive menu with actions that will act on the window you clicked over. For example, if you click right over the right hand window and select\
      "Edit", the file displayed on the right hand side will be loaded into a text editor.

At the bottom of the display is a two line window called the "Line Comparison" window. This will show the "current line" from the left and right windows, one on top of the other. The "current line"\
      is defined by the line that has the blinking insertion cursor, which can be set by merely clicking on any line in the display. This window may be hidden if the <btn>View</btn> menu item\
      <btn>Show Line Comparison</btn> is deselected.
All difference regions (DRs) are highlighted to set them apart from the surrounding text. The <itl>current difference region</itl>, or <bld>CDR</bld>, is further set apart so that it can be\
      correlated to its partner in the other text widget (that is, the CDR on the left matches the CDR on the right).

<hdr>Changing the CDR</hdr>

The CDR can be changed in a sequential manner by means of the <btn>Next</btn> and <btn>Previous</btn> buttons. The <btn>First</btn> and <btn>Last</btn> buttons allow you to quickly navigate to the\
      first or last CDR, respectively. For random access to the DRs, use the dropdown listbox in the toolbar or the diff map, described below.

By clicking right over a window and using the popup menu you can select <btn>Find Nearest Diff</btn> to find the diff record nearest the point where you clicked.

You may also select any highlighted diff region as the current diff region by double-clicking on it.

<hdr>Operations</hdr>

1. From the <btn>File</btn> menu:

The <btn>New...</btn> button displays a dialog where you may choose two files to compare. Selecting "Ok" from the dialog will diff the two files. The <btn>Recompute Diffs</btn> button recomputes the\
      differences between the two files whose names appear at the top of the <itl>$g(name)</itl> window. The <btn>Write Report...</btn> lets you create a report file that contains the information\
      visible in the windows. Lastly, the <btn>Exit</btn> button terminates <itl>$g(name)</itl>.

2. From the <btn>Edit</btn> menu:

<btn>Copy</btn> copies the currently selected text to the system clipboard. <btn>Find</btn> pops up a dialog to let you search either text window for a specified text string. <btn>Edit File 1</btn> and <btn>Edit File 2</btn> launch an editor on the files displayed in the left- and right-hand panes.  <btn>Preferences</btn> pops up a dialog box from which display (and other) options can be
changed and saved.

3. From the <btn>View</btn> menu:

<btn>Show Line Numbers</btn> toggles the display of line numbers in the text widgets. If <btn>Synchronize Scrollbars</btn> is on, the left and right text widgets are synchronized i.e. scrolling one\
      of the windows scrolls the other. If <btn>Auto Center</btn> is on, pressing the Next or Prev buttons centers the new CDR automatically. <btn>Show Diff Map</btn> toggles the display of the diff\
      map (see below) on or off. <btn>Show Merge Preview</btn> shows or hides the merge preview (see below). <btn>Show Line Comparison</btn> toggles the display of the "line comparison" window at\
      the bottom of the display.

4. From the <btn>Mark</btn> menu:

The <btn>Mark Current Diff</btn> creates a new toolbar button that will jump to the current diff region. The <btn>Clear Current Diff Mark</btn> will remove the toolbar mark button associated with\
      the current diff region, if one exists.

5. From the <btn>Merge</btn> menu:

The <btn>Show Merge Window</btn> button pops up a window with the current merged version of the two files. The <btn>Write Merge File</btn> button will allow you to save the contents of that window\
      to a file.

6. From the <btn>Help</btn> menu:

The <btn>About $g(name)</btn> button displays copyright and author information. The <btn>On GUI</btn> button generates this window. The <btn>On Command Line</btn> button displays help on the\
      $g(name) command line options. The <btn>On Preferences</btn> button displays help on the user-settable preferences.

7. From the toolbar:

The first tool is a dropdown list of all of the differences in a standard diff-type format. You may use this list to go directly to any diff record. The <btn>Next</btn> and <btn>Previous</btn>\
      buttons take you to the "next" and "previous" DR, respectively. The <btn>First</btn> and <btn>Last</btn> buttons take you to the "first" and "last" DR. The <btn>Center</btn> button centers the\
      CDRs in their respective text windows. You can set <btn>Auto Center</btn> in <btn>Preferences</btn> to do this automatically for you as you navigate through the diff records.

<hdr>Keyboard Navigation</hdr>

When a text widget has the focus, you may use the following shortcut keys:
<cmp>
	f	First diff
	c	Center current diff
	l	Last diff
	n	Next diff
	p	Previous diff
	1	Merge Choice 1
	2	Merge Choice 2
</cmp>
The cursor, Home, End, PageUp and PageDown keys work as expected, adjusting the view in whichever text window has the focus. Note that if <btn>Synchronize Scrollbars</btn> is set in\
      <btn>Preferences</btn>, both windows will scroll at the same time.

<hdr>Scrolling</hdr>

To scroll the text widgets independently, make sure <btn>Synchronize Scrollbars</btn> in <btn>Preferences</btn> is off. If it is on, scrolling any text widget scrolls all others. Scrolling does not\
      change the current diff record (CDR).

<hdr>Diff Marks</hdr>

You can set "markers" at specific diff regions for easier navigation. To do this, click on the <btn>Set Mark</btn> button. It will create a new toolbar button that will jump back to this diff\
      region. To clear a diff mark, go to that diff record and click on the <btn>Clear Mark</btn> button.

<hdr>Diff Map</hdr>

The diff map is a map of all the diff regions. It is shown in the middle of the main window if "Diff Map" on the View menu is on. The map is a miniature of the file's diff regions from top to\
      bottom. Each diff region is rendered as a patch of color, Delete as red, Insert as green and Change as blue. In the case of a 3-way merge, overlap regions are marked in yellow. The height of each patch corresponds to the relative size of the diff region. A\
      thumb lets you interact with the map as if it were a scrollbar.
All diff regions are drawn on the map even if too small to be visible. For large files with small diff regions, this may result in patches overwriting each other.

<hdr>Merging</hdr>

To merge the two files, go through the difference regions (via "Next", "Prev" or whatever other means you prefer) and select "Left" or "Right" (next to the "Merge Choice:" label) for each. Selecting\
      "Left" means that the the left-most file's version of the difference will be used in creating the final result; choosing "Right" means that the right-most file's difference will be used. Each\
      choice is recorded, and can be changed arbitrarily many times. To commit the final, merged result to disk, choose "Write Merge File..." from the <btn>Merge</btn> menu.

<hdr>Merge Preview</hdr>

To see a preview of the file that would be written by "Write Merge File...", select "Show Merge Window" in the View menu. A separate window is shown containing the preview. It is updated as you\
      change merge choices. It is synchronized with the other text widgets if "Synchronize Scrollbars" is on.

<hdr>Credits</hdr>

Thanks to Wayne Throop for beta testing, and for giving valuable suggestions (and code!) along the way. Thanks (and credit) to John Heidemann for his window tags routines, which I shamelessly stole\
      (with permission) out of his great Tk-based Solitaire game, <itl>Klondike</itl>. Thanks to D. Elson (author of <itl>tkCVS</itl>) for writing the code that extends the RCS support to include\
      CVS. Thanks to John Brown for writing the code that extends the revision control support to SCCS.

<bld>Major</bld> thanks to Warren Jones (wjones@tc.fluke.com) and Peter Brandstrom (qraprbm@era-lvk.ericsson.se) for going way above and beyond the call. Warren added support for NT and cleaned up\
      the Unix code as well. Peter, independently, did the same thing and then added the new interface. The end result was the 2.x series...  Many, many thanks to you both!

<bld>Major</bld> thanks also to Bryan Oakley (boakley@vignette.com), who made the GUI even more appealing...	 Bryan did a <itl>ton</itl> of work, the result of which was the 3.x series.  Dorothy\
      Robinson provided helpful comments and patches for 3.x, too.  Thanks, Bryan and Dorothy!

Thanks to Dean Jones (dean@gallant.com) for permission to use his icons in the toolbar. 

Many, many thanks also to the many others who have written and provided ideas and encouragement and code since <itl>$g(name)</itl> was first released!	I haven't done much coding since the 1.x\
      series; almost every new feature that has come about since then has been the result of volunteer efforts.  Thanks, folks!
<hdr>Author</hdr>
John M. Klassa
<hdr>Comments</hdr>

Questions and comments should be sent to the TkDiff mailing list at http://www.accurev.com/free/tkdiff.
    }

    set text [subst\
        -nobackslashes -nocommands $text]
    do-text-info .help $title $text
}

######################################################################
# display help on the preferences
######################################################################
proc do-help-preferences {} {
    global g
    global pref

    customize-initLabels

    set title "$g(name) Preferences"
    set text {
<hdr>Overview</hdr>

Preferences are stored in a file in your home directory (identified by the environment variable <cmp>HOME</cmp>. If the environment variable <cmp>HOME</cmp> is not set the platform-specific variant\
      of "/" will be used. If you are on a Windows platform the file will be named <cmp>_tkdiff.rc</cmp> and will have the attribute "hidden". For all other platforms the file will be named\
      ".tkdiffrc". You may override the name and location of this file	by setting the environment variable <cmp>TKDIFFRC</cmp> to whatever filename you wish.

Preferences are organized into three categories: General, Display and Appearance.

<hdr>General</hdr>

<bld>$pref(diffcmd)</bld>

This is the command (with arguments) to run to generate a diff of the two files. Typically this will be "diff". If you are using gnu diff you might want to set it to "diff --ignore-space-change" to\
      ignore changes in whitespace. When this command is run, the names of two files to be diffed will be added as the last to arguments on the command line.

<bld>$pref(tmpdir)</bld>

The name of a directory for files that are temporarily created while $g(name) is running.

<bld>$pref(editor)</bld>

The name of an external editor program to use when editing a file (ie: when you select "Edit" from the popup menu). If this value is blank, a simple editor built in to $g(name) will be used. For\
      windows users you might want to set this to "notepad". Unix users may want to set this to "xterm -e vi" or perhaps "gnuclient". When run, the name of the file to edit will be appened as the\
      last argument on the command line.

<bld>$pref(geometry)</bld>

This defines the default size, in characters of the two text windows. The format should be <cmp>WIDTHxHEIGHT</cmp>. For example, "80x40".

<bld>$pref(fancyButtons)</bld>

If set, toolbar buttons will mimic the visual behavior of typical Microsoft Windows applications. Buttons will initially be flat until the cursor moves over them, at which time they will be raised.
If unset, toolbar buttons will always appear raised.

<bld>$pref(toolbarIcons)</bld>

If set, the toolbar buttons will use icons instead of text labels.
If unset, the toolbar buttons will use text labels instead of icons.

<bld>$pref(autocenter)</bld>

If set, whenever a new diff record becomes the current diff record (for example, when pressing the next or previous buttons), the diff record will be automatically centered on the screen.
If unset, no automatic scrolling will occur.

<bld>$pref(syncscroll)</bld>

If set, scrolling either text window will result in both windows scrolling.
If not set, the windows will scroll independent of each other.

<bld>$pref(autoselect)</bld>

If set, automatically select the nearest visible diff region when scrolling.
If not set, the current diff region will not change during scrolling.
This only takes effect if <bld>$pref(syncscroll)</bld> is set.

<hdr>Display</hdr>

<bld>$pref(showln)</bld>

If set, line numbers will be displayed alongside each line of each file.
If not set, no line numbers will appear.

<bld>$pref(tagln)</bld>

If set, line numbers are highlighted with the options defined in the Appearance section of the preferences.
If not set, line numbers won't be highlighted.

<bld>$pref(showcbs)</bld>

If set, change bars will be displayed alongside each line of each file.
If not set, no change bars will appear.

<bld>$pref(tagcbs)</bld>

If set, change indicators will be highlighted. If <itl>$pref(colorcbs)</itl> is set they will appear as solid colored bars that match the colors used in the diff map. If <itl>$pref(colorcbs)</itl>\
      is not set, the change indicators will be highlighted according to the options defined in the Appearance section of preferences.

<bld>$pref(showmap)</bld>

If set, colorized, graphical "diff map" will be displayed between the two files, showing regions that have changed. Red is used to show deleted lines, green for added lines, blue for changed\
      lines, and yellow for overlapping lines during a 3-way merge.
If not set, the diff map will not be shown.

<bld>$pref(showlineview)</bld>

If set, show a window at the bottom of the display that shows the current line from each file, one on top of the other. This window is most useful to do a byte-by-byte comparison of a line that has\
      changed.
If not set, the window will not be shown.

<bld>$pref(tagtext)</bld>

If set, the file contents will be highlighted with the options defined in the Appearance section of the preferences.
If not set, the file contents won't be highlighted.

<bld>$pref(colorcbs)</bld>

If set, the change bars will display as solid bars of color that match the colors used by the diff map.
If not set, the change bars will display a "+" for lines that exist in only one file, a "-" for lines that are missing from only one file, and "!" for lines that are different between the two files.

<hdr>Appearance</hdr>

<bld>$pref(textopt)</bld>

This is a list of Tk text widget options that are applied to each of the two text windows in the main display. If you have Tk installed on your machine these will be documented in the "Text.n" man\
      page.

<bld>$pref(difftag)</bld>

This is a list of Tk text widget tag options that are applied to all diff regions. Use this option to make diff regions stand out from regular text.

<bld>$pref(deltag)</bld>

This is a list of Tk text widget tag options that are applied to the current diff region. These options have a higher priority than those for all diff regions. So, for example, if you set the\
      forground for all diff regions to be black and set the foreground for the current diff region to be blue, the current diff region foreground color will be used.

<bld>$pref(instag)</bld>

This is a list of Tk text widget tag options that are applied to regions that have been inserted. These options have a higher priority than those for all diff regions.

<bld>$pref(chgtag)</bld>

This is a list of Tk text widget tag options that are applied to regions that have been changed. These options have a higher priority than those for all diff regions.

<bld>$pref(currtag)</bld>

This is a list of Tk text widget tag options that are applied to the current diff region. These tags have a higher priority than those for all diff regions, and a higher priority than the change,\
      inserted and deleted diff regions.

<bld>$pref(bytetag)</bld>

This is a list of Tk text widget tag options that are applied to individual characters in the line view. These options do not affect the main text displays.

<bld>$pref(tabstops)</bld>

This defines the number of characters for each tabstop in the main display windows. The default is 8.
    }

    # since we have embedded references to the preference labels in
    # the text, we need to perform substitutions. Because of this, if
    # you edit the above text, be sure to properly escape any dollar
    # signs that are not meant to be treated as a variable reference

    set text [subst\
        -nobackslashes -nocommands $text]
    do-text-info .help-preferences $title $text
}

######################################################################
#
# text formatting routines derived from Klondike
# Reproduced here with permission from their author.
#
# Copyright (C) 1993,1994 by John Heidemann <johnh@ficus.cs.ucla.edu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. The name of John Heidemann may not be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY JOHN HEIDEMANN ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL JOHN HEIDEMANN BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
######################################################################

proc put-text {tw txt} {
    global tk_version

    if {$tk_version >= 8.0} {
	$tw configure\
	    -font {Helvetica 10}

	$tw tag configure bld\
	    -font {Helvetica 10 bold}
	$tw tag configure cmp\
	    -font {Courier 10 bold}
	$tw tag configure hdr\
	    -font {Helvetica 14 bold}\
	    -underline 1
	$tw tag configure itl\
	    -font {Times 10 italic}

	$tw tag configure btn\
	    -font {Courier 9}\
	    -foreground black\
	    -background white\
	    -relief groove\
	    -borderwidth 2

	$tw tag configure ttl\
	    -font {Helvetica 14 italic}\
	    -foreground blue\
	    -justify center

    } else {
	$tw configure\
	    -font -*-Helvetica-Medium-R-Normal-*-14-*

	$tw tag configure bld\
	    -font -*-Helvetica-Bold-R-Normal-*-14-*
	$tw tag configure cmp\
	    -font -*-Courier-Medium-R-Normal-*-14-*
	$tw tag configure hdr\
	    -font -*-Helvetica-Bold-R-Normal-*-18-*\
	    -underline 1
	$tw tag configure itl\
	    -font -*-Times-Medium-I-Normal-*-14-*

	$tw tag configure btn\
	    -font -*-Courier-Medium-R-Normal-*-12-*\
	    -foreground black\
	    -background white\
	    -relief groove\
	    -borderwidth 2

	$tw tag configure ttl\
	    -font -*-Helvetica-Bold-R-Normal-*-18-*\
	    -foreground blue\
	    -justify center

    }
    $tw tag configure rev\
        -foreground white\
        -background black

    $tw mark set insert 0.0

    set t $txt

    while {[regexp\
        -indices {<([^@>]*)>} $t match inds] == 1} {

	set start [lindex $inds 0]
	set end [lindex $inds 1]
	set keyword [string range $t $start $end]

	set oldend [$tw index end]

	$tw insert end [string range $t 0 [expr {$start - 2}]]

	purge-all-tags $tw $oldend insert

	if {[string range $keyword 0 0] == "/"} {
	    set keyword [string trimleft $keyword "/"]
	    if {[info exists tags($keyword)] == 0} {
		error "end tag $keyword without beginning"
	    }
	    $tw tag add $keyword $tags($keyword) insert
	    unset tags($keyword)
	} else {
	    if {[info exists tags($keyword)] == 1} {
		error "nesting of begin tag $keyword"
	    }
	    set tags($keyword) [$tw index insert]
	}

	set t [string range $t [expr {$end + 2}] end]
    }

    set oldend [$tw index end]
    $tw insert end $t
    purge-all-tags $tw $oldend insert
}

proc purge-all-tags {w start end} {
    foreach tag [$w tag names $start] {
	$w tag remove $tag $start $end
    }
}

proc do-edit {} {
    global g
    global opts
    global finfo
    global w

    if {$g(activeWindow) == $w(LeftText)} {
	set fileno 1
    } elseif {$g(activeWindow) == $w(RightText)} {
	set fileno 2
    } else {
	set fileno 1
    }

    if {$finfo(tmp,$fileno)} {
	do-error "This file is not editable."
    } else {
	if {[string length [string trim $opts(editor)]] == 0} {
	    simpleEd open $finfo(pth,$fileno)
	} else {
	    eval exec $opts(editor) "{$finfo(pth,$fileno)}" &
	}
    }
}


##########################################################################
# A simple editor, from Bryan Oakley.
##########################################################################
proc simpleEd {command args} {
    global font

    switch $command {
	open {
		set filename [lindex $args 0]

		set w .editor
		set count 0
		while {[winfo exists ${w}$count]} {
		    incr count 1
		}
		set w ${w}$count

		toplevel $w\
		    -borderwidth 2\
		    -relief sunken
		wm title $w "$filename - Simple Editor"
		wm group $w .

		menu $w.menubar
		$w configure\
		    -menu $w.menubar

		$w.menubar add cascade\
		    -label "File"\
		    -menu $w.menubar.fileMenu
		$w.menubar add cascade\
		    -label "Edit"\
		    -menu $w.menubar.editMenu

		menu $w.menubar.fileMenu
		menu $w.menubar.editMenu

		$w.menubar.fileMenu add command\
		    -label "Save"\
		    -underline 1\
		    -command [list simpleEd save $filename $w]
		$w.menubar.fileMenu add command\
		    -label "Save As..."\
		    -underline 1\
		    -command [list simpleEd saveAs $filename $w]
		$w.menubar.fileMenu add separator
		$w.menubar.fileMenu add command\
		    -label "Exit"\
		    -underline 1\
		    -command [list simpleEd exit $w]

		$w.menubar.editMenu add command\
		    -label "Cut"\
		    -command [list event generate $w.text <<Cut>>]
		$w.menubar.editMenu add command\
		    -label "Copy"\
		    -command [list event generate $w.text <<Copy>>]
		$w.menubar.editMenu add command\
		    -label "Paste"\
		    -command [list event generate $w.text <<Paste>>]

		text $w.text\
		    -wrap none\
		    -xscrollcommand [list $w.hsb set]\
		    -yscrollcommand [list $w.vsb set]\
		    -borderwidth 0\
		    -font $font
		scrollbar $w.vsb\
		    -orient vertical\
		    -command [list $w.text yview]
		scrollbar $w.hsb\
		    -orient horizontal\
		    -command [list $w.text xview]

		grid $w.text\
		    -row 0\
		    -column 0\
		    -sticky nsew
		grid $w.vsb\
		    -row 0\
		    -column 1\
		    -sticky ns
		grid $w.hsb\
		    -row 1\
		    -column 0\
		    -sticky ew

		grid columnconfigure $w 0\
		    -weight 1
		grid columnconfigure $w 1\
		    -weight 0
		grid rowconfigure $w 0\
		    -weight 1
		grid rowconfigure $w 1\
		    -weight 0

		set fd [open $filename]
		$w.text insert 1.0 [read $fd]
		close $fd
	    }
	save {
		set filename [lindex $args 0]
		set w [lindex $args 1]
		set fd [open $filename w]
		puts $fd [$w.text get 1.0 "end-1c"]
		close $fd
	    }
	saveAs {
		set filename [lindex $args 0]
		set w [lindex $args 1]
		set filename [tk_getSaveFile\
		    -initialfile $filename]
		if {$filename != ""} {
		    simpleEd save $filename $w
		}
	    }
	exit {
		set w [lindex $args 0]
		destroy $w
	    }
    }

}

# end of simpleEd

#################################################################
# combobox.tcl reproduced here with permission from its author.
#################################################################
# Copyright (c) 1998, Bryan Oakley
# All Rights Reservered
#
# Bryan Oakley
# oakley@channelpoint.com
#
# combobox v1.07 October 9, 1998
#
# a combobox / dropdown listbox (pick your favorite name) widget
# written in pure tcl
#
# this code is freely distributable without restriction, but is
# provided as-is with no waranty expressed or implied.
#
# thanks to the following people who provided beta test support or
# patches to the code (in no particular order):
#
# Scott Beasley	    Alexandre Ferrieux	    Todd Helfter
# Matt Gushee	    Laurent Duperval	    John Jackson
# Fred Rapp	    Christopher Nelson
# Eric Galluzzo	    Jean-Francois Moine

# A special thanks to Martin M. Hunt who provided several good ideas,
# and always with a patch to implement them. Jean-Francois Moine,
# Todd Helfter and John Jackson were also kind enough to send in some
# code patches.

package require Tk 8.0
package provide combobox 1.07

namespace eval ::combobox {

    # this is the public interface
    namespace export combobox

    # get the scrollbar width. Because we try to be clever and draw our
    # own button instead of using a tk widget, we need to know what size
    # button to create. This little hack tells us the width of a scroll
    # bar.
    #
    # NB: we need to be sure and pick a window	that doesn't already
    # exist...
    set sbtest ".sbtest"
    set count 0
    while {[winfo exists $sbtest]} {
	set sbtest ".sbtest$count"
	incr count
    }
    scrollbar $sbtest
    set sb_width [winfo reqwidth $sbtest]
    destroy $sbtest

    # the image used for the button...
    image create bitmap ::combobox::bimage\
        -data {
	#define down_arrow_width 15
	#define down_arrow_height 15
	static char down_arrow_bits[] = {
	    0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,
	    0x00,0x80,0xf8,0x8f,0xf0,0x87,0xe0,0x83,
	    0xc0,0x81,0x80,0x80,0x00,0x80,0x00,0x80,
	    0x00,0x80,0x00,0x80,0x00,0x80
	}
    }
}

# this is the command that gets exported, and creates a new
# combobox widget. It works like other widget commands in that
# it takes as its first argument a widget path, and any remaining
# arguments are option/value pairs for the widget
proc ::combobox::combobox {w args} {

    # build it...
    eval build $w $args

    # set some bindings...
    setBindings $w

    # and we are done!
    return $w
}


# builds the combobox...
proc ::combobox::build {w args} {
    if {[winfo exists $w]} {
	error "window name \"$w\" already exists"
    }

    # create the namespace for this instance, and define a few
    # variables
    namespace eval ::combobox::$w {

	variable ignoreTrace 0
	variable oldFocus {}
	variable oldGrab {}
	variable oldValue {}
	variable options
	variable this
	variable widgets

    }

    # import the widgets and options arrays into this proc so
    # we don't have to use fully qualified names, which is a
    # pain.
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    # we need these to be defined, regardless if the user defined
    # them for us or not...
    array set options [list\
        -height 0\
        -maxheight 10\
        -command {}\
        -image {}\
        -textvariable {}\
        -editable 1\
        -commandstate normal\
        -state normal\
        -xscrollcommand {}]

    # this lets us reference the actual widget name from within
    # the namespace of the widget.
    namespace eval ::combobox::$w "set this $w"

    # the basic, always-visible parts of the combobox. We do these
    # here, because we want to query some of them for their default
    # values, which we want to juggle to other widgets. I suppose
    # I could use the options database, but for simplicity I choose
    # not to...
    set widgets(this) [frame $w\
        -class Combobox\
        -takefocus 0]
    set widgets(entry) [entry $w.entry\
        -takefocus 1]
    set widgets(button) [label $w.button\
        -takefocus 0]

    # we will later rename the frame's widget proc to be our
    # own custom widget proc. We need to keep track of this
    # new name, so we'll define and store it here...
    set widgets(frame) ::combobox::${w}::$w

    # gotta do this sooner or later. Might as well do it now
    pack $widgets(entry)\
        -side left\
        -fill both\
        -expand yes
    pack $widgets(button)\
        -side right\
        -fill y\
        -expand no

    # now, steal some attributes from the entry widget and store
    # them in our own options array
    foreach option [list\
        -background -foreground\
        -relief -borderwidth\
        -highlightthickness -highlightbackground\
        -font -width\
        -selectbackground -selectborderwidth\
        -selectforeground -takefocus] {
	set options($option) [$widgets(entry) cget $option]
    }

    # I should probably do this in a catch, but for now it's
    # good enough... What it does, obviously, is put all of
    # the option/values pairs into an array. Make them easier
    # to handle later on...
    array set options $args

    # now, the dropdown list... the same renaming nonsense
    # must go on here as well...
    set widgets(popup) [toplevel $w.top]
    set widgets(listbox) [listbox $w.top.list]
    set widgets(vsb) [scrollbar $w.top.vsb]

    pack $widgets(listbox)\
        -side left\
        -fill both\
        -expand y

    # fine tune the widgets based on the options (and a few
    # arbitrary values...)

    # NB: we are going to use the frame to handle the relief
    # of the widget as a whole, so the entry widget will be
    # flat. This makes the button which drops down the list
    # to appear "inside" the entry widget.

    $widgets(vsb) configure\
        -command "$widgets(listbox) yview"\
        -highlightthickness 0

    $widgets(button) configure\
        -highlightthickness 0\
        -borderwidth 1\
        -relief raised\
        -width [expr {[winfo reqwidth $widgets(vsb)] - 2}]

    $widgets(entry) configure\
        -borderwidth 0\
        -relief flat\
        -textvariable ::combobox::${w}::entryTextVariable\
        -highlightthickness 0

    $widgets(popup) configure\
        -borderwidth 1\
        -relief sunken

    $widgets(listbox) configure\
        -selectmode browse\
        -background [$widgets(entry) cget -bg]\
        -yscrollcommand "$widgets(vsb) set"\
        -borderwidth 0


    trace variable ::combobox::${w}::entryTextVariable w [list ::combobox::entryTrace $w]

    # do some window management foo on the dropdown window
    wm overrideredirect $widgets(popup) 1
    wm transient $widgets(popup) [winfo toplevel $w]
    wm group $widgets(popup) [winfo parent $w]
    wm resizable $widgets(popup) 0 0
    wm withdraw $widgets(popup)

    # this moves the original frame widget proc into our
    # namespace and gives it a handy name
    rename ::$w $widgets(frame)

    # now, create our widget proc. Obviously (?) it goes in
    # the global namespace. All combobox widgets will actually
    # share the same widget proc to cut down on the amount of
    # bloat.
    proc ::$w {command args} "
	eval ::combobox::widgetProc $w \$command \$args
    "

    # ok, the thing exists... let's do a bit more configuration.
    foreach opt [array names options] {
	::combobox::configure $widgets(this) set $opt $options($opt)
    }


}

# this is called whenever the contents of the entry widget changes;
# it's main purpose is to update the public textvariable, if
# any
proc ::combobox::entryTrace {w args} {
    upvar ::combobox::${w}::options options
    upvar ::combobox::${w}::ignoreTrace ignoreTrace

    if {[string length $options(-textvariable)]} {
	set ignoreTrace 1
	uplevel \#0 [list set $options(-textvariable) [set ::combobox::${w}::entryTextVariable]]
	unset ignoreTrace
    }
}

# here's where we do most of the binding foo. I think there's probably
# a few bindings I ought to add that I just haven't thought about...
#
# I'm not convinced these are the proper bindings. Ideally all bindings
# should be on "Combobox", but because of my juggling of bindtags I'm
# not convinced thats what I want to do. But, it all seems to work, its
# just not as robust as it could be.
proc ::combobox::setBindings {w} {
    namespace eval ::combobox::$w {
	variable widgets
	variable options

	# juggle the bindtags. The basic idea here is to associate the
	# widget name with the entry widget, so if a user does a bind
	# on the combobox it will get handled properly since it is
	# the entry widget that has keyboard focus.
	bindtags $widgets(entry) [concat $widgets(this) [bindtags $widgets(entry)]]

	bindtags $widgets(button) [concat $widgets(this) [bindtags $widgets(button)]]

	# make sure we clean up after ourselves...
	bind $widgets(entry) <Destroy> [list ::combobox::destroyHandler $this]

	# this closes the listbox if we get hidden
	bind $widgets(this) <Unmap> "$widgets(this) close"

	# this helps (but doesn't fully solve) focus issues. The general
	# idea is, whenever the frame gets focus it gets passed on to
	# the entry widget
	bind $widgets(this) <FocusIn> "tkTabToWindow $widgets(entry)"

	# override the default bindings for tab and shift-tab. The
	# focus procs take a widget as their only parameter and we
	# want to make sure the right window gets used (for shift-
	# tab we want it to appear as if the event was generated
	# on the frame rather than the entry. I

	bind $widgets(entry) <Tab> "
	    tkTabToWindow \[tk_focusNext $widgets(entry)\]
	    break
	"
	bind $widgets(entry) <Shift-Tab> "
	    tkTabToWindow \[tk_focusPrev $widgets(this)\]
	    break
	"

	# this makes our "button" (which is actually a label)
	# do the right thing
	bind $widgets(button) <ButtonPress-1> [list $widgets(this) toggle]

	# this lets the autoscan of the listbox work, even if they
	# move the cursor over the entry widget.
	bind $widgets(entry) <B1-Enter> "break"

	# this will (hopefully) close (and lose the grab on) the
	# listbox if the user clicks anywhere outside of it. Note
	# that on Windows, you can click on some other app and
	# the listbox will still be there, because tcl won't see
	# that button click
	bind Combobox <Any-ButtonPress> [list $widgets(this) close]
	bind Combobox <Any-ButtonRelease> [list $widgets(this) close]

	bind $widgets(listbox) <ButtonRelease-1> "
	    ::combobox::select $widgets(this) \[$widgets(listbox) nearest %y\]
	    break
	"

	bind $widgets(vsb) <ButtonPress-1> {continue}
	bind $widgets(vsb) <ButtonRelease-1> {continue}

	bind $widgets(listbox) <Any-Motion> {
	    %W selection clear 0 end
	    %W activate @%x,%y
	    %W selection anchor @%x,%y
	    %W selection set @%x,%y @%x,%y
	    # need to do a yview if the cursor goes off the top
	    # or bottom of the window... (or do we?)
	}

	# these events need to be passed from the entry
	# widget to the listbox, or need some sort of special
	# handling....
	foreach event [list <Up> <Down> <Tab> <Return> <Escape> <Next> <Prior> <Double-1> <1> <Any-KeyPress> <FocusIn> <FocusOut>] {
	    bind $widgets(entry) $event "::combobox::handleEvent $widgets(this) $event"
	}

    }
}

# this proc handles events from the entry widget that we want handled
# specially (typically, to allow navigation of the list even though
# the focus is in the entry widget)
proc ::combobox::handleEvent {w event} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options
    upvar ::combobox::${w}::oldValue oldValue

    # for all of these events, if we have a special action we'll
    # do that and do a "return -code break" to keep additional
    # bindings from firing. Otherwise we'll let the event fall
    # on through.
    switch $event {
	"<Any-KeyPress>" {
		# if the widget is editable, clear the selection.
		# this makes it more obvious what will happen if the
		# user presses <Return> (and helps our code know what
		# to do if the user presses return)
		if {$options(-editable)} {
		    $widgets(listbox) see 0
		    $widgets(listbox) selection clear 0 end
		    $widgets(listbox) selection anchor 0
		    $widgets(listbox) activate 0
		}
	    }
	"<FocusIn>" {
		set oldValue [$widgets(entry) get]
	    }
	"<FocusOut>" {
		if {[winfo ismapped $widgets(popup)]} {
		    return\
		        -code break

		} else {
		    # did the value change?
		    set newValue [set ::combobox::${w}::entryTextVariable]
		    if {$oldValue != $newValue} {
			callCommand $widgets(this) $newValue
		    }
		}
	    }
	"<1>" {
		set editable [::combobox::getBoolean $options(-editable)]
		if {!$editable} {
		    if {[winfo ismapped $widgets(popup)]} {
			$widgets(this) close
			return\
			    -code break


		    } else {
			if {$options(-state) != "disabled"} {
			    $widgets(this) open
			    return\
			        -code break

			}
		    }
		}
	    }
	"<Double-1>" {
		if {$options(-state) != "disabled"} {
		    $widgets(this) toggle
		    return\
		        -code break

		}
	    }
	"<Tab>" {
		if {[winfo ismapped $widgets(popup)]} {
		    ::combobox::find $widgets(this)
		    return\
		        -code break

		} else {
		    ::combobox::setValue $widgets(this) [$widgets(this) get]
		}
	    }
	"<Escape>" {
		$widgets(entry) delete 0 end
		$widgets(entry) insert 0 $oldValue
		if {[winfo ismapped $widgets(popup)]} {
		    $widgets(this) close
		    return\
		        -code break

		}
	    }
	"<Return>" {
		# did the value change?
		set newValue [set ::combobox::${w}::entryTextVariable]
		if {$oldValue != $newValue} {
		    callCommand $widgets(this) $newValue
		}

		if 0 {
		    if {$options(-editable)} {
			# if there is something in the list that is selected,
			# we'll pick it. Otherwise, use whats in the
			# entry widget...
			set index [$widgets(listbox) curselection]
			if {[winfo ismapped $widgets(popup)] && [llength $index] > 0} {

			    ::combobox::select $widgets(this) [$widgets(listbox) curselection]
			    return\
			        -code break


			} else {
			    # the value doesn't change in this case, but we
			    # do need to arrange for the -command to be called
			    callCommand $widgets(this) [set ::combobox::${w}::entryTextVariable]
			    $widgets(this) close

			    return
			}
		    }
		}

		if {[winfo ismapped $widgets(popup)]} {
		    ::combobox::select $widgets(this) [$widgets(listbox) curselection]
		    return\
		        -code break

		}

	    }
	"<Next>" {
		$widgets(listbox) yview scroll 1 pages
		set index [$widgets(listbox) index @0,0]
		$widgets(listbox) see $index
		$widgets(listbox) activate $index
		$widgets(listbox) selection clear 0 end
		$widgets(listbox) selection anchor $index
		$widgets(listbox) selection set $index

	    }
	"<Prior>" {
		$widgets(listbox) yview scroll\
		    -1 pages
		set index [$widgets(listbox) index @0,0]
		$widgets(listbox) activate $index
		$widgets(listbox) see $index
		$widgets(listbox) selection clear 0 end
		$widgets(listbox) selection anchor $index
		$widgets(listbox) selection set $index
	    }
	"<Down>" {
		if {[winfo ismapped $widgets(popup)]} {
		    tkListboxUpDown $widgets(listbox) 1
		    return\
		        -code break


		} else {
		    if {$options(-state) != "disabled"} {
			$widgets(this) open
			return\
			    -code break

		    }
		}
	    }
	"<Up>" {
		if {[winfo ismapped $widgets(popup)]} {
		    tkListboxUpDown $widgets(listbox) -1
		    return\
		        -code break


		} else {
		    if {$options(-state) != "disabled"} {
			$widgets(this) open
			return\
			    -code break

		    }
		}
	    }
    }
}

# this cleans up the mess that is left behind when the widget goes away
# at least, that's the theory.
proc ::combobox::destroyHandler {w} {

    # kill any trace we may have started...
    namespace eval ::combobox::$w {
	variable options
	variable widgets

	# kill any trace we have for the user's -textvariable
	catch {
	    if {[info exists options(-textvariable)]} {
		if {[string length $options(-textvariable)]} {
		    trace vdelete $options(-textvariable) w [list ::combobox::vTrace $widgets(this)]
		}
	    }
	}
    }

    # kill the namespace
    catch {namespace delete ::combobox::$w}
}

# finds something in the listbox that matches the pattern in the
# entry widget
#
# I'm not convinced this is working the way it ought to. It works,
# but is the behavior what is expected? I've also got a gut feeling
# that there's a better way to do this, but I'm too lazy to figure
# it out...
proc ::combobox::find {w {exact 0}} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    ## *sigh* this logic is rather gross and convoluted. Surely
    ## there is a more simple, straight-forward way to implement
    ## all this. As the saying goes, I lack the time to make it
    ## shorter...

    # use what is already in the entry widget as a pattern
    set pattern [$widgets(entry) get]

    if {[string length $pattern] == 0} {
	# clear the current selection
	$widgets(listbox) see 0
	$widgets(listbox) selection clear 0 end
	$widgets(listbox) selection anchor 0
	$widgets(listbox) activate 0
	return
    }

    # we're going to be searching this list...
    set list [$widgets(listbox) get 0 end]

    # if we are doing an exact match, try to find,
    # well, an exact match
    if {$exact} {
	set exactMatch [lsearch\
	    -exact $list $pattern]
    }

    # search for it. We'll try to be clever and not only
    # search for a match for what they typed, but a match for
    # something close to what they typed. We'll keep removing one
    # character at a time from the pattern until we find a match
    # of some sort.
    set index -1
    while {$index == -1 && [string length $pattern]} {
	set index [lsearch\
	    -glob $list "$pattern*"]
	if {$index == -1} {
	    regsub {.$} $pattern {} pattern
	}
    }

    # this is the item that most closely matches...
    set thisItem [lindex $list $index]

    # did we find a match? If so, do some additional munging...
    if {$index != -1} {

	# we need to find the part of the first item that is
	# unique wrt the second... I know there's probably a
	# simpler way to do this...

	set nextIndex [expr {$index + 1}]
	set nextItem [lindex $list $nextIndex]

	# we don't really need to do much if the next
	# item doesn't match our pattern...
	if {[string match $pattern* $nextItem]} {
	    # ok, the next item matches our pattern, too
	    # now the trick is to find the first character
	    # where they *don't* match...
	    set marker [string length $pattern]
	    while {$marker <= [string length $pattern]} {
		set a [string index $thisItem $marker]
		set b [string index $nextItem $marker]
		if {[string compare $a $b] == 0} {
		    append pattern $a
		    incr marker
		} else {
		    break
		}
	    }
	} else {
	    set marker [string length $pattern]
	}

    } else {
	set marker end
	set index 0
    }

    # ok, we know the pattern and what part is unique;
    # update the entry widget and listbox appropriately
    if {$exact && $exactMatch == -1} {
	$widgets(listbox) selection clear 0 end
	$widgets(listbox) see $index
    } else {
	$widgets(entry) delete 0 end
	$widgets(entry) insert end $thisItem
	$widgets(entry) selection clear
	$widgets(entry) selection range $marker end
	$widgets(listbox) activate $index
	$widgets(listbox) selection clear 0 end
	$widgets(listbox) selection anchor $index
	$widgets(listbox) selection set $index
	$widgets(listbox) see $index
    }
}

# selects an item from the list and sets the value of the combobox
# to that value
proc ::combobox::select {w index} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    catch {
	set data [$widgets(listbox) get [lindex $index 0]]
	::combobox::setValue $widgets(this) $data
	$widgets(entry) selection range 0 end
    }

    $widgets(this) close
}

proc ::combobox::handleScrollbar {w {action "unknown"}} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    if {$options(-height) == 0} {
	set hlimit $options(-maxheight)
    } else {
	set hlimit $options(-height)
    }

    switch $action {
	"grow" {
		if {$hlimit > 0 && [$widgets(listbox) size] > $hlimit} {
		    pack $widgets(vsb)\
		        -side right\
		        -fill y\
		        -expand n
		}
	    }
	"shrink" {
		if {$hlimit > 0 && [$widgets(listbox) size] <= $hlimit} {
		    pack forget $widgets(vsb)
		}
	    }
	"crop" {
		# this means the window was cropped and we definitely
		# need a scrollbar no matter what the user wants
		pack $widgets(vsb)\
		    -side right\
		    -fill y\
		    -expand n
	    }
	default {
		if {$hlimit > 0 && [$widgets(listbox) size] > $hlimit} {
		    pack $widgets(vsb)\
		        -side right\
		        -fill y\
		        -expand n
		} else {
		    pack forget $widgets(vsb)
		}
	    }
    }
}

# computes the geometry of the popup list based on the size of the
# combobox...
proc ::combobox::computeGeometry {w} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    if {$options(-height) == 0 && $options(-maxheight) != "0"} {
	# if this is the case, count the items and see if
	# it exceeds our maxheight. If so, set the listbox
	# size to maxheight...
	set nitems [$widgets(listbox) size]
	if {$nitems > $options(-maxheight)} {
	    # tweak the height of the listbox
	    $widgets(listbox) configure\
	        -height $options(-maxheight)
	} else {
	    # un-tweak the height of the listbox
	    $widgets(listbox) configure\
	        -height 0
	}
	update idletasks
    }

    # compute height and width of the dropdown list
    set bd [$widgets(popup) cget -borderwidth]
    set height [expr {[winfo reqheight $widgets(popup)] + $bd + $bd}]
    set width [winfo width $widgets(this)]

    # figure out where to place it on the screen, trying to take into
    # account we may be running under some virtual window manager
    set screenWidth [winfo screenwidth $widgets(this)]
    set screenHeight [winfo screenheight $widgets(this)]
    set rootx [winfo rootx $widgets(this)]
    set rooty [winfo rooty $widgets(this)]
    set vrootx [winfo vrootx $widgets(this)]
    set vrooty [winfo vrooty $widgets(this)]

    # the x coordinate is simply the rootx of our widget, adjusted for
    # the virtual window. We won't worry about whether the window will
    # be offscreen to the left or right -- we want the illusion that it
    # is part of the entry widget, so if part of the entry widget is off-
    # screen, so will the list. If you want to change the behavior,
    # simply change the if statement... (and be sure to update this
    # comment!)
    set x [expr {$rootx + $vrootx}]
    if {0} {
	set rightEdge [expr {$x + $width}]
	if {$rightEdge > $screenWidth} {
	    set x [expr {$screenWidth - $width}]
	}
	if {$x < 0} {
	    set x 0
	}
    }

    # the y coordinate is the rooty plus vrooty offset plus
    # the height of the static part of the widget plus 1 for a
    # tiny bit of visual separation...
    set y [expr {$rooty + $vrooty + [winfo reqheight $widgets(this)] + 1}]
    set bottomEdge [expr {$y + $height}]

    if {$bottomEdge >= $screenHeight} {
	# ok. Fine. Pop it up above the entry widget isntead of
	# below.
	set y [expr {($rooty - $height - 1) + $vrooty}]

	if {$y < 0} {
	    # this means it extends beyond our screen. How annoying.
	    # Now we'll try to be real clever and either pop it up or
	    # down, depending on which way gives us the biggest list.
	    # then, we'll trim the list to fit and force the use of
	    # a scrollbar

	    # (sadly, for windows users this measurement doesn't
	    # take into consideration the height of the taskbar,
	    # but don't blame me -- there isn't any way to detect
	    # it or figure out its dimensions. The same probably
	    # applies to any window manager with some magic windows
	    # glued to the top or bottom of the screen)

	    if {$rooty > [expr {$screenHeight / 2}]} {
		# we are in the lower half of the screen --
		# pop it up. Y is zero; that parts easy. The height
		# is simply the y coordinate of our widget, minus
		# a pixel for some visual separation. The y coordinate
		# will be the topof the screen.
		set y 1
		set height [expr {$rooty - 1 - $y}]

	    } else {
		# we are in the upper half of the screen --
		# pop it down
		set y [expr {$rooty + $vrooty + [winfo reqheight $widgets(this)] + 1}]
		set height [expr {$screenHeight - $y}]

	    }

	    # force a scrollbar
	    handleScrollbar $widgets(this) crop
	}
    }

    if {$y < 0} {
	# hmmm. Bummer.
	set y 0
	set height $screenheight
    }

    set geometry [format "=%dx%d+%d+%d" $width $height $x $y]
    return $geometry
}

# perform an internal widget command, then mung any error results
# to look like it came from our megawidget. A lot of work just to
# give the illusion that our megawidget is an atomic widget
proc ::combobox::doInternalWidgetCommand {w subwidget command args} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    set subcommand $command
    set command [concat $widgets($subwidget) $command $args]
    if {[catch $command result]} {
	# replace the subwidget name with the megawidget name
	regsub $widgets($subwidget) $result $widgets(this) result

	# replace specific instances of the subwidget command
	# with out megawidget command
	switch $subwidget,$subcommand {
	    listbox,index {
		    regsub "index" $result "list index" result
		}
	    listbox,insert {
		    regsub "insert" $result "list insert" result
		}
	    listbox,delete {
		    regsub "delete" $result "list delete" result
		}
	    listbox,get {
		    regsub "get" $result "list get" result
		}
	    listbox,size {
		    regsub "size" $result "list size" result
		}
	}
	error $result

    } else {
	return $result
    }
}


# this is the widget proc that gets called when you do something like
# ".checkbox configure ..."
proc ::combobox::widgetProc {w command args} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options
    upvar ::combobox::${w}::oldFocus oldFocus
    upvar ::combobox::${w}::oldFocus oldGrab

    # this is just shorthand notation...
    set doWidgetCommand [list ::combobox::doInternalWidgetCommand $widgets(this)]

    if {$command == "list"} {
	# ok, the next argument is a list command; we'll
	# rip it from args and append it to command to
	# create a unique internal command
	#
	# NB: because of the sloppy way we are doing this,
	# we'll also let the user enter our secret command
	# directly (eg: listinsert, listdelete), but we
	# won't document that fact
	set command "list[lindex $args 0]"
	set args [lrange $args 1 end]
    }

    # many of these commands are just synonyms for specific
    # commands in one of the subwidgets. We'll get them out
    # of the way first, then do the custom commands.
    switch $command {
	bbox {
		eval $doWidgetCommand entry bbox $args
	    }
	delete {
		eval $doWidgetCommand entry delete $args
	    }
	get {
		eval $doWidgetCommand entry get $args
	    }
	icursor {
		eval $doWidgetCommand entry icursor $args
	    }
	index {
		eval $doWidgetCommand entry index $args
	    }
	insert {
		eval $doWidgetCommand entry insert $args
	    }
	scan {
		eval $doWidgetCommand entry scan $args
	    }
	selection {
		eval $doWidgetCommand entry selection $args
	    }
	xview {
		eval $doWidgetCommand entry xview $args
	    }
	listget {
		eval $doWidgetCommand listbox get $args
	    }
	listindex {
		eval $doWidgetCommand listbox index $args
	    }
	listsize {
		eval $doWidgetCommand listbox size $args
	    }
	subwidget {
		set knownWidgets [list button entry listbox popup vsb]
		if {[llength $args] == 0} {
		    return $knownWidgets
		}

		set name [lindex $args 0]
		if {[lsearch $knownWidgets $name] != -1} {
		    return $widgets($name)
		} else {
		    error "unknown subwidget $name"
		}
	    }
	listinsert {
		eval $doWidgetCommand listbox insert $args
		handleScrollbar $w "grow"
	    }
	listdelete {
		eval $doWidgetCommand listbox delete $args
		handleScrollbar $w "shrink"
	    }
	toggle {
		# ignore this command if the widget is disabled...
		if {$options(-state) == "disabled"} return

		# pops down the list if it is not, hides it
		# if it is...
		if {[winfo ismapped $widgets(popup)]} {
		    $widgets(this) close
		} else {
		    $widgets(this) open
		}
	    }
	open {

		# if this is an editable combobox, the focus should
		# be set to the entry widget
		if {$options(-editable)} {
		    focus $widgets(entry)
		    $widgets(entry) select range 0 end
		    $widgets(entry) icur end
		}

		# if we are disabled, we won't allow this to happen
		if {$options(-state) == "disabled"} {
		    return 0
		}

		# compute the geometry of the window to pop up, and set
		# it, and force the window manager to take notice
		# (even if it is not presently visible).
		#
		# this isn't strictly necessary if the window is already
		# mapped, but we'll go ahead and set the geometry here
		# since its harmless and *may* actually reset the geometry
		# to something better in some weird case.
		set geometry [::combobox::computeGeometry $widgets(this)]
		wm geometry $widgets(popup) $geometry
		update idletasks

		# if we are already open, there's nothing else to do
		if {[winfo ismapped $widgets(popup)]} {
		    return 0
		}

		# save the widget that currently has the focus; we'll restore
		# the focus there when we're done
		set oldFocus [focus]

		# ok, tweak the visual appearance of things and
		# make the list pop up
		$widgets(button) configure\
		    -relief sunken
		wm deiconify $widgets(popup)
		#	    raise $widgets(popup) [winfo parent $widgets(this)]

		# force focus to the entry widget so we can handle keypress
		# events for traversal
		focus\
		    -force $widgets(entry)
		raise $widgets(popup) [winfo parent $widgets(this)]

		# select something by default, but only if its an
		# exact match...
		::combobox::find $widgets(this) 1

		# save the current grab state for the display containing
		# this widget. We'll restore it when we close the dropdown
		# list
		set status "none"
		set grab [grab current $widgets(this)]
		if {$grab != ""} {
		    set status [grab status $grab]
		}
		set oldGrab [list $grab $status]
		unset grab status

		# *gasp* do a global grab!!! Mom always told not to
		# do things like this, but these are desparate times.
		grab\
		    -global $widgets(this)

		# fake the listbox into thinking it has focus. This is
		# necessary to get scanning initialized properly in the
		# listbox.
		event generate $widgets(listbox) <B1-Enter>

		return 1
	    }
	close {
		# if we are already closed, don't do anything...
		if {![winfo ismapped $widgets(popup)]} {
		    return 0
		}

		# restore the focus and grab, but ignore any errors...
		# we're going to be paranoid and release the grab before
		# trying to set any other grab because we really really
		# really want to make sure the grab is released.
		catch {focus $oldFocus} result
		catch {grab release $widgets(this)}
		catch {
		    set status [lindex $oldGrab 1]
		    if {$status == "global"} {
			grab\
			    -global [lindex $oldGrab 0]
		    } elseif {$status == "local"} {
			grab [lindex $oldGrab 0]
		    }
		    unset status
		}

		# hides the listbox
		$widgets(button) configure\
		    -relief raised
		wm withdraw $widgets(popup)

		# select the data in the entry widget. Not sure
		# why, other than observation seems to suggest that's
		# what windows widgets do.
		set editable [::combobox::getBoolean $options(-editable)]
		if {$editable} {
		    $widgets(entry) selection range 0 end
		    $widgets(button) configure\
		        -relief raised
		}


		# magic tcl stuff (see tk.tcl in the distribution
		# lib directory)
		tkCancelRepeat

		return 1
	    }
	cget {
		# tries to mimic the standard "cget" command
		if {[llength $args] != 1} {
		    error "wrong # args: should be \"$widgets(this) cget option\""
		}
		set option [lindex $args 0]
		return [::combobox::configure $widgets(this) cget $option]
	    }
	configure {
		# trys to mimic the standard "configure" command
		if {[llength $args] == 0} {
		    # this isn't the same format as "real" widgets,
		    # but for now its good enough
		    foreach item [lsort [array names options]] {
			lappend result [list $item $options($item)]
		    }
		    return $result

		} elseif {[llength $args] == 1} {
		    # they are requesting configure information...
		    set option [lindex $args 0]
		    return [::combobox::configure $widgets(this) get $option]
		} else {
		    array set tmpopt $args
		    foreach opt [array names tmpopt] {
			::combobox::configure $widgets(this) set $opt $tmpopt($opt)
		    }
		}
	    }
	default {
		error "bad option \"$command\""
	    }
    }
}

# handles all of the configure and cget foo
proc ::combobox::configure {w action {option ""} {newValue ""}} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options
    set namespace "::combobox::${w}"

    if {$action == "get"} {
	# this really ought to do more than just get the value,
	# but for the time being I don't fully support the configure
	# command in all its glory...
	if {$option == "-value"} {
	    return [list "-value" [$widgets(entry) get]]
	} else {
	    return [list $option $options($option)]
	}

    } elseif {$action == "cget"} {
	if {$option == "-value"} {
	    return [$widgets(entry) get]
	} else {
	    return $options($option)
	}

    } else {

	if {[info exists options($option)]} {
	    set oldValue $options($option)
	    set options($option) $newValue
	} else {
	    set oldValue ""
	    set options($option) $newValue
	}

	# some (actually, most) options require us to
	# do something, like change the attributes of
	# a widget or two. Here's where we do that...
	switch -- $option {
	    -background {
		    $widgets(frame) configure\
		        -background $newValue
		    $widgets(entry) configure\
		        -background $newValue
		    $widgets(listbox) configure\
		        -background $newValue
		    $widgets(vsb) configure\
		        -background $newValue
		    $widgets(vsb) configure\
		        -troughcolor $newValue
		}
	    -borderwidth {
		    $widgets(frame) configure\
		        -borderwidth $newValue
		}
	    -command {
		    # nothing else to do...
		}
	    -commandstate {
		    # do some value checking...
		    if {$newValue != "normal" && $newValue != "disabled"} {
			set options($option) $oldValue
			error "bad state value \"$newValue\"; must be normal or disabled"
		    }
		}
	    -cursor {
		    $widgets(frame) configure\
		        -cursor $newValue
		    $widgets(entry) configure\
		        -cursor $newValue
		    $widgets(listbox) configure\
		        -cursor $newValue
		}
	    -editable {
		    if {$newValue} {
			# it's editable...
			$widgets(entry) configure\
			    -state normal
		    } else {
			$widgets(entry) configure\
			    -state disabled
		    }
		}
	    -font {
		    $widgets(entry) configure\
		        -font $newValue
		    $widgets(listbox) configure\
		        -font $newValue
		}
	    -foreground {
		    $widgets(entry) configure\
		        -foreground $newValue
		    $widgets(button) configure\
		        -foreground $newValue
		    $widgets(listbox) configure\
		        -foreground $newValue
		}
	    -height {
		    $widgets(listbox) configure\
		        -height $newValue
		    handleScrollbar $w
		}
	    -highlightbackground {
		    $widgets(frame) configure\
		        -highlightbackground $newValue
		}
	    -highlightcolor {
		    $widgets(frame) configure\
		        -highlightcolor $newValue
		}
	    -highlightthickness {
		    $widgets(frame) configure\
		        -highlightthickness $newValue
		}
	    -image {
		    if {[string length $newValue] > 0} {
			$widgets(button) configure\
			    -image $newValue
		    } else {
			$widgets(button) configure\
			    -image ::combobox::bimage
		    }
		}
	    -maxheight {
		    # computeGeometry may dork with the actual height
		    # of the listbox, so let's undork it
		    $widgets(listbox) configure\
		        -height $options(-height)
		    handleScrollbar $w
		}
	    -relief {
		    $widgets(frame) configure\
		        -relief $newValue
		}
	    -selectbackground {
		    $widgets(entry) configure\
		        -selectbackground $newValue
		    $widgets(listbox) configure\
		        -selectbackground $newValue
		}
	    -selectborderwidth {
		    $widgets(entry) configure\
		        -selectborderwidth $newValue
		    $widgets(listbox) configure\
		        -selectborderwidth $newValue
		}
	    -selectforeground {
		    $widgets(entry) configure\
		        -selectforeground $newValue
		    $widgets(listbox) configure\
		        -selectforeground $newValue
		}
	    -state {
		    if {$newValue == "normal"} {
			# it's enabled
			set editable [::combobox::getBoolean $options(-editable)]
			if {$editable} {
			    $widgets(entry) configure\
			        -state normal
			    $widgets(entry) configure\
			        -takefocus 1
			}
		    } elseif {$newValue == "disabled"} {
			# it's disabled
			$widgets(entry) configure\
			    -state disabled
			$widgets(entry) configure\
			    -takefocus 0

		    } else {
			set options($option) $oldValue
			error "bad state value \"$newValue\"; must be normal or disabled"
		    }

		}
	    -takefocus {
		    $widgets(entry) configure\
		        -takefocus $newValue
		}
	    -textvariable {
		    # destroy our trace on the old value, if any
		    if {[string length $oldValue] > 0} {
			trace vdelete $oldValue w [list ::combobox::vTrace $widgets(this)]
		    }
		    # set up a trace on the new value, if any. Also, set
		    # the value of the widget to the current value of
		    # the variable

		    set variable ::$newValue
		    if {[string length $newValue] > 0} {
			if {[info exists $variable]} {
			    ::combobox::setValue $widgets(this) [set $variable]
			}
			trace variable $variable w [list ::combobox::vTrace $widgets(this)]
		    }
		}
	    -value {
		    ::combobox::setValue $widgets(this) $newValue
		}
	    -width {
		    $widgets(entry) configure\
		        -width $newValue
		    $widgets(listbox) configure\
		        -width $newValue
		}
	    -xscrollcommand {
		    $widgets(entry) configure\
		        -xscrollcommand $newValue
		}
	    default {
		    error "unknown option \"$option\""
		}
	}
    }
}

# this proc is called whenever the user changes the value of
# the -textvariable associated with a widget
proc ::combobox::vTrace {w args} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options
    upvar ::combobox::${w}::ignoreTrace ignoreTrace

    if {[info exists ignoreTrace]} return
    ::combobox::setValue $widgets(this) [set ::$options(-textvariable)]
}

# sets the value of the combobox and calls the -command, if defined
proc ::combobox::setValue {w newValue {index -1}} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options
    upvar ::combobox::${w}::ignoreTrace ignoreTrace
    upvar ::combobox::${w}::oldValue oldValue

    # set our internal textvariable; this will cause any public
    # textvariable (ie: defined by the user) to be updated as
    # well
    set ::combobox::${w}::entryTextVariable $newValue

    # redefine our concept of the "old value". Do it before running
    # any associated command so we can be sure it happens even
    # if the command somehow fails.
    set oldValue $newValue

    # call the associated command. The proc will handle whether or
    # not to actually call it, and with what args
    callCommand $w $newValue
}

# call the associated command, if any
proc ::combobox::callCommand {w newValue} {
    upvar ::combobox::${w}::widgets widgets
    upvar ::combobox::${w}::options options

    # call the associated command, if defined and -commandstate is
    # set to "normal"
    if {$options(-commandstate) == "normal" && [string length $options(-command)] > 0} {
	set args [list $widgets(this) $newValue]
	uplevel \#0 $options(-command) $args
    }
}


# returns the value of a (presumably) boolean string (ie: it should
# do the right thing if the string is "yes", "no", "true", 1, etc
proc ::combobox::getBoolean {value {errorValue 1}} {
    if {[catch {expr {([string trim $value]) ?1:0}} res]} {
	return $errorValue
    } else {
	return $res
    }
}

# computes the combobox widget name based on the name of one of
# it's children widgets.. Not presently used, but might come in
# handy...
proc ::combobox::widgetName {w} {
    while {$w != "."} {
	if {[winfo class $w] == "Combobox"} {
	    return $w
	}
	set w [winfo parent $w]
    }
    error "internal error: $w is not a child of a combobox"
}


# end of combobox.tcl

######################################################################
# icon image data. 
######################################################################
image create photo findImage\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAjUAAMIHEiwoEF3
AOQpXMiQIQB3ARC6a6fO3buHAiVWfAcPYwB1AN6pa/fQnUkAIy+qEwiy3bp07DqaPPmS3TqS
Kz/SA8ATQDyB8XoCoJczI4B2F+VBjCjvocyBCNOVS9cxAE+rUqliRHhznbunEY96dbl15kyC
Zs8OrDgzJ1uTRVnSYzcO5M8AQeu6I0oQ5DukAOAJlglPJVR5gBMifNjUqTyoAM6NK1f1auTJ
YDuuOxdTKM/NneGFHVkRLEKKE0GeFGzRdODWMhd7Xipb6FKDuAsGBAA7
}

image create photo centerDiffsImage\
    -format gif\
    -data {
R0lGODlhFAAUAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAAAiUAAMIHBjAHYCD
ANwRHHjOncOHBgkRSgjRYUOEGAEYMpQRoUMA/8SJFGdwY0JyKFFSBGCuZcuSHN25bLmyo0aO
Nj+GJAkg0caNiU6q/DjToE9DQWW6rNkxUdCcBneONHhy5FCDM106zErzo82vB3XuTEm27Equ
aJd6BQsVpFSRZcmeTYuWKduM7hpW3Lv33MK/gAUGBAA7
}

image create photo firstDiffImage\
    -format gif\
    -data {
R0lGODlhFAAUAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAAAiUAAMIdFevoMGD
Bd0JXBig3j9ChAxJnDixHkOBDilqlGjxIkGEIBVevHjOnbtzI1MKLAkAwEmVJN0BIKTIJUqY
AVgS+neo5kuVOv9J7Gkzpc5BFIn+XHg06SGlN1fKbDlTYiKqRRmWNFnV0FWTS7XqtGoz6six
XrMClRkxbdizbMm+jQngUKK7ao1OxTo3JliTZgUGBAA7
}

image create photo prevDiffImage\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAiGAAMIHCjwnDt3
5wgqLHjQHQBChgwlAtAw4cIABh9GnIjwIsOH/yIeUkTR4sWMECWW9DgQJcmOJx0SGhRR5KGR
Kxei3JjT406VMH06BECUaFCWGXsilfkP51GCKGnWdGryY9GUE4s+xfiT47mqCrsq1SmT51ao
ZYGCDevwUKK3Y8k2PLg2IAA7
}

image create photo nextDiffImage\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAiGAAMIHHjOncGD
5wYqVFgQACFDhhIBcJdwIUN3DgsdUjSxokWBDR9G7PixIYCTIiWeJGmx4T9ChA6x/BggJESJ
FGnWtDmSoseLGSFC3DizJMaiNE2uRLrQ5U2mQFNCJYhRak6dPHH+vGjQ4VOETasWEmrokFmO
V6OOLYt2a1iHbXWGTbswIAA7
}

image create photo lastDiffImage\
    -format gif\
    -data {
R0lGODlhFAAUAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAAAiTAAMIHHjOncGD
5wYqVFgQgMOH7hIuZOgOwD9ChA4BiDiRokVDhhJtlNgxQENCIEVyLGmyIsqQI1meO5lyJEmK
BgG8VGnwZsuHOmtCvHmyEEiQh5IqiumRkNGjh5auXFgUqVSfTQtFZSrT5VWWHrmCFVhwakl3
9dKqXZvW3cR6F18enVvv7b+5eEHWXYiWrV+3AgMCADs=
}

image create photo rediffImage\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQCrPQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAicAAMIHEiwoMF0
7AD0euVKl8OHrhjqAgDvnDsAGDOmG2jR3TmDIAVaxFiRoMJXKF/1ypgR5UqPIWOCTIfQnc2b
ABpS/Bgg3cmUQIOqBHBxIUpYADYKLEqUp8ynUKMatFgy5LmrWEdOrDoQIcuvrnSWPJfQqFCg
YhPCAtqrrduUL8/9fIWUJs2LQ2EGmFt34MWmBNPdvKlUquEAAQEAOw==
}

image create photo markSetImage\
    -format gif\
    -data {
R0lGODlhFAAUAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1Pjisd/UjtHJ
a8O4SL2qJcWqAK+SAJN6AGJiAEpKADIyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAAAiZAAMIHEhQoLqD
CAsqFAigIQB3Dd0tNKjOXSxXrmABWBABgLqCByECuAir5EYJHimKvOgqFqxXrzZ2lBhgJUaY
LV/GOpkSIqybOF3ClPlQIEShMF/lfLVzAcqPRhsKXRqTY1GCFaUy1ckTKkiRGhtapTkxa82u
ExUSJZs2qtOUbQ2ujTsQ4luvbdXNpRtA712+UeEC7ou3YEAAADt=
}

image create photo markClearImage\
    -format gif\
    -data {
R0lGODlhFAAUAPcAAAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1Pjisd/UjtHJ
a8O4SL2qJcWqAK+SAJN6AGJiAEpKADIyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAAAiwAAMIHEhQoLqD
CAsCWKhwIbyFANwNXBiD4UF3sVw9rLhQXQCKNTguzLgxZMePMWqo5OgqVkmVNwAIXHhDpUl3
7gCkhMkwJ02bHHfWiCkzQM5YP1cKJepRoM+kNoculEhQXc6cNW3GzNm0oFWdUSviLDgRbFST
RRsuzYpWrVaoHMsujYgVKMOPUYkCWPCQbY2iP/UuiACgr9S0NDvulQBAXd+7ZYv6bPowLdmB
By8LDAgAOw==
}

image create photo mergeChoice1Image\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAiIAAMIHEiwYMFz
7gAQ+meoIaGHECEeAuDuoDt35wxqFIgQAMWMGzkmVHRooseTKD1WPAgy5MCOhAZRvEizJsaR
hxrq3LkzEcWXIz+eG0qUqMujSJMixJg0AEyhRYuKVDjIUMqrMxUy5MnVkM+bAEgaOpSorNmz
X6eSnGmzZkunCT825fh2btKAADt=
}

image create photo mergeChoice2Image\
    -format gif\
    -data {
R0lGODdhFAAUAPf/AAAAAIAAAACAAICAAAAAgIAAgACAgMDAwMDcwKbK8P/w1P/isf/Ujv/G
a/+4SP+qJf+qANySALl6AJZiAHNKAFAyAP/j1P/Hsf+rjv+Pa/9zSP9XJf9VANxJALk9AJYx
AHMlAFAZAP/U1P+xsf+Ojv9ra/9ISP8lJf4AANwAALkAAJYAAHMAAFAAAP/U4/+xx/+Oq/9r
j/9Ic/8lV/8AVdwASbkAPZYAMXMAJVAAGf/U8P+x4v+O1P9rxv9IuP8lqv8AqtwAkrkAepYA
YnMASlAAMv/U//+x//+O//9r//9I//8l//4A/twA3LkAuZYAlnMAc1AAUPDU/+Kx/9SO/8Zr
/7hI/6ol/6oA/5IA3HoAuWIAlkoAczIAUOPU/8ex/6uO/49r/3NI/1cl/1UA/0kA3D0AuTEA
liUAcxkAUNTU/7Gx/46O/2tr/0hI/yUl/wAA/gAA3AAAuQAAlgAAcwAAUNTj/7HH/46r/2uP
/0hz/yVX/wBV/wBJ3AA9uQAxlgAlcwAZUNTw/7Hi/47U/2vG/0i4/yWq/wCq/wCS3AB6uQBi
lgBKcwAyUNT//7H//47//2v//0j//yX//wD+/gDc3AC5uQCWlgBzcwBQUNT/8LH/4o7/1Gv/
xkj/uCX/qgD/qgDckgC5egCWYgBzSgBQMtT/47H/x47/q2v/j0j/cyX/VwD/VQDcSQC5PQCW
MQBzJQBQGdT/1LH/sY7/jmv/a0j/SCX/JQD+AADcAAC5AACWAABzAABQAOP/1Mf/sav/jo//
a3P/SFf/JVX/AEncAD25ADGWACVzABlQAPD/1OL/sdT/jsb/a7j/SKr/Jar/AJLcAHq5AGKW
AEpzADJQAP//1P//sf//jv//a///SP//Jf7+ANzcALm5AJaWAHNzAFBQAPLy8ubm5tra2s7O
zsLCwra2tqqqqp6enpKSkoaGhnp6em5ubmJiYlZWVkpKSj4+PjIyMiYmJhoaGg4ODv/78KCg
pICAgP8AAAD/AP//AAAA//8A/wD//////yH5BAEAAAEALAAAAAAUABQAQAiNAAMIHEiwYEF3
AP79GzSIkMOHhAwZKkQIgLtzBguec3cxo8eNACxiHIgwpMmTIQ8dUiTSo8aRBDdynEkTIcWW
ARBGlMizJ8+VFgOcG0q0KEKWHV0qXcp0qUyYA4tKBVkxaU6UWAFMrIoR4SCfYCXe5AjgUKKz
aNMeMgT0osyaNMsihfqxpNWmQ5s2DQgAOw==
}

image create photo mergeChoice12Image\
    -format gif\
    -data {
R0lGODlhFAAUAPMHAAAAAAB6uQCS3CWq/0i4/47U/7Hi/////729vQAAAAAAAAAAAAAAAAAAAAAA
AAAAACH5BAEAAAgALAAAAAAUABQAAAT+ECGEECgAIYQQggghhBBCCIFiAEQIIYQQQgghhCACxRAA
AAAAAAABAAghUA4hpBRYSimllAEQAuVAQgghhBBCCCECAoRAGIQQQgghkBBCiAAIIRAGgUMIIYQQ
QggBEEQIgTAGAAAAACAAAACEEEIgDAARQgghhBBCCCGIEAIBIIQQQghBhBBCCCGEEEIIIgQKQAgh
hBBCECGEEEIImAIQggghAAAAAAAAAATEFIAQQmCUUmAppZRCCDkFIAQREIQQQgghhBBIyCkAISAI
IYRAQgghhJARAEIACiGEEEIIIQYZMACEEAAAAAAAgACAMQJACCGEEEQIIYQQAiMAhCAPQgghhBBC
CCEEQQAIIYQiADs=
}

image create photo mergeChoice21Image\
    -format gif\
    -data {
R0lGODlhFAAUAPMHAAAAAAB6uQCS3CWq/0i4/47U/7Hi/////729vQAAAAAAAAAAAAAAAAAAAAAA
AAAAACH5BAEAAAgALAAAAAAUABQAAAT+ECGEEEIIIYRAgQAhhBBCCCGEEEQIIWAKQAghBCAAAAAA
AACAmAIBQgiBUUoppRRYCiHkFIAQAoJAQgghhBBCCDkFAoSAIIQQQgghkBBCRgAIASGEgEIIIYQY
ZASAEEQAAAAAAAAAMOAIACGEEEIIIQQRQgiMABBCCCGIEEIIIYQQCABBhBBCCCEECkAIIoQQQggh
hBBCEBQDEEIIIYQQggghhEAxBAAAAAQAAAAAQgiUQyAhpZRSSillAAQRKIcQQgghhBBICBEAIRAG
IYRAQgghhBAiAEIIgjDIEEIIIYQQUAiAEEIgjAEAgAAAAAAAACGEEARhAIQQQgghhCAPQgghhEAA
CCEEEUIIIYQiADs=
}

image create photo nullImage

# run the main proc
main