File: game.cpp

package info (click to toggle)
tinymux 2.10.1.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,212 kB
  • ctags: 8,535
  • sloc: cpp: 111,587; sh: 5,867; ansic: 141; makefile: 139
file content (3705 lines) | stat: -rw-r--r-- 98,650 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
/*! \file game.cpp
 * \brief Main program and misc functions.
 *
 * $Id: game.cpp 5585 2012-05-07 16:59:46Z brazilofmux $
 *
 */

#include "copyright.h"
#include "autoconf.h"
#include "config.h"
#include "externs.h"

#include <signal.h>

#include "attrs.h"
#include "command.h"
#include "comsys.h"
#include "file_c.h"
#include "functions.h"
#include "help.h"
#include "mguests.h"
#include "muxcli.h"
#include "pcre.h"
#include "powers.h"
#ifdef REALITY_LVLS
#include "levels.h"
#endif // REALITY_LVLS

#if defined(INLINESQL)
#include <mysql.h>

MYSQL *mush_database = NULL;
#endif // INLINESQL

void do_dump(dbref executor, dbref caller, dbref enactor, int eval, int key)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);

#if defined(HAVE_WORKING_FORK)
    if (mudstate.dumping)
    {
        notify(executor, T("Dumping in progress. Try again later."));
        return;
    }
#endif
    notify(executor, T("Dumping..."));
    fork_and_dump(key);
}

// print out stuff into error file
//
void report(void)
{
    STARTLOG(LOG_BUGS, "BUG", "INFO");
    log_text(T("Command: \xE2\x80\x98"));
    log_text(mudstate.debug_cmd);
    log_text(T("\xE2\x80\x99"));
    ENDLOG;
    if (Good_obj(mudstate.curr_executor))
    {
        STARTLOG(LOG_BUGS, "BUG", "INFO");
        log_text(T("Player: "));
        log_name_and_loc(mudstate.curr_executor);
        if (  mudstate.curr_enactor != mudstate.curr_executor
           && Good_obj(mudstate.curr_enactor))
        {
            log_text(T(" Enactor: "));
            log_name_and_loc(mudstate.curr_enactor);
        }
        ENDLOG;
    }
}

/* ----------------------------------------------------------------------
 * regexp_match: Load a regular expression match and insert it into
 * registers.
 */

bool regexp_match
(
    UTF8 *pattern,
    UTF8 *str,
    int case_opt,
    UTF8 *args[],
    int nargs
)
{
    int matches;
    int i;
    const char *errptr;
    int erroffset;

    /*
     * Load the regexp pattern. This allocates memory which must be
     * later freed. A free() of the regexp does free all structures
     * under it.
     */

    pcre *re;
    if (  MuxAlarm.bAlarmed
       || (re = pcre_compile((char *)pattern, PCRE_UTF8|case_opt, &errptr, &erroffset, NULL)) == NULL)
    {
        /*
         * This is a matching error. We have an error message in
         * regexp_errbuf that we can ignore, since we're doing
         * command-matching.
         */
        return false;
    }

    // To capture N substrings, you need space for 3(N+1) offsets in the
    // offset vector. We'll allow 2N-1 substrings and possibly ignore some.
    //
    const int ovecsize = 6 * nargs;
    int *ovec = new int[ovecsize];

    /*
     * Now we try to match the pattern. The relevant fields will
     * automatically be filled in by this.
     */
    matches = pcre_exec(re, NULL, (char *)str, static_cast<int>(strlen((char *)str)), 0, 0, ovec, ovecsize);
    if (matches < 0)
    {
        delete [] ovec;
        MEMFREE(re);
        return false;
    }

    if (matches == 0)
    {
        // There were too many substring matches. See docs for
        // pcre_copy_substring().
        //
        matches = ovecsize / 3;
    }

    /*
     * Now we fill in our args vector. Note that in regexp matching,
     * 0 is the entire string matched, and the parenthesized strings
     * go from 1 to 9. We DO PRESERVE THIS PARADIGM, for consistency
     * with other languages.
     */

    for (i = 0; i < nargs; ++i)
    {
        args[i] = alloc_lbuf("regexp_match");
        if (pcre_copy_substring((char *)str, ovec, matches, i,
                                (char *)args[i], LBUF_SIZE) < 0)
        {
            free_lbuf(args[i]);
            args[i] = NULL;
        }
    }

    delete [] ovec;
    MEMFREE(re);
    return true;
}

/* ----------------------------------------------------------------------
 * atr_match: Check attribute list for wild card matches and queue them.
 */

static int atr_match1
(
    dbref thing,
    dbref parent,
    dbref player,
    UTF8  type,
    UTF8  *str,
    UTF8  *raw_str,
    int   check_exclude,
    int   hash_insert
)
{
    // See if we can do it.  Silently fail if we can't.
    //
    if (!could_doit(player, parent, A_LUSE))
    {
        return -1;
    }

    int match = 0;
    if (  (  AMATCH_CMD    == type
          && mudstate.bfNoCommands.IsSet(parent))
       || (  AMATCH_LISTEN == type
          && mudstate.bfNoListens.IsSet(parent)))
    {
        // We may need to process the hash_insert to support exclusion of
        // this parent's $-commands before we return no matches.
        //
        if (hash_insert)
        {
            // Because we know this object contains no commands, there is no
            // need to look at the attribute values.
            //
            atr_push();
            unsigned char *as;
            for (int atr = atr_head(parent, &as); atr; atr = atr_next(&as))
            {
                ATTR *ap = atr_num(atr);

                if (  ap
                   && 0 == (ap->flags & AF_NOPROG)
                   && (  !check_exclude
                      || (  0 == (ap->flags & AF_PRIVATE)
                         && !hashfindLEN(&(ap->number), sizeof(ap->number), &mudstate.parent_htab))))
                {
                    hashaddLEN(&(ap->number), sizeof(ap->number), &atr, &mudstate.parent_htab);
                }
            }
            atr_pop();
        }
        return match;
    }

    bool bFoundCommands = false;
    bool bFoundListens  = false;

    atr_push();
    unsigned char *as;
    for (int atr = atr_head(parent, &as); atr; atr = atr_next(&as))
    {
        ATTR *ap = atr_num(atr);

        // Never check NOPROG attributes.
        //
        if (  !ap
           || (ap->flags & AF_NOPROG))
        {
            continue;
        }

        // We need to grab the attribute even before we know whether we'll use
        // it or not in order to maintain cached knowledge about ^-Commands
        // and $-Commands.
        //
        dbref aowner;
        int   aflags;
        UTF8 buff[LBUF_SIZE];
        atr_get_str(buff, parent, atr, &aowner, &aflags);

        UTF8 *s = NULL;
        if (  0 == (aflags & AF_NOPROG)
           &&  (  AMATCH_CMD    == buff[0]
               || AMATCH_LISTEN == buff[0]))
        {
            s = (UTF8 *)strchr((char *)buff+1, ':');
            if (s)
            {
                if (AMATCH_CMD == buff[0])
                {
                    bFoundCommands = true;
                }
                else
                {
                    bFoundListens = true;
                }
            }
        }

        // If we aren't the bottom level, check if we saw this attr
        // before. Also exclude it if the attribute type is PRIVATE.
        //
        if (  check_exclude
           && (  (ap->flags & AF_PRIVATE)
              || (aflags & AF_PRIVATE)
              || hashfindLEN(&(ap->number), sizeof(ap->number), &mudstate.parent_htab)))
        {
            continue;
        }

        // If we aren't the top level, remember this attr so we
        // exclude it from now on.
        //
        if (hash_insert)
        {
            hashaddLEN(&(ap->number), sizeof(ap->number), &atr, &mudstate.parent_htab);
        }

        if (aflags & AF_NOPROG)
        {
            continue;
        }

        // Check for the leadin character after excluding the attrib.
        // This lets non-command attribs on the child block commands
        // on the parent.
        //
        if (buff[0] != type)
        {
            continue;
        }

        // Was there a ':'?
        //
        if (!s)
        {
            continue;
        }
        *s++ = '\0';

        UTF8 *args[NUM_ENV_VARS];
        if (  (  0 != (aflags & AF_REGEXP)
            && regexp_match(buff + 1, (aflags & AF_NOPARSE) ? raw_str : str,
                ((aflags & AF_CASE) ? 0 : PCRE_CASELESS), args, NUM_ENV_VARS))
           || (  0 == (aflags & AF_REGEXP)
              && wild(buff + 1, (aflags & AF_NOPARSE) ? raw_str : str,
                args, NUM_ENV_VARS)))
        {
            match = 1;
            CLinearTimeAbsolute lta;
            wait_que(thing, player, player, AttrTrace(aflags, 0), false, lta,
                NOTHING, 0,
                s,
                NUM_ENV_VARS, (const UTF8 **)args,
                mudstate.global_regs);

            for (int i = 0; i < NUM_ENV_VARS; i++)
            {
                if (args[i])
                {
                    free_lbuf(args[i]);
                }
            }
        }
    }
    atr_pop();

    if (bFoundCommands)
    {
        mudstate.bfNoCommands.Clear(parent);
        mudstate.bfCommands.Set(parent);
    }
    else
    {
        mudstate.bfCommands.Clear(parent);
        mudstate.bfNoCommands.Set(parent);
    }

    if (bFoundListens)
    {
        mudstate.bfNoListens.Clear(parent);
        mudstate.bfListens.Set(parent);
    }
    else
    {
        mudstate.bfListens.Clear(parent);
        mudstate.bfNoListens.Set(parent);
    }
    return match;
}

bool atr_match
(
    dbref thing,
    dbref player,
    UTF8  type,
    UTF8  *str,
    UTF8  *raw_str,
    bool check_parents
)
{
    int lev, result;
    bool exclude, insert;
    dbref parent;

    // If thing is halted or we are matching $-commands on a NO_COMMAND
    // object, don't check anything
    //
    if (  Halted(thing)
       || (  AMATCH_CMD == type
          && No_Command(thing)))
    {
        return false;
    }

    // If we're matching ^-commands, strip ANSI
    //
    if (AMATCH_LISTEN == type)
    {
        // Remember, strip_color returns a pointer to a static buffer
        // within itself.
        //
        str = strip_color(str);
    }

    // If not checking parents, just check the thing
    //
    bool match = false;
    if (!check_parents)
    {
        return (atr_match1(thing, thing, player, type, str, raw_str, false, false) > 0);
    }

    // Check parents, ignoring halted objects
    //
    exclude = false;
    insert = true;
    hashflush(&mudstate.parent_htab);
    ITER_PARENTS(thing, parent, lev)
    {
        if (!Good_obj(Parent(parent)))
        {
            insert = false;
        }
        result = atr_match1(thing, parent, player, type, str, raw_str,
            exclude, insert);
        if (result > 0)
        {
            match = true;
        }
        else if (result < 0)
        {
            return match;
        }
        exclude = true;
    }
    return match;
}

/* ---------------------------------------------------------------------------
 * notify_check: notifies the object #target of the message msg, and
 * optionally notify the contents, neighbors, and location also.
 */

static bool check_filter(dbref object, dbref player, int filter, const UTF8 *msg)
{
    int aflags;
    dbref aowner;
    UTF8 *buf = atr_pget(object, filter, &aowner, &aflags);
    if (!*buf)
    {
        free_lbuf(buf);
        return true;
    }

    reg_ref **preserve = NULL;
    preserve = PushRegisters(MAX_GLOBAL_REGS);
    save_global_regs(preserve);

    UTF8 *nbuf = alloc_lbuf("check_filter");
    UTF8 *dp = nbuf;
    mux_exec(buf, LBUF_SIZE-1, nbuf, &dp, object, player, player,
        AttrTrace(aflags, EV_FIGNORE|EV_EVAL|EV_TOP),
        NULL, 0);
    *dp = '\0';
    dp = nbuf;
    free_lbuf(buf);

    restore_global_regs(preserve);
    PopRegisters(preserve, MAX_GLOBAL_REGS);
    preserve = NULL;

    if (!(aflags & AF_REGEXP))
    {
        do
        {
            UTF8 *cp = parse_to(&dp, ',', EV_STRIP_CURLY);
            mudstate.wild_invk_ctr = 0;
            if (  MuxAlarm.bAlarmed
               || quick_wild(cp, msg))
            {
                free_lbuf(nbuf);
                return false;
            }
        } while (dp != NULL);
    }
    else
    {
        int case_opt = (aflags & AF_CASE) ? 0 : PCRE_CASELESS;
        do
        {
            int erroffset;
            const char *errptr;
            UTF8 *cp = parse_to(&dp, ',', EV_STRIP_CURLY);
            pcre *re;
            if (  !MuxAlarm.bAlarmed
               && (re = pcre_compile((char *)cp, PCRE_UTF8|case_opt, &errptr, &erroffset, NULL)) != NULL)
            {
                const int ovecsize = 33;
                int ovec[ovecsize];
                int matches = pcre_exec(re, NULL, (char *)msg, static_cast<int>(strlen((char *)msg)), 0, 0,
                    ovec, ovecsize);
                if (0 <= matches)
                {
                    MEMFREE(re);
                    free_lbuf(nbuf);
                    return false;
                }
                MEMFREE(re);
            }
        } while (dp != NULL);
    }
    free_lbuf(nbuf);
    return true;
}

static UTF8 *make_prefix(dbref object, dbref player, int prefix, const UTF8 *dflt)
{
    int aflags;
    dbref aowner;
    UTF8 *buf, *nbuf, *cp;

    buf = atr_pget(object, prefix, &aowner, &aflags);
    if (!*buf)
    {
        cp = buf;
        if (NULL == dflt)
        {
            safe_str(T("From "), buf, &cp);
            if (Good_obj(object))
            {
                safe_str(Moniker(object), buf, &cp);
            }
            else
            {
                safe_str(Moniker(player), buf, &cp);
            }
            safe_chr(',', buf, &cp);
        }
        else
        {
            safe_str(dflt, buf, &cp);
        }
    }
    else
    {
        reg_ref **preserve = NULL;
        preserve = PushRegisters(MAX_GLOBAL_REGS);
        save_global_regs(preserve);

        nbuf = cp = alloc_lbuf("add_prefix");
        mux_exec(buf, LBUF_SIZE-1, nbuf, &cp, object, player, player,
            AttrTrace(aflags, EV_FIGNORE|EV_EVAL|EV_TOP),
            NULL, 0);
        free_lbuf(buf);

        restore_global_regs(preserve);
        PopRegisters(preserve, MAX_GLOBAL_REGS);

        buf = nbuf;
    }
    if (cp != buf)
    {
        safe_chr(' ', buf, &cp);
    }
    *cp = '\0';
    return buf;
}

/* Do HTML escaping, converting < to &lt;, etc.  'dest' needs to be
 * allocated & freed by the caller.
 *
 * If you're using this to append to a string, you can pass in the
 * safe_{str|chr} (UTF8 **) so we can just do the append directly,
 * saving you an alloc_lbuf()...free_lbuf().  If you want us to append
 * from the start of 'dest', just pass in a 0 for 'destp'.
 *
 * Returns 0 if the copy succeeded, 1 if it failed.
 */
bool html_escape(const UTF8 *src, UTF8 *dest, UTF8 **destp)
{
    const UTF8 *msg_orig;
    bool ret = false;

    if (destp == 0)
    {
        UTF8 *temp = dest;
        destp = &temp;
    }

    for (msg_orig = src; msg_orig && *msg_orig && !ret; msg_orig++)
    {
        UTF8 *p = *destp;
        switch (*msg_orig)
        {
        case '<':
            safe_str(T("&lt;"), dest, destp);
            break;

        case '>':
            safe_str(T("&gt;"), dest, destp);
            break;

        case '&':
            safe_str(T("&amp;"), dest, destp);
            break;

        case '\"':
            safe_str(T("&quot;"), dest, destp);
            break;

        default:
            safe_chr(*msg_orig, dest, destp);
            break;
        }

        // For <>&\, this may cause an extra loop around before it figures out that we are
        // out of buffer, but no harm is done in this, and the common case is a single character.
        //
        if (p == *destp)
        {
            ret = true;
        }
    }
    **destp = 0;
    return ret;
}

void notify_check(dbref target, dbref sender, const mux_string &msg, int key)
{
    // If speaker is invalid or message is empty, just exit.
    //
    if (  !Good_obj(target)
       || 0 == msg.length_byte())
    {
        return;
    }

#ifdef WOD_REALMS
    if ((key & MSG_OOC) == 0)
    {
        if ((key & MSG_SAYPOSE) != 0)
        {
            if (REALM_DO_HIDDEN_FROM_YOU == DoThingToThingVisibility(target, sender, ACTION_IS_TALKING))
            {
                return;
            }
        }
        else
        {
            if (REALM_DO_HIDDEN_FROM_YOU == DoThingToThingVisibility(target, sender, ACTION_IS_MOVING))
            {
                return;
            }
        }
    }
#endif // WOD_REALMS

    // Enforce a recursion limit
    //
    mudstate.ntfy_nest_lev++;
    if (mudconf.ntfy_nest_lim <= mudstate.ntfy_nest_lev)
    {
        mudstate.ntfy_nest_lev--;
        return;
    }

    mux_string *msg_ns = new mux_string;
    mux_string *msgFinal = new mux_string;
    UTF8 *tp;
    UTF8 *prefix;
    dbref aowner,  recip, obj;
    int i, nargs, aflags;
    FWDLIST *fp;

    // If we want NOSPOOF output, generate it.  It is only needed if we are
    // sending the message to the target object.
    //
    if (key & MSG_ME)
    {
        if (  Nospoof(target)
           && target != sender
           && target != mudstate.curr_enactor
           && target != mudstate.curr_executor)
        {
            // I'd really like to use tprintf here but I can't because the
            // caller may have.  notify(target, tprintf(...)) is quite common
            // in the code.
            //
            msg_ns->import(T("["), 1);
            msg_ns->append(Moniker(sender));
            msg_ns->append_TextPlain(T("("), 1);
            msg_ns->append(sender);
            msg_ns->append_TextPlain(T(")"), 1);

            if (sender != Owner(sender))
            {
                msg_ns->append_TextPlain(T("{"), 1);
                msg_ns->append(Moniker(Owner(sender)));
                msg_ns->append_TextPlain(T("}"), 1);
            }

            if (sender != mudstate.curr_enactor)
            {
                msg_ns->append_TextPlain(T("<-("), 3);
                msg_ns->append(mudstate.curr_enactor);
                msg_ns->append_TextPlain(T(")"), 1);
            }

            switch (DecodeMsgSource(key))
            {
            case MSG_SRC_COMSYS:
                msg_ns->append_TextPlain(T(",comsys"));
                break;

            case MSG_SRC_KILL:
                msg_ns->append_TextPlain(T(",kill"));
                break;

            case MSG_SRC_GIVE:
                msg_ns->append_TextPlain(T(",give"));
                break;

            case MSG_SRC_PAGE:
                msg_ns->append_TextPlain(T(",page"));
                break;

            default:
                if (key & MSG_SAYPOSE)
                {
                    msg_ns->append_TextPlain(T(",saypose"));
                }
                break;
            }

            msg_ns->append_TextPlain(T("] "), 2);
        }
    }
    msg_ns->append(msg);

    // msg contains the raw message, msg_ns contains the NOSPOOFed msg.
    //
    bool check_listens = !Halted(target);
    switch (Typeof(target))
    {
    case TYPE_PLAYER:
        if (key & MSG_ME)
        {
            if (key & MSG_HTML)
            {
                raw_notify_html(target, *msg_ns);
            }
            else
            {
                msgFinal->import(*msg_ns);
                if (Html(target))
                {
                    msgFinal->encode_Html();
                }
                raw_notify(target, *msgFinal);
            }
        }
        if (!mudconf.player_listen)
        {
            check_listens = false;
        }

        // FALLTHROUGH

    case TYPE_THING:
    case TYPE_ROOM:

        // If we're in a pipe, objects can receive raw_notify if
        // they're not a player. (players were already notified
        // above.
        //
        if (  mudstate.inpipe
           && !isPlayer(target))
        {
            raw_notify(target, *msg_ns);
        }

        // Forward puppet message if it is for me.
        //
        bool has_neighbors = Has_location(target);
        dbref targetloc = where_is(target);
        bool is_audible = Audible(target);

        if ( (key & MSG_ME)
           && Puppet(target)
           && (target != Owner(target))
           && (  (key & MSG_PUP_ALWAYS)
              || (  targetloc != Location(Owner(target))
                 && targetloc != Owner(target))))
        {
            msgFinal->import(Moniker(target));
            msgFinal->append_TextPlain(T("> "), 2);
            msgFinal->append(*msg_ns);
            raw_notify(Owner(target), *msgFinal);
        }

        // Check for @Listen match if it will be useful.
        //
        UTF8 *msgPlain = alloc_lbuf("notify_check.plain");
        msg.export_TextPlain(msgPlain);
        bool pass_listen = false;
        UTF8 *args[NUM_ENV_VARS];
        nargs = 0;
        if (  check_listens
           && (key & (MSG_ME | MSG_INV_L))
           && H_Listen(target))
        {
            tp = atr_get("notify_check.790", target, A_LISTEN, &aowner, &aflags);
            if (*tp && wild(tp, msgPlain, args, NUM_ENV_VARS))
            {
                for (nargs = NUM_ENV_VARS; nargs && (!args[nargs - 1] || !(*args[nargs - 1])); nargs--)
                {
                    ; // Nothing
                }
                pass_listen = true;
            }
            free_lbuf(tp);
        }

        // If we matched the @listen or are monitoring, check the
        // USE lock.
        //
        bool pass_uselock = false;
        if (  (key & MSG_ME)
           && check_listens
           && (  pass_listen
              || Monitor(target)))
        {
            pass_uselock = could_doit(sender, target, A_LUSE);
        }

        // Process AxHEAR if we pass LISTEN, USElock and it's for me.
        //
        if (  (key & MSG_ME)
           && pass_listen
           && pass_uselock
           && mudstate.nHearNest <= 2)
        {
            mudstate.nHearNest++;
            if (sender != target)
            {
                did_it( sender, target, 0, NULL, 0, NULL, A_AHEAR, 0,
                        (const UTF8 **)args, nargs);
            }
            else
            {
                did_it( sender, target, 0, NULL, 0, NULL, A_AMHEAR, 0,
                        (const UTF8 **)args, nargs);
            }
            did_it( sender, target, 0, NULL, 0, NULL, A_AAHEAR, 0,
                    (const UTF8 **)args, nargs);
            mudstate.nHearNest--;
        }

        // Get rid of match arguments. We don't need them anymore.
        //
        if (pass_listen)
        {
            for (i = 0; i < nargs; i++)
            {
                if (args[i] != NULL)
                {
                    free_lbuf(args[i]);
                }
            }
        }

        // Process ^-listens if for me, MONITOR, and we pass USElock.
        //
        if (  (key & MSG_ME)
           && pass_uselock
           && sender != target
           && Monitor(target))
        {
            atr_match(target, sender, AMATCH_LISTEN, msgPlain, msgPlain, false);
        }

        // Deliver message to forwardlist members.
        //
        if ( (key & MSG_FWDLIST)
           && is_audible
           && check_filter(target, sender, A_FILTER, msgPlain))
        {
            fp = fwdlist_get(target);
            if (NULL != fp)
            {
                prefix = make_prefix(target, sender, A_PREFIX, NULL);
                msgFinal->import(prefix);
                free_lbuf(prefix);
                msgFinal->append(msg);

                for (i = 0; i < fp->count; i++)
                {
                    recip = fp->data[i];
                    if (  !Good_obj(recip)
                       || recip == target)
                    {
                        continue;
                    }
                    notify_check(recip, sender, *msgFinal,
                        MSG_ME | MSG_F_UP | MSG_F_CONTENTS | MSG_S_INSIDE | (key & (MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
                }
            }
        }

        // Deliver message through audible exits.
        //
        if (key & MSG_INV_EXITS)
        {
            DOLIST(obj, Exits(target))
            {
                recip = Location(obj);
                if (  Audible(obj)
                   && (  recip != target
                      && check_filter(obj, sender, A_FILTER, msgPlain)))
                {
                    prefix = make_prefix(obj, target, A_PREFIX, T("From a distance,"));
                    msgFinal->import(prefix);
                    free_lbuf(prefix);

                    msgFinal->append(msg);
                    notify_check(recip, sender, *msgFinal,
                        MSG_ME | MSG_F_UP | MSG_F_CONTENTS | MSG_S_INSIDE | (key & (MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
                }
            }
        }

        // Deliver message through neighboring audible exits.
        //
        if (  has_neighbors
           && (  (key & MSG_NBR_EXITS)
              || (  (key & MSG_NBR_EXITS_A)
                 && is_audible)))
        {
            // If from inside, we have to add the prefix string of
            // the container.
            //
            if (key & MSG_S_INSIDE)
            {
                prefix = make_prefix(target, sender, A_PREFIX, NULL);
                msgFinal->import(prefix);
                free_lbuf(prefix);

                msgFinal->append(msg);
            }
            else
            {
                msgFinal->import(msg);
            }

            mux_string *msgPrefixed2 = new mux_string;

            DOLIST(obj, Exits(Location(target)))
            {
                recip = Location(obj);
                if (  Good_obj(recip)
                   && Audible(obj)
                   && recip != targetloc
                   && recip != target
                   && check_filter(obj, sender, A_FILTER, msgPlain))
                {
                    prefix = make_prefix(obj, target, A_PREFIX, T("From a distance,"));
                    msgPrefixed2->import(prefix);
                    free_lbuf(prefix);

                    msgPrefixed2->append(*msgFinal);
                    notify_check(recip, sender, *msgPrefixed2,
                        MSG_ME | MSG_F_UP | MSG_F_CONTENTS | MSG_S_INSIDE | (key & (MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
                }
            }
            delete msgPrefixed2;
        }

        // Deliver message to contents.
        //
        if (  (  (key & MSG_INV)
              || (  (key & MSG_INV_L)
                 && pass_listen))
           && check_filter(target, sender, A_INFILTER, msgPlain))
        {
            // Don't prefix the message if we were given the MSG_NOPREFIX key.
            //
            if (key & MSG_S_OUTSIDE)
            {
                prefix = make_prefix(target, sender, A_INPREFIX, T(""));
                msgFinal->import(prefix);
                free_lbuf(prefix);

                msgFinal->append(msg);
            }
            else
            {
                msgFinal->import(msg);
            }

            DOLIST(obj, Contents(target))
            {
                if (obj != target)
                {
                    notify_check(obj, sender, *msgFinal,
                        MSG_ME | MSG_F_DOWN | MSG_S_OUTSIDE | (key & (MSG_HTML | MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
                }
            }
        }

        // Deliver message to neighbors.
        //
        if (  has_neighbors
           && (  (key & MSG_NBR)
              || (  (key & MSG_NBR_A)
                 && is_audible
                 && check_filter(target, sender, A_FILTER, msgPlain))))
        {
            if (key & MSG_S_INSIDE)
            {
                prefix = make_prefix(target, sender, A_PREFIX, T(""));
                msgFinal->import(prefix);
                free_lbuf(prefix);

                msgFinal->append(msg);
            }
            else
            {
                msgFinal->import(msg);
            }

            DOLIST(obj, Contents(targetloc))
            {
                if (  obj != target
                   && obj != targetloc)
                {
                    notify_check(obj, sender, *msgFinal,
                        MSG_ME | MSG_F_DOWN | MSG_S_OUTSIDE | (key & (MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
                }
            }
        }

        // Deliver message to container.
        //
        if (  has_neighbors
           && (  (key & MSG_LOC)
              || ( (key & MSG_LOC_A)
                 && is_audible
                 && check_filter(target, sender, A_FILTER, msgPlain))))
        {
            if (key & MSG_S_INSIDE)
            {
                prefix = make_prefix(target, sender, A_PREFIX, NULL);
                msgFinal->import(prefix);
                free_lbuf(prefix);
                msgFinal->append(msg);
            }
            else
            {
                msgFinal->import(msg);
            }

            notify_check(targetloc, sender, *msgFinal,
                MSG_ME | MSG_F_UP | MSG_S_INSIDE | (key & (MSG_SRC_MASK | MSG_SAYPOSE | MSG_OOC)));
        }
        free_lbuf(msgPlain);
    }
    delete msgFinal;
    delete msg_ns;
    mudstate.ntfy_nest_lev--;
}

void notify_check(dbref target, dbref sender, const UTF8 *msg, int key)
{
    // If speaker is invalid or message is empty, just exit.
    //
    if (  !Good_obj(target)
       || !msg
       || !*msg)
    {
        return;
    }

    mux_string *sMsg = new mux_string(msg);

    notify_check(target, sender, *sMsg, key);

    delete sMsg;
}

void notify_except(dbref loc, dbref player, dbref exception, const UTF8 *msg, int key)
{
    dbref first;

    if (loc != exception)
    {
        notify_check(loc, player, msg, MSG_ME_ALL | MSG_F_UP | MSG_S_INSIDE | MSG_NBR_EXITS_A | key);
    }
    DOLIST(first, Contents(loc))
    {
        if (first != exception)
        {
            notify_check(first, player, msg, MSG_ME | MSG_F_DOWN | MSG_S_OUTSIDE | key);
        }
    }
}

void notify_except2(dbref loc, dbref player, dbref exc1, dbref exc2, const UTF8 *msg)
{
    dbref first;

    if (  loc != exc1
       && loc != exc2)
    {
        notify_check(loc, player, msg, MSG_ME_ALL | MSG_F_UP | MSG_S_INSIDE | MSG_NBR_EXITS_A);
    }
    DOLIST(first, Contents(loc))
    {
        if (  first != exc1
           && first != exc2)
        {
            notify_check(first, player, msg, MSG_ME | MSG_F_DOWN | MSG_S_OUTSIDE);
        }
    }
}

/* ----------------------------------------------------------------------
 * Reporting of CPU information.
 */

static void report_timecheck
(
    dbref player,
    bool yes_screen,
    bool yes_log,
    bool yes_clear
)
{
    int thing, obj_counted;
    CLinearTimeDelta ltdPeriod, ltdTotal;
    CLinearTimeAbsolute ltaNow;
    ltaNow.GetUTC();
    ltdPeriod = ltaNow - mudstate.cpu_count_from;

    if (  yes_log
       && (LOG_TIMEUSE & mudconf.log_options))
    {
        start_log(T("OBJ"), T("CPU"));
        log_name(player);
        log_text(T(" checks object time use over "));
        log_number(ltdPeriod.ReturnSeconds());
        log_text(T(" seconds" ENDLINE));
    }
    else
    {
        yes_log = false;
        STARTLOG(LOG_ALWAYS, "WIZ", "TIMECHECK");
        log_name(player);
        log_text(T(" checks object time use over "));
        log_number(ltdPeriod.ReturnSeconds());
        log_text(T(" seconds"));
        ENDLOG;
    }

    obj_counted = 0;
    ltdTotal.Set100ns(0);

    // Step through the db. Care only about the ones that are nonzero.
    //
    DO_WHOLE_DB(thing)
    {
        CLinearTimeDelta &ltd = db[thing].cpu_time_used;
        if (ltd.Return100ns())
        {
            ltdTotal += ltd;
            long used_msecs = ltd.ReturnMilliseconds();
            obj_counted++;
            if (yes_log)
            {
                Log.tinyprintf(T("#%d\t%ld" ENDLINE), thing, used_msecs);
            }
            if (yes_screen)
            {
                raw_notify(player, tprintf(T("#%d\t%ld"), thing, used_msecs));
            }
            if (yes_clear)
            {
                ltd.Set100ns(0);
            }
        }
    }

    long lTotal = ltdTotal.ReturnMilliseconds();
    long lPeriod = ltdPeriod.ReturnSeconds();

    if (yes_screen)
    {
        raw_notify(player,
            tprintf(T("Counted %d objects using %ld msecs over %d seconds."),
            obj_counted, lTotal, lPeriod));
    }

    if (yes_log)
    {
        Log.tinyprintf(T("Counted %d objects using %ld msecs over %d seconds."),
            obj_counted, lTotal, lPeriod);
        end_log();
    }

    if (yes_clear)
    {
        mudstate.cpu_count_from = ltaNow;
    }
}

void do_timecheck(dbref executor, dbref caller, dbref enactor, int eval, int key)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);

    bool yes_screen, yes_log, yes_clear;

    yes_screen = yes_log = yes_clear = false;

    if (key == 0)
    {
        // No switches, default to printing to screen and clearing counters.
        //
        yes_screen = true;
        yes_clear = true;
    }
    else
    {
        if (key & TIMECHK_RESET)
        {
            yes_clear = true;
        }
        if (key & TIMECHK_SCREEN)
        {
            yes_screen = true;
        }
        if (key & TIMECHK_LOG)
        {
            yes_log = true;
        }
    }
    report_timecheck(executor, yes_screen, yes_log, yes_clear);
}

void do_shutdown
(
    dbref executor,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    UTF8 *message,
    const UTF8 *cargs[],
    int ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    if (!Can_SiteAdmin(executor))
    {
        notify(executor, NOPERM_MESSAGE);
        return;
    }

    raw_broadcast(0, T("GAME: Shutdown by %s"), Moniker(Owner(executor)));
    STARTLOG(LOG_ALWAYS, "WIZ", "SHTDN");
    log_text(T("Shutdown by "));
    log_name(executor);
    ENDLOG;

    STARTLOG(LOG_ALWAYS, "WIZ", "SHTDN");
    log_text(T("Shutdown status: "));
    log_text(message);
    ENDLOG;

    int fd;
    if (mux_open(&fd, mudconf.status_file, O_RDWR|O_CREAT|O_TRUNC|O_BINARY))
    {
        mux_write(fd, message, static_cast<unsigned int>(strlen((char *)message)));
        mux_write(fd, ENDLINE, sizeof(ENDLINE)-1);
        DebugTotalFiles++;
        if (mux_close(fd) == 0)
        {
            DebugTotalFiles--;
        }
    }

    // Do we perform a normal or an emergency shutdown? Normal
    // shutdown is handled by exiting the main loop in shovechars,
    // emergency shutdown is done here.
    //
    if (key & SHUTDN_PANIC)
    {
        // Close down the network interface.
        //
        emergency_shutdown();

        local_presync_database();
#if defined(TINYMUX_MODULES)
        ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
        while (NULL != p)
        {
            p->pSink->presync_database();
            p = p->pNext;
        }
        final_modules();
#endif // TINYMUX_MODULES

        // Close the attribute text db and dump the header db.
        //
#ifndef MEMORY_BASED
        // Save cached modified attribute list
        //
        al_store();
#endif // MEMORY_BASED

        pcache_sync();
        SYNC;
        CLOSE;

        STARTLOG(LOG_ALWAYS, "DMP", "PANIC");
        log_text(T("Panic dump: "));
        log_text(mudconf.crashdb);
        ENDLOG;
        dump_database_internal(DUMP_I_PANIC);
        STARTLOG(LOG_ALWAYS, "DMP", "DONE");
        log_text(T("Panic dump complete: "));
        log_text(mudconf.crashdb);
        ENDLOG;
    }

    // Set up for normal shutdown.
    //
    mudstate.shutdown_flag = true;
}

// There are several types of dumps:
//
// Type 0 - Normal   mudstate.dumping controlled
// Type 1 - Panic    uncontrolled but only one of these happening at a time.
// Type 2 - Restart  mudstate.dumping controlled.
// Type 3 - FLAT     mudstate.dumping controlled.
// Type 4 - signal   uncontrolled and if we fault twice, the game ends --
//                   see check_panicking.
//
// When changing this function and to keep forking dumps safe, keep in mind
// that the following combinations can be occuring at the same time. Don't
// touch each other's files.
//
// Type 0 and 2 are allowed to touch each other's files. Type 1 and 4 should not
// touch files used in Type 0 or Type 2.
//
typedef struct
{
    UTF8      **ppszOutputBase;
    const UTF8 *szOutputSuffix;
    bool        bUseTemporary;
    int         fType;
    const UTF8 *pszErrorMessage;
} DUMP_PROCEDURE;

static DUMP_PROCEDURE DumpProcedures[NUM_DUMP_TYPES] =
{
    { NULL,             T(""),     false, 0,                             T("") }, // 0 -- Handled specially.
    { &mudconf.crashdb, T(""),     false, UNLOAD_VERSION | UNLOAD_FLAGS, T("Opening crash file") }, // 1
    { &mudconf.indb,    T(""),     true,  OUTPUT_VERSION | OUTPUT_FLAGS, T("Opening input file") }, // 2
    { &mudconf.indb,   T(".FLAT"), false, UNLOAD_VERSION | UNLOAD_FLAGS, T("Opening flatfile")   }, // 3
    { &mudconf.indb,   T(".SIG"),  false, UNLOAD_VERSION | UNLOAD_FLAGS, T("Opening signalled flatfile")}  // 4
};

#if defined(WINDOWS_FILES)
#define POPEN_READ_OP "rb"
#define POPEN_WRITE_OP "wb"
#elif defined(UNIX_FILES)
#define POPEN_READ_OP "r"
#define POPEN_WRITE_OP "w"
#endif // UNIX_FILES

void dump_database_internal(int dump_type)
{
    UTF8 tmpfile[SIZEOF_PATHNAME+32];
    UTF8 outfn[SIZEOF_PATHNAME+32];
    UTF8 prevfile[SIZEOF_PATHNAME+32];
    FILE *f;

    if (  dump_type < 0
       || NUM_DUMP_TYPES <= dump_type)
    {
        return;
    }

    bool bPotentialConflicts = false;
#if defined(HAVE_WORKING_FORK)
    // If we are already dumping for some reason, and suddenly get a type 1 or
    // type 4 dump, basically don't touch mail and comsys files. The other
    // dump will take care of them as well as can be expected for now, and if
    // we try to, we'll just step on them.
    //
    if (  mudstate.dumping
       && (  dump_type == DUMP_I_PANIC
          || dump_type == DUMP_I_SIGNAL))
    {
        bPotentialConflicts = true;
    }
#endif // HAVE_WORKING_FORK

    // Call the local dump function only if another dump is not already
    // in progress.
    //
    local_dump_database(dump_type);
#if defined(TINYMUX_MODULES)
    ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->dump_database(dump_type);
        p = p->pNext;
    }
#endif // TINYMUX_MODULES

    if (0 < dump_type)
    {
        DUMP_PROCEDURE *dp = &DumpProcedures[dump_type];
        bool bOpen;

        mux_sprintf(outfn, sizeof(outfn), T("%s%s"), *(dp->ppszOutputBase), dp->szOutputSuffix);
        if (dp->bUseTemporary)
        {
            mux_sprintf(tmpfile, sizeof(tmpfile), T("%s.#%d#"), outfn, mudstate.epoch);
            RemoveFile(tmpfile);
            bOpen = mux_fopen(&f, tmpfile, T("wb"));
        }
        else
        {
            RemoveFile(outfn);
            bOpen = mux_fopen(&f, outfn, T("wb"));
        }

        if (bOpen)
        {
            DebugTotalFiles++;
            setvbuf(f, NULL, _IOFBF, 16384);
            db_write(f, F_MUX, dp->fType);
            if (fclose(f) == 0)
            {
                DebugTotalFiles--;
            }

            if (dp->bUseTemporary)
            {
                ReplaceFile(tmpfile, outfn);
            }
        }
        else
        {
            log_perror(T("DMP"), T("FAIL"), dp->pszErrorMessage, outfn);
        }

        if (!bPotentialConflicts)
        {
            if (mudconf.have_mailer)
            {
                if (mux_fopen(&f, mudconf.mail_db, T("wb")))
                {
                    DebugTotalFiles++;
                    dump_mail(f);
                    if (fclose(f) == 0)
                    {
                        DebugTotalFiles--;
                    }
                }
            }
            if (mudconf.have_comsys)
            {
                save_comsys(mudconf.comsys_db);
            }
        }
        return;
    }

    // Nuke our predecessor
    //
    if (mudconf.compress_db)
    {
        mux_sprintf(prevfile, sizeof(prevfile), T("%s.prev.gz"), mudconf.outdb);
        mux_sprintf(tmpfile, sizeof(tmpfile), T("%s.#%d#.gz"), mudconf.outdb, mudstate.epoch - 1);
        RemoveFile(tmpfile);
        mux_sprintf(tmpfile, sizeof(tmpfile), T("%s.#%d#.gz"), mudconf.outdb, mudstate.epoch);
        mux_sprintf(outfn, sizeof(outfn), T("%s.gz"), mudconf.outdb);

        f = popen((char *)tprintf(T("%s > %s"), mudconf.compress, tmpfile), POPEN_WRITE_OP);
        if (f)
        {
            DebugTotalFiles++;
            setvbuf(f, NULL, _IOFBF, 16384);
            db_write(f, F_MUX, OUTPUT_VERSION | OUTPUT_FLAGS);
            if (pclose(f) != -1)
            {
                DebugTotalFiles--;
            }
            ReplaceFile(outfn, prevfile);
            if (ReplaceFile(tmpfile, outfn) < 0)
            {
                log_perror(T("SAV"), T("FAIL"), T("Renaming output file to DB file"), tmpfile);
            }
        }
        else
        {
            log_perror(T("SAV"), T("FAIL"), T("Opening"), tmpfile);
        }
    }
    else
    {
        mux_sprintf(prevfile, sizeof(prevfile), T("%s.prev"), mudconf.outdb);
        mux_sprintf(tmpfile, sizeof(tmpfile), T("%s.#%d#"), mudconf.outdb, mudstate.epoch - 1);
        RemoveFile(tmpfile);
        mux_sprintf(tmpfile, sizeof(tmpfile), T("%s.#%d#"), mudconf.outdb, mudstate.epoch);

        if (mux_fopen(&f, tmpfile, T("wb")))
        {
            DebugTotalFiles++;
            setvbuf(f, NULL, _IOFBF, 16384);
            db_write(f, F_MUX, OUTPUT_VERSION | OUTPUT_FLAGS);
            if (fclose(f) == 0)
            {
                DebugTotalFiles--;
            }
            ReplaceFile(mudconf.outdb, prevfile);
            if (ReplaceFile(tmpfile, mudconf.outdb) < 0)
            {
                log_perror(T("SAV"), T("FAIL"), T("Renaming output file to DB file"), tmpfile);
            }
        }
        else
        {
            log_perror(T("SAV"), T("FAIL"), T("Opening"), tmpfile);
        }
    }

    if (mudconf.have_mailer)
    {
        if (mux_fopen(&f, mudconf.mail_db, T("wb")))
        {
            DebugTotalFiles++;
            dump_mail(f);
            if (fclose(f) == 0)
            {
                DebugTotalFiles--;
            }
        }
    }

    if (mudconf.have_comsys)
    {
        save_comsys(mudconf.comsys_db);
    }
}

static void dump_database(void)
{
    UTF8 *buff;

    mudstate.epoch++;

#if defined(HAVE_WORKING_FORK)
    if (mudstate.dumping)
    {
        STARTLOG(LOG_DBSAVES, "DMP", "DUMP");
        log_text(T("Waiting on previously-forked child before dumping... "));
        ENDLOG;

        while (mudstate.dumping)
        {
            // We have a forked dump in progress, so we will wait until the
            // child exits.
            //
            MuxAlarm.Sleep(time_1s);
        }
    }
    mudstate.dumping = true;
    mudstate.dumped  = 0;
#endif // HAVE_WORKING_FORK
    buff = alloc_mbuf("dump_database");
    mux_sprintf(buff, MBUF_SIZE, T("%s.#%d#"), mudconf.outdb, mudstate.epoch);

    STARTLOG(LOG_DBSAVES, "DMP", "DUMP");
    log_text(T("Dumping: "));
    log_text(buff);
    ENDLOG;

    local_presync_database();
#if defined(TINYMUX_MODULES)
    ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->presync_database();
        p = p->pNext;
    }
#endif // TINYMUX_MODULES

#ifndef MEMORY_BASED
    // Save cached modified attribute list
    //
    al_store();
#endif // MEMORY_BASED

    pcache_sync();

    dump_database_internal(DUMP_I_NORMAL);
    SYNC;

    STARTLOG(LOG_DBSAVES, "DMP", "DONE")
    log_text(T("Dump complete: "));
    log_text(buff);
    ENDLOG;
    free_mbuf(buff);

#if defined(HAVE_WORKING_FORK)
    // This doesn't matter. We are about the stop the game. However,
    // leave it in.
    //
    mudstate.dumping = false;
    local_dump_complete_signal();
#endif // HAVE_WORKING_FORK

#if defined(TINYMUX_MODULES)
    p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->dump_complete_signal();
        p = p->pNext;
    }
#endif // TINYMUX_MODULES
}

void fork_and_dump(int key)
{
#if defined(HAVE_WORKING_FORK)
    static volatile bool bRequestAccepted = false;

    // fork_and_dump is never called with mudstate.dumping true, but we'll
    // ensure that assertion now.
    //
    if (  bRequestAccepted
       || mudstate.dumping)
    {
        return;
    }
    bRequestAccepted = true;
#endif // HAVE_WORKING_FORK

    // If no options were given, then it means DUMP_TEXT+DUMP_STRUCT.
    //
    if (key == 0)
    {
        key = DUMP_TEXT+DUMP_STRUCT;
    }

    if (*mudconf.dump_msg)
    {
        raw_broadcast(0, T("%s"), mudconf.dump_msg);
    }
    check_mail_expiration();
    UTF8 *buff = alloc_lbuf("fork_and_dump");
    if (key & (DUMP_TEXT|DUMP_STRUCT))
    {
        STARTLOG(LOG_DBSAVES, "DMP", "CHKPT");
        if (key & DUMP_TEXT)
        {
            log_text(T("SYNCing"));
            if (key & DUMP_STRUCT)
            {
                log_text(T(" and "));
            }
        }
        if (key & DUMP_STRUCT)
        {
            mudstate.epoch++;
            mux_sprintf(buff, LBUF_SIZE, T("%s.#%d#"), mudconf.outdb, mudstate.epoch);
            log_text(T("Checkpointing: "));
            log_text(buff);
        }
        ENDLOG;
    }
    if (key & DUMP_FLATFILE)
    {
        STARTLOG(LOG_DBSAVES, "DMP", "FLAT");
        log_text(T("Creating flatfile: "));
        mux_sprintf(buff, LBUF_SIZE, T("%s.FLAT"), mudconf.outdb);
        log_text(buff);
        ENDLOG;
    }
    free_lbuf(buff);

    local_presync_database();
#if defined(TINYMUX_MODULES)
    ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->presync_database();
        p = p->pNext;
    }
#endif // TINYMUX_MODULES

#ifndef MEMORY_BASED
    // Save cached modified attribute list
    //
    al_store();
#endif // MEMORY_BASED

    pcache_sync();
    SYNC;

#if defined(HAVE_WORKING_FORK)
    mudstate.write_protect = true;
    int child = 0;
    bool bChildExists = false;
    mudstate.dumping = true;
    mudstate.dumped  = 0;
    bool bAttemptFork = mudconf.fork_dump;
#if !defined(HAVE_PREAD) \
 || !defined(HAVE_PWRITE)
    if (key & DUMP_FLATFILE)
    {
        // Don't attempt a fork()'ed @dump/flat without pread()/pwrite()
        // support.
        //
        bAttemptFork = false;
    }
#endif // !HAVE_PREAD !HAVE_PWRITE
#endif // HAVE_WORKING_FORK

    if (key & (DUMP_STRUCT|DUMP_FLATFILE))
    {
#if defined(HAVE_WORKING_FORK)
        if (bAttemptFork)
        {
            child = fork();
        }
        if (child == 0)
        {
            // If we don't clear this alarm, the child will eventually receive a
            // SIG_PROF.
            //
            MuxAlarm.Clear();
#endif // HAVE_WORKING_FORK

            if (key & DUMP_STRUCT)
            {
                dump_database_internal(DUMP_I_NORMAL);
            }
            if (key & DUMP_FLATFILE)
            {
                dump_database_internal(DUMP_I_FLAT);
            }
#if defined(HAVE_WORKING_FORK)
            if (mudconf.fork_dump)
            {
                _exit(0);
            }
        }
        else if (child < 0)
        {
            log_perror(T("DMP"), T("FORK"), NULL, T("fork()"));
        }
        else
        {
            mudstate.dumper = child;
            if (mudstate.dumper == mudstate.dumped)
            {
                // The child process executed and exited before fork() returned
                // to the parent process.  Without a process id, the parent's
                // SIGCHLD handler could not be certain that the pid of the
                // exiting process would match the pid of this child.
                //
                // At the this point, we can be sure, however, there's
                // nothing much left to do.
                //
                // See SIGCHLD handler in bsd.cpp.
                //
                mudstate.dumper = 0;
                mudstate.dumped = 0;
            }
            else
            {
                bChildExists = true;
            }
        }
#endif // HAVE_WORKING_FORK
    }

#if defined(HAVE_WORKING_FORK)
    mudstate.write_protect = false;
    if (!bChildExists)
    {
        // We have the ability to fork children, but we are not configured to
        // use it; or, we tried to fork a child and failed; or, we didn't
        // need to dump the structure or a flatfile; or, the child has finished
        // dumping already.
        //
        mudstate.dumper = 0;
        mudstate.dumping = false;
        local_dump_complete_signal();
#if defined(TINYMUX_MODULES)
        ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
        while (NULL != p)
        {
            p->pSink->dump_complete_signal();
            p = p->pNext;
        }
#endif // TINYMUX_MODULES
    }
    bRequestAccepted = false;
#endif // HAVE_WORKING_FORK

    if (*mudconf.postdump_msg)
    {
        raw_broadcast(0, T("%s"), mudconf.postdump_msg);
    }
}

#define LOAD_GAME_SUCCESS           0
#define LOAD_GAME_NO_INPUT_DB     (-1)
#define LOAD_GAME_CANNOT_OPEN     (-2)
#define LOAD_GAME_LOADING_PROBLEM (-3)

#ifdef MEMORY_BASED
static int load_game(void)
#else // MEMORY_BASED
static int load_game(int ccPageFile)
#endif // MEMORY_BASED
{
    FILE *f = NULL;
    UTF8 infile[SIZEOF_PATHNAME+8];
    struct stat statbuf;
    int db_format, db_version, db_flags;

    bool compressed = false;

    if (mudconf.compress_db)
    {
        mux_sprintf(infile, sizeof(infile), T("%s.gz"), mudconf.indb);
        if (stat((char *)infile, &statbuf) == 0)
        {
            f = popen((char *)tprintf(T(" %s < %s"), mudconf.uncompress, infile), POPEN_READ_OP);
            if (f != NULL)
            {
                DebugTotalFiles++;
                compressed = true;
            }
        }
    }

    if (!compressed)
    {
        mux_strncpy(infile, mudconf.indb, sizeof(infile)-1);
        if (stat((char *)infile, &statbuf) != 0)
        {
            // Indicate that we couldn't load because the input db didn't
            // exist.
            //
            return LOAD_GAME_NO_INPUT_DB;
        }

        if (!mux_fopen(&f, infile, T("rb")))
        {
            return LOAD_GAME_CANNOT_OPEN;
        }
        DebugTotalFiles++;
        setvbuf(f, NULL, _IOFBF, 16384);
    }

    // Ok, read it in.
    //
    STARTLOG(LOG_STARTUP, "INI", "LOAD")
    log_text(T("Loading: "));
    log_text(infile);
    ENDLOG
    if (db_read(f, &db_format, &db_version, &db_flags) < 0)
    {
        // Everything is not ok.
        //
        if (compressed)
        {
            if (pclose(f) != -1)
            {
                DebugTotalFiles--;
            }
        }
        else
        {
            if (fclose(f) == 0)
            {
                DebugTotalFiles--;
            }
        }
        f = 0;

        STARTLOG(LOG_ALWAYS, "INI", "FATAL")
        log_text(T("Error loading "));
        log_text(infile);
        ENDLOG
        return LOAD_GAME_LOADING_PROBLEM;
    }

    // Everything is ok.
    //
    if (compressed)
    {
        if (pclose(f) != -1)
        {
            DebugTotalFiles--;
        }
    }
    else
    {
        if (fclose(f) == 0)
        {
            DebugTotalFiles--;
        }
    }
    f = 0;

#ifndef MEMORY_BASED
    if (db_flags & V_DATABASE)
    {
        // It loaded an output file.
        //
        if (ccPageFile == HF_OPEN_STATUS_NEW)
        {
            STARTLOG(LOG_STARTUP, "INI", "LOAD");
            log_text(T("Attributes are not present in either the input file or the attribute database."));
            ENDLOG;
        }
    }
    else
    {
        // It loaded a flatfile.
        //
        if (ccPageFile == HF_OPEN_STATUS_OLD)
        {
            STARTLOG(LOG_STARTUP, "INI", "LOAD");
            log_text(T("Attributes present in both the input file and the attribute database."));
            ENDLOG;
        }
    }
#endif // !MEMORY_BASED

    if (mudconf.have_comsys)
    {
        load_comsys(mudconf.comsys_db);
    }

    if (mudconf.have_mailer)
    {
        if (mux_fopen(&f, mudconf.mail_db, T("rb")))
        {
            DebugTotalFiles++;
            setvbuf(f, NULL, _IOFBF, 16384);
            Log.tinyprintf(T("LOADING: %s" ENDLINE), mudconf.mail_db);
            load_mail(f);
            Log.tinyprintf(T("LOADING: %s (done)" ENDLINE), mudconf.mail_db);
            if (fclose(f) == 0)
            {
                DebugTotalFiles--;
            }
            f = 0;
        }
    }
    STARTLOG(LOG_STARTUP, "INI", "LOAD");
    log_text(T("Load complete."));
    ENDLOG;

    return LOAD_GAME_SUCCESS;
}


/*
 * match a list of things, using the no_command flag
 *
 * This seems to be always called with type == AMATCH_CMD...
 * So the fact that ansi_strip is done within atr_match only
 * brings about a if () performance hit...
 *
 */

bool list_check
(
    dbref thing,
    dbref player,
    UTF8  type,
    UTF8  *str,
    UTF8  *raw_str,
    bool check_parent
)
{
    bool bMatch = false;

    int limit = mudstate.db_top;
    while (NOTHING != thing)
    {
#ifdef REALITY_LVLS
        if ((thing != player)
           && (!(No_Command(thing)))
           && IsReal(thing, player))
#else
        if (  thing != player
           && !No_Command(thing))
#endif // REALITY_LVLS
        {
            bMatch |= atr_match(thing, player, type, str, raw_str, check_parent);
        }

        // Non-authoritative test of circular reference.
        //
        dbref next;
        if (  thing == (next = Next(thing))
           || --limit < 0
           || MuxAlarm.bAlarmed)
        {
            break;
        }
        thing = next;
    }
    return bMatch;
}

bool Hearer(dbref thing)
{
    if (  mudstate.inpipe
       && thing == mudstate.poutobj)
    {
        return true;
    }

    if (  Connected(thing)
       || Puppet(thing)
       || H_Listen(thing))
    {
        return true;
    }

    if (Monitor(thing))
    {
        if (mudstate.bfListens.IsSet(thing))
        {
            return true;
        }
        else if (mudstate.bfNoListens.IsSet(thing))
        {
            return false;
        }
        else
        {
            bool bFoundCommands = false;

            UTF8 *buff = alloc_lbuf("Hearer");
            atr_push();
            unsigned char *as;
            for (int atr = atr_head(thing, &as); atr; atr = atr_next(&as))
            {
                ATTR *ap = atr_num(atr);
                if (  !ap
                   || (ap->flags & AF_NOPROG))
                {
                    continue;
                }

                int   aflags;
                dbref aowner;
                atr_get_str(buff, thing, atr, &aowner, &aflags);

                if (aflags & AF_NOPROG)
                {
                    continue;
                }

                UTF8 *s = NULL;
                if (  AMATCH_CMD    == buff[0]
                   || AMATCH_LISTEN == buff[0])
                {
                    s = (UTF8 *)strchr((char *)buff+1, ':');
                    if (s)
                    {
                        if (AMATCH_CMD == buff[0])
                        {
                            bFoundCommands = true;
                        }
                        else
                        {
                            free_lbuf(buff);
                            atr_pop();
                            mudstate.bfListens.Set(thing);
                            return true;
                        }
                    }
                }
            }
            free_lbuf(buff);
            atr_pop();

            mudstate.bfNoListens.Set(thing);

            if (bFoundCommands)
            {
                mudstate.bfNoCommands.Clear(thing);
                mudstate.bfCommands.Set(thing);
            }
            else
            {
                mudstate.bfCommands.Clear(thing);
                mudstate.bfNoCommands.Set(thing);
            }
        }
    }
    return false;
}

void do_readcache(dbref executor, dbref caller, dbref enactor, int eval, int key)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);

    helpindex_load(executor);
    fcache_load(executor);
}

static void process_preload(void)
{
    dbref thing, parent, aowner;
    int aflags, lev;
    UTF8 *tstr;

    tstr = alloc_lbuf("process_preload.string");
    DO_WHOLE_DB(thing)
    {
        // Ignore GOING objects.
        //
        if (Going(thing))
        {
            continue;
        }

        scheduler.RunTasks(10);

        // Look for a STARTUP attribute in parents.
        //
        if (mudconf.run_startup)
        {
            ITER_PARENTS(thing, parent, lev)
            {
                if (H_Startup(thing))
                {
                    did_it(Owner(thing), thing, 0, NULL, 0, NULL, A_STARTUP,
                        0, NULL, 0);

                    // Process queue entries as we add them.
                    //
                    scheduler.RunTasks(10);
                    break;
                 }
            }
        }

        // Look for a FORWARDLIST attribute.
        //
        if (H_Fwdlist(thing))
        {
            atr_get_str(tstr, thing, A_FORWARDLIST, &aowner, &aflags);
            if (*tstr)
            {
                FWDLIST *fp = fwdlist_load(GOD, tstr);
                if (NULL != fp)
                {
                    fwdlist_set(thing, fp);

                    if (fp->data)
                    {
                        delete [] fp->data;
                    }
                    delete fp;
                    fp = NULL;
                }
            }
        }
    }
    free_lbuf(tstr);
}

#ifndef MEMORY_BASED

/*
 * ---------------------------------------------------------------------------
 * * info: display info about the file being read or written.
 */

static void info(int fmt, int flags, int ver)
{
    const UTF8 *cp;

    if (fmt == F_MUX)
    {
        cp = T("MUX");
    }
    else
    {
        cp = T("*unknown*");
    }
    Log.tinyprintf(T("%s version %d:"), cp, ver);
    if (  ver < MIN_SUPPORTED_VERSION
       || MAX_SUPPORTED_VERSION < ver)
    {
        Log.WriteString(T(" Unsupported version"));
        exit(1);
    }
    else if (  (  (  1 == ver
                  || 2 == ver)
               && (flags & MANDFLAGS_V2) != MANDFLAGS_V2)
            || (  3 == ver
               && (flags & MANDFLAGS_V3) != MANDFLAGS_V3)
            || (  4 == ver
               && (flags & MANDFLAGS_V4) != MANDFLAGS_V4))
    {
        Log.WriteString(T(" Unsupported flags"));
        exit(1);
    }
    if (flags & V_DATABASE)
        Log.WriteString(T(" Database"));
    if (flags & V_ATRNAME)
        Log.WriteString(T(" AtrName"));
    if (flags & V_ATRKEY)
        Log.WriteString(T(" AtrKey"));
    if (flags & V_ATRMONEY)
        Log.WriteString(T(" AtrMoney"));
    Log.WriteString(T(ENDLINE));
}

static const UTF8 *standalone_infile = NULL;
static const UTF8 *standalone_outfile = NULL;
static const UTF8 *standalone_basename = NULL;
static bool standalone_check = false;
static bool standalone_load = false;
static bool standalone_unload = false;

static void dbconvert(void)
{
    int setflags, clrflags, ver;
    int db_ver, db_format, db_flags;

    Log.SetBasename(T("-"));
    Log.StartLogging();

    SeedRandomNumberGenerator();

    pool_init(POOL_LBUF, LBUF_SIZE);
    pool_init(POOL_MBUF, MBUF_SIZE);
    pool_init(POOL_SBUF, SBUF_SIZE);
    pool_init(POOL_BOOL, sizeof(struct boolexp));
    pool_init(POOL_STRING, sizeof(mux_string));

    cf_init();

    // Decide what conversions to do and how to format the output file.
    //
    setflags = clrflags = ver = 0;
    bool do_redirect = false;

    bool do_write = true;
    if (standalone_check)
    {
        do_write = false;
    }
    if (standalone_load)
    {
        clrflags = 0xffffffff;
        setflags = OUTPUT_FLAGS;
        ver = OUTPUT_VERSION;
        do_redirect = true;
    }
    else if (standalone_unload)
    {
        clrflags = 0xffffffff;
        setflags = UNLOAD_FLAGS;
        ver = UNLOAD_VERSION;
    }

    // Open the database
    //
    init_attrtab();

    UTF8 dirfile[SIZEOF_PATHNAME];
    UTF8 *dirfile_c = dirfile;
    safe_copy_str(standalone_basename, dirfile, &dirfile_c, (SIZEOF_PATHNAME-1));
    safe_copy_str(T(".dir"), dirfile, &dirfile_c, (SIZEOF_PATHNAME-1));
    *dirfile_c = '\0';

    UTF8 pagfile[SIZEOF_PATHNAME];
    UTF8 *pagfile_c = pagfile;
    safe_copy_str(standalone_basename, pagfile, &pagfile_c, (SIZEOF_PATHNAME-1));
    safe_copy_str(T(".pag"), pagfile, &pagfile_c, (SIZEOF_PATHNAME-1));
    *pagfile_c = '\0';

    int cc = init_dbfile(dirfile, pagfile, 650);
    if (cc == HF_OPEN_STATUS_ERROR)
    {
        Log.tinyprintf(T("Can\xE2\x80\x99t open database in (%s, %s) files\n"), dirfile, pagfile);
        exit(1);
    }
    else if (cc == HF_OPEN_STATUS_OLD)
    {
        if (setflags == OUTPUT_FLAGS)
        {
            Log.tinyprintf(T("Would overwrite existing database (%s, %s)\n"), dirfile, pagfile);
            CLOSE;
            exit(1);
        }
    }
    else if (cc == HF_OPEN_STATUS_NEW)
    {
        if (setflags == UNLOAD_FLAGS)
        {
            Log.tinyprintf(T("Database (%s, %s) is empty.\n"), dirfile, pagfile);
            CLOSE;
            exit(1);
        }
    }

    FILE *fpIn;
    if (!mux_fopen(&fpIn, standalone_infile, T("rb")))
    {
        exit(1);
    }

    // Go do it.
    //
    if (do_redirect)
    {
        cache_redirect();
    }

    setvbuf(fpIn, NULL, _IOFBF, 16384);
    if (db_read(fpIn, &db_format, &db_ver, &db_flags) < 0)
    {
        cache_cleanup();
        exit(1);
    }

    if (do_redirect)
    {
        cache_pass2();
    }
    Log.WriteString(T("Input: "));
    info(db_format, db_flags, db_ver);

    if (standalone_check)
    {
        do_dbck(NOTHING, NOTHING, NOTHING, 0, DBCK_FULL);
    }
    fclose(fpIn);

    if (do_write)
    {
        FILE *fpOut;
        if (!mux_fopen(&fpOut, standalone_outfile, T("wb")))
        {
            exit(1);
        }

        db_flags = (db_flags & ~clrflags) | setflags;
        if (db_format != F_MUX)
        {
            db_ver = 3;
        }
        if (ver != 0)
        {
            db_ver = ver;
        }
        Log.WriteString(T("Output: "));
        info(F_MUX, db_flags, db_ver);
        setvbuf(fpOut, NULL, _IOFBF, 16384);
#ifndef MEMORY_BASED
        // Save cached modified attribute list
        //
        al_store();
#endif // MEMORY_BASED
        db_write(fpOut, F_MUX, db_ver | db_flags);
        fclose(fpOut);
    }
    CLOSE;
#ifdef SELFCHECK
    db_free();
#endif
    exit(0);
}
#endif // MEMORY_BASED

static void write_pidfile(const UTF8 *pFilename)
{
    FILE *fp;
    if (mux_fopen(&fp, pFilename, T("wb")))
    {
        mux_fprintf(fp, T("%d" ENDLINE), game_pid);
        fclose(fp);
    }
    else
    {
        STARTLOG(LOG_ALWAYS, "PID", "FAIL");
        Log.tinyprintf(T("Failed to write pidfile %s\n"), pFilename);
        ENDLOG;
    }
}

#ifdef INLINESQL
static void init_sql(void)
{
    if ('\0' != mudconf.sql_server[0])
    {
        STARTLOG(LOG_STARTUP,"SQL","CONN");
        log_text(T("Connecting: "));
        log_text(mudconf.sql_database);
        log_text(T("@"));
        log_text(mudconf.sql_server);
        log_text(T(" as "));
        log_text(mudconf.sql_user);
        ENDLOG;

        mush_database = mysql_init(NULL);

        if (mush_database)
        {
#ifdef MYSQL_OPT_RECONNECT
            // As of MySQL 5.0.3, the default is no longer to reconnect.
            //
            my_bool reconnect = 1;
            mysql_options(mush_database, MYSQL_OPT_RECONNECT, (const char *)&reconnect);
#endif
            mysql_options(mush_database, MYSQL_SET_CHARSET_NAME, "utf8");

            if (mysql_real_connect(mush_database,
                       (char *)mudconf.sql_server, (char *)mudconf.sql_user,
                       (char *)mudconf.sql_password,
                       (char *)mudconf.sql_database, 0, NULL, 0))
            {
#ifdef MYSQL_OPT_RECONNECT
                // Before MySQL 5.0.19, mysql_real_connect sets the option
                // back to default, so we set it again.
                //
                mysql_options(mush_database, MYSQL_OPT_RECONNECT, (const char *)&reconnect);
#endif
                STARTLOG(LOG_STARTUP,"SQL","CONN");
                log_text(T("Connected to MySQL"));
                ENDLOG;
            }
            else
            {
                STARTLOG(LOG_STARTUP,"SQL","CONN");
                log_text(T("Unable to connect"));
                ENDLOG;
                mysql_close(mush_database);
                mush_database = NULL;
            }
        }
        else
        {
            STARTLOG(LOG_STARTUP,"SQL","CONN");
            log_text(T("MySQL Library unavailable"));
            ENDLOG;
        }
    }
}

#endif // INLINESQL
long DebugTotalFiles = 3;
long DebugTotalSockets = 0;
#if defined(WINDOWS_NETWORKING)
long DebugTotalThreads = 1;
long DebugTotalSemaphores = 0;
#endif // WINDOWS_NETWORKING
#ifdef MEMORY_ACCOUNTING
long DebugTotalMemory = 0;
#endif

#define CLI_DO_CONFIG_FILE CLI_USER+0
#define CLI_DO_MINIMAL     CLI_USER+1
#define CLI_DO_VERSION     CLI_USER+2
#define CLI_DO_USAGE       CLI_USER+3
#define CLI_DO_INFILE      CLI_USER+4
#define CLI_DO_OUTFILE     CLI_USER+5
#define CLI_DO_CHECK       CLI_USER+6
#define CLI_DO_LOAD        CLI_USER+7
#define CLI_DO_UNLOAD      CLI_USER+8
#define CLI_DO_BASENAME    CLI_USER+9
#define CLI_DO_PID_FILE    CLI_USER+10
#define CLI_DO_ERRORPATH   CLI_USER+11

static bool bMinDB = false;
static bool bSyntaxError = false;
static const UTF8 *conffile = NULL;
static bool bVersion = false;
static const UTF8 *pErrorBasename = T("");
static bool bServerOption = false;

#define NUM_CLI_OPTIONS (sizeof(OptionTable)/sizeof(OptionTable[0]))
static CLI_OptionEntry OptionTable[] =
{
    { "c", CLI_REQUIRED, CLI_DO_CONFIG_FILE },
    { "s", CLI_NONE,     CLI_DO_MINIMAL     },
    { "v", CLI_NONE,     CLI_DO_VERSION     },
    { "h", CLI_NONE,     CLI_DO_USAGE       },
#ifndef MEMORY_BASED
    { "i", CLI_REQUIRED, CLI_DO_INFILE      },
    { "o", CLI_REQUIRED, CLI_DO_OUTFILE     },
    { "k", CLI_NONE,     CLI_DO_CHECK       },
    { "l", CLI_NONE,     CLI_DO_LOAD        },
    { "u", CLI_NONE,     CLI_DO_UNLOAD      },
    { "d", CLI_REQUIRED, CLI_DO_BASENAME    },
#endif // MEMORY_BASED
    { "p", CLI_REQUIRED, CLI_DO_PID_FILE    },
    { "e", CLI_REQUIRED, CLI_DO_ERRORPATH   }
};

static void CLI_CallBack(CLI_OptionEntry *p, const char *pValue)
{
    if (p)
    {
        switch (p->m_Unique)
        {
        case CLI_DO_PID_FILE:
            bServerOption = true;
            mudconf.pid_file = (UTF8 *)pValue;
            break;

        case CLI_DO_CONFIG_FILE:
            bServerOption = true;
            conffile = (UTF8 *)pValue;
            break;

        case CLI_DO_MINIMAL:
            bServerOption = true;
            bMinDB = true;
            break;

        case CLI_DO_VERSION:
            bServerOption = true;
            bVersion = true;
            break;

        case CLI_DO_ERRORPATH:
            bServerOption = true;
            pErrorBasename = (UTF8 *)pValue;
            break;

#ifndef MEMORY_BASED
        case CLI_DO_INFILE:
            mudstate.bStandAlone = true;
            standalone_infile = (UTF8 *)pValue;
            break;

        case CLI_DO_OUTFILE:
            mudstate.bStandAlone = true;
            standalone_outfile = (UTF8 *)pValue;
            break;

        case CLI_DO_CHECK:
            mudstate.bStandAlone = true;
            standalone_check = true;
            break;

        case CLI_DO_LOAD:
            mudstate.bStandAlone = true;
            standalone_load = true;
            break;

        case CLI_DO_UNLOAD:
            mudstate.bStandAlone = true;
            standalone_unload = true;
            break;

        case CLI_DO_BASENAME:
            mudstate.bStandAlone = true;
            standalone_basename = (UTF8 *)pValue;
            break;
#endif

        case CLI_DO_USAGE:
        default:
            bSyntaxError = true;
            break;
        }
    }
    else
    {
        bSyntaxError = true;
    }
}

#if defined(__INTEL_COMPILER) && defined(_M_IX86)

#define CPU_FD_ID 0x00200000UL

#define CPUID_0 0

// GenuineIntel
//
#define INTEL_MFGSTR_EBX  0x756E6547  // 'uneG'
#define INTEL_MFGSTR_ECX  0x6C65746E  // 'letn'
#define INTEL_MFGSTR_EDX  0x49656E69  // 'Ieni'

// AuthenticAMD
//
#define AMD_MFGSTR_EBX    0x68747541  // 'htuA'
#define AMD_MFGSTR_ECX    0x444D4163  // 'DMAc'
#define AMD_MFGSTR_EDX    0x69746E65  // 'itne'

#define CPUID_1 1

#define CPU_STEPPING(x)  ((x      ) & 0x00000000F)
#define CPU_MODEL(x)     ((x >>  4) & 0x00000000F)
#define CPU_FAMILY(x)    ((x >>  8) & 0x00000000F)
#define CPU_TYPE(x)      ((x >> 12) & 0x00000000F)
#define CPU_EXTMODEL(x)  ((x >> 16) & 0x00000000F)
#define CPU_EXTFAMILY(x) ((x >> 20) & 0x00000000F)

// Feature bits reported in EDX.
//
#define CPU_FEATURE_MMX     0x00800000UL
#define CPU_FEATURE_FSXR    0x01000000UL
#define CPU_FEATURE_SSE     0x02000000UL
#define CPU_FEATURE_SSE2    0x04000000UL

// Feature bits reported in ECX.
//
#define CPU_FEATURE2_SSE3   0x00000001UL
#define CPU_FEATURE2_DTES64 0x00000002UL
#define CPU_FEATURE2_SSSE3  0x00000200UL
#define CPU_FEATURE2_SSE41  0x00080000UL
#define CPU_FEATURE2_SSE42  0x00100000UL
#define CPU_FEATURE2_POPCNT 0x00800000UL
#define CPU_FEATURE2_AES    0x02000000UL

// Indicators.
//
// OLDOS tags indicate that the CPU supports SSE[n], but the operating system
// will throw an exception when they are used.
//
//
#define CPU_TYPE_UNSPECIALIZED               0x00000001UL
#define CPU_TYPE_FAMILY_5                    0x00000002UL
#define CPU_TYPE_FAMILY_6                    0x00000004UL
#define CPU_TYPE_FAMILY_5_MMX                0x00000008UL
#define CPU_TYPE_FAMILY_6_MMX                0x00000010UL
#define CPU_TYPE_FAMILY_6_MMX_FSXR           0x00000020UL
#define CPU_TYPE_FAMILY_6_MMX_FSXR_SSE_OLDOS 0x00000040UL
#define CPU_TYPE_FAMILY_6_MMX_FSXR_SSE       0x00000080UL
#define CPU_TYPE_FAMILY_F_SSE2_OLDOS         0x00000100UL
#define CPU_TYPE_FAMILY_F_SSE2               0x00000200UL
#define CPU_TYPE_FAMILY_6_MMX_FSXR_SSE2      0x00000400UL
#define CPU_TYPE_FAMILY_6_MMX_FSXR_SSE3      0x00000800UL
#define CPU_TYPE_FAMILY_F_SSE3               0x00000800UL
#define CPU_TYPE_FAMILY_6_SSSE3              0x00001000UL
#define CPU_TYPE_FAMILY_6_SSE41              0x00002000UL
#define CPU_TYPE_FAMILY_6_SSE42_POPCNT       0x00008000UL
#define CPU_TYPE_FAMILY_6_AES_DTE64          0x00010000UL

static void cpu_init(void)
{
    UINT32 dwCPUID;

    // Determine whether CPUID instruction is supported.
    //
    __asm
    {
        // Obtain a copy of the flags register.
        //
        pushfd
        pop     eax
        mov     dwCPUID,eax

        // Attempt to flip the ID bit.
        //
        xor     eax,CPU_FD_ID
        push    eax
        popfd

        // Obtain a second copy of the flags register.
        //
        pushfd
        pop     eax
        xor     dwCPUID,eax
    }

    // If the ID bit didn't toggle, the CPUID instruction is not supported.
    //
    if (CPU_FD_ID != dwCPUID)
    {
        // CPUID instruction is not supported.
        //
        __intel_cpu_indicator = CPU_TYPE_UNSPECIALIZED;
        return;
    }

    UINT32 dwHighest;
    UINT32 dwMfgStr_ebx;
    UINT32 dwMfgStr_ecx;
    UINT32 dwMfgStr_edx;

    // CPUID is supported.
    //
    __asm
    {
        mov eax,CPUID_0
        cpuid
        mov dwHighest,eax
        mov dwMfgStr_ebx,ebx
        mov dwMfgStr_ecx,ecx
        mov dwMfgStr_edx,edx
    }

    if (0 == dwHighest)
    {
        // We can't decipher anything with only CPUID (EAX=$0) available.
        //
        __intel_cpu_indicator = CPU_TYPE_UNSPECIALIZED;
        return;
    }

    typedef enum
    {
        Intel = 0,
        AMD
    } CPUMaker;

    CPUMaker maker;
    if (  INTEL_MFGSTR_EBX == dwMfgStr_ebx
       && INTEL_MFGSTR_ECX == dwMfgStr_ecx
       && INTEL_MFGSTR_EDX == dwMfgStr_edx)
    {
        maker = Intel;
    }
    else if (  AMD_MFGSTR_EBX == dwMfgStr_ebx
            && AMD_MFGSTR_ECX == dwMfgStr_ecx
            && AMD_MFGSTR_EDX == dwMfgStr_edx)
    {
        maker = AMD;
    }
    else
    {
        // It's not Intel or AMD.
        //
        __intel_cpu_indicator = CPU_TYPE_UNSPECIALIZED;
        return;
    }

    UINT32 dwSignature;
    UINT32 dwBrand;
    UINT32 dwFeatures2;
    UINT32 dwFeatures;

    __asm
    {
        mov eax,CPUID_1
        cpuid
        mov dwSignature,eax
        mov dwBrand,ebx
        mov dwFeatures2,ecx
        mov dwFeatures,edx
    }

    (void)(dwBrand);

    // Develop 'Effective' Family and Model.
    //
    UINT32 dwEffFamily;
    if (CPU_FAMILY(dwSignature) == 0xF)
    {
        dwEffFamily = CPU_FAMILY(dwSignature) + CPU_EXTFAMILY(dwSignature);
    }
    else
    {
        dwEffFamily = CPU_FAMILY(dwSignature);
    }
    UINT32 dwEffModel;
    if (CPU_MODEL(dwSignature) == 0xF)
    {
        dwEffModel = CPU_MODEL(dwSignature) + (CPU_EXTMODEL(dwSignature) << 4);
    }
    else
    {
        dwEffModel = CPU_MODEL(dwSignature);
    }

#define ADVF_MMX   0x00000001UL
#define ADVF_FSXR  0x00000002UL
#define ADVF_SSE   0x00000004UL
#define ADVF_SSE2  0x00000008UL
#define ADVF_SSE3  0x00000010UL
#define ADVF_SSSE3 0x00000020UL
#define ADVF_SSE41 0x00000040UL
#define ADVF_SSE42 0x00000080UL
#define ADVF_AES   0x00000100UL

    UINT32 dwAdvFeatures = 0;

    // Decode the features the chips claim to possess.
    //
    if (dwFeatures & CPU_FEATURE_MMX)
    {
        dwAdvFeatures |= ADVF_MMX;
    }
    if (dwFeatures & CPU_FEATURE_FSXR)
    {
        dwAdvFeatures |= ADVF_FSXR;
    }
    if (dwFeatures & CPU_FEATURE_SSE)
    {
        dwAdvFeatures |= ADVF_SSE;
    }
    if (dwFeatures & CPU_FEATURE_SSE2)
    {
        dwAdvFeatures |= ADVF_SSE2;
    }
    if (dwFeatures2 & CPU_FEATURE2_SSE3)
    {
        dwAdvFeatures |= ADVF_SSE3;
    }
    if (dwFeatures2 & CPU_FEATURE2_SSSE3)
    {
        dwAdvFeatures |= ADVF_SSSE3;
    }
    if (dwFeatures2 & CPU_FEATURE2_SSE41)
    {
        dwAdvFeatures |= ADVF_SSE41;
    }
    if (dwFeatures2 & CPU_FEATURE2_SSE42)
    {
        dwAdvFeatures |= ADVF_SSE42;
    }
    if (dwFeatures2 & CPU_FEATURE2_AES)
    {
        dwAdvFeatures |= ADVF_AES;
    }

    // Test whether operating system will allow use of these extensions.
    //
    UINT32 dwUseable = dwAdvFeatures;
    if (dwUseable & ADVF_MMX)
    {
        try
        {
            __asm
            {
                // Let's try a MMX instruction.
                //
                emms
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_MMX|ADVF_SSE|ADVF_SSE2|ADVF_SSE3|ADVF_SSSE3|ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSE)
    {
        try
        {
            __asm
            {
                // Let's try a SSE instruction.
                //
                xorps xmm0, xmm0
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSE|ADVF_SSE2|ADVF_SSE3|ADVF_SSSE3|ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSE2)
    {
        try
        {
            __asm
            {
                // Let's try a SSE2 instruction.
                //
                xorpd xmm0, xmm0
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSE2|ADVF_SSE3|ADVF_SSSE3|ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSE3)
    {
        try
        {
            __asm
            {
                // Let's try a SSE3 instruction.
                //
                haddpd xmm1,xmm2
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSE3|ADVF_SSSE3|ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSSE3)
    {
        try
        {
            __asm
            {
                // Let's try a SSSE3 instruction.
                //
                phaddw xmm1,xmm2
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSSE3|ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSE41)
    {
        try
        {
            __asm
            {
                // Let's try a SSE41 instruction.
                //
                pcmpeqq xmm1,xmm2
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSE41|ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_SSE42)
    {
        try
        {
            __asm
            {
                // Let's try a SSE42 instruction.
                //
                pcmpgtq xmm1,xmm2
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_SSE42|ADVF_AES);
        }
    }

    if (dwUseable & ADVF_AES)
    {
        try
        {
            __asm
            {
                // Let's try a AES instruction.
                //
                aesenc xmm1,xmm2
            }
        }
        catch (...)
        {
            dwUseable &= ~(ADVF_AES);
        }
    }

    // Map tested features to an indicator for CPU dispatching.
    //
    if (dwEffFamily <= 4)
    {
        __intel_cpu_indicator = CPU_TYPE_UNSPECIALIZED;
    }
    else if (5 == dwEffFamily)
    {
        if (dwUseable & ADVF_MMX)
        {
            __intel_cpu_indicator = CPU_TYPE_FAMILY_5_MMX;
        }
        else
        {
            __intel_cpu_indicator = CPU_TYPE_FAMILY_5;
        }
    }
    else
    {
        if (dwUseable & ADVF_MMX)
        {
            if (dwUseable & ADVF_FSXR)
            {
                if (dwUseable & ADVF_SSE)
                {
                    if (dwUseable & ADVF_SSE2)
                    {
                        if (dwUseable & ADVF_SSE3)
                        {
                            if (dwUseable & ADVF_SSSE3)
                            {
                                if (dwUseable & ADVF_SSE41)
                                {
                                    if (dwUseable & ADVF_SSE42)
                                    {
                                        if (dwUseable & ADVF_AES)
                                        {
                                            __intel_cpu_indicator = CPU_TYPE_FAMILY_6_AES_DTE64;
                                        }
                                        else
                                        {
                                            __intel_cpu_indicator = CPU_TYPE_FAMILY_6_SSE42_POPCNT;
                                        }
                                    }
                                    else
                                    {
                                        __intel_cpu_indicator = CPU_TYPE_FAMILY_6_SSE41;
                                    }
                                }
                                else
                                {
                                    __intel_cpu_indicator = CPU_TYPE_FAMILY_6_SSSE3;
                                }
                            }
                            else if (dwEffFamily < 15)
                            {
                                __intel_cpu_indicator = CPU_TYPE_FAMILY_6_MMX_FSXR_SSE3;
                            }
                            else
                            {
                                __intel_cpu_indicator = CPU_TYPE_FAMILY_F_SSE3;
                            }
                        }
                        else
                        {
                            if (dwEffFamily < 15)
                            {
                                __intel_cpu_indicator = CPU_TYPE_FAMILY_6_MMX_FSXR_SSE2;
                            }
                            else
                            {
                                __intel_cpu_indicator = CPU_TYPE_FAMILY_F_SSE2;
                            }
                        }
                    }
                    else
                    {
                        __intel_cpu_indicator = CPU_TYPE_FAMILY_6_MMX_FSXR_SSE;
                    }
                }
                else
                {
                    __intel_cpu_indicator = CPU_TYPE_FAMILY_6_MMX_FSXR;
                }
            }
            else
            {
                __intel_cpu_indicator = CPU_TYPE_FAMILY_6_MMX;
            }
        }
        else
        {
            __intel_cpu_indicator = CPU_TYPE_FAMILY_6;
        }
    }

    // Report findings to the log.
    //
    mux_fprintf(stderr, T("cpu_init: %s, Family %u, Model %u, %s%s%s%s%s%s%s%s%s" ENDLINE),
        (Intel == maker ? "Intel" : (AMD == maker ? "AMD" : "Unknown")),
        dwEffFamily,
        dwEffModel,
        (dwUseable & ADVF_MMX)  ? "MMX " : "",
        (dwUseable & ADVF_FSXR) ? "FSXR ": "",
        (dwUseable & ADVF_SSE)  ? "SSE ": "",
        (dwUseable & ADVF_SSE2) ? "SSE2 ": "",
        (dwUseable & ADVF_SSE3) ? "SSE3 ": "",
        (dwUseable & ADVF_SSSE3) ? "SSSE3 ": "",
        (dwUseable & ADVF_SSE41) ? "SSE41 ": "",
        (dwUseable & ADVF_SSE42) ? "SSE42 ": "",
        (dwUseable & ADVF_AES) ? "AES ": "");

    if (dwUseable != dwAdvFeatures)
    {
        UINT32 dw = dwAdvFeatures & (~dwUseable);
        mux_fprintf(stderr, T("cpu_init: %s%s%s%s%s%s%s%s%s unsupported by OS." ENDLINE),
            (dw & ADVF_MMX)  ? "MMX ": "",
            (dw & ADVF_FSXR) ? "FSXR ": "",
            (dw & ADVF_SSE)  ? "SSE ": "",
            (dw & ADVF_SSE2) ? "SSE2 ": "",
            (dw & ADVF_SSE3) ? "SSE3 ": "",
            (dw & ADVF_SSSE3) ? "SSSE3 ": "",
            (dw & ADVF_SSE41) ? "SSE41 ": "",
            (dw & ADVF_SSE42) ? "SSE42 ": "",
            (dw & ADVF_AES) ? "AES ": "");
    }
}

#endif // __INTEL_COMPILER

#if defined(WINDOWS_NETWORKING)
void DetectWindowsCapabilities()
{
    // Get a handle to ws2_32.dll
    //
    HINSTANCE hInstWs2_32 = LoadLibrary(L"ws2_32");
    if (NULL != hInstWs2_32)
    {
        fpGetNameInfo = (FGETNAMEINFO *)GetProcAddress(hInstWs2_32, "getnameinfo");
        fpGetAddrInfo = (FGETADDRINFO *)GetProcAddress(hInstWs2_32, "getaddrinfo");
        fpFreeAddrInfo = (FFREEADDRINFO *)GetProcAddress(hInstWs2_32, "freeaddrinfo");

        // These interfaces are all-or-nothing.
        //
        if (  NULL == fpGetNameInfo
           || NULL == fpGetAddrInfo
           || NULL == fpFreeAddrInfo)
        {
            fpGetNameInfo = NULL;
            fpGetAddrInfo = NULL;
            fpFreeAddrInfo = NULL;
            FreeLibrary(hInstWs2_32);
            hInstWs2_32 = NULL;
        }
    }

    if (NULL == hInstWs2_32)
    {
        // Get a handle to wship6.dll (part of the Windows 2000 IPv6 technology preview).
        //
        HINSTANCE hInstWship6 = LoadLibrary(L"wship6");
        if (NULL != hInstWship6)
        {
            fpGetNameInfo = (FGETNAMEINFO *)GetProcAddress(hInstWship6, "getnameinfo");
            fpGetAddrInfo = (FGETADDRINFO *)GetProcAddress(hInstWship6, "getaddrinfo");
            fpFreeAddrInfo = (FFREEADDRINFO *)GetProcAddress(hInstWship6, "freeaddrinfo");

            // These interfaces are all-or-nothing.
            //
            if (  NULL == fpGetNameInfo
               || NULL == fpGetAddrInfo
               || NULL == fpFreeAddrInfo)
            {
                fpGetNameInfo = NULL;
                fpGetAddrInfo = NULL;
                fpFreeAddrInfo = NULL;
                FreeLibrary(hInstWship6);
                hInstWship6 = NULL;
            }
        }
    }
}
#endif // WINDOWS_NETWORKING

#define DBCONVERT_NAME1 T("dbconvert")
#define DBCONVERT_NAME2 T("dbconvert.exe")

int DCL_CDECL main(int argc, char *argv[])
{
#if defined(__INTEL_COMPILER) && defined(_M_IX86)
    cpu_init();
#endif

    build_version();

    // Look for dbconvert[.exe] in the program name.
    //
    size_t nProg = strlen(argv[0]);
    const char *pProg = argv[0] + nProg - 1;
    while (  nProg
          && (  mux_isalpha(*pProg)
             || *pProg == '.'))
    {
        nProg--;
        pProg--;
    }
    pProg++;
    mudstate.bStandAlone = false;
    if (  mux_stricmp((UTF8 *)pProg, DBCONVERT_NAME1) == 0
       || mux_stricmp((UTF8 *)pProg, DBCONVERT_NAME2) == 0)
    {
        mudstate.bStandAlone = true;
    }

    mudconf.pid_file = (UTF8 *)"netmux.pid";

    // Parse the command line
    //
    CLI_Process(argc, argv, OptionTable, NUM_CLI_OPTIONS, CLI_CallBack);

#ifndef MEMORY_BASED
    if (mudstate.bStandAlone)
    {
        int n = 0;
        if (standalone_check)
        {
            n++;
        }
        if (standalone_load)
        {
            n++;
        }
        if (standalone_unload)
        {
            n++;
        }
        if (  !standalone_basename
           || !standalone_infile
           || !standalone_outfile
           || n != 1
           || bServerOption)
        {
            bSyntaxError = true;
        }
        else
        {
            dbconvert();
            return 0;
        }
    }
    else
#endif // MEMORY_BASED

    if (bVersion)
    {
        mux_fprintf(stderr, T("Version: %s" ENDLINE), mudstate.version);
        return 1;
    }
    if (  bSyntaxError
       || conffile == NULL
       || !bServerOption)
    {
        mux_fprintf(stderr, T("Version: %s" ENDLINE), mudstate.version);
        if (mudstate.bStandAlone)
        {
            mux_fprintf(stderr, T("Usage: %s -d <dbname> -i <infile> [-o <outfile>] [-l|-u|-k]" ENDLINE), pProg);
            mux_fprintf(stderr, T("  -d  Basename." ENDLINE));
            mux_fprintf(stderr, T("  -i  Input file." ENDLINE));
            mux_fprintf(stderr, T("  -k  Check." ENDLINE));
            mux_fprintf(stderr, T("  -l  Load." ENDLINE));
            mux_fprintf(stderr, T("  -o  Output file." ENDLINE));
            mux_fprintf(stderr, T("  -u  Unload." ENDLINE));
        }
        else
        {
            mux_fprintf(stderr, T("Usage: %s [-c <filename>] [-p <filename>] [-h] [-s] [-v]" ENDLINE), pProg);
            mux_fprintf(stderr, T("  -c  Specify configuration file." ENDLINE));
            mux_fprintf(stderr, T("  -e  Specify logfile basename (or '-' for stderr)." ENDLINE));
            mux_fprintf(stderr, T("  -h  Display this help." ENDLINE));
            mux_fprintf(stderr, T("  -p  Specify process ID file." ENDLINE));
            mux_fprintf(stderr, T("  -s  Start with a minimal database." ENDLINE));
            mux_fprintf(stderr, T("  -v  Display version string." ENDLINE ENDLINE));
        }
        return 1;
    }

    mudstate.bStandAlone = false;

    FLOAT_Initialize();
    TIME_Initialize();
    SeedRandomNumberGenerator();

    Log.SetBasename(pErrorBasename);
    Log.StartLogging();
    game_pid = mux_getpid();
    write_pidfile(mudconf.pid_file);

    BuildSignalNamesTable();

#ifdef MEMORY_ACCOUNTING
    extern CHashFile hfAllocData;
    extern CHashFile hfIdentData;
    extern bool bMemAccountingInitialized;
    hfAllocData.Open("svdptrs.dir", "svdptrs.pag", 40);
    hfIdentData.Open("svdlines.dir", "svdlines.pag", 40);
    bMemAccountingInitialized = true;
#endif

#if defined(WINDOWS_NETWORKING)

    hGameProcess = GetCurrentProcess();
    DetectWindowsCapabilities();

    // Initialize WinSock.
    //
    WORD wVersionRequested = MAKEWORD(2,2);
    WSADATA wsaData;
    if (WSAStartup(wVersionRequested, &wsaData) != 0)
    {
        Log.WriteString(T("ERROR: Could not initialize WinSock." ENDLINE));
        return 101;
    }

    if (  LOBYTE(wsaData.wVersion) != 2
       || HIBYTE(wsaData.wVersion) != 2)
    {
        // We can't run on this version of WinSock.
        //
        Log.tinyprintf(T("INFO: WinSock v%d.%d instead of v2.2." ENDLINE),
            LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
        //WSACleanup();
        //return 102;
    }

#endif // WINDOWS_NETWORKING

    mudstate.restart_time.GetUTC();
    mudstate.start_time = mudstate.restart_time;
    mudstate.restart_count= 0;

    mudstate.cpu_count_from.GetUTC();
    pool_init(POOL_LBUF, LBUF_SIZE);
    pool_init(POOL_MBUF, MBUF_SIZE);
    pool_init(POOL_SBUF, SBUF_SIZE);
    pool_init(POOL_BOOL, sizeof(struct boolexp));

    pool_init(POOL_DESC, sizeof(DESC));
    pool_init(POOL_QENTRY, sizeof(BQUE));
    pool_init(POOL_LBUFREF, sizeof(lbuf_ref));
    pool_init(POOL_REGREF, sizeof(reg_ref));
    pool_init(POOL_STRING, sizeof(mux_string));
    tcache_init();
    pcache_init();
    cf_init();
#if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
    init_rlimit();
#endif // HAVE_SETRLIMIT RLIMIT_NOFILE
    init_cmdtab();
    init_logout_cmdtab();
    init_flagtab();
    init_powertab();
    init_functab();
    init_attrtab();
    init_version();

#if defined(TINYMUX_MODULES)
    // The module subsystem must be ready to go before the configuration files
    // are consumed.  However, this means that the modules can't really do
    // much until they get a notification that the part of loading they depend
    // on is complete.
    //
#if defined(HAVE_WORKING_FORK) && defined(STUB_SLAVE)
    boot_stubslave(GOD, GOD, GOD, 0);
#endif // HAVE_WORKING_FORK && STUB_SLAVE
    init_modules();
#endif // TINYMUX_MODULES

    mudconf.config_file = StringClone(conffile);
    mudconf.log_dir = StringClone(pErrorBasename);
    cf_read();

#if defined(TINYMUX_MODULES)
    MUX_RESULT mr = mux_CreateInstance(CID_QueryServer, NULL, UseSlaveProcess, IID_IQueryControl, (void **)&mudstate.pIQueryControl);
    if (MUX_SUCCEEDED(mr))
    {
        mr = mudstate.pIQueryControl->Connect(mudconf.sql_server, mudconf.sql_database, mudconf.sql_user, mudconf.sql_password);
        if (MUX_SUCCEEDED(mr))
        {
            mux_IQuerySink *pIQuerySink = NULL;
            mr = mux_CreateInstance(CID_QueryClient, NULL, UseSameProcess, IID_IQuerySink, (void **)&pIQuerySink);
            if (MUX_SUCCEEDED(mr))
            {
                mr = mudstate.pIQueryControl->Advise(pIQuerySink);
                if (MUX_SUCCEEDED(mr))
                {
                    pIQuerySink->Release();
                    pIQuerySink = NULL;
                }
                else
                {
                    mudstate.pIQueryControl->Release();
                    mudstate.pIQueryControl = NULL;

                    STARTLOG(LOG_ALWAYS, "INI", "LOAD");
                    log_printf(T("Couldn\xE2\x80\x99t connect sink to server (%d)."), mr);
                    ENDLOG;
                }
            }
            else
            {
                mudstate.pIQueryControl->Release();
                mudstate.pIQueryControl = NULL;

                STARTLOG(LOG_ALWAYS, "INI", "LOAD");
                log_printf(T("Couldn\xE2\x80\x99t create Query Sink (%d)."), mr);
                ENDLOG;
            }
        }
        else
        {
            mudstate.pIQueryControl->Release();
            mudstate.pIQueryControl = NULL;

            STARTLOG(LOG_ALWAYS, "INI", "LOAD");
            log_printf(T("Couldn\xE2\x80\x99t connect to Query Server (%d)."), mr);
            ENDLOG;
        }
    }
    else
    {
        STARTLOG(LOG_ALWAYS, "INI", "LOAD");
        log_text(T("Couldn\xE2\x80\x99t create interface to Query Server."));
        ENDLOG;
    }
#endif // TINYMUX_MODULES

#if defined(INLINESQL)
    init_sql();
#endif // INLINESQL

#ifdef UNIX_SSL
    if (!initialize_ssl())
    {
        // Do some extra handling?
        // We do log all errors in initialize_ssl, so it may be unneeded.
    }
#endif

    fcache_init();
    helpindex_init();

#ifdef MEMORY_BASED
    db_free();
#else // MEMORY_BASED
    if (bMinDB)
    {
        RemoveFile(mudconf.game_dir);
        RemoveFile(mudconf.game_pag);
    }
    int ccPageFile = init_dbfile(mudconf.game_dir, mudconf.game_pag, mudconf.cache_pages);
    if (HF_OPEN_STATUS_ERROR == ccPageFile)
    {
        STARTLOG(LOG_ALWAYS, "INI", "LOAD");
        log_text(T("Couldn\xE2\x80\x99t load text database: "));
        log_text(mudconf.game_dir);
        log_text(mudconf.game_pag);
        ENDLOG;
        return 2;
    }
#endif // MEMORY_BASED

    mudstate.record_players = 0;

    if (bMinDB)
    {
        db_make_minimal();
    }
    else
    {
#ifdef MEMORY_BASED
        int ccInFile = load_game();
#else // MEMORY_BASED
        int ccInFile = load_game(ccPageFile);
#endif // MEMORY_BASED
        if (LOAD_GAME_NO_INPUT_DB == ccInFile)
        {
            // The input file didn't exist.
            //
#ifndef MEMORY_BASED
            if (HF_OPEN_STATUS_NEW == ccPageFile)
            {
                // Since the .db file didn't exist, and the .pag/.dir files
                // were newly created, just create a minimal DB.
                //
#endif // !MEMORY_BASED
                db_make_minimal();
                ccInFile = LOAD_GAME_SUCCESS;
#ifndef MEMORY_BASED
            }
#endif // !MEMORY_BASED
        }
        if (ccInFile != LOAD_GAME_SUCCESS)
        {
            STARTLOG(LOG_ALWAYS, "INI", "LOAD")
            log_text(T("Couldn\xE2\x80\x99t load: "));
            log_text(mudconf.indb);
            ENDLOG
            return 2;
        }
    }
    set_signals();
    Guest.StartUp();

    // Do a consistency check and set up the freelist
    //
    do_dbck(NOTHING, NOTHING, NOTHING, 0, 0);

    // Reset all the hash stats
    //
    hashreset(&mudstate.command_htab);
    hashreset(&mudstate.channel_htab);
    hashreset(&mudstate.mail_htab);
    hashreset(&mudstate.logout_cmd_htab);
    hashreset(&mudstate.func_htab);
    hashreset(&mudstate.flags_htab);
    hashreset(&mudstate.attr_name_htab);
    hashreset(&mudstate.player_htab);
    hashreset(&mudstate.fwdlist_htab);
    hashreset(&mudstate.desc_htab);
    hashreset(&mudstate.reference_htab);

    ValidateConfigurationDbrefs();
    process_preload();

#if defined(HAVE_WORKING_FORK)
    load_restart_db();
    if (!mudstate.restarting)
#endif // HAVE_WORKING_FORK
    {
        if (fclose(stdout) == 0)
        {
            DebugTotalFiles--;
        }
        if (fclose(stdin) == 0)
        {
            DebugTotalFiles--;
        }
    }
#ifdef UNIX_SSL
    SetupPorts(&nMainGamePorts, aMainGamePorts, &mudconf.ports, &mudconf.sslPorts, mudconf.ip_address);
#else
    SetupPorts(&nMainGamePorts, aMainGamePorts, &mudconf.ports, NULL, mudconf.ip_address);
#endif

#if defined(HAVE_WORKING_FORK) || defined(WINDOWS_THREADS)
    boot_slave(GOD, GOD, GOD, 0, 0);
#endif // HAVE_WORKING_FORK

    // All intialization should be complete, allow the local
    // extensions to configure themselves.
    //
    local_startup();

#if defined(TINYMUX_MODULES)
    ServerEventsSinkNode *p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->startup();
        p = p->pNext;
    }
#endif // TINYMUX_MODULES

    init_timer();

    shovechars(nMainGamePorts, aMainGamePorts);

#ifdef INLINESQL
     if (mush_database)
     {
         mysql_close(mush_database);
         mush_database = NULL;
         STARTLOG(LOG_STARTUP,"SQL","DISC");
         log_text(T("SQL shut down"));
         ENDLOG;
     }
#endif // INLINESQL

    close_sockets(false, T("Going down - Bye"));
    dump_database();

    // All shutdown, barring logfiles, should be done, shutdown the
    // local extensions.
    //
    local_shutdown();

#if defined(TINYMUX_MODULES)
    p = g_pServerEventsSinkListHead;
    while (NULL != p)
    {
        p->pSink->shutdown();
        p = p->pNext;
    }
    final_modules();
#endif // TINYMUX_MODULES
    CLOSE;

#if defined(HAVE_WORKING_FORK)
    CleanUpSlaveSocket();
    CleanUpSlaveProcess();
#ifdef STUB_SLAVE
    CleanUpStubSlaveSocket();
    WaitOnStubSlaveProcess();
#endif
#endif // HAVE_WORKING_FORK
#if defined(WINDOWS_NETWORKING)
    shutdown_slave();
#endif

#ifdef SELFCHECK
    // Go ahead and explicitly free the memory for these things so
    // that it's easy to spot unintentional memory leaks.
    //
    int i;
    for (i = 0; i < mudstate.nHelpDesc; i++)
    {
        helpindex_clean(i);
    }

    finish_mail();
    finish_cmdtab();
    db_free();
#endif

#if defined(WINDOWS_NETWORKING)
    // Critical section not needed any more.
    //
    DeleteCriticalSection(&csDescriptorList);
    WSACleanup();
#endif // WINDOWS_NETWORKING

#ifdef UNIX_SSL
    shutdown_ssl();
#endif

    return 0;
}

#if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
void init_rlimit(void)
{
    struct rlimit *rlp;

    rlp = (struct rlimit *)alloc_lbuf("rlimit");

    if (getrlimit(RLIMIT_NOFILE, rlp))
    {
        log_perror(T("RLM"), T("FAIL"), NULL, T("getrlimit()"));
        free_lbuf(rlp);
        return;
    }
    rlp->rlim_cur = rlp->rlim_max;
    if (setrlimit(RLIMIT_NOFILE, rlp))
    {
        log_perror(T("RLM"), T("FAIL"), NULL, T("setrlimit()"));
    }
    free_lbuf(rlp);

}
#endif // HAVE_SETRLIMIT RLIMIT_NOFILE

bool mux_fopen(FILE **pFile, const UTF8 *filename, const UTF8 *mode)
{
    if (pFile)
    {
        *pFile = NULL;
        if (  NULL != filename
           && NULL != mode)
        {
#if defined(WINDOWS_FILES) && !defined(__INTEL_COMPILER) && (_MSC_VER >= 1400)
            // 1400 is Visual C++ 2005
            //
            return (fopen_s(pFile, (const char *)filename, (const char *)mode) == 0);
#else
            *pFile = fopen((char *)filename, (char *)mode);
            if (NULL != *pFile)
            {
                return true;
            }
#endif // WINDOWS_FILES
        }
    }
    return false;
}

bool mux_open(int *pfh, const UTF8 *filename, int oflag)
{
    if (NULL != pfh)
    {
        *pfh = MUX_OPEN_INVALID_HANDLE_VALUE;
        if (NULL != filename)
        {
#if defined(WINDOWS_FILES) && !defined(__INTEL_COMPILER) && (_MSC_VER >= 1400)
            // 1400 is Visual C++ 2005
            //
            return (_sopen_s(pfh, (const char *)filename, oflag, _SH_DENYNO, _S_IREAD|_S_IWRITE) == 0);
#elif defined(WINDOWS_FILES)
            *pfh = _open((char *)filename, oflag, _S_IREAD|_S_IWRITE);
            return (0 <= *pfh);
#else
            *pfh = open((char *)filename, oflag, 0600);
            return (0 <= *pfh);
#endif
        }
    }
    return false;
}

const UTF8 *mux_strerror(int errnum)
{
#if defined(WINDOWS_FILES) && !defined(__INTEL_COMPILER) && (_MSC_VER >= 1400)
    // 1400 is Visual C++ 2005
    //
    static UTF8 buffer[80];
    strerror_s((char *)buffer, sizeof(buffer), errnum);
    return buffer;
#else
    return (UTF8 *)strerror(errnum);
#endif
}