summaryrefslogtreecommitdiff
path: root/src/qcommon/files.cpp
blob: 2eb0546f9c9fdab9395735c53fd77fbab8e9b327 (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
/*
   Copyright (C) 2016 Victor Roemer (wtfbbqhax), <victor@badsec.org>.
   Copyright (C) 2000-2013 Darklegion Development
   Copyright (C) 1999-2005 Id Software, Inc.
   Copyright (C) 2015-2019 GrangerHub

   This file is part of Tremulous.

   Tremulous is free software; you can redistribute it
   and/or modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 3 of the License,
   or (at your option) any later version.

   Tremulous 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 Tremulous; if not, see <https://www.gnu.org/licenses/>
   
*/

#include "files.h"

#ifdef _WIN32
#include <io.h>
#include <windows.h>
#endif

#include <cctype>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>

#include "cmd.h"
#include "cvar.h"
#include "md4.h"
#include "q_platform.h"
#include "q_shared.h"
#include "qcommon.h"
#include "unzip.h"
#include "vm.h"

#ifndef DEDICATED
#include "client/cl_rest.h"
#endif
#include "sys/sys_shared.h"

using namespace std;

#define MAX_ZPATH 256
#define MAX_SEARCH_PATHS 4096
#define MAX_FILEHASH_SIZE 1024

static bool FS_IsDemoExt(const char *filename);
static bool FS_IsExt(const char *filename, const char *ext, int namelen);

struct fileInPack_t {
    char* name;
    unsigned long pos;  // file info position in zip
    unsigned long len;  // uncompressed file size
    fileInPack_t* next;
};

struct pack_t {
    char pakPathname[MAX_OSPATH];  // /tremulous/baseq3
    char pakFilename[MAX_OSPATH];  // /tremulous/base/pak0.pk3
    char pakBasename[MAX_OSPATH];  // pak0
    char pakGamename[MAX_OSPATH];  // base
    unzFile handle;  // handle to zip file
    int checksum;  // regular checksum
    int pure_checksum;  // checksum for pure
    int numfiles;  // number of files in pk3
    int referenced;  // referenced file flags
    int hashSize;  // hash table size (power of 2)
    fileInPack_t **hashTable;  // hash table
    fileInPack_t *buildBuffer;  // buffer with the filenames etc.
    // some multiprotocol stuff
    bool onlyPrimary;
    bool onlyAlternate;
    pack_t *primaryVersion;

    // member functions
    inline fileInPack_t* find(string filename);
    inline bool is_pure();
};

struct directory_t {
    char path[MAX_OSPATH];
    char fullpath[MAX_OSPATH];  // /tremulous/base
    char gamedir[MAX_OSPATH];  // base
};

struct searchpath_t {
    pack_t *pack;  // only one of pack / dir will be non nullptr
    directory_t *dir;
    searchpath_t *next;
};

static char fs_gamedir[MAX_OSPATH];  // this will be a single file name with no separators
static cvar_t *fs_debug;
static cvar_t *fs_homepath;

static cvar_t *fs_basepath;
static cvar_t *fs_basegame;
#ifdef __APPLE__
static cvar_t *fs_apppath;  // Also search the .app bundle for .pk3 files
#endif
static cvar_t *fs_gamedirvar;

static searchpath_t *fs_searchpaths;
static int fs_readCount;  // total bytes read
static int fs_loadCount;  // total files read
static int fs_loadStack;  // total files in memory
static int fs_packFiles = 0;  // total number of files in packs

static int fs_checksumFeed;

union qfile_gut {
    FILE *o;
    unzFile z;
};

struct qfile_ut {
    qfile_gut file;
    bool unique;
};

struct fileHandleData_t {
    qfile_ut handleFiles;
    bool handleSync;
    int fileSize;
    int zipFilePos;
    int zipFileLen;
    bool zipFile;
    char name[MAX_ZPATH];

    void close();
};

static fileHandleData_t fsh[MAX_FILE_HANDLES];

// TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
// wether we did a reorder on the current search path when joining the server

static bool fs_reordered;

// never load anything from pk3 files that are not present at the server when pure

static int fs_numServerPaks = 0;
static int fs_serverPaks[MAX_SEARCH_PATHS];  // checksums
static char *fs_serverPakNames[MAX_SEARCH_PATHS];  // pk3 names

// only used for autodownload, to make sure the client has at least
// all the pk3 files that are referenced at the server side

static int fs_numServerReferencedPaks;
static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];  // checksums
static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];  // pk3 names

// last valid game folder used
char lastValidBase[MAX_OSPATH];
char lastValidGame[MAX_OSPATH];

#ifdef FS_MISSING
FILE *missingFiles = nullptr;
#endif

/*
==============
FS_Initialized
==============
*/

bool FS_Initialized(void) { return fs_searchpaths ? true : false; }

/*
=================
pack_t::is_pure()

FIXME: also use hashed file names
=================
*/
inline bool pack_t::is_pure()
{
    if (fs_numServerPaks)
    {
        for (int i = 0; i < fs_numServerPaks; i++)
            if (checksum == fs_serverPaks[i])
                return true;

        return false;
    }
    return true;
}

/*
=================
FS_LoadStack
return load stack
=================
*/
int FS_LoadStack(void) { return fs_loadStack; }

inline fileInPack_t* pack_t::find(string filename)
{
    long hash = 0;
    auto fn = filename.c_str();
    for (long i = 0; fn[i]; i++)
    {
        long c = tolower(fn[i]);
        if (c == '.')
            break; // FIXME probably a bad idea

        if (c == '\\')
            c = '/';
        hash += c * (i + 119);
    }
    hash = (hash ^ (hash >> 10) ^ (hash >> 20));
    hash &= (hashSize - 1);

    for (auto file = hashTable[hash]; file; file = file->next)
    {
        if (FS_FilenameCompare(file->name, fn) == false)
            return file;
    }
    return nullptr;
}
/*
================
return a hash value for the filename
================
*/
static long FS_HashFileName(const char *fname, int hashSize)
{
    int i;
    long hash;
    char letter;

    hash = 0;
    i = 0;
    while (fname[i] != '\0')
    {
        letter = tolower(fname[i]);
        if (letter == '.') break;  // don't include extension
        if (letter == '\\') letter = '/';  // damn path names
        if (letter == PATH_SEP) letter = '/';  // damn path names
        hash += (long)(letter) * (i + 119);
        i++;
    }
    hash = (hash ^ (hash >> 10) ^ (hash >> 20));
    hash &= (hashSize - 1);
    return hash;
}

static fileHandle_t FS_HandleForFile(void)
{
    for (int i = 1; i < MAX_FILE_HANDLES; i++)
    {
        if (fsh[i].handleFiles.file.o == nullptr)
        {
            return i;
        }
    }
    Com_Error(ERR_DROP, "FS_HandleForFile: none free");
    return 0;
}

static FILE *FS_FileForHandle(fileHandle_t f)
{
    if (f < 1 || f >= MAX_FILE_HANDLES)
    {
        Com_Error(ERR_DROP, "FS_FileForHandle: out of range");
    }

    if (fsh[f].zipFile == true)
    {
        Com_Error(ERR_DROP, "FS_FileForHandle: can't get FILE on zip file");
    }

    if (!fsh[f].handleFiles.file.o)
    {
        Com_Error(ERR_DROP, "FS_FileForHandle: nullptr");
    }

    return fsh[f].handleFiles.file.o;
}

void FS_ForceFlush(fileHandle_t f)
{
    FILE *file = FS_FileForHandle(f);
    setvbuf(file, nullptr, _IONBF, 0);
}

/*
================
FS_fplength
================
*/

long FS_fplength(FILE *h)
{
    long pos = ftell(h);
    fseek(h, 0, SEEK_END);

    long end = ftell(h);
    fseek(h, pos, SEEK_SET);

    return end;
}

/*
================
FS_filelength

If this is called on a non-unique FILE (from a pak file),
it will return the size of the pak file, not the expected
size of the file.
================
*/
long FS_filelength(fileHandle_t f)
{
    FILE *h = FS_FileForHandle(f);
    if (h == nullptr) return -1;

    return FS_fplength(h);
}

/*
====================
FS_ReplaceSeparators

Fix things up differently for win/unix/mac
====================
*/
void FS_ReplaceSeparators(char *path)
{
    bool lastCharWasSep = false;

    for (char *s = path; *s; s++)
    {
        if (*s == '/' || *s == '\\')
        {
            if (!lastCharWasSep)
            {
                *s = PATH_SEP;
                lastCharWasSep = true;
            }
            else
            {
                memmove(s, s + 1, strlen(s));
            }
        }
        else
        {
            lastCharWasSep = false;
        }
    }
}

/*
===================
FS_BuildOSPath

Qpath may have either forward or backwards slashes
===================
*/
char *FS_BuildOSPath(const char *base, const char *game, const char *qpath)
{
    char temp[MAX_OSPATH];
    // "FIXME FS_BuildOSPath() returns static buffer with function scope"

    // This code will alternate between 2 different buffers-
    // XXX 3 or more calls to FS_BuildOSPath in a row are not safe.
    static char ospath[2][MAX_OSPATH];
    static bool toggle;

    toggle = !toggle;  // flip-flop to allow two returns without clash

    if (!game || !game[0])
    {
        game = fs_gamedir;
    }

    Com_sprintf(temp, sizeof(temp), "/%s/%s", game, qpath);
    FS_ReplaceSeparators(temp);
    Com_sprintf(ospath[toggle], sizeof(ospath[0]), "%s%s", base, temp);

    Com_DPrintf(S_COLOR_GREEN "%s: returning " S_COLOR_RED "%s\n",
            __FUNCTION__, ospath[toggle]);

    return ospath[toggle];
}

/*
============
FS_OpenWithDefault

Wrapper for Sys_OpenWithDefault()
============
*/
static bool FS_OpenWithDefault( const char *path )
{
    if( Sys_OpenWithDefault( path ) )
    {
        // minimize the client's window
        Cmd_ExecuteString( "minimize" );
        return true;
    }

    return false;
}

/*
============
FS_BrowseHomepath

Opens the homepath in the default file manager
============
*/
bool FS_BrowseHomepath( void )
{
    const char *homePath = Sys_DefaultHomePath( );

    if (!homePath || !homePath[0])
    {
        homePath = fs_basepath->string;
    }

    if( FS_OpenWithDefault( homePath ) )
        return true;

    Com_Printf( S_COLOR_RED "FS_BrowseHomepath: failed to open the homepath with the default file manager.\n" S_COLOR_WHITE );
    return false;
}

/*
============
FS_OpenBaseGamePath

Opens the given path for the
base game in the default file manager
============
*/
bool FS_OpenBaseGamePath( const char *baseGamePath )
{
    const char *homePath = Sys_DefaultHomePath( );
    const char *path;

    if (!homePath || !homePath[0])
    {
        homePath = fs_basepath->string;
    }

    path = FS_BuildOSPath( homePath, fs_basegame->string, baseGamePath);

    if( FS_OpenWithDefault( path ) )
        return true;

    Com_Printf( S_COLOR_RED "FS_BrowseHomepath: failed to open the homepath with the default file manager.\n" S_COLOR_WHITE );
    return false;
}

/*
============
FS_CreatePath

Creates any directories needed to store the given filename
============
*/
bool FS_CreatePath(const char *OSPath)
{
    // make absolutely sure that it can't back up the path
    // FIXME: is c: allowed???
    if (strstr(OSPath, "..") || strstr(OSPath, "::"))
    {
        Com_Printf("WARNING: refusing to create relative path \"%s\"\n", OSPath);
        return true;
    }

    char path[MAX_OSPATH];
    Q_strncpyz(path, OSPath, sizeof(path));
    FS_ReplaceSeparators(path);

    // Skip creation of the root directory as it will always be there
    char *ofs = strchr(path, PATH_SEP);
    if (ofs != nullptr)
    {
        ofs++;
    }

    for (; ofs != nullptr && *ofs; ofs++)
    {
        if (*ofs == PATH_SEP)
        {
            // create the directory
            *ofs = 0;
            if (!Sys_Mkdir(path))
            {
                Com_Error(ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"", path);
            }
            *ofs = PATH_SEP;
        }
    }

    return false;
}

/*
=================
FS_CheckFilenameIsMutable

ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
=================
 */
static void FS_CheckFilenameIsMutable(const char *filename, const char *function)
{
    // Check if the filename ends with the library, QVM, or pk3 extension
    if (Sys_DllExtension(filename) || COM_CompareExtension(filename, ".qvm") ||
        COM_CompareExtension(filename, ".lua") || COM_CompareExtension(filename, ".pk3"))
    {
        Com_Error(ERR_FATAL, "%s: Not allowed to manipulate '%s' due to %s extension",
                function, filename, COM_GetExtension(filename));
    }
}

/*
===========
FS_Remove

===========
*/
void FS_Remove(const char *osPath)
{
    FS_CheckFilenameIsMutable(osPath, __FUNCTION__);
// RB begin
#if defined(_WIN32)
    ::DeleteFile(osPath);
#else
    remove(osPath);
#endif
}

/*
===========
FS_HomeRemove

===========
*/
void FS_HomeRemove(const char *homePath)
{
    FS_CheckFilenameIsMutable(homePath, __FUNCTION__);
    FS_Remove(FS_BuildOSPath(fs_homepath->string, fs_gamedir, homePath));
}

#if 0
bool FS_RemoveDir(const char* relativePath)
{
    bool success = true;
    success = Sys_Rmdir(FS_BuildOSPath(fs_homepath->string, fs_gamedir, relativePath));
    return success;
}
#endif

/*
================
FS_FileInPathExists

Tests if path and file exists
================
*/
bool FS_FileInPathExists(const char *testpath)
{
    FILE *filep;

    filep = Sys_FOpen(testpath, "rb");

    if (filep)
    {
        fclose(filep);
        return true;
    }

    return false;
}

/*
================
FS_FileExists

Tests if the file exists in the current gamedir, this DOES NOT
search the paths.  This is to determine if opening a file to write
(which always goes into the current gamedir) will cause any overwrites.
NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
================
*/
bool FS_FileExists(const char *file)
{
    return FS_FileInPathExists(FS_BuildOSPath(fs_homepath->string, fs_gamedir, file));
}

/*
================
FS_SV_FileExists

Tests if the file exists
================
*/
bool FS_SV_FileExists(const char *file)
{
    char *testpath = FS_BuildOSPath(fs_homepath->string, file, "");
    testpath[strlen(testpath) - 1] = '\0';

    return FS_FileInPathExists(testpath);
}

/*
===========
FS_SV_FOpenFileWrite

===========
*/
fileHandle_t FS_SV_FOpenFileWrite(const char *filename)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    char *ospath = FS_BuildOSPath(fs_homepath->string, filename, "");
    ospath[strlen(ospath) - 1] = '\0';

    fileHandle_t f = FS_HandleForFile();
    fsh[f].zipFile = false;

    Com_DPrintf("FS_SV_FOpenFileWrite: %s\n", ospath);

    FS_CheckFilenameIsMutable(ospath, __FUNCTION__);

    if (FS_CreatePath(ospath))
    {
        return 0;
    }

    Com_DPrintf("writing to: %s\n", ospath);
    fsh[f].handleFiles.file.o = Sys_FOpen(ospath, "wb");

    Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name));

    fsh[f].handleSync = false;
    if (!fsh[f].handleFiles.file.o)
    {
        f = 0;
    }

    return f;
}

/*
===========
FS_SV_FOpenFileRead

Search for a file somewhere below the home path then base path
in that order
===========
*/
long FS_SV_FOpenFileRead(const char *filename, fileHandle_t *fp)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    fileHandle_t f = FS_HandleForFile();
    fsh[f].zipFile = false;

    Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name));

    // don't let sound stutter
    S_ClearSoundBuffer();

    // search homepath
    char *ospath = FS_BuildOSPath(fs_homepath->string, filename, "");
    // remove trailing slash
    ospath[strlen(ospath) - 1] = '\0';

    Com_DPrintf("FS_SV_FOpenFileRead (fs_homepath): %s\n", ospath);

    fsh[f].handleFiles.file.o = Sys_FOpen(ospath, "rb");
    fsh[f].handleSync = false;
    if (!fsh[f].handleFiles.file.o)
    {
        // If fs_homepath == fs_basepath, don't bother
        if (Q_stricmp(fs_homepath->string, fs_basepath->string))
        {
            // search basepath
            ospath = FS_BuildOSPath(fs_basepath->string, filename, "");
            ospath[strlen(ospath) - 1] = '\0';

            Com_DPrintf("FS_SV_FOpenFileRead (fs_basepath): %s\n", ospath);

            fsh[f].handleFiles.file.o = Sys_FOpen(ospath, "rb");
            fsh[f].handleSync = false;
        }

        if (!fsh[f].handleFiles.file.o)
        {
            f = 0;
        }
    }

    *fp = f;
    if (f)
    {
        return FS_filelength(f);
    }

    return -1;
}

/*
===========
FS_SV_Rename

===========
*/
void FS_SV_Rename(const char *from, const char *to, bool safe)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    // don't let sound stutter
    S_ClearSoundBuffer();

    char *from_ospath = FS_BuildOSPath(fs_homepath->string, from, "");
    char *to_ospath = FS_BuildOSPath(fs_homepath->string, to, "");

    from_ospath[strlen(from_ospath) - 1] = '\0';
    to_ospath[strlen(to_ospath) - 1] = '\0';

    Com_DPrintf("FS_SV_Rename: (%s) %s --> %s\n", safe ? "safe" : "unsafe", from_ospath, to_ospath);

    if (safe)
    {
        FS_CheckFilenameIsMutable(to_ospath, __FUNCTION__);
    }

    rename(from_ospath, to_ospath);
}

/*
===========
FS_Rename

===========
*/
void FS_Rename(const char *from, const char *to)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    // don't let sound stutter
    S_ClearSoundBuffer();

    char *from_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, from);
    char *to_ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, to);

    Com_DPrintf("FS_Rename: %s --> %s\n", from_ospath, to_ospath);

    FS_CheckFilenameIsMutable(to_ospath, __FUNCTION__);

    rename(from_ospath, to_ospath);
}

/*
==============
FS_FCloseFile

If the FILE pointer is an open pak file, leave it open.

For some reason, other dll's can't just cal fclose()
on files returned by FS_FOpenFile...
==============
*/
void fileHandleData_t::close()
{
    if (zipFile == true)
    {
        unzCloseCurrentFile(handleFiles.file.z);

        if (handleFiles.unique)
            unzClose(handleFiles.file.z);
    }
    // we didn't find it as a pak, so close it as a unique file
    else if (handleFiles.file.o)
    {
        ::fclose(handleFiles.file.o);
    }

    ::memset(this, 0, sizeof(*this));
}

void FS_FCloseFile(fileHandle_t f)
{
    if (!fs_searchpaths)
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");

    fsh[f].close();

    ::memset(&fsh[f], 0, sizeof(fsh[f]));
}

/*
===========
FS_FOpenFileWrite

===========
*/
fileHandle_t FS_FOpenFileWrite(const char *filename)
{

    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    fileHandle_t f = FS_HandleForFile();
    fsh[f].zipFile = false;

    char *ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename);

    Com_DPrintf("FS_FOpenFileWrite: %s\n", ospath);

    FS_CheckFilenameIsMutable(ospath, __FUNCTION__);

    if (FS_CreatePath(ospath))
    {
        return 0;
    }

    // enabling the following line causes a recursive function call loop
    // when running with +set logfile 1 +set developer 1
    // Com_DPrintf( "writing to: %s\n", ospath );
    fsh[f].handleFiles.file.o = Sys_FOpen(ospath, "wb");

    Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name));

    fsh[f].handleSync = false;
    if (!fsh[f].handleFiles.file.o)
    {
        f = 0;
    }
    return f;
}

/*
===========
FS_FOpenFileAppend

===========
*/
fileHandle_t FS_FOpenFileAppend(const char *filename)
{
    char *ospath;
    fileHandle_t f;

    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    f = FS_HandleForFile();
    fsh[f].zipFile = false;

    Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name));

    // don't let sound stutter
    S_ClearSoundBuffer();

    ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename);

    Com_DPrintf("FS_FOpenFileAppend: %s\n", ospath);

    FS_CheckFilenameIsMutable(ospath, __FUNCTION__);

    if (FS_CreatePath(ospath))
    {
        return 0;
    }

    fsh[f].handleFiles.file.o = Sys_FOpen(ospath, "ab");
    fsh[f].handleSync = false;
    if (!fsh[f].handleFiles.file.o)
    {
        f = 0;
    }
    return f;
}

/*
===========
FS_FCreateOpenPipeFile

===========
*/
fileHandle_t FS_FCreateOpenPipeFile(const char *filename)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    fileHandle_t f = FS_HandleForFile();
    fsh[f].zipFile = false;

    Q_strncpyz(fsh[f].name, filename, sizeof(fsh[f].name));

    // don't let sound stutter
    S_ClearSoundBuffer();

    char *ospath = FS_BuildOSPath(fs_homepath->string, fs_gamedir, filename);

    Com_DPrintf("FS_FCreateOpenPipeFile: %s\n", ospath);

    FS_CheckFilenameIsMutable(ospath, __FUNCTION__);

    FILE *fifo = Sys_Mkfifo(ospath);
    if (fifo)
    {
        fsh[f].handleFiles.file.o = fifo;
        fsh[f].handleSync = false;
    }
    else
    {
        Com_Printf(S_COLOR_YELLOW
            "WARNING: Could not create new com_pipefile at %s. "
            "com_pipefile will not be used.\n",
            ospath);
        f = 0;
    }

    return f;
}

/*
===========
FS_FilenameCompare

Ignore case and seprator char distinctions
===========
*/
bool FS_FilenameCompare(const char *s1, const char *s2)
{
    int c1, c2;

    do
    {
        c1 = *s1++;
        c2 = *s2++;

        if (c1 >= 'a' && c1 <= 'z')
        {
            c1 -= ('a' - 'A');
        }
        if (c2 >= 'a' && c2 <= 'z')
        {
            c2 -= ('a' - 'A');
        }

        if (c1 == '\\' || c1 == ':')
        {
            c1 = '/';
        }
        if (c2 == '\\' || c2 == ':')
        {
            c2 = '/';
        }

        if (c1 != c2)
        {
            return true;  // strings not equal
        }
    } while (c1);

    return false;  // strings are equal
}

/*
===========
FS_IsExt

Return true if ext matches file extension filename
===========
*/
static bool FS_IsExt(const char *filename, const char *ext, int namelen)
{
    int extlen = strlen(ext);

    if (extlen > namelen) return false;

    filename += namelen - extlen;

    return !Q_stricmp(filename, ext);
}

/*
===========
FS_IsDemoExt

Return true if filename has a demo extension
===========
*/

static bool FS_IsDemoExt(const char *filename)
{
    const char *ext_test = strrchr(filename, '.');
    if (ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
    {
        int protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
        if (protocol == PROTOCOL_VERSION) return true;

        for (int i = 0; demo_protocols[i]; i++)
            if (demo_protocols[i] == protocol) return true;
    }

    return false;
}

/*
===========
FS_FOpenFileReadDir

Tries opening file "filename" in searchpath "search"
Returns filesize and an open FILE pointer.
===========
*/
long FS_FOpenFileReadDir(
    const char *filename, void *_search, fileHandle_t *file, bool uniqueFILE, bool unpure)
{
    pack_t *pak;
    directory_t *dir;
    char *netpath;
    FILE *filep;
    int len;

    searchpath_t *search = static_cast<searchpath_t *>(_search);

    if (filename == nullptr)
        Com_Error(ERR_FATAL, "FS_FOpenFileRead: nullptr 'filename' parameter passed");

    // qpaths are not supposed to have a leading slash
    if (filename[0] == '/' || filename[0] == '\\') filename++;

    // make absolutely sure that it can't back up the path.
    // The searchpaths do guarantee that something will always
    // be prepended, so we don't need to worry about "c:" or "//limbo"
    if (strstr(filename, "..") || strstr(filename, "::"))
    {
        if (file == nullptr) return false;

        *file = 0;
        return -1;
    }

    if (file == nullptr)
    {
        // just wants to see if file is there

        if ( fs_debug->integer )
        {
            Com_Printf(S_COLOR_GREEN "Searching for: " S_COLOR_RED "%s\n", filename);
        }

        // is the element a pak file?
        if (search->pack)
        {
            auto pakfile = search->pack->find(filename);
            if (pakfile)
            {
                // found it!
                if (!pakfile->len)
                {
                    // FIXME: It's not nice, but legacy code depends on
                    // positive value if file exists no matter what size
                    return 1;
                }

                return pakfile->len;
            }
        }
        else if (search->dir)
        {
            dir = search->dir;

            netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
            filep = Sys_FOpen(netpath, "rb");

            if (filep)
            {
                len = FS_fplength(filep);
                fclose(filep);

                if (len)
                    return len;
                else
                    return 1;
            }
        }

        return 0;
    }

    *file = FS_HandleForFile();
    fsh[*file].handleFiles.unique = uniqueFILE;

    // is the element a pak file?
    if (search->pack)
    {
        pak = search->pack;
        auto pakfile = pak->find(filename);
        if (pakfile )
        {
            if ( fs_debug->integer == 2 )
                Com_Printf(S_COLOR_GREEN "#2 Searching for: " S_COLOR_RED "%s\n", filename);

            // disregard if it doesn't match one of the allowed pure pak files
            if (!unpure && !pak->is_pure())
            {
                if ( fs_debug->integer == 2 )
                    Com_Printf(S_COLOR_GREEN "Ugh-oh %s found in unpure pk3\n", filename);

                *file = 0;
                return -1;
            }

            len = strlen(filename);

            if (!(pak->referenced & FS_GENERAL_REF))
            {
                if ( !FS_IsExt(filename, ".shader", len)
                        && !FS_IsExt(filename, ".mtr", len)
                        && !FS_IsExt(filename, ".txt", len)
                        && !FS_IsExt(filename, ".cfg", len)
                        && !FS_IsExt(filename, ".config", len)
                        && !FS_IsExt(filename, ".arena", len)
                        && !FS_IsExt(filename, ".menu", len)
                        && !strstr(filename, "levelshots") )
                {
                    pak->referenced |= FS_GENERAL_REF;
                }
            }

            if (strstr(filename, "cgame.qvm"))
                pak->referenced |= FS_CGAME_REF;

            if (strstr(filename, "ui.qvm"))
                pak->referenced |= FS_UI_REF;

            if (uniqueFILE)
            {
                fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
                if ( !fsh[*file].handleFiles.file.z )
                    Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
            }
            else
            {
                fsh[*file].handleFiles.file.z = pak->handle;
            }

            Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
            fsh[*file].zipFile = true;

            // set the file position in the zip file (also sets the current file info)
            unzSetOffset(fsh[*file].handleFiles.file.z, pakfile->pos);

            // open the file in the zip
            unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
            fsh[*file].zipFilePos = pakfile->pos;
            fsh[*file].zipFileLen = pakfile->len;

            if ( fs_debug->integer )
            {
                Com_Printf( "FS_FOpenFileRead: %s (found in '%s')\n",
                        filename, pak->pakFilename);
            }

            return pakfile->len;
        }
    }
    else if (search->dir)
    {
        // check a file in the directory tree

        // if we are running restricted, the only files we
        // will allow to come from the directory are .cfg files
        len = strlen(filename);
        // FIXME TTimo I'm not sure about the fs_numServerPaks test
        // if you are using FS_ReadFile to find out if a file exists,
        //   this test can make the search fail although the file is in the directory
        // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
        // turned out I used FS_FileExists instead
        if (!unpure && fs_numServerPaks)
        {
            if (!FS_IsExt(filename, ".cfg", len) &&  // for config files
                !FS_IsExt(filename, ".lua", len) &&  // lua 
                !FS_IsExt(filename, ".menu", len) &&  // menu files
                !FS_IsExt(filename, ".game", len) &&  // menu files
                !FS_IsExt(filename, ".dat", len) &&  // for journal files
                !FS_IsDemoExt(filename))  // demos
            {
                *file = 0;
                return -1;
            }
        }

        dir = search->dir;

        netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
        filep = Sys_FOpen(netpath, "rb");

        if (filep == nullptr)
        {
            *file = 0;
            return -1;
        }

        Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
        fsh[*file].zipFile = false;

        if (fs_debug->integer)
        {
            Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n",
                    filename, dir->path, PATH_SEP, dir->gamedir);
        }

        fsh[*file].handleFiles.file.o = filep;
        return FS_fplength(filep);
    }

    *file = 0;
    return -1;
}

/*
===========
FS_FOpenFileRead

Finds the file in the search path.
Returns filesize and an open FILE pointer.
Used for streaming data out of either a
separate file or a ZIP file.
===========
*/
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, bool uniqueFILE)
{
    searchpath_t *search;
    long len;

    if (!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization");

    bool isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
    for (search = fs_searchpaths; search; search = search->next)
    {
        // autoexec.cfg and q3config.cfg can only be loaded outside of pk3 files.
        if (isLocalConfig && search->pack) continue;

        len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, false);

        if (file == nullptr)
        {
            if (len > 0) return len;
        }
        else
        {
            if (len >= 0 && *file) return len;
        }
    }

#ifdef FS_MISSING
    if (missingFiles) fprintf(missingFiles, "%s\n", filename);
#endif

    if (file)
    {
        *file = 0;
        return -1;
    }
    else
    {
        // When file is nullptr, we're querying the existance of the file
        // If we've got here, it doesn't exist
        return 0;
    }
}

/*
=================
FS_FindVM

Find a suitable VM file in search path order.

In each searchpath try:
 - open DLL file if DLL loading enabled
 - open QVM file

Enable search for DLL by setting enableDll to FSVM_ENABLEDLL

write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
Return the searchpath in "startSearch".
=================
*/

static directory_t fs_directory_overpath_game;
static searchpath_t fs_searchpath_overpath_game;
static directory_t fs_directory_overpath_basegame;
static searchpath_t fs_searchpath_overpath_basegame;

int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll)
{
    searchpath_t *search, *lastSearch;
    directory_t *dir;
    pack_t *pack;
    char dllName[MAX_OSPATH], qvmName[MAX_OSPATH];
    char *netpath;

    if (!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization");

    if (enableDll) Com_sprintf(dllName, sizeof(dllName), "%s" DLL_EXT, name);

    Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.qvm", name);

    lastSearch = static_cast<searchpath_t *>(*startSearch);
    if (*startSearch == nullptr)
	{
		const char *overpath = Cvar_VariableString( "fs_overpath" );
		if(overpath[0])
		{
			// set up some special searchpath elements
			Q_strncpyz( fs_directory_overpath_game.path, overpath, sizeof( fs_directory_overpath_game.path ) );
			Q_strncpyz( fs_directory_overpath_game.gamedir, fs_gamedir, sizeof( fs_directory_overpath_game.gamedir ) );
			fs_searchpath_overpath_game.next = &fs_searchpath_overpath_basegame;
			fs_searchpath_overpath_game.pack = NULL;
			fs_searchpath_overpath_game.dir = &fs_directory_overpath_game;
			Q_strncpyz( fs_directory_overpath_basegame.path, overpath, sizeof( fs_directory_overpath_basegame.path ) );
			Q_strncpyz( fs_directory_overpath_basegame.gamedir, fs_basegame->string, sizeof( fs_directory_overpath_basegame.gamedir ) );
			fs_searchpath_overpath_basegame.next = fs_searchpaths;
			fs_searchpath_overpath_basegame.pack = NULL;
			fs_searchpath_overpath_basegame.dir = &fs_directory_overpath_basegame;
			search = &fs_searchpath_overpath_game;
		}
		else
			search = fs_searchpaths;
	}
    else
        search = lastSearch->next;

    while (search)
    {
        if (search->dir && (!fs_numServerPaks || !strcmp(name, "game") || (search == &fs_searchpath_overpath_game || search == &fs_searchpath_overpath_basegame)))
        {
            dir = search->dir;

            if (enableDll && (search == &fs_searchpath_overpath_game || search == &fs_searchpath_overpath_basegame))
            {
                netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);

                if (FS_FileInPathExists(netpath))
                {
                    Q_strncpyz(found, netpath, foundlen);
                    *startSearch = search;

                    return VMI_NATIVE;
                }
            }

            if (FS_FOpenFileReadDir(qvmName, search, nullptr, false, false) > 0)
            {
                *startSearch = search;
                return VMI_COMPILED;
            }
        }
        else if (search->pack)
        {
            pack = search->pack;

            if (lastSearch && lastSearch->pack)
            {
                // make sure we only try loading one VM file per game dir
                // i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3

                if (!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
                {
                    search = search->next;
                    continue;
                }
            }

            if (FS_FOpenFileReadDir(qvmName, search, nullptr, false, false) > 0)
            {
                *startSearch = search;

                return VMI_COMPILED;
            }
        }

        search = search->next;
    }

    return -1;
}

int FS_Read(void *buffer, int len, fileHandle_t f)
{
    int block, remaining;
    int read;
    byte *buf;
    int tries;

    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!f)
    {
        return 0;
    }

    buf = (byte *)buffer;
    fs_readCount += len;

    if (fsh[f].zipFile == false)
    {
        remaining = len;
        tries = 0;
        while (remaining)
        {
            block = remaining;
            read = fread(buf, 1, block, fsh[f].handleFiles.file.o);
            if (read == 0)
            {
                // we might have been trying to read from a CD, which
                // sometimes returns a 0 read on windows
                if (!tries)
                {
                    tries = 1;
                }
                else
                {
                    return len - remaining;  // Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
                }
            }

            if (read == -1)
            {
                Com_Error(ERR_FATAL, "FS_Read: -1 bytes read");
            }

            remaining -= read;
            buf += read;
        }
        return len;
    }
    else
    {
        return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
    }
}

/*
=================
FS_Write

Properly handles partial writes
=================
*/
int FS_Write(const void *buffer, int len, fileHandle_t h)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!h)
    {
        return 0;
    }

    FILE *f = FS_FileForHandle(h);
    byte *buf = (byte *)buffer;

    int remaining = len;
    int tries = 0;
    while (remaining)
    {
        int block = remaining;
        int written = fwrite(buf, 1, block, f);
        if (written == 0)
        {
            if (!tries)
            {
                tries = 1;
            }
            else
            {
                Com_Printf("FS_Write: 0 bytes written\n");
                return 0;
            }
        }

        if (written == -1)
        {
            Com_Printf("FS_Write: -1 bytes written\n");
            return 0;
        }

        remaining -= written;
        buf += written;
    }

    if (fsh[h].handleSync)
    {
        fflush(f);
    }
    return len;
}

void QDECL FS_Printf(fileHandle_t h, const char *fmt, ...)
{
    va_list argptr;
    char msg[MAXPRINTMSG];

    va_start(argptr, fmt);
    Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
    va_end(argptr);

    FS_Write(msg, strlen(msg), h);
}

#define PK3_SEEK_BUFFER_SIZE 65536

/*
=================
FS_Seek

=================
*/
int FS_Seek(fileHandle_t f, long offset, enum FS_Origin origin)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
        return -1;
    }

    if (fsh[f].zipFile == true)
    {
        // FIXME: this is really, really crappy
        //(but better than what was here before)
        byte buffer[PK3_SEEK_BUFFER_SIZE];
        int remainder;
        int currentPosition = FS_FTell(f);

        // change negative offsets into FS_SEEK_SET
        if (offset < 0)
        {
            switch (origin)
            {
                case FS_SEEK_END:
                    remainder = fsh[f].zipFileLen + offset;
                    break;

                case FS_SEEK_CUR:
                    remainder = currentPosition + offset;
                    break;

                case FS_SEEK_SET:
                default:
                    remainder = 0;
                    break;
            }

            if (remainder < 0)
            {
                remainder = 0;
            }

            origin = FS_SEEK_SET;
        }
        else
        {
            if (origin == FS_SEEK_END)
            {
                remainder = fsh[f].zipFileLen - currentPosition + offset;
            }
            else
            {
                remainder = offset;
            }
        }

        switch (origin)
        {
            case FS_SEEK_SET:
                if (remainder == currentPosition)
                {
                    return offset;
                }
                unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
                unzOpenCurrentFile(fsh[f].handleFiles.file.z);
            // fallthrough

            case FS_SEEK_END:  // fall through
            case FS_SEEK_CUR:
                while (remainder > PK3_SEEK_BUFFER_SIZE)
                {
                    FS_Read(buffer, PK3_SEEK_BUFFER_SIZE, f);
                    remainder -= PK3_SEEK_BUFFER_SIZE;
                }
                FS_Read(buffer, remainder, f);
                return offset;

            default:
                Com_Error(ERR_FATAL, "Bad origin in FS_Seek");
                return -1;
        }
    }
    else
    {
        FILE *file;
        file = FS_FileForHandle(f);
        int _origin;
        switch (origin)
        {
            case FS_SEEK_CUR:
                _origin = SEEK_CUR;
                break;
            case FS_SEEK_END:
                _origin = SEEK_END;
                break;
            case FS_SEEK_SET:
                _origin = SEEK_SET;
                break;
            default:
                Com_Error(ERR_FATAL, "Bad origin in FS_Seek");
                break;
        }

        return fseek(file, offset, _origin);
    }
}

/*
======================================================================================

CONVENIENCE FUNCTIONS FOR ENTIRE FILES

======================================================================================
*/

int FS_FileIsInPAK_A(bool alternate, const char *filename, int *pChecksum)
{
    if (!fs_searchpaths)
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");

    if (!filename)
        Com_Error(ERR_FATAL, "FS_FOpenFileRead: nullptr 'filename' parameter passed");

    // qpaths are not supposed to have a leading slash
    if (filename[0] == '/' || filename[0] == '\\')
        filename++;

    // make absolutely sure that it can't back up the path.
    // The searchpaths do guarantee that something will always
    // be prepended, so we don't need to worry about "c:" or "//limbo"
    if (strstr(filename, "..") || strstr(filename, "::"))
        return -1;

    //
    // search through the path, one element at a time
    //
    for (auto search = fs_searchpaths; search; search = search->next)
    {
        if (!search->pack)
            continue;

        // disregard if it doesn't match one of the allowed pure pak files
        if (!search->pack->is_pure())
            continue;

        if ((alternate && search->pack->onlyPrimary) ||
            (!alternate && search->pack->onlyAlternate))
            continue;

        auto found = search->pack->find(filename);
        if (found)
        {
            if (pChecksum)
                *pChecksum = search->pack->pure_checksum;

            return 1;
        }
    }
    return -1;
}

int FS_FileIsInPAK(const char *filename, int *pChecksum)
{
    return FS_FileIsInPAK_A(false, filename, pChecksum);
}
/*
============
FS_ReadFileDir

Filename are relative to the quake search path
a null buffer will just return the file length without loading
If searchPath is non-nullptr search only in that specific search path
============
*/
long FS_ReadFileDir(const char *qpath, void *searchPath, bool unpure, void **buffer)
{
    fileHandle_t h;
    byte *buf;
    bool isConfig;
    long len;

    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!qpath || !qpath[0])
    {
        Com_Error(ERR_FATAL, "FS_ReadFile with empty name");
    }

    buf = nullptr;  // quiet compiler warning

    // if this is a .cfg file and we are playing back a journal, read
    // it from the journal file
    if (strstr(qpath, ".cfg"))
    {
        isConfig = true;
        if (com_journal && com_journal->integer == 2)
        {
            Com_DPrintf("Loading %s from journal file.\n", qpath);

            int r = FS_Read(&len, sizeof(len), com_journalDataFile);
            if (r != sizeof(len))
            {
                if (buffer != nullptr) *buffer = nullptr;
                return -1;
            }

            // if the file didn't exist when the journal was created
            if (!len)
            {
                if (buffer == nullptr)
                {
                    return 1;  // hack for old journal files
                }
                *buffer = nullptr;
                return -1;
            }

            if (buffer == nullptr)
            {
                return len;
            }

            buf = static_cast<byte *>(Hunk_AllocateTempMemory(len + 1));
            *buffer = buf;

            r = FS_Read(buf, len, com_journalDataFile);
            if (r != len)
            {
                Com_Error(ERR_FATAL, "Read from journalDataFile failed");
            }

            fs_loadCount++;
            fs_loadStack++;

            // guarantee that it will have a trailing 0 for string operations
            buf[len] = 0;

            return len;
        }
    }
    else
    {
        isConfig = false;
    }

    searchpath_t *search = static_cast<searchpath_t *>(searchPath);
    if (search == nullptr)
    {
        // look for it in the filesystem or pack files
        len = FS_FOpenFileRead(qpath, &h, false);
    }
    else
    {
        // look for it in a specific search path only
        len = FS_FOpenFileReadDir(qpath, search, &h, false, unpure);
    }

    if (h == 0)
    {
        if (buffer)
        {
            *buffer = nullptr;
        }
        // if we are journalling and it is a config file, write a zero to the journal file
        if (isConfig && com_journal && com_journal->integer == 1)
        {
            Com_DPrintf("Writing zero for %s to journal file.\n", qpath);
            len = 0;
            FS_Write(&len, sizeof(len), com_journalDataFile);
            FS_Flush(com_journalDataFile);
        }
        return -1;
    }

    if (!buffer)
    {
        if (isConfig && com_journal && com_journal->integer == 1)
        {
            Com_DPrintf("Writing len for %s to journal file.\n", qpath);
            FS_Write(&len, sizeof(len), com_journalDataFile);
            FS_Flush(com_journalDataFile);
        }
        FS_FCloseFile(h);
        return len;
    }

    fs_loadCount++;
    fs_loadStack++;

    buf = static_cast<byte *>(Hunk_AllocateTempMemory(len + 1));
    *buffer = buf;

    FS_Read(buf, len, h);

    // guarantee that it will have a trailing 0 for string operations
    buf[len] = 0;
    FS_FCloseFile(h);

    // if we are journalling and it is a config file, write it to the journal file
    if (isConfig && com_journal && com_journal->integer == 1)
    {
        Com_DPrintf("Writing %s to journal file.\n", qpath);
        FS_Write(&len, sizeof(len), com_journalDataFile);
        FS_Write(buf, len, com_journalDataFile);
        FS_Flush(com_journalDataFile);
    }
    return len;
}

/*
============
FS_ReadFile

Filename are relative to the quake search path
a null buffer will just return the file length without loading
============
*/
long FS_ReadFile(const char *qpath, void **buffer)
{
    return FS_ReadFileDir(qpath, nullptr, false, buffer);
}
/*
=============
FS_FreeFile
=============
*/
void FS_FreeFile(void *buffer)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }
    if (!buffer)
    {
        Com_Error(ERR_FATAL, "FS_FreeFile( nullptr )");
    }

    fs_loadStack--;
    Hunk_FreeTempMemory(buffer);

    // if all of our temp files are free, clear all of our space
    if (fs_loadStack == 0)
    {
        Hunk_ClearTempMemory();
    }
}

/*
============
FS_WriteFile

Filename are relative to the quake search path
============
*/
void FS_WriteFile(const char *qpath, const void *buffer, int size)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!qpath || !buffer)
    {
        Com_Error(ERR_FATAL, "FS_WriteFile: nullptr parameter");
    }

    fileHandle_t f = FS_FOpenFileWrite(qpath);
    if (!f)
    {
        Com_Printf("Failed to open %s\n", qpath);
        return;
    }

    FS_Write(buffer, size, f);
    FS_FCloseFile(f);
}

/*
==========================================================================

ZIP FILE LOADING

==========================================================================
*/

/*
=================
FS_LoadZipFile

Creates a new pack_t in the search chain for the contents of a zip file.
=================
*/
static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename)
{
    int fs_numHeaderLongs = 0;
    unsigned long len = 0;
    char filename[MAX_ZPATH];

    auto z = unzOpen(zipfile);

    unz_global_info gi;
    int err = unzGetGlobalInfo(z, &gi);
    if (err) return nullptr;

    err = unzGoToFirstFile(z);
    if (err) return nullptr;

    for (uLong i = 0; i < gi.number_entry; i++)
    {
        unz_file_info fi;
        err = unzGetCurrentFileInfo(
            z, &fi, filename, sizeof(filename), nullptr, 0, nullptr, 0);

        if (err) break;

        len += strlen(filename) + 1;
        unzGoToNextFile(z);
    }

    fileInPack_t *buildBuffer =
        static_cast<fileInPack_t *>(Z_Malloc((gi.number_entry * sizeof(fileInPack_t)) + len));

    char *namePtr = ((char *)buildBuffer) + gi.number_entry * sizeof(fileInPack_t);

    int *fs_headerLongs = static_cast<int *>(Z_Malloc((gi.number_entry + 1) * sizeof(int)));

    fs_headerLongs[fs_numHeaderLongs] = LittleLong(fs_checksumFeed);
    fs_numHeaderLongs++;

    // get the hash table size from the number of files in the zip
    // because lots of custom pk3 files have less than 32 or 64 files
    uLong hashsiz;
    for (hashsiz = 1; hashsiz <= MAX_FILEHASH_SIZE; hashsiz <<= 1)
    {
        if (hashsiz > gi.number_entry) break;
    }

    pack_t *pack = static_cast<pack_t *>(Z_Malloc(sizeof(pack_t) + hashsiz * sizeof(fileInPack_t *)));

    pack->hashSize = hashsiz;
    pack->hashTable = (fileInPack_t **)(((char *)pack) + sizeof(pack_t));

    for (int i = 0; i < pack->hashSize; i++)
    {
        pack->hashTable[i] = nullptr;
    }

    Q_strncpyz(pack->pakFilename, zipfile, sizeof(pack->pakFilename));
    Q_strncpyz(pack->pakBasename, basename, sizeof(pack->pakBasename));

    // strip .pk3 if needed
    if ( strlen(pack->pakBasename) > 4 &&
        !Q_stricmp(pack->pakBasename + strlen(pack->pakBasename) - 4, ".pk3"))
    {
        pack->pakBasename[strlen(pack->pakBasename) - 4] = '\0';
    }

    pack->handle = z;
    pack->numfiles = gi.number_entry;
    unzGoToFirstFile(z);
    for (uLong i = 0; i < gi.number_entry; i++)
    {
        unz_file_info fi;
        err = unzGetCurrentFileInfo(
            z, &fi, filename, sizeof(filename), nullptr, 0, nullptr, 0);

        if (err) break;

        if (fi.uncompressed_size)
        {
            fs_headerLongs[fs_numHeaderLongs] = LittleLong(fi.crc);
            fs_numHeaderLongs++;
        }

        Q_strlwr(filename);
        long hash = FS_HashFileName(filename, pack->hashSize);

        buildBuffer[i].name = namePtr;
        strcpy(buildBuffer[i].name, filename);
        namePtr += strlen(filename) + 1;

        // store the file position in the zip
        buildBuffer[i].pos = unzGetOffset(z);
        buildBuffer[i].len = fi.uncompressed_size;
        buildBuffer[i].next = pack->hashTable[hash];

        pack->hashTable[hash] = &buildBuffer[i];
        unzGoToNextFile(z);
    }

    pack->checksum =
        Com_BlockChecksum(&fs_headerLongs[1], sizeof(*fs_headerLongs) * (fs_numHeaderLongs - 1));
    pack->pure_checksum =
        Com_BlockChecksum(fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs);
    pack->checksum = LittleLong(pack->checksum);
    pack->pure_checksum = LittleLong(pack->pure_checksum);

    Z_Free(fs_headerLongs);

    pack->buildBuffer = buildBuffer;
    return pack;
}

/*
=================
FS_FreePak

Frees a pak structure and releases all associated resources
=================
*/

static void FS_FreePak(pack_t *thepak)
{
    unzClose(thepak->handle);
    Z_Free(thepak->buildBuffer);
    Z_Free(thepak);
}

/*
=================
FS_GetZipChecksum

Compares whether the given pak file matches a referenced checksum
=================
*/
bool FS_CompareZipChecksum(const char *zipfile)
{
    pack_t *thepak = FS_LoadZipFile(zipfile, "");

    if (!thepak) return false;

    int checksum = thepak->checksum;
    FS_FreePak(thepak);

    for (int i = 0; i < fs_numServerReferencedPaks; i++)
    {
        if (checksum == fs_serverReferencedPaks[i]) return true;
    }

    return false;
}

/*
=================================================================================

DIRECTORY SCANNING FUNCTIONS

=================================================================================
*/

#define MAX_FOUND_FILES 0x1000

static int FS_ReturnPath(const char *zname, char *zpath, int *depth)
{
    int newdep = 0;
    int len = 0;
    int at = 0;
    zpath[0] = 0;

    while (zname[at] != 0)
    {
        if (zname[at] == '/' || zname[at] == '\\')
        {
            len = at;
            newdep++;
        }
        at++;
    }
    strcpy(zpath, zname);
    zpath[len] = 0;
    *depth = newdep;

    return len;
}

/*
==================
FS_AddFileToList
==================
*/
static int FS_AddFileToList(char *name, char *list[MAX_FOUND_FILES], int nfiles)
{
    if (nfiles == MAX_FOUND_FILES - 1)
    {
        return nfiles;
    }

    for (int i = 0; i < nfiles; i++)
    {
        if (!Q_stricmp(name, list[i]))
        {
            return nfiles;  // allready in list
        }
    }
    list[nfiles] = CopyString(name);
    nfiles++;

    return nfiles;
}

/*
===============
FS_ListFilteredFiles

Returns a uniqued list of files that match the given criteria
from all search paths
===============
*/
char **FS_ListFilteredFiles(const char *path, const char *extension, const char *filter,
    int *numfiles, bool allowNonPureFilesOnDisk)
{
    int nfiles;
    char **listCopy;
    char *list[MAX_FOUND_FILES];
    searchpath_t *search;
    int i;
    int pathLength;
    int extensionLength;
    int length, pathDepth, temp;
    pack_t *pak;
    fileInPack_t *buildBuffer;
    char zpath[MAX_ZPATH];

    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!path)
    {
        *numfiles = 0;
        return nullptr;
    }
    if (!extension)
    {
        extension = "";
    }

    pathLength = strlen(path);
    if (path[pathLength - 1] == '\\' || path[pathLength - 1] == '/')
    {
        pathLength--;
    }
    extensionLength = strlen(extension);
    nfiles = 0;
    FS_ReturnPath(path, zpath, &pathDepth);

    //
    // search through the path, one element at a time, adding to list
    //
    for (search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (search->pack)
        {
            // ZOID:  If we are pure, don't search for files on paks that
            // aren't on the pure list
            if (!search->pack->is_pure())
            {
                continue;
            }

            // look through all the pak file elements
            pak = search->pack;
            buildBuffer = pak->buildBuffer;
            for (i = 0; i < pak->numfiles; i++)
            {
                char *name;
                int zpathLen, depth;

                // check for directory match
                name = buildBuffer[i].name;
                //
                if (filter)
                {
                    // case insensitive
                    if (!Com_FilterPath(filter, name, false)) continue;
                    // unique the match
                    nfiles = FS_AddFileToList(name, list, nfiles);
                }
                else
                {
                    zpathLen = FS_ReturnPath(name, zpath, &depth);

                    if ((depth - pathDepth) > 2 || pathLength > zpathLen ||
                        Q_stricmpn(name, path, pathLength))
                    {
                        continue;
                    }

                    // check for extension match
                    length = strlen(name);
                    if (length < extensionLength)
                    {
                        continue;
                    }

                    if (Q_stricmp(name + length - extensionLength, extension))
                    {
                        continue;
                    }
                    // unique the match

                    temp = pathLength;
                    if (pathLength)
                    {
                        temp++;  // include the '/'
                    }
                    nfiles = FS_AddFileToList(name + temp, list, nfiles);
                }
            }
        }
        else if (search->dir)
        {  // scan for files in the filesystem

            // don't scan directories for files if we are pure or restricted
            if (fs_numServerPaks && !allowNonPureFilesOnDisk)
            {
                continue;
            }
            else
            {
                int numSysFiles;
                char *netpath = FS_BuildOSPath(search->dir->path, search->dir->gamedir, path);
                char **sysFiles = Sys_ListFiles(netpath, extension, filter, &numSysFiles, false);
                for (i = 0; i < numSysFiles; i++)
                {
                    // unique the match
                    char *name = sysFiles[i];
                    nfiles = FS_AddFileToList(name, list, nfiles);
                }
                Sys_FreeFileList(sysFiles);
            }
        }
    }

    // return a copy of the list
    *numfiles = nfiles;

    if (!nfiles)
    {
        return nullptr;
    }

    listCopy = static_cast<char **>(Z_Malloc((nfiles + 1) * sizeof(*listCopy)));
    for (i = 0; i < nfiles; i++)
    {
        listCopy[i] = list[i];
    }
    listCopy[i] = nullptr;

    return listCopy;
}

/*
=================
FS_ListFiles
=================
*/
char **FS_ListFiles(const char *path, const char *extension, int *numfiles)
{
    return FS_ListFilteredFiles(path, extension, nullptr, numfiles, false);
}

/*
=================
FS_FreeFileList
=================
*/
void FS_FreeFileList(char **list)
{
    if (!fs_searchpaths)
    {
        Com_Error(ERR_FATAL, "Filesystem call made without initialization");
    }

    if (!list)
    {
        return;
    }

    for (int i = 0; list[i]; i++)
    {
        Z_Free(list[i]);
    }

    Z_Free(list);
}

/*
================
FS_GetFileList
================
*/
int FS_GetFileList(const char *path, const char *extension, char *listbuf, int bufsize)
{
    int nFiles = 0;
    int nTotal = 0;
    *listbuf = 0;

    if (Q_stricmp(path, "$modlist") == 0)
    {
        return FS_GetModList(listbuf, bufsize);
    }

    char **pFiles = FS_ListFiles(path, extension, &nFiles);

    for (int i = 0; i < nFiles; i++)
    {
        int nLen = strlen(pFiles[i]) + 1;
        if (nTotal + nLen + 1 < bufsize)
        {
            strcpy(listbuf, pFiles[i]);
            listbuf += nLen;
            nTotal += nLen;
        }
        else
        {
            nFiles = i;
            break;
        }
    }

    FS_FreeFileList(pFiles);

    return nFiles;
}

/*
================
FS_GetFilteredFiles
================
*/
int FS_GetFilteredFiles(
    const char *path, const char *extension, const char *filter, char *listbuf, int bufsize)
{
    int nFiles = 0;
    int nTotal = 0;
    *listbuf = 0;

    char **pFiles = FS_ListFilteredFiles(path, extension, filter, &nFiles, false);

    for (int i = 0; i < nFiles; i++)
    {
        int nLen = strlen(pFiles[i]) + 1;
        if (nTotal + nLen + 1 < bufsize)
        {
            strcpy(listbuf, pFiles[i]);
            listbuf += nLen;
            nTotal += nLen;
        }
        else
        {
            nFiles = i;
            break;
        }
    }

    FS_FreeFileList(pFiles);

    return nFiles;
}

/*
=======================
Sys_ConcatenateFileLists

mkv: Naive implementation. Concatenates three lists into a
     new list, and frees the old lists from the heap.
bk001129 - from cvs1.17 (mkv)

FIXME TTimo those two should move to common.c next to Sys_ListFiles
=======================
 */
static unsigned int Sys_CountFileList(char **list)
{
    unsigned int i = 0;
    if (list)
    {
        while (*list)
        {
            list++;
            i++;
        }
    }
    return i;
}

static char **Sys_ConcatenateFileLists(char **list0, char **list1)
{
    char **cat, **dst;

    int totalLength = 0;
    totalLength += Sys_CountFileList(list0);
    totalLength += Sys_CountFileList(list1);

    /* Create new list. */
    dst = cat = static_cast<char **>(Z_Malloc((totalLength + 1) * sizeof(char *)));

    /* Copy over lists. */
    if (list0)
    {
        for (char **src = list0; *src; src++, dst++) *dst = *src;
    }

    if (list1)
    {
        for (char **src = list1; *src; src++, dst++) *dst = *src;
    }

    // Terminate the list
    *dst = nullptr;

    // Free our old lists.
    // NOTE: not freeing their content, it's been merged in dst and still being used
    if (list0) Z_Free(list0);
    if (list1) Z_Free(list1);

    return cat;
}

/*
================
FS_GetModList

Returns a list of mod directory names
A mod directory is a peer to baseq3 with a pk3 or pk3dir in it
================
*/
int	FS_GetModList( char *listbuf, int bufsize )
{
    char * start = listbuf;
    *listbuf = '\0';

    // paths to search for mods
    const char * const paths[] = {
        fs_basepath->string,
        fs_homepath->string
    };

    char **pFiles = nullptr;
    for (int i = 0; i < ARRAY_LEN(paths); i++)
    {
        int dummy;
        char **pFiles0 = Sys_ListFiles(paths[i], NULL, NULL, &dummy, true);
        pFiles = Sys_ConcatenateFileLists(pFiles, pFiles0);
    }

    int nMods = 0;
    int nTotal = 0;
    for (int i = 0; i < Sys_CountFileList(pFiles); i++)
    {
        const char* name = pFiles[i];

        if ( name[0] == '.' )
            continue;

        // In order to be a valid mod the directory must contain at least one
        // .pk3 or .pk3dir we didn't keep the information when we merged the
        // directory names, as to what OS Path it was found under so we will
        // try each of them here.
        int nPaks = 0;
        int nPakDirs = 0;
        for (int j = 0; j < ARRAY_LEN(paths); j++)
        {
            const char* path = FS_BuildOSPath(paths[j], name, "");
            int nDirs = 0; 

            char **pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, false);
            char **pDirs = Sys_ListFiles(path, "/", NULL, &nDirs, false);
            for (int k = 0; k < nDirs; k++)
            {
                // we only want to count directories ending with ".pk3dir"
                if (FS_IsExt(pDirs[k], ".pk3dir", strlen(pDirs[k])))
                    nPakDirs++;
            }

            // we only use Sys_ListFiles to check whether files are present
            Sys_FreeFileList(pPaks);
            Sys_FreeFileList(pDirs);

            if (nPaks > 0 || nPakDirs > 0)
                break;
        }

		if (nPaks > 0 || nPakDirs > 0)
        {
			size_t nLen = strlen(name) + 1;

			if (nTotal + nLen + 1 < bufsize)
            {
				strcpy(listbuf, name);
				listbuf += nLen;
				nTotal += nLen;
				nMods++;
			}
            else
            {
                Com_Printf(S_COLOR_RED "Warning: Too many mods!\n");
				break;
			}
		}
    }

    Sys_FreeFileList( pFiles );
    return nMods;
}

//============================================================================

/*
================
FS_Dir_f
================
*/
void FS_Dir_f(void)
{
    const char *path;
    const char *extension;

    if (Cmd_Argc() < 2 || Cmd_Argc() > 3)
    {
        Com_Printf("usage: dir <directory> [extension]\n");
        return;
    }

    if (Cmd_Argc() == 2)
    {
        path = Cmd_Argv(1);
        extension = "";
    }
    else
    {
        path = Cmd_Argv(1);
        extension = Cmd_Argv(2);
    }

    Com_Printf("Directory of %s %s\n", path, extension);
    Com_Printf("---------------\n");

    int ndirs;
    char **dirnames = FS_ListFiles(path, extension, &ndirs);

    for (int i = 0; i < ndirs; i++)
    {
        Com_Printf("%s\n", dirnames[i]);
    }
    FS_FreeFileList(dirnames);
}

/*
===========
FS_ConvertPath
===========
*/
void FS_ConvertPath(char *s)
{
    while (*s)
    {
        if (*s == '\\' || *s == ':')
        {
            *s = '/';
        }
        s++;
    }
}

/*
===========
FS_PathCmp

Ignore case and seprator char distinctions
===========
*/
int FS_PathCmp(const char *s1, const char *s2)
{
    int c1, c2;

    do
    {
        c1 = *s1++;
        c2 = *s2++;

        if (c1 >= 'a' && c1 <= 'z')
        {
            c1 -= ('a' - 'A');
        }
        if (c2 >= 'a' && c2 <= 'z')
        {
            c2 -= ('a' - 'A');
        }

        if (c1 == '\\' || c1 == ':')
        {
            c1 = '/';
        }
        if (c2 == '\\' || c2 == ':')
        {
            c2 = '/';
        }

        if (c1 < c2)
        {
            return -1;  // strings not equal
        }
        else if (c1 > c2)
        {
            return 1;
        }
    } while (c1);

    return 0;  // strings are equal
}

/*
================
FS_SortFileList
================
*/
void FS_SortFileList(char **filelist, int numfiles)
{
    char **sortedlist = static_cast<char **>(Z_Malloc((numfiles + 1) * sizeof(*sortedlist)));
    sortedlist[0] = nullptr;

    int numsortedfiles = 0;
    for (int i = 0; i < numfiles; i++)
    {
        int j;
        for (j = 0; j < numsortedfiles; j++)
        {
            if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) break;
        }

        int k;
        for (k = numsortedfiles; k > j; k--)
        {
            sortedlist[k] = sortedlist[k - 1];
        }

        sortedlist[j] = filelist[i];
        numsortedfiles++;
    }
    ::memcpy(filelist, sortedlist, numfiles * sizeof(*filelist));
    Z_Free(sortedlist);
}

/*
================
FS_NewDir_f
================
*/
void FS_NewDir_f(void)
{
    if (Cmd_Argc() < 2)
    {
        Com_Printf("usage: fdir <filter>\n");
        Com_Printf("example: fdir *q3dm*.bsp\n");
        return;
    }

    Com_Printf("---------------\n");

    const char *filter = Cmd_Argv(1);

    int ndirs;
    char **dirnames = FS_ListFilteredFiles("", "", filter, &ndirs, false);

    FS_SortFileList(dirnames, ndirs);
    for (int i = 0; i < ndirs; i++)
    {
        FS_ConvertPath(dirnames[i]);
        Com_Printf("%s\n", dirnames[i]);
    }
    Com_Printf("%d files listed\n", ndirs);
    FS_FreeFileList(dirnames);
}

/*
============
FS_Path_f

============
*/
void FS_Path_f(void)
{
    Com_Printf("We are looking in the current search path:\n");

    for (auto s = fs_searchpaths; s; s = s->next)
    {
        if (s->pack)
        {
            Com_Printf("%s (%i files%s)\n",
                    s->pack->pakFilename,
                    s->pack->numfiles,
                    s->pack->onlyPrimary ? ", not for 1.1"
                    : s->pack->onlyAlternate ? ", only for 1.1" : "");

            if (s->pack->primaryVersion)
                Com_Printf("        (the 1.1 version of %s)\n",
                        s->pack->primaryVersion->pakFilename);

            if (fs_numServerPaks)
            {
                if (!s->pack->is_pure())
                {
                    Com_Printf("    not on the pure list\n");
                }
                else
                {
                    Com_Printf("    on the pure list\n");
                }
            }
        }
        else
        {
            Com_Printf("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir);
        }
    }

    Com_Printf("\n");
    for (int i = 1; i < MAX_FILE_HANDLES; i++)
    {
        if (fsh[i].handleFiles.file.o)
        {
            Com_Printf("handle %i: %s\n", i, fsh[i].name);
        }
    }
}

/*
============
FS_TouchFile_f
============
*/
void FS_TouchFile_f(void)
{
    if (Cmd_Argc() != 2)
    {
        Com_Printf("Usage: touchFile <file>\n");
        return;
    }

    fileHandle_t f;
    FS_FOpenFileRead(Cmd_Argv(1), &f, false);
    if (f)
    {
        FS_FCloseFile(f);
    }
}

/*
============
FS_Which
============
*/

bool FS_Which(const char *filename, void *searchPath)
{
    searchpath_t *search = static_cast<searchpath_t *>(searchPath);

    if (FS_FOpenFileReadDir(filename, search, nullptr, false, false) > 0)
    {
        if (search->pack)
        {
            Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
            return true;
        }
        else if (search->dir)
        {
            Com_Printf("File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
            return true;
        }
    }

    return false;
}

/*
============
FS_Which_f
============
*/
void FS_Which_f(void)
{
    const char *filename = Cmd_Argv(1);

    if (!filename[0])
    {
        Com_Printf("Usage: which <file>\n");
        return;
    }

    // qpaths are not supposed to have a leading slash
    if (filename[0] == '/' || filename[0] == '\\') filename++;

    // just wants to see if file is there
    for (searchpath_t *search = fs_searchpaths; search; search = search->next)
        if (FS_Which(filename, search)) return;

    Com_Printf("File not found: \"%s\"\n", filename);
}

//===========================================================================

static int QDECL paksort(const void *a, const void *b)
{
    char *aa = *(char **)a;
    char *bb = *(char **)b;

    return FS_PathCmp(aa, bb);
}

/*
================
FS_AddGameDirectory

Sets fs_gamedir, adds the directory to the head of the path,
then loads the zip headers
================
*/
void FS_AddGameDirectory(const char *path, const char *dir)
{
    pack_t *pak;
    char curpath[MAX_OSPATH + 1];
    int numfiles;
    char **pakfiles;
    int pakfilesi;
    char **pakfilestmp;
    int numdirs;
    char **pakdirs;
    int pakdirsi;
    char **pakdirstmp;

    int lengths[10][2];

    // Unique
    for (searchpath_t *sp = fs_searchpaths; sp; sp = sp->next)
    {
        if (sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir))
            return;  // we've already got this one
    }

    Q_strncpyz(fs_gamedir, dir, sizeof(fs_gamedir));

    // find all pak files in this directory
    Q_strncpyz(curpath, FS_BuildOSPath(path, dir, ""), sizeof(curpath));
    curpath[strlen(curpath) - 1] = '\0';  // strip the trailing slash

    // Get .pk3 files
    pakfiles = Sys_ListFiles(curpath, ".pk3", nullptr, &numfiles, false);

    qsort(pakfiles, numfiles, sizeof(char *), paksort);

    if (fs_numServerPaks)
    {
        numdirs = 0;
        pakdirs = nullptr;
    }
    else
    {
        // Get top level directories (we'll filter them later since the Sys_ListFiles filtering is
        // terrible)
        pakdirs = Sys_ListFiles(curpath, "/", nullptr, &numdirs, false);
        qsort(pakdirs, numdirs, sizeof(char *), paksort);
    }

    char prefixBuf[MAX_STRING_CHARS];
    Q_strncpyz(prefixBuf, Cvar_VariableString("fs_pk3PrefixPairs"), sizeof(prefixBuf));
    int numPairs = 0;

    char *p = prefixBuf;
    if (!p[0]) p = nullptr;

    const char *prefixes[10][2];
    while (p)
    {
        prefixes[numPairs][0] = p;
        p = strchr(p, '&');
        if (!p)
        {
            Com_Printf(S_COLOR_YELLOW "WARNING: fs_pk3PrefixPairs ends with an incomplete pair\n");
            break;
        }
        lengths[numPairs][0] = (int)(p - prefixes[numPairs][0]);
        *p++ = '\0';
        prefixes[numPairs][1] = p;
        p = strchr(p, '|');
        if (p)
        {
            lengths[numPairs][1] = (int)(p - prefixes[numPairs][1]);
            *p++ = '\0';
        }
        else
        {
            lengths[numPairs][1] = (int)strlen(prefixes[numPairs][1]);
        }
        if (lengths[numPairs][0] == 0 && lengths[numPairs][1] == 0)
        {
            Com_Printf(S_COLOR_YELLOW
                "WARNING: fs_pk3PrefixPairs contains a null-null pair, "
                "skipping this pair\n");
            continue;
        }
        if (lengths[numPairs][0] != 0 && lengths[numPairs][1] != 0 &&
            !Q_stricmpn(prefixes[numPairs][0], prefixes[numPairs][1],
                MIN(lengths[numPairs][0], lengths[numPairs][1])))
        {
            Com_Printf(S_COLOR_YELLOW
                "WARNING: in fs_pk3PrefixPairs, one of '%s' and '%s' is a real prefix "
                "of the other, skipping this pair\n",
                prefixes[numPairs][0], prefixes[numPairs][1]);

            continue;
        }
        ++numPairs;
    }
    searchpath_t *otherSearchpaths = fs_searchpaths;

    pakfilesi = 0;
    pakdirsi = 0;

    while ((pakfilesi < numfiles) || (pakdirsi < numdirs))
    {
        bool pakwhich;
        // Check if a pakfile or pakdir comes next
        if (pakfilesi >= numfiles)
        {
            pakwhich = false;  // We've used all the pak files, it must be a pak directory.
        }
        else if (pakdirsi >= numdirs)
        {
            pakwhich = true;  // We've used all the pak directories, it must be a pak file.
        }
        else
        {
            // Could be either, compare to see which name comes first
            // Need tmp variables for appropriate indirection for paksort()
            pakfilestmp = &pakfiles[pakfilesi];
            pakdirstmp = &pakdirs[pakdirsi];
            pakwhich = (paksort(pakfilestmp, pakdirstmp) < 0);
        }

        if (pakwhich)
        {
            // The next .pk3 file is before the next .pk3dir
            char *pakfile = FS_BuildOSPath(path, dir, pakfiles[pakfilesi]);
            if ((pak = FS_LoadZipFile(pakfile, pakfiles[pakfilesi])) == 0)
            {
                // This isn't a .pk3! Next!
                pakfilesi++;
                continue;
            }

            Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
            // store the game name for downloading
            Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));

            fs_packFiles += pak->numfiles;

            searchpath_t *search = static_cast<searchpath_t *>(Z_Malloc(sizeof(searchpath_t)));
            search->pack = pak;
            search->next = fs_searchpaths;
            fs_searchpaths = search;

            pak->onlyPrimary = false;
            pak->onlyAlternate = false;
            for (int i = 0; i < numPairs; ++i)
            {
                if (lengths[i][0] && !Q_stricmpn(pak->pakBasename, prefixes[i][0], lengths[i][0]))
                {
                    pak->onlyPrimary = true;
                    break;
                }
                else if (lengths[i][1] &&
                         !Q_stricmpn(pak->pakBasename, prefixes[i][1], lengths[i][1]))
                {
                    pak->onlyAlternate = true;
                    break;
                }
            }

            pak->primaryVersion = nullptr;
            pakfilesi++;
        }
        else
        {
            // The next .pk3dir is before the next .pk3 file
            // But wait, this could be any directory, we're filtering to only ending with ".pk3dir"
            // here.
            int len = strlen(pakdirs[pakdirsi]);
            if (!FS_IsExt(pakdirs[pakdirsi], ".pk3dir", len))
            {
                // This isn't a .pk3dir! Next!
                pakdirsi++;
                continue;
            }

            char *pakfile = FS_BuildOSPath(path, dir, pakdirs[pakdirsi]);

            // add the directory to the search path
            searchpath_t *search = static_cast<searchpath_t *>(Z_Malloc(sizeof(searchpath_t)));
            search->dir = static_cast<directory_t *>(Z_Malloc(sizeof(*search->dir)));

            Q_strncpyz(search->dir->path, curpath, sizeof(search->dir->path));  // c:\quake3\baseq3
            Q_strncpyz(search->dir->fullpath, pakfile,
                sizeof(search->dir->fullpath));  // c:\quake3\baseq3\mypak.pk3dir
            Q_strncpyz(search->dir->gamedir, pakdirs[pakdirsi],
                sizeof(search->dir->gamedir));  // mypak.pk3dir

            search->next = fs_searchpaths;
            fs_searchpaths = search;

            pakdirsi++;
        }
    }

    // done
    Sys_FreeFileList(pakfiles);
    Sys_FreeFileList(pakdirs);

    if (numPairs > 0)
    {
        int bnlengths[2];
        for (searchpath_t *search = fs_searchpaths; search != otherSearchpaths;
             search = search->next)
        {
            if (!(search->pack && search->pack->onlyPrimary))
            {
                continue;
            }

            bnlengths[0] = (int)strlen(search->pack->pakBasename);
            for (searchpath_t *srch = fs_searchpaths; srch != otherSearchpaths; srch = srch->next)
            {
                if (!(srch->pack && srch->pack->onlyAlternate))
                {
                    continue;
                }

                bnlengths[1] = (int)strlen(srch->pack->pakBasename);
                for (int i = 0; i < numPairs; ++i)
                {
                    if (lengths[i][0] && lengths[i][1] && bnlengths[0] >= lengths[i][0] &&
                        bnlengths[1] >= lengths[i][1] &&
                        !Q_stricmp(search->pack->pakBasename + lengths[i][0],
                            srch->pack->pakBasename + lengths[i][1]))
                    {
                        srch->pack->primaryVersion = search->pack;
                        break;
                    }
                }
            }
        }
    }

    //
    // add the directory to the search path
    //
    searchpath_t *search = static_cast<searchpath_t *>(Z_Malloc(sizeof(searchpath_t)));
    search->dir = static_cast<directory_t *>(Z_Malloc(sizeof(*search->dir)));

    Q_strncpyz(search->dir->path, path, sizeof(search->dir->path));
    Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath));
    Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir));

    search->next = fs_searchpaths;
    fs_searchpaths = search;
}

/*
================
FS_CheckDirTraversal

Check whether the string contains stuff like "../" to prevent directory traversal bugs
and return true if it does.
================
*/

bool FS_CheckDirTraversal(const char *checkdir)
{
    if (strstr(checkdir, "../") || strstr(checkdir, "..\\")) return true;

    return false;
}

/*
================
FS_ComparePaks

----------------
dlstring == true

Returns a list of pak files that we should download from the server. They all get stored
in the current gamedir and an FS_Restart will be fired up after we download them all.

The string is the format:

@remotename@localname [repeat]

static int		fs_numServerReferencedPaks;
static int		fs_serverReferencedPaks[MAX_SEARCH_PATHS];
static char		*fs_serverReferencedPakNames[MAX_SEARCH_PATHS];

----------------
dlstring == false

we are not interested in a download string format, we want something human-readable
(this is used for diagnostics while connecting to a pure server)

================
*/
bool FS_ComparePaks(char *neededpaks, int len, bool dlstring)
{
    if (!fs_numServerReferencedPaks)
    {
        return false;  // Server didn't send any pack information along
    }

    char *origpos = neededpaks;
    *neededpaks = '\0';

    bool havepak = false;
    for (int i = 0; i < fs_numServerReferencedPaks; i++)
    {
        // Ok, see if we have this pak file
        havepak = false;

        // Make sure the server cannot make us write to non-quake3 directories.
        if (FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
        {
            Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
            continue;
        }

        for (searchpath_t *sp = fs_searchpaths; sp; sp = sp->next)
        {
            if (sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i])
            {
                havepak = true;  // This is it!
                break;
            }
        }

        if (!havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i])
        {
            // Don't got it
            if (dlstring)
            {
                // We need this to make sure we won't hit the end of the buffer or the server could
                // overwrite non-pk3 files on clients by writing so much crap into neededpaks that
                // Q_strcat cuts off the .pk3 extension.

                origpos += strlen(origpos);

                // Remote name
                Q_strcat(neededpaks, len, "@");
                Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]);
                Q_strcat(neededpaks, len, ".pk3");

                // Local name
                Q_strcat(neededpaks, len, "@");
                // Do we have one with the same name?
                if (FS_SV_FileExists(va("%s.pk3", fs_serverReferencedPakNames[i])))
                {
                    char st[MAX_ZPATH];
                    // We already have one called this, we need to download it to another name
                    // Make something up with the checksum in it
                    Com_sprintf(st, sizeof(st), "%s.%08x.pk3", fs_serverReferencedPakNames[i],
                        fs_serverReferencedPaks[i]);
                    Q_strcat(neededpaks, len, st);
                }
                else
                {
                    Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]);
                    Q_strcat(neededpaks, len, ".pk3");
                }

                // Find out whether it might have overflowed the buffer and don't add this file to
                // the
                // list if that is the case.
                if (strlen(origpos) + (origpos - neededpaks) >= (len - 1))
                {
                    *origpos = '\0';
                    break;
                }
            }
            else
            {
                Q_strcat(neededpaks, len, fs_serverReferencedPakNames[i]);
                Q_strcat(neededpaks, len, ".pk3");
                // Do we have one with the same name?
                if (FS_SV_FileExists(va("%s.pk3", fs_serverReferencedPakNames[i])))
                {
                    Q_strcat(neededpaks, len, " (local file exists with wrong checksum)");
                }
                Q_strcat(neededpaks, len, "\n");
            }
        }
    }

    if (*neededpaks)
    {
        return true;
    }

    return false;  // We have them all
}

/*
================
FS_Shutdown

Frees all resources.
================
*/

void FS_Shutdown(bool closemfp)
{
    for (int i = 0; i < MAX_FILE_HANDLES; i++)
    {
        if (fsh[i].fileSize) FS_FCloseFile(i);
    }

    searchpath_t *next;
    // free everything
    for (auto p = fs_searchpaths; p; p = next)
    {
        next = p->next;
        if (p->pack) FS_FreePak(p->pack);
        if (p->dir) Z_Free(p->dir);
        Z_Free(p);
    }

    // Any FS_ calls will now be an error until reinitialized
    fs_searchpaths = nullptr;

    Cmd_RemoveCommand("path");
    Cmd_RemoveCommand("dir");
    Cmd_RemoveCommand("fdir");
    Cmd_RemoveCommand("touchFile");
    Cmd_RemoveCommand("which");

#ifdef FS_MISSING
    if (closemfp)
    {
        fclose(missingFiles);
    }
#endif
}

/*
================
FS_ReorderPurePaks
NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
  this can lead to misleading situations, see
https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
================
*/
static void FS_ReorderPurePaks(void)
{
    // do this before fs_numServerPaks check?
    fs_reordered = false;

    // only relevant when connected to pure server
    if (!fs_numServerPaks) return;

    // we insert in order at the beginning of the list
    auto p_insert_index = &fs_searchpaths;
    for (int i = 0; i < fs_numServerPaks; i++)
    {
        // track the pointer-to-current-item
        auto p_previous = p_insert_index;
        for (auto s = *p_insert_index; s; s = s->next)
        {
            // the part of the list before p_insert_index has been sorted already
            if (s->pack && fs_serverPaks[i] == s->pack->checksum)
            {
                fs_reordered = true;

                // move this element to the insert list
                *p_previous = s->next;
                s->next = *p_insert_index;
                *p_insert_index = s;

                // increment insert list
                p_insert_index = &s->next;

                // iterate to next server pack
                break;
            }
            p_previous = &s->next;
        }
    }
}

/*
================
FS_Startup
================
*/
static void FS_Startup(const char *gameName)
{
    Com_Printf("----- FS_Startup -----\n");
    fs_packFiles = 0;

    fs_debug = Cvar_Get("fs_debug", "0", 0);
    Cvar_Get ("fs_overpath", Sys_BinaryPath(), CVAR_INIT|CVAR_PROTECTED );
    fs_basepath = Cvar_Get("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT | CVAR_PROTECTED);
    fs_basegame = Cvar_Get("fs_basegame", BASEGAME, CVAR_INIT);

    const char *homePath = Sys_DefaultHomePath();
    if (!homePath || !homePath[0])
    {
        homePath = fs_basepath->string;
    }

    fs_homepath = Cvar_Get("fs_homepath", homePath, CVAR_INIT | CVAR_PROTECTED);
    fs_gamedirvar = Cvar_Get("fs_game", BASEGAME, CVAR_INIT | CVAR_SYSTEMINFO);

#ifdef DEDICATED
    // add search path elements in reverse priority order
    if (fs_basepath->string[0])
        FS_AddGameDirectory(fs_basepath->string, gameName);

    // NOTE: same filtering below for mods and basegame
    if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string))
    {
        FS_CreatePath(fs_homepath->string);
        FS_AddGameDirectory(fs_homepath->string, gameName);
    }

    // check for additional base game so mods can be based upon other mods
    if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) )
    {
        if (fs_basepath->string[0])
            FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
        if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string))
            FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
    }

    // check for additional game folder for mods
    if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) )
    {
        if (fs_basepath->string[0])
            FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
        if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string,fs_basepath->string))
            FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
    }

#else

    // add search path elements in reverse priority order
    if (fs_basepath->string[0])
    {
        FS_AddGameDirectory(fs_basepath->string, "base");
    }

#ifdef __APPLE__
    // Make MacOSX also include the base path included with the .app bundle
    fs_apppath = Cvar_Get("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT | CVAR_PROTECTED);
    if (fs_apppath->string[0])
    {
        FS_AddGameDirectory(fs_apppath->string, "base");
    }
#endif

    // NOTE: same filtering below for mods and basegame
    if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string))
    {
        FS_CreatePath(fs_homepath->string);
        FS_AddGameDirectory(fs_homepath->string, "base");
    }

    // check for additional base game so mods can be based upon other mods
    if (fs_basegame->string[0] && Q_stricmp(fs_basegame->string, gameName))
    {
        if (fs_basepath->string[0])
            FS_AddGameDirectory(fs_basepath->string, fs_basegame->string);
        if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string))
            FS_AddGameDirectory(fs_homepath->string, fs_basegame->string);
    }

    // check for additional game folder for mods
    if (fs_gamedirvar->string[0] && Q_stricmp(fs_gamedirvar->string, gameName))
    {
        if (fs_basepath->string[0])
            FS_AddGameDirectory(fs_basepath->string, fs_gamedirvar->string);
        if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string))
            FS_AddGameDirectory(fs_homepath->string, fs_gamedirvar->string);
    }

    // NOTE: same filtering below for mods and basegame
    if (fs_homepath->string[0] && Q_stricmp(fs_homepath->string, fs_basepath->string))
    {
        FS_CreatePath(fs_homepath->string);
        FS_AddGameDirectory(fs_homepath->string, gameName);
    }

    // add search path elements in reverse priority order
    if (fs_basepath->string[0])
    {
        FS_AddGameDirectory(fs_basepath->string, gameName);
    }

#ifdef __APPLE__
    // Make MacOSX also include the base path included with the .app bundle
    fs_apppath = Cvar_Get("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT | CVAR_PROTECTED);
    if (fs_apppath->string[0])
    {
        FS_AddGameDirectory(fs_apppath->string, gameName);
    }
#endif
#endif

    // add our commands
    Cmd_AddCommand("path", FS_Path_f);
    Cmd_AddCommand("dir", FS_Dir_f);
    Cmd_AddCommand("fdir", FS_NewDir_f);
    Cmd_AddCommand("touchFile", FS_TouchFile_f);
    Cmd_AddCommand("which", FS_Which_f);

    // reorder the pure pk3 files according to server order
    FS_ReorderPurePaks();

    // print the current search paths
    FS_Path_f();

    // We just loaded, it's not modified
    fs_gamedirvar->modified = false;

    Com_Printf("----------------------\n");

#ifdef FS_MISSING
    if (missingFiles == nullptr)
    {
        missingFiles = Sys_FOpen("\\missing.txt", "ab");
    }
#endif

    Com_Printf("%d files in pk3 files\n", fs_packFiles);
}

/*
=====================
FS_LoadedPakChecksums

Returns a space separated string containing the checksums of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakChecksums(bool alternate)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (!search->pack) continue;
        if ((alternate && search->pack->onlyPrimary) || (!alternate && search->pack->onlyAlternate))
            continue;
        Q_strcat(info, sizeof(info), va("%i ", search->pack->checksum));
    }

    return info;
}

/*
=====================
FS_LoadedPakNames

Returns a space separated string containing the names of all loaded pk3 files.
Servers with sv_pure set will get this string and pass it to clients.
=====================
*/
const char *FS_LoadedPakNames(bool alternate)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (!search->pack) continue;
        if ((alternate && search->pack->onlyPrimary) || (!alternate && search->pack->onlyAlternate))
            continue;
        if (info[0]) Q_strcat(info, sizeof(info), " ");
        Q_strcat(info, sizeof(info), search->pack->pakBasename);
    }

    return info;
}

/*
=====================
FS_LoadedPakPureChecksums

Returns a space separated string containing the pure checksums of all loaded pk3 files.
Servers with sv_pure use these checksums to compare with the checksums the clients send
back to the server.
=====================
*/
const char *FS_LoadedPakPureChecksums(bool alternate)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (!search->pack) continue;
        if ((alternate && search->pack->onlyPrimary) || (!alternate && search->pack->onlyAlternate))
            continue;
        Q_strcat(info, sizeof(info), va("%i ", search->pack->pure_checksum));
    }

    return info;
}

/*
=====================
FS_ReferencedPakChecksums

Returns a space separated string containing the checksums of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakChecksums(bool alternate)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (search->pack)
        {
            if ((alternate and search->pack->onlyPrimary) or
                (!alternate and search->pack->onlyAlternate))
                continue;

            if (search->pack->referenced or
                (search->pack->primaryVersion and search->pack->primaryVersion->referenced) or
                (*fs_gamedirvar->string and Q_stricmp(fs_gamedirvar->string, BASEGAME) and
                    Q_stricmp(search->pack->pakGamename, fs_gamedirvar->string) == 0))
            {
                Q_strcat(info, sizeof(info), va("%i ", search->pack->checksum));
            }
        }
    }

    return info;
}

/*
=====================
FS_ReferencedPakPureChecksums

Returns a space separated string containing the pure checksums of all referenced pk3 files.
Servers with sv_pure set will get this string back from clients for pure validation

The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
=====================
*/
const char *FS_ReferencedPakPureChecksums(void)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    int checksum = fs_checksumFeed;
    int numPaks = 0;
    for (int nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1)
    {
        if (nFlags & FS_GENERAL_REF)
        {
            // add a delimter between must haves and general refs
            // Q_strcat(info, sizeof(info), "@ ");
            info[strlen(info) + 1] = '\0';
            info[strlen(info) + 2] = '\0';
            info[strlen(info)] = '@';
            info[strlen(info)] = ' ';
        }
        for (auto search = fs_searchpaths; search; search = search->next)
        {
            // is the element a pak file and has it been referenced based on flag?
            if (search->pack && (search->pack->referenced & nFlags))
            {
                Q_strcat(info, sizeof(info), va("%i ", search->pack->pure_checksum));
                if (nFlags & (FS_CGAME_REF | FS_UI_REF)) break;

                checksum ^= search->pack->pure_checksum;
                numPaks++;
            }
        }
    }
    // last checksum is the encoded number of referenced pk3s
    checksum ^= numPaks;
    Q_strcat(info, sizeof(info), va("%i ", checksum));

    return info;
}

/*
=====================
FS_ReferencedPakNames

Returns a space separated string containing the names of all referenced pk3 files.
The server will send this to the clients so they can check which files should be auto-downloaded.
=====================
*/
const char *FS_ReferencedPakNames(bool alternate)
{
    static char info[BIG_INFO_STRING];
    info[0] = 0;

    // we want to return ALL pk3's from the fs_game path
    // and referenced one's from base
    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file?
        if (search->pack)
        {
            if ((alternate && search->pack->onlyPrimary) ||
                (!alternate && search->pack->onlyAlternate))
                continue;

            if (search->pack->referenced ||
                (search->pack->primaryVersion && search->pack->primaryVersion->referenced) ||
                (fs_gamedirvar->string[0] && Q_stricmp(fs_gamedirvar->string, BASEGAME) &&
                    !Q_stricmp(search->pack->pakGamename, fs_gamedirvar->string)))
            {
                if (*info) Q_strcat(info, sizeof(info), " ");

                Q_strcat(info, sizeof(info), search->pack->pakGamename);
                Q_strcat(info, sizeof(info), "/");
                Q_strcat(info, sizeof(info), search->pack->pakBasename);
            }
        }
    }

    return info;
}

/*
=====================
FS_ClearPakReferences
=====================
*/
void FS_ClearPakReferences(int flags)
{
    if (!flags) flags = -1;

    for (auto search = fs_searchpaths; search; search = search->next)
    {
        // is the element a pak file and has it been referenced?
        if (search->pack) search->pack->referenced &= ~flags;
    }
}

/*
=====================
FS_PureServerSetLoadedPaks

If the string is empty, all data sources will be allowed.
If not empty, only pk3 files that match one of the space
separated checksums will be checked for files, with the
exception of .cfg and .dat files.
=====================
*/
void FS_PureServerSetLoadedPaks(const char *pakSums, const char *pakNames)
{
    Cmd_TokenizeString(pakSums);

    int c = Cmd_Argc();
    if (c > MAX_SEARCH_PATHS) c = MAX_SEARCH_PATHS;

    fs_numServerPaks = c;

    for (int i = 0; i < c; i++) fs_serverPaks[i] = atoi(Cmd_Argv(i));

    if (fs_numServerPaks)
    {
        Com_DPrintf("Connected to a pure server.\n");
    }
    else if (fs_reordered)
    {
        // force a restart to make sure the search order will be correct
        Com_DPrintf("FS search reorder is required\n");
        FS_Restart(fs_checksumFeed);
        return;
    }

    for (int i = 0; i < c; i++)
    {
        if (fs_serverPakNames[i]) Z_Free(fs_serverPakNames[i]);
        fs_serverPakNames[i] = nullptr;
    }

    if (pakNames && pakNames[0])
    {
        Cmd_TokenizeString(pakNames);

        int d = Cmd_Argc();
        if (d > MAX_SEARCH_PATHS) d = MAX_SEARCH_PATHS;

        for (int i = 0; i < d; i++) fs_serverPakNames[i] = CopyString(Cmd_Argv(i));
    }
}

/*
=====================
FS_PureServerSetReferencedPaks

The checksums and names of the pk3 files referenced at the server
are sent to the client and stored here. The client will use these
checksums to see if any pk3 files need to be auto-downloaded.
=====================
*/
void FS_PureServerSetReferencedPaks(const char *pakSums, const char *pakNames)
{
    Cmd_TokenizeString(pakSums);

    unsigned c = Cmd_Argc();
    if (c > MAX_SEARCH_PATHS) c = MAX_SEARCH_PATHS;

    for (unsigned i = 0; i < c; i++) fs_serverReferencedPaks[i] = atoi(Cmd_Argv(i));

    for (unsigned i = 0; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
    {
        if (fs_serverReferencedPakNames[i]) Z_Free(fs_serverReferencedPakNames[i]);
        fs_serverReferencedPakNames[i] = nullptr;
    }

    unsigned d = 0;
    if (pakNames && *pakNames)
    {
        Cmd_TokenizeString(pakNames);

        d = Cmd_Argc();
        if (d > c) d = c;

        for (unsigned i = 0; i < d; i++) fs_serverReferencedPakNames[i] = CopyString(Cmd_Argv(i));
    }

    // ensure that there are as many checksums as there are pak names.
    if (d < c) c = d;

    fs_numServerReferencedPaks = c;
}

/*
================
FS_InitFilesystem

Called only at inital startup, not when the filesystem
is resetting due to a game change
================
*/
void FS_InitFilesystem(void)
{
    // allow command line parms to override our defaults
    // we have to specially handle this, because normal command
    // line variable sets don't happen until after the filesystem
    // has already been initialized
    Com_StartupVariable("fs_overpath");
    Com_StartupVariable("fs_basepath");
    Com_StartupVariable("fs_homepath");
    Com_StartupVariable("fs_game");
    Com_StartupVariable("fs_pk3PrefixPairs");

    if (!FS_FilenameCompare(Cvar_VariableString("fs_game"), BASEGAME)) Cvar_Set("fs_game", "");

    // try to start up normally
    FS_Startup(BASEGAME);

    // if we can't find default.cfg, assume that the paths are
    // busted and error out now, rather than getting an unreadable
    // graphics screen when the font fails to load
    if (FS_ReadFile("default.cfg", nullptr) <= 0)
    {
        Com_Error(ERR_FATAL, "Couldn't load default.cfg");
    }

    Q_strncpyz(lastValidBase, fs_basegame->string, sizeof(lastValidBase));
    Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}

/*
================
FS_Restart
================
*/
void FS_Restart(int checksumFeed)
{
    // free anything we currently have loaded
    FS_Shutdown(false);

    // set the checksum feed
    fs_checksumFeed = checksumFeed;

    // clear pak references
    FS_ClearPakReferences(0);

    // try to start up normally
    FS_Startup(BASEGAME);

    // if we can't find default.cfg, assume that the paths are
    // busted and error out now, rather than getting an unreadable
    // graphics screen when the font fails to load
    if (FS_ReadFile("default.cfg", nullptr) <= 0)
    {
        // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
        // (for instance a TA demo server)
        if (lastValidBase[0])
        {
            FS_PureServerSetLoadedPaks("", "");
            Cvar_Set("fs_basegame", lastValidBase);
            Cvar_Set("fs_game", lastValidGame);
            lastValidBase[0] = lastValidGame[0] = '\0';
            FS_Restart(checksumFeed);
            Com_Error(ERR_DROP, "Invalid game folder");
            return;
        }
        Com_Error(ERR_FATAL, "Couldn't load default.cfg");
    }

    if (Q_stricmp(fs_gamedirvar->string, lastValidGame))
    {
        // skip the autogen.cfg if "safe" is on the command line
        if (!Com_SafeMode())
        {
            Cbuf_AddText("exec " Q3CONFIG_CFG "\n");
        }
    }

    Q_strncpyz(lastValidBase, fs_basegame->string, sizeof(lastValidBase));
    Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
}

/*
=================
FS_ConditionalRestart

Restart if necessary
Return true if restarting due to game directory changed, false otherwise
=================
*/
bool FS_ConditionalRestart(int checksumFeed, bool disconnect)
{
    if (fs_gamedirvar->modified)
    {
        if (FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
            (*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, BASEGAME)) &&
            (*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, BASEGAME)))
        {
            Com_GameRestart(checksumFeed, disconnect);
            return true;
        }
        fs_gamedirvar->modified = false;
    }

    if (checksumFeed != fs_checksumFeed)
        FS_Restart(checksumFeed);

    else if (fs_numServerPaks && !fs_reordered)
        FS_ReorderPurePaks();

    return false;
}

/*
========================================================================================

Handle based file calls for virtual machines

========================================================================================
*/

int FS_FOpenFileByMode(const char *qpath, fileHandle_t *f, enum FS_Mode mode)
{
    int r;
    bool sync = false;

    switch (mode)
    {
        case FS_READ:
            r = FS_FOpenFileRead(qpath, f, true);
            break;

        case FS_WRITE:
            *f = FS_FOpenFileWrite(qpath);
            r = 0;
            if (*f == 0) r = -1;
            break;

        case FS_APPEND_SYNC:
            sync = true;
        // fall through

        case FS_APPEND:
            *f = FS_FOpenFileAppend(qpath);
            r = 0;
            if (*f == 0) r = -1;
            break;

        default:
            Com_Error(ERR_FATAL, "FS_FOpenFileByMode: bad mode");
            return -1;
    }

    if (!f) return r;

    if (*f)
    {
        fsh[*f].fileSize = r;
    }
    fsh[*f].handleSync = sync;

    return r;
}

int FS_FTell(fileHandle_t f)
{
    if (fsh[f].zipFile == true) return unztell(fsh[f].handleFiles.file.z);
    return ftell(fsh[f].handleFiles.file.o);
}

void FS_Flush(fileHandle_t f)
{
    fflush(fsh[f].handleFiles.file.o);
}

void FS_FilenameCompletion(const char *dir, const char *ext, bool stripExt,
    void (*callback)(const char *s), bool allowNonPureFilesOnDisk)
{
    int nfiles;
    char filename[MAX_STRING_CHARS];
    char **filenames = FS_ListFilteredFiles(dir, ext, nullptr, &nfiles, allowNonPureFilesOnDisk);

    FS_SortFileList(filenames, nfiles);

    for (int i = 0; i < nfiles; i++)
    {
        FS_ConvertPath(filenames[i]);
        Q_strncpyz(filename, filenames[i], MAX_STRING_CHARS);
        if (stripExt) COM_StripExtension(filename, filename, sizeof(filename));
        callback(filename);
    }
    FS_FreeFileList(filenames);
}

const char *FS_GetCurrentGameDir(void)
{
    if (fs_gamedirvar->string[0]) return fs_gamedirvar->string;
    return BASEGAME;
}