File: predicates.cpp

package info (click to toggle)
tinymux 2.10.1.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 6,212 kB
  • ctags: 8,535
  • sloc: cpp: 111,587; sh: 5,867; ansic: 141; makefile: 139
file content (3137 lines) | stat: -rw-r--r-- 77,621 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
/*! \file predicates.cpp
 * \brief Miscellaneous commands and functions.
 *
 * $Id: predicates.cpp 5881 2016-12-31 04:09:57Z sdennis $
 *
 * In theory, most of these functions could plausibly be called
 * "predicates", either because they determine some boolean property
 * of the input, or because they perform some action that makes them
 * verb-like.  In practice, this is a miscellany.
 */

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

#include <signal.h>

#include "attrs.h"
#include "command.h"
#include "interface.h"
#include "mathutil.h"
#include "powers.h"
#ifdef REALITY_LVLS
#include "levels.h"
#endif // REALITY_LVLS

UTF8 *DCL_CDECL tprintf(__in_z const UTF8 *fmt,...)
{
    static UTF8 buff[LBUF_SIZE];
    va_list ap;
    va_start(ap, fmt);
    mux_vsnprintf(buff, LBUF_SIZE, fmt, ap);
    va_end(ap);
    return buff;
}

void DCL_CDECL safe_tprintf_str(UTF8 *str, UTF8 **bp, __in_z const UTF8 *fmt,...)
{
    va_list ap;
    va_start(ap, fmt);
    size_t nAvailable = LBUF_SIZE - (*bp - str);
    size_t len = mux_vsnprintf(*bp, (int)nAvailable, fmt, ap);
    va_end(ap);
    *bp += len;
}

/* ---------------------------------------------------------------------------
 * insert_first, remove_first: Insert or remove objects from lists.
 */

dbref insert_first(dbref head, dbref thing)
{
    s_Next(thing, head);
    return thing;
}

dbref remove_first(dbref head, dbref thing)
{
    if (head == thing)
    {
        return Next(thing);
    }

    dbref prev;

    DOLIST(prev, head)
    {
        if (Next(prev) == thing)
        {
            s_Next(prev, Next(thing));
            return head;
        }
    }
    return head;
}

/* ---------------------------------------------------------------------------
 * reverse_list: Reverse the order of members in a list.
 */

dbref reverse_list(dbref list)
{
    dbref newlist, rest;

    newlist = NOTHING;
    while (list != NOTHING)
    {
        rest = Next(list);
        s_Next(list, newlist);
        newlist = list;
        list = rest;
    }
    return newlist;
}

/* ---------------------------------------------------------------------------
 * member - indicate if thing is in list
 */

bool member(dbref thing, dbref list)
{
    DOLIST(list, list)
    {
        if (list == thing)
        {
            return true;
        }
    }
    return false;
}

bool could_doit(dbref player, dbref thing, int locknum)
{
    if (thing == HOME)
    {
        return true;
    }

    // If nonplayer tries to get key, then no.
    //
    if (  !isPlayer(player)
       && Key(thing))
    {
        return false;
    }
    if (Pass_Locks(player))
    {
        return true;
    }

    dbref aowner;
    int   aflags;
    UTF8 *key = atr_get("could_doit.134", thing, locknum, &aowner, &aflags);
    bool doit = eval_boolexp_atr(player, thing, thing, key);
    free_lbuf(key);
    return doit;
}

bool can_see(dbref player, dbref thing, bool can_see_loc)
{
    // Don't show if all the following apply: Sleeping players should not be
    // seen.  The thing is a disconnected player.  The player is not a
    // puppet.
    //
    if (  mudconf.dark_sleepers
       && isPlayer(thing)
       && !Connected(thing)
       && !Puppet(thing))
    {
        return false;
    }

    // You don't see yourself or exits.
    //
    if (  player == thing
       || isExit(thing))
    {
        return false;
    }

    // To be visible, light must come from either the location (can_see_loc)
    // or the object itself (Light(thing)).  This light is then blocked
    // by the object itself being dark (it blocked its own light), by not
    // passing the visibility lock, or by being in a different reality.
    //
    // The exception to the above is mudconf.see_own_dark which allows a
    // myopic self-examination.
    //
    return (  (  (  can_see_loc
                 || Light(thing))
              && !Dark(thing)
#ifdef REALITY_LVLS
              && IsReal(player, thing)
#endif // REALITY_LVLS
              && could_doit(player, thing, A_LVISIBLE))
           || (  mudconf.see_own_dark
              && MyopicExam(player, thing)));
}

static bool pay_quota(dbref who, int cost)
{
    // If no cost, succeed
    //
    if (cost <= 0)
    {
        return true;
    }

    // determine quota
    //
    dbref aowner;
    int aflags;
    UTF8 *quota_str = atr_get("pay_quota.200", Owner(who), A_RQUOTA, &aowner, &aflags);
    int quota = mux_atol(quota_str);
    free_lbuf(quota_str);

    // enough to build?  Wizards always have enough.
    //
    quota -= cost;
    if (  quota < 0
       && !Free_Quota(who)
       && !Free_Quota(Owner(who)))
    {
        return false;
    }

    // Dock the quota.
    //
    UTF8 buf[I32BUF_SIZE];
    mux_ltoa(quota, buf);
    atr_add_raw(Owner(who), A_RQUOTA, buf);

    return true;
}

bool canpayfees(dbref player, dbref who, int pennies, int quota)
{
    if (  !Wizard(who)
       && !Wizard(Owner(who))
       && !Free_Money(who)
       && !Free_Money(Owner(who))
       && (Pennies(Owner(who)) < pennies))
    {
        if (player == who)
        {
            notify(player, tprintf(T("Sorry, you don\xE2\x80\x99t have enough %s."),
                       mudconf.many_coins));
        }
        else
        {
            notify(player, tprintf(T("Sorry, that player doesn\xE2\x80\x99t have enough %s."),
                mudconf.many_coins));
        }
        return false;
    }
    if (mudconf.quotas)
    {
        if (!pay_quota(who, quota))
        {
            if (player == who)
            {
                notify(player, T("Sorry, your building contract has run out."));
            }
            else
            {
                notify(player,
                    T("Sorry, that player\xE2\x80\x99s building contract has run out."));
            }
            return false;
        }
    }
    payfor(who, pennies);
    return true;
}

bool payfor(dbref who, int cost)
{
    if (  Wizard(who)
       || Wizard(Owner(who))
       || Free_Money(who)
       || Free_Money(Owner(who)))
    {
        return true;
    }
    who = Owner(who);
    int tmp;
    if ((tmp = Pennies(who)) >= cost)
    {
        s_Pennies(who, tmp - cost);
        return true;
    }
    return false;
}

void add_quota(dbref who, int payment)
{
    dbref aowner;
    int aflags;
    UTF8 buf[I32BUF_SIZE];

    UTF8 *quota = atr_get("add_quota.288", who, A_RQUOTA, &aowner, &aflags);
    mux_ltoa(mux_atol(quota) + payment, buf);
    free_lbuf(quota);
    atr_add_raw(who, A_RQUOTA, buf);
}

void giveto(dbref who, int pennies)
{
    if (  Wizard(who)
       || Wizard(Owner(who))
       || Free_Money(who)
       || Free_Money(Owner(who)))
    {
        return;
    }
    who = Owner(who);
    s_Pennies(who, Pennies(who) + pennies);
}

// Every character in the name must be allowed by one of the character sets mentioned.
// If no character sets are mentions, everything is allowed.
//
bool IsRestricted(const UTF8 *pName, int charset)
{
    if (0 == charset)
    {
        return false;
    }

    while ('\0' != pName[0])
    {
        bool bAllowed = false;
        if (  (ALLOW_CHARSET_ASCII & charset)
           && (0x80 & pName[0]) == 0)
        {
            bAllowed = true;
        }
        else if (  (ALLOW_CHARSET_8859_1 & charset)
                && mux_is8859_1(pName))
        {
            bAllowed = true;
        }
        else if (  (ALLOW_CHARSET_8859_2 & charset)
                && mux_is8859_2(pName))
        {
            bAllowed = true;
        }

        if (!bAllowed)
        {
            return true;
        }
        pName = utf8_NextCodePoint(pName);
    }
    return false;
}

// The following function validates that the object names (which will be
// used for things and rooms, but not for players or exits) and generates
// a canonical form of that name (with optimized ANSI).
//
UTF8 *MakeCanonicalObjectName(const UTF8 *pName, size_t *pnName, bool *pbValid, int charset)
{
    static UTF8 Buf[MBUF_SIZE];

    *pnName = 0;
    *pbValid = false;

    if (!pName)
    {
        return NULL;
    }

    // Build up what the real name would be. If we pass all the
    // checks, this is what we will return as a result.
    //
    mux_field fldLen = StripTabsAndTruncate(pName, Buf, MBUF_SIZE-1, MBUF_SIZE-1);

    // Disallow pure ANSI names. There must be at least -something-
    // visible.
    //
    if (0 == fldLen.m_column)
    {
        return NULL;
    }

    // Get the stripped version (Visible parts without color info).
    //
    size_t nStripped;
    const UTF8 *pStripped = strip_color(Buf, &nStripped);

    // Do not allow LOOKUP_TOKEN, NUMBER_TOKEN, NOT_TOKEN, or SPACE
    // as the first character, or SPACE as the last character
    //
    if (  (UTF8 *)strchr((char *)"*!#", pStripped[0])
       || mux_isspace(pStripped[0])
       || mux_isspace(pStripped[nStripped-1]))
    {
        return NULL;
    }

    // Only printable characters besides ARG_DELIMITER, AND_TOKEN,
    // and OR_TOKEN are allowed.
    //
    const UTF8 *p = pStripped;
    while ('\0' != *p)
    {
        if (!mux_isobjectname(p))
        {
            return NULL;
        }
        p = utf8_NextCodePoint(p);
    }

    // Special names are specifically dis-allowed.
    //
    if (  (nStripped == 2 && memcmp("me", pStripped, 2) == 0)
       || (nStripped == 4 && (  memcmp("home", pStripped, 4) == 0
                             || memcmp("here", pStripped, 4) == 0)))
    {
        return NULL;
    }

    if (IsRestricted(pStripped, charset))
    {
        return NULL;
    }

    *pnName = fldLen.m_byte;
    *pbValid = true;
    return Buf;
}

// The following function validates exit names.
//
UTF8 *MakeCanonicalExitName(const UTF8 *pName, size_t *pnName, bool *pbValid)
{
    static UTF8 Buf[MBUF_SIZE];

    *pnName = 0;
    *pbValid = false;

    if (!pName)
    {
        return NULL;
    }

    mux_strncpy(Buf, pName, mux_strlen(pName));

    // Sanitize the input before processing.
    //
    MUX_STRTOK_STATE tts;
    mux_strtok_src(&tts, Buf);
    mux_strtok_ctl(&tts, T(";"));

    // Break the exitname down into semi-colon-separated segments.  The first
    // segment can contain color as it is used for showing the exit, but the
    // remaining segments are stripped of color.  A valid exitname requires
    // at least one (display) segment.
    //
    UTF8 *ptr;
    mux_string clean_names;
    bool bHaveDisplay = false;
    for (ptr = mux_strtok_parse(&tts); ptr; ptr = mux_strtok_parse(&tts))
    {
        UTF8 *pTrimmedSegment = NULL;
        if (bHaveDisplay)
        {
            // No color allowed in segments after the first one.
            //
            UTF8 *pNoColor = strip_color(ptr);
            pTrimmedSegment = trim_spaces(pNoColor);
        }
        else
        {
            // Color allowed in first segment.
            //
            pTrimmedSegment = trim_spaces(ptr);
        }

        // Ignore segments which contained nothing but spaces.
        //
        if ('\0' != pTrimmedSegment[0])
        {
            bool valid = false;
            size_t len = 0;

            UTF8 *pValidSegment = MakeCanonicalObjectName(pTrimmedSegment, &len, &valid, mudconf.exit_name_charset);
            if (valid)
            {
                if (bHaveDisplay)
                {
                    clean_names.append(T(";"));
                    clean_names.append(mux_string(pValidSegment));
                }
                else
                {
                    clean_names.prepend(pValidSegment);
                    bHaveDisplay = true;
                }
            }
        }
    }


    *pbValid = bHaveDisplay;
    if (!bHaveDisplay)
    {
        *pnName = 0;
        return Buf;
    }

    clean_names.export_TextColor(Buf);
    *pnName = mux_strlen(Buf);

    return Buf;
}

// The following function validates the player name. ANSI is not
// allowed in player names. However, a player name must satisfy
// the requirements of a regular name as well.
//
bool ValidatePlayerName(const UTF8 *pName)
{
    if (!pName)
    {
        return false;
    }
    size_t nName = strlen((char *)pName);

    // Verify that name is not empty, but not too long, either.
    //
    if (  nName <= 0
       || PLAYER_NAME_LIMIT <= nName)
    {
        return false;
    }

    // Do not allow LOOKUP_TOKEN, NUMBER_TOKEN, NOT_TOKEN, or SPACE
    // as the first character, or SPACE as the last character
    //
    if (  (UTF8 *)strchr((char *)"*!#", pName[0])
       || mux_isspace(pName[0])
       || mux_isspace(pName[nName-1]))
    {
        return false;
    }

    // Only printable characters besides ARG_DELIMITER, AND_TOKEN,
    // and OR_TOKEN are allowed.
    //
    if (  mudstate.bStandAlone
       || mudconf.name_spaces)
    {
        const UTF8 *p = pName;
        while ('\0' != *p)
        {
            if (  !mux_isplayername(p)
               && ' ' != *p)
            {
                return false;
            }
            p = utf8_NextCodePoint(p);
        }
    }
    else
    {
        const UTF8 *p = pName;
        while ('\0' != *p)
        {
            if (!mux_isplayername(p))
            {
                return false;
            }
            p = utf8_NextCodePoint(p);
        }
    }

    // Special names are specifically dis-allowed.
    //
    if (  (nName == 2 && memcmp("me", pName, 2) == 0)
       || (nName == 4 && (  memcmp("home", pName, 4) == 0
                         || memcmp("here", pName, 4) == 0)))
    {
        return false;
    }

    if (IsRestricted(pName, mudconf.player_name_charset))
    {
        return false;
    }
    return true;
}

bool ok_password(const UTF8 *password, const UTF8 **pmsg)
{
    *pmsg = NULL;

    if (*password == '\0')
    {
        *pmsg = T("Null passwords are not allowed.");
        return false;
    }

    int num_upper = 0;
    int num_special = 0;
    int num_lower = 0;

    const UTF8 *scan = password;
    for ( ; *scan; scan = utf8_NextCodePoint(scan))
    {
        if (  !mux_isprint(scan)
           || mux_isspace(*scan))
        {
            *pmsg = T("Illegal character in password.");
            return false;
        }
        if (mux_isupper_ascii(*scan))
        {
            num_upper++;
        }
        else if (mux_islower_ascii(*scan))
        {
            num_lower++;
        }
        else if (  *scan != '\''
                && *scan != '-')
        {
            num_special++;
        }
    }

    if (  !mudstate.bStandAlone
       && mudconf.safer_passwords)
    {
        if (num_upper < 1)
        {
            *pmsg = T("The password must contain at least one capital letter.");
            return false;
        }
        if (num_lower < 1)
        {
            *pmsg = T("The password must contain at least one lowercase letter.");
            return false;
        }
        if (num_special < 1)
        {
            *pmsg = T("The password must contain at least one number or a symbol other than the apostrophe or dash.");
            return false;
        }
    }
    return true;
}

/* ---------------------------------------------------------------------------
 * handle_ears: Generate the 'grows ears' and 'loses ears' messages.
 */

void handle_ears(dbref thing, bool could_hear, bool can_hear)
{
    static const UTF8 *poss[5] =
    {
        T(""),
        T("its"),
        T("her"),
        T("his"),
        T("their")
    };

    if (could_hear != can_hear)
    {
        mux_string *sStr = new mux_string(Moniker(thing));
        if (isExit(thing))
        {
            mux_cursor iPos;
            if (sStr->search(T(";"), &iPos))
            {
                sStr->truncate(iPos);
            }
        }
        int gender = get_gender(thing);

        if (can_hear)
        {
            sStr->append_TextPlain(tprintf(T(" grow%s ears and can now hear."),
                                 (gender == 4) ? "" : "s"));
        }
        else
        {
            sStr->append_TextPlain(tprintf(T(" lose%s %s ears and become%s deaf."),
                                 (gender == 4) ? "" : "s", poss[gender],
                                 (gender == 4) ? "" : "s"));
        }
        notify_check(thing, thing, *sStr, MSG_ME | MSG_NBR | MSG_LOC | MSG_INV);
        delete sStr;
    }
}

// For lack of better place the @switch code is here.
//
void do_switch
(
    dbref executor, dbref caller, dbref enactor,
    int eval, int key,
    UTF8 *expr,
    UTF8 *args[], int nargs,
    const UTF8 *cargs[], int ncargs
)
{
    if (  !expr
       || nargs <= 0)
    {
        return;
    }

    bool bMatchOne;
    switch (key & SWITCH_MASK)
    {
    case SWITCH_DEFAULT:
        if (mudconf.switch_df_all)
        {
            bMatchOne = false;
        }
        else
        {
            bMatchOne = true;
        }
        break;

    case SWITCH_ANY:
        bMatchOne = false;
        break;

    case SWITCH_ONE:
    default:
        bMatchOne = true;
        break;
    }

    // Now try a wild card match of buff with stuff in coms.
    //
    bool bAny = false;
    int a;
    UTF8 *buff, *bp;
    buff = bp = alloc_lbuf("do_switch");
    CLinearTimeAbsolute lta;
    for (  a = 0;
              (  !bMatchOne
              || !bAny)
           && a < nargs - 1
           && args[a]
           && args[a + 1];
           a += 2)
    {
        bp = buff;
        mux_exec(args[a], LBUF_SIZE-1, buff, &bp, executor, caller, enactor, eval|EV_FCHECK|EV_EVAL|EV_TOP,
            cargs, ncargs);
        *bp = '\0';
        if (wild_match(buff, expr))
        {
            UTF8 *tbuf = replace_tokens(args[a+1], NULL, NULL, expr);
            wait_que(executor, caller, enactor, eval, false, lta, NOTHING, 0,
                tbuf,
                ncargs, cargs,
                mudstate.global_regs);
            free_lbuf(tbuf);
            bAny = true;
        }
    }

    free_lbuf(buff);
    if (  a < nargs
       && !bAny
       && args[a])
    {
        UTF8 *tbuf = replace_tokens(args[a], NULL, NULL, expr);
        wait_que(executor, caller, enactor, eval, false, lta, NOTHING, 0,
            tbuf,
            ncargs, cargs,
            mudstate.global_regs);
        free_lbuf(tbuf);
    }

    if (key & SWITCH_NOTIFY)
    {
        UTF8 *tbuf = alloc_lbuf("switch.notify_cmd");
        mux_strncpy(tbuf, T("@notify/quiet me"), LBUF_SIZE-1);
        wait_que(executor, caller, enactor, eval, false, lta, NOTHING, A_SEMAPHORE,
            tbuf,
            ncargs, cargs,
            mudstate.global_regs);
        free_lbuf(tbuf);
    }
}

// Also for lack of better place the @ifelse code is here.
// Idea for @ifelse from ChaoticMUX.
//
void do_if
(
    dbref player, dbref caller, dbref enactor,
    int eval, int key,
    UTF8 *expr,
    UTF8 *args[], int nargs,
    const UTF8 *cargs[], int ncargs
)
{
    UNUSED_PARAMETER(key);

    if (  !expr
       || nargs <= 0)
    {
        return;
    }

    UTF8 *buff, *bp;
    CLinearTimeAbsolute lta;
    buff = bp = alloc_lbuf("do_if");

    mux_exec(expr, LBUF_SIZE-1, buff, &bp, player, caller, enactor, eval|EV_FCHECK|EV_EVAL|EV_TOP,
        cargs, ncargs);
    *bp = '\0';

    int a = !xlate(buff);
    free_lbuf(buff);

    if (a < nargs)
    {
        wait_que(player, caller, enactor, eval, false, lta, NOTHING, 0,
            args[a],
            ncargs, cargs,
            mudstate.global_regs);
    }
}

void do_addcommand
(
    dbref player,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    int   nargs,
    UTF8 *name,
    UTF8 *command,
    const UTF8 *cargs[],
    int   ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    // Validate command name.
    //
    static UTF8 pName[LBUF_SIZE];
    if (1 <= nargs)
    {
        mux_string *sName = new mux_string(name);
        sName->strip(T("\r\n\t "));
        sName->LowerCase();
        sName->export_TextPlain(pName);
        delete sName;
    }
    if (  0 == nargs
       || '\0' == pName[0]
       || (  pName[0] == '_'
          && pName[1] == '_'))
    {
        notify(player, T("That is not a valid command name."));
        return;
    }

    // Validate object/attribute.
    //
    dbref thing;
    ATTR *pattr;
    if (  !parse_attrib(player, command, &thing, &pattr)
       || !pattr)
    {
        notify(player, T("No such attribute."));
        return;
    }
    if (!See_attr(player, thing, pattr))
    {
        notify(player, NOPERM_MESSAGE);
        return;
    }

    CMDENT *old = (CMDENT *)hashfindLEN(pName, strlen((char *)pName),
        &mudstate.command_htab);

    CMDENT *cmd;
    ADDENT *add, *nextp;

    if (  old
       && (old->callseq & CS_ADDED))
    {
        // Don't allow the same (thing,atr) in the list.
        //
        for (nextp = old->addent; nextp != NULL; nextp = nextp->next)
        {
            if (  nextp->thing == thing
               && nextp->atr == pattr->number)
            {
                notify(player, tprintf(T("%s already added."), pName));
                return;
            }
        }

        // Otherwise, add another (thing,atr) to the list.
        //
        add = (ADDENT *)MEMALLOC(sizeof(ADDENT));
        ISOUTOFMEMORY(add);
        add->thing = thing;
        add->atr = pattr->number;
        add->name = StringClone(pName);
        add->next = old->addent;
        old->addent = add;
    }
    else
    {
        if (old)
        {
            // Delete the old built-in (which will later be added back as
            // __name).
            //
            hashdeleteLEN(pName, strlen((char *)pName), &mudstate.command_htab);
        }

        cmd = NULL;
        try
        {
            cmd = new CMDENT;
        }
        catch (...)
        {
            ; // Nothing.
        }
        ISOUTOFMEMORY(cmd);
        cmd->cmdname = StringClone(pName);
        cmd->switches = NULL;
        cmd->perms = 0;
        cmd->extra = 0;
        if (  old
           && (old->callseq & CS_LEADIN))
        {
            cmd->callseq = CS_ADDED|CS_ONE_ARG|CS_LEADIN;
        }
        else
        {
            cmd->callseq = CS_ADDED|CS_ONE_ARG;
        }
        cmd->flags = CEF_ALLOC;
        add = (ADDENT *)MEMALLOC(sizeof(ADDENT));
        ISOUTOFMEMORY(add);
        add->thing = thing;
        add->atr = pattr->number;
        add->name = StringClone(pName);
        add->next = NULL;
        cmd->addent = add;

        hashaddLEN(pName, strlen((char *)pName), cmd, &mudstate.command_htab);

        if (  old
           && strcmp((char *)pName, (char *)old->cmdname) == 0)
        {
            // We are @addcommand'ing over a built-in command by its
            // unaliased name, therefore, we want to re-target all the
            // aliases.
            //
            UTF8 *p = tprintf(T("__%s"), pName);
            hashdeleteLEN(p, strlen((char *)p), &mudstate.command_htab);
            hashreplall(old, cmd, &mudstate.command_htab);
            hashaddLEN(p, strlen((char *)p), old, &mudstate.command_htab);
        }
    }

    // We reset the one letter commands here so you can overload them.
    //
    cache_prefix_cmds();
    notify(player, tprintf(T("Command %s added."), pName));
}

void do_listcommands(dbref player, dbref caller, dbref enactor, int eval,
                     int key, UTF8 *name, const UTF8 *cargs[], int ncargs)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    CMDENT *old;
    ADDENT *nextp;
    bool didit = false;

    // Let's make this case insensitive...
    //
    size_t nCased;
    UTF8  *pCased = mux_strlwr(name, nCased);

    if (*pCased)
    {
        old = (CMDENT *)hashfindLEN(pCased, nCased, &mudstate.command_htab);

        if (  old
           && (old->callseq & CS_ADDED))
        {
            // If it's already found in the hash table, and it's being added
            // using the same object and attribute...
            //
            for (nextp = old->addent; nextp != NULL; nextp = nextp->next)
            {
                ATTR *ap = (ATTR *)atr_num(nextp->atr);
                const UTF8 *pName = T("(WARNING: Bad Attribute Number)");
                if (ap)
                {
                    pName = ap->name;
                }
                notify(player, tprintf(T("%s: #%d/%s"), nextp->name, nextp->thing, pName));
            }
        }
        else
        {
            notify(player, tprintf(T("%s not found in command table."), pCased));
        }
        return;
    }
    else
    {
        UTF8 *pKeyName;
        int  nKeyName;
        for (old = (CMDENT *)hash_firstkey(&mudstate.command_htab, &nKeyName, &pKeyName);
             old != NULL;
             old = (CMDENT *)hash_nextkey(&mudstate.command_htab, &nKeyName, &pKeyName))
        {
            if (old->callseq & CS_ADDED)
            {
                pKeyName[nKeyName] = '\0';
                for (nextp = old->addent; nextp != NULL; nextp = nextp->next)
                {
                    if (strcmp((char *)pKeyName, (char *)nextp->name) != 0)
                    {
                        continue;
                    }
                    ATTR *ap = (ATTR *)atr_num(nextp->atr);
                    const UTF8 *pName = T("(WARNING: Bad Attribute Number)");
                    if (ap)
                    {
                        pName = ap->name;
                    }
                    notify(player, tprintf(T("%s: #%d/%s"), nextp->name,
                        nextp->thing, pName));
                    didit = true;
                }
            }
        }
    }

    if (!didit)
    {
        notify(player, T("No added commands found in command table."));
    }
}

void do_delcommand
(
    dbref player,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    int   nargs,
    UTF8 *name,
    UTF8 *command,
    const UTF8 *cargs[],
    int  ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(nargs);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    if (!*name)
    {
        notify(player, T("Sorry."));
        return;
    }

    dbref thing = NOTHING;
    int atr = NOTHING;
    ATTR *pattr;
    if (*command)
    {
        if (  !parse_attrib(player, command, &thing, &pattr)
           || !pattr)
        {
            notify(player, T("No such attribute."));
            return;
        }
        if (!See_attr(player, thing, pattr))
        {
            notify(player, NOPERM_MESSAGE);
            return;
        }
        atr = pattr->number;
    }

    // Let's make this case insensitive...
    //
    size_t nCased;
    UTF8  *pCased = mux_strlwr(name, nCased);

    CMDENT *old, *cmd;
    ADDENT *prev = NULL, *nextp;
    old = (CMDENT *)hashfindLEN(pCased, nCased, &mudstate.command_htab);

    if (  old
       && (old->callseq & CS_ADDED))
    {
        UTF8 *p__Name = tprintf(T("__%s"), pCased);
        size_t n__Name = strlen((char *)p__Name);

        if (command[0] == '\0')
        {
            // Delete all @addcommand'ed associations with the given name.
            //
            for (prev = old->addent; prev != NULL; prev = nextp)
            {
                nextp = prev->next;
                MEMFREE(prev->name);
                prev->name = NULL;
                MEMFREE(prev);
                prev = NULL;
            }
            hashdeleteLEN(pCased, nCased, &mudstate.command_htab);
            cmd = (CMDENT *)hashfindLEN(p__Name, n__Name, &mudstate.command_htab);
            if (cmd)
            {
                hashaddLEN(cmd->cmdname, strlen((char *)cmd->cmdname), cmd,
                    &mudstate.command_htab);
                if (strcmp((char *)pCased, (char *)cmd->cmdname) != 0)
                {
                    hashaddLEN(pCased, nCased, cmd, &mudstate.command_htab);
                }

                hashdeleteLEN(p__Name, n__Name, &mudstate.command_htab);
                hashaddLEN(p__Name, n__Name, cmd, &mudstate.command_htab);
                hashreplall(old, cmd, &mudstate.command_htab);
            }
            else
            {
                // TODO: Delete everything related to 'old'.
                //
            }
            MEMFREE(old->cmdname);
            old->cmdname = NULL;
            MEMFREE(old);
            old = NULL;
            cache_prefix_cmds();
            notify(player, T("Done."));
        }
        else
        {
            // Remove only the (name,thing,atr) association.
            //
            for (nextp = old->addent; nextp != NULL; nextp = nextp->next)
            {
                if (  nextp->thing == thing
                   && nextp->atr == atr)
                {
                    MEMFREE(nextp->name);
                    nextp->name = NULL;
                    if (!prev)
                    {
                        if (!nextp->next)
                        {
                            hashdeleteLEN(pCased, nCased, &mudstate.command_htab);
                            cmd = (CMDENT *)hashfindLEN(p__Name, n__Name,
                                &mudstate.command_htab);
                            if (cmd)
                            {
                                hashaddLEN(cmd->cmdname, strlen((char *)cmd->cmdname),
                                    cmd, &mudstate.command_htab);
                                if (strcmp((char *)pCased, (char *)cmd->cmdname) != 0)
                                {
                                    hashaddLEN(pCased, nCased, cmd,
                                        &mudstate.command_htab);
                                }

                                hashdeleteLEN(p__Name, n__Name,
                                    &mudstate.command_htab);
                                hashaddLEN(p__Name, n__Name, cmd,
                                    &mudstate.command_htab);
                                hashreplall(old, cmd,
                                    &mudstate.command_htab);
                            }
                            MEMFREE(old->cmdname);
                            old->cmdname = NULL;
                            MEMFREE(old);
                            old = NULL;
                        }
                        else
                        {
                            old->addent = nextp->next;
                            MEMFREE(nextp);
                            nextp = NULL;
                        }
                    }
                    else
                    {
                        prev->next = nextp->next;
                        MEMFREE(nextp);
                        nextp = NULL;
                    }
                    cache_prefix_cmds();
                    notify(player, T("Done."));
                    return;
                }
                prev = nextp;
            }
            notify(player, T("Command not found in command table."));
        }
    }
    else
    {
        notify(player, T("Command not found in command table."));
    }
}

/*
 * @prog 'glues' a user's input to a command. Once executed, the first string
 * input from any of the doers's logged in descriptors, will go into
 * A_PROGMSG, which can be substituted in <command> with %0. Commands already
 * queued by the doer will be processed normally.
 */

void handle_prog(DESC *d, UTF8 *message)
{
    // Allow the player to pipe a command while in interactive mode.
    //
    if (*message == '|')
    {
        do_command(d, message + 1);

        if (d->program_data != NULL)
        {
            queue_string(d, tprintf(T("%s>%s "), COLOR_INTENSE, COLOR_RESET));

            if (OPTION_YES == UsState(d, TELNET_EOR))
            {
                // Use telnet protocol's EOR command to show prompt.
                //
                const UTF8 aEOR[2] = { NVT_IAC, NVT_EOR };
                queue_write_LEN(d, aEOR, sizeof(aEOR));
            }
            else if (OPTION_YES != UsState(d, TELNET_SGA))
            {
                // Use telnet protocol's GOAHEAD command to show prompt.
                //
                const UTF8 aGoAhead[2] = { NVT_IAC, NVT_GA };
                queue_write_LEN(d, aGoAhead, sizeof(aGoAhead));
            }
        }
        return;
    }
    dbref aowner;
    int aflags, i;
    UTF8 *cmd = atr_get("handle_prog.1215", d->player, A_PROGCMD, &aowner, &aflags);
    CLinearTimeAbsolute lta;
    wait_que(d->program_data->wait_enactor, d->player, d->player,
        AttrTrace(aflags, 0), false, lta, NOTHING, 0,
        cmd,
        1, (const UTF8 **)&message,
        d->program_data->wait_regs);

    // First, set 'all' to a descriptor we find for this player.
    //
    DESC *all = (DESC *)hashfindLEN(&(d->player), sizeof(d->player), &mudstate.desc_htab) ;

    if (  all
       && all->program_data)
    {
        PROG *program = all->program_data;
        for (i = 0; i < MAX_GLOBAL_REGS; i++)
        {
            if (program->wait_regs[i])
            {
                RegRelease(program->wait_regs[i]);
                program->wait_regs[i] = NULL;
            }
        }

        // Set info for all player descriptors to NULL
        //
        DESC_ITER_PLAYER(d->player, all)
        {
            mux_assert(program == all->program_data);
            all->program_data = NULL;
        }

        MEMFREE(program);
    }
    atr_clr(d->player, A_PROGCMD);
    free_lbuf(cmd);
}

void do_quitprog(dbref player, dbref caller, dbref enactor, int eval, int key, UTF8 *name, const UTF8 *cargs[], int ncargs)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    dbref doer;

    if (*name)
    {
        doer = match_thing(player, name);
    }
    else
    {
        doer = player;
    }

    if (  !(  Prog(player)
           || Prog(Owner(player)))
       && player != doer)
    {
        notify(player, NOPERM_MESSAGE);
        return;
    }
    if (  !Good_obj(doer)
       || !isPlayer(doer))
    {
        notify(player, T("That is not a player."));
        return;
    }
    if (!Connected(doer))
    {
        notify(player, T("That player is not connected."));
        return;
    }
    DESC *d;
    bool isprog = false;
    DESC_ITER_PLAYER(doer, d)
    {
        if (NULL != d->program_data)
        {
            isprog = true;
        }
    }

    if (!isprog)
    {
        notify(player, T("Player is not in an @program."));
        return;
    }

    d = (DESC *)hashfindLEN(&doer, sizeof(doer), &mudstate.desc_htab);
    int i;

    if (  d
       && d->program_data)
    {
        PROG *program = d->program_data;
        for (i = 0; i < MAX_GLOBAL_REGS; i++)
        {
            if (program->wait_regs[i])
            {
                RegRelease(program->wait_regs[i]);
                program->wait_regs[i] = NULL;
            }
        }

        // Set info for all player descriptors to NULL.
        //
        DESC_ITER_PLAYER(doer, d)
        {
            mux_assert(program == d->program_data);
            d->program_data = NULL;
        }

        MEMFREE(program);
    }

    atr_clr(doer, A_PROGCMD);
    notify(player, T("@program cleared."));
    notify(doer, T("Your @program has been terminated."));
}

void do_prog
(
    dbref player,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    int   nargs,
    UTF8 *name,
    UTF8 *command,
    const UTF8 *cargs[],
    int   ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(nargs);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    if (  !name
       || !*name)
    {
        notify(player, T("No players specified."));
        return;
    }

    dbref doer = match_thing(player, name);
    if (  !(  Prog(player)
           || Prog(Owner(player)))
       && player != doer)
    {
        notify(player, NOPERM_MESSAGE);
        return;
    }
    if (  !Good_obj(doer)
       || !isPlayer(doer))
    {
        notify(player, T("That is not a player."));
        return;
    }
    if (!Connected(doer))
    {
        notify(player, T("That player is not connected."));
        return;
    }

    // Check to see if the enactor already has an @prog input pending.
    //
    DESC *d;
    DESC_ITER_PLAYER(doer, d)
    {
        if (d->program_data != NULL)
        {
            notify(player, T("Input already pending."));
            return;
        }
    }

    UTF8 *msg = command;
    UTF8 *attrib = parse_to(&msg, ':', 1);

    if (msg && *msg)
    {
        notify(doer, msg);
    }

    dbref thing;
    ATTR *ap;
    if (!parse_attrib(player, attrib, &thing, &ap))
    {
        notify(player, NOMATCH_MESSAGE);
        return;
    }
    if (ap)
    {
        dbref aowner;
        int   aflags;
        int   lev;
        dbref parent;
        UTF8 *pBuffer = NULL;
        bool bFound = false;
        ITER_PARENTS(thing, parent, lev)
        {
            pBuffer = atr_get("do_prog.1405", parent, ap->number, &aowner, &aflags);
            if (pBuffer[0])
            {
                bFound = true;
                break;
            }
            free_lbuf(pBuffer);
        }
        if (bFound)
        {
            if (  (   God(player)
                  || !God(thing))
               && See_attr(player, thing, ap))
            {
                atr_add_raw(doer, A_PROGCMD, pBuffer);
            }
            else
            {
                notify(player, NOPERM_MESSAGE);
                free_lbuf(pBuffer);
                return;
            }
            free_lbuf(pBuffer);
        }
        else
        {
            notify(player, T("Attribute not present on object."));
            return;
        }
    }
    else
    {
        notify(player, T("No such attribute."));
        return;
    }

    PROG *program = (PROG *)MEMALLOC(sizeof(PROG));
    ISOUTOFMEMORY(program);
    program->wait_enactor = player;
    for (int i = 0; i < MAX_GLOBAL_REGS; i++)
    {
        program->wait_regs[i] = mudstate.global_regs[i];
        if (mudstate.global_regs[i])
        {
            RegAddRef(mudstate.global_regs[i]);
        }
    }

    // Now, start waiting.
    //
    DESC_ITER_PLAYER(doer, d)
    {
        d->program_data = program;

        queue_string(d, tprintf(T("%s>%s "), COLOR_INTENSE, COLOR_RESET));

        if (OPTION_YES == UsState(d, TELNET_EOR))
        {
            // Use telnet protocol's EOR command to show prompt.
            //
            const UTF8 aEOR[2] = { NVT_IAC, NVT_EOR };
            queue_write_LEN(d, aEOR, sizeof(aEOR));
        }
        else if (OPTION_YES != UsState(d, TELNET_SGA))
        {
            // Use telnet protocol's GOAHEAD command to show prompt.
            //
            const UTF8 aGoAhead[2] = { NVT_IAC, NVT_GA };
            queue_write_LEN(d, aGoAhead, sizeof(aGoAhead));
        }
    }
}

/* ---------------------------------------------------------------------------
 * do_restart: Restarts the game.
 */
void do_restart(dbref executor, dbref caller, dbref enactor, int eval, int key)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);

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

    bool bDenied = false;
#if defined(HAVE_WORKING_FORK)
    if (mudstate.dumping)
    {
        notify(executor, T("Dumping. Please try again later."));
        bDenied = true;
    }
#endif // HAVE_WORKING_FORK


    if (!mudstate.bCanRestart)
    {
        notify(executor, T("Server just started. Please try again in a few seconds."));
        bDenied = true;
    }
    if (bDenied)
    {
        STARTLOG(LOG_ALWAYS, "WIZ", "RSTRT");
        log_text(T("Restart requested but not executed by "));
        log_name(executor);
        ENDLOG;
        return;
    }

#ifdef UNIX_SSL
    raw_broadcast(0, T("GAME: Restart by %s, please wait.  (All SSL connections will be dropped.)"), Moniker(Owner(executor)));
#else
    raw_broadcast(0, T("GAME: Restart by %s, please wait."), Moniker(Owner(executor)));
#endif
    STARTLOG(LOG_ALWAYS, "WIZ", "RSTRT");
    log_text(T("Restart by "));
    log_name(executor);
    ENDLOG;

#ifdef UNIX_SSL
    CleanUpSSLConnections();
#endif

    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

#ifndef MEMORY_BASED
    al_store();
#endif
    pcache_sync();
    dump_database_internal(DUMP_I_RESTART);
    SYNC;
    CLOSE;

#if defined(WINDOWS_NETWORKING)
    WSACleanup();
#endif // WINDOWS_NETWORKING
#if defined(WINDOWS_PROCESSES)
    exit(12345678);
#elif defined(UNIX_PROCESSES)
#if defined(HAVE_WORKING_FORK)
    dump_restart_db();
    CleanUpSlaveSocket();
    CleanUpSlaveProcess();
#endif // HAVE_WORKING_FORK

    Log.StopLogging();

#ifdef GAME_DOOFERMUX
    execl("bin/netmux", mudconf.mud_name, "-c", mudconf.config_file, "-p",
        mudconf.pid_file, "-e", mudconf.log_dir, (char *)NULL);
#else
    execl("bin/netmux", "netmux", "-c", mudconf.config_file, "-p",
        mudconf.pid_file, "-e", mudconf.log_dir, (char *)NULL);
#endif // GAME_DOOFERMUX
    mux_assert(false);
#endif // UNIX_PROCESSES
}

/* ---------------------------------------------------------------------------
 * do_backup: Backs up and restarts the game
 * By Wadhah Al-Tailji (7-21-97), altailji@nmt.edu
 * Ported to MUX2 by Patrick Hill (7-5-2001), hellspawn@anomux.org
 */

#if defined(WINDOWS_PROCESSES)

void do_backup(dbref player, dbref caller, dbref enactor, int eval, int key)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(key);

    notify(player, T("This feature is not yet available on Windows-hosted MUX."));
}

#elif defined(UNIX_PROCESSES)

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

#if defined(HAVE_WORKING_FORK)
    if (mudstate.dumping)
    {
        notify(executor, T("Dumping. Please try again later."));
    }
#endif // HAVE_WORKING_FORK

    raw_broadcast(0, T("GAME: Backing up database. Please wait."));
    STARTLOG(LOG_ALWAYS, "WIZ", "BACK");
    log_text(T("Backup by "));
    log_name(executor);
    ENDLOG;

#ifdef MEMORY_BASED
    // Invoking _backupflat.sh with an argument prompts the backup script
    // to use it as the flatfile.
    //
    dump_database_internal(DUMP_I_FLAT);
    system((char *)tprintf(T("./_backupflat.sh %s.FLAT 1>&2"), mudconf.indb));
#else // MEMORY_BASED
    // Invoking _backupflat.sh without an argument prompts the backup script
    // to use dbconvert itself.
    //
    dump_database_internal(DUMP_I_NORMAL);
    system((char *)tprintf(T("./_backupflat.sh 1>&2")));
#endif // MEMORY_BASED
    raw_broadcast(0, T("GAME: Backup finished."));
}
#endif // UNIX_PROCESSES

/* ---------------------------------------------------------------------------
 * do_comment: Implement the @@ (comment) command. Very cpu-intensive :-)
 */

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

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

static dbref promote_dflt(dbref old, dbref new0)
{
    if (  old == NOPERM
       || new0 == NOPERM)
    {
        return NOPERM;
    }
    if (  old == AMBIGUOUS
       || new0 == AMBIGUOUS)
    {
        return AMBIGUOUS;
    }
    return NOTHING;
}

dbref match_possessed(dbref player, dbref thing, UTF8 *target, dbref dflt, bool check_enter)
{
    // First, check normally.
    //
    if (Good_obj(dflt))
    {
        return dflt;
    }

    // Didn't find it directly.  Recursively do a contents check.
    //
    dbref result, result1;
    UTF8 *buff, *place, *s1, *d1, *temp;
    UTF8 *start = target;
    while (*target)
    {
        // Fail if no ' characters.
        //
        place = target;
        target = (UTF8 *)strchr((char *)place, '\'');
        if (  target == NULL
           || !*target)
        {
            return dflt;
        }

        // If string started with a ', skip past it
        //
        if (place == target)
        {
            target++;
            continue;
        }

        // If next character is not an s or a space, skip past
        //
        temp = target++;
        if (!*target)
        {
            return dflt;
        }
        if (  *target != 's'
           && *target != 'S'
           && *target != ' ')
        {
            continue;
        }

        // If character was not a space make sure the following character is
        // a space.
        //
        if (*target != ' ')
        {
            target++;
            if (!*target)
            {
                return dflt;
            }
            if (*target != ' ')
            {
                continue;
            }
        }

        // Copy the container name to a new buffer so we can terminate it.
        //
        buff = alloc_lbuf("is_posess");
        for (s1 = start, d1 = buff; *s1 && (s1 < temp); *d1++ = (*s1++))
        {
            ; // Nothing.
        }
        *d1 = '\0';

        // Look for the container here and in our inventory.  Skip past if we
        // can't find it.
        //
        init_match(thing, buff, NOTYPE);
        if (player == thing)
        {
            match_neighbor();
            match_possession();
        }
        else
        {
            match_possession();
        }
        result1 = match_result();

        free_lbuf(buff);
        if (!Good_obj(result1))
        {
            dflt = promote_dflt(dflt, result1);
            continue;
        }

        // If we don't control it and it is either dark or opaque, skip past.
        //
        bool control = Controls(player, result1);
        if (  (  Dark(result1)
              || Opaque(result1))
           && !control)
        {
            dflt = promote_dflt(dflt, NOTHING);
            continue;
        }

        // Validate object has the ENTER bit set, if requested.
        //
        if (  check_enter
           && !Enter_ok(result1)
           && !control)
        {
            dflt = promote_dflt(dflt, NOPERM);
            continue;
        }

        // Look for the object in the container.
        //
        init_match(result1, target, NOTYPE);
        match_possession();
        result = match_result();
        result = match_possessed(player, result1, target, result, check_enter);
        if (Good_obj(result))
        {
            return result;
        }
        dflt = promote_dflt(dflt, result);
    }
    return dflt;
}

/* ---------------------------------------------------------------------------
 * parse_range: break up <what>,<low>,<high> syntax
 */

void parse_range(UTF8 **name, dbref *low_bound, dbref *high_bound)
{
    UTF8 *buff1 = *name;
    if (buff1 && *buff1)
    {
        *name = parse_to(&buff1, ',', EV_STRIP_TS);
    }
    if (buff1 && *buff1)
    {
        UTF8 *buff2 = parse_to(&buff1, ',', EV_STRIP_TS);
        if (buff1 && *buff1)
        {
            while (mux_isspace(*buff1))
            {
                buff1++;
            }

            if (*buff1 == NUMBER_TOKEN)
            {
                buff1++;
            }

            *high_bound = mux_atol(buff1);
            if (*high_bound >= mudstate.db_top)
            {
                *high_bound = mudstate.db_top - 1;
            }
        }
        else
        {
            *high_bound = mudstate.db_top - 1;
        }

        while (mux_isspace(*buff2))
        {
            buff2++;
        }

        if (*buff2 == NUMBER_TOKEN)
        {
            buff2++;
        }

        *low_bound = mux_atol(buff2);
        if (*low_bound < 0)
        {
            *low_bound = 0;
        }
    }
    else
    {
        *low_bound = 0;
        *high_bound = mudstate.db_top - 1;
    }
}

bool parse_thing_slash(dbref player, const UTF8 *thing, const UTF8 **after, dbref *it)
{
    // Get name up to '/'.
    //
    size_t i = 0;
    while (  thing[i] != '\0'
          && thing[i] != '/')
    {
        i++;
    }

    // If no '/' in string, return failure.
    //
    if (thing[i] == '\0')
    {
        *after = NULL;
        *it = NOTHING;
        return false;
    }
    *after = thing + i + 1;

    // Look for the object.
    //
    init_match(player, thing, i, NOTYPE);
    match_everything(MAT_EXIT_PARENTS);
    *it = match_result();

    // Return status of search.
    //
    return Good_obj(*it);
}

bool get_obj_and_lock(dbref player, const UTF8 *what, dbref *it, ATTR **attr, UTF8 *errmsg, UTF8 **bufc)
{
    // Get name up to '/'.
    //
    size_t i = 0;
    while (  what[i] != '\0'
          && what[i] != '/')
    {
        i++;
    }

    *it = match_thing_quiet(player, what, i);
    if (!Good_obj(*it))
    {
        safe_match_result(*it, errmsg, bufc);
        return false;
    }

    int anum;
    if (what[i] == '/')
    {
        // <obj>/<lock> syntax, use the named lock.
        //
        if (!search_nametab(player, lock_sw, what + i + 1, &anum))
        {
            safe_str(T("#-1 LOCK NOT FOUND"), errmsg, bufc);
            return false;
        }
    }
    else
    {
        // Not <obj>/<lock>, do a normal get of the default lock.
        //
        anum = A_LOCK;
    }

    // Get the attribute definition, fail if not found.
    //
    *attr = atr_num(anum);
    if (NULL == *attr)
    {
        safe_str(T("#-1 LOCK NOT FOUND"), errmsg, bufc);
        return false;
    }
    return true;
}

// ---------------------------------------------------------------------------
// bCanReadAttr, bCanSetAttr: Verify permission to affect attributes.
// ---------------------------------------------------------------------------

bool bCanReadAttr(dbref executor, dbref target, ATTR *tattr, bool bCheckParent)
{
    if (!tattr)
    {
        return false;
    }

    dbref aowner;
    int aflags;

    if (  !mudstate.bStandAlone
       && bCheckParent)
    {
        atr_pget_info(target, tattr->number, &aowner, &aflags);
    }
    else
    {
        atr_get_info(target, tattr->number, &aowner, &aflags);
    }

    int mAllow = AF_VISUAL;
    if (  (tattr->flags & mAllow)
       || (aflags & mAllow))
    {
        if (  mudstate.bStandAlone
           || tattr->number != A_DESC
           || mudconf.read_rem_desc
           || nearby(executor, target))
        {
            return true;
        }
    }
    int mDeny = 0;
    if (WizRoy(executor))
    {
        if (God(executor))
        {
            mDeny = AF_INTERNAL;
        }
        else
        {
            mDeny = AF_INTERNAL|AF_DARK;
        }
    }
    else if (  Owner(executor) == aowner
            || Examinable(executor, target))
    {
        mDeny = AF_INTERNAL|AF_DARK|AF_MDARK;
    }
    if (mDeny)
    {
        if (  (tattr->flags & mDeny)
           || (aflags & mDeny))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    return false;
}

bool bCanSetAttr(dbref executor, dbref target, ATTR *tattr)
{
    if (!tattr)
    {
        return false;
    }

    int mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST;
    if (!God(executor))
    {
        if (God(target))
        {
            return false;
        }
        if (Wizard(executor))
        {
            mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST|AF_LOCK|AF_GOD;
        }
        else if (Controls(executor, target))
        {
            mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST|AF_LOCK|AF_WIZARD|AF_GOD;
        }
        else
        {
            return false;
        }
    }

    dbref aowner;
    int aflags;
    if (  (tattr->flags & mDeny)
#ifdef FIRANMUX
       || Immutable(target)
#endif
       || (  atr_get_info(target, tattr->number, &aowner, &aflags)
          && (aflags & mDeny)))
    {
        return false;
    }
    else
    {
        return true;
    }
}

bool bCanLockAttr(dbref executor, dbref target, ATTR *tattr)
{
    if (!tattr)
    {
        return false;
    }

    int mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST;
    if (!God(executor))
    {
        if (God(target))
        {
            return false;
        }
        if (Wizard(executor))
        {
            mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST|AF_GOD;
        }
        else
        {
            mDeny = AF_INTERNAL|AF_IS_LOCK|AF_CONST|AF_WIZARD|AF_GOD;
        }
    }

    dbref aowner;
    int aflags;
    if (  (tattr->flags & mDeny)
       || !atr_get_info(target, tattr->number, &aowner, &aflags)
       || (aflags & mDeny))
    {
        return false;
    }
    else if (  Wizard(executor)
            || Owner(executor) == aowner)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/* ---------------------------------------------------------------------------
 * where_is: Returns place where obj is linked into a list.
 * ie. location for players/things, source for exits, NOTHING for rooms.
 */

dbref where_is(dbref what)
{
    if (!Good_obj(what))
    {
        return NOTHING;
    }

    dbref loc;
    switch (Typeof(what))
    {
    case TYPE_PLAYER:
    case TYPE_THING:
        loc = Location(what);
        break;

    case TYPE_EXIT:
        loc = Exits(what);
        break;

    default:
        loc = NOTHING;
        break;
    }
    return loc;
}

/* ---------------------------------------------------------------------------
 * where_room: Return room containing player, or NOTHING if no room or
 * recursion exceeded.  If player is a room, returns itself.
 */

dbref where_room(dbref what)
{
    for (int count = mudconf.ntfy_nest_lim; count > 0; count--)
    {
        if (!Good_obj(what))
        {
            break;
        }
        if (isRoom(what))
        {
            return what;
        }
        if (!Has_location(what))
        {
            break;
        }
        what = Location(what);
    }
    return NOTHING;
}

bool locatable(dbref player, dbref it, dbref enactor)
{
    // No sense if trying to locate a bad object
    //
    if (!Good_obj(it))
    {
        return false;
    }

    if (Hidden(it) && !See_Hidden(player))
    {
        return false;
    }

    dbref loc_it = where_is(it);

    // Succeed if we can examine the target, if we are the target, if we can
    // examine the location, if a wizard caused the lookup, or if the target
    // caused the lookup.
    //
    if (  Examinable(player, it)
       || Find_Unfindable(player)
       || loc_it == player
       || (  loc_it != NOTHING
          && (  Examinable(player, loc_it)
             || loc_it == where_is(player)))
       || Wizard(enactor)
       || it == enactor)
    {
        return true;
    }

    dbref room_it = where_room(it);
    bool findable_room;
    if (Good_obj(room_it))
    {
        findable_room = Findable(room_it);
    }
    else
    {
        findable_room = true;
    }

    // Succeed if we control the containing room or if the target is findable
    // and the containing room is not unfindable.
    //
    if (  (  room_it != NOTHING
          && Examinable(player, room_it))
       || Find_Unfindable(player)
       || (  Findable(it)
          && findable_room))
    {
        return true;
    }

    // We can't do it.
    //
    return false;
}

/* ---------------------------------------------------------------------------
 * nearby: Check if thing is nearby player (in inventory, in same room, or
 * IS the room.
 */

bool nearby(dbref player, dbref thing)
{
    if (  !Good_obj(player)
       || !Good_obj(thing))
    {
        return false;
    }
    if (  Can_Hide(thing)
       && Hidden(thing)
       && !See_Hidden(player))
    {
        return false;
    }
    dbref thing_loc = where_is(thing);
    if (thing_loc == player)
    {
        return true;
    }
    dbref player_loc = where_is(player);
    if (  thing_loc == player_loc
       || thing == player_loc)
    {
        return true;
    }
    return false;
}

/*
 * ---------------------------------------------------------------------------
 * * exit_visible, exit_displayable: Is exit visible?
 */
bool exit_visible(dbref exit, dbref player, int key)
{
#ifdef WOD_REALMS
    if (!mudstate.bStandAlone)
    {
        int iRealmDirective = DoThingToThingVisibility(player, exit,
            ACTION_IS_STATIONARY);
        if (REALM_DO_HIDDEN_FROM_YOU == iRealmDirective)
        {
            return false;
        }
    }
#endif // WOD_REALMS

#ifdef REALITY_LVLS
    if (!mudstate.bStandAlone)
    {
        if (!IsReal(player, exit))
        {
            return false;
        }
    }
#endif // REALITY_LVLS

    // Exam exit's location
    //
    if (  (key & VE_LOC_XAM)
       || Examinable(player, exit)
       || Light(exit))
    {
        return true;
    }

    // Dark location or base
    //
    if (  (key & (VE_LOC_DARK | VE_BASE_DARK))
       || Dark(exit))
    {
        return false;
    }

    // Default
    //
    return true;
}

// Exit visible to look
//
bool exit_displayable(dbref exit, dbref player, int key)
{
#if !defined(WOD_REALMS) && !defined(REALITY_LVLS)
    UNUSED_PARAMETER(player);
#endif // WOD_REALMS

    // Dark exit
    //
    if (Dark(exit))
    {
        return false;
    }

#ifdef WOD_REALMS
    if (!mudstate.bStandAlone)
    {
        int iRealmDirective = DoThingToThingVisibility(player, exit,
            ACTION_IS_STATIONARY);
        if (REALM_DO_HIDDEN_FROM_YOU == iRealmDirective)
        {
            return false;
        }
    }
#endif // WOD_REALMS

#ifdef REALITY_LVLS
    if (!mudstate.bStandAlone)
    {
        if (!IsReal(player, exit))
        {
            return false;
        }
    }
#endif // REALITY_LVLS

    // Light exit
    //
    if (Light(exit))
    {
        return true;
    }

    // Dark location or base.
    //
    if (key & (VE_LOC_DARK | VE_BASE_DARK))
    {
        return false;
    }

    // Default
    //
    return true;
}

/* ---------------------------------------------------------------------------
 * did_it: Have player do something to/with thing
 */

void did_it(dbref player, dbref thing, int what, const UTF8 *def, int owhat,
            const UTF8 *odef, int awhat, int ctrl_flags,
            const UTF8 *args[], int nargs)
{
    if (MuxAlarm.bAlarmed)
    {
        return;
    }

    UTF8 *d, *buff, *act, *charges, *bp;
    dbref loc, aowner;
    int num, aflags;

    // If we need to call exec() from within this function, we first save
    // the state of the global registers, in order to avoid munging them
    // inappropriately. Do note that the restoration to their original
    // values occurs BEFORE the execution of the @a-attribute. Therefore,
    // any changing of setq() values done in the @-attribute and @o-attribute
    // will NOT be passed on. This prevents odd behaviors that result from
    // odd @verbs and so forth (the idea is to preserve the caller's control
    // of the global register values).
    //

    bool need_pres = false;
    reg_ref **preserve = NULL;

    // message to player.
    //
    if (what > 0)
    {
        d = atr_pget(thing, what, &aowner, &aflags);
        if (*d)
        {
            need_pres = true;
            preserve = PushRegisters(MAX_GLOBAL_REGS);
            save_global_regs(preserve);

            buff = bp = alloc_lbuf("did_it.1");
            mux_exec(d, LBUF_SIZE-1, buff, &bp, thing, player, player,
                AttrTrace(aflags, EV_EVAL|EV_FIGNORE|EV_FCHECK|EV_TOP),
                args, nargs);
            *bp = '\0';
            if (  (aflags & AF_HTML)
               && Html(player))
            {
                safe_str(T("\r\n"), buff, &bp);
                *bp = '\0';
                notify_html(player, buff);
            }
#if defined(FIRANMUX)
            else if (  A_DESC == what
                    && Linewrap(player)
                    && isPlayer(player)
                    && (  !Linewrap(thing)
                       || isPlayer(thing)))
            {
                UTF8 *p = alloc_lbuf("did_it.2");
                linewrap_general(buff, 71, p, LBUF_SIZE-1, T("     "), 5);
                notify(player, p);
                free_lbuf(p);
            }
#endif // FIRANMUX
            else
            {
                notify(player, buff);
            }
            free_lbuf(buff);
        }
        else if (def)
        {
            notify(player, def);
        }
        free_lbuf(d);
    }
    else if (what < 0 && def)
    {
        notify(player, def);
    }

    // message to neighbors.
    //
    if (  0 < owhat
       && Has_location(player)
       && Good_obj(loc = Location(player)))
    {
        d = atr_pget(thing, owhat, &aowner, &aflags);
        if (*d)
        {
            if (!need_pres)
            {
                need_pres = true;
                preserve = PushRegisters(MAX_GLOBAL_REGS);
                save_global_regs(preserve);
            }
            buff = bp = alloc_lbuf("did_it.2");
            mux_exec(d, LBUF_SIZE-1, buff, &bp, thing, player, player,
                 AttrTrace(aflags, EV_EVAL|EV_FIGNORE|EV_FCHECK|EV_TOP),
                 args, nargs);
            *bp = '\0';
#if !defined(FIRANMUX)
            if (*buff)
#endif // FIRANMUX
            {
#ifdef REALITY_LVLS
                if (aflags & AF_NONAME)
                {
                    notify_except2_rlevel(loc, player, player, thing, buff);
                }
                else
                {
                    notify_except2_rlevel(loc, player, player, thing,
                        tprintf(T("%s %s"), Moniker(player), buff));
                }
#else
                if (aflags & AF_NONAME)
                {
                    notify_except2(loc, player, player, thing, buff);
                }
                else
                {
                    notify_except2(loc, player, player, thing,
                        tprintf(T("%s %s"), Moniker(player), buff));
                }
#endif // REALITY_LVLS
            }
            free_lbuf(buff);
        }
        else if (odef)
        {
#ifdef REALITY_LVLS
            if (ctrl_flags & VERB_NONAME)
            {
                notify_except2_rlevel(loc, player, player, thing, odef);
            }
            else
            {
                notify_except2_rlevel(loc, player, player, thing,
                        tprintf(T("%s %s"), Moniker(player), odef));
            }
#else
            if (ctrl_flags & VERB_NONAME)
            {
                notify_except2(loc, player, player, thing, odef);
            }
            else
            {
                notify_except2(loc, player, player, thing,
                        tprintf(T("%s %s"), Moniker(player), odef));
            }
#endif // REALITY_LVLS
        }
        free_lbuf(d);
    } else if (  owhat < 0
              && odef
              && Has_location(player)
              && Good_obj(loc = Location(player)))
    {
#ifdef REALITY_LVLS
        if (ctrl_flags & VERB_NONAME)
        {
            notify_except2_rlevel(loc, player, player, thing, odef);
        }
        else
        {
            notify_except2_rlevel(loc, player, player, thing, tprintf(T("%s %s"), Name(player), odef));
        }
#else
        if (ctrl_flags & VERB_NONAME)
        {
            notify_except2(loc, player, player, thing, odef);
        }
        else
        {
            notify_except2(loc, player, player, thing, tprintf(T("%s %s"), Name(player), odef));
        }
#endif // REALITY_LVLS
    }

    // If we preserved the state of the global registers, restore them.
    //
    if (need_pres)
    {
        restore_global_regs(preserve);
        PopRegisters(preserve, MAX_GLOBAL_REGS);
    }

    // Do the action attribute.
    //
#ifdef REALITY_LVLS
    if (  0 < awhat
       && IsReal(thing, player))
#else
    if (0 < awhat)
#endif // REALITY_LVLS
    {
        if (*(act = atr_pget(thing, awhat, &aowner, &aflags)))
        {
            dbref aowner2;
            int   aflags2;
            charges = atr_pget(thing, A_CHARGES, &aowner2, &aflags2);
            if (*charges)
            {
                num = mux_atol(charges);
                if (num > 0)
                {
                    buff = alloc_sbuf("did_it.charges");
                    mux_ltoa(num-1, buff);
                    atr_add_raw(thing, A_CHARGES, buff);
                    free_sbuf(buff);
                }
                else if (*(buff = atr_pget(thing, A_RUNOUT, &aowner2, &aflags2)))
                {
                    free_lbuf(act);
                    act = buff;
                }
                else
                {
                    free_lbuf(act);
                    free_lbuf(buff);
                    free_lbuf(charges);
                    return;
                }
            }
            free_lbuf(charges);
            CLinearTimeAbsolute lta;
            wait_que(thing, player, player, AttrTrace(aflags, 0), false, lta,
                NOTHING, 0,
                act,
                nargs, args,
                mudstate.global_regs);
        }
        free_lbuf(act);
    }
}

/* ---------------------------------------------------------------------------
 * do_verb: Command interface to did_it.
 */

void do_verb(dbref executor, dbref caller, dbref enactor, int eval, int key,
             UTF8 *victim_str, UTF8 *args[], int nargs, const UTF8 *cargs[], int ncargs)
{
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(key);
    UNUSED_PARAMETER(cargs);
    UNUSED_PARAMETER(ncargs);

    // Look for the victim.
    //
    if (  !victim_str
       || !*victim_str)
    {
        notify(executor, T("Nothing to do."));
        return;
    }

    // Get the victim.
    //
    init_match(executor, victim_str, NOTYPE);
    match_everything(MAT_EXIT_PARENTS);
    dbref victim = noisy_match_result();
    if (!Good_obj(victim))
    {
        return;
    }

    // Get the actor.  Default is my cause.
    //
    dbref actor;
    if (  nargs >= 1
       && args[0] && *args[0])
    {
        init_match(executor, args[0], NOTYPE);
        match_everything(MAT_EXIT_PARENTS);
        actor = noisy_match_result();
        if (!Good_obj(actor))
        {
            return;
        }
    }
    else
    {
        actor = enactor;
    }

    // Check permissions.  There are two possibilities:
    //
    //    1. Executor controls both victim and actor. In this case,
    //       victim runs his action list.
    //
    //    2. Executor controls actor. In this case victim does not run
    //       his action list and any attributes that executor cannot read
    //       from victim are defaulted.
    //
    if (!Controls(executor, actor))
    {
        notify_quiet(executor, T("Permission denied,"));
        return;
    }

    ATTR *ap;
    int what = -1;
    int owhat = -1;
    int awhat = -1;
    const UTF8 *whatd = NULL;
    const UTF8 *owhatd = NULL;
    int nxargs = 0;
    dbref aowner = NOTHING;
    int aflags = NOTHING;
    UTF8 *xargs[10];

    switch (nargs) // Yes, this IS supposed to fall through.
    {
    case 7:
        // Get arguments.
        //
        parse_arglist(victim, actor, actor, args[6],
            EV_STRIP_LS | EV_STRIP_TS, xargs, 10, NULL, 0, &nxargs);

    case 6:
        // Get action attribute.
        //
        ap = atr_str(args[5]);
        if (ap)
        {
            awhat = ap->number;
        }

    case 5:
        // Get others message default.
        //
        if (args[4] && *args[4])
        {
            owhatd = args[4];
        }

    case 4:
        // Get others message attribute.
        //
        ap = atr_str(args[3]);
        if (ap && (ap->number > 0))
        {
            owhat = ap->number;
        }

    case 3:
        // Get enactor message default.
        //
        if (args[2] && *args[2])
        {
            whatd = args[2];
        }

    case 2:
        // Get enactor message attribute.
        //
        ap = atr_str(args[1]);
        if (ap && (ap->number > 0))
        {
            what = ap->number;
        }
    }

    // If executor doesn't control both, enforce visibility restrictions.
    //
    if (!Controls(executor, victim))
    {
        ap = NULL;
        if (what != -1)
        {
            atr_get_info(victim, what, &aowner, &aflags);
            ap = atr_num(what);
        }
        if (  !ap
           || !bCanReadAttr(executor, victim, ap, false)
           || (  ap->number == A_DESC
              && !mudconf.read_rem_desc
              && !Examinable(executor, victim)
              && !nearby(executor, victim)))
        {
            what = -1;
        }

        ap = NULL;
        if (owhat != -1)
        {
            atr_get_info(victim, owhat, &aowner, &aflags);
            ap = atr_num(owhat);
        }
        if (  !ap
           || !bCanReadAttr(executor, victim, ap, false)
           || (  ap->number == A_DESC
              && !mudconf.read_rem_desc
              && !Examinable(executor, victim)
              && !nearby(executor, victim)))
        {
            owhat = -1;
        }

        awhat = 0;
    }

    // Go do it.
    //
    did_it(actor, victim, what, whatd, owhat, owhatd, awhat,
        key & VERB_NONAME, (const UTF8 **)xargs, nxargs);

    // Free user args.
    //
    for (int i = 0; i < nxargs; i++)
    {
        free_lbuf(xargs[i]);
    }
}

// --------------------------------------------------------------------------
// OutOfMemory: handle an out of memory condition.
//
void OutOfMemory(const UTF8 *SourceFile, unsigned int LineNo)
{
    mudstate.asserting++;
    if (  1 <= mudstate.asserting
       && mudstate.asserting <= 2)
    {
        Log.tinyprintf(T("%s(%u): Out of memory." ENDLINE), SourceFile, LineNo);
        Log.Flush();
        if (  !mudstate.bStandAlone
           && mudstate.bCanRestart)
        {
            do_restart(GOD, GOD, GOD, 0, 0);
        }
        else
        {
            abort();
        }
    }
    mudstate.asserting--;
}

// --------------------------------------------------------------------------
// AssertionFailed: A logical assertion has failed.
//
bool AssertionFailed(const UTF8 *SourceFile, unsigned int LineNo)
{
    mudstate.asserting++;
    if (  1 <= mudstate.asserting
       && mudstate.asserting <= 2)
    {
        Log.tinyprintf(T("%s(%u): Assertion failed." ENDLINE), SourceFile, LineNo);
        report();
        Log.Flush();
        if (  !mudstate.bStandAlone
           && mudstate.bCanRestart)
        {
            do_restart(GOD, GOD, GOD, 0, 0);
        }
        else
        {
            abort();
        }
    }
    else
    {
        abort();
    }
    mudstate.asserting--;
    return false;
}

static void ListReferences(dbref executor, UTF8 *reference_name)
{
    dbref target = NOTHING;
    bool global_only = false;
    mux_string refstr(reference_name);

    if (  NULL == reference_name
       || '\0' == reference_name[0])
    {
        global_only = true;
        refstr.prepend('_');
    }
    else
    {
        global_only = false;
        target = lookup_player(executor, reference_name, 1);
        if (!Good_obj(target))
        {
            raw_notify(executor, T("No such player."));
            return;
        }

        if (!Controls(executor, target))
        {
            raw_notify(executor, NOPERM_MESSAGE);
            return;
        }
    }

    //  Listing:
    //    - if global_only is true, list all references that begin with _
    //    - Otherwise, list all references whose owner is target
    //
    reference_entry *htab_entry;
    bool match_found = false;

    CHashTable* htab = &mudstate.reference_htab;
    for (  htab_entry = (struct reference_entry *) hash_firstentry(htab);
           NULL != htab_entry;
           htab_entry = (struct reference_entry *) hash_nextentry(htab))
    {
        if (  (  global_only
              && '_' == htab_entry->name[0])
           || (  !global_only
              && target == htab_entry->owner))
        {
            if (!Good_obj(htab_entry->target))
            {
                continue;
            }

            if (!match_found)
            {
                match_found = true;
                raw_notify(executor, tprintf(T("%-12s %-20s %-20s"),
                            T("Reference"), T("Target"), T("Owner")));
                raw_notify(executor,
                        T("-------------------------------------------------------"));
            }

            UTF8 *object_buf =
                unparse_object(executor, htab_entry->target, false);

            raw_notify(executor, tprintf(T("%-12s %-20s %-20s"), htab_entry->name,
                        object_buf, Moniker(htab_entry->owner)));

            free_lbuf(object_buf);
        }
    }

    if (!match_found)
    {
        raw_notify(executor, T("GAME: No references found."));
    }
    else
    {
        raw_notify(executor,
                T("---------------- End of Reference List ----------------"));
    }
}

void do_reference
(
    dbref executor,
    dbref caller,
    dbref enactor,
    int   eval,
    int   key,
    int   nargs,
    UTF8 *reference_name,
    UTF8 *object_name,
    const UTF8 *cargs[],
    int   ncargs
)
{
    UNUSED_PARAMETER(caller);
    UNUSED_PARAMETER(enactor);
    UNUSED_PARAMETER(eval);
    UNUSED_PARAMETER(nargs);
    UNUSED_PARAMETER(ncargs);
    UNUSED_PARAMETER(cargs);

    if (key & REFERENCE_LIST)
    {
        ListReferences(executor, reference_name);
        return;
    }

    // References can only be set on objects the executor can examine.
    //
    dbref target = NOTHING;
    if (  NULL != object_name
       && '\0' != object_name[0])
    {
        target = match_thing_quiet(executor, object_name);

        if (!Good_obj(target))
        {
            notify(executor, NOMATCH_MESSAGE);
            return;
        }
        else if (!Examinable(executor, target))
        {
            notify(executor, NOPERM_MESSAGE);
            return;
        }
    }

    mux_string refstr(reference_name);
    if ('_' == reference_name[0])
    {
        if (!Wizard(executor))
        {
            notify(executor, NOPERM_MESSAGE);
            return;
        }
    }
    else
    {
        refstr.append(T("."));
        refstr.append(executor);
    }

    UTF8 tbuf[LBUF_SIZE];
    size_t tbuf_len = refstr.export_TextPlain(tbuf);
    struct reference_entry *result = (reference_entry *)hashfindLEN(
        tbuf, tbuf_len, &mudstate.reference_htab);

    enum { Delete, Add, Update, NotFound, Redundant, OutOfMemory } eOperation;

    if (NULL != result)
    {
        if (NOTHING == target)
        {
            eOperation = Delete;
        }
        else if (result->target == target)
        {
            eOperation = Redundant;
        }
        else // if (result->target != target)
        {
            eOperation = Update;
        }
    }
    else
    {
        if (NOTHING == target)
        {
            eOperation = NotFound;
        }
        else
        {
            eOperation = Add;
            if (  !Wizard(executor)
               && ThrottleReferences(executor))
            {
                raw_notify(executor, T("References requested too quickly."));
                return;
            }
        }
    }

    if (  Delete == eOperation
       || Update == eOperation)
    {
        // Release the existing reference.
        //
        MEMFREE(result->name);
        result->name = NULL;
        MEMFREE(result);
        result = NULL;
        hashdeleteLEN(tbuf, tbuf_len, &mudstate.reference_htab);
    }

    if (  Update == eOperation
       || Add == eOperation)
    {
        try
        {
            result = (reference_entry *)MEMALLOC(sizeof(reference_entry));
        }
        catch(...)
        {
            ; // Nothing;
        }

        if (NULL != result)
        {
            result->target = target;
            result->owner = executor;
            result->name = StringCloneLen(tbuf, tbuf_len);
            hashaddLEN(tbuf, tbuf_len, result, &mudstate.reference_htab);
        }
        else
        {
            eOperation = OutOfMemory;
        }
    }

    if (Delete == eOperation)
    {
        raw_notify(executor, T("Reference cleared."));
    }
    else if (Update == eOperation)
    {
        raw_notify(executor, T("Reference updated."));
    }
    else if (Redundant == eOperation)
    {
        raw_notify(executor, T("That reference already exists."));
    }
    else if (NotFound == eOperation)
    {
        raw_notify(executor, T("No such reference to clear."));
    }
    else if (Add == eOperation)
    {
        raw_notify(executor, T("Reference added."));
    }
    else if (OutOfMemory == eOperation)
    {
        raw_notify(executor, OUT_OF_MEMORY);
    }
}