summary refs log tree commit diff
path: root/Src/hist.c
blob: 70dfac036c68a0def1396be752ca6f715c8b1a02 (plain) (blame)
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
/*
 * hist.c - history expansion
 *
 * This file is part of zsh, the Z shell.
 *
 * Copyright (c) 1992-1997 Paul Falstad
 * All rights reserved.
 *
 * Permission is hereby granted, without written agreement and without
 * license or royalty fees, to use, copy, modify, and distribute this
 * software and to distribute modified versions of this software for any
 * purpose, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 *
 * In no event shall Paul Falstad or the Zsh Development Group be liable
 * to any party for direct, indirect, special, incidental, or consequential
 * damages arising out of the use of this software and its documentation,
 * even if Paul Falstad and the Zsh Development Group have been advised of
 * the possibility of such damage.
 *
 * Paul Falstad and the Zsh Development Group specifically disclaim any
 * warranties, including, but not limited to, the implied warranties of
 * merchantability and fitness for a particular purpose.  The software
 * provided hereunder is on an "as is" basis, and Paul Falstad and the
 * Zsh Development Group have no obligation to provide maintenance,
 * support, updates, enhancements, or modifications.
 *
 */

#include "zsh.mdh"
#include "hist.pro"

/* Functions to call for getting/ungetting a character and for history
 * word control. */

/**/
mod_export int (*hgetc) _((void));

/**/
void (*hungetc) _((int));

/**/
void (*hwaddc) _((int));

/**/
void (*hwbegin) _((int));

/**/
void (*hwend) _((void));

/**/
void (*addtoline) _((int));

/* != 0 means history substitution is turned off */
 
/**/
mod_export int stophist;

/* if != 0, we are expanding the current line */

/**/
mod_export int expanding;

/* these are used to modify the cursor position during expansion */

/**/
mod_export int excs, exlast;

/*
 * Current history event number
 *
 * Note on curhist: with history inactive, this points to the
 * last line actually added to the history list.  With history active,
 * the line does not get added to the list until hend(), if at all.
 * However, curhist is incremented to reflect the current line anyway
 * and a temporary history entry is inserted while the user is editing.
 * If the resulting line was not added to the list, a flag is set so
 * that curhist will be decremented in hbegin().
 *
 * Note curhist is passed to zle on variable length argument list:
 * type must match that retrieved in zle_main_entry.
 */
 
/**/
mod_export zlong curhist;

/**/
struct histent curline;

/* current line count of allocated history entries */

/**/
zlong histlinect;

/* The history lines are kept in a hash, and also doubly-linked in a ring */

/**/
HashTable histtab;
/**/
mod_export Histent hist_ring;
 
/* capacity of history lists */
 
/**/
zlong histsiz;
 
/* desired history-file size (in lines) */
 
/**/
zlong savehistsiz;
 
/* if = 1, we have performed history substitution on the current line *
 * if = 2, we have used the 'p' modifier                              */
 
/**/
int histdone;
 
/* state of the history mechanism */
 
/**/
int histactive;

/* Current setting of the associated option, but sometimes also includes
 * the setting of the HIST_SAVE_NO_DUPS option. */

/**/
int hist_ignore_all_dups;

/* What flags (if any) we should skip when moving through the history */

/**/
mod_export int hist_skip_flags;

/* Bits of histactive variable */
#define HA_ACTIVE	(1<<0)	/* History mechanism is active */
#define HA_NOINC	(1<<1)	/* Don't store, curhist not incremented */
#define HA_INWORD       (1<<2)  /* We're inside a word, don't add
				   start and end markers */

/* Array of word beginnings and endings in current history line. */

/**/
short *chwords;

/* Max, actual position in chwords.
 * nwords = chwordpos/2 because we record beginning and end of words.
 */

/**/
int chwordlen, chwordpos;

/* the last l for s/l/r/ history substitution */
 
/**/
char *hsubl;

/* the last r for s/l/r/ history substitution */
 
/**/
char *hsubr;
 
/* pointer into the history line */
 
/**/
mod_export char *hptr;
 
/* the current history line */
 
/**/
mod_export char *chline;

/*
 * The current history line as seen by ZLE.
 * We modify chline for use in other contexts while ZLE may
 * still be running; ZLE should see only the top-level value.
 *
 * To avoid having to modify this every time we modify chline,
 * we set it when we push the stack, and unset it when we pop
 * the appropriate value off the stack.  As it's never modified
 * on the stack this is the only maintainance we ever do on it.
 * In return, ZLE has to check both zle_chline and (if that's
 * NULL) chline to get the current value.
 */

/**/
mod_export char *zle_chline;

/* true if the last character returned by hgetc was an escaped bangchar *
 * if it is set and NOBANGHIST is unset hwaddc escapes bangchars        */

/**/
int qbang;
 
/* max size of histline */
 
/**/
int hlinesz;
 
/* default event (usually curhist-1, that is, "!!") */
 
static zlong defev;

/* Remember the last line in the history file so we can find it again. */
static struct histfile_stats {
    char *text;
    time_t stim, mtim;
    off_t fpos, fsiz;
    zlong next_write_ev;
} lasthist;

static struct histsave {
    struct histfile_stats lasthist;
    char *histfile;
    HashTable histtab;
    Histent hist_ring;
    zlong curhist;
    zlong histlinect;
    zlong histsiz;
    zlong savehistsiz;
    int locallevel;
} *histsave_stack;
static int histsave_stack_size = 0;
static int histsave_stack_pos = 0;

static zlong histfile_linect;

/* save history context */

/**/
void
hist_context_save(struct hist_stack *hs, int toplevel)
{
    if (toplevel) {
	/* top level, make this version visible to ZLE */
	zle_chline = chline;
	/* ensure line stored is NULL-terminated */
	if (hptr)
	    *hptr = '\0';
    }
    hs->histactive = histactive;
    hs->histdone = histdone;
    hs->stophist = stophist;
    hs->hline = chline;
    hs->hptr = hptr;
    hs->chwords = chwords;
    hs->chwordlen = chwordlen;
    hs->chwordpos = chwordpos;
    hs->hwgetword = hwgetword;
    hs->hgetc = hgetc;
    hs->hungetc = hungetc;
    hs->hwaddc = hwaddc;
    hs->hwbegin = hwbegin;
    hs->hwend = hwend;
    hs->addtoline = addtoline;
    hs->hlinesz = hlinesz;
    /*
     * We save and restore the command stack with history
     * as it's visible to the user interactively, so if
     * we're preserving history state we'll continue to
     * show the current set of commands from input.
     */
    hs->cstack = cmdstack;
    hs->csp = cmdsp;

    stophist = 0;
    chline = NULL;
    hptr = NULL;
    histactive = 0;
    cmdstack = (unsigned char *)zalloc(CMDSTACKSZ);
    cmdsp = 0;
}

/* restore history context */

/**/
void
hist_context_restore(const struct hist_stack *hs, int toplevel)
{
    if (toplevel) {
	/* Back to top level: don't need special ZLE value */
	DPUTS(hs->hline != zle_chline, "BUG: Ouch, wrong chline for ZLE");
	zle_chline = NULL;
    }
    histactive = hs->histactive;
    histdone = hs->histdone;
    stophist = hs->stophist;
    chline = hs->hline;
    hptr = hs->hptr;
    chwords = hs->chwords;
    chwordlen = hs->chwordlen;
    chwordpos = hs->chwordpos;
    hwgetword = hs->hwgetword;
    hgetc = hs->hgetc;
    hungetc = hs->hungetc;
    hwaddc = hs->hwaddc;
    hwbegin = hs->hwbegin;
    hwend = hs->hwend;
    addtoline = hs->addtoline;
    hlinesz = hs->hlinesz;
    if (cmdstack)
	zfree(cmdstack, CMDSTACKSZ);
    cmdstack = hs->cstack;
    cmdsp = hs->csp;
}

/*
 * Mark that the current level of history is within a word whatever
 * characters turn up, or turn that mode off.  This is used for nested
 * parsing of substitutions.
 *
 * The caller takes care only to turn this on or off at the start
 * or end of recursive use of the same mode, so a single flag is
 * good enough here.
 */

/**/
void
hist_in_word(int yesno)
{
    if (yesno)
	histactive |= HA_INWORD;
    else
	histactive &= ~HA_INWORD;
}

/* add a character to the current history word */

static void
ihwaddc(int c)
{
    /* Only if history line exists and lexing has not finished. */
    if (chline && !(errflag || lexstop) &&
	/*
	 * If we're reading inside a word for command substitution
	 * we allow the lexer to expand aliases but don't deal
	 * with them here.  Note matching code in ihungetc().
	 * TBD: it might be neater to deal with all aliases in this
	 * fashion as we never need the expansion in the history
	 * line, only in the lexer and above.
	 */
	!((histactive & HA_INWORD) &&
	  (inbufflags & (INP_ALIAS|INP_HIST)) == INP_ALIAS)) {
	/* Quote un-expanded bangs in the history line. */
	if (c == bangchar && stophist < 2 && qbang)
	    /* If qbang is not set, we do not escape this bangchar as it's *
	     * not necessary (e.g. it's a bang in !=, or it is followed    *
	     * by a space). Roughly speaking, qbang is zero only if the    *
	     * history interpreter has already digested this bang and      *
	     * found that it is not necessary to escape it.                */
	    hwaddc('\\');
	*hptr++ = c;

	/* Resize history line if necessary */
	if (hptr - chline >= hlinesz) {
	    int oldsiz = hlinesz;

	    chline = realloc(chline, hlinesz = oldsiz + 64);
	    hptr = chline + oldsiz;
	}
    }
}

/* This function adds a character to the zle input line. It is used when *
 * zsh expands history (see doexpandhist() in zle_tricky.c). It also     *
 * calculates the new cursor position after the expansion. It is called  *
 * from hgetc() and from gettok() in lex.c for characters in comments.   */

/**/
void
iaddtoline(int c)
{
    if (!expanding || lexstop)
	return;
    if (qbang && c == bangchar && stophist < 2) {
	exlast--;
	zleentry(ZLE_CMD_ADD_TO_LINE, '\\');
    }
    if (excs > zlemetacs) {
	excs += 1 + inbufct - exlast;
	if (excs < zlemetacs)
	    /* this case could be handled better but it is    *
	     * so rare that it does not worth it              */
	    excs = zlemetacs;
    }
    exlast = inbufct;
    zleentry(ZLE_CMD_ADD_TO_LINE, itok(c) ? ztokens[c - Pound] : c);
}


static int
ihgetc(void)
{
    int c = ingetc();

    qbang = 0;
    if (!stophist && !(inbufflags & INP_ALIAS)) {
	/* If necessary, expand history characters. */
	c = histsubchar(c);
	if (c < 0) {
	    /* bad expansion */
	    lexstop = 1;
	    errflag |= ERRFLAG_ERROR;
	    return ' ';
	}
    }
    if ((inbufflags & INP_HIST) && !stophist) {
	/* the current character c came from a history expansion          *
	 * (inbufflags & INP_HIST) and history is not disabled            *
	 * (e.g. we are not inside single quotes). In that case, \!       *
	 * should be treated as ! (since this \! came from a previous     *
	 * history line where \ was used to escape the bang). So if       *
	 * c == '\\' we fetch one more character to see if it's a bang,   *
	 * and if it is not, we unget it and reset c back to '\\'         */
	qbang = 0;
	if (c == '\\' && !(qbang = (c = ingetc()) == bangchar))
	    safeinungetc(c), c = '\\';
    } else if (stophist || (inbufflags & INP_ALIAS))
	/* If the result is a bangchar which came from history or alias  *
	 * expansion, we treat it as an escaped bangchar, unless history *
	 * is disabled. If stophist == 1 it only means that history is   *
	 * temporarily disabled by a !" which won't appear in the        *
	 * history, so we still have an escaped bang. stophist > 1 if    *
	 * history is disabled with NOBANGHIST or by someone else (e.g.  *
	 * when the lexer scans single quoted text).                     */
	qbang = c == bangchar && (stophist < 2);
    hwaddc(c);
    addtoline(c);

    return c;
}

/**/
static void
safeinungetc(int c)
{
    if (lexstop)
	lexstop = 0;
    else
	inungetc(c);
}

/**/
void
herrflush(void)
{
    inpopalias();

    while (!lexstop && inbufct && !strin)
	hwaddc(ingetc());
}

/*
 * Extract :s/foo/bar/ delimiters and arguments
 *
 * The first character expected is the first delimiter.
 * The arguments are stored in the hsubl and hsubr variables.
 *
 * subline is the part of the command line to be matched.
 *
 * If a ':' was found but was not followed by a 'G',
 * *cflagp is set to 1 and the input is backed up to the
 * character following the colon.
 */

/**/
static int
getsubsargs(char *subline, int *gbalp, int *cflagp)
{
    int del, follow;
    char *ptr1, *ptr2;

    del = ingetc();
    ptr1 = hdynread2(del);
    if (!ptr1)
	return 1;
    ptr2 = hdynread2(del);
    if (strlen(ptr1)) {
	zsfree(hsubl);
	hsubl = ptr1;
    } else if (!hsubl) {		/* fail silently on this */
	zsfree(ptr1);
	zsfree(ptr2);
	return 0;
    }
    zsfree(hsubr);
    hsubr = ptr2;
    follow = ingetc();
    if (follow == ':') {
	follow = ingetc();
	if (follow == 'G')
	    *gbalp = 1;
	else {
	    inungetc(follow);
	    *cflagp = 1;
	}
    } else
	inungetc(follow);
    return 0;
}

/* Get the maximum no. of words for a history entry. */

/**/
static int
getargc(Histent ehist)
{
    return ehist->nwords ? ehist->nwords-1 : 0;
}

/**/
static int
substfailed(void)
{
    herrflush();
    zerr("substitution failed");
    return -1;
}

/* Perform history substitution, returning the next character afterwards. */

/**/
static int
histsubchar(int c)
{
    int farg, evset = -1, larg, argc, cflag = 0, bflag = 0;
    zlong ev;
    static int marg = -1;
    static zlong mev = -1;
    char *buf, *ptr;
    char *sline, *lexraw_mark;
    Histent ehist;
    size_t buflen;

    /*
     * If accumulating raw input for use in command substitution,
     * we don't want the history text, so mark it for later removal.
     * It would be better to do this at a level above the history
     * and below the lexer --- but there isn't one.
     *
     * Include the character we are attempting to substitute.
     */
    lexraw_mark = zshlex_raw_mark(-1); 

    /* look, no goto's */
    if (isfirstch && c == hatchar) {
	int gbal = 0;

	/* Line begins ^foo^bar */
	isfirstch = 0;
	inungetc(hatchar);
	if (!(ehist = gethist(defev))
	    || !(sline = getargs(ehist, 0, getargc(ehist))))
	    return -1;

	if (getsubsargs(sline, &gbal, &cflag))
	    return substfailed();
	if (!hsubl)
	    return -1;
	if (subst(&sline, hsubl, hsubr, gbal))
	    return substfailed();
    } else {
	/* Line doesn't begin ^foo^bar */
	if (c != ' ')
	    isfirstch = 0;
	if (c == '\\') {
	    int g = ingetc();

	    if (g != bangchar)
		safeinungetc(g);
	    else {
		qbang = 1;
		return bangchar;
	    }
	}
	if (c != bangchar)
	    return c;
	*hptr = '\0';
	if ((c = ingetc()) == '{') {
	    bflag = cflag = 1;
	    c = ingetc();
	}
	if (c == '\"') {
	    stophist = 1;
	    return ingetc();
	}
	if ((!cflag && inblank(c)) || c == '=' || c == '(' || lexstop) {
	    safeinungetc(c);
	    return bangchar;
	}
	cflag = 0;
	ptr = buf = zhalloc(buflen = 265);

	/* get event number */

	queue_signals();
	if (c == '?') {
	    for (;;) {
		c = ingetc();
		if (c == '?' || c == '\n' || lexstop)
		    break;
		else {
		    *ptr++ = c;
		    if (ptr == buf + buflen) {
			buf = hrealloc(buf, buflen, 2 * buflen);
			ptr = buf + buflen;
			buflen *= 2;
		    }
		}
	    }
	    if (c != '\n' && !lexstop)
		c = ingetc();
	    *ptr = '\0';
	    mev = ev = hconsearch(hsubl = ztrdup(buf), &marg);
	    evset = 0;
	    if (ev == -1) {
		herrflush();
		unqueue_signals();
		zerr("no such event: %s", buf);
		return -1;
	    }
	} else {
	    zlong t0;

	    for (;;) {
		if (inblank(c) || c == ';' || c == ':' || c == '^' ||
		    c == '$' || c == '*' || c == '%' || c == '}' ||
		    c == '\'' || c == '"' || c == '`' || lexstop)
		    break;
		if (ptr != buf) {
		    if (c == '-')
			break;
		    if ((idigit(buf[0]) || buf[0] == '-') && !idigit(c))
			break;
		}
		*ptr++ = c;
		if (ptr == buf + buflen) {
		    buf = hrealloc(buf, buflen, 2 * buflen);
		    ptr = buf + buflen;
		    buflen *= 2;
		}
		if (c == '#' || c == bangchar) {
		    c = ingetc();
		    break;
		}
		c = ingetc();
	    }
	    if (ptr == buf &&
		(c == '}' ||  c == ';' || c == '\'' || c == '"' || c == '`')) {
	      /* Neither event nor word designator, no expansion */
	      safeinungetc(c);
	      return bangchar;
	    }
	    *ptr = 0;
	    if (!*buf) {
		if (c != '%') {
		    if (isset(CSHJUNKIEHISTORY))
			ev = addhistnum(curhist,-1,HIST_FOREIGN);
		    else
			ev = defev;
		    if (c == ':' && evset == -1)
			evset = 0;
		    else
			evset = 1;
		} else {
		    if (marg != -1)
			ev = mev;
		    else
			ev = defev;
		    evset = 0;
		}
	    } else if ((t0 = zstrtol(buf, NULL, 10))) {
		ev = (t0 < 0) ? addhistnum(curhist,t0,HIST_FOREIGN) : t0;
		evset = 1;
	    } else if ((unsigned)*buf == bangchar) {
		ev = addhistnum(curhist,-1,HIST_FOREIGN);
		evset = 1;
	    } else if (*buf == '#') {
		ev = curhist;
		evset = 1;
	    } else if ((ev = hcomsearch(buf)) == -1) {
		herrflush();
		unqueue_signals();
		zerr("event not found: %s", buf);
		return -1;
	    } else
		evset = 1;
	}

	/* get the event */

	if (!(ehist = gethist(defev = ev))) {
	    unqueue_signals();
	    return -1;
	}
	/* extract the relevant arguments */

	argc = getargc(ehist);
	if (c == ':') {
	    cflag = 1;
	    c = ingetc();
	    if (c == '%' && marg != -1) {
		if (!evset) {
		    ehist = gethist(defev = mev);
		    argc = getargc(ehist);
		} else {
		    herrflush();
		    unqueue_signals();
		    zerr("ambiguous history reference");
		    return -1;
		}

	    }
	}
	if (c == '*') {
	    farg = 1;
	    larg = argc;
	    cflag = 0;
	} else {
	    inungetc(c);
	    larg = farg = getargspec(argc, marg, evset);
	    if (larg == -2) {
		unqueue_signals();
		return -1;
	    }
	    if (farg != -1)
		cflag = 0;
	    c = ingetc();
	    if (c == '*') {
		cflag = 0;
		larg = argc;
	    } else if (c == '-') {
		cflag = 0;
		larg = getargspec(argc, marg, evset);
		if (larg == -2) {
		    unqueue_signals();
		    return -1;
		}
		if (larg == -1)
		    larg = argc - 1;
	    } else
		inungetc(c);
	}
	if (farg == -1)
	    farg = 0;
	if (larg == -1)
	    larg = argc;
	if (!(sline = getargs(ehist, farg, larg))) {
	    unqueue_signals();
	    return -1;
	}
	unqueue_signals();
    }

    /* do the modifiers */

    for (;;) {
	c = (cflag) ? ':' : ingetc();
	cflag = 0;
	if (c == ':') {
	    int gbal = 0;

	    if ((c = ingetc()) == 'g') {
		gbal = 1;
		c = ingetc();
		if (c != 's' && c != '&') {
		    zerr("'s' or '&' modifier expected after 'g'");
		    return -1;
		}
	    }
	    switch (c) {
	    case 'p':
		histdone = HISTFLAG_DONE | HISTFLAG_NOEXEC;
		break;
	    case 'a':
		if (!chabspath(&sline)) {
		    herrflush();
		    zerr("modifier failed: a");
		    return -1;
		}
		break;

	    case 'A':
		if (!chrealpath(&sline)) {
		    herrflush();
		    zerr("modifier failed: A");
		    return -1;
		}
		break;
	    case 'c':
		if (!(sline = equalsubstr(sline, 0, 0))) {
		    herrflush();
		    zerr("modifier failed: c");
		    return -1;
		}
		break;
	    case 'h':
		if (!remtpath(&sline)) {
		    herrflush();
		    zerr("modifier failed: h");
		    return -1;
		}
		break;
	    case 'e':
		if (!rembutext(&sline)) {
		    herrflush();
		    zerr("modifier failed: e");
		    return -1;
		}
		break;
	    case 'r':
		if (!remtext(&sline)) {
		    herrflush();
		    zerr("modifier failed: r");
		    return -1;
		}
		break;
	    case 't':
		if (!remlpaths(&sline)) {
		    herrflush();
		    zerr("modifier failed: t");
		    return -1;
		}
		break;
	    case 's':
		if (getsubsargs(sline, &gbal, &cflag))
		    return -1; /* fall through */
	    case '&':
		if (hsubl && hsubr) {
		    if (subst(&sline, hsubl, hsubr, gbal))
			return substfailed();
		} else {
		    herrflush();
		    zerr("no previous substitution");
		    return -1;
		}
		break;
	    case 'q':
		quote(&sline);
		break;
	    case 'Q':
		{
		    int one = noerrs, oef = errflag;

		    noerrs = 1;
		    parse_subst_string(sline);
		    noerrs = one;
		    errflag = oef | (errflag & ERRFLAG_INT);
		    remnulargs(sline);
		    untokenize(sline);
		}
		break;
	    case 'x':
		quotebreak(&sline);
		break;
	    case 'l':
		sline = casemodify(sline, CASMOD_LOWER);
		break;
	    case 'u':
		sline = casemodify(sline, CASMOD_UPPER);
		break;
	    default:
		herrflush();
		zerr("illegal modifier: %c", c);
		return -1;
	    }
	} else {
	    if (c != '}' || !bflag)
		inungetc(c);
	    if (c != '}' && bflag) {
		zerr("'}' expected");
		return -1;
	    }
	    break;
	}
    }

    zshlex_raw_back_to_mark(lexraw_mark);

    /*
     * Push the expanded value onto the input stack,
     * marking this as a history word for purposes of the alias stack.
     */

    lexstop = 0;
    /* this function is called only called from hgetc and only if      *
     * !(inbufflags & INP_ALIAS). History expansion should never be    *
     * done with INP_ALIAS (to prevent recursive history expansion and *
     * histoty expansion of aliases). Escapes are not removed here.    *
     * This is now handled in hgetc.                                   */
    inpush(sline, INP_HIST, NULL); /* sline from heap, don't free */
    histdone |= HISTFLAG_DONE;
    if (isset(HISTVERIFY))
	histdone |= HISTFLAG_NOEXEC | HISTFLAG_RECALL;

    /* Don't try and re-expand line. */
    return ingetc();
}

/* unget a char and remove it from chline. It can only be used *
 * to unget a character returned by hgetc.                     */

static void
ihungetc(int c)
{
    int doit = 1;

    while (!lexstop && !errflag) {
	if (hptr[-1] != (char) c && stophist < 4 &&
	    hptr > chline + 1 && hptr[-1] == '\n' && hptr[-2] == '\\')
	    hungetc('\n'), hungetc('\\');

	if (expanding) {
	    zlemetacs--;
	    zlemetall--;
	    exlast++;
	}
	if (!(histactive & HA_INWORD) ||
	    (inbufflags & (INP_ALIAS|INP_HIST)) != INP_ALIAS) {
	    DPUTS(hptr <= chline, "BUG: hungetc attempted at buffer start");
	    hptr--;
	    DPUTS(*hptr != (char) c, "BUG: wrong character in hungetc() ");
	    qbang = (c == bangchar && stophist < 2 &&
		     hptr > chline && hptr[-1] == '\\');
	} else {
	    /* No active bangs in aliases */
	    qbang = 0;
	}
	if (doit)
	    inungetc(c);
	if (!qbang)
	    return;
	doit = !stophist && ((inbufflags & INP_HIST) ||
				 !(inbufflags & INP_ALIAS));
	c = '\\';
    }
}

/* begin reading a string */

/**/
mod_export void
strinbeg(int dohist)
{
    strin++;
    hbegin(dohist);
    lexinit();
    /*
     * Also initialise some variables owned by the parser but
     * used for communication between the parser and lexer.
     */
    init_parse_status();
}

/* done reading a string */

/**/
mod_export void
strinend(void)
{
    hend(NULL);
    DPUTS(!strin, "BUG: strinend() called without strinbeg()");
    strin--;
    isfirstch = 1;
    histdone = 0;
}

/* dummy functions to use instead of hwaddc(), hwbegin(), and hwend() when
 * they aren't needed */

static void
nohw(UNUSED(int c))
{
}

static void
nohwe(void)
{
}

/* these functions handle adding/removing curline to/from the hist_ring */

static void
linkcurline(void)
{
    if (!hist_ring)
	hist_ring = curline.up = curline.down = &curline;
    else {
	curline.up = hist_ring;
	curline.down = hist_ring->down;
	hist_ring->down = hist_ring->down->up = &curline;
	hist_ring = &curline;
    }
    curline.histnum = ++curhist;
}

static void
unlinkcurline(void)
{
    curline.up->down = curline.down;
    curline.down->up = curline.up;
    if (hist_ring == &curline) {
	if (!histlinect)
	    hist_ring = NULL;
	else
	    hist_ring = curline.up;
    }
    curhist--;
}

/* initialize the history mechanism */

/**/
mod_export void
hbegin(int dohist)
{
    char *hf;

    isfirstln = isfirstch = 1;
    errflag &= ~ERRFLAG_ERROR;
    histdone = 0;
    if (!dohist)
	stophist = 2;
    else if (dohist != 2)
	stophist = (!interact || unset(SHINSTDIN)) ? 2 : 0;
    else
	stophist = 0;
    /*
     * pws: We used to test for "|| (inbufflags & INP_ALIAS)"
     * in this test, but at this point we don't have input
     * set up up so this can trigger unnecessarily.
     * I don't see how the test at this point could ever be
     * useful, since we only get here when we're initialising
     * the history mechanism, before we've done any input.
     *
     * (I also don't see any point where this function is called with
     * dohist=0.)
     */
    if (stophist == 2) {
	chline = hptr = NULL;
	hlinesz = 0;
	chwords = NULL;
	chwordlen = 0;
	hgetc = ingetc;
	hungetc = inungetc;
	hwaddc = nohw;
	hwbegin = nohw;
	hwend = nohwe;
	addtoline = nohw;
    } else {
	chline = hptr = zshcalloc(hlinesz = 64);
	chwords = zalloc((chwordlen = 64) * sizeof(short));
	hgetc = ihgetc;
	hungetc = ihungetc;
	hwaddc = ihwaddc;
	hwbegin = ihwbegin;
	hwend = ihwend;
	addtoline = iaddtoline;
	if (!isset(BANGHIST))
	    stophist = 4;
    }
    chwordpos = 0;

    if (hist_ring && !hist_ring->ftim && !strin)
	hist_ring->ftim = time(NULL);
    if ((dohist == 2 || (interact && isset(SHINSTDIN))) && !strin) {
	histactive = HA_ACTIVE;
	attachtty(mypgrp);
	linkcurline();
	defev = addhistnum(curhist, -1, HIST_FOREIGN);
    } else
	histactive = HA_ACTIVE | HA_NOINC;

    hf = getsparam("HISTFILE");
    /*
     * For INCAPPENDHISTORYTIME, when interactive, save the history here
     * as it gives a better estimate of the times of commands.
     *
     * If INCAPPENDHISTORY is also set we've already done it.
     *
     * If SHAREHISTORY is also set continue to do so in the
     * standard place, because that's safer about reading and
     * rewriting history atomically.
     *
     * The histsave_stack_pos test won't usually fail here.
     * We need to test the opposite for the hend() case because we
     * need to save in the history file we've switched to, but then
     * we pop immediately after that so the variable becomes zero.
     * We will already have saved the line and restored the history
     * so that (correctly) nothing happens here.  But it shows
     * I thought about it.
     */
    if (isset(INCAPPENDHISTORYTIME) && !isset(SHAREHISTORY) &&
	!isset(INCAPPENDHISTORY) &&
	!(histactive & HA_NOINC) && !strin && histsave_stack_pos == 0)
	savehistfile(hf, 0, HFILE_USE_OPTIONS | HFILE_FAST);
}

/**/
void
histreduceblanks(void)
{
    int i, len, pos, needblank, spacecount = 0, trunc_ok;
    char *lastptr, *ptr;

    if (isset(HISTIGNORESPACE))
	while (chline[spacecount] == ' ') spacecount++;

    for (i = 0, len = spacecount; i < chwordpos; i += 2) {
	len += chwords[i+1] - chwords[i]
	     + (i > 0 && chwords[i] > chwords[i-1]);
    }
    if (chline[len] == '\0')
	return;

    /* Remember where the delimited words end */
    if (chwordpos)
	lastptr = chline + chwords[chwordpos-1];
    else
	lastptr = chline;

    for (i = 0, pos = spacecount; i < chwordpos; i += 2) {
	len = chwords[i+1] - chwords[i];
	needblank = (i < chwordpos-2 && chwords[i+2] > chwords[i+1]);
	if (pos != chwords[i]) {
	    memmove(chline + pos, chline + chwords[i], len + needblank);
	    chwords[i] = pos;
	    chwords[i+1] = chwords[i] + len;
	}
	pos += len + needblank;
    }

    /*
     * A terminating comment isn't recorded as a word.
     * Only truncate the line if just whitespace remains.
     */
    trunc_ok = 1;
    for (ptr = lastptr; *ptr; ptr++) {
	if (!inblank(*ptr)) {
	    trunc_ok = 0;
	    break;
	}
    }
    if (trunc_ok) {
	chline[pos] = '\0';
    } else {
	ptr = chline + pos;
	while ((*ptr++ = *lastptr++))
	    ;
    }
}

/**/
void
histremovedups(void)
{
    Histent he, next;
    for (he = hist_ring; he; he = next) {
	next = up_histent(he);
	if (he->node.flags & HIST_DUP)
	    freehistnode(&he->node);
    }
}

/**/
mod_export zlong
addhistnum(zlong hl, int n, int xflags)
{
    int dir = n < 0? -1 : n > 0? 1 : 0;
    Histent he = gethistent(hl, dir);
			     
    if (!he)
	return 0;
    if (he->histnum != hl)
	n -= dir;
    if (n)
	he = movehistent(he, n, xflags);
    if (!he)
	return dir < 0? firsthist() - 1 : curhist + 1;
    return he->histnum;
}

/**/
mod_export Histent
movehistent(Histent he, int n, int xflags)
{
    while (n < 0) {
	if (!(he = up_histent(he)))
	    return NULL;
	if (!(he->node.flags & xflags))
	    n++;
    }
    while (n > 0) {
	if (!(he = down_histent(he)))
	    return NULL;
	if (!(he->node.flags & xflags))
	    n--;
    }
    checkcurline(he);
    return he;
}

/**/
mod_export Histent
up_histent(Histent he)
{
    return !he || he->up == hist_ring? NULL : he->up;
}

/**/
mod_export Histent
down_histent(Histent he)
{
    return he == hist_ring? NULL : he->down;
}

/**/
mod_export Histent
gethistent(zlong ev, int nearmatch)
{
    Histent he;

    if (!hist_ring)
	return NULL;

    if (ev - hist_ring->down->histnum < hist_ring->histnum - ev) {
	for (he = hist_ring->down; he->histnum < ev; he = he->down) ;
	if (he->histnum != ev) {
	    if (nearmatch == 0
	     || (nearmatch < 0 && (he = up_histent(he)) == NULL))
		return NULL;
	}
    }
    else {
	for (he = hist_ring; he->histnum > ev; he = he->up) ;
	if (he->histnum != ev) {
	    if (nearmatch == 0
	     || (nearmatch > 0 && (he = down_histent(he)) == NULL))
		return NULL;
	}
    }

    checkcurline(he);
    return he;
}

static void
putoldhistentryontop(short keep_going)
{
    static Histent next = NULL;
    Histent he = (keep_going || !hist_ring) ? next : hist_ring->down;
    if (he)
	next = he->down;
    else
	return;
    if (isset(HISTEXPIREDUPSFIRST) && !(he->node.flags & HIST_DUP)) {
	static zlong max_unique_ct = 0;
	if (!keep_going)
	    max_unique_ct = savehistsiz;
	do {
	    if (max_unique_ct-- <= 0 || he == hist_ring) {
		max_unique_ct = 0;
		he = hist_ring->down;
		next = hist_ring;
		break;
	    }
	    he = next;
	    next = he->down;
	} while (!(he->node.flags & HIST_DUP));
    }
    if (he != hist_ring->down) {
	he->up->down = he->down;
	he->down->up = he->up;
	he->up = hist_ring;
	he->down = hist_ring->down;
	hist_ring->down = he->down->up = he;
    }
    hist_ring = he;
}

/**/
Histent
prepnexthistent(void)
{
    Histent he; 
    int curline_in_ring = hist_ring == &curline;

    if (curline_in_ring)
	unlinkcurline();
    if (hist_ring && hist_ring->node.flags & HIST_TMPSTORE) {
	curhist--;
	freehistnode(&hist_ring->node);
    }

    if (histlinect < histsiz || !hist_ring) {
	he = (Histent)zshcalloc(sizeof *he);
	if (!hist_ring)
	    hist_ring = he->up = he->down = he;
	else {
	    he->up = hist_ring;
	    he->down = hist_ring->down;
	    hist_ring->down = he->down->up = he;
	    hist_ring = he;
	}
	histlinect++;
    }
    else {
	putoldhistentryontop(0);
	freehistdata(hist_ring, 0);
	he = hist_ring;
    }
    he->histnum = ++curhist;
    if (curline_in_ring)
	linkcurline();
    return he;
}

/* A helper function for hend() */

static int
should_ignore_line(Eprog prog)
{
    if (isset(HISTIGNORESPACE)) {
	if (*chline == ' ' || aliasspaceflag)
	    return 1;
    }

    if (!prog)
	return 0;

    if (isset(HISTNOFUNCTIONS)) {
	Wordcode pc = prog->prog;
	wordcode code = *pc;
	if (wc_code(code) == WC_LIST && WC_LIST_TYPE(code) & Z_SIMPLE
	 && wc_code(pc[2]) == WC_FUNCDEF)
	    return 1;
    }

    if (isset(HISTNOSTORE)) {
	char *b = getjobtext(prog, NULL);
	int saw_builtin;
	if (*b == 'b' && strncmp(b,"builtin ",8) == 0) {
	    b += 8;
	    saw_builtin = 1;
	} else
	    saw_builtin = 0;
	if (*b == 'h' && strncmp(b,"history",7) == 0 && (!b[7] || b[7] == ' ')
	 && (saw_builtin || !shfunctab->getnode(shfunctab,"history")))
	    return 1;
	if (*b == 'r' && (!b[1] || b[1] == ' ')
	 && (saw_builtin || !shfunctab->getnode(shfunctab,"r")))
	    return 1;
	if (*b == 'f' && b[1] == 'c' && b[2] == ' ' && b[3] == '-'
	 && (saw_builtin || !shfunctab->getnode(shfunctab,"fc"))) {
	    b += 3;
	    do {
		if (*++b == 'l')
		    return 1;
	    } while (ialpha(*b));
	}
    }

    return 0;
}

/* say we're done using the history mechanism */

/**/
mod_export int
hend(Eprog prog)
{
    LinkList hookargs = newlinklist();
    int flag, hookret, stack_pos = histsave_stack_pos;
    /*
     * save:
     * 0: don't save
     * 1: save normally
     * -1: save temporarily, delete after next line
     * -2: save internally but mark for not writing
     */
    int save = 1;
    char *hf;

    DPUTS(stophist != 2 && !(inbufflags & INP_ALIAS) && !chline,
	  "BUG: chline is NULL in hend()");
    queue_signals();
    if (histdone & HISTFLAG_SETTY)
	settyinfo(&shttyinfo);
    if (!(histactive & HA_NOINC))
	unlinkcurline();
    if (histactive & HA_NOINC) {
	zfree(chline, hlinesz);
	zfree(chwords, chwordlen*sizeof(short));
	chline = hptr = NULL;
	chwords = NULL;
	histactive = 0;
	unqueue_signals();
	return 1;
    }
    if (hist_ignore_all_dups != isset(HISTIGNOREALLDUPS)
     && (hist_ignore_all_dups = isset(HISTIGNOREALLDUPS)) != 0)
	histremovedups();

    if (hptr) {
	/*
	 * Added the following in case the test "hptr < chline + 1"
	 * is more than just paranoia.
	 */
	DPUTS(hptr < chline, "History end pointer off start of line");
	*hptr = '\0';
    }
    addlinknode(hookargs, "zshaddhistory");
    addlinknode(hookargs, chline);
    callhookfunc("zshaddhistory", hookargs, 1, &hookret);
    /* For history sharing, lock history file once for both read and write */
    hf = getsparam("HISTFILE");
    if (isset(SHAREHISTORY) && !lockhistfile(hf, 0)) {
	readhistfile(hf, 0, HFILE_USE_OPTIONS | HFILE_FAST);
	curline.histnum = curhist+1;
    }
    flag = histdone;
    histdone = 0;
    if (hptr < chline + 1)
	save = 0;
    else {
	if (hptr[-1] == '\n') {
	    if (chline[1]) {
		*--hptr = '\0';
	    } else
		save = 0;
	}
	if (chwordpos <= 2)
	    save = 0;
	else if (should_ignore_line(prog))
	    save = -1;
	else if (hookret == 2)
	    save = -2;
	else if (hookret)
	    save = -1;
    }
    if (flag & (HISTFLAG_DONE | HISTFLAG_RECALL)) {
	char *ptr;

	ptr = ztrdup(chline);
	if ((flag & (HISTFLAG_DONE | HISTFLAG_RECALL)) == HISTFLAG_DONE) {
	    zputs(ptr, shout);
	    fputc('\n', shout);
	    fflush(shout);
	}
	if (flag & HISTFLAG_RECALL) {
	    zpushnode(bufstack, ptr);
	    save = 0;
	} else
	    zsfree(ptr);
    }
    if (save || *chline == ' ') {
	Histent he;
	for (he = hist_ring; he && he->node.flags & HIST_FOREIGN;
	     he = up_histent(he)) ;
	if (he && he->node.flags & HIST_TMPSTORE) {
	    if (he == hist_ring)
		curline.histnum = curhist--;
	    freehistnode(&he->node);
	}
    }
    if (save) {
	Histent he;
	int newflags;

#ifdef DEBUG
	/* debugging only */
	if (chwordpos%2) {
	    hwend();
	    DPUTS(1, "BUG: uncompleted line in history");
	}
#endif
	/* get rid of pesky \n which we've already nulled out */
	if (chwordpos > 1 && !chline[chwords[chwordpos-2]]) {
	    chwordpos -= 2;
	    /* strip superfluous blanks, if desired */
	    if (isset(HISTREDUCEBLANKS))
		histreduceblanks();
	}
	if (save == -1)
	    newflags = HIST_TMPSTORE;
	else if (save == -2)
	    newflags = HIST_NOWRITE;
	else
	    newflags = 0;
	if ((isset(HISTIGNOREDUPS) || isset(HISTIGNOREALLDUPS)) && save > 0
	 && hist_ring && histstrcmp(chline, hist_ring->node.nam) == 0) {
	    /* This history entry compares the same as the previous.
	     * In case minor changes were made, we overwrite the
	     * previous one with the current one.  This also gets the
	     * timestamp right.  Perhaps, preserve the HIST_OLD flag.
	     */
	    he = hist_ring;
	    newflags |= he->node.flags & HIST_OLD; /* Avoid re-saving */
	    freehistdata(he, 0);
	    curline.histnum = curhist;
	} else
	    he = prepnexthistent();

	he->node.nam = ztrdup(chline);
	he->stim = time(NULL);
	he->ftim = 0L;
	he->node.flags = newflags;

	if ((he->nwords = chwordpos/2)) {
	    he->words = (short *)zalloc(chwordpos * sizeof(short));
	    memcpy(he->words, chwords, chwordpos * sizeof(short));
	}
	if (!(newflags & HIST_TMPSTORE))
	    addhistnode(histtab, he->node.nam, he);
    }
    zfree(chline, hlinesz);
    zfree(chwords, chwordlen*sizeof(short));
    chline = hptr = NULL;
    chwords = NULL;
    histactive = 0;
    /*
     * For normal INCAPPENDHISTORY case and reasoning, see hbegin().
     */
    if (isset(SHAREHISTORY) ? histfileIsLocked() :
	(isset(INCAPPENDHISTORY) || (isset(INCAPPENDHISTORYTIME) &&
				     histsave_stack_pos != 0)))
	savehistfile(hf, 0, HFILE_USE_OPTIONS | HFILE_FAST);
    unlockhistfile(hf); /* It's OK to call this even if we aren't locked */
    /*
     * No good reason for the user to push the history more than once, but
     * it's easy to be tidy...
     */
    while (histsave_stack_pos > stack_pos)
	pophiststack();
    unqueue_signals();
    return !(flag & HISTFLAG_NOEXEC || errflag);
}

/* Gives current expansion word if not last word before chwordpos. */

/**/
int hwgetword = -1;

/* begin a word */

/**/
void
ihwbegin(int offset)
{
    if (stophist == 2 || (histactive & HA_INWORD))
	return;
    if (chwordpos%2)
	chwordpos--;	/* make sure we're on a word start, not end */
    /* If we're expanding an alias, we should overwrite the expansion
     * in the history.
     */
    if ((inbufflags & INP_ALIAS) && !(inbufflags & INP_HIST))
	hwgetword = chwordpos;
    else
	hwgetword = -1;
    chwords[chwordpos++] = hptr - chline + offset;
}

/* add a word to the history List */

/**/
void
ihwend(void)
{
    if (stophist == 2 || (histactive & HA_INWORD))
	return;
    if (chwordpos%2 && chline) {
	/* end of word reached and we've already begun a word */
	if (hptr > chline + chwords[chwordpos-1]) {
	    chwords[chwordpos++] = hptr - chline;
	    if (chwordpos >= chwordlen) {
		chwords = (short *) realloc(chwords,
					    (chwordlen += 32) * 
					    sizeof(short));
	    }
	    if (hwgetword > -1 &&
		(inbufflags & INP_ALIAS) && !(inbufflags & INP_HIST)) {
		/* We want to reuse the current word position */
		chwordpos = hwgetword;
		/* Start from where previous word ended, if possible */
		hptr = chline + chwords[chwordpos ? chwordpos - 1 : 0];
	    }
	} else {
	    /* scrub that last word, it doesn't exist */
	    chwordpos--;
	}
    }
}

/* Go back to immediately after the last word, skipping space. */

/**/
void
histbackword(void)
{
    if (!(chwordpos%2) && chwordpos)
	hptr = chline + chwords[chwordpos-1];
}

/* Get the start and end point of the current history word */

/**/
static void
hwget(char **startptr)
{
    int pos = hwgetword > -1 ? hwgetword : chwordpos - 2;

#ifdef DEBUG
    /* debugging only */
    if (hwgetword == -1 && !chwordpos) {
	/* no words available */
	DPUTS(1, "BUG: hwget() called with no words");
	*startptr = "";
	return;
    } 
    else if (hwgetword == -1 && chwordpos%2) {
	DPUTS(1, "BUG: hwget() called in middle of word");
	*startptr = "";
	return;
    }
#endif

    *startptr = chline + chwords[pos];
    chline[chwords[++pos]] = '\0';
}

/* Replace the current history word with rep, if different */

/**/
void
hwrep(char *rep)
{
    char *start;
    hwget(&start);

    if (!strcmp(rep, start))
	return;
    
    hptr = start;
    chwordpos = (hwgetword > -1) ? hwgetword : chwordpos - 2;
    hwbegin(0);
    qbang = 1;
    while (*rep)
	hwaddc(*rep++);
    hwend();
}

/* Get the entire current line, deleting it in the history. */

/**/
mod_export char *
hgetline(void)
{
    /* Currently only used by pushlineoredit().
     * It's necessary to prevent that from getting too pally with
     * the history code.
     */
    char *ret;

    if (!chline || hptr == chline)
	return NULL;
    *hptr = '\0';
    ret = dupstring(chline);

    /* reset line */
    hptr = chline;
    chwordpos = 0;
    hwgetword = -1;

    return ret;
}

/* get an argument specification */

/**/
static int
getargspec(int argc, int marg, int evset)
{
    int c, ret = -1;

    if ((c = ingetc()) == '0')
	return 0;
    if (idigit(c)) {
	ret = 0;
	while (idigit(c)) {
	    ret = ret * 10 + c - '0';
	    c = ingetc();
	}
	inungetc(c);
    } else if (c == '^')
	ret = 1;
    else if (c == '$')
	ret = argc;
    else if (c == '%') {
	if (evset) {
	    herrflush();
	    zerr("Ambiguous history reference");
	    return -2;
	}
	if (marg == -1) {
	    herrflush();
	    zerr("%% with no previous word matched");
	    return -2;
	}
	ret = marg;
    } else
	inungetc(c);
    return ret;
}

/* do ?foo? search */

/**/
static zlong
hconsearch(char *str, int *marg)
{
    int t1 = 0;
    char *s;
    Histent he;

    for (he = up_histent(hist_ring); he; he = up_histent(he)) {
	if (he->node.flags & HIST_FOREIGN)
	    continue;
	if ((s = strstr(he->node.nam, str))) {
	    int pos = s - he->node.nam;
	    while (t1 < he->nwords && he->words[2*t1] <= pos)
		t1++;
	    *marg = t1 - 1;
	    return he->histnum;
	}
    }
    return -1;
}

/* do !foo search */

/**/
zlong
hcomsearch(char *str)
{
    Histent he;
    int len = strlen(str);

    for (he = up_histent(hist_ring); he; he = up_histent(he)) {
	if (he->node.flags & HIST_FOREIGN)
	    continue;
	if (strncmp(he->node.nam, str, len) == 0)
	    return he->histnum;
    }
    return -1;
}

/* various utilities for : modifiers */

/**/
int
chabspath(char **junkptr)
{
    char *current, *dest;

    if (!**junkptr)
	return 1;

    if (**junkptr != '/') {
	*junkptr = zhtricat(metafy(zgetcwd(), -1, META_HEAPDUP), "/", *junkptr);
    }

    current = *junkptr;
    dest = *junkptr;

#ifdef HAVE_SUPERROOT
    while (*current == '/' && current[1] == '.' && current[2] == '.' &&
	   (!current[3] || current[3] == '/')) {
	*dest++ = '/';
	*dest++ = '.';
	*dest++ = '.';
	current += 3;
    }
#endif

    for (;;) {
	if (*current == '/') {
#ifdef __CYGWIN__
	    if (current == *junkptr && current[1] == '/')
		*dest++ = *current++;
#endif
	    *dest++ = *current++;
	    while (*current == '/')
		current++;
	} else if (!*current) {
	    while (dest > *junkptr + 1 && dest[-1] == '/')
		dest--;
	    *dest = '\0';
	    break;
	} else if (current[0] == '.' && current[1] == '.' &&
		   (!current[2] || current[2] == '/')) {
		if (current == *junkptr || dest == *junkptr) {
		    *dest++ = '.';
		    *dest++ = '.';
		    current += 2;
		} else if (dest > *junkptr + 2 &&
			   !strncmp(dest - 3, "../", 3)) {
		    *dest++ = '.';
		    *dest++ = '.';
		    current += 2;
		} else if (dest > *junkptr + 1) {
		    *dest = '\0';
		    for (dest--;
			 dest > *junkptr + 1 && dest[-1] != '/';
			 dest--);
		    if (dest[-1] != '/')
			dest--;
		    current += 2;
		    if (*current == '/')
			current++;
		} else if (dest == *junkptr + 1) {
		    /* This might break with Cygwin's leading double slashes? */
		    current += 2;
		} else {
		    return 0;
		}
	} else if (current[0] == '.' && (current[1] == '/' || !current[1])) {
	     while (*++current == '/');
	} else {
	    while (*current != '/' && *current != '\0')
		if ((*dest++ = *current++) == Meta)
		    *dest++ = *current++;
	}
    }
    return 1;
}

/**/
int
chrealpath(char **junkptr)
{
    char *str;
#ifdef HAVE_REALPATH
# ifdef REALPATH_ACCEPTS_NULL
    char *lastpos, *nonreal, *real;
# else
    char *lastpos, *nonreal, pathbuf[PATH_MAX];
    char *real = pathbuf;
# endif
#endif

    if (!**junkptr)
	return 1;

    /* Notice that this means ..'s are applied before symlinks are resolved! */
    if (!chabspath(junkptr))
	return 0;

#ifndef HAVE_REALPATH
    return 1;
#else
    /*
     * Notice that this means you cannot pass relative paths into this
     * function!
     */
    if (**junkptr != '/')
	return 0;

    unmetafy(*junkptr, NULL);

    lastpos = strend(*junkptr);
    nonreal = lastpos + 1;

    while (!
#ifdef REALPATH_ACCEPTS_NULL
	   /* realpath() with a NULL second argument uses malloc() to get
	    * memory so we don't need to worry about overflowing PATH_MAX */
	   (real = realpath(*junkptr, NULL))
#else
	   realpath(*junkptr, real)
#endif
	) {
	if (errno == EINVAL || errno == ENOMEM)
	    return 0;

	if (nonreal == *junkptr) {
#ifndef REALPATH_ACCEPTS_NULL
	    real = NULL;
#endif
	    break;
	}

	while (*nonreal != '/' && nonreal >= *junkptr)
	    nonreal--;
	*nonreal = '\0';
    }

    str = nonreal;
    while (str <= lastpos) {
	if (*str == '\0')
	    *str = '/';
	str++;
    }

    if (real) {
	*junkptr = metafy(str = bicat(real, nonreal), -1, META_HEAPDUP);
	zsfree(str);
#ifdef REALPATH_ACCEPTS_NULL
	free(real);
#endif
    } else {
	*junkptr = metafy(nonreal, lastpos - nonreal + 1, META_HEAPDUP);
    }
#endif

    return 1;
}

/**/
int
remtpath(char **junkptr)
{
    char *str = strend(*junkptr);

    /* ignore trailing slashes */
    while (str >= *junkptr && IS_DIRSEP(*str))
	--str;
    /* skip filename */
    while (str >= *junkptr && !IS_DIRSEP(*str))
	--str;
    if (str < *junkptr) {
	if (IS_DIRSEP(**junkptr))
	    *junkptr = dupstring ("/");
	else
	    *junkptr = dupstring (".");

	return 0;
    }
    /* repeated slashes are considered like a single slash */
    while (str > *junkptr && IS_DIRSEP(str[-1]))
	--str;
    /* never erase the root slash */
    if (str == *junkptr) {
	++str;
	/* Leading doubled slashes (`//') have a special meaning on cygwin
	   and some old flavor of UNIX, so we do not assimilate them to
	   a single slash.  However a greater number is ok to squeeze. */
	if (IS_DIRSEP(*str) && !IS_DIRSEP(str[1]))
	    ++str;
    }
    *str = '\0';
    return 1;
}

/**/
int
remtext(char **junkptr)
{
    char *str;

    for (str = strend(*junkptr); str >= *junkptr && !IS_DIRSEP(*str); --str)
	if (*str == '.') {
	    *str = '\0';
	    return 1;
	}
    return 0;
}

/**/
int
rembutext(char **junkptr)
{
    char *str;

    for (str = strend(*junkptr); str >= *junkptr && !IS_DIRSEP(*str); --str)
	if (*str == '.') {
	    *junkptr = dupstring(str + 1); /* .xx or xx? */
	    return 1;
	}
    /* no extension */
    *junkptr = dupstring ("");
    return 0;
}

/**/
mod_export int
remlpaths(char **junkptr)
{
    char *str = strend(*junkptr);

    if (IS_DIRSEP(*str)) {
	/* remove trailing slashes */
	while (str >= *junkptr && IS_DIRSEP(*str))
	    --str;
	str[1] = '\0';
    }
    for (; str >= *junkptr; --str)
	if (IS_DIRSEP(*str)) {
	    *str = '\0';
	    *junkptr = dupstring(str + 1);
	    return 1;
	}
    return 0;
}

/*
 * Return modified version of str from the heap with modification
 * according to one of the CASMOD_* types defined in zsh.h; CASMOD_NONE
 * is not handled, for obvious reasons.
 */

/**/
char *
casemodify(char *str, int how)
{
    char *str2 = zhalloc(2 * strlen(str) + 1);
    char *ptr2 = str2;
    int nextupper = 1;

#ifdef MULTIBYTE_SUPPORT
    if (isset(MULTIBYTE)) {
	VARARR(char, mbstr, MB_CUR_MAX);
	mbstate_t ps;

	mb_metacharinit();
	memset(&ps, 0, sizeof(ps));
	while (*str) {
	    wint_t wc;
	    int len = mb_metacharlenconv(str, &wc), mod = 0, len2;
	    /*
	     * wc is set to WEOF if the start of str couldn't be
	     * converted.  Presumably WEOF doesn't match iswlower(), but
	     * better be safe.
	     */
	    if (wc == WEOF) {
		while (len--)
		    *ptr2++ = *str++;
		/* not alphanumeric */
		nextupper = 1;
		continue;
	    }
	    switch (how) {
	    case CASMOD_LOWER:
		if (iswupper(wc)) {
		    wc = towlower(wc);
		    mod = 1;
		}
		break;

	    case CASMOD_UPPER:
		if (iswlower(wc)) {
		    wc = towupper(wc);
		    mod = 1;
		}
		break;

	    case CASMOD_CAPS:
	    default:		/* shuts up compiler */
		if (IS_COMBINING(wc))
			break;
		if (!iswalnum(wc))
		    nextupper = 1;
		else if (nextupper) {
		    if (iswlower(wc)) {
			wc = towupper(wc);
			mod = 1;
		    }
		    nextupper = 0;
		} else if (iswupper(wc)) {
		    wc = towlower(wc);
		    mod = 1;
		}
		break;
	    }
	    if (mod && (len2 = wcrtomb(mbstr, wc, &ps)) > 0) {
		char *mbptr;

		for (mbptr = mbstr; mbptr < mbstr + len2; mbptr++) {
		    if (imeta(STOUC(*mbptr))) {
			*ptr2++ = Meta;
			*ptr2++ = *mbptr ^ 32;
		    } else
			*ptr2++ = *mbptr;
		}
		str += len;
	    } else {
		while (len--)
		    *ptr2++ = *str++;
	    }
	}
    }
    else
#endif
	while (*str) {
	    int c;
	    if (*str == Meta) {
		c = str[1] ^ 32;
		str += 2;
	    } else
		c = *str++;
	    switch (how) {
	    case CASMOD_LOWER:
		if (isupper(c))
		    c = tolower(c);
		break;

	    case CASMOD_UPPER:
		if (islower(c))
		    c = toupper(c);
		break;

	    case CASMOD_CAPS:
	    default:		/* shuts up compiler */
		if (!ialnum(c))
		    nextupper = 1;
		else if (nextupper) {
		    if (islower(c))
			c = toupper(c);
		    nextupper = 0;
		} else if (isupper(c))
		    c = tolower(c);
		break;
	    }
	    if (imeta(c)) {
		*ptr2++ = Meta;
		*ptr2++ = c ^ 32;
	    } else
		*ptr2++ = c;
	}
    *ptr2 = '\0';
    return str2;
}


/*
 * Substitute "in" for "out" in "*strptr" and update "*strptr".
 * If "gbal", do global substitution.
 *
 * This returns a result from the heap.  There seems to have
 * been some confusion on this point.
 */

/**/
int
subst(char **strptr, char *in, char *out, int gbal)
{
    char *str = *strptr, *substcut, *sptr;
    int off, inlen, outlen;

    if (!*in)
	in = str, gbal = 0;

    if (isset(HISTSUBSTPATTERN)) {
	int fl = SUB_LONG|SUB_REST|SUB_RETFAIL;
	char *oldin = in;
	if (gbal)
	    fl |= SUB_GLOBAL;
	if (*in == '#' || *in == Pound) {
	    /* anchor at head, flag needed if SUB_END is also set */
	    fl |= SUB_START;
	    in++;
	}
	if (*in == '%') {
	    /* anchor at tail */
	    in++;
	    fl |= SUB_END;
	}
	if (in == oldin) {
	    /* no anchor, substring match */
	    fl |= SUB_SUBSTR;
	}
	if (in == str)
	    in = dupstring(in);
	if (parse_subst_string(in) || errflag)
	    return 1;
	if (parse_subst_string(out) || errflag)
	    return 1;
	singsub(&in);
	if (getmatch(strptr, in, fl, 1, out))
	    return 0;
    } else {
	if ((substcut = (char *)strstr(str, in))) {
	    inlen = strlen(in);
	    sptr = convamps(out, in, inlen);
	    outlen = strlen(sptr);

	    do {
		*substcut = '\0';
		off = substcut - *strptr + outlen;
		substcut += inlen;
		*strptr = zhtricat(*strptr, sptr, substcut);
		str = (char *)*strptr + off;
	    } while (gbal && (substcut = (char *)strstr(str, in)));

	    return 0;
	}
    }

    return 1;
}

/**/
static char *
convamps(char *out, char *in, int inlen)
{
    char *ptr, *ret, *pp;
    int slen, sdup = 0;

    for (ptr = out, slen = 0; *ptr; ptr++, slen++)
	if (*ptr == '\\')
	    ptr++, sdup = 1;
	else if (*ptr == '&')
	    slen += inlen - 1, sdup = 1;
    if (!sdup)
	return out;
    ret = pp = (char *) zhalloc(slen + 1);
    for (ptr = out; *ptr; ptr++)
	if (*ptr == '\\')
	    *pp++ = *++ptr;
	else if (*ptr == '&') {
	    strcpy(pp, in);
	    pp += inlen;
	} else
	    *pp++ = *ptr;
    *pp = '\0';
    return ret;
}

/**/
mod_export void
checkcurline(Histent he)
{
    if (he->histnum == curhist && (histactive & HA_ACTIVE)) {
	curline.node.nam = chline;
	curline.nwords = chwordpos/2;
	curline.words = chwords;
    }
}

/**/
mod_export Histent
quietgethist(int ev)
{
    return gethistent(ev, GETHIST_EXACT);
}

/**/
static Histent
gethist(int ev)
{
    Histent ret;

    ret = quietgethist(ev);
    if (!ret) {
	herrflush();
	zerr("no such event: %d", ev);
    }
    return ret;
}

/**/
static char *
getargs(Histent elist, int arg1, int arg2)
{
    short *words = elist->words;
    int pos1, nwords = elist->nwords;

    if (arg2 < arg1 || arg1 >= nwords || arg2 >= nwords) {
	/* remember, argN is indexed from 0, nwords is total no. of words */
	herrflush();
	zerr("no such word in event");
	return NULL;
    }

    pos1 = words[2*arg1];
    return dupstrpfx(elist->node.nam + pos1, words[2*arg2+1] - pos1);
}

/**/
int
quote(char **tr)
{
    char *ptr, *rptr, **str = (char **)tr;
    int len = 3;
    int inquotes = 0;

    for (ptr = *str; *ptr; ptr++, len++)
	if (*ptr == '\'') {
	    len += 3;
	    if (!inquotes)
		inquotes = 1;
	    else
		inquotes = 0;
	} else if (inblank(*ptr) && !inquotes && ptr[-1] != '\\')
	    len += 2;
    ptr = *str;
    *str = rptr = (char *) zhalloc(len);
    *rptr++ = '\'';
    for (; *ptr; ptr++)
	if (*ptr == '\'') {
	    if (!inquotes)
		inquotes = 1;
	    else
		inquotes = 0;
	    *rptr++ = '\'';
	    *rptr++ = '\\';
	    *rptr++ = '\'';
	    *rptr++ = '\'';
	} else if (inblank(*ptr) && !inquotes && ptr[-1] != '\\') {
	    *rptr++ = '\'';
	    *rptr++ = *ptr;
	    *rptr++ = '\'';
	} else
	    *rptr++ = *ptr;
    *rptr++ = '\'';
    *rptr++ = 0;
    return 0;
}

/**/
static int
quotebreak(char **tr)
{
    char *ptr, *rptr, **str = (char **)tr;
    int len = 3;

    for (ptr = *str; *ptr; ptr++, len++)
	if (*ptr == '\'')
	    len += 3;
	else if (inblank(*ptr))
	    len += 2;
    ptr = *str;
    *str = rptr = (char *) zhalloc(len);
    *rptr++ = '\'';
    for (; *ptr;)
	if (*ptr == '\'') {
	    *rptr++ = '\'';
	    *rptr++ = '\\';
	    *rptr++ = '\'';
	    *rptr++ = '\'';
	    ptr++;
	} else if (inblank(*ptr)) {
	    *rptr++ = '\'';
	    *rptr++ = *ptr++;
	    *rptr++ = '\'';
	} else
	    *rptr++ = *ptr++;
    *rptr++ = '\'';
    *rptr++ = '\0';
    return 0;
}

/* read an arbitrary amount of data into a buffer until stop is found */

#if 0 /**/
char *
hdynread(int stop)
{
    int bsiz = 256, ct = 0, c;
    char *buf = (char *)zalloc(bsiz), *ptr;

    ptr = buf;
    while ((c = ingetc()) != stop && c != '\n' && !lexstop) {
	if (c == '\\')
	    c = ingetc();
	*ptr++ = c;
	if (++ct == bsiz) {
	    buf = realloc(buf, bsiz *= 2);
	    ptr = buf + ct;
	}
    }
    *ptr = 0;
    if (c == '\n') {
	inungetc('\n');
	zerr("delimiter expected");
	zfree(buf, bsiz);
	return NULL;
    }
    return buf;
}
#endif

/**/
static char *
hdynread2(int stop)
{
    int bsiz = 256, ct = 0, c;
    char *buf = (char *)zalloc(bsiz), *ptr;

    ptr = buf;
    while ((c = ingetc()) != stop && c != '\n' && !lexstop) {
	if (c == '\\')
	    c = ingetc();
	*ptr++ = c;
	if (++ct == bsiz) {
	    buf = realloc(buf, bsiz *= 2);
	    ptr = buf + ct;
	}
    }
    *ptr = 0;
    if (c == '\n')
	inungetc('\n');
    return buf;
}

/**/
void
inithist(void)
{
    createhisttable();
}

/**/
void
resizehistents(void)
{
    if (histlinect > histsiz) {
	/* The reason we don't just call freehistnode(hist_ring->down) is
	 * so that we can honor the HISTEXPIREDUPSFIRST setting. */
	putoldhistentryontop(0);
	freehistnode(&hist_ring->node);
	while (histlinect > histsiz) {
	    putoldhistentryontop(1);
	    freehistnode(&hist_ring->node);
	}
    }
}

static int
readhistline(int start, char **bufp, int *bufsiz, FILE *in)
{
    char *buf = *bufp;
    if (fgets(buf + start, *bufsiz - start, in)) {
	int len = start + strlen(buf + start);
	if (len == start)
	    return -1;
	if (buf[len - 1] != '\n') {
	    if (!feof(in)) {
		if (len < (*bufsiz) - 1)
		    return -1;
		*bufp = zrealloc(buf, 2 * (*bufsiz));
		*bufsiz = 2 * (*bufsiz);
		return readhistline(len, bufp, bufsiz, in);
	    }
	}
	else {
	    buf[len - 1] = '\0';
	    if (len > 1 && buf[len - 2] == '\\') {
		buf[--len - 1] = '\n';
		if (!feof(in))
		    return readhistline(len, bufp, bufsiz, in);
	    }
	}
	return len;
    }
    return 0;
}

/**/
void
readhistfile(char *fn, int err, int readflags)
{
    char *buf, *start = NULL;
    FILE *in;
    Histent he;
    time_t stim, ftim, tim = time(NULL);
    off_t fpos;
    short *words;
    struct stat sb;
    int nwordpos, nwords, bufsiz;
    int searching, newflags, l, ret, uselex;

    if (!fn && !(fn = getsparam("HISTFILE")))
	return;
    if (stat(unmeta(fn), &sb) < 0 ||
	sb.st_size == 0)
	return;
    if (readflags & HFILE_FAST) {
	if ((lasthist.fsiz == sb.st_size && lasthist.mtim == sb.st_mtime)
	    || lockhistfile(fn, 0))
	    return;
	lasthist.fsiz = sb.st_size;
	lasthist.mtim = sb.st_mtime;
    } else if ((ret = lockhistfile(fn, 1))) {
	if (ret == 2) {
	    zwarn("locking failed for %s: %e: reading anyway", fn, errno);
	} else {
	    zerr("locking failed for %s: %e", fn, errno);
	    return;
	}
    }
    if ((in = fopen(unmeta(fn), "r"))) {
	nwords = 64;
	words = (short *)zalloc(nwords*sizeof(short));
	bufsiz = 1024;
	buf = zalloc(bufsiz);

	pushheap();
	if (readflags & HFILE_FAST && lasthist.text) {
	    if (lasthist.fpos < lasthist.fsiz) {
		fseek(in, lasthist.fpos, 0);
		searching = 1;
	    }
	    else {
		histfile_linect = 0;
		searching = -1;
	    }
	} else
	    searching = 0;

	newflags = HIST_OLD | HIST_READ;
	if (readflags & HFILE_FAST)
	    newflags |= HIST_FOREIGN;
	if (readflags & HFILE_SKIPOLD
	 || (hist_ignore_all_dups && newflags & hist_skip_flags))
	    newflags |= HIST_MAKEUNIQUE;
	while (fpos = ftell(in), (l = readhistline(0, &buf, &bufsiz, in))) {
	    char *pt;
	    int remeta = 0;

	    if (l < 0) {
		zerr("corrupt history file %s", fn);
		break;
	    }

	    /*
	     * Handle the special case that we're reading from an
	     * old shell with fewer meta characters, so we need to
	     * metafy some more.  (It's not clear why the history
	     * file is metafied at all; some would say this is plain
	     * stupid.  But we're stuck with it now without some
	     * hairy workarounds for compatibility).
	     *
	     * This is rare so doesn't need to be that efficient; just
	     * allocate space off the heap.
	     */
	    for (pt = buf; *pt; pt++) {
		if (*pt == Meta && pt[1])
		    pt++;
		else if (imeta(*pt)) {
		    remeta = 1;
		    break;
		}
	    }
	    if (remeta) {
		unmetafy(buf, &remeta);
		pt = metafy(buf, remeta, META_USEHEAP);
	    } else {
		pt = buf;
	    }

	    if (*pt == ':') {
		pt++;
		stim = zstrtol(pt, NULL, 0);
		for (; *pt != ':' && *pt; pt++);
		if (*pt) {
		    pt++;
		    ftim = zstrtol(pt, NULL, 0);
		    for (; *pt != ';' && *pt; pt++);
		    if (*pt)
			pt++;
		} else
		    ftim = stim;
	    } else {
		if (*pt == '\\' && pt[1] == ':')
		    pt++;
		stim = ftim = 0;
	    }

	    if (searching) {
		if (searching > 0) {
		    if (stim == lasthist.stim
		     && histstrcmp(pt, lasthist.text) == 0)
			searching = 0;
		    else {
			fseek(in, 0, 0);
			histfile_linect = 0;
			searching = -1;
		    }
		    continue;
		}
		else if (stim < lasthist.stim) {
		    histfile_linect++;
		    continue;
		}
		searching = 0;
	    }

	    if (readflags & HFILE_USE_OPTIONS) {
		histfile_linect++;
		lasthist.fpos = fpos;
		lasthist.stim = stim;
	    }

	    he = prepnexthistent();
	    he->node.nam = ztrdup(pt);
	    he->node.flags = newflags;
	    if ((he->stim = stim) == 0)
		he->stim = he->ftim = tim;
	    else if (ftim < stim)
		he->ftim = stim + ftim;
	    else
		he->ftim = ftim;

	    /*
	     * Divide up the words.
	     */
	    start = pt;
	    uselex = isset(HISTLEXWORDS) && !(readflags & HFILE_FAST);
	    histsplitwords(pt, &words, &nwords, &nwordpos, uselex);

	    he->nwords = nwordpos/2;
	    if (he->nwords) {
		he->words = (short *)zalloc(nwordpos*sizeof(short));
		memcpy(he->words, words, nwordpos*sizeof(short));
	    } else
		he->words = (short *)NULL;
	    addhistnode(histtab, he->node.nam, he);
	    if (he->node.flags & HIST_DUP) {
		freehistnode(&he->node);
		curhist--;
	    }
	    /*
	     * Do this last out of paranoia in case use of
	     * heap is disguised...
	     */
	    if (uselex || remeta)
		freeheap();
	}
	if (start && readflags & HFILE_USE_OPTIONS) {
	    zsfree(lasthist.text);
	    lasthist.text = ztrdup(start);
	}
	zfree(words, nwords*sizeof(short));
	zfree(buf, bufsiz);

	popheap();
	fclose(in);
    } else if (err)
	zerr("can't read history file %s", fn);

    unlockhistfile(fn);

    if (zleactive)
	zleentry(ZLE_CMD_SET_HIST_LINE, curhist);
}

#ifdef HAVE_FCNTL_H
static int flock_fd = -1;

/*
 * Lock file using fcntl().  Return 0 on success, 1 on failure of
 * locking mechanism, 2 on permanent failure (e.g. permission).
 */

static int
flockhistfile(char *fn, int keep_trying)
{
    struct flock lck;
    long sleep_us = 0x10000; /* about 67 ms */
    time_t end_time;

    if (flock_fd >= 0)
	return 0; /* already locked */

    if ((flock_fd = open(unmeta(fn), O_RDWR | O_NOCTTY)) < 0)
	return errno == ENOENT ? 0 : 2; /* "successfully" locked missing file */

    lck.l_type = F_WRLCK;
    lck.l_whence = SEEK_SET;
    lck.l_start = 0;
    lck.l_len = 0;  /* lock the whole file */

    /*
     * Timeout is ten seconds.
     */
    end_time = time(NULL) + (time_t)10;
    while (fcntl(flock_fd, F_SETLKW, &lck) == -1) {
	if (!keep_trying || time(NULL) >= end_time ||
	    /*
	     * Randomise wait to minimise clashes with shells exiting at
	     * the same time.
	     */
	    !zsleep_random(sleep_us, end_time)) {
	    close(flock_fd);
	    flock_fd = -1;
	    return 1;
	}
	sleep_us <<= 1;
    }

    return 0;
}
#endif

/**/
void
savehistfile(char *fn, int err, int writeflags)
{
    char *t, *tmpfile, *start = NULL;
    FILE *out;
    Histent he;
    zlong xcurhist = curhist - !!(histactive & HA_ACTIVE);
    int extended_history = isset(EXTENDEDHISTORY);
    int ret;

    if (!interact || savehistsiz <= 0 || !hist_ring
     || (!fn && !(fn = getsparam("HISTFILE"))))
	return;
    if (writeflags & HFILE_FAST) {
	he = gethistent(lasthist.next_write_ev, GETHIST_DOWNWARD);
	while (he && he->node.flags & HIST_OLD) {
	    lasthist.next_write_ev = he->histnum + 1;
	    he = down_histent(he);
	}
	if (!he || lockhistfile(fn, 0))
	    return;
	if (histfile_linect > savehistsiz + savehistsiz / 5)
	    writeflags &= ~HFILE_FAST;
    }
    else {
	if (lockhistfile(fn, 1)) {
	    zerr("locking failed for %s: %e", fn, errno);
	    return;
	}
	he = hist_ring->down;
    }
    if (writeflags & HFILE_USE_OPTIONS) {
	if (isset(APPENDHISTORY) || isset(INCAPPENDHISTORY)
	 || isset(INCAPPENDHISTORYTIME) || isset(SHAREHISTORY))
	    writeflags |= HFILE_APPEND | HFILE_SKIPOLD;
	else
	    histfile_linect = 0;
	if (isset(HISTSAVENODUPS))
	    writeflags |= HFILE_SKIPDUPS;
	if (isset(SHAREHISTORY))
	    extended_history = 1;
    }
    errno = 0;
    if (writeflags & HFILE_APPEND) {
	int fd = open(unmeta(fn), O_CREAT | O_WRONLY | O_APPEND | O_NOCTTY, 0600);
	tmpfile = NULL;
	out = fd >= 0 ? fdopen(fd, "a") : NULL;
    } else if (!isset(HISTSAVEBYCOPY)) {
	int fd = open(unmeta(fn), O_CREAT | O_WRONLY | O_TRUNC | O_NOCTTY, 0600);
	tmpfile = NULL;
	out = fd >= 0 ? fdopen(fd, "w") : NULL;
    } else {
	tmpfile = bicat(unmeta(fn), ".new");
	if (unlink(tmpfile) < 0 && errno != ENOENT)
	    out = NULL;
	else {
	    struct stat sb;
	    int old_exists = stat(unmeta(fn), &sb) == 0;
	    uid_t euid = geteuid();

	    if (old_exists
#if defined HAVE_FCHMOD && defined HAVE_FCHOWN
	     && euid
#endif
	     && sb.st_uid != euid) {
		free(tmpfile);
		tmpfile = NULL;
		if (err) {
		    if (isset(APPENDHISTORY) || isset(INCAPPENDHISTORY)
		     || isset(INCAPPENDHISTORYTIME) || isset(SHAREHISTORY))
			zerr("rewriting %s would change its ownership -- skipped", fn);
		    else
			zerr("rewriting %s would change its ownership -- history not saved", fn);
		    err = 0; /* Don't report a generic error below. */
		}
		out = NULL;
	    } else {
		int fd = open(tmpfile, O_CREAT | O_WRONLY | O_EXCL, 0600);
		if (fd >=0) {
		    out = fdopen(fd, "w");
		    if (!out)
			close(fd);
		} else
		    out = NULL;
	    }

#ifdef HAVE_FCHMOD
	    if (old_exists && out) {
#ifdef HAVE_FCHOWN
		if (fchown(fileno(out), sb.st_uid, sb.st_gid) < 0) {} /* IGNORE FAILURE */
#endif
		if (fchmod(fileno(out), sb.st_mode) < 0) {} /* IGNORE FAILURE */
	    }
#endif
	}
    }
    if (out) {
	char *history_ignore;
	Patprog histpat = NULL;

	pushheap();

	if ((history_ignore = getsparam("HISTORY_IGNORE")) != NULL) {
	    tokenize(history_ignore = dupstring(history_ignore));
	    remnulargs(history_ignore);
	    histpat = patcompile(history_ignore, 0, NULL);
	}

	ret = 0;
	for (; he && he->histnum <= xcurhist; he = down_histent(he)) {
	    int count_backslashes = 0;

	    if ((writeflags & HFILE_SKIPDUPS && he->node.flags & HIST_DUP)
	     || (writeflags & HFILE_SKIPFOREIGN && he->node.flags & HIST_FOREIGN)
	     || he->node.flags & HIST_TMPSTORE)
		continue;
	    if (histpat &&
		pattry(histpat, metafy(he->node.nam, -1, META_HEAPDUP))) {
		continue;
	    }
	    if (writeflags & HFILE_SKIPOLD) {
		if (he->node.flags & (HIST_OLD|HIST_NOWRITE))
		    continue;
		he->node.flags |= HIST_OLD;
		if (writeflags & HFILE_USE_OPTIONS)
		    lasthist.next_write_ev = he->histnum + 1;
	    }
	    if (writeflags & HFILE_USE_OPTIONS) {
		lasthist.fpos = ftell(out);
		lasthist.stim = he->stim;
		histfile_linect++;
	    }
	    t = start = he->node.nam;
	    if (extended_history) {
		ret = fprintf(out, ": %ld:%ld;", (long)he->stim,
			      he->ftim? (long)(he->ftim - he->stim) : 0L);
	    } else if (*t == ':')
		ret = fputc('\\', out);

	    for (; ret >= 0 && *t; t++) {
		if (*t == '\n')
		    if ((ret = fputc('\\', out)) < 0)
			break;
		if (*t == '\\')
		    count_backslashes++;
		else
		    count_backslashes = 0;
		if ((ret = fputc(*t, out)) < 0)
		    break;
	    }
	    if (ret < 0)
	    	break;
	    if (count_backslashes && (count_backslashes % 2 == 0))
		if ((ret = fputc(' ', out)) < 0)
		    break;
	    if (ret < 0 || (ret = fputc('\n', out)) < 0)
		break;
	}
	if (ret >= 0 && start && writeflags & HFILE_USE_OPTIONS) {
	    struct stat sb;
	    if ((ret = fflush(out)) >= 0) {
		if (fstat(fileno(out), &sb) == 0) {
		    lasthist.fsiz = sb.st_size;
		    lasthist.mtim = sb.st_mtime;
		}
		zsfree(lasthist.text);
		lasthist.text = ztrdup(start);
	    }
	}
	if (fclose(out) < 0 && ret >= 0)
	    ret = -1;
	if (ret >= 0) {
	    if (tmpfile) {
		if (rename(tmpfile, unmeta(fn)) < 0) {
		    zerr("can't rename %s.new to $HISTFILE", fn);
		    ret = -1;
		    err = 0;
#ifdef HAVE_FCNTL_H
		} else {
		    /* We renamed over the locked HISTFILE, so close fd.
		     * If we do more writing, we'll get a lock then. */
		    if (flock_fd >= 0) {
			close(flock_fd);
			flock_fd = -1;
		    }
#endif
		}
	    }

	    if (ret >= 0 && writeflags & HFILE_SKIPOLD
		&& !(writeflags & (HFILE_FAST | HFILE_NO_REWRITE))) {
		int remember_histactive = histactive;

		/* Zeroing histactive avoids unnecessary munging of curline. */
		histactive = 0;
		/* The NULL leaves HISTFILE alone, preserving fn's value. */
		pushhiststack(NULL, savehistsiz, savehistsiz, -1);

		hist_ignore_all_dups |= isset(HISTSAVENODUPS);
		readhistfile(fn, err, 0);
		hist_ignore_all_dups = isset(HISTIGNOREALLDUPS);
		if (histlinect)
		    savehistfile(fn, err, 0);

		pophiststack();
		histactive = remember_histactive;
	    }
	}

	popheap();
    } else
	ret = -1;

    if (ret < 0 && err) {
	if (tmpfile)
	    zerr("failed to write history file %s.new: %e", fn, errno);
	else
	    zerr("failed to write history file %s: %e", fn, errno);
    }
    if (tmpfile)
	free(tmpfile);

    unlockhistfile(fn);
}

static int lockhistct;

static int
checklocktime(char *lockfile, long *sleep_usp, time_t then)
{
    time_t now = time(NULL);

    if (now + 10 < then) {
	/* File is more than 10 seconds in the future? */
	errno = EEXIST;
	return -1;
    }

    if (now - then < 10) {
	/*
	 * To give the effect of a gradually increasing backoff,
	 * we'll sleep a period based on the time we've spent so far.
	 */
	DPUTS(now < then, "time flowing backwards through history");
	/*
	 * Randomise to minimise clashes with shells exiting at the same
	 * time.
	 */
	(void)zsleep_random(*sleep_usp, then + 10);
	*sleep_usp <<= 1;
    } else
	unlink(lockfile);

    return 0;
}

/*
 * Lock history file.  Return 0 on success, 1 on failure to lock this
 * time, 2 on permanent failure (e.g. permission).
 */

/**/
int
lockhistfile(char *fn, int keep_trying)
{
    int ct = lockhistct;
    int ret = 0;
    long sleep_us = 0x10000; /* about 67 ms */

    if (!fn && !(fn = getsparam("HISTFILE")))
	return 1;

    if (!lockhistct++) {
	struct stat sb;
	int fd;
	char *lockfile;
#ifdef HAVE_LINK
# ifdef HAVE_SYMLINK
	char pidbuf[32], *lnk;
# else
	char *tmpfile;
# endif
#endif

#ifdef HAVE_FCNTL_H
	if (isset(HISTFCNTLLOCK))
	    return flockhistfile(fn, keep_trying);
#endif

	lockfile = bicat(unmeta(fn), ".LOCK");
	/* NOTE: only use symlink locking on a link()-having host in order to
	 * avoid a change from open()-based locking to symlink()-based. */
#ifdef HAVE_LINK
# ifdef HAVE_SYMLINK
	sprintf(pidbuf, "/pid-%ld/host-", (long)mypid);
	lnk = getsparam("HOST");
	lnk = bicat(pidbuf, lnk ? lnk : "");
	/* We'll abuse fd as our success flag. */
	while ((fd = symlink(lnk, lockfile)) < 0) {
	    if (errno != EEXIST) {
		ret = 2;
		break;
	    } else if (!keep_trying) {
		ret = 1;
		break;
	    }
	    if (lstat(lockfile, &sb) < 0) {
		if (errno == ENOENT)
		    continue;
		break;
	    }
	    if (checklocktime(lockfile, &sleep_us, sb.st_mtime) < 0) {
		ret = 1;
		break;
	    }
	}
	if (fd < 0)
	    lockhistct--;
	free(lnk);
# else /* not HAVE_SYMLINK */
	if ((fd = gettempfile(fn, 0, &tmpfile)) >= 0) {
	    FILE *out = fdopen(fd, "w");
	    if (out) {
		fprintf(out, "%ld %s\n", (long)getpid(), getsparam("HOST"));
		fclose(out);
	    } else
		close(fd);
	    while (link(tmpfile, lockfile) < 0) {
		if (errno != EEXIST) {
		    ret = 2;
		    break;
		} else if (!keep_trying) {
		    ret = 1;
		    break;
		} else if (lstat(lockfile, &sb) < 0) {
		    if (errno == ENOENT)
			continue;
		    ret = 2;
		} else {
		    if (checklocktime(lockfile, &sleep_us, sb.st_mtime) < 0) {
			ret = 1;
			break;
		    }
		    continue;
		}
		lockhistct--;
		break;
	    }
	    unlink(tmpfile);
	    free(tmpfile);
	}
# endif /* not HAVE_SYMLINK */
#else /* not HAVE_LINK */
	while ((fd = open(lockfile, O_WRONLY|O_CREAT|O_EXCL, 0644)) < 0) {
	    if (errno != EEXIST) {
		ret = 2;
		break;
	    } else if (!keep_trying) {
		ret = 1;
		break;
	    }
	    if (lstat(lockfile, &sb) < 0) {
		if (errno == ENOENT)
		    continue;
		ret = 2;
		break;
	    }
	    if (checklocktime(lockfile, &sleep_us, sb.st_mtime) < 0) {
		ret = 1;
		break;
	    }
	}
	if (fd < 0)
	    lockhistct--;
	else {
	    FILE *out = fdopen(fd, "w");
	    if (out) {
		fprintf(out, "%ld %s\n", (long)mypid, getsparam("HOST"));
		fclose(out);
	    } else
		close(fd);
	}
#endif /* not HAVE_LINK */
	free(lockfile);
    }

    if (ct == lockhistct) {
#ifdef HAVE_FCNTL_H
	if (flock_fd >= 0) {
	    close(flock_fd);
	    flock_fd = -1;
	}
#endif
	DPUTS(ret == 0, "BUG: return value non-zero on locking error");
	return ret;
    }
    return 0;
}

/* Unlock the history file if this corresponds to the last nested lock
 * request.  If we don't have the file locked, just return.
 */

/**/
void
unlockhistfile(char *fn)
{
    if (!fn && !(fn = getsparam("HISTFILE")))
	return;
    if (--lockhistct) {
	if (lockhistct < 0)
	    lockhistct = 0;
    }
    else {
	char *lockfile;
	fn = unmeta(fn);
	lockfile = zalloc(strlen(fn) + 5 + 1);
	sprintf(lockfile, "%s.LOCK", fn);
	unlink(lockfile);
	free(lockfile);
#ifdef HAVE_FCNTL_H
	if (flock_fd >= 0) {
	    close(flock_fd);
	    flock_fd = -1;
	}
#endif
    }
}

/**/
int
histfileIsLocked(void)
{
    return lockhistct > 0;
}

/*
 * Get the words in the current buffer. Using the lexer. 
 *
 * As far as I can make out, this is a gross hack based on a gross hack.
 * When analysing lines from within zle, we tweak the metafied line
 * positions (zlemetall and zlemetacs) directly in the lexer.  That's
 * bad enough, but this function appears to be designed to be called
 * from outside zle, pretending to be in zle and calling out, so
 * we set zlemetall and zlemetacs locally and copy the current zle line,
 * which may not even be valid at this point.
 *
 * However, I'm so confused it could simply be baking Bakewell tarts.
 *
 * list may be an existing linked list (off the heap), in which case
 * it will be appended to; otherwise it will be created.
 *
 * If buf is set we will take input from that string, else we will
 * attempt to use ZLE directly in a way they tell you not to do on all
 * programming courses.
 *
 * If index is non-NULL, and input is from a string in ZLE, *index
 * is set to the position of the end of the current editor word.
 *
 * flags is passed directly to lexflags, see lex.c, except that
 * we 'or' in the bit LEXFLAGS_ACTIVE to make sure the variable
 * is set.
 */

/**/
mod_export LinkList
bufferwords(LinkList list, char *buf, int *index, int flags)
{
    int num = 0, cur = -1, got = 0, ne = noerrs;
    int owb = wb, owe = we, oadx = addedx, onc = nocomments;
    int ona = noaliases, ocs = zlemetacs, oll = zlemetall;
    int forloop = 0, rcquotes = opts[RCQUOTES];
    char *p, *addedspaceptr;

    if (!list)
	list = newlinklist();

    /*
     * With RC_QUOTES, 'foo '' bar' comes back as 'foo ' bar'.  That's
     * not very useful.  As nothing in here requires the fully processed
     * string expression, we just turn the option off for this function.
     */
    opts[RCQUOTES] = 0;
    addedx = 0;
    noerrs = 1;
    zcontext_save();
    lexflags = flags | LEXFLAGS_ACTIVE;
    /*
     * Are we handling comments?
     */
    nocomments = !(flags & (LEXFLAGS_COMMENTS_KEEP|
			    LEXFLAGS_COMMENTS_STRIP));
    if (buf) {
	int l = strlen(buf);

	p = (char *) zhalloc(l + 2);
	memcpy(p, buf, l);
	/*
	 * I'm sure this space is here for a reason, but it's
	 * a pain in the neck:  when we get back a string that's
	 * not finished it's very hard to tell if a space at the
	 * end is this one or not.  We use two tricks below to
	 * work around this.
	 */
	addedspaceptr = p + l;
	*addedspaceptr = ' ';
	addedspaceptr[1] = '\0';
	inpush(p, 0, NULL);
	zlemetall = strlen(p) ;
	zlemetacs = zlemetall + 1;
    } else {
	int ll, cs;
	char *linein;

	linein = zleentry(ZLE_CMD_GET_LINE, &ll, &cs);
	zlemetall = ll + 1; /* length of line plus space added below */
	zlemetacs = cs;

	if (!isfirstln && chline) {
	    p = (char *) zhalloc(hptr - chline + ll + 2);
	    memcpy(p, chline, hptr - chline);
	    memcpy(p + (hptr - chline), linein, ll);
	    addedspaceptr = p + (hptr - chline) + ll;
	    *addedspaceptr = ' ';
	    addedspaceptr[1] = '\0';
	    inpush(p, 0, NULL);

	    /*
	     * advance line length and character position over
	     * prepended string.
	     */
	    zlemetall += hptr - chline;
	    zlemetacs += hptr - chline;
	} else {
	    p = (char *) zhalloc(ll + 2);
	    memcpy(p, linein, ll);
	    addedspaceptr = p + ll;
	    *addedspaceptr = ' ';
	    p[zlemetall] = '\0';
	    inpush(p, 0, NULL);
	}
	zsfree(linein);
    }
    if (zlemetacs)
	zlemetacs--;
    strinbeg(0);
    noaliases = 1;
    do {
	if (incond)
	    incond = 1 + (tok != DINBRACK && tok != INPAR &&
			  tok != DBAR && tok != DAMPER &&
			  tok != BANG);
	ctxtlex();
	if (tok == ENDINPUT || tok == LEXERR)
	    break;
	if (tok == FOR) {
	    /*
	     * The way for (( expr1 ; expr2; expr3 )) is parsed is:
	     * - a FOR tok
	     * - a DINPAR with no tokstr
	     * - two DINPARS with tokstr's expr1, expr2.
	     * - a DOUTPAR with tokstr expr3.
	     *
	     * We'll decrement the variable forloop as we verify
	     * the various stages.
	     *
	     * Don't ask me, ma'am, I'm just the programmer.
	     */
	    forloop = 5;
	} else {
	    switch (forloop) {
	    case 1:
		if (tok != DOUTPAR)
		    forloop = 0;
		break;

	    case 2:
	    case 3:
	    case 4:
		if (tok != DINPAR)
		    forloop = 0;
		break;

	    default:
		/* nothing to do */
		break;
	    }
	}
	if (tokstr) {
	    switch (tok) {
	    case ENVARRAY:
		p = dyncat(tokstr, "=(");
		break;

	    case DINPAR:
		if (forloop) {
		    /* See above. */
		    p = dyncat(tokstr, ";");
		} else {
		    /*
		     * Mathematical expressions analysed as a single
		     * word.  That's correct because it behaves like
		     * double quotes.  Whitespace in the middle is
		     * similarly retained, so just add the parentheses back.
		     */
		    p = zhtricat("((", tokstr, "))");
		}
		break;

	    default:
		p = dupstring(tokstr);
		break;
	    }
	    if (*p) {
		untokenize(p);
		if (ingetptr() == addedspaceptr + 1) {
		    /*
		     * Whoops, we've read past the space we added, probably
		     * because we were expecting a terminator but when
		     * it didn't turn up we shrugged our shoulders thinking
		     * it might as well be a complete string anyway.
		     * So remove the space.  C.f. below for the case
		     * where the missing terminator caused a lex error.
		     * We use the same paranoid test.
		     */
		    int plen = strlen(p);
		    if (plen && p[plen-1] == ' ' &&
			(plen == 1 || p[plen-2] != Meta))
			p[plen-1] = '\0';
		}
		addlinknode(list, p);
		num++;
	    }
	} else if (buf) {
	    if (IS_REDIROP(tok) && tokfd >= 0) {
		char b[20];

		sprintf(b, "%d%s", tokfd, tokstrings[tok]);
		addlinknode(list, dupstring(b));
		num++;
	    } else if (tok != NEWLIN) {
		addlinknode(list, dupstring(tokstrings[tok]));
		num++;
	    }
	}
	if (forloop) {
	    if (forloop == 1) {
		/*
		 * Final "))" of for loop to match opening,
		 * since we've just added the preceding element.
 		 */
		addlinknode(list, dupstring("))"));
	    }
	    forloop--;
	}
	if (!got && !lexflags) {
	    got = 1;
	    cur = num - 1;
	}
    } while (tok != ENDINPUT && tok != LEXERR);
    if (buf && tok == LEXERR && tokstr && *tokstr) {
	int plen;
	untokenize((p = dupstring(tokstr)));
	plen = strlen(p);
	/*
	 * Strip the space we added for lexing but which won't have
	 * been swallowed by the lexer because we aborted early.
	 * The test is paranoia.
	 */
	if (plen && p[plen-1] == ' ' && (plen == 1 || p[plen-2] != Meta))
	    p[plen - 1] = '\0';
	addlinknode(list, p);
	num++;
    }
    if (cur < 0 && num)
	cur = num - 1;
    noaliases = ona;
    strinend();
    inpop();
    errflag &= ~ERRFLAG_ERROR;
    nocomments = onc;
    noerrs = ne;
    zcontext_restore();
    zlemetacs = ocs;
    zlemetall = oll;
    wb = owb;
    we = owe;
    addedx = oadx;
    opts[RCQUOTES] = rcquotes;

    if (index)
	*index = cur;

    return list;
}

/*
 * Split up a line into words for use in a history file.
 *
 * lineptr is the line to be split.
 *
 * *wordsp and *nwordsp are an array already allocated to hold words
 * and its length.  The array holds both start and end positions,
 * so *nwordsp actually counts twice the number of words in the
 * original string.  *nwordsp may be zero in which case the array
 * will be allocated.
 *
 * *nwordposp returns the used length of *wordsp in the same units as
 * *nwordsp, i.e. twice the number of words in the input line.
 *
 * If uselex is 1, attempt to do this using the lexical analyser.
 * This is more accurate, but slower; for reading history files it's
 * controlled by the option HISTLEXWORDS.  If this failed (which
 * indicates a bug in the shell) it falls back to whitespace-separated
 * strings, printing a message if in debug mode.
 *
 * If uselex is 0, just look for whitespace-separated words; the only
 * special handling is for a backslash-newline combination as used
 * by the history file format to save multiline buffers.
 */
/**/
mod_export void
histsplitwords(char *lineptr, short **wordsp, int *nwordsp, int *nwordposp,
	       int uselex)
{
    int nwords = *nwordsp, nwordpos = 0;
    short *words = *wordsp;
    char *start = lineptr;

    if (uselex) {
	LinkList wordlist;
	LinkNode wordnode;
	int nwords_max;

	wordlist = bufferwords(NULL, lineptr, NULL,
			       LEXFLAGS_COMMENTS_KEEP);
	nwords_max = 2 * countlinknodes(wordlist);
	if (nwords_max > nwords) {
	    *nwordsp = nwords = nwords_max;
	    *wordsp = words = (short *)zrealloc(words, nwords*sizeof(short));
	}
	for (wordnode = firstnode(wordlist);
	     wordnode;
	     incnode(wordnode)) {
	    char *word = getdata(wordnode);
	    char *lptr, *wptr = word;
	    int loop_next = 0, skipping;

	    /* Skip stuff at the start of the word */
	    for (;;) {
		/*
		 * Not really an oddity: "\\\n" is
		 * removed from input as if whitespace.
		 */
		if (inblank(*lineptr))
		    lineptr++;
		else if (lineptr[0] == '\\' && lineptr[1] == '\n') {
		    /*
		     * Optimisation: we handle this in the loop below,
		     * too.
		     */
		    lineptr += 2;
		} else
		    break;
	    }
	    lptr = lineptr;
	    /*
	     * Skip chunks of word with possible intervening
	     * backslash-newline.
	     *
	     * To get round C's annoying lack of ability to
	     * reference the outer loop, we'll break from this
	     * one with
	     * loop_next = 0: carry on as normal
	     * loop_next = 1: break from outer loop
	     * loop_next = 2: continue round outer loop.
	     */
	    do {
		skipping = 0;
		if (strpfx(wptr, lptr)) {
		    /*
		     * Normal case: word from lexer matches start of
		     * string from line.  Just advance over it.
		     */
		    int len;
		    if (!strcmp(wptr, ";") && strpfx(";;", lptr)) {
			/*
			 * Don't get confused between a semicolon that's
			 * probably really a newline and a double
			 * semicolon that's terminating a case.
			 */
			loop_next = 2;
			break;
		    }
		    len = strlen(wptr);
		    lptr += len;
		    wptr += len;
		} else {
		    /*
		     * Didn't get to the end of the word.
		     * See what's amiss.
		     */
		    int bad = 0;
		    /*
		     * Oddity 1: newlines turn into semicolons.
		     */
		    if (!strcmp(wptr, ";"))
		    {
			loop_next = 2;
			break;
		    }
		    while (*lptr) {
			if (!*wptr) {
			    /*
			     * End of the word before the end of the
			     * line: not good.
			     */
			    bad = 1;
			    loop_next = 1;
			    break;
			}
			/*
			 * Oddity 2: !'s turn into |'s.
			 */
			if (*lptr == *wptr ||
			    (*lptr == '!' && *wptr == '|')) {
			    lptr++;
			    if (!*++wptr)
				break;
			} else if (lptr[0] == '\\' &&
				   lptr[1] == '\n') {
			    /*
			     * \\\n can occur in the middle of a word;
			     * wptr is already pointing at this, we
			     * just need to skip over the break
			     * in lptr and look at the next chunk.
			     */
			    lptr += 2;
			    skipping = 1;
			    break;
			} else {
			    bad = 1;
			    loop_next = 1;
			    break;
			}
		    }
		    if (bad) {
#ifdef DEBUG
			dputs(ERRMSG("bad wordsplit reading history: "
				     "%s\nat: %s\nword: %s"),
			      start, lineptr, word);
#endif
			lineptr = start;
			nwordpos = 0;
			uselex = 0;
			loop_next = 1;
		    }
		}
	    } while (skipping);
	    if (loop_next) {
		if (loop_next == 1)
		    break;
		continue;
	    }
	    /* Record position of current word... */
	    words[nwordpos++] = lineptr - start;
	    words[nwordpos++] = lptr - start;

	    /* ready for start of next word. */
	    lineptr = lptr;
	}
    }
    if (!uselex) {
	do {
	    for (;;) {
		if (inblank(*lineptr))
		    lineptr++;
		else if (lineptr[0] == '\\' && lineptr[1] == '\n')
		    lineptr += 2;
		else
		    break;
	    }
	    if (*lineptr) {
		if (nwordpos >= nwords) {
		    *nwordsp = nwords = nwords + 64;
		    *wordsp = words = (short *)
			zrealloc(words, nwords*sizeof(*words));
		}
		words[nwordpos++] = lineptr - start;
		while (*lineptr && !inblank(*lineptr))
		    lineptr++;
		words[nwordpos++] = lineptr - start;
	    }
	} while (*lineptr);
    }

    *nwordposp = nwordpos;
}

/* Move the current history list out of the way and prepare a fresh history
 * list using hf for HISTFILE, hs for HISTSIZE, and shs for SAVEHIST.  If
 * the hf value is an empty string, HISTFILE will be unset from the new
 * environment; if it is NULL, HISTFILE will not be changed, not even by the
 * pop function (this functionality is used internally to rewrite the current
 * history file without affecting pointers into the environment).
 */

/**/
int
pushhiststack(char *hf, zlong hs, zlong shs, int level)
{
    struct histsave *h;
    int curline_in_ring = (histactive & HA_ACTIVE) && hist_ring == &curline;

    if (histsave_stack_pos == histsave_stack_size) {
	histsave_stack_size += 5;
	histsave_stack = zrealloc(histsave_stack,
			    histsave_stack_size * sizeof (struct histsave));
    }

    if (curline_in_ring)
	unlinkcurline();

    h = &histsave_stack[histsave_stack_pos++];

    h->lasthist = lasthist;
    if (hf) {
	if ((h->histfile = getsparam("HISTFILE")) != NULL && *h->histfile)
	    h->histfile = ztrdup(h->histfile);
	else
	    h->histfile = "";
    } else
	h->histfile = NULL;
    h->histtab = histtab;
    h->hist_ring = hist_ring;
    h->curhist = curhist;
    h->histlinect = histlinect;
    h->histsiz = histsiz;
    h->savehistsiz = savehistsiz;
    h->locallevel = level;

    memset(&lasthist, 0, sizeof lasthist);
    if (hf) {
	if (*hf)
	    setsparam("HISTFILE", ztrdup(hf));
	else
	    unsetparam("HISTFILE");
    }
    hist_ring = NULL;
    curhist = histlinect = 0;
    if (zleactive)
	zleentry(ZLE_CMD_SET_HIST_LINE, curhist);
    histsiz = hs;
    savehistsiz = shs;
    inithist(); /* sets histtab */

    if (curline_in_ring)
	linkcurline();

    return histsave_stack_pos;
}


/**/
int
pophiststack(void)
{
    struct histsave *h;
    int curline_in_ring = (histactive & HA_ACTIVE) && hist_ring == &curline;

    if (histsave_stack_pos == 0)
	return 0;

    if (curline_in_ring)
	unlinkcurline();

    deletehashtable(histtab);
    zsfree(lasthist.text);

    h = &histsave_stack[--histsave_stack_pos];

    lasthist = h->lasthist;
    if (h->histfile) {
	if (*h->histfile)
	    setsparam("HISTFILE", h->histfile);
	else
	    unsetparam("HISTFILE");
    }
    histtab = h->histtab;
    hist_ring = h->hist_ring;
    curhist = h->curhist;
    if (zleactive)
	zleentry(ZLE_CMD_SET_HIST_LINE, curhist);
    histlinect = h->histlinect;
    histsiz = h->histsiz;
    savehistsiz = h->savehistsiz;

    if (curline_in_ring)
	linkcurline();

    return histsave_stack_pos + 1;
}

/* If pop_through > 0, pop all array items >= the 1-relative index value.
 * If pop_through <= 0, pop (-1)*pop_through levels off the stack.
 * If the (new) top of stack is from a higher locallevel, auto-pop until
 * it is not.
 */

/**/
int
saveandpophiststack(int pop_through, int writeflags)
{
    if (pop_through <= 0) {
	pop_through += histsave_stack_pos + 1;
	if (pop_through <= 0)
	    pop_through = 1;
    }
    while (pop_through > 1
     && histsave_stack[pop_through-2].locallevel > locallevel)
	pop_through--;
    if (histsave_stack_pos < pop_through)
	return 0;
    do {
	if (!nohistsave)
	    savehistfile(NULL, 1, writeflags);
	pophiststack();
    } while (histsave_stack_pos >= pop_through);
    return 1;
}