File: dirdiff

package info (click to toggle)
dirdiff 2.0-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 160 kB
  • ctags: 19
  • sloc: tcl: 2,873; ansic: 305; makefile: 56
file content (3109 lines) | stat: -rwxr-xr-x 86,650 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
#!/bin/sh
# Tcl ignores the next line \
exec wish "$0" -- "${1+$@}"

# Copyright (C) 1999-2004 Paul Mackerras.  All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or (at your option) any later version.

set Script [info script]
set ScriptTail [file tail $Script]
if {[file type $Script] == "link"} {
  set ScriptBin [file join [file dirname $Script] [file readlink $Script]]
} else { 
  set ScriptBin $Script
}
set TclExe [info nameofexecutable]
set compound_ok [expr {$tcl_version >= 8.4}]

set nofilecmp [catch {load libfilecmp.so.0.0}]
set rcsflag {}
set diffbflag {}
set diffBflag {}
set diffiflag {}
set diffwflag {}
set diffdflag {}
set ctxlines 3
set showsame 0
set underlinetabs 0
set bitkeeper 0
set bkgetmode " "
set redisp_immed 1
set diffnewfirst 0
set nukefiles {*.o *~ *.orig CVS *.a *.link *.old *.save .depend .*.flags SCCS}
set filelistfont {Helvetica -12}
set textfont {Courier -12}
set maxdepth 9999999
set nxdirmode 0
set docvsignore 0

set defaultcvsignore {
    RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS
    .make.state .nse_depinfo *~ \#* .\#* ,* _$* *$
    *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb
    *.o *.obj *.so *.exe *.Z *.elc *.ln core
}

if {$tcl_platform(platform) == "windows"} {
   set TclExe [file attributes $TclExe -shortname]
   # I don't like it any better than you do
   set nullfile "C:/temp/nulfile"
   set nf [open "$nullfile" w]
   close $nf
} else {
   set nullfile "/dev/null"
}
set diffprogram {}
set showprogram {}

set numlines 20
set canvy0 0
set canvy 0
set canvx 0

set have_unidiff 1
set caught [catch "exec diff -u $nullfile $nullfile" err]
if {$caught != 0} {
   puts "Unified diff not available.  Will use context diff for patches."
   set have_unidiff 0
}

catch {source ~/.dirdiff}

proc ignorefile pat {
    global nukefiles
    if {$pat == "!"} {
	set nukefiles {}
    } else {
	lappend nukefiles $pat
    }
}

set linespc [font metrics $filelistfont -linespace]
if {$linespc < 15} {set linespc 15}
set blotw [expr $linespc-3]
set bloth [expr $linespc-3]
set blotspc $linespc

proc usage {} {
    puts stderr {Usage: dirdiff [options]... dir1 dir2 ...

Options:
   -a, --all		don't exclude any files
   -o, --only pattern	only process files matching pattern
   -I, --ignore pattern	don't process files matching pattern
   -r, --rcs		ignore differences in RCS strings
   -t, --bktag		ignore differences in Bitkeeper strings
   -c, --context num	set number of lines of context to show
   -b, -w, -B, -i, -d	pass these on to diff(1)
   -S			show files that are the same in the file list
   -K			Bitkeeper support
   -C			Ignore files listed in .cvsignore files

Note: dirdiff needs to be able to load the libfilecmp.so.0.0 shared library
for the -r or -t flags to work.}
}

proc NewDirDialog {} {
   global d0 d1 d2 d3 d4
   toplevel .newdirDlg
   wm transient .newdirDlg
   wm title .newdirDlg "Directories"
   set waitvar 0

   frame .newdirDlg.top -borderwidth 2 -relief groove
   pack .newdirDlg.top -side top -fill x \
      -ipadx 20 -ipady 20 -padx 5 -pady 5

   button .newdirDlg.top.b0 -text "Browse..." -command { set d0 [tk_chooseDirectory] }
   button .newdirDlg.top.b1 -text "Browse..." -command { set d1 [tk_chooseDirectory] }
   button .newdirDlg.top.b2 -text "Browse..." -command { set d2 [tk_chooseDirectory] }
   button .newdirDlg.top.b3 -text "Browse..." -command { set d3 [tk_chooseDirectory] }
   button .newdirDlg.top.b4 -text "Browse..." -command { set d4 [tk_chooseDirectory] }
   for { set n 0 } { $n < 5 } { incr n } {
      set dn [expr {$n + 1}]
      label .newdirDlg.top.l$n -text "Directory $dn"
      entry .newdirDlg.top.e$n -width 25 -textvariable d$n
      grid .newdirDlg.top.l$n -row $n -column 0 -sticky e
      grid .newdirDlg.top.e$n -row $n -column 1 -sticky sew -pady 4
      grid .newdirDlg.top.b$n -row $n -column 2 -sticky w
   }
   grid columnconfigure .newdirDlg.top 0 -weight 0
   grid columnconfigure .newdirDlg.top 1 -weight 1
   grid columnconfigure .newdirDlg.top 2 -weight 0

   frame .newdirDlg.bot
   button .newdirDlg.bot.ok -text "OK" -width 5 -default active \
      -command {
         set dirs [list $d0 $d1 $d2 $d3 $d4]
         destroy .newdirDlg
         set waitvar 1
      }
   button .newdirDlg.bot.cancel -text "Cancel" -width 5 -default normal \
      -command {
         set dirs {}
         destroy .newdirDlg
         exit 0
      }

   pack .newdirDlg.bot -side bottom -fill x -expand n
   pack .newdirDlg.bot.ok .newdirDlg.bot.cancel \
      -side left -fill none -expand y -pady 4

   tkwait variable waitvar
}

proc addfiles {sd} {
    global dirs stat onlyfiles statinfo fserial nextserial
    global filetype filesize filetime nxdirmode
    global docvsignore cvsignores defaultcvsignore
    if {$nxdirmode == 0} {
	set dcount 0
	foreach d $dirs {
	    if {[catch {file stat $d/$sd stat}] == 0} {
		if {$stat(type) == "directory"} {incr dcount}
	    }
	}
	if {$dcount <= 1} {
	    return {}
	}
    }
    if {$docvsignore} {
	# read the .cvsignore in each directory
	set cvsignores($sd) {}
	foreach d $dirs {
	    catch {
		set ign $defaultcvsignore
		set f [open $d/$sd.cvsignore r]
		while {[gets $f line] >= 0} {
		    foreach i [split $line] {
			if {$i == "!"} {
			    set ign {}
			} else {
			    lappend ign $i
			}
		    }
		}
		close $f
		set cvsignores($sd) [concat $cvsignores($sd) $ign]
	    }
	}
	set cvsignores($sd) [lsort -unique $cvsignores($sd)]
    }
    foreach d $dirs {
	foreach f [lsort [glob -nocomplain $d/$sd* $d/$sd.*]] {
	    set fs $sd[file tail $f]
	    set wantim 0
	    if [notnuked $fs] {
		if {[catch {file lstat $f stat}] == 0} {
		    if {$stat(type) == "file"} {
			if [info exists onlyfiles] {
			    foreach o $onlyfiles {
				if [string match $o $fs] {
				    set wantim 1
				    break
				}
			    }
			} else {
			    set wantim [notcvsignored $fs]
			}
		    } elseif {$stat(type) == "directory"} {
			append fs /
			set wantim 1
		    }
		}
	    }
	    if {$wantim} {
		if {![info exists files($fs)]} {
		    set fserial($fs) [incr nextserial]
		    set files($fs) 1
		}
		set filetype($f) $stat(type)
		set filesize($f) $stat(size)
		set filetime($f) $stat(mtime)
	    }
	}
    }
    return [lsort [array names files]]
}

# Called to re-lstat a given file across all directories
proc updatefileinfo {f} {
    global dirs filetype filesize filetime

    foreach d $dirs {
	set df [joinname $d [string trimright $f /]]
	if {[catch {file lstat $df stat}] == 0} {
	    set filetype($df) $stat(type)
	    set filesize($df) $stat(size)
	    set filetime($df) $stat(mtime)
	} else {
	    catch {unset filetype($df)}
	}
    }
}

# Returns 1 if we are interested in this file, i.e. if it isn't
# matched by something in the exclude list
proc notnuked {f} {
    global nukefiles
    set ft [file tail $f]
    if {$ft == "." || $ft == ".."} {
	return 0
    }
    foreach n $nukefiles {
	if {[string match $n $f] || [string match $n $ft]} {
	    return 0
	}
    }
    return 1
}

proc notcvsignored {f} {
    global docvsignore cvsignores
    set sd [file dirname $f]/
    if {$sd == "./"} {
	set sd ""
    }
    set ft [file tail $f]
    if {$docvsignore && [info exists cvsignores($sd)]} {
	foreach n $cvsignores($sd) {
	    if {[string match $n $ft]} {
		return 0
	    }
	}
    }
    return 1
}

proc joinname {dir f} {
    global filemode
    if {$filemode} {
	return $dir
    }
    return [file join $dir $f]
}

proc fileisa {f t} {
    global filetype
    return [expr {[info exists filetype($f)] && $filetype($f) == $t}]
}

proc diffages {f showsame maxdepth} {
    global dirs nofilecmp rcsflag filesize filetime nxdirmode
    set numgroups 0
    set notexist {}
    set doesexist {}
    foreach d $dirs {
	set sameas($d) {}
	set group($d) 0
	set fname [joinname $d [string trimright $f /]]
	if {!([fileisa $fname "file"]
	      || ($maxdepth <= 0 && [fileisa $fname "directory"]))} {
	    set fd [file dirname $fname]
	    if {$nxdirmode || [file dirname $f] == "." \
		    || [fileisa $fd "directory"]} {
		lappend notexist $d
	    }
	} else {
	    lappend doesexist $d
	    set fsize($d) $filesize($fname)
	    set fmtime($d) $filetime($fname)
	    foreach d2 $dirs {
		if {$d2 == $d} break
		if {$sameas($d2) != "" || $group($d2) == 0} continue
		if {$fsize($d) == $fsize($d2) \
			&& $fmtime($d) == $fmtime($d2)} {
		    set notsame 0
		} elseif {$rcsflag != "" || $fsize($d) == $fsize($d2)} {
		    set fname2 [joinname $d2 [string trimright $f /]]
		    if $nofilecmp {
			set notsame [catch {exec cmp -s $fname $fname2}]
		    } else {
			set same 0
			catch {
			    set same [eval filecmp $rcsflag $fname $fname2]
			}
			set notsame [expr !$same]
		    }
		} else {
		    set notsame 1
		}
		if {$notsame == 0} {
		    set sameas($d) $d2
		    set g $group($d2)
		    set group($d) $g
		    lappend groupelts($g) $d
		    if {$fmtime($d) > $gmtime($g)} {
			set gmtime($g) $fmtime($d)
		    }
		    break
		}
	    }
	    if {$sameas($d) == ""} {
		incr numgroups
		set group($d) $numgroups
		set groupelts($numgroups) $d
		set gmtime($numgroups) $fmtime($d)
	    }
	}
    }
    if {!$showsame && $numgroups == 1 && $notexist == ""} {
	return {}
    }
    set glist {}
    for {set g 1} {$g <= $numgroups} {incr g} {
	lappend glist [list [format "%.8x" $gmtime($g)] $g]
    }
    set grank(0) 0
    set rank 1
    foreach xx [lsort -decreasing $glist] {
	set g [lindex $xx 1]
	set grank($g) $rank
	incr rank
    }
    set res {}
    foreach d $dirs {
	lappend res $grank($group($d))
    }
    return [list $numgroups $res]
}

proc subdirgroups {sd} {
    global dirs
    set nummiss 0
    set groups {}
    foreach d $dirs {
	set fn [joinname $d $sd]
	if {![fileisa $fn "directory"]} {
	    set pd [file dirname $sd]
	    lappend groups 0
	    set fnp [joinname $d $pd]
	    if {$pd == "." || [fileisa $fnp "directory"]} {
		incr nummiss
	    }
	} else {
	    lappend groups 1
	}
    }
    if {$nummiss == 0} {
	return {}
    }
    return [list dir $groups]
}

set stringx 8

proc initcanv {} {
    global canvw canvx canvy canvy0 linespc stringx ruletype
    global dirs arroww blotspc blotw ycoord filelistfont
    $canvw delete all
    $canvw yview moveto 0
    $canvw conf -scrollregion {0 0 0 1}
    catch {unset ycoord}
    catch {unset ruletype}
    set canvy $canvy0
    if {![info exists arroww]} {
	set stringx [expr $blotspc + 8]
	return
    }
    set numdirs [llength $dirs]
    set stringx [expr $numdirs * $blotspc + 8]
    $arroww delete all
    set arrowh [expr ($numdirs+1) * $linespc]
    $arroww conf -height $arrowh
    set y 0
    set yoff [expr $linespc / 2]
    set x [expr $canvx + 3 + ($blotw / 2)]
    set x2 [expr $stringx - 3]
    set horiz [expr $arrowh + 2]
    foreach d $dirs {
	set y2 [expr $y + $yoff]
	set t [$arroww create line $x $horiz $x $y2 $x2 $y2 \
		-width 2 -arrow first]
	$arroww addtag arrows withtag $t
	set t [$arroww create text $stringx $y -text $d -anchor nw \
		   -font $filelistfont]
	$arroww addtag strings withtag $t
	incr y $linespc
	incr x $blotspc
    }
    
    set dx [expr [$arroww cget -width] / 2]
    set dy [expr $horiz - 1]
    $arroww create text $dx $dy -text "Older <- " -anchor se
    $arroww create image $dx $dy -image paper_red -anchor sw
    incr dx $blotspc
    $arroww create image $dx $dy -image paper_orange -anchor sw
    incr dx $blotspc
    $arroww create image $dx $dy -image paper_yellow -anchor sw
    incr dx $blotspc
    $arroww create image $dx $dy -image paper_yellowgreen -anchor sw
    incr dx $blotspc
    $arroww create image $dx $dy -image paper_green -anchor sw
    incr dx $blotspc
    $arroww create text $dx $dy -text " -> Newer" -anchor sw
}

proc addcline {blots str} {
    global canvy canvx linespc stringx blotw bloth blotspc canvw ycoord
    global filelistfont
    set x [expr $canvx+1]
    set y [expr $canvy+1]
    foreach b $blots {
	set t [$canvw create image $x $y -image $b -anchor nw]
	$canvw addtag blots withtag $t
	incr x $blotspc
    }
    set t [$canvw create text $stringx $canvy -anchor nw -text $str \
	      -font $filelistfont]
    $canvw addtag strings withtag $t
    set ycoord($str) $canvy
    incr canvy $linespc
    set vis [lindex [$canvw yview] 1]
    $canvw conf -scrollregion "0 0 0 $canvy"
    if {$vis >= 1.0} {
	$canvw yview moveto 1
    }
}

proc displine {groups name} {
    global agecolors
    set ng [lindex $groups 0]
    set cols $agecolors($ng)
    set blots {}
    foreach g [lindex $groups 1] {
	lappend blots [lindex $cols $g]
    }
    addcline $blots $name
}

proc dispfilelines {groups} {
    global agecolors dirs
    set ng [lindex $groups 0]
    set cols $agecolors($ng)
    set n 0
    foreach g [lindex $groups 1] {
	addcline [lindex $cols $g] [lindex $dirs $n]
	incr n
    }
}

proc ruleoff {stopped} {
    global canvw canvy linespc ruletype
    set y [expr $canvy + $linespc/2]
    set color black
    if {$stopped} {set color red}
    $canvw create line 0 $y [$canvw cget -width] $y -width 2 -fill $color
    incr canvy $linespc
    set vis [lindex [$canvw yview] 1]
    $canvw conf -scrollregion "0 0 0 $canvy"
    if {$vis >= 1.0} {
	$canvw yview moveto 1
    }
    set ruletype $stopped
}

proc updatecline {si di f} {
    global ycoord canvw blotspc bloth blotw groups
    global filemode dirs changed
    if {$filemode} {
	set fs [lindex $dirs $si]
	set fd [lindex $dirs $di]
	if {![info exists ycoord($fs)] || ![info exists ycoord($fd)]} return
	set ys [expr $ycoord($fs) + 2]
	set yd [expr $ycoord($fd) + 2]
	set xs 2
	set xd 2
    } else {
	if {![info exists ycoord($f)]} return
	set ys [expr $ycoord($f) + 2]
	set yd $ys
	set xs [expr $si * $blotspc + 2]
	set xd [expr $di * $blotspc + 2]
    }
    set ts [$canvw find overlapping $xs $ys \
	    [expr $xs+$blotw-2] [expr $ys+$bloth-2]]
    set td [$canvw find overlapping $xd $yd \
	    [expr $xd+$blotw-2] [expr $yd+$bloth-2]]
    if {$ts != "" && $td != ""} {
	$canvw itemconf $td -image [$canvw itemcget $ts -image]
        set changed 1
    }
    set ng [lindex $groups($f) 0]
    set g [lindex $groups($f) 1]
    set groups($f) [list $ng [lreplace $g $di $di [lindex $g $si]]]
}

proc refreshcline {f} {
    global ycoord canvw blotspc bloth blotw groups
    global agecolors changed
    if {![info exists ycoord($f)]} return
    set y [expr $ycoord($f) + 2]
    set ng [lindex $groups($f) 0]
    set cols $agecolors($ng)
    set x 2
    foreach g [lindex $groups($f) 1] {
	set t [$canvw find overlapping $x $y \
		[expr $x+$blotw-2] [expr $y+$bloth-2]]
	if {$t != ""} {
	    $canvw itemconf $t -image [lindex $cols $g]
            set changed 1
	}
	incr x $blotspc
    }
}

proc makepatchmenu {base} {
    global dirs
    menu $base.p -tearoff 0
    set sub1 0
    foreach d1 $dirs {
	set any 0
	incr sub1
	menu $base.p.$sub1 -tearoff 0
	foreach d2 $dirs {
	    if {$d1 == $d2} continue
	    set any 1
	    $base.p.$sub1 add command -label "$d2" \
		    -command "makepatch \"$d1\" \"$d2\""
	}
	if {$any} {
	    $base.p add cascade -label "$d1 ->" -menu $base.p.$sub1
	}
	incr sub1
    }
    $base add cascade -label "Make patch" -menu $base.p
}

proc maketouchmenu {base} {
    global dirs dirreadonly
    menu $base.t -tearoff 0
    set i 0
    foreach d $dirs {
	if {!$dirreadonly($i)} {
	    $base.t add command -label $d -command "touchfiles \"$d\""
	}
	incr i
    }
    $base add cascade -label "Touch" -menu $base.t
}

proc makebkgetmenu {base} {
    global dirs bitkeeper
    menu $base.g -tearoff 0
    foreach d $dirs {
	$base.g add command -label $d -command "bkgetfiles \"$d\""
    }
    $base add cascade -label "BK get" -menu $base.g \
	    -state [expr {$bitkeeper? "normal": "disabled"}]
}

proc readonlychange {i} {
    global dirreadonly
    .bar.file.t entryconf $i \
	-state [expr {$dirreadonly($i)? "disabled": "normal"}]
    selcurfile
}

proc makewins {} {
    global canvw numlines linespc arroww diffbut copybut filelabel nofilecmp
    global filemode dirs dirinterest filelistfont dirreadonly
    global rcsflag diffiflag diffwflag diffbflag diffBflag diffdflag
    global bitkeeper bgcolors

    set i 0
    foreach d $dirs {
	set dirreadonly($i) 0
	incr i
    }

    # Native-style menubar
    menu .bar
    .bar add cascade -label "File" -menu .bar.file

    # File menu
    menu .bar.file
    .bar.file add command -label "Rediff" -command rediff
    if {!$filemode} {
	.bar.file add command -label "Redisplay" -command "redisplay 1"
    }
    set menubg [lindex [.bar.file configure -background] 4]
    set bgcolors(1) [list $menubg $menubg]
    set bgcolors(2) [list $menubg green "#ff8080"]
    set bgcolors(3) [list $menubg green yellow "#ff8080"]
    set bgcolors(4) [list $menubg green yellow orange "#ff8080"]
    set bgcolors(5) [list $menubg green "#e0ff90" yellow orange "#ff8080"]

    makepatchmenu .bar.file
    maketouchmenu .bar.file
    makebkgetmenu .bar.file
    .bar.file add command -label "Exclude selection" -command exclsel
    .bar.file add command -label "Stop" -command "set stopped 1"
    .bar.file add separator
    .bar.file add command -label "Quit" -command "set stopped 1; destroy ."

    # Diff menu
    set diffbut .bar.diff
    menu $diffbut
    .bar add cascade -label "Diff" -menu $diffbut
    $diffbut add command -label "All" -command difffiles

    # Copy menu
    set copybut .bar.copy
    menu $copybut
    .bar add cascade -label "Copy/Del" -menu $copybut

    # Options menu
    menu .bar.options
    .bar add cascade -label "Options" -menu .bar.options

    .bar.options add radiobutton -label "Literal comparison" \
	    -variable rcsflag -value " " \
	    -state [expr {$nofilecmp? "disabled": "normal"}]
    .bar.options add radiobutton -label "Ignore differences in RCS strings" \
	    -variable rcsflag -value "-rcs" \
	    -state [expr {$nofilecmp? "disabled": "normal"}]
    .bar.options add radiobutton -label "Ignore differences in BK tags" \
	    -variable rcsflag -value "-bk" \
	    -state [expr {$nofilecmp? "disabled": "normal"}]
    .bar.options add checkbutton -label "Show files that are identical" \
	    -variable showsame
    .bar.options add checkbutton -label "Bitkeeper support" \
	    -variable bitkeeper \
	    -command bkchange

    menu .bar.options.bkmode -tearoff 0
    .bar.options.bkmode add radiobutton -label "Expand keywords" \
	    -variable bkgetmode -value " "
    .bar.options.bkmode add radiobutton -label "Don't expand keywords" \
	    -variable bkgetmode -value "k"
    .bar.options.bkmode add radiobutton -label "Check out for editing" \
	    -variable bkgetmode -value "e"

    .bar.options add cascade -label "BK get mode" \
	    -menu .bar.options.bkmode \
	    -state [expr {$bitkeeper? "normal": "disabled"}]
    .bar.options add checkbutton -label "Redisplay immediately" \
	    -variable redisp_immed
    .bar.options add checkbutton -label "Show files that aren't in some dirs" \
	    -variable nxdirmode
    .bar.options add checkbutton -label "Ignore files in .cvsignore" \
	    -variable docvsignore
    .bar.options add command -label "Excluded files..." -command exclfilelist
    .bar.options add command -label "Diff options..." -command diffoptions
    .bar.options add command -label "External viewers..." -command extprograms
    .bar.options add command -label "Save options" -command saveoptions

    .bar.options add separator
    set i 0
    foreach d $dirs {
	set dirinterest($i) 1
	.bar.options add checkbutton -label "Show $d" \
		-variable dirinterest($i) -command redisplay
	incr i
    }

    .bar.options add separator
    set i 0
    foreach d $dirs {
	.bar.options add checkbutton -label "Read-only $d" \
		-variable dirreadonly($i) -command "readonlychange $i"
	incr i
    }

    # Help menu
    menu .bar.help
    .bar add cascade -label "Help" -menu .bar.help
    .bar.help add command -label "About dirdiff" -command about
    .bar.help add command -label "About diff" -command about_diff
    .bar.help add command -label "Show help text" -command helptext

    . configure -menu .bar

    # make the filename display bar
    if {!$filemode} {
	frame .file -relief sunk -bd 1
	set filelabel .file.name
	#label $filelabel -relief flat -padx 7 -text "File: "
	label $filelabel -relief flat -padx 7 -image paper
        set fileentry .file.ent
        entry $fileentry -relief sunk -bd 1 -textvariable selfile \
               -font $filelistfont
	pack $filelabel -side left
	pack $fileentry -side left -fill x -expand yes
	pack .file -side top -fill x
    }

    # make the frame containing the 2 canvases (one for the top section
    # containing the directory names, one for the files) and the scrollbar
    # in file mode the top section is omitted
    frame .cf
    if {$filemode} {
	set numlines [llength $dirs]
    }
    canvas .cf.c -height [expr $numlines * $linespc] \
	    -yscrollincr $linespc -yscrollcommand ".csb set" \
            -bg white -relief sunk -bd 1
    set canvw .cf.c
    if {!$filemode} {
	canvas .cf.d -height [expr 3 * $linespc] \
               -relief flat -bd 1 -highlightthickness 0
	set arroww .cf.d
	pack .cf.d -side top -fill x
    }
    pack .cf.c -side bottom -fill both -expand 1
    scrollbar .csb -command "$canvw yview" -highlightthickness 0
    pack .csb -side right -fill y
    pack .cf -side left -fill both -expand 1

    if {!$filemode} {
	bind $fileentry <Return> "search_canvas"
    }
    # set up event bindings on the main canvas
    bind $canvw <1> {selcanvline %x %y 0}
    bind $canvw <Shift-1> {selcanvline %x %y 1}
    bind $canvw <B1-Motion> {selcanvline %x %y 2}
    bind $canvw <Control-1> {selcanvline %x %y 3}
    # This caused selcurfile to always be done twice
    #bind $canvw <ButtonRelease-1> {selcurfile}
    bind $canvw <ButtonRelease-4> "$canvw yview scroll -5 u"
    bind $canvw <ButtonRelease-5> "$canvw yview scroll 5 u"
    bind $canvw <2> "$canvw scan mark 0 %y"
    bind $canvw <B2-Motion> "$canvw scan dragto 0 %y"
    bind $canvw <Double-Button-1> "set doubleclick 1; showsomediff 0"
    bind $canvw <Key-Return> "showsomediff 0"
    $canvw conf -scrollregion {0 0 0 1}
    if {!$filemode} {
	bind . N "diffnextfile 1"
	bind . P "diffnextfile -1"
    }
    bind . C copydifffile
    bind . <Key-Return> "showsomediff 0"
    bind . <Key-Prior> "$canvw yview scroll -1 p"
    bind . <Key-Next> "$canvw yview scroll 1 p"
    bind . <Key-Delete> "$canvw yview scroll -1 p"
    bind . <Key-BackSpace> "$canvw yview scroll -1 p"
    bind . <Key-space> "$canvw yview scroll 1 p"
    bind . <Key-Up> "$canvw yview scroll -1 u"
    bind . <Key-Down> "$canvw yview scroll 1 u"
    bind . Q "set stopped 1; destroy ."
    # Need a way to unselect all
    bind . <Escape> resetsel

}

proc bkchange {} {
    global bitkeeper
    set state [expr {$bitkeeper? "normal": "disabled"}]
    .bar.options entryconf "BK*" -state $state
    .bar.file entryconf "BK*" -state $state
}

proc about {} {
    set w .about
    if {[winfo exists $w]} {
	raise $w
	return
    }
    toplevel $w
    wm title $w "About dirdiff"
    message $w.m -text {
Dirdiff version 2.0

Copyright  1999-2004 Paul Mackerras

Use and redistribute under the terms of the GNU General Public License

(CVS $Revision: 1.52 $)} \
	    -justify center -aspect 400
    pack $w.m -side top -fill x -padx 20 -pady 20
    button $w.ok -text Close -command "destroy $w"
    pack $w.ok -side bottom
}

proc about_diff {} {
    set w .about_diff
    if {[winfo exists $w]} {
	raise $w
	return
    }
    toplevel $w
    wm title $w "About diff"
    set retval [catch "exec diff -v" err]
    message $w.m -text $err -justify center -aspect 600
    pack $w.m -side top -fill x -padx 20 -pady 20
    if {$retval == 0} {
       text $w.t -bg white -yscrollcommand "$w.sb set" -wrap word
       scrollbar $w.sb -command "$w.t yview"
       pack $w.sb -side right -fill y
       pack $w.t -side left -fill both -expand 1
       set fdh [open "|diff --help" r]
       while { [eof $fdh] == 0 } {
          $w.t insert end "[gets $fdh]\n"
       }
       pack $w.t -side top -fill both -expand yes
    }
    button $w.ok -text Close -command "destroy $w"
    pack $w.ok -side bottom
}

proc helptext {} {
    set w .help
    if {[winfo exists $w]} {
	raise $w
	return
    }
    toplevel $w
    wm title $w "Dirdiff help"
    text $w.t -font {Times -14} -yscrollcommand "$w.sb set" -wrap word
    scrollbar $w.sb -command "$w.t yview"
    pack $w.sb -side right -fill y
    pack $w.t -side left -fill both -expand 1
    bind $w <Key-Prior> "$w.t yview scroll -1 p"
    bind $w <Key-BackSpace> "$w.t yview scroll -1 p"
    bind $w <Key-Delete> "$w.t yview scroll -1 p"
    bind $w b "$w.t yview scroll -1 p"
    bind $w B "$w.t yview scroll -1 p"
    bind $w <Key-Up> "$w.t yview scroll -1 u"
    bind $w <Key-Down> "$w.t yview scroll 1 u"
    bind $w d "$w.t yview scroll \[expr \"int(\[$w.t cget -height\]/2)\"\] u"
    bind $w D "$w.t yview scroll \[expr \"int(\[$w.t cget -height\]/2)\"\] u"
    bind $w u "$w.t yview scroll \[expr \"int(-\[$w.t cget -height\]/2)\"\] u"
    bind $w U "$w.t yview scroll \[expr \"int(-\[$w.t cget -height\]/2)\"\] u"
    bind $w q "destroy $w"
    bind $w Q "destroy $w"
    $w.t insert end {Dirdiff instructions.

Dirdiff compares all the files in up to five directories.  There is one \
column in the main window for each directory.

Each file is shown with a coloured square indicating its status.  Files \
are like leaves on a deciduous tree: the newest ones are green, and then \
they turn yellow, orange, and red as they get older.

Double-click a file to show differences between two versions.  By default, \
the first and last versions are compared, but this can be changed by the \
'Diff' menu in the main window.  

You can select several files to copy or to make a patch by shift-clicking.

You can search for a file by typing part of its name in the entry and \
pressing the <Return> key.

In the diff window, check the boxes on the left margin for changes you \
want to preserve, and then choose 'Merge' to move those changes into one \
of the files.  Alternatively, choose 'Copy' in the main window to copy \
across the whole file, replacing any changes.

'Make patch' produces a file describing the changes between the files that \
can be applied by the patch tool.  You can edit the patch before saving, \
and may wish to add explanatory text, instructions, or patch(1) Prereq \
lines at the beginning.  To save the patch, enter a filename in the patch \
window relative to the current directory, and choose 'Save'.  This will \
also close the window.

If you are sending out patches, then the "from" directory should be the \
original version of the source.  Try to make sure that the two files have \
the same number of leading directories.  See the patch(1) man page for \
more information.
    }

    $w.t conf -state disabled
}

proc filediffs {} {
    global groups selitem fserial
    updatefileinfo .
    set groups(.) [set gr [diffages . 1 1]]
    set fserial(.) 1
    dispfilelines $gr
    clearsecsel
    selcurfile
}

proc diffsin {sd maxdepth} {
    global groups stopped showsame alllines nxdirmode
    foreach f [addfiles $sd] {
	if {$stopped} return
	lappend alllines $f
	set d [string trimright $f /]
	if {$d == $f || $maxdepth <= 0} {
	    set groups($f) [set gr [diffages $f $showsame $maxdepth]]
	    if [interesting_line $gr] {
		displine $gr $f
	    }
	} else {
	    set groups($f) [set gr [subdirgroups $d]]
	    if {$nxdirmode == 0 && [interesting_line $gr]} {
		displine $gr $f
	    }
	    diffsin $f [expr $maxdepth-1]
	}
	catch update
    }
}

proc canvdiffs {} {
    global canvw groups stopped filemode alllines
    global filetype filetime filesize maxdepth
    set stopped 0
    set alllines {}
    catch {unset filetype}
    catch {unset filetime}
    catch {unset filesize}
    initcanv
    if {$filemode} {
	filediffs
    } else {
	diffsin {} $maxdepth
	if {[catch update]} return
	ruleoff $stopped
    }
    if {[catch update]} return
    if {[lindex [$canvw yview] 1] >= 1.0} {
	$canvw yview moveto 0
    }
}

proc textitemat {x y} {
    global canvw
    foreach i [$canvw find overlapping $x $y [expr $x+50] $y] {
	if {[$canvw type $i] == "text"} {
	    return $i
	}
    }
    return {}
}

proc itemofname {f} {
    global stringx ycoord linespc
    if {![info exists ycoord($f)]} {
	return {}
    }
    return [textitemat [expr {$stringx+5}] [expr {$ycoord($f) + $linespc/2}]]
}

proc addtobbox {bbox x y} {
    set x0 [lindex $bbox 0]
    set y0 [lindex $bbox 1]
    set x1 [lindex $bbox 2]
    set y1 [lindex $bbox 3]
    if {$x < $x0} {set x0 $x}
    if {$y < $y0} {set y0 $y}
    if {$x > $x1} {set x1 $x}
    if {$x > $y1} {set y1 $y}
    return [list $x0 $y0 $x1 $y1]
}

proc selcanvline {x y tipe} {
    global canvw stringx selitem secsel clickitem groups selfile clickmode
    global filemode doubleclick clicky
    if {$filemode} return
    set x [expr $stringx+5]
    set y [$canvw canvasy $y]
    set it [textitemat $x $y]
    if {$it == {}} return
    if {$tipe == 0} {
	# click, no shift
	clearsecsel
	selectitem $it
	set clickitem $it
	set clicky $y
	set clickmode 1
	selcurfile
	addsecsel $it
	set doubleclick 0
    } elseif {$tipe == 1} {
	# shift-click
	set clickitem $it
	set clicky $y
	if {$it != $selitem} {
	    if {![info exists secsel($it)]} {
		set clickmode 1
		addsecsel $it
	    } else {
		set clickmode 0
		remsecsel $it
	    }
	}
	set doubleclick 0
    } elseif {$tipe == 2 || $tipe == 3} {
	# motion with button 1 down
	if {$tipe == 2 && [info exists doubleclick] && $doubleclick} return
	if {![info exists clickitem]} return
	foreach i [$canvw find overlapping \
		       $x [expr {$y < $clicky? $y: $clicky}] \
		       [expr $x+50] [expr {$y > $clicky? $y: $clicky}]] {
	    if {[$canvw type $i] == "text"} {
		set f [$canvw itemcget $i -text]
		if {$groups($f) == $groups($selfile)} {
		    if {$clickmode && ![info exists secsel($i)]} {
			addsecsel $i
		    } elseif {!$clickmode && [info exists secsel($i)]} {
			remsecsel $i
		    }
		}
	    }
	}
    }
}

proc selectitem {it} {
    global selitem canvw
    set selitem $it
    $canvw select from $it 0
    $canvw select to $it end
}

proc addsecsel {it} {
    global canvw secsel
    set t [eval $canvw create rect [$canvw bbox $it] -outline {{}} \
	    -tags secsel -fill [$canvw cget -selectbackground]]
    $canvw lower $t
    set secsel($it) $t
}

proc remsecsel {it} {
    global canvw secsel
    $canvw delete $secsel($it)
    unset secsel($it)
}

proc clearsecsel {} {
    global canvw secsel
    $canvw delete secsel
    catch {unset secsel}
}

proc selnextline {inc} {
    global canvw selitem linespc stringx canvy filemode
    if {$filemode} {
	if {$inc != 0} {
	    return 0
	}
	selcurfile
	return 1
    }
    if {$selitem == ""} {
	return 0
    }
    set y [expr [lindex [$canvw bbox $selitem] 1] + $linespc * $inc + 5]
    set x [expr $stringx+5]
    set i [textitemat $x $y]
    if {$i == ""} {
	return 0
    }
    clearsecsel
    selectitem $i
    set bbox [$canvw bbox $i]
    set y [expr {([lindex $bbox 1] + [lindex $bbox 3]) / 2.0}]
    if {$canvy > 0} {
	set ytop [expr {($y - $linespc / 2.0) / $canvy}]
	set ybot [expr {($y + $linespc / 2.0) / $canvy}]
	set wnow [$canvw yview]
	if {$ytop < [lindex $wnow 0]} {
	    $canvw yview moveto $ytop
	} elseif {$ybot > [lindex $wnow 1]} {
	    set wh [expr {[lindex $wnow 1] - [lindex $wnow 0]}]
	    $canvw yview moveto [expr {$ybot - $wh}]
	}
    } else {
	$canvw yview moveto 0
    }
    selcurfile
    addsecsel $i
    return 1
}

proc calcgroupelts {f} {
    global groupelts numgroups groups
    set gr $groups($f)
    set numgroups [lindex $gr 0]
    if {$numgroups == "dir"} {
	set numgroups 1
    }
    set gr [lindex $gr 1]
    for {set g 0} {$g <= $numgroups} {incr g} {
	set groupelts($g) {}
    }
    set i 0
    foreach g $gr {
	lappend groupelts($g) $i
	incr i
    }
}

proc selcurfile {} {
    global canvw selitem filelabel selfile groups filemode
    global groupelts diffbut copybut numgroups
    if {!$filemode} {
	if {$selitem == ""} return
	set selfile [$canvw itemcget $selitem -text]
    } else {
	set selfile .
    }
    calcgroupelts $selfile
    set x [string trimright $selfile /]
    if {$x == $selfile} {
	if {[info exists filelabel]} {
	    $filelabel conf -image paper
	}
	confdiffbut 0
	confcopybutfile
    } else {
	if {[info exists filelabel]} {
	    $filelabel conf -image folder
	}
	confdiffbut 1
	confcopybutdir
    }
}

proc mkdiffimage {gn go} {
    global numgroups agecolors
    set cols $agecolors($numgroups)
    set i1 [lindex $cols $go]
    set i2 [lindex $cols $gn]
    set iname "icon-$i1-$i2"
    if {![info exists $iname]} {
	set w1 [image width $i1]
	set w2 [image width $i2]
	set h [image height $i1]
	image create photo $iname -width [expr {$w1+$w2}] -height $h
	$iname copy $i1
	$iname copy $i2 -to $w1 0
    }
    return $iname
}

proc confdiffbut {isdir} {
    global diffbut numgroups dirs selfile groupelts filemode
    global groups agecolors bgcolors compound_ok
    $diffbut delete 0 end
    destroy [winfo children $diffbut]
    set ng [lindex $groups($selfile) 0]

    if {$isdir} {
	# do nothing
    } elseif {$numgroups == 1} {
	set xi [lindex $groupelts(1) 0]
	if {$xi != ""} {
	    set x [lindex $dirs $xi]
	    $diffbut add command -label "Show $x" \
		    -command "showfile \"$x\" \"$selfile\""
	}
    } elseif {$numgroups > 1} {
	for {set gn 1} {$gn < $numgroups} {incr gn} {
	    set yi [lindex $groupelts($gn) 0]
	    if {$yi == ""} continue

            set age [lindex [lindex $groups($selfile) 1] $yi]
            set im [lindex $agecolors($ng) $age]
            set cl [lindex $bgcolors($ng) $age]
	    set y [lindex $dirs $yi]
            if {[winfo exists $diffbut.$gn]} {destroy $diffbut.$gn}
            menu $diffbut.$gn -tearoff 0
            set any 0
	    for {set go [expr $gn+1]} {$go <= $numgroups} {incr go} {
		set xi [lindex $groupelts($go) 0]
                set age [lindex [lindex $groups($selfile) 1] $xi]
                set im2 [lindex $agecolors($ng) $age]
                set cl2 [lindex $bgcolors($ng) $age]
		set xi [lindex $groupelts($go) 0]
		if {$xi == ""} continue
		set x [lindex $dirs $xi]
		set cmd "diff2 \"$x\" \"$y\" \"$selfile\""
		if {$numgroups <= 3} {
		    if {$compound_ok} {
			$diffbut add command -label "$x vs. $y" \
			    -command $cmd \
			    -image [mkdiffimage $gn $go] \
			    -compound left
		    } else {
			$diffbut add command -label "$x vs. $y" \
			    -command $cmd
		    }
		} else {
		    incr any
		    if {$compound_ok} {
			$diffbut.$gn add command -label "$x" \
			    -image $im2 -compound left \
			    -command $cmd
		    } else {
			$diffbut.$gn add command -label "$x" \
			    -background $cl2 \
			    -command $cmd
		    }
		}
	    }
	    if {$any} {
                if {$compound_ok} {
	            $diffbut add cascade -label "$y vs. ..." \
                       -image $im -compound left \
		       -menu $diffbut.$gn
	        } else {
	            $diffbut add cascade -label "$y vs. ..." \
                       -background $cl \
		       -menu $diffbut.$gn
                }
            }
        }
    }
    if {!$filemode} {
	$diffbut add separator
	$diffbut add command -label "Rediff selected file(s)" \
		-command "redifffiles"
    }
    .bar entryconfigure 2 -state normal
}

proc mkcopyimage {i1 i2} {
    if {$i1 == ""} {
	return $i2
    }
    if {$i2 == ""} {
	return $i1
    }
    set iname "icon-$i1-$i2"
    if {![info exists $iname]} {
	set w1 [image width $i1]
	set w2 [image width $i2]
	set h [image height $i1]
	image create photo $iname -width [expr {$w1+$w2}] -height $h
	$iname copy $i1
	$iname copy $i2 -to $w1 0
    }
    return $iname
}

proc confcopybutfile {} {
    global copybut groupelts numgroups selfile dirs
    global groups agecolors bgcolors compound_ok dirreadonly
    $copybut delete 0 end
    destroy [winfo children $copybut]
    set numdirs [llength $dirs]
    set srcs {}
    set rev {}
    set ng [lindex $groups($selfile) 0]

    for {set gn 1} {$gn <= $numgroups} {incr gn} {
	set srcs [concat $srcs $groupelts($gn)]
	set src [lindex $groupelts($gn) 0]
	if {$src == ""} continue
        set age [lindex [lindex $groups($selfile) 1] $src]
        set im [lindex $agecolors($ng) $age]
        set cl [lindex $bgcolors($ng) $age]

	set x [lindex $dirs $src]
        if {[winfo exists $copybut.new2old$src]} {destroy $copybut.new2old$src}
	menu $copybut.new2old$src -tearoff 0
        set dsts {}
	for {set dst 0} {$dst < $numdirs} {incr dst} {
	    if {!$dirreadonly($dst) && [lsearch $srcs $dst] < 0} {
                lappend dsts $dst
	    }
	}
	set any [llength $dsts]
        if {$any} {
	    foreach dst $dsts {
                set age [lindex [lindex $groups($selfile) 1] $dst]
                set im2 [lindex $agecolors($ng) $age]
                set cl2 [lindex $bgcolors($ng) $age]
                if {$im2 == "ex"} {set im2 ""}
		set y [lindex $dirs $dst]
		set cmd "copyselfile \"$src\" \"$dst\" \"$selfile\" 0"
		if {$any == 1} {
		    if {$compound_ok} {
			$copybut add command -label "$x -> $y" \
			    -command $cmd -image [mkcopyimage $im $im2] \
			    -compound left
		    } else {
			$copybut add command -label "$x -> $y" \
			    -command $cmd
		    }
		} elseif {$compound_ok} {
		    $copybut.new2old$src add command -label "$y" \
                        -image $im2 -compound left \
			-command $cmd
                } else {
		    $copybut.new2old$src add command -label "$y" \
                        -background $cl2 \
			-command $cmd
                }
	    }
	    if {$any > 1} {
		if {$compound_ok} {
		    $copybut add cascade -label "$x ->" \
			-image $im -compound left \
			-menu $copybut.new2old$src
		} else {
		    $copybut add cascade -label "$x ->" \
			-background $cl \
			-menu $copybut.new2old$src
		}
	    }
        }
    }
    set needsep 1
    for {set gn $numgroups} {$gn >= 1} {incr gn -1} {
	set src [lindex $groupelts($gn) 0]
	if {$src == ""} continue

        set age [lindex [lindex $groups($selfile) 1] $src]
        set im [lindex $agecolors($ng) $age]
        set cl [lindex $bgcolors($ng) $age]
	set x [lindex $dirs $src]
        if {[winfo exists $copybut.old2new$src]} {destroy $copybut.old2new$src}
	menu $copybut.old2new$src -tearoff 0
	set dsts {}
	for {set gd 1} {$gd < $gn} {incr gd} {
	    foreach dst $groupelts($gd) {
		if {!$dirreadonly($dst)} {
		    lappend dsts $dst
		}
	    }
	}
        set any [llength $dsts]
	if {$any} {
	    if $needsep {
		$copybut add separator
		set needsep 0
	    }
	    foreach dst $dsts {
                set age [lindex [lindex $groups($selfile) 1] $dst]
                set im2 [lindex $agecolors($ng) $age]
                set cl2 [lindex $bgcolors($ng) $age]
		set y [lindex $dirs $dst]
		set cmd "copyselfile \"$src\" \"$dst\" \"$selfile\" 1"
		if {$any == 1} {
		    if {$compound_ok} {
			$copybut add command -label "$x -> $y" \
			    -command $cmd -image [mkcopyimage $im $im2] \
			    -compound left
		    } else {
			$copybut add command -label "$x -> $y" \
			    -command $cmd
		    }
		} elseif {$compound_ok} {
		    $copybut.old2new$src add command -label "$y" \
                        -image $im2 -compound left \
			-command $cmd
                } else {
		    $copybut.old2new$src add command -label "$y" \
                        -background $cl2 \
			-command $cmd
                }
	    }
	}
        if {$any > 1} {
            if {$compound_ok} {
	        $copybut add cascade -label "$x ->" \
                    -image $im -compound left \
                    -menu $copybut.old2new$src
            } else {
	        $copybut add cascade -label "$x ->" \
                    -background $cl \
                    -menu $copybut.old2new$src
            }
        }
    }
    if {$groupelts(0) != {}} {
	set needsep 1
	for {set gn 1} {$gn <= $numgroups} {incr gn} {
	    foreach dst $groupelts($gn) {
		if {$dirreadonly($dst)} continue
		set x [lindex $dirs $dst]
		if $needsep {
		    $copybut add separator
		    set needsep 0
		}
                if {$compound_ok} {
		    $copybut add command -label "Remove from $x" \
                        -image ex -compound left \
			-command "removeselfile \"$dst\" \"$selfile\""
                } else {
		    $copybut add command -label "Remove from $x" \
			-command "removeselfile \"$dst\" \"$selfile\""
                }
	    }
	}
    }
    .bar entryconfigure 3 -state normal
}

proc confcopybutdir {} {
    global copybut groupelts selfile dirs compound_ok dirreadonly
    $copybut delete 0 end
    set srcs $groupelts(1)
    set dsts $groupelts(0)
    if {$srcs != {} && $dsts != {}} {
	foreach s $srcs {
	    set x [lindex $dirs $s]
	    foreach d $dsts {
		if {$dirreadonly($d)} continue
		set y [lindex $dirs $d]
		$copybut add command -label "$x -> $y" \
			-command "copyselfile \"$s\" \"$d\" \"$selfile\" 0"
	    }
	}
	set needsep 1
	foreach s $srcs {
	    if {$dirreadonly($s)} continue
	    set x [lindex $dirs $s]
	    if {$needsep} {
		$copybut add separator
		set needsep 0
	    }
            if {$compound_ok} {
	        $copybut add command -label "Remove from $x" \
                    -image ex -compound left \
		    -command "removeselfile \"$s\" \"$selfile\""
            } else {
	        $copybut add command -label "Remove from $x" \
		    -command "removeselfile \"$s\" \"$selfile\""
            }
	}
    }
    .bar entryconfigure 3 -state normal
}

proc resetsel {} {
    global selitem selfile filelabel diffbut copybut
    global canvw
    set selitem {}
    set selfile {}
    $canvw select clear
    if {[info exists filelabel]} {
	$filelabel conf -image paper
    }
    .bar entryconfigure 2 -state disabled
    .bar entryconfigure 3 -state disabled
    clearsecsel
}

proc removediffs {} {
    global texttop textw diffing difff
    catch {destroy $texttop}
    catch {unset texttop}
    catch {unset textw}
    catch {close $difff}
    set diffing 0
}

proc showfile {d f} {
    global showprogram

    set fn [joinname $d $f]

    # Show the file in an external viewer
    if { [llength $showprogram] > 0} {
       eval "exec $showprogram \"$fn\" &"
       return
    }
    # Or make our own viewer
    global textw difflist texttop mergebut
    if {!([info exists textw] && [winfo exists $textw])} {
	maketextw
    } else {
	raise $texttop
    }
    wm title $texttop "Contents of $fn"
    set difflist {}
    $mergebut.m delete 0 end
    $textw conf -state normal -tabs {}
    $textw delete 0.0 end
    set nl {}
    set f [open $fn r]
    set n [gets $f line]
    while {$n >= 0} {
	$textw insert end "$nl$line"
	set nl "\n"
	set n [gets $f line]
    }
    close $f
    $textw conf -state disabled
}

proc redifffiles {} {
    global groups showsame selfile rediffed groups
    if {$selfile == {}} return
    set files [secondarysel $selfile]
    foreach f $files {
	updatefileinfo $f
	set d [string trimright $f /]
	if {[lindex $groups($f) 0] != "dir"} {
	    set groups($f) [diffages $f 1 0]
	} else {
	    set groups($f) [subdirgroups $d]
	}
	refreshcline $f
    }
    selcurfile
    set rediffed $selfile
}

proc diff2 {d1 d2 f} {
    global diffprogram nullfile

    global textw groups dirs numgroups bgcolors selfile difflist texttop
    global difff lno diffdirs diffiflag diffwflag diffbflag diffBflag diffdflag
    global ctxlines diffoldcolor diffnewcolor difffile charwidth mergebut
    global diffing filemode rediffed diffnewfirst underlinetabs
    set group [lindex $groups($selfile) 1]
    set i1 [lindex $group [lsearch $dirs $d1]]
    set i2 [lindex $group [lsearch $dirs $d2]]
    if {($i1 > $i2) == $diffnewfirst} {
	set x $d1
	set d1 $d2
	set d2 $x
	set x $i1
	set i1 $i2
	set i2 $x
    }
    set ds [list $d1 $d2]
    if {$diffing} {
	if {$ds == $diffdirs && $f == $difffile} return
	catch {close $difff}
    }
    set diffdirs $ds
    set difffile $f
    if {[info exists rediffed] && $rediffed == $f} {
	unset rediffed
    }
    set path1 [joinname $d1 $f]
    set path2 [joinname $d2 $f]
    set diffopts "-U $ctxlines $diffiflag $diffwflag $diffbflag $diffBflag $diffdflag"

    if { [llength $diffprogram] > 0} {
       eval "exec $diffprogram \"$path1\" \"$path2\" &"
       return
    }
    # If we used an external diff program, its options are used.  If we didn't,
    # we use our diffopts, and we may be in trouble.
    set caught [catch "exec diff $diffopts $nullfile $nullfile" err]
    if {$caught != 0} {
       set msg "diff $diffopts\n$err\n"
       append msg "Suggestion: Use an external diff viewer such as tkdiff or gvimdiff"
       error_popup "$msg"
       return
    }

    # Build a window
    if {![info exists textw] || ![winfo exists $textw]} {
	maketextw
    }
    if {$filemode} {
	wm title $texttop "Differences: $d1 vs $d2"
    } else {
	wm title $texttop "Differences: $f"
    }
    set difflist {}
    $mergebut.m delete 0 end
    $textw conf -state normal
    $textw delete 0.0 end
    set charwidth [font measure [$textw cget -font] n]
    $textw conf -tabs "[expr 4*$charwidth] left [expr 12*$charwidth] left"
    set x $bgcolors($numgroups)
    $textw tag delete [$textw tag names]
    set diffoldcolor [lindex $x $i1]
    set diffnewcolor [lindex $x $i2]
    $textw tag conf d1 -back $diffoldcolor
    $textw tag conf d2 -back $diffnewcolor
    $textw tag conf sep -back blue
    $textw tag conf ul -underline $underlinetabs
    $textw tag lower sep

    # Start a diff
    set difff [open "|diff $diffopts $path1 $path2" r]
    set diffing 1
    set lno 1
    catch {unset oldin}
    catch {unset newin}
    global linegroups linegroupnum linegrouplast lineinfo
    catch {unset linegroups}
    set linegroupnum 0
    set linegrouplast 0
    catch {unset lineinfo}
    global file1lnum file2lnum incline lineinfo
    set file1lnum 0
    set file2lnum 0
    catch {unset incline}
    catch {unset lineinfo}
    fconfigure $difff -blocking 0
    fileevent $difff readable "readdiff $difff"
}

proc readdiff {f} {
    global difff lno textw difflist dirreadonly
    global incline lineinfo
    global linegroups linegroupnum linegrouplast
    global file1lnum file2lnum diffing textfont
    if {$f != $difff} {
	catch {close $f}
	return
    }
    set n [gets $difff line]
    if {$n < 0} {
	if {![eof $difff]} return
	catch {close $difff}
	set diffing 0
	if {$lno > 1} {
	    $textw delete "end - 1c" end
	    set t [$textw tag names "end - 1l"]
	    if {$t != ""} {
		$textw tag add $t "end - 1l" end
	    }
	}
	$textw conf -state disabled
	if {$lno > 3} {
	    global mergebut diffdirs difffile
	    global groups dirs diffmtime
	    set group [lindex $groups($difffile) 1]
	    foreach i {0 1} {
		set g [lindex $group [lsearch $dirs [lindex $diffdirs $i]]]
		set k 0
		foreach gx $group {
		    if {$gx == $g && !$dirreadonly($k)} {
			set f [lindex $dirs $k]
			$mergebut.m add command -label "update $f" \
			    -command "diffmerge $i \"$f\""
			set path [joinname $f $difffile]
			set diffmtime($path) [file mtime $path]
		    }
		    incr k
		}
	    }
	}
	return
    }
    set x [string index $line 0]
    if {$x == "@" && [regexp { -([0-9,]+) .*\+([0-9,]+) } $line z r1 r2]} {
	set line "\t            $r1        $r2       "
	set file1lnum [string range $r1 0 [expr [string wordend $r1 0]-1]]
	set file2lnum [string range $r2 0 [expr [string wordend $r2 0]-1]]
	lappend difflist $lno
	set line [string range $line 1 end]
	$textw insert end "$line\n"
	set lend [$textw index "$lno.0 + 1l"]
	set i1 [$textw index "$lno.16 + [string length $r1] c"]
	set i2 [$textw index "$i1 + 8c + [string length $r2] c"]
	$textw tag add sep $lno.0 $lno.8
	$textw tag add d1 $lno.8 $i1
	$textw tag add d2 $i1 $i2
	$textw tag add sep $i2 $lend
	set linegrouplast 0
	incr lno
	return
    }
    set ix 1
    if {($x == "-" || $x == "+") && $lno > 3} {
	set incline($lno) 0
	if {!$linegrouplast} {
	    incr linegroupnum
	    set linegroups($linegroupnum) {}
	    set linegrouplast 1
	}
	lappend linegroups($linegroupnum) $lno
	checkbutton $textw.inc$lno -variable incline($lno) \
	    -font {Courier -10} -cursor top_left_arrow \
		-highlightthickness 0 -padx 2 -pady 0
	$textw window create end -window $textw.inc$lno -stretch true
	bind $textw.inc$lno "<Shift-Button-1>" \
		"$textw.inc$lno toggle; togglegroup $linegroupnum $lno; break"
	bind $textw.inc$lno "<Any-Button-3>" \
		"$textw.inc$lno toggle; togglegroup $linegroupnum $lno"
	set ix 2
	set line [string range $line 1 end]
	set lineinfo($lno) [list $file1lnum $file2lnum [expr {$x=="+"}] $line]
    } elseif {$x == "-" || $x == "+"} {
	set line [string trimleft $line $x]
    } elseif {$x == " "} {
	set line [string range $line 1 end]
    }
    $textw insert end "\t"
    set col 0
    set trailb [string length [string trimright $line]]
    while {[set tpos [string first "\t" $line]] >= 0} {
	if {$tpos > 0} {
	    $textw insert end [string range $line 0 [expr $tpos-1]]
	    if {$trailb < $tpos} {
		$textw tag add ul $lno.[expr $ix+$trailb] \
		    $lno.[expr $ix+$tpos]
		set trailb 0
	    } else {
		set trailb [expr $trailb-$tpos]
	    }
	    incr ix $tpos
	    incr col $tpos
	}
	set nsp [expr {8 - ($col & 7)}]
	$textw insert end [string range "         " 1 $nsp] ul
	set line [string range $line [expr $tpos+1] end]
	incr ix $nsp
	incr col $nsp
	if {$trailb > 0} {incr trailb -1}
    }
    $textw insert end "$line\n"
    set tpos [string length $line]
    if {$trailb < $tpos} {
	$textw tag add ul $lno.[expr $ix+$trailb] $lno.[expr $ix+$tpos]
    }
    set lend [$textw index "$lno.0 + 1l"]
    if {$x == "-"} {
	$textw tag add d1 $lno.0 $lend
    } elseif {$x == "+"} {
	$textw tag add d2 $lno.0 $lend
    } else {
	set linegrouplast 0
    }
    if {$linegrouplast} {
	$textw tag add bindtag$lno $lno.0 $lend
	$textw tag bind bindtag$lno "<Button-1>" \
		"$textw.inc$lno toggle; break"
	$textw tag bind bindtag$lno "<Shift-Button-1>" \
		"$textw.inc$lno toggle; togglegroup $linegroupnum $lno; break"
	$textw tag bind bindtag$lno "<Any-Button-3>" \
		"$textw.inc$lno toggle; togglegroup $linegroupnum $lno; break"
    }
    if {$x != "+"} {incr file1lnum}
    if {$x != "-"} {incr file2lnum}
    incr lno
}

proc changeunderlinetabs {} {
    global textw underlinetabs
    $textw tag conf ul -underline $underlinetabs
}

proc togglegroup {group lno} {
    global incline linegroups textw
    if $incline($lno) {
	set state select
    } else {
	set state deselect
    }
    foreach l $linegroups($group) {
	$textw.inc$l $state
    }
}

proc invertbuttons {} {
    global incline textw
    foreach l [array names incline] {
	set incline($l) [expr {1 - $incline($l)}]
    }
}

proc mergelist {} {
    global incline lineinfo lno
    set mlist {}
    for {set i 1} {$i <= $lno} {incr i} {
	if {[info exists incline($i)]} {
	    lappend mlist [list $incline($i) $lineinfo($i)]
	}
    }
    return $mlist
}

proc diffmerge {ix dir} {
    global diffdirs difffile diffmtime fserial
    global dirs diffoldcolor diffnewcolor textfont
    set infile [joinname $dir $difffile]
    if {$diffmtime($infile) != [file mtime $infile]} {
	error_popup "File $infile has changed since the diff was performed."
	return
    }
    set mlist [mergelist]

    set di [lsearch -exact $dirs $dir]
    set fi $fserial($difffile)
    set w ".merge:$di:$fi"
    catch {destroy $w}
    toplevel $w
    wm title $w "Dirdiff: merged $infile"
    frame $w.bar -relief raised -border 2
    pack $w.bar -side top -fill x
    menubutton $w.bar.file -text File -menu $w.bar.file.m -padx 10 -pady 1
    menu $w.bar.file.m -tearoff 0
    $w.bar.file.m add command -label Save -command "savemerge $w"
    $w.bar.file.m add command -label Close -command "destroy $w"
    pack $w.bar.file -side left
    menubutton $w.bar.edit -text Edit -menu $w.bar.edit.m -padx 10 -pady 1
    menu $w.bar.edit.m -tearoff 0
    $w.bar.edit.m add command -label Cut -command "tk_textCut $w.t"
    $w.bar.edit.m add command -label Copy -command "tk_textCopy $w.t"
    $w.bar.edit.m add command -label Paste -command "tk_textPaste $w.t"
    $w.bar.edit.m add command -label Find \
	    -command "difffind :merge:$di:$fi $w.t"
    pack $w.bar.edit -side left
    frame $w.f -relief sunk -border 2
    entry $w.f.filename
    $w.f.filename insert 0 $infile
    pack $w.f.filename -side left -fill x -expand 1
    pack $w.f -side top -fill x
    text $w.t -yscrollcommand "$w.sb set" -font $textfont
    scrollbar $w.sb -command "$w.t yview"
    pack $w.sb -side right -fill y
    pack $w.t -side left -fill both -expand 1
    bind $w <Key-Prior> "$w.t yview scroll -1 p"
    bind $w <Key-Next> "$w.t yview scroll 1 p"
    set cols [list $diffoldcolor $diffnewcolor]
    $w.t tag conf insl -back [lindex $cols [expr {1 - $ix}]]
    $w.t tag conf ndel -back [lindex $cols $ix]

    set inf [open $infile r]
    set l 1
    foreach mm $mlist {
	set inc [lindex $mm 0]
	set m [lindex $mm 1]
	set tl [lindex $m $ix]
	if {!$inc} {
	    if {[lindex $m 2] == $ix} {
		while {$l < $tl} {
		    if {[gets $inf line] < 0} return
		    $w.t insert end $line
		    $w.t insert end \n
		    incr l
		}
		if {[gets $inf line] < 0} return
		$w.t insert end $line ndel
		$w.t insert end \n ndel
		incr l
	    }
	    continue
	}
	while {$l < $tl} {
	    if {[gets $inf line] < 0} return
	    $w.t insert end $line
	    $w.t insert end \n
	    incr l
	}
	if {[lindex $m 2] != $ix} {
	    # insert this line
	    $w.t insert end [lindex $m 3] insl
	    $w.t insert end \n insl
	} else {
	    # delete this line
	    if {[gets $inf line] < 0} return
	    incr l
	}
    }
    while {[gets $inf line] >= 0} {
	$w.t insert end $line
	$w.t insert end \n
    }
    # delete last newline
    catch {$w.t delete "end - 1c" end}
    close $inf
}

proc savemerge {w} {
    set infile [$w.f.filename get]
    if {$infile == {}} {return}
    set tmpfile "$infile.tmp"
    set tf [open $tmpfile w]
    puts -nonewline $tf [$w.t get 0.0 end]
    close $tf
    bkedit $infile
    catch {file attr $tmpfile -perm [file attr $infile -perm]}
    file rename -force $infile $infile.orig
    file rename $tmpfile $infile
    destroy $w
    redifffiles
}

proc nextdiff {} {
    global textw difflist
    set ltop [expr int([$textw index @0,0])]
    foreach l $difflist {
	if {$l > $ltop} {
	    $textw yview $l.0
	    break
	}
    }
}

proc prevdiff {} {
    global textw difflist
    set ltop [expr int([$textw index @0,0])]
    set lprev {}
    foreach l $difflist {
	if {$l >= $ltop} {
	    if {$lprev != {}} {
		$textw yview $lprev.0
	    }
	    break
	}
	set lprev $l
    }
}

proc diffnextfile {inc} {
    global diffdirs selfile numgroups groups dirs textw
    global ycoord canvw
    if {!([info exists textw] && [winfo exists $textw])} return
    if {![selnextline $inc] || $numgroups <= 1 || ![info exists diffdirs]} {
	return
    }
    set d1 [lindex $diffdirs 0]
    set d2 [lindex $diffdirs 1]
    set group [lindex $groups($selfile) 1]
    set i1 [lindex $group [lsearch $dirs $d1]]
    set i2 [lindex $group [lsearch $dirs $d2]]
    if {$i1 == 0 || $i2 == 0 || $i1 == $i2} return
    diff2 $d1 $d2 $selfile
}

proc showsomediff {inc} {
    global diffdirs difffile selfile numgroups groups dirs textw
    global ycoord canvw groupelts dirinterest
    if {![selnextline $inc]} return
    if {[lindex $groups($selfile) 0] == "dir"} return

    if {$numgroups <= 1} {
	set xi [lindex $groupelts(1) 0]
	if {$xi != ""} {
	    showfile [lindex $dirs $xi] $selfile
	}
	return
    }

    set group [lindex $groups($selfile) 1]

    set g1 1
    set g2 1
    if {[info exists diffdirs] && [info exists difffile]} {
	set d1 [lindex $diffdirs 0]
	set d2 [lindex $diffdirs 1]
	set i1 [lsearch $dirs $d1]
	set i2 [lsearch $dirs $d2]
	set g1 [lindex $group $i1]
	set g2 [lindex $group $i2]
	if {$difffile != $selfile || \
		([info exists rediffed] && $rediffed == $difffile)} {
	    # looking at a different file from last time,
	    # try to do the same diff
	    if {$g1 > 0 && $g2 > 0 && $g1 != $g2 \
		    && $dirinterest($i1) && $dirinterest($i2)} {
		diff2 $d1 $d2 $selfile
		return
	    }
	    set g1 1
	    set g2 1
	} else {
	    # looking at the same file as last time,
	    # do the next diff
	    if {$g2 < $g1} {
		set x $g1
		set g1 $g2
		set g2 $x
	    }
	}
    }

    # work out which groups are interesting (have interesting dirs)
    for {set g 0} {$g <= $numgroups} {incr g} {
	set groupinterest($g) {}
	foreach i $groupelts($g) {
	    if $dirinterest($i) {
		set groupinterest($g) $i
		break
	    }
	}
    }

    set ncomb [expr {$numgroups * ($numgroups - 1) / 2}]
    for {} {$ncomb > 0} {incr ncomb -1} {
	if {[incr g2] > $numgroups} {
	    if {[incr g1] >= $numgroups} {
		set g1 1
	    }
	    set g2 [expr {$g1 + 1}]
	}
	if {$groupelts($g1) != {} && $groupelts($g2) != {} \
		&& $groupinterest($g1) != {} && $groupinterest($g2) != {}} {
	    set d1 [lindex $dirs $groupinterest($g1)]
	    set d2 [lindex $dirs $groupinterest($g2)]
	    diff2 $d1 $d2 $selfile
	    return
	}
    }
}

proc copydifffile {} {
    global diffdirs selfile groups dirs changed
    if {![info exists diffdirs]} return
    set d1 [lindex $diffdirs 0]
    set d2 [lindex $diffdirs 1]
    if {[lindex $groups($selfile) 0] == "dir"} return
    set group [lindex $groups($selfile) 1]
    set n1 [lsearch $dirs $d1]
    set n2 [lsearch $dirs $d2]
    set i1 [lindex $group $n1]
    set i2 [lindex $group $n2]
    if {$i1 == 0 || $i2 == 0 || $i1 == $i2} return
    set changed 0
    copyfile $n2 $n1 $selfile 0
    if {$changed} redisplay
}

proc maketextw {} {
    global textw texttop mergebut filemode textfont
    toplevel .diffs
    wm title .diffs "Differences"
    frame .diffs.bar -relief sunken -border 2
    pack .diffs.bar -side top -fill x
    button .diffs.bar.rediff -text Rediff -command "diffnextfile 0"
    pack .diffs.bar.rediff -side left
    button .diffs.bar.options -text Options -command diffoptions
    pack .diffs.bar.options -side left
    button .diffs.bar.find -text Find -command "difffind :diffs .diffs.t"
    pack .diffs.bar.find -side left
    menubutton .diffs.bar.merge -text Merge -menu .diffs.bar.merge.m -padx 10
    menu .diffs.bar.merge.m -tearoff 0
    pack .diffs.bar.merge -side left
    if {!$filemode} {
	button .diffs.bar.next -text "Next file" -command "diffnextfile 1"
	pack .diffs.bar.next -side left
	button .diffs.bar.prev -text "Previous file" -command "diffnextfile -1"
	pack .diffs.bar.prev -side left
    }
    button .diffs.bar.invert -text "Invert" -command "invertbuttons"
    pack .diffs.bar.invert -side left
    set texttop .diffs
    set textw .diffs.t
    set mergebut .diffs.bar.merge
    text $textw -width 84 -height 32 -yscrollcommand ".diffs.sb set" \
	-font $textfont
    scrollbar .diffs.sb -command "$textw yview"
    pack .diffs.sb -side right -fill y
    pack $textw -side left -fill both -expand 1
    bind .diffs <Key-Prior> "$textw yview scroll -1 p"
    bind .diffs b "$textw yview scroll -1 p"
    bind .diffs B "$textw yview scroll -1 p"
    bind .diffs <Key-BackSpace> "$textw yview scroll -1 p"
    bind .diffs <Key-Delete> "$textw yview scroll -1 p"
    bind .diffs <Key-Next> "$textw yview scroll 1 p"
    bind .diffs <Key-space> "$textw yview scroll 1 p"
    bind .diffs <Key-Up> "$textw yview scroll -1 u"
    bind .diffs <Key-Down> "$textw yview scroll 1 u"
    bind .diffs d "$textw yview scroll \[expr \"int(\[$textw cget -height\]/2)\"\] u"
    bind .diffs D "$textw yview scroll \[expr \"int(\[$textw cget -height\]/2)\"\] u"
    bind .diffs u "$textw yview scroll \[expr \"int(-\[$textw cget -height\]/2)\"\] u"
    bind .diffs U "$textw yview scroll \[expr \"int(-\[$textw cget -height\]/2)\"\] u"
    bind .diffs n nextdiff
    bind .diffs p prevdiff
    if {!$filemode} {
	bind .diffs N "diffnextfile 1"
	bind .diffs P "diffnextfile -1"
    }
    bind .diffs q removediffs
    bind .diffs Q "set stopped 1; destroy ."
    bind .diffs <Key-Home> "$textw yview 1.0"
    bind .diffs g "$textw yview 1.0"
    bind .diffs <Key-End> "$textw yview -pickplace \[$textw index end\]"
    bind .diffs G "$textw yview -pickplace \[$textw index end\]"
    bind .diffs C copydifffile
}

proc diffoptions {} {
    global optionw
    if {[info exists optionw] && [winfo exists $optionw]} {
	raise $optionw
	return
    }
    set optionw .options
    toplevel $optionw
    wm title .options "Dirdiff options"
    checkbutton $optionw.diffiflag -text "Ignore case" \
	    -offvalue "" -onvalue "-i" -anchor w
    pack $optionw.diffiflag -side top -fill x
    checkbutton $optionw.diffwflag -text "Ignore all white space" \
	    -offvalue "" -onvalue "-w" -anchor w
    pack $optionw.diffwflag -side top -fill x
    checkbutton $optionw.diffbflag -text "Ignore amount of white space" \
	    -offvalue "" -onvalue "-b" -anchor w
    pack $optionw.diffbflag -side top -fill x
    checkbutton $optionw.diffBflag -text "Ignore blank lines" \
	    -offvalue "" -onvalue "-B" -anchor w
    pack $optionw.diffBflag -side top -fill x
    checkbutton $optionw.diffdflag -text "Minimize diffs" \
	    -offvalue "" -onvalue "-d" -anchor w
    pack $optionw.diffdflag -side top -fill x
    checkbutton $optionw.ultabs -text "Underline tabs" -anchor w \
	    -variable underlinetabs -command changeunderlinetabs
    pack $optionw.ultabs -side top -fill x
    checkbutton $optionw.newfirst -text "Newer file first" -anchor w \
	    -variable diffnewfirst
    pack $optionw.newfirst -side top -fill x
    frame $optionw.ctx
    pack $optionw.ctx -side top
    label $optionw.ctx.l -text "Lines of context: "
    pack $optionw.ctx.l -side left
    entry $optionw.ctx.v -width 5 -textvariable ctxlines
    pack $optionw.ctx.v -side left
    button $optionw.save -text "Save options" -command saveoptions
    pack $optionw.save -side top -fill x
    frame $optionw.space -height 6
    pack $optionw.space -side top -fill x
    button $optionw.dismiss -text "Dismiss" -command "destroy $optionw"
    pack $optionw.dismiss -side bottom -fill x
    bind $optionw <Return> "destroy $optionw"
}

proc saveoptions {} {
    global rcsflag diffiflag diffwflag diffbflag diffBflag diffdflag
    global ctxlines showsame underlinetabs bitkeeper nukefiles redisp_immed
    global diffprogram showprogram
    global bkgetmode diffnewfirst textfont filelistfont nxdirmode
    global docvsignore
    set f [open "~/.dirdiff" w]
    puts $f [list set diffprogram $diffprogram]
    puts $f [list set showprogram $showprogram]
    puts $f [list set rcsflag $rcsflag]
    puts $f [list set diffiflag $diffiflag]
    puts $f [list set diffwflag $diffwflag]
    puts $f [list set diffbflag $diffbflag]
    puts $f [list set diffBflag $diffBflag]
    puts $f [list set diffdflag $diffdflag]
    puts $f [list set ctxlines $ctxlines]
    puts $f [list set showsame $showsame]
    puts $f [list set underlinetabs $underlinetabs]
    puts $f [list set bitkeeper $bitkeeper]
    puts $f [list set bkgetmode $bkgetmode]
    puts $f [list set redisp_immed $redisp_immed]
    puts $f [list set diffnewfirst $diffnewfirst]
    puts $f [list set nukefiles $nukefiles]
    puts $f [list set filelistfont $filelistfont]
    puts $f [list set textfont $textfont]
    puts $f [list set nxdirmode $nxdirmode]
    puts $f [list set docvsignore $docvsignore]
    close $f
}

proc difffind {tag txt} {
    global dfindw$tag igncase$tag diffiflag regexp$tag backwards$tag
    if {[info exists dfindw$tag] && [winfo exists [set dfindw$tag]]} {
	raise [set dfindw$tag]
	return
    }
    set w .find$tag
    set dfindw$tag $w
    toplevel $w
    wm title $w "Dirdiff: Find"
    frame $w.f
    pack $w.f -side top -fill x -expand 1
    button $w.f.b -text "Find:" -command [list dofind $tag $txt $w]
    bind $w <Return> [list dofind $tag $txt $w]
    pack $w.f.b -side left
    entry $w.f.e
    pack $w.f.e -side right
    if {![info exists igncase$tag]} {
	set igncase$tag [expr {$diffiflag != {}}]
    }
    checkbutton $w.case -variable igncase$tag -text "Ignore case" -anchor w
    pack $w.case -side top -fill x
    checkbutton $w.regexp -variable regexp$tag -text "Regular expression" \
	    -anchor w
    pack $w.regexp -side top -fill x
    checkbutton $w.backwards -variable backwards$tag \
	    -text "Search backwards" -anchor w
    pack $w.backwards -side top -fill x
    button $w.close -text "Close" -command "destroy $w"
    pack $w.close -side top -fill x
}

proc dofind {tag txt w} {
    global dfindw$tag igncase$tag regexp$tag backwards$tag
    if {![winfo exists $txt]} return
    set w [set dfindw$tag]
    set str [$w.f.e get]
    if {$str == {}} return
    set back [set backwards$tag]
    # By default, start the search from the insertion point.
    # If there is a selection, start from the end of the selection for
    # a forwards search, or from the beginning for a backwards search.
    set start [$txt index insert]
    if {[$txt tag ranges sel] != {}} {
	if {$back} {
	    set start [$txt index sel.first]
	} else {
	    set start [$txt index sel.last]
	}
    }
    set opts {}
    if {$back} {
	lappend opts "-backwards"
    }
    if {[set regexp$tag]} {
	lappend opts "-regexp"
    }
    if {[set igncase$tag]} {
	lappend opts "-nocase"
    }
    set pos [eval $txt search $opts -count count -- [list $str] $start]
    if {$pos == {}} {
	bell
	return
    }
    set epos "$pos + $count c"
    $txt mark set insert $epos
    $txt tag remove sel 0.0 end
    $txt tag add sel $pos $epos
    $txt see $epos
    $txt see $pos
}

proc makepatch {d1 d2} {
    global patchnum selfile patchfiles patch_outfile
    global showprogram

    set files [secondarysel $selfile]
    if {$files == {}} {
	error_popup "No files selected!"
	return
    }
    if {![info exists patchnum]} {
	set patchnum 0
    }
    set patchfiles($patchnum) $files

    # Put the diff in a temporary file for external viewer
    if { [llength $showprogram] > 0} {
       set patch_outfile "patch${patchnum}.diff"
       set w [open $patch_outfile w]
    # Or build our own viewer
    } else {
       set w ".patch:$patchnum"
       catch {destroy $w}
       toplevel $w
       wm title $w "Patch: $d1 to $d2"
       frame $w.bar -relief raised -border 2
       pack $w.bar -side top -fill x
       menubutton $w.bar.file -text File -menu $w.bar.file.m -padx 10 -pady 1
       menu $w.bar.file.m -tearoff 0
       $w.bar.file.m add command -label Save -command "savepatch $w"
       $w.bar.file.m add command -label Close -command "destroy $w"
       pack $w.bar.file -side left
       menubutton $w.bar.edit -text Edit -menu $w.bar.edit.m -padx 10 -pady 1
       menu $w.bar.edit.m -tearoff 0
       $w.bar.edit.m add command -label Cut -command "tk_textCut $w.t"
       $w.bar.edit.m add command -label Copy -command "tk_textCopy $w.t"
       $w.bar.edit.m add command -label Paste -command "tk_textPaste $w.t"
       $w.bar.edit.m add command -label Find \
	    -command "difffind :patch:$patchnum $w.t"
       pack $w.bar.edit -side left
       frame $w.f -relief sunk -border 2
       label $w.f.l -text "Filename: "
       entry $w.f.filename
       $w.f.filename insert 0 "patch$patchnum"
       pack $w.f.l -side left
       pack $w.f.filename -side left -fill x -expand 1
       pack $w.f -side top -fill x
       text $w.t -yscrollcommand "$w.sb set"
       scrollbar $w.sb -command "$w.t yview"
       pack $w.sb -side right -fill y
       pack $w.t -side left -fill both -expand 1
       bind $w <Key-Prior> "$w.t yview scroll -1 p"
       bind $w <Key-Next> "$w.t yview scroll 1 p"
    }

    patchnext $patchnum $w $d1 $d2 0
    incr patchnum
}

# Output lines to either our external patchfile or the internal vieiwer
proc lineout {w line} {
    if {[string match ".*" $w]} {
        $w.t insert end "$line\n"
    } else {
        puts $w "$line"
    }
}

proc patchnext {pnum w d1 d2 i} {
    global patchfiles have_unidiff showprogram patch_outfile nullfile

    set contextopt [expr {$have_unidiff ? "-u" : "-c"}]
    update
    for {} {[set f [lindex $patchfiles($pnum) $i]] != {}} {incr i} {
	set p1 [joinname $d1 $f]
	set p2 [joinname $d2 $f]
	if {[file exists $p1] && [file exists $p2]} {
	    set fh [open "|diff $contextopt $p1 $p2" r]
	} elseif {[file exists $p1] && ! [file exists $p2]} {
	    set fh [open "|diff $contextopt $p1 $nullfile" r]
	} elseif {! [file exists $p1] && [file exists $p2]} {
	    set fh [open "|diff $contextopt $nullfile $p2" r]
	} else {
            continue
	}
	fconfigure $fh -blocking 0
	fileevent $fh readable "readpatch $fh $pnum $w $d1 $d2 $i \"$f\""
	return
    }
    if {[string match ".*" $w]} {
       $w.t delete "end - 1c" end
    } else {
        close $w
        eval "exec $showprogram \"$patch_outfile\" &"
        # Should we remove the tempfile here?  We don't have it if we used 
        # the internal viewer
    }
    unset patchfiles($pnum)
}

proc diffl_out {w d1 d2 f} {
    global have_unidiff
    set contextopt [expr {$have_unidiff ? "-urN" : "-cr"}]
    lineout $w "diff $contextopt [joinname $d1 $f] [joinname $d2 $f]"
}

proc readpatch {difff pnum w d1 d2 i f} {
    global have_unidiff showprogram
    set n [gets $difff line]
    if {$n < 0} {
	if {![eof $difff]} return
	catch {close $difff}
	patchnext $pnum $w $d1 $d2 [expr $i+1]
	return
    }
    if {[string match "Binary*" $line]} return
    if {$have_unidiff} {
       if {[string match "---*" $line]} {
           diffl_out $w $d1 $d2 $f
        }
    } else {
       if {[string match "\*\*\* ${d1}*" $line]} {
           diffl_out $w $d1 $d2 $f
        }
    }
    lineout $w $line
}

proc savepatch {w} {
    set outfile [$w.f.filename get]
    if {$outfile == {}} {return}
    set outf [open $outfile w]
    puts -nonewline $outf [$w.t get 0.0 end]
    close $outf
    destroy $w
}

# invoked from the File->Touch menu item
proc touchfiles {d} {
    global selfile
    set files [secondarysel $selfile]
    if {$files == {}} {
	error_popup "No files selected!"
	return
    }
    set now [clock seconds]
    set bad {}
    foreach f $files {
	set df [file join $d $f]
	if {[catch {file mtime $df $now} err]} {
	    append bad "$df: $err\n"
	}
    }
    if {$bad != {}} {
	error_popup "Errors occurred:\n$bad"
    }
    redifffiles
}

# invoked from the File->BK get menu item
proc bkgetfiles {d} {
    global selfile bkgetmode
    set files [secondarysel $selfile]
    if {$files == {}} {
	error_popup "No files selected!"
	return
    }
    set bad {}
    set flag "-qT"
    if {$bkgetmode != " "} {
	append flag $bkgetmode
    }
    foreach f $files {
	set df [file join $d $f]
	if {[catch {exec bk get $flag $df} err]} {
	    append bad "$df: $err\n"
	}
    }
    if {$bad != {}} {
	error_popup "Errors occurred:\n$bad"
    }
    redifffiles
}

proc exclfilelist {} {
    global exclw nukefiles
    if {[info exists exclw] && [winfo exists $exclw]} {
	raise $exclw
	return
    }
    toplevel .excl
    wm title .excl "Dirdiff: excluded files"
    set exclw .excl
    frame $exclw.b
    listbox $exclw.l -height 10 -width 40 -yscrollcommand "$exclw.sb set" \
	    -selectmode single
    scrollbar $exclw.sb -command "$exclw.l yview"
    entry $exclw.e
    pack $exclw.b -side bottom -fill x
    pack $exclw.e -side bottom -fill x
    pack $exclw.sb -side right -fill y
    pack $exclw.l -side left -fill both -expand 1
    button $exclw.b.add -text "Add" -padx 20 -command addexcl
    button $exclw.b.rem -text "Remove" -command remexcl
    button $exclw.b.close -text "Close" -command closeexcl
    pack $exclw.b.add -side left -fill x
    pack $exclw.b.rem -side left -fill x
    pack $exclw.b.close -side right -fill x
    bind $exclw.e <Return> "addexcl"
    foreach i $nukefiles {
	$exclw.l insert end $i
    }
}

proc addexcl {} {
    global exclw nukefiles
    if {[info exists exclw] && [winfo exists $exclw]} {
	set e [$exclw.e get]
	if {$e != {}} {
	    $exclw.l insert end $e
	    lappend nukefiles $e
	    $exclw.l see end
	}
    }
}

proc remexcl {} {
    global exclw nukefiles
    if {[info exists exclw] && [winfo exists $exclw]} {
	set s [$exclw.l curselection]
	if {$s != {}} {
	    $exclw.l delete $s
	    set nukefiles [lreplace $nukefiles $s $s]
	}
    }
}

proc exclsel {} {
    global selfile nukefiles exclw
    set files [secondarysel $selfile]
    foreach f $files {
	set df [string trimright $f /]
	if {$df != {}} {
	    lappend nukefiles $df
	    if {[info exists exclw] && [winfo exists $exclw]} {
		$exclw.l insert end $df
	    }
	}
    }
    redisplay
}

proc extprograms {} {
   global showprogram diffprogram
   toplevel .ext
   frame .ext.top
   label .ext.top.diffl -text "Diff Viewing/Merging"
   entry .ext.top.diffe -textvariable diffprogram
   label .ext.top.showl -text "File Viewing"
   entry .ext.top.showe -textvariable showprogram
   grid .ext.top.diffl -row 0 -column 0 -sticky e
   grid .ext.top.diffe -row 0 -column 1 -sticky nsew -pady 4
   grid .ext.top.showl -row 1 -column 0 -sticky e
   grid .ext.top.showe -row 1 -column 1 -sticky nsew -pady 4
   grid columnconfigure .ext.top 0 -weight 0
   grid columnconfigure .ext.top 1 -weight 1
   pack .ext.top -fill x -expand yes
   frame .ext.bot
   button .ext.bot.ok -text "OK" \
     -command {
        destroy .ext
     }
  pack .ext.bot .ext.bot.ok -fill x -expand yes
}

proc closeexcl {} {
    global exclw
    catch {destroy $exclw}
    catch {unset exclw}
}

proc secondarysel {fname} {
    global secsel canvw
    set files {}
    foreach it [array names secsel] {
	lappend files [$canvw itemcget $it -text]
    }
    if {$files == {}} {
	if {$fname == {}} {
	    return {}
	}
	set files [list $fname]
    }
    return [lsort $files]
}

proc copyselfile {src dst fname confirm} {
    global dirs changed
    set files [secondarysel $fname]
    set n [llength $files]
    set changed 0
    if {$n == 1} {
	copyfile $src $dst $fname $confirm
    } else {
	if {$confirm} {
	    set sd [lindex $dirs $src]
	    set dd [lindex $dirs $dst]
	    if {![confirm_popup "Copy $n older files from $sd to $dd?"]} {
		return
	    }
	}
	foreach f $files {
	    copyfile $src $dst $f 0
	}
    }
    if {$changed} redisplay
    after idle selcurfile
}

proc copyfile {src dst fname confirm} {
    global dirs bitkeeper filemode
    set sd [lindex $dirs $src]
    set dd [lindex $dirs $dst]
    set srcf [joinname $sd $fname]
    set dstf [joinname $dd $fname]
    if {$filemode} {
	set msg "$src to $dst"
	set copydst $dstf
    } else {
	set msg "$fname from $sd to $dd"
	set copydst [file dirname $dstf]
    }
    if {$confirm} {
	if {![confirm_popup "Copy older $msg?"]} {
	    return
	}
    }
    set z [string trimright $fname /]
    if {$z != $fname} {
	copydir $src $dst $z
	return
    }
    bkedit $dstf
    if [catch {file copy -force -- $srcf $copydst} err] {
	error_popup "Error copying $msg: $err"
    } else {
	bknew $dstf
	updatecline $src $dst $fname
	if {$bitkeeper} {
	    # make file writable if it isn't already
	    set perm [file attr $dstf -perm]
	    if {($perm & 0200) == 0} {
		file attr $dstf -perm [expr {$perm | 0200}]
	    }
	}
    }
}

proc copydir {src dst dname} {
    global dirs groups alllines
    set sn [lindex $dirs $src]
    set dn [lindex $dirs $dst]
    if [catch {exec cp -p -r $sn/$dname [file dirname $dn/$dname]} err] {
	error_popup "Error copying $dname from $sn to $dn: $err"
	return
    }
    foreach f $alllines {
	if [string match $dname* $f] {
	    updatecline $src $dst $f
	}
    }
}

proc bkedit {name} {
    global bitkeeper
    if {!$bitkeeper} return
    set sfile [file join [file dirname $name] SCCS "s.[file tail $name]"]
    if {[file isfile $sfile] && ![file writable $name]} {
	if [catch {exec bk edit -q $name} err] {
	    error_popup "Warning: couldn't check out $name: $err"
	}
    }
}

proc bknew {name} {
    global bitkeeper bkgetmode
    if {!$bitkeeper} return
    set sdir [file join [file dirname $name] SCCS]
    set sfile [file join $sdir "s.[file tail $name]"]
    if {[file isdir $sdir] && ![file exists $sfile]} {
	if [catch {exec bk new -q $name} err] {
	    error_popup "Warning: couldn't create new BK file $name: $err"
	} else {
	    set flag "-qT"
	    if {$bkgetmode != " "} {
		append flag $bkgetmode
	    }
	    if [catch {exec bk get $flag $name} err ] {
		error_popup "Warning: couldn't check out new BK file $name: $err"
	    }
	}
    }
}

proc removeselfile {dst fname} {
    global groupelts dirs changed
    set files [secondarysel $fname]
    if {$files == {}} return
    set nf 0
    set nd 0
    foreach x $files {
	if {[string range $x end end] == "/"} {
	    incr nd
	} else {
	    incr nf
	}
    }
    set dd [lindex $dirs $dst]
    if {$nd + $nf == 1} {
	set x [string trimright [joinname $dd $fname] /]
	if {![confirm_popup "Remove $x?"]} {
	    return
	}
    } else {
	set stuff "Remove "
	if {$nd > 0} {
	    if {$nd == 1} {
		append stuff "1 directory "
	    } else {
		append stuff "$nd directories "
	    }
	    if {$nf > 0} {
		append stuff "and "
	    }
	}
	if {$nf == 1} {
	    append stuff "1 file "
	} elseif {$nf > 1} {
	    append stuff "$nf files "
	}
	append stuff "from $dd?"
	if {![confirm_popup $stuff]} {
	    return
	}
    }
    set changed 0
    foreach f $files {
	set d [string trimright $f /]
	set dstf [joinname $dd $d]
	if {$d == $f} {
	    set bad [catch {file delete $dstf} err]
	} else {
	    set bad [catch {file delete -force $dstf} err]
	}
	if $bad {
	    error_popup "Error deleting $dstf: $err"
	} else {
	    updatecline [lindex $groupelts(0) 0] $dst $f
	}
    }
    if {$changed} redisplay
    after idle selcurfile
}

proc confirm_popup msg {
    global confirm_ok
    set confirm_ok 0
    set w .confirm
    toplevel $w
    wm transient $w .
    message $w.m -text $msg -justify center -aspect 400
    pack $w.m -side top -fill x -padx 20 -pady 20
    button $w.ok -text OK -command "set confirm_ok 1; destroy $w"
    pack $w.ok -side left -fill x
    button $w.cancel -text Cancel -command "destroy $w"
    pack $w.cancel -side right -fill x
    bind $w <Visibility> "grab $w; focus $w"
    tkwait window $w
    return $confirm_ok
}

proc error_popup msg {
    set w .error
    toplevel $w
    wm transient $w .
    message $w.m -text $msg -justify center -aspect 400
    pack $w.m -side top -fill x -padx 20 -pady 20
    button $w.ok -text OK -command "destroy $w"
    pack $w.ok -side bottom -fill x
    bind $w <Visibility> "grab $w; focus $w"
    tkwait window $w
}

proc notalldirs {dirs} {
    set type ""
    foreach d $dirs {
	if {[catch {file lstat $d stat} err]} {
	    puts stderr $err
	    exit 1
	}
	if {$type == ""} {
	    set type $stat(type)
	} elseif {$type != $stat(type)} {
	    puts stderr "Error: $d is a $stat(type) but [lindex $dirs 0] is a $type"
	    exit 1
	}
    }
    return [expr {$type == "file"}]
}

proc go {} {
    global diffing filemode dirs nextserial
    if {[llength $dirs] == 0} {exit 0}
    set diffing 0
    set nextserial 0
    set filemode [notalldirs $dirs]
    icons
    makewins
    initcanv
    resetsel
    removediffs
    update
    canvdiffs
}

proc rediff {} {
    initcanv
    resetsel
    removediffs
    update
    canvdiffs
}

proc repackgroups {gr} {
    if {[lindex $gr 0] == "dir"} {
	return $gr
    }
    set glist [lindex $gr 1]
    set glsort [lsort $glist]
    set ng(0) 0
    set lg 0
    set gc 0
    foreach e $glsort {
	if {$e != $lg} {
	    set lg $e
	    incr gc
	    set ng($e) $gc
	}
    }
    if {$gc == [lindex $gr 0]} {
	return $gr
    }
    set newlist {}
    foreach e $glist {
	lappend newlist $ng($e)
    }
    return [list $gc $newlist]
}

proc interesting_line {gr} {
    global dirinterest dirs showsame
    if {$gr == {}} {
	return 0
    }
    if {$showsame} {
	return 1
    }
    set glist [lindex $gr 1]
    set i 0
    foreach e $glist {
	if $dirinterest($i) {
	    if {[info exists first]} {
		if {$e != $first} {
		    return 1
		}
	    } else {
		set first $e
	    }
	}
	incr i
    }
    return 0
}

proc redisplay {{zapdiffs 0}} {
    global canvw canvy canvy0 alllines groups ruletype linespc stringx
    global ruletype selfile secsel ycoord filemode redisp_immed
    if {$filemode || !($zapdiffs || $redisp_immed)} return
    set y [expr {[lindex [$canvw yview] 0] * $canvy}]
    set i [textitemat [expr {$stringx+5}] [expr {$y + $linespc/2}]]
    set topy 0
    set topline {}
    if {$i != {}} {
	set topline [$canvw itemcget $i -text]
    }
    if {$zapdiffs} {
	removediffs
    } else {
	set filesel $selfile
	set filesecsel [secondarysel $selfile]
    }
    $canvw delete all
    set canvy $canvy0
    $canvw conf -scrollregion "0 0 0 1"
    catch {unset ycoord}
    resetsel
    foreach f $alllines {
	if {$f == $topline} {
	    set topy $canvy
	}
	set gr $groups($f)
	if {$gr != {} && [notnuked [string trimright $f /]]} {
	    set gr [repackgroups $gr]
	    set groups($f) $gr
	    if {[interesting_line $gr]} {
		displine $gr $f
	    }
	}
    }
    if {[info exists ruletype]} {
	ruleoff $ruletype
    }
    if {$canvy > 0} {
	$canvw yview moveto [expr {$topy * 1.0 / $canvy}]
    } else {
	$canvw yview moveto 0
    }
    if {!$zapdiffs} {
	foreach f $filesecsel {
	    set i [itemofname $f]
	    if {$i != {}} {
		addsecsel $i
	    }
	}
	set i [itemofname $filesel]
	if {$i != {}} {
	    selectitem $i
	    addsecsel $i
	}
	selcurfile
    }
}

proc icons {} {
   global agecolors

   image create photo ex \
       -format gif -data {
R0lGODlhEAANAIAAAAAAAP///yH+Dk1hZGUgd2l0aCBHSU1QACH5BAEAAAEA
LAAAAAAQAA0AAAIgjI95ABqcWENSVXMtzE5CR30g5o3PJkYiR05LenauqRQA
Ow==
}
   image create photo folder \
       -format gif -data {
R0lGODlhEAANAMIAAISEhMbGxv/si////wAAAAAAAAAAAAAAACH+Dk1hZGUg
d2l0aCBHSU1QACH5BAEAAAQALAAAAAAQAA0AAAMoSATM+nAFQUUAUYFZ6W3g
II4kyQxd2p1qy7bpC1fyLNQzDusu6P+ABAA7
}
   image create photo paper \
       -format gif -data {
R0lGODlhEAANAKEAAISEhP///8bGxgAAACH+Dk1hZGUgd2l0aCBHSU1QACH5
BAEAAAMALAAAAAAQAA0AAAIp3ICpxhcPAxCgufhAoE1jmXRfVDHeKIloaq6s
cY4l7M4XasdfrvSIUQAAOw==
}
   image create photo paper_green \
       -format gif -data {
R0lGODlhEAANAMIAAP///4SEhP7/vsbGxgDKAP///////////yH5BAEAAAcALAAAAAAQAA0A
AAMoeBfcrnCRSUmwUdZ5Mezb821hBJKecpKBiVLt+KbaG6szvZaf4zOKBAA7
}
   image create photo paper_yellowgreen \
       -format gif -data {
R0lGODlhEAANAMIAAP///4SEhP7/vsbGxgCAAACAQNLmAP///yH5BAEAAAcALAAAAAAQAA0A
AAMoeBfcrnCZSU2wUdZ5Mezb821hBJKecpKBiVLt+KbaG6szvZaf4zOKBAA7
}
   image create photo paper_yellow \
       -format gif -data {
R0lGODlhEAANAMIAAP///4SEhPfhAMbGxv///////////////yH5BAEAAAMALAAAAAAQAA0A
AAMoOBPcrnCJSUWwUdZ5Mezb821hBJKecpKBiVLt+KbaG6szvZaf4zOKBAA7
}
   image create photo paper_orange \
       -format gif -data {
R0lGODlhEAANAMIAAP///4SEhOxzAMbGxv///////////////yH5BAEAAAMALAAAAAAQAA0A
AAMoOBPcrnCJSUWwUdZ5Mezb821hBJKecpKBiVLt+KbaG6szvZaf4zOKBAA7
}
   image create photo paper_red \
       -format gif -data {
R0lGODlhEAANAKEAAISEhOE+IbchAP///yH5BAEAAAMALAAAAAAQAA0AAAIo3ICpxhcPA5DN
xQcEZfPK1HQeFo4QUJqbIY4op66W+bJxPbuhwiNGAQA7
}


   set agecolors(dir) {ex folder}
   set agecolors(0) {ex}
   set agecolors(1) {ex paper}
   set agecolors(2) {ex paper_green paper_red}
   set agecolors(3) {ex paper_green paper_yellow paper_red}
   set agecolors(4) {ex paper_green paper_yellowgreen paper_orange paper_red}
   set agecolors(5) {ex paper_green paper_yellowgreen paper_yellow paper_orange paper_red}
}

proc midy {bbox} {
    return [expr ([lindex $bbox 1] + [lindex $bbox 3]) / 2]
}

proc search_canvas {} {
    global canvw selfile clickitem clickmode clicky
    set search $selfile
    resetsel
    update
    set str_items [$canvw find withtag strings]
    foreach idx $str_items {
	set name [$canvw itemcget $idx -text]
	if {[string match "*$search*" $name]} {
	    set selitem $idx
	    $canvw select from $idx 0
	    $canvw select to $idx end
	    set clickitem $idx
	    set clicky [midy [$canvw bbox $clickitem]]
	    set clickmode 1
	    selcurfile
	    addsecsel $idx
	}
    }
}

if {![info exists dirs]} {
    global onlyfiles ctxlines showsame
    set dirs {}
    set ok 1
    set argc [llength $argv]
    set moreopts 1
    for {set i 0} {$i < $argc} {incr i} {
	set arg [lindex $argv $i]
	if {$moreopts && [string range $arg 0 0] == "-"} {
	    switch -regexp -- $arg {
		"--" {
		    set moreopts 0
		}
		"-a|--all" {
		    set nukefiles {}
		}
		"-o|--only" {
		    incr i
		    if {$i < $argc} {
			lappend onlyfiles [lindex $argv $i]
			set nukefiles {}
		    } else {
			puts stderr "no argument given to $arg option"
			set ok 0
		    }
		}
		"-I|--ignore" {
		    incr i
		    if {$i < $argc} {
			ignorefile [lindex $argv $i]
		    } else {
			puts stderr "no argument given to $arg option"
			set ok 0
		    }
		}
		"-r|--rcs" {
		    if $nofilecmp {
			puts stderr "can't use $arg: libfilecmp.so.0.0 couldn't be loaded"
			set ok 0
		    }
		    set rcsflag "-rcs"
		}
		"-t|--bktag" {
		    if $nofilecmp {
			puts stderr "can't use $arg: libfilecmp.so.0.0 couldn't be loaded"
			set ok 0
		    }
		    set rcsflag "-bk"
		}
		"-c|--context" {
		    incr i
		    if {$i < $argc} {
			set ctxlines [lindex $argv $i]
		    } else {
			puts stderr "no argument given to $arg option"
			set ok 0
		    }
		}
		"-D|--maxdepth" {
		    incr i
		    if {$i < $argc} {
			set maxdepth [lindex $argv $i]
		    } else {
			puts stderr "no argument given to $arg option"
			set ok 0
		    }
		}
		"-b" { set diffbflag "-b" }
		"-w" { set diffwflag "-w" }
		"-B" { set diffBflag "-B" }
		"-i" { set diffiflag "-i" }
		"-d" { set diffdflag "-d" }
		"-S" { set showsame 1 }
		"-K" { set bitkeeper 1 }
		"-C" { set docvsignore 1 }
		"-h|--help" {
		    usage
		    exit 0
		}
		default {
		    puts stderr "unrecognized option $arg"
		    set ok 0
		}
	    }
	} elseif {$arg != {}} {
	    lappend dirs $arg
	}
    }
    if {$ok && [llength $dirs] == 0} {
        # Ask for directories if they weren't on the command line
        wm withdraw .
        NewDirDialog
        #set dirs [list $d0 $d1 $d2 $d3 $d4]
        # Prune out the empty entries
        set newlist {}
        for {set i 0} {$i < [llength $dirs]} {incr i} {
           if {[lindex $dirs $i] != {} } {
               lappend newlist [lindex $dirs $i]
           }
        }
        set dirs $newlist
        if {[llength $dirs] < 2 } {
            # Can't user error_popup here without de-iconifying . first
            tk_dialog .err "Error" "Need at least 2 directories" error 0 {OK}
	    set ok 0
        }
        wm deiconify .
    }
    if {!$ok} {exit 1}
    set newd {}
    foreach d $dirs {
	set x [glob -nocomplain $d]
	if {$x == {}} {
	    set x $d
	}
	set newd [concat $newd $x]
    }
    if {[llength $newd] > 5} {
	puts stderr "Error: more than 5 directories or files specified"
	exit 1
    }
    set dirs $newd
    set doit 1
}

if [info exists doit] {go}