File: xom.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 (5756 lines) | stat: -rw-r--r-- 189,624 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
/**
 * @file
 * @brief All things Xomly
**/

#include "AppHdr.h"

#include "xom.h"

#include <algorithm>
#include <functional>

#include "abyss.h"
#include "acquire.h"
#include "act-iter.h"
#include "areas.h"
#include "artefact.h"
#include "branch.h"
#include "cloud.h"
#include "corpse.h"
#include "coordit.h"
#include "database.h"
#ifdef WIZARD
#include "dbg-util.h"
#endif
#include "delay.h"
#include "directn.h"
#include "dlua.h"
#include "english.h"
#include "env.h"
#include "errors.h"
#include "god-item.h"
#include "item-name.h"
#include "item-prop.h"
#include "item-status-flag-type.h"
#include "items.h"
#include "item-use.h"
#include "losglobal.h"
#include "makeitem.h"
#include "map-knowledge.h"
#include "message.h"
#include "misc.h"
#include "mon-behv.h"
#include "mon-cast.h"
#include "mon-clone.h"
#include "mon-death.h"
#include "mon-pick.h"
#include "mon-place.h"
#include "mon-poly.h"
#include "mon-tentacle.h"
#include "mon-util.h"
#include "mutation.h"
#include "nearby-danger.h"
#include "notes.h"
#include "output.h"
#include "place.h"
#include "player-stats.h"
#include "potion.h"
#include "prompt.h"
#include "random-pick.h"
#include "religion.h"
#include "shout.h"
#include "spl-clouds.h"
#include "spl-goditem.h"
#include "spl-monench.h"
#include "spl-transloc.h"
#include "stairs.h"
#include "stash.h"
#include "state.h"
#include "stepdown.h"
#include "stringutil.h"
#include "syscalls.h"
#include "tag-version.h"
#include "teleport.h"
#include "terrain.h"
#include "transform.h"
#include "traps.h"
#include "travel.h"
#include "viewchar.h"
#include "view.h"

#ifdef DEBUG_XOM
#    define DEBUG_RELIGION
#    define NOTE_DEBUG_XOM
#endif

#ifdef DEBUG_RELIGION
#    define DEBUG_DIAGNOSTICS
#    define DEBUG_GIFTS
#endif

static void _do_xom_event(xom_event_type event_type, int sever);
static int _xom_event_badness(xom_event_type event_type);

static bool _action_is_bad(xom_event_type action)
{
    return action > XOM_LAST_GOOD_ACT && action <= XOM_LAST_BAD_ACT;
}

// Spells to be cast at tension > 0, i.e. usually in battle situations.
// Spells later in the list require higher severity to have a chance of being
// selected. Spells are sorted by level, then very roughly by power when
// neither planned for nor capability to repeatedly cast it.
static const vector<spell_type> _xom_random_spells =
{
    SPELL_SUMMON_SMALL_MAMMAL,
    SPELL_GLOOM,
    SPELL_FUGUE_OF_THE_FALLEN,
    SPELL_OLGREBS_TOXIC_RADIANCE,
    SPELL_BATTLESPHERE,
    SPELL_AWAKEN_ARMOUR,
    SPELL_MARTYRS_KNELL,
    SPELL_LEDAS_LIQUEFACTION,
    SPELL_FORGE_BLAZEHEART_GOLEM,
    SPELL_ANIMATE_DEAD,
    SPELL_INTOXICATE,
    SPELL_SUMMON_MANA_VIPER,
    SPELL_WALKING_ALEMBIC,
    SPELL_SUMMON_CACTUS,
    SPELL_DISPERSAL,
    SPELL_DEATH_CHANNEL,
    SPELL_SUMMON_HYDRA,
    SPELL_SPHINX_SISTERS,
    SPELL_DIAMOND_SAWBLADES,
    SPELL_MALIGN_GATEWAY,
    SPELL_DISCORD,
    SPELL_DISJUNCTION,
    SPELL_SUMMON_HORRIBLE_THINGS,
    SPELL_SUMMON_DRAGON,
    SPELL_FULSOME_FUSILLADE,
    SPELL_CHAIN_OF_CHAOS
};

static const char *_xom_message_arrays[NUM_XOM_MESSAGE_TYPES][6] =
{
    // XM_NORMAL
    {
        "Xom is interested.",
        "Xom is mildly amused.",
        "Xom is amused.",
        "Xom is highly amused!",
        "Xom thinks this is hilarious!",
        "Xom roars with laughter!"
    },

    // XM_INTRIGUED
    {
        "Xom is interested.",
        "Xom is very interested.",
        "Xom is extremely interested.",
        "Xom is intrigued!",
        "Xom is very intrigued!",
        "Xom is fascinated!"
    }
};

/**
 * How much does Xom like you right now?
 *
 * Doesn't account for boredom, or whether or not you actually worship Xom.
 *
 * @return An index mapping to an entry in xom_moods.
 */
int xom_favour_rank()
{
    static const int breakpoints[] = { 20, 50, 80, 120, 150, 180};
    for (unsigned int i = 0; i < ARRAYSZ(breakpoints); ++i)
        if (you.raw_piety <= breakpoints[i])
            return i;
    return ARRAYSZ(breakpoints);
}

static const char* xom_moods[] = {
    "a very special plaything of Xom.",
    "a special plaything of Xom.",
    "a plaything of Xom.",
    "a toy of Xom.",
    "a favourite toy of Xom.",
    "a beloved toy of Xom.",
    "Xom's teddy bear."
};

static const char *describe_xom_mood()
{
    const int mood = xom_favour_rank();
    ASSERT(mood >= 0);
    ASSERT((size_t) mood < ARRAYSZ(xom_moods));
    return xom_moods[mood];
}

const string describe_xom_favour()
{
    string favour;
    if (!you_worship(GOD_XOM))
        favour = "a very buggy toy of Xom.";
    else if (you.gift_timeout < 1)
        favour = "a BORING thing.";
    else
        favour = describe_xom_mood();

    return favour;
}

#define XOM_SPEECH(x) x
static string _get_xom_speech(const string &key)
{
    string result = getSpeakString("Xom " + key);

    if (result.empty())
        result = getSpeakString("Xom " XOM_SPEECH("general effect"));

    if (result.empty())
        return "Xom makes something happen.";

    return result;
}

static bool _xom_is_bored()
{
    return you_worship(GOD_XOM) && !you.gift_timeout;
}

static bool _xom_feels_nasty()
{
    // Xom will only directly kill you with a bad effect if you're under
    // penance from him, or if he's bored.
    return you.penance[GOD_XOM] || _xom_is_bored();
}

bool xom_is_nice(int tension)
{
    if (player_under_penance(GOD_XOM))
        return false;

    if (you_worship(GOD_XOM))
    {
        // If you.gift_timeout is 0, then Xom is BORED. He HATES that.
        if (!you.gift_timeout)
            return false;

        // At high tension Xom is more likely to be nice, at zero
        // tension the opposite.
        const int tension_bonus
            = (tension == -1 ? 0 // :
// Xom needs to be less negative
//              : tension ==  0 ? -min(abs(HALF_MAX_PIETY - you.piety) / 2,
//                                     you.piety / 10)
                             : min((MAX_PIETY - you.raw_piety) / 2,
                                   random2(tension)));

        const int effective_piety = you.raw_piety + tension_bonus;
        ASSERT_RANGE(effective_piety, 0, MAX_PIETY + 1);

#ifdef DEBUG_XOM
        mprf(MSGCH_DIAGNOSTICS,
             "Xom: tension: %d, piety: %d -> tension bonus = %d, eff. piety: %d",
             tension, you.raw_piety, tension_bonus, effective_piety);
#endif

        // Whether Xom is nice depends largely on his mood (== piety).
        return x_chance_in_y(effective_piety, MAX_PIETY);
    }
    else // CARD_XOM (XXX: There is no Xom card anymore. Is this needed?)
        return coinflip();
}

static void _xom_is_stimulated(int maxinterestingness,
                               const char *message_array[],
                               bool force_message)
{
    if (!you_worship(GOD_XOM) || maxinterestingness <= 0)
        return;

    // Xom is not directly stimulated by his own acts.
    if (crawl_state.which_god_acting() == GOD_XOM)
        return;

    int interestingness = random2(piety_scale(maxinterestingness));

    interestingness = min(200, interestingness);

#if defined(DEBUG_RELIGION) || defined(DEBUG_GIFTS) || defined(DEBUG_XOM)
    mprf(MSGCH_DIAGNOSTICS,
         "Xom: gift_timeout: %d, maxinterestingness = %d, interestingness = %d",
         you.gift_timeout, maxinterestingness, interestingness);
#endif

    bool was_stimulated = false;
    if (interestingness > you.gift_timeout && interestingness >= 10)
    {
        you.gift_timeout = interestingness;
        was_stimulated = true;
    }

    if (was_stimulated || force_message)
    {
        god_speaks(GOD_XOM,
                   ((interestingness > 160) ? message_array[5] :
                    (interestingness >  80) ? message_array[4] :
                    (interestingness >  60) ? message_array[3] :
                    (interestingness >  40) ? message_array[2] :
                    (interestingness >  20) ? message_array[1]
                                            : message_array[0]));
        //updating piety status line
        you.redraw_title = true;
    }
}

void xom_is_stimulated(int maxinterestingness, xom_message_type message_type,
                       bool force_message)
{
    _xom_is_stimulated(maxinterestingness, _xom_message_arrays[message_type],
                       force_message);
}

void xom_is_stimulated(int maxinterestingness, const string& message,
                       bool force_message)
{
    if (!you_worship(GOD_XOM))
        return;

    const char *message_array[6];

    for (int i = 0; i < 6; ++i)
        message_array[i] = message.c_str();

    _xom_is_stimulated(maxinterestingness, message_array, force_message);
}

void xom_tick()
{
    // Xom now ticks every action, not every 20 turns.
    if (one_chance_in(20))
    {
        // Xom semi-randomly drifts your piety.
        const string old_xom_favour = describe_xom_favour();
        const bool good = (you.raw_piety == HALF_MAX_PIETY ? coinflip()
                                                       : you.raw_piety > HALF_MAX_PIETY);
        int size = abs(you.raw_piety - HALF_MAX_PIETY);

        // Piety slowly drifts towards the extremes.
        const int delta = piety_scale(x_chance_in_y(511, 1000) ? 1 : -1);
        size += delta;
        if (size > HALF_MAX_PIETY)
            size = HALF_MAX_PIETY;

        you.raw_piety = HALF_MAX_PIETY + (good ? size : -size);
        string new_xom_favour = describe_xom_favour();
        you.redraw_title = true; // redraw piety/boredom display
        if (old_xom_favour != new_xom_favour)
        {
            // If we entered another favour state, take a big step into
            // the new territory, to avoid oscillating favour announcements
            // every few turns.
            size += delta * 8;
            if (size > HALF_MAX_PIETY)
                size = HALF_MAX_PIETY;

            // If size was 0 to begin with, it may become negative, but that
            // doesn't really matter.
            you.raw_piety = HALF_MAX_PIETY + (good ? size : -size);
        }
#ifdef DEBUG_XOM
        const string note = make_stringf("xom_tick(), delta: %d, piety: %d",
                                         delta, you.raw_piety);
        take_note(Note(NOTE_MESSAGE, 0, 0, note), true);
#endif

        // ...but he gets bored...
        if (you.gift_timeout > 0 && coinflip())
           you.gift_timeout--;

        new_xom_favour = describe_xom_favour();
        if (old_xom_favour != new_xom_favour)
        {
            const string msg = "You are now " + new_xom_favour;
            god_speaks(you.religion, msg.c_str());
        }

        if (you.gift_timeout == 1)
            simple_god_message(" is getting BORED.");
    }

    if (x_chance_in_y(2 + you.faith(), 6))
    {
        const int tension = get_tension(GOD_XOM);
        const int chance = (tension ==  0 ? 1 :
                            tension <=  5 ? 2 :
                            tension <= 10 ? 3 :
                            tension <= 20 ? 4
                                          : 5);

        // If Xom is bored, the chances for Xom acting are sort of reversed.
        if (!you.gift_timeout && x_chance_in_y(25 - chance*chance, 100))
        {
            xom_acts(abs(you.raw_piety - HALF_MAX_PIETY), maybe_bool::maybe, tension);
            return;
        }
        else if (you.gift_timeout <= 1 && chance > 0
                 && x_chance_in_y(chance - 1, 80))
        {
            // During tension, Xom may briefly forget about being bored.
            const int interest = random2(chance * 15);
            if (interest > 0)
            {
                if (interest < 25)
                    simple_god_message(" is interested.");
                else
                    simple_god_message(" is intrigued.");

                you.gift_timeout += interest;
                //updating piety status line
                you.redraw_title = true;
#if defined(DEBUG_RELIGION) || defined(DEBUG_XOM)
                mprf(MSGCH_DIAGNOSTICS,
                     "tension %d (chance: %d) -> increase interest to %d",
                     tension, chance, you.gift_timeout);
#endif
            }
        }

        if (x_chance_in_y(chance*chance, 100))
            xom_acts(abs(you.raw_piety - HALF_MAX_PIETY), maybe_bool::maybe, tension);
    }
}

static bool mon_nearby(function<bool(monster&)> filter)
{
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
        if (filter(**mi))
            return true;
    return false;
}

// Picks 100 random grids from the level and checks whether they've been
// marked as seen (explored) or known (mapped). If seen_only is true,
// grids only "seen" via magic mapping don't count. Returns the
// estimated percentage value of exploration.
static int _exploration_estimate(bool seen_only = false)
{
    int seen  = 0;
    int total = 0;
    int tries = 0;

    do
    {
        tries++;

        coord_def pos = random_in_bounds();
        if (!seen_only && env.map_knowledge(pos).known() || env.map_knowledge(pos).seen())
        {
            seen++;
            total++;
            continue;
        }

        bool open = true;
        if (cell_is_solid(pos) && !feat_is_closed_door(env.grid(pos)))
        {
            open = false;
            for (adjacent_iterator ai(pos); ai; ++ai)
            {
                if (map_bounds(*ai) && (!feat_is_opaque(env.grid(*ai))
                                        || feat_is_closed_door(env.grid(*ai))))
                {
                    open = true;
                    break;
                }
            }
        }

        if (open)
            total++;
    }
    while (total < 100 && tries < 1000);

    // If we didn't get any qualifying grids, there are probably so few
    // of them you've already seen them all.
    if (total == 0)
        return 100;

    if (total < 100)
        seen *= 100 / total;

    return seen;
}

static bool _teleportation_check()
{
    if (crawl_state.game_is_sprint())
        return false;

    return !you.no_tele();
}

/// Try to choose a random player-castable spell.
static spell_type _choose_random_spell(int sever)
{
    const int spellenum = max(1, sever);
    vector<spell_type> ok_spells;
    const vector<spell_type> &spell_list = _xom_random_spells;
    for (int i = 0; i < min(spellenum, (int)spell_list.size()); ++i)
    {
        const spell_type spell = spell_list[i];
        if (!spell_is_useless(spell, true, true, true))
            ok_spells.push_back(spell);
    }

    if (!ok_spells.size())
        return SPELL_NO_SPELL;
    return ok_spells[random2(ok_spells.size())];
}

/// Cast a random spell 'through' the player.
static void _xom_random_spell(int sever)
{
    const spell_type spell = _choose_random_spell(sever);
    int power = sever + you.experience_level * 2
                + get_tension() + you.runes.count() * 2;

    if (spell == SPELL_NO_SPELL)
        return;

    god_speaks(GOD_XOM, _get_xom_speech("spell effect").c_str());

#if defined(DEBUG_DIAGNOSTICS) || defined(DEBUG_RELIGION) || defined(DEBUG_XOM)
    mprf(MSGCH_DIAGNOSTICS,
         "_xom_makes_you_cast_random_spell(); spell: %d",
         spell);
#endif

    your_spells(spell, power, false);
    const string note = make_stringf("cast spell '%s'", spell_title(spell));
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// Map out the level, detect items across the level, and detect creatures.
static void _xom_divination(int sever)
{
    god_speaks(GOD_XOM, _get_xom_speech("divination").c_str());

    magic_mapping(5 + sever * 2, 50 + random2avg(sever * 2, 2), false);

    const int prev_detected = count_detected_mons();
    const int num_creatures = detect_creatures(sever);
    const int num_items = detect_items(sever);

    if (num_creatures == 0 && num_items == 0)
        canned_msg(MSG_DETECT_NOTHING);
    else if (num_creatures == prev_detected)
    {
        // This is not strictly true. You could have cast Detect
        // Creatures with a big enough fuzz that the detected glyph is
        // still on the map when the original one has been killed. Then
        // another one is spawned, so the number is the same as before.
        // There's no way we can check this, however.
        mpr("You detect items, but no nearby creatures.");
    }
    else
    {
        if (num_items > 0)
            mpr("You detect items and creatures!");
        else
            mpr("You detect creatures, but no further items.");
    }

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "divination: all"), true);
}

static void _try_brand_switch(const int item_index)
{
    if (item_index == NON_ITEM)
        return;

    item_def &item(env.item[item_index]);

    if (item.base_type != OBJ_WEAPONS)
        return;

    if (is_unrandom_artefact(item))
        return;

    // Only do it some of the time.
    if (one_chance_in(2))
        return;

    if (get_weapon_brand(item) == SPWPN_NORMAL)
        return;

    // TODO: shared code with _do_chaos_upgrade
    mprf("%s erupts in a glittering mayhem of colour.",
                            item.name(DESC_THE, false, false, false).c_str());
    if (is_random_artefact(item))
        artefact_set_property(item, ARTP_BRAND, SPWPN_CHAOS);
    else
        item.brand = SPWPN_CHAOS;
}

static void _xom_make_item(object_class_type base, int subtype, int power)
{
    god_acting gdact(GOD_XOM);

    int thing_created = items(true, base, subtype, power, 0, GOD_XOM);

    if (thing_created == NON_ITEM)
    {
        god_speaks(GOD_XOM, "\"No, never mind.\"");
        return;
    }
    else if (base == OBJ_ARMOUR && subtype == ARM_ORB && one_chance_in(4))
        god_speaks(GOD_XOM, _get_xom_speech("orb gift").c_str());

    _try_brand_switch(thing_created);

    static char gift_buf[100];
    snprintf(gift_buf, sizeof(gift_buf), "god gift: %s",
             env.item[thing_created].name(DESC_PLAIN).c_str());
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, gift_buf), true);

    canned_msg(MSG_SOMETHING_APPEARS);
    move_item_to_grid(&thing_created, you.pos());

    if (thing_created == NON_ITEM) // if it fell into lava
        simple_god_message(" snickers.", false, GOD_XOM);

    stop_running();
}

/// Xom's 'acquirement'. A gift for the player, of a sort...
static void _xom_acquirement(int /*sever*/)
{
    god_speaks(GOD_XOM, _get_xom_speech("general gift").c_str());

    const object_class_type types[] =
    {
        OBJ_WEAPONS,  OBJ_ARMOUR,   OBJ_JEWELLERY,  OBJ_BOOKS,
        OBJ_STAVES,   OBJ_WANDS,    OBJ_MISCELLANY, OBJ_GOLD,
        OBJ_MISSILES, OBJ_TALISMANS
    };
    const object_class_type force_class = RANDOM_ELEMENT(types);

    const int item_index = acquirement_create_item(force_class, GOD_XOM,
            false, you.pos());
    if (item_index == NON_ITEM)
    {
        god_speaks(GOD_XOM, "\"No, never mind.\"");
        return;
    }

    _try_brand_switch(item_index);

    const string note = make_stringf("god gift: %s",
                                     env.item[item_index].name(DESC_PLAIN).c_str());
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);

    stop_running();
    more();
}

/// Create a random item and give it to the player.
static void _xom_random_item(int sever)
{
    god_speaks(GOD_XOM, _get_xom_speech("general gift").c_str());
    _xom_make_item(OBJ_RANDOM, OBJ_RANDOM, sever * 3);
    more();
}

static bool _choose_mutatable_monster(const monster& mon)
{
    return mon.alive() && mon.can_safely_mutate();
}

static bool _choose_enchantable_monster(const monster& mon)
{
    return mon.alive() && !mon.wont_attack()
           && !mons_invuln_will(mon);
}

static bool _is_chaos_upgradeable(const item_def &item)
{
    // Change randarts, but not other artefacts.
    if (is_unrandom_artefact(item))
        return false;

    // Staves can't be changed either, since they don't have brands in the way
    // other weapons do.
    if (item.base_type == OBJ_STAVES
#if TAG_MAJOR_VERSION == 34
        || item.base_type == OBJ_RODS
#endif
       )
{
        return false;
}

    // Only upgrade permanent items, since the player should get a
    // chance to use the item if he or she can defeat the monster.
    if (item.flags & ISFLAG_SUMMONED)
        return false;

    // Blessed weapons are protected, being gifts from good gods.
    if (is_blessed(item))
        return false;

    // God gifts are protected -- but not his own!
    if (item.orig_monnum < 0)
    {
        god_type iorig = static_cast<god_type>(-item.orig_monnum);
        if (iorig > GOD_NO_GOD && iorig < NUM_GODS && iorig != GOD_XOM)
            return false;
    }

    // Don't stuff player inventory slots with chaos throwables.
    if (item.base_type == OBJ_MISSILES)
        return false;

    return true;
}

static bool _choose_chaos_upgrade(const monster& mon)
{
    // Only choose monsters that will attack.
    if (!mon.alive() || mons_attitude(mon) != ATT_HOSTILE
        || mons_is_fleeing(mon))
    {
        return false;
    }

    if (mons_itemuse(mon) < MONUSE_STARTING_EQUIPMENT)
        return false;

    // Holy beings are presumably protected by another god, unless
    // they're gifts from a chaotic god.
    if (mon.is_holy() && !is_chaotic_god(mon.god))
        return false;

    // God gifts from good gods will be protected by their god from
    // being given chaos weapons, while other gods won't mind the help
    // in their servants' killing the player.
    if (is_good_god(mon.god))
        return false;

    mon_inv_type slots[] = {MSLOT_WEAPON, MSLOT_ALT_WEAPON, MSLOT_MISSILE};

    // NOTE: Code assumes that the monster will only be carrying one
    // missile launcher at a time.
    bool special_launcher = false;
    for (int i = 0; i < 3; ++i)
    {
        const mon_inv_type slot = slots[i];
        const int          midx = mon.inv[slot];

        if (midx == NON_ITEM)
            continue;
        const item_def &item(env.item[midx]);

        // The monster already has a chaos weapon. Give the upgrade to
        // a different monster.
        if (is_chaotic_item(item))
            return false;

        if (_is_chaos_upgradeable(item))
        {
            if (item.base_type != OBJ_MISSILES)
                return true;

            // If, for some weird reason, a monster is carrying a bow
            // and javelins, then branding the javelins is okay, since
            // they won't be fired by the bow.
            if (!special_launcher || is_throwable(&mon, item))
                return true;
        }

        if (is_range_weapon(item))
        {
            // If the launcher alters its ammo, then branding the
            // monster's ammo won't be an upgrade.
            int brand = get_weapon_brand(item);
            if (brand == SPWPN_FLAMING || brand == SPWPN_FREEZING
                || brand == SPWPN_VENOM)
            {
                special_launcher = true;
            }
        }
    }

    return false;
}

static void _do_chaos_upgrade(item_def &item, const monster* mon)
{
    ASSERT(item.base_type == OBJ_MISSILES
           || item.base_type == OBJ_WEAPONS);
    ASSERT(!is_unrandom_artefact(item));

    if (mon && you.can_see(*mon) && item.base_type == OBJ_WEAPONS)
    {
        const description_level_type desc = mon->friendly() ? DESC_YOUR
                                                            : DESC_THE;
        mprf("%s %s erupts in a glittering mayhem of colour.",
            apostrophise(mon->name(desc)).c_str(),
            item.name(DESC_PLAIN, false, false, false).c_str());
    }

    const int brand = (item.base_type == OBJ_WEAPONS) ? (int) SPWPN_CHAOS
                                                      : (int) SPMSL_CHAOS;

    if (is_random_artefact(item))
        artefact_set_property(item, ARTP_BRAND, brand);
    else
    {
        item.brand = brand;

        // Make sure it's visibly special.
        if (!(item.flags & ISFLAG_COSMETIC_MASK))
            item.flags |= ISFLAG_GLOWING;

        // Give some extra enchantments to tempt players into using chaos brand.
        if (item.base_type == OBJ_WEAPONS)
            item.plus  += random_range(2, 4);
    }
}

// Xom forcibly sends you to a special bazaar,
// with visuals pretending it's banishment.
static void _xom_bazaar_trip(int /*sever*/)
{
    if (brdepth[BRANCH_ABYSS] == -1)
    {
        // Only possible in wizmode, as the message implies, but it crashes.
        mprf(MSGCH_ERROR, "Not even Xom can make wizards leave Sprint. "
                          "Aborting Xom's Bazaar banishment.");
    }
    else
    {
        god_speaks(GOD_XOM, _get_xom_speech("bazaar trip").c_str());
        run_animation(ANIMATION_BANISH, UA_BRANCH_ENTRY, false);
        dlua.callfn("dgn_set_persistent_var", "sb", "xom_bazaar", true);
        down_stairs(DNGN_ENTER_BAZAAR);
        you.props[XOM_BAZAAR_TRIP_COUNT].get_int()++;
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "banished to a bazaar"),
                  true);
    }
}

static const vector<random_pick_entry<monster_type>> _xom_summons =
{
  { -4, 26,   5, FLAT, MONS_BUTTERFLY },
  { -4, -1,   5, FLAT, MONS_QUOKKA },
  { -3,  6,  60, SEMI, MONS_CRIMSON_IMP },
  { -1,  6,  40, SEMI, MONS_IRON_IMP },
  {  2,  8,  40, SEMI, MONS_SHADOW_IMP },
  {  3,  8,  50, SEMI, MONS_UFETUBUS },
  {  3,  8,  40, SEMI, MONS_WHITE_IMP },
  {  3,  8,  50, SEMI, MONS_DRUDE },
  {  4,  8,   5, SEMI, MONS_MUMMY },
  {  4, 10,  75, SEMI, MONS_PHANTOM },
  {  5, 10,  10, SEMI, MONS_BOMBARDIER_BEETLE },
  {  5, 12,  90, SEMI, MONS_SWAMP_DRAKE },
  {  5, 12,  25, SEMI, MONS_WEEPING_SKULL },
  {  7, 14,  50, SEMI, MONS_ORANGE_DEMON },
  {  7, 15,  95, SEMI, MONS_SHAPESHIFTER },
  {  8, 14,  40, SEMI, MONS_ICE_DEVIL },
  {  8, 14,  40, SEMI, MONS_RED_DEVIL },
  {  8, 15,  60, SEMI, MONS_BOGGART },
  {  8, 20, 155, SEMI, MONS_CHAOS_SPAWN },
  {  9, 14,  60, SEMI, MONS_HELLWING },
  {  9, 14,   5, FLAT, MONS_TOENAIL_GOLEM },
  {  9, 14,  30, SEMI, MONS_VAMPIRE },
  {  9, 16,  50, SEMI, MONS_YNOXINUL },
  { 10, 14,  40, SEMI, MONS_HELL_RAT },
  { 10, 14,  30, SEMI, MONS_KOBOLD_DEMONOLOGIST },
  { 10, 15,  90, SEMI, MONS_ABOMINATION_SMALL },
  { 10, 16,  50, SEMI, MONS_UGLY_THING },
  { 10, 17,  50, SEMI, MONS_SOUL_EATER },
  { 10, 18,  85, SEMI, MONS_RUST_DEVIL },
  { 11, 17,  50, SEMI, MONS_SMOKE_DEMON },
  { 11, 17,  30, SEMI, MONS_DREAM_SHEEP },
  { 11, 20,  80, SEMI, MONS_WORLDBINDER },
  { 11, 22,  50, SEMI, MONS_NEQOXEC },
  { 12, 16,  30, SEMI, MONS_OBSIDIAN_BAT },
  { 12, 18,  30, SEMI, MONS_TARANTELLA },
  { 12, 18,  15, SEMI, MONS_DEMONSPAWN },
  { 13, 19,  75, SEMI, MONS_SUN_DEMON },
  { 13, 20,  75, SEMI, MONS_SIXFIRHY },
  { 13, 20,  15, SEMI, MONS_GREAT_ORB_OF_EYES },
  { 13, 21, 105, SEMI, MONS_LAUGHING_SKULL },
  { 14, 22,  90, SEMI, MONS_ABOMINATION_LARGE },
  { 14, 22, 105, SEMI, MONS_GLOWING_SHAPESHIFTER },
  { 15, 22,  50, SEMI, MONS_HELL_HOG },
  { 15, 23,   1, FLAT, MONS_OBSIDIAN_STATUE },
  { 16, 22,  10, SEMI, MONS_BUNYIP },
  { 16, 23,  50, SEMI, MONS_RADROACH },
  { 16, 25,  75, SEMI, MONS_VERY_UGLY_THING },
  { 16, 24,  25, SEMI, MONS_SPHINX_MARAUDER },
  { 17, 24,  35, SEMI, MONS_GLOWING_ORANGE_BRAIN },
  { 17, 33,  35, SEMI, MONS_SHADOW_DEMON },
  { 17, 33,  65, SEMI, MONS_SIN_BEAST },
  { 17, 33,  15, SEMI, MONS_CACODEMON },
  { 17, 33,  15, SEMI, MONS_ZYKZYL },
  { 18, 25,  50, SEMI, MONS_GUARDIAN_SPHINX },
  { 18, 33,  35, SEMI, MONS_REAPER },
  { 18, 24,  30, SEMI, MONS_DANCING_WEAPON },
  { 19, 26,   1, FLAT, MONS_ORANGE_STATUE },
  { 20, 33,  30, SEMI, MONS_APOCALYPSE_CRAB },
  { 21, 33,  30, SEMI, MONS_TENTACLED_MONSTROSITY },
  { 22, 33,   1, FLAT, MONS_STARFLOWER },
  { 23, 33,  30, SEMI, MONS_HELLEPHANT },
  { 24, 33,   5, SEMI, MONS_MOTH_OF_WRATH },
  { 25, 33,   5, SEMI, MONS_NEKOMATA },
};

// Whenever choosing a monster that obviously comes in bands, spawn a few more,
// which is then used later on to not count for the summon count range of the
// power tier the given Xom summon calls for.
static int _xom_pal_minibands(monster_type mtype)
{
    int count = 1;

    if (mtype == MONS_BUTTERFLY || mtype == MONS_LAUGHING_SKULL ||
        mtype == MONS_DREAM_SHEEP)
    {
        count = x_chance_in_y(you.experience_level, 27) ? 3 : 2;
    }
    else if (mtype == MONS_HELL_RAT || mtype == MONS_BOGGART ||
             mtype == MONS_UGLY_THING || mtype == MONS_TARANTELLA ||
             mtype == MONS_HELL_HOG || mtype == MONS_VERY_UGLY_THING)
    {
        count = 2;
    }

    return count;
}

// Don't let later summoners double-up later on in summon calls;
// it gets too messy too quickly to tell what's happening.
static bool _xom_pal_summonercheck(monster_type mtype)
{
     return mtype == MONS_OBSIDIAN_STATUE || mtype == MONS_ORANGE_STATUE ||
            mtype == MONS_GLOWING_ORANGE_BRAIN || mtype == MONS_SHADOW_DEMON;
}

// This and _xom_random_pal keep three tiers of enemies that are each scaled
// to three tiers of XL, spawning either more of weaker monsters or less
// of stronger monsters whenever Xom summons allies or enemies.
static int _xom_pal_counting(int roll, bool isFriendly)
{
    int count = 0;

    if (roll <= 150)
    {
        if (you.experience_level < 4)
            count = random_range(2, 3);
        else if (you.experience_level < 10)
            count = random_range(3, 4);
        else if (you.experience_level < 19)
            count = random_range(3, 5);
        else
            count = random_range(4, 5);
    }
    else if (roll <= 300)
    {
        if (you.experience_level < 10)
            count = random_range(1, 2);
        else if (you.experience_level < 19)
            count = random_range(2, 3);
        else
            count = random_range(2, 4);
    }
    else
    {
        if (you.experience_level < 10)
            count = 1;
        else if (you.experience_level < 19)
            count = random_range(1, 2);
        else
            count = random_range(2, 3);
    }

    if (you.runes.count() > ZOT_ENTRY_RUNES + 1)
        count += div_rand_round(you.runes.count(), ZOT_ENTRY_RUNES + 2);

    if (!isFriendly && _xom_feels_nasty())
        count *= 1.5;

    return count;
}

static monster_type _xom_random_pal(int roll, bool isFriendly)
{
    monster_picker xom_picker;
    int variance = you.experience_level;

    // Tiers here match _xom_pal_counting's tiers of strength related
    // inversely to summon count but scaling up versus one's XL regardless.
    if (roll <= 130)
        if (you.experience_level < 19)
           variance += -4;
        else
           variance += random_range(-4, -3);
    else if (roll <= 300)
        if (you.experience_level < 19)
            variance += random_range(-2, -1);
        else
            variance += random_range(-2, 0);
    else
        if (you.experience_level < 10)
            variance += random_range(-1, 1);
        else if (you.experience_level < 19)
            variance += random_range(0, 2);
        else
            variance += random_range(1, 3);

    // Make it a little flashier if it's allied or if Xom's quite dissatisfied.
    if (isFriendly)
        variance += random_range(1, 4);
    else if (_xom_is_bored())
        variance += random_range(2, 4);
    else if (you.penance[GOD_XOM])
        variance += random_range(4, 6);

    variance = min(33, variance);

#ifdef DEBUG_DIAGNOSTICS
    mprf(MSGCH_DIAGNOSTICS, "_xom_random_pal(); xl variance roll: %d", roll);
#endif

    monster_type mon_type = xom_picker.pick(_xom_summons, variance, MONS_CRIMSON_IMP);

    // Endgame and extended monsters Xom has some fondness for (in being jokes
    // or highly chaotic), but which are mostly meant to stay in their branches,
    // get a small extra chance to be picked in the appropriate branch or Zigs.
    // Makes it a little more dramatic.
    if ((player_in_branch(BRANCH_ZOT) || player_in_branch(BRANCH_ZIGGURAT))
         && one_chance_in(13))
    {
        mon_type = random_choose_weighted(5, MONS_DEATH_COB,
                                          4, MONS_KILLER_KLOWN,
                                          3, MONS_PROTEAN_PROGENITOR,
                                          2, MONS_CURSE_TOE);
    }
    else if ((player_in_branch(BRANCH_PANDEMONIUM) ||
              player_in_branch(BRANCH_ZIGGURAT)) && one_chance_in(13))
    {
        mon_type = x_chance_in_y(3, 5) ? MONS_DEMONSPAWN_BLOOD_SAINT :
                                         MONS_DEMONSPAWN_CORRUPTER;
    }
    else if (player_in_branch(BRANCH_ZIGGURAT) && one_chance_in(4))
    {
        mon_type = x_chance_in_y(5, 7) ? MONS_PANDEMONIUM_LORD :
                                         MONS_PLAYER_GHOST;
    }

    return mon_type;
}

static bool _player_is_dead()
{
    return you.hp <= 0
        || you.did_escape_death();
}

static void _note_potion_effect(potion_type pot)
{
    string potion_name = potion_type_name(static_cast<int>(pot));

    string potion_msg = "potion effect ";

    potion_msg += ("(" + potion_name + ")");

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, potion_msg), true);
}


/// Feed the player a notionally-good potion effect.
static void _xom_do_potion(int /*sever*/)
{
    potion_type pot = POT_CURING;
    do
    {
        pot = random_choose_weighted(10, POT_CURING,
                                     10, POT_HEAL_WOUNDS,
                                     10, POT_MAGIC,
                                     10, POT_HASTE,
                                     10, POT_MIGHT,
                                     10, POT_BRILLIANCE,
                                     10, POT_INVISIBILITY,
                                     5,  POT_AMBROSIA,
                                     5,  POT_ATTRACTION,
                                     5,  POT_BERSERK_RAGE,
                                     1,  POT_EXPERIENCE);
    }
    while (!get_potion_effect(pot)->can_quaff()); // ugh

    // Experience uses default power, other potions get bonus power.
    // Curing, heal wounds, magic and berserk rage ignore power.
    const int pow = pot == POT_EXPERIENCE ? 40 : 150;

    god_speaks(GOD_XOM, _get_xom_speech("potion effect").c_str());

    _note_potion_effect(pot);

    get_potion_effect(pot)->effect(true, pow);

    level_change(); // need this for !xp - see mantis #3245
}

static void _confuse_monster(monster* mons, int sever)
{
    if (mons->clarity())
        return;
    if (mons->is_peripheral())
        return;

    const bool was_confused = mons->confused();
    if (mons->add_ench(mon_enchant(ENCH_CONFUSION,
          &env.mons[ANON_FRIENDLY_MONSTER], random2(sever) * 10)))
    {
        if (was_confused)
            simple_monster_message(*mons, " looks rather more confused.");
        else
            simple_monster_message(*mons, " looks rather confused.");
    }
}

static void _xom_confuse_monsters(int sever)
{
    bool spoke = false;
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (mi->wont_attack() || one_chance_in(20))
            continue;

        // Only give this message once.
        if (!spoke)
            god_speaks(GOD_XOM, _get_xom_speech("confusion").c_str());
        spoke = true;

        _confuse_monster(*mi, sever);
    }

    if (spoke)
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "confuse monster(s)"),
                  true);
    }
}

/// Post a passel of pals to the player.
static void _xom_send_allies(int sever)
{
    int strengthRoll = random2(1000 - (MAX_PIETY + sever) * 5);
    int count = _xom_pal_counting(strengthRoll, true);
    int num_actually_summoned = 0;

    for (int i = 0; i < count; ++i)
    {
        monster_type mon_type = _xom_random_pal(strengthRoll, true);

        mgen_data mg(mon_type, BEH_FRIENDLY, you.pos(), MHITYOU, MG_FORCE_BEH, GOD_XOM);
        mg.set_summoned(&you, MON_SUMM_AID, summ_dur(3));

        // Even though the friendlies are charged to you for accounting,
        // they should still show as Xom's fault if one of them kills you.
        mg.non_actor_summoner = "Xom";

        // Banding monsters don't count against the overall summon roll range,
        // and are restricted themselves in _xom_pal_minibands.
        int miniband = _xom_pal_minibands(mon_type);

        for (int j = 0; j < miniband; ++j)
        {
            monster* made = create_monster(mg);

            if (made)
            {
                num_actually_summoned++;
                if (made->type == MONS_REAPER)
                    _do_chaos_upgrade(*made->weapon(), made);
            }
        }

        // To make given random monster summonings more coherent, have a good
        // chance to jump forward and make the next summon the same as the last,
        // but only if it's not already a banding monster or a late summoner.
        if (x_chance_in_y(2, 3) && miniband == 1 &&
            !_xom_pal_summonercheck(mon_type) && i < count - 1)
        {
            i += 1;
            monster* made = create_monster(mg);

            if (made)
            {
                num_actually_summoned++;
                if (made->type == MONS_REAPER)
                    _do_chaos_upgrade(*made->weapon(), made);
            }
        }
    }

    if (num_actually_summoned)
    {
        god_speaks(GOD_XOM, _get_xom_speech("multiple summons").c_str());

        const string note = make_stringf("summons %d friend%s",
                                         num_actually_summoned,
                                         num_actually_summoned > 1 ? "s" : "");
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
}

/// Send a single pal to the player's aid, hopefully.
static void _xom_send_one_ally(int sever)
{
    int strengthRoll = random2(1000 - (MAX_PIETY + sever) * 5);
    const monster_type mon_type = _xom_random_pal(strengthRoll, true);

    mgen_data mg(mon_type, BEH_FRIENDLY, you.pos(), MHITYOU, MG_FORCE_BEH, GOD_XOM);
    mg.set_summoned(&you, MON_SUMM_AID, summ_dur(6));

    mg.non_actor_summoner = "Xom";

    if (monster *summons = create_monster(mg))
    {
        // Add a little extra length and regen. Make friends with your new pal.
        int extra = random_range(100, 200);
        summons->add_ench(mon_enchant(ENCH_SUMMON_TIMER, nullptr, extra));
        summons->add_ench(mon_enchant(ENCH_REGENERATION, nullptr, 2000));
        god_speaks(GOD_XOM, _get_xom_speech("single summon").c_str());

        if (summons->type == MONS_REAPER)
            _do_chaos_upgrade(*summons->weapon(), summons);

        const string note = make_stringf("summons friendly %s",
                                         summons->name(DESC_PLAIN).c_str());
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
}

/**
 * Try to polymorph the given monster. If 'helpful', hostile monsters will
 * (try to) turn into weaker ones, and friendly monsters into stronger ones;
 * if (!helpful), the reverse is true.
 *
 * @param mons      The monster in question.
 * @param helpful   Whether to try to be helpful.
 */
static void _xom_polymorph_monster(monster &mons, bool helpful)
{
    god_speaks(GOD_XOM,
               helpful ? _get_xom_speech("good monster polymorph").c_str()
                       : _get_xom_speech("bad monster polymorph").c_str());

    const bool see_old = you.can_see(mons);
    const string old_name = see_old ? mons.full_name(DESC_PLAIN)
                                    : "something unseen";

    if (one_chance_in(8)
        && !mons_is_ghost_demon(mons.type)
        && !mons.is_shapeshifter()
        && mons.holiness() & MH_NATURAL
        && (you.experience_level > 4 || _xom_feels_nasty()))
    {
        mons.add_ench(one_chance_in(3) ? ENCH_GLOWING_SHAPESHIFTER
                                       : ENCH_SHAPESHIFTER);
    }

    const bool powerup = !(mons.wont_attack() ^ helpful);

    if (powerup)
    {
        if (you.experience_level > 4 && !helpful)
            mons.polymorph(PPT_MORE);
        else
            mons.polymorph(PPT_SAME);

        if (you.experience_level < 10 && !helpful)
            mons.malmutate(nullptr);
    }

    else
        mons.polymorph(PPT_LESS);

    const bool see_new = you.can_see(mons);

    if (see_old || see_new)
    {
        const string new_name = see_new ? mons.full_name(DESC_PLAIN)
                                        : "something unseen";

        string note = make_stringf("%s polymorph %s -> %s",
                                   helpful ? "good" : "bad",
                                   old_name.c_str(), new_name.c_str());

#ifdef NOTE_DEBUG_XOM
        note += " (";
        note += (powerup ? "upgrade" : "downgrade");
        note += ")";
#endif
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
}

/// Find a monster to poly.
static monster* _xom_mons_poly_target()
{
    vector<monster*> polymorphable;

    // XXX: Polymorphing early bats over liquids turn into D:1 acid dragons
    //      and killer bees, so skip them while polymorphing at low xls.
    //      Likewise, there's very few plant polymorph options.
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (_choose_mutatable_monster(**mi) && !mi->is_firewood()
           && ((env.grid(mi->pos()) != DNGN_DEEP_WATER)
               && (env.grid(mi->pos()) != DNGN_LAVA) || you.experience_level > 4)
           && (!(mi->holiness() & MH_PLANT) || you.experience_level > 8))
        {
            polymorphable.push_back(*mi);
        }
    }

    shuffle_array(polymorphable);

    if (polymorphable.empty())
        return nullptr;
    else
        return polymorphable[0];
}

/// Try to polymporph a nearby monster into something weaker... or stronger.
static void _xom_polymorph_nearby_monster(bool helpful)
{
    monster* mon = _xom_mons_poly_target();
    if (mon)
        _xom_polymorph_monster(*mon, helpful);
}

/// Try to polymporph a nearby monster into something weaker.
static void _xom_good_polymorph(int /*sever*/)
{
    _xom_polymorph_nearby_monster(true);
}

/// Try to polymporph a nearby monster into something stronger.
static void _xom_bad_polymorph(int /*sever*/)
{
    _xom_polymorph_nearby_monster(false);
}

/// Which monsters, if any, can Xom currently swap with the player?
static vector<monster*> _rearrangeable_pieces()
{
    vector<monster* > mons;
    if (player_stair_delay() || monster_at(you.pos()))
        return mons;

    for (monster_near_iterator mi(&you, LOS_NO_TRANS); mi; ++mi)
    {
        if (!mons_is_tentacle_or_tentacle_segment(mi->type))
            mons.push_back(*mi);
    }
    return mons;
}

// Swap places with a random monster and, depending on severity, also
// between monsters. This can be pretty bad if there are a lot of
// hostile monsters around.
static void _xom_rearrange_pieces(int sever)
{
    vector<monster*> mons = _rearrangeable_pieces();
    if (mons.empty())
        return;

    god_speaks(GOD_XOM, _get_xom_speech("rearrange the pieces").c_str());

    const int num_mons = mons.size();

    // Swap places with a random monster.
    monster* mon = mons[random2(num_mons)];
    transpose_with_monster(mon);

    // Sometimes confuse said monster.
    if (coinflip())
        _confuse_monster(mon, sever);

    if (num_mons > 1 && x_chance_in_y(sever, 70))
    {
        bool did_message = false;
        const int max_repeats = min(num_mons / 2, 8);
        const int repeats     = min(random2(sever / 10) + 1, max_repeats);
        for (int i = 0; i < repeats; ++i)
        {
            const int mon1 = random2(num_mons);
            int mon2 = mon1;
            while (mon1 == mon2)
                mon2 = random2(num_mons);

            if (mons[mon1]->swap_with(mons[mon2], MV_TRANSLOCATION))
            {
                if (!did_message)
                {
                    mpr("Some monsters swap places.");
                    did_message = true;
                }
                if (one_chance_in(4))
                    _confuse_monster(mons[mon1], sever);
                if (one_chance_in(4))
                    _confuse_monster(mons[mon2], sever);
            }
        }
    }
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "swap monsters"), true);
}

static int _xom_random_stickable(const int HD)
{
    unsigned int c;

    static const int arr[] =
    {
        WPN_CLUB, WPN_SPEAR, WPN_TRIDENT, WPN_HALBERD,
        WPN_GLAIVE, WPN_QUARTERSTAFF, WPN_SHORTBOW, WPN_ORCBOW,
        WPN_LONGBOW, WPN_GIANT_CLUB, WPN_GIANT_SPIKED_CLUB
    };

    // Maximum snake hd is 11 (anaconda) so random2(hd) gives us 0-10, and
    // weapon_rarity also gives us 1-10.
    do
    {
        c = random2(HD);
    }
    while (c >= ARRAYSZ(arr)
           || random2(HD) > weapon_rarity(arr[c]) && x_chance_in_y(c, HD));

    return arr[c];
}

static bool _hostile_snake(monster& mon)
{
    return mon.attitude == ATT_HOSTILE
            && mons_genus(mon.type) == MONS_SNAKE;
}

// An effect similar to old sticks to snakes (which worked on "sticks" other
// than arrows)
//  * Transformations are permanent.
//  * Weapons are always non-cursed.
//  * HD influences the enchantment and type of the weapon.
//  * Weapon is not guaranteed to be useful.
//  * Weapon will never be branded.
static void _xom_snakes_to_sticks(int /*sever*/)
{
    bool action = false;
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (!_hostile_snake(**mi))
            continue;

        if (!action)
        {
            take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                           "snakes to sticks"), true);
            god_speaks(GOD_XOM, _get_xom_speech("snakes to sticks").c_str());
            action = true;
        }

        const object_class_type base_type = coinflip() ? OBJ_MISSILES
                                                       : OBJ_WEAPONS;

        const int sub_type =
            (base_type == OBJ_MISSILES ? MI_JAVELIN
             : _xom_random_stickable(mi->get_experience_level()));

        int item_slot = items(false, base_type, sub_type,
                              mi->get_experience_level() / 3 - 1,
                              0, -1);

        if (item_slot == NON_ITEM)
            continue;

        item_def &item(env.item[item_slot]);

        // Always limit the quantity to 1.
        item.quantity = 1;

        // Output some text since otherwise snakes will disappear silently.
        mprf("%s reforms as %s.", mi->name(DESC_THE).c_str(),
             item.name(DESC_A).c_str());

        // Dismiss monster silently.
        move_item_to_grid(&item_slot, mi->pos());
        monster_die(**mi, KILL_RESET, NON_MONSTER, true);
    }
}

// Xom counts up webs to light on fire.
static vector<coord_def> _xom_counts_webs()
{
    vector<coord_def> webs;

    for (vision_iterator ri(you); ri; ++ri)
    {
        if (env.grid(*ri) == DNGN_TRAP_WEB)
            webs.push_back(*ri);
    }

    return webs;
}

// Xom burns down all webs in sight, replacing them with fire clouds.
// All other sorts of clouds are removed, and anybody in a web is freed.
static void _xom_lights_up_webs(int /*sever*/)
{
    int webs_count = 0;
    int blaze_time = 3 + random2(4) * 3;

    vector<coord_def> candidates = _xom_counts_webs();

    for (coord_def pos : candidates)
    {
        flash_tile(pos, RED, 0);
        animation_delay(20, true);

        if (cloud_at(pos))
            delete_cloud(pos);

        place_cloud(CLOUD_FIRE, pos, blaze_time, nullptr, 0);

        webs_count++;
        env.map_knowledge(pos).set_feature(DNGN_FLOOR);
        dungeon_terrain_changed(pos, DNGN_FLOOR);

        if (actor* act = actor_at(pos))
            if (act->caught_by() == CAUGHT_WEB)
                act->stop_being_caught();
    }

    view_clear_overlays();

    if (webs_count > 0)
    {
        god_speaks(GOD_XOM, _get_xom_speech("lights up webs").c_str());
        mprf("%s %s into flame!", number_in_words(webs_count).c_str(),
              webs_count == 1 ? "web bursts" : "webs burst");
        string note = make_stringf("lit up %d webs", webs_count);
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
}

/// Try to find a nearby hostile monster with an animateable weapon.
static monster* _find_monster_with_animateable_weapon()
{
    vector<monster* > mons_wpn;
    for (monster_near_iterator mi(&you, LOS_NO_TRANS); mi; ++mi)
    {
        if (mi->wont_attack() || mi->is_summoned()
            || mons_itemuse(**mi) < MONUSE_STARTING_EQUIPMENT
            || (mi->flags & MF_HARD_RESET))
        {
            continue;
        }

        const int mweap = mi->inv[MSLOT_WEAPON];
        if (mweap == NON_ITEM)
            continue;

        const item_def weapon = env.item[mweap];

        if (weapon.base_type == OBJ_WEAPONS
            && !(weapon.flags & ISFLAG_SUMMONED)
            && weapon.quantity == 1
            && !is_range_weapon(weapon)
            && !is_special_unrandom_artefact(weapon)
            && get_weapon_brand(weapon) != SPWPN_DISTORTION)
        {
            mons_wpn.push_back(*mi);
        }
    }
    if (mons_wpn.empty())
        return nullptr;
    return mons_wpn[random2(mons_wpn.size())];
}

static void _xom_animate_monster_weapon(int sever)
{
    // Pick a random monster...
    monster* mon = _find_monster_with_animateable_weapon();
    if (!mon)
        return;

    god_speaks(GOD_XOM, _get_xom_speech("animate monster weapon").c_str());

    // ...and get its weapon.
    const int wpn = mon->inv[MSLOT_WEAPON];
    ASSERT(wpn != NON_ITEM);

    const int dur = min(2 + (random2(sever) / 5), 6);

    mgen_data mg(MONS_DANCING_WEAPON, BEH_FRIENDLY, mon->pos(), mon->mindex(),
                 MG_NONE, GOD_XOM);
    mg.set_summoned(&you, SPELL_TUKIMAS_DANCE, summ_dur(dur));

    mg.non_actor_summoner = "Xom";

    monster *dancing = create_monster(mg);

    if (!dancing)
        return;

    // Make the monster unwield its weapon.
    mon->unequip(MSLOT_WEAPON, false, true);

    mprf("%s %s dances into the air!",
         apostrophise(mon->name(DESC_THE)).c_str(),
         env.item[wpn].name(DESC_PLAIN).c_str());

    destroy_item(dancing->inv[MSLOT_WEAPON]);

    dancing->inv[MSLOT_WEAPON] = wpn;
    env.item[wpn].set_holding_monster(*dancing);
    dancing->colour = env.item[wpn].get_colour();
}

// Have Xom make a big ring of temporary harmless plantlife around the player.
static void _xom_harmless_flora(int /*sever*/)
{
    bool created = false;
    bool perfectRing = coinflip();
    int radius = random_choose_weighted(54 - you.experience_level, 2,
                                        27, 3,
                                        13 + you.experience_level, 4);

    monster_type mon_type = x_chance_in_y(13 + you.experience_level, 54) ?
                            MONS_DEMONIC_PLANT : MONS_TOADSTOOL;

    for (radius_iterator ri(you.pos(), radius, C_SQUARE, LOS_NO_TRANS); ri; ++ri)
    {
        // Half of the time, make it imperfect on the inner parts.
        if (ri->distance_from(you.pos()) != radius
            && !perfectRing && x_chance_in_y(1, 3))
        {
            continue;
        }

        if (!actor_at(*ri) && monster_habitable_grid(MONS_PLANT, *ri))
        {
            mgen_data mg(mon_type, BEH_HOSTILE, *ri, MHITYOU,
                         MG_FORCE_BEH | MG_FORCE_PLACE, GOD_XOM);
            mg.set_summoned(&you, MON_SUMM_AID, summ_dur(5));

            mg.non_actor_summoner = "Xom";

            if (create_monster(mg))
                created = true;
        }
    }

    if (created)
    {
        god_speaks(GOD_XOM, _get_xom_speech("flora ring").c_str());
        if (mon_type == MONS_DEMONIC_PLANT)
            mpr("Demonic plants sprout up around you!");
        else
            mpr("Toadstools sprout up around you!");

        const string note = make_stringf("made a garden");
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
    else
        canned_msg(MSG_NOTHING_HAPPENS); // shouldn't be reached, and yet
}

// Can Xom reasonably convert a feature into interconnected doors?
// Avoids altars, stairs, portals, and runed doors. Allow anywhere
// diggable or otherwise walkable, and glassifies solid doors.
static bool _xom_door_replaceable(dungeon_feature_type feat)
{
    return !feat_is_critical(feat)
            && ((feat_has_solid_floor(feat)) || feat_is_diggable(feat)
                || (feat_is_door(feat) && !feat_is_runed(feat)));
}

// Find a group of monsters in a certain range of the player,
// then move them towards or away from the target, according to a cap.
// Return how many were moved for further assessing how many more may be moved.
static int _xom_count_and_move_group(int min_range, int max_range,
                                      bool inwards, int cap = INT_MAX)
{
    int moved = 0;
    vector<monster*> collectable;

    for (radius_iterator ri(you.pos(), max_range, C_SQUARE, LOS_NO_TRANS, true); ri; ++ri)
    {
        if (grid_distance(*ri, you.pos()) < min_range
            || !monster_at(*ri)
            || monster_at(*ri)->wont_attack())
        {
            continue;
        }

        collectable.push_back(monster_at(*ri));
    }

    shuffle_array(collectable);

    for (monster *moving_mons : collectable)
    {
        if (moved == cap)
            break;

        coord_def empty;

        if (inwards)
        {
            // Blink close a limited number of hostile enemies
            // adjacent or one tile away.
            if (!find_habitable_spot_near(you.pos(), mons_base_type(*moving_mons),
                                          2, empty))
            {
                continue;
            }

            if (moving_mons->blink_to(empty, true))
            {
                simple_monster_message(*moving_mons, " is shoved forward by the hand of Xom!");
                moving_mons->drain_action_energy();
                behaviour_event(moving_mons, ME_DISTURB, nullptr, you.pos());
                ++moved;
            }
        }
        else
        {
            int placeable_count = 0;
            coord_def spot;

            // Xom can heavily relocate enemies as desired to make this ring,
            // though teleporting them away by default would be more boring.

            // First try to blink the monster somewhere the player can still see.
            for (radius_iterator ri(moving_mons->pos(), 9, C_SQUARE, LOS_NO_TRANS, true);
                 ri; ++ri)
            {
                // Only look for unoccupied viable spaces
                // outside the entire door ring.
                if (actor_at(*ri) || !monster_habitable_grid(moving_mons, *ri)
                    || grid_distance(*ri, you.pos()) < 6)
                {
                    continue;
                }

                if (one_chance_in(++placeable_count))
                    spot = *ri;
            }

            // If that didn't work, try somewhere the player can't see.
            if (spot.origin())
            {
                for (radius_iterator ri(moving_mons->pos(), 9, C_SQUARE, LOS_NO_TRANS, true);
                    ri; ++ri)
                {
                    if (actor_at(*ri) || !monster_habitable_grid(moving_mons, *ri)
                        || grid_distance(*ri, you.pos()) < 6)
                    {
                        continue;
                    }

                    if (one_chance_in(++placeable_count))
                        spot = *ri;
                }
            }

            // If that still didn't work, just teleport the monster.
            if (spot.origin())
                moving_mons->teleport(true);
            else if (moving_mons->blink_to(spot, true))
            {
                moving_mons->drain_action_energy();
                ++moved;
            }
        }
    }

    return moved;
}

// Have Xom make a huge, slightly distant ring of clear, disconnected doors,
// and move enemies in or out according to Xom's mood.
static void _xom_door_ring(bool good)
{
    bool created = false;
    int total_moved = 0;
    int dug = 0;
    const int min_radius = 3;
    const int max_radius = 5;

    dungeon_feature_type feat = DNGN_CLOSED_CLEAR_DOOR;

    if (good)
    {
        // If meant to be good, shove out all adjacent hostile enemies.
        // Split to prioritize inside the ring are moved first
        // before moving those where the doors will appear.
        total_moved += _xom_count_and_move_group(1, min_radius - 1, false);
        total_moved += _xom_count_and_move_group(min_radius, max_radius, false);
    }
    else
    {
        // If meant to be bad, shove in visible enemies closer to the player,
        // capped by XL and how many are already adjacent.
        // Once more, prioritize monsters in the closer ring's range first.
        int soft_cap = max(1, div_rand_round(you.experience_level, 6));
        int inner_cap = _xom_feels_nasty() ? 8 : 2 + random_range(1, soft_cap);

        int moved = _xom_count_and_move_group(min_radius, max_radius,
                                              true, inner_cap);
        total_moved += moved;
        inner_cap -= moved;

        if (you.normal_vision >= max_radius + 1 && inner_cap > 0)
        {
            total_moved += _xom_count_and_move_group(max_radius + 1, you.normal_vision,
                                                     true, inner_cap);
        }

        total_moved += _xom_count_and_move_group(min_radius, max_radius, false);
    }

    // Either way, place the door ring round the player in a radius of 3 to 5.
    // It won't be perfect- skipping altars and stairs, rarely failing to
    // find a better spot for a monster- but it's more than enough for Xom.
    for (radius_iterator ri(you.pos(), max_radius, C_SQUARE, LOS_NONE); ri; ++ri)
    {
        if (in_bounds(*ri) && !actor_at(*ri)
            && grid_distance(*ri, you.pos()) >= min_radius
            && grid_distance(*ri, you.pos()) <= max_radius
            && _xom_door_replaceable(env.grid(*ri)))
        {
            if (cloud_at(*ri))
                delete_cloud(*ri);

            // For later messaging's sake, track how much is being dug out.
            if (feat_is_diggable(env.grid(*ri)))
                dug++;

            dungeon_terrain_changed(*ri, feat, false, true);

            map_wiz_props_marker *marker = new map_wiz_props_marker(*ri);
            marker->set_property("connected_exclude", "true");
            env.markers.add(marker);

            created = true;
        }
    }

    if (created)
    {
        env.markers.clear_need_activate();
        string message;

        if (dug > 60)
            message = "The dungeon churns and warps with monstrous intensity.";
        else if (dug > 30)
            message = "The dungeon churns and warps violently around you.";
        else
            message = "The dungeon churns and shimmers intensely around you.";

        mprf(good ? MSGCH_GOD : MSGCH_WARN, "%s", message.c_str());

        string note = "";
        if (good)
        {
            god_speaks(GOD_XOM, _get_xom_speech("kind door ring").c_str());
            note = make_stringf("made a ring of doors, pushed %d %s out",
                                total_moved, total_moved != 1 ? "others"
                                                              : "other");
        }
        else
        {
            god_speaks(GOD_XOM, _get_xom_speech("mean door ring").c_str());
            note = make_stringf("made a ring of doors, pulled %d %s in",
                                total_moved, total_moved != 1 ? "others"
                                                              : "other");
        }

        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
    else
        canned_msg(MSG_NOTHING_HAPPENS);
}

static void _xom_good_door_ring(int /*sever*/)
{
    _xom_door_ring(true);
}

static void _xom_bad_door_ring(int /*sever*/)
{
    _xom_door_ring(false);
}

static const map<dungeon_feature_type, int> terrain_fake_shatter_chances = {
    { DNGN_CLOSED_DOOR,      90 },
    { DNGN_GRATE,            90 },
    { DNGN_ORCISH_IDOL,      90 },
    { DNGN_GRANITE_STATUE,   90 },
    { DNGN_CLEAR_ROCK_WALL,  33 },
    { DNGN_ROCK_WALL,        33 },
    { DNGN_SLIMY_WALL,       25 },
    { DNGN_CRYSTAL_WALL,     25 },
    { DNGN_TREE,             25 },
    { DNGN_CLEAR_STONE_WALL, 15 },
    { DNGN_STONE_WALL,       15 },
    { DNGN_METAL_STATUE,      5 },
    { DNGN_ZOT_STATUE,        5 },
    { DNGN_METAL_WALL,        5 },
};

static int _xom_shatter_walls(coord_def where, bool more_than_dig)
{
    dungeon_feature_type feat = env.grid(where);

    if (!in_bounds(where)
         || env.markers.property_at(where, MAT_ANY, "veto_destroy") == "veto")
    {
        return 0;
    }

    if (feat_is_tree(feat))
        feat = DNGN_TREE;
    else if (feat_is_door(feat))
        feat = DNGN_CLOSED_DOOR;

    auto chance = terrain_fake_shatter_chances.find(feat);

    if (chance == terrain_fake_shatter_chances.end()
        || ((!feat_is_diggable(feat) || feat_is_door(feat)) && !more_than_dig)
        || !x_chance_in_y(chance->second, 100))
    {
        return 0;
    }

    if (you.see_cell(where))
    {
        if (feat_is_door(feat))
            mpr("A door shatters!");
        else if (feat == DNGN_GRATE)
            mpr("An iron grate is ripped into pieces!");
    }

    noisy(spell_effect_noise(SPELL_SHATTER), where);
    destroy_wall(where);

    if (feat == DNGN_ROCK_WALL || feat == DNGN_STONE_WALL
        || feat == DNGN_GRANITE_STATUE)
    {
        mgen_data mg(MONS_PILE_OF_DEBRIS, BEH_HOSTILE, where, MHITYOU,
                     MG_FORCE_BEH | MG_FORCE_PLACE);

        create_monster(mg);
    }

    return 1;
}

// Xom produces Shatter level noise, demolishes random features, and also
// fails to actually do any actual damage. Unlike actual Shatter, this both
// leaves behind debris and usually has very little chance to do more than dig.
static void _xom_fake_shatter(int /*sever*/)
{
    bool more_than_dig = one_chance_in(5);

    god_speaks(GOD_XOM, _get_xom_speech("fake shatter").c_str());

    if (silenced(you.pos()))
        mpr("The dungeon shakes... harmlessly?");
    else
    {
        noisy(spell_effect_noise(SPELL_SHATTER), you.pos());
        mprf(MSGCH_SOUND, "The dungeon rumbles... harmlessly?");
    }

    run_animation(ANIMATION_SHAKE_VIEWPORT, UA_PLAYER);

    int dest = 0;
    int rocks = 0;

    for (distance_iterator di(you.pos(), true, true, LOS_RADIUS); di; ++di)
    {
        if (!cell_see_cell(you.pos(), *di, LOS_SOLID))
            continue;

        dest += _xom_shatter_walls(*di, more_than_dig);
    }

    for (distance_iterator di(you.pos(), true, true, LOS_NO_TRANS); di; ++di)
    {
        if (one_chance_in(5) && rocks <= dest / 2 && !monster_at(*di)
              && !cell_is_solid(*di))
        {
            int rock_spot = items(true, OBJ_MISSILES, MI_LARGE_ROCK, 0, 0, GOD_XOM);
            env.item[rock_spot].quantity = 1;
            move_item_to_grid(&rock_spot, *di);
            rocks++;
        }
    }

    if (rocks)
        mpr("Some rocks are dislodged from the ceiling.");

    if (dest)
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "fake shatter"), true);

}

static void _xom_give_mutations(bool good)
{
    if (!you.can_safely_mutate())
        return;

    god_speaks(GOD_XOM, good ? _get_xom_speech("good mutations").c_str()
                             : _get_xom_speech("random mutations").c_str());

    const int num_tries = random2(4) + 1;

    const string note = make_stringf("give %smutation%s",
#ifdef NOTE_DEBUG_XOM
             good ? "good " : "random ",
#else
             "",
#endif
             num_tries > 1 ? "s" : "");

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    mpr("Your body is suffused with distortional energy.");

    bool failMsg = true;

    for (int i = num_tries; i > 0; --i)
    {
        // One bad mutation guaranteed when under Xom wrath.
        if (you.penance[GOD_XOM] && i == num_tries && !good)
        {
            if (!mutate(RANDOM_BAD_MUTATION, "Xom's mischief",
                        failMsg, false, true, false, MUTCLASS_NORMAL))
            {
                failMsg = false;
            }
        }
        // RANDOM_XOM_MUTATION is a flat coinflip for good or bad,
        // as opposed to RANDOM_MUTATION being 60-40 good or bad.
        else if (!mutate(good ? RANDOM_GOOD_MUTATION : RANDOM_XOM_MUTATION,
                    good ? "Xom's grace" : "Xom's mischief",
                    failMsg, false, true, false, MUTCLASS_NORMAL))
        {
            failMsg = false;
        }
    }
}

static void _xom_give_good_mutations(int) { _xom_give_mutations(true); }
static void _xom_give_bad_mutations(int) { _xom_give_mutations(false); }

static void _xom_drop_lightning()
{
    bolt beam;

    beam.flavour      = BEAM_ELECTRICITY;
    beam.glyph        = dchar_glyph(DCHAR_FIRED_BURST);
    beam.damage       = dice_def(3, 30);
    beam.target       = you.pos();
    beam.name         = "blast of lightning";
    beam.colour       = LIGHTCYAN;
    beam.thrower      = KILL_NON_ACTOR;
    beam.source_id    = MID_NOBODY;
    beam.aux_source   = "Xom's lightning strike";
    beam.ex_size      = 2;
    beam.is_explosion = true;

    beam.explode(true, true);
}

static void _xom_spray_lightning(coord_def position)
{
    bolt beam;

    // range has no tracer, so randomness is ok
    beam.range        = 7;
    beam.source       = you.pos();
    beam.target       = position;
    beam.target.x     += random_range(-1, 1);
    beam.target.y     += random_range(-1, 1);
    while (beam.target == you.pos())
    {
        beam.target.x     += random_range(-1, 1);
        beam.target.y     += random_range(-1, 1);
    }
    beam.thrower      = KILL_NON_ACTOR;
    beam.source_id    = MID_NOBODY;
    beam.aux_source   = "Xom's lightning strike";

    int power = 20 + you.experience_level * 5;
    if (you.runes.count() > ZOT_ENTRY_RUNES + 1)
        power += you.runes.count() * 3;

    // uncontrolled, so no player tracer.
    zappy(ZAP_LIGHTNING_BOLT, power, true, beam);
    beam.fire();
}

// Have Xom throw down divine lightning in a 5x5 explosion, then fire random
// lightning bolts in random directions potentially fudged towards, like
// old black draconian breath.
static void _xom_throw_divine_lightning(int /*sever*/)
{
    god_speaks(GOD_XOM, _get_xom_speech("divine lightning").c_str());

    _xom_drop_lightning();

    int spray_count = random_range(4, max(5, (min(27, get_tension() / 5))));
    int fire_count = 0;

    // Have a chance to actually aim lightning bolts near each present enemy.
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (fire_count < spray_count && one_chance_in(3))
        {
            _xom_spray_lightning(mi->pos());
            fire_count++;
        }
    }

    // Fire spare random bolts at random spots.
    if (fire_count < spray_count)
    {
        for (int i = 0; i < spray_count - fire_count; ++i)
        {
            coord_def randspot = you.pos();
            randspot.x += random_range(-6, 6);
            randspot.y += random_range(-6, 6);
            _xom_spray_lightning(randspot);
            fire_count++;
        }
    }

    string note = make_stringf("divine lightning + %d bolts", spray_count);
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// What scenery nearby would Xom like to mess with, if any?
static vector<coord_def> _xom_scenery_candidates()
{
    vector<coord_def> candidates;
    for (vision_iterator ri(you); ri; ++ri)
    {
        dungeon_feature_type feat = env.grid(*ri);
        if (feat_is_fountain(feat) && feat != DNGN_FOUNTAIN_BLOOD
            && feat != DNGN_FOUNTAIN_EYES)
        {
            candidates.push_back(*ri);
        }
        else if (feat_is_tree(feat))
            candidates.push_back(*ri);
        else if (feat_is_food(feat))
            candidates.push_back(*ri);
    }

    return candidates;
}

// What doors nearby would Xom like to mess with, if any?
static vector<coord_def> _xom_door_candidates()
{
    vector<coord_def> candidates;
    vector<coord_def> closed_doors;
    vector<coord_def> open_doors;
    for (vision_iterator ri(you); ri; ++ri)
    {
        dungeon_feature_type feat = env.grid(*ri);
        if (feat_is_closed_door(feat))
        {
            // Check whether this door is already included in a gate.
            if (find(begin(closed_doors), end(closed_doors), *ri)
                == end(closed_doors))
            {
                // If it's a gate, add all doors belonging to the gate.
                set<coord_def> all_door;
                find_connected_identical(*ri, all_door);
                for (auto dc : all_door)
                    closed_doors.push_back(dc);
            }
        }
        else if (feat_is_open_door(feat) && !actor_at(*ri)
                 && env.igrid(*ri) == NON_ITEM)
        {
            // Check whether this door is already included in a gate.
            if (find(begin(open_doors), end(open_doors), *ri)
                == end(open_doors))
            {
                // Check whether any of the doors belonging to a gate is
                // blocked by an item or monster.
                set<coord_def> all_door;
                find_connected_identical(*ri, all_door);
                bool is_blocked = false;
                for (auto dc : all_door)
                {
                    if (actor_at(dc) || env.igrid(dc) != NON_ITEM)
                    {
                        is_blocked = true;
                        break;
                    }
                }

                // If the doorway isn't blocked, add all doors
                // belonging to the gate.
                if (!is_blocked)
                {
                    for (auto dc : all_door)
                        open_doors.push_back(dc);
                }
            }
        }
    }
    // Order needs to be the same as messaging below, else the messages might
    // not make sense.
    candidates.insert(end(candidates), begin(open_doors), end(open_doors));
    candidates.insert(end(candidates), begin(closed_doors), end(closed_doors));

    return candidates;
}

// Place one or more decorative* features nearish the player.
static void _xom_place_decor()
{
    coord_def place;
    bool success = false;
    int aby = player_in_branch(BRANCH_ABYSS) ? 0 : 1;
    dungeon_feature_type decor = random_choose_weighted(10, DNGN_ALTAR_XOM,
                                                        7, DNGN_TRAP_TELEPORT,
                                                        2, DNGN_CACHE_OF_FRUIT,
                                                        2, DNGN_CACHE_OF_MEAT,
                                                        2, DNGN_CACHE_OF_BAKED_GOODS,
                                                        1, DNGN_CLOSED_DOOR,
                                                        1, DNGN_OPEN_DOOR,
                                                        aby, DNGN_ENTER_ABYSS);

    const int featuresCount = max(2, random2(random2(16)));
    for (int tries = featuresCount; tries > 0; --tries)
    {
        if ((random_near_space(&you, you.pos(), place, false)
             || random_near_space(&you, you.pos(), place, true))
            && env.grid(place) == DNGN_FLOOR && !(env.igrid(place) != NON_ITEM))
        {
            dungeon_terrain_changed(place, decor);
            success = true;
        }
    }

    if (success)
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                       "scenery: changed the scenery"), true);
        const string key = make_stringf("scenery %s", dungeon_feature_name(decor));
        god_speaks(GOD_XOM, _get_xom_speech(key).c_str());
    }
}

static void _xom_summon_butterflies()
{
    bool success = false;
    const int how_many = random_range(10, 20);

    for (int i = 0; i < how_many; ++i)
    {
        mgen_data mg(MONS_BUTTERFLY, BEH_FRIENDLY, you.pos(), MHITYOU,
                     MG_FORCE_BEH, GOD_XOM);
        mg.set_summoned(&you, MON_SUMM_AID, summ_dur(3));
        if (create_monster(mg))
            success = true;
    }

    if (success)
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                       "scenery: summon butterflies"), true);
        god_speaks(GOD_XOM, _get_xom_speech("scenery").c_str());
    }
}

// Mess with nearby terrain features, mostly harmlessly.
static void _xom_change_scenery(int /*sever*/)
{
    vector<coord_def> candidates = _xom_scenery_candidates();

    if (candidates.empty() || one_chance_in(6))
    {
        if (x_chance_in_y(2, 3))
            _xom_place_decor();
        else
            _xom_summon_butterflies();
        return;
    }

    int fountains_blood    = 0;
    int food_swapped       = 0;
    int trees_polymorphed  = 0;

    dungeon_feature_type wtree = random_choose_weighted(4, DNGN_DEMONIC_TREE,
                                                        1, DNGN_PETRIFIED_TREE);
    dungeon_feature_type btree = random_choose_weighted(1, DNGN_TREE,
                                                        3, DNGN_MANGROVE);

    for (coord_def pos : candidates)
    {
        switch (env.grid(pos))
        {
        case DNGN_DRY_FOUNTAIN:
        case DNGN_FOUNTAIN_BLUE:
        case DNGN_FOUNTAIN_SPARKLING:
            if (x_chance_in_y(fountains_blood, 3))
                continue;

            env.grid(pos) = DNGN_FOUNTAIN_BLOOD;
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                fountains_blood++;
            break;
        case DNGN_CACHE_OF_FRUIT:
        case DNGN_CACHE_OF_MEAT:
        case DNGN_CACHE_OF_BAKED_GOODS:
            if (x_chance_in_y(food_swapped, 3))
                continue;

            if (env.grid(pos) == DNGN_CACHE_OF_FRUIT)
                env.grid(pos) = DNGN_CACHE_OF_MEAT;
            else if (env.grid(pos) == DNGN_CACHE_OF_MEAT)
                env.grid(pos) = DNGN_CACHE_OF_BAKED_GOODS;
            else
                env.grid(pos) = DNGN_CACHE_OF_FRUIT;
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                food_swapped++;
            break;
        case DNGN_TREE:
        case DNGN_MANGROVE:
            if (x_chance_in_y(trees_polymorphed, 3))
                continue;

            env.grid(pos) = wtree;
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                trees_polymorphed++;
            break;
        case DNGN_DEMONIC_TREE:
        case DNGN_PETRIFIED_TREE:
            if (x_chance_in_y(trees_polymorphed, 3))
                continue;

            env.grid(pos) = btree;
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                trees_polymorphed++;
            break;
        default:
            break;
        }
    }

    if (!fountains_blood && !food_swapped && !trees_polymorphed)
        return;

    god_speaks(GOD_XOM, _get_xom_speech("scenery").c_str());

    vector<string> effects, terse;
    if (fountains_blood > 0)
    {
        string fountains = make_stringf(
                 "%s fountain%s start%s gushing blood",
                 fountains_blood == 1 ? "a" : "some",
                 fountains_blood == 1 ? ""  : "s",
                 fountains_blood == 1 ? "s" : "");

        if (effects.empty())
            fountains = uppercase_first(fountains);
        effects.push_back(fountains);
        terse.push_back(make_stringf("%d fountains blood", fountains_blood));
    }

    if (food_swapped > 0)
    {
        string snacks = "some nearby snacks are swapped around";

        if (effects.empty())
            snacks = uppercase_first(snacks);
        effects.push_back(snacks);
        terse.push_back(make_stringf("%d snacks swapped", food_swapped));
    }

    if (trees_polymorphed > 0)
    {
        string trees = "some trees are warped by chaos";
        if (effects.empty())
            trees = uppercase_first(trees);
        effects.push_back(trees);
        terse.push_back(make_stringf("%d trees warped", trees_polymorphed));
    }

    if (!effects.empty())
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, ("scenery: "
            + comma_separated_line(terse.begin(), terse.end(), ", ", ", ")).c_str()),
            true);
        mprf("%s!",
             comma_separated_line(effects.begin(), effects.end(),
                                  ", and ").c_str());
    }
}

static void _xom_open_and_close_doors(int /* sever */)
{
    vector<coord_def> candidates = _xom_door_candidates();

    if (candidates.empty())
        return;

    int doors_open      = 0;
    int doors_close     = 0;
    for (coord_def pos : candidates)
    {
        switch (env.grid(pos))
        {
        case DNGN_CLOSED_DOOR:
        case DNGN_CLOSED_CLEAR_DOOR:
        case DNGN_RUNED_DOOR:
        case DNGN_RUNED_CLEAR_DOOR:
            dgn_open_door(pos);
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                doors_open++;
            break;
        case DNGN_OPEN_DOOR:
        case DNGN_OPEN_CLEAR_DOOR:
            dgn_close_door(pos);
            set_terrain_changed(pos);
            if (you.see_cell(pos))
                doors_close++;
            break;
        default:
            break;
        }
    }
    if (!doors_open && !doors_close)
        return;

    god_speaks(GOD_XOM, _get_xom_speech("scenery").c_str());

    vector<string> effects, terse;

    if (doors_open > 0)
    {
        effects.push_back(make_stringf("%s door%s burst%s open",
                                       doors_open == 1 ? "A"    :
                                       doors_open == 2 ? "Two"
                                                       : "Several",
                                       doors_open == 1 ? ""  : "s",
                                       doors_open == 1 ? "s" : ""));
        terse.push_back(make_stringf("%d doors open", doors_open));
    }
    if (doors_close > 0)
    {
        string closed = make_stringf("%s%s door%s slam%s shut",
                 doors_close == 1 ? "a"    :
                 doors_close == 2 ? "two"
                                  : "several",
                 doors_open > 0   ? (doors_close == 1 ? "nother" : " other")
                                  : "",
                 doors_close == 1 ? ""  : "s",
                 doors_close == 1 ? "s" : "");
        if (effects.empty())
            closed = uppercase_first(closed);
        effects.push_back(closed);
        terse.push_back(make_stringf("%d doors close", doors_close));
    }
    if (!effects.empty())
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, ("scenery: "
            + comma_separated_line(terse.begin(), terse.end(), ", ", ", ")).c_str()),
            true);
        mprf("%s!",
             comma_separated_line(effects.begin(), effects.end(),
                                  ", and ").c_str());
    }

    if (doors_open || doors_close)
        noisy(10, you.pos());
}

/// Xom hurls liquid fireballs at your foes! Or, possibly, 'fireballs'.
static void _xom_destruction(int sever, bool real)
{
    bool rc = false;

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (mons_is_projectile(**mi)
            || mons_is_tentacle_or_tentacle_segment(mi->type)
            || one_chance_in(3))
        {
            continue;
        }

        // Skip adjacent monsters, and skip non-hostile monsters if not feeling nasty.
        if (real
            && (adjacent(you.pos(), mi->pos())
                || mi->wont_attack() && !_xom_feels_nasty()))
        {
            continue;
        }

        if (!real)
        {
            if (!rc)
                god_speaks(GOD_XOM, _get_xom_speech("fake destruction").c_str());
            rc = true;
            corona_monster(*mi, &you);
            continue;
        }

        int dice = 2 + div_rand_round(you.experience_level, 13);
        if (you.runes.count() > ZOT_ENTRY_RUNES + 1)
            dice += div_rand_round(you.runes.count(), ZOT_ENTRY_RUNES);

        bolt beam;

        beam.flavour      = BEAM_STICKY_FLAME;
        beam.glyph        = dchar_glyph(DCHAR_FIRED_BURST);
        beam.damage       = dice_def(dice, 4 + sever / 12);
        beam.target       = mi->pos();
        beam.name         = "sticky fireball";
        beam.colour       = RED;
        beam.thrower      = KILL_NON_ACTOR;
        beam.source_id    = MID_NOBODY;
        beam.aux_source   = "Xom's destruction";
        beam.ex_size      = 1;
        beam.is_explosion = true;

        // Only give this message once.
        if (!rc)
            god_speaks(GOD_XOM, _get_xom_speech("destruction").c_str());
        rc = true;

        beam.explode();
    }

    if (rc)
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                       real ? "destruction" : "fake destruction"), true);
    }
}

static void _xom_real_destruction(int sever) { _xom_destruction(sever, true); }
static void _xom_fake_destruction(int sever) { _xom_destruction(sever, false); }

// A crunched down copy of the scroll of butterflies knockback.
static void _xom_harmless_knockback(coord_def p)
{
    monster* mon = monster_at(p);
    if (mon)
    {
        const int dist = random_range(2, 3);
        mon->knockback(you, dist, 0, "hand of Xom");
        behaviour_event(mon, ME_ALERT, &you);
    }
}

// Knock back any nearby monsters without doing damage, then summon an
// increasing amount of living spell force lances to all rocket fire against
// whatever doesn't clear them away the next turn.
static void _xom_force_lances(int /* sever */)
{
    int xl = _xom_feels_nasty() ? you.experience_level / 3
                                : you.experience_level + you.runes.count() / 4;
    int count = 2 + (xl / 2) + random_range(0, div_rand_round(xl, 5));
    int strength = max(1, xl / 2);
    int created = 0;

    // Clear up space for summoning Force Lances, if possible.
    for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS, true); ri; ++ri)
        if (grid_distance(*ri, you.pos()) == 2)
            _xom_harmless_knockback(*ri);

    for (adjacent_iterator ai(you.pos()); ai; ++ai)
        _xom_harmless_knockback(*ai);

    for (int i = 0; i < count; ++i)
    {
        mgen_data mg(MONS_LIVING_SPELL, BEH_FRIENDLY, you.pos(),
                     MHITYOU, MG_FORCE_BEH | MG_FORCE_PLACE | MG_AUTOFOE, GOD_XOM);

        mg.set_summoned(&you, MON_SUMM_AID, summ_dur(2));
        mg.hd = strength;
        mg.props[CUSTOM_SPELL_LIST_KEY].get_vector().push_back(SPELL_FORCE_LANCE);
        mg.non_actor_summoner = "Xom";

        if (create_monster(mg))
            created++;
    }

    if (created > 0)
    {
        const string note = make_stringf("summons %d living force lance%s",
                                         created,
                                         created > 1 ? "s" : "");

        god_speaks(GOD_XOM,  _get_xom_speech("force lance fleet").c_str());
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
    else
        canned_msg(MSG_NOTHING_HAPPENS);
}

static void _xom_enchant_monster(int sever, bool helpful)
{
    vector<monster*> targetable;
    enchant_type ench;
    string ench_name = "";
    int xl = you.experience_level;
    int affected = 0;
    int cap = 0;
    int time = 0;

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (_choose_enchantable_monster(**mi))
            targetable.push_back(*mi);
    }

    if (helpful) // To the player, not the monster.
    {
        cap = 1 + div_rand_round(xl, 5);
        cap = random_range(1, cap);
        ench = random_choose_weighted(200 + xl * 4, ENCH_PETRIFYING,
                                      300 - xl * 5, ENCH_PARALYSIS,
                                      300 - xl * 5, ENCH_VITRIFIED,
                                      200 + xl * 4, ENCH_SLOW);
    }
    else
    {
        cap = 1 + div_rand_round(xl, 7);
        cap = random_range(1, cap);
        ench = random_choose_weighted(200 + xl * 4, ENCH_HASTE,
                                      300, ENCH_MIGHT,
                                      200 + xl * 2, ENCH_REGENERATION,
                                      300 - xl * 5, ENCH_RESISTANCE);
    }

    ench_name = description_for_ench(ench);

    if (ench == ENCH_PETRIFYING || ench == ENCH_PARALYSIS)
        time = 30 + random2(sever / 10);
    else if (ench == ENCH_VITRIFIED || ench == ENCH_SLOW)
        time = 200 + random2(sever);
    else if (ench == ENCH_HASTE || ench == ENCH_MIGHT)
        time = 400 + random2(sever * 4);
    else if (ench == ENCH_REGENERATION || ench == ENCH_RESISTANCE)
        time = 800 + random2(sever * 4);

    god_speaks(GOD_XOM,
               helpful ? _get_xom_speech("good enchant monster").c_str()
                       : _get_xom_speech("bad enchant monster").c_str());

    shuffle_array(targetable);

    for (monster *application : targetable)
    {
        if (affected == cap)
            break;

        mprf("%s suddenly %s %s!",
              application->name(DESC_THE).c_str(),
              (ench == ENCH_PETRIFYING || ench == ENCH_REGENERATION) ? "starts" : "looks",
              ench_name.c_str());

        application->add_ench(mon_enchant(ench, &you, time));
        affected++;
    }

    // Take a note.
    const string note = make_stringf("enchant monster%s (%s, %s)",
                                     affected >= 1 ? "s" : "",
                                     helpful ? "good" : "bad",
                                     ench_name.c_str());
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

static void _xom_good_enchant_monster(int sever)
{
    _xom_enchant_monster(sever, true);
}
static void _xom_bad_enchant_monster(int sever)
{
    _xom_enchant_monster(sever, false);
}

// Look for monsters sufficiently weak enough for Xom to buff.
static vector<monster*> _xom_find_weak_monsters(bool range)
{
    vector<monster*> targetable;
    int runes = (you.runes.count() > ZOT_ENTRY_RUNES) ?
                    div_rand_round(you.runes.count(), ZOT_ENTRY_RUNES) : 0;
    int maximum_hd = 3 + you.experience_level * 7 / 20 + runes;

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        // No counting battlespheres or orbs of destruction. Try not to buff
        // the same target multiple times by checking the most prominent ones.
        // Fuzz the HD range to make it harder to deliberately plan around.
        if (mons_attitude(**mi) == ATT_FRIENDLY
            && !mi->is_peripheral()
            && !(mi->has_ench(ENCH_HASTE) && mi->has_ench(ENCH_INVIS)
                 && mi->has_ench(ENCH_EMPOWERED_SPELLS) && mi->has_ench(ENCH_MIGHT))
            && mi->get_hit_dice() < maximum_hd + (range ? random_range(-2, 1) : 0))
        {
            targetable.push_back(*mi);
        }
    }

    return targetable;
}

// Throw nearly every single monster buff in the game on a random ally in sight.
// Xom will only buff very low HD monsters this way, and will summon weaklings
// if you don't have anything weak enough to get a buff.
static void _xom_hyper_enchant_monster(int sever)
{
    vector<enchant_type> buff_list { ENCH_MIGHT, ENCH_HASTE, ENCH_INVIS,
                                     ENCH_EMPOWERED_SPELLS, ENCH_DEFLECT_MISSILES,
                                     ENCH_RESISTANCE, ENCH_REGENERATION,
                                     ENCH_STRONG_WILLED, ENCH_TOXIC_RADIANCE,
                                     ENCH_DOUBLED_VIGOUR, ENCH_MIRROR_DAMAGE,
                                     ENCH_SWIFT };
    vector<monster*> targetable = _xom_find_weak_monsters(true);
    int time = random_range(200, 200 + sever * 2);
    int xl = you.experience_level;
    int good_god = you_worship(GOD_ELYVILON) || you_worship(GOD_ZIN) ||
                   you_worship(GOD_SHINING_ONE);
    int buff_count = 0;

    if (targetable.empty())
    {
        monster_type mon_type;

        // Mostly more mundane choices than usual Xom summons.
        if (xl < 7)
        {
            mon_type = (good_god || one_chance_in(4)) ? MONS_IGUANA
                                                      : MONS_CERULEAN_IMP;
        }
        else if (xl < 14 + random_range(-1, 1))
        {
            mon_type = (good_god || one_chance_in(4)) ? MONS_BLACK_BEAR
                                                      : MONS_HELL_RAT;
        }
        else if (xl < 21 + random_range(-1, 1))
        {
            mon_type = (good_god || one_chance_in(4)) ? MONS_WYVERN
                                                      : MONS_HELL_HOUND;
        }
        else
        {
            mon_type = (good_god || one_chance_in(3)) ? MONS_ELEPHANT
                                                      : MONS_TOENAIL_GOLEM;
        }

        mgen_data mg(mon_type, BEH_FRIENDLY, you.pos(),
                    MHITYOU, MG_FORCE_BEH | MG_FORCE_PLACE, GOD_XOM);
        mg.set_summoned(&you, MON_SUMM_AID, summ_dur(3));
        mg.non_actor_summoner = "Xom";
        monster* mon = create_monster(mg);

        if (mon)
        {
            targetable.insert(targetable.begin(), mon);
            string summ = make_stringf("%s pulls itself out of thin air.",
                                        targetable[0]->name(DESC_A, true).c_str());
            god_speaks(GOD_XOM, summ.c_str());
        }
    }
    else
    {
        shuffle_array(targetable);

        if (_xom_feels_nasty())
        {
            sort(targetable.begin(), targetable.end(),
            [](const monster* a, const monster* b)
            {return a->get_hit_dice() < b->get_hit_dice();});
        }
    }

    if (!targetable.empty())
    {
        string lines = "";

        for (enchant_type apply : buff_list)
        {
            string ench_name = description_for_ench(apply).c_str();

            // Avoid repeats or completely useless effects.
            if ((targetable[0]->has_ench(apply)
                || apply == ENCH_MIGHT && !mons_has_attacks(*(targetable[0])))
                || (apply == ENCH_EMPOWERED_SPELLS && !targetable[0]->is_actual_spellcaster())
                || (apply == ENCH_SWIFT && targetable[0]->is_stationary())
                || (apply == ENCH_STRONG_WILLED && targetable[0]->willpower() == WILL_INVULN))
            {
                continue;
            }

            if (apply == ENCH_DEFLECT_MISSILES || apply == ENCH_REGENERATION
                || apply == ENCH_TOXIC_RADIANCE || apply == ENCH_MIRROR_DAMAGE
                || apply == ENCH_SWIFT)
            {
                lines += make_stringf("starts %s, ", ench_name.c_str());
            }
            else if (apply == ENCH_EMPOWERED_SPELLS)
                lines += make_stringf("has its spells empowered, ");
            else
                lines += make_stringf("looks %s, ", ench_name.c_str());

            targetable[0]->add_ench(mon_enchant(apply, nullptr, time));
            buff_count++;
        }

    if (buff_count > 0)
    {
        if (targetable[0]->hit_points < targetable[0]->max_hit_points)
        {
            targetable[0]->heal(targetable[0]->max_hit_points);
            lines += make_stringf("is healed, ");
        }

        god_speaks(GOD_XOM, _get_xom_speech("good hyper enchant monster").c_str());

        // Rather than figuring out sentence structure from the above list,
        // just staple on a line from casting Cantrip onto the end instead.
        mprf("%s suddenly %sand looks braver for a moment!",
              targetable[0]->name(DESC_THE, true).c_str(), lines.c_str());
    }

    const string note = make_stringf("buffed friendly %s %d %s",
                                     targetable[0]->name(DESC_PLAIN, true).c_str(),
                                     buff_count, buff_count == 1 ? "time" : "times" );
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
    }
}

static void _xom_mass_charm(int sever)
{
    vector<monster*> targetable;
    int affected = 0;
    int iters = 0;
    int hd_target = 0;
    int target_count = 0;
    int time = 500 + random2(sever);

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        // While Xom won't care, other gods of blasphemer chaos knights might.
        if (!god_hates_monster(**mi) && _choose_enchantable_monster(**mi))
        {
            targetable.push_back(*mi);
            hd_target += mi->get_hit_dice();
            target_count++;
        }
    }

    hd_target /= max(1, target_count);
    shuffle_array(targetable);

    god_speaks(GOD_XOM, _get_xom_speech("mass charm").c_str());

    for (monster *application : targetable)
    {
        // Always guarantee one is affected and one is not affected, regardless
        // of HD. Otherwise, mostly try to get the weaker half.
        if (iters == 0 || (iters > 1 && affected <= target_count / 2
            && application->get_hit_dice() + random_range(-1, 1) <= hd_target))
        {
            simple_monster_message(*application, " is charmed.");
            application->add_ench(mon_enchant(ENCH_CHARM, &you, time));
            affected++;
        }

        iters++;
    }

    const string note = make_stringf("charmed %d monster%s",
                                     affected,  affected != 1 ? "s" : "");
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// Xom makes some scary skeletons pop out.
// This halves enemy willpower, drains them, and fears them.
static void _xom_wave_of_despair(int sever)
{
    int skeleton_count = 0;
    god_speaks(GOD_XOM, _get_xom_speech("wave of despair").c_str());

    // As is done in wiz-item.cc L#154, apparently the simplest way we have for
    // making decorative skeletons is to make a monster and then kill it. Sure.
    for (distance_iterator di(you.pos(), true, true, 2); di; ++di)
    {
        if (!monster_at(*di) && !cell_is_solid(*di)
            && env.grid(*di) != DNGN_ORB_DAIS)
        {
            monster dummy;
            dummy.type = MONS_HUMAN; // maybe random floor monsters? player genus?
            dummy.position = *di;

            item_def* corpse = place_monster_corpse(dummy, true);
            if (corpse)
            {
                turn_corpse_into_skeleton(*corpse);
                skeleton_count++;
            }
        }
    }

    if (skeleton_count)
        mpr("Skeletons, inanimate yet cursed, drop down from the ceiling.");

    draw_ring_animation(you.pos(), you.current_vision, DARKGRAY, MAGENTA, true, 35);
    mprf(MSGCH_DANGER, "A draining tide of despair and horror washes over you and your surroundings!");

    const int pow = 50 + random_range(sever / 2, sever);

    for (radius_iterator ri(you.pos(), LOS_NO_TRANS); ri; ++ri)
    {
        if (monster* mon = monster_at(*ri))
        {
            mon->strip_willpower(&you, pow, true);

            if (mon->holiness() & (MH_NATURAL | MH_PLANT))
                mon->add_ench(mon_enchant(ENCH_DRAINED, &you, pow, 2));

            if (!mon->wont_attack())
                behaviour_event(mon, ME_ANNOY, &you);
        }
    }

    you.strip_willpower(&you, pow, true);
    mass_enchantment(ENCH_FEAR, pow * 5);

    const string note = make_stringf("spooky wave of despair");
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// Xom hastes, slows, or paralyzes the player and everything else in sight
// for the same length of time (give or take time slices and base speed).
// Mostly screws with whatever else might join the fight afterwards,
// ally creation, and also with damage-over-time effects.
static void _xom_time_control(int sever)
{
    duration_type dur;
    enchant_type ench;
    string xomline;
    string message;
    string note;
    int time;
    bool bad = true;

    if (x_chance_in_y(1, 3))
    {
        dur = DUR_HASTE;
        ench = ENCH_HASTE;
        xomline = "fast forward";
        if (you.stasis())
        {
            message = "Your stasis prevents you from being hasted,"
                      " but everything else in sight speeds up!";
            note = "hasted everything in sight";
        }
        else
        {
            message = "You and everything else in sight speed up!";
            note = "hasted player and everything else in sight";
        }
        time = random_range(100, 200) + sever / 3;
    }
    else if (coinflip())
    {
        dur = DUR_SLOW;
        ench = ENCH_SLOW;
        xomline = "slow motion";
        if (you.stasis())
        {
            message = "Your stasis prevents you from being slowed,"
                      " but everything else in sight slows down!";
            note = "slowed everything in sight";
            bad = false;
        }
        else
        {
            message = "You and everything else in sight slow down!";
            note = "slowed player and everything else";
        }
        time = random_range(100, 200) + sever / 3;
    }
    else
    {
        dur = DUR_PARALYSIS;
        ench = ENCH_PARALYSIS;
        xomline = "pause";
        if (you.stasis())
        {
            message = "Your stasis prevents you from being paralysed,"
                      " but everything else in sight stops moving!";
            note = "paralysed everything in sight";
            bad = false;
        }
        else
        {
            message = "You and everything else in sight suddenly stop moving!";
            note = "paralysed player and everything else";

            // Less of a decent joke if it directly kills, so.
            const auto pos = you.pos();
            if (cloud_at(pos) && !is_harmless_cloud(cloud_at(pos)->type))
                delete_cloud(pos);
        }
        time = random_range(30, 50);
    }

    god_speaks(GOD_XOM, _get_xom_speech(xomline).c_str());

    mprf(bad ? MSGCH_WARN : MSGCH_GOD, "%s", message.c_str());

    if (!you.stasis())
        you.increase_duration(dur, time / 10);

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if ((!mons_has_attacks(**mi) && ench != ENCH_PARALYSIS) || mi->stasis())
            continue;

        mi->add_ench(mon_enchant(ench, &you, time));
    }

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

/// Toss some fog around the player. Helping...?
static void _xom_fog(int /*sever*/)
{
    big_cloud(CLOUD_RANDOM_SMOKE, &you, you.pos(), 50, 8 + random2(8));
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "fog"), true);
    god_speaks(GOD_XOM, _get_xom_speech("cloud").c_str());
}

static item_def* _xom_get_random_worn_slot_item(equipment_slot item_slot)
{
    vector<item_def*> worn_slot_item = you.equipment.get_slot_items(item_slot);

    if (worn_slot_item.empty())
        return nullptr;

    return worn_slot_item[random2(worn_slot_item.size())];
}

static void _xom_pseudo_miscast(int /*sever*/)
{
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "silly message"), true);
    god_speaks(GOD_XOM, _get_xom_speech("zero miscast effect").c_str());

    vector<string> messages;
    vector<string> priority;

    vector<item_def *> inv_items;
    for (auto &item : you.inv)
    {
        if (item.defined() && !item_is_equipped(item))
            inv_items.push_back(&item);
    }

    // Assure that the messages vector has at least one element.
    messages.emplace_back("Nothing appears to happen... Ominous!");

    ///////////////////////////////////
    // Dungeon feature dependent stuff.

    vector<dungeon_feature_type> in_view;
    vector<string> in_view_name;

    for (radius_iterator ri(you.pos(), LOS_DEFAULT); ri; ++ri)
    {
        const dungeon_feature_type feat = env.grid(*ri);
        const string feat_name = feature_description_at(*ri, false,
                                                        DESC_THE);
        in_view.push_back(feat);
        in_view_name.push_back(feat_name);
    }

    for (size_t iv = 0; iv < in_view.size(); ++iv)
    {
        string str;

        if (in_view[iv] == DNGN_LAVA)
            str = _get_xom_speech("feature lava");
        else if (in_view[iv] == DNGN_SHALLOW_WATER
                 || in_view[iv] == DNGN_FOUNTAIN_BLUE
                 || in_view[iv] == DNGN_FOUNTAIN_SPARKLING)
        {
            str = _get_xom_speech("feature shallow water");
        }
        else if (in_view[iv] == DNGN_DEEP_WATER)
            str = _get_xom_speech("feature deep water");
        else if (in_view[iv] == DNGN_FOUNTAIN_BLOOD)
            str = _get_xom_speech("feature blood");
        else if (in_view[iv] == DNGN_FOUNTAIN_EYES)
            str = _get_xom_speech("feature eyes");
        else if (in_view[iv] == DNGN_DRY_FOUNTAIN)
            str = _get_xom_speech("feature dry");
        else if (feat_is_statuelike(in_view[iv]))
            str = _get_xom_speech("feature statuelike");
        else if (feat_is_tree(in_view[iv]))
            str = _get_xom_speech("feature tree");
        else if (in_view[iv] == DNGN_CLEAR_ROCK_WALL
                 || in_view[iv] == DNGN_CLEAR_STONE_WALL
                 || in_view[iv] == DNGN_CLEAR_PERMAROCK_WALL
                 || in_view[iv] == DNGN_CRYSTAL_WALL)
        {
            str = _get_xom_speech("feature translucent wall");
        }
        else if (in_view[iv] == DNGN_METAL_WALL)
            str = _get_xom_speech("feature metal wall");
        else if (in_view[iv] == DNGN_STONE_ARCH)
            str = _get_xom_speech("feature stone arch");

        if (!str.empty())
        {
            str = replace_all(str, "@the_feature@", in_view_name[iv]);
            str = replace_all(str, "@The_feature@",
                              uppercase_first(in_view_name[iv]));

            // For name-related bits in graffiti.
            str = do_mon_name_replacements(str);

            messages.push_back(str);
        }
    }

    const dungeon_feature_type feat = env.grid(you.pos());

    if (!feat_is_solid(feat) && feat_stair_direction(feat) == CMD_NO_CMD
        && !feat_is_trap(feat) && feat != DNGN_STONE_ARCH
        && !feat_is_open_door(feat) && feat != DNGN_ABANDONED_SHOP)
    {
        const string feat_name = feature_description_at(you.pos(), false,
                                                        DESC_THE);
        string str;

        if (you.airborne())
        {
            str = _get_xom_speech(
                      feat_is_water(feat) ? "underfoot airborne water"
                                          : "underfoot airborne general");
        }
        else
        {
            str = _get_xom_speech(
                      feat_is_water(feat) ? "underfoot water"
                                          : "underfoot general");
        }

        str = replace_all(str, "@the_feature@", feat_name);
        str = replace_all(str, "@The_feature@", uppercase_first(feat_name));

        // Don't put airborne messages into the priority vector for
        // anyone who can fly a lot.
        if (you.racial_permanent_flight())
            messages.push_back(str);
        else
            priority.push_back(str);
    }

    if (!inv_items.empty())
    {
        const item_def &item = **random_iterator(inv_items);
        string name = item.name(DESC_YOUR, false, false, false);
        string str;

        if (feat_has_solid_floor(feat))
        {
            str = _get_xom_speech(
                      item.quantity == 1 ? "floor inventory singular"
                                         : "floor inventory plural");
        }
        else
            str = _get_xom_speech(
                      item.quantity == 1 ? "inventory singular"
                                         : "inventory plural");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        messages.push_back(str);
    }

    //////////////////////////////////////////////
    // Body, player species, transformations, etc.

    if (get_form()->flesh_equivalent.empty()
        && starts_with(species::skin_name(you.species), "bandage")
        && you_can_wear(SLOT_BODY_ARMOUR, true) != false)
    {
        string str = _get_xom_speech(
                (!you.airborne() && !you.swimming()) ? "floor bandages"
                                                     : "bandages");
        messages.push_back(str);
    }

    if (player_has_ears())
    {
        string str = _get_xom_speech("ears");
        messages.push_back(str);
    }

    {
        string str = _get_xom_speech(
                you.get_mutation_level(MUT_MISSING_EYE) ? "one eye"
                                                        : "eyes");
        messages.push_back(str);
    }

    {
        string str = _get_xom_speech("mouth");
        messages.push_back(str);
    }

    if (player_has_hair())
    {
        string str = _get_xom_speech("hair");
        messages.push_back(str);
    }

    if (player_has_feet() && !you.airborne() && !you.cannot_act())
    {
        string str = _get_xom_speech("impromptu dance");

        str = replace_all(str, "@hand@", you.hand_name(false));
        str = replace_all(str, "@hands@", you.hand_name(true));

        str = replace_all(str, "@foot@", you.foot_name(false));
        str = replace_all(str, "@feet@", you.foot_name(true));

        messages.push_back(str);
    }

    if (you.has_tail())
    {
        string str = _get_xom_speech("tail");
        messages.push_back(str);
    }

    {
        string str = _get_xom_speech("random body part singular");

        str = replace_all(str, "@random_body_part_any_singular@",
                          random_body_part_name(false, BPART_ANY));
        str = replace_all(str, "@random_body_part_internal_singular@",
                          random_body_part_name(false, BPART_INTERNAL));
        str = replace_all(str, "@random_body_part_external_singular@",
                          random_body_part_name(false, BPART_EXTERNAL));

        messages.push_back(str);
    }

    {
        string str = _get_xom_speech("random body part plural");

        str = replace_all(str, "@random_body_part_any_plural@",
                          random_body_part_name(true, BPART_ANY));
        str = replace_all(str, "@random_body_part_internal_plural@",
                          random_body_part_name(true, BPART_INTERNAL));
        str = replace_all(str, "@random_body_part_external_plural@",
                          random_body_part_name(true, BPART_EXTERNAL));

        messages.push_back(str);
    }

    ///////////////////////////
    // Equipment related stuff.

    if (you_can_wear(SLOT_WEAPON, true) != false && !you.weapon())
    {
        const bool one_handed = you.equipment.get_first_slot_item(SLOT_OFFHAND)
                                || you.get_mutation_level(MUT_MISSING_HAND);
        string str = _get_xom_speech(one_handed ? "unarmed one hand"
                                                : "unarmed two hands");

        str = replace_all(str, "@hand@", you.hand_name(false));
        str = replace_all(str, "@hands@", you.hand_name(true));

        messages.push_back(str);
    }

    if (item_def* item = you.equipment.get_first_slot_item(SLOT_OFFHAND))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("offhand slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        messages.push_back(str);
    }

    if (item_def* item = _xom_get_random_worn_slot_item(SLOT_CLOAK))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("cloak slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        // XXX: The formless mutation doesn't technically mean you don't have a
        // form; it means you don't have a head.
        str = replace_all(str, "@head@",
                          you.has_mutation(MUT_FORMLESS) ? "form" : "head");

        messages.push_back(str);
    }

    if (item_def* item = _xom_get_random_worn_slot_item(SLOT_HELMET))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("helmet slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        // XXX: The formless mutation doesn't technically mean you don't have a
        // form; it means you don't have a head.
        str = replace_all(str, "@head@",
                          you.has_mutation(MUT_FORMLESS) ? "form" : "head");

        messages.push_back(str);
    }

    if (item_def* item = _xom_get_random_worn_slot_item(SLOT_GLOVES))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("gloves slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        messages.push_back(str);
    }

    if (item_def* item = _xom_get_random_worn_slot_item(SLOT_LOWER_BODY))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("boots slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        messages.push_back(str);
    }

    if (item_def* item = you.equipment.get_first_slot_item(SLOT_AMULET))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("amulet slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        // XXX: The formless mutation doesn't technically mean you don't have a
        // form; it means you don't have a head.
        str = replace_all(str, "@head@",
                          you.has_mutation(MUT_FORMLESS) ? "form" : "head");

        messages.push_back(str);
    }

    if (item_def* item = you.equipment.get_first_slot_item(SLOT_GIZMO))
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str = _get_xom_speech("gizmo slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        messages.push_back(str);
    }

    if (item_def* item = _xom_get_random_worn_slot_item(SLOT_RING))
    {
        // Don't just say "your ring" here. We want to know which one.
        string name = "your " + item->name(DESC_QUALNAME, false, false, false);
        string str = _get_xom_speech("ring slot");

        str = replace_all(str, "@your_item@", name);
        str = replace_all(str, "@Your_item@", uppercase_first(name));

        string ring_holder_singular;
        string ring_holder_plural;

        ring_holder_singular = you.hand_name(false);
        ring_holder_plural = you.hand_name(true);

        str = replace_all(str, "@hand@", ring_holder_singular);
        str = replace_all(str, "@hands@", ring_holder_plural);

        messages.push_back(str);
    }

    if (item_def* item = you.body_armour())
    {
        string name = "your " + item->name(DESC_BASENAME, false, false, false);
        string str;

        if (name.find("dragon") != string::npos)
            str = _get_xom_speech("dragon armour");
        else if (item->sub_type == ARM_ANIMAL_SKIN)
            str = _get_xom_speech("animal skin");
        else if (item->sub_type == ARM_LEATHER_ARMOUR)
            str = _get_xom_speech("leather armour");
        else if (item->sub_type == ARM_ROBE)
            str = _get_xom_speech("robe");
        else if (item->sub_type >= ARM_RING_MAIL
                 && item->sub_type <= ARM_PLATE_ARMOUR)
        {
            str = _get_xom_speech("metal armour");
        }

        if (!str.empty())
        {
            str = replace_all(str, "@your_item@", name);
            str = replace_all(str, "@Your_item@", uppercase_first(name));

            messages.push_back(str);
        }
    }

    string str;

    if (!priority.empty() && coinflip())
        str = priority[random2(priority.size())];
    else
        str = messages[random2(messages.size())];

    str = maybe_pick_random_substring(str);
    mpr(str);
}

static void _xom_chaos_upgrade(int /*sever*/)
{
    monster* mon = choose_random_nearby_monster(_choose_chaos_upgrade);

    if (!mon)
        return;

    god_speaks(GOD_XOM, _get_xom_speech("chaos upgrade").c_str());

    mon_inv_type slots[] = {MSLOT_WEAPON, MSLOT_ALT_WEAPON, MSLOT_MISSILE};

    bool rc = false;
    for (int i = 0; i < 3 && !rc; ++i)
    {
        item_def* const item = mon->mslot_item(slots[i]);
        if (item && _is_chaos_upgradeable(*item))
        {
            _do_chaos_upgrade(*item, mon);
            rc = true;
        }
    }
    ASSERT(rc);

    // Wake the monster up.
    behaviour_event(mon, ME_ALERT, &you);

    if (rc)
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "chaos upgrade"), true);
}

static void _xom_player_confusion_effect(int sever)
{
    const bool conf = you.confused();
    const int dur = random_range(5, 7);

    if (!confuse_player(dur, true))
        return;

    if (you.can_drink())
    {
        god_speaks(GOD_XOM, _get_xom_speech("confusion").c_str());
        mprf(MSGCH_WARN, "You are %sconfused.", conf ? "more " : "");
    }
    else
    {
        // Since this is very mean if one can't cure it, we might as well
        // fit in another joke simultaneously.
        const bool was_mighty = you.duration[DUR_MIGHT];
        you.increase_duration(DUR_MIGHT, dur);
        god_speaks(GOD_XOM, _get_xom_speech("drinkless confusion").c_str());
        mprf(MSGCH_WARN, "You feel %s and %sconfused.",
            was_mighty ? "mightier" : "very mighty", conf ? "more " : "");
    }

    // At higher severities, Xom is less likely to confuse surrounding
    // creatures. Raise the threshold if you're unable to cure it.
    bool mons_too = false;
    if ((!you.can_drink() && random2(sever) < 60) || random2(sever) < 30)
    {
        for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
        {
            if ((!you.can_drink() && random2(sever) > 60) || random2(sever) > 30)
                continue;
            _confuse_monster(*mi, dur);
            mons_too = true;
        }
    }

    // Take a note.
    string conf_msg = "confusion";
    if (mons_too)
        conf_msg += " (+ monsters)";
    if (!you.can_drink())
        conf_msg += " (+ might)";
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, conf_msg), true);
}

static bool _valid_floor_grid(coord_def pos)
{
    if (!in_bounds(pos))
        return false;

    return env.grid(pos) == DNGN_FLOOR;
}

bool move_stair(coord_def stair_pos, bool away, bool allow_under)
{
    if (!allow_under)
        ASSERT(stair_pos != you.pos());

    dungeon_feature_type feat = env.grid(stair_pos);
    ASSERT(feat_stair_direction(feat) != CMD_NO_CMD);

    coord_def begin, towards;

    bool stairs_moved = false;
    if (away)
    {
        // If the staircase starts out under the player, first shove it
        // onto a neighbouring grid.
        if (allow_under && stair_pos == you.pos())
        {
            coord_def new_pos(stair_pos);
            // Loop twice through all adjacent grids. In the first round,
            // only consider grids whose next neighbour in the direction
            // away from the player is also of type floor. If we didn't
            // find any matching grid, try again without that restriction.
            for (int tries = 0; tries < 2; ++tries)
            {
                int adj_count = 0;
                for (adjacent_iterator ai(stair_pos); ai; ++ai)
                    if (env.grid(*ai) == DNGN_FLOOR
                        && (tries || _valid_floor_grid(*ai + *ai - stair_pos))
                        && one_chance_in(++adj_count))
                    {
                        new_pos = *ai;
                    }

                if (!tries && new_pos != stair_pos)
                    break;
            }

            if (new_pos == stair_pos)
                return false;

            if (!slide_feature_over(stair_pos, new_pos, true))
                return false;

            stair_pos = new_pos;
            stairs_moved = true;
        }

        begin   = you.pos();
        towards = stair_pos;
    }
    else
    {
        // Can't move towards player if it's already adjacent.
        if (adjacent(you.pos(), stair_pos))
            return false;

        begin   = stair_pos;
        towards = you.pos();
    }

    ray_def ray;
    if (!find_ray(begin, towards, ray, opc_solid_see))
    {
        mprf(MSGCH_ERROR, "Couldn't find ray between player and stairs.");
        return stairs_moved;
    }

    // Don't start off under the player.
    if (away)
        ray.advance();

    bool found_stairs = false;
    int  past_stairs  = 0;
    while (in_bounds(ray.pos()) && you.see_cell(ray.pos())
           && !cell_is_solid(ray.pos()) && ray.pos() != you.pos())
    {
        if (ray.pos() == stair_pos)
            found_stairs = true;
        if (found_stairs)
            past_stairs++;
        ray.advance();
    }
    past_stairs--;

    if (!away && cell_is_solid(ray.pos()))
    {
        // Transparent wall between stair and player.
        return stairs_moved;
    }

    if (away && !found_stairs)
    {
        if (cell_is_solid(ray.pos()))
        {
            // Transparent wall between stair and player.
            return stairs_moved;
        }

        mprf(MSGCH_ERROR, "Ray didn't cross stairs.");
    }

    if (away && past_stairs <= 0)
    {
        // Stairs already at edge, can't move further away.
        return stairs_moved;
    }

    if (!in_bounds(ray.pos()) || ray.pos() == you.pos())
        ray.regress();

    while (!you.see_cell(ray.pos()) || env.grid(ray.pos()) != DNGN_FLOOR)
    {
        ray.regress();
        if (!in_bounds(ray.pos()) || ray.pos() == you.pos()
            || ray.pos() == stair_pos)
        {
            // No squares in path are a plain floor.
            return stairs_moved;
        }
    }

    ASSERT(stair_pos != ray.pos());

    string stair_str = feature_description_at(stair_pos, false, DESC_THE);

    mprf("%s slides %s you!", stair_str.c_str(),
         away ? "away from" : "towards");

    // Animate stair moving.
    const feature_def &feat_def = get_feature_def(feat);

    bolt beam;

    beam.range   = INFINITE_DISTANCE;
    beam.flavour = BEAM_VISUAL;
    beam.glyph   = feat_def.symbol();
    beam.colour  = feat_def.colour();
    beam.source  = stair_pos;
    beam.target  = ray.pos();
    beam.name    = "STAIR BEAM";
    beam.draw_delay = 50; // Make beam animation slower than normal.

    beam.aimed_at_spot = true;
    beam.fire();

    // Clear out "missile trails"
    viewwindow();
    update_screen();

    if (!swap_features(stair_pos, ray.pos(), false, false))
    {
        mprf(MSGCH_ERROR, "_move_stair(): failed to move %s",
             stair_str.c_str());
        return stairs_moved;
    }

    return true;
}

static vector<coord_def> _nearby_stairs()
{
    vector<coord_def> stairs_avail;
    for (radius_iterator ri(you.pos(), LOS_RADIUS, C_SQUARE); ri; ++ri)
    {
        if (!cell_see_cell(you.pos(), *ri, LOS_SOLID_SEE))
            continue;

        dungeon_feature_type feat = env.grid(*ri);
        if (feat_stair_direction(feat) != CMD_NO_CMD
            && feat != DNGN_ENTER_SHOP)
        {
            stairs_avail.push_back(*ri);
        }
    }

    return stairs_avail;
}

static void _xom_repel_stairs(bool unclimbable)
{
    vector<coord_def> stairs_avail  = _nearby_stairs();

    // Only works if there are stairs in view.
    if (stairs_avail.empty())
        return;

    bool real_stairs = false;
    for (auto loc : stairs_avail)
        if (feat_is_staircase(env.grid(loc)))
            real_stairs = true;

    // Don't mention staircases if there aren't any nearby.
    string stair_msg = _get_xom_speech("repel stairs");
    string feat_name;

    if (!real_stairs)
    {
        feat_name =
            feat_is_escape_hatch(env.grid(stairs_avail[0])) ? "escape hatch"
                                                            : "gate";
    }
    else
        feat_name = "staircase";

    stair_msg = replace_all(stair_msg, "@staircase@", feat_name);

    god_speaks(GOD_XOM, stair_msg.c_str());

    you.duration[DUR_REPEL_STAIRS_MOVE] = 1000; // 100 turns
    if (unclimbable)
        you.duration[DUR_REPEL_STAIRS_CLIMB] = 500; // 50 turns

    shuffle_array(stairs_avail);
    int count_moved = 0;
    for (coord_def stair : stairs_avail)
        if (move_stair(stair, true, true))
            count_moved++;

    if (!count_moved)
    {
        if (one_chance_in(8))
            mpr("Nothing appears to happen... Ominous!");
        else
            canned_msg(MSG_NOTHING_HAPPENS);
    }
    else
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "repel stairs"), true);
}

static void _xom_moving_stairs(int) { _xom_repel_stairs(false); }
static void _xom_unclimbable_stairs(int) { _xom_repel_stairs(true); }

static void _xom_cloud_trail(int /*sever*/)
{
    you.duration[DUR_CLOUD_TRAIL] = random_range(600, 1200);
    // 80% chance of a useful trail
    cloud_type ctype = random_choose_weighted(20, CLOUD_CHAOS,
                                              9,  CLOUD_MAGIC_TRAIL,
                                              5,  CLOUD_MIASMA,
                                              5,  CLOUD_PETRIFY,
                                              5,  CLOUD_MUTAGENIC,
                                              4,  CLOUD_MISERY,
                                              1,  CLOUD_SALT,
                                              1,  CLOUD_BLASTMOTES);

    bool suppressed = false;
    if (you_worship(GOD_ZIN) && (ctype == CLOUD_CHAOS || ctype == CLOUD_MUTAGENIC))
        suppressed = true;
    else if (is_good_god(you.religion) && (ctype == CLOUD_MIASMA || ctype == CLOUD_MISERY))
        suppressed = true;

    if (suppressed)
        ctype = CLOUD_SALT;

    you.props[XOM_CLOUD_TRAIL_TYPE_KEY] = ctype;

    // Need to explicitly set as non-zero. Use a clean half of the power cap.
    if (you.props[XOM_CLOUD_TRAIL_TYPE_KEY].get_int() == CLOUD_BLASTMOTES)
        you.props[BLASTMOTE_POWER_KEY] = 25;

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "cloud trail"), true);

    const string speech = _get_xom_speech("cloud trail");
    god_speaks(GOD_XOM, speech.c_str());

    if (suppressed)
        simple_god_message(" purifies the foul vapours!");
}

static void _xom_draining(int /*sever*/)
{
    int power = 100;
    const string speech = _get_xom_speech("suffering");
    god_speaks(GOD_XOM, speech.c_str());

    if (you.experience_level < 4
        || (you.hp_max_adj_temp < 0 && !_xom_feels_nasty()))
    {
        power /= 2;
    }

    drain_player(power, true);

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "draining"), true);
}

static void _xom_doom(int /*sever*/)
{
    int power = random_range(15, 25);
    const string speech = _get_xom_speech("suffering");
    god_speaks(GOD_XOM, speech.c_str());

    if (you.experience_level < 9
        || (you.attribute[ATTR_DOOM] > 50 && !_xom_feels_nasty()))
    {
        power /= 2;
    }

    if (!(you.attribute[ATTR_DOOM] + power >= 100))
        mpr("Your doom draws closer.");

    you.doom(power);

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "inflicting Doom"), true);
}

static void _xom_torment(int /*sever*/)
{
    if (_xom_feels_nasty())
    {
        god_speaks(GOD_XOM, _get_xom_speech("draining or torment").c_str());
        torment_player(0, TORMENT_XOM);
    }
    else
    {
        god_speaks(GOD_XOM, _get_xom_speech("torment all").c_str());
        torment(nullptr, TORMENT_XOM, you.pos());
    }

    const string note = make_stringf("torment%s(%d/%d hp)",
                                      _xom_feels_nasty() ? " all (player " : " (",
                                      you.hp, you.hp_max);
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

static monster* _xom_summon_hostile(monster_type hostile)
{
    // Fuzz the monster's placement.
    int placeable_count = 0;
    int distance = you.penance[GOD_XOM] ? 5 : 3;
    coord_def spot = you.pos();

    for (radius_iterator ri(you.pos(), distance, C_SQUARE, LOS_NO_TRANS, true);
             ri; ++ri)
    {
        if ((!feat_has_solid_floor(env.grid(*ri))) || cell_is_solid(*ri)
            || actor_at(*ri) || grid_distance(*ri, you.pos()) <= 1)
        {
            continue;
        }

        if (one_chance_in(++placeable_count))
            spot = *ri;
    }

    monster* mon = create_monster(mgen_data::hostile_at(hostile, true, spot, GOD_XOM)
                          .set_summoned(nullptr, MON_SUMM_WRATH, summ_dur(4))
                          .set_non_actor_summoner("Xom"));

    // To prevent high-stealth players from just ducking around a corner
    // and losing some chunk of hostile summons, give them a helping hand.
    if (mon)
    {
        mon->target = you.pos();
        mon->foe = MHITYOU;
        mon->behaviour = BEH_SEEK;

        if (mon->type == MONS_REAPER)
            _do_chaos_upgrade(*mon->weapon(), mon);
    }

    return mon;
}

static void _xom_summon_hostiles(int sever)
{
    int strengthRoll = random2(1000 - (MAX_PIETY- sever) * 5);
    int num_summoned = 0;
    const bool shadow_creatures = one_chance_in(4);

    if (shadow_creatures)
    {
        // Small number of shadow creatures, but still a little touch of chaos.
        int multiplier = 1;
        int range_cap = div_rand_round(you.experience_level, 8);

        if (_xom_is_bored())
            multiplier = 2;
        else if (you.penance[GOD_XOM])
        {
            multiplier = 3;
            range_cap = 4;
        }

        int count = random_range(1, max(1, range_cap)) * multiplier;

        for (int i = 0; i < multiplier; ++i)
            if (_xom_summon_hostile(_xom_random_pal(strengthRoll, false)))
                num_summoned++;

        for (int i = 0; i < count; ++i)
            if (_xom_summon_hostile(RANDOM_MOBILE_MONSTER))
                num_summoned++;
    }
    else
    {
        int count = _xom_pal_counting(strengthRoll, false);

        for (int i = 0; i < count; ++i)
        {
            monster_type mon_type = _xom_random_pal(strengthRoll, false);

            // As seen in _xom_send_allies, add more of given banding monsters
            // without adding to the overall summon cap.
            int miniband = _xom_pal_minibands(mon_type);

            for (int j = 0; j < miniband; ++j)
                if (_xom_summon_hostile(mon_type))
                    num_summoned++;

            // Again as seen in _xom_send_allies, make summons likely to come in
            // pairs of the same type if neither a band nor later summoners,
            // while still respecting the overall summon cap.
            if (x_chance_in_y(2, 3) && miniband == 1 &&
                !_xom_pal_summonercheck(mon_type) && i < count - 1)
            {
                i += 1;
                if (_xom_summon_hostile(_xom_random_pal(strengthRoll, false)))
                    num_summoned++;
            }
        }
    }

    if (num_summoned > 0)
    {
        const string note = make_stringf("summons %d hostile %s%s",
                                         num_summoned,
                                         shadow_creatures ? "shadow creature"
                                                          : "chaos creature",
                                         num_summoned > 1 ? "s" : "");
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);

        const string speech = _get_xom_speech("hostile monster");
        god_speaks(GOD_XOM, speech.c_str());
    }
}

// Make two hostile clones and one friendly clone. Net danger, but maybe
// the player can make something of it anyway.
static void _xom_send_in_clones(int /*sever*/)
{
    const int friendly_count = you.allies_forbidden() ? 0 : 1;
    const int hostile_count = 2;
    int hostiles_summon_count = 0;
    int friendly_summon_count = 0;
    int power = 0;

    const string speech = _get_xom_speech("send in the clones");
    god_speaks(GOD_XOM, speech.c_str());

    for (int i = 0; i < friendly_count + hostile_count; i++)
    {
        monster* mon = get_free_monster();

        if (!mon || monster_at(you.pos()))
            return;

        mon->type = MONS_PLAYER;
        mon->behaviour = BEH_SEEK;
        mon->set_position(you.pos());
        mon->mid = MID_PLAYER;
        env.mgrid(you.pos()) = mon->mindex();

        if (hostiles_summon_count < hostile_count)
        {
            mon->attitude = ATT_HOSTILE;
            power = -1;
        }
        else
        {
            mon->attitude = ATT_FRIENDLY;
            power = 0;
        }

        if (mons_summon_illusion_from(mon, (actor *)&you, SPELL_NO_SPELL, power, true))
        {
            if (hostiles_summon_count < hostile_count)
                hostiles_summon_count++;
            else
                friendly_summon_count++;
        }
        mon->reset();
    }

    const string note = make_stringf("summoned %d hostile %s + %d friendly %s",
                                     hostiles_summon_count,
                                     hostiles_summon_count == 1 ? "illusion"
                                                                : "illusions",
                                     friendly_summon_count,
                                     friendly_summon_count == 1 ? "illusion"
                                                                : "illusions");
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// Roll per-monster whether they're neutral or hostile.
static bool _xom_maybe_neutral_summon(int sever, bool threat,
                                      monster_type mon_type)
{
    beh_type setting = (x_chance_in_y(sever, 300) || threat) ? BEH_HOSTILE
                                                             : BEH_NEUTRAL;

    mgen_data mg(mon_type, setting, you.pos(), MHITYOU, MG_FORCE_BEH, GOD_XOM);
    mg.set_summoned(&you, MON_SUMM_AID, summ_dur(4));
    mg.non_actor_summoner = "Xom";

    return create_monster(mg);
}

// Drain you for 3/4ths of your mp, then create several brain worms, mana
// vipers, and / or quicksilver elementals from your mp based on your xl. If
// Xom's not bored or wrathful, severity gives a chance of some being neutral.
static void _xom_brain_drain(int sever)
{
    bool created = false;
    bool upgrade = you.penance[GOD_XOM];
    int xl = upgrade ? you.experience_level + 6 : you.experience_level;
    int worm_count = 0;
    int viper_count = 0;
    int quicksilver_count = 0;
    int drain = 1;

    drain = upgrade ? you.magic_points :
            min(you.magic_points, max(1, (you.magic_points * 3 / 4)));

    if (xl < 15)
        worm_count = xl < 5 ? 1 : min(4, div_rand_round(xl - 1, 3));

    if (xl > 11 && xl < 22)
        viper_count = xl < 14 ? 1 : min(4, div_rand_round(xl - 10, 3));

    if (xl > 19)
        quicksilver_count = xl < 22 ? 1 : min(3, div_rand_round(xl - 18, 3));

    // Xom won't do this anyway if you have no MP, so...
    if (drain > 0)
    {
        drain_mp(drain);

        for (int i = 0; i < worm_count; ++i)
            if (_xom_maybe_neutral_summon(sever, upgrade, MONS_BRAIN_WORM))
                created = true;

        for (int i = 0; i < viper_count; ++i)
            if (_xom_maybe_neutral_summon(sever, upgrade, MONS_MANA_VIPER))
                created = true;

        for (int i = 0; i < quicksilver_count; ++i)
            if (_xom_maybe_neutral_summon(sever, upgrade, MONS_QUICKSILVER_ELEMENTAL))
                created = true;

        const string speech = _get_xom_speech("brain drain");
        god_speaks(GOD_XOM, speech.c_str());

        if (created)
        {
            string react = _get_xom_speech("drained brain");

            react = replace_all(react, "@random_body_part_any_singular@",
                                random_body_part_name(false, BPART_ANY));
            react = replace_all(react, "@random_body_part_internal_singular@",
                                random_body_part_name(false, BPART_INTERNAL));
            react = replace_all(react, "@random_body_part_external_singular@",
                                random_body_part_name(false, BPART_EXTERNAL));
            react = replace_all(react, "@random_body_part_any_plural@",
                                random_body_part_name(true, BPART_ANY));
            react = replace_all(react, "@random_body_part_internal_plural@",
                                random_body_part_name(true, BPART_INTERNAL));
            react = replace_all(react, "@random_body_part_external_plural@",
                                random_body_part_name(true, BPART_EXTERNAL));

            react = maybe_pick_random_substring(react);

            const string note = make_stringf("drained mp, created monsters");
            mprf(MSGCH_WARN, "%s", react.c_str());
            take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
        }
        else
        {
            mprf(MSGCH_WARN, "You feel nearly all of your power leaking away!");
            const string note = make_stringf("drained mp");
            take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
        }
    }
}

// XXX: Possibly this could be used elsewhere, like defaults for wizard spells
// for those without speech, but we generally try to just give those custom
// messages per-monster anyway currently.
static const map<shout_type, string> speaking_keys = {
    { S_SILENT,         "dramatically intoning" },
    { S_SHOUT,          "shouting" },
    { S_BARK,           "barking" },
    { S_HOWL,           "howling" },
    { S_SHOUT2,         "shouting twice-over" },
    { S_ROAR,           "roaring" },
    { S_SCREAM,         "screaming" },
    { S_BELLOW,         "bellowing" },
    { S_BLEAT,          "bleating" },
    { S_TRUMPET,        "trumpeting" },
    { S_SCREECH,        "screeching" },
    { S_BUZZ,           "buzzing" },
    { S_MOAN,           "chillingly moaning" },
    { S_GURGLE,         "gurgling" },
    { S_CROAK,          "croaking" },
    { S_GROWL,          "growling" },
    { S_HISS,           "hissing" },
    { S_SKITTER,        "weaving" },
    { S_FAINT_SKITTER,  "faintly weaving" },
    { S_DEMON_TAUNT,    "sneering" },
    { S_CHERUB,         "speaking" },
    { S_SQUEAL,         "squealing" },
    { S_LOUD_ROAR,      "roaring" },
    { S_RUSTLE,         "scribing" },
    { S_SQUEAK,         "squeaking" },
};

static bool _has_min_recall_level()
{
    int min = you.penance[GOD_XOM] ? 3 : 5;
    return you.experience_level > min;
}

// As intense as these checks are, it basically just avoids monsters who
// would otherwise be preoccupied or aren't "real monsters" to kill.
static bool _valid_speaker_of_recall(monster* mon)
{
    return mon->alive() && !mon->wont_attack() && _should_recall(mon)
            && !mon->berserk_or_frenzied() && you.can_see(*mon)
            && !mon->is_summoned() && !mons_is_confused(*mon)
            && !mon->is_peripheral()
            && !mon->petrifying() && !mon->cannot_act() && !mon->asleep()
            && !mon->is_silenced() && !mon->has_ench(ENCH_WORD_OF_RECALL);
}

// Xom forces a random monster in sight to start reciting a Word of Recall.
// Since this is much rarer and less anticipated compared to normal sightings
// of ironbound convokers, it takes extra long to cast.
static void _xom_grants_word_of_recall(int /*sever*/)
{
    int duration = 90 - div_rand_round(you.experience_level, 9) * 10;
    string note = "";

    vector<monster*> targetable;

    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (_valid_speaker_of_recall(*mi))
            targetable.push_back(*mi);
    }

    // Shouldn't be reached outside of wizmode due to
    // having checked for a valid speaker first.
    if (targetable.empty())
        return;

    shuffle_array(targetable);
    string phrasing = "reciting";
    string xom_speech = "grant word of recall";

    shout_type shouting = get_monster_data(targetable[0]->type)->shouts;
    phrasing = speaking_keys.find(shouting)->second;
    if (phrasing == "dramatically intoning")
        xom_speech = "grant voiceless word of recall";

    god_speaks(GOD_XOM, _get_xom_speech(xom_speech).c_str());
    mprf(MSGCH_WARN, "%s is forced to slowly start %s a word of recall!",
                     targetable[0]->name(DESC_A, true, false).c_str(),
                     phrasing.c_str());
    mon_enchant chant_timer = mon_enchant(ENCH_WORD_OF_RECALL, targetable[0], duration);
    targetable[0]->add_ench(chant_timer);

    note = make_stringf("made %s speak a word of recall",
                        targetable[0]->name(DESC_A, true, false).c_str());

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

// Disallow early banishment and make it rarer at lower XL in general.
// While Xom is bored, the chance is increased.
static bool _allow_xom_banishment()
{
    // Always allowed if under penance.
    if (player_under_penance(GOD_XOM))
        return true;

    if (you.experience_level < 9)
        return false;

    const int lv = min(you.experience_level - 9, 11) + (_xom_is_bored() ? 10 : 0);
    if (!x_chance_in_y(lv, lv + 5))
        return false;

    return true;
}

static void _revert_banishment(bool xom_banished = true)
{
    more();
    god_speaks(GOD_XOM, xom_banished
               ? _get_xom_speech("revert own banishment").c_str()
               : _get_xom_speech("revert other banishment").c_str());
    down_stairs(DNGN_EXIT_ABYSS);
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                   "revert banishment"), true);
}

// Only used for Xom rarely reverting others' banishment, now.
void xom_maybe_reverts_banishment()
{
    if (!_xom_feels_nasty() && x_chance_in_y(you.raw_piety, 1000))
        _revert_banishment(false);
}

static void _xom_do_banishment(bool real)
{
    god_speaks(GOD_XOM, _get_xom_speech("banishment").c_str());

    // Handles note taking
    banished("Xom");
    if (!real)
        _revert_banishment();
}

static void _xom_banishment(int /*sever*/) { _xom_do_banishment(true); }
static void _xom_pseudo_banishment(int) { _xom_do_banishment(false); }

static void _xom_noise(int /*sever*/)
{
    // Ranges from shout to shatter volume.
    const int noisiness = 12 + random2(19);

    god_speaks(GOD_XOM, _get_xom_speech("noise").c_str());
    // Xom isn't subject to silence.
    fake_noisy(noisiness, you.pos());

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "noise"), true);
}

static bool _mon_valid_blink_victim(const monster& mon)
{
    return !mon.wont_attack()
            && !mon.no_tele()
            && !mons_is_projectile(mon);
}

static void _xom_blink_monsters(int /*sever*/)
{
    int blinks = 0;
    // Sometimes blink towards the player, sometimes randomly. It might
    // end up being helpful instead of dangerous, but Xom doesn't mind.
    const bool blink_to_player = _xom_feels_nasty() || coinflip();
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (blinks >= 5)
            break;

        if (!_mon_valid_blink_victim(**mi) || coinflip())
            continue;

        // Only give this message once.
        if (!blinks)
            god_speaks(GOD_XOM, _get_xom_speech("blink monsters").c_str());

        if (blink_to_player)
            blink_other_close(*mi, you.pos());
        else
            monster_blink(*mi, true);

        blinks++;
    }

    if (blinks)
    {
        take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "blink monster(s)"),
                  true);
    }
}

static void _xom_cleaving(int sever)
{
    god_speaks(GOD_XOM, _get_xom_speech("cleaving").c_str());

    you.increase_duration(DUR_CLEAVE, 10 + random2(sever));

    if (const item_def* const weapon = you.weapon())
    {
        const bool axe = item_attack_skill(*weapon) == SK_AXES;
        mprf(MSGCH_DURATION,
             "%s %s sharp%s", weapon->name(DESC_YOUR).c_str(),
             conjugate_verb("look", weapon->quantity > 1).c_str(),
             (axe) ? " (like it always does)." : ".");
    }
    else
    {
        mprf(MSGCH_DURATION, "%s",
             you.hands_act("look", "sharp.").c_str());
    }

    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "cleaving"), true);
}


static void _handle_accidental_death(const int orig_hp,
    const FixedVector<uint8_t, NUM_MUTATIONS> &orig_mutation,
    const transformation orig_form)
{
    // Did ouch() return early because the player died from the Xom
    // effect, even though neither is the player under penance nor is
    // Xom bored?
    if ((!you.did_escape_death()
         && you.escaped_death_aux.empty()
         && !_player_is_dead())
        || you.pending_revival) // don't let xom take credit for felid revival
    {
        // The player is fine.
        return;
    }

    string speech_type = XOM_SPEECH("accidental homicide");

    const dungeon_feature_type feat = env.grid(you.pos());

    switch (you.escaped_death_cause)
    {
        case NUM_KILLBY:
        case KILLED_BY_LEAVING:
        case KILLED_BY_WINNING:
        case KILLED_BY_QUITTING:
            speech_type = XOM_SPEECH("weird death");
            break;

        case KILLED_BY_LAVA:
        case KILLED_BY_WATER:
            if (!is_feat_dangerous(feat))
                speech_type = "weird death";
            break;

        default:
            if (is_feat_dangerous(feat))
                speech_type = "weird death";
        break;
    }

    canned_msg(MSG_YOU_DIE);
    god_speaks(GOD_XOM, _get_xom_speech(speech_type).c_str());
    god_speaks(GOD_XOM, _get_xom_speech("resurrection").c_str());

    int pre_mut_hp = you.hp;
    if (you.hp <= 0)
        you.hp = 9999; // avoid spurious recursive deaths if heavily rotten

    // If any mutation has changed, death was because of it.
    for (int i = 0; i < NUM_MUTATIONS; ++i)
    {
        if (orig_mutation[i] > you.mutation[i])
            mutate((mutation_type)i, "Xom's lifesaving", true, true, true);
        else if (orig_mutation[i] < you.mutation[i])
            delete_mutation((mutation_type)i, "Xom's lifesaving", true, true, true);
    }

    if (pre_mut_hp <= 0)
        set_hp(min(orig_hp, you.hp_max));

    if (orig_form != you.form)
    {
        dprf("Trying emergency untransformation.");
        you.transform_uncancellable = false;
        transform(10, orig_form, true);
    }

    if (is_feat_dangerous(feat) && !crawl_state.game_is_sprint())
        you_teleport_now();
}


/**
 * A formatting of Xom actions, their chance to happen, and if it should be done.
 *
 * xom_event_type name         An action for Xom to take.
 * @param int tension_weight   The chance with visible monsters.
 * @param int tension_weight   The chance without visible monsters.
 * @param bool valid           A check to see if this action should be done.
 * @param sever                The intended magnitude of the action.
 * @param tension              How much danger we think the player's in.
 */
struct xom_event_data
{
    xom_event_type name;
    int tension_weight;
    int zero_tension_weight;
    function<bool(int sever, int tension)> valid;
};

static const vector<xom_event_data> _list_xom_good_actions = {
    {
        XOM_GOOD_POTION, 500, 0, [](int /*sv*/, int tn) {return tn > 0;}
    },
    {
        XOM_GOOD_SPELL, 450, 0, [](int sv, int tn)
        {return tn > 0 && _choose_random_spell(sv) != SPELL_NO_SPELL;}
    },
    {
        XOM_GOOD_CONFUSION, 440, 0, [](int /*sv*/, int /*tn*/)
        {return mon_nearby([](monster& mon){ return !mon.wont_attack(); });}
    },
    {
        XOM_GOOD_ENCHANT_MONSTER, 420, 0, [](int /*sv*/, int tn)
        {return tn > 0 && mon_nearby(_choose_enchantable_monster);}
    },
    {
        XOM_GOOD_SINGLE_ALLY, 400, 60, [](int /*sv*/, int tn)
        {return (tn > 0 || (_exploration_estimate(false) < 25))
                && !you.allies_forbidden();}
    },
    {
        XOM_GOOD_POLYMORPH, 275, 0, [](int /*sv*/, int tn)
        {return tn > 0 && _xom_mons_poly_target() != nullptr;}
    },
    {
        XOM_GOOD_ALLIES, 280, 0, [](int /*sv*/, int tn)
        {return tn > 4 && !you.allies_forbidden();}
    },
    {
        XOM_GOOD_FORCE_LANCE_FLEET, 230, 0, [](int /*sv*/, int tn)
        {
            if (tn <= 4)
                return false;

            // Check for a reasonable amount of open space to place
            // these many living spells down in.
            int open_count = 0;
            for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS, true);
                 ri; ++ri)
            {
                if (!cell_is_solid(*ri))
                    open_count++;
            }

            return open_count > 6;
        }
    },
    {
        XOM_GOOD_CLEAVING, 160, 0, [](int /*sv*/, int tn) {return tn > 0;}
    },
    {
        XOM_GOOD_FLORA_RING, 130, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0)
                return false;

            // Check both that there's at least some space to spawn plants
            // and very few smiting-attack monsters around.
            int plant_capacity = 0;
            int smiters = 0;

            for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS, true);
                ri; ++ri)
            {
                if (!monster_at(*ri) && monster_habitable_grid(MONS_PLANT, *ri))
                    plant_capacity++;
            }

            for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
                if (_mons_has_smite_attack(*mi) && grid_distance(mi->pos(), you.pos()) > 2)
                    smiters++;

            return plant_capacity >= 3
                   && smiters < div_rand_round(you.experience_level, 6) - 1;
        }
    },
    {
        XOM_GOOD_DESTRUCTION, 125, 0, [](int /*sv*/, int tn)
        {
            for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
            {
                // Skip adjacent monsters, and skip
                // non-hostile monsters if not feeling nasty.
                if (!mons_is_projectile(**mi)
                    && !mons_is_tentacle_or_tentacle_segment(mi->type)
                    && !adjacent(you.pos(), mi->pos())
                    && (!mi->wont_attack() || _xom_feels_nasty()))
                {
                    return tn > 0;
                }
            }
            return false;
        }
    },
    {
        XOM_GOOD_DOOR_RING, 110, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0)
                return false;

            // Assess each if there's enough room to meaningfully raise a door
            // ring, if there's adjacent hostiles to move so it does anything
            // tactically, and if there's at least visible room to move them to.
            int adjacent_hostiles = 0;
            int replaceable = 0;
            int spare_space_out = 0;

            for (radius_iterator ri(you.pos(), 8, C_SQUARE, LOS_NO_TRANS); ri; ++ri)
            {
                if (grid_distance(*ri, you.pos()) <= 2
                    && monster_at(*ri) && !monster_at(*ri)->wont_attack())
                {
                    adjacent_hostiles++;
                }
                else if (grid_distance(*ri, you.pos()) >= 6 && in_bounds(*ri)
                         && feat_has_solid_floor(env.grid(*ri)))
                {
                    spare_space_out++;
                }
            }

            for (radius_iterator ri(you.pos(), 5, C_SQUARE, LOS_NONE); ri; ++ri)
            {
                if (grid_distance(*ri, you.pos()) >= 3 && in_bounds(*ri)
                    && _xom_door_replaceable(env.grid(*ri)))
                {
                    replaceable++;
                }
            }

            return replaceable > 24 && adjacent_hostiles - 1 < spare_space_out;
        }
    },
    {
        XOM_GOOD_MASS_CHARM, 87, 0, [](int /*sv*/, int tn)
        {return tn > 4 && mon_nearby(_choose_enchantable_monster);}
    },
    {
        XOM_GOOD_HYPER_ENCHANT_MONSTER, 70, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0)
                return false;

            // First, look for weak present monsters.
            vector<monster*> potential = _xom_find_weak_monsters(false);

            // If there isn't, check if there's space to summon something weak.
            if (potential.empty() && x_chance_in_y(2, 5))
            {
                for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS, true);
                    ri; ++ri)
                {
                    if (!cell_is_solid(*ri))
                        return true;
                }
            }

            return !potential.empty();
        }
    },
    {
        XOM_GOOD_FOG, 65, 0, [](int /*sv*/, int tn)
        {return tn > 0 && !cloud_at(you.pos());}
    },
    {
        XOM_GOOD_FAKE_DESTRUCTION, 60, 0, [](int /*sv*/, int tn)
        {return tn > 0 && mon_nearby(_choose_enchantable_monster);}
    },
    {
        // Not the most interesting if the level is already nearly fully
        // explored (presumably cleared), but it can still occasionally
        // happen for runed door vaults and branch ends.
        XOM_GOOD_TELEPORT, 40, 590, [](int /*sv*/, int /*tn*/)
        {return (!player_in_branch(BRANCH_ABYSS) && _teleportation_check())
                && (_exploration_estimate(true) < 80
                || !x_chance_in_y(_exploration_estimate(true), 110));}
    },
    {
        XOM_GOOD_LIGHTNING, 21, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0 || !player_in_a_dangerous_place())
                return false;

            // Make sure there's at least one enemy within
            // the initial lightning radius.
            for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_SOLID, true); ri;
                ++ri)
            {
                const monster *mon = monster_at(*ri);
                if (mon && !mon->wont_attack())
                    return true;
            }

            return false;
        }
    },
    {
        XOM_GOOD_WAVE_OF_DESPAIR, 15, 0, [](int /*sv*/, int tn)
        {return tn > 0 && mon_nearby(_choose_enchantable_monster);}
    },

    // Effects with very specific conditions, given a seemingly high weight
    // despite their flashiness due to how rarely they'll actually come up.
    // Might have more of these come in eventually...
    {
        XOM_GOOD_SNAKES, 405, 0, [](int /*sv*/, int /*tn*/)
        {return mon_nearby(_hostile_snake);}
    },
    {
        XOM_GOOD_LIGHT_UP_WEBS, 205, 0, [](int /*sv*/, int tn)
        {
            // Since this is meant to be a good action, don't set the player's
            // tile on fire if they're close to death.
            if (env.grid(you.pos()) == DNGN_TRAP_WEB
                && you.hp <= (27 - you.res_fire() * 4))
            {
                return false;
            }

            return tn > 0 && !_xom_counts_webs().empty();
        }
    },
    {
        XOM_GOOD_ANIMATE_MON_WPN, 325, 0,[](int /*sv*/, int tn)
        {return tn > 4 && _find_monster_with_animateable_weapon()
                       && !you.allies_forbidden();}
    },

    // Strategic effects that don't care about greater than 0 tension.
    // TODO: replace Xom mood with a visible tension bar, then use gift timeout
    // in the background to choose providing strategic benefits when going
    // to new floors, to make this more controllable, less scummable, to confuse
    // people less about amusing Xom having nothing to do with mood, etc, etc.
    {
        XOM_GOOD_DIVINATION, 420, 500, [](int /*sv*/, int tn)
        {return tn <= 24 && (_exploration_estimate(false) < 80
                || x_chance_in_y(_exploration_estimate(false), 120));}
    },
    {
        XOM_GOOD_SCENERY, 120, 135, [](int /*sv*/, int tn)
        {return (tn <= 4) && (!(_xom_scenery_candidates().empty())
                         || one_chance_in(3));}
    },
    {
        XOM_GOOD_CLOUD_TRAIL, 0, 375, [](int /*sv*/, int tn)
        {return (tn == 0) && (_exploration_estimate(false) < 100)
                          && !you.duration[DUR_CLOUD_TRAIL];}
    },
    {
        XOM_GOOD_BAZAAR_TRIP, 60, 280, [](int sv, int tn)
        {
           // Nesting bazaars makes exploration and shopping lists complain.
           // No leaving Sprint floors in Sprint.
           if (is_level_on_stack(level_id(BRANCH_BAZAAR))
              || player_in_branch(BRANCH_BAZAAR)
              || brdepth[BRANCH_ABYSS] == -1)
           {
              return false;
           }

           // Check if you have enough gold, increqased by each trip.
           if (you.gold < (900 + sv * (4 +
                          (you.props[XOM_BAZAAR_TRIP_COUNT].get_int() * 2))))
           {
              return false;
           }

           // Don't interrupt autotravel too often.
           if (_exploration_estimate(true) > 80
               && !x_chance_in_y(_exploration_estimate(true), 120))
           {
               return false;
           }

           // Each bazaar trip reduces the chance of the next, unless things
           // are going badly enough it'd be funny to save the player.
           return tn > 28
                 || (one_chance_in(you.props[XOM_BAZAAR_TRIP_COUNT].get_int() * 7));
        }
    },
    {
        XOM_GOOD_MUTATION, 32, 400, [](int /*sv*/, int tn)
        {return (random2(tn) < 5 // should really revise strategic benefits....
                 && x_chance_in_y(16, you.how_mutated())
                 && you.can_safely_mutate());}
    },
    {
        XOM_GOOD_RANDOM_ITEM, 33, 775, [](int /*sv*/, int tn) {return (tn < 20) ;}
    },
    {
        XOM_GOOD_ACQUIREMENT, 21, 295, [](int /*sv*/, int tn) {return (tn < 20) ;}
    },
};

static const vector<xom_event_data> _list_xom_bad_actions = {
    {
        XOM_BAD_NOISE, 975, 415, [](int /*sv*/, int tn)
        {return (tn > 0 || !you.penance[GOD_XOM]);}
    },
    {
        XOM_BAD_MISCAST_PSEUDO, 825, 715, [](int /*sv*/, int /*tn*/)
        {return !you.penance[GOD_XOM];}
    },
    {
        XOM_BAD_ENCHANT_MONSTER, 790, 0, [](int /*sv*/, int tn)
        {return tn > 0 && mon_nearby(_choose_enchantable_monster);}
    },
    {
        XOM_BAD_BLINK_MONSTERS, 680, 0, [](int /*sv*/, int tn)
        {return tn > 0 && mon_nearby(_mon_valid_blink_victim);}
    },
    {
        XOM_BAD_CONFUSION, 610, 0, [](int /*sv*/, int tn)
        {return tn > 0 && !you.clarity();}
    },
    {
        XOM_BAD_CHAOS_UPGRADE, 590, 0, [](int /*sv*/, int /*tn*/)
        {return mon_nearby(_choose_chaos_upgrade);}
    },
    {
        XOM_BAD_SWAP_MONSTERS, 540, 0, [](int /*sv*/, int tn)
        {return tn > 0 && _rearrangeable_pieces().size();}
    },
    {
        XOM_BAD_TELEPORT, 475, 1460, [](int /*sv*/, int tn)
        {
            const int explored = _exploration_estimate(true);

            return ((!player_in_branch(BRANCH_ABYSS) || _teleportation_check()))
                 && !((_xom_feels_nasty() && (explored >= 40 || tn > 10))
                     || (explored >= 60 + random2(40)));
        }
    },
    {
        XOM_BAD_POLYMORPH, 380, 0, [](int /*sv*/, int tn)
        {return tn > 0 && _xom_mons_poly_target() != nullptr;}
    },
    {
        XOM_BAD_SUMMON_HOSTILES, 170, 670, [](int /*sv*/, int tn)
        {return tn <= 48;}
    },
    {
        XOM_BAD_TIME_CONTROL, 133, 0, [](int /*sv*/, int tn)
        {return tn > 0 && !you.duration[DUR_HASTE]
         && !you.duration[DUR_SLOW]
         && !you.duration[DUR_PARALYSIS];}
    },
    {
        XOM_BAD_BRAIN_DRAIN, 100, 0, [](int /*sv*/, int tn)
        {return tn > 0 && you.magic_points > 3;}
    },
    {
        XOM_BAD_FAKE_SHATTER, 75, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0)
                return false;

            // Check if there's a reasonable amount of features
            // the fake Xom shatter is likely to collapse.
            int nearby_diggable = 0;
            for (radius_iterator ri(you.pos(), you.current_vision,
                                    C_SQUARE, LOS_NO_TRANS); ri; ++ri)
            {
                if (feat_is_diggable(env.grid(*ri))
                    || feat_is_door(env.grid(*ri)))
                {
                    nearby_diggable++;
                    if (nearby_diggable >= 4)
                        return true;
                }
            }

            return false;
        }
    },
    {
        XOM_BAD_CHAOS_CLOUD, 58, 0, [](int /*sv*/, int tn)
        {return tn > 0 && !cloud_at(you.pos());}
    },
    {
        XOM_BAD_GRANT_WORD_OF_RECALL, 80, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0 || tn > 24 || !_has_min_recall_level())
                return false;

            bool recall_ready = false;
            for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
            {
                if (_valid_speaker_of_recall(*mi))
                    recall_ready = true;
            }

            return recall_ready;
        }
    },
    {
        XOM_BAD_SEND_IN_THE_CLONES, 45, 0, [](int /*sv*/, int tn)
        {
            if (tn == 0 || tn > 24)
                return false;

            int clone_capacity = 0;

            for (radius_iterator ri(you.pos(), 2, C_SQUARE, LOS_NO_TRANS, true);
                ri; ++ri)
            {
                if (!monster_at(*ri) && monster_habitable_grid(MONS_PLAYER_ILLUSION, *ri))
                    clone_capacity++;
            }

            return clone_capacity >= 3;
        }
    },
    {
        XOM_BAD_DOOR_RING, 38, 0, [](int /*sv*/, int tn)
        {
            if (tn <= 4)
                return false;

            // Calculate if there's enough room to raise a meaningful door ring
            // and also if there's enough hostiles present either
            // already adjacent or near enough to blink inwards.
            int adjacent_hostiles = 0;
            int moveable_hostiles = 0;
            int adjacent_space = 0;
            int replaceable = 0;
            int adjascency_cap = 2 + div_rand_round(you.experience_level, 6);

            for (radius_iterator ri(you.pos(), you.current_vision, C_SQUARE, LOS_NO_TRANS); ri; ++ri)
            {
                if (monster_at(*ri) && !monster_at(*ri)->wont_attack())
                    if (grid_distance(*ri, you.pos()) <= 2)
                        adjacent_hostiles++;
                    else
                        moveable_hostiles++;
                else if (feat_has_solid_floor(env.grid(*ri)))
                    adjacent_space++;
            }

            for (radius_iterator ri(you.pos(), 5, C_SQUARE, LOS_NONE); ri; ++ri)
            {
                if (grid_distance(*ri, you.pos()) >= 3
                && in_bounds(*ri)
                && _xom_door_replaceable(env.grid(*ri)))
                {
                    replaceable++;
                }
            }

           return (replaceable > 30 && adjacent_hostiles <= adjascency_cap)
                   && ((moveable_hostiles <= adjacent_space
                   && moveable_hostiles >= 2) || (adjacent_hostiles >= 2));
        }
    },
    {
        XOM_BAD_TORMENT, 6, 0, [](int /*sv*/, int tn)
        {return tn > 0 && !you.res_torment();}
    },

    // Strategic effects.
    {
        XOM_BAD_MUTATION, 210, 1010, [](int /*sv*/, int tn)
        {return tn <= 8 && you.can_safely_mutate();}
    },
    {
        XOM_BAD_DRAINING, 5, 160, [](int /*sv*/, int /*tn*/)
        {return player_prot_life() < 3;}
    },
    {
        XOM_BAD_DOOM, 5, 160, [](int /*sv*/, int tn)
        {return tn <= 8 && (you.attribute[ATTR_DOOM] < 80 ||
                            _xom_feels_nasty());}
    },
    {
        // Since this is an enum-based vector list and we can't adjust weights
        // on conditions otherwise, this duplicates the Doom entry to apply
        // slightly extra Doom on the rN∞ rMut∞ undead. Since direct Banes
        // require boredom or wrath, it should mostly just scare players and
        // block Xomscumming more than anything pressing on Xom balance.
        XOM_BAD_DOOM, 50, 100, [](int /*sv*/, int tn)
        {return tn <= 8 && you.is_lifeless_undead() &&
                (you.attribute[ATTR_DOOM] < 80 || _xom_feels_nasty());}
    },
    {
        XOM_BAD_PSEUDO_BANISHMENT, 2, 1, [](int /*sv*/, int /*tn*/)
        {return !_xom_feels_nasty()
                && !player_in_branch(BRANCH_ABYSS)
                && !(is_level_on_stack(level_id(BRANCH_ABYSS)));}
    },
    {
        XOM_BAD_BANISHMENT, 1, 1, [](int /*sv*/, int /*tn*/)
        {return _allow_xom_banishment()
                && !x_chance_in_y(you.raw_piety * 2, 1000)
                && !player_in_branch(BRANCH_ABYSS)
                && !(is_level_on_stack(level_id(BRANCH_ABYSS)));}
    },

    // Highly circumstantial effects with less total
    // chances than their weight would seem to show.
    {
        XOM_BAD_MOVING_STAIRS, 215, 0, [](int /*sv*/, int /*tn*/)
        {return !(_nearby_stairs().empty());} // Abyss is always min 2 tension!
    },
    {
        XOM_BAD_FIDDLE_WITH_DOORS, 95, 5, [](int /*sv*/, int tn)
        {return ((tn > 4 || (_exploration_estimate(false) < 5)
                 && !_xom_feels_nasty())) && !_xom_door_candidates().empty();}
    },
    {
        XOM_BAD_CLIMB_STAIRS, 55, 0, [](int /*sv*/, int tn)
        { return tn > 0 && !(_nearby_stairs().empty()) &&
                 (feat_stair_direction(env.grid(you.pos())) != CMD_NO_CMD
                 && env.grid(you.pos()) != DNGN_ENTER_SHOP);}
    },
};

/**
 * Try to choose an action for Xom to take.
 *
 * @param niceness      Whether the action should be 'good' for the player.
 * @param sever         The intended magnitude of the action.
 * @param tension       How much danger we think the player's currently in.
 * @return              An bad action for Xom to take, e.g. XOM_DID_NOTHING.
 */
xom_event_type xom_choose_action(bool niceness, int sever, int tension)
{
    sever = max(1, sever);
    vector<pair<const xom_event_data&, int>> weighted_list;
    const xom_event_data* action;

    if (_player_is_dead() && !you.pending_revival)
    {
        // This should only happen if the player used wizard mode to
        // escape death from deep water or lava.
        ASSERT(you.wizard);
        ASSERT(!you.did_escape_death());
        if (is_feat_dangerous(env.grid(you.pos())))
            mprf(MSGCH_DIAGNOSTICS, "Player is standing in deadly terrain, skipping Xom act.");
        else
            mprf(MSGCH_DIAGNOSTICS, "Player is already dead, skipping Xom act.");
        return XOM_PLAYER_DEAD;
    }

    // Choosing any type of good act is less likely at zero tension, especially
    // if Xom is in a bad mood. Choosing any type of bad action at non-zero
    // tension is less likely, especially if Xom is in a good mood.
    if (niceness && tension == 0 && you_worship(GOD_XOM)
        && !x_chance_in_y(you.raw_piety, MAX_PIETY))
    {
#ifdef NOTE_DEBUG_XOM
        take_note(Note(NOTE_MESSAGE, 0, 0, "suppress good act because of "
                        "zero tension"), true);
#endif
        return XOM_DID_NOTHING;
    }
    else if (!niceness && !_xom_feels_nasty() && tension > random2(10)
             && you_worship(GOD_XOM) && x_chance_in_y(you.raw_piety, MAX_PIETY))
    {
#ifdef NOTE_DEBUG_XOM
        const string note = string("suppress bad act because of ") +
                                   tension + " tension";
        take_note(Note(NOTE_MESSAGE, 0, 0, note), true);
#endif
        return XOM_DID_NOTHING;
    }

    // Compile the total list based on Xom's niceness and any degree of tension.
    if (niceness)
    {
        if (tension > 0)
        {
            for (const xom_event_data &effect : _list_xom_good_actions)
                weighted_list.push_back({effect, effect.tension_weight});
        }
        else
        {
            for (const xom_event_data &effect : _list_xom_good_actions)
                if (effect.zero_tension_weight > 0)
                    weighted_list.push_back({effect, effect.zero_tension_weight});
        }
    }
    else
    {
        if (tension > 0)
        {
            for (const xom_event_data &effect : _list_xom_bad_actions)
                weighted_list.push_back({effect, effect.tension_weight});
        }
        else
        {
            for (const xom_event_data &effect : _list_xom_bad_actions)
                if (effect.zero_tension_weight > 0)
                    weighted_list.push_back({effect, effect.zero_tension_weight});
        }
    }

    // With the list compiled, roll through action options to find one.
    while (true)
    {
        action = random_choose_weighted(weighted_list);

        // If there are somehow no valid actions at all (due to changes
        // made to Xom action criteria), break out to do nothing.
        if (!action)
            break;

        // If the action was invalid, set its weight to 0 and try again.
        if (!action->valid(sever, tension))
        {
            find_if(weighted_list.begin(), weighted_list.end(),
                    [action](const pair<const xom_event_data&, int>& entry)
                    {return entry.first.name == action->name;})->second = 0;
        }
        else
            return action->name;
    }

    return XOM_DID_NOTHING;
}

/**
 * Execute the specified Xom Action.
 *
 * @param action        The action type in question; e.g. XOM_BAD_NOISE.
 * @param sever         The severity of the action.
 */
void xom_take_action(xom_event_type action, int sever)
{
    const int  orig_hp       = you.hp;
    const transformation orig_form = you.form;
    const FixedVector<uint8_t, NUM_MUTATIONS> orig_mutation = you.mutation;
    const bool was_bored = _xom_is_bored();

    const bool bad_effect = _action_is_bad(action);

    if (was_bored && bad_effect && Options.note_xom_effects)
        take_note(Note(NOTE_MESSAGE, 0, 0, "XOM is BORED!"), true);

    // actually take the action!
    {
        god_acting gdact(GOD_XOM);
        _do_xom_event(action, sever);
    }

    // If we got here because Xom was bored, reset gift timeout according
    // to the badness of the effect.
    if (bad_effect && _xom_is_bored())
    {
        const int badness = _xom_event_badness(action);
        const int interest = random2avg(badness * 60, 2);
        you.gift_timeout   = min(interest, 255);
        //updating piety status line
        you.redraw_title = true;
#if defined(DEBUG_RELIGION) || defined(DEBUG_XOM)
        mprf(MSGCH_DIAGNOSTICS, "badness: %d, new interest: %d",
             badness, you.gift_timeout);
#endif
    }

    _handle_accidental_death(orig_hp, orig_mutation, orig_form);

    if (you_worship(GOD_XOM) && one_chance_in(5))
    {
        const string old_xom_favour = describe_xom_favour();
        you.raw_piety = random2(MAX_PIETY + 1);
        you.redraw_title = true; // redraw piety/boredom display
        const string new_xom_favour = describe_xom_favour();
        if (was_bored || old_xom_favour != new_xom_favour)
        {
            const string msg = "You are now " + new_xom_favour;
            god_speaks(you.religion, msg.c_str());
        }
#ifdef NOTE_DEBUG_XOM
        const string note = string("reroll piety: ") + you.raw_piety;
        take_note(Note(NOTE_MESSAGE, 0, 0, note), true);
#endif
    }
    else if (was_bored)
    {
        // If we didn't reroll at least mention the new favour
        // now that it's not "BORING thing" anymore.
        const string new_xom_favour = describe_xom_favour();
        const string msg = "You are now " + new_xom_favour;
        god_speaks(you.religion, msg.c_str());
    }
}

/**
 * Let Xom take an action, probably.
 *
 * @param sever         The intended magnitude of the action.
 * @param nice          Whether the action should be 'good' for the player.
 *                      If maybe_bool::maybe, determined by xom's whim.
 *                      May be overridden.
 * @param tension       How much danger we think the player's currently in.
 * @return              Whichever action Xom took, or XOM_DID_NOTHING.
 */
xom_event_type xom_acts(int sever, maybe_bool nice, int tension, bool debug)
{
    bool niceness = nice.to_bool(xom_is_nice(tension));

#if defined(DEBUG_RELIGION) || defined(DEBUG_XOM)
    if (!debug)
    {
        // This probably seems a bit odd, but we really don't want to display
        // these when doing a heavy-duty wiz-mode debug test: just ends up
        // as message spam and the player doesn't get any further information
        // anyway. (jpeg)

        // these numbers (sever, tension) may be modified later...
        mprf(MSGCH_DIAGNOSTICS, "xom_acts(%u, %d, %d); piety: %u, interest: %u",
             niceness, sever, tension, you.raw_piety, you.gift_timeout);

        static char xom_buf[100];
        snprintf(xom_buf, sizeof(xom_buf), "xom_acts(%s, %d, %d), mood: %d",
                 (niceness ? "true" : "false"), sever, tension, you.raw_piety);
        take_note(Note(NOTE_MESSAGE, 0, 0, xom_buf), true);
    }
#endif

    if (tension == -1)
        tension = get_tension(GOD_XOM);

#if defined(DEBUG_RELIGION) || defined(DEBUG_XOM) || defined(DEBUG_TENSION)
    // No message during heavy-duty wizmode testing:
    // Instead all results are written into xom_debug.stat.
    if (!debug)
        mprf(MSGCH_DIAGNOSTICS, "Xom tension: %d", tension);
#endif

    const xom_event_type action = xom_choose_action(niceness, sever, tension);
    if (!debug)
        xom_take_action(action, sever);

    return action;
}

void xom_check_lost_item(const item_def& item)
{
    if (is_unrandom_artefact(item))
        xom_is_stimulated(100, "Xom snickers.", true);
}

void xom_check_destroyed_item(const item_def& item)
{
    if (is_unrandom_artefact(item))
        xom_is_stimulated(100, "Xom snickers.", true);
}

static bool _death_is_funny(const kill_method_type killed_by)
{
    switch (killed_by)
    {
    // The less original deaths are considered boring.
    case KILLED_BY_MONSTER:
    case KILLED_BY_BEAM:
    case KILLED_BY_CLOUD:
    case KILLED_BY_FREEZING:
    case KILLED_BY_BURNING:
    case KILLED_BY_SELF_AIMED:
    case KILLED_BY_SOMETHING:
    case KILLED_BY_TRAP:
        return false;
    default:
        // All others are fun (says Xom).
        return true;
    }
}

void xom_death_message(const kill_method_type killed_by)
{
    if (!you_worship(GOD_XOM) && (!you.worshipped[GOD_XOM] || coinflip()))
        return;

    const int death_tension = get_tension(GOD_XOM);

    // "Normal" deaths with only down to -2 hp and comparatively low tension
    // are considered particularly boring.
    if (!_death_is_funny(killed_by) && you.hp >= -1 * random2(3)
        && death_tension <= random2(10))
    {
        god_speaks(GOD_XOM, _get_xom_speech("boring death").c_str());
    }
    // Unusual methods of dying, really low hp, or high tension make
    // for funny deaths.
    else if (_death_is_funny(killed_by) || you.hp <= -10
             || death_tension >= 20)
    {
        god_speaks(GOD_XOM, _get_xom_speech("laughter").c_str());
    }

    // All others just get ignored by Xom.
}

static int _death_is_worth_saving(const kill_method_type killed_by)
{
    switch (killed_by)
    {
    // These don't count.
    case KILLED_BY_LEAVING:
    case KILLED_BY_WINNING:
    case KILLED_BY_QUITTING:

    // These are too much hassle.
    case KILLED_BY_LAVA:
    case KILLED_BY_WATER:
    case KILLED_BY_DRAINING:
    case KILLED_BY_STARVATION:
    case KILLED_BY_ZOT:
    case KILLED_BY_ROTTING:

    // Don't protect the player from these.
    case KILLED_BY_SELF_AIMED:
    case KILLED_BY_TARGETING:
        return false;

    // Everything else is fair game.
    default:
        return true;
    }
}

static string _get_death_type_keyword(const kill_method_type killed_by)
{
    switch (killed_by)
    {
    case KILLED_BY_MONSTER:
    case KILLED_BY_BEAM:
    case KILLED_BY_BEOGH_SMITING:
    case KILLED_BY_TSO_SMITING:
    case KILLED_BY_DIVINE_WRATH:
        return "actor";
    default:
        return "general";
    }
}

/**
 * Have Xom maybe act to save your life. There is both a flat chance
 * and an additional chance based on tension that he will refuse to
 * save you.
 * @param death_type  The type of death that occurred.
 * @return            True if Xom saves your life, false otherwise.
 */
bool xom_saves_your_life(const kill_method_type death_type)
{
    if (!you_worship(GOD_XOM) || _xom_feels_nasty())
        return false;

    // If this happens, don't bother.
    if (you.hp_max < 1 || you.experience_level < 1)
        return false;

    // Generally a rare effect.
    if (!one_chance_in(20))
        return false;

    if (!_death_is_worth_saving(death_type))
        return false;

    // In addition, the chance depends on the current tension and Xom's mood.
    const int death_tension = get_tension(GOD_XOM);
    if (death_tension < random2(5) || !xom_is_nice(death_tension))
        return false;

    // Fake death message.
    canned_msg(MSG_YOU_DIE);
    more();

    const string key = _get_death_type_keyword(death_type);
    // XOM_SPEECH("life saving actor") or XOM_SPEECH("life saving general")
    string speech = _get_xom_speech("life saving " + key);
    god_speaks(GOD_XOM, speech.c_str());

    // Give back some hp.
    if (you.hp < 1)
        set_hp(1 + random2(you.hp_max/4));

    god_speaks(GOD_XOM, "Xom revives you!");

    // Ideally, this should contain the death cause but that is too much
    // trouble for now.
    take_note(Note(NOTE_XOM_REVIVAL));

    // Make sure Xom doesn't get bored within the next couple of turns.
    if (you.gift_timeout < 10)
        you.gift_timeout = 10;

    return true;
}

// Xom might have something to say when you enter a new level.
void xom_new_level_noise_or_stealth()
{
    if (!you_worship(GOD_XOM) && !player_under_penance(GOD_XOM))
        return;

    // But only occasionally.
    if (one_chance_in(30))
    {
        if (!player_under_penance(GOD_XOM) && coinflip())
        {
            god_speaks(GOD_XOM, _get_xom_speech("stealth player").c_str());
            mpr(you.duration[DUR_STEALTH] ? "You feel more stealthy."
                                          : "You feel stealthy.");
            you.increase_duration(DUR_STEALTH, 10 + random2(80));
            take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1,
                           "stealth player"), true);
        }
        else
            _xom_noise(-1);
    }
    return;
}

/**
 * The Xom teleportation train takes you on instant
 * teleportation to a few random areas, stopping randomly but
 * most likely in an area that is not dangerous to you.
 */
static void _xom_good_teleport(int /*sever*/)
{
    god_speaks(GOD_XOM, _get_xom_speech("teleportation journey").c_str());
    int count = 0;
    do
    {
        count++;
        you_teleport_now();
        more();
        if (one_chance_in(10) || count >= 7 + random2(5))
            break;
    }
    while (x_chance_in_y(3, 4) || player_in_a_dangerous_place());

    // Take a note.
    const string note = make_stringf("%d-stop teleportation journey%s", count,
#ifdef NOTE_DEBUG_XOM
             player_in_a_dangerous_place() ? " (dangerous)" :
#endif
             "");
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

/**
 * The Xom teleportation train takes you on instant
 * teleportation to a few random areas, stopping if either
 * an area is dangerous to you or randomly.
 */
static void _xom_bad_teleport(int /*sever*/)
{
    god_speaks(GOD_XOM,
               _get_xom_speech("teleportation journey").c_str());

    int count = 0;
    do
    {
        you_teleport_now();
        more();
        if (count++ >= 7 + random2(5))
            break;
    }
    while (x_chance_in_y(3, 4) && !player_in_a_dangerous_place());

    // Take a note.
    const string note = make_stringf("%d-stop teleportation journey%s", count,
#ifdef NOTE_DEBUG_XOM
             badness == 3 ? " (dangerous)" : "");
#else
    "");
#endif
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, note), true);
}

/// Place a one-tile chaos cloud on the player, with minor spreading.
static void _xom_chaos_cloud(int /*sever*/)
{
    const int lifetime = 3 + random2(12) * 3;
    const int spread_rate = random_range(5,15);
    place_cloud(CLOUD_CHAOS, you.pos(), lifetime, nullptr, spread_rate);
    take_note(Note(NOTE_XOM_EFFECT, you.raw_piety, -1, "chaos cloud"),
              true);
    god_speaks(GOD_XOM, _get_xom_speech("cloud").c_str());
}

struct xom_effect_count
{
    string effect;
    int    count;

    xom_effect_count(string e, int c) : effect(e), count(c) {};
};

/// A type of action Xom can take.
struct xom_event
{
    /// Wizmode name for the event.
    const char* name;
    /// The event action.
    function<void(int sever)> action;
    /**
     * Rough estimate of how hard a Xom effect hits the player,
     * scaled between 10 (harmless) and 50 (disastrous). Reduces boredom.
     */
    int badness_10x;
};

static const map<xom_event_type, xom_event> xom_events = {
    { XOM_DID_NOTHING, { "nothing" }},
    { XOM_GOOD_POTION, { "potion", _xom_do_potion }},
    { XOM_GOOD_DIVINATION, { "magic mapping + detect items / creatures",
                              _xom_divination }},
    { XOM_GOOD_SPELL, { "tension spell", _xom_random_spell }},
    { XOM_GOOD_CONFUSION, { "confuse monsters", _xom_confuse_monsters }},
    { XOM_GOOD_SINGLE_ALLY, { "single ally", _xom_send_one_ally }},
    { XOM_GOOD_ANIMATE_MON_WPN, { "animate monster weapon",
                                  _xom_animate_monster_weapon }},
    { XOM_GOOD_RANDOM_ITEM, { "random item gift", _xom_random_item }},
    { XOM_GOOD_ACQUIREMENT, { "acquirement", _xom_acquirement }},
    { XOM_GOOD_BAZAAR_TRIP, { "bazaar trip", _xom_bazaar_trip }},
    { XOM_GOOD_ALLIES, { "summon allies", _xom_send_allies }},
    { XOM_GOOD_POLYMORPH, { "good polymorph", _xom_good_polymorph }},
    { XOM_GOOD_TELEPORT, { "good teleportation", _xom_good_teleport }},
    { XOM_GOOD_MUTATION, { "good mutations", _xom_give_good_mutations }},
    { XOM_GOOD_LIGHTNING, { "lightning", _xom_throw_divine_lightning }},
    { XOM_GOOD_SCENERY, { "change scenery", _xom_change_scenery }},
    { XOM_GOOD_FLORA_RING, {"flora ring", _xom_harmless_flora }},
    { XOM_GOOD_DOOR_RING, {"good door ring enclosure", _xom_good_door_ring }},
    { XOM_GOOD_SNAKES, { "snakes to sticks", _xom_snakes_to_sticks }},
    { XOM_GOOD_LIGHT_UP_WEBS, { "light up webs", _xom_lights_up_webs }},
    { XOM_GOOD_DESTRUCTION, { "mass fireball", _xom_real_destruction }},
    { XOM_GOOD_FAKE_DESTRUCTION, { "fake fireball", _xom_fake_destruction }},
    { XOM_GOOD_FORCE_LANCE_FLEET, {"living force lance fleet",
                                   _xom_force_lances }},
    { XOM_GOOD_ENCHANT_MONSTER, { "good enchant monster",
                                  _xom_good_enchant_monster }},
    { XOM_GOOD_HYPER_ENCHANT_MONSTER, { "hyper enchant monster",
                                        _xom_hyper_enchant_monster }},
    { XOM_GOOD_MASS_CHARM, {"mass charm", _xom_mass_charm }},
    { XOM_GOOD_WAVE_OF_DESPAIR, {"wave of despair", _xom_wave_of_despair }},
    { XOM_GOOD_FOG, { "fog", _xom_fog }},
    { XOM_GOOD_CLOUD_TRAIL, { "cloud trail", _xom_cloud_trail }},
    { XOM_GOOD_CLEAVING, { "cleaving", _xom_cleaving }},

    { XOM_BAD_MISCAST_PSEUDO, { "pseudo-miscast", _xom_pseudo_miscast, 20}},
    { XOM_BAD_NOISE, { "noise", _xom_noise, 10 }},
    { XOM_BAD_ENCHANT_MONSTER, { "bad enchant monster",
                                 _xom_bad_enchant_monster, 10}},
    { XOM_BAD_TIME_CONTROL, {"time control", _xom_time_control, 15}},
    { XOM_BAD_BLINK_MONSTERS, { "blink monsters", _xom_blink_monsters, 10}},
    { XOM_BAD_CONFUSION, { "confuse player", _xom_player_confusion_effect, 13}},
    { XOM_BAD_SWAP_MONSTERS, { "swap monsters", _xom_rearrange_pieces, 20 }},
    { XOM_BAD_CHAOS_UPGRADE, { "chaos upgrade", _xom_chaos_upgrade, 20}},
    { XOM_BAD_TELEPORT, { "bad teleportation", _xom_bad_teleport, -1}},
    { XOM_BAD_POLYMORPH, { "bad polymorph", _xom_bad_polymorph, 30}},
    { XOM_BAD_MOVING_STAIRS, { "moving stairs", _xom_moving_stairs, 20}},
    { XOM_BAD_CLIMB_STAIRS, { "unclimbable stairs", _xom_unclimbable_stairs,
                              30}},
    { XOM_BAD_FIDDLE_WITH_DOORS, { "open and close doors", _xom_open_and_close_doors,
                                    15}},
    { XOM_BAD_DOOR_RING, {"bad door ring enclosure", _xom_bad_door_ring, 25}},
    { XOM_BAD_FAKE_SHATTER, {"fake shatter", _xom_fake_shatter, 25}},
    { XOM_BAD_MUTATION, { "random mutations", _xom_give_bad_mutations, 30}},
    { XOM_BAD_SUMMON_HOSTILES, { "summon hostiles", _xom_summon_hostiles, 35}},
    { XOM_BAD_SEND_IN_THE_CLONES, {"friendly and hostile illusions",
                                   _xom_send_in_clones, 40}},
    { XOM_BAD_GRANT_WORD_OF_RECALL, {"speaker of recall",
                                    _xom_grants_word_of_recall, 40}},
    { XOM_BAD_BRAIN_DRAIN, {"mp brain drain", _xom_brain_drain, 30}},
    { XOM_BAD_DRAINING, { "draining", _xom_draining, 23}},
    { XOM_BAD_DOOM, { "doom", _xom_doom, 23}},
    { XOM_BAD_TORMENT, { "torment", _xom_torment, 23}},
    { XOM_BAD_CHAOS_CLOUD, { "chaos cloud", _xom_chaos_cloud, 20}},
    { XOM_BAD_BANISHMENT, { "banishment", _xom_banishment, 50}},
    { XOM_BAD_PSEUDO_BANISHMENT, {"pseudo-banishment", _xom_pseudo_banishment,
                                  10}},
};

static void _do_xom_event(xom_event_type event_type, int sever)
{
    const xom_event *event = map_find(xom_events, event_type);
    if (event && event->action)
        event->action(sever);
}

static int _xom_event_badness(xom_event_type event_type)
{
    if (event_type == XOM_BAD_TELEPORT)
        return player_in_a_dangerous_place() ? 3 : 1;

    const xom_event *event = map_find(xom_events, event_type);
    if (event)
        return div_rand_round(event->badness_10x, 10);
    return 0;
}

string xom_effect_to_name(xom_event_type effect)
{
    const xom_event *event = map_find(xom_events, effect);
    return event ? event->name : "bugginess";
}

/// Basic sanity checks on xom_events.
void validate_xom_events()
{
    string fails;
    set<string> action_names;

    for (int i = 0; i < XOM_LAST_REAL_ACT; ++i)
    {
        const xom_event_type event_type = static_cast<xom_event_type>(i);
        const xom_event *event = map_find(xom_events, event_type);
        if (!event)
        {
            fails += make_stringf("Xom event %d has no associated data!\n", i);
            continue;
        }

        if (action_names.count(event->name))
            fails += make_stringf("Duplicate name '%s'!\n", event->name);
        action_names.insert(event->name);

        if (_action_is_bad(event_type))
        {
            if ((event->badness_10x < 10 || event->badness_10x > 50)
                && event->badness_10x != -1) // implies it's special-cased
            {
                fails += make_stringf("'%s' badness %d outside 10-50 range.\n",
                                      event->name, event->badness_10x);
            }
        }
        else if (event->badness_10x)
        {
            fails += make_stringf("'%s' is not bad, but has badness!\n",
                                  event->name);
        }

        if (event_type != XOM_DID_NOTHING && !event->action)
            fails += make_stringf("No action for '%s'!\n", event->name);
    }

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

#ifdef WIZARD
static bool _sort_xom_effects(const xom_effect_count &a,
                              const xom_effect_count &b)
{
    if (a.count == b.count)
        return a.effect < b.effect;

    return a.count > b.count;
}

static string _list_exploration_estimate()
{
    int explored = 0;
    int mapped   = 0;
    for (int k = 0; k < 10; ++k)
    {
        mapped   += _exploration_estimate(false);
        explored += _exploration_estimate(true);
    }
    mapped /= 10;
    explored /= 10;

    return make_stringf("mapping estimate: %d%%\nexploration estimate: %d%%\n",
                        mapped, explored);
}

// Loops over the entire piety spectrum and calls xom_acts() multiple
// times for each value, then prints the results into a file.
// TODO: Allow specification of niceness, tension, and boredness.
void debug_xom_effects()
{
    // Repeat N times.
    const int N = prompt_for_int("How many iterations over the "
                                 "entire piety range? ", true);

    if (N <= 0)
    {
        canned_msg(MSG_OK);
        return;
    }

    FILE *ostat = fopen_u("xom_debug.stat", "w");
    if (!ostat)
    {
        mprf(MSGCH_ERROR, "Can't write 'xom_debug.stat'. Aborting.");
        return;
    }

    const int real_piety    = you.raw_piety;
    const god_type real_god = you.religion;
    you.religion            = GOD_XOM;
    const int tension       = get_tension(GOD_XOM);

    fprintf(ostat, "---- STARTING XOM DEBUG TESTING ----\n");
    fprintf(ostat, "%s\n", dump_overview_screen().c_str());
    fprintf(ostat, "%s\n", screenshot().c_str());
    fprintf(ostat, "%s\n", _list_exploration_estimate().c_str());
    fprintf(ostat, "%s\n", mpr_monster_list().c_str());
    fprintf(ostat, " --> Tension: %d\n", tension);

    if (player_under_penance(GOD_XOM))
        fprintf(ostat, "You are under Xom's penance!\n");
    else if (_xom_is_bored())
        fprintf(ostat, "Xom is BORED.\n");
    fprintf(ostat, "\nRunning %d times through entire mood cycle.\n", N);
    fprintf(ostat, "---- OUTPUT EFFECT PERCENTAGES ----\n");

    vector<xom_event_type>          mood_effects;
    vector<vector<xom_event_type>>  all_effects;
    vector<string>                  moods;
    vector<int>                     mood_good_acts;

    string old_mood = "";
    string     mood = "";

    // Add an empty list to later add all effects to.
    all_effects.push_back(mood_effects);
    moods.emplace_back("total");
    mood_good_acts.push_back(0); // count total good acts

    int mood_good = 0;
    for (int p = 0; p <= MAX_PIETY; ++p)
    {
        you.raw_piety = p;
        int sever     = abs(p - HALF_MAX_PIETY);
        mood          = describe_xom_mood();
        if (old_mood != mood)
        {
            if (!old_mood.empty())
            {
                all_effects.push_back(mood_effects);
                mood_effects.clear();
                mood_good_acts.push_back(mood_good);
                mood_good_acts[0] += mood_good;
                mood_good = 0;
            }
            moods.push_back(mood);
            old_mood = mood;
        }

        // Repeat N times.
        for (int i = 0; i < N; ++i)
        {
            const xom_event_type result = xom_acts(sever, maybe_bool::maybe, tension,
                                                   true);

            mood_effects.push_back(result);
            all_effects[0].push_back(result);

            if (result <= XOM_LAST_GOOD_ACT)
                mood_good++;
        }
    }
    all_effects.push_back(mood_effects);
    mood_effects.clear();
    mood_good_acts.push_back(mood_good);
    mood_good_acts[0] += mood_good;

    const int num_moods = moods.size();
    vector<xom_effect_count> xom_ec_pairs;
    for (int i = 0; i < num_moods; ++i)
    {
        mood_effects    = all_effects[i];
        const int total = mood_effects.size();

        if (i == 0)
            fprintf(ostat, "\nTotal effects (all piety ranges)\n");
        else
            fprintf(ostat, "\nMood: You are %s\n", moods[i].c_str());

        fprintf(ostat, "GOOD%7.2f%%\n",
                (100.0 * (float) mood_good_acts[i] / (float) total));
        fprintf(ostat, "BAD %7.2f%%\n",
                (100.0 * (float) (total - mood_good_acts[i]) / (float) total));

        sort(mood_effects.begin(), mood_effects.end());

        xom_ec_pairs.clear();
        xom_event_type old_effect = XOM_DID_NOTHING;
        int count      = 0;
        for (int k = 0; k < total; ++k)
        {
            if (mood_effects[k] != old_effect)
            {
                if (count > 0)
                {
                    xom_ec_pairs.emplace_back(xom_effect_to_name(old_effect),
                                              count);
                }
                old_effect = mood_effects[k];
                count = 1;
            }
            else
                count++;
        }

        if (count > 0)
            xom_ec_pairs.emplace_back(xom_effect_to_name(old_effect), count);

        sort(xom_ec_pairs.begin(), xom_ec_pairs.end(), _sort_xom_effects);
        for (const xom_effect_count &xec : xom_ec_pairs)
        {
            fprintf(ostat, "%7.2f%%    %s\n",
                    (100.0 * xec.count / total),
                    xec.effect.c_str());
        }
    }
    fprintf(ostat, "---- FINISHED XOM DEBUG TESTING ----\n");
    fclose(ostat);
    mpr("Results written into 'xom_debug.stat'.");

    you.raw_piety= real_piety;
    you.religion = real_god;
}
#endif // WIZARD