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

#include "config.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#if !defined(sun) && !defined(B43) && !defined(ISC) && !defined(pyr) && !defined(_CX_UX)
# include <time.h>
#endif
#include <sys/time.h>
#ifndef sun
#include <sys/ioctl.h>
#endif


/* for solaris 2.1, Unixware (SVR4.2) and possibly others: */
#ifdef HAVE_STROPTS_H
# include <sys/stropts.h>
#endif

#include "screen.h"
#include "extern.h"
#include "logfile.h"
#include "layout.h"
#include "viewport.h"
#include "list_generic.h"

extern struct comm comms[];
extern char *rc_name;
extern char *RcFileName, *home;
extern char *BellString, *ActivityString, *ShellProg, *ShellArgs[];
extern char *hstatusstring, *captionstring, *timestring;
extern char *wliststr, *wlisttit;
extern int captionalways;
extern int queryflag;
extern char *hardcopydir, *screenlogfile, *logtstamp_string;
extern int log_flush, logtstamp_on, logtstamp_after;
extern char *VisualBellString;
extern int VBellWait, MsgWait, MsgMinWait, SilenceWait;
extern char SockPath[], *SockName;
extern int TtyMode, auto_detach, use_altscreen;
extern int iflag, maxwin;
extern int focusminwidth, focusminheight;
extern int use_hardstatus, visual_bell;
#ifdef COLOR
extern int attr2color[][4];
extern int nattr2color;
#endif
extern int hardstatusemu;
extern char *printcmd;
extern int default_startup;
extern int defobuflimit;
extern int defnonblock;
extern int defmousetrack;
extern int ZombieKey_destroy;
extern int ZombieKey_resurrect;
extern int ZombieKey_onerror;
#ifdef AUTO_NUKE
extern int defautonuke;
#endif
extern int separate_sids;
extern struct NewWindow nwin_default, nwin_undef;
#ifdef COPY_PASTE
extern int join_with_cr;
extern int compacthist;
extern int search_ic;
# ifdef FONT
extern int pastefont;
# endif
extern unsigned char mark_key_tab[];
extern char *BufferFile;
#endif
#ifdef POW_DETACH
extern char *BufferFile, *PowDetachString;
#endif
#ifdef MULTIUSER
extern struct acluser *EffectiveAclUser;	/* acl.c */
#endif
extern struct term term[];      /* terminal capabilities */
#ifdef MAPKEYS
extern char *kmapdef[];
extern char *kmapadef[];
extern char *kmapmdef[];
#endif
extern struct mchar mchar_so, mchar_null;
extern int renditions[];
extern int VerboseCreate;
#ifdef UTF8
extern char *screenencodings;
#endif
#ifdef DW_CHARS
extern int cjkwidth;
#endif

static int  CheckArgNum __P((int, char **));
static void ClearAction __P((struct action *));
static void SaveAction __P((struct action *, int, char **, int *));
static int  NextWindow __P((void));
static int  PreviousWindow __P((void));
static int  MoreWindows __P((void));
static void CollapseWindowlist __P((void));
static void LogToggle __P((int));
static void ShowInfo __P((void));
static void ShowDInfo __P((void));
static struct win *WindowByName __P((char *));
static int  WindowByNumber __P((char *));
static int  ParseOnOff __P((struct action *, int *));
static int  ParseWinNum __P((struct action *, int *));
static int  ParseBase __P((struct action *, char *, int *, int, char *));
static int  ParseNum1000 __P((struct action *, int *));
static char **SaveArgs __P((char **));
static int  IsNum __P((char *, int));
static void Colonfin __P((char *, int, char *));
static void InputSelect __P((void));
static void InputSetenv __P((char *));
static void InputAKA __P((void));
#ifdef MULTIUSER
static int  InputSu __P((struct win *, struct acluser **, char *));
static void su_fin __P((char *, int, char *));
#endif
static void AKAfin __P((char *, int, char *));
#ifdef COPY_PASTE
static void copy_reg_fn __P((char *, int, char *));
static void ins_reg_fn __P((char *, int, char *));
#endif
static void process_fn __P((char *, int, char *));
#ifdef PASSWORD
static void pass1 __P((char *, int, char *));
static void pass2 __P((char *, int, char *));
#endif
#ifdef POW_DETACH
static void pow_detach_fn __P((char *, int, char *));
#endif
static void digraph_fn __P((char *, int, char *));
static int  digraph_find __P((const char *buf));
static void confirm_fn __P((char *, int, char *));
static int  IsOnDisplay __P((struct win *));
static void ResizeRegions __P((char *, int));
static void ResizeFin __P((char *, int, char *));
static struct action *FindKtab __P((char *, int));
static void SelectFin __P((char *, int, char *));
static void SelectLayoutFin __P((char *, int, char *));
static void ShowWindowsX __P((char *));


extern struct layer *flayer;
extern struct display *display, *displays;
extern struct win *fore, *console_window, *windows;
extern struct acluser *users;
extern struct layout *layouts, *layout_attach, layout_last_marker;
extern struct layout *laytab[];

extern char screenterm[], HostName[], version[];
extern struct NewWindow nwin_undef, nwin_default;
extern struct LayFuncs WinLf, MarkLf;

extern const int Z0width, Z1width;
extern int real_uid, real_gid;

#ifdef NETHACK
extern int nethackflag;
#endif


extern struct win **wtab;

#ifdef MULTIUSER
extern char *multi;
extern int maxusercount;
#endif
char NullStr[] = "";

struct plop plop_tab[MAX_PLOP_DEFS];

#ifndef PTYMODE
# define PTYMODE 0622
#endif

int TtyMode = PTYMODE;
int hardcopy_append = 0;
int all_norefresh = 0;
#ifdef ZMODEM
int zmodem_mode = 0;
char *zmodem_sendcmd;
char *zmodem_recvcmd;
static char *zmodes[4] = {"off", "auto", "catch", "pass"};
#endif

int idletimo;
struct action idleaction;
#ifdef BLANKER_PRG
char **blankerprg;
#endif

struct action ktab[256 + KMAP_KEYS];	/* command key translation table */
struct kclass {
  struct kclass *next;
  char *name;
  struct action ktab[256 + KMAP_KEYS];
};
struct kclass *kclasses;

#ifdef MAPKEYS
struct action umtab[KMAP_KEYS+KMAP_AKEYS];
struct action dmtab[KMAP_KEYS+KMAP_AKEYS];
struct action mmtab[KMAP_KEYS+KMAP_AKEYS];
struct kmap_ext *kmap_exts;
int kmap_extn;
static int maptimeout = 300;
#endif

#ifndef MAX_DIGRAPH
#define MAX_DIGRAPH 512
#endif

struct digraph
{
  unsigned char d[2];
  int value;
};

/* digraph table taken from old vim and rfc1345 */
static struct digraph digraphs[MAX_DIGRAPH + 1] = {
    {{' ', ' '}, 160},	/* � */
    {{'N', 'S'}, 160},	/* � */
    {{'~', '!'}, 161},	/* � */
    {{'!', '!'}, 161},	/* � */
    {{'!', 'I'}, 161},	/* � */
    {{'c', '|'}, 162},	/* � */
    {{'c', 't'}, 162},	/* � */
    {{'$', '$'}, 163},	/* � */
    {{'P', 'd'}, 163},	/* � */
    {{'o', 'x'}, 164},	/* � */
    {{'C', 'u'}, 164},	/* � */
    {{'C', 'u'}, 164},	/* � */
    {{'E', 'u'}, 164},	/* � */
    {{'Y', '-'}, 165},	/* � */
    {{'Y', 'e'}, 165},	/* � */
    {{'|', '|'}, 166},	/* � */
    {{'B', 'B'}, 166},	/* � */
    {{'p', 'a'}, 167},	/* � */
    {{'S', 'E'}, 167},	/* � */
    {{'"', '"'}, 168},	/* � */
    {{'\'', ':'}, 168},	/* � */
    {{'c', 'O'}, 169},	/* � */
    {{'C', 'o'}, 169},	/* � */
    {{'a', '-'}, 170},	/* � */
    {{'<', '<'}, 171},	/* � */
    {{'-', ','}, 172},	/* � */
    {{'N', 'O'}, 172},	/* � */
    {{'-', '-'}, 173},	/* � */
    {{'r', 'O'}, 174},	/* � */
    {{'R', 'g'}, 174},	/* � */
    {{'-', '='}, 175},	/* � */
    {{'\'', 'm'}, 175},	/* � */
    {{'~', 'o'}, 176},	/* � */
    {{'D', 'G'}, 176},	/* � */
    {{'+', '-'}, 177},	/* � */
    {{'2', '2'}, 178},	/* � */
    {{'2', 'S'}, 178},	/* � */
    {{'3', '3'}, 179},	/* � */
    {{'3', 'S'}, 179},	/* � */
    {{'\'', '\''}, 180},	/* � */
    {{'j', 'u'}, 181},	/* � */
    {{'M', 'y'}, 181},	/* � */
    {{'p', 'p'}, 182},	/* � */
    {{'P', 'I'}, 182},	/* � */
    {{'~', '.'}, 183},	/* � */
    {{'.', 'M'}, 183},	/* � */
    {{',', ','}, 184},	/* � */
    {{'\'', ','}, 184},	/* � */
    {{'1', '1'}, 185},	/* � */
    {{'1', 'S'}, 185},	/* � */
    {{'o', '-'}, 186},	/* � */
    {{'>', '>'}, 187},	/* � */
    {{'1', '4'}, 188},	/* � */
    {{'1', '2'}, 189},	/* � */
    {{'3', '4'}, 190},	/* � */
    {{'~', '?'}, 191},	/* � */
    {{'?', '?'}, 191},	/* � */
    {{'?', 'I'}, 191},	/* � */
    {{'A', '`'}, 192},	/* � */
    {{'A', '!'}, 192},	/* � */
    {{'A', '\''}, 193},	/* � */
    {{'A', '^'}, 194},	/* � */
    {{'A', '>'}, 194},	/* � */
    {{'A', '~'}, 195},	/* � */
    {{'A', '?'}, 195},	/* � */
    {{'A', '"'}, 196},	/* � */
    {{'A', ':'}, 196},	/* � */
    {{'A', '@'}, 197},	/* � */
    {{'A', 'A'}, 197},	/* � */
    {{'A', 'E'}, 198},	/* � */
    {{'C', ','}, 199},	/* � */
    {{'E', '`'}, 200},	/* � */
    {{'E', '!'}, 200},	/* � */
    {{'E', '\''}, 201},	/* � */
    {{'E', '^'}, 202},	/* � */
    {{'E', '>'}, 202},	/* � */
    {{'E', '"'}, 203},	/* � */
    {{'E', ':'}, 203},	/* � */
    {{'I', '`'}, 204},	/* � */
    {{'I', '!'}, 204},	/* � */
    {{'I', '\''}, 205},	/* � */
    {{'I', '^'}, 206},	/* � */
    {{'I', '>'}, 206},	/* � */
    {{'I', '"'}, 207},	/* � */
    {{'I', ':'}, 207},	/* � */
    {{'D', '-'}, 208},	/* � */
    {{'N', '~'}, 209},	/* � */
    {{'N', '?'}, 209},	/* � */
    {{'O', '`'}, 210},	/* � */
    {{'O', '!'}, 210},	/* � */
    {{'O', '\''}, 211},	/* � */
    {{'O', '^'}, 212},	/* � */
    {{'O', '>'}, 212},	/* � */
    {{'O', '~'}, 213},	/* � */
    {{'O', '?'}, 213},	/* � */
    {{'O', '"'}, 214},	/* � */
    {{'O', ':'}, 214},	/* � */
    {{'/', '\\'}, 215},	/* � */
    {{'*', 'x'}, 215},	/* � */
    {{'O', '/'}, 216},	/* � */
    {{'U', '`'}, 217},	/* � */
    {{'U', '!'}, 217},	/* � */
    {{'U', '\''}, 218},	/* � */
    {{'U', '^'}, 219},	/* � */
    {{'U', '>'}, 219},	/* � */
    {{'U', '"'}, 220},	/* � */
    {{'U', ':'}, 220},	/* � */
    {{'Y', '\''}, 221},	/* � */
    {{'I', 'p'}, 222},	/* � */
    {{'T', 'H'}, 222},	/* � */
    {{'s', 's'}, 223},	/* � */
    {{'s', '"'}, 223},	/* � */
    {{'a', '`'}, 224},	/* � */
    {{'a', '!'}, 224},	/* � */
    {{'a', '\''}, 225},	/* � */
    {{'a', '^'}, 226},	/* � */
    {{'a', '>'}, 226},	/* � */
    {{'a', '~'}, 227},	/* � */
    {{'a', '?'}, 227},	/* � */
    {{'a', '"'}, 228},	/* � */
    {{'a', ':'}, 228},	/* � */
    {{'a', 'a'}, 229},	/* � */
    {{'a', 'e'}, 230},	/* � */
    {{'c', ','}, 231},	/* � */
    {{'e', '`'}, 232},	/* � */
    {{'e', '!'}, 232},	/* � */
    {{'e', '\''}, 233},	/* � */
    {{'e', '^'}, 234},	/* � */
    {{'e', '>'}, 234},	/* � */
    {{'e', '"'}, 235},	/* � */
    {{'e', ':'}, 235},	/* � */
    {{'i', '`'}, 236},	/* � */
    {{'i', '!'}, 236},	/* � */
    {{'i', '\''}, 237},	/* � */
    {{'i', '^'}, 238},	/* � */
    {{'i', '>'}, 238},	/* � */
    {{'i', '"'}, 239},	/* � */
    {{'i', ':'}, 239},	/* � */
    {{'d', '-'}, 240},	/* � */
    {{'n', '~'}, 241},	/* � */
    {{'n', '?'}, 241},	/* � */
    {{'o', '`'}, 242},	/* � */
    {{'o', '!'}, 242},	/* � */
    {{'o', '\''}, 243},	/* � */
    {{'o', '^'}, 244},	/* � */
    {{'o', '>'}, 244},	/* � */
    {{'o', '~'}, 245},	/* � */
    {{'o', '?'}, 245},	/* � */
    {{'o', '"'}, 246},	/* � */
    {{'o', ':'}, 246},	/* � */
    {{':', '-'}, 247},	/* � */
    {{'o', '/'}, 248},	/* � */
    {{'u', '`'}, 249},	/* � */
    {{'u', '!'}, 249},	/* � */
    {{'u', '\''}, 250},	/* � */
    {{'u', '^'}, 251},	/* � */
    {{'u', '>'}, 251},	/* � */
    {{'u', '"'}, 252},	/* � */
    {{'u', ':'}, 252},	/* � */
    {{'y', '\''}, 253},	/* � */
    {{'i', 'p'}, 254},	/* � */
    {{'t', 'h'}, 254},	/* � */
    {{'y', '"'}, 255},	/* � */
    {{'y', ':'}, 255},	/* � */
    {{'"', '['}, 196},	/* � */
    {{'"', '\\'}, 214},	/* � */
    {{'"', ']'}, 220},	/* � */
    {{'"', '{'}, 228},	/* � */
    {{'"', '|'}, 246},	/* � */
    {{'"', '}'}, 252},	/* � */
    {{'"', '~'}, 223}	/* � */
};

#define RESIZE_FLAG_H 1
#define RESIZE_FLAG_V 2
#define RESIZE_FLAG_L 4

static char *resizeprompts[] = {
  "resize # lines: ",
  "resize -h # lines: ",
  "resize -v # lines: ",
  "resize -b # lines: ",
  "resize -l # lines: ",
  "resize -l -h # lines: ",
  "resize -l -v # lines: ",
  "resize -l -b # lines: ",
};


static int
parse_input_int(buf, len, val)
const char *buf;
int len;
int *val;
{
  int x = 0, i;
  if (len >= 1 && ((*buf == 'U' && buf[1] == '+') || (*buf == '0' && (buf[1] == 'x' || buf[1] == 'X'))))
    {
      x = 0;
      for (i = 2; i < len; i++)
	{
	  if (buf[i] >= '0' && buf[i] <= '9')
	    x = x * 16 | (buf[i] - '0');
	  else if (buf[i] >= 'a' && buf[i] <= 'f')
	    x = x * 16 | (buf[i] - ('a' - 10));
	  else if (buf[i] >= 'A' && buf[i] <= 'F')
	    x = x * 16 | (buf[i] - ('A' - 10));
	  else
	    return 0;
	}
    }
  else if (buf[0] == '0')
    {
      x = 0;
      for (i = 1; i < len; i++)
	{
	  if (buf[i] < '0' || buf[i] > '7')
	    return 0;
	  x = x * 8 | (buf[i] - '0');
	}
    }
  else
    return 0;
  *val = x;
  return 1;
}

char *noargs[1];

int enter_window_name_mode = 0;

void
InitKeytab()
{
  register unsigned int i;
#ifdef MAPKEYS
  char *argarr[2];
#endif

  for (i = 0; i < sizeof(ktab)/sizeof(*ktab); i++)
    {
      ktab[i].nr = RC_ILLEGAL;
      ktab[i].args = noargs;
      ktab[i].argl = 0;
    }
#ifdef MAPKEYS
  for (i = 0; i < KMAP_KEYS+KMAP_AKEYS; i++)
    {
      umtab[i].nr = RC_ILLEGAL;
      umtab[i].args = noargs;
      umtab[i].argl = 0;
      dmtab[i].nr = RC_ILLEGAL;
      dmtab[i].args = noargs;
      dmtab[i].argl = 0;
      mmtab[i].nr = RC_ILLEGAL;
      mmtab[i].args = noargs;
      mmtab[i].argl = 0;
    }
  argarr[1] = 0;
  for (i = 0; i < NKMAPDEF; i++)
    {
      if (i + KMAPDEFSTART < T_CAPS)
	continue;
      if (i + KMAPDEFSTART >= T_CAPS + KMAP_KEYS)
	continue;
      if (kmapdef[i] == 0)
	continue;
      argarr[0] = kmapdef[i];
      SaveAction(dmtab + i + (KMAPDEFSTART - T_CAPS), RC_STUFF, argarr, 0);
    }
  for (i = 0; i < NKMAPADEF; i++)
    {
      if (i + KMAPADEFSTART < T_CURSOR)
	continue;
      if (i + KMAPADEFSTART >= T_CURSOR + KMAP_AKEYS)
	continue;
      if (kmapadef[i] == 0)
	continue;
      argarr[0] = kmapadef[i];
      SaveAction(dmtab + i + (KMAPADEFSTART - T_CURSOR + KMAP_KEYS), RC_STUFF, argarr, 0);
    }
  for (i = 0; i < NKMAPMDEF; i++)
    {
      if (i + KMAPMDEFSTART < T_CAPS)
	continue;
      if (i + KMAPMDEFSTART >= T_CAPS + KMAP_KEYS)
	continue;
      if (kmapmdef[i] == 0)
	continue;
      argarr[0] = kmapmdef[i];
      argarr[1] = 0;
      SaveAction(mmtab + i + (KMAPMDEFSTART - T_CAPS), RC_STUFF, argarr, 0);
    }
#endif

  ktab['h'].nr = RC_HARDCOPY;
#ifdef BSDJOBS
  ktab['z'].nr = ktab[Ctrl('z')].nr = RC_SUSPEND;
#endif
  ktab['c'].nr = ktab[Ctrl('c')].nr = RC_SCREEN;
  ktab[' '].nr = ktab[Ctrl(' ')].nr =
    ktab['n'].nr = ktab[Ctrl('n')].nr = RC_NEXT;
  ktab['N'].nr = RC_NUMBER;
  ktab[Ctrl('h')].nr = ktab[0177].nr = ktab['p'].nr = ktab[Ctrl('p')].nr = RC_PREV;
  ktab['k'].nr = ktab[Ctrl('k')].nr = RC_KILL;
  ktab['l'].nr = ktab[Ctrl('l')].nr = RC_REDISPLAY;
  ktab['w'].nr = ktab[Ctrl('w')].nr = RC_WINDOWS;
  ktab['v'].nr = RC_VERSION;
  ktab[Ctrl('v')].nr = RC_DIGRAPH;
  ktab['q'].nr = ktab[Ctrl('q')].nr = RC_XON;
  ktab['s'].nr = ktab[Ctrl('s')].nr = RC_XOFF;
  ktab['t'].nr = ktab[Ctrl('t')].nr = RC_TIME;
  ktab['i'].nr = ktab[Ctrl('i')].nr = RC_INFO;
  ktab['m'].nr = ktab[Ctrl('m')].nr = RC_LASTMSG;
  ktab['A'].nr = RC_TITLE;
#if defined(UTMPOK) && defined(LOGOUTOK)
  ktab['L'].nr = RC_LOGIN;
#endif
  ktab[','].nr = RC_LICENSE;
  ktab['W'].nr = RC_WIDTH;
  ktab['.'].nr = RC_DUMPTERMCAP;
  ktab[Ctrl('\\')].nr = RC_QUIT;
#ifdef DETACH
  ktab['d'].nr = ktab[Ctrl('d')].nr = RC_DETACH;
# ifdef POW_DETACH
  ktab['D'].nr = RC_POW_DETACH;
# endif
#endif
  ktab['r'].nr = ktab[Ctrl('r')].nr = RC_WRAP;
  ktab['f'].nr = ktab[Ctrl('f')].nr = RC_FLOW;
  ktab['C'].nr = RC_CLEAR;
  ktab['Z'].nr = RC_RESET;
  ktab['H'].nr = RC_LOG;
  ktab['M'].nr = RC_MONITOR;
  ktab['?'].nr = RC_HELP;
#ifdef MULTI
  ktab['*'].nr = RC_DISPLAYS;
#endif
  {
    char *args[2];
    args[0] = "-";
    args[1] = NULL;
    SaveAction(ktab + '-', RC_SELECT, args, 0);
  }
  for (i = 0; i < ((maxwin && maxwin < 10) ? maxwin : 10); i++)
    {
      char *args[2], arg1[10];
      args[0] = arg1;
      args[1] = 0;
      sprintf(arg1, "%d", i);
      SaveAction(ktab + '0' + i, RC_SELECT, args, 0);
    }
  ktab['\''].nr = RC_SELECT; /* calling a window by name */
  {
    char *args[2];
    args[0] = "-b";
    args[1] = 0;
    SaveAction(ktab + '"', RC_WINDOWLIST, args, 0);
  }
  ktab[Ctrl('G')].nr = RC_VBELL;
  ktab[':'].nr = RC_COLON;
#ifdef COPY_PASTE
  ktab['['].nr = ktab[Ctrl('[')].nr = RC_COPY;
  {
    char *args[2];
    args[0] = ".";
    args[1] = 0;
    SaveAction(ktab + ']', RC_PASTE, args, 0);
    SaveAction(ktab + Ctrl(']'), RC_PASTE, args, 0);
  }
  ktab['{'].nr = RC_HISTORY;
  ktab['}'].nr = RC_HISTORY;
  ktab['>'].nr = RC_WRITEBUF;
  ktab['<'].nr = RC_READBUF;
  ktab['='].nr = RC_REMOVEBUF;
#endif
#ifdef POW_DETACH
  ktab['D'].nr = RC_POW_DETACH;
#endif
#ifdef LOCK
  ktab['x'].nr = ktab[Ctrl('x')].nr = RC_LOCKSCREEN;
#endif
  ktab['b'].nr = ktab[Ctrl('b')].nr = RC_BREAK;
  ktab['B'].nr = RC_POW_BREAK;
  ktab['_'].nr = RC_SILENCE;
  ktab['S'].nr = RC_SPLIT;
  ktab['Q'].nr = RC_ONLY;
  ktab['X'].nr = RC_REMOVE;
  ktab['F'].nr = RC_FIT;
  ktab['\t'].nr = RC_FOCUS;
  {
    char *args[2];
    args[0] = "prev";
    args[1] = 0;
    SaveAction(ktab + T_BACKTAB - T_CAPS + 256, RC_FOCUS, args, 0);
  }
  {
    char *args[2];
    args[0] = "-v";
    args[1] = 0;
    SaveAction(ktab + '|', RC_SPLIT, args, 0);
  }
  /* These come last; they may want overwrite others: */
  if (DefaultEsc >= 0)
    {
      ClearAction(&ktab[DefaultEsc]);
      ktab[DefaultEsc].nr = RC_OTHER;
    }
  if (DefaultMetaEsc >= 0)
    {
      ClearAction(&ktab[DefaultMetaEsc]);
      ktab[DefaultMetaEsc].nr = RC_META;
    }

  idleaction.nr = RC_BLANKER;
  idleaction.args = noargs;
  idleaction.argl = 0;
}

static struct action *
FindKtab(class, create)
char *class;
int create;
{
  struct kclass *kp, **kpp;
  int i;

  if (class == 0)
    return ktab;
  for (kpp = &kclasses; (kp = *kpp) != 0; kpp = &kp->next)
    if (!strcmp(kp->name, class))
      break;
  if (kp == 0)
    {
      if (!create)
	return 0;
      if (strlen(class) > 80)
	{
	  Msg(0, "Command class name too long.");
	  return 0;
	}
      kp = malloc(sizeof(*kp));
      if (kp == 0)
	{
	  Msg(0, "%s", strnomem);
	  return 0;
	}
      kp->name = SaveStr(class);
      for (i = 0; i < (int)(sizeof(kp->ktab)/sizeof(*kp->ktab)); i++)
	{
	  kp->ktab[i].nr = RC_ILLEGAL;
	  kp->ktab[i].args = noargs;
	  kp->ktab[i].argl = 0;
	  kp->ktab[i].quiet = 0;
	}
      kp->next = 0;
      *kpp = kp;
    }
  return kp->ktab;
}

static void
ClearAction(act)
struct action *act;
{
  char **p;

  if (act->nr == RC_ILLEGAL)
    return;
  act->nr = RC_ILLEGAL;
  if (act->args == noargs)
    return;
  for (p = act->args; *p; p++)
    free(*p);
  free((char *)act->args);
  act->args = noargs;
  act->argl = 0;
}

/*
 * ProcessInput: process input from display and feed it into
 * the layer on canvas D_forecv.
 */

#ifdef MAPKEYS

/*
 *  This ProcessInput just does the keybindings and passes
 *  everything else on to ProcessInput2.
 */

void
ProcessInput(ibuf, ilen)
char *ibuf;
int ilen;
{
  int ch, slen;
  unsigned char *s, *q;
  int i, l;
  char *p;

  debug1("ProcessInput: %d bytes\n", ilen);
  if (display == 0 || ilen == 0)
    return;
  if (D_seql)
    evdeq(&D_mapev);
  slen = ilen;
  s = (unsigned char *)ibuf;
  while (ilen-- > 0)
    {
      ch = *s++;
      if (D_dontmap || !D_nseqs)
	{
          D_dontmap = 0;
	  continue;
	}
      for (;;)
	{
	  debug3("cmp %c %c[%d]\n", ch, *D_seqp, D_seqp - D_kmaps);
	  if (*D_seqp != ch)
	    {
	      l = D_seqp[D_seqp[-D_seql-1] + 1];
	      if (l)
		{
		  D_seqp += l * 2 + 4;
		  debug1("miss %d\n", D_seqp - D_kmaps);
		  continue;
		}
	      debug("complete miss\n");
	      D_mapdefault = 0;
	      l = D_seql;
	      p = (char *)D_seqp - l;
	      D_seql = 0;
	      D_seqp = D_kmaps + 3;
	      if (l == 0)
		break;
	      if ((q = D_seqh) != 0)
		{
		  D_seqh = 0;
		  i = q[0] << 8 | q[1];
		  i &= ~KMAP_NOTIMEOUT;
		  debug1("Mapping former hit #%d - ", i);
		  debug2("%d(%s) - ", q[2], q + 3);
		  if (StuffKey(i))
		    ProcessInput2((char *)q + 3, q[2]);
		  if (display == 0)
		    return;
		  l -= q[2];
		  p += q[2];
		}
	      else
	        D_dontmap = 1;
	      debug1("flush old %d\n", l);
	      ProcessInput(p, l);
	      if (display == 0)
		return;
	      evdeq(&D_mapev);
	      continue;
	    }
	  if (D_seql++ == 0)
	    {
	      /* Finish old stuff */
	      slen -= ilen + 1;
	      debug1("finish old %d\n", slen);
	      if (slen)
	        ProcessInput2(ibuf, slen);
	      if (display == 0)
		return;
	      D_seqh = 0;
	    }
	  ibuf = (char *)s;
	  slen = ilen;
	  D_seqp++;
	  l = D_seql;
	  debug2("length am %d, want %d\n", l, D_seqp[-l - 1]);
	  if (l == D_seqp[-l - 1])
	    {
	      if (D_seqp[l] != l)
		{
		  q = D_seqp + 1 + l;
		  if (D_kmaps + D_nseqs > q && q[2] > l && !bcmp(D_seqp - l, q + 3, l))
		    {
		      debug1("have another mapping (%s), delay execution\n", q + 3);
		      D_seqh = D_seqp - 3 - l;
		      D_seqp = q + 3 + l;
		      break;
		    }
		}
	      i = D_seqp[-l - 3] << 8 | D_seqp[-l - 2];
	      i &= ~KMAP_NOTIMEOUT;
	      debug1("Mapping #%d - ", i);
	      p = (char *)D_seqp - l;
	      debug2("%d(%s) - ", l, p);
	      D_seql = 0;
	      D_seqp = D_kmaps + 3;
	      D_seqh = 0;
	      if (StuffKey(i))
		ProcessInput2(p, l);
	      if (display == 0)
		return;
	    }
	  break;
	}
    }
  if (D_seql)
    {
      debug("am in sequence -> check for timeout\n");
      l = D_seql;
      for (s = D_seqp; ; s += i * 2 + 4)
	{
	  if (s[-l-3] & KMAP_NOTIMEOUT >> 8)
	    break;
	  if ((i = s[s[-l-1] + 1]) == 0)
	    {
	      SetTimeout(&D_mapev, maptimeout);
	      evenq(&D_mapev);
	      break;
	    }
	}
    }
  ProcessInput2(ibuf, slen);
}

#else
# define ProcessInput2 ProcessInput
#endif


/*
 *  Here only the screen escape commands are handled.
 */

void
ProcessInput2(ibuf, ilen)
char *ibuf;
int ilen;
{
  char *s;
  int ch, slen;
  struct action *ktabp;

  debug1("ProcessInput2: %d bytes\n", ilen);
  while (ilen && display)
    {
      debug1(" - ilen now %d bytes\n", ilen);
      flayer = D_forecv->c_layer;
      fore = D_fore;
      slen = ilen;
      s = ibuf;
      if (!D_ESCseen)
	{
	  while (ilen > 0)
	    {
	      if ((unsigned char)*s++ == D_user->u_Esc)
		break;
	      ilen--;
	    }
	  slen -= ilen;
	  if (slen)
	    DoProcess(fore, &ibuf, &slen, 0);
	  if (--ilen == 0)
	    {
	      D_ESCseen = ktab;
	      WindowChanged(fore, 'E');
	    }
	}
      if (ilen <= 0)
        return;
      ktabp = D_ESCseen ? D_ESCseen : ktab;
      if (D_ESCseen)
        {
          D_ESCseen = 0;
          WindowChanged(fore, 'E');
        }
      ch = (unsigned char)*s;

      /* 
       * As users have different esc characters, but a common ktab[],
       * we fold back the users esc and meta-esc key to the Default keys
       * that can be looked up in the ktab[]. grmbl. jw.
       * XXX: make ktab[] a per user thing.
       */
      if (ch == D_user->u_Esc) 
        ch = DefaultEsc;
      else if (ch == D_user->u_MetaEsc) 
        ch = DefaultMetaEsc;

      if (ch >= 0)
        DoAction(&ktabp[ch], ch);
      ibuf = (char *)(s + 1);
      ilen--;
    }
}

void
DoProcess(p, bufp, lenp, pa)
struct win *p;
char **bufp;
int *lenp;
struct paster *pa;
{
  int oldlen;
  struct display *d = display;

#ifdef COPY_PASTE
  /* XXX -> PasteStart */
  if (pa && *lenp > 1 && p && p->w_slowpaste)
    {
      /* schedule slowpaste event */
      SetTimeout(&p->w_paster.pa_slowev, p->w_slowpaste);
      evenq(&p->w_paster.pa_slowev);
      return;
    }
#endif
  while (flayer && *lenp)
    {
#ifdef COPY_PASTE
      if (!pa && p && p->w_paster.pa_pastelen && flayer == p->w_paster.pa_pastelayer)
	{
	  debug("layer is busy - beep!\n");
	  WBell(p, visual_bell);
	  *bufp += *lenp;
	  *lenp = 0;
	  display = d;
	  return;
	}
#endif
      oldlen = *lenp;
      LayProcess(bufp, lenp);
#ifdef COPY_PASTE
      if (pa && !pa->pa_pastelayer)
	break;		/* flush rest of paste */
#endif
      if (*lenp == oldlen)
	{
	  if (pa)
	    {
	      display = d;
	      return;
	    }
	  /* We're full, let's beep */
	  debug("layer is full - beep!\n");
	  WBell(p, visual_bell);
	  break;
	}
    }
  *bufp += *lenp;
  *lenp = 0;
  display = d;
#ifdef COPY_PASTE
  if (pa && pa->pa_pastelen == 0)
    FreePaster(pa);
#endif
}

int
FindCommnr(str)
const char *str;
{
  int x, m, l = 0, r = RC_LAST;
  while (l <= r)
    {
      m = (l + r) / 2;
      x = strcmp(str, comms[m].name);
      if (x > 0)
	l = m + 1;
      else if (x < 0)
	r = m - 1;
      else
	return m;
    }
  return RC_ILLEGAL;
}

static int
CheckArgNum(nr, args)
int nr;
char **args;
{
  int i, n;
  static char *argss[] = {"no", "one", "two", "three", "four", "OOPS"};
  static char *orformat[] = 
    {
      "%s: %s: %s argument%s required",
      "%s: %s: %s or %s argument%s required",
      "%s: %s: %s, %s or %s argument%s required",
      "%s: %s: %s, %s, %s or %s argument%s required"
    };

  n = comms[nr].flags & ARGS_MASK;
  for (i = 0; args[i]; i++)
    ;
  if (comms[nr].flags & ARGS_ORMORE)
    {
      if (i < n)
	{
	  Msg(0, "%s: %s: at least %s argument%s required", 
	      rc_name, comms[nr].name, argss[n], n != 1 ? "s" : "");
	  return -1;
	}
    }
  else if ((comms[nr].flags & ARGS_PLUS1) && 
           (comms[nr].flags & ARGS_PLUS2) &&
	   (comms[nr].flags & ARGS_PLUS3))
    {
      if (i != n && i != n + 1 && i != n + 2 && i != n + 3)
        {
	  Msg(0, orformat[3], rc_name, comms[nr].name, argss[n], 
	      argss[n + 1], argss[n + 2], argss[n + 3], "");
	  return -1;
	}
    }
  else if ((comms[nr].flags & ARGS_PLUS1) &&
           (comms[nr].flags & ARGS_PLUS2))
    {
      if (i != n && i != n + 1 && i != n + 2)
	{
	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n], 
	      argss[n + 1], argss[n + 2], "");
          return -1;
	}
    }
  else if ((comms[nr].flags & ARGS_PLUS1) &&
           (comms[nr].flags & ARGS_PLUS3))
    {
      if (i != n && i != n + 1 && i != n + 3)
        {
	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n], 
	      argss[n + 1], argss[n + 3], "");
	  return -1;
	}
    }
  else if ((comms[nr].flags & ARGS_PLUS2) &&
           (comms[nr].flags & ARGS_PLUS3))
    {
      if (i != n && i != n + 2 && i != n + 3)
        {
	  Msg(0, orformat[2], rc_name, comms[nr].name, argss[n], 
	      argss[n + 2], argss[n + 3], "");
	  return -1;
	}
    }
  else if (comms[nr].flags & ARGS_PLUS1)
    {
      if (i != n && i != n + 1)
        {
	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n], 
	      argss[n + 1], n != 0 ? "s" : "");
	  return -1;
	}
    }
  else if (comms[nr].flags & ARGS_PLUS2)
    {
      if (i != n && i != n + 2)
        {
	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n], 
	      argss[n + 2], "s");
	  return -1;
	}
    }
  else if (comms[nr].flags & ARGS_PLUS3)
    {
      if (i != n && i != n + 3)
        {
	  Msg(0, orformat[1], rc_name, comms[nr].name, argss[n], 
	      argss[n + 3], "");
	  return -1;
	}
    }
  else if (i != n)
    {
      Msg(0, orformat[0], rc_name, comms[nr].name, argss[n], n != 1 ? "s" : "");
      return -1;
    }
  return i;
}

static void
StuffFin(buf, len, data)
char *buf;
int len;
char *data;
{
  if (!flayer)
    return;
  while(len)
    LayProcess(&buf, &len);
}

/* If the command is not 'quieted', then use Msg to output the message. If it's a remote
 * query, then Msg takes care of also outputting the message to the querying client.
 *
 * If we want the command to be quiet, and it's a remote query, then use QueryMsg so that
 * the response does go back to the querying client.
 *
 * If the command is quieted, and it's not a remote query, then just don't print the message.
 */
#define OutputMsg	(!act->quiet ? Msg : queryflag >= 0 ? QueryMsg : Dummy)

/*ARGSUSED*/
void
DoAction(act, key)
struct action *act;
int key;
{
  int nr = act->nr;
  char **args = act->args;
  int *argl = act->argl;
  struct win *p;
  int argc, i, n, msgok;
  char *s;
  char ch;
  struct display *odisplay = display;
  struct acluser *user;

  user = display ? D_user : users;
  if (nr == RC_ILLEGAL)
    {
      debug1("key '%c': No action\n", key);
      return;
    }
  n = comms[nr].flags;
  /* Commands will have a CAN_QUERY flag, depending on whether they have
   * something to return on a query. For example, 'windows' can return a result,
   * but 'other' cannot.
   * If some command causes an error, then it should reset queryflag to -1, so that
   * the process requesting the query can be notified that an error happened.
   */
  if (!(n & CAN_QUERY) && queryflag >= 0)
    {
      /* Query flag is set, but this command cannot be queried. */
      OutputMsg(0, "%s command cannot be queried.", comms[nr].name);
      queryflag = -1;
      return;
    }
  if ((n & NEED_DISPLAY) && display == 0)
    {
      OutputMsg(0, "%s: %s: display required", rc_name, comms[nr].name);
      queryflag = -1;
      return;
    }
  if ((n & NEED_FORE) && fore == 0)
    {
      OutputMsg(0, "%s: %s: window required", rc_name, comms[nr].name);
      queryflag = -1;
      return;
    }
  if ((n & NEED_LAYER) && flayer == 0)
    {
      OutputMsg(0, "%s: %s: display or window required", rc_name, comms[nr].name);
      queryflag = -1;
      return;
    }
  if ((argc = CheckArgNum(nr, args)) < 0)
    return;
#ifdef MULTIUSER
  if (display)
    {
      if (AclCheckPermCmd(D_user, ACL_EXEC, &comms[nr]))
        {
	  OutputMsg(0, "%s: %s: permission denied (user %s)", 
	      rc_name, comms[nr].name, (EffectiveAclUser ? EffectiveAclUser : D_user)->u_name);
	  queryflag = -1;
	  return;
	}
    }
#endif /* MULTIUSER */

  msgok = display && !*rc_name;
  switch(nr)
    {
    case RC_SELECT:
      if (!*args)
        InputSelect();
      else if (args[0][0] == '-' && !args[0][1])
	{
	  SetForeWindow((struct win *)0);
	  Activate(0);
	}
      else if (args[0][0] == '.' && !args[0][1])
	{
	  if (!fore)
	    {
	      OutputMsg(0, "select . needs a window");
	      queryflag = -1;
	    }
	  else
	    {
	      SetForeWindow(fore);
	      Activate(0);
	    }
	}
      else if (ParseWinNum(act, &n) == 0)
        SwitchWindow(n);
      else if (queryflag >= 0)
	queryflag = -1;	/* ParseWinNum already prints out an appropriate error message. */
      break;
#ifdef AUTO_NUKE
    case RC_DEFAUTONUKE:
      if (ParseOnOff(act, &defautonuke) == 0 && msgok)
	OutputMsg(0, "Default autonuke turned %s", defautonuke ? "on" : "off");
      if (display && *rc_name)
	D_auto_nuke = defautonuke;
      break;
    case RC_AUTONUKE:
      if (ParseOnOff(act, &D_auto_nuke) == 0 && msgok)
	OutputMsg(0, "Autonuke turned %s", D_auto_nuke ? "on" : "off");
      break;
#endif
    case RC_DEFOBUFLIMIT:
      if (ParseNum(act, &defobuflimit) == 0 && msgok)
	OutputMsg(0, "Default limit set to %d", defobuflimit);
      if (display && *rc_name)
	{
	  D_obufmax = defobuflimit;
	  D_obuflenmax = D_obuflen - D_obufmax;
	}
      break;
    case RC_OBUFLIMIT:
      if (*args == 0)
	OutputMsg(0, "Limit is %d, current buffer size is %d", D_obufmax, D_obuflen);
      else if (ParseNum(act, &D_obufmax) == 0 && msgok)
	OutputMsg(0, "Limit set to %d", D_obufmax);
      D_obuflenmax = D_obuflen - D_obufmax;
      break;
    case RC_DUMPTERMCAP:
      WriteFile(user, (char *)0, DUMP_TERMCAP);
      break;
    case RC_HARDCOPY:
      {
	int mode = DUMP_HARDCOPY;
	char *file = NULL;

	if (args[0])
	  {
	    if (!strcmp(*args, "-h"))
	      {
		mode = DUMP_SCROLLBACK;
		file = args[1];
	      }
	    else if (!strcmp(*args, "--") && args[1])
	      file = args[1];
	    else
	      file = args[0];
	  }

	if (args[0] && file == args[0] && args[1])
	  {
	    OutputMsg(0, "%s: hardcopy: too many arguments", rc_name);
	    break;
	  }
	WriteFile(user, file, mode);
      }
      break;
    case RC_DEFLOG:
      (void)ParseOnOff(act, &nwin_default.Lflag);
      break;
    case RC_LOG:
      n = fore->w_log ? 1 : 0;
      ParseSwitch(act, &n);
      LogToggle(n);
      break;
#ifdef BSDJOBS
    case RC_SUSPEND:
      Detach(D_STOP);
      break;
#endif
    case RC_NEXT:
      if (MoreWindows())
	SwitchWindow(NextWindow());
      break;
    case RC_PREV:
      if (MoreWindows())
	SwitchWindow(PreviousWindow());
      break;
    case RC_KILL:
      {
	char *name;

	if (key >= 0)
	  {
#ifdef PSEUDOS
	    Input(fore->w_pwin ? "Really kill this filter [y/n]" : "Really kill this window [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_KILL);
#else
	    Input("Really kill this window [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_KILL);
#endif
	    break;
	  }
	n = fore->w_number;
#ifdef PSEUDOS
	if (fore->w_pwin)
	  {
	    FreePseudowin(fore);
	    OutputMsg(0, "Filter removed.");
	    break;
	  }
#endif
	name = SaveStr(fore->w_title);
	KillWindow(fore);
	OutputMsg(0, "Window %d (%s) killed.", n, name);
	if (name)
	  free(name);
	break;
      }
    case RC_QUIT:
      if (key >= 0)
	{
	  Input("Really quit and kill all your windows [y/n]", 1, INP_RAW, confirm_fn, NULL, RC_QUIT);
	  break;
	}
      Finit(0);
      /* NOTREACHED */
#ifdef DETACH
    case RC_DETACH:
      if (*args && !strcmp(*args, "-h"))
        Hangup();
      else
        Detach(D_DETACH);
      break;
# ifdef POW_DETACH
    case RC_POW_DETACH:
      if (key >= 0)
	{
	  static char buf[2];

	  buf[0] = key;
	  Input(buf, 1, INP_RAW, pow_detach_fn, NULL, 0);
	}
      else
        Detach(D_POWER); /* detach and kill Attacher's parent */
      break;
# endif
#endif
    case RC_DEBUG:
#ifdef DEBUG
      if (!*args)
        {
	  if (dfp)
	    OutputMsg(0, "debugging info is written to %s/", DEBUGDIR);
	  else
	    OutputMsg(0, "debugging is currently off. Use 'debug on' to enable.");
	  break;
	}
      if (dfp)
        {
	  debug("debug: closing debug file.\n");
	  fflush(dfp);
	  fclose(dfp);
	  dfp = NULL;
	}
      if (strcmp("off", *args))
        opendebug(0, 1);
# ifdef SIG_NODEBUG
      else if (display)
        kill(D_userpid, SIG_NODEBUG);	/* a one shot item, but hey... */
# endif /* SIG_NODEBUG */
#else
      if (*args == 0 || strcmp("off", *args))
        OutputMsg(0, "Sorry, screen was compiled without -DDEBUG option.");
#endif
      break;
#ifdef ZMODEM
    case RC_ZMODEM:
      if (*args && !strcmp(*args, "sendcmd"))
	{
	  if (args[1])
	    {
	      free(zmodem_sendcmd);
	      zmodem_sendcmd = SaveStr(args[1]);
	    }
	  if (msgok)
	    OutputMsg(0, "zmodem sendcmd: %s", zmodem_sendcmd);
	  break;
	}
      if (*args && !strcmp(*args, "recvcmd"))
	{
	  if (args[1])
	    {
	      free(zmodem_recvcmd);
	      zmodem_recvcmd = SaveStr(args[1]);
	    }
	  if (msgok)
	    OutputMsg(0, "zmodem recvcmd: %s", zmodem_recvcmd);
	  break;
	}
      if (*args)
	{
	  for (i = 0; i < 4; i++)
	    if (!strcmp(zmodes[i], *args))
	      break;
	  if (i == 4 && !strcmp(*args, "on"))
	    i = 1;
	  if (i == 4)
	    {
	      OutputMsg(0, "usage: zmodem off|auto|catch|pass");
	      break;
	    }
	  zmodem_mode = i;
	}
      if (msgok)
	OutputMsg(0, "zmodem mode is %s", zmodes[zmodem_mode]);
      break;
#endif
    case RC_UNBINDALL:
      {
        register unsigned int i;

        for (i = 0; i < sizeof(ktab)/sizeof(*ktab); i++)
	  ClearAction(&ktab[i]);
        OutputMsg(0, "Unbound all keys." );
        break;
      }
    case RC_ZOMBIE:
      {
        if (!(s = *args))
          {
            ZombieKey_destroy = 0;
            break;
          }
	if (*argl == 0 || *argl > 2)
	  {
	    OutputMsg(0, "%s:zombie: one or two characters expected.", rc_name);
	    break;
	  }
	if (args[1])
	  {
	    if (!strcmp(args[1], "onerror"))
	      {
		ZombieKey_onerror = 1;
	      } else {
		OutputMsg(0, "usage: zombie [keys [onerror]]");
	    	break;
	      }
	  } else
	    ZombieKey_onerror = 0;
        ZombieKey_destroy = args[0][0];
        ZombieKey_resurrect = *argl == 2 ? args[0][1] : 0;
      }
      break;
    case RC_WALL:
#ifdef MULTIUSER
      s = D_user->u_name;
#else
      s = D_usertty;
#endif
        {
	  struct display *olddisplay = display;
          display = 0;		/* no display will cause a broadcast */
          OutputMsg(0, "%s: %s", s, *args);
	  display = olddisplay;
        }
      break;
    case RC_AT:
      /* where this AT command comes from: */
      if (!user)
	break;
#ifdef MULTIUSER
      s = SaveStr(user->u_name);
      /* DO NOT RETURN FROM HERE WITHOUT RESETTING THIS: */
      EffectiveAclUser = user;
#else
      s = SaveStr(display ? D_usertty : user->u_name);
#endif
      n = strlen(args[0]);
      if (n) n--;
      /*
       * the windows/displays loops are quite dangerous here, take extra
       * care not to trigger landmines. Things may appear/disappear while
       * we are walking along.
       */
      switch (args[0][n])
        {
	case '*':		/* user */
	  {
	    struct display *nd;
	    struct acluser *u;

	    if (!n)
	      u = user;
	    else
	      {
		for (u = users; u; u = u->u_next)
		  {
		    debug3("strncmp('%s', '%s', %d)\n", *args, u->u_name, n);
		    if (!strncmp(*args, u->u_name, n))
		      break;
		  }
		if (!u)
		  {
		    args[0][n] = '\0';
		    OutputMsg(0, "Did not find any user matching '%s'", args[0]);
		    break;
		  }
	      }
	    debug1("at all displays of user %s\n", u->u_name);
	    for (display = displays; display; display = nd)
	      {
		nd = display->d_next;
		if (D_forecv == 0)
		  continue;
		flayer = D_forecv->c_layer;
		fore = D_fore;
	        if (D_user != u)
		  continue;
		debug1("AT display %s\n", D_usertty);
		DoCommand(args + 1, argl + 1);
		if (display)
		  OutputMsg(0, "command from %s: %s %s", 
		      s, args[1], args[2] ? args[2] : "");
		display = NULL;
		flayer = 0;
		fore = NULL;
	      }
	    break;
	  }
	case '%':		/* display */
	  {
	    struct display *nd;

	    debug1("at display matching '%s'\n", args[0]);
	    for (display = displays; display; display = nd)
	      {
	        nd = display->d_next;
		if (D_forecv == 0)
		  continue;
		fore = D_fore;
		flayer = D_forecv->c_layer;
	        if (strncmp(args[0], D_usertty, n) && 
		    (strncmp("/dev/", D_usertty, 5) || 
		     strncmp(args[0], D_usertty + 5, n)) &&
		    (strncmp("/dev/tty", D_usertty, 8) ||
		     strncmp(args[0], D_usertty + 8, n)))
		  continue;
		debug1("AT display %s\n", D_usertty);
		DoCommand(args + 1, argl + 1);
		if (display)
		  OutputMsg(0, "command from %s: %s %s", 
		      s, args[1], args[2] ? args[2] : "");
		display = NULL;
		fore = NULL;
		flayer = 0;
	      }
	    break;
	  }
	case '#':		/* window */
	  n--;
	  /* FALLTHROUGH */
	default:
	  {
	    struct win *nw;
	    int ch;

	    n++;
	    ch = args[0][n];
	    args[0][n] = '\0';
	    if (!*args[0] || (i = WindowByNumber(args[0])) < 0)
	      {
	        args[0][n] = ch;      /* must restore string in case of bind */
	        /* try looping over titles */
		for (fore = windows; fore; fore = nw)
		  {
		    nw = fore->w_next;
		    if (strncmp(args[0], fore->w_title, n))
		      continue;
		    debug2("AT window %d(%s)\n", fore->w_number, fore->w_title);
		    /*
		     * consider this a bug or a feature: 
		     * while looping through windows, we have fore AND
		     * display context. This will confuse users who try to 
		     * set up loops inside of loops, but often allows to do 
		     * what you mean, even when you adress your context wrong.
		     */
		    i = 0;
		    /* XXX: other displays? */
		    if (fore->w_layer.l_cvlist)
		      display = fore->w_layer.l_cvlist->c_display;
		    flayer = fore->w_savelayer ? fore->w_savelayer : &fore->w_layer;
		    DoCommand(args + 1, argl + 1);	/* may destroy our display */
		    if (fore && fore->w_layer.l_cvlist)
		      {
		        display = fore->w_layer.l_cvlist->c_display;
		        OutputMsg(0, "command from %s: %s %s", 
			    s, args[1], args[2] ? args[2] : "");
		      }
		  }
		display = NULL;
		fore = NULL;
		if (i < 0)
		  OutputMsg(0, "%s: at '%s': no such window.\n", rc_name, args[0]);
		break;
	      }
	    else if (i < maxwin && (fore = wtab[i]))
	      {
	        args[0][n] = ch;      /* must restore string in case of bind */
	        debug2("AT window %d (%s)\n", fore->w_number, fore->w_title);
		if (fore->w_layer.l_cvlist)
		  display = fore->w_layer.l_cvlist->c_display;
		flayer = fore->w_savelayer ? fore->w_savelayer : &fore->w_layer;
		DoCommand(args + 1, argl + 1);
		if (fore && fore->w_layer.l_cvlist)
		  {
		    display = fore->w_layer.l_cvlist->c_display;
		    OutputMsg(0, "command from %s: %s %s", 
		        s, args[1], args[2] ? args[2] : "");
		  }
		display = NULL;
		fore = NULL;
	      }
	    else
	      OutputMsg(0, "%s: at [identifier][%%|*|#] command [args]", rc_name);
	    break;
	  }
	}
      free(s);
#ifdef MULTIUSER
      EffectiveAclUser = NULL;
#endif
      break;

#ifdef COPY_PASTE
    case RC_READREG:
#ifdef ENCODINGS
      i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
      if (args[0] && args[1] && !strcmp(args[0], "-e"))
	{
	  i = FindEncoding(args[1]);
	  if (i == -1)
	    {
	      OutputMsg(0, "%s: readreg: unknown encoding", rc_name);
	      break;
	    }
	  args += 2;
	}
#endif
      /* 
       * Without arguments we prompt for a destination register.
       * It will receive the copybuffer contents.
       * This is not done by RC_PASTE, as we prompt for source
       * (not dest) there.
       */
      if ((s = *args) == NULL)
	{
	  Input("Copy to register:", 1, INP_RAW, copy_reg_fn, NULL, 0);
	  break;
	}
      if (*argl != 1)
	{
	  OutputMsg(0, "%s: copyreg: character, ^x, or (octal) \\032 expected.", rc_name);
	  break;
	}
      ch = args[0][0];
      /* 
       * With two arguments we *really* read register contents from file
       */
      if (args[1])
        {
	  if (args[2])
	    {
	      OutputMsg(0, "%s: readreg: too many arguments", rc_name);
	      break;
	    }
	  if ((s = ReadFile(args[1], &n)))
	    {
	      struct plop *pp = plop_tab + (int)(unsigned char)ch;

	      if (pp->buf)
		free(pp->buf);
	      pp->buf = s;
	      pp->len = n;
#ifdef ENCODINGS
	      pp->enc = i;
#endif
	    }
	}
      else
        /*
	 * with one argument we copy the copybuffer into a specified register
	 * This could be done with RC_PASTE too, but is here to be consistent
	 * with the zero argument call.
	 */
        copy_reg_fn(&ch, 0, NULL);
      break;
#endif
    case RC_REGISTER:
#ifdef ENCODINGS
      i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
      if (args[0] && args[1] && !strcmp(args[0], "-e"))
	{
	  i = FindEncoding(args[1]);
	  if (i == -1)
	    {
	      OutputMsg(0, "%s: register: unknown encoding", rc_name);
	      break;
	    }
	  args += 2;
	  argc -= 2;
	}
#endif
      if (argc != 2)
	{
	  OutputMsg(0, "%s: register: illegal number of arguments.", rc_name);
	  break;
	}
      if (*argl != 1)
	{
	  OutputMsg(0, "%s: register: character, ^x, or (octal) \\032 expected.", rc_name);
	  break;
	}
      ch = args[0][0];
#ifdef COPY_PASTE
      if (ch == '.')
	{
	  if (user->u_plop.buf != NULL)
	    UserFreeCopyBuffer(user);
	  if (args[1] && args[1][0])
	    {
	      user->u_plop.buf = SaveStrn(args[1], argl[1]);
	      user->u_plop.len = argl[1];
#ifdef ENCODINGS
	      user->u_plop.enc = i;
#endif
	    }
	}
      else
#endif
	{
	  struct plop *plp = plop_tab + (int)(unsigned char)ch;

	  if (plp->buf)
	    free(plp->buf);
	  plp->buf = SaveStrn(args[1], argl[1]);
	  plp->len = argl[1];
#ifdef ENCODINGS
	  plp->enc = i;
#endif
	}
      break;
    case RC_PROCESS:
      if ((s = *args) == NULL)
	{
	  Input("Process register:", 1, INP_RAW, process_fn, NULL, 0);
	  break;
	}
      if (*argl != 1)
	{
	  OutputMsg(0, "%s: process: character, ^x, or (octal) \\032 expected.", rc_name);
	  break;
	}
      ch = args[0][0];
      process_fn(&ch, 0, NULL);
      break;
    case RC_STUFF:
      s = *args;
      if (!args[0])
	{
	  Input("Stuff:", 100, INP_COOKED, StuffFin, NULL, 0);
	  break;
	}
      n = *argl;
      if (args[1])
	{
	  if (strcmp(s, "-k"))
	    {
	      OutputMsg(0, "%s: stuff: invalid option %s", rc_name, s);
	      break;
	    }
	  s = args[1];
	  for (i = T_CAPS; i < T_OCAPS; i++)
	    if (strcmp(term[i].tcname, s) == 0)
	      break;
	  if (i == T_OCAPS)
	    {
	      OutputMsg(0, "%s: stuff: unknown key '%s'", rc_name, s);
	      break;
	    }
#ifdef MAPKEYS
	  if (StuffKey(i - T_CAPS) == 0)
	    break;
#endif
	  s = display ? D_tcs[i].str : 0;
	  if (s == 0)
	    break;
	  n = strlen(s);
	}
      while(n)
        LayProcess(&s, &n);
      break;
    case RC_REDISPLAY:
      Activate(-1);
      break;
    case RC_WINDOWS:
			if (args[0]) {
				ShowWindowsX(args[0]);
				break;
			}
      ShowWindows(-1);
      break;
    case RC_VERSION:
      OutputMsg(0, "screen %s", version);
      break;
    case RC_TIME:
      if (*args)
	{
	  timestring = SaveStr(*args);
	  break;
	}
      OutputMsg(0, "%s", MakeWinMsg(timestring, fore, '%'));
      break;
    case RC_INFO:
      ShowInfo();
      break;
    case RC_DINFO:
      ShowDInfo();
      break;
    case RC_COMMAND:
	{
	  struct action *ktabp = ktab;
	  if (argc == 2 && !strcmp(*args, "-c"))
	    {
	      if ((ktabp = FindKtab(args[1], 0)) == 0)
		{
		  OutputMsg(0, "Unknown command class '%s'", args[1]);
		  break;
		}
	    }
	  if (D_ESCseen != ktab || ktabp != ktab)
	    {
	      if (D_ESCseen != ktabp)
	        {
	          D_ESCseen = ktabp;
	          WindowChanged(fore, 'E');
	        }
	      break;
	    }
	  if (D_ESCseen)
	    {
	      D_ESCseen = 0;
	      WindowChanged(fore, 'E');
	    }
	}
      /* FALLTHROUGH */
    case RC_OTHER:
      if (MoreWindows())
	SwitchWindow(display && D_other ? D_other->w_number : NextWindow());
      break;
    case RC_META:
      if (user->u_Esc == -1)
        break;
      ch = user->u_Esc;
      s = &ch;
      n = 1;
      LayProcess(&s, &n);
      break;
    case RC_XON:
      ch = Ctrl('q');
      s = &ch;
      n = 1;
      LayProcess(&s, &n);
      break;
    case RC_XOFF:
      ch = Ctrl('s');
      s = &ch;
      n = 1;
      LayProcess(&s, &n);
      break;
    case RC_DEFBREAKTYPE:
    case RC_BREAKTYPE:
	{
	  static char *types[] = { "TIOCSBRK", "TCSBRK", "tcsendbreak", NULL };
	  extern int breaktype;

	  if (*args)
	    {
	      if (ParseNum(act, &n))
		for (n = 0; n < (int)(sizeof(types)/sizeof(*types)); n++)
		  {
		    for (i = 0; i < 4; i++)
		      {
			ch = args[0][i];
			if (ch >= 'a' && ch <= 'z')
			  ch -= 'a' - 'A';
			if (ch != types[n][i] && (ch + ('a' - 'A')) != types[n][i])
			  break;
		      }
		    if (i == 4)
		      break;
		  }
	      if (n < 0 || n >= (int)(sizeof(types)/sizeof(*types)))
	        OutputMsg(0, "%s invalid, chose one of %s, %s or %s", *args, types[0], types[1], types[2]);
	      else
	        {
		  breaktype = n;
	          OutputMsg(0, "breaktype set to (%d) %s", n, types[n]);
		}
	    }
	  else
	    OutputMsg(0, "breaktype is (%d) %s", breaktype, types[breaktype]);
	}
      break;
    case RC_POW_BREAK:
    case RC_BREAK:
      n = 0;
      if (*args && ParseNum(act, &n))
	break;
      SendBreak(fore, n, nr == RC_POW_BREAK);
      break;
#ifdef LOCK
    case RC_LOCKSCREEN:
      Detach(D_LOCK);
      break;
#endif
    case RC_WIDTH:
    case RC_HEIGHT:
      {
	int w, h;
	int what = 0;
	
        i = 1;
	if (*args && !strcmp(*args, "-w"))
	  what = 1;
	else if (*args && !strcmp(*args, "-d"))
	  what = 2;
	if (what)
	  args++;
	if (what == 0 && flayer && !display)
	  what = 1;
	if (what == 1)
	  {
	    if (!flayer)
	      {
		OutputMsg(0, "%s: %s: window required", rc_name, comms[nr].name);
		break;
	      }
	    w = flayer->l_width;
	    h = flayer->l_height;
	  }
	else
	  {
	    if (!display)
	      {
		OutputMsg(0, "%s: %s: display required", rc_name, comms[nr].name);
		break;
	      }
	    w = D_width;
	    h = D_height;
	  }
        if (*args && args[0][0] == '-')
	  {
	    OutputMsg(0, "%s: %s: unknown option %s", rc_name, comms[nr].name, *args);
	    break;
	  }
	if (nr == RC_HEIGHT)
	  {
	    if (!*args)
	      {
#define H0height 42
#define H1height 24
		if (h == H0height)
		  h = H1height;
		else if (h == H1height)
		  h = H0height;
		else if (h > (H0height + H1height) / 2)
		  h = H0height;
		else
		  h = H1height;
	      }
	    else
	      {
		h = atoi(*args);
		if (args[1])
		  w = atoi(args[1]);
	      }
	  }
	else
	  {
	    if (!*args)
	      {
		if (w == Z0width)
		  w = Z1width;
		else if (w == Z1width)
		  w = Z0width;
		else if (w > (Z0width + Z1width) / 2)
		  w = Z0width;
		else
		  w = Z1width;
	      }
	    else
	      {
		w = atoi(*args);
		if (args[1])
		  h = atoi(args[1]);
	      }
	  }
        if (*args && args[1] && args[2])
	  {
	    OutputMsg(0, "%s: %s: too many arguments", rc_name, comms[nr].name);
	    break;
	  }
	if (w <= 0)
	  {
	    OutputMsg(0, "Illegal width");
	    break;
	  }
	if (h <= 0)
	  {
	    OutputMsg(0, "Illegal height");
	    break;
	  }
	if (what == 1)
	  {
	    if (flayer->l_width == w && flayer->l_height == h)
	      break;
	    ResizeLayer(flayer, w, h, (struct display *)0);
	    break;
	  }
	if (D_width == w && D_height == h)
	  break;
	if (what == 2)
	  {
	    ChangeScreenSize(w, h, 1);
	  }
	else
	  {
	    if (ResizeDisplay(w, h) == 0)
	      {
		Activate(D_fore ? D_fore->w_norefresh : 0);
		/* autofit */
		ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, 0);
		break;
	      }
	    if (h == D_height)
	      OutputMsg(0, "Your termcap does not specify how to change the terminal's width to %d.", w);
	    else if (w == D_width)
	      OutputMsg(0, "Your termcap does not specify how to change the terminal's height to %d.", h);
	    else
	      OutputMsg(0, "Your termcap does not specify how to change the terminal's resolution to %dx%d.", w, h);
	  }
      }
      break;
    case RC_DEFDYNAMICTITLE:
      (void)ParseOnOff(act, &nwin_default.dynamicaka);
      break;
    case RC_DYNAMICTITLE:
      (void)ParseOnOff(act, &fore->w_dynamicaka);
      break;
    case RC_TITLE:
      if (queryflag >= 0)
	{
	  if (fore)
	    OutputMsg(0, "%s", fore->w_title);
	  else
	    queryflag = -1;
	  break;
	}
      if (*args == 0)
	InputAKA();
      else
	ChangeAKA(fore, *args, strlen(*args));
      break;
    case RC_COLON:
      Input(":", MAXSTR, INP_EVERY, Colonfin, NULL, 0);
      if (*args && **args)
	{
	  s = *args;
	  n = strlen(s);
	  LayProcess(&s, &n);
	}
      break;
    case RC_LASTMSG:
      if (D_status_lastmsg)
	OutputMsg(0, "%s", D_status_lastmsg);
      break;
    case RC_SCREEN:
      DoScreen("key", args);
      break;
    case RC_WRAP:
      if (ParseSwitch(act, &fore->w_wrap) == 0 && msgok)
        OutputMsg(0, "%cwrap", fore->w_wrap ? '+' : '-');
      break;
    case RC_FLOW:
      if (*args)
	{
	  if (args[0][0] == 'a')
	    {
	      fore->w_flow = (fore->w_flow & FLOW_AUTO) ? FLOW_AUTOFLAG |FLOW_AUTO|FLOW_NOW : FLOW_AUTOFLAG;
	    }
	  else
	    {
	      if (ParseOnOff(act, &n))
		break;
	      fore->w_flow = (fore->w_flow & FLOW_AUTO) | n;
	    }
	}
      else
	{
	  if (fore->w_flow & FLOW_AUTOFLAG)
	    fore->w_flow = (fore->w_flow & FLOW_AUTO) | FLOW_NOW;
	  else if (fore->w_flow & FLOW_NOW)
	    fore->w_flow &= ~FLOW_NOW;
	  else
	    fore->w_flow = fore->w_flow ? FLOW_AUTOFLAG|FLOW_AUTO|FLOW_NOW : FLOW_AUTOFLAG;
	}
      SetFlow(fore->w_flow & FLOW_NOW);
      if (msgok)
	OutputMsg(0, "%cflow%s", (fore->w_flow & FLOW_NOW) ? '+' : '-',
	    (fore->w_flow & FLOW_AUTOFLAG) ? "(auto)" : "");
      break;
#ifdef MULTIUSER
    case RC_DEFWRITELOCK:
      if (args[0][0] == 'a')
	nwin_default.wlock = WLOCK_AUTO;
      else
	{
	  if (ParseOnOff(act, &n))
	    break;
	  nwin_default.wlock = n ? WLOCK_ON : WLOCK_OFF;
	}
      break;
    case RC_WRITELOCK:
      if (*args)
	{
	  if (args[0][0] == 'a')
	    {
	      fore->w_wlock = WLOCK_AUTO;
	    }
	  else
	    {
	      if (ParseOnOff(act, &n))
		break;
	      fore->w_wlock = n ? WLOCK_ON : WLOCK_OFF;
	    }
	  /* 
	   * user may have permission to change the writelock setting, 
	   * but he may never aquire the lock himself without write permission
	   */
	  if (!AclCheckPermWin(D_user, ACL_WRITE, fore))
	    fore->w_wlockuser = D_user;
	}
      OutputMsg(0, "writelock %s", (fore->w_wlock == WLOCK_AUTO) ? "auto" :
	  ((fore->w_wlock == WLOCK_OFF) ? "off" : "on"));
      break;
#endif
    case RC_CLEAR:
      ResetAnsiState(fore);
      WriteString(fore, "\033[H\033[J", 6);
      break;
    case RC_RESET:
      ResetAnsiState(fore);
#ifdef ZMODEM
      if (fore->w_zdisplay)
        zmodem_abort(fore, fore->w_zdisplay);
#endif
      WriteString(fore, "\033c", 2);
      break;
    case RC_MONITOR:
      n = fore->w_monitor != MON_OFF;
#ifdef MULTIUSER
      if (display)
	n = n && (ACLBYTE(fore->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id));
#endif
      if (ParseSwitch(act, &n))
	break;
      if (n)
	{
#ifdef MULTIUSER
	  if (display)	/* we tell only this user */
	    ACLBYTE(fore->w_mon_notify, D_user->u_id) |= ACLBIT(D_user->u_id);
	  else
	    for (i = 0; i < maxusercount; i++)
	      ACLBYTE(fore->w_mon_notify, i) |= ACLBIT(i);
#endif
	  if (fore->w_monitor == MON_OFF)
	    fore->w_monitor = MON_ON;
	  OutputMsg(0, "Window %d (%s) is now being monitored for all activity.", fore->w_number, fore->w_title);
	}
      else
	{
#ifdef MULTIUSER
	  if (display) /* we remove only this user */
	    ACLBYTE(fore->w_mon_notify, D_user->u_id) 
	      &= ~ACLBIT(D_user->u_id);
	  else
	    for (i = 0; i < maxusercount; i++)
	      ACLBYTE(fore->w_mon_notify, i) &= ~ACLBIT(i);
	  for (i = maxusercount - 1; i >= 0; i--)
	    if (ACLBYTE(fore->w_mon_notify, i))
	      break;
	  if (i < 0)
#endif
	    fore->w_monitor = MON_OFF;
	  OutputMsg(0, "Window %d (%s) is no longer being monitored for activity.", fore->w_number, fore->w_title);
	}
      break;
#ifdef MULTI
    case RC_DISPLAYS:
      display_displays();
      break;
#endif
    case RC_WINDOWLIST:
      if (!*args)
        display_windows(0, WLIST_NUM, (struct win *)0);
      else if (!strcmp(*args, "string"))
	{
	  if (args[1])
	    {
	      if (wliststr)
		free(wliststr);
	      wliststr = SaveStr(args[1]);
	    }
	  if (msgok)
	    OutputMsg(0, "windowlist string is '%s'", wliststr);
	}
      else if (!strcmp(*args, "title"))
	{
	  if (args[1])
	    {
	      if (wlisttit)
		free(wlisttit);
	      wlisttit = SaveStr(args[1]);
	    }
	  if (msgok)
	    OutputMsg(0, "windowlist title is '%s'", wlisttit);
	}
      else
	{
	  int flag = 0;
	  int blank = 0;
	  for (i = 0; i < argc; i++)
	    if (!args[i])
	      continue;
	    else if (!strcmp(args[i], "-m"))
	      flag |= WLIST_MRU;
	    else if (!strcmp(args[i], "-b"))
	      blank = 1;
	    else if (!strcmp(args[i], "-g"))
	      flag |= WLIST_NESTED;
	    else
	      {
		OutputMsg(0, "usage: windowlist [-b] [-g] [-m] [string [string] | title [title]]");
		break;
	      }
	  if (i == argc)
	    display_windows(blank, flag, (struct win *)0);
	}
      break;
    case RC_HELP:
      if (argc == 2 && !strcmp(*args, "-c"))
	{
	  struct action *ktabp;
	  if ((ktabp = FindKtab(args[1], 0)) == 0)
	    {
	      OutputMsg(0, "Unknown command class '%s'", args[1]);
	      break;
	    }
          display_help(args[1], ktabp);
	}
      else
        display_help((char *)0, ktab);
      break;
    case RC_LICENSE:
      display_copyright();
      break;
#ifdef COPY_PASTE
    case RC_COPY:
      if (flayer->l_layfn != &WinLf)
	{
	  OutputMsg(0, "Must be on a window layer");
	  break;
	}
      MarkRoutine();
      WindowChanged(fore, 'P');
      break;
    case RC_HISTORY:
      {
        static char *pasteargs[] = {".", 0};
	static int pasteargl[] = {1};

	if (flayer->l_layfn != &WinLf)
	  {
	    OutputMsg(0, "Must be on a window layer");
	    break;
	  }
	if (GetHistory() == 0)
	  break;
	if (user->u_plop.buf == NULL)
	  break;
	args = pasteargs;
	argl = pasteargl;
      }
      /*FALLTHROUGH*/
    case RC_PASTE:
      {
        char *ss, *dbuf, dch;
        int l = 0;
# ifdef ENCODINGS
	int enc = -1;
# endif

	/*
	 * without args we prompt for one(!) register to be pasted in the window
	 */
	if ((s = *args) == NULL)
	  {
	    Input("Paste from register:", 1, INP_RAW, ins_reg_fn, NULL, 0);
	    break;
	  }
	if (args[1] == 0 && !fore)	/* no window? */
	  break;
	/*	
	 * with two arguments we paste into a destination register
	 * (no window needed here).
	 */
	if (args[1] && argl[1] != 1)
	  {
	    OutputMsg(0, "%s: paste destination: character, ^x, or (octal) \\032 expected.",
		rc_name);
	    break;
	  }
# ifdef ENCODINGS
        else if (fore)
	  enc = fore->w_encoding;
# endif

	/*
	 * measure length of needed buffer 
	 */
        for (ss = s = *args; (ch = *ss); ss++)
          {
	    if (ch == '.')
	      {
# ifdef ENCODINGS
		if (enc == -1)
		  enc = user->u_plop.enc;
		if (enc != user->u_plop.enc)
		  l += RecodeBuf((unsigned char *)user->u_plop.buf, user->u_plop.len, user->u_plop.enc, enc, (unsigned char *)0);
		else
# endif
		  l += user->u_plop.len;
	      }
	    else
	      {
# ifdef ENCODINGS
		if (enc == -1)
		  enc = plop_tab[(int)(unsigned char)ch].enc;
		if (enc != plop_tab[(int)(unsigned char)ch].enc)
		  l += RecodeBuf((unsigned char *)plop_tab[(int)(unsigned char)ch].buf, plop_tab[(int)(unsigned char)ch].len, plop_tab[(int)(unsigned char)ch].enc, enc, (unsigned char *)0);
		else
# endif
                  l += plop_tab[(int)(unsigned char)ch].len;
	      }
          }
        if (l == 0)
	  {
	    OutputMsg(0, "empty buffer");
	    break;
	  }
	/*
	 * shortcut: 
	 * if there is only one source and the destination is a window, then
	 * pass a pointer rather than duplicating the buffer.
	 */
        if (s[1] == 0 && args[1] == 0)
# ifdef ENCODINGS
	  if (enc == (*s == '.' ? user->u_plop.enc : plop_tab[(int)(unsigned char)*s].enc))
# endif
            {
	      MakePaster(&fore->w_paster, *s == '.' ? user->u_plop.buf : plop_tab[(int)(unsigned char)*s].buf, l, 0);
	      break;
            }
	/*
	 * if no shortcut, we construct a buffer
	 */
        if ((dbuf = (char *)malloc(l)) == 0)
          {
	    OutputMsg(0, "%s", strnomem);
	    break;
          }
        l = 0;
	/*
	 * concatenate all sources into our own buffer, copy buffer is
	 * special and is skipped if no display exists.
	 */
        for (ss = s; (ch = *ss); ss++)
          {
	    struct plop *pp = (ch == '.' ? &user->u_plop : &plop_tab[(int)(unsigned char)ch]);
#ifdef ENCODINGS
	    if (pp->enc != enc)
	      {
		l += RecodeBuf((unsigned char *)pp->buf, pp->len, pp->enc, enc, (unsigned char *)dbuf + l);
		continue;
	      }
#endif
	    bcopy(pp->buf, dbuf + l, pp->len);
	    l += pp->len;
          }
	/*
	 * when called with one argument we paste our buffer into the window 
	 */
	if (args[1] == 0)
	  {
	    MakePaster(&fore->w_paster, dbuf, l, 1);
	  }
	else
	  {
	    /*
	     * we have two arguments, the second is already in dch.
	     * use this as destination rather than the window.
	     */
	    dch = args[1][0];
	    if (dch == '.')
	      {
	        if (user->u_plop.buf != NULL)
	          UserFreeCopyBuffer(user);
		user->u_plop.buf = dbuf;
		user->u_plop.len = l;
#ifdef ENCODINGS
		user->u_plop.enc = enc;
#endif
	      }
	    else
	      {
		struct plop *pp = plop_tab + (int)(unsigned char)dch;
		if (pp->buf)
		  free(pp->buf);
		pp->buf = dbuf;
		pp->len = l;
#ifdef ENCODINGS
		pp->enc = enc;
#endif
	      }
	  }
        break;
      }
    case RC_WRITEBUF:
      if (!user->u_plop.buf)
	{
	  OutputMsg(0, "empty buffer");
	  break;
	}
#ifdef ENCODINGS
	{
	  struct plop oldplop;

	  oldplop = user->u_plop;
	  if (args[0] && args[1] && !strcmp(args[0], "-e"))
	    {
	      int enc, l;
	      char *newbuf;

	      enc = FindEncoding(args[1]);
	      if (enc == -1)
		{
		  OutputMsg(0, "%s: writebuf: unknown encoding", rc_name);
		  break;
		}
	      if (enc != oldplop.enc)
		{
		  l = RecodeBuf((unsigned char *)oldplop.buf, oldplop.len, oldplop.enc, enc, (unsigned char *)0);
		  newbuf = malloc(l + 1);
		  if (!newbuf)
		    {
		      OutputMsg(0, "%s", strnomem);
		      break;
		    }
		  user->u_plop.len = RecodeBuf((unsigned char *)oldplop.buf, oldplop.len, oldplop.enc, enc, (unsigned char *)newbuf);
		  user->u_plop.buf = newbuf;
		  user->u_plop.enc = enc;
		}
	      args += 2;
	    }
#endif
	  if (args[0] && args[1])
	    OutputMsg(0, "%s: writebuf: too many arguments", rc_name);
	  else
	    WriteFile(user, args[0], DUMP_EXCHANGE);
#ifdef ENCODINGS
	  if (user->u_plop.buf != oldplop.buf)
	    free(user->u_plop.buf);
	  user->u_plop = oldplop;
	}
#endif
      break;
    case RC_READBUF:
#ifdef ENCODINGS
      i = fore ? fore->w_encoding : display ? display->d_encoding : 0;
      if (args[0] && args[1] && !strcmp(args[0], "-e"))
	{
	  i = FindEncoding(args[1]);
	  if (i == -1)
	    {
	      OutputMsg(0, "%s: readbuf: unknown encoding", rc_name);
	      break;
	    }
	  args += 2;
	}
#endif
      if (args[0] && args[1])
	{
	  OutputMsg(0, "%s: readbuf: too many arguments", rc_name);
	  break;
	}
      if ((s = ReadFile(args[0] ? args[0] : BufferFile, &n)))
	{
	  if (user->u_plop.buf)
	    UserFreeCopyBuffer(user);
	  user->u_plop.len = n;
	  user->u_plop.buf = s;
#ifdef ENCODINGS
	  user->u_plop.enc = i;
#endif
	}
      break;
    case RC_REMOVEBUF:
      KillBuffers();
      break;
    case RC_IGNORECASE:
      (void)ParseSwitch(act, &search_ic);
      if (msgok)
        OutputMsg(0, "Will %signore case in searches", search_ic ? "" : "not ");
      break;
#endif				/* COPY_PASTE */
    case RC_ESCAPE:
      if (*argl == 0)
	SetEscape(user, -1, -1);
      else if (*argl == 2)
	SetEscape(user, (int)(unsigned char)args[0][0], (int)(unsigned char)args[0][1]);
      else
	{
	  OutputMsg(0, "%s: two characters required after escape.", rc_name);
	  break;
	}
      /* Change defescape if master user. This is because we only
       * have one ktab.
       */
      if (display && user != users)
	break;
      /* FALLTHROUGH */
    case RC_DEFESCAPE:
      if (*argl == 0)
	SetEscape(NULL, -1, -1);
      else if (*argl == 2)
	SetEscape(NULL, (int)(unsigned char)args[0][0], (int)(unsigned char)args[0][1]);
      else
	{
	  OutputMsg(0, "%s: two characters required after defescape.", rc_name);
	  break;
	}
#ifdef MAPKEYS
      CheckEscape();
#endif
      break;
    case RC_CHDIR:
      s = *args ? *args : home;
      if (chdir(s) == -1)
	OutputMsg(errno, "%s", s);
      break;
    case RC_SHELL:
    case RC_DEFSHELL:
      if (ParseSaveStr(act, &ShellProg) == 0)
        ShellArgs[0] = ShellProg;
      break;
    case RC_HARDCOPYDIR:
      if (*args)
        (void)ParseSaveStr(act, &hardcopydir);
      if (msgok)
	OutputMsg(0, "hardcopydir is %s\n", hardcopydir && *hardcopydir ? hardcopydir : "<cwd>");
      break;
    case RC_LOGFILE:
      if (*args)
	{
	  char buf[1024];
	  if (args[1] && !(strcmp(*args, "flush")))
	    {
	      log_flush = atoi(args[1]);
	      if (msgok)
		OutputMsg(0, "log flush timeout set to %ds\n", log_flush);
	      break;
	    }
	  if (ParseSaveStr(act, &screenlogfile))
	    break;
	  if (fore && fore->w_log)
	    if (DoStartLog(fore, buf, sizeof(buf)))
	      OutputMsg(0, "Error opening logfile \"%s\"", buf);
	  if (!msgok)
	    break;
	}
      OutputMsg(0, "logfile is '%s'", screenlogfile);
      break;
    case RC_LOGTSTAMP:
      if (!*args || !strcmp(*args, "on") || !strcmp(*args, "off"))
        {
	  if (ParseSwitch(act, &logtstamp_on) == 0 && msgok)
            OutputMsg(0, "timestamps turned %s", logtstamp_on ? "on" : "off");
        }
      else if (!strcmp(*args, "string"))
	{
	  if (args[1])
	    {
	      if (logtstamp_string)
		free(logtstamp_string);
	      logtstamp_string = SaveStr(args[1]);
	    }
	  if (msgok)
	    OutputMsg(0, "logfile timestamp is '%s'", logtstamp_string);
	}
      else if (!strcmp(*args, "after"))
	{
	  if (args[1])
	    {
	      logtstamp_after = atoi(args[1]);
	      if (!msgok)
		break;
	    }
	  OutputMsg(0, "timestamp printed after %ds\n", logtstamp_after);
	}
      else
        OutputMsg(0, "usage: logtstamp [after [n]|string [str]|on|off]");
      break;
    case RC_SHELLTITLE:
      (void)ParseSaveStr(act, &nwin_default.aka);
      break;
    case RC_TERMCAP:
    case RC_TERMCAPINFO:
    case RC_TERMINFO:
      if (!rc_name || !*rc_name)
        OutputMsg(0, "Sorry, too late now. Place that in your .screenrc file.");
      break;
    case RC_SLEEP:
      break;			/* Already handled */
    case RC_TERM:
      s = NULL;
      if (ParseSaveStr(act, &s))
	break;
      if (strlen(s) > MAXTERMLEN)
	{
	  OutputMsg(0, "%s: term: argument too long ( < %d)", rc_name, MAXTERMLEN);
	  free(s);
	  break;
	}
      strncpy(screenterm, s, MAXTERMLEN);
      screenterm[MAXTERMLEN] = '\0';
      free(s);
      debug1("screenterm set to %s\n", screenterm);
      MakeTermcap((display == 0));
      debug("new termcap made\n");
      break;
    case RC_ECHO:
      if (!msgok && (!rc_name || strcmp(rc_name, "-X")))
	break;
      /*
       * user typed ^A:echo... well, echo isn't FinishRc's job,
       * but as he wanted to test us, we show good will
       */
      if (argc > 1 && !strcmp(*args, "-n"))
	{
	  args++;
	  argc--;
	}
      s = *args;
      if (argc > 1 && !strcmp(*args, "-p"))
	{
	  args++;
	  argc--;
	  s = *args;
	  if (s)
	    s = MakeWinMsg(s, fore, '%');
	}
      if (s)
	OutputMsg(0, "%s", s);
      else
	{
	  OutputMsg(0, "%s: 'echo [-n] [-p] \"string\"' expected.", rc_name);
	  queryflag = -1;
	}
      break;
    case RC_BELL:
    case RC_BELL_MSG:
      if (*args == 0)
	{
	  char buf[256];
	  AddXChars(buf, sizeof(buf), BellString);
	  OutputMsg(0, "bell_msg is '%s'", buf);
	  break;
	}
      (void)ParseSaveStr(act, &BellString);
      break;
#ifdef COPY_PASTE
    case RC_BUFFERFILE:
      if (*args == 0)
	BufferFile = SaveStr(DEFAULT_BUFFERFILE);
      else if (ParseSaveStr(act, &BufferFile))
        break;
      if (msgok)
        OutputMsg(0, "Bufferfile is now '%s'", BufferFile);
      break;
#endif
    case RC_ACTIVITY:
      (void)ParseSaveStr(act, &ActivityString);
      break;
#if defined(DETACH) && defined(POW_DETACH)
    case RC_POW_DETACH_MSG:
      if (*args == 0)
        {
	  char buf[256];
          AddXChars(buf, sizeof(buf), PowDetachString);
	  OutputMsg(0, "pow_detach_msg is '%s'", buf);
	  break;
	}
      (void)ParseSaveStr(act, &PowDetachString);
      break;
#endif
#if defined(UTMPOK) && defined(LOGOUTOK)
    case RC_LOGIN:
      n = fore->w_slot != (slot_t)-1;
      if (*args && !strcmp(*args, "always"))
	{
	  fore->w_lflag = 3;
	  if (!displays && n)
	    SlotToggle(n);
	  break;
	}
      if (*args && !strcmp(*args, "attached"))
	{
	  fore->w_lflag = 1;
	  if (!displays && n)
	    SlotToggle(0);
	  break;
	}
      if (ParseSwitch(act, &n) == 0)
        SlotToggle(n);
      break;
    case RC_DEFLOGIN:
      if (!strcmp(*args, "always"))
	nwin_default.lflag |= 2;
      else if (!strcmp(*args, "attached"))
	nwin_default.lflag &= ~2;
      else
        (void)ParseOnOff(act, &nwin_default.lflag);
      break;
#endif
    case RC_DEFFLOW:
      if (args[0] && args[1] && args[1][0] == 'i')
	{
	  iflag = 1;
	  for (display = displays; display; display = display->d_next)
	    {
	      if (!D_flow)
		continue;
#if defined(TERMIO) || defined(POSIX)
	      D_NewMode.tio.c_cc[VINTR] = D_OldMode.tio.c_cc[VINTR];
	      D_NewMode.tio.c_lflag |= ISIG;
#else /* TERMIO || POSIX */
	      D_NewMode.m_tchars.t_intrc = D_OldMode.m_tchars.t_intrc;
#endif /* TERMIO || POSIX */
	      SetTTY(D_userfd, &D_NewMode);
	    }
	}
      if (args[0] && args[0][0] == 'a')
	nwin_default.flowflag = FLOW_AUTOFLAG;
      else
	(void)ParseOnOff(act, &nwin_default.flowflag);
      break;
    case RC_DEFWRAP:
      (void)ParseOnOff(act, &nwin_default.wrap);
      break;
    case RC_DEFC1:
      (void)ParseOnOff(act, &nwin_default.c1);
      break;
#ifdef COLOR
    case RC_DEFBCE:
      (void)ParseOnOff(act, &nwin_default.bce);
      break;
#endif
    case RC_DEFGR:
      (void)ParseOnOff(act, &nwin_default.gr);
      break;
    case RC_DEFMONITOR:
      if (ParseOnOff(act, &n) == 0)
        nwin_default.monitor = (n == 0) ? MON_OFF : MON_ON;
      break;
    case RC_DEFMOUSETRACK:
      if (ParseOnOff(act, &n) == 0)
	defmousetrack = (n == 0) ? 0 : 1000;
      break;
    case RC_MOUSETRACK:
      if (!args[0])
	{
	  OutputMsg(0, "Mouse tracking for this display is turned %s", D_mousetrack ? "on" : "off");
	}
      else if (ParseOnOff(act, &n) == 0)
	{
	  D_mousetrack = n == 0 ? 0 : 1000;
	  if (D_fore)
	    MouseMode(D_fore->w_mouse);
	}
      break;
    case RC_DEFSILENCE:
      if (ParseOnOff(act, &n) == 0)
        nwin_default.silence = (n == 0) ? SILENCE_OFF : SILENCE_ON;
      break;
    case RC_VERBOSE:
      if (!*args)
	OutputMsg(0, "W%s echo command when creating windows.", 
	  VerboseCreate ? "ill" : "on't");
      else if (ParseOnOff(act, &n) == 0)
        VerboseCreate = n;
      break;
    case RC_HARDSTATUS:
      if (display)
	{
	  OutputMsg(0, "%s", "");	/* wait till mintime (keep gcc quiet) */
          RemoveStatus();
	}
      if (args[0] && strcmp(args[0], "on") && strcmp(args[0], "off"))
	{
          struct display *olddisplay = display;
	  int old_use, new_use = -1;

	  s = args[0];
	  if (!strncmp(s, "always", 6))
	    s += 6;
	  if (!strcmp(s, "firstline"))
	    new_use = HSTATUS_FIRSTLINE;
	  else if (!strcmp(s, "lastline"))
	    new_use = HSTATUS_LASTLINE;
	  else if (!strcmp(s, "ignore"))
	    new_use = HSTATUS_IGNORE;
	  else if (!strcmp(s, "message"))
	    new_use = HSTATUS_MESSAGE;
	  else if (!strcmp(args[0], "string"))
	    {
	      if (!args[1])
		{
		  char buf[256];
		  AddXChars(buf, sizeof(buf), hstatusstring);
		  OutputMsg(0, "hardstatus string is '%s'", buf);
		  break;
		}
	    }
	  else
	    {
	      OutputMsg(0, "%s: usage: hardstatus [always]lastline|ignore|message|string [string]", rc_name);
	      break;
	    }
	  if (new_use != -1)
	    {
	      hardstatusemu = new_use | (s == args[0] ? 0 : HSTATUS_ALWAYS);
	      for (display = displays; display; display = display->d_next)
		{
		  RemoveStatus();
		  new_use = hardstatusemu & ~HSTATUS_ALWAYS;
		  if (D_HS && s == args[0])
		    new_use = HSTATUS_HS;
		  ShowHStatus((char *)0);
		  old_use = D_has_hstatus;
		  D_has_hstatus = new_use;
		  if ((new_use == HSTATUS_LASTLINE && old_use != HSTATUS_LASTLINE) || (new_use != HSTATUS_LASTLINE && old_use == HSTATUS_LASTLINE))
		    ChangeScreenSize(D_width, D_height, 1);
		  if ((new_use == HSTATUS_FIRSTLINE && old_use != HSTATUS_FIRSTLINE) || (new_use != HSTATUS_FIRSTLINE && old_use == HSTATUS_FIRSTLINE))
		    ChangeScreenSize(D_width, D_height, 1);
		  RefreshHStatus();
		}
	    }
	  if (args[1])
	    {
	      if (hstatusstring)
		free(hstatusstring);
	      hstatusstring = SaveStr(args[1]);
	      for (display = displays; display; display = display->d_next)
	        RefreshHStatus();
	    }
	  display = olddisplay;
	  break;
	}
      (void)ParseSwitch(act, &use_hardstatus);
      if (msgok)
        OutputMsg(0, "messages displayed on %s", use_hardstatus ? "hardstatus line" : "window");
      break;
    case RC_CAPTION:
      if (strcmp(args[0], "always") == 0 || strcmp(args[0], "splitonly") == 0)
	{
	  struct display *olddisplay = display;

	  captionalways = args[0][0] == 'a';
	  for (display = displays; display; display = display->d_next)
	    ChangeScreenSize(D_width, D_height, 1);
	  display = olddisplay;
	}
      else if (strcmp(args[0], "string") == 0)
	{
	  if (!args[1])
	    {
	      char buf[256];
	      AddXChars(buf, sizeof(buf), captionstring);
	      OutputMsg(0, "caption string is '%s'", buf);
	      break;
	    }
	}
      else
	{
	  OutputMsg(0, "%s: usage: caption always|splitonly|string <string>", rc_name);
	  break;
	}
      if (!args[1])
	break;
      if (captionstring)
	free(captionstring);
      captionstring = SaveStr(args[1]);
      RedisplayDisplays(0);
      break;
    case RC_CONSOLE:
      n = (console_window != 0);
      if (ParseSwitch(act, &n))
        break;
      if (TtyGrabConsole(fore->w_ptyfd, n, rc_name))
	break;
      if (n == 0)
	  OutputMsg(0, "%s: releasing console %s", rc_name, HostName);
      else if (console_window)
	  OutputMsg(0, "%s: stealing console %s from window %d (%s)", rc_name, 
	      HostName, console_window->w_number, console_window->w_title);
      else
	  OutputMsg(0, "%s: grabbing console %s", rc_name, HostName);
      console_window = n ? fore : 0;
      break;
    case RC_ALLPARTIAL:
      if (ParseOnOff(act, &all_norefresh))
	break;
      if (!all_norefresh && fore)
	Activate(-1);
      if (msgok)
        OutputMsg(0, all_norefresh ? "No refresh on window change!\n" :
			       "Window specific refresh\n");
      break;
    case RC_PARTIAL:
      (void)ParseSwitch(act, &n);
      fore->w_norefresh = n;
      break;
    case RC_VBELL:
      if (ParseSwitch(act, &visual_bell) || !msgok)
        break;
      if (visual_bell == 0)
        OutputMsg(0, "switched to audible bell.");
      else
        OutputMsg(0, "switched to visual bell.");
      break;
    case RC_VBELLWAIT:
      if (ParseNum1000(act, &VBellWait) == 0 && msgok)
        OutputMsg(0, "vbellwait set to %.10g seconds", VBellWait/1000.);
      break;
    case RC_MSGWAIT:
      if (ParseNum1000(act, &MsgWait) == 0 && msgok)
        OutputMsg(0, "msgwait set to %.10g seconds", MsgWait/1000.);
      break;
    case RC_MSGMINWAIT:
      if (ParseNum1000(act, &MsgMinWait) == 0 && msgok)
        OutputMsg(0, "msgminwait set to %.10g seconds", MsgMinWait/1000.);
      break;
    case RC_SILENCEWAIT:
      if (ParseNum(act, &SilenceWait))
	break;
      if (SilenceWait < 1)
	SilenceWait = 1;
      for (p = windows; p; p = p->w_next)
	p->w_silencewait = SilenceWait;
      if (msgok)
	OutputMsg(0, "silencewait set to %d seconds", SilenceWait);
      break;
    case RC_BUMPRIGHT:
      if (fore->w_number < NextWindow())
        WindowChangeNumber(fore->w_number, NextWindow());
      break;
    case RC_BUMPLEFT:
      if (fore->w_number > PreviousWindow())
        WindowChangeNumber(fore->w_number, PreviousWindow());
      break;
    case RC_COLLAPSE:
      CollapseWindowlist();
      break;
    case RC_NUMBER:
      if (*args == 0)
        OutputMsg(0, queryflag >= 0 ? "%d (%s)" : "This is window %d (%s).", fore->w_number, fore->w_title);
      else
        {
	  int old = fore->w_number;
	  int rel = 0, parse;
	  if (args[0][0] == '+')
	    rel = 1;
	  else if (args[0][0] == '-')
	    rel = -1;
	  if (rel)
	    ++act->args[0];
	  parse = ParseNum(act, &n);
	  if (rel)
	    --act->args[0];
	  if (parse)
	    break;
	  if (rel > 0)
	    n += old;
	  else if (rel < 0)
	    n = old - n;
	  if (!WindowChangeNumber(old, n))
	    {
	      /* Window number could not be changed. */
	      queryflag = -1;
	      return;
	    }
	}
      break;

		case RC_ZOMBIE_TIMEOUT:
			if (argc != 1) {
				Msg(0, "Setting zombie polling needs a timeout arg\n");
				break;
			}

			nwin_default.poll_zombie_timeout = atoi(args[0]);
			if (fore)
				fore->w_poll_zombie_timeout = nwin_default.poll_zombie_timeout;
			debug1("Setting zombie polling to %d\n", nwin_default.poll_zombie_timeout);
			break;

		case RC_SORT:
			if (fore) {
			/* Better do not allow this. Not sure what the utmp stuff in number
			* command above is for (you get four entries in e.g. /var/log/wtmp
			* per number switch). But I don't know enough about this.
			*/
				Msg(0, "Sorting inside a window is not allowed. Push CTRL-a \" "
					"and try again\n");
				break;
			}
			/*
			* Simple sort algorithm: Look out for the smallest, put it
			* to the first place, look out for the 2nd smallest, ...
			*/
			for (i = 0; i < maxwin ; i++) {
				if (wtab[i] == NULL)
					continue;
				n = i;

				for (nr = i + 1; nr < maxwin; nr++) {
					if (wtab[nr] == NULL)
						continue;
					debug2("Testing window %d and %d.\n", nr, n);
					if (strcmp(wtab[nr]->w_title,wtab[n]->w_title) < 0)
						n = nr;
				}

				if (n != i) {
					debug2("Exchange window %d and %d.\n", i, n);
					p = wtab[n];
					wtab[n] = wtab[i];
					wtab[i] = p;
					wtab[n]->w_number = n;
					wtab[i]->w_number = i;
#ifdef MULTIUSER
					/* exchange the acls for these windows. */
					AclWinSwap(i, n);
#endif
				}
			}
			WindowChanged((struct win *)0, 0);
			break;

    case RC_SILENCE:
      n = fore->w_silence != 0;
      i = fore->w_silencewait;
      if (args[0] && (args[0][0] == '-' || (args[0][0] >= '0' && args[0][0] <= '9')))
        {
	  if (ParseNum(act, &i))
	    break;
	  n = i > 0;
	}
      else if (ParseSwitch(act, &n))
        break;
      if (n)
        {
#ifdef MULTIUSER
	  if (display)	/* we tell only this user */
	    ACLBYTE(fore->w_lio_notify, D_user->u_id) |= ACLBIT(D_user->u_id);
	  else
	    for (n = 0; n < maxusercount; n++)
	      ACLBYTE(fore->w_lio_notify, n) |= ACLBIT(n);
#endif
	  fore->w_silencewait = i;
	  fore->w_silence = SILENCE_ON;
	  SetTimeout(&fore->w_silenceev, fore->w_silencewait * 1000);
	  evenq(&fore->w_silenceev);

	  if (!msgok)
	    break;
	  OutputMsg(0, "The window is now being monitored for %d sec. silence.", fore->w_silencewait);
	}
      else
        {
#ifdef MULTIUSER
	  if (display) /* we remove only this user */
	    ACLBYTE(fore->w_lio_notify, D_user->u_id) 
	      &= ~ACLBIT(D_user->u_id);
	  else
	    for (n = 0; n < maxusercount; n++)
	      ACLBYTE(fore->w_lio_notify, n) &= ~ACLBIT(n);
	  for (i = maxusercount - 1; i >= 0; i--)
	    if (ACLBYTE(fore->w_lio_notify, i))
	      break;
	  if (i < 0)
#endif
	    {
	      fore->w_silence = SILENCE_OFF;
	      evdeq(&fore->w_silenceev);
	    }
	  if (!msgok)
	    break;
	  OutputMsg(0, "The window is no longer being monitored for silence.");
	}
      break;
#ifdef COPY_PASTE
    case RC_DEFSCROLLBACK:
      (void)ParseNum(act, &nwin_default.histheight);
      break;
    case RC_SCROLLBACK:
      if (flayer->l_layfn == &MarkLf)
	{
	  OutputMsg(0, "Cannot resize scrollback buffer in copy/scrollback mode.");
	  break;
	}
      (void)ParseNum(act, &n);
      ChangeWindowSize(fore, fore->w_width, fore->w_height, n);
      if (msgok)
	OutputMsg(0, "scrollback set to %d", fore->w_histheight);
      break;
#endif
    case RC_SESSIONNAME:
      if (*args == 0)
	OutputMsg(0, "This session is named '%s'\n", SockName);
      else
	{
	  char buf[MAXPATHLEN];

	  s = 0;
	  if (ParseSaveStr(act, &s))
	    break;
	  if (!*s || strlen(s) + (SockName - SockPath) > MAXPATHLEN - 13 || index(s, '/'))
	    {
	      OutputMsg(0, "%s: bad session name '%s'\n", rc_name, s);
	      free(s);
	      break;
	    }
	  strncpy(buf, SockPath, SockName - SockPath);
	  sprintf(buf + (SockName - SockPath), "%d.%s", (int)getpid(), s); 
	  free(s);
	  if ((access(buf, F_OK) == 0) || (errno != ENOENT))
	    {
	      OutputMsg(0, "%s: inappropriate path: '%s'.", rc_name, buf);
	      break;
	    }
	  if (rename(SockPath, buf))
	    {
	      OutputMsg(errno, "%s: failed to rename(%s, %s)", rc_name, SockPath, buf);
	      break;
	    }
	  debug2("rename(%s, %s) done\n", SockPath, buf);
	  strcpy(SockPath, buf);
	  MakeNewEnv();
	  WindowChanged((struct win *)0, 'S');
	}
      break;
    case RC_SETENV:
      if (!args[0] || !args[1])
        {
	  debug1("RC_SETENV arguments missing: %s\n", args[0] ? args[0] : "");
          InputSetenv(args[0]);
	}
      else
        {
          xsetenv(args[0], args[1]);
          MakeNewEnv();
	}
      break;
    case RC_UNSETENV:
      unsetenv(*args);
      MakeNewEnv();
      break;
#ifdef COPY_PASTE
    case RC_DEFSLOWPASTE:
      (void)ParseNum(act, &nwin_default.slow);
      break;
    case RC_SLOWPASTE:
      if (*args == 0)
	OutputMsg(0, fore->w_slowpaste ? 
               "Slowpaste in window %d is %d milliseconds." :
               "Slowpaste in window %d is unset.", 
	    fore->w_number, fore->w_slowpaste);
      else if (ParseNum(act, &fore->w_slowpaste) == 0 && msgok)
	OutputMsg(0, fore->w_slowpaste ?
               "Slowpaste in window %d set to %d milliseconds." :
               "Slowpaste in window %d now unset.", 
	    fore->w_number, fore->w_slowpaste);
      break;
    case RC_MARKKEYS:
      if (CompileKeys(*args, *argl, mark_key_tab))
	{
	  OutputMsg(0, "%s: markkeys: syntax error.", rc_name);
	  break;
	}
      debug1("markkeys %s\n", *args);
      break;
# ifdef FONT
    case RC_PASTEFONT:
      if (ParseSwitch(act, &pastefont) == 0 && msgok)
        OutputMsg(0, "Will %spaste font settings", pastefont ? "" : "not ");
      break;
# endif
    case RC_CRLF:
      (void)ParseSwitch(act, &join_with_cr);
      break;
    case RC_COMPACTHIST:
      if (ParseSwitch(act, &compacthist) == 0 && msgok)
	OutputMsg(0, "%scompacting history lines", compacthist ? "" : "not ");
      break;
#endif
#ifdef NETHACK
    case RC_NETHACK:
      (void)ParseOnOff(act, &nethackflag);
      break;
#else
    case RC_NETHACK:
      Msg(0, "nethack disabled at build time");
      break;
#endif
    case RC_HARDCOPY_APPEND:
      (void)ParseOnOff(act, &hardcopy_append);
      break;
    case RC_VBELL_MSG:
      if (*args == 0) 
        { 
	  char buf[256];
          AddXChars(buf, sizeof(buf), VisualBellString);
	  OutputMsg(0, "vbell_msg is '%s'", buf);
	  break; 
	}
      (void)ParseSaveStr(act, &VisualBellString);
      debug1(" new vbellstr '%s'\n", VisualBellString);
      break;
    case RC_DEFMODE:
      if (ParseBase(act, *args, &n, 8, "octal"))
        break;
      if (n < 0 || n > 0777)
	{
	  OutputMsg(0, "%s: mode: Invalid tty mode %o", rc_name, n);
          break;
	}
      TtyMode = n;
      if (msgok)
	OutputMsg(0, "Ttymode set to %03o", TtyMode);
      break;
    case RC_AUTODETACH:
      (void)ParseOnOff(act, &auto_detach);
      break;
    case RC_STARTUP_MESSAGE:
      (void)ParseOnOff(act, &default_startup);
      break;
#ifdef PASSWORD
    case RC_PASSWORD:
      if (*args)
	{
	  n = (*user->u_password) ? 1 : 0;
	  if (user->u_password != NullStr) free((char *)user->u_password);
	  user->u_password = SaveStr(*args);
	  if (!strcmp(user->u_password, "none"))
	    {
	      if (n)
	        OutputMsg(0, "Password checking disabled");
	      free(user->u_password);
	      user->u_password = NullStr;
	    }
	}
      else
	{
	  if (!fore)
	    {
	      OutputMsg(0, "%s: password: window required", rc_name);
	      break;
	    }
	  Input("New screen password:", 100, INP_NOECHO, pass1, display ? (char *)D_user : (char *)users, 0);
	}
      break;
#endif				/* PASSWORD */
    case RC_BIND:
	{
	  struct action *ktabp = ktab;
	  int kflag = 0;

	  for (;;)
	    {
	      if (argc > 2 && !strcmp(*args, "-c"))
		{
		  ktabp = FindKtab(args[1], 1);
		  if (ktabp == 0)
		    break;
		  args += 2;
		  argl += 2;
		  argc -= 2;
		}
	      else if (argc > 1 && !strcmp(*args, "-k"))
	        {
		  kflag = 1;
		  args++;
		  argl++;
		  argc--;
		}
	      else
	        break;
	    }
#ifdef MAPKEYS
          if (kflag)
	    {
	      for (n = 0; n < KMAP_KEYS; n++)
		if (strcmp(term[n + T_CAPS].tcname, *args) == 0)
		  break;
	      if (n == KMAP_KEYS)
		{
		  OutputMsg(0, "%s: bind: unknown key '%s'", rc_name, *args);
		  break;
		}
	      n += 256;
	    }
	  else
#endif
	  if (*argl != 1)
	    {
	      OutputMsg(0, "%s: bind: character, ^x, or (octal) \\032 expected.", rc_name);
	      break;
	    }
	  else
	    n = (unsigned char)args[0][0];

	  if (args[1])
	    {
	      if ((i = FindCommnr(args[1])) == RC_ILLEGAL)
		{
		  OutputMsg(0, "%s: bind: unknown command '%s'", rc_name, args[1]);
		  break;
		}
	      if (CheckArgNum(i, args + 2) < 0)
		break;
	      ClearAction(&ktabp[n]);
	      SaveAction(ktabp + n, i, args + 2, argl + 2);
	    }
	  else
	    ClearAction(&ktabp[n]);
	}
      break;
#ifdef MAPKEYS
    case RC_BINDKEY:
	{
	  struct action *newact;
          int newnr, fl = 0, kf = 0, af = 0, df = 0, mf = 0;
	  struct display *odisp = display;
	  int used = 0;
          struct kmap_ext *kme = NULL;

	  for (; *args && **args == '-'; args++, argl++)
	    {
	      if (strcmp(*args, "-t") == 0)
		fl = KMAP_NOTIMEOUT;
	      else if (strcmp(*args, "-k") == 0)
		kf = 1;
	      else if (strcmp(*args, "-a") == 0)
		af = 1;
	      else if (strcmp(*args, "-d") == 0)
		df = 1;
	      else if (strcmp(*args, "-m") == 0)
		mf = 1;
	      else if (strcmp(*args, "--") == 0)
		{
		  args++;
		  argl++;
		  break;
		}
	      else
		{
	          OutputMsg(0, "%s: bindkey: invalid option %s", rc_name, *args);
		  return;
		}
	    }
	  if (df && mf)
	    {
	      OutputMsg(0, "%s: bindkey: -d does not work with -m", rc_name);
	      break;
	    }
	  if (*args == 0)
	    {
	      if (mf)
		display_bindkey("Edit mode", mmtab);
	      else if (df)
		display_bindkey("Default", dmtab);
	      else
		display_bindkey("User", umtab);
	      break;
	    }
	  if (kf == 0)
	    {
	      if (af)
		{
		  OutputMsg(0, "%s: bindkey: -a only works with -k", rc_name);
		  break;
		}
	      if (*argl == 0)
		{
		  OutputMsg(0, "%s: bindkey: empty string makes no sense", rc_name);
		  break;
		}
	      for (i = 0, kme = kmap_exts; i < kmap_extn; i++, kme++)
		if (kme->str == 0)
		  {
		    if (args[1])
		      break;
		  }
		else
		  if (*argl == (kme->fl & ~KMAP_NOTIMEOUT) && bcmp(kme->str, *args, *argl) == 0)
		      break;
	      if (i == kmap_extn)
		{
		  if (!args[1])
		    {
		      OutputMsg(0, "%s: bindkey: keybinding not found", rc_name);
		      break;
		    }
		  kmap_extn += 8;
		  kmap_exts = (struct kmap_ext *)xrealloc((char *)kmap_exts, kmap_extn * sizeof(*kmap_exts));
		  kme = kmap_exts + i;
		  bzero((char *)kme, 8 * sizeof(*kmap_exts));
		  for (; i < kmap_extn; i++, kme++)
		    {
		      kme->str = 0;
		      kme->dm.nr = kme->mm.nr = kme->um.nr = RC_ILLEGAL;
		      kme->dm.args = kme->mm.args = kme->um.args = noargs;
		      kme->dm.argl = kme->mm.argl = kme->um.argl = 0;
		    }
		  i -= 8;
		  kme -= 8;
		}
	      if (df == 0 && kme->dm.nr != RC_ILLEGAL)
		used = 1;
	      if (mf == 0 && kme->mm.nr != RC_ILLEGAL)
		used = 1;
	      if ((df || mf) && kme->um.nr != RC_ILLEGAL)
		used = 1;
	      i += KMAP_KEYS + KMAP_AKEYS;
	      newact = df ? &kme->dm : mf ? &kme->mm : &kme->um;
	    }
	  else
	    {
	      for (i = T_CAPS; i < T_OCAPS; i++)
		if (strcmp(term[i].tcname, *args) == 0)
		  break;
	      if (i == T_OCAPS)
		{
		  OutputMsg(0, "%s: bindkey: unknown key '%s'", rc_name, *args);
		  break;
		}
	      if (af && i >= T_CURSOR && i < T_OCAPS)
	        i -=  T_CURSOR - KMAP_KEYS;
	      else
	        i -=  T_CAPS;
	      newact = df ? &dmtab[i] : mf ? &mmtab[i] : &umtab[i];
	    }
	  if (args[1])
	    {
	      if ((newnr = FindCommnr(args[1])) == RC_ILLEGAL)
		{
		  OutputMsg(0, "%s: bindkey: unknown command '%s'", rc_name, args[1]);
		  break;
		}
	      if (CheckArgNum(newnr, args + 2) < 0)
		break;
	      ClearAction(newact);
	      SaveAction(newact, newnr, args + 2, argl + 2);
	      if (kf == 0 && args[1])
		{
		  if (kme->str)
		    free(kme->str);
		  kme->str = SaveStrn(*args, *argl);
		  kme->fl = fl | *argl;
		}
	    }
	  else
	    ClearAction(newact);
	  for (display = displays; display; display = display->d_next)
	    remap(i, args[1] ? 1 : 0);
	  if (kf == 0 && !args[1])
	    {
	      if (!used && kme->str)
		{
		  free(kme->str);
		  kme->str = 0;
		  kme->fl = 0;
		}
	    }
	  display = odisp;
	}
      break;
    case RC_MAPTIMEOUT:
      if (*args)
	{
          if (ParseNum(act, &n))
	    break;
	  if (n < 0)
	    {
	      OutputMsg(0, "%s: maptimeout: illegal time %d", rc_name, n);
	      break;
	    }
	  maptimeout = n;
	}
      if (*args == 0 || msgok)
        OutputMsg(0, "maptimeout is %dms", maptimeout);
      break;
    case RC_MAPNOTNEXT:
      D_dontmap = 1;
      break;
    case RC_MAPDEFAULT:
      D_mapdefault = 1;
      break;
#endif
#ifdef MULTIUSER
    case RC_ACLCHG:
    case RC_ACLADD:
    case RC_ADDACL:
    case RC_CHACL:
      UsersAcl(NULL, argc, args);
      break;
    case RC_ACLDEL:
      if (UserDel(args[0], NULL))
	break;
      if (msgok)
	OutputMsg(0, "%s removed from acl database", args[0]);
      break;
    case RC_ACLGRP:
      /*
       * modify a user to gain or lose rights granted to a group.
       * This group is actually a normal user whose rights were defined
       * with chacl in the usual way.
       */
      if (args[1])
        {
	  if (strcmp(args[1], "none"))	/* link a user to another user */
	    {
	      if (AclLinkUser(args[0], args[1]))
		break;
	      if (msgok)
		OutputMsg(0, "User %s joined acl-group %s", args[0], args[1]);
	    }
	  else				/* remove all groups from user */
	    {
	      struct acluser *u;
	      struct aclusergroup *g;

	      if (!(u = *FindUserPtr(args[0])))
	        break;
	      while ((g = u->u_group))
	        {
		  u->u_group = g->next;
	  	  free((char *)g);
	        }
	    }
	}
      else				/* show all groups of user */
	{
	  char buf[256], *p = buf;
	  int ngroups = 0;
	  struct acluser *u;
	  struct aclusergroup *g;

	  if (!(u = *FindUserPtr(args[0])))
	    {
	      if (msgok)
		OutputMsg(0, "User %s does not exist.", args[0]);
	      break;
	    }
	  g = u->u_group;
	  while (g)
	    {
	      ngroups++;
	      sprintf(p, "%s ", g->u->u_name);
	      p += strlen(p);
	      if (p > buf+200)
		break;
	      g = g->next;
	    }
	  if (ngroups)
	    *(--p) = '\0';
	  OutputMsg(0, "%s's group%s: %s.", args[0], (ngroups == 1) ? "" : "s",
	      (ngroups == 0) ? "none" : buf);
	}
      break;
    case RC_ACLUMASK:
    case RC_UMASK:
      while ((s = *args++))
        {
	  char *err = 0;

	  if (AclUmask(display ? D_user : users, s, &err))
	    OutputMsg(0, "umask: %s\n", err);
	}
      break;
    case RC_MULTIUSER:
      if (ParseOnOff(act, &n))
	break;
      multi = n ? "" : 0;
      chsock();
      if (msgok)
	OutputMsg(0, "Multiuser mode %s", multi ? "enabled" : "disabled");
      break;
#endif /* MULTIUSER */
#ifdef PSEUDOS
    case RC_EXEC:
      winexec(args);
      break;
#endif
#ifdef MULTI
    case RC_NONBLOCK:
      i = D_nonblock >= 0;
      if (*args && ((args[0][0] >= '0' && args[0][0] <= '9') || args[0][0] == '.'))
	{
          if (ParseNum1000(act, &i))
	    break;
	}
      else if (!ParseSwitch(act, &i))
	i = i == 0 ? -1 : 1000;
      else
	break;
      if (msgok && i == -1)
        OutputMsg(0, "display set to blocking mode");
      else if (msgok && i == 0)
        OutputMsg(0, "display set to nonblocking mode, no timeout");
      else if (msgok)
        OutputMsg(0, "display set to nonblocking mode, %.10gs timeout", i/1000.);
      D_nonblock = i;
      if (D_nonblock <= 0)
	evdeq(&D_blockedev);
      break;
    case RC_DEFNONBLOCK:
      if (*args && ((args[0][0] >= '0' && args[0][0] <= '9') || args[0][0] == '.'))
	{
          if (ParseNum1000(act, &defnonblock))
	    break;
	}
      else if (!ParseOnOff(act, &defnonblock))
        defnonblock = defnonblock == 0 ? -1 : 1000;
      else
	break;
      if (display && *rc_name)
	{
	  D_nonblock = defnonblock;
          if (D_nonblock <= 0)
	    evdeq(&D_blockedev);
	}
      break;
#endif
    case RC_GR:
#ifdef ENCODINGS
      if (fore->w_gr == 2)
	fore->w_gr = 0;
#endif
      if (ParseSwitch(act, &fore->w_gr) == 0 && msgok)
        OutputMsg(0, "Will %suse GR", fore->w_gr ? "" : "not ");
#ifdef ENCODINGS
      if (fore->w_gr == 0 && fore->w_FontE)
	fore->w_gr = 2;
#endif
      break;
    case RC_C1:
      if (ParseSwitch(act, &fore->w_c1) == 0 && msgok)
        OutputMsg(0, "Will %suse C1", fore->w_c1 ? "" : "not ");
      break;
#ifdef COLOR
    case RC_BCE:
      if (ParseSwitch(act, &fore->w_bce) == 0 && msgok)
        OutputMsg(0, "Will %serase with background color", fore->w_bce ? "" : "not ");
      break;
#endif
#ifdef ENCODINGS
    case RC_KANJI:
    case RC_ENCODING:
#ifdef UTF8
      if (*args && !strcmp(args[0], "-d"))
	{
	  if (!args[1])
	    OutputMsg(0, "encodings directory is %s", screenencodings ? screenencodings : "<unset>");
	  else
	    {
	      free(screenencodings);
	      screenencodings = SaveStr(args[1]);
	    }
	  break;
	}
      if (*args && !strcmp(args[0], "-l"))
	{
	  if (!args[1])
	    OutputMsg(0, "encoding: -l: argument required");
	  else if (LoadFontTranslation(-1, args[1]))
	    OutputMsg(0, "encoding: could not load utf8 encoding file");
	  else if (msgok)
	    OutputMsg(0, "encoding: utf8 encoding file loaded");
	  break;
	}
#else
      if (*args && (!strcmp(args[0], "-l") || !strcmp(args[0], "-d")))
	{
	  if (msgok)
	    OutputMsg(0, "encoding: screen is not compiled for UTF-8.");
	  break;
	}
#endif
      for (i = 0; i < 2; i++)
	{
	  if (args[i] == 0)
	    break;
	  if (!strcmp(args[i], "."))
	    continue;
	  n = FindEncoding(args[i]);
	  if (n == -1)
	    {
	      OutputMsg(0, "encoding: unknown encoding '%s'", args[i]);
	      break;
	    }
	  if (i == 0 && fore)
	    {
	      WinSwitchEncoding(fore, n);
	      ResetCharsets(fore);
	    }
	  else if (i && display)
	    D_encoding  = n;
	}
      break;
    case RC_DEFKANJI:
    case RC_DEFENCODING:
      n = FindEncoding(*args);
      if (n == -1)
	{
	  OutputMsg(0, "defencoding: unknown encoding '%s'", *args);
	  break;
	}
      nwin_default.encoding = n;
      break;
#endif

#ifdef UTF8
    case RC_DEFUTF8:
      n = nwin_default.encoding == UTF8;
      if (ParseSwitch(act, &n) == 0)
	{
	  nwin_default.encoding = n ? UTF8 : 0;
	  if (msgok)
            OutputMsg(0, "Will %suse UTF-8 encoding for new windows", n ? "" : "not ");
	}
      break;
    case RC_UTF8:
      for (i = 0; i < 2; i++)
	{
	  if (i && args[i] == 0)
	    break;
	  if (args[i] == 0)
	    n = fore->w_encoding != UTF8;
	  else if (strcmp(args[i], "off") == 0)
	    n = 0;
	  else if (strcmp(args[i], "on") == 0)
	    n = 1;
	  else
	    {
	      OutputMsg(0, "utf8: illegal argument (%s)", args[i]);
	      break;
	    }
	  if (i == 0)
	    {
	      WinSwitchEncoding(fore, n ? UTF8 : 0);
	      if (msgok)
		OutputMsg(0, "Will %suse UTF-8 encoding", n ? "" : "not ");
	    }
	  else if (display)
	    D_encoding = n ? UTF8 : 0;
	  if (args[i] == 0)
	    break;
	}
      break;
#endif

    case RC_PRINTCMD:
      if (*args)
	{
	  if (printcmd)
	    free(printcmd);
	  printcmd = 0;
	  if (**args)
	    printcmd = SaveStr(*args);
	}
      if (*args == 0 || msgok)
	{
	  if (printcmd)
	    OutputMsg(0, "using '%s' as print command", printcmd);
	  else
	    OutputMsg(0, "using termcap entries for printing");
	    break;
	}
      break;

    case RC_DIGRAPH:
      if (argl && argl[0] > 0 && args[1] && argl[1] > 0)
	{
	  if (argl[0] != 2)
	    {
	      OutputMsg(0, "Two characters expected to define a digraph");
	      break;
	    }
	  i = digraph_find(args[0]);
	  digraphs[i].d[0] = args[0][0];
	  digraphs[i].d[1] = args[0][1];
	  if (!parse_input_int(args[1], argl[1], &digraphs[i].value))
	    {
	      if (!(digraphs[i].value = atoi(args[1])))
		{
		  if (!args[1][1])
		    digraphs[i].value = (int)args[1][0];
#ifdef UTF8
		  else
		    {
		      int t;
		      unsigned char *s = (unsigned char *)args[1];
		      digraphs[i].value = 0;
		      while (*s)
			{
			  t = FromUtf8(*s++, &digraphs[i].value);
			  if (t == -1)
			    continue;
			  if (t == -2)
			    digraphs[i].value = 0;
			  else
			    digraphs[i].value = t;
			  break;
			}
		    }
#endif
		}
	    }
	  break;
	}
      Input("Enter digraph: ", 10, INP_EVERY, digraph_fn, NULL, 0);
      if (*args && **args)
	{
	  s = *args;
	  n = strlen(s);
	  LayProcess(&s, &n);
	}
      break;

    case RC_DEFHSTATUS:
      if (*args == 0)
	{
	  char buf[256];
          *buf = 0;
	  if (nwin_default.hstatus)
            AddXChars(buf, sizeof(buf), nwin_default.hstatus);
	  OutputMsg(0, "default hstatus is '%s'", buf);
	  break;
        }
      (void)ParseSaveStr(act, &nwin_default.hstatus);
      if (*nwin_default.hstatus == 0)
	{
	  free(nwin_default.hstatus);
	  nwin_default.hstatus = 0;
	}
      break;
    case RC_HSTATUS:
      (void)ParseSaveStr(act, &fore->w_hstatus);
      if (*fore->w_hstatus == 0)
	{
	  free(fore->w_hstatus);
	  fore->w_hstatus = 0;
	}
      WindowChanged(fore, 'h');
      break;

#ifdef FONT
    case RC_DEFCHARSET:
    case RC_CHARSET:
      if (*args == 0)
        {
	  char buf[256];
          *buf = 0;
	  if (nwin_default.charset)
            AddXChars(buf, sizeof(buf), nwin_default.charset);
	  OutputMsg(0, "default charset is '%s'", buf);
	  break;
        }
      n = strlen(*args);
      if (n == 0 || n > 6)
	{
	  OutputMsg(0, "%s: %s: string has illegal size.", rc_name, comms[nr].name);
	  break;
	}
      if (n > 4 && (
        ((args[0][4] < '0' || args[0][4] > '3') && args[0][4] != '.') ||
        ((args[0][5] < '0' || args[0][5] > '3') && args[0][5] && args[0][5] != '.')))
	{
	  OutputMsg(0, "%s: %s: illegal mapping number.", rc_name, comms[nr].name);
	  break;
	}
      if (nr == RC_CHARSET)
	{
	  SetCharsets(fore, *args);
	  break;
	}
      if (nwin_default.charset)
	free(nwin_default.charset);
      nwin_default.charset = SaveStr(*args);
      break;
#endif
#ifdef COLOR
    case RC_ATTRCOLOR:
      s = args[0];
      if (*s >= '0' && *s <= '9')
        i = *s - '0';
      else
	for (i = 0; i < 8; i++)
	  if (*s == "dubrsBiI"[i])
	    break;
      s++;
      nr = 0;
      if (*s && s[1] && !s[2])
	{
	  if (*s == 'd' && s[1] == 'd')
	    nr = 3;
	  else if (*s == '.' && s[1] == 'd')
	    nr = 2;
	  else if (*s == 'd' && s[1] == '.')
	    nr = 1;
	  else if (*s != '.' || s[1] != '.')
	    s--;
	  s += 2;
	}
      if (*s || i < 0 || i >= 8)
	{
	  OutputMsg(0, "%s: attrcolor: unknown attribute '%s'.", rc_name, args[0]);
	  break;
	}
      n = 0;
      if (args[1])
        n = ParseAttrColor(args[1], args[2], 1);
      if (n == -1)
	break;
      attr2color[i][nr] = n;
      n = 0;
      for (i = 0; i < 8; i++)
	if (attr2color[i][0] || attr2color[i][1] || attr2color[i][2] || attr2color[i][3])
	  n |= 1 << i;
      nattr2color = n;
      break;
#endif
    case RC_RENDITION:
      i = -1;
      if (strcmp(args[0], "bell") == 0)
	{
	  i = REND_BELL;
	}
      else if (strcmp(args[0], "monitor") == 0)
	{
	  i = REND_MONITOR;
	}
      else if (strcmp(args[0], "silence") == 0)
	{
	  i = REND_SILENCE;
	}
      else if (strcmp(args[0], "so") != 0)
	{
	  OutputMsg(0, "Invalid option '%s' for rendition", args[0]);
	  break;
	}

      ++args;
      ++argl;

      if (i != -1)
	{
	  renditions[i] = ParseAttrColor(args[0], args[1], 1);
	  WindowChanged((struct win *)0, 'w');
	  WindowChanged((struct win *)0, 'W');
	  WindowChanged((struct win *)0, 0);
	  break;
	}

      /* We are here, means we want to set the sorendition. */
      /* FALLTHROUGH*/
    case RC_SORENDITION:
      i = 0;
      if (*args)
	{
          i = ParseAttrColor(*args, args[1], 1);
	  if (i == -1)
	    break;
	  ApplyAttrColor(i, &mchar_so);
	  WindowChanged((struct win *)0, 0);
	  debug2("--> %x %x\n", mchar_so.attr, mchar_so.color);
	}
      if (msgok)
#ifdef COLOR
        OutputMsg(0, "Standout attributes 0x%02x  color 0x%02x", (unsigned char)mchar_so.attr, 0x99 ^ (unsigned char)mchar_so.color);
#else
        OutputMsg(0, "Standout attributes 0x%02x ", (unsigned char)mchar_so.attr);
#endif
      break;

      case RC_SOURCE:
	do_source(*args);
	break;

#ifdef MULTIUSER
    case RC_SU:
      s = NULL;
      if (!*args)
        {
	  OutputMsg(0, "%s:%s screen login", HostName, SockPath);
          InputSu(D_fore, &D_user, NULL);
	}
      else if (!args[1])
        InputSu(D_fore, &D_user, args[0]);
      else if (!args[2])
        s = DoSu(&D_user, args[0], args[1], "\377");
      else
        s = DoSu(&D_user, args[0], args[1], args[2]);
      if (s)
        OutputMsg(0, "%s", s);
      break;
#endif /* MULTIUSER */
    case RC_SPLIT:
      s = args[0];
      if (s && !strcmp(s, "-v"))
        AddCanvas(SLICE_HORI);
      else
        AddCanvas(SLICE_VERT);
      Activate(-1);
      break;
    case RC_REMOVE:
      RemCanvas();
      Activate(-1);
      break;
    case RC_ONLY:
      OneCanvas();
      Activate(-1);
      break;
    case RC_FIT:
      D_forecv->c_xoff = D_forecv->c_xs;
      D_forecv->c_yoff = D_forecv->c_ys;
      RethinkViewportOffsets(D_forecv);
      ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, 0);
      flayer = D_forecv->c_layer;
      LaySetCursor();
      break;
    case RC_FOCUS:
      {
	struct canvas *cv = 0;
	if (!*args || !strcmp(*args, "next"))
	  cv = D_forecv->c_next ? D_forecv->c_next : D_cvlist;
	else if (!strcmp(*args, "prev"))
	  {
	    for (cv = D_cvlist; cv->c_next && cv->c_next != D_forecv; cv = cv->c_next)
	      ;
	  }
	else if (!strcmp(*args, "top"))
	  cv = D_cvlist;
	else if (!strcmp(*args, "bottom"))
	  {
	    for (cv = D_cvlist; cv->c_next; cv = cv->c_next)
	      ;
	  }
	else if (!strcmp(*args, "up"))
	  cv = FindCanvas(D_forecv->c_xs, D_forecv->c_ys - 1);
	else if (!strcmp(*args, "down"))
	  cv = FindCanvas(D_forecv->c_xs, D_forecv->c_ye + 2);
	else if (!strcmp(*args, "left"))
	  cv = FindCanvas(D_forecv->c_xs - 1, D_forecv->c_ys);
	else if (!strcmp(*args, "right"))
	  cv = FindCanvas(D_forecv->c_xe + 1, D_forecv->c_ys);
	else
	  {
	    OutputMsg(0, "%s: usage: focus [next|prev|up|down|left|right|top|bottom]", rc_name);
	    break;
	  }
	SetForeCanvas(display, cv);
      }
      break;
    case RC_RESIZE:
      i = 0;
      if (D_forecv->c_slorient == SLICE_UNKN)
	{
	  OutputMsg(0, "resize: need more than one region");
	  break;
	}
      for (; *args; args++)
	{
	  if (!strcmp(*args, "-h"))
	    i |= RESIZE_FLAG_H;
	  else if (!strcmp(*args, "-v"))
	    i |= RESIZE_FLAG_V;
	  else if (!strcmp(*args, "-b"))
	    i |= RESIZE_FLAG_H | RESIZE_FLAG_V;
	  else if (!strcmp(*args, "-p"))
	    i |= D_forecv->c_slorient == SLICE_VERT ? RESIZE_FLAG_H : RESIZE_FLAG_V;
	  else if (!strcmp(*args, "-l"))
	    i |= RESIZE_FLAG_L;
	  else
	    break;
	}
      if (*args && args[1])
	{
	  OutputMsg(0, "%s: usage: resize [-h] [-v] [-l] [num]\n", rc_name);
	  break;
	}
      if (*args)
	ResizeRegions(*args, i);
      else
	Input(resizeprompts[i], 20, INP_EVERY, ResizeFin, (char*)0, i);
      break;
    case RC_SETSID:
      (void)ParseSwitch(act, &separate_sids);
      break;
    case RC_EVAL:
      args = SaveArgs(args);
      for (i = 0; args[i]; i++)
	{
	  if (args[i][0])
	    Colonfin(args[i], strlen(args[i]), (char *)0);
	  free(args[i]);
	}
      free(args);
      break;
    case RC_ALTSCREEN:
      (void)ParseSwitch(act, &use_altscreen);
      if (msgok)
        OutputMsg(0, "Will %sdo alternate screen switching", use_altscreen ? "" : "not ");
      break;
    case RC_MAXWIN:
      if (!args[0])
	{
	  OutputMsg(0, "maximum windows allowed: %d", maxwin);
	  break;
	}
      if (ParseNum(act, &n))
	break;
      if (n < 1)
        OutputMsg(0, "illegal maxwin number specified");
      else if (n > 2048)
	OutputMsg(0, "maximum 2048 windows allowed");
      else if (n > maxwin && windows)
	OutputMsg(0, "may increase maxwin only when there's no window");
      else
	{
	  if (!windows)
            {
	      wtab = realloc(wtab, n * sizeof(struct win *));
              bzero(wtab, n * sizeof(struct win *));
            }
	  maxwin = n;
	}
      break;
    case RC_BACKTICK:
      if (ParseBase(act, *args, &n, 10, "decimal"))
	break;
      if (!args[1])
        setbacktick(n, 0, 0, (char **)0);
      else
	{
	  int lifespan, tick;
	  if (argc < 4)
	    {
	      OutputMsg(0, "%s: usage: backtick num [lifespan tick cmd args...]", rc_name);
	      break;
	    }
	  if (ParseBase(act, args[1], &lifespan, 10, "decimal"))
	    break;
	  if (ParseBase(act, args[2], &tick, 10, "decimal"))
	    break;
	  setbacktick(n, lifespan, tick, SaveArgs(args + 3));
	}
      WindowChanged(0, '`');
      break;
    case RC_BLANKER:
#ifdef BLANKER_PRG
      if (blankerprg)
	{
          RunBlanker(blankerprg);
	  break;
	}
#endif
      ClearAll();
      CursorVisibility(-1);
      D_blocked = 4;
      break;
#ifdef BLANKER_PRG
    case RC_BLANKERPRG:
      if (!args[0])
	{
	  if (blankerprg)
	    {
	      char path[MAXPATHLEN];
	      char *p = path, **pp;
	      for (pp = blankerprg; *pp; pp++)
		p += snprintf(p, sizeof(path) - (p - path) - 1, "%s ", *pp);
	      *(p - 1) = '\0';
	      OutputMsg(0, "blankerprg: %s", path);
	    }
	  else
	    OutputMsg(0, "No blankerprg set.");
	  break;
	}
      if (blankerprg)
	{
	  char **pp;
	  for (pp = blankerprg; *pp; pp++)
	    free(*pp);
	  free(blankerprg);
	  blankerprg = 0;
	}
      if (args[0][0])
	blankerprg = SaveArgs(args);
      break;
#endif
    case RC_IDLE:
      if (*args)
	{
	  struct display *olddisplay = display;
	  if (!strcmp(*args, "off"))
	    idletimo = 0;
	  else if (args[0][0])
	    idletimo = atoi(*args) * 1000;
	  if (argc > 1)
	    {
	      if ((i = FindCommnr(args[1])) == RC_ILLEGAL)
		{
		  OutputMsg(0, "%s: idle: unknown command '%s'", rc_name, args[1]);
		  break;
		}
	      if (CheckArgNum(i, args + 2) < 0)
		break;
	      ClearAction(&idleaction);
	      SaveAction(&idleaction, i, args + 2, argl + 2);
	    }
	  for (display = displays; display; display = display->d_next)
	    ResetIdle();
	  display = olddisplay;
	}
      if (msgok)
	{
	  if (idletimo)
	    OutputMsg(0, "idle timeout %ds, %s", idletimo / 1000, comms[idleaction.nr].name);
	  else
	    OutputMsg(0, "idle off");
	}
      break;
    case RC_FOCUSMINSIZE:
      for (i = 0; i < 2 && args[i]; i++)
	{
	  if (!strcmp(args[i], "max") || !strcmp(args[i], "_"))
	    n = -1;
	  else
	    n = atoi(args[i]);
	  if (i == 0)
	    focusminwidth = n;
	  else
            focusminheight = n;
	}
      if (msgok)
	{
	  char b[2][20];
	  for (i = 0; i < 2; i++)
	    {
	      n = i == 0 ? focusminwidth : focusminheight;
	      if (n == -1)
		strcpy(b[i], "max");
	      else
		sprintf(b[i], "%d", n);
	    }
          OutputMsg(0, "focus min size is %s %s\n", b[0], b[1]);
	}
      break;
    case RC_GROUP:
      if (*args)
	{
	  fore->w_group = 0;
	  if (args[0][0])
	    {
	      fore->w_group = WindowByName(*args);
	      if (fore->w_group == fore || (fore->w_group && fore->w_group->w_type != W_TYPE_GROUP))
		fore->w_group = 0;
	    }
	  WindowChanged((struct win *)0, 'w');
	  WindowChanged((struct win *)0, 'W');
	  WindowChanged((struct win *)0, 0);
	}
      if (msgok)
	{
	  if (fore->w_group)
	    OutputMsg(0, "window group is %d (%s)\n", fore->w_group->w_number, fore->w_group->w_title);
	  else
	    OutputMsg(0, "window belongs to no group");
	}
      break;
    case RC_LAYOUT:
      // A number of the subcommands for "layout" are ignored, or not processed correctly when there
      // is no attached display.

      if (!strcmp(args[0], "title"))
	{
          if (!display)
            {
	      if (!args[1])  // There is no display, and there is no new title. Ignore.
		break;
	      if (!layout_attach || layout_attach == &layout_last_marker)
		layout_attach = CreateLayout(args[1], 0);
	      else
		RenameLayout(layout_attach, args[1]);
	      break;
	    }

	  if (!D_layout)
	    {
	      OutputMsg(0, "not on a layout");
	      break;
	    }
	  if (!args[1])
	    {
	      OutputMsg(0, "current layout is %d (%s)", D_layout->lay_number, D_layout->lay_title);
	      break;
	    }
	  RenameLayout(D_layout, args[1]);
	}
      else if (!strcmp(args[0], "number"))
	{
	  if (!display)
	    {
	      if (args[1] && layout_attach && layout_attach != &layout_last_marker)
		RenumberLayout(layout_attach, atoi(args[1]));
	      break;
	    }

	  if (!D_layout)
	    {
	      OutputMsg(0, "not on a layout");
	      break;
	    }
	  if (!args[1])
	    {
	      OutputMsg(0, "This is layout %d (%s).\n", D_layout->lay_number, D_layout->lay_title);
	      break;
	    }
	   RenumberLayout(D_layout, atoi(args[1]));
	   break;
	}
      else if (!strcmp(args[0], "autosave"))
	{
	  if (!display)
	    {
	      if (args[1] && layout_attach && layout_attach != &layout_last_marker)
		{
		  if (!strcmp(args[1], "on"))
		    layout_attach->lay_autosave = 1;
		  else if (!strcmp(args[1], "off"))
		    layout_attach->lay_autosave = 0;
		}
	      break;
	    }

	  if (!D_layout)
	    {
	      OutputMsg(0, "not on a layout");
	      break;
	    }
	  if (args[1])
	    {
	      if (!strcmp(args[1], "on"))
		D_layout->lay_autosave = 1;
	      else if (!strcmp(args[1], "off"))
		D_layout->lay_autosave = 0;
	      else
		{
		  OutputMsg(0, "invalid argument. Give 'on' or 'off");
		  break;
		}
	    }
	  if (msgok)
	    OutputMsg(0, "autosave is %s", D_layout->lay_autosave ? "on" : "off");
	}
      else if (!strcmp(args[0], "new"))
	{
	  char *t = args[1];
	  n = 0;
	  if (t)
	    {
	      while (*t >= '0' && *t <= '9')
		t++;
	      if (t != args[1] && (!*t || *t == ':'))
		{
		  n = atoi(args[1]);
		  if (*t)
		    t++;
		}
	      else
		t = args[1];
	    }
	  if (!t || !*t)
	    t = "layout";
          NewLayout(t, n);
	  Activate(-1);
	}
      else if (!strcmp(args[0], "save"))
	{
	  if (!args[1])
	    {
	      OutputMsg(0, "usage: layout save <name>");
	      break;
	    }
	  if (display)
	    SaveLayout(args[1], &D_canvas);
	}
      else if (!strcmp(args[0], "select"))
	{
	  if (!display)
	    {
	      if (args[1])
		layout_attach = FindLayout(args[1]);
	      break;
	    }
          if (!args[1])
	    {
	      Input("Switch to layout: ", 20, INP_COOKED, SelectLayoutFin, NULL, 0);
	      break;
	    }
	  SelectLayoutFin(args[1], strlen(args[1]), (char *)0);
	}
      else if (!strcmp(args[0], "next"))
	{
	  if (!display)
	    {
	      if (layout_attach && layout_attach != &layout_last_marker)
		layout_attach = layout_attach->lay_next ? layout_attach->lay_next : layouts;;
	      break;
	    }
	  struct layout *lay = D_layout;
	  if (lay)
	    lay = lay->lay_next ? lay->lay_next : layouts;
	  else
	    lay = layouts;
	  if (!lay)
	    {
	      OutputMsg(0, "no layout defined");
	      break;
	    }
	  if (lay == D_layout)
	    break;
	  LoadLayout(lay, &D_canvas);
	  Activate(-1);
	}
      else if (!strcmp(args[0], "prev"))
	{
	  struct layout *lay = display ? D_layout : layout_attach;
	  struct layout *target = lay;
	  if (lay)
	    {
	      for (lay = layouts; lay->lay_next && lay->lay_next != target; lay = lay->lay_next)
		;
	    }
	  else
	    lay = layouts;

	  if (!display)
	    {
	      layout_attach = lay;
	      break;
	    }

	  if (!lay)
	    {
	      OutputMsg(0, "no layout defined");
	      break;
	    }
	  if (lay == D_layout)
	    break;
	  LoadLayout(lay, &D_canvas);
	  Activate(-1);
	}
      else if (!strcmp(args[0], "attach"))
	{
	  if (!args[1])
	    {
	      if (!layout_attach)
	        OutputMsg(0, "no attach layout set");
	      else if (layout_attach == &layout_last_marker)
	        OutputMsg(0, "will attach to last layout");
	      else
	        OutputMsg(0, "will attach to layout %d (%s)", layout_attach->lay_number, layout_attach->lay_title);
	      break;
	    }
	  if (!strcmp(args[1], ":last"))
	    layout_attach = &layout_last_marker;
	  else if (!args[1][0])
	    layout_attach = 0;
	  else
	    {
	      struct layout *lay;
	      lay = FindLayout(args[1]);
	      if (!lay)
		{
		  OutputMsg(0, "unknown layout '%s'", args[1]);
		  break;
		}
	      layout_attach = lay;
	    }
	}
      else if (!strcmp(args[0], "show"))
	{
	  ShowLayouts(-1);
	}
      else if (!strcmp(args[0], "remove"))
	{
	  struct layout *lay = display ? D_layout : layouts;
	  if (args[1])
	    {
	      lay = layouts ? FindLayout(args[1]) : (struct layout *)0;
	      if (!lay)
		{
		  OutputMsg(0, "unknown layout '%s'", args[1]);
		  break;
		}
	    }
	  if (lay)
	    RemoveLayout(lay);
	}
      else if (!strcmp(args[0], "dump"))
	{
	  if (!display)
	    OutputMsg(0, "Must have a display for 'layout dump'.");
	  else if (!LayoutDumpCanvas(&D_canvas, args[1] ? args[1] : "layout-dump"))
	    OutputMsg(errno, "Error dumping layout.");
	  else
	    OutputMsg(0, "Layout dumped to \"%s\"", args[1] ? args[1] : "layout-dump");
	}
      else
	OutputMsg(0, "unknown layout subcommand");
      break;
#ifdef DW_CHARS
    case RC_CJKWIDTH:
      if(ParseSwitch(act, &cjkwidth) == 0)
      {
        if(msgok)
          OutputMsg(0, "Treat ambiguous width characters as %s width", cjkwidth ? "full" : "half");
      }
      break;
#endif
    default:
#ifdef HAVE_BRAILLE
      /* key == -2: input from braille keybord, msgok always 0 */
      DoBrailleAction(act, key == -2 ? 0 : msgok);
#endif
      break;
    }
  if (display != odisplay)
    {
      for (display = displays; display; display = display->d_next)
        if (display == odisplay)
	  break;
    }
}
#undef OutputMsg

void
CollapseWindowlist()
/* renumber windows from 0, leaving no gaps */
{
  int pos, moveto=0;

  for (pos = 1; pos < MAXWIN; pos++)
    if (wtab[pos])
      for (; moveto < pos; moveto++)
        if (!wtab[moveto])
          {
          WindowChangeNumber(pos, moveto);
          break;
          }
}

void
DoCommand(argv, argl) 
char **argv;
int *argl;
{
  struct action act;
  const char *cmd = *argv;

  act.quiet = 0;
  /* For now, we actually treat both 'supress error' and 'suppress normal message' as the
   * same, and ignore all messages on either flag. If we wanted to do otherwise, we would
   * need to change the definition of 'OutputMsg' slightly. */
  if (*cmd == '@')	/* Suppress error */
    {
      act.quiet |= 0x01;
      cmd++;
    }
  if (*cmd == '-')	/* Suppress normal message */
    {
      act.quiet |= 0x02;
      cmd++;
    }

  if ((act.nr = FindCommnr(cmd)) == RC_ILLEGAL)
    {
      Msg(0, "%s: unknown command '%s'", rc_name, cmd);
      return;
    }
  act.args = argv + 1;
  act.argl = argl + 1;
  DoAction(&act, -1);
}

static void
SaveAction(act, nr, args, argl)
struct action *act;
int nr;
char **args;
int *argl;
{
  register int argc = 0;
  char **pp;
  int *lp;

  if (args)
    while (args[argc])
      argc++;
  if (argc == 0)
    {
      act->nr = nr;
      act->args = noargs;
      act->argl = 0;
      return;
    }
  if ((pp = (char **)malloc((unsigned)(argc + 1) * sizeof(char *))) == 0)
    Panic(0, "%s", strnomem);
  if ((lp = (int *)malloc((unsigned)(argc) * sizeof(int))) == 0)
    Panic(0, "%s", strnomem);
  act->nr = nr;
  act->args = pp;
  act->argl = lp;
  while (argc--)
    {
      *lp = argl ? *argl++ : (int)strlen(*args);
      *pp++ = SaveStrn(*args++, *lp++);
    }
  *pp = 0;
}

static char **
SaveArgs(args)
char **args;
{
  register char **ap, **pp;
  register int argc = 0;

  while (args[argc])
    argc++;
  if ((pp = ap = (char **)malloc((unsigned)(argc + 1) * sizeof(char **))) == 0)
    Panic(0, "%s", strnomem);
  while (argc--)
    *pp++ = SaveStr(*args++);
  *pp = 0;
  return ap;
}


/*
 * buf is split into argument vector args.
 * leading whitespace is removed.
 * @!| abbreviations are expanded.
 * the end of buffer is recognized by '\0' or an un-escaped '#'.
 * " and ' are interpreted.
 *
 * argc is returned.
 */
int 
Parse(buf, bufl, args, argl)
char *buf, **args;
int bufl, *argl;
{
  register char *p = buf, **ap = args, *pp;
  register int delim, argc;
  int *lp = argl;

  debug2("Parse %d %s\n", bufl, buf);
  argc = 0;
  pp = buf;
  delim = 0;
  for (;;)
    {
      *lp = 0;
      while (*p && (*p == ' ' || *p == '\t'))
	++p;
#ifdef PSEUDOS
      if (argc == 0 && *p == '!')
	{
	  *ap++ = "exec";
	  *lp++ = 4;
	  p++;
	  argc++;
	  continue;
        }
#endif
      if (*p == '\0' || *p == '#' || *p == '\n')
	{
	  *p = '\0';
	  for (delim = 0; delim < argc; delim++)
	    debug1("-- %s\n", args[delim]);
	  args[argc] = 0;
	  return argc;
	}
      if (++argc >= MAXARGS)
	{
	  Msg(0, "%s: too many tokens.", rc_name);
	  return 0;
	}
      *ap++ = pp;

      debug1("- new arg %s\n", p);
      while (*p)
	{
	  if (*p == delim)
	    delim = 0;
	  else if (delim != '\'' && *p == '\\' && (p[1] == 'n' || p[1] == 'r' || p[1] == 't' || p[1] == '\'' || p[1] == '"' || p[1] == '\\' || p[1] == '$' || p[1] == '#' || p[1] == '^' || (p[1] >= '0' && p[1] <= '7')))
	    {
	      p++;
	      if (*p >= '0' && *p <= '7')
		{
		  *pp = *p - '0';
		  if (p[1] >= '0' && p[1] <= '7')
		    {
		      p++;
		      *pp = (*pp << 3) | (*p - '0');
		      if (p[1] >= '0' && p[1] <= '7')
			{
			  p++;
			  *pp = (*pp << 3) | (*p - '0');
			}
		    }
		  pp++;
		}
	      else
		{
		  switch (*p)
		    {
		      case 'n': *pp = '\n'; break;
		      case 'r': *pp = '\r'; break;
		      case 't': *pp = '\t'; break;
		      default: *pp = *p; break;
		    }
		  pp++;
		}
	    }
	  else if (delim != '\'' && *p == '$' && (p[1] == '{' || p[1] == ':' || (p[1] >= 'a' && p[1] <= 'z') || (p[1] >= 'A' && p[1] <= 'Z') || (p[1] >= '0' && p[1] <= '9') || p[1] == '_'))

	    {
	      char *ps, *pe, op, *v, xbuf[11], path[MAXPATHLEN];
	      int vl;

	      ps = ++p;
	      debug1("- var %s\n", ps);
	      p++;
	      while (*p)
		{
		  if (*ps == '{' && *p == '}')
		    break;
		  if (*ps == ':' && *p == ':')
		    break;
		  if (*ps != '{' && *ps != ':' && (*p < 'a' || *p > 'z') && (*p < 'A' || *p > 'Z') && (*p < '0' || *p > '9') && *p != '_')
		    break;
		  p++;
		}
	      pe = p;
	      if (*ps == '{' || *ps == ':')
		{
		  if (!*p)
		    {
		      Msg(0, "%s: bad variable name.", rc_name);
		      return 0;
		    }
		  p++;
		}
	      op = *pe;
	      *pe = 0;
	      debug1("- var is '%s'\n", ps);
	      if (*ps == ':')
		v = gettermcapstring(ps + 1);
	      else
		{
		  if (*ps == '{')
		    ps++;
		  v = xbuf;
		  if (!strcmp(ps, "TERM"))
		    v = display ? D_termname : "unknown";
		  else if (!strcmp(ps, "COLUMNS"))
		    sprintf(xbuf, "%d", display ? D_width : -1);
		  else if (!strcmp(ps, "LINES"))
		    sprintf(xbuf, "%d", display ? D_height : -1);
		  else if (!strcmp(ps, "PID"))
		    sprintf(xbuf, "%d", getpid());
		  else if (!strcmp(ps, "PWD"))
		    {
		      if (getcwd(path, sizeof(path) - 1) == 0)
			v = "?";
		      else
			v = path;
		    }
		  else if (!strcmp(ps, "STY"))
		    {
		      if ((v = strchr(SockName, '.')))	/* Skip the PID */
			v++;
		      else
			v = SockName;
		    }
		  else
		    v = getenv(ps);
		}
	      *pe = op;
	      vl = v ? strlen(v) : 0;
	      if (vl)
		{
		  debug1("- sub is '%s'\n", v);
		  if (p - pp < vl)
		    {
		      int right = buf + bufl - (p + strlen(p) + 1);
		      if (right > 0)
			{
			  bcopy(p, p + right, strlen(p) + 1);
			  p += right;
			}
		    }
		  if (p - pp < vl)
		    {
		      Msg(0, "%s: no space left for variable expansion.", rc_name);
		      return 0;
		    }
		  bcopy(v, pp, vl);
		  pp += vl;
		}
	      continue;
	    }
	  else if (delim != '\'' && *p == '^' && p[1])
	    {
	      p++;
	      *pp++ = *p == '?' ? '\177' : *p & 0x1f;
	    }
	  else if (delim == 0 && (*p == '\'' || *p == '"'))
	    delim = *p;
	  else if (delim == 0 && (*p == ' ' || *p == '\t' || *p == '\n'))
	    break;
	  else
	    *pp++ = *p;
	  p++;
	}
      if (delim)
	{
	  Msg(0, "%s: Missing %c quote.", rc_name, delim);
	  return 0;
	}
      if (*p)
	p++;
      *pp = 0;
      debug2("- arg done, '%s' rest %s\n", ap[-1], p);
      *lp++ = pp - ap[-1];
      pp++;
    }
}

void
SetEscape(u, e, me)
struct acluser *u;
int e, me;
{
  if (u)
    {
      u->u_Esc = e;
      u->u_MetaEsc = me;
    }
  else
    {
      if (users)
	{
	  if (DefaultEsc >= 0)
	    ClearAction(&ktab[DefaultEsc]);
	  if (DefaultMetaEsc >= 0)
	    ClearAction(&ktab[DefaultMetaEsc]);
	}
      DefaultEsc = e;
      DefaultMetaEsc = me;
      if (users)
	{
	  if (DefaultEsc >= 0)
	    {
	      ClearAction(&ktab[DefaultEsc]);
	      ktab[DefaultEsc].nr = RC_OTHER;
	    }
	  if (DefaultMetaEsc >= 0)
	    {
	      ClearAction(&ktab[DefaultMetaEsc]);
	      ktab[DefaultMetaEsc].nr = RC_META;
	    }
	}
    }
}

int
ParseSwitch(act, var)
struct action *act;
int *var;
{
  if (*act->args == 0)
    {
      *var ^= 1;
      return 0;
    }
  return ParseOnOff(act, var);
}

static int
ParseOnOff(act, var)
struct action *act;
int *var;
{
  register int num = -1;
  char **args = act->args;

  if (args[1] == 0)
    {
      if (strcmp(args[0], "on") == 0)
	num = 1;
      else if (strcmp(args[0], "off") == 0)
	num = 0;
    }
  if (num < 0)
    {
      Msg(0, "%s: %s: invalid argument. Give 'on' or 'off'", rc_name, comms[act->nr].name);
      return -1;
    }
  *var = num;
  return 0;
}

int
ParseSaveStr(act, var)
struct action *act;
char **var;
{
  char **args = act->args;
  if (*args == 0 || args[1])
    {
      Msg(0, "%s: %s: one argument required.", rc_name, comms[act->nr].name);
      return -1;
    }
  if (*var)
    free(*var);
  *var = SaveStr(*args);
  return 0;
}

int
ParseNum(act, var)
struct action *act;
int *var;
{
  int i;
  char *p, **args = act->args;

  p = *args;
  if (p == 0 || *p == 0 || args[1])
    {
      Msg(0, "%s: %s: invalid argument. Give one argument.",
          rc_name, comms[act->nr].name);
      return -1;
    }
  i = 0; 
  while (*p)
    {
      if (*p >= '0' && *p <= '9')
	i = 10 * i + (*p - '0');
      else
	{
	  Msg(0, "%s: %s: invalid argument. Give numeric argument.",
	      rc_name, comms[act->nr].name);
	  return -1;
	}    
      p++;
    }
  debug1("ParseNum got %d\n", i);
  *var = i;
  return 0;
}

static int
ParseNum1000(act, var)
struct action *act;
int *var;
{
  int i;
  char *p, **args = act->args;
  int dig = 0;

  p = *args;
  if (p == 0 || *p == 0 || args[1])
    {
      Msg(0, "%s: %s: invalid argument. Give one argument.",
          rc_name, comms[act->nr].name);
      return -1;
    }
  i = 0; 
  while (*p)
    {
      if (*p >= '0' && *p <= '9')
	{
	  if (dig < 4)
	    i = 10 * i + (*p - '0');
          else if (dig == 4 && *p >= '5')
	    i++;
	  if (dig)
	    dig++;
	}
      else if (*p == '.' && !dig)
        dig++;
      else
	{
	  Msg(0, "%s: %s: invalid argument. Give floating point argument.",
	      rc_name, comms[act->nr].name);
	  return -1;
	}    
      p++;
    }
  if (dig == 0)
    i *= 1000;
  else
    while (dig++ < 4)
      i *= 10;
  if (i < 0)
    i = (int)((unsigned int)~0 >> 1);
  debug1("ParseNum1000 got %d\n", i);
  *var = i;
  return 0;
}

static struct win *
WindowByName(s)
char *s;
{
  struct win *p;

  for (p = windows; p; p = p->w_next)
    if (!strcmp(p->w_title, s))
      return p;
  for (p = windows; p; p = p->w_next)
    if (!strncmp(p->w_title, s, strlen(s)))
      return p;
  return 0;
}

static int
WindowByNumber(str)
char *str;
{
  int i;
  char *s;

  for (i = 0, s = str; *s; s++)
    {
      if (*s < '0' || *s > '9')
        break;
      i = i * 10 + (*s - '0');
    }
  return *s ? -1 : i;
}

/* 
 * Get window number from Name or Number string.
 * Numbers are tried first, then names, a prefix match suffices.
 * Be careful when assigning numeric strings as WindowTitles.
 */
int
WindowByNoN(str)
char *str;
{
  int i;
  struct win *p;
  
  if ((i = WindowByNumber(str)) < 0 || i >= maxwin)
    {
      if ((p = WindowByName(str)))
	return p->w_number;
      return -1;
    }
  return i;
}

static int
ParseWinNum(act, var)
struct action *act;
int *var;
{
  char **args = act->args;
  int i = 0;

  if (*args == 0 || args[1])
    {
      Msg(0, "%s: %s: one argument required.", rc_name, comms[act->nr].name);
      return -1;
    }
  
  i = WindowByNoN(*args);
  if (i < 0)
    {
      Msg(0, "%s: %s: invalid argument. Give window number or name.",
          rc_name, comms[act->nr].name);
      return -1;
    }
  debug1("ParseWinNum got %d\n", i);
  *var = i;
  return 0;
}

static int
ParseBase(act, p, var, base, bname)
struct action *act;
char *p;
int *var;
int base;
char *bname;
{
  int i = 0;
  int c;

  if (*p == 0)
    {
      Msg(0, "%s: %s: empty argument.", rc_name, comms[act->nr].name);
      return -1;
    }
  while ((c = *p++))
    {
      if (c >= 'a' && c <= 'z')
	c -= 'a' - 'A';
      if (c >= 'A' && c <= 'Z')
	c -= 'A' - ('0' + 10);
      c -= '0';
      if (c < 0 || c >= base)
	{
	  Msg(0, "%s: %s: argument is not %s.", rc_name, comms[act->nr].name, bname);
	  return -1;
	}    
      i = base * i + c;
    }
  debug1("ParseBase got %d\n", i);
  *var = i;
  return 0;
}

static int
IsNum(s, base)
register char *s;
register int base;
{
  for (base += '0'; *s; ++s)
    if (*s < '0' || *s > base)
      return 0;
  return 1;
}

int
IsNumColon(s, base, p, psize)
int base, psize;
char *s, *p;
{
  char *q;
  if ((q = rindex(s, ':')) != 0)
    {
      strncpy(p, q + 1, psize - 1);
      p[psize - 1] = '\0';
      *q = '\0';
    }
  else
    *p = '\0';
  return IsNum(s, base);
}

void
SwitchWindow(n)
int n;
{
  struct win *p;

  debug1("SwitchWindow %d\n", n);
  if (n < 0 || n >= maxwin)
    {
      ShowWindows(-1);
      return;
    }
  if ((p = wtab[n]) == 0)
    {
      ShowWindows(n);
      return;
    }
  if (display == 0)
    {
      fore = p;
      return;
    }
  if (p == D_fore)
    {
      Msg(0, "This IS window %d (%s).", n, p->w_title);
      return;
    }
#ifdef MULTIUSER
  if (AclCheckPermWin(D_user, ACL_READ, p))
    {
      Msg(0, "Access to window %d denied.", p->w_number);
      return;
    }
#endif
  SetForeWindow(p);
  Activate(fore->w_norefresh);  
}

/*
 * SetForeWindow changes the window in the input focus of the display.
 * Puts window wi in canvas display->d_forecv.
 */
void
SetForeWindow(wi)
struct win *wi;
{
  struct win *p;
  if (display == 0)
    {
      fore = wi;
      return;
    }
  p = Layer2Window(D_forecv->c_layer);
  SetCanvasWindow(D_forecv, wi);
  if (p)
    WindowChanged(p, 'u');
  if (wi)
    WindowChanged(wi, 'u');
  flayer = D_forecv->c_layer;
  /* Activate called afterwards, so no RefreshHStatus needed */
}


/*****************************************************************/

/* 
 *  Activate - make fore window active
 *  norefresh = -1 forces a refresh, disregard all_norefresh then.
 */
void
Activate(norefresh)
int norefresh;
{
  debug1("Activate(%d)\n", norefresh);
  if (display == 0)
    return;
  if (D_status)
    {
      Msg(0, "%s", "");	/* wait till mintime (keep gcc quiet) */
      RemoveStatus();
    }

  if (MayResizeLayer(D_forecv->c_layer))
    ResizeLayer(D_forecv->c_layer, D_forecv->c_xe - D_forecv->c_xs + 1, D_forecv->c_ye - D_forecv->c_ys + 1, display);

  fore = D_fore;
  if (fore)
    {
      /* XXX ? */
      if (fore->w_monitor != MON_OFF)
	fore->w_monitor = MON_ON;
      fore->w_bell = BELL_ON;
      WindowChanged(fore, 'f');

#if 0
      if (ResizeDisplay(fore->w_width, fore->w_height))
	{
	  debug2("Cannot resize from (%d,%d)", D_width, D_height);
	  debug2(" to (%d,%d) -> resize window\n", fore->w_width, fore->w_height);
	  DoResize(D_width, D_height);
	}
#endif
    }
  Redisplay(norefresh + all_norefresh);
}


static int
NextWindow()
{
  register struct win **pp;
  int n = fore ? fore->w_number : maxwin;
  struct win *group = fore ? fore->w_group : 0;

  for (pp = fore ? wtab + n + 1 : wtab; pp != wtab + n; pp++)
    {
      if (pp == wtab + maxwin)
	pp = wtab;
      if (*pp)
	{
	  if (!fore || group == (*pp)->w_group)
	    break;
	}
    }
  if (pp == wtab + n)
    return -1;
  return pp - wtab;
}

static int
PreviousWindow()
{
  register struct win **pp;
  int n = fore ? fore->w_number : -1;
  struct win *group = fore ? fore->w_group : 0;

  for (pp = wtab + n - 1; pp != wtab + n; pp--)
    {
      if (pp == wtab - 1)
	pp = wtab + maxwin - 1;
      if (*pp)
	{
	  if (!fore || group == (*pp)->w_group)
	    break;
	}
    }
  if (pp == wtab + n)
    return -1;
  return pp - wtab;
}

static int
MoreWindows()
{
  char *m = "No other window.";
  if (windows && (fore == 0 || windows->w_next))
    return 1;
  if (fore == 0)
    {
      Msg(0, "No window available");
      return 0;
    }
  Msg(0, m, fore->w_number);	/* other arg for nethack */
  return 0;
}

void
KillWindow(wi)
struct win *wi;
{
  struct win **pp, *p;
  struct canvas *cv;
  int gotone;
  struct layout *lay;

  /*
   * Remove window from linked list.
   */
  for (pp = &windows; (p = *pp); pp = &p->w_next)
    if (p == wi)
      break;
  ASSERT(p);
  *pp = p->w_next;
  wi->w_inlen = 0;
  wtab[wi->w_number] = 0;

  if (windows == 0)
    {
      FreeWindow(wi);
      Finit(0);
    }

  /*
   * switch to different window on all canvases
   */
  for (display = displays; display; display = display->d_next)
    {
      gotone = 0;
      for (cv = D_cvlist; cv; cv = cv->c_next)
	{
	  if (Layer2Window(cv->c_layer) != wi)
	    continue;
	  /* switch to other window */
	  SetCanvasWindow(cv, FindNiceWindow(D_other, 0));
	  gotone = 1;
	}
      if (gotone)
	{
#ifdef ZMODEM
	  if (wi->w_zdisplay == display)
	    {
	      D_blocked = 0;
	      D_readev.condpos = D_readev.condneg = 0;
	    }
#endif
	  Activate(-1);
	}
    }

  /* do the same for the layouts */
  for (lay = layouts; lay; lay = lay->lay_next)
    UpdateLayoutCanvas(&lay->lay_canvas, wi);

  FreeWindow(wi);
  WindowChanged((struct win *)0, 'w');
  WindowChanged((struct win *)0, 'W');
  WindowChanged((struct win *)0, 0);
}

static void
LogToggle(on)
int on;
{
  char buf[1024];

  if ((fore->w_log != 0) == on)
    {
      if (display && !*rc_name)
	Msg(0, "You are %s logging.", on ? "already" : "not");
      return;
    }
  if (fore->w_log != 0)
    {
      Msg(0, "Logfile \"%s\" closed.", fore->w_log->name);
      logfclose(fore->w_log);
      fore->w_log = 0;
      WindowChanged(fore, 'f');
      return;
    }
  if (DoStartLog(fore, buf, sizeof(buf)))
    {
      Msg(errno, "Error opening logfile \"%s\"", buf);
      return;
    }
  if (ftell(fore->w_log->fp) == 0)
    Msg(0, "Creating logfile \"%s\".", fore->w_log->name);
  else
    Msg(0, "Appending to logfile \"%s\".", fore->w_log->name);
  WindowChanged(fore, 'f');
}

char *
AddWindows(buf, len, flags, where)
char *buf;
int len;
int flags;
int where;
{
  register char *s, *ss;
  register struct win **pp, *p;
  register char *cmd;
  int l;

  s = ss = buf;
  if ((flags & 8) && where < 0)
    {
      *s = 0;
      return ss;
    }
  for (pp = ((flags & 4) && where >= 0) ? wtab + where + 1: wtab; pp < wtab + maxwin; pp++)
    {
      int rend = -1;
      if (pp - wtab == where && ss == buf)
        ss = s;
      if ((p = *pp) == 0)
	continue;
      if ((flags & 1) && display && p == D_fore)
	continue;
      if (display && D_fore && D_fore->w_group != p->w_group)
	continue;

      cmd = p->w_title;
      l = strlen(cmd);
      if (l > 20)
        l = 20;
      if (s - buf + l > len - 24)
	break;
      if (s > buf || (flags & 4))
	{
	  *s++ = ' ';
	  *s++ = ' ';
	}
      if (p->w_number == where)
        {
          ss = s;
          if (flags & 8)
            break;
        }
      if (!(flags & 4) || where < 0 || ((flags & 4) && where < p->w_number))
	{
	  if (p->w_monitor == MON_DONE && renditions[REND_MONITOR] != -1)
	    rend = renditions[REND_MONITOR];
	  else if ((p->w_bell == BELL_DONE || p->w_bell == BELL_FOUND) && renditions[REND_BELL] != -1)
	    rend = renditions[REND_BELL];
	  else if ((p->w_silence == SILENCE_FOUND || p->w_silence == SILENCE_DONE) && renditions[REND_SILENCE] != -1)
	    rend = renditions[REND_SILENCE];
	}
      if (rend != -1)
	AddWinMsgRend(s, rend);
      sprintf(s, "%d", p->w_number);
      s += strlen(s);
      if (display && p == D_fore)
	*s++ = '*';
      if (!(flags & 2))
	{
          if (display && p == D_other)
	    *s++ = '-';
          s = AddWindowFlags(s, len, p);
	}
      *s++ = ' ';
      strncpy(s, cmd, l);
      s += l;
      if (rend != -1)
	AddWinMsgRend(s, -1);
    }
  *s = 0;
  return ss;
}

char *
AddWindowFlags(buf, len, p)
char *buf;
int len;
struct win *p;
{
  char *s = buf;
  if (p == 0 || len < 12)
    {
      *s = 0;
      return s;
    }
#if 0
  if (display && p == D_fore)
    *s++ = '*';
  if (display && p == D_other)
    *s++ = '-';
#endif
  if (p->w_layer.l_cvlist && p->w_layer.l_cvlist->c_lnext)
    *s++ = '&';
  if (p->w_monitor == MON_DONE
#ifdef MULTIUSER
      && display && (ACLBYTE(p->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id))
#endif
     )
    *s++ = '@';
  if (p->w_bell == BELL_DONE)
    *s++ = '!';
#ifdef UTMPOK
  if (p->w_slot != (slot_t) 0 && p->w_slot != (slot_t) -1)
    *s++ = '$';
#endif
  if (p->w_log != 0)
    {
      strcpy(s, "(L)");
      s += 3;
    }
  if (p->w_ptyfd < 0 && p->w_type != W_TYPE_GROUP)
    *s++ = 'Z';
  *s = 0;
  return s;
}

char *
AddOtherUsers(buf, len, p)
char *buf;
int len;
struct win *p;
{
  struct display *d, *olddisplay = display;
  struct canvas *cv;
  char *s;
  int l;

  s = buf;
  for (display = displays; display; display = display->d_next)
    {
      if (olddisplay && D_user == olddisplay->d_user)
	continue;
      for (cv = D_cvlist; cv; cv = cv->c_next)
	if (Layer2Window(cv->c_layer) == p)
	  break;
      if (!cv)
	continue;
      for (d = displays; d && d != display; d = d->d_next)
	if (D_user == d->d_user)
	  break;
      if (d && d != display)
	continue;
      if (len > 1 && s != buf)
	{
	  *s++ = ',';
	  len--;
	}
      l = strlen(D_user->u_name);
      if (l + 1 > len)
	break;
      strcpy(s, D_user->u_name);
      s += l;
      len -= l;
    }
  *s = 0;
  display = olddisplay;
  return s;
}

void
ShowWindows(where)
int where;
{
  char buf[1024];
  char *s, *ss;

  if (display && where == -1 && D_fore)
    where = D_fore->w_number;
  ss = AddWindows(buf, sizeof(buf), 0, where);
  s = buf + strlen(buf);
  if (display && ss - buf > D_width / 2)
    {
      ss -= D_width / 2;
      if (s - ss < D_width)
	{
	  ss = s - D_width;
	  if (ss < buf)
	    ss = buf;
	}
    }
  else
    ss = buf;
  Msg(0, "%s", ss);
}

/*
* String Escape based windows listing
* mls: currently does a Msg() call for each(!) window, dunno why
*/
static void
ShowWindowsX(str)
char *str;
{
	int i;
	debug1("ShowWindowsX: string [%s]", str);
	for (i = 0; i < maxwin ; i++) {
		if (!wtab[i])
			continue;
		Msg(0, "%s", MakeWinMsg(str, wtab[i], '%'));
	}
}


static void
ShowInfo()
{
  char buf[512], *p;
  register struct win *wp = fore;
  register int i;

  if (wp == 0)
    {
      Msg(0, "(%d,%d)/(%d,%d) no window", D_x + 1, D_y + 1, D_width, D_height);
      return;
    }
  p = buf;
  if (buf < (p += GetAnsiStatus(wp, p)))
    *p++ = ' ';
  sprintf(p, "(%d,%d)/(%d,%d)",
    wp->w_x + 1, wp->w_y + 1, wp->w_width, wp->w_height);
#ifdef COPY_PASTE
  sprintf(p += strlen(p), "+%d", wp->w_histheight);
#endif
  sprintf(p += strlen(p), " %c%sflow",
  	  (wp->w_flow & FLOW_NOW) ? '+' : '-',
	  (wp->w_flow & FLOW_AUTOFLAG) ? "" : 
	   ((wp->w_flow & FLOW_AUTO) ? "(+)" : "(-)"));
  if (!wp->w_wrap) sprintf(p += strlen(p), " -wrap");
  if (wp->w_insert) sprintf(p += strlen(p), " ins");
  if (wp->w_origin) sprintf(p += strlen(p), " org");
  if (wp->w_keypad) sprintf(p += strlen(p), " app");
  if (wp->w_log)    sprintf(p += strlen(p), " log");
  if (wp->w_monitor != MON_OFF
#ifdef MULTIUSER
      && (ACLBYTE(wp->w_mon_notify, D_user->u_id) & ACLBIT(D_user->u_id))
#endif
     )
    sprintf(p += strlen(p), " mon");
  if (wp->w_mouse) sprintf(p += strlen(p), " mouse");
#ifdef COLOR
  if (wp->w_bce) sprintf(p += strlen(p), " bce");
#endif
  if (!wp->w_c1) sprintf(p += strlen(p), " -c1");
  if (wp->w_norefresh) sprintf(p += strlen(p), " nored");

  p += strlen(p);
#ifdef FONT
# ifdef ENCODINGS
  if (wp->w_encoding && (display == 0 || D_encoding != wp->w_encoding || EncodingDefFont(wp->w_encoding) <= 0))
    {
      *p++ = ' ';
      strcpy(p, EncodingName(wp->w_encoding));
      p += strlen(p);
    }
#  ifdef UTF8
  if (wp->w_encoding != UTF8)
#  endif
# endif
    if (display && (D_CC0 || (D_CS0 && *D_CS0)))
      {
	if (wp->w_gr == 2)
	  {
	    sprintf(p, " G%c", wp->w_Charset + '0');
	    if (wp->w_FontE >= ' ')
	      p[3] = wp->w_FontE;
	    else
	      {
	        p[3] = '^';
	        p[4] = wp->w_FontE ^ 0x40;
		p++;
	      }
	    p[4] = '[';
	    p++;
	  }
	else if (wp->w_gr)
	  sprintf(p++, " G%c%c[", wp->w_Charset + '0', wp->w_CharsetR + '0');
	else
	  sprintf(p, " G%c[", wp->w_Charset + '0');
	p += 4;
	for (i = 0; i < 4; i++)
	  {
	    if (wp->w_charsets[i] == ASCII)
	      *p++ = 'B';
	    else if (wp->w_charsets[i] >= ' ')
	      *p++ = wp->w_charsets[i];
	    else
	      {
		*p++ = '^';
		*p++ = wp->w_charsets[i] ^ 0x40;
	      }
	  }
	*p++ = ']';
	*p = 0;
      }
#endif

  if (wp->w_type == W_TYPE_PLAIN)
    {
      /* add info about modem control lines */
      *p++ = ' ';
      TtyGetModemStatus(wp->w_ptyfd, p);
    }
#ifdef BUILTIN_TELNET
  else if (wp->w_type == W_TYPE_TELNET)
    {
      *p++ = ' ';
      TelStatus(wp, p, sizeof(buf) - 1 - (p - buf));
    }
#endif
  Msg(0, "%s %d(%s)", buf, wp->w_number, wp->w_title);
}

static void
ShowDInfo()
{
  char buf[512], *p;
  if (display == 0)
    return;
  p = buf;
  sprintf(p, "(%d,%d)", D_width, D_height),
  p += strlen(p);
#ifdef ENCODINGS
  if (D_encoding)
    {
      *p++ = ' ';
      strcpy(p, EncodingName(D_encoding));
      p += strlen(p);
    }
#endif
  if (D_CXT)
    {
      strcpy(p, " xterm");
      p += strlen(p);
    }
#ifdef COLOR
  if (D_hascolor)
    {
      strcpy(p, " color");
      p += strlen(p);
    }
#endif
#ifdef FONT
  if (D_CG0)
    {
      strcpy(p, " iso2022");
      p += strlen(p);
    }
  else if (D_CS0 && *D_CS0)
    {
      strcpy(p, " altchar");
      p += strlen(p);
    }
#endif
  Msg(0, "%s", buf);
}

static void
AKAfin(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  ASSERT(display);
  if (len && fore)
    ChangeAKA(fore, buf, strlen(buf));

  enter_window_name_mode = 0;
}

static void
InputAKA()
{
  char *s, *ss;
  int n;

  if (enter_window_name_mode == 1) return;

  enter_window_name_mode = 1;

  Input("Set window's title to: ", sizeof(fore->w_akabuf) - 1, INP_COOKED, AKAfin, NULL, 0);
  s = fore->w_title;
  if (!s)
    return;
  for (; *s; s++)
    {
      if ((*(unsigned char *)s & 0x7f) < 0x20 || *s == 0x7f)
	continue;
      ss = s;
      n = 1;
      LayProcess(&ss, &n);
    }
}

static void
Colonfin(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  char mbuf[256];

  RemoveStatus();
  if (buf[len] == '\t')
    {
      int m, x;
      int l = 0, r = RC_LAST;
      int showmessage = 0;
      char *s = buf;

      while (*s && s - buf < len)
	if (*s++ == ' ')
	  return;

      /* Showing a message when there's no hardstatus or caption cancels the input */
      if (display &&
	  (captionalways || D_has_hstatus == HSTATUS_LASTLINE || (D_canvas.c_slperp && D_canvas.c_slperp->c_slnext)))
	showmessage = 1;

      while (l <= r)
	{
	  m = (l + r) / 2;
	  x = strncmp(buf, comms[m].name, len);
	  if (x > 0)
	    l = m + 1;
	  else if (x < 0)
	    r = m - 1;
	  else
	    {
	      s = mbuf;
	      for (l = m - 1; l >= 0 && strncmp(buf, comms[l].name, len) == 0; l--)
		;
	      for (m = ++l; m <= r && strncmp(buf, comms[m].name, len) == 0 && s - mbuf < sizeof(mbuf); m++)
		s += snprintf(s, sizeof(mbuf) - (s - mbuf), " %s", comms[m].name);
	      if (l < m - 1)
		{
		  if (showmessage)
		    Msg(0, "Possible commands:%s", mbuf);
		}
	      else
		{
		  s = mbuf;
		  len = snprintf(mbuf, sizeof(mbuf), "%s \t", comms[l].name + len);
		  if (len > 0 && len < sizeof(mbuf))
		    LayProcess(&s, &len);
		}
	      break;
	    }
	}
      if (l > r && showmessage)
	Msg(0, "No commands matching '%*s'", len, buf);
      return;
    }

  if (!len || buf[len])
    return;

  len = strlen(buf) + 1;
  if (len > (int)sizeof(mbuf))
    RcLine(buf, len);
  else
    {
      bcopy(buf, mbuf, len);
      RcLine(mbuf, sizeof mbuf);
    }
}

static void
SelectFin(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  int n;

  if (!len || !display)
    return;
  if (len == 1 && *buf == '-')
    {
      SetForeWindow((struct win *)0);
      Activate(0);
      return;
    }
  if ((n = WindowByNoN(buf)) < 0)
    return;
  SwitchWindow(n);
}

static void
SelectLayoutFin(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  struct layout *lay;

  if (!len || !display)
    return;
  if (len == 1 && *buf == '-')
    {
      LoadLayout((struct layout *)0, (struct canvas *)0);
      Activate(0);
      return;
    }
  lay = FindLayout(buf);
  if (!lay)
    Msg(0, "No such layout\n");
  else if (lay == D_layout)
    Msg(0, "This IS layout %d (%s).\n", lay->lay_number, lay->lay_title);
  else
    {
      LoadLayout(lay, &D_canvas);
      Activate(0);
    }
}

    
static void
InputSelect()
{
  Input("Switch to window: ", 20, INP_COOKED, SelectFin, NULL, 0);
}

static char setenv_var[31];


static void
SetenvFin1(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  if (!len || !display)
    return;
  InputSetenv(buf);
}
  
static void
SetenvFin2(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  if (!len || !display)
    return;
  debug2("SetenvFin2: setenv '%s' '%s'\n", setenv_var, buf);
  xsetenv(setenv_var, buf);
  MakeNewEnv();
}

static void
InputSetenv(arg)
char *arg;
{
  static char setenv_buf[50 + sizeof(setenv_var)];	/* need to be static here, cannot be freed */

  if (arg)
    {
      strncpy(setenv_var, arg, sizeof(setenv_var) - 1);
      sprintf(setenv_buf, "Enter value for %s: ", setenv_var);
      Input(setenv_buf, 30, INP_COOKED, SetenvFin2, NULL, 0);
    }
  else
    Input("Setenv: Enter variable name: ", 30, INP_COOKED, SetenvFin1, NULL, 0);
}

/*
 * the following options are understood by this parser:
 * -f, -f0, -f1, -fy, -fa
 * -t title, -T terminal-type, -h height-of-scrollback, 
 * -ln, -l0, -ly, -l1, -l
 * -a, -M, -L
 */
void
DoScreen(fn, av)
char *fn, **av;
{
  struct NewWindow nwin;
  register int num;
  char buf[20];

  nwin = nwin_undef;
  while (av && *av && av[0][0] == '-')
    {
      if (av[0][1] == '-')
	{
	  av++;
	  break;
	}
      switch (av[0][1])
	{
	case 'f':
	  switch (av[0][2])
	    {
	    case 'n':
	    case '0':
	      nwin.flowflag = FLOW_NOW * 0;
	      break;
	    case 'y':
	    case '1':
	    case '\0':
	      nwin.flowflag = FLOW_NOW * 1;
	      break;
	    case 'a':
	      nwin.flowflag = FLOW_AUTOFLAG;
	      break;
	    default:
	      break;
	    }
	  break;
	case 't':	/* no more -k */
	  if (av[0][2])
	    nwin.aka = &av[0][2];
	  else if (*++av)
	    nwin.aka = *av;
	  else
	    --av;
	  break;
	case 'T':
	  if (av[0][2])
	    nwin.term = &av[0][2];
	  else if (*++av)
	    nwin.term = *av;
	  else
	    --av;
	  break;
	case 'h':
	  if (av[0][2])
	    nwin.histheight = atoi(av[0] + 2);
	  else if (*++av)
	    nwin.histheight = atoi(*av);
	  else 
	    --av;
	  break;
#ifdef LOGOUTOK
	case 'l':
	  switch (av[0][2])
	    {
	    case 'n':
	    case '0':
	      nwin.lflag = 0;
	      break;
	    case 'y':
	    case '1':
	    case '\0':
	      nwin.lflag = 1;
	      break;
	    case 'a':
	      nwin.lflag = 3;
	      break;
	    default:
	      break;
	    }
	  break;
#endif
	case 'a':
	  nwin.aflag = 1;
	  break;
	case 'M':
	  nwin.monitor = MON_ON;
	  break;
	case 'L':
	  nwin.Lflag = 1;
	  break;
	default:
	  Msg(0, "%s: screen: invalid option -%c.", fn, av[0][1]);
	  break;
	}
      ++av;
    }
  if (av && *av && IsNumColon(*av, 10, buf, sizeof(buf)))
    {
      if (*buf != '\0')
	nwin.aka = buf;
      num = atoi(*av);
      if (num < 0 || (maxwin && num > maxwin - 1) || (!maxwin && num > MAXWIN - 1))
	{
	  Msg(0, "%s: illegal screen number %d.", fn, num);
	  num = 0;
	}
      nwin.StartAt = num;
      ++av;
    }
  if (av && *av)
    {
      nwin.args = av;
      if (!nwin.aka)
        nwin.aka = Filename(*av);
    }
  MakeWindow(&nwin);
}

#ifdef COPY_PASTE
/*
 * CompileKeys must be called before Markroutine is first used.
 * to initialise the keys with defaults, call CompileKeys(NULL, mark_key_tab);
 *
 * s is an ascii string in a termcap-like syntax. It looks like
 *   "j=u:k=d:l=r:h=l: =.:" and so on...
 * this example rebinds the cursormovement to the keys u (up), d (down),
 * l (left), r (right). placing a mark will now be done with ".".
 */
int
CompileKeys(s, sl, array)
char *s;
int sl;
unsigned char *array;
{
  int i;
  unsigned char key, value;

  if (sl == 0)
    {
      for (i = 0; i < 256; i++)
        array[i] = i;
      return 0;
    }
  debug1("CompileKeys: '%s'\n", s);
  while (sl)
    {
      key = *(unsigned char *)s++;
      if (*s != '=' || sl < 3)
	return -1;
      sl--;
      do 
	{
	  s++;
	  sl -= 2;
	  value = *(unsigned char *)s++;
	  array[value] = key;
	}
      while (*s == '=' && sl >= 2);
      if (sl == 0) 
	break;
      if (*s++ != ':')
	return -1;
      sl--;
    }
  return 0;
}
#endif /* COPY_PASTE */

/*
 *  Asynchronous input functions
 */

#if defined(DETACH) && defined(POW_DETACH)
static void
pow_detach_fn(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  debug("pow_detach_fn called\n");
  if (len)
    {
      memset(buf, 0, len);
      return;
    }
  if (ktab[(int)(unsigned char)*buf].nr != RC_POW_DETACH)
    {
      if (display)
        write(D_userfd, "\007", 1);
      Msg(0, "Detach aborted.");
    }
  else
    Detach(D_POWER);
}
#endif /* POW_DETACH */

#ifdef COPY_PASTE
static void
copy_reg_fn(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  struct plop *pp = plop_tab + (int)(unsigned char)*buf;

  if (len)
    {
      memset(buf, 0, len);
      return;
    }
  if (pp->buf)
    free(pp->buf);
  pp->buf = 0;
  pp->len = 0;
  if (D_user->u_plop.len)
    {
      if ((pp->buf = (char *)malloc(D_user->u_plop.len)) == NULL)
	{
	  Msg(0, "%s", strnomem);
	  return;
	}
      bcopy(D_user->u_plop.buf, pp->buf, D_user->u_plop.len);
    }
  pp->len = D_user->u_plop.len;
#ifdef ENCODINGS
  pp->enc = D_user->u_plop.enc;
#endif
  Msg(0, "Copied %d characters into register %c", D_user->u_plop.len, *buf);
}

static void
ins_reg_fn(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  struct plop *pp = plop_tab + (int)(unsigned char)*buf;

  if (len)
    {
      memset(buf, 0, len);
      return;
    }
  if (!fore)
    return;	/* Input() should not call us w/o fore, but you never know... */
  if (*buf == '.')
    Msg(0, "ins_reg_fn: Warning: pasting real register '.'!");
  if (pp->buf)
    {
      MakePaster(&fore->w_paster, pp->buf, pp->len, 0);
      return;
    }
  Msg(0, "Empty register.");
}
#endif /* COPY_PASTE */

static void
process_fn(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  struct plop *pp = plop_tab + (int)(unsigned char)*buf;

  if (len)
    {
      memset(buf, 0, len);
      return;
    }
  if (pp->buf)
    {
      ProcessInput(pp->buf, pp->len);
      return;
    }
  Msg(0, "Empty register.");
}

static void
confirm_fn(buf, len, data)
char *buf;
int len;
char *data;
{
  struct action act;

  if (len || (*buf != 'y' && *buf != 'Y'))
    {
      memset(buf, 0, len);
      return;
    }
  act.nr = *(int *)data;
  act.args = noargs;
  act.argl = 0;
  act.quiet = 0;
  DoAction(&act, -1);
}

#ifdef MULTIUSER
struct inputsu
{
  struct acluser **up;
  char name[24];
  char pw1[130];	/* FreeBSD crypts to 128 bytes */
  char pw2[130];
};

static void
su_fin(buf, len, data)
char *buf;
int len;
char *data;
{
  struct inputsu *i = (struct inputsu *)data;
  char *p;
  int l;

  if (!*i->name)
    { p = i->name; l = sizeof(i->name) - 1; }
  else if (!*i->pw1)
    { strcpy(p = i->pw1, "\377"); l = sizeof(i->pw1) - 1; }
  else
    { strcpy(p = i->pw2, "\377"); l = sizeof(i->pw2) - 1; }
  if (buf && len)
    strncpy(p, buf, 1 + ((l < len) ? l : len));
  if (!*i->name)
    Input("Screen User: ", sizeof(i->name) - 1, INP_COOKED, su_fin, (char *)i, 0);
  else if (!*i->pw1)
    Input("User's UNIX Password: ", sizeof(i->pw1)-1, INP_COOKED|INP_NOECHO, su_fin, (char *)i, 0);
  else if (!*i->pw2)
    Input("User's Screen Password: ", sizeof(i->pw2)-1, INP_COOKED|INP_NOECHO, su_fin, (char *)i, 0);
  else
    {
      if ((p = DoSu(i->up, i->name, i->pw2, i->pw1)))
        Msg(0, "%s", p);
      free((char *)i);
    }
}
 
static int
InputSu(w, up, name)
struct win *w;
struct acluser **up;
char *name;
{
  struct inputsu *i;

  if (!(i = (struct inputsu *)calloc(1, sizeof(struct inputsu))))
    return -1;

  i->up = up;
  if (name && *name)
    su_fin(name, (int)strlen(name), (char *)i); /* can also initialise stuff */
  else
    su_fin((char *)0, 0, (char *)i);
  return 0;
}
#endif	/* MULTIUSER */

#ifdef PASSWORD

static void
pass1(buf, len, data)
char *buf;
int len;
char *data;
{
  struct acluser *u = (struct acluser *)data;

  if (!*buf)
    return;
  ASSERT(u);
  if (u->u_password != NullStr)
    free((char *)u->u_password);
  u->u_password = SaveStr(buf);
  bzero(buf, strlen(buf));
  Input("Retype new password:", 100, INP_NOECHO, pass2, data, 0);
}

static void
pass2(buf, len, data)
char *buf;
int len;
char *data;
{
  int st;
  char salt[3];
  struct acluser *u = (struct acluser *)data;

  ASSERT(u);
  if (!buf || strcmp(u->u_password, buf))
    {
      Msg(0, "[ Passwords don't match - checking turned off ]");
      if (u->u_password != NullStr)
        {
          bzero(u->u_password, strlen(u->u_password));
          free((char *)u->u_password);
	}
      u->u_password = NullStr;
    }
  else if (u->u_password[0] == '\0')
    {
      Msg(0, "[ No password - no secure ]");
      if (buf)
        bzero(buf, strlen(buf));
    }
  
  if (u->u_password != NullStr)
    {
      for (st = 0; st < 2; st++)
	salt[st] = 'A' + (int)((time(0) >> 6 * st) % 26);
      salt[2] = 0;
      buf = crypt(u->u_password, salt);
      bzero(u->u_password, strlen(u->u_password));
      free((char *)u->u_password);
      if (!buf)
	{
	  Msg(0, "[ crypt() error - no secure ]");
	  u->u_password = NullStr;
	  return;
	}
      u->u_password = SaveStr(buf);
      bzero(buf, strlen(buf));
#ifdef COPY_PASTE
      if (u->u_plop.buf)
	UserFreeCopyBuffer(u);
      u->u_plop.len = strlen(u->u_password);
# ifdef ENCODINGS
      u->u_plop.enc = 0;
#endif
      if (!(u->u_plop.buf = SaveStr(u->u_password)))
	{
	  Msg(0, "%s", strnomem);
          D_user->u_plop.len = 0;
	}
      else
	Msg(0, "[ Password moved into copybuffer ]");
#else				/* COPY_PASTE */
      Msg(0, "[ Crypted password is \"%s\" ]", u->u_password);
#endif				/* COPY_PASTE */
    }
}
#endif /* PASSWORD */

static int
digraph_find(buf)
const char *buf;
{
  int i;
  for (i = 0; i < MAX_DIGRAPH && digraphs[i].d[0]; i++)
    if ((digraphs[i].d[0] == (unsigned char)buf[0] && digraphs[i].d[1] == (unsigned char)buf[1]) ||
	(digraphs[i].d[0] == (unsigned char)buf[1] && digraphs[i].d[1] == (unsigned char)buf[0]))
      break;
  return i;
}

static void
digraph_fn(buf, len, data)
char *buf;
int len;
char *data;	/* dummy */
{
  int ch, i, x;

  ch = buf[len];
  if (ch)
    {
      buf[len + 1] = ch;		/* so we can restore it later */
      if (ch < ' ' || ch == '\177')
	return;
      if (len >= 1 && ((*buf == 'U' && buf[1] == '+') || (*buf == '0' && (buf[1] == 'x' || buf[1] == 'X'))))
	{
	  if (len == 1)
	    return;
	  if ((ch < '0' || ch > '9') && (ch < 'a' || ch > 'f') && (ch < 'A' || ch > 'F'))
	    {
	      buf[len] = '\034';	/* ^] is ignored by Input() */
	      return;
	    }
	  if (len == (*buf == 'U' ? 5 : 3))
	    buf[len] = '\n';
	  return;
	}
      if (len && *buf == '0')
	{
	  if (ch < '0' || ch > '7')
	    {
	      buf[len] = '\034';	/* ^] is ignored by Input() */
	      return;
	    }
	  if (len == 3)
	    buf[len] = '\n';
	  return;
	}
      if (len == 1)
        buf[len] = '\n';
      return;
    }
  if (len < 1)
    return;
  if (buf[len + 1])
    {
      buf[len] = buf[len + 1];	/* stored above */
      len++;
    }
  if (len < 2)
    return;
  if (!parse_input_int(buf, len, &x))
    {
      i = digraph_find(buf);
      if ((x = digraphs[i].value) <= 0)
	{
	  Msg(0, "Unknown digraph");
	  return;
	}
    }
  i = 1;
  *buf = x;
#ifdef UTF8
  if (flayer->l_encoding == UTF8)
    i = ToUtf8(buf, x);	/* buf is big enough for all UTF-8 codes */
#endif
  while(i)
    LayProcess(&buf, &i);
}

#ifdef MAPKEYS
int
StuffKey(i)
int i;
{
  struct action *act;
  int discard = 0;
  int keyno = i;

  debug1("StuffKey #%d", i);
#ifdef DEBUG
  if (i < KMAP_KEYS)
    debug1(" - %s", term[i + T_CAPS].tcname);
#endif

  if (i < KMAP_KEYS && D_ESCseen)
    {
      struct action *act = &D_ESCseen[i + 256];
      if (act->nr != RC_ILLEGAL)
	{
	  D_ESCseen = 0;
	  WindowChanged(fore, 'E');
          DoAction(act, i + 256);
	  return 0;
	}
      discard = 1;
    }

  if (i >= T_CURSOR - T_CAPS && i < T_KEYPAD - T_CAPS && D_cursorkeys)
    i += T_OCAPS - T_CURSOR;
  else if (i >= T_KEYPAD - T_CAPS && i < T_OCAPS - T_CAPS && D_keypad)
    i += T_OCAPS - T_CURSOR;
  debug1(" - action %d\n", i);
  flayer = D_forecv->c_layer;
  fore = D_fore;
  act = 0;
#ifdef COPY_PASTE
  if (flayer && flayer->l_mode == 1)
    act = i < KMAP_KEYS+KMAP_AKEYS ? &mmtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].mm;
#endif
  if ((!act || act->nr == RC_ILLEGAL) && !D_mapdefault)
    act = i < KMAP_KEYS+KMAP_AKEYS ? &umtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].um;
  if (!act || act->nr == RC_ILLEGAL)
    act = i < KMAP_KEYS+KMAP_AKEYS ? &dmtab[i] : &kmap_exts[i - (KMAP_KEYS+KMAP_AKEYS)].dm;

  if (discard && (!act || act->nr != RC_COMMAND))
    {
      /* if the input was just a single byte we let it through */
      if (D_tcs[keyno + T_CAPS].str && strlen(D_tcs[keyno + T_CAPS].str) == 1)
	return -1;
      if (D_ESCseen)
        {
          D_ESCseen = 0;
          WindowChanged(fore, 'E');
        }
      return 0;
    }
  D_mapdefault = 0;

  if (act == 0 || act->nr == RC_ILLEGAL)
    return -1;
  DoAction(act, 0);
  return 0;
}
#endif


static int
IsOnDisplay(wi)
struct win *wi;
{
  struct canvas *cv;
  ASSERT(display);
  for (cv = D_cvlist; cv; cv = cv->c_next)
    if (Layer2Window(cv->c_layer) == wi)
      return 1;
  return 0;
}

struct win *
FindNiceWindow(wi, presel)
struct win *wi;
char *presel;
{
  int i;

  debug2("FindNiceWindow %d %s\n", wi ? wi->w_number : -1 , presel ? presel : "NULL");
  if (presel)
    {
      i = WindowByNoN(presel);
      if (i >= 0)
	wi = wtab[i];
    }
  if (!display)
    return wi;
#ifdef MULTIUSER
  if (wi && AclCheckPermWin(D_user, ACL_READ, wi))
    wi = 0;
#endif
  if (!wi || (IsOnDisplay(wi) && !presel))
    {
      /* try to get another window */
      wi = 0;
#ifdef MULTIUSER
      for (wi = windows; wi; wi = wi->w_next)
	if (!wi->w_layer.l_cvlist && !AclCheckPermWin(D_user, ACL_WRITE, wi))
	  break;
      if (!wi)
        for (wi = windows; wi; wi = wi->w_next)
	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi) && !AclCheckPermWin(D_user, ACL_WRITE, wi))
	    break;
      if (!wi)
	for (wi = windows; wi; wi = wi->w_next)
	  if (!wi->w_layer.l_cvlist && !AclCheckPermWin(D_user, ACL_READ, wi))
	    break;
      if (!wi)
	for (wi = windows; wi; wi = wi->w_next)
	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi) && !AclCheckPermWin(D_user, ACL_READ, wi))
	    break;
#endif
      if (!wi)
	for (wi = windows; wi; wi = wi->w_next)
	  if (!wi->w_layer.l_cvlist)
	    break;
      if (!wi)
	for (wi = windows; wi; wi = wi->w_next)
	  if (wi->w_layer.l_cvlist && !IsOnDisplay(wi))
	    break;
    }
#ifdef MULTIUSER
  if (wi && AclCheckPermWin(D_user, ACL_READ, wi))
    wi = 0;
#endif
  return wi;
}

#if 0

/* sorted list of all commands */
static struct comm **commtab;
static int ncommtab;

void
AddComms(cos, hand)
struct comm *cos;
void (*hand) __P((struct comm *, char **, int));
{
  int n, i, j, r;
  for (n = 0; cos[n].name; n++)
    ;
  if (n == 0)
    return;
  if (commtab)
    commtab = (struct commt *)realloc(commtab, sizeof(*commtab) * (ncommtab + n));
  else
    commtab = (struct commt *)malloc(sizeof(*commtab) * (ncommtab + n));
  if (!commtab)
    Panic(0, strnomem);
  for (i = 0; i < n; i++)
    {
      for (j = 0; j < ncommtab; j++)
	{
	  r = strcmp(cos[i].name, commtab[j]->name);
	  if (r == 0)
	    Panic(0, "Duplicate command: %s\n", cos[i].name);
	  if (r < 0)
	    break;
	}
      for (r = ncommtab; r > j; r--)
	commtab[r] = commtab[r - 1];
      commtab[j] = cos + i;
      cos[i].handler = hand;
      bzero(cos[i].userbits, sizeof(cos[i].userbits));
      ncommtab++;
    }
}

struct comm *
FindComm(str)
char *str;
{
  int x, m, l = 0, r = ncommtab - 1;
  while (l <= r)
    {
      m = (l + r) / 2;
      x = strcmp(str, commtab[m]->name);
      if (x > 0)
	l = m + 1;
      else if (x < 0)
	r = m - 1;
      else
	return commtab[m];
    }
  return 0;
}

#endif

static int
CalcSlicePercent(cv, percent)
struct canvas *cv;
int percent;
{
  int w, wsum, up;
  if (!cv || !cv->c_slback)
    return percent;
  up = CalcSlicePercent(cv->c_slback->c_slback, percent);
  w = cv->c_slweight;
  for (cv = cv->c_slback->c_slperp, wsum = 0; cv; cv = cv->c_slnext)
    wsum += cv->c_slweight;
  if (wsum == 0)
    return 0;
  return (up * w) / wsum;
}

static int
ChangeCanvasSize(fcv, abs, diff, gflag, percent)
struct canvas *fcv;	/* make this canvas bigger */
int abs;		/* mode: 0:rel 1:abs 2:max */
int diff;		/* change this much */
int gflag;		/* go up if neccessary */
int percent;
{
  struct canvas *cv;
  int done, have, m, dir;

  debug3("ChangeCanvasSize abs %d diff %d percent=%d\n", abs, diff, percent);
  if (abs == 0 && diff == 0)
    return 0;
  if (abs == 2)
    {
      if (diff == 0)
	  fcv->c_slweight = 0;
      else
	{
          for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
	    cv->c_slweight = 0;
	  fcv->c_slweight = 1;
	  cv = fcv->c_slback->c_slback;
	  if (gflag && cv && cv->c_slback)
	    ChangeCanvasSize(cv, abs, diff, gflag, percent);
	}
      return diff;
    }
  if (abs)
    {
      if (diff < 0)
	diff = 0;
      if (percent && diff > percent)
	diff = percent;
    }
  if (percent)
    {
      int wsum, up;
      for (cv = fcv->c_slback->c_slperp, wsum = 0; cv; cv = cv->c_slnext)
	wsum += cv->c_slweight;
      if (wsum)
	{
	  up = gflag ? CalcSlicePercent(fcv->c_slback->c_slback, percent) : percent;
          debug3("up=%d, wsum=%d percent=%d\n", up, wsum, percent);
	  if (wsum < 1000)
	    {
	      int scale = wsum < 10 ? 1000 : 100;
	      for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
		cv->c_slweight *= scale;
	      wsum *= scale;
	      debug1("scaled wsum to %d\n", wsum);
	    }
	  for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
	    {
	      if (cv->c_slweight)
		{
	          cv->c_slweight = (cv->c_slweight * up) / percent;
		  if (cv->c_slweight == 0)
		    cv->c_slweight = 1;
		}
	      debug1("  - weight %d\n", cv->c_slweight);
	    }
	  diff = (diff * wsum) / percent;
	  percent = wsum;
	}
    }
  else
    {
      if (abs && diff == (fcv->c_slorient == SLICE_VERT ? fcv->c_ye - fcv->c_ys + 2 : fcv->c_xe - fcv->c_xs + 2))
	return 0;
      /* fix weights to real size (can't be helped, sorry) */
      for (cv = fcv->c_slback->c_slperp; cv; cv = cv->c_slnext)
	{
	  cv->c_slweight = cv->c_slorient == SLICE_VERT ? cv->c_ye - cv->c_ys + 2 : cv->c_xe - cv->c_xs + 2;
	  debug1("  - weight %d\n", cv->c_slweight);
	}
    }
  if (abs)
    diff = diff - fcv->c_slweight;
  debug1("diff = %d\n", diff);
  if (diff == 0)
    return 0;
  if (diff < 0)
    {
      cv = fcv->c_slnext ? fcv->c_slnext : fcv->c_slprev;
      fcv->c_slweight += diff;
      cv->c_slweight -= diff;
      return diff;
    }
  done = 0;
  dir = 1;
  for (cv = fcv->c_slnext; diff > 0; cv = dir > 0 ? cv->c_slnext : cv->c_slprev)
    {
      if (!cv)
	{
	  debug1("reached end, dir is %d\n", dir);
	  if (dir == -1)
	    break;
	  dir = -1;
	  cv = fcv;
	  continue;
	}
      if (percent)
	m = 1;
      else
        m = cv->c_slperp ? CountCanvasPerp(cv) * 2 : 2;
      debug2("min is %d, have %d\n", m, cv->c_slweight);
      if (cv->c_slweight > m)
	{
	  have = cv->c_slweight - m;
	  if (have > diff)
	    have = diff;
	  debug1("subtract %d\n", have);
	  cv->c_slweight -= have;
	  done += have;
	  diff -= have;
	}
    }
  if (diff && gflag)
    {
      /* need more room! */
      cv = fcv->c_slback->c_slback;
      if (cv && cv->c_slback)
        done += ChangeCanvasSize(fcv->c_slback->c_slback, 0, diff, gflag, percent);
    }
  fcv->c_slweight += done;
  debug1("ChangeCanvasSize returns %d\n", done);
  return done;
}

static void
ResizeRegions(arg, flags)
char *arg;
int flags;
{
  struct canvas *cv;
  int diff, l;
  int gflag = 0, abs = 0, percent = 0;
  int orient = 0;

  ASSERT(display);
  if (!*arg)
    return;
  if (D_forecv->c_slorient == SLICE_UNKN)
    {
      Msg(0, "resize: need more than one region");
      return;
    }
  gflag = flags & RESIZE_FLAG_L ? 0 : 1;
  orient |= flags & RESIZE_FLAG_H ? SLICE_HORI : 0;
  orient |= flags & RESIZE_FLAG_V ? SLICE_VERT : 0;
  if (orient == 0)
    orient = D_forecv->c_slorient;
  l = strlen(arg);
  if (*arg == '=')
    {
      /* make all regions the same height */
      struct canvas *cv = gflag ? &D_canvas : D_forecv->c_slback;
      if (cv->c_slperp->c_slorient & orient)
	EqualizeCanvas(cv->c_slperp, gflag);
      /* can't use cv->c_slorient directly as it can be D_canvas */
      if ((cv->c_slperp->c_slorient ^ (SLICE_HORI ^ SLICE_VERT)) & orient)
        {
	  if (cv->c_slback)
	    {
	      cv = cv->c_slback;
	      EqualizeCanvas(cv->c_slperp, gflag);
	    }
	  else
	   EqualizeCanvas(cv, gflag);
        }
      ResizeCanvas(cv);
      RecreateCanvasChain();
      RethinkDisplayViewports();
      ResizeLayersToCanvases();
      return;
    }
  if (!strcmp(arg, "min") || !strcmp(arg, "0"))
    {
      abs = 2;
      diff = 0;
    }
  else if (!strcmp(arg, "max") || !strcmp(arg, "_"))
    {
      abs = 2;
      diff = 1;
    }
  else
    {
      if (l > 0 && arg[l - 1] == '%')
	percent = 1000;
      if (*arg == '+')
	diff = atoi(arg + 1);
      else if (*arg == '-')
	diff = -atoi(arg + 1);
      else
	{
	  diff = atoi(arg);		/* +1 because of caption line */
	  if (diff < 0)
	    diff = 0;
	  abs = diff == 0 ? 2 : 1;
	}
    }
  if (!abs && !diff)
    return;
  if (percent)
    diff = diff * percent / 100;
  cv = D_forecv;
  if (cv->c_slorient & orient)
    ChangeCanvasSize(cv, abs, diff, gflag, percent);
  if (cv->c_slback->c_slorient & orient)
    ChangeCanvasSize(cv->c_slback, abs, diff, gflag, percent);

  ResizeCanvas(&D_canvas);
  RecreateCanvasChain();
  RethinkDisplayViewports();
  ResizeLayersToCanvases();
  return;

#if 0

  if (siz + diff < 1)
    diff = 1 - siz;
  if (siz + diff > dsize - (nreg - 1) * 2 - 1)
    diff = dsize - (nreg - 1) * 2 - 1 - siz;
  if (diff == 0 || siz + diff < 1)
    return;

  if (diff < 0)
    {
      if (D_forecv->c_next)
	{
	  D_forecv->c_ye += diff;
	  D_forecv->c_next->c_ys += diff;
	  D_forecv->c_next->c_yoff += diff;
	}
      else
	{
	  for (cv = D_cvlist; cv; cv = cv->c_next)
	    if (cv->c_next == D_forecv)
	      break;
	  ASSERT(cv);
	  cv->c_ye -= diff;
	  D_forecv->c_ys -= diff;
	  D_forecv->c_yoff -= diff;
	}
    }
  else
    {
      int s, i = 0, found = 0, di = diff, d2;
      s = dsize - (nreg - 1) * 2 - 1 - siz;
      for (cv = D_cvlist; cv; i = cv->c_ye + 2, cv = cv->c_next)
	{
	  if (cv == D_forecv)
	    {
	      cv->c_ye = i + (cv->c_ye - cv->c_ys) + diff;
	      cv->c_yoff -= cv->c_ys - i;
	      cv->c_ys = i;
	      found = 1;
	      continue;
	    }
	  s -= cv->c_ye - cv->c_ys;
	  if (!found)
	    {
	      if (s >= di)
		continue;
	      d2 = di - s;
	    }
	  else
	    d2 = di > cv->c_ye - cv->c_ys ? cv->c_ye - cv->c_ys : di;
	  di -= d2;
	  cv->c_ye = i + (cv->c_ye - cv->c_ys) - d2;
	  cv->c_yoff -= cv->c_ys - i;
	  cv->c_ys = i;
        }
    }
  RethinkDisplayViewports();
  ResizeLayersToCanvases();
#endif
}

static void
ResizeFin(buf, len, data)
char *buf;
int len;
char *data;
{
  int ch;
  int flags = *(int *)data;
  ch = ((unsigned char *)buf)[len];
  if (ch == 0)
    {
      ResizeRegions(buf, flags);
      return;
    }
  if (ch == 'h')
    flags ^= RESIZE_FLAG_H;
  else if (ch == 'v')
    flags ^= RESIZE_FLAG_V;
  else if (ch == 'b')
    flags |= RESIZE_FLAG_H|RESIZE_FLAG_V;
  else if (ch == 'p')
    flags ^= D_forecv->c_slorient == SLICE_VERT ? RESIZE_FLAG_H : RESIZE_FLAG_V;
  else if (ch == 'l')
    flags ^= RESIZE_FLAG_L;
  else
    return;
  inp_setprompt(resizeprompts[flags], NULL);
  *(int *)data = flags;
  buf[len] = '\034';
}

void
SetForeCanvas(d, cv)
struct display *d;
struct canvas *cv;
{
  struct display *odisplay = display;
  if (d->d_forecv == cv)
    return;

  display = d;
  D_forecv = cv;
  if ((focusminwidth && (focusminwidth < 0 || D_forecv->c_xe - D_forecv->c_xs + 1 < focusminwidth)) ||
      (focusminheight && (focusminheight < 0 || D_forecv->c_ye - D_forecv->c_ys + 1 < focusminheight)))
    {
      ResizeCanvas(&D_canvas);
      RecreateCanvasChain();
      RethinkDisplayViewports();
      ResizeLayersToCanvases();	/* redisplays */
    }
  fore = D_fore = Layer2Window(D_forecv->c_layer);
  if (D_other == fore)
    D_other = 0;
  flayer = D_forecv->c_layer;
#ifdef RXVT_OSC
  if (D_xtermosc[2] || D_xtermosc[3])
    {
      Activate(-1);
    }
  else
#endif
    {
      RefreshHStatus();
#ifdef RXVT_OSC
      RefreshXtermOSC();
#endif
      flayer = D_forecv->c_layer;
      CV_CALL(D_forecv, LayRestore();LaySetCursor());
      WindowChanged(0, 'F');
    }

  display = odisplay;
}

#ifdef RXVT_OSC
void
RefreshXtermOSC()
{
  int i;
  struct win *p;

  p = Layer2Window(D_forecv->c_layer);
  for (i = 4; i >=0; i--)
    SetXtermOSC(i, p ? p->w_xtermosc[i] : 0, "\a");
}
#endif

int
ParseAttrColor(s1, s2, msgok)
char *s1, *s2;
int msgok;
{
  int i, n;
  char *s, *ss;
  int r = 0;

  s = s1;
  while (*s == ' ')
    s++;
  ss = s;
  while (*ss && *ss != ' ')
    ss++;
  while (*ss == ' ')
    ss++;
  if (*s && (s2 || *ss || !((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '.')))
    {
      int mode = 0, n = 0;
      if (*s == '+')
	{
	  mode = 1;
	  s++;
	}
      else if (*s == '-')
	{
	  mode = -1;
	  s++;
	}
      else if (*s == '!')
	{
	  mode = 2;
	  s++;
	}
      else if (*s == '=')
	s++;
      if (*s >= '0' && *s <= '9')
	{
	  n = *s++ - '0';
	  if (*s >= '0' && *s <= '9')
	    n = n * 16 + (*s++ - '0');
	  else if (*s >= 'a' && *s <= 'f')
	    n = n * 16 + (*s++ - ('a' - 10));
	  else if (*s >= 'A' && *s <= 'F')
	    n = n * 16 + (*s++ - ('A' - 10));
	  else if (*s && *s != ' ')
	    {
	      if (msgok)
		Msg(0, "Illegal attribute hexchar '%c'", *s);
	      return -1;
	    }
	}
      else
	{
	  while (*s && *s != ' ')
	    {
	      if (*s == 'd')
		n |= A_DI;
	      else if (*s == 'u')
		n |= A_US;
	      else if (*s == 'b')
		n |= A_BD;
	      else if (*s == 'r')
		n |= A_RV;
	      else if (*s == 's')
		n |= A_SO;
	      else if (*s == 'B')
		n |= A_BL;
	      else
		{
		  if (msgok)
		    Msg(0, "Illegal attribute specifier '%c'", *s);
		  return -1;
		}
	      s++;
	    }
	}
      if (*s && *s != ' ')
	{
	  if (msgok)
	    Msg(0, "junk after attribute description: '%c'", *s);
	  return -1;
	}
      if (mode == -1)
	r = n << 8 | n;
      else if (mode == 1)
	r = n << 8;
      else if (mode == 2)
	r = n;
      else if (mode == 0)
	r = 0xffff ^ n;
    }
  while (*s && *s == ' ')
    s++;

  if (s2)
    {
      if (*s)
	{
	  if (msgok)
	    Msg(0, "junk after description: '%c'", *s);
	  return -1;
	}
      s = s2;
      while (*s && *s == ' ')
	s++;
    }

#ifdef COLOR
  if (*s)
    {
      static char costr[] = "krgybmcw d    i.01234567 9     f               FKRGYBMCW      I ";
      int numco = 0, j;

      n = 0;
      if (*s == '.')
	{
	  numco++;
	  n = 0x0f;
	  s++;
	}
      for (j = 0; j < 2 && *s && *s != ' '; j++)
	{
	  for (i = 0; costr[i]; i++)
	    if (*s == costr[i])
	      break;
	  if (!costr[i])
	    {
	      if (msgok)
		Msg(0, "illegal color descriptor: '%c'", *s);
	      return -1;
	    }
	  numco++;
	  n = n << 4 | (i & 15);
#ifdef COLORS16
	  if (i >= 48)
	    n = (n & 0x20ff) | 0x200;
#endif
	  s++;
	}
      if ((n & 0xf00) == 0xf00)
        n ^= 0xf00;	/* clear superflous bits */
#ifdef COLORS16
      if (n & 0x2000)
	n ^= 0x2400;	/* shift bit into right position */
#endif
      if (numco == 1)
	n |= 0xf0;	/* don't change bg color */
      if (numco != 2 && n != 0xff)
	n |= 0x100;	/* special invert mode */
      if (*s && *s != ' ')
	{
	  if (msgok)
	    Msg(0, "junk after color description: '%c'", *s);
	  return -1;
	}
      n ^= 0xff;
      r |= n << 16;
    }
#endif

  while (*s && *s == ' ')
    s++;
  if (*s)
    {
      if (msgok)
	Msg(0, "junk after description: '%c'", *s);
      return -1;
    }
  debug1("ParseAttrColor %06x\n", r);
  return r;
}

/*
 *  Color coding:
 *    0-7 normal colors
 *    9   default color
 *    e   just set intensity
 *    f   don't change anything
 *  Intensity is encoded into bits 17(fg) and 18(bg).
 */
void
ApplyAttrColor(i, mc)
int i;
struct mchar *mc;
{
  debug1("ApplyAttrColor %06x\n", i);
  mc->attr |= i >> 8 & 255;
  mc->attr ^= i & 255;
#ifdef COLOR
  i = (i >> 16) ^ 0xff;
  if ((i & 0x100) != 0)
    {
      i &= 0xeff;
      if (mc->attr & (A_SO|A_RV))
# ifdef COLORS16
        i = ((i & 0x0f) << 4) | ((i & 0xf0) >> 4) | ((i & 0x200) << 1) | ((i & 0x400) >> 1);
# else
        i = ((i & 0x0f) << 4) | ((i & 0xf0) >> 4);
# endif
    }
# ifdef COLORS16
  if ((i & 0x0f) != 0x0f)
    mc->attr = (mc->attr & 0xbf) | ((i >> 3) & 0x40);
  if ((i & 0xf0) != 0xf0)
    mc->attr = (mc->attr & 0x7f) | ((i >> 3) & 0x80);
# endif
  mc->color = 0x99 ^ mc->color;
  if ((i & 0x0e) == 0x0e)
    i = (i & 0xf0) | (mc->color & 0x0f);
  if ((i & 0xe0) == 0xe0)
    i = (i & 0x0f) | (mc->color & 0xf0);
  mc->color = 0x99 ^ i;
  debug2("ApplyAttrColor - %02x %02x\n", mc->attr, i);
#endif
}