File: main.c

package info (click to toggle)
xterm 344-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,024 kB
  • sloc: ansic: 76,762; sh: 4,285; perl: 2,869; makefile: 813; xml: 40; sed: 11
file content (5722 lines) | stat: -rw-r--r-- 154,572 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
/* $XTermId: main.c,v 1.845 2018/12/16 23:06:59 tom Exp $ */

/*
 * Copyright 2002-2017,2018 by Thomas E. Dickey
 *
 *                         All Rights Reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name(s) of the above copyright
 * holders shall not be used in advertising or otherwise to promote the
 * sale, use or other dealings in this Software without prior written
 * authorization.
 *
 * Copyright 1987, 1988  X Consortium
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the X Consortium shall not be
 * used in advertising or otherwise to promote the sale, use or other dealings
 * in this Software without prior written authorization from the X Consortium.
 *
 * Copyright 1987, 1988 by Digital Equipment Corporation, Maynard.
 *
 *                         All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of Digital not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.
 *
 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 */

/*
 *				 W A R N I N G
 *
 * If you think you know what all of this code is doing, you are
 * probably very mistaken.  There be serious and nasty dragons here.
 *
 * This client is *not* to be taken as an example of how to write X
 * Toolkit applications.  It is in need of a substantial rewrite,
 * ideally to create a generic tty widget with several different parsing
 * widgets so that you can plug 'em together any way you want.  Don't
 * hold your breath, though....
 */

/* main.c */

#define RES_OFFSET(field)	XtOffsetOf(XTERM_RESOURCE, field)

#include <xterm.h>
#include <version.h>
#include <graphics.h>

#include <X11/cursorfont.h>
#include <X11/Xlocale.h>

#if OPT_TOOLBAR

#if defined(HAVE_LIB_XAW)
#include <X11/Xaw/Form.h>
#elif defined(HAVE_LIB_XAW3D)
#include <X11/Xaw3d/Form.h>
#elif defined(HAVE_LIB_XAW3DXFT)
#include <X11/Xaw3dxft/Form.h>
#elif defined(HAVE_LIB_NEXTAW)
#include <X11/neXtaw/Form.h>
#elif defined(HAVE_LIB_XAWPLUS)
#include <X11/XawPlus/Form.h>
#endif

#endif /* OPT_TOOLBAR */

#include <pwd.h>
#include <ctype.h>

#include <data.h>
#include <error.h>
#include <menu.h>
#include <main.h>
#include <xstrings.h>
#include <xtermcap.h>
#include <xterm_io.h>

#if OPT_WIDE_CHARS
#include <charclass.h>
#endif

#ifdef __osf__
#define USE_SYSV_SIGNALS
#define WTMP
#include <pty.h>		/* openpty() */
#endif

#ifdef __sgi
#include <grp.h>		/* initgroups() */
#endif

static void Syntax(char *) GCC_NORETURN;
static void HsSysError(int) GCC_NORETURN;

#if defined(__SCO__) || defined(SVR4) || defined(_POSIX_SOURCE) || ( defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 1) )
#define USE_POSIX_SIGNALS
#endif

#if defined(SYSV) && !defined(SVR4) && !defined(ISC22) && !defined(ISC30)
/* older SYSV systems cannot ignore SIGHUP.
   Shell hangs, or you get extra shells, or something like that */
#define USE_SYSV_SIGHUP
#endif

#if defined(sony) && defined(bsd43) && !defined(KANJI)
#define KANJI
#endif

#ifdef linux
#define USE_SYSV_PGRP
#define USE_SYSV_SIGNALS
#define WTMP
#ifdef __GLIBC__
#if (__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))
#include <pty.h>
#endif
#endif
#endif

#ifdef __MVS__
#define USE_SYSV_PGRP
#define USE_SYSV_SIGNALS
#endif

#ifdef __CYGWIN__
#define WTMP
#endif

#ifdef __SCO__
#ifndef _SVID3
#define _SVID3
#endif
#endif

#if defined(__GLIBC__) && !defined(linux)
#define USE_SYSV_PGRP
#define WTMP
#endif

#if defined(USE_TTY_GROUP) || defined(USE_UTMP_SETGID) || defined(HAVE_INITGROUPS)
#include <grp.h>
#endif

#ifndef TTY_GROUP_NAME
#define TTY_GROUP_NAME "tty"
#endif

#include <sys/stat.h>

#ifdef Lynx
#ifndef BSDLY
#define BSDLY	0
#endif
#ifndef VTDLY
#define VTDLY	0
#endif
#ifndef FFDLY
#define FFDLY	0
#endif
#endif

#ifdef SYSV			/* { */

#ifdef USE_USG_PTYS		/* AT&T SYSV has no ptyio.h */
#include <sys/stropts.h>	/* for I_PUSH */
#include <poll.h>		/* for POLLIN */
#endif /* USE_USG_PTYS */

#define USE_SYSV_SIGNALS
#define	USE_SYSV_PGRP

#if !defined(TIOCSWINSZ) || defined(__SCO__) || defined(__UNIXWARE__)
#define USE_SYSV_ENVVARS	/* COLUMNS/LINES vs. TERMCAP */
#endif

/*
 * now get system-specific includes
 */
#ifdef macII
#include <sys/ttychars.h>
#undef USE_SYSV_ENVVARS
#undef FIOCLEX
#undef FIONCLEX
#define setpgrp2 setpgrp
#include <sgtty.h>
#include <sys/resource.h>
#endif

#ifdef __hpux
#include <sys/ptyio.h>
#endif /* __hpux */

#ifdef __osf__
#undef  USE_SYSV_PGRP
#define setpgrp setpgid
#endif

#ifdef __sgi
#include <sys/sysmacros.h>
#endif /* __sgi */

#ifdef sun
#include <sys/strredir.h>
#endif

#else /* } !SYSV { */ /* BSD systems */

#ifdef __QNX__

#ifndef __QNXNTO__
#define ttyslot() 1
#else
#define USE_SYSV_PGRP
extern __inline__
int
ttyslot(void)
{
    return 1;			/* yuk */
}
#endif

#else

#if defined(__INTERIX) || defined(__APPLE__)
#define setpgrp setpgid
#endif

#ifndef linux
#ifndef VMS
#ifndef USE_POSIX_TERMIOS
#ifndef USE_ANY_SYSV_TERMIO
#include <sgtty.h>
#endif
#endif /* USE_POSIX_TERMIOS */
#ifdef Lynx
#include <resource.h>
#else
#include <sys/resource.h>
#endif
#endif /* !VMS */
#endif /* !linux */

#endif /* __QNX__ */

#endif /* } !SYSV */

/* Xpoll.h and <sys/param.h> on glibc 2.1 systems have colliding NBBY's */
#if defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1)))
#ifndef NOFILE
#define NOFILE OPEN_MAX
#endif
#elif !(defined(VMS) || defined(WIN32) || defined(Lynx) || defined(__GNU__) || defined(__MVS__))
#include <sys/param.h>		/* for NOFILE */
#endif

#if defined(BSD) && (BSD >= 199103)
#define WTMP
#endif

#include <stdio.h>

#ifdef __hpux
#include <sys/utsname.h>
#endif /* __hpux */

#if defined(apollo) && (OSMAJORVERSION == 10) && (OSMINORVERSION < 4)
#define ttyslot() 1
#endif /* apollo */

#if defined(UTMPX_FOR_UTMP)
#define UTMP_STR utmpx
#else
#define UTMP_STR utmp
#endif

#if defined(USE_UTEMPTER)
#include <utempter.h>
#endif

#if defined(I_FIND) && defined(I_PUSH)
#define PUSH_FAILS(fd,name) ioctl(fd, I_FIND, name) == 0 \
			 && ioctl(fd, I_PUSH, name) < 0
#else
#define PUSH_FAILS(fd,name) ioctl(fd, I_PUSH, name) < 0
#endif

#if defined(UTMPX_FOR_UTMP)

#include <utmpx.h>

#define call_endutent  endutxent
#define call_getutid   getutxid
#define call_pututline pututxline
#define call_setutent  setutxent
#define call_updwtmp   updwtmpx

#elif defined(HAVE_UTMP)

#include <utmp.h>

#if defined(_CRAY) && (OSMAJORVERSION < 8)
extern struct utmp *getutid __((struct utmp * _Id));
#endif

#define call_endutent  endutent
#define call_getutid   getutid
#define call_pututline pututline
#define call_setutent  setutent
#define call_updwtmp   updwtmp

#endif

#if defined(USE_LASTLOG) && defined(HAVE_LASTLOG_H)
#include <lastlog.h>		/* caution: glibc includes utmp.h here */
#endif

#ifndef USE_LASTLOGX
#if defined(_NETBSD_SOURCE) && defined(_PATH_LASTLOGX)
#define USE_LASTLOGX 1
#endif
#endif

#ifdef  PUCC_PTYD
#include <local/openpty.h>
#endif /* PUCC_PTYD */

#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
#include <util.h>		/* openpty() */
#endif

#if defined(__FreeBSD__) || defined(__DragonFly__)
#include <libutil.h>		/* openpty() */
#endif

#if !defined(UTMP_FILENAME)
#if defined(UTMP_FILE)
#define UTMP_FILENAME UTMP_FILE
#elif defined(_PATH_UTMP)
#define UTMP_FILENAME _PATH_UTMP
#else
#define UTMP_FILENAME "/etc/utmp"
#endif
#endif

#ifndef LASTLOG_FILENAME
#ifdef _PATH_LASTLOG
#define LASTLOG_FILENAME _PATH_LASTLOG
#else
#define LASTLOG_FILENAME "/usr/adm/lastlog"	/* only on BSD systems */
#endif
#endif

#if !defined(WTMP_FILENAME)
#if defined(WTMP_FILE)
#define WTMP_FILENAME WTMP_FILE
#elif defined(_PATH_WTMP)
#define WTMP_FILENAME _PATH_WTMP
#elif defined(SYSV)
#define WTMP_FILENAME "/etc/wtmp"
#else
#define WTMP_FILENAME "/usr/adm/wtmp"
#endif
#endif

#include <signal.h>

#if defined(__SCO__) || (defined(ISC) && !defined(_POSIX_SOURCE))
#undef SIGTSTP			/* defined, but not the BSD way */
#endif

#ifdef SIGTSTP
#include <sys/wait.h>
#endif

#if defined(__SCO__) || defined(__UNIXWARE__)
#undef ECHOKE
#undef ECHOCTL
#endif

#if defined(HAVE_SYS_TTYDEFAULTS_H) && !defined(CEOF)
#include <sys/ttydefaults.h>
#endif

#ifdef X_NOT_POSIX
extern long lseek();
#if defined(USG) || defined(SVR4)
extern unsigned sleep();
#else
extern void sleep();
#endif
extern char *ttyname();
#endif

#if defined(SYSV) && defined(DECL_PTSNAME)
extern char *ptsname(int);
#endif

#ifndef VMS
static void reapchild(int /* n */ );
static int spawnXTerm(XtermWidget	/* xw */
		      ,unsigned /* line_speed */ );
static void remove_termcap_entry(char *, const char *);
#ifdef USE_PTY_SEARCH
static int pty_search(int * /* pty */ );
#endif
#endif /* ! VMS */

static int get_pty(int *pty, char *from);
static void resize_termcap(XtermWidget xw);
static void set_owner(char *device, unsigned uid, unsigned gid, unsigned mode);

static Bool added_utmp_entry = False;

#ifdef HAVE_POSIX_SAVED_IDS
static uid_t save_euid;
static gid_t save_egid;
#endif

static uid_t save_ruid;
static gid_t save_rgid;

#if defined(USE_UTMP_SETGID)
static int really_get_pty(int *pty, char *from);
#endif

#if defined(USE_SYSV_UTMP) && !defined(USE_UTEMPTER)
static Bool xterm_exiting = False;
#endif

static char *explicit_shname = NULL;

/*
** Ordinarily it should be okay to omit the assignment in the following
** statement. Apparently the c89 compiler on AIX 4.1.3 has a bug, or does
** it? Without the assignment though the compiler will init command_to_exec
** to 0xffffffff instead of NULL; and subsequent usage, e.g. in spawnXTerm() to
** SEGV.
*/
static char **command_to_exec = NULL;

#if OPT_LUIT_PROG
static char **command_to_exec_with_luit = NULL;
static unsigned command_length_with_luit = 0;
#endif

#define TERMCAP_ERASE "kb"
#define VAL_INITIAL_ERASE A2E(8)

/* choose a nice default value for speed - if we make it too low, users who
 * mistakenly use $TERM set to vt100 will get padding delays.  Setting it to a
 * higher value is not useful since legacy applications (termcap) that care
 * about padding generally store the code in a short, which does not have
 * enough bits for the extended values.
 */
#ifdef B38400			/* everyone should define this */
#define VAL_LINE_SPEED B38400
#else /* ...but xterm's used this for a long time */
#define VAL_LINE_SPEED B9600
#endif

/*
 * Allow use of system default characters if defined and reasonable.
 * These are based on the BSD ttydefaults.h
 */
#ifndef CBRK
#define CBRK     0xff		/* was 0 */
#endif
#ifndef CDISCARD
#define CDISCARD CONTROL('O')
#endif
#ifndef CDSUSP
#define CDSUSP   CONTROL('Y')
#endif
#ifndef CEOF
#define CEOF     CONTROL('D')
#endif
#ifndef CEOL
#define CEOL	 0xff		/* was 0 */
#endif
#ifndef CERASE
#define CERASE   0177
#endif
#ifndef CERASE2
#define	CERASE2  CONTROL('H')
#endif
#ifndef CFLUSH
#define CFLUSH   CONTROL('O')
#endif
#ifndef CINTR
#define CINTR    CONTROL('C')
#endif
#ifndef CKILL
#define CKILL	 CONTROL('U')	/* was '@' */
#endif
#ifndef CLNEXT
#define CLNEXT   CONTROL('V')
#endif
#ifndef CNUL
#define CNUL     0
#endif
#ifndef CQUIT
#define CQUIT    CONTROL('\\')
#endif
#ifndef CRPRNT
#define CRPRNT   CONTROL('R')
#endif
#ifndef CREPRINT
#define CREPRINT CRPRNT
#endif
#ifndef CSTART
#define CSTART   CONTROL('Q')
#endif
#ifndef CSTATUS
#define	CSTATUS  CONTROL('T')
#endif
#ifndef CSTOP
#define CSTOP    CONTROL('S')
#endif
#ifndef CSUSP
#define CSUSP    CONTROL('Z')
#endif
#ifndef CSWTCH
#define CSWTCH   0
#endif
#ifndef CWERASE
#define CWERASE  CONTROL('W')
#endif

#ifdef USE_ANY_SYSV_TERMIO
#define TERMIO_STRUCT struct termio
#define ttySetAttr(fd, datap) ioctl(fd, TCSETA, datap)
#define ttyGetAttr(fd, datap) ioctl(fd, TCGETA, datap)
#define ttyFlush(fd)          ioctl(fd, TCFLSH, 1)
#elif defined(USE_POSIX_TERMIOS)
#define TERMIO_STRUCT struct termios
#define ttySetAttr(fd, datap) tcsetattr(fd, TCSANOW, datap)
#define ttyGetAttr(fd, datap) tcgetattr(fd, datap)
#define ttyFlush(fd)          tcflush(fd, TCOFLUSH)
#endif /* USE_ANY_SYSV_TERMIO */

#ifndef VMS
#ifdef TERMIO_STRUCT
/* The following structures are initialized in main() in order
** to eliminate any assumptions about the internal order of their
** contents.
*/
static TERMIO_STRUCT d_tio;

#ifndef ONLCR
#define ONLCR 0
#endif

#ifndef OPOST
#define OPOST 0
#endif

#define D_TIO_FLAGS (OPOST | ONLCR)

#ifdef HAS_LTCHARS
static struct ltchars d_ltc;
#endif /* HAS_LTCHARS */

#ifdef TIOCLSET
static unsigned int d_lmode;
#endif /* TIOCLSET */

#else /* !TERMIO_STRUCT */

#define D_SG_FLAGS (EVENP | ODDP | ECHO | CRMOD)

static struct sgttyb d_sg =
{
    0, 0, 0177, CKILL, (D_SG_FLAGS | XTABS)
};
static struct tchars d_tc =
{
    CINTR, CQUIT, CSTART,
    CSTOP, CEOF, CBRK
};
static struct ltchars d_ltc =
{
    CSUSP, CDSUSP, CRPRNT,
    CFLUSH, CWERASE, CLNEXT
};
static int d_disipline = NTTYDISC;
static long int d_lmode = LCRTBS | LCRTERA | LCRTKIL | LCTLECH;
#ifdef sony
static long int d_jmode = KM_SYSSJIS | KM_ASCII;
static struct jtchars d_jtc =
{
    'J', 'B'
};
#endif /* sony */
#endif /* TERMIO_STRUCT */
#endif /* ! VMS */

/*
 * SYSV has the termio.c_cc[V] and ltchars; BSD has tchars and ltchars;
 * SVR4 has only termio.c_cc, but it includes everything from ltchars.
 * POSIX termios has termios.c_cc, which is similar to SVR4.
 */
#define TTYMODE(name) { name, sizeof(name)-1, 0, 0 }
static Boolean override_tty_modes = False;
/* *INDENT-OFF* */
static struct {
    const char *name;
    size_t len;
    int set;
    int value;
} ttyModes[] = {
    TTYMODE("intr"),		/* tchars.t_intrc ; VINTR */
#define XTTYMODE_intr	0
    TTYMODE("quit"),		/* tchars.t_quitc ; VQUIT */
#define XTTYMODE_quit	1
    TTYMODE("erase"),		/* sgttyb.sg_erase ; VERASE */
#define XTTYMODE_erase	2
    TTYMODE("kill"),		/* sgttyb.sg_kill ; VKILL */
#define XTTYMODE_kill	3
    TTYMODE("eof"),		/* tchars.t_eofc ; VEOF */
#define XTTYMODE_eof	4
    TTYMODE("eol"),		/* VEOL */
#define XTTYMODE_eol	5
    TTYMODE("swtch"),		/* VSWTCH */
#define XTTYMODE_swtch	6
    TTYMODE("start"),		/* tchars.t_startc ; VSTART */
#define XTTYMODE_start	7
    TTYMODE("stop"),		/* tchars.t_stopc ; VSTOP */
#define XTTYMODE_stop	8
    TTYMODE("brk"),		/* tchars.t_brkc */
#define XTTYMODE_brk	9
    TTYMODE("susp"),		/* ltchars.t_suspc ; VSUSP */
#define XTTYMODE_susp	10
    TTYMODE("dsusp"),		/* ltchars.t_dsuspc ; VDSUSP */
#define XTTYMODE_dsusp	11
    TTYMODE("rprnt"),		/* ltchars.t_rprntc ; VREPRINT */
#define XTTYMODE_rprnt	12
    TTYMODE("flush"),		/* ltchars.t_flushc ; VDISCARD */
#define XTTYMODE_flush	13
    TTYMODE("weras"),		/* ltchars.t_werasc ; VWERASE */
#define XTTYMODE_weras	14
    TTYMODE("lnext"),		/* ltchars.t_lnextc ; VLNEXT */
#define XTTYMODE_lnext	15
    TTYMODE("status"),		/* VSTATUS */
#define XTTYMODE_status	16
    TTYMODE("erase2"),		/* VERASE2 */
#define XTTYMODE_erase2	17
    TTYMODE("eol2"),		/* VEOL2 */
#define XTTYMODE_eol2	18
    TTYMODE("tabs"),		/* TAB0 */
#define XTTYMODE_tabs	19
    TTYMODE("-tabs"),		/* TAB3 */
#define XTTYMODE__tabs	20
};

#ifndef TAB0
#define TAB0 0
#endif

#ifndef TAB3
#if defined(OXTABS)
#define TAB3 OXTABS
#elif defined(XTABS)
#define TAB3 XTABS
#endif
#endif

#ifndef TABDLY
#define TABDLY (TAB0|TAB3)
#endif

#define isTtyMode(p,q) (ttyChars[p].myMode == q && ttyModes[q].set)

#define isTabMode(n) \
	(isTtyMode(n, XTTYMODE_tabs) || \
	 isTtyMode(n, XTTYMODE__tabs))

#define TMODE(ind,var) \
	if (ttyModes[ind].set) \
	    var = (cc_t) ttyModes[ind].value

#define validTtyChar(data, n) \
	    (ttyChars[n].sysMode >= 0 && \
	     ttyChars[n].sysMode < (int) XtNumber(data.c_cc))

static const struct {
    int sysMode;
    int myMode;
    int myDefault;
} ttyChars[] = {
#ifdef VINTR
    { VINTR,    XTTYMODE_intr,   CINTR },
#endif
#ifdef VQUIT
    { VQUIT,    XTTYMODE_quit,   CQUIT },
#endif
#ifdef VERASE
    { VERASE,   XTTYMODE_erase,  CERASE },
#endif
#ifdef VKILL
    { VKILL,    XTTYMODE_kill,   CKILL },
#endif
#ifdef VEOF
    { VEOF,     XTTYMODE_eof,    CEOF },
#endif
#ifdef VEOL
    { VEOL,     XTTYMODE_eol,    CEOL },
#endif
#ifdef VSWTCH
    { VSWTCH,   XTTYMODE_swtch,  CNUL },
#endif
#ifdef VSTART
    { VSTART,   XTTYMODE_start,  CSTART },
#endif
#ifdef VSTOP
    { VSTOP,    XTTYMODE_stop,   CSTOP },
#endif
#ifdef VSUSP
    { VSUSP,    XTTYMODE_susp,   CSUSP },
#endif
#ifdef VDSUSP
    { VDSUSP,   XTTYMODE_dsusp,  CDSUSP },
#endif
#ifdef VREPRINT
    { VREPRINT, XTTYMODE_rprnt,  CREPRINT },
#endif
#ifdef VDISCARD
    { VDISCARD, XTTYMODE_flush,  CDISCARD },
#endif
#ifdef VWERASE
    { VWERASE,  XTTYMODE_weras,  CWERASE },
#endif
#ifdef VLNEXT
    { VLNEXT,   XTTYMODE_lnext,  CLNEXT },
#endif
#ifdef VSTATUS
    { VSTATUS,  XTTYMODE_status, CSTATUS },
#endif
#ifdef VERASE2
    { VERASE2,  XTTYMODE_erase2, CERASE2 },
#endif
#ifdef VEOL2
    { VEOL2,    XTTYMODE_eol2,   CNUL },
#endif
    { -1,       XTTYMODE_tabs,   TAB0 },
    { -1,       XTTYMODE__tabs,  TAB3 },
};
/* *INDENT-ON* */

static int parse_tty_modes(char *s);

#ifndef USE_UTEMPTER
#ifdef USE_SYSV_UTMP
#if (defined(AIXV3) && (OSMAJORVERSION < 4)) && !(defined(getutid))
extern struct utmp *getutid();
#endif /* AIXV3 */

#else /* not USE_SYSV_UTMP */
static char etc_utmp[] = UTMP_FILENAME;
#endif /* USE_SYSV_UTMP */

#if defined(USE_LASTLOG) && defined(USE_STRUCT_LASTLOG)
static char etc_lastlog[] = LASTLOG_FILENAME;
#else
#undef USE_LASTLOG
#endif

#ifdef WTMP
static char etc_wtmp[] = WTMP_FILENAME;
#endif
#endif /* !USE_UTEMPTER */

/*
 * Some people with 4.3bsd /bin/login seem to like to use login -p -f user
 * to implement xterm -ls.  They can turn on USE_LOGIN_DASH_P and turn off
 * WTMP and USE_LASTLOG.
 */
#ifdef USE_LOGIN_DASH_P
#ifndef LOGIN_FILENAME
#define LOGIN_FILENAME "/bin/login"
#endif
static char bin_login[] = LOGIN_FILENAME;
#endif

static char noPassedPty[2];
static char *passedPty = noPassedPty;	/* name if pty if slave */

#if defined(TIOCCONS) || defined(SRIOCSREDIR)
static int Console;
#include <X11/Xmu/SysUtil.h>	/* XmuGetHostname */
#define MIT_CONSOLE_LEN	12
#define MIT_CONSOLE "MIT_CONSOLE_"
static char mit_console_name[255 + MIT_CONSOLE_LEN + 1] = MIT_CONSOLE;
static Atom mit_console;
#endif /* TIOCCONS */

#ifndef USE_SYSV_UTMP
static int tslot;
#endif /* USE_SYSV_UTMP */
static sigjmp_buf env;

#define SetUtmpHost(dst, screen) \
	{ \
	    char host[sizeof(dst) + 1]; \
	    strncpy(host, DisplayString(screen->display), sizeof(host) - 1); \
	    host[sizeof(dst)] = '\0'; \
	    TRACE(("DisplayString(%s)\n", host)); \
	    if (!resource.utmpDisplayId) { \
		char *endptr = strrchr(host, ':'); \
		if (endptr) { \
		    TRACE(("trimming display-id '%s'\n", host)); \
		    *endptr = '\0'; \
		} \
	    } \
	    copy_filled(dst, host, sizeof(dst)); \
	}

#ifdef HAVE_UTMP_UT_SYSLEN
#  define SetUtmpSysLen(utmp) 			   \
	{ \
	    utmp.ut_host[sizeof(utmp.ut_host)-1] = '\0'; \
	    utmp.ut_syslen = (short) ((int) strlen(utmp.ut_host) + 1); \
	}
#endif

/* used by VT (charproc.c) */

static XtResource application_resources[] =
{
    Sres("iconGeometry", "IconGeometry", icon_geometry, NULL),
    Sres(XtNtitle, XtCTitle, title, NULL),
    Sres(XtNiconHint, XtCIconHint, icon_hint, NULL),
    Sres(XtNiconName, XtCIconName, icon_name, NULL),
    Sres("termName", "TermName", term_name, NULL),
    Sres("ttyModes", "TtyModes", tty_modes, NULL),
    Sres("validShells", "ValidShells", valid_shells, NULL),
    Bres("hold", "Hold", hold_screen, False),
    Bres("utmpInhibit", "UtmpInhibit", utmpInhibit, False),
    Bres("utmpDisplayId", "UtmpDisplayId", utmpDisplayId, True),
    Bres("messages", "Messages", messages, True),
    Ires("minBufSize", "MinBufSize", minBufSize, 4096),
    Ires("maxBufSize", "MaxBufSize", maxBufSize, 32768),
    Sres("menuLocale", "MenuLocale", menuLocale, DEF_MENU_LOCALE),
    Sres("omitTranslation", "OmitTranslation", omitTranslation, NULL),
    Sres("keyboardType", "KeyboardType", keyboardType, "unknown"),
#if OPT_PRINT_ON_EXIT
    Ires("printModeImmediate", "PrintModeImmediate", printModeNow, 0),
    Ires("printOptsImmediate", "PrintOptsImmediate", printOptsNow, 9),
    Sres("printFileImmediate", "PrintFileImmediate", printFileNow, NULL),
    Ires("printModeOnXError", "PrintModeOnXError", printModeOnXError, 0),
    Ires("printOptsOnXError", "PrintOptsOnXError", printOptsOnXError, 9),
    Sres("printFileOnXError", "PrintFileOnXError", printFileOnXError, NULL),
#endif
#if OPT_SUNPC_KBD
    Bres("sunKeyboard", "SunKeyboard", sunKeyboard, False),
#endif
#if OPT_HP_FUNC_KEYS
    Bres("hpFunctionKeys", "HpFunctionKeys", hpFunctionKeys, False),
#endif
#if OPT_SCO_FUNC_KEYS
    Bres("scoFunctionKeys", "ScoFunctionKeys", scoFunctionKeys, False),
#endif
#if OPT_SUN_FUNC_KEYS
    Bres("sunFunctionKeys", "SunFunctionKeys", sunFunctionKeys, False),
#endif
#if OPT_TCAP_FKEYS
    Bres("tcapFunctionKeys", "TcapFunctionKeys", termcapKeys, False),
#endif
#if OPT_INITIAL_ERASE
    Bres("ptyInitialErase", "PtyInitialErase", ptyInitialErase, DEF_INITIAL_ERASE),
    Bres("backarrowKeyIsErase", "BackarrowKeyIsErase", backarrow_is_erase, DEF_BACKARO_ERASE),
#endif
    Bres("useInsertMode", "UseInsertMode", useInsertMode, False),
#if OPT_ZICONBEEP
    Ires("zIconBeep", "ZIconBeep", zIconBeep, 0),
    Sres("zIconTitleFormat", "ZIconTitleFormat", zIconFormat, "*** %s"),
#endif
#if OPT_PTY_HANDSHAKE
    Bres("waitForMap", "WaitForMap", wait_for_map, False),
    Bres("ptyHandshake", "PtyHandshake", ptyHandshake, True),
    Bres("ptySttySize", "PtySttySize", ptySttySize, DEF_PTY_STTY_SIZE),
#endif
#if OPT_REPORT_CCLASS
    Bres("reportCClass", "ReportCClass", reportCClass, False),
#endif
#if OPT_REPORT_COLORS
    Bres("reportColors", "ReportColors", reportColors, False),
#endif
#if OPT_REPORT_FONTS
    Bres("reportFonts", "ReportFonts", reportFonts, False),
#endif
#if OPT_REPORT_ICONS
    Bres("reportIcons", "ReportIcons", reportIcons, False),
#endif
#if OPT_SAME_NAME
    Bres("sameName", "SameName", sameName, True),
#endif
#if OPT_SESSION_MGT
    Bres("sessionMgt", "SessionMgt", sessionMgt, True),
#endif
#if OPT_TOOLBAR
    Bres(XtNtoolBar, XtCToolBar, toolBar, True),
#endif
#if OPT_MAXIMIZE
    Bres(XtNmaximized, XtCMaximized, maximized, False),
    Sres(XtNfullscreen, XtCFullscreen, fullscreen_s, "off"),
#endif
};

static String fallback_resources[] =
{
#if OPT_TOOLBAR
    "*toolBar: false",
#endif
    "*SimpleMenu*menuLabel.vertSpace: 100",
    "*SimpleMenu*HorizontalMargins: 16",
    "*SimpleMenu*Sme.height: 16",
    "*SimpleMenu*Cursor: left_ptr",
    "*mainMenu.Label:  Main Options (no app-defaults)",
    "*vtMenu.Label:  VT Options (no app-defaults)",
    "*fontMenu.Label:  VT Fonts (no app-defaults)",
#if OPT_TEK4014
    "*tekMenu.Label:  Tek Options (no app-defaults)",
#endif
    NULL
};

/* Command line options table.  Only resources are entered here...there is a
   pass over the remaining options after XrmParseCommand is let loose. */
/* *INDENT-OFF* */
#define DATA(option,pattern,type,value) { (char *) option, (char *) pattern, type, (XPointer) value }
static XrmOptionDescRec optionDescList[] = {
DATA("-geometry",	"*vt100.geometry",XrmoptionSepArg,	NULL),
DATA("-132",		"*c132",	XrmoptionNoArg,		"on"),
DATA("+132",		"*c132",	XrmoptionNoArg,		"off"),
DATA("-ah",		"*alwaysHighlight", XrmoptionNoArg,	"on"),
DATA("+ah",		"*alwaysHighlight", XrmoptionNoArg,	"off"),
DATA("-aw",		"*autoWrap",	XrmoptionNoArg,		"on"),
DATA("+aw",		"*autoWrap",	XrmoptionNoArg,		"off"),
#ifndef NO_ACTIVE_ICON
DATA("-ai",		"*activeIcon",	XrmoptionNoArg,		"off"),
DATA("+ai",		"*activeIcon",	XrmoptionNoArg,		"on"),
#endif /* NO_ACTIVE_ICON */
DATA("-b",		"*internalBorder",XrmoptionSepArg,	NULL),
DATA("-bc",		"*cursorBlink",	XrmoptionNoArg,		"on"),
DATA("+bc",		"*cursorBlink",	XrmoptionNoArg,		"off"),
DATA("-bcf",		"*cursorOffTime",XrmoptionSepArg,	NULL),
DATA("-bcn",		"*cursorOnTime",XrmoptionSepArg,	NULL),
DATA("-bdc",		"*colorBDMode",	XrmoptionNoArg,		"off"),
DATA("+bdc",		"*colorBDMode",	XrmoptionNoArg,		"on"),
DATA("-cb",		"*cutToBeginningOfLine", XrmoptionNoArg, "off"),
DATA("+cb",		"*cutToBeginningOfLine", XrmoptionNoArg, "on"),
DATA("-cc",		"*charClass",	XrmoptionSepArg,	NULL),
DATA("-cm",		"*colorMode",	XrmoptionNoArg,		"off"),
DATA("+cm",		"*colorMode",	XrmoptionNoArg,		"on"),
DATA("-cn",		"*cutNewline",	XrmoptionNoArg,		"off"),
DATA("+cn",		"*cutNewline",	XrmoptionNoArg,		"on"),
DATA("-cr",		"*cursorColor",	XrmoptionSepArg,	NULL),
DATA("-cu",		"*curses",	XrmoptionNoArg,		"on"),
DATA("+cu",		"*curses",	XrmoptionNoArg,		"off"),
DATA("-dc",		"*dynamicColors",XrmoptionNoArg,	"off"),
DATA("+dc",		"*dynamicColors",XrmoptionNoArg,	"on"),
DATA("-fb",		"*boldFont",	XrmoptionSepArg,	NULL),
DATA("-fbb",		"*freeBoldBox", XrmoptionNoArg,		"off"),
DATA("+fbb",		"*freeBoldBox", XrmoptionNoArg,		"on"),
DATA("-fbx",		"*forceBoxChars", XrmoptionNoArg,	"off"),
DATA("+fbx",		"*forceBoxChars", XrmoptionNoArg,	"on"),
#ifndef NO_ACTIVE_ICON
DATA("-fi",		"*iconFont",	XrmoptionSepArg,	NULL),
#endif /* NO_ACTIVE_ICON */
#if OPT_RENDERFONT
DATA("-fa",		"*faceName",	XrmoptionSepArg,	NULL),
DATA("-fd",		"*faceNameDoublesize", XrmoptionSepArg,	NULL),
DATA("-fs",		"*faceSize",	XrmoptionSepArg,	NULL),
#endif
#if OPT_WIDE_ATTRS && OPT_ISO_COLORS
DATA("-itc",		"*colorITMode",	XrmoptionNoArg,		"off"),
DATA("+itc",		"*colorITMode",	XrmoptionNoArg,		"on"),
#endif
#if OPT_WIDE_CHARS
DATA("-fw",		"*wideFont",	XrmoptionSepArg,	NULL),
DATA("-fwb",		"*wideBoldFont", XrmoptionSepArg,	NULL),
#endif
#if OPT_INPUT_METHOD
DATA("-fx",		"*ximFont",	XrmoptionSepArg,	NULL),
#endif
#if OPT_HIGHLIGHT_COLOR
DATA("-hc",		"*highlightColor", XrmoptionSepArg,	NULL),
DATA("-hm",		"*highlightColorMode", XrmoptionNoArg,	"on"),
DATA("+hm",		"*highlightColorMode", XrmoptionNoArg,	"off"),
DATA("-selfg",		"*highlightTextColor", XrmoptionSepArg,	NULL),
DATA("-selbg",		"*highlightColor", XrmoptionSepArg,	NULL),
#endif
#if OPT_HP_FUNC_KEYS
DATA("-hf",		"*hpFunctionKeys",XrmoptionNoArg,	"on"),
DATA("+hf",		"*hpFunctionKeys",XrmoptionNoArg,	"off"),
#endif
DATA("-hold",		"*hold",	XrmoptionNoArg,		"on"),
DATA("+hold",		"*hold",	XrmoptionNoArg,		"off"),
#if OPT_INITIAL_ERASE
DATA("-ie",		"*ptyInitialErase", XrmoptionNoArg,	"on"),
DATA("+ie",		"*ptyInitialErase", XrmoptionNoArg,	"off"),
#endif
DATA("-j",		"*jumpScroll",	XrmoptionNoArg,		"on"),
DATA("+j",		"*jumpScroll",	XrmoptionNoArg,		"off"),
#if OPT_C1_PRINT
DATA("-k8",		"*allowC1Printable", XrmoptionNoArg,	"on"),
DATA("+k8",		"*allowC1Printable", XrmoptionNoArg,	"off"),
#endif
DATA("-kt",		"*keyboardType", XrmoptionSepArg,	NULL),
/* parse logging options anyway for compatibility */
DATA("-l",		"*logging",	XrmoptionNoArg,		"on"),
DATA("+l",		"*logging",	XrmoptionNoArg,		"off"),
DATA("-lf",		"*logFile",	XrmoptionSepArg,	NULL),
DATA("-ls",		"*loginShell",	XrmoptionNoArg,		"on"),
DATA("+ls",		"*loginShell",	XrmoptionNoArg,		"off"),
DATA("-mb",		"*marginBell",	XrmoptionNoArg,		"on"),
DATA("+mb",		"*marginBell",	XrmoptionNoArg,		"off"),
DATA("-mc",		"*multiClickTime", XrmoptionSepArg,	NULL),
DATA("-mesg",		"*messages",	XrmoptionNoArg,		"off"),
DATA("+mesg",		"*messages",	XrmoptionNoArg,		"on"),
DATA("-ms",		"*pointerColor",XrmoptionSepArg,	NULL),
DATA("-nb",		"*nMarginBell",	XrmoptionSepArg,	NULL),
DATA("-nul",		"*underLine",	XrmoptionNoArg,		"off"),
DATA("+nul",		"*underLine",	XrmoptionNoArg,		"on"),
DATA("-pc",		"*boldColors",	XrmoptionNoArg,		"on"),
DATA("+pc",		"*boldColors",	XrmoptionNoArg,		"off"),
DATA("-rw",		"*reverseWrap",	XrmoptionNoArg,		"on"),
DATA("+rw",		"*reverseWrap",	XrmoptionNoArg,		"off"),
DATA("-s",		"*multiScroll",	XrmoptionNoArg,		"on"),
DATA("+s",		"*multiScroll",	XrmoptionNoArg,		"off"),
DATA("-sb",		"*scrollBar",	XrmoptionNoArg,		"on"),
DATA("+sb",		"*scrollBar",	XrmoptionNoArg,		"off"),
#if OPT_REPORT_CCLASS
DATA("-report-charclass","*reportCClass", XrmoptionNoArg,	"on"),
#endif
#if OPT_REPORT_COLORS
DATA("-report-colors",	"*reportColors", XrmoptionNoArg,	"on"),
#endif
#if OPT_REPORT_ICONS
DATA("-report-icons",	"*reportIcons",	XrmoptionNoArg,		"on"),
#endif
#if OPT_REPORT_FONTS
DATA("-report-fonts",	"*reportFonts", XrmoptionNoArg,		"on"),
#endif
#ifdef SCROLLBAR_RIGHT
DATA("-leftbar",	"*rightScrollBar", XrmoptionNoArg,	"off"),
DATA("-rightbar",	"*rightScrollBar", XrmoptionNoArg,	"on"),
#endif
DATA("-rvc",		"*colorRVMode",	XrmoptionNoArg,		"off"),
DATA("+rvc",		"*colorRVMode",	XrmoptionNoArg,		"on"),
DATA("-sf",		"*sunFunctionKeys", XrmoptionNoArg,	"on"),
DATA("+sf",		"*sunFunctionKeys", XrmoptionNoArg,	"off"),
DATA("-sh",		"*scaleHeight", XrmoptionSepArg,	NULL),
DATA("-si",		"*scrollTtyOutput", XrmoptionNoArg,	"off"),
DATA("+si",		"*scrollTtyOutput", XrmoptionNoArg,	"on"),
DATA("-sk",		"*scrollKey",	XrmoptionNoArg,		"on"),
DATA("+sk",		"*scrollKey",	XrmoptionNoArg,		"off"),
DATA("-sl",		"*saveLines",	XrmoptionSepArg,	NULL),
#if OPT_SUNPC_KBD
DATA("-sp",		"*sunKeyboard", XrmoptionNoArg,		"on"),
DATA("+sp",		"*sunKeyboard", XrmoptionNoArg,		"off"),
#endif
#if OPT_TEK4014
DATA("-t",		"*tekStartup",	XrmoptionNoArg,		"on"),
DATA("+t",		"*tekStartup",	XrmoptionNoArg,		"off"),
#endif
DATA("-ti",		"*decTerminalID",XrmoptionSepArg,	NULL),
DATA("-tm",		"*ttyModes",	XrmoptionSepArg,	NULL),
DATA("-tn",		"*termName",	XrmoptionSepArg,	NULL),
#if OPT_WIDE_CHARS
DATA("-u8",		"*utf8",	XrmoptionNoArg,		"2"),
DATA("+u8",		"*utf8",	XrmoptionNoArg,		"0"),
#endif
#if OPT_LUIT_PROG
DATA("-lc",		"*locale",	XrmoptionNoArg,		"on"),
DATA("+lc",		"*locale",	XrmoptionNoArg,		"off"),
DATA("-lcc",		"*localeFilter",XrmoptionSepArg,	NULL),
DATA("-en",		"*locale",	XrmoptionSepArg,	NULL),
#endif
DATA("-uc",		"*cursorUnderLine", XrmoptionNoArg,	"on"),
DATA("+uc",		"*cursorUnderLine", XrmoptionNoArg,	"off"),
DATA("-ulc",		"*colorULMode",	XrmoptionNoArg,		"off"),
DATA("+ulc",		"*colorULMode",	XrmoptionNoArg,		"on"),
DATA("-ulit",       	"*italicULMode", XrmoptionNoArg,        "off"),
DATA("+ulit",       	"*italicULMode", XrmoptionNoArg,        "on"),
DATA("-ut",		"*utmpInhibit",	XrmoptionNoArg,		"on"),
DATA("+ut",		"*utmpInhibit",	XrmoptionNoArg,		"off"),
DATA("-im",		"*useInsertMode", XrmoptionNoArg,	"on"),
DATA("+im",		"*useInsertMode", XrmoptionNoArg,	"off"),
DATA("-vb",		"*visualBell",	XrmoptionNoArg,		"on"),
DATA("+vb",		"*visualBell",	XrmoptionNoArg,		"off"),
DATA("-pob",		"*popOnBell",	XrmoptionNoArg,		"on"),
DATA("+pob",		"*popOnBell",	XrmoptionNoArg,		"off"),
#if OPT_WIDE_CHARS
DATA("-wc",		"*wideChars",	XrmoptionNoArg,		"on"),
DATA("+wc",		"*wideChars",	XrmoptionNoArg,		"off"),
DATA("-mk_width",	"*mkWidth",	XrmoptionNoArg,		"on"),
DATA("+mk_width",	"*mkWidth",	XrmoptionNoArg,		"off"),
DATA("-cjk_width",	"*cjkWidth",	XrmoptionNoArg,		"on"),
DATA("+cjk_width",	"*cjkWidth",	XrmoptionNoArg,		"off"),
#endif
DATA("-wf",		"*waitForMap",	XrmoptionNoArg,		"on"),
DATA("+wf",		"*waitForMap",	XrmoptionNoArg,		"off"),
#if OPT_ZICONBEEP
DATA("-ziconbeep",	"*zIconBeep",	XrmoptionSepArg,	NULL),
#endif
#if OPT_SAME_NAME
DATA("-samename",	"*sameName",	XrmoptionNoArg,		"on"),
DATA("+samename",	"*sameName",	XrmoptionNoArg,		"off"),
#endif
#if OPT_SESSION_MGT
DATA("-sm",		"*sessionMgt",	XrmoptionNoArg,		"on"),
DATA("+sm",		"*sessionMgt",	XrmoptionNoArg,		"off"),
#endif
#if OPT_TOOLBAR
DATA("-tb",		"*"XtNtoolBar,	XrmoptionNoArg,		"on"),
DATA("+tb",		"*"XtNtoolBar,	XrmoptionNoArg,		"off"),
#endif
#if OPT_MAXIMIZE
DATA("-maximized",	"*maximized",	XrmoptionNoArg,		"on"),
DATA("+maximized",	"*maximized",	XrmoptionNoArg,		"off"),
DATA("-fullscreen",	"*fullscreen",	XrmoptionNoArg,		"on"),
DATA("+fullscreen",	"*fullscreen",	XrmoptionNoArg,		"off"),
#endif
/* options that we process ourselves */
DATA("-help",		NULL,		XrmoptionSkipNArgs,	NULL),
DATA("-version",	NULL,		XrmoptionSkipNArgs,	NULL),
DATA("-baudrate",	NULL,		XrmoptionSkipArg,	NULL),
DATA("-class",		NULL,		XrmoptionSkipArg,	NULL),
DATA("-e",		NULL,		XrmoptionSkipLine,	NULL),
DATA("-into",		NULL,		XrmoptionSkipArg,	NULL),
/* bogus old compatibility stuff for which there are
   standard XtOpenApplication options now */
DATA("%",		"*tekGeometry",	XrmoptionStickyArg,	NULL),
DATA("#",		".iconGeometry",XrmoptionStickyArg,	NULL),
DATA("-T",		".title",	XrmoptionSepArg,	NULL),
DATA("-n",		"*iconName",	XrmoptionSepArg,	NULL),
DATA("-r",		"*reverseVideo",XrmoptionNoArg,		"on"),
DATA("+r",		"*reverseVideo",XrmoptionNoArg,		"off"),
DATA("-rv",		"*reverseVideo",XrmoptionNoArg,		"on"),
DATA("+rv",		"*reverseVideo",XrmoptionNoArg,		"off"),
DATA("-w",		".borderWidth", XrmoptionSepArg,	NULL),
#undef DATA
};

static OptionHelp xtermOptions[] = {
{ "-version",              "print the version number" },
{ "-help",                 "print out this message" },
{ "-display displayname",  "X server to contact" },
{ "-geometry geom",        "size (in characters) and position" },
{ "-/+rv",                 "turn on/off reverse video" },
{ "-bg color",             "background color" },
{ "-fg color",             "foreground color" },
{ "-bd color",             "border color" },
{ "-bw number",            "border width in pixels" },
{ "-fn fontname",          "normal text font" },
{ "-fb fontname",          "bold text font" },
{ "-/+fbb",                "turn on/off normal/bold font comparison inhibit"},
{ "-/+fbx",                "turn off/on linedrawing characters"},
#if OPT_RENDERFONT
{ "-fa pattern",           "FreeType font-selection pattern" },
{ "-fd pattern",           "FreeType Doublesize font-selection pattern" },
{ "-fs size",              "FreeType font-size" },
#endif
#if OPT_WIDE_CHARS
{ "-fw fontname",          "doublewidth text font" },
{ "-fwb fontname",         "doublewidth bold text font" },
#endif
#if OPT_INPUT_METHOD
{ "-fx fontname",          "XIM fontset" },
#endif
{ "-iconic",               "start iconic" },
{ "-name string",          "client instance, icon, and title strings" },
{ "-baudrate rate",        "set line-speed (default 38400)" },
{ "-class string",         "class string (XTerm)" },
{ "-title string",         "title string" },
{ "-xrm resourcestring",   "additional resource specifications" },
{ "-/+132",                "turn on/off 80/132 column switching" },
{ "-/+ah",                 "turn on/off always highlight" },
#ifndef NO_ACTIVE_ICON
{ "-/+ai",                 "turn off/on active icon" },
{ "-fi fontname",          "icon font for active icon" },
#endif /* NO_ACTIVE_ICON */
{ "-b number",             "internal border in pixels" },
{ "-/+bc",                 "turn on/off text cursor blinking" },
{ "-bcf milliseconds",     "time text cursor is off when blinking"},
{ "-bcn milliseconds",     "time text cursor is on when blinking"},
{ "-/+bdc",                "turn off/on display of bold as color"},
{ "-/+cb",                 "turn on/off cut-to-beginning-of-line inhibit" },
{ "-cc classrange",        "specify additional character classes" },
{ "-/+cm",                 "turn off/on ANSI color mode" },
{ "-/+cn",                 "turn on/off cut newline inhibit" },
{ "-cr color",             "text cursor color" },
{ "-/+cu",                 "turn on/off curses emulation" },
{ "-/+dc",                 "turn off/on dynamic color selection" },
#if OPT_HIGHLIGHT_COLOR
{ "-/+hm",                 "turn on/off selection-color override" },
{ "-selbg color",          "selection background color" },
{ "-selfg color",          "selection foreground color" },
/* -hc is deprecated, not shown in help message */
#endif
#if OPT_HP_FUNC_KEYS
{ "-/+hf",                 "turn on/off HP Function Key escape codes" },
#endif
{ "-/+hold",               "turn on/off logic that retains window after exit" },
#if OPT_INITIAL_ERASE
{ "-/+ie",                 "turn on/off initialization of 'erase' from pty" },
#endif
{ "-/+im",                 "use insert mode for TERMCAP" },
{ "-/+j",                  "turn on/off jump scroll" },
#if OPT_C1_PRINT
{ "-/+k8",                 "turn on/off C1-printable classification"},
#endif
{ "-kt keyboardtype",      "set keyboard type:" KEYBOARD_TYPES },
#ifdef ALLOWLOGGING
{ "-/+l",                  "turn on/off logging" },
{ "-lf filename",          "logging filename (use '-' for standard out)" },
#else
{ "-/+l",                  "turn on/off logging (not supported)" },
{ "-lf filename",          "logging filename (not supported)" },
#endif
{ "-/+ls",                 "turn on/off login shell" },
{ "-/+mb",                 "turn on/off margin bell" },
{ "-mc milliseconds",      "multiclick time in milliseconds" },
{ "-/+mesg",               "forbid/allow messages" },
{ "-ms color",             "pointer color" },
{ "-nb number",            "margin bell in characters from right end" },
{ "-/+nul",                "turn off/on display of underlining" },
{ "-/+aw",                 "turn on/off auto wraparound" },
{ "-/+pc",                 "turn on/off PC-style bold colors" },
{ "-/+rw",                 "turn on/off reverse wraparound" },
{ "-/+s",                  "turn on/off multiscroll" },
{ "-/+sb",                 "turn on/off scrollbar" },
#if OPT_REPORT_CCLASS
{"-report-charclass",      "report \"charClass\" after initialization"},
#endif
#if OPT_REPORT_COLORS
{ "-report-colors",        "report colors as they are allocated" },
#endif
#if OPT_REPORT_FONTS
{ "-report-fonts",         "report fonts as loaded to stdout" },
#endif
#ifdef SCROLLBAR_RIGHT
{ "-rightbar",             "force scrollbar right (default left)" },
{ "-leftbar",              "force scrollbar left" },
#endif
{ "-/+rvc",                "turn off/on display of reverse as color" },
{ "-/+sf",                 "turn on/off Sun Function Key escape codes" },
{ "-sh number",            "scale line-height values by the given number" },
{ "-/+si",                 "turn on/off scroll-on-tty-output inhibit" },
{ "-/+sk",                 "turn on/off scroll-on-keypress" },
{ "-sl number",            "number of scrolled lines to save" },
#if OPT_SUNPC_KBD
{ "-/+sp",                 "turn on/off Sun/PC Function/Keypad mapping" },
#endif
#if OPT_TEK4014
{ "-/+t",                  "turn on/off Tek emulation window" },
#endif
#if OPT_TOOLBAR
{ "-/+tb",                 "turn on/off toolbar" },
#endif
{ "-ti termid",            "terminal identifier" },
{ "-tm string",            "terminal mode keywords and characters" },
{ "-tn name",              "TERM environment variable name" },
#if OPT_WIDE_CHARS
{ "-/+u8",                 "turn on/off UTF-8 mode (implies wide-characters)" },
#endif
#if OPT_LUIT_PROG
{ "-/+lc",                 "turn on/off locale mode using luit" },
{ "-lcc path",             "filename of locale converter (" DEFLOCALEFILTER ")" },
/* -en is deprecated, not shown in help message */
#endif
{ "-/+uc",                 "turn on/off underline cursor" },
{ "-/+ulc",                "turn off/on display of underline as color" },
{ "-/+ulit",               "turn off/on display of underline as italics" },
#ifdef HAVE_UTMP
{ "-/+ut",                 "turn on/off utmp support" },
#else
{ "-/+ut",                 "turn on/off utmp support (not available)" },
#endif
{ "-/+vb",                 "turn on/off visual bell" },
{ "-/+pob",                "turn on/off pop on bell" },
#if OPT_WIDE_ATTRS && OPT_ISO_COLORS
{ "-/+itc",                "turn off/on display of italic as color"},
#endif
#if OPT_WIDE_CHARS
{ "-/+wc",                 "turn on/off wide-character mode" },
{ "-/+mk_width",           "turn on/off simple width convention" },
{ "-/+cjk_width",          "turn on/off legacy CJK width convention" },
#endif
{ "-/+wf",                 "turn on/off wait for map before command exec" },
{ "-e command args ...",   "command to execute" },
#if OPT_TEK4014
{ "%geom",                 "Tek window geometry" },
#endif
{ "#geom",                 "icon window geometry" },
{ "-T string",             "title name for window" },
{ "-n string",             "icon name for window" },
#if defined(TIOCCONS) || defined(SRIOCSREDIR)
{ "-C",                    "intercept console messages" },
#else
{ "-C",                    "intercept console messages (not supported)" },
#endif
{ "-Sccn",                 "slave mode on \"ttycc\", file descriptor \"n\"" },
{ "-into windowId",        "use the window id given to -into as the parent window rather than the default root window" },
#if OPT_ZICONBEEP
{ "-ziconbeep percent",    "beep and flag icon of window having hidden output" },
#endif
#if OPT_SAME_NAME
{ "-/+samename",           "turn on/off the no-flicker option for title and icon name" },
#endif
#if OPT_SESSION_MGT
{ "-/+sm",                 "turn on/off the session-management support" },
#endif
#if OPT_MAXIMIZE
{"-/+maximized",           "turn on/off maxmize on startup" },
{"-/+fullscreen",          "turn on/off fullscreen on startup" },
#endif
{ NULL, NULL }};
/* *INDENT-ON* */

static const char *const message[] =
{
    "Fonts should be fixed width and, if both normal and bold are specified, should",
    "have the same size.  If only a normal font is specified, it will be used for",
    "both normal and bold text (by doing overstriking).  The -e option, if given,",
    "must appear at the end of the command line, otherwise the user's default shell",
    "will be started.  Options that start with a plus sign (+) restore the default.",
    NULL};

/*
 * Decode a key-definition.  This combines the termcap and ttyModes, for
 * comparison.  Note that octal escapes in ttyModes are done by the normal
 * resource translation.  Also, ttyModes allows '^-' as a synonym for disabled.
 */
static int
decode_keyvalue(char **ptr, int termcap)
{
    char *string = *ptr;
    int value = -1;

    TRACE(("decode_keyvalue '%s'\n", string));
    if (*string == '^') {
	switch (*++string) {
	case '?':
	    value = A2E(ANSI_DEL);
	    break;
	case '-':
	    if (!termcap) {
		errno = 0;
#if defined(_POSIX_VDISABLE) && defined(HAVE_UNISTD_H)
		value = _POSIX_VDISABLE;
#endif
#if defined(_PC_VDISABLE)
		if (value == -1) {
		    value = (int) fpathconf(0, _PC_VDISABLE);
		    if (value == -1) {
			if (errno != 0)
			    break;	/* skip this (error) */
			value = 0377;
		    }
		}
#elif defined(VDISABLE)
		if (value == -1)
		    value = VDISABLE;
#endif
		break;
	    }
	    /* FALLTHRU */
	default:
	    value = CONTROL(*string);
	    break;
	}
	++string;
    } else if (termcap && (*string == '\\')) {
	char *s = (string + 1);
	char *d;
	int temp = (int) strtol(s, &d, 8);
	if (PartS2L(s, d) && temp > 0) {
	    value = temp;
	    string = d;
	}
    } else {
	value = CharOf(*string);
	++string;
    }
    *ptr = string;
    TRACE(("...decode_keyvalue %#x\n", value));
    return value;
}

static int
matchArg(XrmOptionDescRec * table, const char *param)
{
    int result = -1;
    int n;
    int ch;

    for (n = 0; (ch = table->option[n]) != '\0'; ++n) {
	if (param[n] == ch) {
	    result = n;
	} else {
	    if (param[n] != '\0')
		result = -1;
	    break;
	}
    }

    return result;
}

/* return the number of argv[] entries which constitute arguments of option */
static int
countArg(XrmOptionDescRec * item)
{
    int result = 0;

    switch (item->argKind) {
    case XrmoptionNoArg:
	/* FALLTHRU */
    case XrmoptionIsArg:
	/* FALLTHRU */
    case XrmoptionStickyArg:
	break;
    case XrmoptionSepArg:
	/* FALLTHRU */
    case XrmoptionResArg:
	/* FALLTHRU */
    case XrmoptionSkipArg:
	result = 1;
	break;
    case XrmoptionSkipLine:
	break;
    case XrmoptionSkipNArgs:
	result = (int) (long) (item->value);
	break;
    }
    return result;
}

#define isOption(string) (Boolean)((string)[0] == '-' || (string)[0] == '+')

/*
 * Parse the argument list, more/less as XtInitialize, etc., would do, so we
 * can find our own "-help" and "-version" options reliably.  Improve on just
 * doing that, by detecting ambiguous options (things that happen to match the
 * abbreviated option we are examining), and making it smart enough to handle
 * "-d" as an abbreviation for "-display".  Doing this requires checking the
 * standard table (something that the X libraries should do).
 */
static XrmOptionDescRec *
parseArg(int *num, char **argv, char **valuep)
{
    /* table adapted from XtInitialize, used here to improve abbreviations */
    /* *INDENT-OFF* */
#define DATA(option,kind) { (char *) option, NULL, kind, (XtPointer) NULL }
    static XrmOptionDescRec opTable[] = {
	DATA("+synchronous",	   XrmoptionNoArg),
	DATA("-background",	   XrmoptionSepArg),
	DATA("-bd",		   XrmoptionSepArg),
	DATA("-bg",		   XrmoptionSepArg),
	DATA("-bordercolor",	   XrmoptionSepArg),
	DATA("-borderwidth",	   XrmoptionSepArg),
	DATA("-bw",		   XrmoptionSepArg),
	DATA("-display",	   XrmoptionSepArg),
	DATA("-fg",		   XrmoptionSepArg),
	DATA("-fn",		   XrmoptionSepArg),
	DATA("-font",		   XrmoptionSepArg),
	DATA("-foreground",	   XrmoptionSepArg),
	DATA("-iconic",		   XrmoptionNoArg),
	DATA("-name",		   XrmoptionSepArg),
	DATA("-reverse",	   XrmoptionNoArg),
	DATA("-selectionTimeout",  XrmoptionSepArg),
	DATA("-synchronous",	   XrmoptionNoArg),
	DATA("-title",		   XrmoptionSepArg),
	DATA("-xnllanguage",	   XrmoptionSepArg),
	DATA("-xrm",		   XrmoptionResArg),
	DATA("-xtsessionID",	   XrmoptionSepArg),
	/* These xterm options are processed after XtOpenApplication */
#if defined(TIOCCONS) || defined(SRIOCSREDIR)
	DATA("-C",		   XrmoptionNoArg),
#endif /* TIOCCONS */
	DATA("-S",		   XrmoptionStickyArg),
	DATA("-D",		   XrmoptionNoArg),
    };
#undef DATA
    /* *INDENT-ON* */

    XrmOptionDescRec *result = 0;
    Cardinal inlist;
    Cardinal limit = XtNumber(optionDescList) + XtNumber(opTable);
    int atbest = -1;
    int best = -1;
    int test;
    Boolean exact = False;
    int ambiguous1 = -1;
    int ambiguous2 = -1;
    char *option;
    char *value;

#define ITEM(n) ((Cardinal)(n) < XtNumber(optionDescList) \
		 ? &optionDescList[n] \
		 : &opTable[(Cardinal)(n) - XtNumber(optionDescList)])

    if ((option = argv[*num]) != 0) {
	Boolean need_value;
	Boolean have_value = False;

	TRACE(("parseArg %s\n", option));
	if ((value = argv[(*num) + 1]) != 0) {
	    have_value = (Boolean) !isOption(value);
	}
	for (inlist = 0; inlist < limit; ++inlist) {
	    XrmOptionDescRec *check = ITEM(inlist);

	    test = matchArg(check, option);
	    if (test < 0)
		continue;

	    /* check for exact match */
	    if ((test + 1) == (int) strlen(check->option)) {
		if (check->argKind == XrmoptionStickyArg) {
		    if (strlen(option) > strlen(check->option)) {
			exact = True;
			atbest = (int) inlist;
			break;
		    }
		} else if ((test + 1) == (int) strlen(option)) {
		    exact = True;
		    atbest = (int) inlist;
		    break;
		}
	    }

	    need_value = (Boolean) (test > 0 && countArg(check) > 0);

	    if (need_value && value != 0) {
		;
	    } else if (need_value ^ have_value) {
		TRACE(("...skipping, need %d vs have %d\n", need_value, have_value));
		continue;
	    }

	    /* special-case for our own options - always allow abbreviation */
	    if (test > 0
		&& ITEM(inlist)->argKind >= XrmoptionSkipArg) {
		atbest = (int) inlist;
		if (ITEM(inlist)->argKind == XrmoptionSkipNArgs) {
		    /* in particular, silence a warning about ambiguity */
		    exact = 1;
		}
		break;
	    }
	    if (test > best) {
		best = test;
		atbest = (int) inlist;
	    } else if (test == best) {
		if (atbest >= 0) {
		    if (atbest > 0) {
			ambiguous1 = (int) inlist;
			ambiguous2 = (int) atbest;
		    }
		    atbest = -1;
		}
	    }
	}
    }

    *valuep = 0;
    if (atbest >= 0) {
	result = ITEM(atbest);
	if (!exact) {
	    if (ambiguous1 >= 0 && ambiguous2 >= 0) {
		xtermWarning("ambiguous option \"%s\" vs \"%s\"\n",
			     ITEM(ambiguous1)->option,
			     ITEM(ambiguous2)->option);
	    } else if (strlen(option) > strlen(result->option)) {
		result = 0;
	    }
	}
	if (result != 0) {
	    TRACE(("...result %s\n", result->option));
	    /* expand abbreviations */
	    if (result->argKind != XrmoptionStickyArg) {
		if (strcmp(argv[*num], result->option)) {
		    argv[*num] = x_strdup(result->option);
		}
	    }

	    /* adjust (*num) to skip option value */
	    (*num) += countArg(result);
	    TRACE(("...next %s\n", NonNull(argv[*num])));
	    if (result->argKind == XrmoptionSkipArg) {
		*valuep = argv[*num];
		TRACE(("...parameter %s\n", NonNull(*valuep)));
	    }
	}
    }
#undef ITEM
    return result;
}

static void
Syntax(char *badOption)
{
    OptionHelp *opt;
    OptionHelp *list = sortedOpts(xtermOptions, optionDescList, XtNumber(optionDescList));
    int col;

    TRACE(("Syntax error at %s\n", badOption));
    xtermWarning("bad command line option \"%s\"\r\n\n", badOption);

    fprintf(stderr, "usage:  %s", ProgramName);
    col = 8 + (int) strlen(ProgramName);
    for (opt = list; opt->opt; opt++) {
	int len = 3 + (int) strlen(opt->opt);	/* space [ string ] */
	if (col + len > 79) {
	    fprintf(stderr, "\r\n   ");		/* 3 spaces */
	    col = 3;
	}
	fprintf(stderr, " [%s]", opt->opt);
	col += len;
    }

    fprintf(stderr, "\r\n\nType %s -help for a full description.\r\n\n",
	    ProgramName);
    exit(1);
}

static void
Version(void)
{
    printf("%s\n", xtermVersion());
    fflush(stdout);
}

static void
Help(void)
{
    OptionHelp *opt;
    OptionHelp *list = sortedOpts(xtermOptions, optionDescList, XtNumber(optionDescList));
    const char *const *cpp;

    printf("%s usage:\n    %s [-options ...] [-e command args]\n\n",
	   xtermVersion(), ProgramName);
    printf("where options include:\n");
    for (opt = list; opt->opt; opt++) {
	printf("    %-28s %s\n", opt->opt, opt->desc);
    }

    putchar('\n');
    for (cpp = message; *cpp; cpp++)
	puts(*cpp);
    putchar('\n');
    fflush(stdout);
}

#if defined(TIOCCONS) || defined(SRIOCSREDIR)
/* ARGSUSED */
static Boolean
ConvertConsoleSelection(Widget w GCC_UNUSED,
			Atom *selection GCC_UNUSED,
			Atom *target GCC_UNUSED,
			Atom *type GCC_UNUSED,
			XtPointer *value GCC_UNUSED,
			unsigned long *length GCC_UNUSED,
			int *format GCC_UNUSED)
{
    /* we don't save console output, so can't offer it */
    return False;
}
#endif /* TIOCCONS */

/*
 * DeleteWindow(): Action proc to implement ICCCM delete_window.
 */
/* ARGSUSED */
static void
DeleteWindow(Widget w,
	     XEvent *event GCC_UNUSED,
	     String *params GCC_UNUSED,
	     Cardinal *num_params GCC_UNUSED)
{
#if OPT_TEK4014
    if (w == toplevel) {
	if (TEK4014_SHOWN(term))
	    hide_vt_window();
	else
	    do_hangup(w, (XtPointer) 0, (XtPointer) 0);
    } else if (TScreenOf(term)->Vshow)
	hide_tek_window();
    else
#endif
	do_hangup(w, (XtPointer) 0, (XtPointer) 0);
}

/* ARGSUSED */
static void
KeyboardMapping(Widget w GCC_UNUSED,
		XEvent *event,
		String *params GCC_UNUSED,
		Cardinal *num_params GCC_UNUSED)
{
    switch (event->type) {
    case MappingNotify:
	XRefreshKeyboardMapping(&event->xmapping);
	break;
    }
}

static XtActionsRec actionProcs[] =
{
    {"DeleteWindow", DeleteWindow},
    {"KeyboardMapping", KeyboardMapping},
};

/*
 * Some platforms use names such as /dev/tty01, others /dev/pts/1.  Parse off
 * the "tty01" or "pts/1" portion, and return that for use as an identifier for
 * utmp.
 */
static char *
my_pty_name(char *device)
{
    size_t len = strlen(device);
    Bool name = False;

    while (len != 0) {
	int ch = device[len - 1];
	if (isdigit(ch)) {
	    len--;
	} else if (ch == '/') {
	    if (name)
		break;
	    len--;
	} else if (isalpha(ch)) {
	    name = True;
	    len--;
	} else {
	    break;
	}
    }
    TRACE(("my_pty_name(%s) -> '%s'\n", device, device + len));
    return device + len;
}

/*
 * If the name contains a '/', it is a "pts/1" case.  Otherwise, return the
 * last few characters for a utmp identifier.
 */
static char *
my_pty_id(char *device)
{
    char *name = my_pty_name(device);
    char *leaf = x_basename(name);

    if (name == leaf) {		/* no '/' in the name */
	int len = (int) strlen(leaf);
	if (PTYCHARLEN < len)
	    leaf = leaf + (len - PTYCHARLEN);
    }
    TRACE(("my_pty_id  (%s) -> '%s'\n", device, leaf));
    return leaf;
}

/*
 * Set the tty/pty identifier
 */
static void
set_pty_id(char *device, char *id)
{
    char *name = my_pty_name(device);
    char *leaf = x_basename(name);

    if (name == leaf) {
	strcpy(my_pty_id(device), id);
    } else {
	strcpy(leaf, id);
    }
    TRACE(("set_pty_id(%s) -> '%s'\n", id, device));
}

/*
 * The original -S option accepts two characters to identify the pty, and a
 * file-descriptor (assumed to be nonzero).  That is not general enough, so we
 * check first if the option contains a '/' to delimit the two fields, and if
 * not, fall-thru to the original logic.
 */
static Bool
ParseSccn(char *option)
{
    char *leaf = x_basename(option);
    Bool code = False;

    passedPty = x_strdup(option);
    if (leaf != option) {
	if (leaf - option > 0
	    && isdigit(CharOf(*leaf))
	    && sscanf(leaf, "%d", &am_slave) == 1) {
	    size_t len = (size_t) (leaf - option - 1);
	    /*
	     * If we have a slash, we only care about the part after the slash,
	     * which is a file-descriptor.  The part before the slash can be
	     * the /dev/pts/XXX value, but since we do not need to reopen it,
	     * it is useful mainly for display in a "ps -ef".
	     */
	    passedPty[len] = 0;
	    code = True;
	}
    } else {
	code = (sscanf(option, "%c%c%d",
		       passedPty, passedPty + 1, &am_slave) == 3);
	passedPty[2] = '\0';
    }
    TRACE(("ParseSccn(%s) = '%s' %d (%s)\n", option,
	   passedPty, am_slave, code ? "OK" : "ERR"));
    return code;
}

#if defined(USE_SYSV_UTMP) && !defined(USE_UTEMPTER)
/*
 * From "man utmp":
 * xterm and other terminal emulators directly create a USER_PROCESS record
 * and generate the ut_id by using the last two letters of /dev/ttyp%c or by
 * using p%d for /dev/pts/%d.  If they find a DEAD_PROCESS for this id, they
 * recycle it, otherwise they create a new entry.  If they can, they will mark
 * it as DEAD_PROCESS on exiting and it is advised that they null ut_line,
 * ut_time, ut_user and ut_host as well.
 *
 * Generally ut_id allows no more than 3 characters (plus null), even if the
 * pty implementation allows more than 3 digits.
 */
static char *
my_utmp_id(char *device)
{
    typedef struct UTMP_STR UTMP_STRUCT;
#define	UTIDSIZE	(sizeof(((UTMP_STRUCT *)NULL)->ut_id))
    static char result[UTIDSIZE + 1];

#if defined(__SCO__) || defined(__UNIXWARE__)
    /*
     * Legend does not support old-style pty's, has no related compatibility
     * issues, and can use the available space in ut_id differently from the
     * default convention.
     *
     * This scheme is intended to avoid conflicts both with other users of
     * utmpx as well as between multiple xterms.  First, Legend uses all of the
     * characters of ut_id, and adds no terminating NUL is required (the
     * default scheme may add a trailing NUL).  Second, all xterm entries will
     * start with the letter 'x' followed by three digits, which will be the
     * last three digits of the device name, regardless of the format of the
     * device name, with leading 0's added where necessary.  For instance, an
     * xterm on /dev/pts/3 will have a ut_id of x003; an xterm on /dev/pts123
     * will have a ut_id of x123.  Under the other convention, /dev/pts/3 would
     * have a ut_id of p3 and /dev/pts123 would have a ut_id of p123.
     */
    int len, n;

    len = strlen(device);
    n = UTIDSIZE;
    result[n] = '\0';
    while ((n > 0) && (len > 0) && isdigit(device[len - 1]))
	result[--n] = device[--len];
    while (n > 0)
	result[--n] = '0';
    result[0] = 'x';
#else
    char *name = my_pty_name(device);
    char *leaf = x_basename(name);
    size_t len = strlen(leaf);

    if ((UTIDSIZE - 1) < len)
	leaf = leaf + (len - (UTIDSIZE - 1));
    sprintf(result, "p%s", leaf);
#endif

    TRACE(("my_utmp_id (%s) -> '%s'\n", device, result));
    return result;
}
#endif /* USE_SYSV_UTMP */

#ifdef USE_POSIX_SIGNALS

typedef void (*sigfunc) (int);

/* make sure we sure we ignore SIGCHLD for the cases parent
   has just been stopped and not actually killed */

static sigfunc
posix_signal(int signo, sigfunc func)
{
    struct sigaction act, oact;

    act.sa_handler = func;
    sigemptyset(&act.sa_mask);
#ifdef SA_RESTART
    act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
#else
    act.sa_flags = SA_NOCLDSTOP;
#endif
    if (sigaction(signo, &act, &oact) < 0)
	return (SIG_ERR);
    return (oact.sa_handler);
}

#endif /* USE_POSIX_SIGNALS */

#if defined(DISABLE_SETUID) || defined(USE_UTMP_SETGID)
static void
disableSetUid(void)
{
    TRACE(("process %d disableSetUid\n", (int) getpid()));
    if (setuid(save_ruid) == -1) {
	xtermWarning("unable to reset uid\n");
	exit(1);
    }
    TRACE_IDS;
}
#else
#define disableSetUid()		/* nothing */
#endif /* DISABLE_SETUID */

#if defined(DISABLE_SETGID) || defined(USE_UTMP_SETGID)
static void
disableSetGid(void)
{
    TRACE(("process %d disableSetGid\n", (int) getpid()));
    if (setegid(save_rgid) == -1) {
	xtermWarning("unable to reset effective gid\n");
	exit(1);
    }
    TRACE_IDS;
}
#else
#define disableSetGid()		/* nothing */
#endif /* DISABLE_SETGID */

#if defined(HAVE_POSIX_SAVED_IDS)
#if (!defined(USE_UTEMPTER) || !defined(DISABLE_SETGID))
static void
setEffectiveGroup(gid_t group)
{
    TRACE(("process %d setEffectiveGroup(%d)\n", (int) getpid(), (int) group));
    if (setegid(group) == -1) {
#ifdef __MVS__
	if (!(errno == EMVSERR))	/* could happen if _BPX_SHAREAS=REUSE */
#endif
	{
	    xtermPerror("setegid(%d)", (int) group);
	}
    }
    TRACE_IDS;
}
#endif

#if !defined(USE_UTMP_SETGID) && (!defined(USE_UTEMPTER) || !defined(DISABLE_SETUID))
static void
setEffectiveUser(uid_t user)
{
    TRACE(("process %d setEffectiveUser(%d)\n", (int) getpid(), (int) user));
    if (seteuid(user) == -1) {
#ifdef __MVS__
	if (!(errno == EMVSERR))
#endif
	{
	    xtermPerror("seteuid(%d)", (int) user);
	}
    }
    TRACE_IDS;
}
#endif
#endif /* HAVE_POSIX_SAVED_IDS */

#if OPT_LUIT_PROG
static Boolean
complex_command(char **args)
{
    Boolean result = False;
    if (x_countargv(args) == 1) {
	char *check = xtermFindShell(args[0], False);
	if (check == 0) {
	    result = True;
	} else {
	    free(check);
	}
    }
    return result;
}
#endif

static unsigned
lookup_baudrate(const char *value)
{
    struct speed {
	unsigned given_speed;	/* values for 'ospeed' */
	unsigned actual_speed;	/* the actual speed */
    };

#define DATA(number) { B##number, number }

    static struct speed const speeds[] =
    {
	DATA(0),
	DATA(50),
	DATA(75),
	DATA(110),
	DATA(134),
	DATA(150),
	DATA(200),
	DATA(300),
	DATA(600),
	DATA(1200),
	DATA(1800),
	DATA(2400),
	DATA(4800),
	DATA(9600),
#ifdef B19200
	DATA(19200),
#elif defined(EXTA)
	{EXTA, 19200},
#endif
#ifdef B28800
	DATA(28800),
#endif
#ifdef B38400
	DATA(38400),
#elif defined(EXTB)
	{EXTB, 38400},
#endif
#ifdef B57600
	DATA(57600),
#endif
#ifdef B76800
	DATA(76800),
#endif
#ifdef B115200
	DATA(115200),
#endif
#ifdef B153600
	DATA(153600),
#endif
#ifdef B230400
	DATA(230400),
#endif
#ifdef B307200
	DATA(307200),
#endif
#ifdef B460800
	DATA(460800),
#endif
#ifdef B500000
	DATA(500000),
#endif
#ifdef B576000
	DATA(576000),
#endif
#ifdef B921600
	DATA(921600),
#endif
#ifdef B1000000
	DATA(1000000),
#endif
#ifdef B1152000
	DATA(1152000),
#endif
#ifdef B1500000
	DATA(1500000),
#endif
#ifdef B2000000
	DATA(2000000),
#endif
#ifdef B2500000
	DATA(2500000),
#endif
#ifdef B3000000
	DATA(3000000),
#endif
#ifdef B3500000
	DATA(3500000),
#endif
#ifdef B4000000
	DATA(4000000),
#endif
    };
#undef DATA
    unsigned result = 0;
    long check;
    char *next;
    if (x_toupper(*value) == 'B')
	value++;
    if (isdigit(CharOf(*value))) {
	check = strtol(value, &next, 10);
	if (FullS2L(value, next) && (check > 0)) {
	    Cardinal n;
	    for (n = 0; n < XtNumber(speeds); ++n) {
		if (speeds[n].actual_speed == (unsigned) check) {
		    result = speeds[n].given_speed;
		    break;
		}
	    }
	}
    }
    if (result == 0) {
	fprintf(stderr, "unsupported value for baudrate: %s\n", value);
    }
    return result;
}

int
main(int argc, char *argv[]ENVP_ARG)
{
#if OPT_MAXIMIZE
#define DATA(name) { #name, es##name }
    static const FlagList tblFullscreen[] =
    {
	DATA(Always),
	DATA(Never)
    };
#undef DATA
#endif

    Widget form_top, menu_top;
    Dimension menu_high;
    TScreen *screen;
    int mode;
    char *my_class = x_strdup(DEFCLASS);
    unsigned line_speed = VAL_LINE_SPEED;
    Window winToEmbedInto = None;

    ProgramName = argv[0];

#ifdef HAVE_POSIX_SAVED_IDS
    save_euid = geteuid();
    save_egid = getegid();
#endif

    save_ruid = getuid();
    save_rgid = getgid();

#if defined(DISABLE_SETUID) || defined(DISABLE_SETGID)
#if defined(DISABLE_SETUID)
    disableSetUid();
#endif
#if defined(DISABLE_SETGID)
    disableSetGid();
#endif
    TRACE_IDS;
#endif

    /* extra length in case longer tty name like /dev/ttyq255 */
    ttydev = TypeMallocN(char, sizeof(TTYDEV) + 80);
#ifdef USE_PTY_DEVICE
    ptydev = TypeMallocN(char, sizeof(PTYDEV) + 80);
    if (!ttydev || !ptydev)
#else
    if (!ttydev)
#endif
    {
	xtermWarning("unable to allocate memory for ttydev or ptydev\n");
	exit(1);
    }
    strcpy(ttydev, TTYDEV);
#ifdef USE_PTY_DEVICE
    strcpy(ptydev, PTYDEV);
#endif

#if defined(USE_UTMP_SETGID)
    get_pty(NULL, NULL);
    disableSetUid();
    disableSetGid();
    TRACE_IDS;
#define get_pty(pty, from) really_get_pty(pty, from)
#endif

    /* Do these first, since we may not be able to open the display */
    TRACE_OPTS(xtermOptions, optionDescList, XtNumber(optionDescList));
    TRACE_ARGV("Before XtOpenApplication", argv);
    if (argc > 1) {
	XrmOptionDescRec *option_ptr;
	char *option_value;
	int n;
	Bool quit = False;

	for (n = 1; n < argc; n++) {
	    if ((option_ptr = parseArg(&n, argv, &option_value)) == 0) {
		if (argv[n] == 0) {
		    break;
		} else if (isOption(argv[n])) {
		    Syntax(argv[n]);
		} else if (explicit_shname != 0) {
		    xtermWarning("Explicit shell already was %s\n", explicit_shname);
		    Syntax(argv[n]);
		}
		explicit_shname = xtermFindShell(argv[n], True);
		if (explicit_shname == 0)
		    exit(0);
		TRACE(("...explicit shell %s\n", explicit_shname));
	    } else if (!strcmp(option_ptr->option, "-e")) {
		command_to_exec = (argv + n + 1);
		if (!command_to_exec[0])
		    Syntax(argv[n]);
		break;
	    } else if (!strcmp(option_ptr->option, "-version")) {
		Version();
		quit = True;
	    } else if (!strcmp(option_ptr->option, "-help")) {
		Help();
		quit = True;
	    } else if (!strcmp(option_ptr->option, "-baudrate")) {
		if ((line_speed = lookup_baudrate(option_value)) == 0) {
		    Help();
		    quit = True;
		}
	    } else if (!strcmp(option_ptr->option, "-class")) {
		free(my_class);
		if ((my_class = x_strdup(option_value)) == 0) {
		    Help();
		    quit = True;
		}
	    } else if (!strcmp(option_ptr->option, "-into")) {
		char *endPtr;
		winToEmbedInto = (Window) strtol(option_value, &endPtr, 0);
		if (!FullS2L(option_value, endPtr)) {
		    Help();
		    quit = True;
		}
	    }
	}
	if (quit)
	    exit(0);
	/*
	 * If there is anything left unparsed, and we're not using "-e",
	 * then give up.
	 */
	if (n < argc && !command_to_exec) {
	    Syntax(argv[n]);
	}
    }

    /* This dumped core on HP-UX 9.05 with X11R5 */
#if OPT_I18N_SUPPORT
    XtSetLanguageProc(NULL, NULL, NULL);
#endif

#ifdef TERMIO_STRUCT		/* { */
    /* Initialization is done here rather than above in order
     * to prevent any assumptions about the order of the contents
     * of the various terminal structures (which may change from
     * implementation to implementation).
     */
    memset(&d_tio, 0, sizeof(d_tio));
    d_tio.c_iflag = ICRNL | IXON;
    d_tio.c_oflag = TAB3 | D_TIO_FLAGS;
    {
	Cardinal nn;

	/* fill in default-values */
	for (nn = 0; nn < XtNumber(ttyChars); ++nn) {
	    if (validTtyChar(d_tio, nn)) {
		d_tio.c_cc[ttyChars[nn].sysMode] =
		    (cc_t) ttyChars[nn].myDefault;
	    }
	}
    }
#if defined(macII) || defined(ATT) || defined(CRAY)	/* { */
    d_tio.c_cflag = line_speed | CS8 | CREAD | PARENB | HUPCL;
    d_tio.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK;
#ifdef ECHOKE
    d_tio.c_lflag |= ECHOKE | IEXTEN;
#endif
#ifdef ECHOCTL
    d_tio.c_lflag |= ECHOCTL | IEXTEN;
#endif
#ifndef USE_TERMIOS		/* { */
    d_tio.c_line = 0;
#endif /* } */
#ifdef HAS_LTCHARS		/* { */
    d_ltc.t_suspc = CSUSP;	/* t_suspc */
    d_ltc.t_dsuspc = CDSUSP;	/* t_dsuspc */
    d_ltc.t_rprntc = CRPRNT;
    d_ltc.t_flushc = CFLUSH;
    d_ltc.t_werasc = CWERASE;
    d_ltc.t_lnextc = CLNEXT;
#endif /* } HAS_LTCHARS */
#ifdef TIOCLSET			/* { */
    d_lmode = 0;
#endif /* } TIOCLSET */
#else /* }{ else !macII, ATT, CRAY */
#ifndef USE_POSIX_TERMIOS
#ifdef BAUD_0			/* { */
    d_tio.c_cflag = CS8 | CREAD | PARENB | HUPCL;
#else /* }{ !BAUD_0 */
    d_tio.c_cflag = line_speed | CS8 | CREAD | PARENB | HUPCL;
#endif /* } !BAUD_0 */
#else /* USE_POSIX_TERMIOS */
    d_tio.c_cflag = CS8 | CREAD | PARENB | HUPCL;
    cfsetispeed(&d_tio, line_speed);
    cfsetospeed(&d_tio, line_speed);
#endif
    d_tio.c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK;
#ifdef ECHOKE
    d_tio.c_lflag |= ECHOKE | IEXTEN;
#endif
#ifdef ECHOCTL
    d_tio.c_lflag |= ECHOCTL | IEXTEN;
#endif
#ifndef USE_POSIX_TERMIOS
#ifdef NTTYDISC
    d_tio.c_line = NTTYDISC;
#else
    d_tio.c_line = 0;
#endif
#endif /* USE_POSIX_TERMIOS */
#ifdef __sgi
    d_tio.c_cflag &= ~(HUPCL | PARENB);
    d_tio.c_iflag |= BRKINT | ISTRIP | IGNPAR;
#endif
#ifdef __MVS__
    d_tio.c_cflag &= ~(HUPCL | PARENB);
#endif
    {
	Cardinal nn;
	int i;

	/* try to inherit tty settings */
	for (i = 0; i <= 2; i++) {
	    TERMIO_STRUCT deftio;
	    if (ttyGetAttr(i, &deftio) == 0) {
		for (nn = 0; nn < XtNumber(ttyChars); ++nn) {
		    if (validTtyChar(d_tio, nn)) {
			d_tio.c_cc[ttyChars[nn].sysMode] =
			    deftio.c_cc[ttyChars[nn].sysMode];
		    }
		}
		break;
	    }
	}
    }
#if defined(USE_TERMIOS) || defined(USE_POSIX_TERMIOS)	/* { */
    d_tio.c_cc[VMIN] = 1;
    d_tio.c_cc[VTIME] = 0;
#endif /* } */
#ifdef HAS_LTCHARS		/* { */
    d_ltc.t_suspc = CharOf('\000');	/* t_suspc */
    d_ltc.t_dsuspc = CharOf('\000');	/* t_dsuspc */
    d_ltc.t_rprntc = CharOf('\377');	/* reserved... */
    d_ltc.t_flushc = CharOf('\377');
    d_ltc.t_werasc = CharOf('\377');
    d_ltc.t_lnextc = CharOf('\377');
#endif /* } HAS_LTCHARS */

#ifdef TIOCLSET			/* { */
    d_lmode = 0;
#endif /* } TIOCLSET */
#endif /* } macII, ATT, CRAY */
#endif /* } TERMIO_STRUCT */

    /* Init the Toolkit. */
    {
#if defined(HAVE_POSIX_SAVED_IDS) && !defined(USE_UTMP_SETGID) && !defined(USE_UTEMPTER)
	setEffectiveGroup(save_rgid);
	setEffectiveUser(save_ruid);
	TRACE_IDS;
#endif
	toplevel = xtermOpenApplication(&app_con,
					my_class,
					optionDescList,
					XtNumber(optionDescList),
					&argc, (String *) argv,
					fallback_resources,
					sessionShellWidgetClass,
					NULL, 0);

	XtGetApplicationResources(toplevel, (XtPointer) &resource,
				  application_resources,
				  XtNumber(application_resources), NULL, 0);
	TRACE_XRES();
#if OPT_MAXIMIZE
	resource.fullscreen = extendedBoolean(resource.fullscreen_s,
					      tblFullscreen,
					      XtNumber(tblFullscreen));
#endif
	VTInitTranslations();
#if OPT_PTY_HANDSHAKE
	resource.wait_for_map0 = resource.wait_for_map;
#endif

#if defined(HAVE_POSIX_SAVED_IDS) && !defined(USE_UTMP_SETGID)
#if !defined(DISABLE_SETUID) || !defined(DISABLE_SETGID)
#if !defined(DISABLE_SETUID)
	setEffectiveUser(save_euid);
#endif
#if !defined(DISABLE_SETGID)
	setEffectiveGroup(save_egid);
#endif
	TRACE_IDS;
#endif
#endif
    }

    /*
     * ICCCM delete_window.
     */
    XtAppAddActions(app_con, actionProcs, XtNumber(actionProcs));

    /*
     * fill in terminal modes
     */
    if (resource.tty_modes) {
	int n = parse_tty_modes(resource.tty_modes);
	if (n < 0) {
	    xtermWarning("bad tty modes \"%s\"\n", resource.tty_modes);
	} else if (n > 0) {
	    override_tty_modes = True;
	}
    }
    initZIconBeep();
    hold_screen = resource.hold_screen ? 1 : 0;
    if (resource.icon_geometry != NULL) {
	int scr, junk;
	int ix, iy;
	Arg args[2];

	for (scr = 0;		/* yyuucchh */
	     XtScreen(toplevel) != ScreenOfDisplay(XtDisplay(toplevel), scr);
	     scr++) ;

	args[0].name = XtNiconX;
	args[1].name = XtNiconY;
	XGeometry(XtDisplay(toplevel), scr, resource.icon_geometry, "",
		  0, 0, 0, 0, 0, &ix, &iy, &junk, &junk);
	args[0].value = (XtArgVal) ix;
	args[1].value = (XtArgVal) iy;
	XtSetValues(toplevel, args, 2);
    }

    XtSetValues(toplevel, ourTopLevelShellArgs,
		number_ourTopLevelShellArgs);

#if OPT_WIDE_CHARS
    /* seems as good a place as any */
    init_classtab();
#endif

    /* Parse the rest of the command line */
    TRACE_ARGV("After XtOpenApplication", argv);
    for (argc--, argv++; argc > 0; argc--, argv++) {
	if (!isOption(*argv)) {
#ifdef VMS
	    Syntax(*argv);
#else
	    if (argc > 1)
		Syntax(*argv);
	    continue;
#endif
	}

	TRACE(("parsing %s\n", argv[0]));
	switch (argv[0][1]) {
	case 'C':
#if defined(TIOCCONS) || defined(SRIOCSREDIR)
#ifndef __sgi
	    {
		struct stat sbuf;

		/* Must be owner and have read/write permission.
		   xdm cooperates to give the console the right user. */
		if (!stat("/dev/console", &sbuf) &&
		    (sbuf.st_uid == save_ruid) &&
		    !access("/dev/console", R_OK | W_OK)) {
		    Console = True;
		} else
		    Console = False;
	    }
#else /* __sgi */
	    Console = True;
#endif /* __sgi */
#endif /* TIOCCONS */
	    continue;
	case 'S':
	    if (!ParseSccn(*argv + 2))
		Syntax(*argv);
	    continue;
#ifdef DEBUG
	case 'D':
	    debug = True;
	    continue;
#endif /* DEBUG */
	case 'b':
	    if (strcmp(argv[0], "-baudrate"))
		Syntax(*argv);
	    argc--, argv++;
	    continue;
	case 'c':
	    if (strcmp(argv[0], "-class"))
		Syntax(*argv);
	    argc--, argv++;
	    continue;
	case 'e':
	    if (strcmp(argv[0], "-e"))
		Syntax(*argv);
	    command_to_exec = (argv + 1);
	    break;
	case 'i':
	    if (strcmp(argv[0], "-into"))
		Syntax(*argv);
	    argc--, argv++;
	    continue;

	default:
	    Syntax(*argv);
	}
	break;
    }

    SetupMenus(toplevel, &form_top, &menu_top, &menu_high);

    term = (XtermWidget) XtVaCreateManagedWidget("vt100", xtermWidgetClass,
						 form_top,
#if OPT_TOOLBAR
						 XtNmenuBar, menu_top,
						 XtNresizable, True,
						 XtNfromVert, menu_top,
						 XtNleft, XawChainLeft,
						 XtNright, XawChainRight,
						 XtNtop, XawChainTop,
						 XtNbottom, XawChainBottom,
						 XtNmenuHeight, menu_high,
#endif
						 (XtPointer) 0);
    decode_keyboard_type(term, &resource);

    screen = TScreenOf(term);
    screen->inhibit = 0;

#ifdef ALLOWLOGGING
    if (term->misc.logInhibit)
	screen->inhibit |= I_LOG;
#endif
    if (term->misc.signalInhibit)
	screen->inhibit |= I_SIGNAL;
#if OPT_TEK4014
    if (term->misc.tekInhibit)
	screen->inhibit |= I_TEK;
#endif

    /*
     * We might start by showing the tek4014 window.
     */
#if OPT_TEK4014
    if (screen->inhibit & I_TEK)
	TEK4014_ACTIVE(term) = False;

    if (TEK4014_ACTIVE(term) && !TekInit())
	SysError(ERROR_INIT);
#endif

    /*
     * Start the toolbar at this point, after the first window has been setup.
     */
#if OPT_TOOLBAR
    ShowToolbar(resource.toolBar);
#endif

    xtermOpenSession();

    /*
     * Set title and icon name if not specified
     */
    if (command_to_exec) {
	Arg args[2];

	if (!resource.title) {
	    if (command_to_exec) {
		resource.title = x_basename(command_to_exec[0]);
	    }			/* else not reached */
	}

	if (!resource.icon_name)
	    resource.icon_name = resource.title;
	XtSetArg(args[0], XtNtitle, resource.title);
	XtSetArg(args[1], XtNiconName, resource.icon_name);

	TRACE(("setting:\n\ttitle \"%s\"\n\ticon \"%s\"\n\thint \"%s\"\n\tbased on command \"%s\"\n",
	       resource.title,
	       resource.icon_name,
	       NonNull(resource.icon_hint),
	       *command_to_exec));

	XtSetValues(toplevel, args, 2);
    }
#if OPT_LUIT_PROG
    if (term->misc.callfilter) {
	char **split_filter = x_splitargs(term->misc.localefilter);
	unsigned count_split = x_countargv(split_filter);
	unsigned count_exec = x_countargv(command_to_exec);
	unsigned count_using = (unsigned) (term->misc.use_encoding ? 2 : 0);

	command_to_exec_with_luit = TypeCallocN(char *,
						  (count_split
						   + count_exec
						   + count_using
						   + 8));
	if (command_to_exec_with_luit == NULL)
	    SysError(ERROR_LUMALLOC);

	x_appendargv(command_to_exec_with_luit, split_filter);
	if (count_using) {
	    char *encoding_opt[4];
	    encoding_opt[0] = x_strdup("-encoding");
	    encoding_opt[1] = term->misc.locale_str;
	    encoding_opt[2] = 0;
	    x_appendargv(command_to_exec_with_luit, encoding_opt);
	}
	command_length_with_luit = x_countargv(command_to_exec_with_luit);
	if (count_exec) {
	    static char *fixup_shell[] =
	    {(char *) "sh", (char *) "-c", 0};
	    char *delimiter[2];
	    delimiter[0] = x_strdup("--");
	    delimiter[1] = 0;
	    x_appendargv(command_to_exec_with_luit, delimiter);
	    if (complex_command(command_to_exec)) {
		x_appendargv(command_to_exec_with_luit, fixup_shell);
	    }
	    x_appendargv(command_to_exec_with_luit, command_to_exec);
	}
	TRACE_ARGV("luit command", command_to_exec_with_luit);
	xtermSetenv("XTERM_FILTER", *command_to_exec_with_luit);
    }
#endif

    if_DEBUG({
	/* Set up stderr properly.  Opening this log file cannot be
	   done securely by a privileged xterm process (although we try),
	   so the debug feature is disabled by default. */
	char dbglogfile[TIMESTAMP_LEN + 20];
	int i = -1;
	timestamp_filename(dbglogfile, "xterm.debug.log.");
	if (creat_as(save_ruid, save_rgid, False, dbglogfile, 0600) > 0) {
	    i = open(dbglogfile, O_WRONLY | O_TRUNC);
	}
	if (i >= 0) {
	    dup2(i, 2);

	    /* mark this file as close on exec */
	    (void) fcntl(i, F_SETFD, 1);
	}
    });

    spawnXTerm(term, line_speed);

#ifndef VMS
    /* Child process is out there, let's catch its termination */

#ifdef USE_POSIX_SIGNALS
    (void) posix_signal(SIGCHLD, reapchild);
#else
    (void) signal(SIGCHLD, reapchild);
#endif
    /* Realize procs have now been executed */

    if (am_slave >= 0) {	/* Write window id so master end can read and use */
	char buf[80];

	buf[0] = '\0';
	sprintf(buf, "%lx\n", XtWindow(SHELL_OF(CURRENT_EMU())));
	IGNORE_RC(write(screen->respond, buf, strlen(buf)));
    }
#ifdef AIXV3
#if (OSMAJORVERSION < 4)
    /* In AIXV3, xterms started from /dev/console have CLOCAL set.
     * This means we need to clear CLOCAL so that SIGHUP gets sent
     * to the slave-pty process when xterm exits.
     */

    {
	TERMIO_STRUCT tio;

	if (ttyGetAttr(screen->respond, &tio) == -1)
	    SysError(ERROR_TIOCGETP);

	tio.c_cflag &= ~(CLOCAL);

	if (ttySetAttr(screen->respond, &tio) == -1)
	    SysError(ERROR_TIOCSETP);
    }
#endif
#endif
#if defined(USE_ANY_SYSV_TERMIO) || defined(__MVS__) || defined(__minix)
    if (0 > (mode = fcntl(screen->respond, F_GETFL, 0)))
	SysError(ERROR_F_GETFL);
#ifdef O_NDELAY
    mode |= O_NDELAY;
#else
    mode |= O_NONBLOCK;
#endif /* O_NDELAY */
    if (fcntl(screen->respond, F_SETFL, mode))
	SysError(ERROR_F_SETFL);
#else /* !USE_ANY_SYSV_TERMIO */
    mode = 1;
    if (ioctl(screen->respond, FIONBIO, (char *) &mode) == -1)
	SysError(ERROR_FIONBIO);
#endif /* USE_ANY_SYSV_TERMIO, etc */

    /* The erase character is used to delete the current completion */
#if OPT_DABBREV
#ifdef TERMIO_STRUCT
    screen->dabbrev_erase_char = d_tio.c_cc[VERASE];
#else
    screen->dabbrev_erase_char = d_sg.sg_erase;
#endif
    TRACE(("set dabbrev erase_char %#x\n", screen->dabbrev_erase_char));
#endif

    FD_ZERO(&pty_mask);
    FD_ZERO(&X_mask);
    FD_ZERO(&Select_mask);
    FD_SET(screen->respond, &pty_mask);
    FD_SET(ConnectionNumber(screen->display), &X_mask);
    FD_SET(screen->respond, &Select_mask);
    FD_SET(ConnectionNumber(screen->display), &Select_mask);
    max_plus1 = ((screen->respond < ConnectionNumber(screen->display))
		 ? (1 + ConnectionNumber(screen->display))
		 : (1 + screen->respond));

#endif /* !VMS */
    if_DEBUG({
	TRACE(("debugging on pid %d\n", (int) getpid()));
    });
    XSetErrorHandler(xerror);
    XSetIOErrorHandler(xioerror);
#if OPT_SESSION_MGT
    IceSetIOErrorHandler(ice_error);
#endif

    initPtyData(&VTbuffer);
#ifdef ALLOWLOGGING
    if (term->misc.log_on) {
	StartLog(term);
    }
#endif

    xtermEmbedWindow(winToEmbedInto);
#if OPT_COLOR_RES
    TRACE(("checking reverseVideo before rv %s fg %s, bg %s\n",
	   term->misc.re_verse0 ? "reverse" : "normal",
	   NonNull(TScreenOf(term)->Tcolors[TEXT_FG].resource),
	   NonNull(TScreenOf(term)->Tcolors[TEXT_BG].resource)));

    if (term->misc.re_verse0) {
	if (isDefaultForeground(TScreenOf(term)->Tcolors[TEXT_FG].resource)
	    && isDefaultBackground(TScreenOf(term)->Tcolors[TEXT_BG].resource)) {
	    TScreenOf(term)->Tcolors[TEXT_FG].resource = x_strdup(XtDefaultBackground);
	    TScreenOf(term)->Tcolors[TEXT_BG].resource = x_strdup(XtDefaultForeground);
	} else {
	    ReverseVideo(term);
	}
	term->misc.re_verse = True;
	update_reversevideo();
	TRACE(("updated  reverseVideo after  rv %s fg %s, bg %s\n",
	       term->misc.re_verse ? "reverse" : "normal",
	       NonNull(TScreenOf(term)->Tcolors[TEXT_FG].resource),
	       NonNull(TScreenOf(term)->Tcolors[TEXT_BG].resource)));
    }
#endif /* OPT_COLOR_RES */

#if OPT_MAXIMIZE
    if (resource.maximized)
	RequestMaximize(term, True);
#endif
    for (;;) {
#if OPT_TEK4014
	if (TEK4014_ACTIVE(term))
	    TekRun();
	else
#endif
	    VTRun(term);
    }
}

#if defined(__osf__) || (defined(__GLIBC__) && !defined(USE_USG_PTYS)) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
#define USE_OPENPTY 1
static int opened_tty = -1;
#endif

/*
 * This function opens up a pty master and stuffs its value into pty.
 *
 * If it finds one, it returns a value of 0.  If it does not find one,
 * it returns a value of !0.  This routine is designed to be re-entrant,
 * so that if a pty master is found and later, we find that the slave
 * has problems, we can re-enter this function and get another one.
 */
static int
get_pty(int *pty, char *from GCC_UNUSED)
{
    int result = 1;

#if defined(USE_OPENPTY)
    result = openpty(pty, &opened_tty, ttydev, NULL, NULL);
    if (opened_tty >= 0) {
	close(opened_tty);
	opened_tty = -1;
    }
#elif defined(HAVE_POSIX_OPENPT) && defined(HAVE_PTSNAME) && defined(HAVE_GRANTPT_PTY_ISATTY)
    if ((*pty = posix_openpt(O_RDWR)) >= 0) {
	char *name = ptsname(*pty);
	if (name != 0) {
	    strcpy(ttydev, name);
	    result = 0;
	}
    }
#ifdef USE_PTY_SEARCH
    if (result) {
	result = pty_search(pty);
    }
#endif
#elif defined(PUCC_PTYD)
    result = ((*pty = openrpty(ttydev, ptydev,
			       (resource.utmpInhibit ? OPTY_NOP : OPTY_LOGIN),
			       save_ruid, from)) < 0);
#elif defined(__QNXNTO__)
    result = pty_search(pty);
#else
#if defined(USE_USG_PTYS) || defined(__CYGWIN__)
#if defined(__MVS__)
    result = pty_search(pty);
#else
    result = ((*pty = open("/dev/ptmx", O_RDWR)) < 0);
#endif
#if defined(SVR4) || defined(__SCO__)
    if (!result)
	strcpy(ttydev, ptsname(*pty));
#endif

#elif defined(AIXV3)

    if ((*pty = open("/dev/ptc", O_RDWR)) >= 0) {
	strcpy(ttydev, ttyname(*pty));
	result = 0;
    }
#elif defined(__convex__)

    char *pty_name;
    extern char *getpty(void);

    while ((pty_name = getpty()) != NULL) {
	if ((*pty = open(pty_name, O_RDWR)) >= 0) {
	    strcpy(ptydev, pty_name);
	    strcpy(ttydev, pty_name);
	    *x_basename(ttydev) = 't';
	    result = 0;
	    break;
	}
    }

#elif defined(sequent)

    result = ((*pty = getpseudotty(&ttydev, &ptydev)) < 0);

#elif defined(__sgi) && (OSMAJORVERSION >= 4)

    char *tty_name;

    tty_name = _getpty(pty, O_RDWR, 0622, 0);
    if (tty_name != 0) {
	strcpy(ttydev, tty_name);
	result = 0;
    }
#elif (defined(__sgi) && (OSMAJORVERSION < 4)) || (defined(umips) && defined (SYSTYPE_SYSV))

    struct stat fstat_buf;

    *pty = open("/dev/ptc", O_RDWR);
    if (*pty >= 0 && (fstat(*pty, &fstat_buf)) >= 0) {
	result = 0;
	sprintf(ttydev, "/dev/ttyq%d", minor(fstat_buf.st_rdev));
    }
#elif defined(__hpux)

    /*
     * Use the clone device if it works, otherwise use pty_search logic.
     */
    if ((*pty = open("/dev/ptym/clone", O_RDWR)) >= 0) {
	char *name = ptsname(*pty);
	if (name != 0) {
	    strcpy(ttydev, name);
	    result = 0;
	} else {		/* permissions, or other unexpected problem */
	    close(*pty);
	    *pty = -1;
	    result = pty_search(pty);
	}
    } else {
	result = pty_search(pty);
    }

#else

    result = pty_search(pty);

#endif
#endif

    TRACE(("get_pty(ttydev=%s, ptydev=%s) %s fd=%d\n",
	   ttydev != 0 ? ttydev : "?",
	   ptydev != 0 ? ptydev : "?",
	   result ? "FAIL" : "OK",
	   pty != 0 ? *pty : -1));
    return result;
}

static void
set_pty_permissions(uid_t uid, unsigned gid, unsigned mode)
{
#ifdef USE_TTY_GROUP
    struct group *ttygrp;

    if ((ttygrp = getgrnam(TTY_GROUP_NAME)) != 0) {
	gid = (unsigned) ttygrp->gr_gid;
	mode &= 0660U;
    }
    endgrent();
#endif /* USE_TTY_GROUP */

    TRACE_IDS;
    set_owner(ttydev, (unsigned) uid, gid, mode);
}

#ifdef get_pty			/* USE_UTMP_SETGID */
#undef get_pty
/*
 * Call the real get_pty() before relinquishing root-setuid, caching the
 * result.
 */
static int
get_pty(int *pty, char *from)
{
    static int m_pty = -1;
    int result = -1;

    if (pty == NULL) {
	result = really_get_pty(&m_pty, from);

	seteuid(0);
	set_pty_permissions(save_ruid, save_rgid, 0600U);
	seteuid(save_ruid);
	TRACE_IDS;

    } else if (m_pty != -1) {
	*pty = m_pty;
	result = 0;
    } else {
	result = -1;
    }
    TRACE(("get_pty(ttydev=%s, ptydev=%s) %s fd=%d (utmp setgid)\n",
	   ttydev != 0 ? ttydev : "?",
	   ptydev != 0 ? ptydev : "?",
	   result ? "FAIL" : "OK",
	   pty != 0 ? *pty : -1));
#ifdef USE_OPENPTY
    if (opened_tty >= 0) {
	close(opened_tty);
	opened_tty = -1;
    }
#endif
    return result;
}
#endif

/*
 * Called from get_pty to iterate over likely pseudo terminals
 * we might allocate.  Used on those systems that do not have
 * a functional interface for allocating a pty.
 * Returns 0 if found a pty, 1 if fails.
 */
#ifdef USE_PTY_SEARCH
static int
pty_search(int *pty)
{
    static int devindex = 0, letter = 0;

#if defined(CRAY) || defined(__MVS__)
    while (devindex < MAXPTTYS) {
	sprintf(ttydev, TTYFORMAT, devindex);
	sprintf(ptydev, PTYFORMAT, devindex);
	devindex++;

	TRACE(("pty_search(ttydev=%s, ptydev=%s)\n", ttydev, ptydev));
	if ((*pty = open(ptydev, O_RDWR)) >= 0) {
	    return 0;
	}
    }
#else /* CRAY || __MVS__ */
    while (PTYCHAR1[letter]) {
	ttydev[strlen(ttydev) - 2] =
	    ptydev[strlen(ptydev) - 2] = PTYCHAR1[letter];

	while (PTYCHAR2[devindex]) {
	    ttydev[strlen(ttydev) - 1] =
		ptydev[strlen(ptydev) - 1] = PTYCHAR2[devindex];
	    devindex++;

	    TRACE(("pty_search(ttydev=%s, ptydev=%s)\n", ttydev, ptydev));
	    if ((*pty = open(ptydev, O_RDWR)) >= 0) {
#ifdef sun
		/* Need to check the process group of the pty.
		 * If it exists, then the slave pty is in use,
		 * and we need to get another one.
		 */
		int pgrp_rtn;
		if (ioctl(*pty, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) {
		    close(*pty);
		    continue;
		}
#endif /* sun */
		return 0;
	    }
	}
	devindex = 0;
	letter++;
    }
#endif /* CRAY else */
    /*
     * We were unable to allocate a pty master!  Return an error
     * condition and let our caller terminate cleanly.
     */
    return 1;
}
#endif /* USE_PTY_SEARCH */

/*
 * The only difference in /etc/termcap between 4014 and 4015 is that
 * the latter has support for switching character sets.  We support the
 * 4015 protocol, but ignore the character switches.  Therefore, we
 * choose 4014 over 4015.
 *
 * Features of the 4014 over the 4012: larger (19") screen, 12-bit
 * graphics addressing (compatible with 4012 10-bit addressing),
 * special point plot mode, incremental plot mode (not implemented in
 * later Tektronix terminals), and 4 character sizes.
 * All of these are supported by xterm.
 */

#if OPT_TEK4014
static const char *const tekterm[] =
{
    "tek4014",
    "tek4015",			/* 4014 with APL character set support */
    "tek4012",			/* 4010 with lower case */
    "tek4013",			/* 4012 with APL character set support */
    "tek4010",			/* small screen, upper-case only */
    "dumb",
    0
};
#endif

/* The VT102 is a VT100 with the Advanced Video Option included standard.
 * It also adds Escape sequences for insert/delete character/line.
 * The VT220 adds 8-bit character sets, selective erase.
 * The VT320 adds a 25th status line, terminal state interrogation.
 * The VT420 has up to 48 lines on the screen.
 */

static const char *const vtterm[] =
{
#ifdef USE_X11TERM
    "x11term",			/* for people who want special term name */
#endif
    DFT_TERMTYPE,		/* for people who want special term name */
    "xterm",			/* the prefered name, should be fastest */
    "vt102",
    "vt100",
    "ansi",
    "dumb",
    0
};

/* ARGSUSED */
static void
hungtty(int i GCC_UNUSED)
{
    DEBUG_MSG("handle:hungtty\n");
    siglongjmp(env, 1);
}

#if OPT_PTY_HANDSHAKE
#define NO_FDS {-1, -1}

static int cp_pipe[2] = NO_FDS;	/* this pipe is used for child to parent transfer */
static int pc_pipe[2] = NO_FDS;	/* this pipe is used for parent to child transfer */

typedef enum {			/* c == child, p == parent                        */
    PTY_BAD,			/* c->p: can't open pty slave for some reason     */
    PTY_FATALERROR,		/* c->p: we had a fatal error with the pty        */
    PTY_GOOD,			/* c->p: we have a good pty, let's go on          */
    PTY_NEW,			/* p->c: here is a new pty slave, try this        */
    PTY_NOMORE,			/* p->c; no more pty's, terminate                 */
    UTMP_ADDED,			/* c->p: utmp entry has been added                */
    UTMP_TTYSLOT,		/* c->p: here is my ttyslot                       */
    PTY_EXEC			/* p->c: window has been mapped the first time    */
} status_t;

typedef struct {
    status_t status;
    int error;
    int fatal_error;
    int tty_slot;
    int rows;
    int cols;
    char buffer[1024];
} handshake_t;

/* the buffer is large enough that we can always have a trailing null */
#define copy_handshake(dst, src) \
	strncpy(dst.buffer, src, sizeof(dst.buffer) - 1)[sizeof(dst.buffer) - 1] = '\0'

#if OPT_TRACE
static void
trace_handshake(const char *tag, handshake_t * data)
{
    const char *status = "?";
    switch (data->status) {
    case PTY_BAD:
	status = "PTY_BAD";
	break;
    case PTY_FATALERROR:
	status = "PTY_FATALERROR";
	break;
    case PTY_GOOD:
	status = "PTY_GOOD";
	break;
    case PTY_NEW:
	status = "PTY_NEW";
	break;
    case PTY_NOMORE:
	status = "PTY_NOMORE";
	break;
    case UTMP_ADDED:
	status = "UTMP_ADDED";
	break;
    case UTMP_TTYSLOT:
	status = "UTMP_TTYSLOT";
	break;
    case PTY_EXEC:
	status = "PTY_EXEC";
	break;
    }
    TRACE(("handshake %s %s errno=%d, error=%d device \"%s\"\n",
	   tag,
	   status,
	   data->error,
	   data->fatal_error,
	   data->buffer));
}
#define TRACE_HANDSHAKE(tag, data) trace_handshake(tag, data)
#else
#define TRACE_HANDSHAKE(tag, data)	/* nothing */
#endif

/* HsSysError()
 *
 * This routine does the equivalent of a SysError but it handshakes
 * over the errno and error exit to the master process so that it can
 * display our error message and exit with our exit code so that the
 * user can see it.
 */

static void
HsSysError(int error)
{
    handshake_t handshake;

    memset(&handshake, 0, sizeof(handshake));
    handshake.status = PTY_FATALERROR;
    handshake.error = errno;
    handshake.fatal_error = error;
    copy_handshake(handshake, ttydev);

    if (resource.ptyHandshake && (cp_pipe[1] >= 0)) {
	TRACE(("HsSysError errno=%d, error=%d device \"%s\"\n",
	       handshake.error,
	       handshake.fatal_error,
	       handshake.buffer));
	TRACE_HANDSHAKE("writing", &handshake);
	IGNORE_RC(write(cp_pipe[1],
			(const char *) &handshake,
			sizeof(handshake)));
    } else {
	xtermWarning("fatal pty error errno=%d, error=%d device \"%s\"\n",
		     handshake.error,
		     handshake.fatal_error,
		     handshake.buffer);
	fprintf(stderr, "%s\n", SysErrorMsg(handshake.error));
	fprintf(stderr, "Reason: %s\n", SysReasonMsg(handshake.fatal_error));
    }
    exit(error);
}

void
first_map_occurred(void)
{
    if (resource.wait_for_map) {
	if (pc_pipe[1] >= 0) {
	    handshake_t handshake;
	    TScreen *screen = TScreenOf(term);

	    memset(&handshake, 0, sizeof(handshake));
	    handshake.status = PTY_EXEC;
	    handshake.rows = screen->max_row;
	    handshake.cols = screen->max_col;

	    TRACE(("first_map_occurred: %dx%d\n", MaxRows(screen), MaxCols(screen)));
	    TRACE_HANDSHAKE("writing", &handshake);
	    IGNORE_RC(write(pc_pipe[1],
			    (const char *) &handshake,
			    sizeof(handshake)));
	    close(cp_pipe[0]);
	    close(pc_pipe[1]);
	}
	resource.wait_for_map = False;
    }
}
#else
/*
 * temporary hack to get xterm working on att ptys
 */
static void
HsSysError(int error)
{
    xtermWarning("fatal pty error %d (errno=%d) on tty %s\n",
		 error, errno, ttydev);
    exit(error);
}
#endif /* OPT_PTY_HANDSHAKE else !OPT_PTY_HANDSHAKE */

#ifndef VMS
static void
set_owner(char *device, unsigned uid, unsigned gid, unsigned mode)
{
    int why;

    TRACE_IDS;
    TRACE(("set_owner(%s, uid=%d, gid=%d, mode=%#o\n",
	   device, (int) uid, (int) gid, (unsigned) mode));

    if (chown(device, (uid_t) uid, (gid_t) gid) < 0) {
	why = errno;
	if (why != ENOENT
	    && save_ruid == 0) {
	    xtermPerror("Cannot chown %s to %ld,%ld",
			device, (long) uid, (long) gid);
	}
	TRACE(("...chown failed: %s\n", strerror(why)));
    } else if (chmod(device, (mode_t) mode) < 0) {
	why = errno;
	if (why != ENOENT) {
	    struct stat sb;
	    if (stat(device, &sb) < 0) {
		xtermPerror("Cannot chmod %s to %03o",
			    device, (unsigned) mode);
	    } else if (mode != (sb.st_mode & 0777U)) {
		xtermPerror("Cannot chmod %s to %03lo currently %03lo",
			    device,
			    (unsigned long) mode,
			    (unsigned long) (sb.st_mode & 0777U));
		TRACE(("...stat uid=%d, gid=%d, mode=%#o\n",
		       (int) sb.st_uid, (int) sb.st_gid, (unsigned) sb.st_mode));
	    }
	}
	TRACE(("...chmod failed: %s\n", strerror(why)));
    }
}

/*
 * utmp data may not be null-terminated; even if it is, there may be garbage
 * after the null.  This fills the unused part of the result with nulls.
 */
static void
copy_filled(char *target, const char *source, size_t len)
{
    size_t used = 0;
    while (used < len) {
	if ((target[used] = source[used]) == 0)
	    break;
	++used;
    }
    while (used < len) {
	target[used++] = '\0';
    }
}

#if defined(HAVE_UTMP) && defined(USE_SYSV_UTMP) && !defined(USE_UTEMPTER)
/*
 * getutid() only looks at ut_type and ut_id.
 * But we'll also check ut_line in find_utmp().
 */
static void
init_utmp(int type, struct UTMP_STR *tofind)
{
    memset(tofind, 0, sizeof(*tofind));
    tofind->ut_type = (short) type;
    copy_filled(tofind->ut_id, my_utmp_id(ttydev), sizeof(tofind->ut_id));
    copy_filled(tofind->ut_line, my_pty_name(ttydev), sizeof(tofind->ut_line));
}

/*
 * We could use getutline() if we didn't support old systems.
 */
static struct UTMP_STR *
find_utmp(struct UTMP_STR *tofind)
{
    struct UTMP_STR *result;
    struct UTMP_STR limited;
    struct UTMP_STR working;

    for (;;) {
	memset(&working, 0, sizeof(working));
	working.ut_type = tofind->ut_type;
	copy_filled(working.ut_id, tofind->ut_id, sizeof(tofind->ut_id));
#if defined(__digital__) && defined(__unix__) && (defined(OSMAJORVERSION) && OSMAJORVERSION < 5)
	working.ut_type = 0;
#endif
	if ((result = call_getutid(&working)) == 0)
	    break;
	copy_filled(limited.ut_line, result->ut_line, sizeof(result->ut_line));
	if (!memcmp(limited.ut_line, tofind->ut_line, sizeof(limited.ut_line)))
	    break;
	/*
	 * Solaris, IRIX64 and HPUX manpages say to fill the static area
	 * pointed to by the return-value to zeros if searching for multiple
	 * occurrences.  Otherwise it will continue to return the same value.
	 */
	memset(result, 0, sizeof(*result));
    }
    return result;
}
#endif /* HAVE_UTMP... */

#define close_fd(fd) close(fd), fd = -1

#if defined(TIOCNOTTY) && (!defined(__GLIBC__) || (__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 1)))
#define USE_NO_DEV_TTY 1
#else
#define USE_NO_DEV_TTY 0
#endif

static int
same_leaf(char *a, char *b)
{
    char *p = x_basename(a);
    char *q = x_basename(b);
    return !strcmp(p, q);
}

/*
 * "good enough" (inode wouldn't port to Cygwin)
 */
static int
same_file(const char *a, const char *b)
{
    struct stat asb;
    struct stat bsb;
    int result = 0;

    if ((stat(a, &asb) == 0)
	&& (stat(b, &bsb) == 0)
	&& ((asb.st_mode & S_IFMT) == S_IFREG)
	&& ((bsb.st_mode & S_IFMT) == S_IFREG)
	&& (asb.st_mtime == bsb.st_mtime)
	&& (asb.st_size == bsb.st_size)) {
	result = 1;
    }
    return result;
}

static int
findValidShell(const char *haystack, const char *needle)
{
    int result = -1;
    int count = -1;
    const char *s, *t;
    size_t have;
    size_t want = strlen(needle);

    TRACE(("findValidShell:\n%s\n", NonNull(haystack)));

    for (s = t = haystack; (s != 0) && (*s != '\0'); s = t) {
	++count;
	if ((t = strchr(s, '\n')) == 0) {
	    t = s + strlen(s);
	}
	have = (size_t) (t - s);

	if ((have >= want) && (*s != '#')) {
	    char *p = malloc(have + 1);

	    if (p != 0) {
		char *q;

		memcpy(p, s, have);
		p[have] = '\0';
		if ((q = x_strtrim(p)) != 0) {
		    TRACE(("...test %s\n", q));
		    if (!strcmp(q, needle)) {
			result = count;
		    } else if (same_leaf(q, (char *) needle) &&
			       same_file(q, needle)) {
			result = count;
		    }
		    free(q);
		}
		free(p);
	    }
	    if (result >= 0)
		break;
	}
	while (*t == '\n') {
	    ++t;
	}
    }
    return result;
}

static int
ourValidShell(const char *pathname)
{
    return findValidShell(x_strtrim(resource.valid_shells), pathname);
}

#if defined(HAVE_GETUSERSHELL) && defined(HAVE_ENDUSERSHELL)
static Boolean
validShell(const char *pathname)
{
    int result = -1;

    if (validProgram(pathname)) {
	char *q;
	int count = -1;

	TRACE(("validShell:getusershell\n"));
	while ((q = getusershell()) != 0) {
	    ++count;
	    TRACE(("...test \"%s\"\n", q));
	    if (!strcmp(q, pathname)) {
		result = count;
		break;
	    }
	}
	endusershell();

	if (result < 0)
	    result = ourValidShell(pathname);
    }

    TRACE(("validShell %s ->%d\n", NonNull(pathname), result));
    return (result >= 0);
}
#else
/*
 * Only set $SHELL for paths found in the standard location.
 */
static Boolean
validShell(const char *pathname)
{
    int result = -1;
    const char *ok_shells = "/etc/shells";
    char *blob;
    struct stat sb;
    size_t rc;
    FILE *fp;

    if (validProgram(pathname)) {

	TRACE(("validShell:%s\n", ok_shells));

	if (stat(ok_shells, &sb) == 0
	    && (sb.st_mode & S_IFMT) == S_IFREG
	    && ((size_t) sb.st_size > 0)
	    && ((size_t) sb.st_size < (((size_t) ~0) - 2))
	    && (blob = calloc((size_t) sb.st_size + 2, sizeof(char))) != 0) {

	    if ((fp = fopen(ok_shells, "r")) != 0) {
		rc = fread(blob, sizeof(char), (size_t) sb.st_size, fp);
		fclose(fp);

		if (rc == (size_t) sb.st_size) {
		    blob[rc] = '\0';
		    result = findValidShell(blob, pathname);
		}
	    }
	    free(blob);
	}
	if (result < 0)
	    result = ourValidShell(pathname);
    }
    TRACE(("validShell %s ->%d\n", NonNull(pathname), result));
    return (result > 0);
}
#endif

static char *
resetShell(char *oldPath)
{
    char *newPath = x_strdup("/bin/sh");
    char *envPath = getenv("SHELL");
    if (oldPath != 0)
	free(oldPath);
    if (!IsEmpty(envPath))
	xtermSetenv("SHELL", newPath);
    return newPath;
}

/*
 *  Inits pty and tty and forks a login process.
 *  Does not close fd Xsocket.
 *  If slave, the pty named in passedPty is already open for use
 */
static int
spawnXTerm(XtermWidget xw, unsigned line_speed)
{
    TScreen *screen = TScreenOf(xw);
    Cardinal nn;
#if OPT_PTY_HANDSHAKE
    Bool got_handshake_size = False;
    handshake_t handshake;
    int done;
#endif
#if OPT_INITIAL_ERASE
    int initial_erase = VAL_INITIAL_ERASE;
    Bool setInitialErase;
#endif
    int rc = 0;
    int ttyfd = -1;
    Bool ok_termcap;
    char *newtc;

#ifdef TERMIO_STRUCT
    TERMIO_STRUCT tio;
#ifdef __MVS__
    TERMIO_STRUCT gio;
#endif /* __MVS__ */
#ifdef TIOCLSET
    unsigned lmode;
#endif /* TIOCLSET */
#ifdef HAS_LTCHARS
    struct ltchars ltc;
#endif /* HAS_LTCHARS */
#else /* !TERMIO_STRUCT */
    int ldisc = 0;
    int discipline;
    unsigned lmode;
    struct tchars tc;
    struct ltchars ltc;
    struct sgttyb sg;
#ifdef sony
    int jmode;
    struct jtchars jtc;
#endif /* sony */
#endif /* TERMIO_STRUCT */

    char *shell_path = 0;
    char *shname, *shname_minus;
    int i;
#if USE_NO_DEV_TTY
    int no_dev_tty = False;
#endif
    const char *const *envnew;	/* new environment */
    char buf[64];
    char *TermName = NULL;
#ifdef TTYSIZE_STRUCT
    TTYSIZE_STRUCT ts;
#endif
    struct passwd pw;
    char *login_name = NULL;
#ifndef USE_UTEMPTER
#ifdef HAVE_UTMP
    struct UTMP_STR utmp;
#ifdef USE_SYSV_UTMP
    struct UTMP_STR *utret = NULL;
#endif
#ifdef USE_LASTLOG
    struct lastlog lastlog;
#endif
#ifdef USE_LASTLOGX
    struct lastlogx lastlogx;
#endif /* USE_LASTLOG */
#endif /* HAVE_UTMP */
#endif /* !USE_UTEMPTER */

#if OPT_TRACE
    unsigned long xterm_parent = (unsigned long) getpid();
#endif

    /* Noisy compilers (suppress some unused-variable warnings) */
    (void) rc;
#if defined(HAVE_UTMP) && defined(USE_SYSV_UTMP) && !defined(USE_UTEMPTER)
    (void) utret;
#endif

    screen->uid = save_ruid;
    screen->gid = save_rgid;

#ifdef SIGTTOU
    /* so that TIOCSWINSZ || TIOCSIZE doesn't block */
    signal(SIGTTOU, SIG_IGN);
#endif

#if OPT_PTY_HANDSHAKE
    memset(&handshake, 0, sizeof(handshake));
#endif

    if (am_slave >= 0) {
	screen->respond = am_slave;
	set_pty_id(ttydev, passedPty);
#ifdef USE_PTY_DEVICE
	set_pty_id(ptydev, passedPty);
#endif
	if (xtermResetIds(screen) < 0)
	    exit(1);
    } else {
	Bool tty_got_hung;

	/*
	 * Sometimes /dev/tty hangs on open (as in the case of a pty
	 * that has gone away).  Simply make up some reasonable
	 * defaults.
	 */

	if (!sigsetjmp(env, 1)) {
	    signal(SIGALRM, hungtty);
	    alarm(2);		/* alarm(1) might return too soon */
	    ttyfd = open("/dev/tty", O_RDWR);
	    alarm(0);
	    tty_got_hung = False;
	} else {
	    tty_got_hung = True;
	    ttyfd = -1;
	    errno = ENXIO;
	}
	shell_path = 0;
	memset(&pw, 0, sizeof(pw));
#if OPT_PTY_HANDSHAKE
	got_handshake_size = False;
#endif /* OPT_PTY_HANDSHAKE */
#if OPT_INITIAL_ERASE
	initial_erase = VAL_INITIAL_ERASE;
#endif
	signal(SIGALRM, SIG_DFL);

	/*
	 * Check results and ignore current control terminal if
	 * necessary.  ENXIO is what is normally returned if there is
	 * no controlling terminal, but some systems (e.g. SunOS 4.0)
	 * seem to return EIO.  Solaris 2.3 is said to return EINVAL.
	 * Cygwin returns ENOENT.  FreeBSD can return ENOENT, especially
	 * if xterm is run within a jail.
	 */
#if USE_NO_DEV_TTY
	no_dev_tty = False;
#endif
	if (ttyfd < 0) {
	    if (tty_got_hung || errno == ENXIO || errno == EIO ||
		errno == ENOENT ||
#ifdef ENODEV
		errno == ENODEV ||
#endif
		errno == EINVAL || errno == ENOTTY || errno == EACCES) {
#if USE_NO_DEV_TTY
		no_dev_tty = True;
#endif
#ifdef HAS_LTCHARS
		ltc = d_ltc;
#endif /* HAS_LTCHARS */
#ifdef TIOCLSET
		lmode = d_lmode;
#endif /* TIOCLSET */
#ifdef TERMIO_STRUCT
		tio = d_tio;
#else /* !TERMIO_STRUCT */
		sg = d_sg;
		tc = d_tc;
		discipline = d_disipline;
#ifdef sony
		jmode = d_jmode;
		jtc = d_jtc;
#endif /* sony */
#endif /* TERMIO_STRUCT */
	    } else {
		SysError(ERROR_OPDEVTTY);
	    }
	} else {

	    /* Get a copy of the current terminal's state,
	     * if we can.  Some systems (e.g., SVR4 and MacII)
	     * may not have a controlling terminal at this point
	     * if started directly from xdm or xinit,
	     * in which case we just use the defaults as above.
	     */
#ifdef HAS_LTCHARS
	    if (ioctl(ttyfd, TIOCGLTC, &ltc) == -1)
		ltc = d_ltc;
#endif /* HAS_LTCHARS */
#ifdef TIOCLSET
	    if (ioctl(ttyfd, TIOCLGET, &lmode) == -1)
		lmode = d_lmode;
#endif /* TIOCLSET */
#ifdef TERMIO_STRUCT
	    rc = ttyGetAttr(ttyfd, &tio);
	    if (rc == -1)
		tio = d_tio;
#else /* !TERMIO_STRUCT */
	    rc = ioctl(ttyfd, TIOCGETP, (char *) &sg);
	    if (rc == -1)
		sg = d_sg;
	    if (ioctl(ttyfd, TIOCGETC, (char *) &tc) == -1)
		tc = d_tc;
	    if (ioctl(ttyfd, TIOCGETD, (char *) &discipline) == -1)
		discipline = d_disipline;
#ifdef sony
	    if (ioctl(ttyfd, TIOCKGET, (char *) &jmode) == -1)
		jmode = d_jmode;
	    if (ioctl(ttyfd, TIOCKGETC, (char *) &jtc) == -1)
		jtc = d_jtc;
#endif /* sony */
#endif /* TERMIO_STRUCT */

	    /*
	     * If ptyInitialErase is set, we want to get the pty's
	     * erase value.  Just in case that will fail, first get
	     * the value from /dev/tty, so we will have something
	     * at least.
	     */
#if OPT_INITIAL_ERASE
	    if (resource.ptyInitialErase) {
#ifdef TERMIO_STRUCT
		initial_erase = tio.c_cc[VERASE];
#else /* !TERMIO_STRUCT */
		initial_erase = sg.sg_erase;
#endif /* TERMIO_STRUCT */
		TRACE(("%s initial_erase:%d (from /dev/tty)\n",
		       rc == 0 ? "OK" : "FAIL",
		       initial_erase));
	    }
#endif
#ifdef __MVS__
	    if (ttyGetAttr(ttyfd, &gio) == 0) {
		gio.c_cflag &= ~(HUPCL | PARENB);
		ttySetAttr(ttyfd, &gio);
	    }
#endif /* __MVS__ */

	    close_fd(ttyfd);
	}

	if (get_pty(&screen->respond, XDisplayString(screen->display))) {
	    SysError(ERROR_PTYS);
	}
	TRACE_GET_TTYSIZE(screen->respond, "after get_pty");
#if OPT_INITIAL_ERASE
	if (resource.ptyInitialErase) {
#ifdef TERMIO_STRUCT
	    TERMIO_STRUCT my_tio;
	    rc = ttyGetAttr(screen->respond, &my_tio);
	    if (rc == 0)
		initial_erase = my_tio.c_cc[VERASE];
#else /* !TERMIO_STRUCT */
	    struct sgttyb my_sg;
	    rc = ioctl(screen->respond, TIOCGETP, (char *) &my_sg);
	    if (rc == 0)
		initial_erase = my_sg.sg_erase;
#endif /* TERMIO_STRUCT */
	    TRACE(("%s initial_erase:%d (from pty)\n",
		   (rc == 0) ? "OK" : "FAIL",
		   initial_erase));
	}
#endif /* OPT_INITIAL_ERASE */
    }

    /* avoid double MapWindow requests */
    XtSetMappedWhenManaged(SHELL_OF(CURRENT_EMU()), False);

    wm_delete_window = XInternAtom(XtDisplay(toplevel), "WM_DELETE_WINDOW",
				   False);

    if (!TEK4014_ACTIVE(xw))
	VTInit(xw);		/* realize now so know window size for tty driver */
#if defined(TIOCCONS) || defined(SRIOCSREDIR)
    if (Console) {
	/*
	 * Inform any running xconsole program
	 * that we are going to steal the console.
	 */
	XmuGetHostname(mit_console_name + MIT_CONSOLE_LEN, 255);
	mit_console = XInternAtom(screen->display, mit_console_name, False);
	/* the user told us to be the console, so we can use CurrentTime */
	XtOwnSelection(SHELL_OF(CURRENT_EMU()),
		       mit_console, CurrentTime,
		       ConvertConsoleSelection, NULL, NULL);
    }
#endif
#if OPT_TEK4014
    if (TEK4014_ACTIVE(xw)) {
	envnew = tekterm;
    } else
#endif
    {
	envnew = vtterm;
    }

    /*
     * This used to exit if no termcap entry was found for the specified
     * terminal name.  That's a little unfriendly, so instead we'll allow
     * the program to proceed (but not to set $TERMCAP) if the termcap
     * entry is not found.
     */
    ok_termcap = True;
    if (!get_termcap(xw, TermName = resource.term_name)) {
	const char *last = NULL;
	char *next;

	TermName = x_strdup(*envnew);
	ok_termcap = False;
	while (*envnew != NULL) {
	    if (last == NULL || strcmp(last, *envnew)) {
		next = x_strdup(*envnew);
		if (get_termcap(xw, next)) {
		    free(TermName);
		    TermName = next;
		    ok_termcap = True + 1;
		    break;
		} else {
		    free(next);
		}
	    }
	    last = *envnew;
	    envnew++;
	}
    }
    if (ok_termcap) {
	resource.term_name = TermName;
	resize_termcap(xw);
    }

    /*
     * Check if ptyInitialErase is not set.  If so, we rely on the termcap
     * (or terminfo) to tell us what the erase mode should be set to.
     */
#if OPT_INITIAL_ERASE
    TRACE(("resource ptyInitialErase is %sset\n",
	   resource.ptyInitialErase ? "" : "not "));
    setInitialErase = False;
    if (override_tty_modes && ttyModes[XTTYMODE_erase].set) {
	initial_erase = ttyModes[XTTYMODE_erase].value;
	setInitialErase = True;
    } else if (resource.ptyInitialErase) {
	/* EMPTY */ ;
    } else if (ok_termcap) {
	char *s = get_tcap_erase(xw);
	TRACE(("...extracting initial_erase value from termcap\n"));
	if (s != 0) {
	    char *save = s;
	    initial_erase = decode_keyvalue(&s, True);
	    setInitialErase = True;
	    free(save);
	}
    }
    TRACE(("...initial_erase:%d\n", initial_erase));

    TRACE(("resource backarrowKeyIsErase is %sset\n",
	   resource.backarrow_is_erase ? "" : "not "));
    if (resource.backarrow_is_erase) {	/* see input.c */
	if (initial_erase == ANSI_DEL) {
	    UIntClr(xw->keyboard.flags, MODE_DECBKM);
	} else {
	    xw->keyboard.flags |= MODE_DECBKM;
	    xw->keyboard.reset_DECBKM = 1;
	}
	TRACE(("...sets DECBKM %s\n",
	       (xw->keyboard.flags & MODE_DECBKM) ? "on" : "off"));
    } else {
	xw->keyboard.reset_DECBKM = 2;
    }
#endif /* OPT_INITIAL_ERASE */

#ifdef TTYSIZE_STRUCT
    /* tell tty how big window is */
#if OPT_TEK4014
    if (TEK4014_ACTIVE(xw)) {
	setup_winsize(ts, TDefaultRows, TDefaultCols,
		      TFullHeight(TekScreenOf(tekWidget)),
		      TFullWidth(TekScreenOf(tekWidget)));
    } else
#endif
    {
	setup_winsize(ts, MaxRows(screen), MaxCols(screen),
		      FullHeight(screen), FullWidth(screen));
    }
    TRACE_RC(i, SET_TTYSIZE(screen->respond, ts));
    TRACE(("spawn SET_TTYSIZE %dx%d return %d\n",
	   TTYSIZE_ROWS(ts),
	   TTYSIZE_COLS(ts), i));
#endif /* TTYSIZE_STRUCT */

#if !defined(USE_OPENPTY)
#if defined(USE_USG_PTYS) || defined(HAVE_POSIX_OPENPT)
    /*
     * utempter checks the ownership of the device; some implementations
     * set ownership in grantpt - do this first.
     */
    grantpt(screen->respond);
#endif
#if !defined(USE_USG_PTYS) && defined(HAVE_POSIX_OPENPT)
    unlockpt(screen->respond);
    TRACE_GET_TTYSIZE(screen->respond, "after unlockpt");
#endif
#endif /* !USE_OPENPTY */

    added_utmp_entry = False;
#if defined(USE_UTEMPTER)
#undef UTMP
    if ((xw->misc.login_shell || !command_to_exec) && !resource.utmpInhibit) {
	struct UTMP_STR dummy;

	/* Note: utempter may trim it anyway */
	SetUtmpHost(dummy.ut_host, screen);
	TRACE(("...calling addToUtmp(pty=%s, hostname=%s, master_fd=%d)\n",
	       ttydev, dummy.ut_host, screen->respond));
	addToUtmp(ttydev, dummy.ut_host, screen->respond);
	added_utmp_entry = True;
    }
#endif

    if (am_slave < 0) {
#if OPT_PTY_HANDSHAKE
	if (resource.ptyHandshake && (pipe(pc_pipe) || pipe(cp_pipe)))
	    SysError(ERROR_FORK);
#endif
	TRACE(("Forking...\n"));
	if ((screen->pid = fork()) == -1)
	    SysError(ERROR_FORK);

	if (screen->pid == 0) {
#ifdef USE_USG_PTYS
	    int ptyfd = -1;
	    char *pty_name;
#endif
	    /*
	     * now in child process
	     */
#if defined(_POSIX_SOURCE) || defined(SVR4) || defined(__convex__) || defined(__SCO__) || defined(__QNX__)
	    int pgrp = setsid();	/* variable may not be used... */
#else
	    int pgrp = getpid();
#endif
	    TRACE_CHILD

#ifdef USE_USG_PTYS
#ifdef HAVE_SETPGID
		setpgid(0, 0);
#else
		setpgrp();
#endif
	    unlockpt(screen->respond);
	    TRACE_GET_TTYSIZE(screen->respond, "after unlockpt");
	    if ((pty_name = ptsname(screen->respond)) == 0) {
		SysError(ERROR_PTSNAME);
	    } else if ((ptyfd = open(pty_name, O_RDWR)) < 0) {
		SysError(ERROR_OPPTSNAME);
	    }
#ifdef I_PUSH
	    else if (PUSH_FAILS(ptyfd, "ptem")) {
		SysError(ERROR_PTEM);
	    }
#if !defined(SVR4) && !(defined(SYSV) && defined(i386))
	    else if (!x_getenv("CONSEM")
		     && PUSH_FAILS(ptyfd, "consem")) {
		SysError(ERROR_CONSEM);
	    }
#endif /* !SVR4 */
	    else if (PUSH_FAILS(ptyfd, "ldterm")) {
		SysError(ERROR_LDTERM);
	    }
#ifdef SVR4			/* from Sony */
	    else if (PUSH_FAILS(ptyfd, "ttcompat")) {
		SysError(ERROR_TTCOMPAT);
	    }
#endif /* SVR4 */
#endif /* I_PUSH */
	    ttyfd = ptyfd;
#ifndef __MVS__
	    close_fd(screen->respond);
#endif /* __MVS__ */

#ifdef TTYSIZE_STRUCT
	    /* tell tty how big window is */
#if OPT_TEK4014
	    if (TEK4014_ACTIVE(xw)) {
		setup_winsize(ts, TDefaultRows, TDefaultCols,
			      TFullHeight(TekScreenOf(tekWidget)),
			      TFullWidth(TekScreenOf(tekWidget)));
	    } else
#endif /* OPT_TEK4014 */
	    {
		setup_winsize(ts, MaxRows(screen), MaxCols(screen),
			      FullHeight(screen), FullWidth(screen));
	    }
	    trace_winsize(ts, "initial tty size");
#endif /* TTYSIZE_STRUCT */

#endif /* USE_USG_PTYS */

	    (void) pgrp;	/* not all branches use this variable */

#if OPT_PTY_HANDSHAKE		/* warning, goes for a long ways */
	    if (resource.ptyHandshake) {
		char *ptr;

		/* close parent's sides of the pipes */
		close(cp_pipe[0]);
		close(pc_pipe[1]);

		/* Make sure that our sides of the pipes are not in the
		 * 0, 1, 2 range so that we don't fight with stdin, out
		 * or err.
		 */
		if (cp_pipe[1] <= 2) {
		    if ((i = fcntl(cp_pipe[1], F_DUPFD, 3)) >= 0) {
			IGNORE_RC(close(cp_pipe[1]));
			cp_pipe[1] = i;
		    }
		}
		if (pc_pipe[0] <= 2) {
		    if ((i = fcntl(pc_pipe[0], F_DUPFD, 3)) >= 0) {
			IGNORE_RC(close(pc_pipe[0]));
			pc_pipe[0] = i;
		    }
		}

		/* we don't need the socket, or the pty master anymore */
		close(ConnectionNumber(screen->display));
#ifndef __MVS__
		if (screen->respond >= 0)
		    close(screen->respond);
#endif /* __MVS__ */

		/* Now is the time to set up our process group and
		 * open up the pty slave.
		 */
#ifdef USE_SYSV_PGRP
#if defined(CRAY) && (OSMAJORVERSION > 5)
		IGNORE_RC(setsid());
#else
		IGNORE_RC(setpgrp());
#endif
#endif /* USE_SYSV_PGRP */

#if defined(__QNX__) && !defined(__QNXNTO__)
		qsetlogin(getlogin(), ttydev);
#endif
		if (ttyfd >= 0) {
#ifdef __MVS__
		    if (ttyGetAttr(ttyfd, &gio) == 0) {
			gio.c_cflag &= ~(HUPCL | PARENB);
			ttySetAttr(ttyfd, &gio);
		    }
#else /* !__MVS__ */
		    close_fd(ttyfd);
#endif /* __MVS__ */
		}

		for (;;) {
#if USE_NO_DEV_TTY
		    if (!no_dev_tty
			&& (ttyfd = open("/dev/tty", O_RDWR)) >= 0) {
			ioctl(ttyfd, TIOCNOTTY, (char *) NULL);
			close_fd(ttyfd);
		    }
#endif /* USE_NO_DEV_TTY */
#ifdef CSRG_BASED
		    IGNORE_RC(revoke(ttydev));
#endif
		    if ((ttyfd = open(ttydev, O_RDWR)) >= 0) {
			TRACE_GET_TTYSIZE(ttyfd, "after open");
			TRACE_RC(i, SET_TTYSIZE(ttyfd, ts));
			TRACE_GET_TTYSIZE(ttyfd, "after SET_TTYSIZE fixup");
#if defined(CRAY) && defined(TCSETCTTY)
			/* make /dev/tty work */
			ioctl(ttyfd, TCSETCTTY, 0);
#endif
#if ((defined(__GLIBC__) && defined(__FreeBSD_kernel__)) || defined(__GNU__)) && defined(TIOCSCTTY)
			/* make /dev/tty work */
			ioctl(ttyfd, TIOCSCTTY, 0);
#endif
#ifdef USE_SYSV_PGRP
			/* We need to make sure that we are actually
			 * the process group leader for the pty.  If
			 * we are, then we should now be able to open
			 * /dev/tty.
			 */
			if ((i = open("/dev/tty", O_RDWR)) >= 0) {
			    /* success! */
			    close(i);
			    break;
			}
#else /* USE_SYSV_PGRP */
			break;
#endif /* USE_SYSV_PGRP */
		    }
		    perror("open ttydev");
#ifdef TIOCSCTTY
		    ioctl(ttyfd, TIOCSCTTY, 0);
#endif
		    /* let our master know that the open failed */
		    handshake.status = PTY_BAD;
		    handshake.error = errno;
		    copy_handshake(handshake, ttydev);
		    TRACE_HANDSHAKE("writing", &handshake);
		    IGNORE_RC(write(cp_pipe[1],
				    (const char *) &handshake,
				    sizeof(handshake)));

		    /* get reply from parent */
		    i = (int) read(pc_pipe[0], (char *) &handshake,
				   sizeof(handshake));
		    if (i <= 0) {
			/* parent terminated */
			exit(1);
		    }

		    if (handshake.status == PTY_NOMORE) {
			/* No more ptys, let's shutdown. */
			exit(1);
		    }

		    /* We have a new pty to try */
		    if (ttyfd >= 0)
			close(ttyfd);
		    free(ttydev);
		    ttydev = x_strdup(handshake.buffer);
		}

		/* use the same tty name that everyone else will use
		 * (from ttyname)
		 */
		if ((ptr = ttyname(ttyfd)) != 0) {
		    free(ttydev);
		    ttydev = x_strdup(ptr);
		}
	    }
#endif /* OPT_PTY_HANDSHAKE -- from near fork */

	    set_pty_permissions(screen->uid,
				(unsigned) screen->gid,
				(resource.messages
				 ? 0622U
				 : 0600U));

	    /*
	     * set up the tty modes
	     */
	    {
#ifdef TERMIO_STRUCT
#if defined(umips) || defined(CRAY) || defined(linux)
		/* If the control tty had its modes screwed around with,
		   eg. by lineedit in the shell, or emacs, etc. then tio
		   will have bad values.  Let's just get termio from the
		   new tty and tailor it.  */
		if (ttyGetAttr(ttyfd, &tio) == -1)
		    SysError(ERROR_TIOCGETP);
		tio.c_lflag |= ECHOE;
#endif /* umips */
		/* Now is also the time to change the modes of the
		 * child pty.
		 */
		/* input: nl->nl, don't ignore cr, cr->nl */
		UIntClr(tio.c_iflag, (INLCR | IGNCR));
		tio.c_iflag |= ICRNL;
#if OPT_WIDE_CHARS && defined(IUTF8)
#if OPT_LUIT_PROG
		if (command_to_exec_with_luit == 0)
#endif
		    if (screen->utf8_mode)
			tio.c_iflag |= IUTF8;
#endif
		/* output: cr->cr, nl is not return, no delays, ln->cr/nl */
#ifndef USE_POSIX_TERMIOS
		UIntClr(tio.c_oflag,
			(OCRNL
			 | ONLRET
			 | NLDLY
			 | CRDLY
			 | TABDLY
			 | BSDLY
			 | VTDLY
			 | FFDLY));
#endif /* USE_POSIX_TERMIOS */
		tio.c_oflag |= D_TIO_FLAGS;
#ifndef USE_POSIX_TERMIOS
# if defined(Lynx) && !defined(CBAUD)
#  define CBAUD V_CBAUD
# endif
		UIntClr(tio.c_cflag, CBAUD);
#ifdef BAUD_0
		/* baud rate is 0 (don't care) */
#elif defined(HAVE_TERMIO_C_ISPEED)
		tio.c_ispeed = tio.c_ospeed = line_speed;
#else /* !BAUD_0 */
		tio.c_cflag |= line_speed;
#endif /* !BAUD_0 */
#else /* USE_POSIX_TERMIOS */
		cfsetispeed(&tio, line_speed);
		cfsetospeed(&tio, line_speed);
#ifdef __MVS__
		/* turn off bits that can't be set from the slave side */
		tio.c_cflag &= ~(PACKET | PKT3270 | PTU3270 | PKTXTND);
#endif /* __MVS__ */
		/* Clear CLOCAL so that SIGHUP is sent to us
		   when the xterm ends */
		tio.c_cflag &= (unsigned) ~CLOCAL;
#endif /* USE_POSIX_TERMIOS */
		/* enable signals, canonical processing (erase, kill, etc),
		 * echo
		 */
		tio.c_lflag |= ISIG | ICANON | ECHO | ECHOE | ECHOK;
#ifdef ECHOKE
		tio.c_lflag |= ECHOKE | IEXTEN;
#endif
#ifdef ECHOCTL
		tio.c_lflag |= ECHOCTL | IEXTEN;
#endif
		for (nn = 0; nn < XtNumber(ttyChars); ++nn) {
		    if (validTtyChar(tio, nn)) {
			int sysMode = ttyChars[nn].sysMode;
#ifdef __MVS__
			if (tio.c_cc[sysMode] != 0) {
			    switch (sysMode) {
			    case VEOL:
			    case VEOF:
				continue;
			    }
			}
#endif
			tio.c_cc[sysMode] = (cc_t) ttyChars[nn].myDefault;
		    }
		}

		if (override_tty_modes) {
		    TRACE(("applying termios ttyModes\n"));
		    for (nn = 0; nn < XtNumber(ttyChars); ++nn) {
			if (validTtyChar(tio, nn)) {
			    TMODE(ttyChars[nn].myMode,
				  tio.c_cc[ttyChars[nn].sysMode]);
			} else if (isTabMode(nn)) {
			    unsigned tmp = (unsigned) tio.c_oflag;
			    tmp = tmp & (unsigned) ~TABDLY;
			    tmp |= (unsigned) ttyModes[ttyChars[nn].myMode].value;
			    tio.c_oflag = tmp;
			}
		    }
#ifdef HAS_LTCHARS
		    /* both SYSV and BSD have ltchars */
		    TMODE(XTTYMODE_susp, ltc.t_suspc);
		    TMODE(XTTYMODE_dsusp, ltc.t_dsuspc);
		    TMODE(XTTYMODE_rprnt, ltc.t_rprntc);
		    TMODE(XTTYMODE_flush, ltc.t_flushc);
		    TMODE(XTTYMODE_weras, ltc.t_werasc);
		    TMODE(XTTYMODE_lnext, ltc.t_lnextc);
#endif
		}
#ifdef HAS_LTCHARS
#ifdef __hpux
		/* ioctl chokes when the "reserved" process group controls
		 * are not set to _POSIX_VDISABLE */
		ltc.t_rprntc = _POSIX_VDISABLE;
		ltc.t_rprntc = _POSIX_VDISABLE;
		ltc.t_flushc = _POSIX_VDISABLE;
		ltc.t_werasc = _POSIX_VDISABLE;
		ltc.t_lnextc = _POSIX_VDISABLE;
#endif /* __hpux */
		if (ioctl(ttyfd, TIOCSLTC, &ltc) == -1)
		    HsSysError(ERROR_TIOCSETC);
#endif /* HAS_LTCHARS */
#ifdef TIOCLSET
		if (ioctl(ttyfd, TIOCLSET, (char *) &lmode) == -1)
		    HsSysError(ERROR_TIOCLSET);
#endif /* TIOCLSET */
		if (ttySetAttr(ttyfd, &tio) == -1)
		    HsSysError(ERROR_TIOCSETP);

		/* ignore errors here - some platforms don't work */
		UIntClr(tio.c_cflag, CSIZE);
		if (screen->input_eight_bits)
		    tio.c_cflag |= CS8;
		else
		    tio.c_cflag |= CS7;
		(void) ttySetAttr(ttyfd, &tio);

#else /* !TERMIO_STRUCT */
		sg.sg_flags &= ~(ALLDELAY | XTABS | CBREAK | RAW);
		sg.sg_flags |= ECHO | CRMOD;
		/* make sure speed is set on pty so that editors work right */
		sg.sg_ispeed = line_speed;
		sg.sg_ospeed = line_speed;
		/* reset t_brkc to default value */
		tc.t_brkc = -1;
#ifdef LPASS8
		if (screen->input_eight_bits)
		    lmode |= LPASS8;
		else
		    lmode &= ~(LPASS8);
#endif
#ifdef sony
		jmode &= ~KM_KANJI;
#endif /* sony */

		ltc = d_ltc;

		if (override_tty_modes) {
		    TRACE(("applying sgtty ttyModes\n"));
		    TMODE(XTTYMODE_intr, tc.t_intrc);
		    TMODE(XTTYMODE_quit, tc.t_quitc);
		    TMODE(XTTYMODE_erase, sg.sg_erase);
		    TMODE(XTTYMODE_kill, sg.sg_kill);
		    TMODE(XTTYMODE_eof, tc.t_eofc);
		    TMODE(XTTYMODE_start, tc.t_startc);
		    TMODE(XTTYMODE_stop, tc.t_stopc);
		    TMODE(XTTYMODE_brk, tc.t_brkc);
		    /* both SYSV and BSD have ltchars */
		    TMODE(XTTYMODE_susp, ltc.t_suspc);
		    TMODE(XTTYMODE_dsusp, ltc.t_dsuspc);
		    TMODE(XTTYMODE_rprnt, ltc.t_rprntc);
		    TMODE(XTTYMODE_flush, ltc.t_flushc);
		    TMODE(XTTYMODE_weras, ltc.t_werasc);
		    TMODE(XTTYMODE_lnext, ltc.t_lnextc);
		    if (ttyModes[XTTYMODE_tabs].set
			|| ttyModes[XTTYMODE__tabs].set) {
			sg.sg_flags &= ~XTABS;
			if (ttyModes[XTTYMODE__tabs].set.set)
			    sg.sg_flags |= XTABS;
		    }
		}

		if (ioctl(ttyfd, TIOCSETP, (char *) &sg) == -1)
		    HsSysError(ERROR_TIOCSETP);
		if (ioctl(ttyfd, TIOCSETC, (char *) &tc) == -1)
		    HsSysError(ERROR_TIOCSETC);
		if (ioctl(ttyfd, TIOCSETD, (char *) &discipline) == -1)
		    HsSysError(ERROR_TIOCSETD);
		if (ioctl(ttyfd, TIOCSLTC, (char *) &ltc) == -1)
		    HsSysError(ERROR_TIOCSLTC);
		if (ioctl(ttyfd, TIOCLSET, (char *) &lmode) == -1)
		    HsSysError(ERROR_TIOCLSET);
#ifdef sony
		if (ioctl(ttyfd, TIOCKSET, (char *) &jmode) == -1)
		    HsSysError(ERROR_TIOCKSET);
		if (ioctl(ttyfd, TIOCKSETC, (char *) &jtc) == -1)
		    HsSysError(ERROR_TIOCKSETC);
#endif /* sony */
#endif /* TERMIO_STRUCT */
#if defined(TIOCCONS) || defined(SRIOCSREDIR)
		if (Console) {
#ifdef TIOCCONS
		    int on = 1;
		    if (ioctl(ttyfd, TIOCCONS, (char *) &on) == -1)
			xtermPerror("cannot open console");
#endif
#ifdef SRIOCSREDIR
		    int fd = open("/dev/console", O_RDWR);
		    if (fd == -1 || ioctl(fd, SRIOCSREDIR, ttyfd) == -1)
			xtermPerror("cannot open console");
		    IGNORE_RC(close(fd));
#endif
		}
#endif /* TIOCCONS */
	    }

	    signal(SIGCHLD, SIG_DFL);
#ifdef USE_SYSV_SIGHUP
	    /* watch out for extra shells (I don't understand either) */
	    signal(SIGHUP, SIG_DFL);
#else
	    signal(SIGHUP, SIG_IGN);
#endif
	    /* restore various signals to their defaults */
	    signal(SIGINT, SIG_DFL);
	    signal(SIGQUIT, SIG_DFL);
	    signal(SIGTERM, SIG_DFL);

	    /*
	     * If we're not asked to let the parent process set the terminal's
	     * erase mode, or if we had the ttyModes erase resource, then set
	     * the terminal's erase mode from our best guess.
	     */
#if OPT_INITIAL_ERASE
	    TRACE(("check if we should set erase to %d:%s\n\tptyInitialErase:%d,\n\toveride_tty_modes:%d,\n\tXTTYMODE_erase:%d\n",
		   initial_erase,
		   setInitialErase ? "YES" : "NO",
		   resource.ptyInitialErase,
		   override_tty_modes,
		   ttyModes[XTTYMODE_erase].set));
	    if (setInitialErase) {
#if OPT_TRACE
		int old_erase;
#endif
#ifdef TERMIO_STRUCT
		if (ttyGetAttr(ttyfd, &tio) == -1)
		    tio = d_tio;
#if OPT_TRACE
		old_erase = tio.c_cc[VERASE];
#endif
		tio.c_cc[VERASE] = (cc_t) initial_erase;
		TRACE_RC(rc, ttySetAttr(ttyfd, &tio));
#else /* !TERMIO_STRUCT */
		if (ioctl(ttyfd, TIOCGETP, (char *) &sg) == -1)
		    sg = d_sg;
#if OPT_TRACE
		old_erase = sg.sg_erase;
#endif
		sg.sg_erase = initial_erase;
		rc = ioctl(ttyfd, TIOCSETP, (char *) &sg);
#endif /* TERMIO_STRUCT */
		TRACE(("%s setting erase to %d (was %d)\n",
		       rc ? "FAIL" : "OK", initial_erase, old_erase));
	    }
#endif

	    xtermCopyEnv(environ);

	    /*
	     * standards.freedesktop.org/startup-notification-spec/
	     * notes that this variable is used when a "reliable" mechanism is
	     * not available; in practice it must be unset to avoid confusing
	     * GTK applications.
	     */
	    xtermUnsetenv("DESKTOP_STARTUP_ID");
	    /*
	     * We set this temporarily to work around poor design of Xcursor.
	     * Unset it here to avoid confusion.
	     */
	    xtermUnsetenv("XCURSOR_PATH");

	    xtermSetenv("TERM", resource.term_name);
	    if (!resource.term_name)
		*get_tcap_buffer(xw) = 0;

	    sprintf(buf, "%lu",
		    ((unsigned long) XtWindow(SHELL_OF(CURRENT_EMU()))));
	    xtermSetenv("WINDOWID", buf);

	    /* put the display into the environment of the shell */
	    xtermSetenv("DISPLAY", XDisplayString(screen->display));

	    xtermSetenv("XTERM_VERSION", xtermVersion());
	    xtermSetenv("XTERM_LOCALE", xtermEnvLocale());

	    /*
	     * For debugging only, add environment variables that can be used
	     * in scripts to selectively kill xterm's parent or child
	     * processes.
	     */
#if OPT_TRACE
	    sprintf(buf, "%lu", (unsigned long) xterm_parent);
	    xtermSetenv("XTERM_PARENT", buf);
	    sprintf(buf, "%lu", (unsigned long) getpid());
	    xtermSetenv("XTERM_CHILD", buf);
#endif

	    signal(SIGTERM, SIG_DFL);

	    /* this is the time to go and set up stdin, out, and err
	     */
	    {
#if defined(CRAY) && (OSMAJORVERSION >= 6)
		close_fd(ttyfd);

		IGNORE_RC(close(0));

		if (open("/dev/tty", O_RDWR)) {
		    SysError(ERROR_OPDEVTTY);
		}
		IGNORE_RC(close(1));
		IGNORE_RC(close(2));
		dup(0);
		dup(0);
#else
		/* dup the tty */
		for (i = 0; i <= 2; i++)
		    if (i != ttyfd) {
			IGNORE_RC(close(i));
			IGNORE_RC(dup(ttyfd));
		    }
#ifndef ATT
		/* and close the tty */
		if (ttyfd > 2)
		    close_fd(ttyfd);
#endif
#endif /* CRAY */
	    }

#if !defined(USE_SYSV_PGRP)
#ifdef TIOCSCTTY
	    setsid();
	    ioctl(0, TIOCSCTTY, 0);
#endif
	    ioctl(0, TIOCSPGRP, (char *) &pgrp);
	    setpgrp(0, 0);
	    close(open(ttydev, O_WRONLY));
	    setpgrp(0, pgrp);
#if defined(__QNX__)
	    tcsetpgrp(0, pgrp /*setsid() */ );
#endif
#endif /* !USE_SYSV_PGRP */

#ifdef Lynx
	    {
		TERMIO_STRUCT t;
		if (ttyGetAttr(0, &t) >= 0) {
		    /* this gets lost somewhere on our way... */
		    t.c_oflag |= OPOST;
		    ttySetAttr(0, &t);
		}
	    }
#endif

#ifdef HAVE_UTMP
	    login_name = NULL;
	    if (x_getpwuid(screen->uid, &pw)) {
		login_name = x_getlogin(screen->uid, &pw);
	    }
	    if (login_name != NULL) {
		xtermSetenv("LOGNAME", login_name);	/* for POSIX */
	    }
#ifndef USE_UTEMPTER
#ifdef USE_UTMP_SETGID
	    setEffectiveGroup(save_egid);
	    TRACE_IDS;
#endif
#ifdef USE_SYSV_UTMP
	    /* Set up our utmp entry now.  We need to do it here
	     * for the following reasons:
	     *   - It needs to have our correct process id (for
	     *     login).
	     *   - If our parent was to set it after the fork(),
	     *     it might make it out before we need it.
	     *   - We need to do it before we go and change our
	     *     user and group id's.
	     */
	    (void) call_setutent();
	    init_utmp(DEAD_PROCESS, &utmp);

	    /* position to entry in utmp file */
	    /* Test return value: beware of entries left behind: PSz 9 Mar 00 */
	    utret = find_utmp(&utmp);
	    if (utret == 0) {
		(void) call_setutent();
		init_utmp(USER_PROCESS, &utmp);
		utret = find_utmp(&utmp);
		if (utret == 0) {
		    (void) call_setutent();
		}
	    }
#if OPT_TRACE
	    if (!utret)
		TRACE(("getutid: NULL\n"));
	    else
		TRACE(("getutid: pid=%d type=%d user=%s line=%.*s id=%.*s\n",
		       (int) utret->ut_pid, utret->ut_type, utret->ut_user,
		       (int) sizeof(utret->ut_line), utret->ut_line,
		       (int) sizeof(utret->ut_id), utret->ut_id));
#endif

	    /* set up the new entry */
	    utmp.ut_type = USER_PROCESS;
#ifdef HAVE_UTMP_UT_XSTATUS
	    utmp.ut_xstatus = 2;
#endif
	    copy_filled(utmp.ut_user,
			(login_name != NULL) ? login_name : "????",
			sizeof(utmp.ut_user));
	    /* why are we copying this string again?  (see above) */
	    copy_filled(utmp.ut_id, my_utmp_id(ttydev), sizeof(utmp.ut_id));
	    copy_filled(utmp.ut_line,
			my_pty_name(ttydev), sizeof(utmp.ut_line));

#ifdef HAVE_UTMP_UT_HOST
	    SetUtmpHost(utmp.ut_host, screen);
#endif
#ifdef HAVE_UTMP_UT_SYSLEN
	    SetUtmpSysLen(utmp);
#endif

	    copy_filled(utmp.ut_name,
			(login_name) ? login_name : "????",
			sizeof(utmp.ut_name));

	    utmp.ut_pid = getpid();
#if defined(HAVE_UTMP_UT_XTIME)
#if defined(HAVE_UTMP_UT_SESSION)
	    utmp.ut_session = getsid(0);
#endif
	    utmp.ut_xtime = time((time_t *) 0);
	    utmp.ut_tv.tv_usec = 0;
#else
	    utmp.ut_time = time((time_t *) 0);
#endif

	    /* write out the entry */
	    if (!resource.utmpInhibit) {
		errno = 0;
		call_pututline(&utmp);
		TRACE(("pututline: id %.*s, line %.*s, pid %ld, errno %d %s\n",
		       (int) sizeof(utmp.ut_id), utmp.ut_id,
		       (int) sizeof(utmp.ut_line), utmp.ut_line,
		       (long) utmp.ut_pid,
		       errno, (errno != 0) ? strerror(errno) : ""));
	    }
#ifdef WTMP
#if defined(WTMPX_FILE) && (defined(SVR4) || defined(__SCO__))
	    if (xw->misc.login_shell)
		updwtmpx(WTMPX_FILE, &utmp);
#elif defined(linux) && defined(__GLIBC__) && (__GLIBC__ >= 2) && !(defined(__powerpc__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
	    if (xw->misc.login_shell)
		call_updwtmp(etc_wtmp, &utmp);
#else
	    if (xw->misc.login_shell &&
		(i = open(etc_wtmp, O_WRONLY | O_APPEND)) >= 0) {
		IGNORE_RC(write(i, (char *) &utmp, sizeof(utmp)));
		close(i);
	    }
#endif
#endif
	    /* close the file */
	    (void) call_endutent();

#else /* USE_SYSV_UTMP */
	    /* We can now get our ttyslot!  We can also set the initial
	     * utmp entry.
	     */
	    tslot = ttyslot();
	    added_utmp_entry = False;
	    {
		if (tslot > 0 && OkPasswd(&pw) && !resource.utmpInhibit &&
		    (i = open(etc_utmp, O_WRONLY)) >= 0) {
		    memset(&utmp, 0, sizeof(utmp));
		    copy_filled(utmp.ut_line,
				my_pty_name(ttydev),
				sizeof(utmp.ut_line));
		    copy_filled(utmp.ut_name, login_name,
				sizeof(utmp.ut_name));
#ifdef HAVE_UTMP_UT_HOST
		    SetUtmpHost(utmp.ut_host, screen);
#endif
#ifdef HAVE_UTMP_UT_SYSLEN
		    SetUtmpSysLen(utmp);
#endif

		    utmp.ut_time = time((time_t *) 0);
		    lseek(i, (long) (tslot * sizeof(utmp)), 0);
		    IGNORE_RC(write(i, (char *) &utmp, sizeof(utmp)));
		    close(i);
		    added_utmp_entry = True;
#if defined(WTMP)
		    if (xw->misc.login_shell &&
			(i = open(etc_wtmp, O_WRONLY | O_APPEND)) >= 0) {
			int status;
			status = write(i, (char *) &utmp, sizeof(utmp));
			status = close(i);
		    }
#elif defined(MNX_LASTLOG)
		    if (xw->misc.login_shell &&
			(i = open(_U_LASTLOG, O_WRONLY)) >= 0) {
			lseek(i, (long) (screen->uid *
					 sizeof(utmp)), 0);
			IGNORE_RC(write(i, (char *) &utmp, sizeof(utmp)));
			close(i);
		    }
#endif /* WTMP or MNX_LASTLOG */
		} else
		    tslot = -tslot;
	    }

	    /* Let's pass our ttyslot to our parent so that it can
	     * clean up after us.
	     */
#if OPT_PTY_HANDSHAKE
	    if (resource.ptyHandshake) {
		handshake.tty_slot = tslot;
	    }
#endif /* OPT_PTY_HANDSHAKE */
#endif /* USE_SYSV_UTMP */

#ifdef USE_LASTLOGX
	    if (xw->misc.login_shell) {
		memset(&lastlogx, 0, sizeof(lastlogx));
		copy_filled(lastlogx.ll_line,
			    my_pty_name(ttydev),
			    sizeof(lastlogx.ll_line));
		X_GETTIMEOFDAY(&lastlogx.ll_tv);
		SetUtmpHost(lastlogx.ll_host, screen);
		updlastlogx(_PATH_LASTLOGX, screen->uid, &lastlogx);
	    }
#endif

#ifdef USE_LASTLOG
	    if (xw->misc.login_shell &&
		(i = open(etc_lastlog, O_WRONLY)) >= 0) {
		size_t size = sizeof(struct lastlog);
		off_t offset = (off_t) ((size_t) screen->uid * size);

		memset(&lastlog, 0, size);
		copy_filled(lastlog.ll_line,
			    my_pty_name(ttydev),
			    sizeof(lastlog.ll_line));
		SetUtmpHost(lastlog.ll_host, screen);
		lastlog.ll_time = time((time_t *) 0);
		if (lseek(i, offset, 0) != (off_t) (-1)) {
		    IGNORE_RC(write(i, (char *) &lastlog, size));
		}
		close(i);
	    }
#endif /* USE_LASTLOG */

#if defined(USE_UTMP_SETGID)
	    disableSetGid();
	    TRACE_IDS;
#endif

#if OPT_PTY_HANDSHAKE
	    /* Let our parent know that we set up our utmp entry
	     * so that it can clean up after us.
	     */
	    if (resource.ptyHandshake) {
		handshake.status = UTMP_ADDED;
		handshake.error = 0;
		copy_handshake(handshake, ttydev);
		TRACE_HANDSHAKE("writing", &handshake);
		IGNORE_RC(write(cp_pipe[1], (char *) &handshake, sizeof(handshake)));
	    }
#endif /* OPT_PTY_HANDSHAKE */
#endif /* USE_UTEMPTER */
#endif /* HAVE_UTMP */

	    IGNORE_RC(setgid(screen->gid));
	    TRACE_IDS;
#ifdef HAVE_INITGROUPS
	    if (geteuid() == 0 && OkPasswd(&pw)) {
		if (initgroups(login_name, pw.pw_gid)) {
		    perror("initgroups failed");
		    SysError(ERROR_INIGROUPS);
		}
	    }
#endif
	    if (setuid(screen->uid)) {
		SysError(ERROR_SETUID);
	    }
	    TRACE_IDS;
#if OPT_PTY_HANDSHAKE
	    if (resource.ptyHandshake) {
		/* mark the pipes as close on exec */
		(void) fcntl(cp_pipe[1], F_SETFD, 1);
		(void) fcntl(pc_pipe[0], F_SETFD, 1);

		/* We are at the point where we are going to
		 * exec our shell (or whatever).  Let our parent
		 * know we arrived safely.
		 */
		handshake.status = PTY_GOOD;
		handshake.error = 0;
		copy_handshake(handshake, ttydev);
		TRACE_HANDSHAKE("writing", &handshake);
		IGNORE_RC(write(cp_pipe[1],
				(const char *) &handshake,
				sizeof(handshake)));

		if (resource.wait_for_map) {
		    i = (int) read(pc_pipe[0], (char *) &handshake,
				   sizeof(handshake));
		    if (i != sizeof(handshake) ||
			handshake.status != PTY_EXEC) {
			/* some very bad problem occurred */
			exit(ERROR_PTY_EXEC);
		    }
		    if (handshake.rows > 0 && handshake.cols > 0) {
			TRACE(("handshake read ttysize: %dx%d\n",
			       handshake.rows, handshake.cols));
			set_max_row(screen, handshake.rows);
			set_max_col(screen, handshake.cols);
#ifdef TTYSIZE_STRUCT
			got_handshake_size = True;
			setup_winsize(ts, MaxRows(screen), MaxCols(screen),
				      FullHeight(screen), FullWidth(screen));
			trace_winsize(ts, "got handshake");
#endif /* TTYSIZE_STRUCT */
		    }
		}
	    }
#endif /* OPT_PTY_HANDSHAKE */

#ifdef USE_SYSV_ENVVARS
	    {
		char numbuf[12];
		sprintf(numbuf, "%d", MaxCols(screen));
		xtermSetenv("COLUMNS", numbuf);
		sprintf(numbuf, "%d", MaxRows(screen));
		xtermSetenv("LINES", numbuf);
	    }
#ifdef HAVE_UTMP
	    if (OkPasswd(&pw)) {	/* SVR4 doesn't provide these */
		if (!x_getenv("HOME"))
		    xtermSetenv("HOME", pw.pw_dir);
		if (!x_getenv("SHELL"))
		    xtermSetenv("SHELL", pw.pw_shell);
	    }
#endif /* HAVE_UTMP */
#else /* USE_SYSV_ENVVARS */
	    if (*(newtc = get_tcap_buffer(xw)) != '\0') {
		resize_termcap(xw);
		if (xw->misc.titeInhibit && !xw->misc.tiXtraScroll) {
		    remove_termcap_entry(newtc, "ti=");
		    remove_termcap_entry(newtc, "te=");
		}
		/*
		 * work around broken termcap entries */
		if (resource.useInsertMode) {
		    remove_termcap_entry(newtc, "ic=");
		    /* don't get duplicates */
		    remove_termcap_entry(newtc, "im=");
		    remove_termcap_entry(newtc, "ei=");
		    remove_termcap_entry(newtc, "mi");
		    if (*newtc)
			strcat(newtc, ":im=\\E[4h:ei=\\E[4l:mi:");
		}
		if (*newtc) {
#if OPT_INITIAL_ERASE
		    unsigned len;
		    remove_termcap_entry(newtc, TERMCAP_ERASE "=");
		    len = (unsigned) strlen(newtc);
		    if (len != 0 && newtc[len - 1] == ':')
			len--;
		    sprintf(newtc + len, ":%s=\\%03o:",
			    TERMCAP_ERASE,
			    CharOf(initial_erase));
#endif
		    xtermSetenv("TERMCAP", newtc);
		}
	    }
#endif /* USE_SYSV_ENVVARS */
#ifdef OWN_TERMINFO_ENV
	    xtermSetenv("TERMINFO", OWN_TERMINFO_DIR);
#endif

#if OPT_PTY_HANDSHAKE
	    /*
	     * Need to reset after all the ioctl bashing we did above.
	     *
	     * If we expect the waitForMap logic to set the handshake-size,
	     * use that to prevent races.
	     */
	    TRACE(("should we reset screensize after pty-handshake?\n"));
	    TRACE(("... ptyHandshake      :%d\n", resource.ptyHandshake));
	    TRACE(("... ptySttySize       :%d\n", resource.ptySttySize));
	    TRACE(("... got_handshake_size:%d\n", got_handshake_size));
	    TRACE(("... wait_for_map0     :%d\n", resource.wait_for_map0));
	    if (resource.ptyHandshake
		&& resource.ptySttySize
		&& (got_handshake_size || !resource.wait_for_map0)) {
#ifdef TTYSIZE_STRUCT
		TRACE_RC(i, SET_TTYSIZE(0, ts));
		trace_winsize(ts, "ptyHandshake SET_TTYSIZE");
#endif /* TTYSIZE_STRUCT */
	    }
#endif /* OPT_PTY_HANDSHAKE */
	    signal(SIGHUP, SIG_DFL);

	    /*
	     * If we have an explicit shell to run, make that set $SHELL.
	     * Next, allow an existing setting of $SHELL, for absolute paths.
	     * Otherwise, if $SHELL is not set, determine it from the user's
	     * password information, if possible.
	     *
	     * Incidentally, our setting of $SHELL tells luit to use that
	     * program rather than choosing between $SHELL and "/bin/sh".
	     */
	    if (validShell(explicit_shname)) {
		xtermSetenv("SHELL", explicit_shname);
	    } else if (validProgram(shell_path = x_getenv("SHELL"))) {
		if (!validShell(shell_path)) {
		    xtermUnsetenv("SHELL");
		}
	    } else if ((!OkPasswd(&pw) && !x_getpwuid(screen->uid, &pw))
		       || *(shell_path = x_strdup(pw.pw_shell)) == 0) {
		shell_path = resetShell(shell_path);
	    } else if (validShell(shell_path)) {
		xtermSetenv("SHELL", shell_path);
	    } else {
		shell_path = resetShell(shell_path);
	    }

	    /*
	     * Set $XTERM_SHELL, which is not necessarily a valid shell, but
	     * is executable.
	     */
	    if (validProgram(explicit_shname)) {
		shell_path = explicit_shname;
	    } else if (shell_path == 0) {
		/* this could happen if the explicit shname lost a race */
		shell_path = resetShell(shell_path);
	    }
	    xtermSetenv("XTERM_SHELL", shell_path);

	    shname = x_basename(shell_path);
	    TRACE(("shell path '%s' leaf '%s'\n", shell_path, shname));

#if OPT_LUIT_PROG
	    /*
	     * Use two copies of command_to_exec, in case luit is not actually
	     * there, or refuses to run.  In that case we will fall-through to
	     * to command that the user gave anyway.
	     */
	    if (command_to_exec_with_luit && command_to_exec) {
		char *myShell = xtermFindShell(*command_to_exec_with_luit, False);
		xtermSetenv("XTERM_SHELL", myShell);
		free(myShell);
		TRACE_ARGV("spawning luit command", command_to_exec_with_luit);
		execvp(*command_to_exec_with_luit, command_to_exec_with_luit);
		xtermPerror("Can't execvp %s", *command_to_exec_with_luit);
		xtermWarning("cannot support your locale.\n");
	    }
#endif
	    if (command_to_exec) {
		char *myShell = xtermFindShell(*command_to_exec, False);
		xtermSetenv("XTERM_SHELL", myShell);
		free(myShell);
		TRACE_ARGV("spawning command", command_to_exec);
		execvp(*command_to_exec, command_to_exec);
		if (command_to_exec[1] == 0)
		    execlp(shell_path, shname, "-c", command_to_exec[0],
			   (void *) 0);
		xtermPerror("Can't execvp %s", *command_to_exec);
	    }
#ifdef USE_SYSV_SIGHUP
	    /* fix pts sh hanging around */
	    signal(SIGHUP, SIG_DFL);
#endif

	    if ((shname_minus = TextAlloc(strlen(shname) + 1)) != 0) {
		(void) strcpy(shname_minus, "-");
		(void) strcat(shname_minus, shname);
	    } else {
		static char default_minus[] = "-sh";
		shname_minus = default_minus;
	    }
#ifndef TERMIO_STRUCT
	    ldisc = (!XStrCmp("csh", shname + strlen(shname) - 3)
		     ? NTTYDISC
		     : 0);
	    ioctl(0, TIOCSETD, (char *) &ldisc);
#endif /* !TERMIO_STRUCT */

#ifdef USE_LOGIN_DASH_P
	    if (xw->misc.login_shell && OkPasswd(&pw) && added_utmp_entry)
		execl(bin_login, "login", "-p", "-f", login_name, (void *) 0);
#endif

#if OPT_LUIT_PROG
	    if (command_to_exec_with_luit) {
		if (xw->misc.login_shell) {
		    char *params[4];
		    params[0] = x_strdup("-argv0");
		    params[1] = shname_minus;
		    params[2] = NULL;
		    x_appendargv(command_to_exec_with_luit
				 + command_length_with_luit,
				 params);
		}
		TRACE_ARGV("final luit command", command_to_exec_with_luit);
		execvp(*command_to_exec_with_luit, command_to_exec_with_luit);
		/* Exec failed. */
		xtermPerror("Can't execvp %s", *command_to_exec_with_luit);
	    }
#endif
	    execlp(shell_path,
		   (xw->misc.login_shell ? shname_minus : shname),
		   (void *) 0);

	    /* Exec failed. */
	    xtermPerror("Could not exec %s", shell_path);
	    IGNORE_RC(sleep(5));
	    free(shell_path);
	    exit(ERROR_EXEC);
	}
	/* end if in child after fork */
#if OPT_PTY_HANDSHAKE
	if (resource.ptyHandshake) {
	    /* Parent process.  Let's handle handshaked requests to our
	     * child process.
	     */

	    /* close childs's sides of the pipes */
	    close(cp_pipe[1]);
	    close(pc_pipe[0]);

	    for (done = 0; !done;) {
		if (read(cp_pipe[0],
			 (char *) &handshake,
			 sizeof(handshake)) <= 0) {
		    /* Our child is done talking to us.  If it terminated
		     * due to an error, we will catch the death of child
		     * and clean up.
		     */
		    break;
		}

		TRACE_HANDSHAKE("read", &handshake);
		switch (handshake.status) {
		case PTY_GOOD:
		    /* Success!  Let's free up resources and
		     * continue.
		     */
		    done = 1;
		    break;

		case PTY_BAD:
		    /* The open of the pty failed!  Let's get
		     * another one.
		     */
		    IGNORE_RC(close(screen->respond));
		    if (get_pty(&screen->respond, XDisplayString(screen->display))) {
			/* no more ptys! */
			xtermPerror("child process can find no available ptys");
			handshake.status = PTY_NOMORE;
			TRACE_HANDSHAKE("writing", &handshake);
			IGNORE_RC(write(pc_pipe[1],
					(const char *) &handshake,
					sizeof(handshake)));
			exit(ERROR_PTYS);
		    }
		    handshake.status = PTY_NEW;
		    copy_handshake(handshake, ttydev);
		    TRACE_HANDSHAKE("writing", &handshake);
		    IGNORE_RC(write(pc_pipe[1],
				    (const char *) &handshake,
				    sizeof(handshake)));
		    break;

		case PTY_FATALERROR:
		    errno = handshake.error;
		    close(cp_pipe[0]);
		    close(pc_pipe[1]);
		    SysError(handshake.fatal_error);
		    /*NOTREACHED */

		case UTMP_ADDED:
		    /* The utmp entry was set by our slave.  Remember
		     * this so that we can reset it later.
		     */
		    added_utmp_entry = True;
#ifndef	USE_SYSV_UTMP
		    tslot = handshake.tty_slot;
#endif /* USE_SYSV_UTMP */
		    free(ttydev);
		    ttydev = x_strdup(handshake.buffer);
		    break;
		case PTY_NEW:
		case PTY_NOMORE:
		case UTMP_TTYSLOT:
		case PTY_EXEC:
		default:
		    xtermWarning("unexpected handshake status %d\n",
				 (int) handshake.status);
		}
	    }
	    /* close our sides of the pipes */
	    if (!resource.wait_for_map) {
		close(cp_pipe[0]);
		close(pc_pipe[1]);
	    }
	}
#endif /* OPT_PTY_HANDSHAKE */
    }

    /* end if no slave */
    /*
     * still in parent (xterm process)
     */
#ifdef USE_SYSV_SIGHUP
    /* hung sh problem? */
    signal(SIGHUP, SIG_DFL);
#else
    signal(SIGHUP, SIG_IGN);
#endif

/*
 * Unfortunately, System V seems to have trouble divorcing the child process
 * from the process group of xterm.  This is a problem because hitting the
 * INTR or QUIT characters on the keyboard will cause xterm to go away if we
 * don't ignore the signals.  This is annoying.
 */

#if defined(USE_SYSV_SIGNALS) && !defined(SIGTSTP)
    signal(SIGINT, SIG_IGN);

#ifndef SYSV
    /* hung shell problem */
    signal(SIGQUIT, SIG_IGN);
#endif
    signal(SIGTERM, SIG_IGN);
#elif defined(SYSV) || defined(__osf__)
    /* if we were spawned by a jobcontrol smart shell (like ksh or csh),
     * then our pgrp and pid will be the same.  If we were spawned by
     * a jobcontrol dumb shell (like /bin/sh), then we will be in our
     * parent's pgrp, and we must ignore keyboard signals, or we will
     * tank on everything.
     */
    if (getpid() == getpgrp()) {
	(void) signal(SIGINT, Exit);
	(void) signal(SIGQUIT, Exit);
	(void) signal(SIGTERM, Exit);
    } else {
	(void) signal(SIGINT, SIG_IGN);
	(void) signal(SIGQUIT, SIG_IGN);
	(void) signal(SIGTERM, SIG_IGN);
    }
    (void) signal(SIGPIPE, Exit);
#else /* SYSV */
    signal(SIGINT, Exit);
    signal(SIGQUIT, Exit);
    signal(SIGTERM, Exit);
    signal(SIGPIPE, Exit);
#endif /* USE_SYSV_SIGNALS and not SIGTSTP */
#ifdef NO_LEAKS
    if (ok_termcap != True)
	free(TermName);
#endif

    return 0;
}				/* end spawnXTerm */

void
Exit(int n)
{
    XtermWidget xw = term;
    TScreen *screen = TScreenOf(xw);

#ifdef USE_UTEMPTER
    DEBUG_MSG("handle:Exit USE_UTEMPTER\n");
    if (!resource.utmpInhibit && added_utmp_entry) {
	TRACE(("...calling removeFromUtmp\n"));
	removeFromUtmp();
    }
#elif defined(HAVE_UTMP)
#ifdef USE_SYSV_UTMP
    struct UTMP_STR utmp;
    struct UTMP_STR *utptr;

    DEBUG_MSG("handle:Exit USE_SYSV_UTMP\n");
    /* don't do this more than once */
    if (xterm_exiting) {
	exit(n);
    }
    xterm_exiting = True;

#ifdef PUCC_PTYD
    closepty(ttydev, ptydev, (resource.utmpInhibit ? OPTY_NOP : OPTY_LOGIN), screen->respond);
#endif /* PUCC_PTYD */

    /* cleanup the utmp entry we forged earlier */
    if (!resource.utmpInhibit
#if OPT_PTY_HANDSHAKE		/* without handshake, no way to know */
	&& (resource.ptyHandshake && added_utmp_entry)
#endif /* OPT_PTY_HANDSHAKE */
	) {
#if defined(USE_UTMP_SETGID)
	setEffectiveGroup(save_egid);
	TRACE_IDS;
#endif
	init_utmp(USER_PROCESS, &utmp);
	(void) call_setutent();

	/*
	 * We could use getutline() if we didn't support old systems.
	 */
	while ((utptr = find_utmp(&utmp)) != 0) {
	    if (utptr->ut_pid == screen->pid) {
		utptr->ut_type = DEAD_PROCESS;
#if defined(HAVE_UTMP_UT_XTIME)
#if defined(HAVE_UTMP_UT_SESSION)
		utptr->ut_session = getsid(0);
#endif
		utptr->ut_xtime = time((time_t *) 0);
		utptr->ut_tv.tv_usec = 0;
#else
		*utptr->ut_user = 0;
		utptr->ut_time = time((time_t *) 0);
#endif
		(void) call_pututline(utptr);
#ifdef WTMP
#if defined(WTMPX_FILE) && (defined(SVR4) || defined(__SCO__))
		if (xw->misc.login_shell)
		    updwtmpx(WTMPX_FILE, utptr);
#elif defined(linux) && defined(__GLIBC__) && (__GLIBC__ >= 2) && !(defined(__powerpc__) && (__GLIBC__ == 2) && (__GLIBC_MINOR__ == 0))
		copy_filled(utmp.ut_line, utptr->ut_line, sizeof(utmp.ut_line));
		if (xw->misc.login_shell)
		    call_updwtmp(etc_wtmp, utptr);
#else
		/* set wtmp entry if wtmp file exists */
		if (xw->misc.login_shell) {
		    int fd;
		    if ((fd = open(etc_wtmp, O_WRONLY | O_APPEND)) >= 0) {
			IGNORE_RC(write(fd, utptr, sizeof(*utptr)));
			close(fd);
		    }
		}
#endif
#endif
		break;
	    }
	    memset(utptr, 0, sizeof(*utptr));	/* keep searching */
	}
	(void) call_endutent();
#ifdef USE_UTMP_SETGID
	disableSetGid();
	TRACE_IDS;
#endif
    }
#else /* not USE_SYSV_UTMP */
    int wfd;
    struct utmp utmp;

    DEBUG_MSG("handle:Exit !USE_SYSV_UTMP\n");
    if (!resource.utmpInhibit && added_utmp_entry &&
	(am_slave < 0 && tslot > 0)) {
#if defined(USE_UTMP_SETGID)
	setEffectiveGroup(save_egid);
	TRACE_IDS;
#endif
	if ((wfd = open(etc_utmp, O_WRONLY)) >= 0) {
	    memset(&utmp, 0, sizeof(utmp));
	    lseek(wfd, (long) (tslot * sizeof(utmp)), 0);
	    IGNORE_RC(write(wfd, (char *) &utmp, sizeof(utmp)));
	    close(wfd);
	}
#ifdef WTMP
	if (xw->misc.login_shell &&
	    (wfd = open(etc_wtmp, O_WRONLY | O_APPEND)) >= 0) {
	    copy_filled(utmp.ut_line,
			my_pty_name(ttydev),
			sizeof(utmp.ut_line));
	    utmp.ut_time = time((time_t *) 0);
	    IGNORE_RC(write(wfd, (char *) &utmp, sizeof(utmp)));
	    close(wfd);
	}
#endif /* WTMP */
#ifdef USE_UTMP_SETGID
	disableSetGid();
	TRACE_IDS;
#endif
    }
#endif /* USE_SYSV_UTMP */
#endif /* HAVE_UTMP */

    cleanup_colored_cursor();

    /*
     * Flush pending data before releasing ownership, so nobody else can write
     * in the middle of the data.
     */
    ttyFlush(screen->respond);

#ifdef USE_PTY_SEARCH
    if (am_slave < 0) {
	TRACE_IDS;
	/* restore ownership of tty and pty */
	set_owner(ttydev, 0, 0, 0666U);
#if (defined(USE_PTY_DEVICE) && !defined(__sgi) && !defined(__hpux))
	set_owner(ptydev, 0, 0, 0666U);
#endif
    }
#endif

    /*
     * Close after releasing ownership to avoid race condition: other programs
     * grabbing it, and *then* having us release ownership....
     */
    close(screen->respond);	/* close explicitly to avoid race with slave side */
#ifdef ALLOWLOGGING
    if (screen->logging)
	CloseLog(xw);
#endif

    xtermPrintOnXError(xw, n);

#ifdef NO_LEAKS
    if (n == 0) {
	Display *dpy = TScreenOf(xw)->display;

	TRACE(("Freeing memory leaks\n"));

	if (toplevel) {
	    XtDestroyWidget(toplevel);
	    TRACE(("destroyed top-level widget\n"));
	}
	sortedOpts(0, 0, 0);
	noleaks_charproc();
	noleaks_ptydata();
#if OPT_GRAPHICS
	noleaks_graphics();
#endif
#if OPT_WIDE_CHARS
	noleaks_CharacterClass();
#endif
	/* XrmSetDatabase(dpy, 0); increases leaks ;-) */
	XtCloseDisplay(dpy);
	XtDestroyApplicationContext(app_con);
	xtermCloseSession();
	TRACE(("closed display\n"));

	TRACE_CLOSE();
    }
#endif

    exit(n);
}

/* ARGSUSED */
static void
resize_termcap(XtermWidget xw)
{
    char *newtc = get_tcap_buffer(xw);

#ifndef USE_SYSV_ENVVARS
    if (!TEK4014_ACTIVE(xw) && *newtc) {
	TScreen *screen = TScreenOf(xw);
	char *ptr1, *ptr2;
	size_t i;
	int li_first = 0;
	char *temp;
	char oldtc[TERMCAP_SIZE];

	strcpy(oldtc, newtc);
	TRACE(("resize %s\n", oldtc));
	if ((ptr1 = x_strindex(oldtc, "co#")) == NULL) {
	    strcat(oldtc, "co#80:");
	    ptr1 = x_strindex(oldtc, "co#");
	}
	if ((ptr2 = x_strindex(oldtc, "li#")) == NULL) {
	    strcat(oldtc, "li#24:");
	    ptr2 = x_strindex(oldtc, "li#");
	}
	if (ptr1 > ptr2) {
	    li_first++;
	    temp = ptr1;
	    ptr1 = ptr2;
	    ptr2 = temp;
	}
	ptr1 += 3;
	ptr2 += 3;
	strncpy(newtc, oldtc, i = (size_t) (ptr1 - oldtc));
	temp = newtc + i;
	sprintf(temp, "%d", (li_first
			     ? MaxRows(screen)
			     : MaxCols(screen)));
	temp += strlen(temp);
	if ((ptr1 = strchr(ptr1, ':')) != 0 && (ptr1 < ptr2)) {
	    strncpy(temp, ptr1, i = (size_t) (ptr2 - ptr1));
	    temp += i;
	    sprintf(temp, "%d", (li_first
				 ? MaxCols(screen)
				 : MaxRows(screen)));
	    if ((ptr2 = strchr(ptr2, ':')) != 0) {
		strcat(temp, ptr2);
	    }
	}
	TRACE(("   ==> %s\n", newtc));
	TRACE(("   new size %dx%d\n", MaxRows(screen), MaxCols(screen)));
    }
#endif /* USE_SYSV_ENVVARS */
}

#endif /* ! VMS */

/*
 * Does a non-blocking wait for a child process.  If the system
 * doesn't support non-blocking wait, do nothing.
 * Returns the pid of the child, or 0 or -1 if none or error.
 */
int
nonblocking_wait(void)
{
#ifdef USE_POSIX_WAIT
    pid_t pid;

    pid = waitpid(-1, NULL, WNOHANG);
#elif defined(USE_SYSV_SIGNALS) && (defined(CRAY) || !defined(SIGTSTP))
    /* cannot do non-blocking wait */
    int pid = 0;
#else /* defined(USE_SYSV_SIGNALS) && (defined(CRAY) || !defined(SIGTSTP)) */
#if defined(Lynx)
    int status;
#else
    union wait status;
#endif
    int pid;

    pid = wait3(&status, WNOHANG, (struct rusage *) NULL);
#endif /* USE_POSIX_WAIT else */
    return pid;
}

#ifndef VMS

/* ARGSUSED */
static void
reapchild(int n GCC_UNUSED)
{
    int olderrno = errno;
    int pid;

    DEBUG_MSG("handle:reapchild\n");

    pid = wait(NULL);

#ifdef USE_SYSV_SIGNALS
    /* cannot re-enable signal before waiting for child
     * because then SVR4 loops.  Sigh.  HP-UX 9.01 too.
     */
    (void) signal(SIGCHLD, reapchild);
#endif

    do {
	if (pid == TScreenOf(term)->pid) {
	    DEBUG_MSG("Exiting\n");
	    if (hold_screen)
		caught_intr = True;
	    else
		need_cleanup = True;
	}
    } while ((pid = nonblocking_wait()) > 0);

    errno = olderrno;
}
#endif /* !VMS */

static void
remove_termcap_entry(char *buf, const char *str)
{
    char *base = buf;
    char *first = base;
    int count = 0;
    size_t len = strlen(str);

    TRACE(("*** remove_termcap_entry('%s', '%s')\n", str, buf));

    while (*buf != 0) {
	if (!count && !strncmp(buf, str, len)) {
	    while (*buf != 0) {
		if (*buf == '\\')
		    buf++;
		else if (*buf == ':')
		    break;
		if (*buf != 0)
		    buf++;
	    }
	    while ((*first++ = *buf++) != 0) {
		;
	    }
	    TRACE(("...removed_termcap_entry('%s', '%s')\n", str, base));
	    return;
	} else if (*buf == '\\') {
	    buf++;
	} else if (*buf == ':') {
	    first = buf;
	    count = 0;
	} else if (!isspace(CharOf(*buf))) {
	    count++;
	}
	if (*buf != 0)
	    buf++;
    }
    TRACE(("...cannot remove\n"));
}

/*
 * parse_tty_modes accepts lines of the following form:
 *
 *         [SETTING] ...
 *
 * where setting consists of the words in the ttyModes[] array followed by a
 * character or ^char.
 */
static int
parse_tty_modes(char *s)
{
    int c;
    Cardinal j, k;
    int count = 0;
    Boolean found;

    TRACE(("parse_tty_modes\n"));
    for (;;) {
	size_t len;

	while (*s && isspace(CharOf(*s))) {
	    s++;
	}
	if (!*s) {
	    return count;
	}

	for (len = 0; s[len] && !isspace(CharOf(s[len])); ++len) {
	    ;
	}
	found = False;
	for (j = 0; j < XtNumber(ttyModes); ++j) {
	    if (len == ttyModes[j].len
		&& strncmp(s,
			   ttyModes[j].name,
			   ttyModes[j].len) == 0) {
		found = True;
		break;
	    }
	}
	if (!found) {
	    return -1;
	}

	s += ttyModes[j].len;
	while (*s && isspace(CharOf(*s))) {
	    s++;
	}

	/* check if this needs a parameter */
	found = False;
	for (k = 0, c = 0; k < XtNumber(ttyChars); ++k) {
	    if ((int) j == ttyChars[k].myMode) {
		if (ttyChars[k].sysMode < 0) {
		    found = True;
		    c = ttyChars[k].myDefault;
		}
		break;
	    }
	}

	if (!found) {
	    if (!*s
		|| (c = decode_keyvalue(&s, False)) == -1) {
		return -1;
	    }
	}
	ttyModes[j].value = c;
	ttyModes[j].set = 1;
	count++;
	TRACE(("...parsed #%d: %s=%#x\n", count, ttyModes[j].name, c));
    }
}

#ifndef VMS			/* don't use pipes on OpenVMS */
int
GetBytesAvailable(int fd)
{
#if defined(FIONREAD)
    int arg;
    ioctl(fd, FIONREAD, (char *) &arg);
    return (int) arg;
#elif defined(__CYGWIN__)
    fd_set set;
    struct timeval select_timeout =
    {0, 0};

    FD_ZERO(&set);
    FD_SET(fd, &set);
    if (Select(fd + 1, &set, NULL, NULL, &select_timeout) > 0)
	return 1;
    else
	return 0;
#elif defined(FIORDCK)
    return (ioctl(fd, FIORDCHK, NULL));
#else /* !FIORDCK */
    struct pollfd pollfds[1];

    pollfds[0].fd = fd;
    pollfds[0].events = POLLIN;
    return poll(pollfds, 1, 0);
#endif
}
#endif /* !VMS */

/* Utility function to try to hide system differences from
   everybody who used to call killpg() */

int
kill_process_group(int pid, int sig)
{
    TRACE(("kill_process_group(pid=%d, sig=%d)\n", pid, sig));
#if defined(SVR4) || defined(SYSV) || !defined(X_NOT_POSIX)
    return kill(-pid, sig);
#else
    return killpg(pid, sig);
#endif
}

#if OPT_EBCDIC
int
A2E(int x)
{
    char c;
    c = x;
    __atoe_l(&c, 1);
    return c;
}

int
E2A(int x)
{
    char c;
    c = x;
    __etoa_l(&c, 1);
    return c;
}
#endif

#if defined(__QNX__) && !defined(__QNXNTO__)
#include <sys/types.h>
#include <sys/proc_msg.h>
#include <sys/kernel.h>
#include <string.h>
#include <errno.h>

struct _proc_session ps;
struct _proc_session_reply rps;

int
qsetlogin(char *login, char *ttyname)
{
    int v = getsid(getpid());

    memset(&ps, 0, sizeof(ps));
    memset(&rps, 0, sizeof(rps));

    ps.type = _PROC_SESSION;
    ps.subtype = _PROC_SUB_ACTION1;
    ps.sid = v;
    strcpy(ps.name, login);

    Send(1, &ps, &rps, sizeof(ps), sizeof(rps));

    if (rps.status < 0)
	return (rps.status);

    ps.type = _PROC_SESSION;
    ps.subtype = _PROC_SUB_ACTION2;
    ps.sid = v;
    sprintf(ps.name, "//%d%s", getnid(), ttyname);
    Send(1, &ps, &rps, sizeof(ps), sizeof(rps));

    return (rps.status);
}
#endif

#ifdef __minix
int
setpgrp(void)
{
    return 0;
}

void
_longjmp(jmp_buf _env, int _val)
{
    longjmp(_env, _val);
}
#endif