File: game.cpp

package info (click to toggle)
postal1 2015.git20250526%2Bds-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 14,024 kB
  • sloc: cpp: 130,877; ansic: 38,942; python: 874; makefile: 351; sh: 61
file content (4837 lines) | stat: -rw-r--r-- 158,315 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// game.cpp
// Project: Postal
//
// This module deals with the high-level aspects of setting up and running the
// game.
//
// History:
//		11/19/96 MJR	Started.
//		01/15/96 MJR	Added GamePath()
//
//		01/28/97	JMI	Added calls to MenuTrans API (a PalTran).
//
//		01/30/97	MJR	Fixed bug in CorrectifyPath() that accidentally truncated
//							the passed-in string.
//
//		01/31/97	JMI	Now uses FullPath() to get full path for filespecs.
//
//		01/31/97	JMI	Added g_resmgrGame for specific to actual game data.
//
//		01/31/97	JMI	Number of title loops done on start up is now gotten from
//							INI file.
//
//		02/02/97	JMI	Now calls StartTitle() and EndTitle() after launching an
//							edit session, a user game, or a demo game.
//
//		02/02/97	JMI	Now, before exiting, makes sure all samples are done 
//							playing.
//
//		02/03/97	JMI	Changed DoMenu() called to new DoMenuInput() and 
//							DoMenuOutput() calls.
//
//		02/03/97	JMI	Now sets the base path for g_resmgrGame, Shell, & Menus.
//
//		02/04/97	JMI	Added functions to get and set the gamma level.
//
//		02/04/97	JMI	Changed LoadDib() call to Load() (which now supports
//							loading of DIBs).
//
//		02/13/97	JMI	Removed game level alpha XRay stuff (now setup in CHood).
//
//		02/18/97	JMI	Now opens SampleMaster's SAK file.
//
//		03/06/97	JMI	Made PalTranOn() and PalTranOff() extern instead of inline.
//
//		03/17/97	JMI	Made PalTranOff() abortable via a keypress.  Put in the
//							shape of the code for aborting via a key in PalTranOn() but
//							there is currently no interface to MenuTrans to allow this
//							type of abort (or jump).
//
//		03/28/97	JMI	Un#if 0'd the SavePrefs() call.
//
//		03/28/97	JMI	Now stores and resets the current dir.
//
//		04/11/97	JMI	Added Game_Menu_Demo() externally callable function to
//							start the demo.
//
//		04/14/97	JMI	Now specifies which image for StartTitle() to start with.
//
//		04/14/97	JMI	Missed a spot in the previous change.
//
//		04/16/97 MJR	Added simple test of file paths.  Also changed it so that
//							preferences are always saved, even if the game encounters
//							an error beforehand.
//
//							Fixed the simple test of file paths to actual use the
//							file path!!!
//
//		04/17/97 MJR	Put the test for the CD path back in.
//
//		04/22/97	JMI	No longer uses chdir().
//
//		04/22/97	JMI	Now sets g_GameSettings.m_sServer and 
//							g_GameSettings.m_sClient to 0 before running the demo.
//
//		04/24/97	JMI	Currently, aborting the PalTranOff() is a bad idea, so
//							we don't allow it (until we support EndMenuTrans(TRUE) ).
//
//		05/06/97	JMI	Now uses a Gamma multiplier to define a line instead of
//							the exponent defining the curve.
//
//		05/07/97	JMI	Now uses a Gamma exponent and uses the 'Gamma Val' as a
//							constant multiplier:
//							MappedColorVal	= (colorVal ^ GAMMA_EXPONENT) * GammaVal
//
//		05/21/97	JMI	Added a resource manager for resources that are not SAKed.
//
//		05/23/97	JMI	Added a CloseSaks() which closes and purges the SAKs.
//							This solves the problem with the ASSERTions about the logic
//							vars (the RResmgr's were declared at file scope as were the
//							CLogTabVars so it was just a matter of order of destruction
//							that dictated whether the ASSERTions occurred).
//
//		06/03/97	JMI	Commented out error message for read-only prefs file.
//
//		06/03/97	JMI	Now uses g_GameSettings members for demo timeouts instead
//							of the DEMO_TIMEOUT macro.
//
//		06/04/97	JMI	Added conditionally compiled message instead of editor
//							when editor is requested from the menu.
//							Also, now StartTitle() calls within GameLoop() request the
//							last title page.
//
//		06/04/97	JMI	Added AbortAllSamples() call when exitting.
//
//		06/04/97	JMI	Added MUST_BE_ON_CD, EDITOR_DISABLED, and CHECK_FOR_COOKIE 
//							conditional compilation macros and added a check for a 
//							specific U32 in the COOKIE file.
//
//		06/12/97 MJR	Reworked the callbacks so that the game-specific code now
//							resides in this module rather than the menu module.
//							Reworked the entire core loop so it passes all the
//							required parameters to Play() instead of using globals.
//							Moved all the demo and network setup stuff out of play.cpp
//							and into here.
//
//		06/15/97 MJR	More changes in terms of how Play() is called and what
//							this module does to get ready for calling it.
//							Also changed calls to rspDoSystem() into calls to Update().
//
//							Added required calls to DeleteInputDemoData().
//
//		06/15/97 MJR	Made use of new-and-improved input demo interface.
//							(But demo mode is still not working right...had to check
//							it in though to go along with changes in other files).
//
//		06/16/97 MJR	Fixed stupid error that caused demo record not to work.
//
//		06/16/97	JMI	Now passes destination buffer in StartMenu() call.
//
//		06/16/97	JMI	Added g_fontSmall.
//
//					MJR	Added make-a-demo-movie stuff for debugging demo mode
//							problems.
//
//					JMI	Now, based on INI setting g_GameSettings.m_sTrickySystemQuit,
//							we en/disable system quit status flags.
//
//					JMI	Changed "res/fonts/SmallSmash.fnt" to "res/fonts/SmSmash.fnt"
//
//		06/17/97 MJR	Modified CorrectifyBasePath() so it will change any
//							relative paths into absolute paths.  This, in turn, fixed
//							a problem whereby the loading of demo files failed because
//							it assumed the name of the demo file would begin with the
//							HD path.  This assumption normally worked, but failed when
//							the HD path was a relative path.
//
//		06/18/97 MJR	Added SeedRandom() and GetRandom().
//
//					MJR	Fixed bug in CorrectifyBasePath().  Now handles empty
//							paths (it ignores them).
//
//		06/24/97	JMI	Added SynchLog() debug mechanism.  See function comment for
//							functionality details.  See macros in game.h for usage via
//							macro(s).
//
//		06/24/97	JMI	Undefined CHECK_FOR_COOKIE.
//
//					JMI	Changed usage of strcmp to rspStricmp in GetRandom() and
//							SynchLog().
//
//		06/30/97 MJR	Changed client and server objects to use new/delete instead
//							of having them live on the stack.  They are very large,
//							and caused local (stack) data to exceed 32k on the mac.
//
//		07/03/97	JMI	Converted calls to rspOpen/SaveBox() to new parm 
//							conventions.
//
//		07/03/97	JMI	Added Game_ControlsMenu() and actions for editting input
//							settings for keys and mouse.
//
//		07/05/97 MJR	Changed to RSP_BLACK_INDEX instead of 0.
//
//		07/06/97	JMI	Changed ACTION_EDIT_MOUSE_SETTINGS and 
//							ACTION_EDIT_KEY_SETTINGS to ACTION_EDIT_INPUT_SETTINGS.
//							Also, now only one function is called no matter which type
//							of input settings are to be editted, EditInputSettings().
//
//		07/11/97 BRH	Finished up the expiration date checking for the 
//							Registry.  Still need to add something for the Mac
//							version.
//
//		07/11/97 BRH	Fixed typos causing the latest date not to be written to
//							the registry.
//
//		07/13/97	JMI	Now sets the appropriate base path or opens the approriate
//							SAK dependent on the current audio mode.
//
//		07/13/97	JMI	Added Game_StartChallengeGame() and an action for the
//							various challenge game types.
//
//		07/14/97 BRH	Changed calls to Play() to pass the challenge mode flag.
//							Fixed value in Get Registry in case of an error on
//							decrypt.
//
//		07/16/97 BRH	Made changes to the Mac expiration date code to normalize
//							the time to 1970 like the rest of the machines so that
//							the dates can be stored in 1 format.
//
//		07/16/97	JMI	Now uses real time when pausing on the titel screens (in-
//							stead of 'Load Loops').
//
//		07/17/97 BRH	Finished debugging the Mac Prefs file expiration date code.
//
//					MJR	Fixed sample rate problem on the mac.
//
//					BRH	Put in the real expiration date and a comment for the
//							real release date, and updated the current release date
//							to today so that we can still test it.
//
//		07/18/97 BRH	Added game load and save functions so that the player's
//							game can be saved and loaded.  Also added a global
//							stockpile object used to transfer loaded/saved info to/from
//							the CDude's stockpile.
//
//		07/19/97 MJR	Fixed bug where demo mode would start if user cancelled out
//							of a dialog after spending a long time there.
//							Also changed so demo mode will not start if app is in BG.
//
//		07/23/97 BRH	Changed calls to Title functions to use the new array of
//							title screen durations.	 
//
//		07/23/97 BRH	Changed expiration date display for PC back to asctime(gmtime())
//							since ctime didn't work correctly.
//
//		07/26/97	JMI	Added g_fontPostal to replace g_fontSmall.  Got rid of
//							g_fontSmall.
//
//		07/28/97	JMI	Now displays a different message for non-marketing 
//							releases.
//
//		08/01/97 BRH	Cycles through 3 demos rather than just 1. Also added
//							open dialog for playing demos so that the user can choose
//							which demo to play.
//
//		08/02/97	JMI	Now initializes the default RGuiItem font to g_fontBig in-
//							stead of relying on everybody who uses it to invidually set
//							it.
//
//		08/05/97	JMI	Added Game_AudioOptionsChoice().
//
//		08/06/97 MJR	Added socket startup/shutdown.
//
//		08/08/97 MJR	Background and foreground callbacks are now installed here
//							so they are in effect for the entire app.
//
//		08/08/97	JMI	Now passes parameter to start musak in title to 
//							StartTitle().
//
//		08/12/97	JMI	m_szDemoFile was FullPath()'ed twice so the demo wouldn't
//							load.  Fixed.
//
//		08/12/97	JMI	Added SubPathOpenBox() (see proto for details) and
//							FullPathCustom().
//
//		08/13/97 MJR	We now pass difficulty level to Play().
//
//		08/13/97	JMI	No longer remembers the previous demo file you recorded as
//							a patch to either improper usage or problem in 
//							SubPathOpenBox().
//
//		08/14/97	JMI	Added prealm parameter to Game_Save/LoadPlayersGame() so
//							they can query/modify realm settings/flags.
//							Also, changed questionable access on m_action in 
//							Game_SavePlayersGame() and Game_LoadPlayersGame() which 
//							were casting &m_action to a (short*) even though ACTION is
//							a 32 bit value.  May not have worked on the Mac although it
//							would for values less than 32767 and greater than 0 on the 
//							little endian PC.
//							Also, added an ACTION_LOAD_GAME so that could be part of
//							the main loop with the intent of making the loaded 
//							difficulty a local variable but this turned out to be error
//							prone with keeping this value up to date with the proper
//							value (either the INI difficulty or the loaded difficulty)
//							and it was annoying to determine which one to use on each
//							Play() call so I made a function that returns the 
//							appropriate value (but only once...ick).  If you feel like
//							it try it the other way, but be aware that on any iteration
//							g_GameSettings.m_sDifficulty may change via a menu.
//							Also, had to add a flag so one action can lead to another.
//							The main loop used to reset the action after every action
//							making it impossible for one action to lead to another.
//
//		08/15/97	JRD	Added a function to control brightness/contrast in place
//							of gamma.  This was because the gamma function could not
//							recreate a "normal palette."
//
//		08/15/97 JRD	Attempted to hook both brightness and contrast changes to
//							the old gamma slider with a crude algorithm.
//
//		08/18/97	JMI	Now allows ALT-F4 to drop you out of the title sequence.
//
//		08/18/97	JMI	In both debug and release modes, we were setting the do
//							system mode to sleep.  But we'd only restore it in release
//							mode which basically left us in sleep mode in debug mode.
//							Now restores it to TOLERATEOS in debug mode.
//
//		08/19/97 BRH	Uses the game settings m_sNumAvailableDemos to control the
//							demo loop rather than the set macro NUM_DEMO_FILES
//
//					MJR	Added support for new MP flags.
//
//		08/20/97	JMI	Modified Game_LoadPlayersGame() to receive the ptr to the
//							action to fill with the Player's saved action so the 
//							function would not have to use the global m_action.
//							Also, Moved Game_LoadPlayersGame() proto into game.cpp b/c
//							it now takes an ACTION* but ACTION is defined in game.cpp
//							and since no one currently calls this function externally,
//							what the hell.         
//
//		08/21/97 BRH	Changed the game sak to be loaded from the GAME_PATH_GAME
//							directory, getting it ready for the installation process.
//							Also changed the demos to HD path to make it easier for
//							people to load their own demos.  Changed the sound res
//							manager path to the GAME_PATH_SOUND for installation.                                       
//
//		08/21/97	JMI	Changed call to Update() to UpdateSystem() and occurrences
//							of rspUpdateDisplay() to UpdateDisplay().
//
//		08/22/97	JMI	Changed occurrences of UpdateDisplay() back to 
//							rspUpdateDisplay().  Now that we are using the lock 
//							functions correctly, we don't need them.
//							Also, removed rspLockBuffer() and rspUnlockBuffer() that
//							were used to encapsulate the entire app in a lock.
//
//		08/22/97 BRH	Changed the cookie position for use with a new smaller
//							res.sak file since we now have Direct X and more sound, 
//							we needed more space on the CD.
//
//		08/23/97	JMI	Now gets callbacks from the initialization and killing of
//							the main menu and stops any playing title/main-menu musak
//							when the main menu is killed.
//
//		08/24/97	JMI	Added a timeout to the abortion of playing samples just in
//							case there's a bug or a sound driver problem (no need to
//							to taunt infinite loopage).
//
//		08/25/97	JMI	Now sets the sound quality based on the current mode.
//							Also, now, if there's no sak dir and no sak for the current
//							audio mode, complains.
//
//		08/26/97 BRH	Merged in changes from a branched game.cpp which has the
//							special cases for the ending demo level of the game.  
//							Added a function GameEndingSequence which is called
//							when the global flag that indicates the player has won is
//							set.  It plays the demo file and then calls the 
//							Title_EndingSequence.
//
//		08/26/97	JMI	Now any menu can be restore in the GameCore() loop instead
//							of just the main menu by setting pmenuStart to point at the
//							menu to be next started.
//
//		08/30/97 BRH	Fixed the base path for the logic table resource manager
//							to load from the CD rather than the HD path.
//
//		09/02/97	JMI	Added a new option to the demo actions which plays one of
//							the factory preset demos.
//							Also, in the case that there were no factory preset demos
//							and the auto play demo kicked in, it would ASSERT that
//							the filename was "".
//
//		09/02/97	JMI	Now more deluxe control for regarding the starting of the
//							next menu after an action in GameCore().
//
//		09/03/97 BRH	Changed the g_resmgrRes logic table manager to load
//							from the HD path rather than the CD path, so that it
//							is easier to modify, add or change logics, especially
//							if we have to patch them in the future.
//
//		09/04/97	JMI	Now Game_ControlsMenu() only sets a new action if one is
//							not already set.  This keeps the controls menu from setting
//							the action when it is launched from Play.cpp instead of 
//							here.
//
//		09/05/97 PPL	In CorrectifyBasePath, made sure we allocate the buffer for the
//							full path instead of letting getcwd allocate it for us.  It's
//							not that we won't let it -- it's just that the Mac implementation
//							will not do it automatically as the PC implementation would.
//
//		09/05/97 PPL	Per Bill's directions, we will use the path from the CD for
//							the challenge level.
//
//		09/05/97 MJR	A few changes to use the new network stuff.
//
//		09/06/97 MJR	Now inits and kills the network problem GUI.
//
//		09/10/97 BRH	Had to change the res.sak in order to fit the MPlayer
//							and Heat setups on the CD, so I also had to change the
//							cookie.
//
//		09/10/97 MJR	Now properly converts paths from system to rspix format
//							on the start single player and start challenge level
//							dialogs.  This bug only showed up on the Mac.
//
//		09/11/97 BRH	Added different cookie and file position for 
//							COMP_USA_VERSION only.
//
//		09/11/97	JMI	Removed old code for PLAY_SPECIFIC_LEVEL_ONLY macro which
//							no longer exists.
//
//		09/12/97 MJR	Now more code doesn't compile when the editor is disabled,
//							in an attempt to make it harder to hack.
//
//		09/18/97	JMI	Added expiration message for
//							EXPIRATION_MSG_POSTAL_LAUNCH_WEEKEND compile condition.
//
//					JMI	Changed 'will expire on' to 'expires' so it sounds better
//							both past/future/etc tense wise and the 'on' didn't work
//							well with the format "Mon Sep 22 23:59:00" which contains
//							no 'at'.
//
//		09/24/97 BRH	For LOCALE != US version, took out the school yard demo
//							from the ending sequence.
//
//		09/29/97	JMI	Now will try to load any samples SAK in the case that there
//							is no audio mode, the specified mode's samples SAK is not
//							present, and there's no 'NoSak' dir specification.
//							If absolutely no samples SAK is found, a message is 
//							displayed that does not mention whether or not your 
//							hardware supports the specified mode.
//
//		10/01/97 BRH	Changed res.sak location so it would fit on the disk.
//
//		10/08/97	JMI	Made the synchronization logs opened and closed via one
//							set of two functions to make it easier to use them in
//							different scenarios.
//							Also, the logs should now only use the filename (excluding
//							the path) to make it possible for Mac vs. PC logs to be
//							compared.
//
//		10/10/97	JMI	Updated Game_ControlsMenu() to handle joystick option
//							when ALLOW_JOYSTICK is defined.
//
//		10/14/97	JMI	Made SynchLog()'s expr parameter a double instead of an int
//							for more accuracy.
//
//		10/15/97	JMI	Changed the %g used to fprintf() SynchLog() expr values
//							to %0.8f b/c the Mac and PC formats differed slightly.  The
//							Mac one often contains as many as four zeroes after the 
//							last significant decimal, sometimes less, and most of the
//							time none.  The PC never seems to put trailing zeroes.
//
//		10/16/97	JMI	Now mac demo basename is mdefault.dmo (instead of 
//							default.dmo) since the game plays slightly differently on
//							the Mac than on the PC.
//
//		10/22/97	JMI	In the call to Play() for recording demos, FullPathHD() was
//							being called on the passed in path but now that 
//							CRealm::Open() tries all the deluxe path stuff we don't
//							need that (and cannot use it b/c Open() does a conversion
//							to system path format as does FullPathHD() ).
//
//		11/20/97	JMI	Added cooperative flag to Play() calls.
//
//		12/01/97 BRH	Added flags for Add On levels to play calls, and
//							added ACTION_PLAY_ADDON as one of the options. 
//
//		12/04/97 BRH	Added Single player menu option to play add on levels
//							or original levels.
//
//		01/05/98	JMI	Now uses RMix::GetMode() to get sound quality.  Also, now
//							uses the source bits per sample (instead of the device
//							setting) to determine which sample resources to use.
//							Note that the quality is still set based on the device bits
//							per sample though so that the volumes could be tuned 
//							accordingly in SampleMaster's ms_asQualityCategoryAdjustors.
//
//		01/21/98	JMI	Now the foreground and background callbacks use a value,
//							INVALID_CURSOR_SHOW_LEVEL, to flag whether or not they're
//							in the background so they know which callbacks to ignore
//							and which one's to use.  I think that before (under DirectX)
//							we were getting more than one Backcall per Forecall and/or
//							vice-versa.
//
//		03/05/98 BRH	Now attempts to identify the PostalSD disc when the game
//							starts to clear up any confusion about which CD must be
//							in the drive to play the Add on Pack.  The Add on Pack
//							requires the original PostalCD in the drive, and it reads
//							the original res.sak file from that disc.  The PostalSD
//							disc also has a res.sak file on it, but its not the one
//							we want, and if someone tried to play the game with the
//							PostalSD disc in the drive rather than the PostalCD, then
//							the copy protection would flag it as invalid.  So an
//							additional check is now made and if the PostalSD disc
//							is in the drive, it will display a message to tell them
//							to put the PostalCD in the drive.  
//
//		06/04/98 BRH	Removed the demo timeout check from the SPAWN build since
//							the spawn version doesn't have any demo files available
//							it shouldn't try to run them when the user is idle.  It
//							was attempting to do so, and when it can't find a demo
//							file, a message box pops up which would cause much 
//							confusion to the user.
//
//		07/08/98	JMI	Removed extra Close() in checking for add on CD.  Also,
//							moved close that was in incorrect spot in check for add on
//							CD.  These were only annoying in Debug mode when it is
//							flagged.
//
//		09/27/99	JMI	Changed to allow ending sequence only in any locale 
//							satisfying the CompilerOptions macro VIOLENT_LOCALE.
//
//		10/07/99	JMI	Conditional remove Add On start menu option when in 
//							SUPER_POSTAL target.
//
//		10/11/99	JMI	Changed the audio sak name to be RATEjBITS instead of 
//							RATE_BITS to differentiate it from Orig & SD Postal sound
//							saks.
//
//		02/04/00 MJR	Added dialog box to prompt for original CD if 
//							PROMPT_FOR_ORIGINAL_CD is defined.
//
//					MJR	Changed so that it now checks the HD first and the VD
//							second when trying to load the shell sak.  This
//							was done to fix problems with the Japan Add On.
//
//		03/30/00 MJR	Changed to new macro for controlling the test for the
//							original Postal CD to differentiate it from the test for
//							a CD-ROM drive.
//
//							Added AUDIO_SAK_SEPARATOR_CHAR to make it easy to control
//							the separater character in audio sak filenames.
//
//		04/01/00 MJR	Fixed bug with AUDIO_SAK_SEPARATOR_CHAR.
//							Changed so in debug mode, it continues even if not on CD.
//
//		04/03/00 MJR	Modified MUST_BE_ON_CD code so that the test is bypassed if
//							the CD path is to our development server.  This allows
//							for easier testing.
//
//		06/24/01 MJR	Got rid of CompUSA cookie variation.  Also cleaned up a
//							few other macros.
//
////////////////////////////////////////////////////////////////////////////////

#include "RSPiX.h"

#include <time.h>
#ifdef WIN32
	#include <direct.h>
#else
	#include <unistd.h>
#endif

#include "WishPiX/Menu/menu.h"
#include "WishPiX/Prefs/prefs.h"
#include "WishPiX/ResourceManager/resmgr.h"

#include "main.h"
#include "menus.h"
#include "game.h"
#include "localize.h"
#include "play.h"
#include "title.h"
#include "credits.h"
#include "scene.h"
#include "update.h"
#include "gameedit.h"
#include "MenuTrans.h"
#include "SampleMaster.h"
#include "net.h"
#include "NetDlg.h"
#include "input.h"
#include "InputSettingsDlg.h"
#include "encrypt.h"
#include "credits.h"

#include "CompileOptions.h"

////////////////////////////////////////////////////////////////////////////////
// Macros/types/etc.
////////////////////////////////////////////////////////////////////////////////

// Total units required for loading during title sequence (estimated)
#define TITLE_LOAD_UNITS				5000

// TEMPORARY!  Determines how long the fake title sequence load will take.
// Remove this when there's real stuff being loaded.
#define TEMP_TITLE_LOOPS				500
#define TEMP_TITLE_TIME_PER_LOOP		10		// 100 looks normal, 10 goes extremely quickly

// Font stuff
#define BIG_FONT_FILE					"res/fonts/system1.fnt"
#define POSTAL_FONT_FILE				"res/fonts/smash.fnt"
#define FONT_HEIGHT						12						// "Best" for ComicB.
#define FONT_FORE_INDEX					255					// White or black.
#define FONT_BACK_INDEX					0						// Transparent.

#define NORMAL_PAL_TRAN_TIME			750

#define TEMP_ALPHA_EFFECT				"2dEffects/alpha00.bmp"

#define SHELL_SAK_FILENAME				"res/shell/shell.sak"
#define GAME_SAK_FILENAME				"res/game/game.sak"
#define SAMPLES_SAK_SUBDIR				"res/game/"
#define CUTSCENE_SAK_FILENAME_FRMT	"res/cutscene/cutscene%02d.sak"

// Since the game plays slightly differently on the PC than on the Mac,
// we'll have two different sets of demos.
#define DEFAULT_DEMO_PREFIX			"res/demos/default"
#define DEFAULT_DEMO_SUFFIX			".dmo"
#define DEMO_OPEN_TITLE					"Choose a Demo File to Play Back"
#define DEMO_LEVEL_DIR					"res/demos/."
#define ENDING_DEMO_NAME				"res/levels/single/index.rdx"	// Fake name for school.dmo

#define DEMO_DIR							"res/demos/."
#define DEMO_EXT							".dmo"

#define LEVEL_DIR							"res/levels/."

#if WITH_STEAMWORKS
extern bool EnableSteamCloud;
#define SAVEGAME_DIR						(EnableSteamCloud ? "steamcloud" : "savegame")
#else
#define SAVEGAME_DIR						("savegame")
#endif

#define CHECK_FOR_ASSETS_FILENAME	"res/res.sak"
#define CHECK_FOR_POSTALSD_FILENAME "res/hoods/ezmart.sak"
#define COOKIE_VALUE						0x9504cc39 //0xb5cf76dd
#define COOKIE_FILE_POSITION			289546856 //323290320  
#define COOKIE_XOR_MASK					0x6afb39e5 //0x66666666

// Exponent used to define gamma curve.
#define GAMMA_EXPONENT					1.50

// The directories for each type of challenge levels.
#define TIMED_CHALLENGE_LEVEL_DIR		"res/levels/gauntlet/timed/."
#define CHECKPOINT_CHALLENGE_LEVEL_DIR	"res/levels/gauntlet/checkpt/."
#define GOAL_CHALLENGE_LEVEL_DIR			"res/levels/gauntlet/goal/."
#define FLAG_CHALLENGE_LEVEL_DIR			"res/levels/gauntlet/capflag/."

// The titles for the open dialog for each type of challenge levels.
#ifdef MOBILE
#define TIMED_CHALLENGE_OPEN_TITLE			"Timed Challenge"
#define CHECKPOINT_CHALLENGE_OPEN_TITLE	    "Checkpoint Challenge"
#define GOAL_CHALLENGE_OPEN_TITLE			"Goal Challenge"
#define FLAG_CHALLENGE_OPEN_TITLE			"Capture the Flag Challenge"
#else
#define TIMED_CHALLENGE_OPEN_TITLE			"Choose Timed Challenge"
#define CHECKPOINT_CHALLENGE_OPEN_TITLE	"Choose Checkpoint Challenge"
#define GOAL_CHALLENGE_OPEN_TITLE			"Choose Goal Challenge"
#define FLAG_CHALLENGE_OPEN_TITLE			"Choose Capture the Flag Challenge"
#endif

#if TARGET == POSTAL_2015
#define XMAS_SAK_FILENAME				"res/xmas/newgame.sak"
#define XMAS_SAK_SOUND					"res/xmas/new22050_16.sak"
#define XMAS_SCRIPT_FILENAME			"res/xmas/newgame.script"
#define XMAS_SCRIPT_SOUND				"res/xmas/newsound.script"
#endif

#define INVALID_DIFFICULTY						-7

#define TIME_OUT_FOR_ABORT_SOUNDS		3000	// In ms.

// Determines the number of elements in the passed array at compile time.
#define NUM_ELEMENTS(a)					(sizeof(a) / sizeof(a[0]) )

// We use this value to flag the fact that we haven't hidden the cursor.
#define INVALID_CURSOR_SHOW_LEVEL	( (short)0x8000)


// Various action types
typedef enum
	{
	ACTION_NOTHING,
	ACTION_PLAY_SINGLE,
	ACTION_PLAY_BROWSE,
	ACTION_PLAY_HOST,
	ACTION_PLAY_CONNECT,
	ACTION_PLAY_CHALLENGE,
	ACTION_EDITOR,
	ACTION_DEMO_PLAYBACK,
	ACTION_DEMO_RECORD,
	ACTION_EDIT_INPUT_SETTINGS,
	ACTION_POSTAL_ORGAN,
	ACTION_LOAD_GAME,
	ACTION_PLAY_ADDON,
	ACTION_PLAY_ADDON2,
	ACTION_PLAY_ALL
#ifdef MOBILE
	,ACTION_CONTINUE_GAME
#endif
	} ACTION;


////////////////////////////////////////////////////////////////////////////////
// Variables/data
////////////////////////////////////////////////////////////////////////////////

// Global game settings
CGameSettings g_GameSettings;

// Cookie flag
int32_t g_lCookieMonster;

// Global screen buffer
RImage* g_pimScreenBuf;

// Global big font
RFont g_fontBig;

// Global Postal font.
RFont g_fontPostal;

// Resource manager for game resources.  These are resources used by the actual
// game, like things that a CThing loads that is not level specific.  For example,
// CBall loads, of course, foot.bmp, which would be loaded through this ResMgr.
// Note:  This resmgr should not be used for things like info on ordering, menu
// resources, g_fontBig, or anything not specific to the real game.
// Note:  Realm specifc data, such as alpha effects, etc., should be loaded
// through prealm->m_resmgr.
RResMgr	g_resmgrGame;

// Resource manager for shell resources.  Do not use this to load things like
// the main dudes' sprites.
RResMgr	g_resmgrShell;

// Resource manager for non-SAK resources.
RResMgr	g_resmgrRes;

// Time and Date values
int32_t g_lRegTime;
int32_t g_lRegValue;
int32_t g_lExpTime;
int32_t g_lExpValue;
int32_t g_lReleaseTime;

// Stockpile used to transfer loaded/saved data to/from the CDude's stockpile
CStockPile g_stockpile;
bool		g_bTransferStockpile;
int16_t		g_sRealmNumToSave;

// Flag for special end of game demo sequence which is set in Play() when
// it has been determined that the player has won.
bool		g_bLastLevelDemo = false;

// The secret cookie value used to determine if the humongous file exists
static U32	ms_u32Cookie = COOKIE_VALUE;

// These variables are generally controlled via the menu system
static ACTION m_action;
static int32_t m_lDemoBaseTime;
static int32_t m_lDemoTimeOut;
static char	m_szRealmFile[RSP_MAX_PATH+1];
static char m_szDemoFile[RSP_MAX_PATH+1];
static int16_t m_sRealmNum;
static bool m_bJustOneRealm;

// Cursor show level before we went to the background
static int16_t ms_sForegroundCursorShowLevel	= INVALID_CURSOR_SHOW_LEVEL;

// Used by random number stuff
static int32_t m_lRandom = 1;
static RFile* m_pfileRandom = 0;

// Used by if-logging schtuff.
static int32_t	ms_lSynchLogSeq	= 0;

static RFile	ms_fileSynchLog;

// true to create synchronization logs, false to compare to them.
static bool		m_bWriteLogs	= false;

static int16_t	ms_sLoadedDifficulty	= INVALID_DIFFICULTY;

static SampleMaster::SoundInstance	ms_siMusak	= 0;

////////////////////////////////////////////////////////////////////////////////
// Function prototypes
////////////////////////////////////////////////////////////////////////////////

static int16_t GameCore(void);			// Returns 0 on success.

static void ResetDemoTimer(void);

static int16_t OpenSaks(void);			// Returns 0 on success.

static void CloseSaks(void);

static int16_t LoadAssets(void);

static int16_t UnloadAssets(void);

static void GameSetRegistry(void);

static void GameGetRegistry(void);

static void GameEndingSequence(void);

static int16_t GetRealmToRecord(
	char* pszRealmFile,
	int16_t sMaxFileLen);

static int16_t GetDemoFile(
	char* pszDemoFile,
	int16_t sMaxFileLen);

// Callback gets called when OS is about to switch app into the background
static void BackgroundCall(void);

// Callback gets called when OS is about to switch app into the foreground
static void ForegroundCall(void);

// Returns difficulty for games.
// Note that this function is only valid once after a difficulty adjustment
// and then it goes back to the default (g_GameSettings value).
static int16_t GetGameDifficulty(void);	// Returns cached game difficulty.

// Opens the synchronization log with the specified access flags if in a 
// TRACENASSERT mode and synchronization logging is enabled.
// Also, opens the random log, if it is enabled via 
// g_GameSettings.m_szDebugMovie or something.
static void OpenSynchLogs(			// Returns nothing.
	bool	bWriteLogs);				// In:  true to create log, false to compare.

// Closes the synchronization logs, if open.
static void CloseSynchLogs(void);	// Returns nothing.

////////////////////////////////////////////////////////////////////////////////
//
// Load a previously saved game
//
////////////////////////////////////////////////////////////////////////////////

extern int16_t Game_LoadPlayersGame(	// Returns SUCCESS if loaded saved game file
				char* pszSaveName,		// In:  Name of the saved game file to open
				int16_t* psDifficulty,		// Out: Saved game realm difficulty.
				ACTION* paction);			// Out: Saved game action.

bool StatsAreAllowed = false;

int Stat_BulletsFired = 0;
int Stat_BulletsHit = 0;
int Stat_BulletsMissed = 0;
int Stat_Deaths = 0;
int Stat_Suicides = 0;
int Stat_Executions = 0;
int Stat_HitsTaken = 0;
int Stat_DamageTaken = 0;
int Stat_Burns = 0;
int Stat_TimeRunning = 0;
int Stat_KilledHostiles = 0;
int Stat_KilledCivilians = 0;
int Stat_TotalKilled = 0;
int Stat_LevelsPlayed = 0;

uint32_t Flag_Achievements = 0;

#if 1 //PLATFORM_UNIX
#include <sys/stat.h>
static void EnumExistingSaveGames(Menu *menu)
{
    char gamename[RSP_MAX_PATH];
    int i = 0;
    int Max = (sizeof(menu->ami) / sizeof(menu->ami[0])) - 1;
    if (Max > MAX_SAVE_SLOTS)
        Max = MAX_SAVE_SLOTS;

#if MOBILE
    snprintf(gamename, sizeof (gamename), "%s/auto.gme", SAVEGAME_DIR);

    const char *fname = FindCorrectFile(gamename, "w");
    struct stat statbuf;

    const char *str = "unused";
    char timebuf[32];
    menu->ami[0].sEnabled = (stat(fname, &statbuf) != -1);
    if (menu->ami[0].sEnabled)
    {
    	struct tm *tm;
    	if ((tm = localtime((const time_t*)&statbuf.st_mtime)) == NULL)
    		str = "unknown";
    	else
    	{
    		strftime(timebuf, sizeof (timebuf), "%m/%d/%y %H:%M", tm);
    		str = timebuf;
    	}
    }

	snprintf(gamename, sizeof (gamename), "Auto - [%s]", str);
    menu->ami[0].pszText = strdup(gamename);

    for (i = 0; i < Max; i++)
    {
    	snprintf(gamename, sizeof (gamename), "%s/%d.gme", SAVEGAME_DIR, i);

        const char *fname = FindCorrectFile(gamename, "w");
        struct stat statbuf;

        const char *str = "unused";
        char timebuf[32];
        menu->ami[i+1].sEnabled = (stat(fname, &statbuf) != -1);

        if (menu->ami[i+1].sEnabled)
        {
            struct tm *tm;
            if ((tm = localtime((const time_t*)&statbuf.st_mtime)) == NULL)
                str = "unknown";
            else
            {
                strftime(timebuf, sizeof (timebuf), "%m/%d/%y %H:%M", tm);
                str = timebuf;
            }
        }

        snprintf(gamename, sizeof (gamename), "%d - [%s]", i, str);
        menu->ami[i+1].pszText = strdup(gamename);

    }
#else
	for (i = 0; i < Max; i++)
	{
		snprintf(gamename, sizeof (gamename), "%s/%d.gme", SAVEGAME_DIR, i);
		const char *fname = FindCorrectFile(gamename, "w");
		struct stat statbuf;

		const char *str = "unused";
		char timebuf[32];
		menu->ami[i].sEnabled = (stat(fname, &statbuf) != -1);
		if (menu->ami[i].sEnabled)
		{
			struct tm *tm;
			if ((tm = localtime(&statbuf.st_mtime)) == NULL)
				str = "unknown";
			else
			{
				strftime(timebuf, sizeof (timebuf), "%m/%d/%y %H:%M", tm);
				str = timebuf;
			}
		}
		snprintf(gamename, sizeof (gamename), "%s/%d.gme [%s]", SAVEGAME_DIR, i, str);

		menu->ami[i].pszText = strdup(gamename);
	}

#endif
}
#endif

////////////////////////////////////////////////////////////////////////////////
//
// Do the high-level startup stuff, run the game, and then cleanup afterwards.
//
// It is assumed that the system/RSPiX environment are setup properly before
// this function is called.
//
////////////////////////////////////////////////////////////////////////////////
extern void TheGame(void)
	{
	int16_t sResult = 0;

	// Set up callbacks for when OS sends us to foreground or background.
	rspSetBackgroundCallback(BackgroundCall);
	rspSetForegroundCallback(ForegroundCall);

	ms_u32Cookie	= ~ms_u32Cookie;
	g_lRegValue = 0;
	g_lExpValue = 0;
	g_lRegTime = 0;

#ifdef CHECK_EXPIRATION_DATE
	g_lExpTime = EXPIRATION_DATE;
#else
	g_lExpTime = SAFE_DATE;
#endif
	g_lReleaseTime = RELEASE_DATE;

// To make it more confusing for someone debugging through the code, 
// the flag for the cookie check will be this large number SAFE_DATE.
// Once the game determines elsewhere that the cookie is correct, it will
// in some way modify the flag so that it is not SAFE_DATE, then later
// the check will be for anything other than SAFE_DATE
#ifdef CHECK_FOR_COOKIE
	g_lCookieMonster = SAFE_DATE;
#else
	g_lCookieMonster = SAFE_DATE - RELEASE_DATE;
#endif

	g_bTransferStockpile = false;

	// Get pointer to screen buffer and lock it.  Our Update()
	// unlocks and re-locks these each time it is called.
	rspNameBuffers(&g_pimScreenBuf);

	// Lock the RSPiX composite buffer so we can rect it.
	rspLockBuffer();
	// Clear screen buffer
	rspRect(RSP_BLACK_INDEX, g_pimScreenBuf, 
		0, 0, g_pimScreenBuf->m_sWidth, g_pimScreenBuf->m_sHeight);
	// Unlock now that we're done with the composite buffer.
	rspUnlockBuffer();

	// Update display
	rspUpdateDisplay();

	// Read all settings from preference file
	sResult = CSettings::LoadPrefs(g_pszPrefFileName);
	RFile file;

	if (sResult == 0)
		{
#ifdef PROMPT_FOR_ORIGINAL_CD
		rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_OK, g_pszAppName, g_pszPromptForOriginalCD);
#endif

#ifdef REQUIRE_POSTAL_CD
		// Check to make sure the correct CD is in the drive.  The Postal Add On Requires
		// that the original PostalCD is in the drive.
		int16_t	sCorrectCD = -2;

		while (sCorrectCD == -2)
			{
			// We are looking for a disc that has a res.sak, but doesn't have ezmart.sak
			// to insure that they have the original PostalCD in the drive
			if (file.Open(FullPathCD(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				{
				file.Close();
				sCorrectCD++;
				if (file.Open(FullPathCD(CHECK_FOR_POSTALSD_FILENAME), "r", RFile::LittleEndian) != 0)
					{
					sCorrectCD++;
					}
				else
					{
					file.Close();
					}
				}

			if (sCorrectCD != 0)
				{
				TRACE("Game():  Wrong CD in the drive - this is not the original PostalCD\n");
				if (rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_RETRYCANCEL, g_pszCriticalErrorTitle, g_pszWrongCD, "Wrong CD") == 3)
					sCorrectCD = -2;
				else
					sCorrectCD = -3;
				}	
			}
		// If we have the correct CD in the drive, then we can proceed
		sResult = sCorrectCD;

#endif // REQUIRE_POSTAL_CD
		
		// Try loading special file that exists solely for the purpose of checking for
		// valid paths in the prefs file.  We do this for each of the paths.
		if (sResult == 0)
			{
			if (file.Open(FullPathHD(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				file.Close();
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on HD path specified in prefs!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "HD");
				}
			}
		if (sResult == 0)
			{
			if (file.Open(FullPathVD(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				file.Close();
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on VD path specified in prefs!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "VD");
				}
			}
		if (sResult == 0)
			{
			if (file.Open(FullPathSound(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				file.Close();
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on Sound path specified in prefs!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "Sound");
				}
			}
		if (sResult == 0)
			{
			if (file.Open(FullPathGame(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				file.Close();
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on Game path specified in prefs!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "Game");
				}
			}
		if (sResult == 0)
			{
			if (file.Open(FullPathHoods(CHECK_FOR_ASSETS_FILENAME), "r", RFile::LittleEndian) == 0)
				file.Close();
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on Hoods path specified in prefs!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "Hoods");
				}
			}


		// Check for special file, COOKIE, and size.
		if (sResult == 0)
			{
			ms_u32Cookie	^= COOKIE_XOR_MASK; 

			if (file.Open(FullPathCD(CHECK_FOR_ASSETS_FILENAME), "rb", RFile::LittleEndian) == 0)
				{
#if defined(CHECK_FOR_COOKIE)
				if (file.Seek(COOKIE_FILE_POSITION, SEEK_SET) == 0)
					{
					U32	u32Cookie	= 0;
					if (file.Read(&u32Cookie) == 1)
						{
						if (u32Cookie == ms_u32Cookie)
							{
							// Okay, you can play.
							// This can be any number, the check will verify that the
							// g_lCookieMonster is not SAFE_DATE.  
							g_lCookieMonster += 15;
							}
						else
							{
							//sResult	= -4;
							TRACE("Game(): Cookie value is incorrect.\n");
							}
						}
					else
						{
						//sResult	= -3;
						TRACE("Game(): Failed to read cookie.\n");
						}
					}
				else
					{
					//sResult	= -2;
					TRACE("Game(): Cookie file is incorrect size!\n");
					}
#endif // defined(CHECK_FOR_COOKIE)

				file.Close();
				}
			else
				{
				sResult = -1;
				TRACE("Game(): Can't find assets based on CD path specified in prefs!\n");
				}

			// If any problems . . .
			if (sResult != 0)
				{
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszCantFindAssets, "CD");
				}
			}

		// Check for CDROM drive.
		if (sResult == 0)
			{
#if defined(MUST_BE_ON_CD)
			// Check for the special case where the path is the one we use for
			// development.  If someone out there happens to use this as their
			// own path, then they will defeat this test for CD-ROM.  Oh well.
			char* pszDevelopmentPath = "\\\\narnia\\projects\\";
			if (strnicmp(FullPathCD("."), pszDevelopmentPath, strlen(pszDevelopmentPath)) != 0)
				{
#if defined(WIN32)
				if (GetDriveType(FullPathCD(".") ) != DRIVE_CDROM)
#else
				#error MUST_BE_ON_CD feature is currently implemented only for Win32
#endif
					{
					// Only set the error flag if we're in release mode
					#ifndef _DEBUG
						sResult = -1;
					#endif
					TRACE("Game(): CD path is not a CDROM!\n");
					rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszNotOnCDROM);
					}
				}
#endif
			}

		if (sResult == 0)
			{

			// Set the gamma level to value indicated by settings.
			SetGammaLevel(g_GameSettings.m_sGammaVal);

			// If trickier quit specified . . .
			if (g_GameSettings.m_sTrickySystemQuit != FALSE)
				{
				// Add shift key as a requirement for the quit status keys.
				rspSetQuitStatusFlags(RSP_GKF_SHIFT);
				}

			// Open SAKs or setup equivalent paths.
			sResult = OpenSaks();
			if (sResult == 0)
				{
				// Start title, passing the "total units" for its progress meter
				sResult = StartTitle(1, true, &ms_siMusak);
				if (sResult == 0)
					{

					// Load assets that we want to keep around at all times
					sResult = LoadAssets();
					
					// End title (regardless of previous result)
					EndTitle();
					if (sResult == 0)
						{

						// Set the font most GUIs will use (the menu system uses its own RPrint).
						// Note that the size does not matter, we just want to set the font ptr.
						RGuiItem::ms_print.SetFont(15, &g_fontBig);

 						// Do the core game stuff
						sResult = GameCore();

						// If there weren't any errors, wrap things up
						if (!sResult)
							{

							// Do ending credits
							if (rspGetQuitStatus() > 1)
								{
								rspSetQuitStatus(0);
								Credits();
								}
							}
						}
					else
						{
						rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszGeneralError);
						}

					// Unload assets loaded earlier
					UnloadAssets();

					}
				else
					{
					TRACE("Game(): Error returned by StartTitle()!\n");
					rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszTitleError);
					}
				}
			else
				{
				TRACE("Game(): Error returned by OpenSaks().\n");
				}

#if 0
			// Make sure we're not paused . . .
			if (RMix::IsPaused() )
				{
				RMix::Resume();
				}
#endif

			// Abort all samples.
			AbortAllSamples();

			// We should never need a timeout but I don't want to risk a Muppets
			// scenario where a shitty sound driver causes us to think a sound is always
			// playing.
			// Wait for all samples to finish.
			int32_t	lTimeOutTime	= rspGetMilliseconds() + TIME_OUT_FOR_ABORT_SOUNDS;
			// Wait for them to stop.
			while (IsSamplePlaying() == true && rspGetMilliseconds() < lTimeOutTime)
				{
				// Always do periodic updates.
				// Crucial to sound completing.
				UpdateSystem();
				}

			// Close SAKs and/or create SAKs??
			CloseSaks();
			}

		// Save all settings to preference file
		sResult = CSettings::SavePrefs(g_pszPrefFileName);
		if (sResult > 0)
			{
			TRACE("Game(): Read-only prefs file!\n");
//			rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszPrefReadOnly);
			}
		else if (sResult < 0)
			{
			TRACE("Game(): Error writing prefs file!\n");
			rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszPrefWriteError);
			}

		}
	else
		{
		TRACE("Game(): Error returned by ReadGamePrefs()!\n");
		rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszPrefReadError);
		}

	// Remove the callbacks
	rspSetBackgroundCallback(NULL);
	rspSetForegroundCallback(NULL);
	}


////////////////////////////////////////////////////////////////////////////////
//
// Do the core game stuff (display menu, play a game, run the demo, etc.)
//
////////////////////////////////////////////////////////////////////////////////
static int16_t GameCore(void)		// Returns 0 on success.
	{
	int16_t sResult = 0;
	uint16_t usDemoCount = 0;
	bool	bMPath = false,
			bMPathServer = false;

#ifdef CHECK_EXPIRATION_DATE
	#ifdef WIN32
		char acTime[100];
		strcpy(acTime, asctime(gmtime(&g_lExpTime)));
		#define NEXT_LINE "\n\n"
	#else
		char acTime[100];
		uint32_t lTime = g_lExpTime + (((365 * 70UL) + 17) * 24 * 60 * 60); // time_fudge 1900->1970
		strcpy(acTime, ctime(&lTime));
		char* pCR = strchr(acTime, '\n');
		if (pCR != NULL)
			*pCR = 0;
		#define NEXT_LINE "\r\r"
	#endif	// WIN32

	rspMsgBox(
		RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
	#if defined(EXPIRATION_MSG_POSTAL_LAUNCH_WEEKEND)
		// Title
		"Postal Launch Weekend Edition",
	#elif defined(EXPIRATION_MSG_MARKETING_RELEASE)
		// Title
		"Postal Beta Contest",
		// Message Body
		"This is a large, single-player, single-level BETA test version -- that means we're "
		"still working on it and it's not final. But we want your comments to help us make it "
		"even cooler, so we're holding a BETA TEST CONTEST!"
		NEXT_LINE
		"We're giving away tons o' free stuff, including FREE GAMES, T-SHIRTS, and even a hot "
		"NEW DELL 266MHZ COMPUTER!"
		NEXT_LINE
		"If you haven't already registered, visit http://www.gopostal.com to find out more about Postal "
		"and how you can register for the BETA TEST CONTEST!"
		NEXT_LINE
	#else
		// Title
		"Limited-Time Version",
	#endif
		// Message Body
		"This limited-time version will expire on %s"
		NEXT_LINE
		"After the expiration date, you will still be able to get into the game, "
		"but you will notice that everyone bursts into flames and dies.  This is "
		"NOT a bug -- it simply indicates that your version has expired.",
		// Time String
		acTime);
#endif	// CHECK_EXPIRATION_DATE

	#ifndef _WIN32
	UnlockAchievement(ACHIEVEMENT_PLAY_ON_NON_WINDOWS_PLATFORM);
	#endif

	// Clear end of game flag - play will set the flag if the player wins the game
	g_bLastLevelDemo = false;

	// Clear any events that might be in the queue
	rspClearAllInputEvents();
	ClearXInputState();

	// Get the registry value
	GameGetRegistry();

	// Init demo mode times
	m_lDemoBaseTime = rspGetMilliseconds();
	m_lDemoTimeOut = g_GameSettings.m_lInitialDemoTimeOut;

	// Clear flags that are updated by the menu system callbacks (in this module)
	m_action = ACTION_NOTHING;
	m_sRealmNum = 0;
	m_szRealmFile[0] = 0;
	m_bJustOneRealm = false;

	// Flag indicates whether or not menu is active
	bool bMenuActive = false;
	ACTION	actionNext	= ACTION_NOTHING;	// Initialized for safety.

	Menu*	pmenuStart	= NULL;				// Next menu to start if not NULL.
	bool	bPalTran		= true;				// true to PalTranOn() before next
													// menu.
	bool	bTitleImage	= true;				// true to display title image before
													// next menu.
	bool	bTitleMusak	= true;				// true to play title musak during
													// next menu.  Requires title image.
//////////////////////////////////////
//////////////////////////////////////

	// Keep looping until user quits or error occurs.  Maybe even play
	// a game or two along the way.  If there's no user input for a
	// certain amount of time, automatically run the self-playing demo.
	RInputEvent ie;
	memset(&ie, '\0', sizeof (ie));  // fix valgrind complaining... --ryan.
	while (sResult == 0)
		{
		// Clear the end of game flag each time just to be safe, it only needs
		// to be set within the last iteration
		g_bLastLevelDemo = false;

		// As always...
		UpdateSystem();

		// Get next input event
		ie.type	= RInputEvent::None;
		rspGetNextInputEvent(&ie);

		// If there's any key or button input, or the app is in BG mode (per the OS),
		// reset the demo timer
		if ((ie.type != RInputEvent::None) || rspIsBackground())
			ResetDemoTimer();

		// Does user want to exit app?  Do this BEFORE checking whether menu is active
		// so we won't bother activating the menu only to find out we're going to exit.
		if (rspGetQuitStatus())
			break;

		// If menu isn't active, get it going
		if (!bMenuActive)
			{
			// If paltran requested . . .
			if (bPalTran)
				PalTranOn();

			sResult = StartMenu(pmenuStart ? pmenuStart : &menuMain, &g_resmgrShell, g_pimScreenBuf);
			if (sResult == 0)
				{
				bMenuActive = true;
				// Restore defaults.
				pmenuStart	= NULL;
				bPalTran		= true;
				bTitleImage	= true;
				bTitleMusak	= true;
				}
			else
				{
				TRACE("GameLoop(): Error returned by StartMenu()!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, "Cannot initialize menu system, most likely due to a memory or drive error.\n");
				break;
				}
			}

		// Let menu system do its thing
		DoMenuInput(&ie, g_InputSettings.m_sUseJoy);
		DoMenuOutput(g_pimScreenBuf);

		// Update the screen
		rspUpdateDisplay();

		// If this is not the spawn version, then check to see if the user has been
		// idle long enough to run a demo.  The spawn version doesn't have any
		// demos available, so we shouldn't try to run them.
#ifndef SPAWN
		// If there's no user action and the demo timer expired, simulate the
		// appropriate action to start the self-running demo.
#ifndef AUTO_DEMOS_REMOVED // It's time to stop.
		if ((m_action == ACTION_NOTHING) && 
		    ((rspGetMilliseconds() - m_lDemoBaseTime) >= m_lDemoTimeOut) &&
			 g_GameSettings.m_sNumAvailableDemos > 0)
			m_action = ACTION_DEMO_PLAYBACK;
#endif
#endif // SPAWN

		// Reset next action.
		actionNext	= ACTION_NOTHING;

		// Any action to handle?
		if (m_action != ACTION_NOTHING)
			{
			// Handle the action
			switch(m_action)
				{
				//------------------------------------------------------------------------------
				// Play single player game
				//------------------------------------------------------------------------------
				case ACTION_PLAY_SINGLE:
// If this is the spawn version, then they are not allowed to play single
// player, so we will take out some of the single player code so its not
// easy to hack back in.
#ifndef SPAWN
					// End menu
					StopMenu();
					PalTranOff();
					bMenuActive = false;

					// Clear the game winning flag - play will set it before it returns
					// if the player has won the game
					g_bLastLevelDemo = false;

					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_LIVE,					// Input mode
						m_sRealmNum,						// Realm number OR -1 to use realm file
						m_szRealmFile,						// Realm file
						m_bJustOneRealm,					// Whether to play just one realm or not
						false,								// Not challenge mode
						0,								// Not new single player Add on levels
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Use cooperative levels (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						NULL);								// Demo mode file

#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif

						// If the player won the game, show them the last level demo
						// and then the ending cutscenes.
						if (g_bLastLevelDemo)
							GameEndingSequence();

						// clear the end of game flag just to be safe
						g_bLastLevelDemo = false;
#endif
					break;
				
				//------------------------------------------------------------------------------
				// Join a multiplayer game
				//------------------------------------------------------------------------------
				case ACTION_PLAY_BROWSE:
				case ACTION_PLAY_CONNECT:
// If multiplayer is disabled, leave out this code to make it harder to hack back in
#ifndef MULTIPLAYER_DISABLED
					{
					// Set flag as to whether we're browsing or connecting
					bool bBrowse = (m_action == ACTION_PLAY_BROWSE) ? true : false;

					// Startup sockets with selected protocol
					if (RSocket::Startup((RSocket::ProtoType)g_GameSettings.m_usProtocol, false) == 0)
						{
						InitNetProbGUI();

						// Set next menu to start on to the current menu.
						pmenuStart	= GetCurrentMenu();
						// End the menu but don't PalTranOff unless we actually join a game.
						StopMenu();
						bMenuActive = false;
						bPalTran		= false;
						bTitleImage	= false;
						bTitleMusak	= false;

						// Use the net game dialog to join a multiplayer game
						CNetClient* pnetclient = new CNetClient;
						NetMsg msg;
						if (DoNetGameDialog(pnetclient, bBrowse, NULL, &msg) == 0)
							{
							// If the game was actually started...
							if (msg.msg.nothing.ucType == NetMsg::START_GAME)
								{
								PalTranOff();
								// Go back to the main menu when done and do
								// all the deluxe stuff.
								pmenuStart	= NULL;
								bPalTran		= true;
								bTitleImage	= true;
								bTitleMusak	= true;

								ASSERT(pnetclient->GetNumPlayers() >= 1);

								// Create synchronization logs, if enabled.
								OpenSynchLogs(true);

								Play(
									pnetclient,								// Client
									NULL,										// No server (not hosting game)
									INPUT_MODE_LIVE,						// Input mode
									msg.msg.startGame.sRealmNum,		// Realm number OR -1 to use realm file
									msg.msg.startGame.acRealmFile,	// Realm file
									msg.msg.startGame.sRealmNum >= 0 ? false : true, // Whether to play just one realm or not
									false,									// Not challenge mode
									0,									// Not new single player Add On leves
									msg.msg.startGame.sDifficulty,	// Difficulty
									msg.msg.startGame.sRejuvenate,	// Rejunenate (MP only)
									msg.msg.startGame.sTimeLimit,		// Time limit (MP only)
									msg.msg.startGame.sKillLimit,		// Kill limit (MP only)
									msg.msg.startGame.sCoopLevels,	// Cooperative or Deathmatch levels (MP only)
									msg.msg.startGame.sCoopMode,		// Cooperative or Deathmatch mode (MP only)
									msg.msg.startGame.sFrameTime,		// Frame time (MP only)
									NULL);									// Demo mode file

#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif

								// Close synchronization logs, if opened.
								CloseSynchLogs();
								}
							}
						delete pnetclient;
						KillNetProbGUI();
						RSocket::Shutdown();
						}
					else
						{
						TRACE("GameCore(): Couldn't init protocol!\n");
						rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, "The selected network protocol has failed to initialize.  Please contact your system administrator or network vendor.\n");
						}
					}
#endif //MULTIPLAYER_DISABLED
					break;

				//------------------------------------------------------------------------------
				// Host a multiplayer game
				//------------------------------------------------------------------------------
				case ACTION_PLAY_HOST:
// If multiplayer is disabled, leave out this code to make it harder to hack back in
#ifndef MULTIPLAYER_DISABLED
					{
					// Startup sockets with selected protocol
					if (RSocket::Startup((RSocket::ProtoType)g_GameSettings.m_usProtocol, false) == 0)
						{
						InitNetProbGUI();

						// Set next menu to start on to the current menu.
						pmenuStart	= GetCurrentMenu();
						// End the menu but don't PalTranOff unless we actually join a game.
						StopMenu();
						bMenuActive = false;
						bPalTran		= false;
						bTitleImage	= false;
						bTitleMusak	= false;

						// Use the net game dialog to host a multiplayer game
						CNetClient* pnetclient = new CNetClient;
						CNetServer* pnetserver = new CNetServer;
						NetMsg msg;
						if (DoNetGameDialog(pnetclient, false, pnetserver, &msg) == 0)
							{
							// If the game was actually started...
							if (msg.msg.nothing.ucType == NetMsg::START_GAME)
								{
								PalTranOff();
								// Go back to the main menu when done and do
								// all the deluxe stuff.
								pmenuStart	= NULL;
								bPalTran		= true;
								bTitleImage	= true;
								bTitleMusak	= true;

								ASSERT(pnetclient->GetNumPlayers() >= 1);

								// Create synchronization logs, if enabled.
								OpenSynchLogs(true);

								Play(
									pnetclient,								// Client
									pnetserver,								// Server, too
									INPUT_MODE_LIVE,						// Input mode
									msg.msg.startGame.sRealmNum,		// Realm number OR -1 to use realm file
									msg.msg.startGame.acRealmFile,	// Realm file
									msg.msg.startGame.sRealmNum >= 0 ? false : true, // Whether to play just one realm or not
									false,									// Not challenge mode
									0,									// Not new single player Add on levels
									msg.msg.startGame.sDifficulty,	// Difficulty
									msg.msg.startGame.sRejuvenate,	// Rejunenate (MP only)
									msg.msg.startGame.sTimeLimit,		// Time limit (MP only)
									msg.msg.startGame.sKillLimit,		// Kill limit (MP only)
									msg.msg.startGame.sCoopLevels,	// Cooperative or Deathmatch levels (MP only)
									msg.msg.startGame.sCoopMode,		// Cooperative or Deathmatch mode (MP only)
									msg.msg.startGame.sFrameTime,		// Frame time (MP only)
									NULL);									// Demo mode file

#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
								// Close synchronization logs, if opened.
								CloseSynchLogs();
								}
							}
						delete pnetserver;
						delete pnetclient;
						KillNetProbGUI();
						RSocket::Shutdown();
						}
					else
						{
						TRACE("GameCore(): Couldn't init protocol!\n");
						rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, "The selected network protocol has failed to initialize.  Please contact your system administrator or network vendor.\n");
						}
					}
#endif //MULTIPLAYER_DISABLED
					break;

				//------------------------------------------------------------------------------
				// Play challenge game
				//------------------------------------------------------------------------------
				case ACTION_PLAY_CHALLENGE:
					// Remember menu to go back to.
					pmenuStart	= GetCurrentMenu();
					// End the menu.
					StopMenu();
					bMenuActive = false;
					// Turn off paltran but remember to restore.
					PalTranOff();
					bPalTran		= true;
					// Remember to show title, but no musak.
					bTitleImage	= true;
					bTitleMusak	= false;

					// Note that m_sRealmNum, m_szRealmFile, and m_bJustOneRealm are
					// set via the callback, Game_StartChallengeGame().
					// ***ADD FLAG(S) TO THIS CALL INDICATING THIS IS A CHALLENGE GAME***
					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_LIVE,					// Input mode
						m_sRealmNum,						// Realm number OR -1 to use realm file
						m_szRealmFile,						// Realm file
						m_bJustOneRealm,					// Whether to play just one realm or not
						true,									// Play challenge levels
						false,								// Not new single player Add On levels
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Cooperative (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						NULL);								// Demo mode file

#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
					break;

				//------------------------------------------------------------------------------
				// Play Add On levels
				//------------------------------------------------------------------------------
				case ACTION_PLAY_ADDON:
#ifndef SPAWN
					// Remember menu to go back to.
					pmenuStart	= GetCurrentMenu();
					// End the menu.
					StopMenu();
					bMenuActive = false;
					// Turn off paltran but remember to restore.
					PalTranOff();
					bPalTran		= true;
					// Remember to show title, but no musak.
					bTitleImage	= true;
					bTitleMusak	= false;

					// Note that m_sRealmNum, m_szRealmFile, and m_bJustOneRealm are
					// set via the callback, Game_StartChallengeGame().
					// ***ADD FLAG(S) TO THIS CALL INDICATING THIS IS A CHALLENGE GAME***
					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_LIVE,					// Input mode
						m_sRealmNum,						// Realm number OR -1 to use realm file
						m_szRealmFile,						// Realm file
						m_bJustOneRealm,					// Whether to play just one realm or not
						false,								// Don't play challenge levels
						1,									// Play new single player Add on levels
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Cooperative (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						NULL);								// Demo mode file
#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
#endif // SPAWN
					break;
#if TARGET == POSTAL_2015
#ifndef SPAWN
				case ACTION_PLAY_ADDON2:
					// Remember menu to go back to.
					pmenuStart	= GetCurrentMenu();
					// End the menu.
					StopMenu();
					bMenuActive = false;
					// Turn off paltran but remember to restore.
					PalTranOff();
					bPalTran		= true;
					// Remember to show title, but no musak.
					bTitleImage	= true;
					bTitleMusak	= false;

					// Note that m_sRealmNum, m_szRealmFile, and m_bJustOneRealm are
					// set via the callback, Game_StartChallengeGame().
					// ***ADD FLAG(S) TO THIS CALL INDICATING THIS IS A CHALLENGE GAME***
					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_LIVE,					// Input mode
						m_sRealmNum,						// Realm number OR -1 to use realm file
						m_szRealmFile,						// Realm file
						m_bJustOneRealm,					// Whether to play just one realm or not
						false,								// Don't play challenge levels
						2,									// Play new single player Japan Add on levels
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Cooperative (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						NULL);								// Demo mode file
#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
					break;
				case ACTION_PLAY_ALL:
					// Remember menu to go back to.
					pmenuStart	= GetCurrentMenu();
					// End the menu.
					StopMenu();
					bMenuActive = false;
					// Turn off paltran but remember to restore.
					PalTranOff();
					bPalTran		= true;
					// Remember to show title, but no musak.
					bTitleImage	= true;
					bTitleMusak	= false;

					// Note that m_sRealmNum, m_szRealmFile, and m_bJustOneRealm are
					// set via the callback, Game_StartChallengeGame().
					// ***ADD FLAG(S) TO THIS CALL INDICATING THIS IS A CHALLENGE GAME***
					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_LIVE,					// Input mode
						m_sRealmNum,						// Realm number OR -1 to use realm file
						m_szRealmFile,						// Realm file
						m_bJustOneRealm,					// Whether to play just one realm or not
						false,								// Don't play challenge levels
						3,									// Play all other levels, though
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Cooperative (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						NULL);								// Demo mode file
#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
						// If the player won the game, show them the last level demo
						// and then the ending cutscenes.
						if (g_bLastLevelDemo)
							GameEndingSequence();

						// clear the end of game flag just to be safe
						g_bLastLevelDemo = false;
					break;			
#endif // SPAWN
#endif // POSTAL_2015		

				
				//------------------------------------------------------------------------------
				// Playback demo
				//------------------------------------------------------------------------------
				case ACTION_DEMO_PLAYBACK:
					{
					// Prepare all settings for demo mode
					CSettings::PreDemo();

					// If demo debug movie file is specified in prefs, open it now.  The RFile*
					// is does double-duty as a flag, where non-zero means movie mode is enabled.
					RFile* pfileDemoDebugMovie = 0;
#if 0
					if (strlen(g_GameSettings.m_szDemoDebugMovie) > 0)
						{
						pfileDemoDebugMovie = new RFile;
						if (pfileDemoDebugMovie->Open(g_GameSettings.m_szDemoDebugMovie, "rb", RFile::LittleEndian) != 0)
							{
							delete pfileDemoDebugMovie;
							pfileDemoDebugMovie = 0;
							}
						}
#else
					// Compare to synchronization logs, if enabled.
					OpenSynchLogs(false);
#endif

					if (InputDemoInit() == 0)
						{
						// If no specific filename has been set for the demo, then load one of 
						// the default demos.
						if (m_szDemoFile[0] == '\0')
							{
							// If there are default demos . . .
							if(g_GameSettings.m_sNumAvailableDemos > 0)
								{
								sprintf(m_szDemoFile, "%s%d%s", FullPathHD(DEFAULT_DEMO_PREFIX), usDemoCount % MAX((int16_t) 1, g_GameSettings.m_sNumAvailableDemos), DEFAULT_DEMO_SUFFIX);
								}
							}
					
						// If there is now a demo filename . . .
						if (m_szDemoFile[0] != '\0')
							{
							RFile	fileDemo;
							usDemoCount++;
							if (fileDemo.Open(m_szDemoFile, "rb", RFile::LittleEndian) == 0)
								{
								// Read name of realm file
								char szRealmFile[RSP_MAX_PATH];
								fileDemo.Read(szRealmFile);
								// Read whether it's a full path.
								int16_t	sRealmFileIsFullPath;
								fileDemo.Read(&sRealmFileIsFullPath);
								if (!fileDemo.Error())
									{
									// Load input demo data (must be BEFORE setting playback mode)
									if (InputDemoLoad(&fileDemo) == 0)
										{
										// End menu (now that we know there were no errors)
										StopMenu();
										PalTranOff();
										bMenuActive = false;

										Play(
											NULL,									// No client (not network game)
											NULL,									// No server (not network game)
											INPUT_MODE_PLAYBACK,				// Input mode
											-1,									// Always use specific realm file
											szRealmFile,						// Realm file to be played
											false,								// Don't play just one realm
											false,								// Not challenge mode
											0,								// Not new single player Add On levels
											GetGameDifficulty(),				// Difficulty level
											false,								// Rejunenate (MP only)
											0,										// Time limit (MP only)
											0,										// Kill limit (MP only)
											0,										// Cooperative (MP only)
											0,										// Use cooperative mode (MP only)
											0,										// Frame time (MP only)
											pfileDemoDebugMovie);			// Demo mode file

										}
									else
										{
										TRACE("GameCore(): Couldn't load demo data!\n");
										rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileReadError_s, (char*) m_szDemoFile);
										}
									}
								else
									{
									TRACE("GameCore(): Couldn't load realm name!\n");
									rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileReadError_s, (char*) m_szDemoFile);
									}
								fileDemo.Close();
								}
							else
								{
								TRACE("GameCore(): Couldn't open demo file: '%s'\n", m_szDemoFile);
								rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileOpenError_s, (char*) m_szDemoFile);
								}
							}
						else
							{
							TRACE("GameCore(): No demo filename.\n");
							}

						// Reset demo file name for next time.
						m_szDemoFile[0] = 0;
						InputDemoKill();
						}

#if 0
					if (pfileDemoDebugMovie)
						{
						// File may have been closed by Play() if an error occurred
						if (pfileDemoDebugMovie->IsOpen())
							pfileDemoDebugMovie->Close();
						delete pfileDemoDebugMovie;
						pfileDemoDebugMovie = 0;
						}
#else
					CloseSynchLogs();
#endif

#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
					// Restore settings to what they were before demo mode
					CSettings::PostDemo();
					}
					break;

				//------------------------------------------------------------------------------
				// Record demo
				//------------------------------------------------------------------------------
				case ACTION_DEMO_RECORD:
					{
					// Prepare all settings for demo mode
					CSettings::PreDemo();

					// If demo debug movie file is specified in prefs, open it now.  The RFile*
					// is does double-duty as a flag, where non-zero means movie mode is enabled.
					RFile* pfileDemoDebugMovie = 0;
#if 0
					if (strlen(g_GameSettings.m_szDemoDebugMovie) > 0)
						{
						pfileDemoDebugMovie = new RFile;
						if (pfileDemoDebugMovie->Open(g_GameSettings.m_szDemoDebugMovie, "wb", RFile::LittleEndian) != 0)
							{
							delete pfileDemoDebugMovie;
							pfileDemoDebugMovie = 0;
							}
						}
#else
					// Create synchronization logs, if enabled.
					OpenSynchLogs(true);
#endif

					if (InputDemoInit() == 0)
						{

						// Get name of realm to play
						char szRealmFile[RSP_MAX_PATH];
						int16_t	sGetRealmResult	= GetRealmToRecord(szRealmFile, sizeof(szRealmFile));
						switch (sGetRealmResult)
							{
							case 0:	// Success.
								break;
							case 1:	// Not a relative path.  Got a full path.
								break;
							default:	// Error.
								break;
							}

						if (sGetRealmResult >= 0)
							{
							// Get name of demo file to save to
							char szDemoFile[RSP_MAX_PATH];
							if (GetDemoFile(szDemoFile, sizeof(szDemoFile)) == 0)
								{
								// Open demo file
								RFile	fileDemo;
								if (fileDemo.Open(szDemoFile, "wb", RFile::LittleEndian) == 0)
									{
									// Write name of realm file
									fileDemo.Write(szRealmFile);
									// Write whether it's a full path.
									fileDemo.Write(sGetRealmResult);

									// End menu (now that we know there were no errors)
									StopMenu();
									PalTranOff();
									bMenuActive = false;

									Play(
										NULL,									// No client (not network game)
										NULL,									// No server (not network game)
										INPUT_MODE_RECORD,				// Input mode
										-1,									// Always use specific realm file
										szRealmFile,						// Realm file to be played
										false,								// Don't play just one realm
										false,								// Not challenge mode
										0,								// Not new single player Add on levels
										GetGameDifficulty(),				// Difficulty level
										false,								// Rejunenate (MP only)
										0,										// Time limit (MP only)
										0,										// Kill limit (MP only)
										0,										// Cooperative (MP only)
										0,										// Use cooperative mode (MP only)
										0,										// Frame time (MP only)
										pfileDemoDebugMovie);			// Demo mode file
#ifdef MOBILE
	AndroidSetScreenMode(TOUCH_SCREEN_MENU);
#endif
									// Save input data to file
									if (InputDemoSave(&fileDemo) != 0)
										{
										TRACE("GameCore(): Couldn't save demo data!\n");
										rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileWriteError_s, szDemoFile);
										}
									}
								fileDemo.Close();
								}
							else
								{
								TRACE("GameCore(): Couldn't open demo file: '%s'\n", szDemoFile);
								rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileOpenError_s, szDemoFile);
								}
							}

						InputDemoKill();
						}

#if 0
					if (pfileDemoDebugMovie)
						{
						// File may have been closed by Play() if an error occurred
						if (pfileDemoDebugMovie->IsOpen())
							pfileDemoDebugMovie->Close();
						delete pfileDemoDebugMovie;
						pfileDemoDebugMovie = 0;
						}
#else
					CloseSynchLogs();
#endif

					// Restore settings to what they were before demo mode
					CSettings::PostDemo();
					}
					break;

				//------------------------------------------------------------------------------
				// Go to the editor
				//------------------------------------------------------------------------------
				#if !defined(EDITOR_DISABLED)
					case ACTION_EDITOR:
						// End menu
						StopMenu();
						PalTranOff();
						bMenuActive = false;

						// Run the game editor
						GameEdit();
						break;
				#endif

				//------------------------------------------------------------------------------
				// Edit key, mouse, or joystick settings.
				//------------------------------------------------------------------------------
				case ACTION_EDIT_INPUT_SETTINGS:
					// Leave the menu on.
					// Run the input settings editor.
					EditInputSettings();
					break;

				//------------------------------------------------------------------------------
				// Postal organ.
				//------------------------------------------------------------------------------
				case ACTION_POSTAL_ORGAN:
					// Launch Postal Organ.
					PlayWithMyOrgan();
					break;

				//------------------------------------------------------------------------------
				// Load previously saved user game.
				//------------------------------------------------------------------------------
				case ACTION_LOAD_GAME:
					{
					// Static so dialog will "remember" the previously-used name
					static char szFileSaved[RSP_MAX_PATH] = "";

					// If not yet used, start out in appropirate directory
					if (szFileSaved[0] == '\0')
						strcpy(szFileSaved, FullPathHD(SAVEGAME_DIR));

					// Display option dialog to let user choose a realm file
					#if 1 //PLATFORM_UNIX
                    char tmp[RSP_MAX_PATH];
					if (PickFile("Choose Game Slot", EnumExistingSaveGames, szFileSaved, sizeof(szFileSaved)) == 0)
                    {
#ifdef MOBILE
						//Android we have the format "1 - date"
						//Auot save is "Auto - date"
						//Need to create the filename
						char number = szFileSaved[0];
						if (number == 'A') //Check for auto save now
							snprintf(szFileSaved, sizeof (szFileSaved), "%s/auto.gme", SAVEGAME_DIR);
						else
							snprintf(szFileSaved, sizeof (szFileSaved), "%s/%c.gme", SAVEGAME_DIR,number);
						TRACE("Load file: %s",szFileSaved);
#else
                        char *ptr = strrchr(szFileSaved, '[');
                        if (ptr) *(ptr-1) = '\0';
#endif
						// This function will open the saved game file and set the correct game mode
						// and settings.  Note that this modifies the m_action (that's how we get
						// out this state...this confused me for a while but it seems like a good
						// way to choose the appropriate original action).
						Game_LoadPlayersGame(szFileSaved, &ms_sLoadedDifficulty, &actionNext);
						m_bJustOneRealm = false;
                    }
					#else
					if (rspOpenBox(g_pszLoadGameTitle, szFileSaved, szFileSaved, sizeof(szFileSaved), ".gme") == 0)
						{
						// This function will open the saved game file and set the correct game mode
						// and settings.  Note that this modifies the m_action (that's how we get
						// out this state...this confused me for a while but it seems like a good
						// way to choose the appropriate original action).
						Game_LoadPlayersGame(szFileSaved, &ms_sLoadedDifficulty, &actionNext);
						m_bJustOneRealm = false;
						}
					#endif
					break;
					}
#ifdef MOBILE
				case ACTION_CONTINUE_GAME:
					{
						static char szFileSaved[RSP_MAX_PATH] = "";
						snprintf(szFileSaved, sizeof (szFileSaved), "%s/auto.gme", SAVEGAME_DIR);
						Game_LoadPlayersGame(szFileSaved, &ms_sLoadedDifficulty, &actionNext);
						m_bJustOneRealm = false;
					}
					break;
#endif
				//------------------------------------------------------------------------------
				// Oooops
				//------------------------------------------------------------------------------
				default:
					TRACE("GameCore(): Unrecognized action: %ld!\n", (int32_t)m_action);
					break;
				}

			// If this action lead to another action . . .
			if (actionNext != ACTION_NOTHING)
				{
				// Set current action to the next action
				m_action = actionNext;
				}
			else
				{
				// Reset action
				m_action = ACTION_NOTHING;
				}

			// If menu was taken away, restore the screen behind it
			if (!bMenuActive)
				{
				// If title requested . . .
				if (bTitleImage)
					{
					// Only use musak, if specified.
					StartTitle(0, bTitleMusak, &ms_siMusak);
					EndTitle();
					}
				}

			// Reset demo timer
			ResetDemoTimer();
			}
		}

	// Set the registry value before exiting
	GameSetRegistry();

	// If the menu is active, end it
	if (bMenuActive)
		{
		StopMenu();
		PalTranOff();
		bMenuActive = false;
		}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Reset temo timer
//
////////////////////////////////////////////////////////////////////////////////
static void ResetDemoTimer(void)
	{
	// Reset base time
	m_lDemoBaseTime = rspGetMilliseconds();
	
	// Change timeout to use persistant timeout
	m_lDemoTimeOut = g_GameSettings.m_lPersistentDemoTimeOut;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Get realm to be recorded
//
////////////////////////////////////////////////////////////////////////////////
static int16_t GetRealmToRecord(	// Returns 0 on success, negative on error, 1 if      
											// not subpathable (i.e., returned path is full path).
	char* pszRealmFile,				
	int16_t sMaxFileLen)
	{
	int16_t sResult = 0;

	// Static so dialog will "remember" the previously-used name
	static char	szFile[RSP_MAX_PATH]	= "";

	// If not yet used, start out in appropriate directory
//	if (szFile[0] == '\0')
		strcpy(szFile, FullPathHD(LEVEL_DIR));

	// Display open dialog to let user choose a file
	sResult = SubPathOpenBox(FullPathHD(""), "Choose Realm To Record", szFile, szFile, sizeof(szFile), "rlm");
	if (sResult >= 0)
		{
		// Convert path to RSPiX path.
		char*	pszFullPath	= rspPathFromSystem(szFile);
		// Check if result will fit into specified buffer
		if (strlen(pszFullPath) < sMaxFileLen)
			{
			strcpy(pszRealmFile, pszFullPath);
			}
		else
			{
			sResult = -1;
			TRACE("GetRealmToRecord(): File name too long to return in specified buffer!\n");
			}
	
		}
	return sResult;
	}

////////////////////////////////////////////////////////////////////////////////
//
// Get a subpath relative to the specified game path.
//
////////////////////////////////////////////////////////////////////////////////
extern int16_t SubPathOpenBox(		// Returns 0 on success, negative on error, 1 if 
											// not subpathable (i.e., returned path is full path).
	char*	pszFullPath,				// In:  Full path to be relative to (system format).
	char* pszBoxTitle,				// In:  Title of box.
	char*	pszDefFileName,			// In:  Default filename (system format).
	char* pszChosenFileName,		// Out: User's choice (system format).
	int16_t sStrSize,					// In:  Amount of memory pointed to by pszChosenFileName.
	char*	pszFilter /*= NULL*/)	// In:  If not NULL, '.' delimited extension based filename
											//	filter specification.  Ex: ".cpp.h.exe.lib" or "cpp.h.exe.lib"
											// Note: Cannot use '.' in filter.  Preceding '.' ignored.
	{
	int16_t	sResult;

	char	szBasePath[RSP_MAX_PATH];
	int32_t	lBasePathLen	= strlen(pszFullPath);
	if (lBasePathLen < sizeof(szBasePath) )
		{
		strcpy(szBasePath, pszFullPath);

		// Get index to last character
		int16_t sLastIndex = lBasePathLen;
		if (sLastIndex > 0)
			sLastIndex--;

		#ifdef WIN32
			// If base path doesn't end with a slash, add one
			if (szBasePath[sLastIndex] != RSP_SYSTEM_PATH_SEPARATOR)
				{
				if ((sLastIndex + 2) < RSP_MAX_PATH)
					{
					szBasePath[sLastIndex+1] = RSP_SYSTEM_PATH_SEPARATOR;
					szBasePath[sLastIndex+2] = 0;
					}
				else
					{
					sResult = -1;
					TRACE("SubPathOpenBox(): Path would've exceed max length with separator tacked on!\n");
					}
				}
		#else
			// If base path ends with a colon, get rid of it
			if (szBasePath[sLastIndex] == RSP_SYSTEM_PATH_SEPARATOR)
				szBasePath[sLastIndex] = 0;
		#endif

		char szChosenFileName[RSP_MAX_PATH];

		// Display open dialog to let user choose a file
		sResult = rspOpenBox(pszBoxTitle, pszDefFileName, szChosenFileName, sizeof(szChosenFileName), pszFilter);
		if (sResult == 0)
			{
			// Attempt to remove path from the specified name
			int32_t	lFullPathLen	= strlen(szBasePath);
			if (rspStrnicmp(szChosenFileName, szBasePath, lFullPathLen) == 0)
				{
				// Copy sub path to destination.
				strcpy(pszChosenFileName, szChosenFileName + lFullPathLen);
				}
			else
				{
				// Not subpathable.
				sResult	= 1;
				// Return fullpath.
				// Copy full path to destination.
				strcpy(pszChosenFileName, szChosenFileName);
				}
			}
		}
	else
		{
		sResult	= -2;
		TRACE("SubPathOpenBox(): pszFullPath string too long.\n");
		}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Get name of demo file
//
////////////////////////////////////////////////////////////////////////////////
static int16_t GetDemoFile(
	char* pszDemoFile,
	int16_t sMaxFileLen)
	{
	int16_t sResult = 0;
	
	// Static so dialog will "remember" the previously-used name
	static char szFile[RSP_MAX_PATH] = "";

	// If not yet used, start out in appropriate directory
	if (szFile[0] == '\0')
		strcpy(szFile, FullPathVD(DEMO_DIR));

	// Display save dialog to let user choose a file
	sResult = rspSaveBox(g_pszSaveDemoTitle, szFile, szFile, sizeof(szFile), DEMO_EXT);
	if (sResult == 0)
		{
		// Check if result will fit into specified buffer
		if (strlen(szFile) < sMaxFileLen)
			{
			strcpy(pszDemoFile, szFile);
			}
		else
			{
			sResult = -1;
			TRACE("GetDemoFile(): File name too long to return in specified buffer!\n");
			}
		}

	return sResult;
	}

////////////////////////////////////////////////////////////////////////////////
// Macro to get the sound SAK and (for the event there is no SAK) dir path.
////////////////////////////////////////////////////////////////////////////////
inline void GetSoundPaths(		// Returns nothing.
	int32_t	lSamplesPerSec,		// In:  The sample rate in samples per second.
	int32_t	lBitsPerSample,		// In:  The number of bits per sample.
	char* pszSakPath,				// Out: The subpath and name of the sound SAK.
										// Should be able to store at least RSP_MAX_PATH
										// characters here.
	char* pszNoSakDir)			// Out: The full path of the sound dir to use when 
										// there is no sak.
										// Should be able to store at least RSP_MAX_PATH
										// characters here.
	{
	// Make the SAK and base path name.
	char	szAudioResDescriptor[256];

	switch (g_GameSettings.m_sAudioLanguage)
	{
		case JAPANESE_AUDIO:
		sprintf(
			szAudioResDescriptor,
			"%ld%s%ld",
			lSamplesPerSec,
			AUDIO_SAK_SEPARATOR_CHAR_JAPANESE,
			lBitsPerSample);
		break;
		case ENGLISH_AUDIO:
		sprintf(
			szAudioResDescriptor,
			"%ld%s%ld",
			lSamplesPerSec,
			AUDIO_SAK_SEPARATOR_CHAR_ENGLISH,
			lBitsPerSample);
		break;
		default:
		sprintf(
			szAudioResDescriptor,
			"%ld%s%ld",
			lSamplesPerSec,
			AUDIO_SAK_SEPARATOR_CHAR,
			lBitsPerSample);
		break;
	}

	// Create the samples SAK sub path.
	strcpy(pszSakPath, SAMPLES_SAK_SUBDIR);
	strcat(pszSakPath, szAudioResDescriptor);
	strcat(pszSakPath, ".sak");

	// Create the samples NO SAK sub path.
	char	szSamplesNoSakSubPath[RSP_MAX_PATH];
	strcpy(szSamplesNoSakSubPath, "sound/");
	strcat(szSamplesNoSakSubPath, szAudioResDescriptor);
	// Note that g_GameSettings.m_szNoSakDir is already system
	// specific and already contains the appropriate ending
	// path delimiter, if any, appropriate to the current
	// platform.
	strcpy(pszNoSakDir, g_GameSettings.m_szNoSakDir);
	strcat(pszNoSakDir, rspPathToSystem(szSamplesNoSakSubPath) );
	}

////////////////////////////////////////////////////////////////////////////////
//
// Open SAKs or set equivalent base paths.
//
////////////////////////////////////////////////////////////////////////////////
static int16_t OpenSaks(void)
	{
	int16_t	sResult	= 0;	// Assume success.
#if TARGET == POSTAL_2015
	int16_t sXmasMode = 0;	// Assume no XMas mode
	time_t lTime;
	struct tm * timeinfo;
	RFile file;
	if (file.Open(FullPathSound(XMAS_SAK_FILENAME), "r", RFile::LittleEndian) == 0) 
	{
		// file is there, test if date is correct
		file.Close();
		time(&lTime);
		timeinfo = localtime (&lTime);
		// XMasMode between 17th and 31st of December
		if(timeinfo->tm_mon==11 && (timeinfo->tm_mday>=17 && timeinfo->tm_mday<=31))
			sXmasMode = 1;
	}
#endif	

	// Set base paths.
	g_resmgrShell.SetBasePath(g_GameSettings.m_szNoSakDir);
	g_resmgrGame.SetBasePath(g_GameSettings.m_szNoSakDir);
	g_resmgrRes.SetBasePath(FullPath(GAME_PATH_HD, "") );

	// Attempt to load the Game SAK . . .
	if (g_resmgrGame.OpenSak(FullPath(GAME_PATH_GAME, GAME_SAK_FILENAME) ) == 0)
		{
		}

#if TARGET == POSTAL_2015
	// is XMas mode activated ?
	if (sXmasMode)
	if (g_resmgrGame.OpenSakAlt(FullPath(GAME_PATH_GAME, XMAS_SAK_FILENAME), FullPath(GAME_PATH_GAME, XMAS_SCRIPT_FILENAME) ) == 0)
		{
		}
#endif

	// Attempt to load the Shell SAK . . .
	if ((g_resmgrShell.OpenSak(FullPath(GAME_PATH_HD, SHELL_SAK_FILENAME) ) == 0) ||
		 (g_resmgrShell.OpenSak(FullPath(GAME_PATH_VD, SHELL_SAK_FILENAME) ) == 0))
		{
		}

	////////////////////////////////////////////////////////////////////////////
	// The Samples res directory and SAK filename are based on the current
	// audio mode.
	////////////////////////////////////////////////////////////////////////////

	// Get the current audio mode, if any.
	int16_t	sInSoundMode;
	int32_t	lSamplesPerSec;
	int32_t	lDevBitsPerSample;
	int32_t	lSrcBitsPerSample;
	int32_t	lMixBitsPerSample;
	if (RMix::GetMode(				// Returns 0 on success;            
											// nonzero if no mode.              
			&lSamplesPerSec,			// Sample rate in samples per second
											// returned here, if not NULL.
			&lDevBitsPerSample,		// Bits per sample of device,
											// returned here, if not NULL.
			NULL,							// Number of channels (1 == mono, 
											// 2 == stereo) returned here, 
											// if not NULL.
			NULL,							// Amount of time in ms to lead the 
											// current play cursor returned here,
											// if not NULL.  This could also be 
											// described as the maximum amount of
											// time in ms that can occur between 
											// calls to rspDoSound.
			NULL,							// Maximum buffer time.  This is the amt
											// that *plBufferTime can be increased to.
											// This is indicative of how much space
											// was/will-be allocated for the sound
											// output device on rspLockSoundOut.
			&lMixBitsPerSample,		// Bits per sample at which samples are
											// mixed, if not NULL.
			&lSrcBitsPerSample)		// Bits per sample at which samples must
											// be to be mixed (0 if no requirement), 
											// if not NULL.
		== 0)
		{
		// Sample quality values set by rspGetSoundOutMode().

		// If no pref on src bits . . .
		if (lSrcBitsPerSample == 0)
			{
			// Set it to the mix quality.  This is a just in case as currently
			// these are always the same as set in main.cpp.
			lSrcBitsPerSample	= lMixBitsPerSample;
			}

		// Note that there is a real sound mode.
		sInSoundMode	= TRUE;
		}
	else
		{
		// In the case that there is no audio mode we still need to access one set of
		// samples so we assume Vanilla settings b/c these use less memory.
		lSamplesPerSec	= MAIN_VANILLA_AUDIO_RATE;
		lDevBitsPerSample	= lMixBitsPerSample = lSrcBitsPerSample = MAIN_VANILLA_AUDIO_BITS;
		
		// Note that there is no real sound mode.
		sInSoundMode	= FALSE;
		}

	// Actual sample rates can (and do) vary from system to system.  We need
	// to "round" the actual rate so it matches one of the specific rates that
	// we're looking for.  The variance we allow for is +/- one percent.
	if ((lSamplesPerSec >= (11025 - 110)) && (lSamplesPerSec <= (11025 + 110)))
		lSamplesPerSec = 11025;
	else if ((lSamplesPerSec >= (22050 - 220)) && (lSamplesPerSec <= (22050 + 220)))
		lSamplesPerSec = 22050;
	else if ((lSamplesPerSec >= (44100 - 441)) && (lSamplesPerSec <= (44100 + 441)))
		lSamplesPerSec = 44100;
	else
		{
		TRACE("OpenSaks(): Unsupported sample rate: %ld!\n", (int32_t)lSamplesPerSec);
		ASSERT(0);
		}

	char	szSamplesSakSubPath[RSP_MAX_PATH];
	char	szSamplesNoSakFullPath[RSP_MAX_PATH];
	GetSoundPaths(lSamplesPerSec, lSrcBitsPerSample, szSamplesSakSubPath, szSamplesNoSakFullPath);

	// Attempt to load the Sample SAK . . .
	if (g_resmgrSamples.OpenSak(FullPath(GAME_PATH_SOUND, szSamplesSakSubPath) ) == 0)
		{
		// Wahoo.  No worries.
#if TARGET == POSTAL_2015
			// Is Xmas mode activated? Is the audio setting on English (there is no Japanese audio for Christmas)?
			if (sXmasMode && g_GameSettings.m_sAudioLanguage == ENGLISH_AUDIO)
			{
				if(lSamplesPerSec==22050 && lSrcBitsPerSample==16)
				if (g_resmgrSamples.OpenSakAlt(FullPath(GAME_PATH_GAME, XMAS_SAK_SOUND), FullPath(GAME_PATH_GAME, XMAS_SCRIPT_SOUND) ) == 0)
					{
					}
			}
#endif
		}
	// Otherwise, if there's a dir for files when there's no SAK . . .
	else if (g_GameSettings.m_szNoSakDir[0] != '\0')
		{
		g_resmgrSamples.SetBasePath(szSamplesNoSakFullPath);
		}
	// Otherwise, . . .
	else
		{
		// If there's a sound mode that was successfully set up . . .
		if (sInSoundMode)
			{
			char	szSoundQuality[256];
			sprintf(szSoundQuality, "%.3f kHz, %hd Bit",
				(float)lSamplesPerSec/(float)1000,
				(int16_t)lSrcBitsPerSample,
				(MAIN_AUDIO_CHANNELS == 1) ? "Mono" : "Stereo");

			rspMsgBox(
				RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
				g_pszAppName,
				g_pszCannotOpenSoundFiles_s_s,
				szSoundQuality,
				szSoundQuality);

			// Failure.
			sResult	= 1;
			}
		else
			{
			// We've one last chance.  Try 'em all.  Technically, we've already
			// tried 22050, 8 (the 'Vanilla mode') if we got here, but let's try
			// them all to make sure.
			struct
				{
				int32_t	lSamplesPerSec;
				int32_t	lBitsPerSample;
				}	amodes[]	=
					{
						// Put the smaller ones first b/c they use less memory.
						{ 22050, 8 },
						{ 11025, 16 },
						{ 22050, 16 },
					};

			int16_t	sModeIndex;
			bool	bSakFound	= false;

			for (sModeIndex = 0; sModeIndex < NUM_ELEMENTS(amodes) && bSakFound == false; sModeIndex++)
				{
				// Get the appropriate sample SAK name.
				GetSoundPaths(amodes[sModeIndex].lSamplesPerSec, amodes[sModeIndex].lBitsPerSample, szSamplesSakSubPath, szSamplesNoSakFullPath);
			
				// Attempt to load the Sample SAK . . .
				if (g_resmgrSamples.OpenSak(FullPath(GAME_PATH_SOUND, szSamplesSakSubPath) ) == 0)
					{
					// Set values to determine SampleMaster quality.
					// This is probably not necessary when using no sound but let's be safe.
					lSamplesPerSec	= amodes[sModeIndex].lSamplesPerSec;
					lSrcBitsPerSample	= amodes[sModeIndex].lBitsPerSample;
					// Got one.
					bSakFound	= true;
#if TARGET == POSTAL_2015
					// Is Xmas mode activated? Is the audio setting on English (there is no Japanese audio for Christmas)?
					if (sXmasMode && g_GameSettings.m_sAudioLanguage == ENGLISH_AUDIO)
						{
						if(lSamplesPerSec==22050 && lSrcBitsPerSample==16)
						if (g_resmgrSamples.OpenSakAlt(FullPath(GAME_PATH_GAME, XMAS_SAK_SOUND), FullPath(GAME_PATH_GAME, XMAS_SCRIPT_SOUND) ) == 0)
							{
							}
						}
#endif
					}
				}

			// If no SAK found . . .
			if (bSakFound == false)
				{
				rspMsgBox(
					RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
					g_pszAppName,
					g_pszNoSoundFiles);

				// Failure.
				sResult	= 1;
				}
			}
		}

	// Set the appropriate quality.
	g_GameSettings.m_eCurSoundQuality	= (SampleMaster::SoundQuality)( ( (lSamplesPerSec / 11025) - 1) * 2 + ( (lDevBitsPerSample / 8) - 1) );

	// Set volumes based on quality's category adjustor.
	int16_t	i;
	for (i = 0; i < SampleMaster::MAX_NUM_SOUND_CATEGORIES; i++)
		{
		SetCategoryVolume((SampleMaster::SoundCategory)i, g_GameSettings.m_asCategoryVolumes[i] );
		}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Close SAKs and/or Purge() them.
//
////////////////////////////////////////////////////////////////////////////////
static void CloseSaks(void)
	{
	g_resmgrShell.Purge();
	g_resmgrShell.CloseSak();
	
	g_resmgrGame.Purge();
	g_resmgrGame.CloseSak();
	
	g_resmgrSamples.Purge();
	g_resmgrSamples.CloseSak();

	g_resmgrRes.Purge();
	g_resmgrRes.CloseSak();
	}


////////////////////////////////////////////////////////////////////////////////
//
// Load game data that we want around the entire game.
//
// I'm not entirely against just keeping all the game data global since that's
// the way it's always been done.  On the other hand, I kind of like the idea
// of using a similar mechanism for loading game data as I did for doing the
// game settings.  It allows various modules to automatically be included in
// the loading process, and keeps the data local to the module.  Back on the
// first hand, we'll probably be grouping data into large, wad-type files, so
// somehow it seems less compelling to try to keep the data separated within
// the app.
//
////////////////////////////////////////////////////////////////////////////////
static int16_t LoadAssets(void)
	{
	// Load font.
	if (g_fontBig.Load(FullPath(GAME_PATH_VD, BIG_FONT_FILE)) != 0)
		{
		TRACE("GameLoadAssets(): Error loading font: %s !\n", FullPath(GAME_PATH_VD, BIG_FONT_FILE));
		return -1;
		}

	// Load font, the smaller.
	if (g_fontPostal.Load(FullPath(GAME_PATH_VD, POSTAL_FONT_FILE) ) != 0)
		{
		TRACE("GameLoadAssets(): Error loading font: %s !\n", FullPath(GAME_PATH_VD, POSTAL_FONT_FILE));
		return -1;
		}

	int16_t i;
	int32_t lTotalTime = 0;
	for (i = 0; i < TitleGetNumTitles(); i++)
		lTotalTime += g_GameSettings.m_alTitleDurations[i];

	// Fake lots of loading with a simple timing loop
	int32_t	lTime;
	int32_t	lLastTime	= rspGetMilliseconds();
	int32_t	lEndTime		= lLastTime + lTotalTime;
	do
		{
		lTime		= rspGetMilliseconds();

		UpdateSystem();

		DoTitle(lTime - lLastTime);

		lLastTime	= lTime;

		} while (lTime < lEndTime && rspGetQuitStatus() == FALSE);

	// If we get this far, return success
	return 0;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Unload game data that was loaded by GameLoadAssets().
//
////////////////////////////////////////////////////////////////////////////////
static int16_t UnloadAssets(void)
	{
	return 0;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Start Single Player Game" menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_StartSinglePlayerGame(
	int16_t sMenuItem)
	{

	// we reset these as we go along.
	const bool usedCheats = ((Flag_Achievements & FLAG_USED_CHEATS) != 0);
	Flag_Achievements = FLAG_USED_M16 | FLAG_KILLED_EVERYTHING | FLAG_KILLED_ONLY_HOSTILES | FLAG_HIGHEST_DIFFICULTY;
	if (usedCheats)
		Flag_Achievements |= FLAG_USED_CHEATS;

	playthroughMS = 0;

// If its a spawn version, then don't allow them to play single player
// games, and to make it harder, we will take out some of the code for
// single player games so its harder to hack back in.
#ifndef SPAWN

	switch (sMenuItem)
		{
		// "ORIGINAL LEVELS"
		case 0:
			m_action = ACTION_PLAY_SINGLE;
			m_sRealmNum = 0;
			m_szRealmFile[0] = 0;
			m_bJustOneRealm = false;
			break;
			// "ADD-ON LEVELS"
			case 1:
				m_action = ACTION_PLAY_ADDON;
				m_sRealmNum = 0;
				m_szRealmFile[0] = 0;
				m_bJustOneRealm = false;
				break;
			case 2:
				m_action = ACTION_PLAY_ADDON2;
				m_sRealmNum = 0;
				m_szRealmFile[0] = 0;
				m_bJustOneRealm = false;
				break;
			case 3:
				m_action = ACTION_PLAY_ALL;
				m_sRealmNum = 0;
				m_szRealmFile[0] = 0;
				m_bJustOneRealm = false;
				break;
			case 4:
				#ifdef MOBILE
				m_action	= ACTION_CONTINUE_GAME;
				#endif
				break;
			case 5:
				#ifndef LOADLEVEL_REMOVED
				#ifndef LOADLEVEL_DIALOG
					{
					// Static so dialog will "remember" the previously-used name
					static char	szFile[RSP_MAX_PATH]	= "";

					// If not yet used, start out in appropriate directory
					if (szFile[0] == '\0')
						strcpy(szFile, FullPathHD(LEVEL_DIR));

					if (rspOpenBox("Load Realm", szFile, szFile, sizeof(szFile), ".rlm") == 0)
						{
						// Convert path from system format to rspix format so it matches the
						// way we normally call Play(), which is with a rspix path.
						rspPathFromSystem(szFile, m_szRealmFile);

						m_action = ACTION_PLAY_SINGLE;
						m_sRealmNum = -1;
						m_bJustOneRealm = true;
						}
					break;
					}
				#endif // LOADLEVEL_DIALOG
				#endif // LOADLEVEL_REMOVED
			case 6:
				m_action	= ACTION_LOAD_GAME;
				break;
			case 7:
				Game_StartChallengeGame(0); 
				break;
		}

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
#endif // SPAWN
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the Level Select
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_StartLevelOnce(
	int16_t sMenuItem)
	{

	// we reset these as we go along.
	const bool usedCheats = ((Flag_Achievements & FLAG_USED_CHEATS) != 0);
	Flag_Achievements = FLAG_USED_M16 | FLAG_KILLED_EVERYTHING | FLAG_KILLED_ONLY_HOSTILES | FLAG_HIGHEST_DIFFICULTY;
	if (usedCheats)
		Flag_Achievements |= FLAG_USED_CHEATS;

	playthroughMS = 0;

// If its a spawn version, then don't allow them to play single player
// games, and to make it harder, we will take out some of the code for
// single player games so its harder to hack back in.
#ifndef SPAWN

	m_action = ACTION_PLAY_ALL;
	m_sRealmNum = sMenuItem;
	m_szRealmFile[0] = 0;
	m_bJustOneRealm = true;

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
#endif // SPAWN
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Start MultiPlayer Game" menu
//
////////////////////////////////////////////////////////////////////////////////
extern bool Game_StartMultiPlayerGame(
	int16_t sMenuItem)
	{
	bool bAccept = true;

	#if defined(MULTIPLAYER_DISABLED)
		rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_OK, APP_NAME, g_pszMultiplayerDisabled);
		bAccept = false;
	#else
		// Do nothing if multiplayer is available
	#endif

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();

	return bAccept;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Join MultiPlayer Game" menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_JoinMultiPlayerGame(
	int16_t sMenuItem)
	{
	switch (sMenuItem)
		{
		// "BROWSE"
		case 0:
			m_action = ACTION_PLAY_BROWSE;
			break;

		// "CONNECT"
		case 1:
			m_action = ACTION_PLAY_CONNECT;
			break;
		}

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}


////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Host MultiPlayer Game" menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_HostMultiPlayerGame(
	int16_t sMenuItem)
	{
	switch (sMenuItem)
		{
		// "HOST"
		case 0:
			m_action = ACTION_PLAY_HOST;
			break;
		}

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Start Demo Game" menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_StartDemoGame(
	int16_t sMenuItem)
	{
	char*	pszDemoFile	= NULL;
	char	szLevelDir[RSP_MAX_PATH]	= "";
	char  szTitle[256] = "";
	TRACE("sMenuItem = %d\n", sMenuItem);
	switch (sMenuItem)
		{
#if TARGET == POSTAL_2015			
		case 0:
			sprintf(m_szDemoFile, "%s/default0.dmo", FullPathHD(DEMO_LEVEL_DIR));
			m_action = ACTION_DEMO_PLAYBACK;
			break;
		case 1:
			sprintf(m_szDemoFile, "%s/default1.dmo", FullPathHD(DEMO_LEVEL_DIR));
			m_action = ACTION_DEMO_PLAYBACK;
			break;
		case 2:
			sprintf(m_szDemoFile, "%s/default2.dmo", FullPathHD(DEMO_LEVEL_DIR));
			m_action = ACTION_DEMO_PLAYBACK;
			break;
#else
		// Browse for and Playback demo
		case 0:
		{
			// Get the filename of the demo to load.
			static char szFile[RSP_MAX_PATH] = "";
			sprintf(szLevelDir, "%s", DEMO_LEVEL_DIR);
			pszDemoFile = szFile;
			// If not yet used, start out in appropriate directory
			if (pszDemoFile[0] == '\0')
				strcpy(pszDemoFile, FullPathHD(szLevelDir) );

			// Display open dialog to let user choose a realm file
			sprintf(szTitle, "%s", DEMO_OPEN_TITLE);
			if (rspOpenBox(szTitle, pszDemoFile, m_szDemoFile, sizeof(m_szDemoFile), ".dmo") == 0)
			{
				m_action = ACTION_DEMO_PLAYBACK;
			}
		}
		break;

		// Play auto demo.
		case 1:
			// Clear demo filename.  This signifies that we should play one of 
			// the auto demos.
			m_szDemoFile[0]	= '\0';
			m_action = ACTION_DEMO_PLAYBACK;
			break;

		// Record demo
		case 2:
			m_action = ACTION_DEMO_RECORD;
#endif
		}

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}


////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Buy" option on the Main Menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_Buy(void)
	{
	rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_OK, APP_NAME, g_pszBuy);

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Editor" option on the Main Menu
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_StartEditor(void)
	{
	#if defined(EDITOR_DISABLED)
		rspMsgBox(RSP_MB_ICN_INFO | RSP_MB_BUT_OK, APP_NAME, g_pszEditorDisabled);
	#else
		m_action = ACTION_EDITOR;
	#endif

	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Controls" menu.
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_ControlsMenu(
	int16_t sMenuItem)
	{
	// Only do this if we're not currently in an action . . .
	if (m_action == ACTION_NOTHING)
		{
		switch (sMenuItem)
			{
			// Edit keyboard settings.
			case 0:
				m_action = ACTION_EDIT_INPUT_SETTINGS;
				break;

			// Edit mouse settings.
			case 1:
				m_action = ACTION_EDIT_INPUT_SETTINGS;
				break;

			// Edit joystick settings.
			case 2:
#if defined(ALLOW_JOYSTICK)
				m_action	= ACTION_EDIT_INPUT_SETTINGS;
#endif	// defined(ALLOW_JOYSTICK)
				break;
			}

		// The main game loop resets the demo timer whenever it notices any user input.
		// However, when the user is in a dialog or message box, the OS handles all the
		// user input, and the main game loop won't know anything about what's going on
		// in there.  If the user spends a long time in there, the demo timer will
		// expire.  We don't want that to happen, so we manually reset the demo timer
		// here in recognition of the fact that some kind of user input obviously occurred.
		ResetDemoTimer();
		}
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for "Audio Options" menu.
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_AudioOptionsChoice(	// Returns nothing.
	int16_t sMenuItem)							// In:  Chosen item.
	{
	switch (sMenuItem)
		{
		case 1:
			m_action = ACTION_POSTAL_ORGAN;
			break;
		case 2:
			// Reload the audio SAK for the correct language.
			// I was expecting to have to find a better place to put
			// this, so that it doesn't reload every single time the
			// option is changed, but it actually seems to be very quick
			// and even works mid-game... Sort of. It's still a bad idea
			// to do that, so I've greyed out the option on the pause
			// screen.
			g_resmgrSamples.Purge();
			g_resmgrSamples.CloseSak();
			OpenSaks();
			break;
		}
	}



////////////////////////////////////////////////////////////////////////////////
//
// Callback for the "Start Challenge" menu.
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_StartChallengeGame(	// Returns nothing.
	int16_t sChallengeNum)							//In: Path to realm to play.
	{
	char*	pszRealmFile	= NULL;
	char	szLevelDir[RSP_MAX_PATH]	= "";
	char	szTitle[256]					= "";

	if (sChallengeNum == 0)
	{
		// Run the Gauntlet.
		m_action = ACTION_PLAY_CHALLENGE;
		m_sRealmNum = 0;
		m_szRealmFile[0] = 0;
		m_bJustOneRealm = false;
	}
	else
	{
		// Convert path from system format to rspix format so it matches the
		// way we normally call Play(), which is with a rspix path.
		// MASSIVE BUG IN rspPathFromSystem() on the Mac -- it doesn't allow
		// the src and dst to be the same, even though the doc says it can!!!!
		// Workaround is to use temporary buffer.
		/*strcpy(m_szRealmFile, sChallengePath);
		char szTmp[RSP_MAX_PATH];
		strcpy(szTmp, m_szRealmFile);
		rspPathFromSystem(szTmp, m_szRealmFile);*/

		//Use RealNum to load the right Realm. So we get all the information (i.e. Background-Image and Text).
		m_action = ACTION_PLAY_CHALLENGE;
		m_sRealmNum = (sChallengeNum - 1); //Values in INI are 1-23, but RealmNum is zero-based
		m_bJustOneRealm = true;
	}
	
	// The main game loop resets the demo timer whenever it notices any user input.
	// However, when the user is in a dialog or message box, the OS handles all the
	// user input, and the main game loop won't know anything about what's going on
	// in there.  If the user spends a long time in there, the demo timer will
	// expire.  We don't want that to happen, so we manually reset the demo timer
	// here in recognition of the fact that some kind of user input obviously occurred.
	ResetDemoTimer();
	}

////////////////////////////////////////////////////////////////////////////////
//
// Callback for the Main Menu init/kill.
//
////////////////////////////////////////////////////////////////////////////////
extern void Game_InitMainMenu(	// Returns nothing.
	int16_t sInit)						// In:  TRUE, if initializing; FALSE, if killing.
	{
	// If initializing the menu . . .
	if (sInit)
		{
		}
	// Otherwise, killing the menu.
	else
		{
		// Abort the title/main-menu musak.
		AbortSample(ms_siMusak);
		// No need to reset ms_siMusak.
		}
	}

////////////////////////////////////////////////////////////////////////////////
//
// Game_SavePlayersGame - Save the realm, game type, difficulty, and stockpile
//
////////////////////////////////////////////////////////////////////////////////

extern int16_t Game_SavePlayersGame(
				char* pszSaveName,		// In:  Name of the save file
				int16_t sDifficulty)		// In:  Current realm difficulty.
{
	RFile rf;
	int16_t sResult = rf.Open(pszSaveName, "wb", RFile::LittleEndian);
	uint32_t ulFileVersion = CRealm::FileVersion;

	if (sResult == SUCCESS)
	{
		rf.Write(ulFileVersion);
		rf.Write(sDifficulty);
		rf.Write((int16_t)m_action);
		rf.Write(g_sRealmNumToSave);
		g_stockpile.Save(&rf);

		// new in version 48.
		rf.Write(Flag_Achievements);

		// new in version 49.
		rf.Write(playthroughMS);

		rf.Close();
	}

	return sResult;
}

////////////////////////////////////////////////////////////////////////////////
//
// Game_LoadPlayersGame - Load a previously saved game, restore the settings
//								  
////////////////////////////////////////////////////////////////////////////////

extern int16_t Game_LoadPlayersGame(
				char* pszSaveName,		// In:  Name of the saved game file to open
				int16_t* psDifficulty,		// Out: Saved game realm difficulty.
				ACTION* paction)			// Out: Saved game action.
{
	RFile rf;
	int16_t sResult = rf.Open(pszSaveName, "rb", RFile::LittleEndian);
	uint32_t ulFileVersion;

	if (sResult == SUCCESS)
	{
		rf.Read(&ulFileVersion);
		rf.Read(psDifficulty);
		// Store as 16 bit value (in case Read() fails (we want to keep original
		// functionality which read directly into m_action) ).
		int16_t	sAction	= (int16_t)*paction;
		// Read as 16 bit.
		rf.Read(&sAction);
		// Store as action.
		*paction			= (ACTION)sAction;

		rf.Read(&m_sRealmNum);
		g_stockpile.Load(&rf, ulFileVersion);

		// new in version 48.
		const bool usedCheats = ((Flag_Achievements & FLAG_USED_CHEATS) != 0);
		Flag_Achievements = 0;
		if (ulFileVersion >= 48)
			rf.Read(&Flag_Achievements);
		if (usedCheats)
			Flag_Achievements |= FLAG_USED_CHEATS;

		#if 0
		printf("achievements:\n");
		#define printflag(x) printf("%s: %s\n", #x, (Flag_Achievements & x) ? "true" : "false");
		printflag(FLAG_USED_M16);
		printflag(FLAG_USED_SHOTGUN);
		printflag(FLAG_USED_DBL_SHOTGUN);
		printflag(FLAG_USED_GRENADE);
		printflag(FLAG_USED_ROCKET);
		printflag(FLAG_USED_MOLOTOV);
		printflag(FLAG_USED_NAPALM);
		printflag(FLAG_USED_FLAMETHROWER);
		printflag(FLAG_USED_PROXIMITY_MINE);
		printflag(FLAG_USED_TIMED_MINE);
		printflag(FLAG_USED_REMOTE_MINE);
		printflag(FLAG_USED_BETTY_MINE);
		printflag(FLAG_USED_HEATSEEKER);
		printflag(FLAG_USED_SPRAY_CANNON);
		printflag(FLAG_USED_DEATHWAD);
		printflag(FLAG_USED_CHEATS);
		printflag(FLAG_KILLED_EVERYTHING);
		printflag(FLAG_KILLED_ONLY_HOSTILES);
		#undef printflag
		#endif

		// new in version 49.
		playthroughMS = -1;  // disable the achievement for old save games.
		if (ulFileVersion >= 49)
			rf.Read(&playthroughMS);

		rf.Close();

		g_bTransferStockpile = true;
	}

	return sResult;
}


////////////////////////////////////////////////////////////////////////////////
//
// GameEndingSequence - Start a demo of the last level
//
////////////////////////////////////////////////////////////////////////////////

void GameEndingSequence(void)
{
	// Prepare all settings for demo mode
	CSettings::PreDemo();

#if VIOLENT_LOCALE

	// If demo debug movie file is specified in prefs, open it now.  The RFile*
	// is does double-duty as a flag, where non-zero means movie mode is enabled.
	RFile* pfileDemoDebugMovie = 0;
	m_pfileRandom = 0;
	if (strlen(g_GameSettings.m_szDemoDebugMovie) > 0)
		{
		m_pfileRandom = new RFile;
		if (m_pfileRandom->Open(g_GameSettings.m_szDemoDebugMovie, "rb", RFile::LittleEndian) != 0)
			{
			delete m_pfileRandom;
			m_pfileRandom = 0;
			}
		}

	if (InputDemoInit() == 0)
		{
		// This is the special end of game demo, so set up the demo name
		sprintf(m_szDemoFile, "%s", FullPathCD(ENDING_DEMO_NAME));

		RFile	fileDemo;
		if (fileDemo.Open(m_szDemoFile, "rb", RFile::LittleEndian) == 0)
			{
			// Read name of realm file
			char szRealmFile[RSP_MAX_PATH];
			fileDemo.Read(szRealmFile);
			// Read whether it's a full path.
			int16_t	sRealmFileIsFullPath;
			fileDemo.Read(&sRealmFileIsFullPath);
			if (!fileDemo.Error())
				{
				// Load input demo data (must be BEFORE setting playback mode)
				if (InputDemoLoad(&fileDemo) == 0)
					{
					// End menu (now that we know there were no errors)
//					StopMenu();
//					PalTranOff();
//					bMenuActive = false;

					Play(
						NULL,									// No client (not network game)
						NULL,									// No server (not network game)
						INPUT_MODE_PLAYBACK,				// Input mode
						-1,									// Always use specific realm file
						szRealmFile,						// Realm file to be played
						false,								// Don't play just one realm
						false,								// Not challenge mode
						0,								// Not new single player Add On levels
						GetGameDifficulty(),				// Difficulty level
						false,								// Rejunenate (MP only)
						0,										// Time limit (MP only)
						0,										// Kill limit (MP only)
						0,										// Cooperative (MP only)
						0,										// Use cooperative mode (MP only)
						0,										// Frame time (MP only)
						pfileDemoDebugMovie);			// Demo mode file
					}
				else
					{
					TRACE("GameCore(): Couldn't load demo data!\n");
					rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileReadError_s, (char*) m_szDemoFile);
					}
				}
			else
				{
				TRACE("GameCore(): Couldn't load realm name!\n");
				rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileReadError_s, (char*) m_szDemoFile);
				}
			fileDemo.Close();
			}
		else
			{
			TRACE("GameCore(): Couldn't open demo file: '%s'\n", m_szDemoFile);
			rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszAppName, g_pszFileOpenError_s, (char*) m_szDemoFile);
			}
		// Reset demo file name for next time.
		m_szDemoFile[0] = 0;
		InputDemoKill();
		}

	if (m_pfileRandom)
		{
		// File may have been closed by Play() if an error occurred
		if (m_pfileRandom->IsOpen())
			m_pfileRandom->Close();
		delete m_pfileRandom;
		m_pfileRandom = 0;
		}

#endif // VIOLENT_LOCALE

	// Restore settings to what they were before demo mode
	CSettings::PostDemo();

	SetInputMode(INPUT_MODE_LIVE);  // take it out of demo mode so achievements can unlock.

	// Do the ending title sequence.
	Title_GameEndSequence();

	// Do special credits:
	Credits(&g_smidFinalSceneCredits);

	UnlockAchievement(ACHIEVEMENT_COMPLETE_GAME);

	if (playthroughMS < MAX_PLAYTHROUGH_ACHIEVEMENT_MS)
		UnlockAchievement(ACHIEVEMENT_COMPLETE_GAME_IN_X_MINUTES);
	if ((Flag_Achievements & FLAG_MASK_WEAPONS) == FLAG_USED_M16)
		UnlockAchievement(ACHIEVEMENT_USE_ONLY_M16);
	if (Flag_Achievements & FLAG_KILLED_EVERYTHING)
		UnlockAchievement(ACHIEVEMENT_KILL_EVERYTHING);
	if (Flag_Achievements & FLAG_KILLED_ONLY_HOSTILES)
		UnlockAchievement(ACHIEVEMENT_KILL_ONLY_HOSTILES);
	if (Flag_Achievements & FLAG_HIGHEST_DIFFICULTY)
		UnlockAchievement(ACHIEVEMENT_COMPLETE_GAME_ON_HARDEST);
}

////////////////////////////////////////////////////////////////////////////////
// Returns a ptr to just the portion of the file path that specifies the file
// name (excluding the path).
////////////////////////////////////////////////////////////////////////////////
static char* GetFileNameFromPath(	// Returns file name.
	char*	pszFullPath)					// In:  File's full path.
	{
	// Scan back for the separator or the beginning.
	char*	pszIndex	= pszFullPath + (strlen(pszFullPath) - 1);

	while (pszIndex >= pszFullPath && *pszIndex != RSP_SYSTEM_PATH_SEPARATOR)
		{
		pszIndex--;
		}

	return (pszIndex + 1);
	}

////////////////////////////////////////////////////////////////////////////////
// Opens the synchronization log with the specified access flags if in a 
// TRACENASSERT mode and synchronization logging is enabled.
// Also, opens the random log, if it is enabled via 
// g_GameSettings.m_szDebugMovie or something.
////////////////////////////////////////////////////////////////////////////////
static void OpenSynchLogs(			// Returns nothing.
	bool	bWriteLogs)					// In:  true to create log, false to compare.
	{
	m_pfileRandom = 0;
	if (strlen(g_GameSettings.m_szDemoDebugMovie) > 0)
		{
		m_pfileRandom = new RFile;
		if (m_pfileRandom->Open(
				g_GameSettings.m_szDemoDebugMovie, 
				bWriteLogs ? "wb" : "rb", 
				RFile::LittleEndian) != 0)
			{
			delete m_pfileRandom;
			m_pfileRandom = 0;
			}
		}

	#if defined(_DEBUG) || defined(TRACENASSERT)
		ms_lSynchLogSeq	= 0;
		if (g_GameSettings.m_szSynchLogFile[0] != '\0')
			{
			if (ms_fileSynchLog.Open(
					g_GameSettings.m_szSynchLogFile, 
					bWriteLogs ? "wb" : "rb", 
					RFile::LittleEndian) == 0)
				{
				// Success.
				}
			else
				{
				TRACE("OpenSynchLogs(): Failed to open 'if' log file \"%s\".\n",
					g_GameSettings.m_szSynchLogFile);
				}
			}
	#endif	// defined(_DEBUG) || defined(TRACENASSERT)

	m_bWriteLogs	= bWriteLogs;
	}

////////////////////////////////////////////////////////////////////////////////
// Closes the synchronization logs, if open.
////////////////////////////////////////////////////////////////////////////////
static void CloseSynchLogs(void)	// Returns nothing.
	{
	if (m_pfileRandom)
		{
		// File may have been closed by Play() if an error occurred
		if (m_pfileRandom->IsOpen())
			m_pfileRandom->Close();
		delete m_pfileRandom;
		m_pfileRandom = 0;
		}

	#if defined(_DEBUG) || defined(TRACENASSERT)
		if (ms_fileSynchLog.IsOpen() )
			{
			ms_fileSynchLog.Close();
			}
	#endif	// defined(_DEBUG) || defined(TRACENASSERT)
	}

////////////////////////////////////////////////////////////////////////////////
// Synchronization logger -- Call this function to log an expression and a user
// value in the synch log.  When active (if g_GameSettings.m_szSynchLog is
// a valid path and filename), if recording a demo, these calls are logged to
// a file including the calling file and line number.  When active, if playing
// back a demo, these calls are compared to those stored in the log and, if
// a discrepancy occurs, a modal dialog box will pop up with the pertinent info
// followed by an ASSERT(0) for easy debugging.
////////////////////////////////////////////////////////////////////////////////
extern int SynchLog(	// Result of expr.
	double	expr,		// In:  Expression to evaluate.
	char*		pszFile,	// In:  Calling file.
	int32_t		lLine,	// In:  Calling line.
	char*		pszExpr,	// In:  Original C++ source expression.
	U32		u32User)	// In:  A user value that is intended to be consistent.
	{
	#if defined(_DEBUG) || defined(TRACENASSERT)
		if (ms_fileSynchLog.IsOpen() )
			{
			if (m_bWriteLogs)
				{
				fprintf(
					ms_fileSynchLog.m_fs, 
					"[Seq: %ld] %s : %ld  <$%s$> == %0.8f; User == %lu\n", 
					ms_lSynchLogSeq++,
					GetFileNameFromPath(pszFile),
					lLine,
					pszExpr,
					expr,
					u32User);
				}
			else
				{
				char		szFileIn[RSP_MAX_PATH];
				char		szExprIn[1024];
				int32_t		lLineIn;
				int32_t		lSeqIn;
				double	exprIn;
				U32		u32UserIn;

				if (fscanf(
					ms_fileSynchLog.m_fs,
					"[Seq: %ld] %s : %ld  <$%1024[^$]$> == %g; User == %lu\n", 
					&lSeqIn,
					szFileIn,
					&lLineIn,
					szExprIn,
					&exprIn,
					&u32UserIn) == 6)
					{
					// Verify . . .
					if (	(rspStricmp(szFileIn, GetFileNameFromPath(pszFile) ) != 0)
						|| (lLineIn != lLine) 
						|| (exprIn != expr) 
						|| (u32UserIn != u32User) )
						{
						char	szOut[2048];
						sprintf(
							szOut,
							"'If' sequence (%ld) mismatch!\n\n"
							"   Was <<%s>> at %s(%ld) which got %g; User == %lu\n\n"
							"   Now <<%s>> at %s(%ld) which got %g; User == %lu",
							ms_lSynchLogSeq,
							szExprIn,
							szFileIn,
							lLineIn,
							exprIn,
							u32UserIn,
							pszExpr,
							GetFileNameFromPath(pszFile),
							lLine,
							expr,
							u32User);

						TRACE("%s\n\n", szOut);

						rspMsgBox(
							RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
							"Postal",
							szOut);

						// Make this easy to debug
						ASSERT(0);
						}

					ms_lSynchLogSeq++;
					}
				else
					{
					TRACE("Synch(): Error reading log file.\n");
					}
				}
			}
#else
		rspMsgBox(
			RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
			"Postal",
			"Synchronization logging is disabled for release mode for safety.\n");
#endif	// defined(_DEBUG) || defined(TRACENASSERT)

	return expr;
	}


////////////////////////////////////////////////////////////////////////////////
// GameGetRegistry
////////////////////////////////////////////////////////////////////////////////

static void GameGetRegistry(void)
{
#ifdef CHECK_EXPIRATION_DATE
	char szTime[40];
	char szTimeEncrypt[40];
	time_t lTime;
	DWORD dwTimeLength;
	DWORD dwSize = 255;
	char szData[256];
	char szName[256];
	int16_t sEncryptedKeyLength = 36;

	uint8_t szKey[40];

	// This is the encoded path name of the registry key where the value is stored
	szKey[0] = 0x07;
	szKey[1] = 0x29;
	szKey[2] = 0xbd;
	szKey[3] = 0x3a;
	szKey[4] = 0xba;
	szKey[5] = 0x22;
	szKey[6] = 0xbe;
	szKey[7] = 0x36;
	szKey[8] = 0xf5;
	szKey[9] = 0x22;
	szKey[10] = 0xfb;
	szKey[11] = 0x24;
	szKey[12] = 0xd0;
	szKey[13] = 0x3a;
	szKey[14] = 0xd4;
	szKey[15] = 0x71;
	szKey[16] = 0xcb;
	szKey[17] = 0x3e;
	szKey[18] = 0xd5;
	szKey[19] = 0x2a;
	szKey[20] = 0xec;
	szKey[21] = 0x29;
	szKey[22] = 0x89;
	szKey[23] = 0x30;
	szKey[24] = 0x8f;
	szKey[25] = 0x78;
	szKey[26] = 0x83;
	szKey[27] = 0x66;
	szKey[28] = 0xb4;
	szKey[29] = 0x40;
	szKey[30] = 0x86;
	szKey[31] = 0x66;
	szKey[32] = 0x8f;
	szKey[33] = 0x71;
	szKey[34] = 0x9b;
	szKey[35] = 0xfe;
	szKey[36] = 0x00;

#ifdef WIN32

	DWORD dwDisposition;
	DWORD dwType;
	DWORD dwNameSize = 255;
	HKEY hkResult;
	int32_t lError;
	int16_t sEncryptedValueLength = 9;


	uint8_t szIn[10];

	// This is the encoded name of the registry value itendifier
	szIn[0] = 0x07;
	szIn[1] = 0x29;
	szIn[2] = 0xa8;
	szIn[3] = 0x0f;
	szIn[4] = 0xa7;
	szIn[5] = 0x0c;
	szIn[6] = 0xa8;
	szIn[7] = 0x0e;
	szIn[8] = 0xfd;
	szIn[9] = 0x00;


	// Get the current time and convert it to a string so it can be encoded
	time( &lTime );
	sprintf(szTime, "%ld", lTime);

	// Decrypte the registry key path so the key can be opened
	Decrypt((char*) szKey, szName, sEncryptedKeyLength);
	szName[sEncryptedKeyLength-2] = 0;
	lError = RegCreateKeyEx(HKEY_LOCAL_MACHINE, szName, 0,
	               "", 	REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
						&hkResult, &dwDisposition);
	// Destroy the source and result.
	memset(szName, 0xeb, sEncryptedKeyLength);

	if (lError == ERROR_SUCCESS && lTime > g_lReleaseTime)
	{
		if (dwDisposition == REG_CREATED_NEW_KEY)
		// Write the initial value
		{
			// Make sure current value is after release value
			dwTimeLength = Encrypt(szTime, szTimeEncrypt, strlen(szTime));
			Decrypt((char*) szIn, szName, sEncryptedValueLength);
			szName[sEncryptedValueLength-2] = 0;
			RegSetValueEx(hkResult, szName, 0, REG_BINARY, (uint8_t *) szTimeEncrypt, dwTimeLength); 
			memset(szName, 0xeb, sEncryptedValueLength);
			g_lRegTime = lTime;
		}
		else
		{
			lError = RegEnumValue(hkResult, 0, szName, &dwNameSize, 0, &dwType, (uint8_t *) szData, &dwSize);
			if (lError != ERROR_SUCCESS)
				g_lRegTime = EXPIRATION_DATE;
			else
			{
				if (Decrypt(szData, szTime, dwSize) == 0)
				{
					szTime[dwSize] = 0;
					g_lRegTime = atol(szTime);
				}
				else
				{
					g_lRegTime = EXPIRATION_DATE;
				}
			}
		}
		RegCloseKey(hkResult);
	}
	else
	// If there was an error opening the registry key, then it will trace the error
	// message here.
	{
		LPVOID lpMsgBuf;

		FormatMessage( 
			 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			 NULL,
			 GetLastError(),
			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			 (LPTSTR) &lpMsgBuf,
			 0,
			 NULL 
		);

		// Display the string.
		TRACE((char*) lpMsgBuf);

		// Free the buffer.
		LocalFree( lpMsgBuf );

		// This failed either because it couldn't write, or because
		// the date has been set back before the release date, so 
		// force this to fail
		g_lRegTime = EXPIRATION_DATE;
 	}

#else // WIN32
	// Do mac version here.
	char szPath[512];
	time( &lTime );
	lTime -= ((365 * 70UL) + 17) * 24 * 60 * 60; // time_fudge 1900->1970

	// Open a prefs file and read the value, or write the value
	// if it is the first time.
	RFile rfPref;
	// If the file does not exist, then write the current date to the file 
	// as long as it is after the release date.
	macGetSpecialPath(MacPreferencesFolderType, true, szPath, 254);
	Decrypt((char*) szKey, szName, sEncryptedKeyLength);
	sEncryptedKeyLength = MAX(0, sEncryptedKeyLength - 2);
	szName[sEncryptedKeyLength] = 0;
	strcat(szPath, szName+19);
	if (rfPref.Open(szPath, "rb", RFile::LittleEndian) != SUCCESS)
	{
		if (rfPref.Open(szPath, "wb", RFile::LittleEndian) != SUCCESS)
		{
			// If the file cannot be created, then hose the program
			g_lRegTime = EXPIRATION_DATE;
		}
		else
		{
			// If the date is set back before the release of the beta, then hose the
			// program
			g_lRegTime = lTime;
			if (lTime < g_lReleaseTime)
				g_lRegTime = lTime = EXPIRATION_DATE;
			dwTimeLength = Encrypt((char*) &lTime, szTimeEncrypt, 4);
			rfPref.Write(&dwTimeLength);
			rfPref.Write(szTime, dwTimeLength); 
			rfPref.Close();
		}
	}
	// If the prefs file is here, then open it and read the last date
	else
	{
		rfPref.Read(&dwSize);
		rfPref.Read(szData, dwSize);
		rfPref.Close();	
		
		if (Decrypt(szData, (char*) &lTime, dwSize) == 0)
		{
			g_lRegTime = lTime;
		}
		else
		{
			g_lRegTime = EXPIRATION_DATE;
		}
	}
	

#endif // WIN32
	if (g_lRegTime < RELEASE_DATE)
		g_lRegTime = EXPIRATION_DATE;

#else // CHECK_EXPIRATION_DATE
	g_lRegTime = 0;
#endif // CHECK_EXPIRATION_DATE
}

////////////////////////////////////////////////////////////////////////////////
// GameSetRegistry
////////////////////////////////////////////////////////////////////////////////

static void GameSetRegistry(void)
{
#ifdef CHECK_EXPIRATION_DATE
	char szTimeEncrypt[40];
	time_t lTime;
	DWORD dwTimeLength;
	char szName[256];
	int16_t sEncryptedKeyLength = 36;
	uint8_t szKey[40];

	szKey[0] = 0x00;
	szKey[1] = 0x3e;
	szKey[2] = 0xde;
	szKey[3] = 0x28;
	szKey[4] = 0xda;
	szKey[5] = 0x46;
	szKey[6] = 0xdd;
	szKey[7] = 0x57;
	szKey[8] = 0xc2;
	szKey[9] = 0x34;
	szKey[10] = 0xc4;
	szKey[11] = 0x32;
	szKey[12] = 0xe8;
	szKey[13] = 0x3f;
	szKey[14] = 0xf8;
	szKey[15] = 0x2c;
	szKey[16] = 0xe8;
	szKey[17] = 0x3e;
	szKey[18] = 0xe8;
	szKey[19] = 0x2a;
	szKey[20] = 0xdc;
	szKey[21] = 0x03;
	szKey[22] = 0xff;
	szKey[23] = 0x14;
	szKey[24] = 0xfb;
	szKey[25] = 0x18;
	szKey[26] = 0xfe;
	szKey[27] = 0x1f;
	szKey[28] = 0xc9;
	szKey[29] = 0x35;
	szKey[30] = 0xe0;
	szKey[31] = 0x02;
	szKey[32] = 0xea;
	szKey[33] = 0x09;
	szKey[34] = 0xf1;
	szKey[35] = 0xf5;
	szKey[36] = 0x00;

#ifdef WIN32

	char szTime[40];
	DWORD dwDisposition;
	DWORD dwSize = 255;
	DWORD dwNameSize = 255;
	HKEY hkResult;
	int32_t lError;
	int16_t sEncryptedValueLength = 9;

	uint8_t szIn[10];

	szIn[0] = 0x07;
	szIn[1] = 0x29;
	szIn[2] = 0xa8;
	szIn[3] = 0x0f;
	szIn[4] = 0xa7;
	szIn[5] = 0x0c;
	szIn[6] = 0xa8;
	szIn[7] = 0x0e;
	szIn[8] = 0xfd;
	szIn[9] = 0x00;


	time( &lTime );
	lTime = MAX(lTime, g_lRegTime);
	sprintf(szTime, "%ld", lTime);

	Decrypt((char*) szKey, szName, sEncryptedKeyLength);
	szName[sEncryptedKeyLength-2] = 0;
	lError = RegCreateKeyEx(HKEY_LOCAL_MACHINE, szName, 0,
	               "", 	REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL,
						&hkResult, &dwDisposition);
	memset(szName, 0xea, sEncryptedKeyLength);

	if (lError == ERROR_SUCCESS)
	{
		// Make sure current value is after release value
		dwTimeLength = Encrypt(szTime, szTimeEncrypt, strlen(szTime));
		Decrypt((char*) szIn, szName, sEncryptedValueLength);
		szName[sEncryptedValueLength-2] = 0;
		RegSetValueEx(hkResult, szName, 0, REG_BINARY, (uint8_t *) szTimeEncrypt, dwTimeLength); 
		memset(szIn, 0xee, sEncryptedValueLength);
		RegCloseKey(hkResult);
	}
	else
	{
		LPVOID lpMsgBuf;

		FormatMessage( 
			 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			 NULL,
			 GetLastError(),
			 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			 (LPTSTR) &lpMsgBuf,
			 0,
			 NULL 
		);

		// Display the string.
		TRACE((char*) lpMsgBuf);

		// Free the buffer.
		LocalFree( lpMsgBuf );
 	}
#else // WIN32
	// Do the Mac version here
	char szPath[512];
	RFile rfPref;
	time( &lTime );
	lTime -= ((365 * 70UL) + 17) * 24 * 60 * 60; // time_fudge 1900->1970

	// Make sure the time is after the last registered time.
	lTime = MAX(lTime, (time_t) g_lRegTime);
 	dwTimeLength = Encrypt((char*) &lTime, szTimeEncrypt, 4);
	macGetSpecialPath(MacPreferencesFolderType, true, szPath, 254);
	Decrypt((char*) szKey, szName, sEncryptedKeyLength);
	sEncryptedKeyLength = MAX(0, sEncryptedKeyLength - 2);
	szName[sEncryptedKeyLength] = 0;
	strcat(szPath, szName+19);
	
 	if (rfPref.Open(szPath, "wb", RFile::LittleEndian) == SUCCESS)
 	{
 		rfPref.Write(&dwTimeLength);
 		rfPref.Write(szTimeEncrypt, dwTimeLength);
		rfPref.Close(); 	
 	}
	// Open the prefs file and write the value here.

#endif // WIN32

#endif // CHECK_EXPIRATION_DATE
}


////////////////////////////////////////////////////////////////////////////////
//
// Seed the random number generator
//
////////////////////////////////////////////////////////////////////////////////
extern void SeedRand(
	int32_t lSeed)
	{
	m_lRandom = lSeed;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Get a random number
//
////////////////////////////////////////////////////////////////////////////////
#if defined(_DEBUG) || defined(TRACENASSERT)
	extern int32_t GetRandomDebug(char* FILE_MACRO, int32_t LINE_MACRO)
		{
		// Get next random number
		int32_t lNewVal = (((m_lRandom = m_lRandom * 214013L + 2531011L) >> 16) & 0x7fff);

		if (m_pfileRandom)
			{
			if (m_bWriteLogs)
				{
				fprintf(
					m_pfileRandom->m_fs,
					"%s : %ld rand = %ld\n", 
					GetFileNameFromPath(FILE_MACRO),
					LINE_MACRO,
					lNewVal);
//				m_pfileRandom->Write(lNewVal);
//				m_pfileRandom->Write(LINE_MACRO);
//				m_pfileRandom->Write(FILE_MACRO);
				}
			else
				{
				int32_t lSavedVal;
				int32_t lSavedLine;
				char szSavedFile[1024];
				fscanf(
					m_pfileRandom->m_fs,
					"%s : %ld rand = %ld\n", 
					szSavedFile,
					&lSavedLine,
					&lSavedVal);
//				m_pfileRandom->Read(&lSavedVal);
//				m_pfileRandom->Read(&lSavedLine);
//				m_pfileRandom->Read(szSavedFile);

				if ((lSavedVal != lNewVal) || (lSavedLine != LINE_MACRO) || (rspStricmp(szSavedFile, GetFileNameFromPath(FILE_MACRO) ) != 0))
					{
					rspMsgBox(
						RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
						"Postal",
						"Random number sequence mismatch!\n\n"
						"   Was %s(%ld) which got %ld\n\n"
						"   Now %s(%ld) which got %ld",
						szSavedFile,
						(int32_t)lSavedLine,
						(int32_t)lSavedVal,
						GetFileNameFromPath(FILE_MACRO),
						LINE_MACRO,
						(int32_t)lNewVal);

					// Make this easy to debug
					ASSERT(0);
					}
				}
			}
		return lNewVal;
		}
#else
	extern int32_t GetRandom(void)
		{
		// Get next random number
		return (((m_lRandom = m_lRandom * 214013L + 2531011L) >> 16) & 0x7fff);
		}
#endif	// defined(_DEBUG) || defined(TRACENASSERT).


////////////////////////////////////////////////////////////////////////////////
//
// Define a rand() to take the place of the stdlib version.  We don't want
// anyone calling that version!
//
////////////////////////////////////////////////////////////////////////////////
// It seems that this only works in debug mode.  In release, the linker
// generates a fatal "multiple definitions of rand()" error.  For now, only
// do this in debug mode.
#ifdef _DEBUG
#ifndef PLATFORM_UNIX
extern int rand(void)
	{
	rspMsgBox(
		RSP_MB_ICN_INFO | RSP_MB_BUT_OK,
		"Postal",
		"The stdlib version of rand() was called.  It is forbidden within this application.");
	return 0;
	}
#endif
#endif


////////////////////////////////////////////////////////////////////////////////
//
// Do palette transition so menu can be displayed on top of existing background.
// NOTE: There must be a matching PalTranOff() for each PalTranOn()!!!
//
////////////////////////////////////////////////////////////////////////////////
extern void PalTranOn(
	int32_t lTime /* = -1 */)								// In:  How long transition should take (or -1 for default)
	{
	if (lTime == -1)
		lTime = NORMAL_PAL_TRAN_TIME;

	StartMenuTrans(lTime);

	// Do until done or keypress.
	while (DoPreMenuTrans() == false)
		UpdateSystem();
	}


////////////////////////////////////////////////////////////////////////////////
//
// Undo the palette transition to restore the original background colors.
//
////////////////////////////////////////////////////////////////////////////////
extern void PalTranOff(void)
	{
	// Do until done
	while (DoPostMenuTrans() == false)
		UpdateSystem();

	// Let paltran finish/clean up.
	EndMenuTrans(true);
	}


////////////////////////////////////////////////////////////////////////////////
//
// Set gamma/brighten-effect value.  Note that there is no value that results
//	in identity.  See Brightness / contrast below:
// RIGHT NOW THIS FUNCTION IS BEING USED TO CALL BRIGHTNESS CONTRAST:
//
////////////////////////////////////////////////////////////////////////////////
extern void SetGammaLevel(	// Returns nothing.
	int16_t sBase)				// New brighten value.
	{
	// For the time being, use this to control the other function:

	// Pick a contrast based on the chosen brightness.
	double dBrightness = double(sBase)/128.0 - 1.0;

	// Allow a larger range:
	dBrightness *= 2.0;

	// This was no clip
	//double dContrast = MIN(1.0 - dBrightness, dBrightness + 1.0);
	// Let's link contrast with brightness and clip:
	double dContrast = (dBrightness + 1.0); // needs to be a value of 1 to be neutral

	// With this scheme, contrast can never be more than +1.0 or less than 0.0
	SetBrightnessContrast(dBrightness,dContrast);
	// Update settings.
	g_GameSettings.m_sGammaVal	= sBase;

	return; // don't set gamma for now

	U8	au8RedMap[256];
	U8	au8GreenMap[256];
	U8	au8BlueMap[256];

	int16_t i;
	int16_t	sClipVal;
	for (	i = 0;
			i < 256; 
			i++)
		{
		sClipVal	= MAX((int16_t)0, MIN(int16_t(pow((double)i / 100.0, GAMMA_EXPONENT) * sBase), (int16_t)255));
		au8RedMap[i]	= (U8)sClipVal;
		au8GreenMap[i]	= (U8)sClipVal;
		au8BlueMap[i]	= (U8)sClipVal;
		}

	// Update map.
	rspSetPaletteMaps(
		0,
		256,
		au8RedMap,
		au8GreenMap,
		au8BlueMap,
		sizeof(U8));

	// Update hardware through new map.
	rspUpdatePalette();

	// Update settings.
	g_GameSettings.m_sGammaVal	= sBase;
	}

////////////////////////////////////////////////////////////////////////////////
//
//	Set Brightness and Contrast.  Zero (neutral) values yield and identity
// curve.  Valid input is from -1 to 1.
//
////////////////////////////////////////////////////////////////////////////////
extern	void	SetBrightnessContrast(
						double dBrightness,	// -1.0 = dim, 0.0 = normal, 1.0 = bright
						double dContrast		// -1.0 = low contrast, 0.0 = normal, 1.0 = high
						)
	{
	U8	au8RedMap[256];
	U8	au8GreenMap[256];
	U8	au8BlueMap[256];

	// I will scale the ranges to within reasonable limits:
	ASSERT( (dBrightness >= -1.0) || (dBrightness <= 1.0));
	//ASSERT( (dContrast >= -1.0) || (dContrast <= 1.0));

	//dContrast = dContrast + 1.0; // this IS the tangent value (0-2)

	int16_t i;
	double dScale = 1.0/128.0;
	for (i=0;i < 256; i++)
		{
		double dX = dScale * i - 1.0;
		int16_t sLev = int16_t(128.0 + 128.0 * (
			 ( ( ( ((1.0 - dContrast) * dX) - dBrightness) * dX) + dContrast) * dX
			 + dBrightness));

		if (sLev < 0) sLev = 0;
		if (sLev > 255) sLev = 255;

		au8RedMap[i]	= (U8)sLev;
		au8GreenMap[i]	= (U8)sLev;
		au8BlueMap[i]	= (U8)sLev;
		}

	// Update map.
	rspSetPaletteMaps(
		0,
		256,
		au8RedMap,
		au8GreenMap,
		au8BlueMap,
		sizeof(U8));

	// Update hardware through new map.
	rspUpdatePalette();
	//----------------------------------
	// set postal levels?
	}


////////////////////////////////////////////////////////////////////////////////
//
// Get gamma/brighten-effect value from palette map (not from settings).
//
////////////////////////////////////////////////////////////////////////////////
extern int16_t GetGammaLevel(void)	// Returns current brighten value.
	{
	return g_GameSettings.m_sGammaVal;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Create a full path out of a partial path.
//
// The partial path must be in "RSPiX neutral" format, which is pretty much
// like a partial Windows path, except with slashes instead of backslashes.
//
// BEWARE: The return value is a pointer to a static string, which means its
// contents are changed every time this function is called!  If you're just
// going to use the string and then be done with it, this should work fine, but
// if you need the string to stick around a while, you should probably do a
// strcpy() into your own string buffer.
//
// There are several variations - pick the one you like best.
//
////////////////////////////////////////////////////////////////////////////////

// This string is much larger than it needs to be in case the string
// size changes as a result of the conversion to system format, in which
// case our tests would miss it until it's too late.  A massive overrun
// will still cause a problem, but that would never happen :)
static char m_acFullPath[RSP_MAX_PATH + RSP_MAX_PATH];

extern char* FullPath(									// Returns full path in system format
	int16_t sPathType,										// In:  PATH_CD, PATH_HD, or PATH_VD
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with the specified base path (copy the string from the game settings)
	if (sPathType == GAME_PATH_CD)
		return FullPathCD(pszPartialPath);
	else if (sPathType == GAME_PATH_HD)
		return FullPathHD(pszPartialPath);
	else if (sPathType == GAME_PATH_VD)
		return FullPathVD(pszPartialPath);
	else if (sPathType == GAME_PATH_SOUND)
		return FullPathSound(pszPartialPath);
	else if (sPathType == GAME_PATH_GAME)
		return FullPathGame(pszPartialPath);
	else if (sPathType == GAME_PATH_HOODS)
		return FullPathHoods(pszPartialPath);
	else 
		{
		TRACE("FullPath(): Unknown path type: %d -- I predict an ASSERT() will occur soon...\n", (int16_t)sPathType);
		ASSERT(1);

		// In case they want to ignore the assert, just return a pointer to an empty string
		m_acFullPath[0] = 0;
		return m_acFullPath;
		}
	}


extern char* FullPathCD(								// Returns full path in system format
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszCDPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszCDPath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


extern char* FullPathHD(								// Returns full path in system format
	const char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszHDPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszHDPath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


extern char* FullPathVD(								// Returns full path in system format
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszVDPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszVDPath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


extern char* FullPathSound(								// Returns full path in system format
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszSoundPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszSoundPath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


extern char* FullPathGame(								// Returns full path in system format
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszGamePath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszGamePath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}

extern char* FullPathHoods(								// Returns full path in system format
	char* pszPartialPath)								// In:  Partial path in RSPiX format
	{
	// Start with proper base path
	ASSERT(strlen(g_GameSettings.m_pszHoodsPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, g_GameSettings.m_pszHoodsPath);
	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


extern char* FullPathCustom(							// Returns full path in system format
	char*	pszFullPath,									// In:  Full path in in RSPiX format.
	char* pszPartialPath)								// In:  Partial path in RSPiX format.
	{
	char*	pszFullSystemPath	= rspPathToSystem(pszFullPath);
	// Start with proper base path
	ASSERT(strlen(pszFullSystemPath) < RSP_MAX_PATH);
	strcpy(m_acFullPath, pszFullSystemPath);

	// Make sure partial path isn't too long.  It is possible that the conversion
	// to the system format will change its length slightly, but it shouldn't be
	// enough to make a real difference to this test.
	ASSERT(strlen(pszPartialPath) < RSP_MAX_PATH);

	// Check if the combination of the partial and base path will be too long.
	ASSERT((strlen(pszPartialPath) + strlen(m_acFullPath)) < RSP_MAX_PATH);

	// Convert specified partial path from rspix to system format, putting the
	// result immediately following the base path
	rspPathToSystem(pszPartialPath, m_acFullPath + strlen(m_acFullPath));

	// Make sure result isn't too long (our buffer can handle it, but it's still a problem)
	ASSERT(strlen(m_acFullPath) < RSP_MAX_PATH);

	// Return pointer to full path
	return m_acFullPath;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Correctify the specified base path.
//
// First, it ensures that the path is absolute (not relative).  Then, it ensures
// the path ends properly, either with or without the system-specific separator
// character, depending on which system we're running on.
//
////////////////////////////////////////////////////////////////////////////////
int16_t CorrectifyBasePath(								// Returns 0 if successfull, non-zero otherwise
	char* pszBasePath,									// I/O: Base path to be corrected
	int16_t sMaxPathLen)									// In:  Maximum length of base path
	{
	int16_t sResult = 0;

	// Make sure they aren't passing an empty string, which should be be left alone
	if (strlen(pszBasePath) > 0)
		{

		// Make sure they aren't passing a string that's already too large!
		if ((strlen(pszBasePath) + 1) <= sMaxPathLen)
			{

			//------------------------------------------------------------------------------
			// Convert path from relative to absolute.  We do this by setting the current
			// directory to the specified path and then asking for the current directory,
			// which is always returned as an absolute path.  If the path is already
			// absolute to begin with, it *should* be unchanged as a result.
			//------------------------------------------------------------------------------

			// Get original directory (let it allocate buffer of at LEAST specified size, more if needed)
			
			// 09/05/97, PPL
			// Apparently, the getcwd function works completely (well, maybe not completely) different
			// on the MAC.  We need to go ahead and allocate our own buffer and free it later because
			// if a NULL is passed in, a NULL is returned.  This should not have any adverse effects
			// on the PC version.
			//char* pszOrigDir = getcwd(NULL, RSP_MAX_PATH);
			char* pszOrigDir = (char*)malloc(RSP_MAX_PATH);
			if (pszOrigDir != NULL)
				{
				// Let's go ahead and get the current working directory here, once we're sure that
				// the string to store it has been properly allocated.
				pszOrigDir = getcwd(pszOrigDir, RSP_MAX_PATH);

				// Change to specified directory, which may be relative or absolute
				if (chdir(pszBasePath) == 0)
					{
					// Get directory, which is always returned as absolute
					if (getcwd(pszBasePath, sMaxPathLen) == NULL)
						{
						sResult = -1;
						TRACE("CorrectifyBasePath(): Couldn't get current directory (was set to '%s')!\n", pszBasePath);
						}
					}
				else
					{
					sResult = -1;
					TRACE("CorrectifyBasePath(): Couldn't change to specified directory: '%s'!\n", pszBasePath);
					}

				// Restore original directory
				if (chdir(pszOrigDir) != 0)
					{
					sResult = -1;
					TRACE("CorrectifyBasePath(): Couldn't restore original directory: '%s'!\n", pszOrigDir);
					}

				// Free buffer that was allocated by getcwd()
				free(pszOrigDir);
				pszOrigDir = 0;
				}

			//------------------------------------------------------------------------------
			// Ensure that path ends properly, either with or without the system-specific
			// separator character, depending on which system we're on.
			//------------------------------------------------------------------------------
			if (sResult == 0)
				{
				// Get index to last character
				int16_t sLastIndex = strlen(pszBasePath);
				if (sLastIndex > 0)
					sLastIndex--;

				#if 1 //def WIN32
					// If base path doesn't end with a slash, add one
					if (pszBasePath[sLastIndex] != RSP_SYSTEM_PATH_SEPARATOR)
						{
						if ((sLastIndex + 2) < RSP_MAX_PATH)
							{
							pszBasePath[sLastIndex+1] = RSP_SYSTEM_PATH_SEPARATOR;
							pszBasePath[sLastIndex+2] = 0;
							}
						else
							{
							sResult = -1;
							TRACE("CorrectifyBasePath(): Path would've exceed max length with separator tacked on!\n");
							}
						}
				#else
					// If base path ends with a colon, get rid of it
					if (pszBasePath[sLastIndex] == RSP_SYSTEM_PATH_SEPARATOR)
						pszBasePath[sLastIndex] = 0;
				#endif
				}
			}
		else
			{
			sResult = -1;
			TRACE("CorrectifyBasePath(): Specified path is already longer than the specified maximum length!\n");
			}
		}

	return sResult;
	}


////////////////////////////////////////////////////////////////////////////////
//
// Notification that we are about to be in the background.
//
////////////////////////////////////////////////////////////////////////////////
static void BackgroundCall(void)
	{
	// TRACE("Background\n");

	// Return CPU to OS.
	rspSetDoSystemMode(RSP_DOSYSTEM_SLEEP);

	// If cursor show level not already stored . . .
	if (ms_sForegroundCursorShowLevel == INVALID_CURSOR_SHOW_LEVEL)
		{
		// Store current cursor show level and then make cursor visible
		ms_sForegroundCursorShowLevel	= rspGetMouseCursorShowLevel();
		rspSetMouseCursorShowLevel(1);
		}
	}


////////////////////////////////////////////////////////////////////////////////
//
// Notification that we are about to be in the foreground.
//
////////////////////////////////////////////////////////////////////////////////
static void ForegroundCall(void)
	{
	// TRACE("Foreground\n");

	#if defined(_DEBUG)
		// Wake CPU.
		rspSetDoSystemMode(RSP_DOSYSTEM_TOLERATEOS);
	#else
		// Return CPU to us.
		rspSetDoSystemMode(RSP_DOSYSTEM_HOGCPU);
	#endif


	// If cursor show level stored . . .
	if (ms_sForegroundCursorShowLevel != INVALID_CURSOR_SHOW_LEVEL)
		{
		// Restore previous cursor show level
		rspSetMouseCursorShowLevel(ms_sForegroundCursorShowLevel);
		ms_sForegroundCursorShowLevel	= 0;

		// Reset the input.
		ClearLocalInput();

		// Flag that we're no longer storing the show level.
		ms_sForegroundCursorShowLevel = INVALID_CURSOR_SHOW_LEVEL;
		}
	}


////////////////////////////////////////////////////////////////////////////////
// Returns difficulty for games.
// Note that this function is only valid once after a difficulty adjustment
// and then it goes back to the default (g_GameSettings value).
////////////////////////////////////////////////////////////////////////////////
static int16_t GetGameDifficulty(void)	// Returns cached game difficulty.
	{
	int16_t sDifficulty	= g_GameSettings.m_sDifficulty;

	// If there is a cached difficulty . . .
	if (ms_sLoadedDifficulty != INVALID_DIFFICULTY)
		{
		// Return cached difficulty.
		sDifficulty	= ms_sLoadedDifficulty;

		// Clear cache.
		ms_sLoadedDifficulty = INVALID_DIFFICULTY;
		}

	return sDifficulty;
	}

////////////////////////////////////////////////////////////////////////////////
// Returns Title of a given Challenge-ID
////////////////////////////////////////////////////////////////////////////////
extern char* GetChallengeTitle(int16_t challengeID)
{
	char title[256];
	char fileName[256];
	Play_GetRealmInfo(false, false, true, 0, challengeID - 1, 0, fileName, 256, title, 256);
	return title;
}


////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////