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

#include <config.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <time.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#include <wsutil/tempfile.h>
#include <wsutil/file_util.h>
#include <wsutil/filesystem.h>
#include <wsutil/ws_version_info.h>

#include <wiretap/merge.h>

#include <epan/exceptions.h>
#include <epan/epan-int.h>
#include <epan/epan.h>
#include <epan/column.h>
#include <epan/packet.h>
#include <epan/column-utils.h>
#include <epan/expert.h>
#include <epan/prefs.h>
#include <epan/dfilter/dfilter.h>
#include <epan/epan_dissect.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-ber.h>
#include <epan/timestamp.h>
#include <epan/dfilter/dfilter-macro.h>
#include <epan/strutil.h>
#include <epan/addr_resolv.h>

#include "color.h"
#include "color_filters.h"
#include "cfile.h"
#include "file.h"
#include "fileset.h"
#include "frame_tvbuff.h"

#include "ui/alert_box.h"
#include "ui/simple_dialog.h"
#include "ui/main_statusbar.h"
#include "ui/progress_dlg.h"
#include "ui/ui_util.h"

/* Needed for addrinfo */
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif

#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif

#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif

#ifdef HAVE_NETDB_H
# include <netdb.h>
#endif

#ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
#endif

#if defined(_WIN32) && defined(INET6)
# include <ws2tcpip.h>
#endif

#ifdef HAVE_LIBPCAP
gboolean auto_scroll_live; /* GTK+ only? */
#endif

static int read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
    column_info *cinfo, gint64 offset);

static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);

typedef enum {
  MR_NOTMATCHED,
  MR_MATCHED,
  MR_ERROR
} match_result;
static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
    void *criterion);
static void match_subtree_text(proto_node *node, gpointer data);
static match_result match_summary_line(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_narrow(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_wide(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_binary(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_dfilter(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_marked(capture_file *cf, frame_data *fdata,
    void *criterion);
static match_result match_time_reference(capture_file *cf, frame_data *fdata,
    void *criterion);
static gboolean find_packet(capture_file *cf,
    match_result (*match_function)(capture_file *, frame_data *, void *),
    void *criterion, search_direction dir);

static const char *cf_get_user_packet_comment(capture_file *cf, const frame_data *fd);

static void cf_open_failure_alert_box(const char *filename, int err,
                      gchar *err_info, gboolean for_writing,
                      int file_type);
static void cf_rename_failure_alert_box(const char *filename, int err);
static void cf_close_failure_alert_box(const char *filename, int err);
static void ref_time_packets(capture_file *cf);
/* Update the progress bar this many times when reading a file. */
#define N_PROGBAR_UPDATES   100
/* We read around 200k/100ms don't update the progress bar more often than that */
#define MIN_QUANTUM         200000
#define MIN_NUMBER_OF_PACKET 1500

/*
 * We could probably use g_signal_...() instead of the callbacks below but that
 * would require linking our CLI programs to libgobject and creating an object
 * instance for the signals.
 */
typedef struct {
  cf_callback_t cb_fct;
  gpointer      user_data;
} cf_callback_data_t;

static GList *cf_callbacks = NULL;

static void
cf_callback_invoke(int event, gpointer data)
{
  cf_callback_data_t *cb;
  GList              *cb_item = cf_callbacks;

  /* there should be at least one interested */
  g_assert(cb_item != NULL);

  while (cb_item != NULL) {
    cb = (cf_callback_data_t *)cb_item->data;
    cb->cb_fct(event, data, cb->user_data);
    cb_item = g_list_next(cb_item);
  }
}


void
cf_callback_add(cf_callback_t func, gpointer user_data)
{
  cf_callback_data_t *cb;

  cb = g_new(cf_callback_data_t,1);
  cb->cb_fct = func;
  cb->user_data = user_data;

  cf_callbacks = g_list_prepend(cf_callbacks, cb);
}

void
cf_callback_remove(cf_callback_t func, gpointer user_data)
{
  cf_callback_data_t *cb;
  GList              *cb_item = cf_callbacks;

  while (cb_item != NULL) {
    cb = (cf_callback_data_t *)cb_item->data;
    if (cb->cb_fct == func && cb->user_data == user_data) {
      cf_callbacks = g_list_remove(cf_callbacks, cb);
      g_free(cb);
      return;
    }
    cb_item = g_list_next(cb_item);
  }

  g_assert_not_reached();
}

void
cf_timestamp_auto_precision(capture_file *cf)
{
  int i;

  /* don't try to get the file's precision if none is opened */
  if (cf->state == FILE_CLOSED) {
    return;
  }

  /* Set the column widths of those columns that show the time in
     "command-line-specified" format. */
  for (i = 0; i < cf->cinfo.num_cols; i++) {
    if (col_has_time_fmt(&cf->cinfo, i)) {
      packet_list_resize_column(i);
    }
  }
}

gulong
cf_get_computed_elapsed(capture_file *cf)
{
  return cf->computed_elapsed;
}

/*
 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
 * replace this
 */
static void compute_elapsed(capture_file *cf, GTimeVal *start_time)
{
  gdouble  delta_time;
  GTimeVal time_now;

  g_get_current_time(&time_now);

  delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
    time_now.tv_usec - start_time->tv_usec;

  cf->computed_elapsed = (gulong) (delta_time / 1000); /* ms */
}

static const nstime_t *
ws_get_frame_ts(void *data, guint32 frame_num)
{
  capture_file *cf = (capture_file *) data;

  if (cf->prev_dis && cf->prev_dis->num == frame_num)
    return &cf->prev_dis->abs_ts;

  if (cf->prev_cap && cf->prev_cap->num == frame_num)
    return &cf->prev_cap->abs_ts;

  if (cf->frames) {
    frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);

    return (fd) ? &fd->abs_ts : NULL;
  }

  return NULL;
}

static const char *
ws_get_user_comment(void *data, const frame_data *fd)
{
  capture_file *cf = (capture_file *) data;

  return cf_get_user_packet_comment(cf, fd);
}

static epan_t *
ws_epan_new(capture_file *cf)
{
  epan_t *epan = epan_new();

  epan->data = cf;
  epan->get_frame_ts = ws_get_frame_ts;
  epan->get_interface_name = cap_file_get_interface_name;
  epan->get_user_comment = ws_get_user_comment;

  return epan;
}

cf_status_t
cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
{
  wtap  *wth;
  gchar *err_info;

  wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
  if (wth == NULL)
    goto fail;

  /* The open succeeded.  Close whatever capture file we had open,
     and fill in the information for this file. */
  cf_close(cf);

  /* Initialize the packet header. */
  wtap_phdr_init(&cf->phdr);

  /* XXX - we really want to initialize this after we've read all
     the packets, so we know how much we'll ultimately need. */
  ws_buffer_init(&cf->buf, 1500);

  /* Create new epan session for dissection.
   * (The old one was freed in cf_close().)
   */
  cf->epan = ws_epan_new(cf);

  /* We're about to start reading the file. */
  cf->state = FILE_READ_IN_PROGRESS;

  cf->wth = wth;
  cf->f_datalen = 0;

  /* Set the file name because we need it to set the follow stream filter.
     XXX - is that still true?  We need it for other reasons, though,
     in any case. */
  cf->filename = g_strdup(fname);

  /* Indicate whether it's a permanent or temporary file. */
  cf->is_tempfile = is_tempfile;

  /* No user changes yet. */
  cf->unsaved_changes = FALSE;

  cf->computed_elapsed = 0;

  cf->cd_t        = wtap_file_type_subtype(cf->wth);
  cf->open_type   = type;
  cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
  cf->count     = 0;
  cf->packet_comment_count = 0;
  cf->displayed_count = 0;
  cf->marked_count = 0;
  cf->ignored_count = 0;
  cf->ref_time_count = 0;
  cf->drops_known = FALSE;
  cf->drops     = 0;
  cf->snap      = wtap_snapshot_length(cf->wth);
  if (cf->snap == 0) {
    /* Snapshot length not known. */
    cf->has_snap = FALSE;
    cf->snap = WTAP_MAX_PACKET_SIZE;
  } else
    cf->has_snap = TRUE;

  /* Allocate a frame_data_sequence for the frames in this file */
  cf->frames = new_frame_data_sequence();

  nstime_set_zero(&cf->elapsed_time);
  cf->ref = NULL;
  cf->prev_dis = NULL;
  cf->prev_cap = NULL;
  cf->cum_bytes = 0;

  /* Adjust timestamp precision if auto is selected, col width will be adjusted */
  cf_timestamp_auto_precision(cf);
  /* XXX needed ? */
  packet_list_queue_draw();
  cf_callback_invoke(cf_cb_file_opened, cf);

  if (cf->cd_t == WTAP_FILE_TYPE_SUBTYPE_BER) {
    /* tell the BER dissector the file name */
    ber_set_filename(cf->filename);
  }

  wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
  wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);

  return CF_OK;

fail:
  cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
  return CF_ERROR;
}

/*
 * Add an encapsulation type to cf->linktypes.
 */
static void
cf_add_encapsulation_type(capture_file *cf, int encap)
{
  guint i;

  for (i = 0; i < cf->linktypes->len; i++) {
    if (g_array_index(cf->linktypes, gint, i) == encap)
      return; /* it's already there */
  }
  /* It's not already there - add it. */
  g_array_append_val(cf->linktypes, encap);
}

/* Reset everything to a pristine state */
void
cf_close(capture_file *cf)
{
  cf->stop_flag = FALSE;
  if (cf->state == FILE_CLOSED)
    return; /* Nothing to do */

  /* Die if we're in the middle of reading a file. */
  g_assert(cf->state != FILE_READ_IN_PROGRESS);

  cf_callback_invoke(cf_cb_file_closing, cf);

  /* close things, if not already closed before */
  color_filters_cleanup();

  if (cf->wth) {
    wtap_close(cf->wth);
    cf->wth = NULL;
  }
  /* We have no file open... */
  if (cf->filename != NULL) {
    /* If it's a temporary file, remove it. */
    if (cf->is_tempfile)
      ws_unlink(cf->filename);
    g_free(cf->filename);
    cf->filename = NULL;
  }
  /* ...which means we have no changes to that file to save. */
  cf->unsaved_changes = FALSE;

  /* no open_routine type */
  cf->open_type = WTAP_TYPE_AUTO;

  /* Clean up the packet header. */
  wtap_phdr_cleanup(&cf->phdr);

  /* Free up the packet buffer. */
  ws_buffer_free(&cf->buf);

  dfilter_free(cf->rfcode);
  cf->rfcode = NULL;
  if (cf->frames != NULL) {
    free_frame_data_sequence(cf->frames);
    cf->frames = NULL;
  }
#ifdef WANT_PACKET_EDITOR
  if (cf->edited_frames) {
    g_tree_destroy(cf->edited_frames);
    cf->edited_frames = NULL;
  }
#endif
  if (cf->frames_user_comments) {
    g_tree_destroy(cf->frames_user_comments);
    cf->frames_user_comments = NULL;
  }
  cf_unselect_packet(cf);   /* nothing to select */
  cf->first_displayed = 0;
  cf->last_displayed = 0;

  /* No frames, no frame selected, no field in that frame selected. */
  cf->count = 0;
  cf->current_frame = 0;
  cf->current_row = 0;
  cf->finfo_selected = NULL;

  /* No frame link-layer types, either. */
  if (cf->linktypes != NULL) {
    g_array_free(cf->linktypes, TRUE);
    cf->linktypes = NULL;
  }

  /* Clear the packet list. */
  packet_list_freeze();
  packet_list_clear();
  packet_list_thaw();

  cf->f_datalen = 0;
  nstime_set_zero(&cf->elapsed_time);

  reset_tap_listeners();

  epan_free(cf->epan);
  cf->epan = NULL;

  /* We have no file open. */
  cf->state = FILE_CLOSED;

  cf_callback_invoke(cf_cb_file_closed, cf);
}

static float
calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
{
  float progbar_val;

  progbar_val = (gfloat) file_pos / (gfloat) size;
  if (progbar_val > 1.0) {

    /*  The file probably grew while we were reading it.
     *  Update file size, and try again.
     */
    size = wtap_file_size(cf->wth, NULL);

    if (size >= 0)
      progbar_val = (gfloat) file_pos / (gfloat) size;

    /*  If it's still > 1, either "wtap_file_size()" failed (in which
     *  case there's not much we can do about it), or the file
     *  *shrank* (in which case there's not much we can do about
     *  it); just clip the progress value at 1.0.
     */
    if (progbar_val > 1.0f)
      progbar_val = 1.0f;
  }

  g_snprintf(status_str, status_size,
             "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
             file_pos / 1024, size / 1024);

  return progbar_val;
}

cf_read_status_t
cf_read(capture_file *cf, gboolean reloading)
{
  int                  err;
  gchar               *err_info;
  gchar               *name_ptr;
  progdlg_t           *progbar        = NULL;
  GTimeVal             start_time;
  epan_dissect_t       edt;
  dfilter_t           *dfcode;
  volatile gboolean    create_proto_tree;
  guint                tap_flags;
  gboolean             compiled;

  /* Compile the current display filter.
   * We assume this will not fail since cf->dfilter is only set in
   * cf_filter IFF the filter was valid.
   */
  compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
  g_assert(!cf->dfilter || (compiled && dfcode));

  /* Get the union of the flags for all tap listeners. */
  tap_flags = union_of_tap_listener_flags();
  create_proto_tree =
    (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));

  reset_tap_listeners();

  name_ptr = g_filename_display_basename(cf->filename);

  if (reloading)
    cf_callback_invoke(cf_cb_file_reload_started, cf);
  else
    cf_callback_invoke(cf_cb_file_read_started, cf);

  /* Record whether the file is compressed.
     XXX - do we know this at open time? */
  cf->iscompressed = wtap_iscompressed(cf->wth);

  /* The packet list window will be empty until the file is completly loaded */
  packet_list_freeze();

  cf->stop_flag = FALSE;
  g_get_current_time(&start_time);

  epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);

  TRY {
#ifdef HAVE_LIBPCAP
    int     displayed_once    = 0;
#endif
    int     count             = 0;

    gint64  size;
    gint64  file_pos;
    gint64  data_offset;

    gint64  progbar_quantum;
    gint64  progbar_nextstep;
    float   progbar_val;
    gchar   status_str[100];

    column_info *cinfo;

    cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;

    /* Find the size of the file. */
    size = wtap_file_size(cf->wth, NULL);

    /* Update the progress bar when it gets to this value. */
    progbar_nextstep = 0;
    /* When we reach the value that triggers a progress bar update,
       bump that value by this amount. */
    if (size >= 0) {
      progbar_quantum = size/N_PROGBAR_UPDATES;
      if (progbar_quantum < MIN_QUANTUM)
        progbar_quantum = MIN_QUANTUM;
    }else
      progbar_quantum = 0;

    while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
      if (size >= 0) {
        count++;
        file_pos = wtap_read_so_far(cf->wth);

        /* Create the progress bar if necessary.
         * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
         */
        if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
          progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
          if (reloading)
            progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
                TRUE, &cf->stop_flag, &start_time, progbar_val);
          else
            progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
                TRUE, &cf->stop_flag, &start_time, progbar_val);
        }

        /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
           when we update it, we have to run the GTK+ main loop to get it
           to repaint what's pending, and doing so may involve an "ioctl()"
           to see if there's any pending input from an X server, and doing
           that for every packet can be costly, especially on a big file. */
        if (file_pos >= progbar_nextstep) {
          if (progbar != NULL) {
            progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
            /* update the packet bar content on the first run or frequently on very large files */
#ifdef HAVE_LIBPCAP
            if (progbar_quantum > 500000 || displayed_once == 0) {
              if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
                displayed_once = 1;
                packets_bar_update();
              }
            }
#endif /* HAVE_LIBPCAP */
            update_progress_dlg(progbar, progbar_val, status_str);
          }
          progbar_nextstep += progbar_quantum;
        }
      }

      if (cf->stop_flag) {
        /* Well, the user decided to abort the read. He/She will be warned and
           it might be enough for him/her to work with the already loaded
           packets.
           This is especially true for very large capture files, where you don't
           want to wait loading the whole file (which may last minutes or even
           hours even on fast machines) just to see that it was the wrong file. */
        break;
      }
      read_packet(cf, dfcode, &edt, cinfo, data_offset);
    }
  }
  CATCH(OutOfMemoryError) {
    simple_message_box(ESD_TYPE_ERROR, NULL,
                   "More information and workarounds can be found at\n"
                   "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
                   "Sorry, but Wireshark has run out of memory and has to terminate now.");
#if 0
    /* Could we close the current capture and free up memory from that? */
#else
    /* we have to terminate, as we cannot recover from the memory error */
    exit(1);
#endif
  }
  ENDTRY;

  /* Free the display name */
  g_free(name_ptr);

  /* Cleanup and release all dfilter resources */
  if (dfcode != NULL) {
    dfilter_free(dfcode);
  }

  epan_dissect_cleanup(&edt);

  /* We're done reading the file; destroy the progress bar if it was created. */
  if (progbar != NULL)
    destroy_progress_dlg(progbar);

  /* We're done reading sequentially through the file. */
  cf->state = FILE_READ_DONE;

  /* Close the sequential I/O side, to free up memory it requires. */
  wtap_sequential_close(cf->wth);

  /* Allow the protocol dissectors to free up memory that they
   * don't need after the sequential run-through of the packets. */
  postseq_cleanup_all_protocols();

  /* compute the time it took to load the file */
  compute_elapsed(cf, &start_time);

  /* Set the file encapsulation type now; we don't know what it is until
     we've looked at all the packets, as we don't know until then whether
     there's more than one type (and thus whether it's
     WTAP_ENCAP_PER_PACKET). */
  cf->lnk_t = wtap_file_encap(cf->wth);

  cf->current_frame = frame_data_sequence_find(cf->frames, cf->first_displayed);
  cf->current_row = 0;

  packet_list_thaw();
  if (reloading)
    cf_callback_invoke(cf_cb_file_reload_finished, cf);
  else
    cf_callback_invoke(cf_cb_file_read_finished, cf);

  /* If we have any displayed packets to select, select the first of those
     packets by making the first row the selected row. */
  if (cf->first_displayed != 0) {
    packet_list_select_first_row();
  }

  if (cf->stop_flag) {
    simple_message_box(ESD_TYPE_WARN, NULL,
                  "The remaining packets in the file were discarded.\n"
                  "\n"
                  "As a lot of packets from the original file will be missing,\n"
                  "remember to be careful when saving the current content to a file.\n",
                  "File loading was cancelled.");
    return CF_READ_ERROR;
  }

  if (err != 0) {
    /* Put up a message box noting that the read failed somewhere along
       the line.  Don't throw out the stuff we managed to read, though,
       if any. */
    switch (err) {

    case WTAP_ERR_UNSUPPORTED:
      simple_error_message_box(
                 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_SHORT_READ:
      simple_error_message_box(
                 "The capture file appears to have been cut short"
                 " in the middle of a packet.");
      break;

    case WTAP_ERR_BAD_FILE:
      simple_error_message_box(
                 "The capture file appears to be damaged or corrupt.\n(%s)",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_DECOMPRESS:
      simple_error_message_box(
                 "The compressed capture file appears to be damaged or corrupt.\n",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    default:
      simple_error_message_box(
                 "An error occurred while reading the"
                 " capture file: %s.", wtap_strerror(err));
      break;
    }
    return CF_READ_ERROR;
  } else
    return CF_READ_OK;
}

#ifdef HAVE_LIBPCAP
cf_read_status_t
cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
{
  gchar            *err_info;
  volatile int      newly_displayed_packets = 0;
  dfilter_t        *dfcode;
  epan_dissect_t    edt;
  gboolean          create_proto_tree;
  guint             tap_flags;
  gboolean          compiled;

  /* Compile the current display filter.
   * We assume this will not fail since cf->dfilter is only set in
   * cf_filter IFF the filter was valid.
   */
  compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
  g_assert(!cf->dfilter || (compiled && dfcode));

  /* Get the union of the flags for all tap listeners. */
  tap_flags = union_of_tap_listener_flags();
  create_proto_tree =
    (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));

  *err = 0;

  packet_list_check_end();
  /* Don't freeze/thaw the list when doing live capture */
  /*packet_list_freeze();*/

  /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/

  epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);

  TRY {
    gint64 data_offset = 0;
    column_info *cinfo;

    cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;

    while (to_read != 0) {
      wtap_cleareof(cf->wth);
      if (!wtap_read(cf->wth, err, &err_info, &data_offset)) {
        break;
      }
      if (cf->state == FILE_READ_ABORTED) {
        /* Well, the user decided to exit Wireshark.  Break out of the
           loop, and let the code below (which is called even if there
           aren't any packets left to read) exit. */
        break;
      }
      if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
        newly_displayed_packets++;
      }
      to_read--;
    }
  }
  CATCH(OutOfMemoryError) {
    simple_message_box(ESD_TYPE_ERROR, NULL,
                   "More information and workarounds can be found at\n"
                   "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
                   "Sorry, but Wireshark has run out of memory and has to terminate now.");
#if 0
    /* Could we close the current capture and free up memory from that? */
    return CF_READ_ABORTED;
#else
    /* we have to terminate, as we cannot recover from the memory error */
    exit(1);
#endif
  }
  ENDTRY;

  /* Update the file encapsulation; it might have changed based on the
     packets we've read. */
  cf->lnk_t = wtap_file_encap(cf->wth);

  /* Cleanup and release all dfilter resources */
  if (dfcode != NULL) {
    dfilter_free(dfcode);
  }

  epan_dissect_cleanup(&edt);

  /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
    cf->count, cf->state, *err);*/

  /* Don't freeze/thaw the list when doing live capture */
  /*packet_list_thaw();*/
  /* With the new packet list the first packet
   * isn't automatically selected.
   */
  if (!cf->current_frame)
    packet_list_select_first_row();

  /* moving to the end of the packet list - if the user requested so and
     we have some new packets. */
  if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
      packet_list_moveto_end();

  if (cf->state == FILE_READ_ABORTED) {
    /* Well, the user decided to exit Wireshark.  Return CF_READ_ABORTED
       so that our caller can kill off the capture child process;
       this will cause an EOF on the pipe from the child, so
       "cf_finish_tail()" will be called, and it will clean up
       and exit. */
    return CF_READ_ABORTED;
  } else if (*err != 0) {
    /* We got an error reading the capture file.
       XXX - pop up a dialog box instead? */
    if (err_info != NULL) {
      g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
                wtap_strerror(*err), cf->filename, err_info);
      g_free(err_info);
    } else {
      g_warning("Error \"%s\" while reading \"%s\"",
                wtap_strerror(*err), cf->filename);
    }
    return CF_READ_ERROR;
  } else
    return CF_READ_OK;
}

void
cf_fake_continue_tail(capture_file *cf) {
  cf->state = FILE_READ_DONE;
}

cf_read_status_t
cf_finish_tail(capture_file *cf, int *err)
{
  gchar     *err_info;
  gint64     data_offset;
  dfilter_t *dfcode;
  column_info *cinfo;
  epan_dissect_t edt;
  gboolean   create_proto_tree;
  guint      tap_flags;
  gboolean   compiled;

  /* Compile the current display filter.
   * We assume this will not fail since cf->dfilter is only set in
   * cf_filter IFF the filter was valid.
   */
  compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
  g_assert(!cf->dfilter || (compiled && dfcode));

  /* Get the union of the flags for all tap listeners. */
  tap_flags = union_of_tap_listener_flags();
  cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
  create_proto_tree =
    (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));

  if (cf->wth == NULL) {
    cf_close(cf);
    return CF_READ_ERROR;
  }

  packet_list_check_end();
  /* Don't freeze/thaw the list when doing live capture */
  /*packet_list_freeze();*/

  epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);

  while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
    if (cf->state == FILE_READ_ABORTED) {
      /* Well, the user decided to abort the read.  Break out of the
         loop, and let the code below (which is called even if there
         aren't any packets left to read) exit. */
      break;
    }
    read_packet(cf, dfcode, &edt, cinfo, data_offset);
  }

  /* Cleanup and release all dfilter resources */
  if (dfcode != NULL) {
    dfilter_free(dfcode);
  }

  epan_dissect_cleanup(&edt);

  /* Don't freeze/thaw the list when doing live capture */
  /*packet_list_thaw();*/

  if (cf->state == FILE_READ_ABORTED) {
    /* Well, the user decided to abort the read.  We're only called
       when the child capture process closes the pipe to us (meaning
       it's probably exited), so we can just close the capture
       file; we return CF_READ_ABORTED so our caller can do whatever
       is appropriate when that happens. */
    cf_close(cf);
    return CF_READ_ABORTED;
  }

  if (auto_scroll_live && cf->count != 0)
    packet_list_moveto_end();

  /* We're done reading sequentially through the file. */
  cf->state = FILE_READ_DONE;

  /* We're done reading sequentially through the file; close the
     sequential I/O side, to free up memory it requires. */
  wtap_sequential_close(cf->wth);

  /* Allow the protocol dissectors to free up memory that they
   * don't need after the sequential run-through of the packets. */
  postseq_cleanup_all_protocols();

  /* Update the file encapsulation; it might have changed based on the
     packets we've read. */
  cf->lnk_t = wtap_file_encap(cf->wth);

  /* Update the details in the file-set dialog, as the capture file
   * has likely grown since we first stat-ed it */
  fileset_update_file(cf->filename);

  if (*err != 0) {
    /* We got an error reading the capture file.
       XXX - pop up a dialog box? */
    if (err_info != NULL) {
      g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
                wtap_strerror(*err), cf->filename, err_info);
      g_free(err_info);
    } else {
      g_warning("Error \"%s\" while reading \"%s\"",
                wtap_strerror(*err), cf->filename);
    }
    return CF_READ_ERROR;
  } else {
    return CF_READ_OK;
  }
}
#endif /* HAVE_LIBPCAP */

gchar *
cf_get_display_name(capture_file *cf)
{
  gchar *displayname;

  /* Return a name to use in displays */
  if (!cf->is_tempfile) {
    /* Get the last component of the file name, and use that. */
    if (cf->filename) {
      displayname = g_filename_display_basename(cf->filename);
    } else {
      displayname=g_strdup("(No file)");
    }
  } else {
    /* The file we read is a temporary file from a live capture or
       a merge operation; we don't mention its name, but, if it's
       from a capture, give the source of the capture. */
    if (cf->source) {
      displayname = g_strdup(cf->source);
    } else {
      displayname = g_strdup("(Untitled)");
    }
  }
  return displayname;
}

void cf_set_tempfile_source(capture_file *cf, gchar *source) {
  if (cf->source) {
    g_free(cf->source);
  }

  if (source) {
    cf->source = g_strdup(source);
  } else {
    cf->source = g_strdup("");
  }
}

const gchar *cf_get_tempfile_source(capture_file *cf) {
  if (!cf->source) {
    return "";
  }

  return cf->source;
}

/* XXX - use a macro instead? */
int
cf_get_packet_count(capture_file *cf)
{
  return cf->count;
}

/* XXX - use a macro instead? */
gboolean
cf_is_tempfile(capture_file *cf)
{
  return cf->is_tempfile;
}

void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
{
  cf->is_tempfile = is_tempfile;
}


/* XXX - use a macro instead? */
void cf_set_drops_known(capture_file *cf, gboolean drops_known)
{
  cf->drops_known = drops_known;
}

/* XXX - use a macro instead? */
void cf_set_drops(capture_file *cf, guint32 drops)
{
  cf->drops = drops;
}

/* XXX - use a macro instead? */
gboolean cf_get_drops_known(capture_file *cf)
{
  return cf->drops_known;
}

/* XXX - use a macro instead? */
guint32 cf_get_drops(capture_file *cf)
{
  return cf->drops;
}

void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
{
  cf->rfcode = rfcode;
}

static int
add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
    epan_dissect_t *edt, dfilter_t *dfcode, column_info *cinfo,
    struct wtap_pkthdr *phdr, const guint8 *buf, gboolean add_to_packet_list)
{
  gint            row               = -1;

  frame_data_set_before_dissect(fdata, &cf->elapsed_time,
                                &cf->ref, cf->prev_dis);
  cf->prev_cap = fdata;

  if (dfcode != NULL) {
      epan_dissect_prime_dfilter(edt, dfcode);
  }

  /* Dissect the frame. */
  epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, buf), fdata, cinfo);

  /* If we don't have a display filter, set "passed_dfilter" to 1. */
  if (dfcode != NULL) {
    fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;

    if (fdata->flags.passed_dfilter) {
      /* This frame passed the display filter but it may depend on other
       * (potentially not displayed) frames.  Find those frames and mark them
       * as depended upon.
       */
      g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
    }
  } else
    fdata->flags.passed_dfilter = 1;

  if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
    cf->displayed_count++;

  if (add_to_packet_list) {
    /* We fill the needed columns from new_packet_list */
      row = packet_list_append(cinfo, fdata);
  }

  if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
  {
    frame_data_set_after_dissect(fdata, &cf->cum_bytes);
    cf->prev_dis = fdata;

    /* If we haven't yet seen the first frame, this is it.

       XXX - we must do this before we add the row to the display,
       as, if the display's GtkCList's selection mode is
       GTK_SELECTION_BROWSE, when the first entry is added to it,
       "cf_select_packet()" will be called, and it will fetch the row
       data for the 0th row, and will get a null pointer rather than
       "fdata", as "gtk_clist_append()" won't yet have returned and
       thus "gtk_clist_set_row_data()" won't yet have been called.

       We thus need to leave behind bread crumbs so that
       "cf_select_packet()" can find this frame.  See the comment
       in "cf_select_packet()". */
    if (cf->first_displayed == 0)
      cf->first_displayed = fdata->num;

    /* This is the last frame we've seen so far. */
    cf->last_displayed = fdata->num;
  }

  epan_dissect_reset(edt);
  return row;
}

/* read in a new packet */
/* returns the row of the new packet in the packet list or -1 if not displayed */
static int
read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
            column_info *cinfo, gint64 offset)
{
  struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
  const guint8 *buf = wtap_buf_ptr(cf->wth);
  frame_data    fdlocal;
  guint32       framenum;
  frame_data   *fdata;
  gboolean      passed;
  int           row = -1;

  /* Add this packet's link-layer encapsulation type to cf->linktypes, if
     it's not already there.
     XXX - yes, this is O(N), so if every packet had a different
     link-layer encapsulation type, it'd be O(N^2) to read the file, but
     there are probably going to be a small number of encapsulation types
     in a file. */
  cf_add_encapsulation_type(cf, phdr->pkt_encap);

  /* The frame number of this packet is one more than the count of
     frames in the file so far. */
  framenum = cf->count + 1;

  frame_data_init(&fdlocal, framenum, phdr, offset, cf->cum_bytes);

  passed = TRUE;
  if (cf->rfcode) {
    epan_dissect_t rf_edt;

    epan_dissect_init(&rf_edt, cf->epan, TRUE, FALSE);
    epan_dissect_prime_dfilter(&rf_edt, cf->rfcode);
    epan_dissect_run(&rf_edt, cf->cd_t, phdr, frame_tvbuff_new(&fdlocal, buf), &fdlocal, NULL);
    passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
    epan_dissect_cleanup(&rf_edt);
  }

  if (passed) {
    /* This does a shallow copy of fdlocal, which is good enough. */
    fdata = frame_data_sequence_add(cf->frames, &fdlocal);

    cf->count++;
    if (phdr->opt_comment != NULL)
      cf->packet_comment_count++;
    cf->f_datalen = offset + fdlocal.cap_len;

    if (!cf->redissecting) {
      row = add_packet_to_packet_list(fdata, cf, edt, dfcode,
                                      cinfo, phdr, buf, TRUE);
    }
  }

  return row;
}

cf_status_t
cf_merge_files(char **out_filenamep, int in_file_count,
               char *const *in_filenames, int file_type, gboolean do_append)
{
  merge_in_file_t *in_files, *in_file;
  char            *out_filename;
  char            *tmpname;
  int              out_fd;
  wtap_dumper     *pdh;
  int              open_err, read_err, write_err, close_err;
  gchar           *err_info, *write_err_info = NULL;
  int              err_fileno;
  int              i;
  gboolean         got_read_error     = FALSE, got_write_error = FALSE;
  gint64           data_offset;
  progdlg_t       *progbar            = NULL;
  gboolean         stop_flag = FALSE;
  gint64           f_len, file_pos;
  float            progbar_val;
  GTimeVal         start_time;
  gchar            status_str[100];
  gint64           progbar_nextstep;
  gint64           progbar_quantum;
  gchar           *display_basename;
  int              selected_frame_type;
  gboolean         fake_interface_ids = FALSE;

  /* open the input files */
  if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
                           &open_err, &err_info, &err_fileno)) {
    g_free(in_files);
    cf_open_failure_alert_box(in_filenames[err_fileno], open_err, err_info,
                              FALSE, 0);
    return CF_ERROR;
  }

  if (*out_filenamep != NULL) {
    out_filename = *out_filenamep;
    out_fd = ws_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
    if (out_fd == -1)
      open_err = errno;
  } else {
    out_fd = create_tempfile(&tmpname, "wireshark");
    if (out_fd == -1)
      open_err = errno;
    out_filename = g_strdup(tmpname);
    *out_filenamep = out_filename;
  }
  if (out_fd == -1) {
    err_info = NULL;
    merge_close_in_files(in_file_count, in_files);
    g_free(in_files);
    cf_open_failure_alert_box(out_filename, open_err, NULL, TRUE, file_type);
    return CF_ERROR;
  }

  selected_frame_type = merge_select_frame_type(in_file_count, in_files);

  /* If we are trying to merge a number of libpcap files with different encapsulation types
   * change the output file type to pcapng and create SHB and IDB:s for the new file use the
   * interface index stored in in_files per file to change the phdr before writing the datablock.
   * XXX should it be an option to convert to pcapng?
   *
   * We need something similar when merging pcapng files possibly with an option to say
   * the same interface(s) used in all in files. SHBs comments should be merged together.
   */
  if ((selected_frame_type == WTAP_ENCAP_PER_PACKET)&&(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP)) {
    /* Write output in pcapng format */
    wtapng_section_t            *shb_hdr;
    wtapng_iface_descriptions_t *idb_inf, *idb_inf_merge_file;
    wtapng_if_descr_t            int_data, *file_int_data;
    GString                     *comment_gstr;
    guint                        itf_count, itf_id = 0;

    fake_interface_ids = TRUE;
    /* Create SHB info */
    shb_hdr      = wtap_file_get_shb_info(in_files[0].wth);
    comment_gstr = g_string_new("");
    g_string_append_printf(comment_gstr, "%s \n",shb_hdr->opt_comment);
    g_string_append_printf(comment_gstr, "File created by merging: \n");
    file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;

    for (i = 0; i < in_file_count; i++) {
        g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
    }
    shb_hdr->section_length = -1;
    /* options */
    shb_hdr->opt_comment   = g_string_free(comment_gstr, FALSE);  /* NULL if not available */
    shb_hdr->shb_hardware  = NULL;        /* NULL if not available, UTF-8 string containing the        */
                                          /*  description of the hardware used to create this section. */
    shb_hdr->shb_os        = NULL;        /* NULL if not available, UTF-8 string containing the name   */
                                          /*  of the operating system used to create this section.     */
    shb_hdr->shb_user_appl = g_strdup("Wireshark"); /* NULL if not available, UTF-8 string containing the name   */
                                          /*  of the application used to create this section.          */

    /* create fake IDB info */
    idb_inf = g_new(wtapng_iface_descriptions_t,1);
    /* TODO make this the number of DIFFERENT encapsulation types
     * check that snaplength is the same too?
     */
    idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));

    for (i = 0; i < in_file_count; i++) {
      idb_inf_merge_file               = wtap_file_get_idb_info(in_files[i].wth);
      for (itf_count = 0; itf_count < idb_inf_merge_file->interface_data->len; itf_count++) {
        /* read the interface data from the in file to our combined interface data */
        file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, itf_count);
        int_data.wtap_encap            = file_int_data->wtap_encap;
        int_data.time_units_per_second = file_int_data->time_units_per_second;
        int_data.link_type             = file_int_data->link_type;
        int_data.snap_len              = file_int_data->snap_len;
        int_data.if_name               = g_strdup(file_int_data->if_name);
        int_data.opt_comment           = NULL;
        int_data.if_description        = NULL;
        int_data.if_speed              = 0;
        int_data.if_tsresol            = file_int_data->if_tsresol;
        int_data.if_filter_str         = NULL;
        int_data.bpf_filter_len        = 0;
        int_data.if_filter_bpf_bytes   = NULL;
        int_data.if_os                 = NULL;
        int_data.if_fcslen             = -1;
        int_data.num_stat_entries      = 0;          /* Number of ISB:s */
        int_data.interface_statistics  = NULL;

        g_array_append_val(idb_inf->interface_data, int_data);
      }
      g_free(idb_inf_merge_file);

      /* Set fake interface Id in per file data */
      in_files[i].interface_id = itf_id;
      itf_id += itf_count;
    }

    pdh = wtap_dump_fdopen_ng(out_fd, file_type,
                              selected_frame_type,
                              merge_max_snapshot_length(in_file_count, in_files),
                              FALSE /* compressed */, shb_hdr, idb_inf /* wtapng_iface_descriptions_t *idb_inf */, &open_err);

    if (pdh == NULL) {
      ws_close(out_fd);
      merge_close_in_files(in_file_count, in_files);
      g_free(in_files);
      cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
                                file_type);
      return CF_ERROR;
    }

  } else {

    pdh = wtap_dump_fdopen(out_fd, file_type,
                           selected_frame_type,
                           merge_max_snapshot_length(in_file_count, in_files),
                           FALSE /* compressed */, &open_err);
    if (pdh == NULL) {
      ws_close(out_fd);
      merge_close_in_files(in_file_count, in_files);
      g_free(in_files);
      cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
                                file_type);
      return CF_ERROR;
    }
  }

  /* Get the sum of the sizes of all the files. */
  f_len = 0;
  for (i = 0; i < in_file_count; i++)
    f_len += in_files[i].size;

  /* Update the progress bar when it gets to this value. */
  progbar_nextstep = 0;
  /* When we reach the value that triggers a progress bar update,
     bump that value by this amount. */
  progbar_quantum = f_len/N_PROGBAR_UPDATES;
  /* Progress so far. */
  progbar_val = 0.0f;

  g_get_current_time(&start_time);

  /* do the merge (or append) */
  for (;;) {
    if (do_append)
      in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
                                         &err_info);
    else
      in_file = merge_read_packet(in_file_count, in_files, &read_err,
                                  &err_info);
    if (in_file == NULL) {
      /* EOF */
      break;
    }

    if (read_err != 0) {
      /* I/O error reading from in_file */
      got_read_error = TRUE;
      break;
    }

    /* Get the sum of the data offsets in all of the files. */
    data_offset = 0;
    for (i = 0; i < in_file_count; i++)
      data_offset += in_files[i].data_offset;

    /* Create the progress bar if necessary.
       We check on every iteration of the loop, so that it takes no
       longer than the standard time to create it (otherwise, for a
       large file, we might take considerably longer than that standard
       time in order to get to the next progress bar step). */
    if (progbar == NULL) {
      progbar = delayed_create_progress_dlg(NULL, "Merging", "files",
        FALSE, &stop_flag, &start_time, progbar_val);
    }

    /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
       when we update it, we have to run the GTK+ main loop to get it
       to repaint what's pending, and doing so may involve an "ioctl()"
       to see if there's any pending input from an X server, and doing
       that for every packet can be costly, especially on a big file. */
    if (data_offset >= progbar_nextstep) {
        /* Get the sum of the seek positions in all of the files. */
        file_pos = 0;
        for (i = 0; i < in_file_count; i++)
          file_pos += wtap_read_so_far(in_files[i].wth);
        progbar_val = (gfloat) file_pos / (gfloat) f_len;
        if (progbar_val > 1.0f) {
          /* Some file probably grew while we were reading it.
             That "shouldn't happen", so we'll just clip the progress
             value at 1.0. */
          progbar_val = 1.0f;
        }
        if (progbar != NULL) {
          g_snprintf(status_str, sizeof(status_str),
                     "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
                     file_pos / 1024, f_len / 1024);
          update_progress_dlg(progbar, progbar_val, status_str);
        }
        progbar_nextstep += progbar_quantum;
    }

    if (stop_flag) {
      /* Well, the user decided to abort the merge. */
      break;
    }

    /* If we have WTAP_ENCAP_PER_PACKET and the infiles are of type
     * WTAP_FILE_TYPE_SUBTYPE_PCAP, we need to set the interface id
     * in the paket header = the interface index we used in the IDBs
     * interface description for this file(encapsulation type).
     */
    if (fake_interface_ids) {
      struct wtap_pkthdr *phdr;

      phdr = wtap_phdr(in_file->wth);
      if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID) {
        phdr->interface_id += in_file->interface_id;
      } else {
        phdr->interface_id = in_file->interface_id;
        phdr->presence_flags = phdr->presence_flags | WTAP_HAS_INTERFACE_ID;
      }
    }
    if (!wtap_dump(pdh, wtap_phdr(in_file->wth),
                   wtap_buf_ptr(in_file->wth), &write_err, &write_err_info)) {
      got_write_error = TRUE;
      break;
    }
  }

  /* We're done merging the files; destroy the progress bar if it was created. */
  if (progbar != NULL)
    destroy_progress_dlg(progbar);

  merge_close_in_files(in_file_count, in_files);
  if (!got_write_error) {
    if (!wtap_dump_close(pdh, &write_err))
      got_write_error = TRUE;
  } else {
    /*
     * We already got a write error; no need to report another
     * write error on close.
     *
     * Don't overwrite the earlier write error.
     */
    (void)wtap_dump_close(pdh, &close_err);
  }

  if (got_read_error) {
    /*
     * Find the file on which we got the error, and report the error.
     */
    for (i = 0; i < in_file_count; i++) {
      if (in_files[i].state == GOT_ERROR) {
        /* Put up a message box noting that a read failed somewhere along
           the line. */
        display_basename = g_filename_display_basename(in_files[i].filename);
        switch (read_err) {

        case WTAP_ERR_SHORT_READ:
          simple_error_message_box(
                     "The capture file %s appears to have been cut short"
                      " in the middle of a packet.", display_basename);
          break;

        case WTAP_ERR_BAD_FILE:
          simple_error_message_box(
                     "The capture file %s appears to be damaged or corrupt.\n(%s)",
                     display_basename, err_info);
          g_free(err_info);
          break;

        case WTAP_ERR_DECOMPRESS:
          simple_error_message_box(
                     "The compressed capture file %s appears to be damaged or corrupt.\n"
                     "(%s)", display_basename,
                     err_info != NULL ? err_info : "no information supplied");
          g_free(err_info);
          break;

        default:
          simple_error_message_box(
                     "An error occurred while reading the"
                     " capture file %s: %s.",
                     display_basename,  wtap_strerror(read_err));
          break;
        }
        g_free(display_basename);
      }
    }
  }

  if (got_write_error) {
    /* Put up an alert box for the write error. */
    if (write_err < 0) {
      /* Wiretap error. */
      switch (write_err) {

      case WTAP_ERR_UNWRITABLE_ENCAP:
        /*
         * This is a problem with the particular frame we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");
        simple_error_message_box(
                      "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.",
                      in_file ? in_file->packet_num : 0, display_basename,
                      wtap_file_type_subtype_string(file_type));
        g_free(display_basename);
        break;

      case WTAP_ERR_PACKET_TOO_LARGE:
        /*
         * This is a problem with the particular frame we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");
        simple_error_message_box(
                      "Frame %u of \"%s\" is too large for a \"%s\" file.",
                      in_file ? in_file->packet_num : 0, display_basename,
                      wtap_file_type_subtype_string(file_type));
        g_free(display_basename);
        break;

      case WTAP_ERR_UNWRITABLE_REC_TYPE:
        /*
         * This is a problem with the particular record we're writing and
         * the file type and subtype we're writing; note that, and report
         * the record number and file type/subtype.
         */
        display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");
        simple_error_message_box(
                      "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.",
                      in_file ? in_file->packet_num : 0, display_basename,
                      wtap_file_type_subtype_string(file_type));
        g_free(display_basename);
        break;

      case WTAP_ERR_UNWRITABLE_REC_DATA:
        /*
         * This is a problem with the particular record we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        display_basename = g_filename_display_basename(in_file ? in_file->filename : "UNKNOWN");
        simple_error_message_box(
                      "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)",
                      in_file ? in_file->packet_num : 0, display_basename,
                      wtap_file_type_subtype_string(file_type),
                      write_err_info != NULL ? write_err_info : "no information supplied");
        g_free(write_err_info);
        g_free(display_basename);
        break;

      default:
        display_basename = g_filename_display_basename(out_filename);
        simple_error_message_box(
                      "An error occurred while writing to the file \"%s\": %s.",
                      out_filename, wtap_strerror(write_err));
        g_free(display_basename);
        break;
      }
    } else {
      /* OS error. */
      write_failure_alert_box(out_filename, write_err);
    }
  }

  if (got_read_error || got_write_error || stop_flag) {
    /* Callers aren't expected to treat an error or an explicit abort
       differently - we put up error dialogs ourselves, so they don't
       have to. */
    return CF_ERROR;
  } else
    return CF_OK;
}

cf_status_t
cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
{
  const char *filter_new = dftext ? dftext : "";
  const char *filter_old = cf->dfilter ? cf->dfilter : "";
  dfilter_t  *dfcode;
  gchar      *err_msg;
  GTimeVal    start_time;

  /* if new filter equals old one, do nothing unless told to do so */
  if (!force && strcmp(filter_new, filter_old) == 0) {
    return CF_OK;
  }

  dfcode=NULL;

  if (dftext == NULL) {
    /* The new filter is an empty filter (i.e., display all packets).
     * so leave dfcode==NULL
     */
  } else {
    /*
     * We have a filter; make a copy of it (as we'll be saving it),
     * and try to compile it.
     */
    dftext = g_strdup(dftext);
    if (!dfilter_compile(dftext, &dfcode, &err_msg)) {
      /* The attempt failed; report an error. */
      simple_message_box(ESD_TYPE_ERROR, NULL,
          "See the help for a description of the display filter syntax.",
          "\"%s\" isn't a valid display filter: %s",
          dftext, err_msg);
      g_free(err_msg);
      g_free(dftext);
      return CF_ERROR;
    }

    /* Was it empty? */
    if (dfcode == NULL) {
      /* Yes - free the filter text, and set it to null. */
      g_free(dftext);
      dftext = NULL;
    }
  }

  /* We have a valid filter.  Replace the current filter. */
  g_free(cf->dfilter);
  cf->dfilter = dftext;
  g_get_current_time(&start_time);


  /* Now rescan the packet list, applying the new filter, but not
     throwing away information constructed on a previous pass. */
  if (dftext == NULL) {
    rescan_packets(cf, "Resetting", "Filter", FALSE);
  } else {
    rescan_packets(cf, "Filtering", dftext, FALSE);
  }

  /* Cleanup and release all dfilter resources */
  dfilter_free(dfcode);

  return CF_OK;
}

void
cf_reftime_packets(capture_file *cf)
{
  ref_time_packets(cf);
}

void
cf_redissect_packets(capture_file *cf)
{
  if (cf->state != FILE_CLOSED) {
    rescan_packets(cf, "Reprocessing", "all packets", TRUE);
  }
}

gboolean
cf_read_record_r(capture_file *cf, const frame_data *fdata,
                 struct wtap_pkthdr *phdr, Buffer *buf)
{
  int    err;
  gchar *err_info;
  gchar *display_basename;

#ifdef WANT_PACKET_EDITOR
  /* if fdata->file_off == -1 it means packet was edited, and we must find data inside edited_frames tree */
  if (G_UNLIKELY(fdata->file_off == -1)) {
    const modified_frame_data *frame = (const modified_frame_data *) g_tree_lookup(cf->edited_frames, GINT_TO_POINTER(fdata->num));

    if (!frame) {
      simple_error_message_box("fdata->file_off == -1, but can't find modified frame.");
      return FALSE;
    }

    *phdr = frame->phdr;
    ws_buffer_assure_space(buf, frame->phdr.caplen);
    memcpy(ws_buffer_start_ptr(buf), frame->pd, frame->phdr.caplen);
    return TRUE;
  }
#endif

  if (!wtap_seek_read(cf->wth, fdata->file_off, phdr, buf, &err, &err_info)) {
    display_basename = g_filename_display_basename(cf->filename);
    switch (err) {

    case WTAP_ERR_BAD_FILE:
      simple_error_message_box("An error occurred while reading from the file \"%s\": %s.\n(%s)",
                 display_basename, wtap_strerror(err),
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    default:
      simple_error_message_box(
                 "An error occurred while reading from the file \"%s\": %s.",
                 display_basename, wtap_strerror(err));
      break;
    }
    g_free(display_basename);
    return FALSE;
  }
  return TRUE;
}

gboolean
cf_read_record(capture_file *cf, frame_data *fdata)
{
  return cf_read_record_r(cf, fdata, &cf->phdr, &cf->buf);
}

/* Rescan the list of packets, reconstructing the CList.

   "action" describes why we're doing this; it's used in the progress
   dialog box.

   "action_item" describes what we're doing; it's used in the progress
   dialog box.

   "redissect" is TRUE if we need to make the dissectors reconstruct
   any state information they have (because a preference that affects
   some dissector has changed, meaning some dissector might construct
   its state differently from the way it was constructed the last time). */
static void
rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
{
  /* Rescan packets new packet list */
  guint32     framenum;
  frame_data *fdata;
  progdlg_t  *progbar = NULL;
  int         count;
  frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
  int         selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
  gboolean    selected_frame_seen;
  float       progbar_val;
  GTimeVal    start_time;
  gchar       status_str[100];
  int         progbar_nextstep;
  int         progbar_quantum;
  epan_dissect_t  edt;
  dfilter_t  *dfcode;
  column_info *cinfo;
  gboolean    create_proto_tree;
  guint       tap_flags;
  gboolean    add_to_packet_list = FALSE;
  gboolean    compiled;
  guint32     frames_count;

  /* Compile the current display filter.
   * We assume this will not fail since cf->dfilter is only set in
   * cf_filter IFF the filter was valid.
   */
  compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
  g_assert(!cf->dfilter || (compiled && dfcode));

  /* Get the union of the flags for all tap listeners. */
  tap_flags = union_of_tap_listener_flags();
  cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
  create_proto_tree =
    (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));

  reset_tap_listeners();
  /* Which frame, if any, is the currently selected frame?
     XXX - should the selected frame or the focus frame be the "current"
     frame, that frame being the one from which "Find Frame" searches
     start? */
  selected_frame = cf->current_frame;

  /* Mark frame num as not found */
  selected_frame_num = -1;

  /* Freeze the packet list while we redo it, so we don't get any
     screen updates while it happens. */
  packet_list_freeze();

  if (redissect) {
    /* We need to re-initialize all the state information that protocols
       keep, because some preference that controls a dissector has changed,
       which might cause the state information to be constructed differently
       by that dissector. */

    /* We might receive new packets while redissecting, and we don't
       want to dissect those before their time. */
    cf->redissecting = TRUE;

    /* 'reset' dissection session */
    epan_free(cf->epan);
    cf->epan = ws_epan_new(cf);
    cf->cinfo.epan = cf->epan;

    /* We need to redissect the packets so we have to discard our old
     * packet list store. */
    packet_list_clear();
    add_to_packet_list = TRUE;
  }

  /* We don't yet know which will be the first and last frames displayed. */
  cf->first_displayed = 0;
  cf->last_displayed = 0;

  /* We currently don't display any packets */
  cf->displayed_count = 0;

  /* Iterate through the list of frames.  Call a routine for each frame
     to check whether it should be displayed and, if so, add it to
     the display list. */
  cf->ref = NULL;
  cf->prev_dis = NULL;
  cf->prev_cap = NULL;
  cf->cum_bytes = 0;

  /* Update the progress bar when it gets to this value. */
  progbar_nextstep = 0;
  /* When we reach the value that triggers a progress bar update,
     bump that value by this amount. */
  progbar_quantum = cf->count/N_PROGBAR_UPDATES;
  /* Count of packets at which we've looked. */
  count = 0;
  /* Progress so far. */
  progbar_val = 0.0f;

  cf->stop_flag = FALSE;
  g_get_current_time(&start_time);

  /* no previous row yet */
  prev_frame_num = -1;
  prev_frame = NULL;

  preceding_frame_num = -1;
  preceding_frame = NULL;
  following_frame_num = -1;
  following_frame = NULL;

  selected_frame_seen = FALSE;

  frames_count = cf->count;

  epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);

  for (framenum = 1; framenum <= frames_count; framenum++) {
    fdata = frame_data_sequence_find(cf->frames, framenum);

    /* Create the progress bar if necessary.
       We check on every iteration of the loop, so that it takes no
       longer than the standard time to create it (otherwise, for a
       large file, we might take considerably longer than that standard
       time in order to get to the next progress bar step). */
    if (progbar == NULL)
      progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
                                            &cf->stop_flag,
                                            &start_time,
                                            progbar_val);

    /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
       when we update it, we have to run the GTK+ main loop to get it
       to repaint what's pending, and doing so may involve an "ioctl()"
       to see if there's any pending input from an X server, and doing
       that for every packet can be costly, especially on a big file. */
    if (count >= progbar_nextstep) {
      /* let's not divide by zero. I should never be started
       * with count == 0, so let's assert that
       */
      g_assert(cf->count > 0);
      progbar_val = (gfloat) count / frames_count;

      if (progbar != NULL) {
        g_snprintf(status_str, sizeof(status_str),
                  "%4u of %u frames", count, frames_count);
        update_progress_dlg(progbar, progbar_val, status_str);
      }

      progbar_nextstep += progbar_quantum;
    }

    if (cf->stop_flag) {
      /* Well, the user decided to abort the filtering.  Just stop.

         XXX - go back to the previous filter?  Users probably just
         want not to wait for a filtering operation to finish;
         unless we cancel by having no filter, reverting to the
         previous filter will probably be even more expensive than
         continuing the filtering, as it involves going back to the
         beginning and filtering, and even with no filter we currently
         have to re-generate the entire clist, which is also expensive.

         I'm not sure what Network Monitor does, but it doesn't appear
         to give you an unfiltered display if you cancel. */
      break;
    }

    count++;

    if (redissect) {
      /* Since all state for the frame was destroyed, mark the frame
       * as not visited, free the GSList referring to the state
       * data (the per-frame data itself was freed by
       * "init_dissection()"), and null out the GSList pointer. */
      frame_data_reset(fdata);
      frames_count = cf->count;
    }

    /* Frame dependencies from the previous dissection/filtering are no longer valid. */
    fdata->flags.dependent_of_displayed = 0;

    if (!cf_read_record(cf, fdata))
      break; /* error reading the frame */

    /* If the previous frame is displayed, and we haven't yet seen the
       selected frame, remember that frame - it's the closest one we've
       yet seen before the selected frame. */
    if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
      preceding_frame_num = prev_frame_num;
      preceding_frame = prev_frame;
    }

    add_packet_to_packet_list(fdata, cf, &edt, dfcode,
                                    cinfo, &cf->phdr,
                                    ws_buffer_start_ptr(&cf->buf),
                                    add_to_packet_list);

    /* If this frame is displayed, and this is the first frame we've
       seen displayed after the selected frame, remember this frame -
       it's the closest one we've yet seen at or after the selected
       frame. */
    if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
      following_frame_num = fdata->num;
      following_frame = fdata;
    }
    if (fdata == selected_frame) {
      selected_frame_seen = TRUE;
      if (fdata->flags.passed_dfilter)
          selected_frame_num = fdata->num;
    }

    /* Remember this frame - it'll be the previous frame
       on the next pass through the loop. */
    prev_frame_num = fdata->num;
    prev_frame = fdata;
  }

  epan_dissect_cleanup(&edt);

  /* We are done redissecting the packet list. */
  cf->redissecting = FALSE;

  if (redissect) {
      frames_count = cf->count;
    /* Clear out what remains of the visited flags and per-frame data
       pointers.

       XXX - that may cause various forms of bogosity when dissecting
       these frames, as they won't have been seen by this sequential
       pass, but the only alternative I see is to keep scanning them
       even though the user requested that the scan stop, and that
       would leave the user stuck with an Wireshark grinding on
       until it finishes.  Should we just stick them with that? */
    for (; framenum <= frames_count; framenum++) {
      fdata = frame_data_sequence_find(cf->frames, framenum);
      frame_data_reset(fdata);
    }
  }

  /* We're done filtering the packets; destroy the progress bar if it
     was created. */
  if (progbar != NULL)
    destroy_progress_dlg(progbar);

  /* Unfreeze the packet list. */
  if (!add_to_packet_list)
    packet_list_recreate_visible_rows();

  /* Compute the time it took to filter the file */
  compute_elapsed(cf, &start_time);

  packet_list_thaw();

  if (selected_frame_num == -1) {
    /* The selected frame didn't pass the filter. */
    if (selected_frame == NULL) {
      /* That's because there *was* no selected frame.  Make the first
         displayed frame the current frame. */
      selected_frame_num = 0;
    } else {
      /* Find the nearest displayed frame to the selected frame (whether
         it's before or after that frame) and make that the current frame.
         If the next and previous displayed frames are equidistant from the
         selected frame, choose the next one. */
      g_assert(following_frame == NULL ||
               following_frame->num >= selected_frame->num);
      g_assert(preceding_frame == NULL ||
               preceding_frame->num <= selected_frame->num);
      if (following_frame == NULL) {
        /* No frame after the selected frame passed the filter, so we
           have to select the last displayed frame before the selected
           frame. */
        selected_frame_num = preceding_frame_num;
        selected_frame = preceding_frame;
      } else if (preceding_frame == NULL) {
        /* No frame before the selected frame passed the filter, so we
           have to select the first displayed frame after the selected
           frame. */
        selected_frame_num = following_frame_num;
        selected_frame = following_frame;
      } else {
        /* Frames before and after the selected frame passed the filter, so
           we'll select the previous frame */
        selected_frame_num = preceding_frame_num;
        selected_frame = preceding_frame;
      }
    }
  }

  if (selected_frame_num == -1) {
    /* There are no frames displayed at all. */
    cf_unselect_packet(cf);
  } else {
    /* Either the frame that was selected passed the filter, or we've
       found the nearest displayed frame to that frame.  Select it, make
       it the focus row, and make it visible. */
    /* Set to invalid to force update of packet list and packet details */
    cf->current_row = -1;
    if (selected_frame_num == 0) {
      packet_list_select_first_row();
    }else{
      if (!packet_list_select_row_from_data(selected_frame)) {
        /* We didn't find a row corresponding to this frame.
           This means that the frame isn't being displayed currently,
           so we can't select it. */
        simple_message_box(ESD_TYPE_INFO, NULL,
                           "The capture file is probably not fully dissected.",
                           "End of capture exceeded.");
      }
    }
  }

  /* Cleanup and release all dfilter resources */
  dfilter_free(dfcode);
}


/*
 * Scan trough all frame data and recalculate the ref time
 * without rereading the file.
 * XXX - do we need a progres bar or is this fast enough?
 */
static void
ref_time_packets(capture_file *cf)
{
  guint32     framenum;
  frame_data *fdata;
  nstime_t rel_ts;

  cf->ref = NULL;
  cf->prev_dis = NULL;
  cf->cum_bytes = 0;

  for (framenum = 1; framenum <= cf->count; framenum++) {
    fdata = frame_data_sequence_find(cf->frames, framenum);

    /* just add some value here until we know if it is being displayed or not */
    fdata->cum_bytes = cf->cum_bytes + fdata->pkt_len;

    /*
     *Timestamps
     */

    /* If we don't have the time stamp of the first packet in the
     capture, it's because this is the first packet.  Save the time
     stamp of this packet as the time stamp of the first packet. */
    if (cf->ref == NULL)
        cf->ref = fdata;
      /* if this frames is marked as a reference time frame, reset
        firstsec and firstusec to this frame */
    if (fdata->flags.ref_time)
        cf->ref = fdata;

    /* If we don't have the time stamp of the previous displayed packet,
     it's because this is the first displayed packet.  Save the time
     stamp of this packet as the time stamp of the previous displayed
     packet. */
    if (cf->prev_dis == NULL) {
        cf->prev_dis = fdata;
    }

    /* Get the time elapsed between the first packet and this packet. */
    fdata->frame_ref_num = (fdata != cf->ref) ? cf->ref->num : 0;
    nstime_delta(&rel_ts, &fdata->abs_ts, &cf->ref->abs_ts);

    /* If it's greater than the current elapsed time, set the elapsed time
     to it (we check for "greater than" so as not to be confused by
     time moving backwards). */
    if ((gint32)cf->elapsed_time.secs < rel_ts.secs
        || ((gint32)cf->elapsed_time.secs == rel_ts.secs && (gint32)cf->elapsed_time.nsecs < rel_ts.nsecs)) {
        cf->elapsed_time = rel_ts;
    }

    /* If this frame is displayed, get the time elapsed between the
     previous displayed packet and this packet. */
    if ( fdata->flags.passed_dfilter ) {
        fdata->prev_dis_num = cf->prev_dis->num;
        cf->prev_dis = fdata;
    }

    /*
     * Byte counts
     */
    if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
        /* This frame either passed the display filter list or is marked as
        a time reference frame.  All time reference frames are displayed
        even if they don't pass the display filter */
        if (fdata->flags.ref_time) {
            /* if this was a TIME REF frame we should reset the cum_bytes field */
            cf->cum_bytes = fdata->pkt_len;
            fdata->cum_bytes = cf->cum_bytes;
        } else {
            /* increase cum_bytes with this packets length */
            cf->cum_bytes += fdata->pkt_len;
        }
    }
  }
}

typedef enum {
  PSP_FINISHED,
  PSP_STOPPED,
  PSP_FAILED
} psp_return_t;

static psp_return_t
process_specified_records(capture_file *cf, packet_range_t *range,
    const char *string1, const char *string2, gboolean terminate_is_stop,
    gboolean (*callback)(capture_file *, frame_data *,
                         struct wtap_pkthdr *, const guint8 *, void *),
    void *callback_args)
{
  guint32          framenum;
  frame_data      *fdata;
  Buffer           buf;
  psp_return_t     ret     = PSP_FINISHED;

  progdlg_t       *progbar = NULL;
  int              progbar_count;
  float            progbar_val;
  GTimeVal         progbar_start_time;
  gchar            progbar_status_str[100];
  int              progbar_nextstep;
  int              progbar_quantum;
  range_process_e  process_this;
  struct wtap_pkthdr phdr;

  wtap_phdr_init(&phdr);
  ws_buffer_init(&buf, 1500);

  /* Update the progress bar when it gets to this value. */
  progbar_nextstep = 0;
  /* When we reach the value that triggers a progress bar update,
     bump that value by this amount. */
  progbar_quantum = cf->count/N_PROGBAR_UPDATES;
  /* Count of packets at which we've looked. */
  progbar_count = 0;
  /* Progress so far. */
  progbar_val = 0.0f;

  cf->stop_flag = FALSE;
  g_get_current_time(&progbar_start_time);

  if (range != NULL)
    packet_range_process_init(range);

  /* Iterate through all the packets, printing the packets that
     were selected by the current display filter.  */
  for (framenum = 1; framenum <= cf->count; framenum++) {
    fdata = frame_data_sequence_find(cf->frames, framenum);

    /* Create the progress bar if necessary.
       We check on every iteration of the loop, so that it takes no
       longer than the standard time to create it (otherwise, for a
       large file, we might take considerably longer than that standard
       time in order to get to the next progress bar step). */
    if (progbar == NULL)
      progbar = delayed_create_progress_dlg(cf->window, string1, string2,
                                            terminate_is_stop,
                                            &cf->stop_flag,
                                            &progbar_start_time,
                                            progbar_val);

    /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
       when we update it, we have to run the GTK+ main loop to get it
       to repaint what's pending, and doing so may involve an "ioctl()"
       to see if there's any pending input from an X server, and doing
       that for every packet can be costly, especially on a big file. */
    if (progbar_count >= progbar_nextstep) {
      /* let's not divide by zero. I should never be started
       * with count == 0, so let's assert that
       */
      g_assert(cf->count > 0);
      progbar_val = (gfloat) progbar_count / cf->count;

      if (progbar != NULL) {
        g_snprintf(progbar_status_str, sizeof(progbar_status_str),
                   "%4u of %u packets", progbar_count, cf->count);
        update_progress_dlg(progbar, progbar_val, progbar_status_str);
      }

      progbar_nextstep += progbar_quantum;
    }

    if (cf->stop_flag) {
      /* Well, the user decided to abort the operation.  Just stop,
         and arrange to return PSP_STOPPED to our caller, so they know
         it was stopped explicitly. */
      ret = PSP_STOPPED;
      break;
    }

    progbar_count++;

    if (range != NULL) {
      /* do we have to process this packet? */
      process_this = packet_range_process_packet(range, fdata);
      if (process_this == range_process_next) {
        /* this packet uninteresting, continue with next one */
        continue;
      } else if (process_this == range_processing_finished) {
        /* all interesting packets processed, stop the loop */
        break;
      }
    }

    /* Get the packet */
    if (!cf_read_record_r(cf, fdata, &phdr, &buf)) {
      /* Attempt to get the packet failed. */
      ret = PSP_FAILED;
      break;
    }
    /* Process the packet */
    if (!callback(cf, fdata, &phdr, ws_buffer_start_ptr(&buf), callback_args)) {
      /* Callback failed.  We assume it reported the error appropriately. */
      ret = PSP_FAILED;
      break;
    }
  }

  /* We're done printing the packets; destroy the progress bar if
     it was created. */
  if (progbar != NULL)
    destroy_progress_dlg(progbar);

  wtap_phdr_cleanup(&phdr);
  ws_buffer_free(&buf);

  return ret;
}

typedef struct {
  epan_dissect_t edt;
  column_info *cinfo;
} retap_callback_args_t;

static gboolean
retap_packet(capture_file *cf, frame_data *fdata,
             struct wtap_pkthdr *phdr, const guint8 *pd,
             void *argsp)
{
  retap_callback_args_t *args = (retap_callback_args_t *)argsp;

  epan_dissect_run_with_taps(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, args->cinfo);
  epan_dissect_reset(&args->edt);

  return TRUE;
}

cf_read_status_t
cf_retap_packets(capture_file *cf)
{
  packet_range_t        range;
  retap_callback_args_t callback_args;
  gboolean              construct_protocol_tree;
  gboolean              filtering_tap_listeners;
  guint                 tap_flags;
  psp_return_t          ret;

  /* Presumably the user closed the capture file. */
  if (cf == NULL) {
    return CF_READ_ABORTED;
  }

  /* Do we have any tap listeners with filters? */
  filtering_tap_listeners = have_filtering_tap_listeners();

  tap_flags = union_of_tap_listener_flags();

  /* If any tap listeners have filters, or require the protocol tree,
     construct the protocol tree. */
  construct_protocol_tree = filtering_tap_listeners ||
                            (tap_flags & TL_REQUIRES_PROTO_TREE);

  /* If any tap listeners require the columns, construct them. */
  callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;

  /* Reset the tap listeners. */
  reset_tap_listeners();

  epan_dissect_init(&callback_args.edt, cf->epan, construct_protocol_tree, FALSE);

  /* Iterate through the list of packets, dissecting all packets and
     re-running the taps. */
  packet_range_init(&range, cf);
  packet_range_process_init(&range);

  ret = process_specified_records(cf, &range, "Recalculating statistics on",
                                  "all packets", TRUE, retap_packet,
                                  &callback_args);

  epan_dissect_cleanup(&callback_args.edt);

  switch (ret) {
  case PSP_FINISHED:
    /* Completed successfully. */
    return CF_READ_OK;

  case PSP_STOPPED:
    /* Well, the user decided to abort the refiltering.
       Return CF_READ_ABORTED so our caller knows they did that. */
    return CF_READ_ABORTED;

  case PSP_FAILED:
    /* Error while retapping. */
    return CF_READ_ERROR;
  }

  g_assert_not_reached();
  return CF_READ_OK;
}

typedef struct {
  print_args_t *print_args;
  gboolean      print_header_line;
  char         *header_line_buf;
  int           header_line_buf_len;
  gboolean      print_formfeed;
  gboolean      print_separator;
  char         *line_buf;
  int           line_buf_len;
  gint         *col_widths;
  int           num_visible_cols;
  gint         *visible_cols;
  epan_dissect_t edt;
} print_callback_args_t;

static gboolean
print_packet(capture_file *cf, frame_data *fdata,
             struct wtap_pkthdr *phdr, const guint8 *pd,
             void *argsp)
{
  print_callback_args_t *args = (print_callback_args_t *)argsp;
  int             i;
  char           *cp;
  int             line_len;
  int             column_len;
  int             cp_off;
  char            bookmark_name[9+10+1];  /* "__frameNNNNNNNNNN__\0" */
  char            bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0"  */
  col_item_t*     col_item;

  /* Fill in the column information if we're printing the summary
     information. */
  if (args->print_args->print_summary) {
    col_custom_prime_edt(&args->edt, &cf->cinfo);
    epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
    epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
  } else
    epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);

  if (args->print_formfeed) {
    if (!new_page(args->print_args->stream))
      goto fail;
  } else {
      if (args->print_separator) {
        if (!print_line(args->print_args->stream, 0, ""))
          goto fail;
      }
  }

  /*
   * We generate bookmarks, if the output format supports them.
   * The name is "__frameN__".
   */
  g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);

  if (args->print_args->print_summary) {
    if (!args->print_args->print_col_headings)
        args->print_header_line = FALSE;
    if (args->print_header_line) {
      if (!print_line(args->print_args->stream, 0, args->header_line_buf))
        goto fail;
      args->print_header_line = FALSE;  /* we might not need to print any more */
    }
    cp = &args->line_buf[0];
    line_len = 0;
    for (i = 0; i < args->num_visible_cols; i++) {
      col_item = &cf->cinfo.columns[args->visible_cols[i]];
      /* Find the length of the string for this column. */
      column_len = (int) strlen(col_item->col_data);
      if (args->col_widths[i] > column_len)
         column_len = args->col_widths[i];

      /* Make sure there's room in the line buffer for the column; if not,
         double its length. */
      line_len += column_len + 1;   /* "+1" for space */
      if (line_len > args->line_buf_len) {
        cp_off = (int) (cp - args->line_buf);
        args->line_buf_len = 2 * line_len;
        args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
        cp = args->line_buf + cp_off;
      }

      /* Right-justify the packet number column. */
      if (col_item->col_fmt == COL_NUMBER)
        g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], col_item->col_data);
      else
        g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_item->col_data);
      cp += column_len;
      if (i != args->num_visible_cols - 1)
        *cp++ = ' ';
    }
    *cp = '\0';

    /*
     * Generate a bookmark, using the summary line as the title.
     */
    if (!print_bookmark(args->print_args->stream, bookmark_name,
                        args->line_buf))
      goto fail;

    if (!print_line(args->print_args->stream, 0, args->line_buf))
      goto fail;
  } else {
    /*
     * Generate a bookmark, using "Frame N" as the title, as we're not
     * printing the summary line.
     */
    g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
    if (!print_bookmark(args->print_args->stream, bookmark_name,
                        bookmark_title))
      goto fail;
  } /* if (print_summary) */

  if (args->print_args->print_dissections != print_dissections_none) {
    if (args->print_args->print_summary) {
      /* Separate the summary line from the tree with a blank line. */
      if (!print_line(args->print_args->stream, 0, ""))
        goto fail;
    }

    /* Print the information in that tree. */
    if (!proto_tree_print(args->print_args, &args->edt, NULL, args->print_args->stream))
      goto fail;

    /* Print a blank line if we print anything after this (aka more than one packet). */
    args->print_separator = TRUE;

    /* Print a header line if we print any more packet summaries */
    if (args->print_args->print_col_headings)
        args->print_header_line = TRUE;
  }

  if (args->print_args->print_hex) {
    if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
      if (!print_line(args->print_args->stream, 0, ""))
        goto fail;
    }
    /* Print the full packet data as hex. */
    if (!print_hex_data(args->print_args->stream, &args->edt))
      goto fail;

    /* Print a blank line if we print anything after this (aka more than one packet). */
    args->print_separator = TRUE;

    /* Print a header line if we print any more packet summaries */
    if (args->print_args->print_col_headings)
        args->print_header_line = TRUE;
  } /* if (args->print_args->print_dissections != print_dissections_none) */

  epan_dissect_reset(&args->edt);

  /* do we want to have a formfeed between each packet from now on? */
  if (args->print_args->print_formfeed) {
    args->print_formfeed = TRUE;
  }

  return TRUE;

fail:
  epan_dissect_reset(&args->edt);
  return FALSE;
}

cf_print_status_t
cf_print_packets(capture_file *cf, print_args_t *print_args)
{
  print_callback_args_t callback_args;
  gint          data_width;
  char         *cp;
  int           i, cp_off, column_len, line_len;
  int           num_visible_col = 0, last_visible_col = 0, visible_col_count;
  psp_return_t  ret;
  GList        *clp;
  fmt_data     *cfmt;
  gboolean      proto_tree_needed;

  callback_args.print_args = print_args;
  callback_args.print_header_line = print_args->print_col_headings;
  callback_args.header_line_buf = NULL;
  callback_args.header_line_buf_len = 256;
  callback_args.print_formfeed = FALSE;
  callback_args.print_separator = FALSE;
  callback_args.line_buf = NULL;
  callback_args.line_buf_len = 256;
  callback_args.col_widths = NULL;
  callback_args.num_visible_cols = 0;
  callback_args.visible_cols = NULL;

  if (!print_preamble(print_args->stream, cf->filename, get_ws_vcs_version_info())) {
    destroy_print_stream(print_args->stream);
    return CF_PRINT_WRITE_ERROR;
  }

  if (print_args->print_summary) {
    /* We're printing packet summaries.  Allocate the header line buffer
       and get the column widths. */
    callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);

    /* Find the number of visible columns and the last visible column */
    for (i = 0; i < prefs.num_cols; i++) {

        clp = g_list_nth(prefs.col_list, i);
        if (clp == NULL) /* Sanity check, Invalid column requested */
            continue;

        cfmt = (fmt_data *) clp->data;
        if (cfmt->visible) {
            num_visible_col++;
            last_visible_col = i;
        }
    }

    /* Find the widths for each of the columns - maximum of the
       width of the title and the width of the data - and construct
       a buffer with a line containing the column titles. */
    callback_args.num_visible_cols = num_visible_col;
    callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
    callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
    cp = &callback_args.header_line_buf[0];
    line_len = 0;
    visible_col_count = 0;
    for (i = 0; i < cf->cinfo.num_cols; i++) {

      clp = g_list_nth(prefs.col_list, i);
      if (clp == NULL) /* Sanity check, Invalid column requested */
          continue;

      cfmt = (fmt_data *) clp->data;
      if (cfmt->visible == FALSE)
          continue;

      /* Save the order of visible columns */
      callback_args.visible_cols[visible_col_count] = i;

      /* Don't pad the last column. */
      if (i == last_visible_col)
        callback_args.col_widths[visible_col_count] = 0;
      else {
        callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
        data_width = get_column_char_width(get_column_format(i));
        if (data_width > callback_args.col_widths[visible_col_count])
          callback_args.col_widths[visible_col_count] = data_width;
      }

      /* Find the length of the string for this column. */
      column_len = (int) strlen(cf->cinfo.columns[i].col_title);
      if (callback_args.col_widths[i] > column_len)
        column_len = callback_args.col_widths[visible_col_count];

      /* Make sure there's room in the line buffer for the column; if not,
         double its length. */
      line_len += column_len + 1;   /* "+1" for space */
      if (line_len > callback_args.header_line_buf_len) {
        cp_off = (int) (cp - callback_args.header_line_buf);
        callback_args.header_line_buf_len = 2 * line_len;
        callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
                                                  callback_args.header_line_buf_len + 1);
        cp = callback_args.header_line_buf + cp_off;
      }

      /* Right-justify the packet number column. */
/*      if (cf->cinfo.col_fmt[i] == COL_NUMBER)
        g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
      else*/
      g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
      cp += column_len;
      if (i != cf->cinfo.num_cols - 1)
        *cp++ = ' ';

      visible_col_count++;
    }
    *cp = '\0';

    /* Now start out the main line buffer with the same length as the
       header line buffer. */
    callback_args.line_buf_len = callback_args.header_line_buf_len;
    callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
  } /* if (print_summary) */

  /* Create the protocol tree, and make it visible, if we're printing
     the dissection or the hex data.
     XXX - do we need it if we're just printing the hex data? */
  proto_tree_needed =
      callback_args.print_args->print_dissections != print_dissections_none ||
      callback_args.print_args->print_hex ||
      have_custom_cols(&cf->cinfo);
  epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);

  /* Iterate through the list of packets, printing the packets we were
     told to print. */
  ret = process_specified_records(cf, &print_args->range, "Printing",
                                  "selected packets", TRUE, print_packet,
                                  &callback_args);
  epan_dissect_cleanup(&callback_args.edt);
  g_free(callback_args.header_line_buf);
  g_free(callback_args.line_buf);
  g_free(callback_args.col_widths);
  g_free(callback_args.visible_cols);

  switch (ret) {

  case PSP_FINISHED:
    /* Completed successfully. */
    break;

  case PSP_STOPPED:
    /* Well, the user decided to abort the printing.

       XXX - note that what got generated before they did that
       will get printed if we're piping to a print program; we'd
       have to write to a file and then hand that to the print
       program to make it actually not print anything. */
    break;

  case PSP_FAILED:
    /* Error while printing.

       XXX - note that what got generated before they did that
       will get printed if we're piping to a print program; we'd
       have to write to a file and then hand that to the print
       program to make it actually not print anything. */
    destroy_print_stream(print_args->stream);
    return CF_PRINT_WRITE_ERROR;
  }

  if (!print_finale(print_args->stream)) {
    destroy_print_stream(print_args->stream);
    return CF_PRINT_WRITE_ERROR;
  }

  if (!destroy_print_stream(print_args->stream))
    return CF_PRINT_WRITE_ERROR;

  return CF_PRINT_OK;
}

typedef struct {
  FILE *fh;
  epan_dissect_t edt;
} write_packet_callback_args_t;

static gboolean
write_pdml_packet(capture_file *cf, frame_data *fdata,
                  struct wtap_pkthdr *phdr, const guint8 *pd,
          void *argsp)
{
  write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;

  /* Create the protocol tree, but don't fill in the column information. */
  epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);

  /* Write out the information in that tree. */
  write_pdml_proto_tree(&args->edt, args->fh);

  epan_dissect_reset(&args->edt);

  return !ferror(args->fh);
}

cf_print_status_t
cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
{
  write_packet_callback_args_t callback_args;
  FILE         *fh;
  psp_return_t  ret;

  fh = ws_fopen(print_args->file, "w");
  if (fh == NULL)
    return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */

  write_pdml_preamble(fh, cf->filename);
  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  callback_args.fh = fh;
  epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);

  /* Iterate through the list of packets, printing the packets we were
     told to print. */
  ret = process_specified_records(cf, &print_args->range, "Writing PDML",
                                  "selected packets", TRUE,
                                  write_pdml_packet, &callback_args);

  epan_dissect_cleanup(&callback_args.edt);

  switch (ret) {

  case PSP_FINISHED:
    /* Completed successfully. */
    break;

  case PSP_STOPPED:
    /* Well, the user decided to abort the printing. */
    break;

  case PSP_FAILED:
    /* Error while printing. */
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  write_pdml_finale(fh);
  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  /* XXX - check for an error */
  fclose(fh);

  return CF_PRINT_OK;
}

static gboolean
write_psml_packet(capture_file *cf, frame_data *fdata,
                  struct wtap_pkthdr *phdr, const guint8 *pd,
          void *argsp)
{
  write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;

  /* Fill in the column information */
  col_custom_prime_edt(&args->edt, &cf->cinfo);
  epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
  epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);

  /* Write out the column information. */
  write_psml_columns(&args->edt, args->fh);

  epan_dissect_reset(&args->edt);

  return !ferror(args->fh);
}

cf_print_status_t
cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
{
  write_packet_callback_args_t callback_args;
  FILE         *fh;
  psp_return_t  ret;

  gboolean proto_tree_needed;

  fh = ws_fopen(print_args->file, "w");
  if (fh == NULL)
    return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */

  write_psml_preamble(&cf->cinfo, fh);
  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  callback_args.fh = fh;

  /* Fill in the column information, only create the protocol tree
     if having custom columns. */
  proto_tree_needed = have_custom_cols(&cf->cinfo);
  epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);

  /* Iterate through the list of packets, printing the packets we were
     told to print. */
  ret = process_specified_records(cf, &print_args->range, "Writing PSML",
                                  "selected packets", TRUE,
                                  write_psml_packet, &callback_args);

  epan_dissect_cleanup(&callback_args.edt);

  switch (ret) {

  case PSP_FINISHED:
    /* Completed successfully. */
    break;

  case PSP_STOPPED:
    /* Well, the user decided to abort the printing. */
    break;

  case PSP_FAILED:
    /* Error while printing. */
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  write_psml_finale(fh);
  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  /* XXX - check for an error */
  fclose(fh);

  return CF_PRINT_OK;
}

static gboolean
write_csv_packet(capture_file *cf, frame_data *fdata,
                 struct wtap_pkthdr *phdr, const guint8 *pd,
                 void *argsp)
{
  write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;

  /* Fill in the column information */
  col_custom_prime_edt(&args->edt, &cf->cinfo);
  epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, &cf->cinfo);
  epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);

  /* Write out the column information. */
  write_csv_columns(&args->edt, args->fh);

  epan_dissect_reset(&args->edt);

  return !ferror(args->fh);
}

cf_print_status_t
cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
{
  write_packet_callback_args_t callback_args;
  gboolean        proto_tree_needed;
  FILE         *fh;
  psp_return_t  ret;

  fh = ws_fopen(print_args->file, "w");
  if (fh == NULL)
    return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */

  write_csv_column_titles(&cf->cinfo, fh);
  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  callback_args.fh = fh;

  /* only create the protocol tree if having custom columns. */
  proto_tree_needed = have_custom_cols(&cf->cinfo);
  epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);

  /* Iterate through the list of packets, printing the packets we were
     told to print. */
  ret = process_specified_records(cf, &print_args->range, "Writing CSV",
                                  "selected packets", TRUE,
                                  write_csv_packet, &callback_args);

  epan_dissect_cleanup(&callback_args.edt);

  switch (ret) {

  case PSP_FINISHED:
    /* Completed successfully. */
    break;

  case PSP_STOPPED:
    /* Well, the user decided to abort the printing. */
    break;

  case PSP_FAILED:
    /* Error while printing. */
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  /* XXX - check for an error */
  fclose(fh);

  return CF_PRINT_OK;
}

static gboolean
carrays_write_packet(capture_file *cf, frame_data *fdata,
             struct wtap_pkthdr *phdr,
             const guint8 *pd, void *argsp)
{
  write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;

  epan_dissect_run(&args->edt, cf->cd_t, phdr, frame_tvbuff_new(fdata, pd), fdata, NULL);
  write_carrays_hex_data(fdata->num, args->fh, &args->edt);
  epan_dissect_reset(&args->edt);

  return !ferror(args->fh);
}

cf_print_status_t
cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
{
  write_packet_callback_args_t callback_args;
  FILE         *fh;
  psp_return_t  ret;

  fh = ws_fopen(print_args->file, "w");

  if (fh == NULL)
    return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */

  if (ferror(fh)) {
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  callback_args.fh = fh;
  epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);

  /* Iterate through the list of packets, printing the packets we were
     told to print. */
  ret = process_specified_records(cf, &print_args->range,
                  "Writing C Arrays",
                  "selected packets", TRUE,
                                  carrays_write_packet, &callback_args);

  epan_dissect_cleanup(&callback_args.edt);

  switch (ret) {
  case PSP_FINISHED:
    /* Completed successfully. */
    break;
  case PSP_STOPPED:
    /* Well, the user decided to abort the printing. */
    break;
  case PSP_FAILED:
    /* Error while printing. */
    fclose(fh);
    return CF_PRINT_WRITE_ERROR;
  }

  fclose(fh);
  return CF_PRINT_OK;
}

gboolean
cf_find_packet_protocol_tree(capture_file *cf, const char *string,
                             search_direction dir)
{
  match_data mdata;

  mdata.string = string;
  mdata.string_len = strlen(string);
  return find_packet(cf, match_protocol_tree, &mdata, dir);
}

gboolean
cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree,  match_data *mdata)
{
  mdata->frame_matched = FALSE;
  mdata->string = convert_string_case(cf->sfilter, cf->case_type);
  mdata->string_len = strlen(mdata->string);
  mdata->cf = cf;
  /* Iterate through all the nodes looking for matching text */
  proto_tree_children_foreach(tree, match_subtree_text, mdata);
  return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
}

static match_result
match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
{
  match_data     *mdata = (match_data *)criterion;
  epan_dissect_t  edt;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  /* Construct the protocol tree, including the displayed text */
  epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
  /* We don't need the column information */
  epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata, NULL);

  /* Iterate through all the nodes, seeing if they have text that matches. */
  mdata->cf = cf;
  mdata->frame_matched = FALSE;
  proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
  epan_dissect_cleanup(&edt);
  return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
}

static void
match_subtree_text(proto_node *node, gpointer data)
{
  match_data   *mdata      = (match_data *) data;
  const gchar  *string     = mdata->string;
  size_t        string_len = mdata->string_len;
  capture_file *cf         = mdata->cf;
  field_info   *fi         = PNODE_FINFO(node);
  gchar         label_str[ITEM_LABEL_LENGTH];
  gchar        *label_ptr;
  size_t        label_len;
  guint32       i;
  guint8        c_char;
  size_t        c_match    = 0;

  /* dissection with an invisible proto tree? */
  g_assert(fi);

  if (mdata->frame_matched) {
    /* We already had a match; don't bother doing any more work. */
    return;
  }

  /* Don't match invisible entries. */
  if (PROTO_ITEM_IS_HIDDEN(node))
    return;

  /* was a free format label produced? */
  if (fi->rep) {
    label_ptr = fi->rep->representation;
  } else {
    /* no, make a generic label */
    label_ptr = label_str;
    proto_item_fill_label(fi, label_str);
  }

  /* Does that label match? */
  label_len = strlen(label_ptr);
  for (i = 0; i < label_len; i++) {
    c_char = label_ptr[i];
    if (cf->case_type)
      c_char = g_ascii_toupper(c_char);
    if (c_char == string[c_match]) {
      c_match++;
      if (c_match == string_len) {
        /* No need to look further; we have a match */
        mdata->frame_matched = TRUE;
        mdata->finfo = fi;
        return;
      }
    } else
      c_match = 0;
  }

  /* Recurse into the subtree, if it exists */
  if (node->first_child != NULL)
    proto_tree_children_foreach(node, match_subtree_text, mdata);
}

gboolean
cf_find_packet_summary_line(capture_file *cf, const char *string,
                            search_direction dir)
{
  match_data mdata;

  mdata.string = string;
  mdata.string_len = strlen(string);
  return find_packet(cf, match_summary_line, &mdata, dir);
}

static match_result
match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
{
  match_data     *mdata      = (match_data *)criterion;
  const gchar    *string     = mdata->string;
  size_t          string_len = mdata->string_len;
  epan_dissect_t  edt;
  const char     *info_column;
  size_t          info_column_len;
  match_result    result     = MR_NOTMATCHED;
  gint            colx;
  guint32         i;
  guint8          c_char;
  size_t          c_match    = 0;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  /* Don't bother constructing the protocol tree */
  epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
  /* Get the column information */
  epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata,
                   &cf->cinfo);

  /* Find the Info column */
  for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
    if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
      /* Found it.  See if we match. */
      info_column = edt.pi.cinfo->columns[colx].col_data;
      info_column_len = strlen(info_column);
      for (i = 0; i < info_column_len; i++) {
        c_char = info_column[i];
        if (cf->case_type)
          c_char = g_ascii_toupper(c_char);
        if (c_char == string[c_match]) {
          c_match++;
          if (c_match == string_len) {
            result = MR_MATCHED;
            break;
          }
        } else
          c_match = 0;
      }
      break;
    }
  }
  epan_dissect_cleanup(&edt);
  return result;
}

typedef struct {
    const guint8 *data;
    size_t        data_len;
} cbs_t;    /* "Counted byte string" */


/*
 * The current match_* routines only support ASCII case insensitivity and don't
 * convert UTF-8 inputs to UTF-16 for matching.
 *
 * We could modify them to use the GLib Unicode routines or the International
 * Components for Unicode library but it's not apparent that we could do so
 * without consuming a lot more CPU and memory or that searching would be
 * significantly better.
 */

gboolean
cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
                    search_direction dir)
{
  cbs_t info;

  info.data = string;
  info.data_len = string_size;

  /* String or hex search? */
  if (cf->string) {
    /* String search - what type of string? */
    switch (cf->scs_type) {

    case SCS_NARROW_AND_WIDE:
      return find_packet(cf, match_narrow_and_wide, &info, dir);

    case SCS_NARROW:
      return find_packet(cf, match_narrow, &info, dir);

    case SCS_WIDE:
      return find_packet(cf, match_wide, &info, dir);

    default:
      g_assert_not_reached();
      return FALSE;
    }
  } else
    return find_packet(cf, match_binary, &info, dir);
}

static match_result
match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
{
  cbs_t        *info       = (cbs_t *)criterion;
  const guint8 *ascii_text = info->data;
  size_t        textlen    = info->data_len;
  match_result  result;
  guint32       buf_len;
  guint8       *pd;
  guint32       i;
  guint8        c_char;
  size_t        c_match    = 0;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  result = MR_NOTMATCHED;
  buf_len = fdata->cap_len;
  pd = ws_buffer_start_ptr(&cf->buf);
  i = 0;
  while (i < buf_len) {
    c_char = pd[i];
    if (cf->case_type)
      c_char = g_ascii_toupper(c_char);
    if (c_char != '\0') {
      if (c_char == ascii_text[c_match]) {
        c_match += 1;
        if (c_match == textlen) {
          result = MR_MATCHED;
          cf->search_pos = i; /* Save the position of the last character
                                 for highlighting the field. */
          break;
        }
      }
      else {
        g_assert(i>=c_match);
        i -= (guint32)c_match;
        c_match = 0;
      }
    }
    i += 1;
  }
  return result;
}

static match_result
match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
{
  guint8       *pd;
  cbs_t        *info       = (cbs_t *)criterion;
  const guint8 *ascii_text = info->data;
  size_t        textlen    = info->data_len;
  match_result  result;
  guint32       buf_len;
  guint32       i;
  guint8        c_char;
  size_t        c_match    = 0;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  result = MR_NOTMATCHED;
  buf_len = fdata->cap_len;
  pd = ws_buffer_start_ptr(&cf->buf);
  i = 0;
  while (i < buf_len) {
    c_char = pd[i];
    if (cf->case_type)
      c_char = g_ascii_toupper(c_char);
    if (c_char == ascii_text[c_match]) {
      c_match += 1;
      if (c_match == textlen) {
        result = MR_MATCHED;
        cf->search_pos = i; /* Save the position of the last character
                               for highlighting the field. */
        break;
      }
    }
    else {
      g_assert(i>=c_match);
      i -= (guint32)c_match;
      c_match = 0;
    }
    i += 1;
  }

  return result;
}

static match_result
match_wide(capture_file *cf, frame_data *fdata, void *criterion)
{
  cbs_t        *info       = (cbs_t *)criterion;
  const guint8 *ascii_text = info->data;
  size_t        textlen    = info->data_len;
  match_result  result;
  guint32       buf_len;
  guint8       *pd;
  guint32       i;
  guint8        c_char;
  size_t        c_match    = 0;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  result = MR_NOTMATCHED;
  buf_len = fdata->cap_len;
  pd = ws_buffer_start_ptr(&cf->buf);
  i = 0;
  while (i < buf_len) {
    c_char = pd[i];
    if (cf->case_type)
      c_char = g_ascii_toupper(c_char);
    if (c_char == ascii_text[c_match]) {
      c_match += 1;
      if (c_match == textlen) {
        result = MR_MATCHED;
        cf->search_pos = i; /* Save the position of the last character
                               for highlighting the field. */
        break;
      }
      i += 1;
    }
    else {
      g_assert(i>=(c_match*2));
      i -= (guint32)c_match*2;
      c_match = 0;
    }
    i += 1;
  }
  return result;
}

static match_result
match_binary(capture_file *cf, frame_data *fdata, void *criterion)
{
  cbs_t        *info        = (cbs_t *)criterion;
  const guint8 *binary_data = info->data;
  size_t        datalen     = info->data_len;
  match_result  result;
  guint32       buf_len;
  guint8       *pd;
  guint32       i;
  size_t        c_match     = 0;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  result = MR_NOTMATCHED;
  buf_len = fdata->cap_len;
  pd = ws_buffer_start_ptr(&cf->buf);
  i = 0;
  while (i < buf_len) {
    if (pd[i] == binary_data[c_match]) {
      c_match += 1;
      if (c_match == datalen) {
        result = MR_MATCHED;
        cf->search_pos = i; /* Save the position of the last character
                               for highlighting the field. */
        break;
      }
    }
    else {
      g_assert(i>=c_match);
      i -= (guint32)c_match;
      c_match = 0;
    }
    i += 1;
  }
  return result;
}

gboolean
cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
                       search_direction dir)
{
  return find_packet(cf, match_dfilter, sfcode, dir);
}

gboolean
cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
                              search_direction dir)
{
  dfilter_t *sfcode;
  gboolean   result;

  if (!dfilter_compile(filter, &sfcode, NULL)) {
     /*
      * XXX - this shouldn't happen, as the filter string is machine
      * generated
      */
    return FALSE;
  }
  if (sfcode == NULL) {
    /*
     * XXX - this shouldn't happen, as the filter string is machine
     * generated.
     */
    return FALSE;
  }
  result = find_packet(cf, match_dfilter, sfcode, dir);
  dfilter_free(sfcode);
  return result;
}

static match_result
match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
{
  dfilter_t      *sfcode = (dfilter_t *)criterion;
  epan_dissect_t  edt;
  match_result    result;

  /* Load the frame's data. */
  if (!cf_read_record(cf, fdata)) {
    /* Attempt to get the packet failed. */
    return MR_ERROR;
  }

  epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
  epan_dissect_prime_dfilter(&edt, sfcode);
  epan_dissect_run(&edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(fdata, &cf->buf), fdata, NULL);
  result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
  epan_dissect_cleanup(&edt);
  return result;
}

gboolean
cf_find_packet_marked(capture_file *cf, search_direction dir)
{
  return find_packet(cf, match_marked, NULL, dir);
}

static match_result
match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
{
  return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
}

gboolean
cf_find_packet_time_reference(capture_file *cf, search_direction dir)
{
  return find_packet(cf, match_time_reference, NULL, dir);
}

static match_result
match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
{
  return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
}

static gboolean
find_packet(capture_file *cf,
            match_result (*match_function)(capture_file *, frame_data *, void *),
            void *criterion, search_direction dir)
{
  frame_data  *start_fd;
  guint32      framenum;
  frame_data  *fdata;
  frame_data  *new_fd = NULL;
  progdlg_t   *progbar = NULL;
  int          count;
  gboolean     found;
  float        progbar_val;
  GTimeVal     start_time;
  gchar        status_str[100];
  int          progbar_nextstep;
  int          progbar_quantum;
  const char  *title;
  match_result result;

  start_fd = cf->current_frame;
  if (start_fd != NULL)  {
    /* Iterate through the list of packets, starting at the packet we've
       picked, calling a routine to run the filter on the packet, see if
       it matches, and stop if so.  */
    count = 0;
    framenum = start_fd->num;

    /* Update the progress bar when it gets to this value. */
    progbar_nextstep = 0;
    /* When we reach the value that triggers a progress bar update,
       bump that value by this amount. */
    progbar_quantum = cf->count/N_PROGBAR_UPDATES;
    /* Progress so far. */
    progbar_val = 0.0f;

    cf->stop_flag = FALSE;
    g_get_current_time(&start_time);

    title = cf->sfilter?cf->sfilter:"";
    for (;;) {
      /* Create the progress bar if necessary.
         We check on every iteration of the loop, so that it takes no
         longer than the standard time to create it (otherwise, for a
         large file, we might take considerably longer than that standard
         time in order to get to the next progress bar step). */
      if (progbar == NULL)
         progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
           FALSE, &cf->stop_flag, &start_time, progbar_val);

      /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
         when we update it, we have to run the GTK+ main loop to get it
         to repaint what's pending, and doing so may involve an "ioctl()"
         to see if there's any pending input from an X server, and doing
         that for every packet can be costly, especially on a big file. */
      if (count >= progbar_nextstep) {
        /* let's not divide by zero. I should never be started
         * with count == 0, so let's assert that
         */
        g_assert(cf->count > 0);

        progbar_val = (gfloat) count / cf->count;

        if (progbar != NULL) {
          g_snprintf(status_str, sizeof(status_str),
                     "%4u of %u packets", count, cf->count);
          update_progress_dlg(progbar, progbar_val, status_str);
        }

        progbar_nextstep += progbar_quantum;
      }

      if (cf->stop_flag) {
        /* Well, the user decided to abort the search.  Go back to the
           frame where we started. */
        new_fd = start_fd;
        break;
      }

      /* Go past the current frame. */
      if (dir == SD_BACKWARD) {
        /* Go on to the previous frame. */
        if (framenum == 1) {
          /*
           * XXX - other apps have a bit more of a detailed message
           * for this, and instead of offering "OK" and "Cancel",
           * they offer things such as "Continue" and "Cancel";
           * we need an API for popping up alert boxes with
           * {Verb} and "Cancel".
           */

          if (prefs.gui_find_wrap)
          {
              statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
              framenum = cf->count;     /* wrap around */
          }
          else
          {
              statusbar_push_temporary_msg("Search reached the beginning.");
              framenum = start_fd->num; /* stay on previous packet */
          }
        } else
          framenum--;
      } else {
        /* Go on to the next frame. */
        if (framenum == cf->count) {
          if (prefs.gui_find_wrap)
          {
              statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
              framenum = 1;             /* wrap around */
          }
          else
          {
              statusbar_push_temporary_msg("Search reached the end.");
              framenum = start_fd->num; /* stay on previous packet */
          }
        } else
          framenum++;
      }
      fdata = frame_data_sequence_find(cf->frames, framenum);

      count++;

      /* Is this packet in the display? */
      if (fdata->flags.passed_dfilter) {
        /* Yes.  Does it match the search criterion? */
        result = (*match_function)(cf, fdata, criterion);
        if (result == MR_ERROR) {
          /* Error; our caller has reported the error.  Go back to the frame
             where we started. */
          new_fd = start_fd;
          break;
        } else if (result == MR_MATCHED) {
          /* Yes.  Go to the new frame. */
          new_fd = fdata;
          break;
        }
      }

      if (fdata == start_fd) {
        /* We're back to the frame we were on originally, and that frame
           doesn't match the search filter.  The search failed. */
        break;
      }
    }

    /* We're done scanning the packets; destroy the progress bar if it
       was created. */
    if (progbar != NULL)
      destroy_progress_dlg(progbar);
  }

  if (new_fd != NULL) {
    /* Find and select */
    cf->search_in_progress = TRUE;
    found = packet_list_select_row_from_data(new_fd);
    cf->search_in_progress = FALSE;
    cf->search_pos = 0; /* Reset the position */
    if (!found) {
      /* We didn't find a row corresponding to this frame.
         This means that the frame isn't being displayed currently,
         so we can't select it. */
      simple_message_box(ESD_TYPE_INFO, NULL,
                         "The capture file is probably not fully dissected.",
                         "End of capture exceeded.");
      return FALSE;
    }
    return TRUE;    /* success */
  } else
    return FALSE;   /* failure */
}

gboolean
cf_goto_frame(capture_file *cf, guint fnumber)
{
  frame_data *fdata;

  fdata = frame_data_sequence_find(cf->frames, fnumber);

  if (fdata == NULL) {
    /* we didn't find a packet with that packet number */
    statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
    return FALSE;   /* we failed to go to that packet */
  }
  if (!fdata->flags.passed_dfilter) {
    /* that packet currently isn't displayed */
    /* XXX - add it to the set of displayed packets? */
    statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
    return FALSE;   /* we failed to go to that packet */
  }

  if (!packet_list_select_row_from_data(fdata)) {
    /* We didn't find a row corresponding to this frame.
       This means that the frame isn't being displayed currently,
       so we can't select it. */
    simple_message_box(ESD_TYPE_INFO, NULL,
                       "The capture file is probably not fully dissected.",
                       "End of capture exceeded.");
    return FALSE;
  }
  return TRUE;  /* we got to that packet */
}

gboolean
cf_goto_top_frame(void)
{
  /* Find and select */
  packet_list_select_first_row();
  return TRUE;  /* we got to that packet */
}

gboolean
cf_goto_bottom_frame(void)
{
  /* Find and select */
  packet_list_select_last_row();
  return TRUE;  /* we got to that packet */
}

/*
 * Go to frame specified by currently selected protocol tree item.
 */
gboolean
cf_goto_framenum(capture_file *cf)
{
  header_field_info *hfinfo;
  guint32            framenum;

  if (cf->finfo_selected) {
    hfinfo = cf->finfo_selected->hfinfo;
    g_assert(hfinfo);
    if (hfinfo->type == FT_FRAMENUM) {
      framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
      if (framenum != 0)
        return cf_goto_frame(cf, framenum);
      }
  }

  return FALSE;
}

/* Select the packet on a given row. */
void
cf_select_packet(capture_file *cf, int row)
{
  epan_dissect_t *old_edt;
  frame_data     *fdata;

  /* Get the frame data struct pointer for this frame */
  fdata = packet_list_get_row_data(row);

  if (fdata == NULL) {
    /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
       the first entry is added to it by "real_insert_row()", that row
       is selected (see "real_insert_row()", in "ui/gtk/gtkclist.c", in both
       our version and the vanilla GTK+ version).

       This means that a "select-row" signal is emitted; this causes
       "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
       to be called.

       "cf_select_packet()" fetches, above, the data associated with the
       row that was selected; however, as "gtk_clist_append()", which
       called "real_insert_row()", hasn't yet returned, we haven't yet
       associated any data with that row, so we get back a null pointer.

       We can't assume that there's only one frame in the frame list,
       either, as we may be filtering the display.

       We therefore assume that, if "row" is 0, i.e. the first row
       is being selected, and "cf->first_displayed" equals
       "cf->last_displayed", i.e. there's only one frame being
       displayed, that frame is the frame we want.

       This means we have to set "cf->first_displayed" and
       "cf->last_displayed" before adding the row to the
       GtkCList; see the comment in "add_packet_to_packet_list()". */

       if (row == 0 && cf->first_displayed == cf->last_displayed)
         fdata = frame_data_sequence_find(cf->frames, cf->first_displayed);
  }

  /* If fdata _still_ isn't set simply give up. */
  if (fdata == NULL) {
    return;
  }

  /* Get the data in that frame. */
  if (!cf_read_record (cf, fdata)) {
    return;
  }

  /* Record that this frame is the current frame. */
  cf->current_frame = fdata;
  cf->current_row = row;

  old_edt = cf->edt;
  /* Create the logical protocol tree. */
  /* We don't need the columns here. */
  cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);

  tap_build_interesting(cf->edt);
  epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr, frame_tvbuff_new_buffer(cf->current_frame, &cf->buf),
                   cf->current_frame, NULL);

  dfilter_macro_build_ftv_cache(cf->edt->tree);

  cf_callback_invoke(cf_cb_packet_selected, cf);

  if (old_edt != NULL)
    epan_dissect_free(old_edt);

}

/* Unselect the selected packet, if any. */
void
cf_unselect_packet(capture_file *cf)
{
  epan_dissect_t *old_edt = cf->edt;

  cf->edt = NULL;

  /* No packet is selected. */
  cf->current_frame = NULL;
  cf->current_row = 0;

  cf_callback_invoke(cf_cb_packet_unselected, cf);

  /* No protocol tree means no selected field. */
  cf_unselect_field(cf);

  /* Destroy the epan_dissect_t for the unselected packet. */
  if (old_edt != NULL)
    epan_dissect_free(old_edt);
}

/* Unset the selected protocol tree field, if any. */
void
cf_unselect_field(capture_file *cf)
{
  cf->finfo_selected = NULL;

  cf_callback_invoke(cf_cb_field_unselected, cf);
}

/*
 * Mark a particular frame.
 */
void
cf_mark_frame(capture_file *cf, frame_data *frame)
{
  if (! frame->flags.marked) {
    frame->flags.marked = TRUE;
    if (cf->count > cf->marked_count)
      cf->marked_count++;
  }
}

/*
 * Unmark a particular frame.
 */
void
cf_unmark_frame(capture_file *cf, frame_data *frame)
{
  if (frame->flags.marked) {
    frame->flags.marked = FALSE;
    if (cf->marked_count > 0)
      cf->marked_count--;
  }
}

/*
 * Ignore a particular frame.
 */
void
cf_ignore_frame(capture_file *cf, frame_data *frame)
{
  if (! frame->flags.ignored) {
    frame->flags.ignored = TRUE;
    if (cf->count > cf->ignored_count)
      cf->ignored_count++;
  }
}

/*
 * Un-ignore a particular frame.
 */
void
cf_unignore_frame(capture_file *cf, frame_data *frame)
{
  if (frame->flags.ignored) {
    frame->flags.ignored = FALSE;
    if (cf->ignored_count > 0)
      cf->ignored_count--;
  }
}

/*
 * Read the comment in SHB block
 */

const gchar *
cf_read_shb_comment(capture_file *cf)
{
  wtapng_section_t *shb_inf;
  const gchar      *temp_str;

  /* Get info from SHB */
  shb_inf = wtap_file_get_shb_info(cf->wth);
  if (shb_inf == NULL)
        return NULL;
  temp_str = shb_inf->opt_comment;
  g_free(shb_inf);

  return temp_str;

}

void
cf_update_capture_comment(capture_file *cf, gchar *comment)
{
  wtapng_section_t *shb_inf;

  /* Get info from SHB */
  shb_inf = wtap_file_get_shb_info(cf->wth);

  /* See if the comment has changed or not */
  if (shb_inf && shb_inf->opt_comment) {
    if (strcmp(shb_inf->opt_comment, comment) == 0) {
      g_free(comment);
      g_free(shb_inf);
      return;
    }
  }

  g_free(shb_inf);

  /* The comment has changed, let's update it */
  wtap_write_shb_comment(cf->wth, comment);
  /* Mark the file as having unsaved changes */
  cf->unsaved_changes = TRUE;
}

static const char *
cf_get_user_packet_comment(capture_file *cf, const frame_data *fd)
{
  if (cf->frames_user_comments)
     return (const char *)g_tree_lookup(cf->frames_user_comments, fd);

  /* g_warning? */
  return NULL;
}

char *
cf_get_comment(capture_file *cf, const frame_data *fd)
{
  char *comment;

  /* fetch user comment */
  if (fd->flags.has_user_comment)
    return g_strdup(cf_get_user_packet_comment(cf, fd));

  /* fetch phdr comment */
  if (fd->flags.has_phdr_comment) {
    struct wtap_pkthdr phdr; /* Packet header */
    Buffer buf; /* Packet data */

    wtap_phdr_init(&phdr);
    ws_buffer_init(&buf, 1500);

    if (!cf_read_record_r(cf, fd, &phdr, &buf))
      { /* XXX, what we can do here? */ }

    comment = phdr.opt_comment;
    wtap_phdr_cleanup(&phdr);
    ws_buffer_free(&buf);
    return comment;
  }
  return NULL;
}

static int
frame_cmp(gconstpointer a, gconstpointer b, gpointer user_data _U_)
{
  const frame_data *fdata1 = (const frame_data *) a;
  const frame_data *fdata2 = (const frame_data *) b;

  return (fdata1->num < fdata2->num) ? -1 :
    (fdata1->num > fdata2->num) ? 1 :
    0;
}

gboolean
cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
{
  char *pkt_comment = cf_get_comment(cf, fd);

  /* Check if the comment has changed */
  if (!g_strcmp0(pkt_comment, new_comment)) {
    g_free(pkt_comment);
    return FALSE;
  }
  g_free(pkt_comment);

  if (pkt_comment)
    cf->packet_comment_count--;

  if (new_comment)
    cf->packet_comment_count++;

  fd->flags.has_user_comment = TRUE;

  if (!cf->frames_user_comments)
    cf->frames_user_comments = g_tree_new_full(frame_cmp, NULL, NULL, g_free);

  /* insert new packet comment */
  g_tree_replace(cf->frames_user_comments, fd, g_strdup(new_comment));

  expert_update_comment_count(cf->packet_comment_count);

  /* OK, we have unsaved changes. */
  cf->unsaved_changes = TRUE;
  return TRUE;
}

/*
 * What types of comments does this capture file have?
 */
guint32
cf_comment_types(capture_file *cf)
{
  guint32 comment_types = 0;

  if (cf_read_shb_comment(cf) != NULL)
    comment_types |= WTAP_COMMENT_PER_SECTION;
  if (cf->packet_comment_count != 0)
    comment_types |= WTAP_COMMENT_PER_PACKET;
  return comment_types;
}

#ifdef WANT_PACKET_EDITOR
static gint
g_direct_compare_func(gconstpointer a, gconstpointer b, gpointer user_data _U_)
{
  if (a > b)
    return 1;
  else if (a < b)
    return -1;
  else
    return 0;
}

static void
modified_frame_data_free(gpointer data)
{
  modified_frame_data *mfd = (modified_frame_data *)data;

  g_free(mfd->pd);
  g_free(mfd);
}

/*
 * Give a frame new, edited data.
 */
void
cf_set_frame_edited(capture_file *cf, frame_data *fd,
                    struct wtap_pkthdr *phdr, guint8 *pd)
{
  modified_frame_data *mfd = (modified_frame_data *)g_malloc(sizeof(modified_frame_data));

  mfd->phdr = *phdr;
  mfd->pd = pd;

  if (cf->edited_frames == NULL)
    cf->edited_frames = g_tree_new_full(g_direct_compare_func, NULL, NULL,
                                        modified_frame_data_free);
  g_tree_insert(cf->edited_frames, GINT_TO_POINTER(fd->num), mfd);
  fd->file_off = -1;

  /* Mark the file as having unsaved changes */
  cf->unsaved_changes = TRUE;
}
#endif

typedef struct {
  wtap_dumper *pdh;
  const char  *fname;
  int          file_type;
} save_callback_args_t;

/*
 * Save a capture to a file, in a particular format, saving either
 * all packets, all currently-displayed packets, or all marked packets.
 *
 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
 * up a message box for the failure.
 */
static gboolean
save_record(capture_file *cf, frame_data *fdata,
            struct wtap_pkthdr *phdr, const guint8 *pd,
            void *argsp)
{
  save_callback_args_t *args = (save_callback_args_t *)argsp;
  struct wtap_pkthdr    hdr;
  int           err;
  gchar        *err_info;
  gchar        *display_basename;
  const char   *pkt_comment;

  if (fdata->flags.has_user_comment)
    pkt_comment = cf_get_user_packet_comment(cf, fdata);
  else
    pkt_comment = phdr->opt_comment;

  /* init the wtap header for saving */
  /* TODO: reuse phdr */
  /* XXX - these are the only flags that correspond to data that we have
     in the frame_data structure and that matter on a per-packet basis.

     For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
     and "on the wire" lengths, or it doesn't.

     For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
     to its callers.

     For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
     from the packet flags. */
  hdr.rec_type = phdr->rec_type;
  hdr.presence_flags = 0;
  if (fdata->flags.has_ts)
    hdr.presence_flags |= WTAP_HAS_TS;
  if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
    hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
  if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
    hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
  hdr.ts.secs      = fdata->abs_ts.secs;
  hdr.ts.nsecs     = fdata->abs_ts.nsecs;
  hdr.caplen       = phdr->caplen;
  hdr.len          = phdr->len;
  hdr.pkt_encap    = fdata->lnk_t;
  /* pcapng */
  hdr.interface_id = phdr->interface_id;   /* identifier of the interface. */
  /* options */
  hdr.pack_flags   = phdr->pack_flags;
  hdr.opt_comment  = g_strdup(pkt_comment);

  /* pseudo */
  hdr.pseudo_header = phdr->pseudo_header;
#if 0
  hdr.drop_count   =
  hdr.pack_flags   =     /* XXX - 0 for now (any value for "we don't have it"?) */
#endif
  /* and save the packet */
  if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
    if (err < 0) {
      /* Wiretap error. */
      switch (err) {

      case WTAP_ERR_UNWRITABLE_ENCAP:
        /*
         * This is a problem with the particular frame we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        simple_error_message_box(
                      "Frame %u has a network type that can't be saved in a \"%s\" file.",
                      fdata->num, wtap_file_type_subtype_string(args->file_type));
        break;

      case WTAP_ERR_PACKET_TOO_LARGE:
        /*
         * This is a problem with the particular frame we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        simple_error_message_box(
                      "Frame %u is larger than Wireshark supports in a \"%s\" file.",
                      fdata->num, wtap_file_type_subtype_string(args->file_type));
        break;

      case WTAP_ERR_UNWRITABLE_REC_TYPE:
        /*
         * This is a problem with the particular record we're writing and
         * the file type and subtype we're writing; note that, and report
         * the record number and file type/subtype.
         */
        simple_error_message_box(
                      "Record %u has a record type that can't be saved in a \"%s\" file.",
                      fdata->num, wtap_file_type_subtype_string(args->file_type));
        break;

      case WTAP_ERR_UNWRITABLE_REC_DATA:
        /*
         * This is a problem with the particular frame we're writing and
         * the file type and subtype we're writing; note that, and report
         * the frame number and file type/subtype.
         */
        simple_error_message_box(
                      "Record %u has data that can't be saved in a \"%s\" file.\n(%s)",
                      fdata->num, wtap_file_type_subtype_string(args->file_type),
                      err_info != NULL ? err_info : "no information supplied");
        g_free(err_info);
        break;

      default:
        display_basename = g_filename_display_basename(args->fname);
        simple_error_message_box(
                      "An error occurred while writing to the file \"%s\": %s.",
                      display_basename, wtap_strerror(err));
        g_free(display_basename);
        break;
      }
    } else {
      /* OS error. */
      write_failure_alert_box(args->fname, err);
    }
    return FALSE;
  }

  g_free(hdr.opt_comment);
  return TRUE;
}

/*
 * Can this capture file be written out in any format using Wiretap
 * rather than by copying the raw data?
 */
gboolean
cf_can_write_with_wiretap(capture_file *cf)
{
  /* We don't care whether we support the comments in this file or not;
     if we can't, we'll offer the user the option of discarding the
     comments. */
  return wtap_dump_can_write(cf->linktypes, 0);
}

/*
 * Should we let the user do a save?
 *
 * We should if:
 *
 *  the file has unsaved changes, and we can save it in some
 *  format through Wiretap
 *
 * or
 *
 *  the file is a temporary file and has no unsaved changes (so
 *  that "saving" it just means copying it).
 *
 * XXX - we shouldn't allow files to be edited if they can't be saved,
 * so cf->unsaved_changes should be true only if the file can be saved.
 *
 * We don't care whether we support the comments in this file or not;
 * if we can't, we'll offer the user the option of discarding the
 * comments.
 */
gboolean
cf_can_save(capture_file *cf)
{
  if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
    /* Saved changes, and we can write it out with Wiretap. */
    return TRUE;
  }

  if (cf->is_tempfile && !cf->unsaved_changes) {
    /*
     * Temporary file with no unsaved changes, so we can just do a
     * raw binary copy.
     */
    return TRUE;
  }

  /* Nothing to save. */
  return FALSE;
}

/*
 * Should we let the user do a "save as"?
 *
 * That's true if:
 *
 *  we can save it in some format through Wiretap
 *
 * or
 *
 *  the file is a temporary file and has no unsaved changes (so
 *  that "saving" it just means copying it).
 *
 * XXX - we shouldn't allow files to be edited if they can't be saved,
 * so cf->unsaved_changes should be true only if the file can be saved.
 *
 * We don't care whether we support the comments in this file or not;
 * if we can't, we'll offer the user the option of discarding the
 * comments.
 */
gboolean
cf_can_save_as(capture_file *cf)
{
  if (wtap_dump_can_write(cf->linktypes, 0)) {
    /* We can write it out with Wiretap. */
    return TRUE;
  }

  if (cf->is_tempfile && !cf->unsaved_changes) {
    /*
     * Temporary file with no unsaved changes, so we can just do a
     * raw binary copy.
     */
    return TRUE;
  }

  /* Nothing to save. */
  return FALSE;
}

/*
 * Does this file have unsaved data?
 */
gboolean
cf_has_unsaved_data(capture_file *cf)
{
  /*
   * If this is a temporary file, or a file with unsaved changes, it
   * has unsaved data.
   */
  return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
}

/*
 * Quick scan to find packet offsets.
 */
static cf_read_status_t
rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
{
  const struct wtap_pkthdr *phdr;
  gchar               *err_info;
  gchar               *name_ptr;
  gint64               data_offset;
  progdlg_t           *progbar        = NULL;
  gint64               size;
  float                progbar_val;
  GTimeVal             start_time;
  gchar                status_str[100];
  gint64               progbar_nextstep;
  gint64               progbar_quantum;
  guint32              framenum;
  frame_data          *fdata;
  int                  count          = 0;
#ifdef HAVE_LIBPCAP
  int                  displayed_once = 0;
#endif

  /* Close the old handle. */
  wtap_close(cf->wth);

  /* Open the new file. */
  /* XXX: this will go through all open_routines for a matching one. But right
     now rescan_file() is only used when a file is being saved to a different
     format than the original, and the user is not given a choice of which
     reader to use (only which format to save it in), so doing this makes
     sense for now. */
  cf->wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, err, &err_info, TRUE);
  if (cf->wth == NULL) {
    cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
    return CF_READ_ERROR;
  }

  /* We're scanning a file whose contents should be the same as what
     we had before, so we don't discard dissection state etc.. */
  cf->f_datalen = 0;

  /* Set the file name because we need it to set the follow stream filter.
     XXX - is that still true?  We need it for other reasons, though,
     in any case. */
  cf->filename = g_strdup(fname);

  /* Indicate whether it's a permanent or temporary file. */
  cf->is_tempfile = is_tempfile;

  /* No user changes yet. */
  cf->unsaved_changes = FALSE;

  cf->cd_t        = wtap_file_type_subtype(cf->wth);
  cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);

  cf->snap      = wtap_snapshot_length(cf->wth);
  if (cf->snap == 0) {
    /* Snapshot length not known. */
    cf->has_snap = FALSE;
    cf->snap = WTAP_MAX_PACKET_SIZE;
  } else
    cf->has_snap = TRUE;

  name_ptr = g_filename_display_basename(cf->filename);

  cf_callback_invoke(cf_cb_file_rescan_started, cf);

  /* Record whether the file is compressed.
     XXX - do we know this at open time? */
  cf->iscompressed = wtap_iscompressed(cf->wth);

  /* Find the size of the file. */
  size = wtap_file_size(cf->wth, NULL);

  /* Update the progress bar when it gets to this value. */
  progbar_nextstep = 0;
  /* When we reach the value that triggers a progress bar update,
     bump that value by this amount. */
  if (size >= 0) {
    progbar_quantum = size/N_PROGBAR_UPDATES;
    if (progbar_quantum < MIN_QUANTUM)
      progbar_quantum = MIN_QUANTUM;
  }else
    progbar_quantum = 0;

  cf->stop_flag = FALSE;
  g_get_current_time(&start_time);

  framenum = 0;
  phdr = wtap_phdr(cf->wth);
  while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
    framenum++;
    fdata = frame_data_sequence_find(cf->frames, framenum);
    fdata->file_off = data_offset;
    if (size >= 0) {
      count++;
      cf->f_datalen = wtap_read_so_far(cf->wth);

      /* Create the progress bar if necessary.
       * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
       */
      if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
        progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
        progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
                                              TRUE, &cf->stop_flag, &start_time, progbar_val);
      }

      /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
         when we update it, we have to run the GTK+ main loop to get it
         to repaint what's pending, and doing so may involve an "ioctl()"
         to see if there's any pending input from an X server, and doing
         that for every packet can be costly, especially on a big file. */
      if (cf->f_datalen >= progbar_nextstep) {
        if (progbar != NULL) {
          progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
          /* update the packet bar content on the first run or frequently on very large files */
#ifdef HAVE_LIBPCAP
          if (progbar_quantum > 500000 || displayed_once == 0) {
            if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
              displayed_once = 1;
              packets_bar_update();
            }
          }
#endif /* HAVE_LIBPCAP */
          update_progress_dlg(progbar, progbar_val, status_str);
        }
        progbar_nextstep += progbar_quantum;
      }
    }

    if (cf->stop_flag) {
      /* Well, the user decided to abort the rescan.  Sadly, as this
         isn't a reread, recovering is difficult, so we'll just
         close the current capture. */
      break;
    }

    /* Add this packet's link-layer encapsulation type to cf->linktypes, if
       it's not already there.
       XXX - yes, this is O(N), so if every packet had a different
       link-layer encapsulation type, it'd be O(N^2) to read the file, but
       there are probably going to be a small number of encapsulation types
       in a file. */
    cf_add_encapsulation_type(cf, phdr->pkt_encap);
  }

  /* Free the display name */
  g_free(name_ptr);

  /* We're done reading the file; destroy the progress bar if it was created. */
  if (progbar != NULL)
    destroy_progress_dlg(progbar);

  /* We're done reading sequentially through the file. */
  cf->state = FILE_READ_DONE;

  /* Close the sequential I/O side, to free up memory it requires. */
  wtap_sequential_close(cf->wth);

  /* compute the time it took to load the file */
  compute_elapsed(cf, &start_time);

  /* Set the file encapsulation type now; we don't know what it is until
     we've looked at all the packets, as we don't know until then whether
     there's more than one type (and thus whether it's
     WTAP_ENCAP_PER_PACKET). */
  cf->lnk_t = wtap_file_encap(cf->wth);

  cf_callback_invoke(cf_cb_file_rescan_finished, cf);

  if (cf->stop_flag) {
    /* Our caller will give up at this point. */
    return CF_READ_ABORTED;
  }

  if (*err != 0) {
    /* Put up a message box noting that the read failed somewhere along
       the line.  Don't throw out the stuff we managed to read, though,
       if any. */
    switch (*err) {

    case WTAP_ERR_UNSUPPORTED:
      simple_error_message_box(
                 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_SHORT_READ:
      simple_error_message_box(
                 "The capture file appears to have been cut short"
                 " in the middle of a packet.");
      break;

    case WTAP_ERR_BAD_FILE:
      simple_error_message_box(
                 "The capture file appears to be damaged or corrupt.\n(%s)",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_DECOMPRESS:
      simple_error_message_box(
                 "The compressed capture file appears to be damaged or corrupt.\n"
                 "(%s)",
                 err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    default:
      simple_error_message_box(
                 "An error occurred while reading the"
                 " capture file: %s.", wtap_strerror(*err));
      break;
    }
    return CF_READ_ERROR;
  } else
    return CF_READ_OK;
}

cf_write_status_t
cf_save_records(capture_file *cf, const char *fname, guint save_format,
                gboolean compressed, gboolean discard_comments,
                gboolean dont_reopen)
{
  gchar           *err_info;
  gchar           *fname_new = NULL;
  wtap_dumper     *pdh;
  frame_data      *fdata;
  addrinfo_lists_t *addr_lists;
  guint            framenum;
  int              err;
#ifdef _WIN32
  gchar           *display_basename;
#endif
  enum {
     SAVE_WITH_MOVE,
     SAVE_WITH_COPY,
     SAVE_WITH_WTAP
  }                    how_to_save;
  save_callback_args_t callback_args;

  cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);

  addr_lists = get_addrinfo_list();

  if (save_format == cf->cd_t && compressed == cf->iscompressed
      && !discard_comments && !cf->unsaved_changes
      && !(addr_lists && wtap_dump_has_name_resolution(save_format))) {
    /* We're saving in the format it's already in, and we're
       not discarding comments, and there are no changes we have
       in memory that aren't saved to the file, and we have no name
       resolution blocks to write, so we can just move or copy the raw data. */

    if (cf->is_tempfile) {
      /* The file being saved is a temporary file from a live
         capture, so it doesn't need to stay around under that name;
         first, try renaming the capture buffer file to the new name.
         This acts as a "safe save", in that, if the file already
         exists, the existing file will be removed only if the rename
         succeeds.

         Sadly, on Windows, as we have the current capture file
         open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
         (to cause the rename to remove an existing target), as
         done by ws_stdio_rename() (ws_rename() is #defined to
         be ws_stdio_rename() on Windows) will fail.

         According to the MSDN documentation for CreateFile(), if,
         when we open a capture file, we were to directly do a CreateFile(),
         opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
         convert it to a file descriptor with _open_osfhandle(),
         that would allow the file to be renamed out from under us.

         However, that doesn't work in practice.  Perhaps the problem
         is that the process doing the rename is the process that
         has the file open. */
#ifndef _WIN32
      if (ws_rename(cf->filename, fname) == 0) {
        /* That succeeded - there's no need to copy the source file. */
        how_to_save = SAVE_WITH_MOVE;
      } else {
        if (errno == EXDEV) {
          /* They're on different file systems, so we have to copy the
             file. */
          how_to_save = SAVE_WITH_COPY;
        } else {
          /* The rename failed, but not because they're on different
             file systems - put up an error message.  (Or should we
             just punt and try to copy?  The only reason why I'd
             expect the rename to fail and the copy to succeed would
             be if we didn't have permission to remove the file from
             the temporary directory, and that might be fixable - but
             is it worth requiring the user to go off and fix it?) */
          cf_rename_failure_alert_box(fname, errno);
          goto fail;
        }
      }
#else
      how_to_save = SAVE_WITH_COPY;
#endif
    } else {
      /* It's a permanent file, so we should copy it, and not remove the
         original. */
      how_to_save = SAVE_WITH_COPY;
    }

    if (how_to_save == SAVE_WITH_COPY) {
      /* Copy the file, if we haven't moved it.  If we're overwriting
         an existing file, we do it with a "safe save", by writing
         to a new file and, if the write succeeds, renaming the
         new file on top of the old file. */
      if (file_exists(fname)) {
        fname_new = g_strdup_printf("%s~", fname);
        if (!copy_file_binary_mode(cf->filename, fname_new))
          goto fail;
      } else {
        if (!copy_file_binary_mode(cf->filename, fname))
          goto fail;
      }
    }
  } else {
    /* Either we're saving in a different format or we're saving changes,
       such as added, modified, or removed comments, that haven't yet
       been written to the underlying file; we can't do that by copying
       or moving the capture file, we have to do it by writing the packets
       out in Wiretap. */

    wtapng_section_t *shb_hdr = NULL;
    wtapng_iface_descriptions_t *idb_inf = NULL;
    int encap;

    shb_hdr = wtap_file_get_shb_info(cf->wth);
    idb_inf = wtap_file_get_idb_info(cf->wth);

    /* Determine what file encapsulation type we should use. */
    encap = wtap_dump_file_encap_type(cf->linktypes);

    if (file_exists(fname)) {
      /* We're overwriting an existing file; write out to a new file,
         and, if that succeeds, rename the new file on top of the
         old file.  That makes this a "safe save", so that we don't
         lose the old file if we have a problem writing out the new
         file.  (If the existing file is the current capture file,
         we *HAVE* to do that, otherwise we're overwriting the file
         from which we're reading the packets that we're writing!) */
      fname_new = g_strdup_printf("%s~", fname);
      pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
                              compressed, shb_hdr, idb_inf, &err);
    } else {
      pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
                              compressed, shb_hdr, idb_inf, &err);
    }
    g_free(idb_inf);
    idb_inf = NULL;

    if (pdh == NULL) {
      cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
      goto fail;
    }

    /* Add address resolution */
    wtap_dump_set_addrinfo_list(pdh, addr_lists);

    /* Iterate through the list of packets, processing all the packets. */
    callback_args.pdh = pdh;
    callback_args.fname = fname;
    callback_args.file_type = save_format;
    switch (process_specified_records(cf, NULL, "Saving", "packets",
                                      TRUE, save_record, &callback_args)) {

    case PSP_FINISHED:
      /* Completed successfully. */
      break;

    case PSP_STOPPED:
      /* The user decided to abort the saving.
         If we're writing to a temporary file, remove it.
         XXX - should we do so even if we're not writing to a
         temporary file? */
      wtap_dump_close(pdh, &err);
      if (fname_new != NULL)
        ws_unlink(fname_new);
      cf_callback_invoke(cf_cb_file_save_stopped, NULL);
      return CF_WRITE_ABORTED;

    case PSP_FAILED:
      /* Error while saving.
         If we're writing to a temporary file, remove it. */
      if (fname_new != NULL)
        ws_unlink(fname_new);
      wtap_dump_close(pdh, &err);
      goto fail;
    }

    if (!wtap_dump_close(pdh, &err)) {
      cf_close_failure_alert_box(fname, err);
      goto fail;
    }

    how_to_save = SAVE_WITH_WTAP;
  }

  if (fname_new != NULL) {
    /* We wrote out to fname_new, and should rename it on top of
       fname.  fname_new is now closed, so that should be possible even
       on Windows.  However, on Windows, we first need to close whatever
       file descriptors we have open for fname. */
#ifdef _WIN32
    wtap_fdclose(cf->wth);
#endif
    /* Now do the rename. */
    if (ws_rename(fname_new, fname) == -1) {
      /* Well, the rename failed. */
      cf_rename_failure_alert_box(fname, errno);
#ifdef _WIN32
      /* Attempt to reopen the random file descriptor using the
         current file's filename.  (At this point, the sequential
         file descriptor is closed.) */
      if (!wtap_fdreopen(cf->wth, cf->filename, &err)) {
        /* Oh, well, we're screwed. */
        display_basename = g_filename_display_basename(cf->filename);
        simple_error_message_box(
                      file_open_error_message(err, FALSE), display_basename);
        g_free(display_basename);
      }
#endif
      goto fail;
    }
  }

  cf_callback_invoke(cf_cb_file_save_finished, NULL);
  cf->unsaved_changes = FALSE;

  if (!dont_reopen) {
    switch (how_to_save) {

    case SAVE_WITH_MOVE:
      /* We just moved the file, so the wtap structure refers to the
         new file, and all the information other than the filename
         and the "is temporary" status applies to the new file; just
         update that. */
      g_free(cf->filename);
      cf->filename = g_strdup(fname);
      cf->is_tempfile = FALSE;
      cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
      break;

    case SAVE_WITH_COPY:
      /* We just copied the file, s all the information other than
         the wtap structure, the filename, and the "is temporary"
         status applies to the new file; just update that. */
      wtap_close(cf->wth);
      /* Although we're just "copying" and then opening the copy, it will
         try all open_routine readers to open the copy, so we need to
         reset the cfile's open_type. */
      cf->open_type = WTAP_TYPE_AUTO;
      cf->wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
      if (cf->wth == NULL) {
        cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
        cf_close(cf);
      } else {
        g_free(cf->filename);
        cf->filename = g_strdup(fname);
        cf->is_tempfile = FALSE;
      }
      cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
      break;

    case SAVE_WITH_WTAP:
      /* Open and read the file we saved to.

         XXX - this is somewhat of a waste; we already have the
         packets, all this gets us is updated file type information
         (which we could just stuff into "cf"), and having the new
         file be the one we have opened and from which we're reading
         the data, and it means we have to spend time opening and
         reading the file, which could be a significant amount of
         time if the file is large.

         If the capture-file-writing code were to return the
         seek offset of each packet it writes, we could save that
         in the frame_data structure for the frame, and just open
         the file without reading it again...

         ...as long as, for gzipped files, the process of writing
         out the file *also* generates the information needed to
         support fast random access to the compressed file. */
      /* rescan_file will cause us to try all open_routines, so
         reset cfile's open_type */
      cf->open_type = WTAP_TYPE_AUTO;
      if (rescan_file(cf, fname, FALSE, &err) != CF_READ_OK) {
        /* The rescan failed; just close the file.  Either
           a dialog was popped up for the failure, so the
           user knows what happened, or they stopped the
           rescan, in which case they know what happened. */
        cf_close(cf);
      }
      break;
    }

    /* If we were told to discard the comments, do so. */
    if (discard_comments) {
      /* Remove SHB comment, if any. */
      wtap_write_shb_comment(cf->wth, NULL);

      /* remove all user comments */
      for (framenum = 1; framenum <= cf->count; framenum++) {
        fdata = frame_data_sequence_find(cf->frames, framenum);

        fdata->flags.has_phdr_comment = FALSE;
        fdata->flags.has_user_comment = FALSE;
      }

      if (cf->frames_user_comments) {
        g_tree_destroy(cf->frames_user_comments);
        cf->frames_user_comments = NULL;
      }

      cf->packet_comment_count = 0;
    }
  }
  return CF_WRITE_OK;

fail:
  if (fname_new != NULL) {
    /* We were trying to write to a temporary file; get rid of it if it
       exists.  (We don't care whether this fails, as, if it fails,
       there's not much we can do about it.  I guess if it failed for
       a reason other than "it doesn't exist", we could report an
       error, so the user knows there's a junk file that they might
       want to clean up.) */
    ws_unlink(fname_new);
    g_free(fname_new);
  }
  cf_callback_invoke(cf_cb_file_save_failed, NULL);
  return CF_WRITE_ERROR;
}

cf_write_status_t
cf_export_specified_packets(capture_file *cf, const char *fname,
                            packet_range_t *range, guint save_format,
                            gboolean compressed)
{
  gchar                       *fname_new = NULL;
  int                          err;
  wtap_dumper                 *pdh;
  save_callback_args_t         callback_args;
  wtapng_section_t            *shb_hdr;
  wtapng_iface_descriptions_t *idb_inf;
  int                          encap;

  cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);

  packet_range_process_init(range);

  /* We're writing out specified packets from the specified capture
     file to another file.  Even if all captured packets are to be
     written, don't special-case the operation - read each packet
     and then write it out if it's one of the specified ones. */

  shb_hdr = wtap_file_get_shb_info(cf->wth);
  idb_inf = wtap_file_get_idb_info(cf->wth);

  /* Determine what file encapsulation type we should use. */
  encap = wtap_dump_file_encap_type(cf->linktypes);

  if (file_exists(fname)) {
    /* We're overwriting an existing file; write out to a new file,
       and, if that succeeds, rename the new file on top of the
       old file.  That makes this a "safe save", so that we don't
       lose the old file if we have a problem writing out the new
       file.  (If the existing file is the current capture file,
       we *HAVE* to do that, otherwise we're overwriting the file
       from which we're reading the packets that we're writing!) */
    fname_new = g_strdup_printf("%s~", fname);
    pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
                            compressed, shb_hdr, idb_inf, &err);
  } else {
    pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
                            compressed, shb_hdr, idb_inf, &err);
  }
  g_free(idb_inf);
  idb_inf = NULL;

  if (pdh == NULL) {
    cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
    goto fail;
  }

  /* Add address resolution */
  wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());

  /* Iterate through the list of packets, processing the packets we were
     told to process.

     XXX - we've already called "packet_range_process_init(range)", but
     "process_specified_records()" will do it again.  Fortunately,
     that's harmless in this case, as we haven't done anything to
     "range" since we initialized it. */
  callback_args.pdh = pdh;
  callback_args.fname = fname;
  callback_args.file_type = save_format;
  switch (process_specified_records(cf, range, "Writing", "specified records",
                                    TRUE, save_record, &callback_args)) {

  case PSP_FINISHED:
    /* Completed successfully. */
    break;

  case PSP_STOPPED:
      /* The user decided to abort the saving.
         If we're writing to a temporary file, remove it.
         XXX - should we do so even if we're not writing to a
         temporary file? */
      wtap_dump_close(pdh, &err);
      if (fname_new != NULL)
        ws_unlink(fname_new);
      cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
      return CF_WRITE_ABORTED;
    break;

  case PSP_FAILED:
    /* Error while saving.
       If we're writing to a temporary file, remove it. */
    if (fname_new != NULL)
      ws_unlink(fname_new);
    wtap_dump_close(pdh, &err);
    goto fail;
  }

  if (!wtap_dump_close(pdh, &err)) {
    cf_close_failure_alert_box(fname, err);
    goto fail;
  }

  if (fname_new != NULL) {
    /* We wrote out to fname_new, and should rename it on top of
       fname; fname is now closed, so that should be possible even
       on Windows.  Do the rename. */
    if (ws_rename(fname_new, fname) == -1) {
      /* Well, the rename failed. */
      cf_rename_failure_alert_box(fname, errno);
      goto fail;
    }
  }

  cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
  return CF_WRITE_OK;

fail:
  if (fname_new != NULL) {
    /* We were trying to write to a temporary file; get rid of it if it
       exists.  (We don't care whether this fails, as, if it fails,
       there's not much we can do about it.  I guess if it failed for
       a reason other than "it doesn't exist", we could report an
       error, so the user knows there's a junk file that they might
       want to clean up.) */
    ws_unlink(fname_new);
    g_free(fname_new);
  }
  cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
  return CF_WRITE_ERROR;
}

static void
cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
                          gboolean for_writing, int file_type)
{
  gchar *display_basename;

  if (err < 0) {
    /* Wiretap error. */
    display_basename = g_filename_display_basename(filename);
    switch (err) {

    case WTAP_ERR_NOT_REGULAR_FILE:
      simple_error_message_box(
            "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
            display_basename);
      break;

    case WTAP_ERR_RANDOM_OPEN_PIPE:
      /* Seen only when opening a capture file for reading. */
      simple_error_message_box(
            "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
            "To capture from a pipe or FIFO use wireshark -i -",
            display_basename);
      break;

    case WTAP_ERR_FILE_UNKNOWN_FORMAT:
      /* Seen only when opening a capture file for reading. */
      simple_error_message_box(
            "The file \"%s\" isn't a capture file in a format Wireshark understands.",
            display_basename);
      break;

    case WTAP_ERR_UNSUPPORTED:
      /* Seen only when opening a capture file for reading. */
      simple_error_message_box(
            "The file \"%s\" contains record data that Wireshark doesn't support.\n",
            "(%s)",
            display_basename,
            err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_CANT_WRITE_TO_PIPE:
      /* Seen only when opening a capture file for writing. */
      simple_error_message_box(
            "The file \"%s\" is a pipe, and %s capture files can't be "
            "written to a pipe.",
            display_basename, wtap_file_type_subtype_string(file_type));
      break;

    case WTAP_ERR_UNWRITABLE_FILE_TYPE:
      /* Seen only when opening a capture file for writing. */
      simple_error_message_box(
            "Wireshark doesn't support writing capture files in that format.");
      break;

    case WTAP_ERR_UNWRITABLE_ENCAP:
      /* Seen only when opening a capture file for writing. */
      simple_error_message_box("Wireshark can't save this capture in that format.");
      break;

    case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
      if (for_writing) {
        simple_error_message_box(
              "Wireshark can't save this capture in that format.");
      } else {
        simple_error_message_box(
              "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
              display_basename);
      }
      break;

    case WTAP_ERR_BAD_FILE:
      /* Seen only when opening a capture file for reading. */
      simple_error_message_box(
            "The file \"%s\" appears to be damaged or corrupt.\n"
            "(%s)",
            display_basename,
            err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    case WTAP_ERR_CANT_OPEN:
      if (for_writing) {
        simple_error_message_box(
              "The file \"%s\" could not be created for some unknown reason.",
              display_basename);
      } else {
        simple_error_message_box(
              "The file \"%s\" could not be opened for some unknown reason.",
              display_basename);
      }
      break;

    case WTAP_ERR_SHORT_READ:
      simple_error_message_box(
            "The file \"%s\" appears to have been cut short"
            " in the middle of a packet or other data.",
            display_basename);
      break;

    case WTAP_ERR_SHORT_WRITE:
      simple_error_message_box(
            "A full header couldn't be written to the file \"%s\".",
            display_basename);
      break;

    case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
      simple_error_message_box(
            "This file type cannot be written as a compressed file.");
      break;

    case WTAP_ERR_DECOMPRESS:
      simple_error_message_box(
            "The compressed file \"%s\" appears to be damaged or corrupt.\n"
            "(%s)", display_basename,
            err_info != NULL ? err_info : "no information supplied");
      g_free(err_info);
      break;

    default:
      simple_error_message_box(
            "The file \"%s\" could not be %s: %s.",
            display_basename,
            for_writing ? "created" : "opened",
            wtap_strerror(err));
      break;
    }
    g_free(display_basename);
  } else {
    /* OS error. */
    open_failure_alert_box(filename, err, for_writing);
  }
}

/*
 * XXX - whether we mention the source pathname, the target pathname,
 * or both depends on the error and on what we find if we look for
 * one or both of them.
 */
static void
cf_rename_failure_alert_box(const char *filename, int err)
{
  gchar *display_basename;

  display_basename = g_filename_display_basename(filename);
  switch (err) {

  case ENOENT:
    /* XXX - should check whether the source exists and, if not,
       report it as the problem and, if so, report the destination
       as the problem. */
    simple_error_message_box("The path to the file \"%s\" doesn't exist.",
                             display_basename);
    break;

  case EACCES:
    /* XXX - if we're doing a rename after a safe save, we should
       probably say something else. */
    simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
                             display_basename);
    break;

  default:
    /* XXX - this should probably mention both the source and destination
       pathnames. */
    simple_error_message_box("The file \"%s\" could not be moved: %s.",
                             display_basename, wtap_strerror(err));
    break;
  }
  g_free(display_basename);
}

/* Check for write errors - if the file is being written to an NFS server,
   a write error may not show up until the file is closed, as NFS clients
   might not send writes to the server until the "write()" call finishes,
   so that the write may fail on the server but the "write()" may succeed. */
static void
cf_close_failure_alert_box(const char *filename, int err)
{
  gchar *display_basename;

  if (err < 0) {
    /* Wiretap error. */
    display_basename = g_filename_display_basename(filename);
    switch (err) {

    case WTAP_ERR_CANT_CLOSE:
      simple_error_message_box(
            "The file \"%s\" couldn't be closed for some unknown reason.",
            display_basename);
      break;

    case WTAP_ERR_SHORT_WRITE:
      simple_error_message_box(
            "Not all the packets could be written to the file \"%s\".",
                    display_basename);
      break;

    default:
      simple_error_message_box(
            "An error occurred while closing the file \"%s\": %s.",
            display_basename, wtap_strerror(err));
      break;
    }
    g_free(display_basename);
  } else {
    /* OS error.
       We assume that a close error from the OS is really a write error. */
    write_failure_alert_box(filename, err);
  }
}

/* Reload the current capture file. */
void
cf_reload(capture_file *cf) {
  gchar    *filename;
  gboolean  is_tempfile;
  int       err;

  /* If the file could be opened, "cf_open()" calls "cf_close()"
     to get rid of state for the old capture file before filling in state
     for the new capture file.  "cf_close()" will remove the file if
     it's a temporary file; we don't want that to happen (for one thing,
     it'd prevent subsequent reopens from working).  Remember whether it's
     a temporary file, mark it as not being a temporary file, and then
     reopen it as the type of file it was.

     Also, "cf_close()" will free "cf->filename", so we must make
     a copy of it first. */
  filename = g_strdup(cf->filename);
  is_tempfile = cf->is_tempfile;
  cf->is_tempfile = FALSE;
  if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
    switch (cf_read(cf, TRUE)) {

    case CF_READ_OK:
    case CF_READ_ERROR:
      /* Just because we got an error, that doesn't mean we were unable
         to read any of the file; we handle what we could get from the
         file. */
      break;

    case CF_READ_ABORTED:
      /* The user bailed out of re-reading the capture file; the
         capture file has been closed - just free the capture file name
         string and return (without changing the last containing
         directory). */
      g_free(filename);
      return;
    }
  } else {
    /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
       Instead, the file was left open, so we should restore "cf->is_tempfile"
       ourselves.

       XXX - change the menu?  Presumably "cf_open()" will do that;
       make sure it does! */
    cf->is_tempfile = is_tempfile;
  }
  /* "cf_open()" made a copy of the file name we handed it, so
     we should free up our copy. */
  g_free(filename);
}

/*
 * Editor modelines
 *
 * Local Variables:
 * c-basic-offset: 2
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * ex: set shiftwidth=2 tabstop=8 expandtab:
 * :indentSize=2:tabSize=8:noTabs=true:
 */