File: mon-util.cc

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

#include "AppHdr.h"

#include "mon-util.h"

#include <algorithm>
#include <cmath>
#include <sstream>

#include "act-iter.h"
#include "areas.h"
#include "artefact.h"
#include "attitude-change.h"
#include "beam.h"
#include "cloud.h"
#include "colour.h"
#include "coordit.h"
#include "database.h"
#include "delay.h"
#include "dgn-overview.h"
#include "directn.h"
#include "dungeon.h"
#include "english.h"
#include "env.h"
#include "tile-env.h"
#include "errors.h"
#include "fight.h"
#include "files.h"
#include "fprop.h"
#include "ghost.h"
#include "god-abil.h"
#include "god-companions.h"
#include "god-item.h"
#include "god-passive.h"
#include "item-name.h"
#include "item-prop.h"
#include "items.h"
#include "libutil.h"
#include "mapmark.h"
#include "message.h"
#include "misc.h"
#include "mgen-data.h"
#include "mon-abil.h"
#include "mon-behv.h"
#include "mon-book.h"
#include "mon-cast.h"
#include "mon-death.h"
#include "mon-explode.h"
#include "mon-place.h"
#include "mon-poly.h"
#include "mon-tentacle.h"
#include "mon-util.h"
#include "mutant-beast.h"
#include "notes.h"
#include "options.h"
#include "random.h"
#include "religion.h"
#include "showsymb.h"
#include "skills.h"
#include "species.h"
#include "spl-util.h"
#include "state.h"
#include "stringutil.h"
#include "tag-version.h"
#include "terrain.h"
#include "rltiles/tiledef-player.h"
#include "tilepick.h"
#include "tileview.h"
#include "timed-effects.h"
#include "transform.h"
#include "traps.h"
#include "unicode.h"
#include "unwind.h"

static FixedVector < int, NUM_MONSTERS > mon_entry;

struct mon_display
{
    char32_t glyph;
    colour_t colour;

    mon_display(unsigned gly = 0, unsigned col = 0)
       : glyph(gly), colour(col) { }
};

static mon_display monster_symbols[NUM_MONSTERS];

#include "mon-spell.h"
#include "mon-data.h"

#define MONDATASIZE ARRAYSZ(mondata)

static bool _give_apostle_proper_name(monster& mon, apostle_type type);
static int _mons_exp(monster_type mclass);

// Macro that saves some typing, nothing more.
#define smc get_monster_data(mc)
// ASSERT(smc) was getting really old
#define ASSERT_smc()                                                    \
    do {                                                                \
        if (!get_monster_data(mc))                                      \
            die("bogus mc (no monster data): %s (%d)",                  \
                mons_type_name(mc, DESC_PLAIN).c_str(), mc);            \
    } while (false)

/* ******************** BEGIN PUBLIC FUNCTIONS ******************** */

bool monster_class_flies(monster_type mc)
{
    return mons_class_flag(mc, M_FLIES);
}

bool monster_inherently_flies(const monster &mons)
{
    // check both so spectral humans and zombified dragons both fly
    return monster_class_flies(mons.type)
        || monster_class_flies(mons_base_type(mons))
        || mons_is_draconian_job(mons.type)
            && monster_class_flies(draconian_subspecies(mons))
        || mons_is_ghost_demon(mons.type) && mons.ghost && mons.ghost->flies
        || mons.has_facet(BF_BAT);
}

dungeon_feature_type preferred_feature_type(monster_type mt)
{
    const habitat_type ht = mons_class_habitat(mt);
    if (ht & HT_DRY_LAND)
        return DNGN_FLOOR;
    if (ht & HT_LAVA)
        return DNGN_LAVA;
    if (ht & HT_DEEP_WATER)
        return DNGN_DEEP_WATER;

    // Nothing should have none of these habitats, but we need to return something.
    return DNGN_FLOOR;
}

typedef map<string, monster_type> mon_name_map;
static mon_name_map Mon_Name_Cache;

void init_mon_name_cache()
{
    if (!Mon_Name_Cache.empty())
        return;

    for (const monsterentry &me : mondata)
    {
        const int          mtype = me.mc;
        const monster_type mon   = monster_type(mtype);

        // Deal sensibly with duplicate entries; refuse or allow the
        // insert, depending on which should take precedence. Some
        // uniques of multiple forms can get away with this, though.
        if (mon == MONS_BAI_SUZHEN_DRAGON
            || mon != MONS_SERPENT_OF_HELL
               && mons_species(mon) == MONS_SERPENT_OF_HELL)
        {
            continue;
        }

        string name = me.name;
        lowercase(name);

        if (Mon_Name_Cache.count(name))
            die("Un-handled duplicate monster name: %s", name.c_str());

        Mon_Name_Cache[name] = mon;
    }
}

static const char *_mon_entry_name(size_t idx)
{
    return mondata[idx].name;
}

monster_type get_monster_by_name(string name, bool substring)
{
    if (name.empty())
        return MONS_PROGRAM_BUG;

    lowercase(name);

    if (!substring)
    {
        if (monster_type *mc = map_find(Mon_Name_Cache, name))
            return *mc;
        return MONS_PROGRAM_BUG;
    }

    size_t idx = find_earliest_match(name, (size_t) 0, ARRAYSZ(mondata),
                                     always_true<size_t>, _mon_entry_name);
    return idx == ARRAYSZ(mondata) ? MONS_PROGRAM_BUG
                                   : (monster_type) mondata[idx].mc;
}

void init_monsters()
{
    // First, fill static array with dummy values. {dlb}
    mon_entry.init(-1);

    // Next, fill static array with location of entry in mondata[]. {dlb}:
    for (unsigned int i = 0; i < MONDATASIZE; ++i)
        mon_entry[mondata[i].mc] = i;

    // Finally, monsters yet with dummy entries point to TTTSNB(tm). {dlb}:
    for (int &entry : mon_entry)
        if (entry == -1)
            entry = mon_entry[MONS_PROGRAM_BUG];

    init_monster_symbols();
}

void init_monster_symbols()
{
    map<unsigned, monster_type> base_mons;
    for (monster_type mc = MONS_0; mc < NUM_MONSTERS; ++mc)
    {
        mon_display &md = monster_symbols[mc];
        if (const monsterentry *me = get_monster_data(mc))
        {
            md.glyph  = me->basechar;
            md.colour = me->colour;
            auto it = base_mons.find(md.glyph);
            if (it == base_mons.end() || it->first == MONS_PROGRAM_BUG)
                base_mons[md.glyph] = mc;
        }
    }

    // Let those follow the feature settings, unless specifically overridden.
    monster_symbols[MONS_ANIMATED_TREE].glyph = get_feat_symbol(DNGN_TREE);

    // Validate all glyphs, even those which didn't come from an override.
    for (monster_type i = MONS_PROGRAM_BUG; i < NUM_MONSTERS; ++i)
        if (wcwidth(monster_symbols[i].glyph) != 1)
            monster_symbols[i].glyph = mons_base_char(i);
}

void set_resist(resists_t &all, mon_resist_flags res, int lev)
{
    if (res > MR_LAST_MULTI)
    {
        ASSERT_RANGE(lev, 0, 2);
        if (lev)
            all |= res;
        else
            all &= ~res;
        return;
    }

    ASSERT_RANGE(lev, -3, 5);
    all = (all & ~(res * 7)) | (res * (lev & 7));
}

int get_mons_class_ac(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    return me ? me->AC : get_monster_data(MONS_PROGRAM_BUG)->AC;
}

int get_mons_class_ev(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    return me ? me->ev : get_monster_data(MONS_PROGRAM_BUG)->ev;
}

static resists_t _apply_holiness_resists(resists_t resists, mon_holy_type mh)
{
    // Undead and non-living beings get full poison resistance.
    if (mh & (MH_UNDEAD | MH_NONLIVING))
        resists = (resists & ~(MR_RES_POISON * 7)) | (MR_RES_POISON * 3);

    // Everything but natural creatures and plants have full rNeg. Set here for
    // the benefit of the monster_info constructor. If you change this, also
    // change monster::res_negative_energy.
    if (!(mh & (MH_NATURAL | MH_PLANT)))
        resists = (resists & ~(MR_RES_NEG * 7)) | (MR_RES_NEG * 3);

    if (mh & (MH_UNDEAD | MH_DEMONIC | MH_PLANT | MH_NONLIVING))
        resists |= MR_RES_TORMENT;

    return resists;
}

/**
 * What special resistances does the given mutant beast facet provide?
 *
 * @param facet     The beast_facet in question, e.g. BF_FIRE.
 * @return          A bitfield of resists corresponding to the given facet;
 *                  e.g. MR_RES_FIRE for BF_FIRE.
 */
static resists_t _beast_facet_resists(beast_facet facet)
{
    static const map<beast_facet, resists_t> resists = {
        { BF_STING, MR_RES_POISON },
        { BF_FIRE,  MR_RES_FIRE },
        { BF_SHOCK, MR_RES_ELEC },
        { BF_OX,    MR_RES_COLD },
    };

    return lookup(resists, facet, 0);
}

resists_t get_mons_class_resists(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    const resists_t resists = me ? me->resists
                                 : get_monster_data(MONS_PROGRAM_BUG)->resists;
    // Don't apply fake holiness resists.
    if (mons_is_sensed(mc))
        return resists;

    // Assumes that, when a monster's holiness differs from other monsters
    // of the same type, that only adds resistances, never removes them.
    // Currently the only such case is MF_FAKE_UNDEAD.
    return _apply_holiness_resists(resists, mons_class_holiness(mc));
}

/// All resists intrinsic to a monster, excluding enchants, equip, etc.
resists_t get_mons_resists(const monster& m)
{
    const monster& mon = get_tentacle_head(m);

    resists_t resists = get_mons_class_resists(mon.type);

    if (mons_is_ghost_demon(mon.type))
        resists |= mon.ghost->resists;

    if (mons_genus(mon.type) == MONS_DRACONIAN && mon.type != MONS_DRACONIAN
        || mon.type == MONS_TIAMAT)
    {
        monster_type subspecies = draconian_subspecies(mon);
        if (subspecies != mon.type)
            resists |= get_mons_class_resists(subspecies);
    }

    if (mon.props.exists(MUTANT_BEAST_FACETS))
        for (auto facet : mon.props[MUTANT_BEAST_FACETS].get_vector())
            resists |= _beast_facet_resists((beast_facet)facet.get_int());

    // This is set from here in case they're undead due to the
    // MF_FAKE_UNDEAD flag. See the comment in get_mons_class_resists.
    return _apply_holiness_resists(resists, mon.holiness());
}

int get_mons_resist(const monster& mon, mon_resist_flags res)
{
    return get_resist(get_mons_resists(mon), res);
}

// Returns true if the monster successfully resists this attempt to poison it.
bool monster_resists_this_poison(const monster& mons, bool force)
{
    const int res = mons.res_poison();
    if (res >= 3)
        return true;
    if (!force && res >= 1 && x_chance_in_y(2, 3))
        return true;
    return false;
}

monster* monster_at(const coord_def &pos)
{
    if (!in_bounds(pos))
        return nullptr;

    const int mindex = env.mgrid(pos);
    if (mindex == NON_MONSTER)
        return nullptr;

    ASSERT(mindex <= MAX_MONSTERS);
    return &env.mons[mindex];
}

/// Are any of the bits set?
bool mons_class_flag(monster_type mc, monclass_flags_t bits)
{
    const monsterentry * const me = get_monster_data(mc);
    return me && (me->bitfields & bits);
}

int monster::wearing(object_class_type obj_type, int sub_type,
                     bool count_plus, bool) const
{
    int ret = 0;
    const item_def *item = 0;

    if (!alive())
        return 0;

    switch (obj_type)
    {
    case OBJ_WEAPONS:
    case OBJ_STAVES:
        {
            const mon_inv_type end = mons_wields_two_weapons(*this)
                                     ? MSLOT_ALT_WEAPON : MSLOT_WEAPON;

            for (int i = MSLOT_WEAPON; i <= end; i = i + 1)
            {
                item = mslot_item((mon_inv_type) i);
                if (item && item->base_type == obj_type
                    && item->sub_type == sub_type)
                {
                    ret++;
                }
            }
        }
        break;

    case OBJ_ARMOUR:

        item = mslot_item(MSLOT_SHIELD);
        if (item && item->is_type(OBJ_ARMOUR, sub_type))
            ret++;

        item = mslot_item(MSLOT_ARMOUR);
        if (item && item->is_type(OBJ_ARMOUR, sub_type))
            ret++;
        break;

    case OBJ_JEWELLERY:
        item = mslot_item(MSLOT_JEWELLERY);
        if (item && item->is_type(OBJ_JEWELLERY, sub_type))
        {
            if (count_plus)
                ret += item->plus;
            else
                ret++;
        }
        break;
    default:
        die("invalid object type %d for monster::wearing()", obj_type);
    }
    return ret;
}

int monster::wearing_ego(object_class_type obj_type, int special) const
{
    int ret = 0;
    const item_def *item = 0;

    if (!alive())
        return 0;

    switch (obj_type)
    {
    case OBJ_WEAPONS:
        {
            const mon_inv_type end = mons_wields_two_weapons(*this)
                                     ? MSLOT_ALT_WEAPON : MSLOT_WEAPON;

            for (int i = MSLOT_WEAPON; i <= end; i++)
            {
                item = mslot_item((mon_inv_type) i);
                if (item && item->base_type == OBJ_WEAPONS
                    && get_weapon_brand(*item) == special)
                {
                    ret++;
                }
            }
        }
        break;

    case OBJ_ARMOUR:
        item = mslot_item(MSLOT_SHIELD);
        if (item && item->base_type == OBJ_ARMOUR
            && get_armour_ego_type(*item) == special)
        {
            ret++;
        }

        item = mslot_item(MSLOT_ARMOUR);
        if (item && item->base_type == OBJ_ARMOUR
            && get_armour_ego_type(*item) == special)
        {
            ret++;
        }
        break;

    case OBJ_JEWELLERY:
    case OBJ_STAVES:
        // No egos.
        break;

    default:
        die("invalid object type %d for monster::wearing_ego()", obj_type);
    }
    return ret;
}

int monster::scan_artefacts(artefact_prop_type ra_prop,
                            vector<const item_def *> *matches) const
{
    UNUSED(matches); //TODO: implement this when it will be required somewhere

    if (!alive())
        return 0;

    int ret = 0;

    if (mons_itemuse(*this) >= MONUSE_STARTING_EQUIPMENT)
    {
        const int weap      = inv[MSLOT_WEAPON];
        const int second    = inv[MSLOT_ALT_WEAPON]; // Two-headed ogres, etc.
        const int armour    = inv[MSLOT_ARMOUR];
        const int shld      = inv[MSLOT_SHIELD];
        const int jewellery = inv[MSLOT_JEWELLERY];

        if (weap != NON_ITEM && env.item[weap].base_type == OBJ_WEAPONS
            && is_artefact(env.item[weap]))
        {
            ret += artefact_property(env.item[weap], ra_prop);
        }

        if (second != NON_ITEM && env.item[second].base_type == OBJ_WEAPONS
            && is_artefact(env.item[second]) && mons_wields_two_weapons(*this))
        {
            ret += artefact_property(env.item[second], ra_prop);
        }

        if (armour != NON_ITEM && env.item[armour].base_type == OBJ_ARMOUR
            && is_artefact(env.item[armour]))
        {
            ret += artefact_property(env.item[armour], ra_prop);
        }

        if (shld != NON_ITEM && env.item[shld].base_type == OBJ_ARMOUR
            && is_artefact(env.item[shld]))
        {
            ret += artefact_property(env.item[shld], ra_prop);
        }

        // XXX: Because monster armour slots are awkward, Wiglaf wears his hat
        //      in the jewelry slot. Since it is always an artefact, this should
        //      mostly work out fine, but I'd be happy for a better solution in
        //      future.
        if (jewellery != NON_ITEM && is_artefact(env.item[jewellery]))
            ret += artefact_property(env.item[jewellery], ra_prop);
    }

    return ret;
}

mon_holy_type holiness_by_name(string name)
{
    lowercase(name);
    for (const auto bit : mon_holy_type::range())
    {
        if (name == holiness_name(bit))
            return bit;
    }
    return MH_NONE;
}

const char * holiness_name(mon_holy_type_flags which_holiness)
{
    switch (which_holiness)
    {
    case MH_HOLY:
        return "holy";
    case MH_NATURAL:
        return "natural";
    case MH_UNDEAD:
        return "undead";
    case MH_DEMONIC:
        return "demonic";
    case MH_NONLIVING:
        return "nonliving";
    case MH_PLANT:
        return "plant";
    default:
        return "bug";
    }
}

/// Hack for demonspawn monsters. TODO: de-bitfieldify!
const char * single_holiness_description(mon_holy_type holiness)
{
    for (const auto bit : mon_holy_type::range())
    {
        if (!(holiness & bit))
            continue;
        if (bit == MH_NATURAL && holiness != MH_NATURAL)
            continue;
        return holiness_name(bit);
    }
    return "eggplant";
}

string holiness_description(mon_holy_type holiness)
{
    string description = "";
    for (const auto bit : mon_holy_type::range())
    {
        if (holiness & bit)
        {
            if (!description.empty())
                description += ",";
            description += holiness_name(bit);
        }
    }
    return description;
}

mon_holy_type mons_class_holiness(monster_type mc)
{
    ASSERT_smc();
    return smc->holiness;
}

const char* intelligence_description(mon_intel_type intel)
{
    switch (intel)
    {
    case I_BRAINLESS:   return "Mindless";
    case I_ANIMAL:      return "Animal";
    case I_HUMAN:       return "Human";
    default:            return "Eggplantelligent";
    }
}

bool mons_class_is_stationary(monster_type mc)
{
    return mons_class_flag(mc, M_STATIONARY);
}

bool mons_class_is_draconic(monster_type mc)
{
    switch (mons_genus(mc))
    {
        case MONS_DRAGON:
        case MONS_DRAKE:
        case MONS_DRACONIAN:
        case MONS_WYRMHOLE:
            return true;
        default:
            return false;
    }
}

/**
 * Can killing this class of monster ever reward xp?
 *
 * This answers whether any agent could receive XP for killing a monster of
 * this class. Monsters that fail this have M_NO_EXP_GAIN set.
 * @param mc       The monster type
 * @param indirect If true this will count monsters that are parts of a parent
 *                 monster as xp rewarding even if the parts themselves don't
 *                 reward xp (e.g. tentacles).
 * @returns True if killing a monster of this class could reward xp, false
 * otherwise.
 */
bool mons_class_gives_xp(monster_type mc, bool indirect)
{
    return !mons_class_flag(mc, M_NO_EXP_GAIN)
        || (indirect && mons_is_tentacle_or_tentacle_segment(mc));
}

/**
 * Can killing this monster reward xp to the given actor?
 *
 * This answers whether the player or a monster could ever receive XP for
 * killing the monster, assuming an appropriate kill_type.
 * @param mon      The monster.
 * @param agent    The actor who would be responsible for the kill.
 * @returns True if killing the monster will reward the agent with xp, false
 * otherwise.
 */
bool mons_gives_xp(const monster& victim, const actor& agent)
{
    const bool mon_killed_friend
        = agent.is_monster() && mons_aligned(&victim, &agent);
    return !victim.is_summoned()                        // no summons
            && mons_class_gives_xp(victim.type)         // class must reward xp
            && (!testbits(victim.flags, MF_WAS_NEUTRAL) // no neutral monsters
                || victim.has_ench(ENCH_MAD))           // ...except frenzied ones
            && !testbits(victim.flags, MF_NO_REWARD)    // no reward for no_reward
            && !testbits(victim.flags, MF_TESSERACT_SPAWN)
            && !mon_killed_friend;
}

bool mons_class_is_threatening(monster_type mo)
{
    return !mons_class_flag(mo, M_NO_THREAT);
}

bool mons_is_threatening(const monster& mons)
{
    return mons_class_is_threatening(mons.type) || mons_is_active_ballisto(mons);
}

bool mons_class_is_fragile(monster_type mc)
{
    return mons_class_flag(mc, M_FRAGILE);
}

bool mons_is_fragile(const monster& mons)
{
    return mons_class_is_fragile(mons.type);
}

/**
 * Is this an active ballistomycete?
 *
 * @param mon             The monster
 * @returns True if the monster is an active ballistomycete, false otherwise.
 */
bool mons_is_active_ballisto(const monster& mon)
{
    return mon.type == MONS_BALLISTOMYCETE && mon.ballisto_activity;
}

/**
 * Is this monster class firewood?
 *
 * Firewood monsters are harmless stationary monsters than don't give xp. These
 * are worthless obstacles: not to be attacked by default, but may be cut down
 * to get to target even if coaligned.
 * @param mc The monster type
 * @returns True if the monster class is firewood, false otherwise.
 */
bool mons_class_is_firewood(monster_type mc)
{
    return mons_class_is_stationary(mc)
           && !mons_class_is_test(mc)
           && mons_class_flag(mc, M_NO_THREAT)
           && !mons_is_tentacle_or_tentacle_segment(mc);
}

/**
 * Is this a test monster? Mainly used for exempting these from various checks
 * like firewood, etc.
 */
bool mons_class_is_test(monster_type mc)
{
    return mc == MONS_TEST_SPAWNER || mc == MONS_TEST_STATUE
        || mc == MONS_TEST_BLOB;
}

// Is this type of monster generally angered by the player attacking them?
// Note: Partially duplicates logic of monster::angered_by_attacks(), but
// should match it outside of exceptions for instances of a monster.
bool mons_class_angered_by_attacks(monster_type mc)
{
    return !mons_is_avatar(mc)
           && !mons_class_is_zombified(mc)
           && !((mons_class_holiness(mc) & MH_NONLIVING)
                 && mons_class_intel(mc) == I_BRAINLESS);
}

// "body" in a purely grammatical sense.
bool mons_has_body(const monster& mon)
{
    if (mon.type == MONS_WEEPING_SKULL
        || mon.type == MONS_LAUGHING_SKULL
        || mons_species(mon.type) == MONS_CURSE_SKULL // including Murray
        || mon.type == MONS_CURSE_TOE
        || mon.type == MONS_DEATH_COB
        || mon.type == MONS_ARMOUR_ECHO
        || mons_class_is_animated_weapon(mon.type)
        || mons_is_tentacle_or_tentacle_segment(mon.type))
    {
        return false;
    }

    switch (mons_base_char(mon.type))
    {
    case 'P':
    case 'v':
    case 'G':
    case '*':
    case 'J':
        return false;
    }

    return true;
}

// Difference in speed between monster and the player for Cheibriados'
// purposes. This is the speed difference disregarding the player's
// slow status.
int cheibriados_monster_player_speed_delta(const monster& mon)
{
    // Ignore the Slow effect.
    unwind_var<int> ignore_slow(you.duration[DUR_SLOW], 0);
    const int pspeed = 1000 / (player_movement_speed() * player_speed());
    dprf("Your delay: %d, your speed: %d, mon speed: %d",
        player_movement_speed(), pspeed, mon.speed);
    return mon.speed - pspeed;
}

bool cheibriados_thinks_mons_is_fast(const monster& mon)
{
    return mons_base_speed(mon) >= 10;
}

bool mons_is_projectile(monster_type mc)
{
    return mons_class_flag(mc, M_PROJECTILE);
}

bool mons_is_projectile(const monster& mon)
{
    return mons_is_projectile(mon.type);
}

bool mons_is_seeker(monster_type mc)
{
    return mc == MONS_FOXFIRE || mc == MONS_SHOOTING_STAR;
}

bool mons_is_seeker(const monster& mon)
{
    return mon.type == MONS_FOXFIRE || mon.type == MONS_SHOOTING_STAR;
}

cloud_type seeker_trail_type(const monster& mon)
{
    if (mon.type == MONS_FOXFIRE)
        return CLOUD_FLAME;
    else
        return CLOUD_MAGIC_TRAIL;
}

bool mons_has_blood(monster_type mc)
{
    return mons_class_flag(mc, M_COLD_BLOOD)
           || mons_class_flag(mc, M_WARM_BLOOD);
}

bool mons_is_sensed(monster_type mc)
{
    return mc == MONS_SENSED
           || mc == MONS_SENSED_FRIENDLY
           || mc == MONS_SENSED_TRIVIAL
           || mc == MONS_SENSED_EASY
           || mc == MONS_SENSED_TOUGH
           || mc == MONS_SENSED_NASTY;
}

bool mons_offers_beogh_conversion(const monster& mon)
{
    return mons_genus(mon.type) == MONS_ORC
           && mon.is_priest() && mon.god == GOD_BEOGH;
}

bool mons_offers_beogh_conversion_now(const monster& mon)
{
    // Do the expensive LOS check last.
    return mons_offers_beogh_conversion(mon)
                // Only try to convert atheists...
                && you.religion == GOD_NO_GOD
                //...who aren't facing Beogh's wrath
                && !you.penance[GOD_BEOGH]
                && !you.has_mutation(MUT_FORLORN)
                && you.hp * 3 / 2 <= you.hp_max
                && !mon.is_summoned() && !mon.friendly()
                && !mon.is_silenced()
                && !mons_is_confused(mon) && mons_is_seeking(mon)
                && mon.foe == MHITYOU && !mons_is_immotile(mon)
                && you.can_see(mon);
}

// Monsters considered as "slime" for Jiyva.
bool mons_class_is_slime(monster_type mc)
{
    return mons_genus(mc) == MONS_JELLY
           || mons_genus(mc) == MONS_FLOATING_EYE
           || mons_genus(mc) == MONS_GLOWING_ORANGE_BRAIN;
}

bool mons_is_slime(const monster& mon)
{
    return mons_class_is_slime(mon.type);
}

bool herd_monster(const monster& mon)
{
    return mons_class_flag(mon.type, M_HERD);
}

// Plant or fungus or really anything with
// permanent plant holiness
bool mons_class_is_plant(monster_type mc)
{
    return bool(mons_class_holiness(mc) & MH_PLANT);
}

bool mons_is_plant(const monster& mon)
{
    return mons_class_is_plant(mon.type);
}

bool mons_eats_items(const monster& mon)
{
    return mons_is_slime(mon) && have_passive(passive_t::jelly_eating);
}

/* Is the actor susceptible to vampirism?
 *
 * Undead actors and summoned, temporary, or ghostified monsters are all not
 * susceptible.
 * @param act The actor.
 * @param only_known Only include information known to the player.
 * @returns True if the actor is susceptible to vampirism, false otherwise.
 */
bool actor_is_susceptible_to_vampirism(const actor& act, bool only_known)
{
    if (!(act.holiness() & (MH_NATURAL | MH_PLANT)))
        return false;

    if (act.is_player())
        return true;

    const monster *mon = act.as_monster();
    // Don't leak phantom mirror info.
    if (act.is_summoned() && (!only_known
                              || !mon->has_ench(ENCH_PHANTOM_MIRROR)
                              || mon->friendly()))
    {
        return false;
    }

    // Don't allow HP draining from firewood.
    return !mon->is_firewood();
}

bool invalid_monster(const monster* mon)
{
    return !mon || invalid_monster_type(mon->type);
}

bool invalid_monster_type(monster_type mt)
{
    return mt < 0 || mt >= NUM_MONSTERS
           || mon_entry[mt] == mon_entry[MONS_PROGRAM_BUG];
}

bool invalid_monster_index(int i)
{
    return i < 0 || i >= MAX_MONSTERS;
}

bool mons_is_statue(monster_type mc)
{
    return mc == MONS_ORANGE_STATUE
           || mc == MONS_OBSIDIAN_STATUE
           || mc == MONS_ICE_STATUE
           || mc == MONS_ROXANNE;
}

/**
 * The mimic [(cackles|chortles...) and ]vanishes in[ a puff of smoke]!
 *
 * @param pos       The mimic's location.
 * @param name      The mimic's name.
 */
static void _mimic_vanish(const coord_def& pos, const string& name)
{
    const bool can_place_smoke = !cloud_at(pos);
    if (can_place_smoke)
        place_cloud(CLOUD_BLACK_SMOKE, pos, 2 + random2(2), nullptr);
    if (!you.see_cell(pos))
        return;

    const char* const smoke_str = can_place_smoke ? " in a puff of smoke" : "";

    const bool can_cackle = !silenced(pos) && !silenced(you.pos());
    const string cackle = can_cackle ? getSpeakString("_laughs_") + " and " : "";

    mprf("The %s mimic %svanishes%s!",
         name.c_str(), cackle.c_str(), smoke_str);
    interrupt_activity(activity_interrupt::mimic);
}

/**
 * Clean up a "feature" that a mimic was pretending to be.
 *
 * @param pos   The location of the 'feature'.
 */
static void _destroy_mimic_feature(const coord_def &pos)
{
#if TAG_MAJOR_VERSION == 34
    const dungeon_feature_type feat = env.grid(pos);
#endif

    unnotice_feature(level_pos(level_id::current(), pos));
    env.grid(pos) = DNGN_FLOOR;
    env.level_map_mask(pos) &= ~MMT_MIMIC;
    set_terrain_changed(pos);
    remove_markers_and_listeners_at(pos);

#if TAG_MAJOR_VERSION == 34
    if (feat_is_door(feat))
        env.level_map_mask(pos) |= MMT_WAS_DOOR_MIMIC;
#endif
}

void discover_mimic(const coord_def& pos)
{
    item_def* item = item_mimic_at(pos);
    const bool feature_mimic = !item && current_feature_is_mimic_at(pos);
    // Is there really a mimic here?
    if (!item && !feature_mimic)
        return;

    const dungeon_feature_type feat = env.grid(pos);

    // If the feature has been destroyed, don't create a floor mimic.
    if (feature_mimic && !feat_is_mimicable(feat, false))
    {
        env.level_map_mask(pos) &= ~MMT_MIMIC;
        return;
    }

    const string name = feature_mimic ? "the " + string(feat_type_name(feat))
                                      : item->name(DESC_THE, false, false,
                                                             false, true);
    const bool plural = feature_mimic ? false : item->quantity > 1;

    if (you.see_cell(pos))
        mprf("%s %s a mimic!", name.c_str(), plural ? "are" : "is");

    const string shortname = feature_mimic ? feat_type_name(feat)
                                           : item->name(DESC_BASENAME);
    if (item)
        destroy_item(item->index(), true);
    else
        _destroy_mimic_feature(pos);
    _mimic_vanish(pos, shortname);

    // Just in case there's another one.
    if (mimic_at(pos))
        discover_mimic(pos);
}

void discover_shifter(monster& shifter)
{
    shifter.flags |= MF_KNOWN_SHIFTER;
}

bool mons_is_demon(monster_type mc)
{
    return mons_class_holiness(mc) & MH_DEMONIC
             && (mons_demon_tier(mc) != 0 && mc != MONS_ANTAEUS
                 || mons_species(mc) == MONS_RAKSHASA);
}

int mons_demon_tier(monster_type mc)
{
    switch (mons_base_char(mc))
    {
    case 'C':
        if (mc != MONS_ANTAEUS)
            return 0;
        // intentional fall-through for Antaeus
    case '&':
        return -1;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    default:
        return 0;
    }
}

// Beware; returns false for Tiamat!
bool mons_is_draconian(monster_type mc)
{
    return mc >= MONS_FIRST_DRACONIAN && mc <= MONS_LAST_DRACONIAN;
}

bool mons_is_base_draconian(monster_type mc)
{
    return mc >= MONS_FIRST_DRACONIAN && mc <= MONS_LAST_BASE_DRACONIAN;
}

bool mons_class_is_peripheral(monster_type mc)
{
    return mons_is_projectile(mc)
           || mons_is_avatar(mc)
           || mons_class_flag(mc, M_PERIPHERAL)
           || mons_class_is_firewood(mc);
}

size_type mons_class_body_size(monster_type mc)
{
    // Should pass base_type to get the right size for derived undead.
    // For normal monsters, base_type is set to type in the constructor.
    const monsterentry *e = get_monster_data(mc);
    return e ? e->size : SIZE_MEDIUM;
}

int max_corpse_chunks(monster_type mc)
{
    switch (mons_class_body_size(mc))
    {
    case SIZE_TINY:
        return 1;
    case SIZE_LITTLE:
        return 2;
    case SIZE_SMALL:
        return 3;
    case SIZE_MEDIUM:
        return 4;
    case SIZE_LARGE:
        return 9;
    case SIZE_GIANT:
        return 12;
    default:
        return 0;
    }
}

int derived_undead_avg_hp(monster_type mtype, int hd, int scale)
{
    static const map<monster_type, int> hp_per_hd_by_type = {
        { MONS_BOUND_SOUL,     100 },
        { MONS_ZOMBIE,          85 },
        { MONS_SPECTRAL_THING,  60 },
        { MONS_DRAUGR,          55 },
        // Simulacra aren't tough, but you can create piles of them. - bwr
        { MONS_SIMULACRUM,      30 },
    };

    const int* hp_per_hd = map_find(hp_per_hd_by_type, mtype);
    ASSERT(hp_per_hd);
    return *hp_per_hd * hd * scale / 10;
}

monster_type mons_genus(monster_type mc)
{
    if (mc == RANDOM_DRACONIAN || mc == RANDOM_BASE_DRACONIAN
        || mc == RANDOM_NONBASE_DRACONIAN
        || (mc == MONS_PLAYER_ILLUSION && species::is_draconian(you.species)))
    {
        return MONS_DRACONIAN;
    }

    if (mc == MONS_NO_MONSTER)
        return MONS_NO_MONSTER;

    ASSERT_smc();
    return smc->genus;
}

monster_type mons_species(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    return me ? me->species : MONS_PROGRAM_BUG;
}

monster_type draconian_subspecies(monster_type type, monster_type base)
{
    const monster_type species = mons_species(type);

    if (species == MONS_DRACONIAN && type != species)
        return base;

    return species;
}

monster_type draconian_subspecies(const monster& mon)
{
    ASSERT(mons_genus(mon.type) == MONS_DRACONIAN);

    if (mon.type == MONS_PLAYER_ILLUSION
        && mons_genus(mon.type) == MONS_DRACONIAN)
    {
        return species::to_mons_species(mon.ghost->species);
    }

    return draconian_subspecies(mon.type, mon.base_monster);
}

monster_type mons_detected_base(monster_type mc)
{
    return mons_genus(mc);
}

/** Does a monster of this type behold opponents like a siren?
 */
bool mons_is_siren_beholder(monster_type mc)
{
    return mc == MONS_MERFOLK_SIREN || mc == MONS_MERFOLK_AVATAR;
}

/** Does this monster behold opponents like a siren?
 *  Ignores any disabilities, checking only the monster's type.
 */
bool mons_is_siren_beholder(const monster& mons)
{
    return mons_is_siren_beholder(mons.type);
}

int get_shout_noise_level(const shout_type shout)
{
    switch (shout)
    {
    case S_SILENT:
        return 0;
    case S_HISS:
    case S_SKITTER:
    case S_FAINT_SKITTER:
    case S_VERY_SOFT:
        return 4;
    case S_SOFT:
        return 6;
    case S_LOUD:
        return 10;
    case S_LOUD_ROAR:
    case S_VERY_LOUD:
        return 12;

    default:
        return 8;
    }
}

// Only beasts and chaos spawns use S_RANDOM for noise type.
// Pandemonium lords can also get here, but this is mostly used for the
// "says" verb used for insults.
static bool _shout_fits_monster(monster_type mc, int shout)
{
    if (shout == NUM_SHOUTS || shout >= NUM_LOUDNESS || shout == S_SILENT)
        return false;

    // Chaos spawns can do anything but demon taunts, since they're
    // not coherent enough to actually say words.
    if (mc == MONS_CHAOS_SPAWN)
        return shout != S_DEMON_TAUNT;

    // For Pandemonium lords, almost everything is fair game. It's only
    // used for the shouting verb ("say", "bellow", "roar", etc.) anyway.
    if (mc != MONS_SIN_BEAST && mc != MONS_MUTANT_BEAST)
        return true;

    switch (shout)
    {
    // Bees, books, cherubs and two-headed ogres never fit.
    case S_SHOUT2:
    case S_BUZZ:
    case S_CHERUB:
    case S_RUSTLE:
    // The beast cannot speak.
    case S_DEMON_TAUNT:
        return false;
    default:
        return true;
    }
}

// If demon_shout is true, we're trying to find a random verb and
// loudness for a Pandemonium lord trying to shout.
shout_type mons_shouts(monster_type mc, bool demon_shout)
{
    ASSERT_smc();
    shout_type u = smc->shouts;

    // Pandemonium lords use this to get the noises.
    if (u == S_RANDOM || demon_shout && u == S_DEMON_TAUNT)
    {
        const int max_shout = (u == S_RANDOM ? NUM_SHOUTS : NUM_LOUDNESS);
        do
        {
            u = static_cast<shout_type>(random2(max_shout));
        }
        while (!_shout_fits_monster(mc, u));
    }

    return u;
}

/// Is the given monster type ever capable of shouting?
bool mons_can_shout(monster_type mc)
{
    // don't use mons_shouts() to avoid S_RANDOM randomization.
    ASSERT_smc();
    return smc->shouts != S_SILENT;
}

bool mons_is_ghost_demon(monster_type mc)
{
    return mons_class_flag(mc, M_GHOST_DEMON);
}

bool mons_is_pghost(monster_type mc)
{
    return mc == MONS_PLAYER_GHOST || mc == MONS_PLAYER_ILLUSION;
}

/**
 * What mutant beast tier does the given XL (base HD) correspond to?
 *
 * If the given value is between tiers, choose the higher possibility.
 *
 * @param xl    The XL (HD) of the mutant beast in question.
 * @return      The corresponding mutant beast tier (e.g. BT_MATURE).
 */
int mutant_beast_tier(int xl)
{
    for (int bt = BT_FIRST; bt < NUM_BEAST_TIERS; ++bt)
        if (xl <= beast_tiers[bt])
            return bt;
    return BT_NONE; // buggy
}

/**
 * Is the provided monster_type a draconian job type? (Not just any draconian,
 * but specifically one with a job! Or the job itself, depending how you think
 * about it.)
 *
 * @param mc    The monster type in question.
 * @return      Whether that monster type is a draconian job.
 **/
bool mons_is_draconian_job(monster_type mc)
{
    return mc >= MONS_FIRST_NONBASE_DRACONIAN
           && mc <= MONS_LAST_NONBASE_DRACONIAN;
}

bool mons_is_unique(monster_type mc)
{
    return mons_class_flag(mc, M_UNIQUE);
}

bool mons_is_or_was_unique(const monster& mon)
{
    return mons_is_unique(mon.type)
           || mon.props.exists(ORIGINAL_TYPE_KEY)
              && mons_is_unique((monster_type) mon.props[ORIGINAL_TYPE_KEY].get_int());
}

bool mons_is_the(monster_type mc)
{
    return mons_class_flag(mc, M_NAME_THE);
}

/**
 * Is the given type one of Hepliaklqana's granted ancestors?
 *
 * @param mc    The type of monster in question.
 * @return      Whether that monster is a player ancestor.
 */
bool mons_is_hepliaklqana_ancestor(monster_type mc)
{
    return mons_class_flag(mc, M_ANCESTOR);
}

/**
 * How well does this monster resist blinding?
 *
 * @param mc    The class of monster in question.
 * @return      1 if the monster resists dark/physical forms of blindness,
 *              2 if the monster additionally resists light-based blinding,
 *              0 otherwise.
 */
int mons_res_blind(monster_type mc)
{
    // Unblindable / non-visual monsters are immune to sources of blindness
    // outside of divine acts or Enfeeble.
    if (mons_class_flag(mc, M_UNBLINDABLE))
        return 2;

    const mon_holy_type holiness = mons_class_holiness(mc);

    // No visual systems to disrupt.
    if (holiness & (MH_NONLIVING | MH_PLANT))
        return 2;

    // Undead can be blinded by light.
    if (holiness & (MH_UNDEAD))
        return 1;

    return 0;
}

/**
 * Can this type of monster survive in deep water?
 *
 * @param type  The monster type in question.
 * @param base  The base type of the monster. (For e.g. draconians.)
 * @return      Whether monsters of this type can survive falling into deep
 *              water.
 *
 * XXX: Duplicates monster::res_water_drowning().
 */
bool mons_resists_drowning(monster_type type, monster_type base)
{
    const habitat_type ht = mons_habitat_type(type, base, true);
    const bool lives_in_deep_water = (ht & HT_DEEP_WATER) == HT_DEEP_WATER;
    return mons_is_unbreathing(type) || lives_in_deep_water;
}

char32_t mons_char(monster_type mc)
{
    if (Options.mon_glyph_overrides.count(mc)
        && Options.mon_glyph_overrides[mc].ch)
    {
        return Options.mon_glyph_overrides[mc].ch;
    }
    else
        return monster_symbols[mc].glyph;
}

char mons_base_char(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    return me ? me->basechar : 0;
}

mon_itemuse_type mons_class_itemuse(monster_type mc)
{
    ASSERT_smc();
    return smc->gmon_use;
}

mon_itemuse_type mons_itemuse(const monster& mon)
{
    if (mon.type == MONS_BOUND_SOUL)
        return mons_class_itemuse(mons_zombie_base(mon));

    return mons_class_itemuse(mon.type);
}

int mons_class_colour(monster_type mc)
{
    ASSERT_smc();
    // Player monster is a dummy monster used only for display purposes, so
    // it's ok to override it here.
    if (mc == MONS_PLAYER
        && Options.mon_glyph_overrides.count(MONS_PLAYER)
        && Options.mon_glyph_overrides[MONS_PLAYER].col)
    {
        return Options.mon_glyph_overrides[MONS_PLAYER].col;
    }
    else
        return monster_symbols[mc].colour;
}

bool mons_class_can_regenerate(monster_type mc)
{
    return !mons_class_flag(mc, M_NO_REGEN);
}

bool mons_can_regenerate(const monster& m)
{
    const monster& mon = get_tentacle_head(m);

    if (testbits(mon.flags, MF_NO_REGEN))
        return false;

    return mons_class_can_regenerate(mon.type);
}

bool mons_class_fast_regen(monster_type mc)
{
    return mons_class_flag(mc, M_FAST_REGEN);
}

int mons_class_regen_amount(monster_type mc)
{
    switch (mc)
    {
    case MONS_PARGHIT:              return 27;
    case MONS_DEMONIC_CRAWLER:
    case MONS_COLOSSAL_AMOEBA:
    case MONS_PROTEAN_PROGENITOR:
    case MONS_ASPIRING_FLESH:       return 6;
    case MONS_SLYMDRA:
    case MONS_MARTYRED_SHADE:       return 4;
    case MONS_BOUNDLESS_TESSERACT:  return 10;
    default:                        return 1;
    }
}

/**
 * Do monsters of the given type ever leave a hide?
 *
 * @param mc      The class of monster in question.
 * @return        Whether the monster has a chance of dropping a hide when
 *                butchered.
 */
bool mons_class_leaves_hide(monster_type mc)
{
    return hide_for_monster(mc) != NUM_ARMOURS;
}

bool mons_class_leaves_wand(monster_type mc)
{
    return mc == MONS_ELEIONOMA || mc == MONS_FENSTRIDER_WITCH;
}

bool mons_class_leaves_organ(monster_type mc)
{
    return mons_class_leaves_hide(mc) || mons_class_leaves_wand(mc);
}

int mons_zombie_size(monster_type mc)
{
    mc = mons_species(mc);
    if (!mons_class_can_be_zombified(mc))
        return Z_NOZOMBIE;

    ASSERT_smc();
    return smc->size > SIZE_MEDIUM ? Z_BIG : Z_SMALL;
}

monster_type mons_zombie_base(const monster& mon)
{
    return mon.base_monster;
}

bool mons_class_is_zombified(monster_type mc)
{
    return mc == MONS_ZOMBIE
        || mc == MONS_DRAUGR
        || mc == MONS_SIMULACRUM
        || mc == MONS_SPECTRAL_THING
        || mc == MONS_BOUND_SOUL;
}

bool mons_class_is_animated_weapon(monster_type type)
{
    return type == MONS_DANCING_WEAPON || type == MONS_SPECTRAL_WEAPON;
}

bool mons_class_is_remnant(monster_type mc)
{
    return mons_class_flag(mc, M_REMNANT);
}

bool mons_class_is_animated_object(monster_type type)
{
    return mons_class_is_animated_weapon(type)
        || type == MONS_ARMOUR_ECHO
        || type == MONS_HAUNTED_ARMOUR;
}

bool mons_is_zombified(const monster& mon)
{
    return mons_class_is_zombified(mon.type);
}

monster_type mons_base_type(const monster& mon)
{
    if (mons_class_is_zombified(mon.type))
        return mons_zombie_base(mon);
    return mon.type;
}

bool mons_class_can_leave_corpse(monster_type mc)
{
    ASSERT_smc();
    return smc->leaves_corpse;
}

bool mons_class_can_be_zombified(monster_type mzc)
{
    monster_type mc = mons_species(mzc);
    ASSERT_smc();
    return !invalid_monster_type(mc)
            && !mons_class_flag(mzc, M_NO_ZOMBIE)
            && !mons_class_flag(mzc, M_INSUBSTANTIAL)
            && !mons_is_tentacle_or_tentacle_segment(mzc)
            && (mons_class_holiness(mzc) & MH_NATURAL
                || mons_class_can_leave_corpse(mc))
            && smc->attack[0].damage; // i.e. has_attack
}

bool mons_can_be_zombified(const monster& mon)
{
    return mons_class_can_be_zombified(mon.type)
           && !mon.is_summoned()
           && !mon.has_ench(ENCH_SOUL_RIPE)
           && mons_has_attacks(mon, true);
}

bool mons_class_can_be_spectralised(monster_type mzc, bool divine)
{
    monster_type mc = mons_species(mzc);
    ASSERT_smc();
    return mons_class_holiness(mzc) & (MH_NATURAL | MH_DEMONIC | MH_HOLY)
        && mc != MONS_PANDEMONIUM_LORD
        && mzc != MONS_ORC_APOSTLE
        && (divine || smc->attack[0].type != AT_NONE); // i.e. has_attack
}

// Does this monster have a soul that can be used for necromancy (Death
// Channel, Simulacrum, Yredelemnul's Bind Soul)? For Bind Soul, allow
// monsters with no attacks if they have some spells to use.
// When called from Bind Soul's targeting interface, take into account only
// known effects.
bool mons_can_be_spectralised(const monster& mon, bool divine, bool only_known)
{
    return mons_class_can_be_spectralised(mon.type, divine)
           && (!mon.is_summoned()
               || only_known && mon.has_ench(ENCH_PHANTOM_MIRROR)
                    && mon.mons_species() != MONS_PLAYER_ILLUSION)
           && !mons_is_tentacle_or_tentacle_segment(mon.type)
           && (!testbits(mon.flags, MF_NO_REWARD)
               || mon.props.exists(KIKU_WRETCH_KEY))
           && (mons_has_attacks(mon, true)
               || divine && mon.has_spells());
}

bool mons_class_can_use_stairs(monster_type mc)
{
    return (!mons_class_is_zombified(mc) || mc == MONS_BOUND_SOUL)
           && !mons_is_tentacle_or_tentacle_segment(mc)
           && !mons_is_seeker(mc)
           && mc != MONS_SILENT_SPECTRE
           && mc != MONS_GERYON
           && mc != MONS_ROYAL_JELLY
           && mc != MONS_BALL_LIGHTNING;
}

bool mons_class_can_use_transporter(monster_type mc)
{
    return !mons_is_tentacle_or_tentacle_segment(mc);
}

bool mons_can_use_stairs(const monster& mon, dungeon_feature_type stair)
{
    if (!mons_class_can_use_stairs(mon.type))
        return false;

    // Summons can't use stairs. (And neither can animated zombies)
    if (mon.is_summoned())
        return false;

    if (mon.has_ench(ENCH_FRIENDLY_BRIBED)
        && (feat_is_branch_entrance(stair) || feat_is_branch_exit(stair)))
    {
        return false;
    }

    // Don't let the pieces of Blorkula individually follow the player between floors
    if (mon.type == MONS_VAMPIRE_BAT
        && mon.props.exists(BLORKULA_REVIVAL_TIMER_KEY))
    {
        return false;
    }

    if (mon.type == MONS_ORB_GUARDIAN && !player_on_orb_run())
        return false;

    // If this is the entrance to a portal vault (or another region of Pandemonium)
    // only friendly monsters can traverse this.
    if (!mon.friendly()
        && (feat_is_portal_entrance(stair) || stair == DNGN_TRANSIT_PANDEMONIUM
                                           || stair == DNGN_ENTER_PANDEMONIUM))
    {
        return false;
    }

    // Everything else is fine
    return true;
}

void name_zombie_from_class(monster& mon, monster_type mc, const string& mon_name)
{
    mon.mname = mon_name;

    // For the Royal Jelly: treat Royal Jelly as a replacement name to
    // avoid mentions of "Royal Jelly the spectral jelly".
    if (mc == MONS_ROYAL_JELLY)
    {
        mon.mname = "Royal Jelly";
        mon.flags |= MF_NAME_REPLACE;
    }
    // Also for the Lernaean hydra: treat Lernaean as an adjective to
    // avoid mentions of "Lernaean hydra the X-headed hydra zombie".
    else if (mc == MONS_LERNAEAN_HYDRA)
    {
        mon.mname = "Lernaean";
        mon.flags |= MF_NAME_ADJECTIVE;
    }
    // Also for the Enchantress: treat Enchantress as an adjective to
    // avoid mentions of "Enchantress the spriggan zombie".
    else if (mc == MONS_ENCHANTRESS)
    {
        mon.mname = "Enchantress";
        mon.flags |= MF_NAME_ADJECTIVE;
    }
    else if (mons_species(mc) == MONS_SERPENT_OF_HELL)
        mon.mname = "";

    if (starts_with(mon.mname, "shaped "))
        mon.flags |= MF_NAME_SUFFIX;

    // It's unlikely there's a desc for "Duvessa the elf zombie", but
    // we still want to allow it if overridden.
    if (!mon.props.exists(DBNAME_KEY))
        mon.props[DBNAME_KEY] = mons_class_name(mon.type);
}

void name_zombie_from_mon(monster& mon, const monster& orig)
{
    if (!mons_is_unique(orig.type) && orig.mname.empty())
        return;

    string name;
    monster_flags_t orig_mon_flags = orig.flags;

    if (!orig.mname.empty())
    {
        if (!(orig.flags & MF_NAME_NOCORPSE))
            name = orig.mname;
        else
            // Remove all the monster's name flags, since it lost its name.
            orig_mon_flags &= ~MF_ALL_NAMES;
    }
    else
        name = mons_type_name(orig.type, DESC_PLAIN);

    name_zombie_from_class(mon, orig.type, name);
    mon.flags |= orig_mon_flags & (MF_NAME_SUFFIX
                                     | MF_NAME_ADJECTIVE
                                     | MF_NAME_DESCRIPTOR);
}

// Derived undead deal 80% of the damage of the base form.
static int _downscale_zombie_damage(int damage)
{
    return max(1, 4 * damage / 5);
}

// Do not include AF_PLAIN, we want that to be overwritten for spectrals
// and simulacra
static const set<attack_flavour> allowed_zombie_af = {
    AF_REACH,
    AF_CRUSH,
    AF_TRAMPLE,
    AF_DRAG,
    AF_DOOM,
};

static mon_attack_def _downscale_zombie_attack(const monster& mons,
                                               mon_attack_def attk)
{
    switch (attk.type)
    {
    case AT_STING: case AT_SPORE:
    case AT_TOUCH: case AT_ENGULF:
        attk.type = AT_HIT;
        break;
    default:
        break;
    }

    attk.damage = _downscale_zombie_damage(attk.damage);
    if (allowed_zombie_af.count(attk.flavour))
        return attk;

    // overwrite all other AFs
    if (mons.type == MONS_SIMULACRUM)
        attk.flavour = AF_COLD;
    else if (mons.mons_species() == MONS_SPECTRAL_THING)
        attk.flavour = AF_DRAIN;
    else
        attk.flavour = AF_PLAIN;

    return attk;
}

/**
 * What attack does the given mutant beast facet provide?
 *
 * @param facet     The facet in question; e.g. BF_STING.
 * @param tier      The tier of the mutant beast; e.g.
 * @return          The attack corresponding to the given facet; e.g. BT_LARVAL
 *                  { AT_STING, AF_REACH_STING, 10 }. Scales with HD.
 *                  For facets that don't provide an attack, is { }.
 */
static mon_attack_def _mutant_beast_facet_attack(int facet, int tier)
{
    const int dam = tier * 5;
    switch (facet)
    {
        case BF_STING:
            return { AT_STING, AF_REACH_STING, dam };
        case BF_OX:
            return { AT_TRAMPLE, AF_TRAMPLE, dam };
        case BF_WEIRD:
            return { AT_CONSTRICT, AF_CRUSH, dam * 2 / 5};
        default:
            return { };
    }
}

/**
 * Get the attack type, attack flavour and damage for the given attack of a
 * mutant beast.
 *
 * @param mon           The monster in question.
 * @param attk_number   Which attack number to get.
 * @return              A mon_attack_def for the specified attack.
 */
static mon_attack_def _mutant_beast_attack(const monster &mon, int attk_number)
{
    const int tier = mutant_beast_tier(mon.get_experience_level());
    if (attk_number == 0)
        return { AT_HIT, AF_PLAIN, tier * 7 + 5 };

    if (!mon.props.exists(MUTANT_BEAST_FACETS))
        return { };

    int cur_attk = 1;
    for (auto facet : mon.props[MUTANT_BEAST_FACETS].get_vector())
    {
        const mon_attack_def atk = _mutant_beast_facet_attack(facet.get_int(),
                                                              tier);
        if (atk.type == AT_NONE)
            continue;

        if (cur_attk == attk_number)
            return atk;

        ++cur_attk;
    }

    return { };
}

/**
 * Get the attack type, attack flavour and damage for the given attack of an
 * ancestor granted by Hepliaklqana_ancestor_attack.
 *
 * @param mon           The monster in question.
 * @param attk_number   Which attack number to get.
 * @return              A mon_attack_def for the specified attack.
 */
static mon_attack_def _hepliaklqana_ancestor_attack(const monster &mon,
                                                     int attk_number)
{
    if (attk_number != 0)
        return { };

    const int HD = mon.get_experience_level();
    const int dam = HD + 3; // 4 at 1 HD, 21 at 18 HD (max)
    // battlemages do double base melee damage (+25-50% including their weapon)
    const int dam_mult = mon.type == MONS_ANCESTOR_BATTLEMAGE ? 2 : 1;

    return { AT_HIT, AF_PLAIN, dam * dam_mult };
}

/** Get the attack type, attack flavour and damage for a monster attack.
 *
 * @param mon The monster to look at.
 * @param attk_number Which attack number to get.
 * @param base_flavour If true, attack flavours that are randomised on every attack
 *                     will have their base flavour returned instead of one of the
 *                     random flavours.
 * @return  A mon_attack_def for the specified attack.
 */
mon_attack_def mons_attack_spec(const monster& m, int attk_number,
                                bool base_flavour)
{
    monster_type mc = m.type;

    const monster& mon = get_tentacle_head(m);

    const bool zombified = mons_is_zombified(mon);
    const int max_attacks = m.has_hydra_multi_attack()
                                ? m.heads() + (m.type == MONS_DRAUGR)
                                : MAX_NUM_ATTACKS;

    if (attk_number < 0 || attk_number >= max_attacks)
        attk_number = 0;

    if (mons_is_ghost_demon(mc))
    {
        if (attk_number == 0 && mon.ghost)
        {
            return { mon.ghost->att_type, mon.ghost->att_flav,
                     mon.ghost->damage };
        }

        return { AT_NONE, AF_PLAIN, 0 };
    }
    else if (mc == MONS_MUTANT_BEAST)
        return _mutant_beast_attack(mon, attk_number);
    else if (mons_is_hepliaklqana_ancestor(mc))
        return _hepliaklqana_ancestor_attack(mon, attk_number);

    if (zombified && mc != MONS_KRAKEN_TENTACLE)
        mc = mons_zombie_base(mon);

    ASSERT_smc();
    mon_attack_def attk = smc->attack[attk_number];

    if (m.type == MONS_DRAUGR)
    {
        if (attk_number == 0)
        {
            attk.flavour = AF_DOOM;
            attk.type    = AT_HIT;
            attk.damage  = 5 + mon.get_hit_dice() * 4 / 3;
        }
        else
            attk = smc->attack[attk_number - 1];
    }

    if (mon.has_hydra_multi_attack() && attk_number > 0)
    {
        if (attk_number > mon.heads() + (mon.type == MONS_DRAUGR))
            return { AT_NONE, AF_PLAIN, 0 };

        attk_number = 0;
        attk = smc->attack[0];
    }

    if (attk_number == 0)
    {
        if (mon.type == MONS_PLAYER_SHADOW)
        {
            if (mon.props.exists(DITH_SHADOW_ATTACK_KEY))
            {
                attk.damage = mon.props[DITH_SHADOW_ATTACK_KEY].get_int();
                if (mon.mslot_item(MSLOT_WEAPON)
                    && mon.mslot_item(MSLOT_WEAPON)->sub_type == WPN_QUICK_BLADE)
                {
                    attk.damage = attk.damage * 3 / 4;
                }
            }
        }

        // summoning miscast monster; hd scaled with miscast severity
        if (mon.type == MONS_NAMELESS)
            attk.damage = mon.get_hit_dice() * 2;

        if (mon.type == MONS_SOUL_WISP)
            attk.damage = 2 + mon.get_hit_dice();

        if (mon.type == MONS_HAUNTED_ARMOUR)
            attk.damage = 5 + (mon.get_hit_dice() * 3 / 4);

        // Boulder beetles get double attack damage and a normal 'hit' attack.
        if (mon.has_ench(ENCH_ROLLING))
        {
            attk.type = AT_HIT;
            attk.damage *= 2;
        }
    }
    // Give Coglin player shadows a second attack for their second weapon
    else if (attk_number == 1 && mon.type == MONS_PLAYER_SHADOW
             && you.has_mutation(MUT_WIELD_OFFHAND))
    {
        attk.type = AT_HIT;
        if (mon.props.exists(DITH_SHADOW_ATTACK_KEY))
        {
            attk.damage = mon.props[DITH_SHADOW_ATTACK_KEY].get_int();
            if (mon.mslot_item(MSLOT_ALT_WEAPON)
                && mon.mslot_item(MSLOT_ALT_WEAPON)->sub_type == WPN_QUICK_BLADE)
            {
                attk.damage = attk.damage * 3 / 4;
            }
        }
    }
    else if (mons_species(mon.type) == MONS_DRACONIAN
             && mon.type != MONS_DRACONIAN
             && attk.type == AT_NONE
             && smc->attack[attk_number - 1].type != AT_NONE)
    {
        // Nonbase draconians inherit aux attacks from their base type.
        // Implicit assumption: base draconian types only get one aux
        // attack, and it's in their second attack slot.
        // If that changes this code will need to be changed.
        const monsterentry* mbase =
            get_monster_data (draconian_subspecies(mon));
        ASSERT(mbase);
        return mbase->attack[1];
    }

    if (mon.type == MONS_ARMOUR_ECHO)
    {
        item_def *def = mon.get_defining_object();
        if (def)
        {
            ASSERT(def->base_type == OBJ_ARMOUR);
            const int typ = def->sub_type;
            const int ac = armour_prop(typ, PARM_AC);
            attk.damage = ac + ac * ac / 2;
        }
    }
    else if (mon.type == MONS_SHADOW_PUPPET)
    {
        if (attk_number == 2)
            attk.damage = 2 + m.get_hit_dice() * 1 / 3;
        else
            attk.damage = 2 + (m.get_hit_dice() * 3 / 2);
    }
    else if (mon.type == MONS_ERYTHROSPITE)
        attk.damage = 3 + m.get_experience_level() * 10 / 9;

    // Vampires get a bite aux in addition to normal attacks.
    if (mon.has_ench(ENCH_VAMPIRE_THRALL)
            && attk.type == AT_NONE
            && smc->attack[attk_number - 1].type != AT_NONE)
    {
        attk.type = AT_BITE;
        attk.flavour = AF_VAMPIRIC;
        attk.damage = 5 + mon.get_experience_level() * 5 / 4;
    }

    if (!base_flavour)
    {
        // TODO: randomization here is not the greatest way of doing any of
        // these...
        if (attk.type == AT_RANDOM)
        {
            attk.type = random_choose(AT_BITE, AT_STING, AT_SPORE, AT_TOUCH,
                                      AT_PECK, AT_HEADBUTT, AT_PUNCH, AT_KICK,
                                      AT_TENTACLE_SLAP, AT_TAIL_SLAP, AT_GORE,
                                      AT_TRUNK_SLAP);
        }

        if (attk.type == AT_CHERUB)
            attk.type = random_choose(AT_HEADBUTT, AT_BITE, AT_PECK, AT_GORE);
    }

    // Slime creature attacks are multiplied by the number merged.
    if (mon.type == MONS_SLIME_CREATURE && mon.blob_size > 1)
        attk.damage *= mon.blob_size;

    return zombified ? _downscale_zombie_attack(mon, attk) : attk;
}

static int _mons_damage(monster_type mc, int rt)
{
    if (rt < 0 || rt > 3)
        rt = 0;
    ASSERT_smc();
    return smc->attack[rt].damage;
}

string mon_attack_name_short(attack_type attack)
{
    switch (attack)
    {
    case AT_SPORE:         return "spore";
    case AT_TENTACLE_SLAP: return "tentacle";
    case AT_TAIL_SLAP:     return "tail";
    case AT_TRUNK_SLAP:    return "trunk";
    case AT_POUNCE:        return "pounce";
    case AT_CHERUB:
    case AT_RANDOM:        return "hit"; // eh
    default:
        return mon_attack_name(attack, false);
    }
}

/**
 * A short description of the given monster attack type.
 *
 * @param attack      The attack to be described; e.g. AT_HIT, AT_SPORE.
 * @param with_object Is the description being used with an object/target?
 *                    True results in e.g. "pounce on"; false, just "pounce".
 *                    Optional parameter, default true.
 * @return            A short description; e.g. "hit", "release spores at".
 */
string mon_attack_name(attack_type attack, bool with_object)
{
    static const char *attack_types[] =
    {
        "hit",         // including weapon attacks
        "bite",
        "sting",

        // spore
        "release spores at",

        "touch",
        "engulf",
        "claw",
        "peck",
        "headbutt",
        "punch",
        "kick",
        "tentacle-slap",
        "tail-slap",
        "gore",
        "constrict",
        "trample",
        "trunk-slap",
#if TAG_MAJOR_VERSION == 34
        "snap closed at",
        "splash",
#endif
        "pounce on",
#if TAG_MAJOR_VERSION == 34
        "sting",
#endif
        "hit, bite, peck, or gore", // AT_CHERUB
#if TAG_MAJOR_VERSION == 34
        "hit", // AT_SHOOT
#endif
        "hit", // AT_WEAP_ONLY,
        "hit or gore", // AT_RANDOM
    };
    COMPILE_CHECK(ARRAYSZ(attack_types) == NUM_ATTACK_TYPES - AT_FIRST_ATTACK);

    const int verb_index = attack - AT_FIRST_ATTACK;
    ASSERT(verb_index < (int)ARRAYSZ(attack_types));

    if (with_object)
        return attack_types[verb_index];
    else
    {
        return replace_all(replace_all(attack_types[verb_index], " at", ""),
                                                                 " on", "");
    }
}

/**
 * Does this monster attack flavour trigger even if the base attack does no
 * damage?
 *
 * @param flavour   The attack flavour in question; e.g. AF_COLD.
 * @return          Whether the flavour attack triggers on a successful hit
 *                  regardless of damage done.
 */
bool flavour_triggers_damageless(attack_flavour flavour)
{
    return flavour == AF_CRUSH
        || flavour == AF_FLOOD
        || flavour == AF_PAIN
        || flavour == AF_PURE_FIRE
        || flavour == AF_AIRSTRIKE
        || flavour == AF_SHADOWSTAB
        || flavour == AF_DROWN
        || flavour == AF_CORRODE
        || flavour == AF_DIM;
}

/**
 * How much special damage does the given attack flavour do for an attack from
 * a monster of the given hit dice?
 *
 * Various effects (e.g. acid) currently go through more complex codepaths. :(
 *
 * @param flavour       The attack flavour in question; e.g. AF_FIRE.
 * @param HD            The HD to calculate damage for.
 * @param random        Whether to roll damage, or (if false) just return
 *                      the top of the range.
 * @return              The damage that the given attack flavour does, before
 *                      resists and other effects are applied.
 */
int flavour_damage(attack_flavour flavour, int HD, bool random)
{
    switch (flavour)
    {
        case AF_FIRE:
            if (random)
                return HD + random2(HD);
            return HD * 2;
        case AF_COLD:
            if (random)
                return HD + random2(HD*2);
            return HD * 3;
        case AF_ELEC:
            if (random)
                return HD + random2(HD/2);
            return HD * 3 / 2;
        case AF_PURE_FIRE:
            if (random)
                return HD * 3 / 2 + random2(HD);
            return HD * 5 / 2;
        case AF_DROWN:
            if (random)
                return HD * 3 / 4 + random2(HD * 3 / 4);
            return HD * 3 / 2;
        // Note: This value is only used for displaying monster damage with xv
        //       and is a lie against non-player targets.
        //       Actual attacks call actor->splash_with_acid() directly.
        case AF_ACID:
        case AF_REACH_TONGUE:
            if (random)
                return roll_dice(4, 3);
            return 12;
        // Just show max damage: this number's only used for display.
        case AF_AIRSTRIKE:
            return pow(HD + 1, 1.2) * 12 / 6;
        case AF_REACH_CLEAVE_UGLY:
            return HD * 3;
        default:
            return 0;
    }
}

/**
 * Does a monster attacking with this flavour reach as if using a polearm?
 *
 * @param flavour   The attack flavour in question; e.g. AF_COLD.
 * @return          Whether the flavour grants inherent reach.
 */
bool flavour_has_reach(attack_flavour flavour)
{
    switch (flavour)
    {
        case AF_REACH:
        case AF_REACH_STING:
        case AF_REACH_TONGUE:
        case AF_RIFT:
        case AF_REACH_CLEAVE_UGLY:
            return true;
        default:
            return false;
    }
}

bool flavour_has_mobility(attack_flavour flavour)
{
    return flavour == AF_SWOOP || flavour == AF_FLANK;
}

bool mons_invuln_will(const monster& mon)
{
    return get_monster_data(mon.type)->willpower == WILL_INVULN;
}

bool mons_has_skeleton(monster_type mc)
{
    return !mons_class_flag(mc, M_NO_SKELETON);
}

/**
 * Given an average max HP value for a given monster type, what should a given
 * monster have?
 *
 * @param avg_hp    The mean hp.
 * @param scale     A scale that the input avg_hp are multiplied by.
 * @return          A max HP value; no more than +-33% from the given average,
 *                  and within about +-10% of the average 95% of the time.
 *                  This value is not multiplied by the scale - it's an actual
 *                  hp value, regardless of the scale on the input.
 *                  If avg_hp is nonzero, always returns at least 1.
 */
int hit_points(int avg_hp, int scale)
{
    if (!avg_hp)
        return 0;

    const int min_perc = 33;
    const int hp_variance = div_rand_round(avg_hp * min_perc, 100);
    const int min_hp = avg_hp - hp_variance;
    const int hp = min_hp + random2avg(hp_variance * 2, 8);
    return max(1, div_rand_round(hp, scale));
}

// This function returns the standard number of hit dice for a type of
// monster, not a particular monster's current hit dice. - bwr
int mons_class_hit_dice(monster_type mc)
{
    const monsterentry *me = get_monster_data(mc);
    return me ? me->HD : 0;
}

/**
 * What base WL does a monster of the given type have?
 *
 * @param type    The monster type in question.
 * @param base    The base type of the monster. (For e.g. draconians.)
 * @return        The WL of a normal monster of that type.
 */
int mons_class_willpower(monster_type type, monster_type base)
{
    const monster_type base_type =
        base != MONS_NO_MONSTER && mons_is_draconian(type)
            ? draconian_subspecies(type, base)
            : type;

    int type_wl = (get_monster_data(base_type))->willpower;

    if (mons_is_draconian_job(type))
        type_wl += 20;

    // Negative values get multiplied with monster hit dice.
    if (type_wl >= 0)
        return type_wl;
    return mons_class_hit_dice(base_type) * -type_wl * 4 / 3;
}

/**
 * Can a monster of the given type see invisible creatures?
 *
 * @param type    The monster type in question.
 * @param base    The base type of the monster. (For e.g. draconians.)
 * @return        Whether a normal monster of that type can see invisible
 *                things.
 */
bool mons_class_sees_invis(monster_type type, monster_type base)
{
    if (mons_class_flag(type, M_SEE_INVIS))
        return true;

    if (base != MONS_NO_MONSTER && mons_is_draconian(type)
        && mons_class_flag(draconian_subspecies(type, base), M_SEE_INVIS))
    {
        return true;
    }

    return false;
}

/**
 * What's the average hp for a given type of monster?
 *
 * @param mc        The type of monster in question.
 * @return          The average hp for that monster; rounds down.
 */
int mons_avg_hp(monster_type mc, int scale)
{
    const monsterentry* me = get_monster_data(mc);

    if (!me)
        return 0;

    return me->avg_hp_10x * scale / 10;
}

/**
 * What's the maximum hp for a given type of monster?
 *
 * @param mc        The type of monster in question.
 * @return          The maximum hp for that monster; rounds down.
 */
int mons_max_hp(monster_type mc)
{
    const monsterentry* me = get_monster_data(mc);

    if (!me)
        return 0;

    // TODO: merge the 133% with their use in hit_points()
    return me->avg_hp_10x * 133 / 1000;
}

static int _mons_exp_is_multiplier(monster_type mc)
{
    ASSERT_smc();
    return smc->exp_is_mult;
}

// Calculate xp for complicated, highly variable monsters using the supplied
// multiplier. Takes into account speed, HD, spells, and melee damage.
static int _calc_exp_with_multiplier(const monster& mon, int exp_mult)
{
    const int speed = mons_base_speed(mon);
    const int hd = mon.get_experience_level();
    const bool spellcaster = mon.has_spells();

    // scale with HD nonlinearly (gross)
    int hd_factor = hd * (25 + hd) / 25;

    int diff = 100;

    // bonus difficulty for casting "strong" spells
    if (spellcaster)
    {
        int spell_danger = 0;
        for (const mon_spell_slot &slot : mon.spells)
        {
            if (spell_difficulty(slot.spell) > 4)
                spell_danger += slot.freq;
        }

        diff += spell_danger / 2;
    }

    // speed and melee damage
    if (speed > 0)
    {
        // Only normal+ speed monsters get a bonus for having high melee
        // damage.
        if (speed >= 10)
        {
            int max_melee = 0;
            for (int i = 0; i < 4; ++i)
                max_melee += _mons_damage(mon.type, i);

            if (max_melee > 30)
                diff += (max_melee / ((speed == 10) ? 4 : 2));
        }

        diff *= speed;
        diff /= 10;
    }

    // Clamp difficulty mod to somewhat sane values (currently 50-250%).
    diff = max(min(diff, 250), 50);

    return exp_mult * hd_factor * diff / 100;
}

/**
 * How much XP will the given monster give out by dying?
 *
 * @param mon        The monster in question.
 * @param real      If false, calculate XP for the given monster's type instead of
 *               this monster's specific stats.
 * @param legacy  If set, use higher XP values for high-XP monsters to emulate
 *               historical (pre-2eadbcd) behaviour.
 * @return How much XP this monster is worth.
 */
int exp_value(const monster& mon, bool real, bool legacy)
{
    // Specially defined by vaults eg. for sprint
    if (mon.exp > 0)
        return mon.exp;

    int x_val = 0;

    // These four are the original arguments.
    const monster_type mc = mon.type;
    int maxhp             = mon.max_hit_points;

    // pghosts and pillusions have no reasonable base values, and you can look
    // up the exact value anyway. Especially for pillusions.
    if (real || mon.type == MONS_PLAYER_GHOST || mon.type == MONS_PLAYER_ILLUSION)
    {
        // Monsters with extra health are much harder, but the xp value
        // shouldn't depend on whether it was boosted at the moment of death.
        if (mon.has_ench(ENCH_BERSERK))
            maxhp = (maxhp * 2 + 1) / 3;

        if (mon.has_ench(ENCH_DOUBLED_VIGOUR))
            maxhp = maxhp / 2;
    }
    else
    {
        const monsterentry *m = get_monster_data(mons_base_type(mon));
        ASSERT(m);
        maxhp = mons_max_hp(mc);
    }

    // Hacks to make merged slime creatures not worth so much exp. We will
    // calculate the experience we would get for 1 blob, and then just
    // multiply it so that exp is linear with blobs merged. -cao
    if (mon.type == MONS_SLIME_CREATURE && mon.blob_size > 1)
        maxhp /= mon.blob_size;

    // Early out for no XP monsters.
    if (!mons_class_gives_xp(mc))
        return 0;

    // Derived undead will reference the base monster, with a divisor
    const bool zombified = mons_is_zombified(mon);

    // Start with the monster's base xp
    if (zombified)
        x_val = _mons_exp(mon.base_monster) / 4;
    else
        x_val = _mons_exp(mc);

    int avg_hp = mons_avg_hp(mc);

    // More complex calculation for special (highly variable) monsters
    if (_mons_exp_is_multiplier(mc))
        x_val = _calc_exp_with_multiplier(mon, x_val);
    // Scale weakly by the monster's actual max hp as a percentage of average
    // max hp. This randomizes exp values slightly. Derived undead and
    // special monsters skip this.
    else if (avg_hp > 0 && !zombified)
    {
        x_val = x_val * 4 + x_val * maxhp / avg_hp;
        x_val /= 5;
    }

    // Scale starcursed mass exp by what percentage of the whole it
    // represents.
    if (mon.type == MONS_STARCURSED_MASS)
        x_val = (x_val * mon.blob_size) / 12;

    // Slime creature exp hack part 2: Scale exp back up by the number of
    // blobs merged. -cao
    if (mon.type == MONS_SLIME_CREATURE && mon.blob_size > 1)
        x_val *= mon.blob_size;

    // Give real XP for all real slime creatures eaten.
    if (mon.type == MONS_SLYMDRA && mon.props.exists(SLYMDRA_SLIMES_EATEN_KEY))
        x_val += mon.props[SLYMDRA_SLIMES_EATEN_KEY].get_int() * 236;

    if (mon.has_ench(ENCH_FIGMENT))
        x_val /= 3;

    // Legacy code used for Gozag bribe and tension calculations.
    // XXX: remove this.
    if (x_val > 750 && legacy)
        x_val = 750 + (x_val - 750) * 2;

    // Guarantee the value is within limits.
    if (x_val <= 0)
        x_val = 1;

    return x_val;
}

static monster_type _random_mons_between(monster_type min, monster_type max)
{
    monster_type mc = MONS_PROGRAM_BUG;

    do // skip removed monsters
    {
        mc = static_cast<monster_type>(random_range(min, max));
    }
    while (mons_is_removed(mc));

    return mc;
}

monster_type random_draconian_monster_species()
{
    return _random_mons_between(MONS_FIRST_BASE_DRACONIAN,
                                MONS_LAST_SPAWNED_DRACONIAN);
}

monster_type random_draconian_job()
{
    return _random_mons_between(MONS_FIRST_NONBASE_DRACONIAN,
                                MONS_LAST_NONBASE_DRACONIAN);
}

static const pair<monster_type, monster_type> _draconian_combos[] =
{
    { MONS_DRACONIAN_STORMCALLER, MONS_WHITE_DRACONIAN },
    { MONS_DRACONIAN_MONK, MONS_GREEN_DRACONIAN },
    { MONS_DRACONIAN_SHIFTER, MONS_PURPLE_DRACONIAN },
    { MONS_DRACONIAN_ANNIHILATOR, MONS_YELLOW_DRACONIAN },
    { MONS_DRACONIAN_KNIGHT, MONS_BLACK_DRACONIAN },
    { MONS_DRACONIAN_SCORCHER, MONS_RED_DRACONIAN },
#if TAG_MAJOR_VERSION == 34
    { MONS_PROGRAM_BUG, MONS_PROGRAM_BUG }, // MONS_MOTTLED_DRACONIAN
#endif
};

// Should have exactly one job per randomly-spawning draconian colour.
COMPILE_CHECK(ARRAYSZ(_draconian_combos) == MONS_LAST_SPAWNED_DRACONIAN
                                            - MONS_FIRST_BASE_DRACONIAN + 1);

monster_type draconian_colour_for_job(monster_type job)
{
    for (auto &drac : _draconian_combos)
        if (drac.first == job)
            return drac.second;

    return MONS_PROGRAM_BUG;
}

monster_type draconian_job_for_colour(monster_type colour)
{
    for (auto &drac : _draconian_combos)
        if (drac.second == colour)
            return drac.first;

    // Doesn't normally spawn, but should still return a random job.
    if (colour > MONS_LAST_SPAWNED_DRACONIAN
        && colour <= MONS_LAST_BASE_DRACONIAN)
    {
        return random_draconian_job();
    }

    return MONS_PROGRAM_BUG;
}

static mon_spellbook_type _get_mc_spellbook(const monster_type mon_type)
{
    return static_cast<mon_spellbook_type>(get_monster_data(mon_type)->sec);
}

mon_spellbook_type get_spellbook(const monster_info &mon)
{
    // special case for vault monsters: if they have a custom book,
    // treat it as MST_GHOST
    if (mon.props.exists(CUSTOM_SPELLS_KEY))
        return MST_GHOST;

    return _get_mc_spellbook(mon.type);
}

// Get a list of unique spells from a monster's preset spellbooks
// or in the case of ghosts their actual spells.
// If flags is non-zero, it returns only spells that match those flags.
vector<mon_spell_slot> get_unique_spells(const monster_info &mi,
                               mon_spell_slot_flags flags)
{
    vector<mon_spell_slot> slots;
    if (!mi.has_spells())
        return slots;

    // No entry for MST_GHOST
    COMPILE_CHECK(ARRAYSZ(mspell_list) == NUM_MSTYPES - 1);

    const mon_spellbook_type book = get_spellbook(mi);

    // TODO: should we build an index to speed this reverse lookup?
    unsigned int msidx;
    for (msidx = 0; msidx < ARRAYSZ(mspell_list); ++msidx)
        if (mspell_list[msidx].type == book)
            break;

    if (mons_genus(mi.type) == MONS_DRACONIAN)
    {
        const mon_spell_slot breath =
            drac_breath(mi.draconian_subspecies());

        if (breath.spell != SPELL_NO_SPELL
            && (flags == MON_SPELL_NO_FLAGS || (breath.flags & flags)))
        {
            slots.push_back(breath);
        }
    }

    // No other spells (e.g. drac and/or wand); quit right away.
    if (book == MST_NO_SPELLS)
        return slots;

    if (book != MST_GHOST)
        ASSERT(msidx < ARRAYSZ(mspell_list));
    for (const mon_spell_slot &slot : (book == MST_GHOST
                                       ? mi.spells
                                       : mspell_list[msidx].spells))
    {
        if (flags != MON_SPELL_NO_FLAGS && !(slot.flags & flags))
            continue;

        if (none_of(slots.begin(), slots.end(),
            [&](const mon_spell_slot& oldslot)
            {
                return oldslot.spell == slot.spell;
            }))
        {
            slots.push_back(slot);
        }
    }

    return slots;
}

mon_spell_slot drac_breath(monster_type drac_type)
{
    spell_type sp;
    switch (drac_type)
    {
    case MONS_BLACK_DRACONIAN:   sp = SPELL_LIGHTNING_BOLT; break;
    case MONS_YELLOW_DRACONIAN:  sp = SPELL_SPIT_ACID; break;
    case MONS_GREEN_DRACONIAN:   sp = SPELL_POISONOUS_CLOUD; break;
    case MONS_PURPLE_DRACONIAN:  sp = SPELL_QUICKSILVER_BOLT; break;
    case MONS_RED_DRACONIAN:     sp = SPELL_SEARING_BREATH; break;
    case MONS_WHITE_DRACONIAN:   sp = SPELL_COLD_BREATH; break;
    case MONS_DRACONIAN:
    case MONS_GREY_DRACONIAN:    sp = SPELL_NO_SPELL; break;
    case MONS_PALE_DRACONIAN:    sp = SPELL_STEAM_BALL; break;

    default:
        die("Invalid draconian subrace: %d", drac_type);
    }

    mon_spell_slot slot;
    slot.spell = sp;
    slot.freq = 62;
    slot.flags = MON_SPELL_NATURAL | MON_SPELL_BREATH;
    return slot;
}

void mons_load_spells(monster& mon)
{
    const mon_spellbook_type book = _get_mc_spellbook(mon.type);

    if (book == MST_GHOST)
        return mon.load_ghost_spells();

    mon.spells.clear();
    if (mons_genus(mon.type) == MONS_DRACONIAN)
    {
        mon_spell_slot breath = drac_breath(draconian_subspecies(mon));
        if (breath.spell != SPELL_NO_SPELL)
            mon.spells.push_back(breath);
    }

    if (book == MST_NO_SPELLS)
        return;

    dprf(DIAG_MONPLACE, "%s: loading spellbook #%d",
         mon.name(DESC_PLAIN, true).c_str(), static_cast<int>(book));

    for (const mon_spellbook &spbook : mspell_list)
        if (spbook.type == book)
        {
            mon.spells.insert(mon.spells.end(),
                                spbook.spells.begin(), spbook.spells.end());
            break;
        }
}

// Never hand out DARKGREY as a monster colour, even if it is randomly
// chosen.
colour_t random_monster_colour()
{
    colour_t col = DARKGREY;
    while (col == DARKGREY)
        col = random_colour();

    return col;
}

// Generate a shiny, new and unscarred monster.
void define_monster(monster& mons, bool friendly)
{
    monster_type mcls         = mons.type;
    ASSERT(!mons_class_is_zombified(mcls)); // should have called define_zombie

    monster_type monbase      = mons.base_monster;
    const monsterentry *m     = get_monster_data(mcls);
    int col                   = mons_class_colour(mcls);
    int hd                    = mons_class_hit_dice(mcls);
    int hp = 0;

    mons.mname.clear();

    // misc
    mons.god = GOD_NO_GOD;

    switch (mcls)
    {
    case MONS_SLIME_CREATURE:
        // Slime creatures start off as only single un-merged blobs.
        mons.blob_size = 1;
        break;

    case MONS_HYDRA:
        // Hydras start off with 4 to 8 heads.
        mons.num_heads = random_range(4, 8);
        break;

    case MONS_LERNAEAN_HYDRA:
        // The Lernaean hydra starts off with 27 heads.
        mons.num_heads = 27;
        break;

    case MONS_SLYMDRA:
        mons.num_heads = random_range(3, 5);
        break;

    case MONS_TIAMAT:
        // Initialise to a random draconian type.
        draconian_change_colour(&mons);
        monbase = mons.base_monster;
        col = mons.colour;
        break;

    case MONS_STARCURSED_MASS:
        mons.blob_size = 12;
        break;

    // Randomize starting speed burst clock
    case MONS_SIXFIRHY:
    case MONS_JIANGSHI:
        mons.move_spurt = random2(360);
        break;

    case MONS_SHAMBLING_MANGROVE:
        mons.mangrove_pests = x_chance_in_y(3, 5) ? random_range(2, 3) : 0;
        break;

    default:
        break;
    }

    if (mons_is_draconian_job(mcls))
        monbase = draconian_colour_for_job(mcls);

    if (col == COLOUR_UNDEF) // but never give out darkgrey to monsters
        col = random_monster_colour();

    // Some calculations.
    if (hp == 0)
        hp = hit_points(m->avg_hp_10x);
    const int hp_max = hp;

    // So let it be written, so let it be done.
    mons.set_hit_dice(hd);
    mons.hit_points      = hp;
    mons.max_hit_points  = hp_max;
    mons.speed_increment = 70;

    if (mons.base_monster == MONS_NO_MONSTER
        || mons.base_monster == MONS_PROGRAM_BUG) // latter is zombie gen
    {
        mons.base_monster = monbase;
    }

    mons.flags      = MF_NO_FLAGS;
    mons.colour     = col;

    mons.bind_melee_flags();

    mons_load_spells(mons);

    // Reset monster enchantments.
    mons.enchantments.clear();
    mons.ench_cache.reset();
    mons.ench_countdown = 0;

    switch (mcls)
    {
    case MONS_PANDEMONIUM_LORD:
    {
        ghost_demon ghost;
        ghost.init_pandemonium_lord(friendly);
        mons.set_ghost(ghost);
        mons.ghost_demon_init();
        mons.bind_melee_flags();
        break;
    }

    case MONS_ORC_APOSTLE:
    {
        ghost_demon ghost;

        // Pull type and power from props, if they have been set
        apostle_type type = mons.props.exists(APOSTLE_TYPE_KEY)
                            ? static_cast<apostle_type>(mons.props[APOSTLE_TYPE_KEY].get_int())
                            : APOSTLE_WARRIOR;

        int pow = mons.props.exists(APOSTLE_POWER_KEY)
                    ? mons.props[APOSTLE_POWER_KEY].get_int()
                    : 50;

        ghost.init_orc_apostle(type, pow);
        mons.set_ghost(ghost);
        mons.ghost_demon_init();

        mons.props[MON_GENDER_KEY] = random_choose(GENDER_MALE,
                                                   GENDER_FEMALE,
                                                   GENDER_NEUTRAL);

        if (type == APOSTLE_WIZARD)
            mons.flags |= MF_CAUTIOUS;

        // Choose tile based on apostle class
        if (type == APOSTLE_WIZARD)
            mons.props[TILE_NUM_KEY].get_short() = 0;
        else if (type == APOSTLE_PRIEST)
            mons.props[TILE_NUM_KEY].get_short() = 100;
        else
            mons.props[TILE_NUM_KEY].get_short() = 200;

        _give_apostle_proper_name(mons, type);

        // Reroll our name until it is different from all player apostle names,
        // to try and lessen possible confusion if they end up with two that
        // have identical names.
        while (!apostle_has_unique_name(mons))
            _give_apostle_proper_name(mons, type);

        break;
    }

    case MONS_PLAYER_GHOST:
    {
        if (define_ghost_from_bones(mons))
            break;
        dprf("No ghosts found in bones, falling back on mirrored player");
        // intentional fallthrough -- fall back on mirroring the player
    }
    case MONS_PLAYER_ILLUSION:
    {
        ghost_demon ghost;
        ghost.init_player_ghost();
        if (mcls == MONS_PLAYER_GHOST)
        {
            // still don't allow undead ghosts, even mirrored
            if (you.undead_state(false) != US_ALIVE)
                ghost.species = SP_HUMAN;
            mons.props[MIRRORED_GHOST_KEY] = true;
        }
        mons.set_ghost(ghost);
        mons.ghost_init(!mons.props.exists(FAKE_MON_KEY));
        break;
    }

    case MONS_UGLY_THING:
    case MONS_VERY_UGLY_THING:
    {
        ghost_demon ghost;
        ghost.init_ugly_thing(mcls == MONS_VERY_UGLY_THING);
        mons.set_ghost(ghost);
        mons.uglything_init();
        break;
    }

    // Load with dummy values so certain monster properties can be queried
    // before placement without crashing (proper setup is done later here)
    case MONS_DANCING_WEAPON:
    case MONS_SPECTRAL_WEAPON:
    case MONS_INUGAMI:
    case MONS_PLATINUM_PARAGON:
    {
        ghost_demon ghost;
        ghost.barebones_init();
        mons.set_ghost(ghost);
        break;
    }

    case MONS_NAMELESS_REVENANT:
        initialize_nobody_memories(mons);
        break;

    default:
        break;
    }

    mons.calc_speed();

    // When all is said and done, this monster had better have some hit
    // points, or it will be dead on arrival
    ASSERT(mons.hit_points > 0);
    ASSERT(mons.max_hit_points > 0);
}

static const char *ugly_colour_names[] =
{
    "red", "brown", "green", "cyan", "purple", "white"
};

string ugly_thing_colour_name(colour_t colour)
{
    int colour_offset = ugly_thing_colour_offset(colour);

    if (colour_offset == -1)
        return "buggy";

    return ugly_colour_names[colour_offset];
}

static const colour_t ugly_colour_values[] =
{
    RED, BROWN, GREEN, CYAN, MAGENTA, LIGHTGREY
};

colour_t ugly_thing_random_colour()
{
    return RANDOM_ELEMENT(ugly_colour_values);
}

int str_to_ugly_thing_colour(const string &s)
{
    COMPILE_CHECK(ARRAYSZ(ugly_colour_values) == ARRAYSZ(ugly_colour_names));
    for (int i = 0, size = ARRAYSZ(ugly_colour_values); i < size; ++i)
        if (s == ugly_colour_names[i])
            return ugly_colour_values[i];
    return BLACK;
}

int ugly_thing_colour_offset(colour_t colour)
{
    for (unsigned i = 0; i < ARRAYSZ(ugly_colour_values); ++i)
    {
        if (make_low_colour(colour) == ugly_colour_values[i])
            return i;
    }

    return -1;
}

void ugly_thing_apply_uniform_band_colour(mgen_data &mg,
    const monster_type *band_monsters, size_t num_monsters_in_band)
{
    // Verify that the whole band is ugly.
    for (size_t i = 0; i < num_monsters_in_band; i++)
    {
        if (!(band_monsters[i] == MONS_UGLY_THING
            || band_monsters[i] == MONS_VERY_UGLY_THING))
        {
            return;
        }
    }

    // Apply a uniform colour to a fully-ugly band.
    if (ugly_thing_colour_offset(mg.colour) == -1)
        mg.colour = ugly_thing_random_colour();
}

static const char *drac_colour_names[] =
{
    "black",
#if TAG_MAJOR_VERSION == 34
    "",
#endif
    "yellow", "green", "purple", "red", "white", "grey", "pale"
};

string draconian_colour_name(monster_type mon_type)
{
    COMPILE_CHECK(ARRAYSZ(drac_colour_names) ==
                  MONS_LAST_BASE_DRACONIAN - MONS_DRACONIAN);

    if (!mons_is_base_draconian(mon_type) || mon_type == MONS_DRACONIAN)
        return "buggy";

    return drac_colour_names[mon_type - MONS_FIRST_BASE_DRACONIAN];
}

monster_type draconian_colour_by_name(const string &name)
{
    COMPILE_CHECK(ARRAYSZ(drac_colour_names)
                  == (MONS_LAST_BASE_DRACONIAN - MONS_DRACONIAN));

    for (unsigned i = 0; i < ARRAYSZ(drac_colour_names); ++i)
    {
        if (name == drac_colour_names[i])
            return static_cast<monster_type>(i + MONS_FIRST_BASE_DRACONIAN);
    }

    return MONS_PROGRAM_BUG;
}

string mons_type_name(monster_type mc, description_level_type desc)
{
    string result;

    if (!mons_is_unique(mc))
    {
        switch (desc)
        {
        case DESC_THE:       result = "the "; break;
        case DESC_A:         result = "a ";   break;
        case DESC_PLAIN: default:             break;
        }
    }
    else if (mons_is_the(mc))
        result = "the ";

    switch (mc)
    {
    case RANDOM_MONSTER:
        result += "random monster";
        return result;
    case RANDOM_DRACONIAN:
        result += "random draconian";
        return result;
    case RANDOM_BASE_DRACONIAN:
        result += "random base draconian";
        return result;
    case RANDOM_NONBASE_DRACONIAN:
        result += "random nonbase draconian";
        return result;
    case WANDERING_MONSTER:
        result += "wandering monster";
        return result;
    default: ;
    }

    const monsterentry *me = get_monster_data(mc);
    if (me == nullptr)
    {
        result += make_stringf("invalid monster_type %d", mc);
        return result;
    }

    result += me->name;

    // Vowel fix: Change 'a orc' to 'an orc'..
    if (result.length() >= 3
        && (result[0] == 'a' || result[0] == 'A')
        && result[1] == ' '
        && is_vowel(result[2])
        // XXX: Hack
        && !starts_with(&result[2], "one-"))
    {
        result.insert(1, "n");
    }

    return result;
}

static string _get_proper_monster_name(const monster& mon)
{
    const monsterentry *me = mon.find_monsterentry();
    if (!me)
        return "";

    string name = getRandMonNameString(me->name);
    if (name.empty())
        name = getRandMonNameString(get_monster_data(mons_genus(mon.type))->name);
    name = do_mon_name_replacements(name);

    return name;
}

// Names a monster (will rename it if it already had a name)
bool give_monster_proper_name(monster& mon)
{
    mon.mname = _get_proper_monster_name(mon);
    if (!mon.props.exists(DBNAME_KEY))
        mon.props[DBNAME_KEY] = mons_class_name(mon.type);

    return mon.is_named();
}

// Names an orc apostle (will rename it if it already had a name)
static bool _give_apostle_proper_name(monster& mon, apostle_type type)
{
    string apostle_key = "orc apostle " + apostle_type_names[type] + " name";
    string name = getRandMonNameString(apostle_key);
    name = do_mon_name_replacements(name);
    mon.mname = name;

    // XXX: The rest of this is duplicated from give_monster_proper_name().
    if (!mon.props.exists(DBNAME_KEY))
        mon.props[DBNAME_KEY] = mons_class_name(mon.type);

    return mon.is_named();
}

// See mons_init for initialization of mon_entry array.
monsterentry *get_monster_data(monster_type mc)
{
    if (mc >= 0 && mc < NUM_MONSTERS)
        return &mondata[mon_entry[mc]];
    else
        return nullptr;
}

static int _mons_exp(monster_type mc)
{
    ASSERT_smc();
    return smc->exp;
}

int mons_class_base_speed(monster_type mc)
{
    ASSERT_smc();
    return smc->speed;
}

mon_energy_usage mons_class_energy(monster_type mc)
{
    ASSERT_smc();
    return smc->energy_usage;
}

mon_energy_usage mons_energy(const monster& mon)
{
    mon_energy_usage meu = mons_class_energy(mons_base_type(mon));
    if (mon.ghost)
        meu.move = meu.swim = mon.ghost->move_energy;
    if (mon.has_ench(ENCH_FIRE_CHAMPION))
        meu.move = meu.move * 2 / 3;
    return meu;
}

int mons_class_zombie_base_speed(monster_type zombie_base_mc, bool slow)
{
    // Draugr and spectrals are both speed 10.
    int penalty = slow ? 2 : 0;
    return max(3, mons_class_base_speed(zombie_base_mc) - penalty);
}

/**
 * What's this monster's base speed, before temporary effects are applied?
 *
 * @param mon       The monster in question.
 * @return          The speed of the monster.
 */
int mons_base_speed(const monster& mon)
{
    if (mon.ghost)
        return mon.ghost->speed;

    if (mon.props.exists(MON_SPEED_KEY))
        return mon.props[MON_SPEED_KEY];

    if (mon.mons_species() == MONS_SPECTRAL_THING
        || mon.mons_species() == MONS_DRAUGR)
    {
        return mons_class_base_speed(mons_zombie_base(mon));
    }

    return mons_is_zombified(mon) ? mons_class_zombie_base_speed(mons_zombie_base(mon), true)
                                  : mons_class_base_speed(mon.type);
}

mon_intel_type mons_class_intel(monster_type mc)
{
    ASSERT_smc();
    return smc->intel;
}

mon_intel_type mons_intel(const monster& m)
{
    const monster& mon = get_tentacle_head(m);

    if (mon.type == MONS_BOUND_SOUL)
        return mons_class_intel(mons_zombie_base(mon));

    return mons_class_intel(mon.type);
}

// What habitats can this monster effectively occupy?
// If core_only is true (defaults to false), ignore flight and large size, and
// consider only 'native' habitat.
habitat_type mons_class_habitat(monster_type mc, bool core_only)
{
    const monsterentry *me = get_monster_data(mc);
    habitat_type ht = (me ? me->habitat : HT_LAND);
    if (!core_only)
    {
        // XXX: No class equivalent of monster::body_size(PSIZE_BODY)!
        size_type st = (me ? me->size : SIZE_GIANT);
        if (ht == HT_LAND && st >= SIZE_GIANT)
            ht = HT_AMPHIBIOUS;
        if (me && monster_class_flies(mc))
            ht = (habitat_type)(ht | HT_FLYER);
    }
    return ht;
}

habitat_type mons_habitat_type(monster_type t, monster_type base_t,
                               bool core_only)
{
    return mons_class_habitat(fixup_zombie_type(t, base_t),
                              core_only);
}

habitat_type mons_habitat(const monster& mon, bool core_only)
{
    const monster_type type = mons_is_draconian_job(mon.type)
        ? draconian_subspecies(mon) : mon.type;

    habitat_type ret = mons_habitat_type(type, mons_base_type(mon), core_only);
    // This includes item-based and temporary flight, which mons_class_habitat cannot!
    if (!core_only && mon.airborne())
        ret = (habitat_type)(ret | HT_FLYER);

    return ret;
}

int mons_power(monster_type mc)
{
    // For now, just return monster hit dice.
    ASSERT_smc();
    return mons_class_hit_dice(mc);
}

/// Are two actors 'aligned'? (Will they refuse to attack each-other?)
bool mons_aligned(const actor *m1, const actor *m2)
{
    if (!m1 || !m2)
        return true;

    if (mons_is_projectile(m1->type) || mons_is_projectile(m2->type))
        return true; // they won't directly attack each-other, anyway

    return mons_atts_aligned(m1->temp_attitude(), m2->temp_attitude());
}

bool mons_atts_aligned(mon_attitude_type fr1, mon_attitude_type fr2)
{
    if (mons_att_wont_attack(fr1) && mons_att_wont_attack(fr2))
        return true;

    return fr1 == fr2;
}

bool mons_class_wields_two_weapons(monster_type mc)
{
    return mons_class_flag(mc, M_TWO_WEAPONS);
}

bool mons_wields_two_weapons(const monster& mon)
{
    if (testbits(mon.flags, MF_TWO_WEAPONS))
        return true;

    return mons_class_wields_two_weapons(mons_base_type(mon));
}

// When this monster reaches its target, does it do impact damage
// and then cease to exist?
bool mons_destroyed_on_impact(const monster& m)
{
    return mons_is_projectile(m) || mons_is_seeker(m);
}

// When this monster reaches its target, does it explode and then
// cease to exist?
bool mons_blows_up(const monster& m)
{
    return mon_explodes_on_death(m.type) && m.type != MONS_BENNU;
}

// When this monster reaches its target, does it cease to exist?
bool mons_self_destructs(const monster& m)
{
    return mons_blows_up(m) || mons_destroyed_on_impact(m);
}

/// Does this monster trigger your attractitis? (Random.)
bool should_attract_mons(const monster &m)
{
    return x_chance_in_y(you.get_mutation_level(MUT_INITIALLY_ATTRACTIVE), 3)
            && grid_distance(you.pos(), m.pos()) > 2
            && !m.is_peripheral()
            && !m.no_tele();
}

bool mons_att_wont_attack(mon_attitude_type fr)
{
    return fr == ATT_FRIENDLY || fr == ATT_GOOD_NEUTRAL || fr == ATT_MARIONETTE;
}

mon_attitude_type mons_attitude(const monster& m)
{
    return m.temp_attitude();
}

bool mons_is_confused(const monster& m, bool class_too)
{
    return (m.has_ench(ENCH_CONFUSION) || m.has_ench(ENCH_MAD) || m.sleepwalking())
           && (class_too || !mons_class_flag(m.type, M_CONFUSED));
}

bool mons_is_wandering(const monster& m)
{
    return m.behaviour == BEH_WANDER || m.behaviour == BEH_BATTY;
}

bool mons_is_seeking(const monster& m)
{
    return m.behaviour == BEH_SEEK;
}

bool mons_is_unbreathing(monster_type mc)
{
    return bool(mons_class_holiness(mc) & (MH_UNDEAD | MH_NONLIVING
                                           | MH_PLANT));
}

// Either running in fear, or trapped and unable to do so (but still wishing to)
bool mons_is_fleeing(const monster& m)
{
    return m.behaviour == BEH_FLEE || mons_is_cornered(m);
}

// Can be either an orderly withdrawal (from which the monster can stop at will)
// or running in fear (from which they cannot)
bool mons_is_retreating(const monster& m)
{
    return m.behaviour == BEH_RETREAT || mons_is_fleeing(m);
}

bool mons_is_cornered(const monster& m)
{
    return m.behaviour == BEH_CORNERED;
}

bool mons_is_influenced_by_sanctuary(const monster& m)
{
    return !m.wont_attack() && !m.is_stationary();
}

bool mons_is_fleeing_sanctuary(const monster& m)
{
    return sanctuary_exists()
           && (m.flags & MF_FLEEING_FROM_SANCTUARY)
           && mons_is_influenced_by_sanctuary(m);
}

// Monster was just put to sleep and should not awaken for any reason until the
// next player action.
bool mons_just_slept(const monster& m)
{
    return bool(m.flags & MF_JUST_SLEPT);
}

// Monster has an enchanted sleep effect and should not awaken from noise or
// automatic stealth checks until it is over (but directly harming them will
// still do it).
bool mons_is_deep_asleep(const monster& m)
{
    return mons_just_slept(m) || m.has_ench(ENCH_DEEP_SLEEP);
}

// Moving body parts, turning oklob flowers and so on counts as motile here.
// So does preparing resurrect, struggling against a net, etc.
bool mons_is_immotile(const monster& mons)
{
    return mons.is_firewood()
        || mons.petrified()
        || mons.asleep()
        || mons.paralysed();
}

bool mons_is_batty(const monster& m)
{
    return mons_class_flag(m.type, M_BATTY) || m.has_facet(BF_BAT);
}

bool mons_is_removed(monster_type mc)
{
    return mc != MONS_PROGRAM_BUG && mons_species(mc) == MONS_PROGRAM_BUG;
}

bool mons_looks_distracted(const monster& m)
{
    return m.foe != MHITYOU && m.behaviour != BEH_BATTY && !m.friendly();
}

void mons_start_fleeing_from_sanctuary(monster& mons)
{
    mons.flags |= MF_FLEEING_FROM_SANCTUARY;
    mons.target = env.sanctuary_pos;

    // If the monster is on top of the center of the santuary, don't let it
    // freeze in place.
    if (mons.pos() == mons.target)
        mons.target += (mons.target - you.pos()).sgn();

    mons.behaviour = BEH_FLEE;
    mons.foe = MHITYOU;
}

void mons_stop_fleeing_from_sanctuary(monster& mons)
{
    const bool had_flag {mons.flags & MF_FLEEING_FROM_SANCTUARY};
    mons.flags &= (~MF_FLEEING_FROM_SANCTUARY);
    if (had_flag)
        behaviour_event(&mons, ME_EVAL, &you);
}

void mons_pacify(monster& mon, mon_attitude_type att, bool no_xp)
{
    // If the _real_ (non-charmed) attitude is already that or better,
    // don't degrade it.
    if (mon.attitude >= att)
        return;

    // Must be done before attitude change, so that proper targets are affected
    if (mon.type == MONS_FLAYED_GHOST)
        end_flayed_effect(&mon);

    // Make the monster permanently neutral.
    mon.attitude = att;
    mon.flags |= MF_WAS_NEUTRAL;

    if (!testbits(mon.flags, MF_PACIFIED) // Don't allow repeatedly pacifying.
        && !no_xp
        && !mon.is_summoned()
        && !testbits(mon.flags, MF_NO_REWARD))
    {
        // Give the player full XP.
        gain_exp(exp_value(mon));
    }
    mon.flags |= MF_PACIFIED;

    if (mon.type == MONS_GERYON)
    {
        simple_monster_message(mon,
            make_stringf(" discards %s horn.",
                         mon.pronoun(PRONOUN_POSSESSIVE).c_str()).c_str());
        monster_drop_things(&mon, false, item_is_horn_of_geryon);
    }

    // End constriction.
    mon.stop_constricting_all();
    mon.stop_being_constricted();

    // Cancel fleeing and such.
    mon.behaviour = BEH_WANDER;

    // Remove haunting, which would otherwise cause monster to continue attacking
    mon.del_ench(ENCH_HAUNTING, true, true);

    // Remove level annotation.
    mon.props[NO_ANNOTATE_KEY] = true;
    remove_unique_annotation(&mon);

    // Make the monster begin leaving the level.
    behaviour_event(&mon, ME_EVAL);

    if (mons_is_mons_class(&mon, MONS_PIKEL))
        pikel_band_neutralise();
    if (mons_is_elven_twin(&mon))
        elven_twins_pacify(&mon);
    if (mons_is_mons_class(&mon, MONS_KIRKE))
        hogs_to_humans();
    if (mon.type == MONS_VAULT_WARDEN)
        timeout_terrain_changes(0, true);

    mons_att_changed(&mon);
}

static bool _mons_should_fire_beneficial(const bolt &beam,
                                         const targeting_tracer &tracer)
{
    // Should monster heal other, haste other or might other be able to
    // target the player? Saying no for now. -cao
    if (beam.target == you.pos())
        return false;

    // Assuming all beneficial beams are enchantments if a foe is in
    // the path the beam will definitely hit them so we shouldn't fire
    // in that case.
    if (tracer.friend_info.count == 0
        || tracer.foe_info.count != 0)
    {
        return false;
    }

    return true;
}

static bool _beneficial_beam_flavour(beam_type flavour)
{
    switch (flavour)
    {
    case BEAM_HASTE:
    case BEAM_HEALING:
    case BEAM_DOUBLE_VIGOUR:
    case BEAM_INVISIBILITY:
    case BEAM_MIGHT:
    case BEAM_AGILITY:
    case BEAM_RESISTANCE:
    case BEAM_CONCENTRATE_VENOM:
        return true;

    default:
        return false;
    }
}

bool mons_should_fire(const bolt& beam, const targeting_tracer &tracer,
                      bool ignore_good_idea)
{
    dprf("tracer: foes %d (pow: %d), friends %d (pow: %d), "
         "foe_ratio: %d",
         tracer.foe_info.count, tracer.foe_info.power,
         tracer.friend_info.count, tracer.friend_info.power,
         beam.foe_ratio);

    // Use different evaluation criteria if the beam is a beneficial
    // enchantment (haste other).
    if (_beneficial_beam_flavour(beam.flavour))
        return _mons_should_fire_beneficial(beam, tracer);

    if (ignore_good_idea)
        return true;

    // After this point, safety/self-interest checks only.
    return tracer.good_to_fire(beam.foe_ratio) >= ai_action::good();
}

/**
 * Is a given spell capable of offensive action (including summoning something
 * that might be)?
 *
 * This is only used for some monster AI logic, and so even if it's a bit of an
 * approximation in some cases, it's hopefully good enough.
 *
 * @param spell         The spell in question.
 * @param needs_lof     Whether the spell is allowed to need direct line of fire
 *                      or not.
 */
bool is_offensive_spell(spell_type spell, maybe_bool needs_lof)
{
    const spell_flags flags = get_spell_flags(spell);

    // These are not offensive spells.
    if (flags & (spflag::escape | spflag::helpful | spflag::selfench))
        return false;

    // Assume that spflag::target and untagged spells both ignore line of
    // fire, while spflag::dir_or_target requires it (regardless of whether it
    // penetrates or not).

    if (needs_lof == true && !(flags & (spflag::dir_or_target)))
        return false;
    else if (needs_lof == false && (flags & (spflag::dir_or_target)))
        return false;

    return true;
}

// Returns true if the monster has an ability that can affect the target
// anywhere in LOS_DEFAULT; i.e., even through glass.
bool mons_has_los_ability(monster_type mon_type)
{
    return mons_is_siren_beholder(mon_type)
           || mon_type == MONS_STARCURSED_MASS;
}

/**
 * What gender are monsters of the given class?
 *
 * Used for pronoun selection.
 *
 * @param mc        The type of monster in question
 * @return          GENDER_NEUTER, _NEUTRAL, _FEMALE, or _MALE.
 */
gender_type mons_class_gender(monster_type mc)
{
    const bool female = mons_class_flag(mc, M_FEMALE);
    const bool male = mons_class_flag(mc, M_MALE);
    const bool neutral = mons_class_flag(mc, M_GENDER_NEUTRAL);
    ASSERT(male + female + neutral <= 1);
    return male ? GENDER_MALE :
         female ? GENDER_FEMALE :
        neutral ? GENDER_NEUTRAL :
                  GENDER_NEUTER;
}

// Use of variant (upper-/lowercase is irrelevant here):
// PRONOUN_SUBJECTIVE : _She_ is tap dancing.
// PRONOUN_POSSESSIVE : _Its_ sword explodes!
// PRONOUN_REFLEXIVE  : The wizard mumbles to _herself_.
// PRONOUN_OBJECTIVE  : You miss _him_.
const char *mons_pronoun(monster_type mon_type, pronoun_type variant,
                         bool visible)
{
    const gender_type gender = !visible ? GENDER_NEUTER
                                        : mons_class_gender(mon_type);
    return decline_pronoun(gender, variant);
}

// XXX: this is awful and should not exist
static const spell_type smitey_spells[] = {
    SPELL_SMITING,
    SPELL_BECKONING_GALE,
    SPELL_AIRSTRIKE,
    SPELL_SYMBOL_OF_TORMENT,
    SPELL_CALL_DOWN_DAMNATION,
    SPELL_CALL_DOWN_LIGHTNING,
    SPELL_FIRE_STORM,
    SPELL_SHATTER,
    SPELL_POLAR_VORTEX,          // dubious
    SPELL_GLACIATE,         // dubious
    SPELL_OZOCUBUS_REFRIGERATION,
    SPELL_MASS_CONFUSION,
    SPELL_ENTROPIC_WEAVE,
    SPELL_GRAVE_CLAW,
    SPELL_AWAKEN_FLESH,
};

/**
 * Does the given monster have spells that can damage without requiring LOF?
 *
 * Smitey (smite, airstrike), full-LOS (torment, refrigeration)...
 *
 * @param mon   The monster in question.
 * @return      Whether the given monster has 'smitey' effects.
 */
bool _mons_has_smite_attack(const monster* mons)
{
    return any_of(begin(smitey_spells), end(smitey_spells),
                  [=] (spell_type sp) { return mons->has_spell(sp); });
}

/**
 * Is the given monster smart and pushy enough to displace other
 * monsters?
 *
 * A shover should not cause damage to the shovee by
 * displacing it, so monsters that trail clouds of badness are
 * ineligible. The shover should also benefit from shoving, so monsters
 * that can smite/torment are ineligible.
 *
 * @param m     The monster in question.
 * @return      Whether that monster is ever allowed to 'push' other monsters.
 */
bool monster_shover(const monster& m)
{
    // Efreet and fire elementals are disqualified because they leave behind
    // clouds of flame. Curse toes are disqualified because they trail
    // clouds of miasma.
    if (mons_genus(m.type) == MONS_EFREET || m.type == MONS_FIRE_ELEMENTAL
        || m.type == MONS_CURSE_TOE)
    {
        return false;
    }

    // Allow the ember to push back to its scarab
    if (m.type == MONS_SOLAR_EMBER)
        return true;

    // Monsters too stupid to use stairs (e.g. non-spectral zombified undead)
    // are also disqualified.
    // However, summons *can* push past pals & cause trouble.
    // XXX: redundant with intelligence check?
    if (!mons_can_use_stairs(m) && !m.is_summoned())
        return false;

    // Geryon really profits from *not* pushing past sin beasts.
    if (m.type == MONS_GERYON)
        return false;
    // Likewise, Robin and her mob.
    if (m.type == MONS_ROBIN)
        return false;

    // no mindless creatures pushing, aside from jellies, which just kind of ooze.
    return mons_intel(m) > I_BRAINLESS || mons_genus(m.type) == MONS_JELLY;
}

/**
 * Is the first monster considered 'senior' to the second; that is, can it
 * 'push' (swap with) the latter?
 *
 * Generally, this is true if m1 and m2 are related, and m1 is higher up the
 * totem pole than m2.
 *
 * Not guaranteed to be transitive or symmetric, though it probably should be.
 *
 * @param m1        The potentially senior monster.
 * @param m2        The potentially junior monster.
 * @param fleeing   Whether the first monster is running away; relevant for
 *                  smiters pushing melee monsters out of the way.
 * @return          Whether m1 can push m2.
 */
bool monster_senior(const monster& m1, const monster& m2, bool fleeing)
{
    // A sun scarab's ember can push past anything to get back to it.
    if (m1.type == MONS_SOLAR_EMBER)
        return true;

    // Monsters can always swap with their own phalanx beetle (to keep from
    // being stuck behind it in hallways forever.)
    if (m2.type == MONS_PHALANX_BEETLE && m1.mid == m2.summoner)
        return true;

    // non-fleeing smiters won't push past anything.
    if (_mons_has_smite_attack(&m1) && !fleeing)
        return false;

    // Fannar's ice beasts can push past Fannar, who benefits from this.
    if (m1.type == MONS_ICE_BEAST && m2.type == MONS_FANNAR)
        return true;

    // Special-case spectral things to push past things that summon them
    // (revenants, ghost crabs).
    // XXX: unify this logic with Fannar's & Geryon's? (summon-buddies?)
    if (m1.type == MONS_SPECTRAL_THING
        && (m2.type == MONS_REVENANT_SOULMONGER || m2.type == MONS_GHOST_CRAB))
    {
        return true;
    }

    // Let warrior apostles push through other apostles, but (importantly)
    // NOT let wizards displace warriors to move into melee range
    if (m1.type == MONS_ORC_APOSTLE && m2.type == MONS_ORC_APOSTLE)
    {
        if (m1.props[APOSTLE_TYPE_KEY].get_int() == APOSTLE_WARRIOR)
        {
            return m2.props[APOSTLE_TYPE_KEY].get_int() != APOSTLE_WARRIOR
                   || m2.get_hit_dice() < m1.get_hit_dice();
        }
        if (m2.props[APOSTLE_TYPE_KEY].get_int() == APOSTLE_WARRIOR)
        {
            return m1.props[APOSTLE_TYPE_KEY].get_int() == APOSTLE_WARRIOR
                   && m2.get_hit_dice() < m1.get_hit_dice();
        }
    }

    // Band leaders can displace followers regardless of type considerations.
    if (m1.is_band_leader_of(m2))
        return true;
    // And prevent followers to displace the leader to avoid constant swapping.
    // -cao
    else if (m1.is_band_follower_of(m2))
        return false;

    // Monsters smart enough to use stairs can push past monsters too stupid
    // to use stairs (so that e.g. non-zombified or spectral zombified undead
    // can push past non-spectral zombified undead).
    if (mons_class_can_use_stairs(m1.type)
        && !mons_class_can_use_stairs(m2.type))
    {
        return true;
    }
    // This check assumes that demonicness is always carried at the monster type
    // level; this is because a full holiness check in such an often-called
    // function is costly.
    const bool related = mons_genus(m1.type) == mons_genus(m2.type)
                            || (   mons_class_holiness(m1.type) & MH_DEMONIC
                                && mons_class_holiness(m2.type) & MH_DEMONIC);

    // Let all related monsters (all demons are 'related') push past ones that
    // are weaker at all. Unrelated ones have to be quite a bit stronger, to
    // reduce excessive swapping and because HD correlates only weakly with
    // monster strength - but still give a small chance for slightly-higher
    // HD monsters to swap, to discourage ratscumming.
    const int hd1 = m1.get_hit_dice();
    const int hd2 = m2.get_hit_dice();
    return related && fleeing
           || related && hd1 > hd2
           || hd1 > hd2 + min(5, random2(11));
}

// XXX: This is very redundant with habitat_is_compatible and is barely used
// outside of creature merging checks, and should be refactored out.
bool mons_class_can_pass(monster_type mc, dungeon_feature_type grid)
{
    // Malign portal *only* passable by eldritch horrors
    if (grid == DNGN_MALIGN_GATEWAY)
    {
        return mc == MONS_ELDRITCH_TENTACLE
               || mc == MONS_ELDRITCH_TENTACLE_SEGMENT;
    }

    // Wall monsters can move on most solid features
    if (mons_class_habitat(mc) & HT_WALLS_ONLY)
    {
        // See the comment in habitat_is_compatible().
        if (feat_is_wall(grid) && !feat_is_permarock(grid) ||
            feat_is_statuelike(grid))
        {
            return true;
        }
    }

    return !feat_is_solid(grid);
}

static bool _mons_can_open_doors(const monster* mon)
{
    return mons_itemuse(*mon) >= MONUSE_OPEN_DOORS;
}

// Some functions that check whether a monster can open/eat/pass a
// given door. These all return false if there's no closed door there.
bool mons_can_open_door(const monster& mon, const coord_def& pos)
{
    if (!_mons_can_open_doors(&mon))
        return false;

    // Creatures allied with the player can't open doors.
    // (to prevent sabotaging the player accidentally.)
    //
    // Blood for Blood gets an exception since they filter in continuously over
    // time and otherwise get stuck behind doors in places like Vaults regularly.
    if (mon.friendly()
        && (!mons_is_blood_for_blood_orc(mon)
            || env.grid(pos) == DNGN_SEALED_DOOR ))
    {
        return false;
    }

    if (env.markers.property_at(pos, MAT_ANY, "door_restrict") == "veto")
        return false;

    return true;
}

bool mons_can_eat_door(const monster& mon, const coord_def& pos)
{
    if (env.markers.property_at(pos, MAT_ANY, "door_restrict") == "veto")
        return false;

    return mons_eats_items(mon)
           || mons_class_flag(mons_base_type(mon), M_EAT_DOORS);
}

bool mons_can_destroy_door(const monster& mon, const coord_def& pos)
{
    if (!mons_class_flag(mons_base_type(mon), M_CRASH_DOORS))
        return false;

    if (env.markers.property_at(pos, MAT_ANY, "door_restrict") == "veto")
        return false;

    return true;
}

static bool _mons_can_pass_door(const monster* mon, const coord_def& pos)
{
    return mon->can_pass_through_feat(DNGN_FLOOR)
           && (mons_can_open_door(*mon, pos)
               || mons_can_eat_door(*mon, pos)
               || mons_can_destroy_door(*mon, pos)
               || mon->can_pass_through_feat(DNGN_CLOSED_DOOR));
}

bool mons_can_traverse(const monster& mon, const coord_def& p,
                       bool only_in_sight, bool checktraps)
{
    // Friendly summons should avoid pathing out of the player's sight
    // (especially as attempting this may make them ignore valid, but longer
    // paths).
    if (only_in_sight && !you.see_cell_no_trans(p))
        return false;

    if (cell_is_runed(p))
        return false;

    // Includes sealed doors.
    if (feat_is_closed_door(env.grid(p)) && _mons_can_pass_door(&mon, p))
        return true;

    if (!mon.is_habitable(p))
        return false;

    return !checktraps || mon.is_trap_safe(p);
}

void mons_remove_from_grid(const monster& mon)
{
    const coord_def pos = mon.pos();
    if (map_bounds(pos) && env.mgrid(pos) == mon.mindex())
        env.mgrid(pos) = NON_MONSTER;
}

mon_inv_type equip_slot_to_mslot(equipment_slot eq)
{
    switch (eq)
    {
    case SLOT_WEAPON:       return MSLOT_WEAPON;
    case SLOT_BODY_ARMOUR:  return MSLOT_ARMOUR;
    case SLOT_OFFHAND:      return MSLOT_SHIELD;
    case SLOT_RING:
    case SLOT_AMULET:       return MSLOT_JEWELLERY;
    default: return NUM_MONSTER_SLOTS;
    }
}

mon_inv_type item_to_mslot(const item_def &item)
{
    switch (item.base_type)
    {
    case OBJ_WEAPONS:
    case OBJ_STAVES:
#if TAG_MAJOR_VERSION == 34
    case OBJ_RODS:
#endif
        return MSLOT_WEAPON;
    case OBJ_MISSILES:
        return MSLOT_MISSILE;
    case OBJ_ARMOUR:
        return equip_slot_to_mslot(get_armour_slot(item));
    case OBJ_JEWELLERY:
        return MSLOT_JEWELLERY;
    case OBJ_WANDS:
        return MSLOT_WAND;
    case OBJ_BOOKS:
    case OBJ_TALISMANS:
    case OBJ_MISCELLANY:
        return MSLOT_MISCELLANY;
    case OBJ_GOLD:
        return MSLOT_GOLD;
    default:
        return NUM_MONSTER_SLOTS;
    }
}

monster_type royal_jelly_ejectable_monster()
{
    return random_choose(MONS_ACID_BLOB,
                         MONS_AZURE_JELLY,
                         MONS_ROCKSLIME,
                         MONS_VOID_OOZE,
                         MONS_STAR_JELLY);
}

// Replaces @foe_god@ and @god_is@ with foe's god name.
//
// Atheists get "You"/"you", and worshippers of nameless gods get "Your
// god"/"your god".
static string _replace_god_name(god_type god, bool need_verb = false,
                                bool capital = false)
{
    string result;

    if (god == GOD_NO_GOD)
        result = capital ? "You" : "you";
    else if (god == GOD_NAMELESS)
        result = capital ? "Your god" : "your god";
    else
    {
        const string godname = god_name(god, false);
        result = capital ? uppercase_first(godname) : godname;
    }

    if (need_verb)
    {
        result += ' ';
        result += conjugate_verb("be", god == GOD_NO_GOD);
    }

    return result;
}

static bool _is_any_god(god_type god)
{
    UNUSED(god);
    return true;
}

static string _random_class_of_god_name(bool (*class_of_god)(god_type god))
{
    string result;
    god_type some_god;

    do
    {
        some_god = random_god();
    }
    while (!class_of_god(some_god));

    const string godname = god_name(some_god, false);
    result = godname;

    return result;
}

static bool _is_any_skill(skill_type skill)
{
    UNUSED(skill);
    return true;
}

static string _random_class_of_skill_name(bool (*class_of_skill)(skill_type skill))
{
    string result;
    skill_type some_skill;

    do
    {
        some_skill = random_skill();
    }
    while (!class_of_skill(some_skill));

    const string skillname = skill_name(some_skill);
    result = skillname;

    return result;
}

// part_class should be a body_part_class_flags value.
string random_body_part_name(bool plural, int part_class)
{
    vector<bool> plural_parts;
    vector<string> body_parts;

    if (part_class & BPART_INTERNAL)
    {
        plural_parts.push_back(false);
        body_parts.push_back("soul");

        plural_parts.push_back(true);
        body_parts.push_back("sinews");

        if (you.has_blood())
        {
            plural_parts.push_back(false);
            body_parts.push_back("blood");
        }

        if (you.has_bones())
        {
            plural_parts.push_back(true);
            body_parts.push_back("bones");
        }
    }

    if (part_class & BPART_EXTERNAL)
    {
        if (!you.get_mutation_level(MUT_FORMLESS))
        {
            plural_parts.push_back(false);
            body_parts.push_back("head");
        }

        string hands;
        if (you.get_mutation_level(MUT_MISSING_HAND))
        {
            hands = you.hand_name(false);
            plural_parts.push_back(false);
        }
        else
        {
            hands = you.hand_name(true);
            plural_parts.push_back(true);
        }
        body_parts.push_back(hands);

        string arms = you.arm_name(true);
        plural_parts.push_back(true);
        body_parts.push_back(arms);

        if (player_has_feet())
        {
            string feet = you.foot_name(true);
            plural_parts.push_back(true);
            body_parts.push_back(feet);
        }

        if (you.has_tail())
        {
            plural_parts.push_back(false);
            body_parts.push_back("tail");
        }

        if (player_has_ears())
        {
            plural_parts.push_back(true);
            body_parts.push_back("ears");
        }

        string eyes;
        if (you.get_mutation_level(MUT_MISSING_EYE))
        {
            plural_parts.push_back(false);
            eyes = "eye";
        }
        else
        {
            plural_parts.push_back(true);
            eyes = "eyes";
        }
        body_parts.push_back(eyes);

        plural_parts.push_back(false);
        body_parts.push_back("mouth");

        if (player_has_hair())
        {
            plural_parts.push_back(false);
            body_parts.push_back("hair");
        }

        string flesh;
        if (you.petrified())
        {
            plural_parts.push_back(false);
            flesh = "stone";
        }
        else if (!get_form()->flesh_equivalent.empty())
        {
            plural_parts.push_back(false);
            flesh = get_form()->flesh_equivalent;
        }
        else
        {
            string skin = species::skin_name(you.species);
            // Check plurality as the species::skin_name() comment suggests.
            plural_parts.push_back(ends_with(skin, "s"));
            flesh = skin;
        }
        body_parts.push_back(flesh);
    }

    int which_part;

    do
    {
        which_part = random2(body_parts.size());
    }
    while (plural_parts[which_part] != plural);

    return body_parts[which_part];
}

static string _get_species_insult(const string &species, const string &type)
{
    string insult;
    string lookup;

    // Get species genus.
    if (!species.empty())
    {
        lookup  = "insult ";
        lookup += species;
        lookup += " ";
        lookup += type;

        insult  = getSpeakString(lowercase(lookup));
    }

    if (insult.empty()) // Species too specific?
    {
        lookup  = "insult general ";
        lookup += type;

        insult  = getSpeakString(lookup);
    }

    return insult;
}

// From should be of the form "prefix @tag@". Replaces all substrings
// of the form "prefix @tag@" with to, and all strings of the form
// "prefix @tag/alt@" with either to (if nonempty) or "prefix alt".
static string _replace_speech_tag(string msg, string from, const string &to)
{
    if (from.empty())
        return msg;
    msg = replace_all(msg, from, to);

    // Change the @ to a / for the next search
    from[from.size() - 1] = '/';

    // @tag/alternative@
    size_t pos = 0;
    while ((pos = msg.find(from, pos)) != string::npos)
    {
        // beginning of tag
        const size_t at_pos = msg.find('@', pos);
        // beginning of alternative
        const size_t alt_pos = pos + from.size();
        // end of tag (one-past-the-end of alternative)
        const size_t alt_end = msg.find('@', alt_pos);

        // unclosed @tag/alt, or "from" has no @: leave it alone.
        if (alt_end == string::npos || at_pos == string::npos)
            break;

        if (to.empty())
        {
            // Replace only the @...@ part.
            msg.replace(at_pos, alt_end - at_pos + 1,
                        msg.substr(alt_pos, alt_end - alt_pos));
            pos = at_pos + (alt_end - alt_pos);
        }
        else
        {
            // Replace the whole from string, up to the second @
            msg.replace(pos, alt_end - pos + 1, to);
            pos += to.size();
        }
    }
    return msg;
}

// Replaces the "@foo@" strings in monster shout and monster speak
// definitions.
string do_mon_str_replacements(const string& in_msg, const monster& mons,
                               int s_type)
{
    string msg = in_msg;

    const actor* foe = (mons.wont_attack()
                          && invalid_monster_index(mons.foe)) ?
                             &you : mons.get_foe();

    if (s_type < 0 || s_type >= NUM_LOUDNESS || s_type == NUM_SHOUTS)
        s_type = mons_shouts(mons.type);

    msg = maybe_pick_random_substring(msg);

    // FIXME: Handle player_genus in case it was not generalised to foe_genus.
    msg = replace_all(msg, "@a_player_genus@",
                article_a(species::name(you.species, species::SPNAME_GENUS)));
    msg = replace_all(msg, "@player_genus@",
                species::name(you.species, species::SPNAME_GENUS));
    msg = replace_all(msg, "@player_genus_plural@",
                pluralise(species::name(you.species, species::SPNAME_GENUS)));

    string foe_genus;

    if (foe == nullptr)
        ;
    else if (foe->is_player())
    {
        foe_genus = species::name(you.species, species::SPNAME_GENUS);

        msg = _replace_speech_tag(msg, " @to_foe@", "");
        msg = _replace_speech_tag(msg, " @at_foe@", "");

        msg = _replace_speech_tag(msg, " @to_foe@", "");
        msg = _replace_speech_tag(msg, " @at_foe@", "");

        msg = replace_all(msg, "@player_only@", "");
        msg = replace_all(msg, " @foe,@", ",");

        msg = replace_all(msg, "@player", "@foe");
        msg = replace_all(msg, "@Player", "@Foe");

        msg = replace_all(msg, "@foe_possessive@", "your");
        msg = replace_all(msg, "@foe@", "you");
        msg = replace_all(msg, "@Foe@", "You");

        msg = replace_all(msg, "@foe_name@", you.your_name);
        msg = replace_all(msg, "@foe_species@", species::name(you.species));
        msg = replace_all(msg, "@foe_genus@", foe_genus);
        msg = replace_all(msg, "@Foe_genus@", uppercase_first(foe_genus));
        msg = replace_all(msg, "@foe_genus_plural@",
                          pluralise(foe_genus));
    }
    else
    {
        string foe_name;
        const monster* m_foe = foe->as_monster();
        if (m_foe->attitude == ATT_FRIENDLY
            && !mons_is_unique(m_foe->type)
            && !crawl_state.game_is_arena())
        {
            foe_name = foe->name(DESC_YOUR);
            const string::size_type pos = foe_name.find("'");
            if (pos != string::npos)
                foe_name = foe_name.substr(0, pos);
        }
        else
            foe_name = foe->name(DESC_THE);

        string prep = "at";
        if (s_type == S_SILENT || s_type == S_SHOUT || s_type == S_NORMAL_VOLUME)
            prep = "to";
        msg = replace_all(msg, "@says@ @to_foe@", "@says@ " + prep + " @foe@");

        msg = _replace_speech_tag(msg, " @to_foe@", " to @foe@");
        msg = _replace_speech_tag(msg, " @at_foe@", " at @foe@");

        msg = replace_all(msg, "@foe,@", "@foe@,");
        msg = replace_all(msg, "@foe_possessive@", "@foe@'s");
        msg = replace_all(msg, "@foe@", foe_name);
        msg = replace_all(msg, "@Foe@", uppercase_first(foe_name));

        if (m_foe->is_named())
            msg = replace_all(msg, "@foe_name@", foe->name(DESC_PLAIN, true));

        string species = mons_type_name(mons_species(m_foe->type), DESC_PLAIN);

        msg = replace_all(msg, "@foe_species@", species);

        foe_genus = mons_type_name(mons_genus(m_foe->type), DESC_PLAIN);

        msg = replace_all(msg, "@foe_genus@", foe_genus);
        msg = replace_all(msg, "@Foe_genus@", uppercase_first(foe_genus));
        msg = replace_all(msg, "@foe_genus_plural@", pluralise(foe_genus));
    }

    description_level_type nocap = DESC_THE, cap = DESC_THE;

    if (mons.is_named() && you.can_see(mons))
    {
        const string name = mons.name(DESC_THE);

        msg = replace_all(msg, "@the_something@", name);
        msg = replace_all(msg, "@The_something@", name);
        msg = replace_all(msg, "@the_monster@",   name);
        msg = replace_all(msg, "@The_monster@",   name);

        msg = replace_all(msg, "@the_something_possessive@",
                          apostrophise(name));
        msg = replace_all(msg, "@The_something_possessive@",
                          apostrophise(name));
        msg = replace_all(msg, "@the_monster_possessive@",
                          apostrophise(name));
        msg = replace_all(msg, "@The_monster_possessive@",
                          apostrophise(name));
    }
    else if (mons.attitude == ATT_FRIENDLY
             && !mons_is_unique(mons.type)
             && !crawl_state.game_is_arena()
             && you.can_see(mons))
    {
        nocap = DESC_PLAIN;
        cap   = DESC_PLAIN;

        msg = replace_all(msg, "@the_something@", "your @the_something@");
        msg = replace_all(msg, "@The_something@", "Your @the_something@");
        msg = replace_all(msg, "@the_monster@",   "your @the_monster@");
        msg = replace_all(msg, "@The_monster@",   "Your @the_monster@");

        msg = replace_all(msg, "@the_something_possessive@",
                          "your @the_something_possessive@");
        msg = replace_all(msg, "@The_something_possessive@",
                          "Your @the_something_possessive@");
        msg = replace_all(msg, "@the_monster_possessive@",
                          "your @the_monster_possessive@");
        msg = replace_all(msg, "@The_monster_possessive@",
                          "Your @the_monster_possessive@");
    }

    // XXX: Shouldn't be able to see 'fake' monsters
    if (you.see_cell(mons.pos()) && mons.mid != MID_NOBODY)
    {
        dungeon_feature_type feat = env.grid(mons.pos());
        if (feat_is_solid(feat) || feat >= NUM_FEATURES)
            msg = replace_all(msg, "@surface@", "buggy surface");
        else if (feat == DNGN_LAVA)
            msg = replace_all(msg, "@surface@", "lava");
        else if (feat_is_water(feat))
            msg = replace_all(msg, "@surface@", "water");
        else if (feat_is_altar(feat))
            msg = replace_all(msg, "@surface@", "altar");
        else
            msg = replace_all(msg, "@surface@", "ground");

        msg = replace_all(msg, "@feature@", raw_feature_description(mons.pos()));
    }
    else
    {
        msg = replace_all(msg, "@surface@", "buggy unseen surface");
        msg = replace_all(msg, "@feature@", "buggy unseen feature");
    }

    string something = mons.name(DESC_PLAIN);
    msg = replace_all(msg, "@something@",   something);
    msg = replace_all(msg, "@a_something@", mons.name(DESC_A));
    msg = replace_all(msg, "@the_something@", mons.name(nocap));
    msg = replace_all(msg, "@the_something_possessive@",
                      apostrophise(mons.name(nocap)));

    something[0] = toupper_safe(something[0]);
    msg = replace_all(msg, "@Something@",   something);
    msg = replace_all(msg, "@A_something@", mons.name(DESC_A));
    msg = replace_all(msg, "@The_something@", mons.name(cap));
    msg = replace_all(msg, "@The_something_possessive@",
                      apostrophise(mons.name(cap)));

    // Player name.
    msg = replace_all(msg, "@player_name@", you.your_name);
    msg = replace_all(msg, "@player_name_possessive@",
                      apostrophise(you.your_name));

    string plain = mons.name(DESC_PLAIN);
    msg = replace_all(msg, "@monster@",     plain);
    msg = replace_all(msg, "@a_monster@",   mons.name(DESC_A));
    msg = replace_all(msg, "@the_monster@", mons.name(nocap));
    msg = replace_all(msg, "@the_monster_possessive@",
                      apostrophise(mons.name(nocap)));

    plain[0] = toupper_safe(plain[0]);
    msg = replace_all(msg, "@Monster@",     plain);
    msg = replace_all(msg, "@A_monster@",   mons.name(DESC_A));
    msg = replace_all(msg, "@The_monster@", mons.name(cap));
    msg = replace_all(msg, "@The_monster_possessive@",
                      apostrophise(mons.name(cap)));

    string subj_or_poss;

    subj_or_poss = mons.pronoun(PRONOUN_SUBJECTIVE);
    msg = replace_all(msg, "@subjective@", subj_or_poss);
    subj_or_poss[0] = toupper_safe(subj_or_poss[0]);
    msg = replace_all(msg, "@Subjective@", subj_or_poss);

    subj_or_poss = mons.pronoun(PRONOUN_POSSESSIVE);
    msg = replace_all(msg, "@possessive@", subj_or_poss);
    subj_or_poss[0] = toupper_safe(subj_or_poss[0]);
    msg = replace_all(msg, "@Possessive@", subj_or_poss);

    msg = replace_all(msg, "@reflexive@",
                      mons.pronoun(PRONOUN_REFLEXIVE));
    msg = replace_all(msg, "@objective@",
                      mons.pronoun(PRONOUN_OBJECTIVE));

    // Body parts.
    bool   can_plural = false;
    string part_str   = mons.hand_name(false, &can_plural);

    msg = replace_all(msg, "@hand@", part_str);
    msg = replace_all(msg, "@Hand@", uppercase_first(part_str));

    if (!can_plural)
        part_str = "NO PLURAL HANDS";
    else
        part_str = mons.hand_name(true);

    msg = replace_all(msg, "@hands@", part_str);
    msg = replace_all(msg, "@Hands@", uppercase_first(part_str));

    can_plural = false;
    part_str   = mons.arm_name(false, &can_plural);

    msg = replace_all(msg, "@arm@", part_str);
    msg = replace_all(msg, "@Arm@", uppercase_first(part_str));

    if (!can_plural)
        part_str = "NO PLURAL ARMS";
    else
        part_str = mons.arm_name(true);

    msg = replace_all(msg, "@arms@", part_str);
    msg = replace_all(msg, "@Arms@", uppercase_first(part_str));

    can_plural = false;
    part_str   = mons.foot_name(false, &can_plural);

    msg = replace_all(msg, "@foot@", part_str);
    msg = replace_all(msg, "@Foot@", uppercase_first(part_str));

    if (!can_plural)
        part_str = "NO PLURAL FEET";
    else
        part_str = mons.foot_name(true);

    msg = replace_all(msg, "@feet@", part_str);
    msg = replace_all(msg, "@Feet@", uppercase_first(part_str));

    if (foe != nullptr)
    {
        const god_type god = foe->deity();

        // Replace with "you are" for atheists.
        msg = replace_all(msg, "@god_is@",
                          _replace_god_name(god, true, false));
        msg = replace_all(msg, "@God_is@", _replace_god_name(god, true, true));

        // No verb needed.
        msg = replace_all(msg, "@foe_god@",
                          _replace_god_name(god, false, false));
        msg = replace_all(msg, "@Foe_god@",
                          _replace_god_name(god, false, true));
    }

    // The monster's god, not the player's. Atheists get
    // "NO GOD"/"NO GOD"/"NO_GOD"/"NO_GOD", and worshippers of nameless
    // gods get "a god"/"its god/my God/My God".
    //
    // XXX: Crawl currently has no first-person possessive pronoun;
    // if it gets one, it should be used for the last two entries.
    if (mons.god == GOD_NO_GOD)
    {
        msg = replace_all(msg, "@a_God@", "NO GOD");
        msg = replace_all(msg, "@A_God@", "NO GOD");
        msg = replace_all(msg, "@possessive_God@", "NO GOD");
        msg = replace_all(msg, "@Possessive_God@", "NO GOD");

        msg = replace_all(msg, "@my_God@", "NO GOD");
        msg = replace_all(msg, "@My_God@", "NO GOD");
    }
    else if (mons.god == GOD_NAMELESS)
    {
        msg = replace_all(msg, "@a_God@", "a god");
        msg = replace_all(msg, "@A_God@", "A god");
        const string possessive = mons.pronoun(PRONOUN_POSSESSIVE) + " god";
        msg = replace_all(msg, "@possessive_God@", possessive);
        msg = replace_all(msg, "@Possessive_God@", uppercase_first(possessive));

        msg = replace_all(msg, "@my_God@", "my God");
        msg = replace_all(msg, "@My_God@", "My God");
    }
    else
    {
        const string godname = god_name(mons.god);
        const string godcap = uppercase_first(godname);
        msg = replace_all(msg, "@a_God@", godname);
        msg = replace_all(msg, "@A_God@", godcap);
        msg = replace_all(msg, "@possessive_God@", godname);
        msg = replace_all(msg, "@Possessive_God@", godcap);

        msg = replace_all(msg, "@my_God@", godname);
        msg = replace_all(msg, "@My_God@", godcap);
    }

    // For randomly generated names.
    msg = replace_all_func(msg, "@RANDGEN@", make_name_randgen);

    if (msg.find("@random_god") != string::npos)
    {
        msg = replace_all(msg, "@random_god@",
                          _random_class_of_god_name(_is_any_god));
        msg = replace_all(msg, "@random_god_chaotic@",
                          _random_class_of_god_name(is_chaotic_god));
        msg = replace_all(msg, "@random_god_evil@",
                          _random_class_of_god_name(is_evil_god));
        msg = replace_all(msg, "@random_god_good@",
                          _random_class_of_god_name(is_good_god));
    }

    if (msg.find("@random_skill") != string::npos)
    {
        msg = replace_all(msg, "@random_skill@",
                          _random_class_of_skill_name(_is_any_skill));
        msg = replace_all(msg, "@random_skill_magic@",
                          _random_class_of_skill_name(is_magic_skill));
        msg = replace_all(msg, "@random_skill_mundane@",
                          _random_class_of_skill_name(is_mundane_skill));
    }

    if (msg.find("@random_body_part") != string::npos)
    {
        msg = replace_all(msg, "@random_body_part_any_singular@",
                          random_body_part_name(false, BPART_ANY));
        msg = replace_all(msg, "@random_body_part_internal_singular@",
                          random_body_part_name(false, BPART_INTERNAL));
        msg = replace_all(msg, "@random_body_part_external_singular@",
                          random_body_part_name(false, BPART_EXTERNAL));
        msg = replace_all(msg, "@random_body_part_any_plural@",
                          random_body_part_name(true, BPART_ANY));
        msg = replace_all(msg, "@random_body_part_internal_plural@",
                          random_body_part_name(true, BPART_INTERNAL));
        msg = replace_all(msg, "@random_body_part_external_plural@",
                          random_body_part_name(true, BPART_EXTERNAL));
    }

    // Replace with species specific insults.
    if (msg.find("@species_insult_") != string::npos)
    {
        msg = replace_all(msg, "@species_insult_adj1@",
                               _get_species_insult(foe_genus, "adj1"));
        msg = replace_all(msg, "@species_insult_adj2@",
                               _get_species_insult(foe_genus, "adj2"));
        msg = replace_all(msg, "@species_insult_noun@",
                               _get_species_insult(foe_genus, "noun"));
    }

    static const char * sound_list[] =
    {
        "says",         // actually S_SILENT
        "shouts",
        "barks",
        "howls",
        "shouts",
        "roars",
        "screams",
        "bellows",
        "bleats",
        "trumpets",
        "screeches",
        "buzzes",
        "moans",
        "gurgles",
        "croaks",
        "growls",
        "hisses",
        "skitters",
        "skitters faintly",
        "sneers",       // S_DEMON_TAUNT
        "says",         // S_CHERUB -- they just speak normally.
        "squeals",
        "roars",
        "rustles",      // dubious
        "squeaks",
        "buggily says", // NUM_SHOUTS
        "breathes",     // S_VERY_SOFT
        "whispers",     // S_SOFT
        "says",         // S_NORMAL_VOLUME
        "shouts",       // S_LOUD
        "screams",      // S_VERY_LOUD
        "caws",
        "laughs",
    };
    COMPILE_CHECK(ARRAYSZ(sound_list) == NUM_LOUDNESS);

    if (s_type < 0 || s_type >= NUM_LOUDNESS || s_type == NUM_SHOUTS)
    {
        mprf(MSGCH_DIAGNOSTICS, "Invalid @says@ type.");
        msg = replace_all(msg, "@says@", "buggily says");
    }
    else
        msg = replace_all(msg, "@says@", sound_list[s_type]);

    msg = maybe_capitalise_substring(msg);

    return msg;
}

// This should take a small subset of what do_mon_str_replacements() does.
string do_mon_name_replacements(const string& in_name)
{
    string name = in_name;

    // For randomly generated names.
    name = replace_all_func(name, "@RANDGEN@", make_name_randgen);

    if (name.find("@random_god") != string::npos)
    {
        name = replace_all(name, "@random_god@",
                           _random_class_of_god_name(_is_any_god));
        name = replace_all(name, "@random_god_chaotic@",
                           _random_class_of_god_name(is_chaotic_god));
        name = replace_all(name, "@random_god_evil@",
                           _random_class_of_god_name(is_evil_god));
        name = replace_all(name, "@random_god_good@",
                           _random_class_of_god_name(is_good_god));
    }

    if (name.find("@random_skill") != string::npos)
    {
        name = replace_all(name, "@random_skill@",
                           _random_class_of_skill_name(_is_any_skill));
        name = replace_all(name, "@random_skill_magic@",
                           _random_class_of_skill_name(is_magic_skill));
        name = replace_all(name, "@random_skill_mundane@",
                           _random_class_of_skill_name(is_mundane_skill));
    }

    return name;
}

/**
 * Get the monster body shape of the given monster.
 * @param mon  The monster in question.
 * @return     The mon_body_shape type of this monster.
 */
mon_body_shape get_mon_shape(const monster& mon)
{
    monster_type base_type;
    if (mons_is_pghost(mon.type))
        base_type = species::to_mons_species(mon.ghost->species);
    else if (mons_is_zombified(mon))
        base_type = mon.base_monster;
    else
        base_type = mon.type;
    return get_mon_shape(base_type);
}

/**
 * Get the monster body shape of the given monster type.
 * @param mc  The monster type in question.
 * @return     The mon_body_shape type of this monster type.
 */
mon_body_shape get_mon_shape(const monster_type mc)
{
    if (mc == MONS_CHAOS_SPAWN)
    {
        return static_cast<mon_body_shape>(random_range(MON_SHAPE_HUMANOID,
                                                        MON_SHAPE_MISC));
    }

    ASSERT_smc();
    return smc->shape;
}

/**
 * What's the normal tile for a given monster type?
 *
 * @param mc    The monster type in question.
 * @return      The tile for that monster, or TILEP_MONS_PROGRAM_BUG for mons
 *              with variable tiles (e.g. merfolk, hydras, slime creatures).
 */
tileidx_t get_mon_base_tile(monster_type mc)
{
    ASSERT_smc();
    return smc->tile.base;
}

/**
 * How should a given monster type's tile vary?
 *
 * @param mc    The monster type in question.
 * @return      An enum describing how display of the monster should vary
 *              (by individual monster instance, or whether they're in water,
 *              etc)
 */
mon_type_tile_variation get_mon_tile_variation(monster_type mc)
{
    ASSERT_smc();
    return smc->tile.variation;
}

/**
 * What's the normal tile for corpses of a given monster type?
 *
 * @param mc    The monster type in question.
 * @return      The tile for that monster's corpse; may be varied slightly
 *              further in some special cases (ugly things, klowns).
 */
tileidx_t get_mon_base_corpse_tile(monster_type mc)
{
    ASSERT_smc();
    return smc->corpse_tile;
}


/**
 * Get a DB lookup string for the given monster body shape.
 * @param mon  The monster body shape type in question.
 * @return     A DB lookup string for the monster body shape.
 */
string get_mon_shape_str(const mon_body_shape shape)
{
    ASSERT_RANGE(shape, MON_SHAPE_HUMANOID, MON_SHAPE_MISC + 1);

    static const char *shape_names[] =
    {
        "bug", "humanoid", "winged humanoid", "tailed humanoid",
        "winged tailed humanoid", "centaur", "naga",
        "quadruped", "tailless quadruped", "winged quadruped",
        "bat", "bird", "snake", "fish",  "insect", "winged insect",
        "arachnid", "centipede", "snail", "plant", "fungus", "orb",
        "blob", "misc"
    };

    COMPILE_CHECK(ARRAYSZ(shape_names) == MON_SHAPE_MISC + 1);
    return shape_names[shape];
}

/** Is this body shape partially humanoid (i.e. does it at least have a
 *  humanoid upper body)?
 *  @param shape  The body shape in question.
 *  @returns      Whether this body shape is partially humanoid.
 */
bool mon_shape_is_humanoid(mon_body_shape shape)
{
    return shape >= MON_SHAPE_FIRST_HUMANOID
           && shape <= MON_SHAPE_LAST_HUMANOID;
}

int get_dist_to_nearest_monster()
{
    int minRange = LOS_RADIUS + 1;
    for (radius_iterator ri(you.pos(), LOS_NO_TRANS, true); ri; ++ri)
    {
        const monster* mon = monster_at(*ri);
        if (mon == nullptr)
            continue;

        if (!mon->visible_to(&you))
            continue;

        // Plants/fungi don't count.
        if ((!mons_is_threatening(*mon) || mon->wont_attack())
            && !mons_class_is_test(mon->type))
        {
            continue;
        }

        int dist = grid_distance(you.pos(), *ri);
        if (dist < minRange)
            minRange = dist;
    }
    return minRange;
}

bool monster_nearby()
{
    for (radius_iterator ri(you.pos(), LOS_DEFAULT); ri; ++ri)
        if (monster_at(*ri))
            return true;
    return false;
}

actor *actor_by_mid(mid_t m, bool require_valid)
{
    if (m == MID_PLAYER)
        return &you;
    return monster_by_mid(m, require_valid);
}

monster *monster_by_mid(mid_t m, bool require_valid)
{
    if (!require_valid)
    {
        if (m == MID_ANON_FRIEND)
            return &env.mons[ANON_FRIENDLY_MONSTER];
        if (m == MID_YOU_FAULTLESS)
            return &env.mons[YOU_FAULTLESS];
    }

    if (unsigned short *mc = map_find(env.mid_cache, m))
        return &env.mons[*mc];
    return 0;
}

monster *cached_monster_copy_by_mid(mid_t m)
{
    for (size_t i = 0; i < env.final_effect_monster_cache.size(); ++i)
    {
        if (env.final_effect_monster_cache[i].mid == m)
            return &env.final_effect_monster_cache[i];
    }

    return nullptr;
}

void init_anon()
{
    monster &mon = env.mons[ANON_FRIENDLY_MONSTER];
    mon.reset();
    mon.type = MONS_PROGRAM_BUG;
    mon.mid = MID_ANON_FRIEND;
    mon.attitude = ATT_FRIENDLY;
    mon.hit_points = mon.max_hit_points = 1000;

    monster &yf = env.mons[YOU_FAULTLESS];
    yf.reset();
    yf.type = MONS_PROGRAM_BUG;
    yf.mid = MID_YOU_FAULTLESS;
    yf.attitude = ATT_FRIENDLY; // higher than this, actually
    yf.hit_points = mon.max_hit_points = 1000;
}

actor *find_agent(mid_t m, kill_category kc)
{
    actor *agent = actor_by_mid(m);
    if (agent)
        return agent;
    switch (kc)
    {
    case KC_YOU:
        // shouldn't happen, there ought to be a valid mid
        return &you;
    case KC_FRIENDLY:
        return &env.mons[ANON_FRIENDLY_MONSTER];
    case KC_OTHER:
        // currently hostile dead/gone monsters are no different from env
        return 0;
    case KC_NCATEGORIES:
    default:
        die("invalid kill category");
    }
}

const char* mons_class_name(monster_type mc)
{
    // Usually, all invalids return "program bug", but since it has value of 0,
    // it's good to tell them apart in error messages.
    if (invalid_monster_type(mc) && mc != MONS_PROGRAM_BUG)
        return "INVALID";

    return get_monster_data(mc)->name;
}

mon_threat_level_type mons_threat_level(const monster &mon, bool real)
{
    const monster& threat = get_tentacle_head(mon);
    if (threat.props.exists(KIKU_WRETCH_KEY))
        return MTHRT_TRIVIAL; // ignores 'real', sorry...

    const double factor = sqrt(exp_needed(you.experience_level) / 30.0);
    const int tension = exp_value(threat, real, true) / (1 + factor);

    if (tension <= 1)
    {
        // Conjurators use melee to conserve mana, MDFis switch plates...
        return MTHRT_TRIVIAL;
    }
    else if (tension <= 5)
    {
        // An easy fight but not ignorable.
        return MTHRT_EASY;
    }
    else if (tension <= 32)
    {
        // Hard but reasonable.
        return MTHRT_TOUGH;
    }
    else
    {
        // Check all wands/jewels several times, wear brown pants...
        return MTHRT_NASTY;
    }
}

bool mons_foe_is_marked(const monster& mon)
{
    if (mon.foe == MHITYOU)
    {
        return (you.duration[DUR_SENTINEL_MARK]
                || testbits(mon.flags, MF_APOSTLE_BAND))
               && in_bounds(you.pos());
    }
    else
        return false;
}

void debug_mondata()
{
    string fails;

    for (monster_type mc = MONS_0; mc < NUM_MONSTERS; ++mc)
    {
        if (invalid_monster_type(mc))
            continue;
        const char* name = mons_class_name(mc);
        if (!name)
        {
            fails += make_stringf("Monster %d has no name\n", mc);
            continue;
        }

        const monsterentry *md = get_monster_data(mc);

        int WL = md->willpower;
        if (WL < 0)
            WL = md->HD * -WL * 4 / 3;
        if (md->willpower > 200 && md->willpower != WILL_INVULN)
            fails += make_stringf("%s has WL %d > 200\n", name, WL);
        if (get_resist(md->resists, MR_RES_POISON) == 2)
            fails += make_stringf("%s has rPois++\n", name);
        if (get_resist(md->resists, MR_RES_ELEC) == 2)
            fails += make_stringf("%s has rElec++\n", name);

        // Tests below apply only to real monsters.
        if (md->bitfields & M_CANT_SPAWN)
            continue;

        if (!md->HD && md->basechar != 'Z') // derived undead...
            fails += make_stringf("%s has 0 HD: %d\n", name, md->HD);
        if (md->avg_hp_10x <= 0 && md->basechar != 'Z')
            fails += make_stringf("%s has <= 0 HP: %d", name, md->avg_hp_10x);

        if (md->basechar == ' ')
            fails += make_stringf("%s has an empty glyph\n", name);

        if (md->AC < 0 && !mons_is_draconian_job(mc))
            fails += make_stringf("%s has negative AC\n", name);
        if (md->ev < 0 && !mons_is_draconian_job(mc))
            fails += make_stringf("%s has negative EV\n", name);
        if (md->exp < 0)
            fails += make_stringf("%s has negative xp\n", name);

        if (md->speed < 0)
            fails += make_stringf("%s has 0 speed\n", name);
        else if (md->speed == 0 && !mons_class_is_firewood(mc))
            fails += make_stringf("%s has 0 speed\n", name);

        const bool male = mons_class_flag(mc, M_MALE);
        const bool female = mons_class_flag(mc, M_FEMALE);
        const bool neutral = mons_class_flag(mc, M_GENDER_NEUTRAL);
        if (male + female + neutral > 1)
            fails += make_stringf("%s has too many genders\n", name);

        if (md->shape == MON_SHAPE_BUGGY)
            fails += make_stringf("%s has no defined shape\n", name);

        const bool has_corpse_tile = md->corpse_tile
                                     && md->corpse_tile != TILE_ERROR;
        if (md->species != mc)
        {
            if (has_corpse_tile)
            {
                fails +=
                    make_stringf("%s isn't a species but has a corpse tile\n",
                                 name);
            }
        }
        else if (!md->leaves_corpse)
        {
            if (has_corpse_tile)
            {
                fails += make_stringf("%s has a corpse tile & no corpse\n",
                                      name);
            }
        }
        else if (!has_corpse_tile)
            fails += make_stringf("%s has a corpse but no corpse tile\n", name);
    }

    dump_test_fails(fails, "mon-data");
}

/**
 * Iterate over mspell_list (mon-spell.h) and look for anything that seems
 * incorrect. Dump the output to a text file & print its location to the
 * console.
 */
void debug_monspells()
{
    string fails;

    // first, build a map from spellbooks to the first monster that uses them
    // (zero-initialised, where 0 == MONS_PROGRAM_BUG).
    monster_type mon_book_map[NUM_MSTYPES] = { };
    for (monster_type mc = MONS_0; mc < NUM_MONSTERS; ++mc)
    {
        if (!invalid_monster_type(mc))
        {
            mon_spellbook_type mon_book = _get_mc_spellbook(mc);
            if (mon_book < ARRAYSZ(mon_book_map) && !mon_book_map[mon_book])
                mon_book_map[mon_book] = mc;
        }
    }

    // then, check every spellbook for errors.

    for (const mon_spellbook &spbook : mspell_list)
    {
        string book_name;
        const monster_type sample_mons = mon_book_map[spbook.type];
        if (!sample_mons)
        {
            string spells;
            if (spbook.spells.empty())
                spells = "no spells";
            else
                for (const mon_spell_slot &spslot : spbook.spells)
                    if (is_valid_spell(spslot.spell))
                        spells += make_stringf(",%s", spell_title(spslot.spell));

            fails += make_stringf("Book #%d is unused (%s)\n", spbook.type,
                                  spells.c_str());
            book_name = make_stringf("#%d", spbook.type);
        }
        else
        {
            const char * const mons_name = get_monster_data(sample_mons)->name;
            book_name = mons_name;
        }

        const char * const bknm = book_name.c_str();

        if (!spbook.spells.size())
            fails += make_stringf("Empty book %s\n", bknm);

        for (const mon_spell_slot &spslot : spbook.spells)
        {
            string spell_name;
            if (!is_valid_spell(spslot.spell))
            {
                fails += make_stringf("Book %s contains invalid spell %d\n",
                                      bknm, spslot.spell);
                spell_name = to_string(spslot.spell);
            }
            else
                spell_name = spell_title(spslot.spell);

            // TODO: export this value somewhere
            const int max_freq = 200;
            if (spslot.freq > max_freq)
            {
                fails += make_stringf("Spellbook %s has spell %s at freq %d "
                                      "(greater than max freq %d)\n",
                                      bknm, spell_name.c_str(),
                                      spslot.freq, max_freq);
            }

            mon_spell_slot_flag category = MON_SPELL_NO_FLAGS;
            for (const auto flag : mon_spell_slot_flags::range())
            {
                if (!(spslot.flags & flag))
                    continue;

                if (flag >= MON_SPELL_FIRST_CATEGORY
                    && flag <= MON_SPELL_LAST_CATEGORY)
                {
                    if (category == MON_SPELL_NO_FLAGS)
                        category = flag;
                    else
                    {
                        fails += make_stringf("Spellbook %s has spell %s in "
                                              "multiple categories (%d and %d)\n",
                                              bknm, spell_name.c_str(),
                                              category, flag);
                    }
                }

                COMPILE_CHECK(MON_SPELL_NOISY > MON_SPELL_LAST_CATEGORY);
                if (flag == MON_SPELL_NOISY
                    && category && !(category & MON_SPELL_INNATE_MASK))
                {
                    fails += make_stringf("Spellbook %s has spell %s marked "
                                          "MON_SPELL_NOISY redundantly\n",
                                          bknm, spell_name.c_str());
                }
            }

            if (category == MON_SPELL_NO_FLAGS)
            {
                fails += make_stringf("Spellbook %s has spell %s with no "
                                      "category\n", bknm, spell_name.c_str());
            }
        }
    }

    dump_test_fails(fails, "mon-spell");
}

// Used when clearing level data, to ensure any additional reset quirks
// are handled properly.
void reset_all_monsters()
{
    for (auto &mons : menv_real)
    {
        // The monsters here have already been saved or discarded, so this
        // is the only place when a constricting monster can legitimately
        // be reset. Thus, clear constriction manually.
        if (!invalid_monster(&mons))
        {
            delete mons.constricting;
            mons.constricting = nullptr;
        }
        mons.reset();
    }

    env.mid_cache.clear();
}

bool mons_is_recallable(const actor* caller, const monster& targ)
{
    // For player, only recall friendly monsters
    if (caller == &you)
    {
        if (!targ.friendly())
            return false;
    }
    // Monster recall requires same attitude and at least normal intelligence
    else if (mons_intel(targ) < I_HUMAN
             || (!caller && targ.friendly())
             || (caller && !mons_aligned(&targ, caller->as_monster()))
             || targ.type == MONS_PLAYER_GHOST)
    {
        return false;
    }

    return targ.alive()
           && !mons_class_is_stationary(targ.type)
           && !targ.is_peripheral()
           && mons_class_is_threatening(targ.type);
}

bool mons_stores_tracking_data(const monster& mons)
{
    return mons.type == MONS_THORN_HUNTER
           || mons.type == MONS_MERFOLK_AVATAR
           || mons.type == MONS_BOULDER_BEETLE;
}

bool mons_is_beast(monster_type mc)
{
    if (!(mons_class_holiness(mc) & MH_NATURAL)
        || mons_class_intel(mc) != I_ANIMAL)
    {
        return false;
    }
    else if (mons_genus(mc) == MONS_UGLY_THING
             || mc == MONS_ICE_BEAST
             || mc == MONS_SKY_BEAST
             || mc == MONS_BUTTERFLY)
    {
        return false;
    }
    else
        return true;
}

bool mons_is_avatar(monster_type mc)
{
    return mons_class_flag(mc, M_AVATAR);
}

bool mons_is_wrath_avatar(const monster &mon)
{
    return mon.type == MONS_GOD_WRATH_AVATAR;
}

bool mons_is_player_shadow(const monster& mon)
{
    return mon.type == MONS_PLAYER_SHADOW
        && mon.attitude == ATT_FRIENDLY; // hostile shadows are god wrath
}

// Zero-damage attacks with special effects (constriction, drowning, pure fire,
// etc.) aren't counted by default, since this is used to decide whether the
// monster can go berserk or be weakened, both of which require an attack with
// non-zero base damage.
bool mons_has_attacks(const monster& mon, bool allow_damageless)
{
    const mon_attack_def attk = mons_attack_spec(mon, 0);
    return attk.type != AT_NONE
           && (attk.type != AT_WEAP_ONLY || mon.weapon(0))
           && (allow_damageless
               || attk.damage > 0
               || (attk.type == AT_WEAP_ONLY && mon.weapon(0)));
}

// The default suitable() function for choose_random_nearby_monster().
bool choose_any_monster(const monster& mon)
{
    return !mons_is_projectile(mon.type);
}

// Pick a random monster within line of sight of the player which matches a
// given criteria and return it.
//
// suitable() should return true for any monsters we want to be eligable.
monster* choose_random_nearby_monster(bool (*suitable)(const monster& mon))
{
    int weight = 0;
    monster* chosen = nullptr;
    for (radius_iterator ri(you.pos(), LOS_NO_TRANS); ri; ++ri)
    {
        monster* mon = monster_at(*ri);
        if (!mon || !suitable(*mon))
            continue;

        if (one_chance_in(++weight))
            chosen = mon;
    }

    return chosen;
}

// Pick a random monster on the current floor which matches a given criteria and
// return it.
//
// suitable() should return true for any monsters we want to be eligable.
monster* choose_random_monster_on_level(bool (*suitable)(const monster& mon))
{
    int weight = 0;
    monster* chosen = nullptr;
    for (monster_iterator mi; mi; ++mi)
    {
        if (!suitable(**mi))
            continue;

        if (one_chance_in(++weight))
            chosen = *mi;
    }

    return chosen;
}

int spell_freq_for_hd(int hd)
{
    return hd + 50;
}

void normalize_spell_freq(monster_spells &spells, int total_freq)
{
    // Not using std::accumulate because slot.freq is only a uint8_t.
    unsigned int total_given_freq = 0;
    for (const auto &slot : spells)
        total_given_freq += slot.freq;

    if (total_given_freq > 0)
    {
        for (auto &slot : spells)
            slot.freq = total_freq * slot.freq / total_given_freq;
    }
    else
    {
        const size_t numspells = spells.size();
        for (auto &slot : spells)
            slot.freq = total_freq / numspells;
    }
}

/// Rounded to player-visible approximations, how hurt is this monster?
mon_dam_level_type mons_get_damage_level(const monster& mons)
{
    if (mons.hit_points <= mons.max_hit_points / 5)
        return MDAM_ALMOST_DEAD;
    else if (mons.hit_points <= mons.max_hit_points * 2 / 5)
        return MDAM_SEVERELY_DAMAGED;
    else if (mons.hit_points <= mons.max_hit_points * 3 / 5)
        return MDAM_HEAVILY_DAMAGED;
    else if (mons.hit_points <= mons.max_hit_points * 4 / 5)
        return MDAM_MODERATELY_DAMAGED;
    else if (mons.hit_points < mons.max_hit_points)
        return MDAM_LIGHTLY_DAMAGED;
    else
        return MDAM_OKAY;
}

string get_damage_level_string(mon_holy_type holi, mon_dam_level_type mdam)
{
    ostringstream ss;
    switch (mdam)
    {
    case MDAM_ALMOST_DEAD:
        ss << "almost";
        ss << (wounded_damaged(holi) ? " destroyed" : " dead");
        return ss.str();
    case MDAM_SEVERELY_DAMAGED:
        ss << "severely";
        break;
    case MDAM_HEAVILY_DAMAGED:
        ss << "heavily";
        break;
    case MDAM_MODERATELY_DAMAGED:
        ss << "moderately";
        break;
    case MDAM_LIGHTLY_DAMAGED:
        ss << "lightly";
        break;
    case MDAM_OKAY:
    default:
        ss << "not";
        break;
    }
    ss << (wounded_damaged(holi) ? " damaged" : " wounded");
    return ss.str();
}

void print_wounds(const monster& mons)
{
    if (!mons.alive() || mons.hit_points == mons.max_hit_points)
        return;

    mon_dam_level_type dam_level = mons_get_damage_level(mons);
    string desc = get_damage_level_string(mons.holiness(), dam_level);

    desc.insert(0, " is ");
    desc += ".";
    simple_monster_message(mons, desc.c_str(), false, MSGCH_MONSTER_DAMAGE,
                           dam_level);
}

// (true == 'damaged') [constructs, undead, etc.]
// and (false == 'wounded') [living creatures, etc.] {dlb}
bool wounded_damaged(mon_holy_type holi)
{
    // this schema needs to be abstracted into real categories {dlb}:
    return bool(holi & (MH_UNDEAD | MH_NONLIVING | MH_PLANT));
}

// Is this monster interesting enough to make notes about?
bool mons_is_notable(const monster& mons)
{
    if (crawl_state.game_is_arena())
        return false;

    // (Ex-)Unique monsters are always interesting
    if (mons_is_or_was_unique(mons))
        return true;
    // If it's never going to attack us, then not interesting
    if (mons.friendly())
        return false;
    // tentacles aren't real monsters.
    if (mons_is_tentacle_or_tentacle_segment(mons.type))
        return false;
    // Hostile ghosts and illusions are always interesting.
    if (mons.type == MONS_PLAYER_GHOST
        || mons.type == MONS_PLAYER_ILLUSION
        || mons.type == MONS_PANDEMONIUM_LORD)
    {
        return true;
    }
    // Jellies are never interesting to Jiyva.
    if (mons.type == MONS_JELLY && have_passive(passive_t::jellies_army))
        return false;
    if (mons_threat_level(mons) == MTHRT_NASTY)
        return true;
    const auto &nm = Options.note_monsters;
    // Don't waste time on moname() if user isn't using this option
    if (!nm.empty())
    {
        const string iname = mons_type_name(mons.type, DESC_A);
        return any_of(begin(nm), end(nm), [&](const text_pattern &pat) -> bool
                                          { return pat.matches(iname); });
    }

    return false;
}

/**
 * Set up fields for mutant beasts that vary by tier & facets (that is, that
 * vary between individual beasts).
 *
 * @param mons          The beast to be initialized.
 * @param HD            The beast's HD. If 0, default to mon-data's version.
 * @param beast_facets  The beast's facets (e.g. fire, bat).
 *                      If empty, chooses two distinct facets at random.
 */
void init_mutant_beast(monster &mons, short HD, vector<int> beast_facets)
{
    if (!HD)
        HD = mons.get_experience_level();

    // MUTANT_BEAST_TIER is to make it visible for mon-info
    mons.props[MUTANT_BEAST_TIER] = HD;

    if (beast_facets.empty())
    {
        vector<int> available_facets;
        for (int f = BF_FIRST; f <= BF_LAST; ++f)
            available_facets.insert(available_facets.end(), f);

        ASSERT(available_facets.size() >= 2);

        shuffle_array(available_facets);
        beast_facets.push_back(available_facets[0]);
        beast_facets.push_back(available_facets[1]);

        ASSERT(beast_facets.size() == 2);
        ASSERT(beast_facets[0] != beast_facets[1]);
    }

    for (auto facet : beast_facets)
    {
        mons.props[MUTANT_BEAST_FACETS].get_vector().push_back(facet);

        switch (facet)
        {
            case BF_BAT:
                mons.props[MON_SPEED_KEY] = mons.speed * 2;
                mons.calc_speed();
                break;
            case BF_FIRE:
                mons.spells.emplace_back(SPELL_FIRE_BREATH, 60,
                                         MON_SPELL_NATURAL | MON_SPELL_BREATH);
                mons.props[CUSTOM_SPELLS_KEY] = true;
                break;
            case BF_SHOCK:
                mons.spells.emplace_back(SPELL_BLINKBOLT, 60,
                                         MON_SPELL_NATURAL);
                mons.props[CUSTOM_SPELLS_KEY] = true;
                break;
            default:
                break;
        }
    }
}

/**
 * If a monster needs to charge up to cast a spell (by 'casting' the spell
 * repeatedly), how many charges does it need until it can actually set the
 * spell off?
 *
 * @param m     The type of monster in question.
 * @return      The required number of charges.
 */
int max_mons_charge(monster_type m)
{
    switch (m)
    {
        case MONS_ORB_SPIDER:
            return 1;
        default:
            return 0;
    }
}

// Deal out damage to nearby pain-bonded monsters based on the distance between them.
void radiate_pain_bond(const monster& mon, int damage, const monster* original_target)
{
    for (actor_near_iterator ai(mon.pos(), LOS_NO_TRANS); ai; ++ai)
    {
        if (!ai->is_monster())
            continue;

        monster* target = ai->as_monster();

        if (&mon == target) // no self-sharing
            continue;

        // Only other pain-bonded monsters are affected.
        if (!target->has_ench(ENCH_PAIN_BOND))
            continue;

        int distance = target->pos().distance_from(mon.pos());
        if (distance > 3)
            continue;

        damage = max(0, div_rand_round(damage * (4 - distance), 5));

        if (damage > 0)
        {
            behaviour_event(target, ME_ANNOY, &you, you.pos());

            // save any potential cleanup of the original target for later
            // (in `monster::hurt`).
            if (target == original_target)
                damage = target->hurt(&you, damage, BEAM_SHARED_PAIN, KILLED_BY_MONSTER, "", "", false);
            else
                damage = target->hurt(&you, damage, BEAM_SHARED_PAIN);

            if (damage > 0)
                radiate_pain_bond(*target, damage, original_target);
        }
    }
}

// When a monster explodes violently, add some spice
void throw_monster_bits(const monster& mon)
{
    for (actor_near_iterator ai(mon.pos(), LOS_NO_TRANS); ai; ++ai)
    {
        if (!ai->is_monster())
            continue;

        monster* target = ai->as_monster();

        if (&mon == target) // can't throw chunks of something at itself.
            continue;

        int distance = target->pos().distance_from(mon.pos());
        if (!one_chance_in(distance + 4)) // generally gonna miss
            continue;

        int damage = 1 + random2(mon.get_hit_dice());

        mprf("%s is hit by a flying piece of %s!",
                target->name(DESC_THE, false).c_str(),
                mon.name(DESC_THE, false).c_str());

        // Because someone will get a kick out of this some day.
        if (mons_class_flag(mons_base_type(mon), M_ACID_SPLASH))
            target->corrode(&you, "a flying bit");

        behaviour_event(target, ME_ANNOY, &you, you.pos());
        target->hurt(&you, damage);
    }
}

/// Add an ancestor spell to the given list.
static void _add_ancestor_spell(monster_spells &spells, spell_type spell)
{
    spells.emplace_back(spell, 25, MON_SPELL_WIZARD);
}

/**
 * Set the correct spells for a given ancestor, corresponding to their HD and
 * type.
 *
 * @param ancestor      The ancestor in question.
 * @param notify        Whether to print messages if anything changes.
 */
void set_ancestor_spells(monster &ancestor, bool notify)
{
    ASSERT(mons_is_hepliaklqana_ancestor(ancestor.type));

    vector<spell_type> old_spells;
    for (auto spellslot : ancestor.spells)
        old_spells.emplace_back(spellslot.spell);

    ancestor.spells = {};
    const int HD = ancestor.get_experience_level();
    switch (ancestor.type)
    {
    case MONS_ANCESTOR_BATTLEMAGE:
        _add_ancestor_spell(ancestor.spells, HD >= 10 ?
                                             SPELL_BOLT_OF_MAGMA :
                                             SPELL_THROW_FROST);
        _add_ancestor_spell(ancestor.spells, HD >= 16 ?
                                             SPELL_LEHUDIBS_CRYSTAL_SPEAR :
                                             SPELL_STONE_ARROW);
        break;
    case MONS_ANCESTOR_HEXER:
        _add_ancestor_spell(ancestor.spells, HD >= 10 ? SPELL_PARALYSE
                                                      : SPELL_SLOW);
        _add_ancestor_spell(ancestor.spells, HD >= 13 ? SPELL_MASS_CONFUSION
                                                      : SPELL_CONFUSE);
        break;
    default:
        break;
    }

    if (HD >= 13)
        ancestor.spells.emplace_back(SPELL_HASTE, 25, MON_SPELL_WIZARD);

    if (ancestor.spells.size())
        ancestor.props[CUSTOM_SPELLS_KEY] = true;

    if (!notify)
        return;

    for (auto spellslot : ancestor.spells)
    {
        if (find(old_spells.begin(), old_spells.end(), spellslot.spell)
            == old_spells.end())
        {
            mprf("%s regains %s memory of %s.",
                 ancestor.name(DESC_YOUR, true).c_str(),
                 ancestor.pronoun(PRONOUN_POSSESSIVE, true).c_str(),
                 spell_title(spellslot.spell));
        }
    }
}

static bool _apply_to_monsters(monster_func f, radius_iterator&& ri)
{
    bool affected_any = false;
    for (; ri; ri++)
    {
        monster* mons = monster_at(*ri);
        if (!invalid_monster(mons))
            affected_any = f(*mons) || affected_any;
    }

    return affected_any;
}

bool apply_monsters_around_square(monster_func f, const coord_def& where,
                                  int radius)
{
    return _apply_to_monsters(f, radius_iterator(where, radius, C_SQUARE,
                                                 LOS_NO_TRANS, true));
}

bool apply_visible_monsters(monster_func f, const coord_def& where, los_type los)
{
    return _apply_to_monsters(f, radius_iterator(where, los, true));
}

int touch_of_beogh_hp_mult(const monster& mon)
{
    const int pow = mon.props.exists(APOSTLE_POWER_KEY)
                    ? mon.props[APOSTLE_POWER_KEY].get_int() : 0;

    return 100 + (min(50, pow * 2 / 3));
}

/**
 * Should all projectiles and beams originating from a particular agent pass
 * through a given actor harmless, regardless of whether they are ordinarily
 * penetrating?
 *
 *  @param agent       The source of the projectile.
 *                     Maybe be nullptr, the projectile has a non-actor source.
 *  @param target      The target in question
 *  @param announce    If true, prints a message stating how the target
 *                     avoided being hit.
 *  @return     Whether the given agent can shoot through this actor.
 */
bool shoot_through_actor(const actor* agent, const actor* target, bool announce)
{
    if (!target)
        return true;

    // Projectiles can be shot through by anyone.
    const monster* mon = target->as_monster();
    if (mon && mons_is_projectile(*mon))
        return true;

    // But all the other checks require an aligned agent.
    if (!agent || !mons_aligned(agent, mon))
        return false;

    // Certain special allies can freely shoot through the player.
    if (target->is_player())
    {
        if (agent->is_monster()
            && (mons_is_hepliaklqana_ancestor(agent->type)
                || mons_is_player_shadow(*agent->as_monster())
                || agent->real_attitude() == ATT_MARIONETTE
                || agent->type == MONS_PLATINUM_PARAGON))
        {
            return true;
        }
    }
    else
    {
        if (mons_is_avatar(target->type) || target->type == MONS_SHOOTING_STAR)
            return true;

        if ((agent->is_player() && have_passive(passive_t::shoot_through_plants)
            || agent->is_monster() && agent->deity() == GOD_FEDHAS)
            && mons_class_is_plant(target->type))
        {
            if (announce && you.can_see(*target))
            {
                simple_god_message(
                            make_stringf(" protects %s plant from harm.",
                                agent->is_player() ? "your" : "a").c_str(),
                            false, GOD_FEDHAS);
            }
            return true;
        }

        if (agent->is_player() && mons_is_hepliaklqana_ancestor(target->type))
        {
            // TODO: this message does not work very well for all sorts of attacks
            // should this be a god message?
            if (announce && you.can_see(*target))
                mprf("%s avoids your attack.", target->name(DESC_THE).c_str());
            return true;
        }

        if (agent->is_player()
            && will_have_passive(passive_t::shadow_attacks)
            && mons_is_player_shadow(*mon))
        {
            return true;
        }

        if (agent->is_player() && testbits(mon->flags, MF_DEMONIC_GUARDIAN))
        {
            if (announce && you.can_see(*mon))
                mpr("Your demonic guardian avoids your attack.");
            return true;
        }

        if (agent->is_player() && mon->type == MONS_HAUNTED_ARMOUR)
            return true;
    }

    return false;
}

/**
 * Would it ever be possible for any hostile action by a given agent to do any
 * harm whatsoever to a given target? This includes damage, debuffs, or anything
 * else we would consider negative.
 *
 * Note: This does not imply that the agent *currently* possesses the means to
 * inflict that harm (ie: it can return true for an agent with no attacks, or
 * only spells the target resists fully). Rather, think of it as 'the target is
 * not naturally invulnerable to all offensive actions by the agent in question'.
 *
 * This includes all cases covered by shoot_through_actor(), but also some
 * additional ones (such as Jivya's jelly protection), where a target cannot be
 * harmed, but still blocks fire.
 *
 *  @param agent       The source of the action. May be nullptr, if the action
 *                     has a non-actor source (or possibly a dead actor).
 *  @param target      The actor that is the target of the action.
 *  @param announce_important  If true, prints a message stating how the target
 *                             avoids harm (in cases where this avoidance is
 *                             unusual).
 *  @param announce_mundane    If true, prints a message stating how the target
 *                             avoids harm (in cases where this avoidance is
 *                             frequent, such as Ancestors avoiding player
 *                             attacks).
 *  @return  Whether the monster could theoretically be harmed by this agent.
 */
bool could_harm(const actor* agent, const actor* target, bool announce_important,
                                                         bool announce_mundane)
{
    if (!target)
        return false;

    // If we can fire through them, we definitely can't harm them.
    if (shoot_through_actor(agent, target, announce_mundane))
        return false;

    // Players in Sanctuaries cannot harm anything.
    if (agent && agent->is_player() && (is_sanctuary(you.pos())))
    {
        if (announce_important)
        {
            string msg = make_stringf("The Sanctuary denies your attempt to harm %s.",
                                        target->name(DESC_THE).c_str());
            god_speaks(GOD_ZIN, msg.c_str());
        }
        return false;
    }

    // Actors in Sanctuaries cannot be harmed by anything.
    if (is_sanctuary(target->pos()))
    {
        if (announce_important && you.see_cell(target->pos()))
        {
            string msg = make_stringf("The Sanctuary protects %s from harm.",
                                        target->name(DESC_THE).c_str());
            god_speaks(GOD_ZIN, msg.c_str());
        }
        return false;
    }

    if (agent && agent->is_player()
        && have_passive(passive_t::neutral_slimes)
        && mons_class_is_slime(target->type)
        && target->wont_attack())
    {
        if (announce_mundane && you.can_see(*target))
            simple_god_message(" protects your slime from harm.", false, GOD_JIYVA);
        return false;
    }

    return true;
}

// As above, but specifically only returns true if the target is an *enemy*
// that the agent could harm (while always returning false for allies).
bool could_harm_enemy(const actor* agent, const actor* target,
                      bool announce_important, bool announce_mundane)
{
    if (mons_aligned(agent, target))
        return false;

    return could_harm(agent, target, announce_important, announce_mundane);
}

/**
 * Returns the maximum distance this type of monster is allowed to be from its
 * creator. It will refuse to move further away than this under its own power,
 * and if circumstances cause it to exceed this, it will abandon other plans to
 * return to this range instead.
 */
int mons_leash_range(monster_type mc)
{
    switch (mc)
    {
        case MONS_RENDING_BLADE:
        case MONS_SOLAR_EMBER:
        case MONS_PHALANX_BEETLE:   return 1;
        case MONS_HAUNTED_ARMOUR:   return 2;
        default:                    return 0; // No leashing
    }
}