File: internals.c

package info (click to toggle)
xrn 9.02-7
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,820 kB
  • ctags: 3,233
  • sloc: ansic: 24,690; makefile: 2,685; yacc: 888; sh: 252; lex: 92; perl: 35; awk: 31; csh: 13
file content (4189 lines) | stat: -rw-r--r-- 102,262 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
#if !defined(lint) && !defined(SABER) && !defined(GCC_WALL)
static char XRNrcsid[] = "$Id: internals.c,v 1.230 1999/01/06 01:50:32 jik Exp $";
#endif

/*
 * xrn - an X-based NNTP news reader
 *
 * Copyright (c) 1988-1993, Ellen M. Sentovich and Rick L. Spickelmier.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of the University of California not
 * be used in advertising or publicity pertaining to distribution of 
 * the software without specific, written prior permission.  The University
 * of California makes no representations about the suitability of this
 * software for any purpose.  It is provided "as is" without express or
 * implied warranty.
 *
 * THE UNIVERSITY OF CALIFORNIA DISCLAIMS ALL WARRANTIES WITH REGARD TO 
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS, IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE FOR
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * internals.c: routines for handling the internal data structures
 *    calls server routines, is calls by the user interface code
 *
 */

#include "copyright.h"
#include "config.h"
#include "utils.h"
#include <X11/Xos.h>
#include <errno.h>
#include <assert.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include "avl.h"
#include "news.h"
#include "artstruct.h"
#include "newsrcfile.h"
#include "resources.h"
#include "server.h"
#include "mesg.h"
#include "error_hnds.h"
#include "save.h"
#include "xrn.h"
#include "buttons.h"
#include "internals.h"
#include "mesg_strings.h"
#include "xmisc.h"
#include "ngMode.h"
#include "artMode.h"
#include "snapshot.h"
#include "modes.h"
#include "cursor.h"
#include "varfile.h"
#include "dialogs.h"
#include "activecache.h"
#include "sort.h"
#include "killfile.h"
#include "file_cache.h"
#include "hash.h"

#ifndef R_OK
#define R_OK 4
#endif


#define BUFFER_SIZE 1024
#define FATAL 0
#define OKAY  1
/*
 * length of lines in the top text window
 */
#define LINE_LENGTH 200

/* set to the value of a group if that group has been prefetched */
static struct newsgroup *PrefetchedGroup = 0;
static struct newsgroup *PrefetchingGroup = 0;
static int PrefetchStage;
static XtWorkProc PrefetchingProc;
static XtWorkProcId prefetch_id;
static Boolean FinishingPrefetch = False;
static int InWorkProc = 0;

#define maybeInfoNow(mesg) \
	_info((mesg), !InWorkProc || FinishingPrefetch)

static void prefetchNextGroup _ARGUMENTS((struct newsgroup *));

#ifndef PREFETCH_CHUNK
#define PREFETCH_CHUNK 5
#endif
#ifndef PREFETCH_MIN_CHUNK
#define PREFETCH_MIN_CHUNK 5
#endif
#ifndef PREFETCH_CHUNK_TIME
#define PREFETCH_CHUNK_TIME 1
#endif

extern Boolean FastServer;

/*
 * next article to get when faulting in articles that are of the top
 * of the subject screen.
 */
static art_num NextPreviousArticle;
  
/* storage for all newsgroups, key is the name of the group */
avl_tree *NewsGroupTable = NIL(avl_tree);

/* number of groups in the active file */
int ActiveGroupsCount = 0;

/* number of the group currently being processed */
struct newsgroup * CurrentGroup = 0;

/* number of groups in the .newsrc file */
ng_num MaxGroupNumber = 0;

struct var_rec *cache_variables = 0;
char *cache_file;

/*
 * see if another xrn is running for this nntpserver
 */
void checkLock()
{
    char *buffer = findServerFile(app_resources.lockFile, isLongNewsrcFile(),
				  NULL);
    char host[64];
    char myhost[64];
    int pid;
    FILE *fp;
    extern int errno;

    if (!buffer) {
	/* silently ignore this condition */
	return;
    }

    if (gethostname(myhost, sizeof(myhost)) == -1) {
	(void) strcpy(myhost, "bogusHost");
    }

    if ((fp = fopen(buffer, "r")) == NULL) {
	if ((fp = fopen(buffer, "w")) == NULL) {
	    /* silently ignore this condition */
	  XtFree(buffer);
	  return;
	}
	XtFree(buffer);
	(void) fprintf(fp, "%s %d\n", myhost, getpid());
	(void) fclose(fp);
	return;
    }

    (void) fscanf(fp, "%s %d", host, &pid);

    /* see if I'm on the same host */
    if (strcmp(host, myhost) == 0) {
	/* whoa!  I am, see if the process is running */
	if ((kill(pid, 0) == -1) && (errno == ESRCH)) {
	    /* hey, it's not running.... */
	    /* why do it right when you can just do this... */
	    removeLock();
	    checkLock();
	    XtFree(buffer);
	    return;
	}
    }
    (void) fprintf(stderr, ERR_XRN_RUN_MSG , host, pid, buffer);
    XtFree(buffer);

    exit(-1);

    return;
}


void removeLock()
{
    char *buffer = findServerFile(app_resources.lockFile, True, NULL);

    if (buffer) {
	(void) unlink(buffer);
	XtFree(buffer);
    }
    return;
}


/*
 * initialize the program and the news system
 *   read newsrc, etc
 *
 *   returns: void
 *
 */
void initializeNews()
{
    char *err_buf;

    xrnBusyCursor();

    if (! (cache_file = findServerFile(app_resources.cacheFile, True, NULL))) {
	err_buf = XtMalloc(strlen(CANT_EXPAND_MSG)+MAXPATHLEN);
	(void) sprintf(err_buf, CANT_EXPAND_MSG, app_resources.cacheFile);
	ehErrorExitXRN(err_buf);
    }

    cache_variables = var_read_file(cache_file);

    start_server();

    do {
	 NewsGroupTable = avl_init_table(strcmp);
	 if (! NewsGroupTable) {
           ehErrorExitXRN(ERROR_OUT_OF_MEM_MSG);
	 }

	 if (app_resources.cacheActive) {
	   active_cache_read(cache_file);
	 }
	 else {
	   getactive(False);
	   if (! app_resources.fullNewsrc)
	     getactive(True);
	 }

	 if (readnewsrc())
	      break;
	 
       ehErrorRetryXRN(ERROR_CANT_READ_NEWSRC_MSG, True);

	 avl_free_table(NewsGroupTable, XtFree,
			(void (*) _ARGUMENTS((void *))) XtFree);
    } while (1);

    if (app_resources.cacheActive)
      rescanBackground();

    xrnUnbusyCursor();

    return;
}

static XtWorkProcId rescan_id = 0;
static int active_serial;
static ng_num rescan_group_number;

/*
  A work procedure which fetches the statistics for a single
  newsgroup, using the getgroup() function.  Give up if the group
  number we're passed in is negative or greater than MaxGroupNumber.
  When we reach MaxGroupNumber, display a message indicating that
  we're done.
  */
static Boolean rescanWorkProc(data)
XtPointer data;
{
  art_num first, last;
  int number;

#ifdef DEBUG
  fprintf(stderr, "rescanWorkProc(%d)\n", rescan_group_number);
#endif

  if (active_read > active_serial) {
    rescan_id = 0;
    return True;
  }

  if (rescan_group_number == MaxGroupNumber) {
    char *buf = XtMalloc(strlen(RESCANNING_BACKGROUND_MSG) + strlen(DONE_MSG) +
			 2);
    (void) sprintf(buf, "%s %s", RESCANNING_BACKGROUND_MSG, DONE_MSG);
    INFO(buf);
    XtFree(buf);
    rescan_group_number++;
  }

  if (rescan_group_number > MaxGroupNumber) {
    rescan_id = 0;
    return True;
  }

  if (Newsrc[rescan_group_number] == CurrentGroup) {
    rescan_group_number++;
    return False;
  }

  if (! IS_SUBSCRIBED(Newsrc[rescan_group_number])) {
    rescan_group_number++;
    return False;
  }

  if (! getgroup(Newsrc[rescan_group_number], &first, &last, &number, False)) {
    articleArrayResync(Newsrc[rescan_group_number], first, last, number);
    redrawNewsgroupTextWidget(Newsrc[rescan_group_number]->name, False);
    resetArticleNewsgroupsList();
  }

  if ((Newsrc[rescan_group_number] == PrefetchingGroup) ||
      (Newsrc[rescan_group_number] == PrefetchedGroup))
    resetPrefetch();
  else
    doPrefetch(0, 0, 0, 0);
    
  rescan_group_number++;
  return False;
}
    

/*
  Do a NEWGROUPS command to check for new groups, then start a
  background procedure to rescan subscribed groups in the .newsrc.
  */
void rescanBackground()
{
#ifdef DEBUG
  fprintf(stderr, "rescanBackground()\n");
#endif

  getactive(True);

  infoNow(RESCANNING_BACKGROUND_MSG);

  if (rescan_id)
    XtRemoveWorkProc(rescan_id);
  active_serial = active_read;
  rescan_group_number = 0;
  rescan_id = XtAppAddWorkProc(TopContext, rescanWorkProc, 0);
}

void cancelRescanBackground()
{
#ifdef DEBUG
  fprintf(stderr, "cancelRescanBackground()\n");
#endif

  if (rescan_id) {
    XtRemoveWorkProc(rescan_id);
    rescan_id = 0;
  }
}

/*
 * get the active file again and grow the Newsrc array if necessary
 */
void rescanServer(
		  _ANSIDECL(Boolean,	force_list)
		  )
     _KNRDECL(Boolean,	force_list)
{
    cancelPrefetch();

    /* update the newsrc file */
    while (!updatenewsrc())
      ehErrorRetryXRN(ERROR_CANT_UPDATE_NEWSRC_MSG, True);

#if !defined(NNTP_REREADS_ACTIVE_FILE)
    stop_server();
    start_server();
#endif

    if (app_resources.cacheActive && !force_list) {
      rescanBackground();
      return;
    }

    getactive(False);
    if (! app_resources.fullNewsrc)
      getactive(True);

    return;
}


#define lsDestroy(lst) \
    if (lst != NIL(struct list)) { \
	struct list *_next; \
	do { \
	    _next = lst->next; \
	    FREE(lst); \
	    lst = _next; \
	} while (lst != NIL(struct list)); \
    }

/*
 * accurately count the number of unread articles in a group
 *
 *   returns: the number of unread articles in the group
 */
static int unreadArticleCount _ARGUMENTS((struct newsgroup *));

static int unreadArticleCount(newsgroup)
    struct newsgroup *newsgroup;
{
    struct article *art;
    art_num first, last;
    int count = 0;

    if (EMPTY_GROUP(newsgroup) ||
	((newsgroup->first == 0) && (newsgroup->last == 0)))
	return 0;

    for (art = artListFirst(newsgroup, &first, &last);
	 art; art = artStructNext(newsgroup, art, &first, &last)) {
	if (IS_UNREAD(art) && IS_AVAIL(art))
	    count += last - first + 1;
    }

    return count;
}


/*
 * accurately count the number of articles in a group
 *
 *   returns: the total number of articles in the group
 */
static int totalArticleCount _ARGUMENTS((struct newsgroup *));

static int totalArticleCount(newsgroup)
    struct newsgroup *newsgroup;
{
    struct article *art;
    art_num first, last;
    int count = 0;
  
    if (EMPTY_GROUP(newsgroup) ||
	((newsgroup->first == 0) && (newsgroup->last == 0)))
	return 0;
    
    for (art = artListFirst(newsgroup, &first, &last);
	 art; art = artStructNext(newsgroup, art, &first, &last)) {
	if (IS_AVAIL(art))
	    count += last - first + 1;
    }

    return count;
}


/*
  When this function returns false, it modifies the article list for
  the newsgroup as a side effect, so any outstanding article
  structures in the caller should be considered invalid.
  */
Boolean articleIsAvailable(newsgroup, i)
    struct newsgroup *newsgroup;
    art_num i;
{
    struct article *art;

    art = artStructGet(newsgroup, i, True);

    if (art->file && *art->file && !IS_ALL_HEADERS(art) && !IS_ROTATED(art) &&
	!IS_XLATED(art) &&
	(access(file_cache_file_name(FileCache, *art->file), R_OK) == 0)) {
      artStructSet(newsgroup, &art);
      return True;
    }

    CLEAR_SUBJECT(art);
    artStructSet(newsgroup, &art);

    (void) fillUpArray(newsgroup, i, i, False, False);

    art = artStructGet(newsgroup, i, False);
    if (art->subject)
      return True;
    else
      return False;
}


/*
  Find the first unread article, or the last article if unread_only is
  false and there are no unread articles, in a group and set the
  group's 'current' to it.  If "check_available" is true, actually
  contacts the NNTP server to verify that the article is available.
 
  Returns True if the group's current article was modified in a way
  which might require the group to be prefetched again, False
  otherwise.

  If the "finished" parameter is non-null, then this function will
  only make "max" attempts to find a current article by contacting the
  NNTP server.  If it succeeds, the parameter will be filled in True;
  otherwise, it'll be filled in False.
  */
static Boolean setCurrentArticle _ARGUMENTS((struct newsgroup *,
					     Boolean, Boolean,
					     Boolean *, int *));

static Boolean setCurrentArticle(
				 _ANSIDECL(struct newsgroup *,	newsgroup),
				 _ANSIDECL(Boolean,		unread_only),
				 _ANSIDECL(Boolean,		check_available),
				 _ANSIDECL(Boolean *,		finished),
				 _ANSIDECL(int *,		max_ptr)
				 )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(Boolean,			unread_only)
     _KNRDECL(Boolean,			check_available)
     _KNRDECL(Boolean *,		finished)
     _KNRDECL(int *,			max_ptr)
{
    struct article *art;
    art_num i, start, avail = 0;
    art_num orig = newsgroup->current;
    int max;

    if (max_ptr)
      max = *max_ptr;
    else
      max = 0;

    if (app_resources.onlyShow > 0) {
	/* if the resource 'onlyShow' is > 0, then mark all but the last
	   'onlyShow' articles as read */
	for (start = newsgroup->last;
	     start >= newsgroup->first && (avail < app_resources.onlyShow);
	     start--) {
	    art = artStructGet(newsgroup, start, False);
	    if (IS_UNREAD(art) && IS_AVAIL(art))
		avail++;
	}
	start++;
    }
    else {
	start = newsgroup->first;
    }

    for (i = start; i<= newsgroup->last; i++) {
	art = artStructGet(newsgroup, i, False);
	if (IS_UNREAD(art) && IS_AVAIL(art)) {
	  if (!check_available || articleIsAvailable(newsgroup, i)) {
	    if (finished)
	      *finished = True;
	    newsgroup->current = i;
	    goto done;
	  }
	  else if (finished && ! --max) {
	    *finished = False;
	    goto done;
	  }
	}
    }

    if (unread_only) {
	newsgroup->current = newsgroup->last + 1;
    }
    else {
	for (i = newsgroup->last; i >= newsgroup->first; i--) {
	    art = artStructGet(newsgroup, i, False);
	    if (IS_AVAIL(art)) {
	      if (!check_available || articleIsAvailable(newsgroup, i)) {
		if (finished)
		  *finished = True;
		newsgroup->current = i;
		goto done;
	      }
	      else if (finished && ! --max) {
		*finished = False;
		goto done;
	      }
	    }
	}
	newsgroup->current = newsgroup->last + 1;
    }

  done:
    return ((orig != newsgroup->current) &&
	    (newsgroup->current <= newsgroup->last));
}

/*
 * convert an array of strings (of 'count' items) into one big string
 * with each substring seperated by newlines
 *
 * bytes is the sum of the string lengths of the strings
 *
 * this routine takes care of allocating the big string
 *
 */
static char * arrayToString _ARGUMENTS((char **, int, int));

static char * arrayToString(array, count, bytes)
    char **array;
    int count;
    int bytes;
{
    char *bigString, *end;
    int i;

    /* bytes for the strings, count for the newlines, 1 for the zero byte */
    bigString = ARRAYALLOC(char, (bytes + count + 1));
    bigString[0] = '\0';

    end = bigString;
    for (i = 0; i < count; i++) {
	(void) strcpy(end, array[i]);
	end += utStrlen(array[i]);
	*end = '\n';
	end++;
    }

    *end = '\0';

    return bigString;
}


int unreadNews()
{
    int i, count = 0;
    struct newsgroup *newsgroup;

    for (i = 0; i < MaxGroupNumber; i++) {
	newsgroup = Newsrc[i];
	if (IS_SUBSCRIBED(newsgroup) && watchingGroup(newsgroup->name))
	    count += unreadArticleCount(newsgroup);
    }
    return count;
}

/*
  Find the line in the specified newsgroup list (as returned by
  unreadGroups, below) closest in the newsrc file to the specified
  group, but not before it, and return the index of the first
  character on the line containing the found group.  If the specified
  group is actually in the newsgroup list, return the index of the
  first character on the line containing the specified group.

  When returning a line containing a newsgroup other than the one
  specified, copies the new group into group_name, after reallocating
  it so that it is just long enough to hold it.

  When returning 0 because no match could be found, makes group_name
  an empty string.
  */
int getNearbyNewsgroup(list, group_name)
    char *list;
    char **group_name;
{
    struct newsgroup *group;
    char *ptr;
    char *match_group = 0;

    if (! group_name)
	return 0;

    if (! *group_name) {
	*group_name = XtRealloc(*group_name, 1);
	**group_name = '\0';
    }

    if (! **group_name) {
	currentGroup(NEWSGROUP_MODE, list, group_name, 0);
	return 0;
    }

    if (! avl_lookup(NewsGroupTable, *group_name, (char **) &group)) {
	**group_name = '\0';
	return 0;
    }

    /*
      First, check the easy case -- the group is in the string.
      */
    for (ptr = list;
	 ptr && (ptr = strstr(ptr, group->name));
	 ptr = index(ptr, '\n')) {
	while ((*ptr != '\n') && (ptr > list))
	    ptr--;
	if (ptr > list)
	    ptr++;
	currentGroup(NEWSGROUP_MODE, ptr, &match_group, 0);
	if (! strcmp(group->name, match_group))
	    break;
    }

    if (ptr) {
	XtFree(match_group);
	return ptr - list;
    }

    /*
      Well, OK, that didn't work.  Algorithm: Figure out the position
      in the Newsrc array of each newsgroup in the newsgroup list in
      order, until we find one whose position is greater than or equal
      to the position of the group we're looking for.  Return that
      group's position in the list.

      If all the newsgroups in the list are earlier in the Newsrc than
      the one we're looking for, return the index of the beginning of
      the end of the list.
      */

    for (ptr = list;
	 ptr && *ptr;
	 ptr = (ptr = index(ptr, '\n')) ? (ptr + 1) : 0) {
	char *gptr;

	currentGroup(NEWSGROUP_MODE, ptr, &match_group, 0);
	if (! avl_lookup(NewsGroupTable, match_group, &gptr))
	    continue;
	if (((struct newsgroup *)gptr)->newsrc >= group->newsrc) {
	    XtFree(*group_name);
	    *group_name = match_group;
	    return ptr - list;
	}
    }

    XtFree(match_group);

    *group_name = XtRealloc(*group_name, 1);
    **group_name = '\0';

    if (ptr && *ptr)
	return ptr - list;

    /*
      This shouldn't ever really happen, because the loop above should
      terminate when it gets to the last line and realizes that
      there's nothing on it, i.e., ptr is true but *ptr is false.
      Just in case, though, we'll put a return here.
      */
    return 0;
}


/*
 * build and return a string of information about groups that need to be read
 */
char *unreadGroups(line_length, mode)
    int line_length;
    int mode;	/* 0 for unread groups, 1 for all subscribed to groups */
{
    static char *dummy = NULL;
    static int dummy_size = 0, padding_size = 0;
    struct newsgroup *newsgroup;
    ng_num i;
    int unread, j;
    int bytes = 0, subscribedGroups = 0;
    char *string, **ar;
    int newsgroup_length = line_length - NEWS_GROUP_LINE_CHARS;

    if (newsgroup_length < 0)
	newsgroup_length = 0;

    ar = ARRAYALLOC(char *, MaxGroupNumber);

    if (! dummy_size) {
      dummy_size = LINE_LENGTH;
      dummy = XtMalloc(dummy_size);
      padding_size = strlen(NEWSGROUPS_INDEX_MSG) + strlen(UNREAD_MSG) +
	strlen(NEWS_IN_MSG) + 10 /* for unread count */ + strlen(NOT_ONE_MSG) +
	10 /* for old count */ + 1 /* for null */;
    }

    for (i = 0; i < MaxGroupNumber; i++) {
	newsgroup = Newsrc[i];

	if (IS_SUBSCRIBED(newsgroup) &&
	   (((unread = unreadArticleCount(newsgroup)) > 0) || mode)) {
	    int total = totalArticleCount(newsgroup);
	    while (dummy_size < padding_size + 
		   MAX(newsgroup_length, strlen(newsgroup->name))) {
	      dummy_size *= 2;
	      dummy = XtRealloc(dummy, dummy_size);
	    }
	    (void) sprintf(dummy, NEWSGROUPS_INDEX_MSG,
	                   (unread > 0 ? UNREAD_MSG : ""),
	                   (total > 0 ? NEWS_IN_MSG : ""),
			   -newsgroup_length, newsgroup->name, unread,
			   ((unread != 1) ? NOT_ONE_MSG : " "),
			   total - unread,
			   /* It's OK if you get warnings about this
			      argument not being used when compiling
			      anything besides the French version. */
			   ((total - unread != 1) ? NOT_ONE_MSG : " "));

	    ar[subscribedGroups++] = XtNewString(dummy);
	    bytes += strlen(dummy);
	}
    }

    string = arrayToString(ar, subscribedGroups, bytes);
    for (j = 0; j < subscribedGroups; j++) {
	FREE(ar[j]);
    }
    FREE(ar);
    return string;
}

/*
  Change a group's status so that it's no longer considered new.
  */
void clearNew(group)
char *group;
{
  struct newsgroup *newsgroup;
  
  if (! avl_lookup(NewsGroupTable, group, (char **) &newsgroup))
    return;

  CLEAR_NEW(newsgroup);
}


/*
 * determine the newsgroups that are not in the .newsrc file
 *
 *   returns a string representing the information
 */
char * newGroups()
{
    int count = 0, bytes = 0;
    avl_generator *gen;
    char *key, *value;
    char **ar;
    char *string;

    ar = ARRAYALLOC(char *, ActiveGroupsCount);

    gen = avl_init_gen(NewsGroupTable, AVL_FORWARD);
    if (! gen) {
      ehErrorExitXRN(ERROR_OUT_OF_MEM_MSG);
    }

    while (avl_gen(gen, &key, &value)) {
	struct newsgroup *newsgroup = (struct newsgroup *) value;

	if (IS_NEW(newsgroup)) {
	    ar[count++] = newsgroup->name;
	    bytes += utStrlen(newsgroup->name);
	}
    }

    avl_free_gen(gen);

    /* no new groups return */
    if (count == 0) {
	FREE(ar);	
	return NIL(char);
    }

    string = arrayToString(ar, count, bytes);
    FREE(ar);
    
    return string;
}

void freePrefetchedGroupArticle()
{
#ifdef DEBUG
    fprintf(stderr, "freePrefetchedGroupArticle()\n");
#endif

    if (PrefetchedGroup) {
	struct article *art = artStructGet(PrefetchedGroup,
					   PrefetchedGroup->current, True);
	if (IS_FETCHED(art))
	    CLEAR_FILE(art);
	artStructSet(PrefetchedGroup, &art);
    }

#ifdef DEBUG
    fprintf(stderr, "freePrefetchedGroupArticle() done\n");
#endif

    return;
}

static void adjustPrefetchChunk _ARGUMENTS((long, long, int *));

static void adjustPrefetchChunk(actual_time, desired_time, chunk_size)
    long actual_time, desired_time;
    int *chunk_size;
{
#ifdef DEBUG
    fprintf(stderr, "adjustPrefetchChunk(%ld, %ld, %d)\n", actual_time,
	    desired_time, *chunk_size);
#endif

    if (! desired_time)
	goto done;
    if (! actual_time) {
	*chunk_size *= 2;
    }
    else {
	*chunk_size = *chunk_size * desired_time / actual_time;
    }

  done:
    if (*chunk_size < PREFETCH_MIN_CHUNK)
      *chunk_size = PREFETCH_MIN_CHUNK;
#ifdef DEBUG
    fprintf(stderr, "adjustPrefetchChunk(%ld, %ld, %d) done\n",
	    actual_time, desired_time, *chunk_size);
#endif
    return;
}


/*
 *   release some resources
 *
 *   returns: void
 */
void releaseNewsgroupResources(newsgroup)
    struct newsgroup *newsgroup;
{
#ifdef DEBUG
    fprintf(stderr, "releaseNewsgroupResources(%s)\n",
	newsgroup ? newsgroup->name : "NULL");
#endif /* DEBUG */

    if (newsgroup) {
	struct article *original, copy;
	art_num artnum;

	groupSnapshotFree(newsgroup);

	if (newsgroup->thread_table) {
	  hash_table_destroy(newsgroup->thread_table);
	  newsgroup->thread_table = 0;
	}

	if ((newsgroup->last == 0) || EMPTY_GROUP(newsgroup)) {
	    return;
	}

	for (artnum = newsgroup->first; artnum <= newsgroup->last; artnum++) {
	    original = artStructGet(newsgroup, artnum, False);
	    copy = *original;

	    CLEAR_ALL_NO_FREE(&copy);

	    SET_UNMARKED(&copy);
	    SET_STRIPPED_HEADERS(&copy);
	    SET_UNROTATED(&copy);
	    SET_UNXLATED(&copy);
	    SET_UNLISTED(&copy);

	    artStructReplace(newsgroup, &original, &copy, artnum);
	}
    }

    return;
}


/*
 * update an article array if the first and/or last article numbers change
 *
 *  returns: void
 */
void articleArrayResync(newsgroup, first, last, number)
    struct newsgroup *newsgroup;
    art_num first, last;
    int number;
{
    struct article *art, copy;
    int i;

    /*
     * if there are actually no articles in the group, free up the
     * article array and set the first/last values
     */
       
    if (number == 0) {
	artListFree(newsgroup);
	newsgroup->first = newsgroup->last + 1;
	return;
    }
    
    /* refuse to resync if last == 0 */
    if (last == 0) {
	return;
    }

    if (first > last) {
	/* all articles have been removed */

	artListFree(newsgroup);
	newsgroup->first = newsgroup->last + 1;
	return;
    }

    /* don't allow first or last to go backwards!!! */
    if (first < newsgroup->first)
	first = newsgroup->first;
    if (last < newsgroup->last)
	last = newsgroup->last;

    if (! artListFirst(newsgroup, 0, 0)) {
	newsgroup->first = first;
	newsgroup->last = last;
	artListSet(newsgroup);
    }
    else {
	copy.status = ART_CLEAR_READ;

	CLEAR_ALL_NO_FREE(&copy);

	SET_UNAVAIL(&copy);
	for (i = newsgroup->first; i < first; i++) {
	    art = artStructGet(newsgroup, i, False);
	    artStructReplace(newsgroup, &art, &copy, i);
	}

	copy.status = ART_CLEAR;
	for (i = MAX(newsgroup->last + 1, first); i <= last; i++) {
	    art = artStructGet(newsgroup, i, False);
	    artStructReplace(newsgroup, &art, &copy, i);
	}

	newsgroup->first = first;
	newsgroup->last = last;
    }
}


char *localKillFile(newsgroup, mode)
    struct newsgroup *newsgroup;
    int mode;
{
    static char buffer[BUFFER_SIZE];
    char *ptr;
    int i;

    if (!createNewsDir()) {
	return NIL(char);
    }

    (void) strcpy(buffer, app_resources.expandedSaveDir);
    i = strlen(buffer);

    buffer[i++] = '/';

    for (ptr = newsgroup->name; *ptr != 0; ptr++) {
	if (*ptr == '.') {
	    if (mode) {
		buffer[i] = '\0';
		(void) mkdir(buffer, 0777);
	    }
	    buffer[i] = '/';
	    i++;
	} else {
	    buffer[i++] = *ptr;
	}
    }
    buffer[i] = '\0';
    if (mode) {
	(void) mkdir(buffer, 0777);
    }
    (void) sprintf(&buffer[i], "/%s", app_resources.killFileName);

    return buffer;
}

char * globalKillFile()
{
    static char buffer[BUFFER_SIZE];

    if (!createNewsDir()) {
	return NIL(char);
    }
    (void) sprintf(buffer, "%s/%s", app_resources.expandedSaveDir,
		   app_resources.killFileName);
    return buffer;
}


/*
  Convert a string to a regular expression matching that string.  The
  resulting regular expression is *not* anchored, i.e., it will match
  any string of which the string passed into it is a subsctring.

  The returned string is static memory which is not valid after the
  next call to this function.
  */
char *stringToRegexp(input, max_length)
    char *input;
{
    static char output[BUFFER_SIZE];
    char *inptr, *outptr;

    max_length -= 2; /* to make room for braces */
    
    /* quote or get rid of all magic characters */
    for (inptr = input, outptr = output;
	 (*inptr && (outptr - output < sizeof(output) - 4));
	 inptr++, outptr++) {
	switch (*inptr) {
	case '/':
	case '\\':
	case '[':
	/* Theoretically, ']' shouldn't be special when it isn't
	   preceded by '[', but it doesn't hurt to be cautious. */
	case ']':
	case '.':
	case '^':
	case '*':
	case '$':
	    *outptr++ = '\\';
	    *outptr = *inptr;
	    break;
	/*
	  Some characters can't be backslashed, because they are
	  literal when backslashed in some regular expression
	  libraries, and when not backslashed in others.  We could do
	  different things here based on whether SYSV_REGEX is
	  defined, but that seems like a bad idea, because it means
	  that the KILL file will have a different meaning based on
	  what kind of system it's read on.  We want KILL file regexps
	  to be portable.

	  Some day, we'll use the GNU regexp library or something on
	  all platforms, and we'll be able to do the right thing for
	  all characters.  In the meantime, we'll check for these
	  special characters by putting them inside square braces,
	  which means the same thing in all of the regular expression
	  packages.
	*/
	    /*
	      The POSIX regexp functions apparently treat \?, \+,
	      \{, and \} specially.
	      */
	case '{':
	case '}':
	case '?':
	case '+':
	case '(':
	/* On some systems, it's an error for there to be a ')' with
	   no matching '(' before it. */
	case ')':
	    *outptr++ = '[';
	    *outptr++ = *inptr;
	    *outptr = ']';
	    break;
	default:
	    *outptr = *inptr;
	    break;
	}
	if (outptr - output >= max_length)
	  break;
    }
    *outptr = '\0';
    return output;
}


/*
 * kill all subjects in the newsgroup that match the kill
 * orders in fp.
 *
 * Returns True if it gets to the end of the group, False otherwise.
 */
/* XXX  THIS ROUTINE REALLY NEEDS TO BE CLEANED UP */
static Boolean killArticles _ARGUMENTS((struct newsgroup *, int *));

static Boolean killArticles(newsgroup, max)
    struct newsgroup *newsgroup;
    int *max;
{
    struct article *art;
    art_num i, start, last;
    char *subject, *from, *newsgroups, *date, *id, *references, *xref, *approved;
    int scount = 0, kcount = 0, mcount = 0, tcount = 0;
    int mesg_name;
    kill_entry *entry;
    kill_file_iter_handle handle = 0;
    kill_file *kf;
    int cur_mode = KILL_LOCAL;

    kf = (kill_file *)newsgroup->kill_file;

    start = MAX(newsgroup->current, MIN(kf->thru + 1, newsgroup->last));
    do {
	art = artStructGet(newsgroup, start, False);
	if (IS_KILLED(art))
	    start++;
    } while (IS_KILLED(art) && (start <= newsgroup->last));

    if (max)
	last = MIN(newsgroup->last, start + *max - 1);
    else
	last = newsgroup->last;

    for (i = start; i <= last; i++) {
	art = artStructGet(newsgroup, i, False);
	if (IS_KILLED(art) || IS_UNAVAIL(art))
	    last = MIN(newsgroup->last, last + 1);
    }

    if (kf->count)
      kf->flags |= KF_CHANGED;

    kf->thru = MAX(kf->thru, MIN(start, last));

    if (start > last)
	return True;

    kf->thru = last;

    while (1) {
      if (! (entry = kill_file_iter(newsgroup, cur_mode, &handle))) {
	if (cur_mode != KILL_LOCAL)
	  break;
	cur_mode = KILL_GLOBAL;
	handle = 0;
	continue;
      }

      if (entry->type != KILL_ENTRY)
	continue;

      mesg_name = newMesgPaneName();

      for (i = start; i <= last; i++) {
	int field_count = 0;

	art = artStructGet(newsgroup, i, False);

	/* short cut */
	if (IS_KILLED(art) || IS_UNAVAIL(art) ||
	    ((entry->entry.action_flags & (KILL_JUNK|KILL_SUBTHREAD|KILL_THREAD))
	     && IS_READ(art)) ||
	    ((entry->entry.action_flags & KILL_MARK) && IS_UNREAD(art)))
	  continue;

#define CHECK_FIELD(flag, name) \
	if (entry->entry.check_flags & flag) { \
	  if ((name = art->name)) \
	    field_count++; \
	} \
	else \
	  name = 0;

	CHECK_FIELD(KILL_SUBJECT, subject);
	CHECK_FIELD(KILL_AUTHOR, from);
	CHECK_FIELD(KILL_NEWSGROUPS, newsgroups);
	CHECK_FIELD(KILL_DATE, date);
	CHECK_FIELD(KILL_ID, id);
	CHECK_FIELD(KILL_REFERENCES, references);
	CHECK_FIELD(KILL_XREF, xref);
	CHECK_FIELD(KILL_APPROVED, approved);

	if (field_count) {
	  struct article copy;
	  unsigned char changed = FALSE;

	  copy = *art;

#ifdef POSIX_REGEX
# define KILL_MATCH(a)	((a) && (! regexec(&entry->entry.reStruct, (a), 0, 0, 0)))
#else
# ifdef SYSV_REGEX
#  define KILL_MATCH(a)	((a) && (regex(entry->entry.reStruct, (a)) != NULL))
# else
#  define KILL_MATCH(a)	((a) && re_exec(a))
# endif
#endif

	  if (KILL_MATCH(subject) || KILL_MATCH(from) ||
	      KILL_MATCH(date) || KILL_MATCH(newsgroups) ||
	      KILL_MATCH(id) || KILL_MATCH(references) ||
	      KILL_MATCH(xref) || KILL_MATCH(approved)) {
	    kill_update_last_used(kf, entry);

	    switch (entry->entry.action_flags) {
	    case KILL_SUBTHREAD:
	    case KILL_THREAD: {
	      char *id = 0, *quoted_id;

	      if (entry->entry.action_flags == KILL_THREAD)
		id = getFirstReference(art->references);
	      if (! id)
		id = art->id;

	      quoted_id = stringToRegexp(id, MAX_KILL_PATTERN_VALUE_LENGTH);
	      add_kill_entry(newsgroup, cur_mode, "References", quoted_id);
	      if (index(app_resources.verboseKill, 't'))
		mesgPane(XRN_INFO, mesg_name, KILL_THREAD_MSG, art->subject);
	      tcount++;
	      /* fall through to kill the article itself */
	    }
	    case KILL_JUNK:
	      SET_READ(&copy);
	      if (index(app_resources.verboseKill, 'j')) {
		mesgPane(XRN_INFO, mesg_name, KILL_KILLED_MSG,
			 art->subject);
	      }
	      kcount++;
	      changed = TRUE;
	      break;

	    case KILL_MARK:
	      SET_UNREAD(&copy);
	      if (index(app_resources.verboseKill, 'm')) {
		mesgPane(XRN_INFO, mesg_name, KILL_UNREAD_MSG,
			 art->subject);
	      }
	      mcount++;
	      changed = TRUE;
	      break;

	    case KILL_SAVE:
	      (void) saveArticle(NIL(char), newsgroup, i, False,
				 False);
	      if (index(app_resources.verboseKill, 's')) {
		mesgPane(XRN_INFO, mesg_name, KILL_SAVED_MSG,
			 art->subject);
	      }
	      scount++;
	      changed = TRUE;
	      break;
	    default:
	      mesgPane(XRN_SERIOUS, mesg_name, UNKNOWN_FUNC_RESPONSE_MSG,
		       entry->entry.action_flags, "kill_file_iter(action_flags)",
		       "killArticles");
	      break;
	    }
	  }

	  if (changed)
	    artStructReplace(newsgroup, &art, &copy, i);
	}
      }
    }

    for (i = start; i <= last; i++) {
	art = artStructGet(newsgroup, i, True);
	SET_KILLED(art);
	artStructSet(newsgroup, &art);
    }

    mesg_name = newMesgPaneName();

#define printcount(c,cmd,m) \
    if (c && index(app_resources.verboseKill, cmd)) { \
	mesgPane(XRN_INFO, mesg_name, m, c, ((c==1) ? "" : NOT_ONE_MSG), \
		 newsgroup->name); \
    }

    printcount(kcount, 'j', COUNT_KILLED_MSG);
    printcount(mcount, 'm', COUNT_UNREAD_MSG);
    printcount(scount, 's', COUNT_SAVED_MSG);
    printcount(tcount, 't', COUNT_THREAD_MSG);

#undef printcount

    if (last == newsgroup->last)
	return True;
    else {
      if (max)
	*max = last - start + 1;
      return False;
    }
}

    
/*
 * mark articles as read if in the kill files
 */
static Boolean checkKillFiles _ARGUMENTS((struct newsgroup *, Boolean));
    
static Boolean checkKillFiles(
			      _ANSIDECL(struct newsgroup *,	newsgroup),
			      _ANSIDECL(Boolean,		prefetching)
			      )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(Boolean,			prefetching)
{
    static int chunk_size;
    long start WALL(= 0), end;
    static struct newsgroup *last_group = 0;
    char dummy[LABEL_SIZE];
    Boolean finished = True;
    fetch_flag_t fetched = newsgroup->fetch;

#ifdef DEBUG
    fprintf(stderr, "checkKillFiles(%s, %d)\n", newsgroup->name, prefetching);
#endif

    /*
      Make sure the local and global kill files for the group are read in.
      */
    read_local_kill_file(newsgroup);
    read_global_kill_file(newsgroup);

    if (fetched != newsgroup->fetch) {
      finished = False;
      goto done;
    }

    if (! has_kill_files(newsgroup))
      goto done;

    (void) sprintf(dummy, PROCESS_KILL_FOR_MSG, newsgroup->name);
    maybeInfoNow(dummy);

    /*
      Reset the chunk size for each newsgroup, because different
      newsgroups have different KILL files and therefore will take
      different amounts of time to kill.
      */
    if (last_group != newsgroup) {
	chunk_size = PREFETCH_CHUNK;
	last_group = newsgroup;
    }
    if (prefetching)
	start = time(0);
    
    finished = killArticles(newsgroup, prefetching ? &chunk_size : 0);

    if (prefetching && !finished) {
	end = time(0);
	adjustPrefetchChunk(end - start, PREFETCH_CHUNK_TIME, &chunk_size);
    }

    if (finished) {
	(void) sprintf(dummy, PROCESS_KILL_FOR_MSG, newsgroup->name);
	(void) strcat(dummy, " ");
	(void) strcat(dummy, DONE_MSG);
	INFO(dummy);
    }

done:
#ifdef DEBUG
    fprintf(stderr, "checkKillFiles(%s, %d) = %d\n",
	    newsgroup->name, prefetching, finished);
#endif
    return finished;

}


void finishPrefetch()
{
    struct newsgroup *our_group = PrefetchingGroup;

#ifdef DEBUG
    fprintf(stderr, "finishPrefetch()\n");
#endif

    FinishingPrefetch = True;
    while (our_group == PrefetchingGroup)
	(*PrefetchingProc)(PrefetchingGroup);
    FinishingPrefetch = False;

#ifdef DEBUG
    fprintf(stderr, "finishPrefetch() done\n");
#endif
}

void resetPrefetch()
{
  struct newsgroup *newsgroup = 0;

  if (PrefetchedGroup) {
    newsgroup = PrefetchedGroup;
    PrefetchedGroup = 0;
  }
  else if (PrefetchingGroup) {
    newsgroup = PrefetchingGroup;
    PrefetchingGroup = 0;
    XtRemoveWorkProc(prefetch_id);
  }

  if (newsgroup)
    prefetchGroup(newsgroup->name);

}
    
void cancelPrefetch()
{
    char msg[LABEL_SIZE];

#ifdef DEBUG
    fprintf(stderr, "cancelPrefetch()\n");
#endif

    if (PrefetchedGroup) {
	freePrefetchedGroupArticle();
	releaseNewsgroupResources(PrefetchedGroup);
    }

    if (PrefetchingGroup) {
	releaseNewsgroupResources(PrefetchingGroup);
	(void) sprintf(msg, PREFETCHING_MSG, PrefetchingGroup->name);
	(void) strcat(msg, " ");
	(void) strcat(msg, ABORTED_MSG);
	INFO(msg);
    }

    PrefetchedGroup = 0;
    PrefetchingGroup = 0;

#ifdef DEBUG
    fprintf(stderr, "cancelPrefetch() done\n");
#endif
}

static int art_num_compare _ARGUMENTS((void *, void *));

static int art_num_compare(key1, key2)
     void *key1, *key2;
{
  return (art_num)key1 - (art_num)key2;
}

static char *backTo _ARGUMENTS((char *, char *, char));

static char *backTo(
		    _ANSIDECL(char *,	start),
		    _ANSIDECL(char *,	ptr),
		    _ANSIDECL(char,	character)
		    )
     _KNRDECL(char *,	start)
     _KNRDECL(char *,	ptr)
     _KNRDECL(char,	character)
{
  for (ptr--; ptr >= start; ptr--)
    if (*ptr == character)
      return ptr;
  return 0;
}

#define THREAD_IT(art) ((listed_or_read == ART_LISTED) ? \
			IS_LISTED(art) : IS_UNREAD(art))

static Boolean threadIncremental _ARGUMENTS((struct newsgroup *,
					     int *,
					     art_num, art_num,
					     int));

static Boolean threadIncremental(
				 _ANSIDECL(struct newsgroup *,	newsgroup),
				 _ANSIDECL(int *,		stage),
				 _ANSIDECL(art_num,		first),
				 _ANSIDECL(art_num,		last),
				 _ANSIDECL(int,			listed_or_read)
				 )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(int *,			stage)
     _KNRDECL(art_num,			first)
     _KNRDECL(art_num,			last)
     _KNRDECL(int,			listed_or_read)
{
  static int chunk_size = PREFETCH_CHUNK;
  time_t start_time WALL (= 0), end_time;
  art_num i, done_count = 0;
  char dummy[LABEL_SIZE];

  if (! (newsgroup->fetch & FETCH_THREADS))
    return True;

  if (stage) {
    if (*stage != PREFETCH_THREAD_STAGE)
      return True;
    start_time = time(0);
  }

  if (! newsgroup->thread_table) {
    art_num this_first, this_last;
    art_num count = 0;
    struct article *this_art;

    (void) sprintf(dummy, THREADING_FOR_MSG, newsgroup->name);
    maybeInfoNow(dummy);

    this_art = artStructGet(newsgroup, first, False);
    if (artStructNext(newsgroup, this_art, &this_first, &this_last))
      this_last--;
    else
      this_last = last;
    this_first = first;

    do {
      if (THREAD_IT(this_art))
	count += this_last - this_first + 1;
      this_art = artStructNext(newsgroup, this_art, &this_first, &this_last);
    } while (this_art);

    if (! count)
      /* We can't thread yet because we haven't decided which articles
	 to display. */
      return True;

    newsgroup->thread_table = hash_table_create(count,
						hash_string_calc,
						hash_string_compare,
						art_num_compare,
						0, 0);

    for (i = first; i <= last; i++) {
      struct article *art = artStructGet(newsgroup, i, False);
      if (art->id && THREAD_IT(art)) {
	int ret = hash_table_insert(newsgroup->thread_table,
				    (void *)art->id, (void *)i, 0);
	assert(ret);
      }
    }

    if (stage)
      return False;
  }

  
  for (i = first; (i <= last) && (! stage || (done_count < chunk_size)); i++) {
    struct article *art = artStructGet(newsgroup, i, False), copy;
    char *references, *ptr;
    art_num parent;
    copy = *art;

    if (copy.parent || !THREAD_IT(&copy))
      continue;

    if (! (copy.references && *copy.references)) {
      copy.parent = (art_num)-1;
      artStructReplace(newsgroup, &art, &copy, i);
      continue;
    }

    done_count++;

    references = XtNewString(copy.references);

    for (ptr = strrchr(references, '>'); ptr;
	 ptr = backTo(references, ptr, '>')) {
      *(ptr + 1) = '\0';
      ptr = backTo(references, ptr, '<');

      if (! ptr)
	break;

      if ((parent = (art_num)hash_table_retrieve(newsgroup->thread_table,
						 (void *)ptr, 0)) !=
	  (art_num)HASH_NO_VALUE) {
	struct article *parent_struct = artStructGet(newsgroup, parent, True);

	copy.parent = parent;
	artStructAddChild(parent_struct, i);
	artStructSet(newsgroup, &parent_struct);
	break;
      }
    }

    XtFree(references);

    if (! copy.parent)
      copy.parent = (art_num)-1;
    artStructReplace(newsgroup, &art, &copy, i);
  }

  if (i > last) {
    for (i = first; i <= last; i++) {
      struct article *art = artStructGet(newsgroup, i, False);
      if (art->parent == (art_num)-1) {
	struct article copy;
	copy = *art;
	CLEAR_PARENT(&copy);
	artStructReplace(newsgroup, &art, &copy, i);
      }
    }
    hash_table_destroy(newsgroup->thread_table);
    newsgroup->thread_table = 0;
    (void) sprintf(dummy, THREADING_FOR_MSG, newsgroup->name);
    (void) strcat(dummy, " ");
    (void) strcat(dummy, DONE_MSG);
    INFO(dummy);

    return True;
  }

  end_time = time(0);
  chunk_size = done_count;
  adjustPrefetchChunk(end_time - start_time,
		      PREFETCH_CHUNK_TIME, &chunk_size);
  return False;
}

#undef THREAD_IT

static void checkThreading _ARGUMENTS((struct newsgroup *, art_num));

static void checkThreading(
			   _ANSIDECL(struct newsgroup *,	newsgroup),
			   _ANSIDECL(art_num,			first)
			   )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(art_num,			first)
{
  art_num i;
  struct article *art, *parent, copy;

  for (i = first; i <= newsgroup->last; i++) {
    art = artStructGet(newsgroup, i, False);
    if (art->parent) {
      parent = artStructGet(newsgroup, art->parent, False);
      if ((art->parent < first) || !IS_LISTED(parent) || !IS_LISTED(art)) {
	copy = *parent;
	artStructRemoveChild(&copy, i);
	artStructReplace(newsgroup, &parent, &copy, art->parent);
	copy = *art;
	CLEAR_PARENT(&copy);
	artStructReplace(newsgroup, &art, &copy, i);
      }
    }
  }
}

  
static void rethreadGroup _ARGUMENTS((struct newsgroup *, art_num,
				      Boolean));

static void rethreadGroup(
			  _ANSIDECL(struct newsgroup *,	newsgroup),
			  _ANSIDECL(art_num,		art),
			  _ANSIDECL(Boolean,		rethread)
			  )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(art_num,			art)
     _KNRDECL(Boolean,			rethread)
{
  art_num i;

  if (rethread) {
    /*
      We're generating a new list after "List Old" or "Goto article",
      which means that articles which weren't displayed before are
      displayed now, so we have to reset everything.

      Otherwise, the only thing that might have happened is some
      articles getting marked read as a result of cross-posts after
      the group was already prefetched, and those will be detected by
      checkThreading(), so we don't have to worry about them here.
      */
    for (i = art; i <= newsgroup->last; i++) {
      struct article *art = artStructGet(newsgroup, i, True);
      CLEAR_CHILDREN(art);
      CLEAR_PARENT(art);
      artStructSet(newsgroup, &art);
    }
  }
  else {
    checkThreading(newsgroup, art);
  }

  (void) threadIncremental(newsgroup, 0, art, newsgroup->last, ART_LISTED);
}
     
static Boolean fetchHeadersIncremental _ARGUMENTS((struct newsgroup *,
						   int *, art_num, art_num,
						   Boolean, Boolean));

static Boolean fetchHeadersIncremental(
				       _ANSIDECL(struct newsgroup *,	newsgroup),
				       _ANSIDECL(int *,			stage),
				       _ANSIDECL(art_num,		first),
				       _ANSIDECL(art_num,		last),
				       _ANSIDECL(Boolean,		unread_only),
				       _ANSIDECL(Boolean,		kill_files)
				       )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(int *,			stage)
     _KNRDECL(art_num,			first)
     _KNRDECL(art_num,			last)
     _KNRDECL(Boolean,			unread_only)
     _KNRDECL(Boolean,			kill_files)
{
    static int chunk_size = PREFETCH_CHUNK;
    time_t start_time WALL (= 0), end_time;
    Boolean finished = True;

    if (stage) {
      if ((*stage < PREFETCH_START_HEADERS_STAGE) ||
	  (*stage > PREFETCH_LAST_HEADERS_STAGE))
	return True;
      start_time = time(0);
    }

    if (! stage || *stage == PREFETCH_SUBJECT_STAGE)
      finished = getsubjectlist(newsgroup, first, last,
				unread_only,
				(stage && ! FinishingPrefetch)
				? &chunk_size : 0);
    if (! stage || *stage == PREFETCH_AUTHOR_STAGE)
      finished = getauthorlist(newsgroup, first, last,
			       unread_only,
			       (stage && ! FinishingPrefetch)
			       ? &chunk_size : 0);
    if (! stage || *stage == PREFETCH_LINES_STAGE)
      finished = getlineslist(newsgroup, first, last,
			      unread_only,
			      (stage && ! FinishingPrefetch)
			      ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_NEWSGROUPS) && kill_files &&
	(! stage || *stage == PREFETCH_NEWSGROUPS_STAGE))
      finished = getnewsgroupslist(newsgroup, first, last,
				   unread_only,
				   (stage && ! FinishingPrefetch)
				   ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_DATES) &&
	(! stage || *stage == PREFETCH_DATE_STAGE))
      finished = getdatelist(newsgroup, first, last,
			     unread_only,
			     (stage && ! FinishingPrefetch)
			     ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_IDS) &&
	(! stage || *stage == PREFETCH_IDS_STAGE))
      finished = getidlist(newsgroup, first, last,
			   unread_only,
			   (stage && ! FinishingPrefetch)
			   ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_XREF) &&
	(! stage || *stage == PREFETCH_XREF_STAGE))
      finished = getxreflist(newsgroup, first, last,
			     unread_only,
			     (stage && ! FinishingPrefetch)
			     ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_APPROVED) &&
	(! stage || *stage == PREFETCH_APPROVED_STAGE))
      finished = getapprovedlist(newsgroup, first, last,
				 unread_only,
				 (stage && ! FinishingPrefetch)
				 ? &chunk_size : 0);
    if ((newsgroup->fetch & FETCH_REFS) &&
	(! stage || *stage == PREFETCH_REFS_STAGE))
      finished = getreflist(newsgroup, first, last,
			    unread_only,
			    (stage && ! FinishingPrefetch)
			    ? &chunk_size : 0);
    if (! finished) { /* that means it was a full chunk */
      end_time = time(0);
      adjustPrefetchChunk(end_time - start_time,
			  PREFETCH_CHUNK_TIME, &chunk_size);
    }

    return finished;
}

/*
 * The reason this is divided into "stages" is so that it can be used
 * in a toolkit work procedure.  The stages allow the work to be
 * divided up so a single work procedure invocation doesn't take too long.
 */
static Boolean setUpGroupIncremental _ARGUMENTS((struct newsgroup *, int *,
						 Boolean, Boolean,
						 Boolean, Boolean,
						 art_num, art_num));

static Boolean setUpGroupIncremental(
				     _ANSIDECL(struct newsgroup *,	newsgroup),
				     _ANSIDECL(int *,			stage),
				     _ANSIDECL(Boolean,			update_last),
				     _ANSIDECL(Boolean,			kill_files),
				     _ANSIDECL(Boolean,			unread_only),
				     _ANSIDECL(Boolean,			threading),
				     _ANSIDECL(art_num,			first),
				     _ANSIDECL(art_num,			last)
				     )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(int *,			stage)
     _KNRDECL(Boolean,			update_last)
     _KNRDECL(Boolean,			kill_files)
     _KNRDECL(Boolean,			unread_only)
     _KNRDECL(Boolean,			threading)
     _KNRDECL(art_num,			first)
     _KNRDECL(art_num,			last)
{
    Boolean finished = True;
    static int chunk_size = PREFETCH_CHUNK;
    struct article *art, copy;
    art_num i;

#ifdef DEBUG
    fprintf(stderr, "setUpGroupIncremental(%s, %d, %d, %d, %d)\n",
	    newsgroup->name, stage ? *stage : 0, update_last, kill_files,
	    unread_only);
#endif

    if (PrefetchingGroup && !stage) {
	if ((PrefetchingGroup == newsgroup) && kill_files && unread_only)
	    finishPrefetch();
	else
	    cancelPrefetch();
    }

    if (PrefetchedGroup && (newsgroup != PrefetchedGroup)) {
	cancelPrefetch();
    }

    if (! PrefetchedGroup) {
	if (! stage || *stage == PREFETCH_GETGROUP_STAGE) {
	    art_num first, last;
	    int number;
	   /*
	    * Update our idea of what the first article in the group
	    * is.  This is necessary because sites that don't
	    * regularly renumber their active files will report a
	    * different first article number for a group in the
	    * response to the LIST command than they will in response
	    * to the GROUP command, and the first article number in
	    * response to the latter command is, in fact, the correct
	    * one.
	    *
	    * If we don't use the first article number returned by the
	    * GROUP command when it is higher than the first article
	    * number returned by the LIST command, then we end up with
	    * two problems: (1) article arrays are much bigger than
	    * they need to be; (2) when the user clicks on "List Old"
	    * in a newsgroup, XRN will have to try to retrieve a large
	    * number of articles before actually finding the first
	    * article in the group.
	    *
	    * Also, update our idea of what the last article in the
	    * group is, if the update_last argument to setUpGroup is
	    * true.
	    */
	    (void) getgroup(newsgroup, &first, &last, &number,
			    stage ? False : True);
	    articleArrayResync(newsgroup, first,
			       update_last ? last : newsgroup->last, number);
	}
	if (! EMPTY_GROUP(newsgroup)) {
	    art_num my_first = first, my_last = last;

	    if (! stage || *stage == PREFETCH_SETCURRENT_STAGE) {
	      time_t start_time, end_time;
	      start_time = time(0);
	      (void) setCurrentArticle(newsgroup, unread_only, False,
				       (stage && ! FinishingPrefetch)
				       ? &finished : 0, &chunk_size);
	      end_time = time(0);
	      if (! finished) {
		adjustPrefetchChunk(end_time - start_time,
				    PREFETCH_CHUNK_TIME, &chunk_size);
	      }
	    }

	    if (! my_first)
	      my_first = newsgroup->current;
	    if (! my_last)
	      my_last = newsgroup->last;

	    if ((! stage) ||
		((*stage >= PREFETCH_START_HEADERS_STAGE) &&
		 (*stage <= PREFETCH_LAST_HEADERS_STAGE)))
	      finished = fetchHeadersIncremental(newsgroup, stage,
						 my_first, my_last,
						 unread_only,
						 kill_files);

	    if (! stage || *stage == PREFETCH_KILL_STAGE) {
	        if ((app_resources.killFiles == TRUE) && kill_files) {
		  fetch_flag_t fetched = newsgroup->fetch;

		  finished = checkKillFiles(newsgroup,
					    (stage && ! FinishingPrefetch)
					    ? True : False);

		  if (! finished || newsgroup->fetch != fetched) {
		    int i;

		    if (! stage)
		      return setUpGroupIncremental(newsgroup, stage,
						   update_last, kill_files,
						   unread_only, threading,
						   first, last);

		    for (i = PREFETCH_START_OPTIONAL_STAGE;
			 i <= PREFETCH_LAST_OPTIONAL_STAGE;
			 i++)
		      if ((PREFETCH_FIELD_BIT(i) & fetched) !=
			  (PREFETCH_FIELD_BIT(i) & newsgroup->fetch)) {
			*stage = i;
			finished = False;
			break;
		      }
		  }
		}
		if (finished) {
		  if (setCurrentArticle(newsgroup, unread_only, True, 0, 0)) {
		    if (! stage)
		      return setUpGroupIncremental(newsgroup, stage, update_last,
						   kill_files, unread_only,
						   threading,
						   first, last);
		    else {
		      *stage = PREFETCH_SETCURRENT_STAGE;
		      finished = False;
		    }
		  }
		  else if ((app_resources.onlyShow > 0) &&
			   app_resources.discardOld) {
		    for (i = newsgroup->first; i < newsgroup->current; i++) {
		      art = artStructGet(newsgroup, i, False);
		      if (IS_UNREAD(art)) {
			copy = *art;
			SET_READ(&copy);
			artStructReplace(newsgroup, &art, &copy, i);
		      }
		    }
		  }
		}
	    }
	    if ((! stage || *stage == PREFETCH_THREAD_STAGE) && threading)
	      finished = threadIncremental(newsgroup, stage, my_first, my_last,
					   ART_READ);
	}
    }

    PrefetchedGroup = 0;

#ifndef NO_IMMEDIATE_WORK_PROC_PREFETCH
    if (! stage)
	prefetchNextGroup(newsgroup);
#endif

#ifdef DEBUG
    fprintf(stderr, "setUpGroupIncremental(%s, %d, %d, %d, %d) = %d\n",
	    newsgroup->name, stage ? *stage : 0, update_last, kill_files,
	    unread_only, finished);
#endif
    return finished;
}

static void setUpGroup _ARGUMENTS((struct newsgroup *, Boolean,
				   Boolean, Boolean, Boolean));

static void setUpGroup(
		       _ANSIDECL(struct newsgroup *,	newsgroup),
		       _ANSIDECL(Boolean,		update_last),
		       _ANSIDECL(Boolean,		kill_files),
		       _ANSIDECL(Boolean,		unread_only),
		       _ANSIDECL(Boolean,		threading)
		       )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(Boolean,			update_last)
     _KNRDECL(Boolean,			kill_files)
     _KNRDECL(Boolean,			unread_only)
     _KNRDECL(Boolean,			threading)
{
#ifdef DEBUG
    fprintf(stderr, "setUpGroup(%s, %d, %d, %d)\n", newsgroup->name,
	    update_last, kill_files, unread_only);
#endif
    (void) setUpGroupIncremental(newsgroup, 0, update_last,
				 kill_files, unread_only, threading, 0, 0);
#ifdef DEBUG
    fprintf(stderr, "setUpGroup(%s, %d, %d, %d) done\n", newsgroup->name,
	    update_last, kill_files, unread_only);
#endif
}


static struct newsgroup * findNewsGroupMatch _ARGUMENTS((char *));

static struct newsgroup * findNewsGroupMatch(name)
    char *name;
{
#ifdef POSIX_REGEX
    regex_t reStruct;
#else
    static char *reRet;
#endif
    int i;

    /* no single character queries -- too confusing */
    if (strlen(name) == 1) {
	return NIL(struct newsgroup);
    }

#ifdef POSIX_REGEX
    if (regcomp(&reStruct, name, REG_NOSUB))
	return 0;
#else
# ifdef SYSV_REGEX
    if ((reRet = regcmp(name, NULL)) == NULL) {
	return NIL(struct newsgroup);
    }
# else
    if ((reRet = re_comp(name)) != NULL) {
	return NIL(struct newsgroup);
    }
# endif
#endif

    for (i = 0; i < MaxGroupNumber; i++) {
	struct newsgroup *newsgroup = Newsrc[i];
#ifdef POSIX_REGEX
	if (! regexec(&reStruct, newsgroup->name, 0, 0, 0)) {
	    regfree(&reStruct);
	    return newsgroup;
	}
#else
# ifdef SYSV_REGEX
	if (regex(reRet, newsgroup->name) != NULL) {
	    FREE(reRet);
	    return newsgroup;
	}
# else
	if (re_exec(newsgroup->name)) {
	    return newsgroup;
	}
# endif
#endif
    }

#ifdef POSIX_REGEX
    regfree(&reStruct);
#else
# ifdef SYSV_REGEX
    free(reRet);
# endif
#endif

    return NIL(struct newsgroup);
}


void catchUp()
/*
 * mark all articles in a newsgroup as read
 *
 *   other functions will take care of releasing resources
 *
 *   returns: void
 *
 */
{
    struct article *art, copy;
    struct newsgroup *newsgroup = CurrentGroup;
    art_num artnum;

    artListSet(newsgroup);
    for (artnum = newsgroup->first; artnum <= newsgroup->last; artnum++) {
	art = artStructGet(newsgroup, artnum, False);
	copy = *art;
	if (IS_UNMARKED(art)) {
	    SET_READ(&copy);
	} else {
	    SET_UNREAD(&copy);
	    SET_UNMARKED(&copy);
	}
	artStructReplace(newsgroup, &art, &copy, artnum);
    }
    return;
}


/*
 * subscribe to a specified newsgroup
 *
 *   returns: void
 *
 */
static void subscribe_group _ARGUMENTS((struct newsgroup *));

static void subscribe_group(newsgroup)
    struct newsgroup *newsgroup;
{
    if (!IS_SUBSCRIBED(newsgroup)) {
	art_num first, last;
	int number;

	if (IS_NOENTRY(newsgroup))
	    addToNewsrcEnd(newsgroup->name, SUBSCRIBE);

	/*
	  Update the first and last article numbers for the newsgroup,
	  since "Rescan" doesn't update groups we're not subscribed to.
	  */
	if (! getgroup(newsgroup, &first, &last, &number, True)) {
	    SET_SUB(newsgroup);
	    articleArrayResync(newsgroup, first, last, number);
	    (void) updateArticleArray(newsgroup, False);
	}
    }
    return;
}


/*
  subscribe to the current newsgroup
  */
void subscribe()
{
    subscribe_group(CurrentGroup);
}


/*
 * unsubscribe to a newsgroup
 *
 *   returns: void
 *
 */
void unsubscribe()
{
    struct newsgroup *newsgroup = CurrentGroup;

    if (IS_NOENTRY(newsgroup))
	addToNewsrcEnd(newsgroup->name, UNSUBSCRIBE);
    else
	SET_UNSUB(newsgroup);
    return;
}

/*
 * build a string that is used as the question for what
 * to do at the end of an article
 *
 *   returns: the question in a static area
 *
 */
static char * buildQuestion _ARGUMENTS((struct newsgroup *, art_num));

static char * buildQuestion(newsgroup, article)
    struct newsgroup *newsgroup;
    art_num article;
{
    static char dummy[LABEL_SIZE];
    long unread, next_unread WALL(= 0);
    ng_num number;
    struct newsgroup *nextnewsgroup WALL(= 0);
    int found;

    unread = unreadArticleCount(newsgroup);

    found = 0;
    for (number = newsgroup->newsrc + 1; number < MaxGroupNumber;
	 number++) {
	nextnewsgroup = Newsrc[number];
	/* find a group that is subscribed to and has unread articles */
	if (IS_SUBSCRIBED(nextnewsgroup) &&
	    ((next_unread = unreadArticleCount(nextnewsgroup)) > 0)) {
	    found = 1;
	    break;
	}
    }
	    
    if (found) {
	if (unread <= 0) {
          (void) sprintf(dummy, QUEST_ART_NOUNREAD_NEXT_STRING,
			 article, newsgroup->name,
			 nextnewsgroup->name, next_unread,
			 (next_unread == 1) ? "" : NOT_ONE_MSG);
	} else {
          (void) sprintf(dummy, QUEST_ART_UNREAD_NEXT_STRING,
			 article, newsgroup->name, unread,
			 nextnewsgroup->name, next_unread,
			 (next_unread == 1) ? "" : NOT_ONE_MSG);
	}
    } else {
	if (unread <= 0) {
          (void) sprintf(dummy, QUEST_ART_NOUNREAD_NONEXT_STRING,
			   article, newsgroup->name);
	} else {
          (void) sprintf(dummy, QUEST_ART_UNREAD_NONEXT_STRING,
			   article, newsgroup->name, unread);
	}
    }
    return dummy;
}


static void handleXref _ARGUMENTS((struct newsgroup *, art_num));

static void handleXref(cur_newsgroup, article)
    struct newsgroup *cur_newsgroup;
    art_num article;
{
    char *string, *ptr, *num_ptr, *group, *gptr;
    art_num number;
    struct newsgroup *newsgroup;
    struct article *this_art;

    this_art = artStructGet(cur_newsgroup, article, False);

    if (IS_XREFED(this_art))
      return;

    if (this_art->xref)
      if (*this_art->xref)
	string = XtNewString(this_art->xref);
      else
	string = NULL;
    else
      xhdr(cur_newsgroup, article, "xref", &string);

    if (string == NIL(char)) {
	/* no xrefs */
	return;
    }

    /*
     * an xrefs line is of the form:
     *
     *   host group:number group:number .... group:number
     */

    if ((ptr = index(string, ' ')) == NIL(char)) {
	FREE(string);
	return;
    }
    ptr++;

    while ((group = strtok(ptr, ":"))) {
	ptr = 0;

	if (! (num_ptr = strtok(ptr, " ")))
	    /* Something is confused.  Give up. */
	    break;

	if ((number = atol(num_ptr)) <= 0)
	    /* Something is confused differently.  Give up. */
	    break;
	
	if (!avl_lookup(NewsGroupTable, group, &gptr)) {
	    /* bogus group */
	    continue;
	}

	/* only Xref groups that are subscribed to */
	
	newsgroup = (struct newsgroup *) gptr;

	if (IS_SUBSCRIBED(newsgroup)) {
	  struct article *art;

	  if (number < newsgroup->first)
	    continue;
	  if (number > newsgroup->last)
	    if (app_resources.rescanOnEnter) {
	      art_num first, last;
	      int count;

	      if (getgroup(newsgroup, &first, &last, &count, False) != NO_GROUP)
		if ((number >= first) && (number <= last))
		  articleArrayResync(newsgroup, first, last, count);
		else
		  continue;
	      else
		continue;
	    }
	    else
	      continue;

	  artListSet(newsgroup);
	  art = artStructGet(newsgroup, number, True);
	  SET_XREFED(art);
	  /* Don't mark read in the current newsgroup; that's the caller's
	     responsibility. */
	  if ((newsgroup != cur_newsgroup) || (article != number))
	    SET_READ(art);
	  artStructSet(newsgroup, &art);
	}
    }
    FREE(string);
    return;
}


/*
 * get the next article
 *
 * returns: XRN_ERROR - article has been canceled
 *          XRN_OKAY  - article returned
 */
int getArticle(newsgroup, article, file, question)
    struct newsgroup *newsgroup;
    art_num article; 
    file_cache_file **file;
    char **question;
{
    struct article *art = artStructGet(newsgroup, article, True);
    file_cache_file *artfile;
    int header = 0, rotation = 0, xlation = 0;

#ifdef DEBUG
    fprintf(stderr, "getArticle(%s, %d)\n", newsgroup->name, article);
#endif

    if (IS_UNFETCHED(art)) {
	/* get the article and handle unavailable ones.... */
	if (IS_ALL_HEADERS(art))
	  header = FULL_HEADER;
	if (IS_ROTATED(art))
	  rotation = ROTATED;
#ifdef XLATE
	if (IS_XLATED(art))
	  xlation = XLATED;
#endif
	artfile = getarticle(newsgroup, article, 0, header | rotation |
			     xlation | PAGEBREAKS | BACKSPACES);
	/* need to refetch it since getarticle() modifies it */
	art = artStructGet(newsgroup, article, True);
	if (artfile)
	  art->file = artfile;
	else {
	    CLEAR_ALL(art);
	    SET_UNAVAIL(art);
	    artStructSet(newsgroup, &art);
	    return XRN_ERROR;
	}
	SET_FETCHED(art);
    } else {
	/* verify that the file still exists */
	if (!art->file || !*art->file ||
	    (access(file_cache_file_name(FileCache, *art->file), R_OK) == -1)) {
	    /* refetch the file */
	    CLEAR_FILE(art);
	    artStructSet(newsgroup, &art);
	    return getArticle(newsgroup, article, file, question);
	}
	file_cache_file_lock(FileCache, *art->file);
    }
    
    *file = art->file;
    if (IS_UNMARKED(art)) {
	SET_READ(art);
    }
    *question = buildQuestion(newsgroup, article);
    handleXref(newsgroup, article);

    artStructSet(newsgroup, &art);
    return XRN_OKAY;
}


static int toggleArtAttribute _ARGUMENTS((file_cache_file **, char **, int));

static int toggleArtAttribute(file, question, attribute)
    file_cache_file **file;
    char **question;
    int attribute;
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art = artStructGet(newsgroup, newsgroup->current, True);
    int ret;

    switch (attribute) {
    case ART_ALL_HEADERS:
	if (IS_ALL_HEADERS(art))
	    SET_STRIPPED_HEADERS(art);
	else
	    SET_ALL_HEADERS(art);
	break;
    case ART_ROTATED:
	if (IS_ROTATED(art))
	    SET_UNROTATED(art);
	else
	    SET_ROTATED(art);
	break;
#ifdef XLATE
    case ART_XLATED:
	if (IS_XLATED(art))
	    SET_UNXLATED(art);
	else
	    SET_XLATED(art);
	break;
#endif
    }

    CLEAR_FILE(art);

    artStructSet(newsgroup, &art);

    ret = getArticle(newsgroup, newsgroup->current, file, question);
    if (ret != XRN_OKAY) {
	mesgPane(XRN_SERIOUS, 0, ART_NOT_AVAIL_MSG, newsgroup->current);
    }
    return ret;
}

int toggleHeaders(file, question)
    file_cache_file **file;
    char **question;
{
    return toggleArtAttribute(file, question, ART_ALL_HEADERS);
}

int toggleRotation(file, question)
    file_cache_file **file;
    char **question;
{
    return toggleArtAttribute(file, question, ART_ROTATED);
}

#ifdef XLATE
int toggleXlation(file, question)
    file_cache_file **file;
    char **question;
{
    return toggleArtAttribute(file, question, ART_XLATED);
}
#endif /* XLATE */

static Boolean prefetchSetFetched _ARGUMENTS((XtPointer));

static Boolean prefetchSetFetched(pClient)
    XtPointer pClient;
{
    struct newsgroup *newsgroup = PrefetchingGroup;
    char msg[LABEL_SIZE];
#ifdef DEBUG
    int mesg_name = newMesgPaneName();
#endif

    if (rescan_id && !FinishingPrefetch) {
      (void) rescanWorkProc(0);
      return False;
    }

    InWorkProc++;

    if (! newsgroup) {
#ifdef DEBUG
	fprintf(stderr, "prefetchSetFetched[%d] returning (not in prefetch)\n",
		mesg_name);
#endif
	goto done;
    }
    if ((struct newsgroup *) pClient != newsgroup) {
#ifdef DEBUG
	fprintf(stderr, "prefetchSetFetched[%d] returning (wrong group)\n",
		mesg_name);
#endif
	goto done;
    }

    artListSet(newsgroup);

#ifdef DEBUG
    fprintf(stderr, "prefetchSetFetched[%d] fetching %s\n", mesg_name,
	    newsgroup->name);
#endif

    /* if the current article is unfetched, fetch it */
    if (FastServer || FinishingPrefetch) {
	struct article *art = artStructGet(newsgroup, newsgroup->current,
					   True);
	if (IS_UNFETCHED(art)) {
	    file_cache_file *artfile;

	    /* if the article can be fetched, mark it so */
	    artfile = getarticle(newsgroup, newsgroup->current, 0,
				 PAGEBREAKS | BACKSPACES);
	    /* need to refetch it since getarticle() modifies it */
	    art = artStructGet(newsgroup, newsgroup->current, True);

	    if (artfile) {
	      art->file = artfile;
	      SET_FETCHED(art);
	    }
	}

	artStructSet(newsgroup, &art);
    }

    PrefetchedGroup = newsgroup;
    PrefetchingGroup = 0;
    (void) sprintf(msg, PREFETCHING_MSG, newsgroup->name);
    (void) strcat(msg, " ");
    (void) strcat(msg, DONE_MSG);
    INFO(msg);

#ifdef DEBUG
    fprintf(stderr, "prefetchSetFetched[%d] fetched %s\n", mesg_name,
	    newsgroup->name);
#endif
  done:
    InWorkProc--;
    return True;
}


static Boolean prefetchGetArticles _ARGUMENTS((XtPointer));

static Boolean prefetchGetArticles(pClient)
    XtPointer pClient;
{
    register struct newsgroup *newsgroup = PrefetchingGroup;
#ifdef DEBUG
    int mesg_name = newMesgPaneName();
#endif

    if (rescan_id && !FinishingPrefetch) {
      (void) rescanWorkProc(0);
      return False;
    }

    InWorkProc++;

    if (! newsgroup) {
#ifdef DEBUG
	fprintf(stderr,
		"prefetchGetArticles[%d] returning (not in prefetch)\n",
		mesg_name);
#endif
	goto done;
    }

    if ((struct newsgroup *) pClient != newsgroup) {
#ifdef DEBUG
	fprintf(stderr, "prefetchGetArticles[%d] returning (wrong group)\n",
		mesg_name);
#endif
	goto done;
    }

    artListSet(newsgroup);

#ifdef DEBUG
    fprintf(stderr, "prefetchGetArticles[%d] fetching %s\n", mesg_name,
	    newsgroup->name);
#endif

    if ((newsgroup->current < newsgroup->first) ||
	(! unreadArticleCount(newsgroup))) {
	/* This will happen if setUpGroup couldn't find any unread
           articles in the newsgroup, in which case newsgroup->current
           will be 0, or if there are no unread articles in the group. */
	cancelPrefetch();
	prefetchNextGroup(newsgroup);
#ifdef DEBUG
	fprintf(stderr, "prefetchGetArticles[%d] fetching group after %s\n",
		mesg_name, newsgroup->name);
#endif
	goto done;
    }

    prefetch_id = XtAppAddWorkProc(TopContext,
				   prefetchSetFetched, newsgroup);
    PrefetchingProc = prefetchSetFetched;

#ifdef DEBUG
    fprintf(stderr, "prefetchGetArticles[%d] continuing with %s\n", mesg_name,
	    newsgroup->name);
#endif
  done:
    InWorkProc--;
    return True;    
}


static Boolean prefetchSetupUnreadGroup _ARGUMENTS((XtPointer));

static Boolean prefetchSetupUnreadGroup(pClient)
    XtPointer pClient;
{
    struct newsgroup *newsgroup = PrefetchingGroup;
#ifdef DEBUG
    int mesg_name = newMesgPaneName();
#endif
    Boolean ret;

    if (rescan_id && !FinishingPrefetch) {
      (void) rescanWorkProc(0);
      return False;
    }

    InWorkProc++;

    if (! newsgroup) {
#ifdef DEBUG
	fprintf(stderr,
		"prefetchSetupUnreadGroup[%d] returning (not in prefetch)\n",
		mesg_name);
#endif
	ret = True;
	goto done;
    }

    if ((struct newsgroup *) pClient != newsgroup) {
#ifdef DEBUG
	fprintf(stderr,
		"prefetchSetupUnreadGroup[%d] returning (wrong newsgroup)\n",
		mesg_name);
#endif
	ret = True;
	goto done;
    }

    if (PrefetchStage <= PREFETCH_LAST_STAGE) {
#ifdef DEBUG
	fprintf(stderr,
		"prefetchSetupUnreadGroup[%d] running stage %d on %s\n",
		mesg_name, PrefetchStage, newsgroup->name);
#endif
	if (setUpGroupIncremental(newsgroup, &PrefetchStage,
				  app_resources.rescanOnEnter,
				  True, True, True,
				  0, 0))
	    PrefetchStage++;
	ret = False;
	goto done;
    }
    else {
	if (! FinishingPrefetch)
	    redrawNewsgroupTextWidget(newsgroup->name, False);
	prefetch_id = XtAppAddWorkProc(TopContext,
				       prefetchGetArticles, newsgroup);
	PrefetchingProc = prefetchGetArticles;
#ifdef DEBUG
	fprintf(stderr, "prefetchSetupUnreadGroup[%d] continuing with %s\n",
		mesg_name, newsgroup->name);
#endif
	ret = True;
	goto done;
    }
  done:
    InWorkProc--;
    return ret;
}


static void prefetchNextGroup _ARGUMENTS((struct newsgroup *));

/*ARGSUSED*/
static void prefetchNextGroup(in_newsgroup)
    struct newsgroup *in_newsgroup;
{
    struct newsgroup *newsgroup;
    register ng_num number;
    char msg[LABEL_SIZE];
#ifdef DEBUG
    int mesg_name = newMesgPaneName();
#endif

#ifdef DEBUG
    fprintf(stderr, "prefetchNextGroup[%d](%s)\n", mesg_name, in_newsgroup ?
	    in_newsgroup->name : "NULL");
#endif

    if (app_resources.prefetchMax < 0)
	/* Don't prefetch at all if prefetchMax is negative. */
	goto done;

    /* find a group that is subscribed to and has unread articles */
    for (number = (in_newsgroup ? in_newsgroup->newsrc + 1 : 0);
	 number < MaxGroupNumber;
	 number++) {
	newsgroup = Newsrc[number];
	if (IS_SUBSCRIBED(newsgroup) && (unreadArticleCount(newsgroup) > 0))
	    break;
    }
    if (number < MaxGroupNumber) {
	if ((PrefetchingGroup == newsgroup) ||
	    (PrefetchedGroup == newsgroup))
	    goto done;
	cancelPrefetch();
	if ((! app_resources.prefetchMax) ||
	    (unreadArticleCount(newsgroup) <= app_resources.prefetchMax)) {
	    PrefetchingGroup = newsgroup;
	    PrefetchStage = PREFETCH_FIRST_STAGE;
	    (void) sprintf(msg, PREFETCHING_MSG, newsgroup->name);
#ifdef DEBUG
	    fprintf(stderr, "prefetchNextGroup[%d] continuing with %s\n",
		    mesg_name, newsgroup->name);
#endif
	    prefetch_id = XtAppAddWorkProc(TopContext,
					   prefetchSetupUnreadGroup, newsgroup);
	    PrefetchingProc = prefetchSetupUnreadGroup;
	    maybeInfoNow(msg);
	}
	
    }
    else if (PrefetchingGroup || PrefetchedGroup)
	cancelPrefetch();

  done:
#ifdef DEBUG
    fprintf(stderr, "prefetchNextGroup[%d](%s) done\n", mesg_name,
	    in_newsgroup ? in_newsgroup->name : "NULL");
#endif
    return;
}


/*
  Prefetch the specified group, if it has unread articles.
  */
void prefetchGroup(group)
    char *group;
{
    struct newsgroup *newsgroup;

#ifdef DEBUG
    fprintf(stderr, "prefetchGroup(%s)\n", group);
#endif

    if (! avl_lookup(NewsGroupTable, group, (char **)&newsgroup)) {
#ifdef DEBUG
	fprintf(stderr, "prefetchGroup(%s) done\n", group);
#endif
	return;
    }

    prefetchNextGroup(newsgroup->newsrc ? Newsrc[newsgroup->newsrc - 1] : 0);

#ifdef DEBUG
    fprintf(stderr, "prefetchGroup(%s) done\n", group);
#endif
    return;
}


/*
 * prefetch the next article, will prefetch the next unread article in
 *   the next group at the end of the current group
 *
 * returns: void
 *
 */
void prefetchNextArticle()
{
    struct newsgroup *newsgroup = CurrentGroup;

#ifdef DEBUG
    fprintf(stderr, "prefetchNextArticle(%s)\n", newsgroup->name);
#endif

    artListSet(newsgroup);
    
    if (newsgroup->current == newsgroup->last) {
#ifdef NO_IMMEDIATE_WORK_PROC_PREFETCH
	/*
	 * if this is the last article, prefetch the next group, and the
	 * first article of the next group
	 */
	prefetchNextGroup(newsgroup);
#endif
	return;
    }

    if (FastServer) {
	art_num artnum = newsgroup->current + 1;
	struct article *art = artStructGet(newsgroup, artnum, True);
	file_cache_file *artfile;

	if (IS_UNFETCHED(art)) {
	  artfile = getarticle(newsgroup, artnum, 0, PAGEBREAKS | BACKSPACES);
	  /* need to refetch it since getarticle() modifies it */
	  art = artStructGet(newsgroup, artnum, True);

	  if (artfile) {
	    file_cache_file_unlock(FileCache, *artfile);
	    art->file = artfile;
	    SET_FETCHED(art);
	    SET_STRIPPED_HEADERS(art);
	    SET_UNROTATED(art);
	    SET_UNXLATED(art);
	  }
	}

	artStructSet(newsgroup, &art);
    }
}



/*
 * mark the articles in a group that have been read
 *
 * returns: True on success, False on failure indicating that the
 * group should not be entered.
 *
 */
Boolean updateArticleArray(
			   _ANSIDECL(struct newsgroup *,	newsgroup),
			   _ANSIDECL(Boolean,			do_unsubbed)
			   )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(Boolean,			do_unsubbed)
{
    struct list *item;
    struct article *art, copy;
    art_num artnum;
#ifndef FIXED_C_NEWS_ACTIVE_FILE
    int number;
#endif

    if (newsgroup->last == 0) {
	return True;
    }

#define CHECK_CACHED(label) \
    if (newsgroup->from_cache) { \
	art_num first, last; \
	int number; \
\
	if (getgroup(newsgroup, &first, &last, &number, False)) { \
	  return False; \
	} \
	else { \
	    articleArrayResync(newsgroup, first, last, number); \
	    newsgroup->from_cache = FALSE; \
	    goto label; \
	} \
    }

    if (!(do_unsubbed || IS_SUBSCRIBED(newsgroup))) {
	artListFree(newsgroup);
	return True;
    }

empty_retry:
    if (EMPTY_GROUP(newsgroup)) {
      CHECK_CACHED(empty_retry);
	artListFree(newsgroup);
	return True;
    }

    artListSet(newsgroup);

    if (newsgroup->nglist == NIL(struct list)) {
	return True;
    }

#ifndef FIXED_C_NEWS_ACTIVE_FILE
#ifdef DEBUG
    fprintf(stderr, "updateArticleArray(%s)\n", newsgroup->name);
#endif

    /* get the group range to fix c-news low number problem */
    if ((XRNState & XRN_NEWS_UP) == XRN_NEWS_UP) {
	(void) getgroup(newsgroup, &newsgroup->first, &newsgroup->last,
			&number, True);
	if ((newsgroup->first == 0 && newsgroup->last == 0) || number == 0) {
	    lsDestroy(newsgroup->nglist);
	    newsgroup->nglist = NIL(struct list);
	    return True;
	}
    }
#endif

    /* process the .newsrc line */

retry:
    for (item = newsgroup->nglist; item != NIL(struct list); item = item->next) {
	switch (item->type) {
	case SINGLE:
	    if (item->contents.single > newsgroup->last) {
		CHECK_CACHED(retry);
		/* something really bad has happened, reset */
		mesgPane(XRN_SERIOUS, 0, ART_NUMBERING_PROBLEM_MSG,
			 newsgroup->name);
		artListFree(newsgroup);
		artListSet(newsgroup);
		lsDestroy(newsgroup->nglist);
		newsgroup->nglist = NIL(struct list);
		return True;
	    }
	    if (item->contents.single >= newsgroup->first) {
		struct article *art = artStructGet(newsgroup,
						   item->contents.single,
						   True);
		art->status = ART_CLEAR_READ;
		artStructSet(newsgroup, &art);
	    }
	    break;

	case RANGE:
	    if ((item->contents.range.start > newsgroup->last) ||
		(item->contents.range.end > newsgroup->last)) {
		CHECK_CACHED(retry);
		/* something really bad has happened, reset */
		mesgPane(XRN_SERIOUS, 0, ART_NUMBERING_PROBLEM_MSG,
			 newsgroup->name);
		artListFree(newsgroup);
		artListSet(newsgroup);
		lsDestroy(newsgroup->nglist);
		newsgroup->nglist = NIL(struct list);
		return True;
	    }
	    if (item->contents.range.start < newsgroup->first) {
		item->contents.range.start = newsgroup->first;
	    }
	    
	    if (item->contents.range.end < newsgroup->first) {
		break;
	    }
	    for (artnum = item->contents.range.start;
		 artnum <= item->contents.range.end; artnum++) {
		art = artStructGet(newsgroup, artnum, False);
		copy = *art;
		copy.status = ART_CLEAR_READ;
		artStructReplace(newsgroup, &art, &copy, artnum);
	    }
	}
    }

#undef CHECK_CACHED

    lsDestroy(newsgroup->nglist);
    newsgroup->nglist = NIL(struct list);
    
    return True;
}


/*
 * mark an article as read
 */
void markArticleAsRead(article)
    art_num article;
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art;

    artListSet(newsgroup);

    art = artStructGet(newsgroup, article, True);
    SET_READ(art);
    SET_UNMARKED(art);
    artStructSet(newsgroup, &art);
}


/*
 * mark an article as unread
 */
void markArticleAsUnread(article)
    art_num article;
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art;

    artListSet(newsgroup);

    art = artStructGet(newsgroup, article, True);
    SET_UNREAD(art);
    SET_MARKED(art);
    artStructSet(newsgroup, &art);
}


/*
 * handle adding items to the newsrc
 *
 *   3 cases
 *
 *   1. add to the beginning
 *        move 0 to MaxGroupNumber-1 down 1, update newsrc fields
 *        update 0
 *        inc MaxGroupNumber
 *   2. add to the end
 *        inc MaxGroupNumber
 *        update MaxGroupNumber-1
 *   3. add after a group (newloc is the current location of the group)
 *      move newloc+1 to end down 1, update newsrc fields
 *      update newloc
 *      in MaxGroupNumber
 *
 *   And the case of 'subscribe' (assumes it moves)
 *
 *   1. add to the beginning
 *        move 0 to oldloc-1 down 1, update newsrc fields
 *        update 0
 *   2. add to the end
 *        move oldloc+1 to MaxGroupNumber-1 update 1, update newsrc fields
 *        upadte MaxGroupNumber-1
 *   3. add after a group
 *
 */

int addToNewsrcBeginning(newGroup, status)
     char *newGroup;
     int status;
{
  struct newsgroup *newsgroup;
  ng_num i;

  if (! verifyGroup(newGroup, &newsgroup, False)) {
    mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, newGroup);
    return BAD_GROUP;
  }
    
  CLEAR_NOENTRY(newsgroup);
  if (status == SUBSCRIBE) {
    subscribe_group(newsgroup);
  } else {
    SET_UNSUB(newsgroup);
  }
  if (newsgroup->newsrc == NOT_IN_NEWSRC) {
    for (i = MaxGroupNumber - 1; i != NOT_IN_NEWSRC; i--) {
      Newsrc[i + 1] = Newsrc[i];
      Newsrc[i + 1]->newsrc = i + 1;
    }

    INC_MAXGROUPNUMBER();
  } else {
    for (i = newsgroup->newsrc - 1; i != NOT_IN_NEWSRC; i--) {
      Newsrc[i + 1] = Newsrc[i];
      Newsrc[i + 1]->newsrc = i + 1;
    }
  }
    
  newsgroup->newsrc = 0;
  Newsrc[0] = newsgroup;
    
  return GOOD_GROUP;
}


int addToNewsrcEnd(newGroup, status)
    char *newGroup;
    int status;
{
    struct newsgroup *newsgroup;
    ng_num i;

    if (! verifyGroup(newGroup, &newsgroup, False)) {
      mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, newGroup);
      return BAD_GROUP;
    }
    
    CLEAR_NOENTRY(newsgroup);
    if (status == SUBSCRIBE) {
	subscribe_group(newsgroup);
    } else {
	SET_UNSUB(newsgroup);
    }
    if (newsgroup->newsrc == NOT_IN_NEWSRC) {
      INC_MAXGROUPNUMBER();
    } else {
	for (i = newsgroup->newsrc + 1; i < MaxGroupNumber; i++) {
	    Newsrc[i - 1] = Newsrc[i];
	    Newsrc[i - 1]->newsrc = i - 1;
	}
    }
    
    newsgroup->newsrc = MaxGroupNumber - 1;
    Newsrc[MaxGroupNumber - 1] = newsgroup;
    
    return GOOD_GROUP;
}


int addToNewsrcAfterGroup(newGroup, afterGroup, status)
    char *newGroup;
    char *afterGroup;
    int status;
{
    struct newsgroup *newsgroup, *ng;
    ng_num newloc, i;

    if (! verifyGroup(newGroup, &newsgroup, False)) {
      mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, newGroup);
      return BAD_GROUP;
    }
    
    CLEAR_NOENTRY(newsgroup);
    if (status == SUBSCRIBE) {
	subscribe_group(newsgroup);
    } else {
	SET_UNSUB(newsgroup);
    }

    if (! avl_lookup(NewsGroupTable, afterGroup, (char **) &ng)) {
      Boolean no_group = True;

      if (! active_read) {
	char *err_buf;

	err_buf = XtMalloc(strlen(MAYBE_LIST_MSG)+strlen(afterGroup));
	(void) sprintf(err_buf, MAYBE_LIST_MSG, afterGroup);

	no_group =
	  (ConfirmationBox(TopLevel, err_buf, "yes", "no", True) ==
	   XRN_CB_ABORT) ||
	  (! verifyGroup(afterGroup, &ng, False));
	
	XtFree(err_buf);
      }

      if (no_group) {
	mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, afterGroup);
	return BAD_GROUP;
      }
    }

    newloc = ng->newsrc;

    if (newloc == NOT_IN_NEWSRC) {
	mesgPane(XRN_SERIOUS, 0, NOT_IN_NEWSRC_MSG, afterGroup);
	return BAD_GROUP;
    }

    if (newsgroup->newsrc == NOT_IN_NEWSRC) {
	for (i = MaxGroupNumber - 1; i >= newloc + 1; i--) {
	    Newsrc[i + 1] = Newsrc[i];
	    Newsrc[i + 1]->newsrc = i + 1;
	}

	INC_MAXGROUPNUMBER();
	newsgroup->newsrc = newloc + 1;
	Newsrc[newloc + 1] = newsgroup;

    } else {
	
	if (newloc + 1 < newsgroup->newsrc) {
	    for (i = newsgroup->newsrc - 1; i >= newloc + 1; i--) {
		Newsrc[i + 1] = Newsrc[i];
		Newsrc[i + 1]->newsrc = i + 1;
	    }
	    newsgroup->newsrc = newloc + 1;
	    Newsrc[newloc + 1] = newsgroup;
	    
	} else if (newsgroup->newsrc < newloc + 1) {
	    for (i = newsgroup->newsrc + 1; i < newloc + 1; i++) {
		Newsrc[i - 1] = Newsrc[i];
		Newsrc[i - 1]->newsrc = i - 1;
	    }
	    newsgroup->newsrc = newloc;
	    Newsrc[newloc] = newsgroup;
	}
	/* if its in the correct location already, don't touch it */
    }
    
    return GOOD_GROUP;
}


int ignoreGroup(group)
char *group;
{
  struct newsgroup *newsgroup;

  if (! verifyGroup(group, &newsgroup, False)) {
    mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, group);
    return BAD_GROUP;
  }

  if (newsgroup->newsrc != NOT_IN_NEWSRC)
      return removeFromNewsrc(group);

  SET_NOENTRY(newsgroup);
  SET_UNSUB(newsgroup);

  return GOOD_GROUP;
}

  
int removeFromNewsrc(group)
char *group;
{
  struct newsgroup *newsgroup;
  int i;

  if (! verifyGroup(group, &newsgroup, False)) {
    mesgPane(XRN_SERIOUS, 0, NO_SUCH_NG_MSG, group);
    return BAD_GROUP;
  }

  if (newsgroup->newsrc != NOT_IN_NEWSRC) {
    MaxGroupNumber--;

    for (i = newsgroup->newsrc; i < MaxGroupNumber; i++) {
      Newsrc[i] = Newsrc[i + 1];
      Newsrc[i]->newsrc = i;
    }

    newsgroup->newsrc = NOT_IN_NEWSRC;
  }

  SET_NOENTRY(newsgroup);
  SET_UNSUB(newsgroup);
  CLEAR_NEW(newsgroup);

  return GOOD_GROUP;
}

  
/*
 * build and return a string that shows the subscription status
 * of all newsgroups; assumes all groups have been subscribed or
 * unsubscribed to by this time.
 *
 *   if sorted is non-zero, the list is sorted alphabetically, if
 *    zero, the list is returned as it exists in the newsrc file
 *
 * The specified regular expression limits the list to the newsgroups
 * whose names match it.  May return NULL if there's an error in the
 * regular expression; otherwise, will never return NULL.
 */
char * getStatusString(line_width, sorted, regexp)
    int line_width;
    int sorted;
    char *regexp;
{
    int i, count = 0, bytes = 0;
    char buffer[1024];
    avl_generator *gen;
    char *key, *value;
    char **ar;
    char *string;
    static int status_width = 0;
    int newsgroup_width;
#ifdef POSIX_REGEX
    regex_t reStruct;
    int reRet;
#else
# ifdef SYSV_REGEX
    char *reRet = 0;
# else
    char *reRet;
# endif
#endif

    if (regexp) {
      if (
#ifdef POSIX_REGEX
	  (reRet = regcomp(&reStruct, regexp, REG_NOSUB))
#else
# ifdef SYSV_REGEX
	  ! (reRet = regcmp(regexp, NULL))
# else
	  (reRet = re_comp(regexp))
# endif
#endif
	  ) {
#ifdef SYSV_REGEX
	mesgPane(XRN_SERIOUS, 0, UNKNOWN_REGEXP_ERROR_MSG, regexp);
#else
# ifdef POSIX_REGEX
	regerror(reRet, &reStruct, error_buffer, sizeof(error_buffer));
# endif
	mesgPane(XRN_SERIOUS, 0, KNOWN_REGEXP_ERROR_MSG, regexp,
# ifdef POSIX_REGEX
		 error_buffer
# else
		 reRet
# endif /* POSIX_REGEX */
		 );
#endif /* SYSV_REGEX */
	return NULL;
      }
    }

    if (! status_width)
	status_width = MAX(utStrlen(IGNORED_MSG),
			   MAX(utStrlen(SUBED_MSG), utStrlen(UNSUBED_MSG)));

    newsgroup_width = line_width - status_width - 1
	/* the 1 is for the space between the newsgroup name and status */;

    ar = ARRAYALLOC(char *, ActiveGroupsCount);

    if (sorted) {
	gen = avl_init_gen(NewsGroupTable, AVL_FORWARD);
	if (! gen) {
          ehErrorExitXRN(ERROR_OUT_OF_MEM_MSG);
	}

	while (avl_gen(gen, &key, &value)) {
	    struct newsgroup *newsgroup = (struct newsgroup *) value;

	    if (regexp &&
#ifdef POSIX_REGEX
		regexec(&reStruct, newsgroup->name, 0, 0, 0)
#else
# ifdef SYSV_REGEX
		! regex(reRet, newsgroup->name)
# else
		! re_exec(newsgroup->name)
# endif
#endif
		)
	      continue;

	    (void) sprintf(buffer, "%*s %s",
			   -newsgroup_width, newsgroup->name,
			   (IS_NOENTRY(newsgroup) ? IGNORED_MSG :
			    (IS_SUBSCRIBED(newsgroup) ? SUBED_MSG : UNSUBED_MSG)));
	    ar[count++] = XtNewString(buffer);
	    bytes += strlen(buffer);
	}
	avl_free_gen(gen);
	
    } else {
	for (i = 0; i < MaxGroupNumber; i++) {
	    struct newsgroup *newsgroup = (struct newsgroup *) Newsrc[i];
	    
	    if (regexp &&
#ifdef POSIX_REGEX
		regexec(&reStruct, newsgroup->name, 0, 0, 0)
#else
# ifdef SYSV_REGEX
		! regex(reRet, newsgroup->name)
# else
		! re_exec(newsgroup->name)
# endif
#endif
		)
	      continue;

	    (void) sprintf(buffer, "%*s %s",
			   -newsgroup_width, newsgroup->name,
			   (IS_SUBSCRIBED(newsgroup) ? SUBED_MSG : UNSUBED_MSG));
	    ar[count++] = XtNewString(buffer);
	    bytes += strlen(buffer);
	}

	gen = avl_init_gen(NewsGroupTable, AVL_FORWARD);
	if (! gen)
	    ehErrorExitXRN(ERROR_OUT_OF_MEM_MSG);
	while (avl_gen(gen, &key, &value)) {
	    struct newsgroup *newsgroup = (struct newsgroup *) value;

	    if (regexp &&
#ifdef POSIX_REGEX
		regexec(&reStruct, newsgroup->name, 0, 0, 0)
#else
# ifdef SYSV_REGEX
		! regex(reRet, newsgroup->name)
# else
		! re_exec(newsgroup->name)
# endif
#endif
		)
	      continue;

	    if (IS_NOENTRY(newsgroup)) {
		(void) sprintf(buffer, "%*s %s",
			       -newsgroup_width, newsgroup->name,
			       IGNORED_MSG);
		ar[count++] = XtNewString(buffer);
		bytes += strlen(buffer);
	    }
	}
	avl_free_gen(gen);
    }	    
    
    string = arrayToString(ar, count, bytes);
    for (i = 0; i < count; i++) {
	FREE(ar[i]);
    }
    FREE(ar);

    if (regexp) {
#ifdef POSIX_REGEX
      regfree(&reStruct);
#else
# ifdef SYSV_REGEX
      free(reRet);
# endif
#endif
    }

    return string;
}



/*
  If art_num is greater than 0, format a single line in the subject
  index, and return its length (including the final newline).  If
  art_num is less than or equal to 0, just return what the length
  would be if a subject line were formatted, and reset our idea of the
  current width of the index window.  Beware that this should be
  called with art_num <= 0 before starting any series of consecutive
  calls to it.
  */
int subjectIndexLine(
		     _ANSIDECL(int,			line_length),
		     _ANSIDECL(char *,			out),
		     _ANSIDECL(struct newsgroup *,	newsgroup),
		     _ANSIDECL(art_num,			artNum),
		     _ANSIDECL(Boolean,			threaded)
		     )
     _KNRDECL(int,			line_length)
     _KNRDECL(char *,			out)
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(art_num,			artNum)
     _KNRDECL(Boolean,			threaded)
{
    static int lineLength, subLength, authorLength, lineWidth;
    static int num_width;
    struct article *art, *parent;
    char *subject, *lines, *author;
    int thread_depth, ret;
    
    if (artNum <= 0) {
      num_width = utDigits(newsgroup->last);
	lineLength = line_length;
	lineLength = MIN(LINE_LENGTH - 1, lineLength); /* for the NULL */
	subLength = lineLength -
	  3 		/* spaces before and after article number */ -
	  num_width 	/* width of article number */ -
	  2		/* spaces after subject, or spaces before and
			   after line count */ -
	  1 /* newline */;
	if (app_resources.displayLineCount) {
	    lineWidth = 6;
	    subLength -= lineWidth;
	}
	else {
	    lineWidth = 0;
	}

	if (subLength < 0) {
	    lineLength -= subLength;
	    subLength = 0;
	}

	authorLength = 0.25 * subLength;
	subLength -= authorLength;

	return lineLength;
    }

    artListSet(newsgroup);
    art = artStructGet(newsgroup, artNum, False);

    if (app_resources.displayLineCount) {
	lines = (art->lines && *art->lines) ? art->lines : "[?]";
    }
    else {
	lines = "";
    }

    if (threaded) {
      hash_table_object loop_table = 0;

    recheck:
      thread_depth = 0;
      parent = art;
      if (loop_table) {
	ret = hash_table_insert(loop_table, (void *)artNum, (void *)1, 1);
	assert(ret);
      }
      while (parent->parent) {
	if (loop_table &&
	    ! hash_table_insert(loop_table, (void *)parent->parent,
				(void *)1, 1)) {
	  hash_table_destroy(loop_table);
	  break;
	}
	if (++thread_depth == subLength) {
	  if (loop_table) {
	    hash_table_destroy(loop_table);
	    break;
	  }
	  else {
	    /* Heavily nested threading could really be authentic, or
	       it could be because of a loop in "References"
	       dependencies.  To find out which it is, we create a
	       hash table to keep track of which articles we've seen,
	       and then redo the thread-depth check.

	       We only create this hash table when we reach the
	       boundary condition, rather than for every article,
	       because creating the hash table and inserting the
	       articles number into it is expensive (well, at least,
	       more expensive than not doing it), and we want this
	       code to be as fast as possible. */
	    loop_table = hash_table_create(subLength + 1,
					   hash_int_calc, hash_int_compare,
					   hash_int_compare, 0, 0);
	    goto recheck;
	  }
	}

	parent = artStructGet(newsgroup, parent->parent, False);
      }
    }
    else {
      thread_depth = 0;
    }

    subject = art->subject;

    author = art->author ? art->author : "(none)";

    (void) sprintf(out, "  %*ld %*.*s%*.*s %*.*s %*.*s\n", num_width,
		   artNum, thread_depth, thread_depth, "",
		   -(subLength-thread_depth), subLength-thread_depth,
		   subject, lineWidth,
		   lineWidth, lines, -authorLength, authorLength,
		   author);
    if (IS_READ(art))
	*out = READ_MARKER;
    else if (IS_MARKED(art))
	*out = UNREAD_MARKER;
    if (IS_SAVED(art))
	*(out + 1) = SAVED_MARKER;
    else if (IS_PRINTED(art))
	*(out + 1) = PRINTED_MARKER;

    return lineLength;
}



char * getSubjects(
		   _ANSIDECL(int,	line_length),
		   _ANSIDECL(art_num,	artNum),
		   _ANSIDECL(Boolean,	rethread)
		   )
     _KNRDECL(int,	line_length)
     _KNRDECL(art_num,	artNum)
     _KNRDECL(Boolean,	rethread)
{
  NextPreviousArticle = artNum - 1;

  rethreadGroup(CurrentGroup, artNum, rethread);

  return art_sort_doit(CurrentGroup, artNum, CurrentGroup->last, line_length);
}


int checkArticle(art)
    art_num art;
{
    struct newsgroup *newsgroup = CurrentGroup;

    /* Check if requested article is not available */
    if (art < newsgroup->first || art > newsgroup->last) {
        return XRN_ERROR;
    }
    return XRN_OKAY;
}    


#define STRIPLEADINGSPACES   for (; *start && isspace((unsigned char)*start);\
				    start++);
#define STRIPENDINGSPACES  for (; (end >= start) && \
			isspace((unsigned char)*end); *end-- = '\0');

char * subjectStrip(str)
    char *str;
{
    register char *start, *end, *ptr;
    static char work[BUFFER_SIZE];

    (void) strncpy(work, str, BUFFER_SIZE);
    start = work;
    work[BUFFER_SIZE - 1] = '\0';

    /*
     * strip leading '[rR][eE]: ' and 'Re^N: ' -
     * only if striprefs is TRUE (want to be able to kill follow-ups)
     */
    while (! strncasecmp(start, "re: ", 4)) {
      start += 4;
      STRIPLEADINGSPACES;
    }

    while (! strncasecmp(start, "re^", 3)) {
      start += 3;
      if ((ptr = index(start, ':')))
	start = ptr + 1;
      STRIPLEADINGSPACES;
    }

    for (end = start + 1; (end = index(end, '(')); end++)
      if (! strncasecmp(end, "(was", 4) &&
	  ((end[4] == ':') || (end[4] == ' '))) {
	*end = '\0';
	break;
      }

    end = index(start, '\0') - 1;
    STRIPENDINGSPACES;

    return start;
}


/*
 * return the subject of an article with trailing/leading spaces stripped,
 * leading '[rR]e: ' stripped, and trailing ' ([wW]as: ' stripped
 */
char * getSubject(article)
    art_num article;
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art;

    artListSet(newsgroup);

    art = artStructGet(newsgroup, article, False);
    return art->subject ? subjectStrip(art->subject) : 0;
}


/*
 * return the author of an article
 */
char * getAuthor(article)
    art_num article;
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art;

    art = artStructGet(newsgroup, article, False);
    return art->author;
}


art_num getPrevNumber()
{
    struct newsgroup *newsgroup = CurrentGroup;
    struct article *art;

    /* search for the next available article in the reverse direction */
    for ( ; NextPreviousArticle >= newsgroup->first; NextPreviousArticle--) {
	art = artStructGet(newsgroup, NextPreviousArticle, False);

	if (IS_UNAVAIL(art))
	    continue;

	if (! art->subject) {
	  (void) fillUpArray(newsgroup,
			     MAX(newsgroup->first, NextPreviousArticle - SUBJECTS),
			     NextPreviousArticle, False, False);
	  NextPreviousArticle++;
	  continue;
	}

	if (art->subject) {
	    return NextPreviousArticle--;
	}
    }

    return 0;
}


/*
 * get the previous subject index line (article number is NextPreviousArticle).
 * only called when going off the top of the subject string
 *
 *   returns a point to a static area
 *
 *  NextPreviousArticle is set to current-1 on building the subject string.
 *  NextPreviousArticle is decremented by this routine.
 */
char *getPrevSubject(line_length)
     int line_length;
{
  static char buffer[BUFFER_SIZE];
  struct newsgroup *newsgroup = CurrentGroup;

  art_num art = getPrevNumber();

  if (art) {
    (void) subjectIndexLine(line_length, buffer, newsgroup, art, False);
    return buffer;
  }

  return 0;
}

			    
static art_num justInCase;   /* old NextPreviousArticle, just in case the search fails */

/* the front-end is about to do an article search, save the starting point */
void startSearch()
{
    justInCase = NextPreviousArticle;
    return;
}


/* the article search failed, restore the original point */
void failedSearch()
{
    NextPreviousArticle = justInCase;
    return;
}


int fillUpArray(
		_ANSIDECL(struct newsgroup *,	newsgroup),
		_ANSIDECL(art_num,		art),
		_ANSIDECL(art_num,		last),
		_ANSIDECL(Boolean,		check_abort),
		_ANSIDECL(Boolean,		kill_files)
		)
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(art_num,			art)
     _KNRDECL(art_num,			last)
     _KNRDECL(Boolean,			check_abort)
     _KNRDECL(Boolean,			kill_files)
{
    int i;

    if (! last)
      last = newsgroup->last;

    for (i = PREFETCH_START_HEADERS_STAGE; i <= PREFETCH_LAST_HEADERS_STAGE; ) {
      if (fetchHeadersIncremental(newsgroup, &i, art, last,
				  False, kill_files))
	i++;
      if (check_abort && abortP())
	return ABORT;
    }

    return(! ABORT);
}


/*
 * getinfofromfile	Get a string from a named file
 *			Handle white space and comments.
 *
 *	Parameters:	"file" is the name of the file to read.
 *
 *	Returns:	Pointer to static data area containing the
 *			first non-ws/comment line in the file.
 *			NULL on error (or lack of entry in file).
 *
 *	Side effects:	None.
 */

char * getinfofromfile(file)
    char *file;
{
	register FILE	*fp;
	register char	*cp;
	static char	buf[256];

	if (file == NULL)
		return (NULL);

	fp = fopen(file, "r");
	if (fp == NULL)
		return (NULL);

	while (fgets(buf, sizeof (buf), fp) != NULL) {
		if (*buf == '\n' || *buf == '#')
			continue;
		cp = index(buf, '\n');
		if (cp)
			*cp = '\0';
		(void) fclose(fp);
		return (buf);
	}

	(void) fclose(fp);
	return (NULL);			 /* No entry */
}


/*
 * enterNewsgroup
 *
 * Arguments:
 *
 * name			The newsgroup to enter.
 * flags		Bit field specifying parameters.
 * 
 * The parameters:
 * 
 * ENTER_SETUP		If true, then try to set up the newsgroup for
 *			reading.  If false, then just set the current
 *			group to the indicated newsgroup.
 * ENTER_UNREAD		If true, only enter the newsgroup if there are
 * 			unread articles articles in it.  If false,
 * 			then enter the newsgroup if any article, read
 *			or not, is available.
 * ENTER_UNSUBBED	If true, then we're allowed to switch to an
 * 			unsubscribed newsgroup.
 * ENTER_SUBSCRIBE	If true, then subscribe to the newsgroup if
 *			it's unsubscribed, and add it to the end of
 *			the .newsrc if it isn't already in it.
 * ENTER_REGEXP		If the group specified can't be found in the
 * 			table, try to do a regular expression match to
 * 			find it.
 *
 * Behavior:
 *
 * Side effects:
 * 
 * Changes CurrentGroup.  If set_up is true and jumping is false,
 * invalidates any prefetched group.  If set_up is true and jumping is
 * true, disables prefetching.  If jumping is true and the newsgroup
 * is unsubscribed, subscribes to the group.  If set_up is true,
 * updates the group's information.
 *
 * *** DOES NOT display error messages.  That's up to the caller.
 *
 * Return value:
 * 
 * GOOD_GROUP If the group was successfully entered.  BAD_GROUP if the
 * group is invalid or some other strange error occurs.  XRN_UNSUBBED
 * if the group is unsubscribed and ENTER_UNSUBBED isn't set.
 * XRN_NOMORE if ENTER_SETUP is set and there are no articles in the
 * group at all.  XRN_NOUNREAD if ENTER_SETUP is set and there are
 * only read articles in the group (if ENTER_UNREAD is set, this is an
 * error condition; otherwise, this return value is informational
 * rather than an error condition, because the newsgroup was still
 * entered even though there were no unread articles -- the last read
 * article is now current and should be displayed).
 */
int enterNewsgroup(name, flags)
    char *name;
    int flags;
{
    int ret = GOOD_GROUP;
    struct newsgroup *newsgroup;
    Boolean unsubbed = False;

    if (!avl_lookup(NewsGroupTable, name, (char **) &newsgroup)) {
      newsgroup = 0;
      if (flags & ENTER_REGEXP)
	newsgroup = findNewsGroupMatch(name);
      if (! (newsgroup || active_read)) {
	char *err_buf;

	err_buf = XtMalloc(strlen(MAYBE_LIST_MSG)+strlen(name));
	(void) sprintf(err_buf, MAYBE_LIST_MSG, name);
	if ((ConfirmationBox(TopLevel, err_buf, "yes", "no", True)
	     == XRN_CB_ABORT) || (! verifyGroup(name, &newsgroup, False))) {
	  XtFree(err_buf);
	  return BAD_GROUP;
	}
      }
      if (! newsgroup)
	return BAD_GROUP;
    }

    if (! IS_SUBSCRIBED(newsgroup)) {
	if (flags & ENTER_UNSUBBED) {
	    if (flags & ENTER_SUBSCRIBE) {
		if (IS_NOENTRY(newsgroup)) {
		    if (addToNewsrcEnd(name, SUBSCRIBE) != GOOD_GROUP)
			return BAD_GROUP;
		}
		else {
		    SET_SUB(newsgroup);
		}
	    }
	    if (! updateArticleArray(newsgroup, flags & ENTER_SETUP)) {
	      return BAD_GROUP;
	    }
	    unsubbed = True;
	}
	else {
	    return XRN_UNSUBBED;
	}
    }

    if (flags & ENTER_SETUP) {
	if (app_resources.rescanOnEnter || unsubbed)
	    setUpGroup(newsgroup, True, False, flags & ENTER_UNREAD,
		       False);

	if (EMPTY_GROUP(newsgroup)) {
	    return XRN_NOMORE;
	}

	do {
	    setUpGroup(newsgroup, False, True, flags & ENTER_UNREAD,
		       True);
	/*
	  We need to do setCurrentArticle again here, even though
	  setUpGroup() does it, because if the group is already
	  prefetched, and *then* the first unread article in it is
	  marked read while reading another group, setUpGroup() won't
	  reset the first unread article (because it doesn't do
	  anything if the group is already prefetched).
	  */
	} while (setCurrentArticle(newsgroup, flags & ENTER_UNREAD,
				   True, 0, 0));

	/*
	  Need to check if the group is empty again, because
	  setUpGroup and/or setCurrentArticle may have discovered that
	  in fact, there aren't any articles at all available in the
	  group (e.g., our cached information about the group is
	  incorrect).
	  */
	if (EMPTY_GROUP(newsgroup)) {
	  return XRN_NOMORE;
	}

	if (newsgroup->current > newsgroup->last)
	  if (flags & ENTER_UNREAD)
	    ret = XRN_NOUNREAD;
	  else
	    /*
	      In an ideal world, this case would never happen, because
	      a group's first and last article numbers as returned by
	      the server would tell EMPTY_GROUP that the group is
	      empty.  Unfortunately, some news servers don't return
	      useful first and last article number information, e.g.,
	      they'll return a range indicating that there are
	      articles in the group when in fact there are not.  So
	      we need to be careful to detect that and deal with it
	      appropriately.
	    */
	    ret = XRN_NOMORE;
	else {
	    struct article *art =
		artStructGet(newsgroup, newsgroup->current, False);
	    if (IS_READ(art))
		ret = XRN_NOUNREAD;
	    else
		ret = GOOD_GROUP;
	}

	if ((ret == XRN_NOUNREAD) && (flags & ENTER_UNREAD))
	  return ret;

	groupSnapshotSave(newsgroup);
    }

    CurrentGroup = newsgroup;

    return ret;
}

void exitNewsgroup()
{
  CurrentGroup = 0;
}


#ifdef POSIX_REGEX
regex_t *
#else
char **
#endif
parseRegexpList(list, list_name, count)
    char *list, *list_name;
    int *count;
{
    char *p, *q, *r;
    int n;
#ifdef POSIX_REGEX
    regex_t *l;
    int reRet;
#else
    char **l;
#endif

    if (! list) {
	return 0;
    }

    /* Count the number of elements in the list, if there are no regexp errors */
    for (p = q = XtNewString(list), n = 0; strtok(p, ", \t\n"); p = 0) n++;

    FREE(q);

    if (! n) {
	return 0;
    }

#ifdef POSIX_REGEX
    l = ARRAYALLOC(regex_t, n);
#else
    l = ARRAYALLOC(char *, n);
#endif

    /* Now build the list */
    for ((p = r = XtNewString(list)), n = 0; (q = strtok(p, ", \t\n")); p = 0) {
#ifdef POSIX_REGEX
	if ((reRet = regcomp(&l[n], q, REG_NOSUB))) {
	    regerror(reRet, &l[n], error_buffer,
		     sizeof(error_buffer));
	    mesgPane(XRN_SERIOUS, 0, KNOWN_LIST_REGEXP_ERROR_MSG,
		     list_name, q, error_buffer);
	    continue;
	}
#else
# ifdef SYSV_REGEX
	if (! (l[n] = regcmp(q, 0))) {
	    mesgPane(XRN_SERIOUS, 0, UNKNOWN_LIST_REGEXP_ERROR_MSG, list_name, q);
	    continue;
	}
# else
	l[n] = q;
	if ((q = re_comp(l[n]))) {
	    mesgPane(XRN_SERIOUS, 0, KNOWN_LIST_REGEXP_ERROR_MSG, list_name, l[n], q);
	    continue;
	}
# endif
#endif
	n++;
    }

#if defined(POSIX_REGEX) || defined(SYSV_REGEX)
    FREE(r);
#endif

    if (! n) {
	FREE(r);
	FREE(l);
	return 0;
    }

    *count = n;

    return l;
}

/*
  Returns -2 if the article doesn't exist, -1 if it exists but is not
  in the specified  newsgroup (or is not in the currently available
  range in the newsgroup), 0 if the article has no xref header, or
  the article number of the article.
  */
art_num getArticleNumberFromIdXref(
			       _ANSIDECL(struct newsgroup *,	newsgroup),
			       _ANSIDECL(char *,		id)
			       )
     _KNRDECL(struct newsgroup *,	newsgroup)
     _KNRDECL(char *,			id)
{
  char *xref, *ptr;
  int len;
  art_num artNum;
  long error_code;
  
  /* First, the easy way, using Xref */
  xref = xhdr_id(newsgroup, id, "xref", &error_code);
  if (xref) {
    for (ptr = strstr(xref, newsgroup->name); ptr;
	 ptr = strstr(ptr + 1, newsgroup->name)) {
      if (((ptr == xref) || isspace(ptr[-1])) &&
	  (len = strlen(newsgroup->name)) && ptr[len] == ':') {
	artNum = atol(&ptr[len+1]);
	XtFree(xref);
	if ((artNum > newsgroup->last) || (artNum < newsgroup->first))
	  return -1;
	else
	  return artNum;
      }
    }
    XtFree(xref);
    return -1;
  }

  if (error_code == ERR_NOART)
    return -2;

  return 0;
}

char *getFirstReference(references)
     char *references;
{
  static char *ref_buf = NULL;
  static int buf_size = 0;
  char *lbrace, *rbrace;

  if (! (references && *references))
    return NULL;

  if (! (lbrace = strchr(references, '<')))
    return NULL;

  if (! (rbrace = strchr(lbrace, '>')))
    return NULL;

  rbrace++;

  if (rbrace - lbrace + 1 > buf_size) {
    buf_size = rbrace - lbrace + 1;
    ref_buf = XtRealloc(ref_buf, buf_size);
  }

  strncpy(ref_buf, lbrace, rbrace - lbrace);
  ref_buf[rbrace - lbrace] = '\0';

  return ref_buf;
}