summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/describe.cc
blob: e7799c92c6fb9dd55ff1a1189ea1456021cdabfd (plain) (blame)
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
/**
 * @file
 * @brief Functions used to print information about various game objects.
**/

#include "AppHdr.h"

#include "describe.h"
#include "process_desc.h"
#include "database.h"

#include <stdio.h>
#include <string>
#include <sstream>
#include <iomanip>
#include <numeric>

#include "externs.h"
#include "options.h"
#include "species.h"

#include "ability.h"
#include "artefact.h"
#include "branch.h"
#include "cio.h"
#include "clua.h"
#include "command.h"
#include "decks.h"
#include "delay.h"
#include "directn.h"
#include "fight.h"
#include "food.h"
#include "ghost.h"
#include "godabil.h"
#include "goditem.h"
#include "godpassive.h"
#include "invent.h"
#include "item_use.h"
#include "itemname.h"
#include "itemprop.h"
#include "items.h"
#include "evoke.h"
#include "jobs.h"
#include "libutil.h"
#include "macro.h"
#include "menu.h"
#include "message.h"
#include "mon-book.h"
#include "mon-chimera.h"
#include "mon-util.h"
#include "output.h"
#include "player.h"
#include "prompt.h"
#include "quiver.h"
#include "religion.h"
#include "skills2.h"
#include "spl-book.h"
#include "spl-summoning.h"
#include "state.h"
#include "strings.h"
#include "unicode.h"
#include "env.h"
#include "spl-cast.h"
#include "spl-util.h"
#include "spl-wpnench.h"
#include "stash.h"
#include "terrain.h"
#include "transform.h"
#include "hints.h"
#include "xom.h"
#include "mon-info.h"
#ifdef USE_TILE_LOCAL
#include "tilereg-crt.h"
#endif
// ========================================================================
//      Internal Functions
// ========================================================================

//---------------------------------------------------------------
//
// append_value
//
// Appends a value to the string. If plussed == 1, will add a + to
// positive values.
//
//---------------------------------------------------------------
static void _append_value(string & description, int valu, bool plussed)
{
    char value_str[80];
    sprintf(value_str, plussed ? "%+d" : "%d", valu);
    description += value_str;
}

static void _append_value(string & description, float fvalu, bool plussed)
{
    char value_str[80];
    sprintf(value_str, plussed ? "%+.1f" : "%.1f", fvalu);
    description += value_str;
}

int count_desc_lines(const string &_desc, const int width)
{
    string desc = get_linebreak_string(_desc, width);

    int count = 0;
    for (int i = 0, size = desc.size(); i < size; ++i)
    {
        const char ch = desc[i];

        if (ch == '\n')
            count++;
    }

    return count;
}

static void _adjust_item(item_def &item);

//---------------------------------------------------------------
//
// print_description
//
// Takes a descrip string filled up with stuff from other functions,
// and displays it with minor formatting to avoid cut-offs in mid
// word and such.
//
//---------------------------------------------------------------

void print_description(const string &body)
{
    describe_info inf;
    inf.body << body;
    print_description(inf);
}

class default_desc_proc
{
public:
    int width() { return get_number_of_cols() - 1; }
    int height() { return get_number_of_lines(); }
    void print(const string &str) { cprintf("%s", str.c_str()); }

    void nextline()
    {
        if (wherey() < height())
            cgotoxy(1, wherey() + 1);
        else
            cgotoxy(1, height());
        // Otherwise cgotoxy asserts; let's just clobber the last line
        // instead, which should be noticeable enough.
    }
};

void print_description(const describe_info &inf)
{
    clrscr();
    textcolor(LIGHTGREY);

    default_desc_proc proc;
    process_description<default_desc_proc>(proc, inf);
}

static void _print_quote(const describe_info &inf)
{
    clrscr();
    textcolor(LIGHTGREY);

    default_desc_proc proc;
    process_quote<default_desc_proc>(proc, inf);
}

static const char* _jewellery_base_ability_string(int subtype)
{
    switch (subtype)
    {
    case RING_SUSTAIN_ABILITIES: return "SustAb";
    case RING_WIZARDRY:          return "Wiz";
    case RING_FIRE:              return "Fire";
    case RING_ICE:               return "Ice";
    case RING_TELEPORTATION:     return "+/*Tele";
    case RING_TELEPORT_CONTROL:  return "+cTele";
    case AMU_CLARITY:            return "Clar";
    case AMU_WARDING:            return "Ward";
    case AMU_RESIST_CORROSION:   return "rCorr";
    case AMU_THE_GOURMAND:       return "Gourm";
#if TAG_MAJOR_VERSION == 34
    case AMU_CONSERVATION:       return "Cons";
    case AMU_CONTROLLED_FLIGHT:  return "cFly";
#endif
    case AMU_RESIST_MUTATION:    return "rMut";
    case AMU_GUARDIAN_SPIRIT:    return "Spirit";
    case AMU_FAITH:              return "Faith";
    case AMU_STASIS:             return "Stasis";
    case AMU_INACCURACY:         return "Inacc";
    }
    return "";
}

#define known_proprt(prop) (proprt[(prop)] && known[(prop)])

struct property_annotators
{
    const char* name;
    artefact_prop_type prop;
    int spell_out;              // 0: "+3", 1: "+++", 2: value doesn't matter
};

static vector<string> _randart_propnames(const item_def& item,
                                         bool no_comma = false)
{
    artefact_properties_t  proprt;
    artefact_known_props_t known;
    artefact_desc_properties(item, proprt, known, true);

    vector<string> propnames;

    // list the following in rough order of importance
    const property_annotators propanns[] =
    {
        // (Generally) negative attributes
        // These come first, so they don't get chopped off!
        { "-Cast",  ARTP_PREVENT_SPELLCASTING,  2 },
        { "-Tele",  ARTP_PREVENT_TELEPORTATION, 2 },
        { "Contam", ARTP_MUTAGENIC,             2 },
        { "*Rage",  ARTP_ANGRY,                 2 },
        { "*Tele",  ARTP_CAUSE_TELEPORTATION,   2 },
        { "Noisy",  ARTP_NOISES,                2 },

        // Evokable abilities come second
        { "+Blink", ARTP_BLINK,                 2 },
        { "+Rage",  ARTP_BERSERK,               2 },
        { "+Inv",   ARTP_INVISIBLE,             2 },
        { "+Fly",   ARTP_FLY,                   2 },
        { "+Fog",   ARTP_FOG,                   2 },

        // Resists, also really important
        { "rElec",  ARTP_ELECTRICITY,           2 },
        { "rPois",  ARTP_POISON,                2 },
        { "rF",     ARTP_FIRE,                  1 },
        { "rC",     ARTP_COLD,                  1 },
        { "rN",     ARTP_NEGATIVE_ENERGY,       1 },
        { "MR",     ARTP_MAGIC,                 1 },

        // Quantitative attributes
        { "HP",     ARTP_HP,                    0 },
        { "MP",     ARTP_MAGICAL_POWER,         0 },
        { "AC",     ARTP_AC,                    0 },
        { "EV",     ARTP_EVASION,               0 },
        { "Str",    ARTP_STRENGTH,              0 },
        { "Dex",    ARTP_DEXTERITY,             0 },
        { "Int",    ARTP_INTELLIGENCE,          0 },
        { "Slay",   ARTP_SLAYING,               0 },

        // Qualitative attributes (and Stealth)
        { "SInv",   ARTP_EYESIGHT,              2 },
        { "Stlth",  ARTP_STEALTH,               1 },
        { "Curse",  ARTP_CURSED,                2 },
        { "Clar",   ARTP_CLARITY,               2 },
        { "RMsl",   ARTP_RMSL,                  2 },
        { "Regen",  ARTP_REGENERATION,          2 },
        { "SustAb", ARTP_SUSTAB,                2 },
    };

    // For randart jewellery, note the base jewellery type if it's not
    // covered by artefact_desc_properties()
    if (item.base_type == OBJ_JEWELLERY
        && (item_ident(item, ISFLAG_KNOW_TYPE)))
    {
        const char* type = _jewellery_base_ability_string(item.sub_type);
        if (*type)
            propnames.push_back(type);
    }
    else if (item_ident(item, ISFLAG_KNOW_TYPE)
             || is_artefact(item)
                && artefact_known_wpn_property(item, ARTP_BRAND))
    {
        string ego;
        if (item.base_type == OBJ_WEAPONS)
            ego = weapon_brand_name(item, true);
        else if (item.base_type == OBJ_ARMOUR)
            ego = armour_ego_name(item, true);
        if (!ego.empty())
        {
            // XXX: Ugly hack for adding a comma if needed.
            for (unsigned i = 0; i < ARRAYSZ(propanns); ++i)
                if (known_proprt(propanns[i].prop)
                    && propanns[i].prop != ARTP_BRAND
                    && !no_comma)
                {
                    ego += ",";
                    break;
                }

            propnames.push_back(ego);
        }
    }

    if (is_unrandom_artefact(item))
    {
        const unrandart_entry *entry = get_unrand_entry(item.special);
        if (entry && entry->inscrip != NULL)
            propnames.push_back(entry->inscrip);
     }

    for (unsigned i = 0; i < ARRAYSZ(propanns); ++i)
    {
        if (known_proprt(propanns[i].prop))
        {
            const int val = proprt[propanns[i].prop];

            // Don't show rF+/rC- for =Fire, or vice versa for =Ice.
            if (item.base_type == OBJ_JEWELLERY)
            {
                if (item.sub_type == RING_FIRE
                    && (propanns[i].prop == ARTP_FIRE && val == 1
                        || propanns[i].prop == ARTP_COLD && val == -1))
                {
                    continue;
                }
                if (item.sub_type == RING_ICE
                    && (propanns[i].prop == ARTP_COLD && val == 1
                        || propanns[i].prop == ARTP_FIRE && val == -1))
                {
                    continue;
                }
            }

            ostringstream work;
            switch (propanns[i].spell_out)
            {
            case 0: // e.g. AC+4
                work << showpos << propanns[i].name << val;
                break;
            case 1: // e.g. F++
            {
                const int sval = min(abs(val), 3);
                work << propanns[i].name
                     << string(sval, (val > 0 ? '+' : '-'));
                break;
            }
            case 2: // e.g. rPois or SInv
                if (propanns[i].prop == ARTP_CURSED && val < 1)
                    continue;

                work << propanns[i].name;
                break;
            }
            propnames.push_back(work.str());
        }
    }

    return propnames;
}

string artefact_inscription(const item_def& item)
{
    if (item.base_type == OBJ_BOOKS)
        return "";

    const vector<string> propnames = _randart_propnames(item);

    string insc = comma_separated_line(propnames.begin(), propnames.end(),
                                       " ", " ");
    if (!insc.empty() && insc[insc.length() - 1] == ',')
        insc.erase(insc.length() - 1);
    return insc;
}

void add_inscription(item_def &item, string inscrip)
{
    if (!item.inscription.empty())
    {
        if (ends_with(item.inscription, ","))
            item.inscription += " ";
        else
            item.inscription += ", ";
    }

    item.inscription += inscrip;
}

static const char* _jewellery_base_ability_description(int subtype)
{
    switch (subtype)
    {
    case RING_SUSTAIN_ABILITIES:
        return "It sustains your strength, intelligence and dexterity.";
    case RING_WIZARDRY:
        return "It improves your spell success rate.";
    case RING_FIRE:
        return "It enhances your fire magic, and weakens your ice magic.";
    case RING_ICE:
        return "It enhances your ice magic, and weakens your fire magic.";
    case RING_TELEPORTATION:
        return "It causes random teleportation, and can be evoked to teleport "
               "at will.";
    case RING_TELEPORT_CONTROL:
        return "It can be evoked for teleport control.";
    case AMU_CLARITY:
        return "It provides mental clarity.";
    case AMU_WARDING:
        return "It may prevent the melee attacks of summoned creatures.";
    case AMU_RESIST_CORROSION:
        return "It protects you from acid and corrosion.";
    case AMU_THE_GOURMAND:
        return "It allows you to eat raw meat even when not hungry.";
#if TAG_MAJOR_VERSION == 34
    case AMU_CONSERVATION:
        return "It protects your inventory from destruction.";
#endif
    case AMU_RESIST_MUTATION:
        return "It protects you from mutation.";
    case AMU_GUARDIAN_SPIRIT:
        return "It causes incoming damage to be split between your health and "
               "magic.";
    case AMU_FAITH:
        return "It allows you to gain divine favour quickly.";
    case AMU_STASIS:
        return "It prevents you from being teleported, slowed, hasted or "
               "paralysed.";
    case AMU_INACCURACY:
        return "It reduces the accuracy of all your attacks.";
    }
    return "";
}

struct property_descriptor
{
    artefact_prop_type property;
    const char* desc;           // If it contains %d, will be replaced by value.
    bool is_graded_resist;
};

static string _randart_descrip(const item_def &item)
{
    string description;

    artefact_properties_t  proprt;
    artefact_known_props_t known;
    artefact_desc_properties(item, proprt, known, true);

    const property_descriptor propdescs[] =
    {
        { ARTP_AC, "It affects your AC (%d).", false },
        { ARTP_EVASION, "It affects your evasion (%d).", false},
        { ARTP_STRENGTH, "It affects your strength (%d).", false},
        { ARTP_INTELLIGENCE, "It affects your intelligence (%d).", false},
        { ARTP_DEXTERITY, "It affects your dexterity (%d).", false},
        { ARTP_SLAYING, "It affects your accuracy and damage with ranged "
                        "weapons and melee attacks (%d).", false},
        { ARTP_FIRE, "fire", true},
        { ARTP_COLD, "cold", true},
        { ARTP_ELECTRICITY, "It insulates you from electricity.", false},
        { ARTP_POISON, "It protects you from poison.", false},
        { ARTP_NEGATIVE_ENERGY, "negative energy", true},
        { ARTP_SUSTAB, "It sustains your strength, intelligence and dexterity.", false},
        { ARTP_MAGIC, "It affects your resistance to hostile enchantments.", false},
        { ARTP_HP, "It affects your health (%d).", false},
        { ARTP_MAGICAL_POWER, "It affects your magic capacity (%d).", false},
        { ARTP_EYESIGHT, "It enhances your eyesight.", false},
        { ARTP_INVISIBLE, "It lets you turn invisible.", false},
        { ARTP_FLY, "It lets you fly.", false},
        { ARTP_BLINK, "It lets you blink.", false},
        { ARTP_BERSERK, "It lets you go berserk.", false},
        { ARTP_NOISES, "It may make noises in combat.", false},
        { ARTP_PREVENT_SPELLCASTING, "It prevents spellcasting.", false},
        { ARTP_CAUSE_TELEPORTATION, "It causes random teleportation.", false},
        { ARTP_PREVENT_TELEPORTATION, "It prevents most forms of teleportation.",
          false},
        { ARTP_ANGRY,  "It may make you go berserk in combat.", false},
        { ARTP_CURSED, "It may recurse itself when equipped.", false},
        { ARTP_CLARITY, "It protects you against confusion.", false},
        { ARTP_MUTAGENIC, "It causes magical contamination when unequipped.", false},
        { ARTP_RMSL, "It protects you from missiles.", false},
        { ARTP_FOG, "It can be evoked to emit clouds of fog.", false},
        { ARTP_REGENERATION, "It increases your rate of regeneration.", false},
    };

    // Give a short description of the base type, for base types with no
    // corresponding ARTP.
    if (item.base_type == OBJ_JEWELLERY
        && (item_ident(item, ISFLAG_KNOW_TYPE)))
    {
        const char* type = _jewellery_base_ability_description(item.sub_type);
        if (*type)
        {
            description += "\n";
            description += type;
        }
    }

    for (unsigned i = 0; i < ARRAYSZ(propdescs); ++i)
    {
        if (known_proprt(propdescs[i].property))
        {
            // Only randarts with ARTP_CURSED > 0 may recurse themselves.
            if (propdescs[i].property == ARTP_CURSED
                && proprt[propdescs[i].property] < 1)
            {
                continue;
            }

            string sdesc = propdescs[i].desc;

            // FIXME Not the nicest hack.
            char buf[80];
            snprintf(buf, sizeof buf, "%+d", proprt[propdescs[i].property]);
            sdesc = replace_all(sdesc, "%d", buf);

            if (propdescs[i].is_graded_resist)
            {
                int idx = proprt[propdescs[i].property] + 3;
                idx = min(idx, 6);
                idx = max(idx, 0);

                const char* prefixes[] =
                {
                    "It makes you extremely vulnerable to ",
                    "It makes you very vulnerable to ",
                    "It makes you vulnerable to ",
                    "Buggy descriptor!",
                    "It protects you from ",
                    "It greatly protects you from ",
                    "It renders you almost immune to "
                };
                sdesc = prefixes[idx] + sdesc + '.';
            }

            description += '\n';
            description += sdesc;
        }
    }

    if (known_proprt(ARTP_STEALTH))
    {
        const int stval = proprt[ARTP_STEALTH];
        char buf[80];
        snprintf(buf, sizeof buf, "\nIt makes you %s%s stealthy.",
                 (stval < -1 || stval > 1) ? "much " : "",
                 (stval < 0) ? "less" : "more");
        description += buf;
    }

    return description;
}
#undef known_proprt

static const char *trap_names[] =
{
#if TAG_MAJOR_VERSION == 34
    "dart",
#endif
    "arrow", "spear",
#if TAG_MAJOR_VERSION > 34
    "teleport",
#endif
    "permanent teleport",
    "alarm", "blade",
    "bolt", "net", "Zot", "needle",
    "shaft", "passage", "pressure plate", "web",
#if TAG_MAJOR_VERSION == 34
    "gas", "teleport",
#endif
};

string trap_name(trap_type trap)
{
    COMPILE_CHECK(ARRAYSZ(trap_names) == NUM_TRAPS);

    if (trap >= 0 && trap < NUM_TRAPS)
        return trap_names[trap];
    return "";
}

string full_trap_name(trap_type trap)
{
    string basename = trap_name(trap);
    switch (trap)
    {
    case TRAP_GOLUBRIA:
        return basename + " of Golubria";
    case TRAP_PLATE:
    case TRAP_WEB:
    case TRAP_SHAFT:
        return basename;
    default:
        return basename + " trap";
    }
}

int str_to_trap(const string &s)
{
    // "Zot trap" is capitalised in trap_names[], but the other trap
    // names aren't.
    const string tspec = lowercase_string(s);

    // allow a couple of synonyms
    if (tspec == "random" || tspec == "any")
        return TRAP_RANDOM;
    else if (tspec == "nonteleport" || tspec == "noteleport"
             || tspec == "nontele" || tspec == "notele")
    {
        return TRAP_NONTELEPORT;
    }

    for (int i = 0; i < NUM_TRAPS; ++i)
        if (tspec == lowercase_string(trap_names[i]))
            return i;

    return -1;
}

//---------------------------------------------------------------
//
// describe_demon
//
// Describes the random demons you find in Pandemonium.
//
//---------------------------------------------------------------
static string _describe_demon(const string& name, flight_type fly)
{
    const uint32_t seed = hash32(&name[0], name.length());
    #define HRANDOM_ELEMENT(arr, id) arr[hash_rand(ARRAYSZ(arr), seed, id)]

    const char* body_descs[] =
    {
        "huge, barrel-shaped ",
        "wispy, insubstantial ",
        "spindly ",
        "skeletal ",
        "horribly deformed ",
        "spiny ",
        "waif-like ",
        "scaly ",
        "sickeningly deformed ",
        "bruised and bleeding ",
        "sickly ",
        "mass of writhing tentacles for a ",
        "mass of ropey tendrils for a ",
        "tree trunk-like ",
        "hairy ",
        "furry ",
        "fuzzy ",
        "obese ",
        "fat ",
        "slimy ",
        "wrinkled ",
        "metallic ",
        "glassy ",
        "crystalline ",
        "muscular ",
        "icky ",
        "swollen ",
        "lumpy ",
        "armoured ",
        "carapaced ",
        "slender ",
    };

    const char* wing_names[] =
    {
        " with small insectoid wings",
        " with large insectoid wings",
        " with moth-like wings",
        " with butterfly wings",
        " with huge, bat-like wings",
        " with fleshy wings",
        " with small, bat-like wings",
        " with hairy wings",
        " with great feathered wings",
        " with shiny metal wings",
    };

    const char* lev_names[] =
    {
        " which hovers in mid-air",
        " with sacs of gas hanging from its back",
    };

    const char* nonfly_names[] =
    {
        " covered in tiny crawling spiders",
        " covered in tiny crawling insects",
        " and the head of a crocodile",
        " and the head of a hippopotamus",
        " and a cruel curved beak for a mouth",
        " and a straight sharp beak for a mouth",
        " and no head at all",
        " and a hideous tangle of tentacles for a mouth",
        " and an elephantine trunk",
        " and an evil-looking proboscis",
        " and dozens of eyes",
        " and two ugly heads",
        " and a long serpentine tail",
        " and a pair of huge tusks growing from its jaw",
        " and a single huge eye in the centre of its forehead",
        " and spikes of black metal for teeth",
        " and a disc-shaped sucker for a head",
        " and huge, flapping ears",
        " and a huge, toothy maw in the centre of its chest",
        " and a giant snail shell on its back",
        " and a dozen heads",
        " and the head of a jackal",
        " and the head of a baboon",
        " and a huge, slobbery tongue",
        " which is covered in oozing lacerations",
        " and the head of a frog",
        " and the head of a yak",
        " and eyes out on stalks",
    };

    const char* misc_descs[] =
    {
        " It seethes with hatred of the living.",
        " Tiny orange flames dance around it.",
        " Tiny purple flames dance around it.",
        " It is surrounded by a weird haze.",
        " It glows with a malevolent light.",
        " It looks incredibly angry.",
        " It oozes with slime.",
        " It dribbles constantly.",
        " Mould grows all over it.",
        " It looks diseased.",
        " It looks as frightened of you as you are of it.",
        " It moves in a series of hideous convulsions.",
        " It moves with an unearthly grace.",
        " It hungers for your soul!",
        " It leaves a glistening oily trail.",
        " It shimmers before your eyes.",
        " It is surrounded by a brilliant glow.",
        " It radiates an aura of extreme power.",
    };

    ostringstream description;
    description << "A powerful demon, " << name << " has ";

    const string a_body = HRANDOM_ELEMENT(body_descs, 1);
    description << article_a(a_body) << "body";

    switch (fly)
    {
    case FL_WINGED:
        description << HRANDOM_ELEMENT(wing_names, 2);
        break;

    case FL_LEVITATE:
        description << HRANDOM_ELEMENT(lev_names, 2);
        break;

    case FL_NONE:  // does not fly
        if (hash_rand(4, seed, 3))
            description << HRANDOM_ELEMENT(nonfly_names, 2);
        break;
    }

    description << ".";

    if (hash_rand(40, seed, 4) < 3)
    {
        if (you.can_smell())
        {
            switch (hash_rand(3, seed, 5))
            {
            case 0:
                description << " It stinks of brimstone.";
                break;
            case 1:
                description << " It is surrounded by a sickening stench.";
                break;
            case 2:
                description << " It smells like rotting flesh"
                            << (player_mutation_level(MUT_SAPROVOROUS) == 3 ?
                                " - yum!" : ".");
                break;
            }
        }
    }
    else if (hash_rand(2, seed, 6))
        description << RANDOM_ELEMENT(misc_descs);

    return description.str();
}

void append_weapon_stats(string &description, const item_def &item)
{
    description += "\nBase accuracy: ";
    _append_value(description, property(item, PWPN_HIT), true);
    description += "  ";

    const int base_dam = property(item, PWPN_DAMAGE);
    const int ammo_type = fires_ammo_type(item);
    const int ammo_dam = ammo_type == MI_NONE ? 0 :
                                                ammo_type_damage(ammo_type);
    description += "Base damage: ";
    _append_value(description, base_dam + ammo_dam, false);
    description += "  ";

    description += "Base attack delay: ";
    _append_value(description, property(item, PWPN_SPEED) / 10.0f, false);
    description += "  ";

    description += "Minimum delay: ";
    _append_value(description, weapon_min_delay(item) / 10.0f, false);

    if (range_skill(item) == SK_SLINGS)
    {
        description += make_stringf("\nFiring bullets:    Base damage: %d",
                                    base_dam +
                                    ammo_type_damage(MI_SLING_BULLET));
    }
}

static string _handedness_string(const item_def &item)
{
    string description;

    switch (you.hands_reqd(item))
    {
    case HANDS_ONE:
        if (you.species == SP_FORMICID)
            description += "It is a weapon for one hand-pair.";
        else
            description += "It is a one handed weapon.";
        break;
    case HANDS_TWO:
        description += "It is a two handed weapon.";
        break;
    }

    return description;
}

//---------------------------------------------------------------
//
// describe_weapon
//
//---------------------------------------------------------------
static string _describe_weapon(const item_def &item, bool verbose)
{
    string description;

    description.reserve(200);

    description = "";

    if (verbose)
    {
        description += "\n";
        append_weapon_stats(description, item);
    }

    const int spec_ench = (is_artefact(item) || verbose)
                          ? get_weapon_brand(item) : SPWPN_NORMAL;
    const int damtype = get_vorpal_type(item);

    if (verbose)
    {
        switch (item_attack_skill(item))
        {
        case SK_POLEARMS:
            description += "\n\nIt can be evoked to extend its reach.";
            break;
        case SK_AXES:
            description += "\n\nIt can hit multiple enemies in an arc"
                           " around the wielder.";
            break;
        case SK_SHORT_BLADES:
            // TODO: should we mention stabbing for "ok" stabbing weapons?
            // (long blades, piercing polearms, and clubs)
            {
                string adj = (item.sub_type == WPN_DAGGER) ? "extremely"
                                                           : "particularly";
                description += "\n\nIt is " + adj + " good for stabbing"
                               " unaware enemies.";
            }
            break;
        default:
            break;
        }
    }

    // special weapon descrip
    if (spec_ench != SPWPN_NORMAL && item_type_known(item))
    {
        description += "\n\n";

        switch (spec_ench)
        {
        case SPWPN_FLAMING:
            if (is_range_weapon(item))
            {
                description += "It turns projectiles fired from it into "
                    "bolts of flame.";
            }
            else
            {
                description += "It emits flame when wielded, causing extra "
                    "injury to most foes and up to double damage against "
                    "particularly susceptible opponents.";
                if (damtype == DVORP_SLICING || damtype == DVORP_CHOPPING)
                {
                    description += " Big, fiery blades are also staple "
                        "armaments of hydra-hunters.";
                }
            }
            break;
        case SPWPN_FREEZING:
            if (is_range_weapon(item))
            {
                description += "It turns projectiles fired from it into "
                    "bolts of frost.";
            }
            else
            {
                description += "It has been specially enchanted to freeze "
                    "those struck by it, causing extra injury to most foes "
                    "and up to double damage against particularly "
                    "susceptible opponents. It can also slow down "
                    "cold-blooded creatures.";
            }
            break;
        case SPWPN_HOLY_WRATH:
            description += "It has been blessed by the Shining One to "
                "cause great damage to the undead and demons.";
            break;
        case SPWPN_ELECTROCUTION:
            if (is_range_weapon(item))
            {
                description += "It charges the ammunition it shoots with "
                    "electricity; occasionally upon a hit, such missiles "
                    "may discharge and cause terrible harm.";
            }
            else
            {
                description += "Occasionally, upon striking a foe, it will "
                    "discharge some electrical energy and cause terrible "
                    "harm.";
            }
            break;
        case SPWPN_VENOM:
            if (is_range_weapon(item))
                description += "It poisons the ammo it fires.";
            else
                description += "It poisons the flesh of those it strikes.";
            break;
        case SPWPN_PROTECTION:
            description += "It protects the one who wields it against "
                "injury (+5 to AC).";
            break;
        case SPWPN_EVASION:
            description += "It affects your evasion (+5 to EV).";
            break;
        case SPWPN_DRAINING:
            description += "A truly terrible weapon, it drains the "
                "life of those it strikes.";
            break;
        case SPWPN_SPEED:
            description += "Attacks with this weapon are significantly faster.";
            break;
        case SPWPN_VORPAL:
            if (is_range_weapon(item))
            {
                description += "Any ";
                description += ammo_name(item);
                description += " fired from it inflicts extra damage.";
            }
            else
            {
                description += "It inflicts extra damage upon your "
                    "enemies.";
            }
            break;
        case SPWPN_CHAOS:
            if (is_range_weapon(item))
            {
                description += "Each time it fires, it turns the "
                    "launched projectile into a different, random type "
                    "of bolt.";
            }
            else
            {
                description += "Each time it hits an enemy it has a "
                    "different, random effect.";
            }
            break;
        case SPWPN_VAMPIRISM:
            description += "It inflicts no extra harm, but heals its "
                "wielder somewhat when it strikes a living foe.";
            break;
        case SPWPN_PAIN:
            description += "In the hands of one skilled in necromantic "
                "magic, it inflicts extra damage on living creatures.";
            break;
        case SPWPN_DISTORTION:
            description += "It warps and distorts space around it. "
                "Unwielding it can cause banishment or high damage.";
            break;
        case SPWPN_PENETRATION:
            description += "Ammo fired by it will pass through the "
                "targets it hits, potentially hitting all targets in "
                "its path until it reaches maximum range.";
            break;
        case SPWPN_REAPING:
            description += "If a monster killed with it leaves a "
                "corpse in good enough shape, the corpse will be "
                "animated as a zombie friendly to the killer.";
            break;
        case SPWPN_ANTIMAGIC:
            description += "It disrupts the flow of magical energy around "
                    "spellcasters and certain magical creatures (including "
                    "the wielder).";
            break;
        }
    }

    if (you.duration[DUR_WEAPON_BRAND] && &item == you.weapon())
    {
        description += "\nIt is temporarily rebranded; it is actually a";
        if ((int) you.props[ORIGINAL_BRAND_KEY] == SPWPN_NORMAL)
            description += "n unbranded weapon.";
        else
        {
            description += " weapon of "
                        + ego_type_string(item, false, you.props[ORIGINAL_BRAND_KEY])
                        + ".";
        }
    }

    if (is_artefact(item))
    {
        string rand_desc = _randart_descrip(item);
        if (!rand_desc.empty())
        {
            description += "\n";
            description += rand_desc;
        }

        // XXX: Can't happen, right?
        if (!item_ident(item, ISFLAG_KNOW_PROPERTIES)
            && item_type_known(item))
        {
            description += "\nThis weapon may have some hidden properties.";
        }
    }

    if (verbose)
    {
        description += "\n\nThis weapon falls into the";

        const skill_type skill = item_attack_skill(item);

        description +=
            make_stringf(" '%s' category. ",
                         skill == SK_FIGHTING ? "buggy" : skill_name(skill));

        description += _handedness_string(item);

        if (!you.could_wield(item, true))
            description += "\nIt is too large for you to wield.";
    }

    if (!is_artefact(item))
    {
        if (item_ident(item, ISFLAG_KNOW_PLUSES) && item.plus >= MAX_WPN_ENCHANT)
            description += "\nIt cannot be enchanted further.";
        else
        {
            description += "\nIt can be maximally enchanted to +";
            _append_value(description, MAX_WPN_ENCHANT, false);
            description += ".";
        }
    }

    return description;
}

//---------------------------------------------------------------
//
// describe_ammo
//
//---------------------------------------------------------------
static string _describe_ammo(const item_def &item)
{
    string description;

    description.reserve(64);

    const bool can_launch = has_launcher(item);
    const bool can_throw  = is_throwable(&you, item, true);

    if (item.special && item_type_known(item))
    {
        description += "\n\n";

        string threw_or_fired;
        if (can_throw)
        {
            threw_or_fired += "threw";
            if (can_launch)
                threw_or_fired += " or ";
        }
        if (can_launch)
            threw_or_fired += "fired";

        switch (item.special)
        {
        case SPMSL_FLAME:
            description += "It turns into a bolt of flame.";
            break;
        case SPMSL_FROST:
            description += "It turns into a bolt of frost.";
            break;
        case SPMSL_CHAOS:
            description += "When ";

            if (can_throw)
            {
                description += "thrown, ";
                if (can_launch)
                    description += "or ";
            }

            if (can_launch)
                description += "fired from an appropriate launcher, ";

            description += "it turns into a bolt of a random type.";
            break;
        case SPMSL_POISONED:
            description += "It is coated with poison.";
            break;
        case SPMSL_CURARE:
            description += "It is tipped with asphyxiating poison.";
            break;
        case SPMSL_PARALYSIS:
            description += "It is tipped with a paralysing substance.";
            break;
        case SPMSL_SLOW:
            description += "It is coated with a substance that causes slowness of the body.";
            break;
        case SPMSL_SLEEP:
            description += "It is coated with a fast-acting tranquilizer.";
            break;
        case SPMSL_CONFUSION:
            description += "It is tipped with a substance that causes confusion.";
            break;
#if TAG_MAJOR_VERSION == 34
        case SPMSL_SICKNESS:
            description += "It has been contaminated by something likely to cause disease.";
            break;
#endif
        case SPMSL_FRENZY:
            description += "It is tipped with a substance that causes a mindless "
                "rage, making people attack friend and foe alike.";
            break;
       case SPMSL_RETURNING:
            description += "A skilled user can throw it in such a way "
                "that it will return to its owner.";
            break;
        case SPMSL_PENETRATION:
            description += "It will pass through any targets it hits, "
                "potentially hitting all targets in its path until it "
                "reaches maximum range.";
            break;
        case SPMSL_DISPERSAL:
            description += "Any target it hits will blink, with a "
                "tendency towards blinking further away from the one "
                "who " + threw_or_fired + " it.";
            break;
        case SPMSL_EXPLODING:
            description += "It will explode into fragments upon "
                "hitting a target, hitting an obstruction, or reaching "
                "the end of its range.";
            break;
        case SPMSL_STEEL:
            description += "Compared to normal ammo, it does 30% more "
                "damage, is destroyed upon impact only 1/10th of the "
                "time.";
            break;
        case SPMSL_SILVER:
            description += "Silver sears all those touched by chaos. "
                "Compared to normal ammo, it does 75% more damage to "
                "chaotic and magically transformed beings. It also does "
                "extra damage against mutated beings according to how "
                "mutated they are. With due care, silver ammo can still "
                "be handled by those it affects.";
            break;
        }
    }

    append_missile_info(description, item);

    return description;
}

void append_armour_stats(string &description, const item_def &item)
{
    description += "\nBase armour rating: ";
    _append_value(description, property(item, PARM_AC), false);
    description += "       ";

    description += "Encumbrance rating: ";
    _append_value(description, -property(item, PARM_EVASION), false);
}

void append_missile_info(string &description, const item_def &item)
{
    const int dam = property(item, PWPN_DAMAGE);
    if (dam)
        description += make_stringf("\nBase damage: %d\n", dam);

    if (ammo_always_destroyed(item))
        description += "\nIt will always be destroyed on impact.";
    else if (!ammo_never_destroyed(item))
        description += "\nIt may be destroyed on impact.";
}

//---------------------------------------------------------------
//
// describe_armour
//
//---------------------------------------------------------------
static string _describe_armour(const item_def &item, bool verbose)
{
    string description;

    description.reserve(200);

    if (verbose
        && item.sub_type != ARM_SHIELD
        && item.sub_type != ARM_BUCKLER
        && item.sub_type != ARM_LARGE_SHIELD)
    {
        description += "\n";
        append_armour_stats(description, item);
    }

    const int ego = get_armour_ego_type(item);
    if (ego != SPARM_NORMAL && item_type_known(item) && verbose)
    {
        description += "\n\n";

        switch (ego)
        {
        case SPARM_RUNNING:
            if (item.sub_type == ARM_NAGA_BARDING)
                description += "It allows its wearer to slither at a great speed.";
            else
                description += "It allows its wearer to run at a great speed.";
            break;
        case SPARM_FIRE_RESISTANCE:
            description += "It protects its wearer from heat.";
            break;
        case SPARM_COLD_RESISTANCE:
            description += "It protects its wearer from cold.";
            break;
        case SPARM_POISON_RESISTANCE:
            description += "It protects its wearer from poison.";
            break;
        case SPARM_SEE_INVISIBLE:
            description += "It allows its wearer to see invisible things.";
            break;
        case SPARM_DARKNESS:
            description += "When activated it hides its wearer from "
                "the sight of others, but also increases "
                "their metabolic rate by a large amount.";
            break;
        case SPARM_STRENGTH:
            description += "It increases the physical power of its wearer (+3 to strength).";
            break;
        case SPARM_DEXTERITY:
            description += "It increases the dexterity of its wearer (+3 to dexterity).";
            break;
        case SPARM_INTELLIGENCE:
            description += "It makes you more clever (+3 to intelligence).";
            break;
        case SPARM_PONDEROUSNESS:
            description += "It is very cumbersome, thus slowing your movement.";
            break;
        case SPARM_FLYING:
            description += "It can be activated to allow its wearer to "
                "fly indefinitely.";
            break;
        case SPARM_JUMPING:
            description += "It can be activated to allow its wearer to "
                "perform a jumping attack.";
            break;
        case SPARM_MAGIC_RESISTANCE:
            description += "It increases its wearer's resistance "
                "to enchantments.";
            break;
        case SPARM_PROTECTION:
            description += "It protects its wearer from harm (+3 to AC).";
            break;
        case SPARM_STEALTH:
            description += "It enhances the stealth of its wearer.";
            break;
        case SPARM_RESISTANCE:
            description += "It protects its wearer from the effects "
                "of both cold and heat.";
            break;

        // These two are only for robes.
        case SPARM_POSITIVE_ENERGY:
            description += "It protects its wearer from "
                "the effects of negative energy.";
            break;
        case SPARM_ARCHMAGI:
            description += "It increases the power of its wearer's "
                "magical spells.";
            break;
#if TAG_MAJOR_VERSION == 34
        case SPARM_PRESERVATION:
            description += "It does nothing special.";
            break;
#endif
        case SPARM_REFLECTION:
            description += "It reflects blocked things back in the "
                "direction they came from.";
            break;

        case SPARM_SPIRIT_SHIELD:
            description += "It shields its wearer from harm at the cost "
                "of magical power.";
            break;

        // This is only for gloves.
        case SPARM_ARCHERY:
            description += "It improves your effectiveness with ranged weaponry.";
            break;
        }
    }

    if (is_artefact(item))
    {
        string rand_desc = _randart_descrip(item);
        if (!rand_desc.empty())
        {
            description += "\n";
            description += rand_desc;
        }

        // Can't happen, right? (XXX)
        if (!item_ident(item, ISFLAG_KNOW_PROPERTIES) && item_type_known(item))
            description += "\nThis armour may have some hidden properties.";
    }

    if (!is_artefact(item))
    {
        const int max_ench = armour_max_enchant(item);
        if (armour_is_hide(item))
        {
            description += "\nEnchanting it will turn it into a suit of "
                           "magical armour.";
        }
        else if (item.plus < max_ench || !item_ident(item, ISFLAG_KNOW_PLUSES))
        {
            description += "\nIt can be maximally enchanted to +";
            _append_value(description, max_ench, false);
            description += ".";
        }
        else
            description += "\nIt cannot be enchanted further.";
    }

    return description;
}

//---------------------------------------------------------------
//
// describe_jewellery
//
//---------------------------------------------------------------
static string _describe_jewellery(const item_def &item, bool verbose)
{
    string description;

    description.reserve(200);

    if (verbose && !is_artefact(item)
        && item_ident(item, ISFLAG_KNOW_PLUSES))
    {
        // Explicit description of ring power.
        if (item.plus != 0)
        {
            switch (item.sub_type)
            {
            case RING_PROTECTION:
                description += "\nIt affects your AC (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            case RING_EVASION:
                description += "\nIt affects your evasion (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            case RING_STRENGTH:
                description += "\nIt affects your strength (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            case RING_INTELLIGENCE:
                description += "\nIt affects your intelligence (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            case RING_DEXTERITY:
                description += "\nIt affects your dexterity (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            case RING_SLAYING:
                description += "\nIt affects your accuracy and damage "
                               "with ranged weapons and melee attacks (";
                _append_value(description, item.plus, true);
                description += ").";
                break;

            default:
                break;
            }
        }
    }

    // Artefact properties.
    if (is_artefact(item))
    {
        string rand_desc = _randart_descrip(item);
        if (!rand_desc.empty())
        {
            description += "\n";
            description += rand_desc;
        }
        if (!item_ident(item, ISFLAG_KNOW_PROPERTIES) ||
            !item_ident(item, ISFLAG_KNOW_TYPE))
        {
            description += "\nThis ";
            description += (jewellery_is_amulet(item) ? "amulet" : "ring");
            description += " may have hidden properties.";
        }
    }

    return description;
}

static bool _compare_card_names(card_type a, card_type b)
{
    return string(card_name(a)) < string(card_name(b));
}

//---------------------------------------------------------------
//
// describe_misc_item
//
//---------------------------------------------------------------
static bool _check_buggy_deck(const item_def &deck, string &desc)
{
    if (!is_deck(deck))
    {
        desc += "This isn't a deck at all!\n";
        return true;
    }

    const CrawlHashTable &props = deck.props;

    if (!props.exists("cards")
        || props["cards"].get_type() != SV_VEC
        || props["cards"].get_vector().get_type() != SV_BYTE
        || cards_in_deck(deck) == 0)
    {
        return true;
    }

    return false;
}

static string _describe_deck(const item_def &item)
{
    string description;

    description.reserve(100);

    description += "\n";

    if (_check_buggy_deck(item, description))
        return "";

    if (item_type_known(item))
        description += deck_contents(item.sub_type) + "\n";

    const vector<card_type> drawn_cards = get_drawn_cards(item);
    if (!drawn_cards.empty())
    {
        description += "Drawn card(s): ";
        for (unsigned int i = 0; i < drawn_cards.size(); ++i)
        {
            if (i != 0)
                description += ", ";
            description += card_name(drawn_cards[i]);
        }
        description += "\n";
    }

    const int num_cards = cards_in_deck(item);
    int last_known_card = -1;
    if (top_card_is_known(item))
    {
        description += "Next card(s): ";
        for (int i = 0; i < num_cards; ++i)
        {
            uint8_t flags;
            const card_type card = get_card_and_flags(item, -i-1, flags);
            if (flags & CFLAG_MARKED)
            {
                if (i != 0)
                    description += ", ";
                description += card_name(card);
                last_known_card = i;
            }
            else
                break;
        }
        description += "\n";
    }

    // Marked cards which we don't know straight off.
    vector<card_type> marked_cards;
    for (int i = last_known_card + 1; i < num_cards; ++i)
    {
        uint8_t flags;
        const card_type card = get_card_and_flags(item, -i-1, flags);
        if (flags & CFLAG_MARKED)
            marked_cards.push_back(card);
    }
    if (!marked_cards.empty())
    {
        sort(marked_cards.begin(), marked_cards.end(),
                  _compare_card_names);

        description += "Marked card(s): ";
        for (unsigned int i = 0; i < marked_cards.size(); ++i)
        {
            if (i != 0)
                description += ", ";
            description += card_name(marked_cards[i]);
        }
        description += "\n";
    }

    // Seen cards in the deck.
    vector<card_type> seen_cards;
    for (int i = 0; i < num_cards; ++i)
    {
        uint8_t flags;
        const card_type card = get_card_and_flags(item, -i-1, flags);

        // This *might* leak a bit of information...oh well.
        if ((flags & CFLAG_SEEN) && !(flags & CFLAG_MARKED))
            seen_cards.push_back(card);
    }
    if (!seen_cards.empty())
    {
        sort(seen_cards.begin(), seen_cards.end(),
                  _compare_card_names);

        description += "Seen card(s): ";
        for (unsigned int i = 0; i < seen_cards.size(); ++i)
        {
            if (i != 0)
                description += ", ";
            description += card_name(seen_cards[i]);
        }
        description += "\n";
    }

    if (item.props.exists("peeked") && item.props["peeked"].get_bool())
    {
        description += "This deck has been peeked at and cannot be used "
                       "with Nemelex Xobeh's abilities.\n";
    }

    return description;
}

// Adds a list of all spells contained in a book or rod to its
// description string.
void append_spells(string &desc, const item_def &item)
{
    if (!item.has_spells())
        return;

    desc += "\n\nSpells                             Type                      Level\n";

    for (int j = 0; j < SPELLBOOK_SIZE; ++j)
    {
        spell_type stype = which_spell_in_book(item, j);
        if (stype == SPELL_NO_SPELL)
            continue;

        string name = (is_memorised(stype) ? "*" : "");
                    name += spell_title(stype);
        desc += chop_string(name, 35);

        string schools;
        if (item.base_type == OBJ_RODS)
            schools = "Evocations";
        else
            schools = spell_schools_string(stype);

        desc += chop_string(schools, 65 - 36);

        desc += make_stringf("%d\n", spell_difficulty(stype));
    }
}

// ========================================================================
//      Public Functions
// ========================================================================

bool is_dumpable_artefact(const item_def &item, bool verbose)
{
    if (is_known_artefact(item))
        return item_ident(item, ISFLAG_KNOW_PROPERTIES);
    else if (!verbose || !item_type_known(item))
        return false;
    else if (item.base_type == OBJ_ARMOUR)
    {
        const int spec_ench = get_armour_ego_type(item);
        return spec_ench >= SPARM_RUNNING && spec_ench <= SPARM_ARCHMAGI;
    }
    else if (item.base_type == OBJ_JEWELLERY)
        return true;

    return false;
}

//---------------------------------------------------------------
//
// get_item_description
//
//---------------------------------------------------------------
string get_item_description(const item_def &item, bool verbose,
                            bool dump, bool noquote)
{
    if (dump)
        noquote = true;

    ostringstream description;

    if (!dump)
    {
        string name = item.name(DESC_INVENTORY_EQUIP);
        if (!in_inventory(item))
            name = uppercase_first(name);
        description << name << ".";
    }

#ifdef DEBUG_DIAGNOSTICS
    if (!dump)
    {
        description << setfill('0');
        description << "\n\n"
                    << "base: " << static_cast<int>(item.base_type)
                    << " sub: " << static_cast<int>(item.sub_type)
                    << " plus: " << item.plus << " plus2: " << item.plus2
                    << " special: " << item.special
                    << "\n"
                    << "quant: " << item.quantity
                    << " colour: " << static_cast<int>(item.colour)
                    << " flags: " << hex << setw(8) << item.flags
                    << dec << "\n"
                    << "x: " << item.pos.x << " y: " << item.pos.y
                    << " link: " << item.link
                    << " slot: " << item.slot
                    << " ident_type: "
                    << static_cast<int>(get_ident_type(item))
                    << " book_number: " << item.book_number()
                    << "\nannotate: "
                    << stash_annotate_item(STASH_LUA_SEARCH_ANNOTATE, &item);
    }
#endif

    if (verbose || (item.base_type != OBJ_WEAPONS
                    && item.base_type != OBJ_ARMOUR
                    && item.base_type != OBJ_BOOKS))
    {
        description << "\n\n";

        bool need_base_desc = true;

        if (dump)
        {
            description << "["
                        << item.name(DESC_DBNAME, true, false, false)
                        << "]";
            need_base_desc = false;
        }
        else if (is_unrandom_artefact(item) && item_type_known(item))
        {
            const string desc = getLongDescription(get_artefact_name(item));
            if (!desc.empty())
            {
                description << desc;
                need_base_desc = false;
                description.seekp((streamoff)-1, ios_base::cur);
                description << " ";
            }
        }
        // Randart jewellery properties will be listed later,
        // just describe artefact status here.
        else if (is_artefact(item) && item_type_known(item)
                 && item.base_type == OBJ_JEWELLERY)
        {
            description << "It is an ancient artefact.";
            need_base_desc = false;
        }

        if (need_base_desc)
        {
            string db_name = item.name(DESC_DBNAME, true, false, false);
            string db_desc = getLongDescription(db_name);

            if (db_desc.empty())
            {
                if (item_type_known(item))
                {
                    description << "[ERROR: no desc for item name '" << db_name
                                << "']\n";
                }
                else
                {
                    description << uppercase_first(item.name(DESC_A, true,
                                                             false, false));
                    description << ".\n";
                }
            }
            else
                description << db_desc;

            // Get rid of newline at end of description; in most cases we
            // will be adding "\n\n" immediately, and we want only one,
            // not two, blank lines.  This allow allows the "unpleasant"
            // message for chunks to appear on the same line.
            description.seekp((streamoff)-1, ios_base::cur);
            description << " ";
        }
    }

    bool need_extra_line = true;
    string desc;
    switch (item.base_type)
    {
    // Weapons, armour, jewellery, books might be artefacts.
    case OBJ_WEAPONS:
        desc = _describe_weapon(item, verbose);
        if (desc.empty())
            need_extra_line = false;
        else
            description << desc;
        break;

    case OBJ_ARMOUR:
        desc = _describe_armour(item, verbose);
        if (desc.empty())
            need_extra_line = false;
        else
            description << desc;
        break;

    case OBJ_JEWELLERY:
        desc = _describe_jewellery(item, verbose);
        if (desc.empty())
            need_extra_line = false;
        else
            description << desc;
        break;

    case OBJ_BOOKS:
        if (!player_can_memorise_from_spellbook(item))
        {
            description << "\nThis book is beyond your current level of "
                           "understanding.";

            if (!item_type_known(item))
                break;
        }

        if (!verbose
            && (Options.dump_book_spells || is_random_artefact(item)))
        {
            append_spells(desc, item);
            if (desc.empty())
                need_extra_line = false;
            else
                description << desc;
        }
        break;

    case OBJ_MISSILES:
        description << _describe_ammo(item);
        break;

    case OBJ_WANDS:
        if (item_type_known(item))
        {
            const int max_charges = wand_max_charges(item.sub_type);
            if (item.plus < max_charges
                || !item_ident(item, ISFLAG_KNOW_PLUSES))
            {
                description << "\nIt can have at most " << max_charges
                            << " charges.";
            }
            else
                description << "\nIt is fully charged.";
        }

        if (item_ident(item, ISFLAG_KNOW_PLUSES) && item.plus == 0
            || item.plus2 == ZAPCOUNT_EMPTY)
        {
            description << "\nUnfortunately, it has no charges left.";
        }
        break;

    case OBJ_CORPSES:
        if (item.sub_type == CORPSE_SKELETON)
            break;
        // intentional fall-through
    case OBJ_FOOD:
        if (item.base_type == OBJ_CORPSES || item.sub_type == FOOD_CHUNK)
        {
            if (food_is_rotten(item))
            {
                if (player_mutation_level(MUT_SAPROVOROUS) == 3)
                    description << "It looks nice and ripe.";
                else
                {
                    description << "In fact, it is rotting away before your "
                                   "eyes.";

                    if (!you.is_undead
                        && !player_mutation_level(MUT_SAPROVOROUS))
                    {
                        description << " Eating it is completely out of the "
                                       "question!";
                    }
                }
            }
            else if (player_mutation_level(MUT_SAPROVOROUS) < 3)
                description << "It looks rather unpleasant.";

            switch (mons_corpse_effect(item.mon_type))
            {
            case CE_POISONOUS:
                description << "\n\nThis meat is poisonous.";
                break;
            case CE_MUTAGEN:
                if (you.species != SP_GHOUL)
                {
                    description << "\n\nEating this meat will cause random "
                                   "mutations.";
                }
                break;
            case CE_ROT:
                if (you.species != SP_GHOUL)
                    description << "\n\nEating this meat will cause rotting.";
                break;
            default:
                break;
            }

            if ((god_hates_cannibalism(you.religion)
                   && is_player_same_genus(item.mon_type))
                || (you_worship(GOD_ZIN)
                   && mons_class_intel(item.mon_type) >= I_NORMAL)
                || (is_good_god(you.religion)
                   && mons_class_holiness(item.mon_type) == MH_HOLY))
            {
                description << "\n\n" << uppercase_first(god_name(you.religion))
                            << " disapproves of eating such meat.";
            }
        }
        break;

    case OBJ_RODS:
        if (verbose)
        {
            description <<
                "\nIt uses its own magic reservoir for casting spells, and "
                "recharges automatically according to the recharging "
                "rate.";

            const int max_charges = MAX_ROD_CHARGE;
            const int max_recharge_rate = MAX_WPN_ENCHANT;
            if (item_ident(item, ISFLAG_KNOW_PLUSES))
            {
                const int num_charges = item.plus2 / ROD_CHARGE_MULT;
                if (max_charges > num_charges)
                {
                    description << "\nIt can currently hold " << num_charges
                                << " charges. It can be magically "
                                << "recharged to contain up to "
                                << max_charges << " charges.";
                }
                else
                    description << "\nIts capacity can be increased no further.";

                const int recharge_rate = item.special;
                if (recharge_rate < max_recharge_rate)
                {
                    description << "\nIts current recharge rate is "
                                << (recharge_rate >= 0 ? "+" : "")
                                << recharge_rate << ". It can be magically "
                                << "recharged up to +" << max_recharge_rate
                                << ".";
                }
                else
                    description << "\nIts recharge rate is at maximum.";
            }
            else
            {
                description << "\nIt can have at most " << max_charges
                            << " charges and +" << max_recharge_rate
                            << " recharge rate.";
            }
        }
        else if (Options.dump_book_spells)
        {
            append_spells(desc, item);
            if (desc.empty())
                need_extra_line = false;
            else
                description << desc;
        }

        {
            string stats = "\n";
            append_weapon_stats(stats, item);
            description << stats;
        }
        description << "\n\nIt falls into the 'Maces & Flails' category.";
        break;

    case OBJ_STAVES:
        {
            string stats = "\n";
            append_weapon_stats(stats, item);
            description << stats;
        }
        description << "\n\nIt falls into the 'Staves' category. ";
        description << _handedness_string(item);
        break;

    case OBJ_MISCELLANY:
        if (is_deck(item))
            description << _describe_deck(item);
        if (is_xp_evoker(item))
        {
            description << "\nOnce released, the spirits within this device "
                           "will dissipate, leaving it inert, though new ones "
                           "may be attracted as its bearer battles through the "
                           "dungeon and grows in power and wisdom.";

            if (!evoker_is_charged(item))
                description << "\n\nThe device is presently inert.";
        }
        break;

    case OBJ_POTIONS:
#ifdef DEBUG_BLOOD_POTIONS
        // List content of timer vector for blood potions.
        if (!dump && is_blood_potion(item))
        {
            item_def stack = static_cast<item_def>(item);
            CrawlHashTable &props = stack.props;
            ASSERT(props.exists("timer"));
            CrawlVector &timer = props["timer"].get_vector();
            ASSERT(!timer.empty());

            description << "\nQuantity: " << stack.quantity
                        << "        Timer size: " << (int) timer.size();
            description << "\nTimers:\n";
            for (int i = 0; i < timer.size(); ++i)
                 description << (timer[i].get_int()) << "  ";
        }
#endif

    case OBJ_SCROLLS:
    case OBJ_ORBS:
    case OBJ_GOLD:
        // No extra processing needed for these item types.
        break;

    default:
        die("Bad item class");
    }

    if (!verbose && item_known_cursed(item))
        description << "\nIt has a curse placed upon it.";
    else
    {
        if (verbose)
        {
            if (need_extra_line)
                description << "\n";
            if (item_known_cursed(item))
                description << "\nIt has a curse placed upon it.";

            if (is_artefact(item))
            {
                if (item.base_type == OBJ_ARMOUR
                    || item.base_type == OBJ_WEAPONS)
                {
                    description << "\nThis ancient artefact cannot be changed "
                        "by magic or mundane means.";
                }
                // Randart jewellery has already displayed this line.
                else if (item.base_type != OBJ_JEWELLERY
                         || (item_type_known(item) && is_unrandom_artefact(item)))
                {
                    description << "\nIt is an ancient artefact.";
                }
            }
        }
    }

    if (conduct_type ct = good_god_hates_item_handling(item))
    {
        description << "\n\n" << uppercase_first(god_name(you.religion))
                    << " opposes the use of such an ";

        if (ct == DID_NECROMANCY)
            description << "evil";
        else
            description << "unholy";

        description << " item.";
    }
    else if (god_hates_item_handling(item))
    {
        description << "\n\n" << uppercase_first(god_name(you.religion))
                    << " disapproves of the use of such an item.";
    }

    if (verbose && origin_describable(item))
        description << "\n" << origin_desc(item) << ".";

    // This information is obscure and differs per-item, so looking it up in
    // a docs file you don't know to exist is tedious.  On the other hand,
    // it breaks the screen for people on very small terminals.
    if (verbose && get_number_of_lines() >= 28)
    {
        description << "\n\n" << "Stash search prefixes: "
                    << userdef_annotate_item(STASH_LUA_SEARCH_ANNOTATE, &item);
        string menu_prefix = item_prefix(item, false);
        if (!menu_prefix.empty())
            description << "\nMenu/colouring prefixes: " << menu_prefix;
    }

    if (verbose && !noquote && (!item_type_known(item) || !is_random_artefact(item)))
    {
        const unsigned int lineWidth = get_number_of_cols();
        const          int height    = get_number_of_lines();
        string quote;
        if (is_unrandom_artefact(item) && item_type_known(item))
            quote = getQuoteString(get_artefact_name(item));
        else
            quote = getQuoteString(item.name(DESC_DBNAME, true, false, false));

        if (count_desc_lines(description.str(), lineWidth)
            + count_desc_lines(quote, lineWidth) < height)
        {
            if (!quote.empty())
                description << "\n\n" << quote;
        }
    }

    return description.str();
}

void get_feature_desc(const coord_def &pos, describe_info &inf)
{
    dungeon_feature_type feat = env.map_knowledge(pos).feat();

    string desc      = feature_description_at(pos, false, DESC_A, false);
    string db_name   = feat == DNGN_ENTER_SHOP ? "a shop" : desc;
    string long_desc = getLongDescription(db_name);

    inf.title = uppercase_first(desc);
    if (!ends_with(desc, ".") && !ends_with(desc, "!")
        && !ends_with(desc, "?"))
    {
        inf.title += ".";
    }

    // If we couldn't find a description in the database then see if
    // the feature's base name is different.
    if (long_desc.empty())
    {
        db_name   = feature_description_at(pos, false, DESC_A, false, true);
        long_desc = getLongDescription(db_name);
    }

    const string marker_desc =
        env.markers.property_at(pos, MAT_ANY, "feature_description_long");

    // suppress this if the feature changed out of view
    if (!marker_desc.empty() && grd(pos) == feat)
        long_desc += marker_desc;

    // Display branch descriptions on the entries to those branches.
    if (feat_is_stair(feat))
    {
        for (branch_iterator it; it; ++it)
        {
            if (it->entry_stairs == feat)
            {
                long_desc += "\n";
                long_desc += getLongDescription(it->shortname);
                break;
            }
        }
    }

    inf.body << long_desc;

    inf.quote = getQuoteString(db_name);
}

// Returns the pressed key in key
static int _print_toggle_message(const describe_info &inf, int& key)
{
    if (inf.quote.empty())
    {
        mouse_control mc(MOUSE_MODE_MORE);
        key = getchm();
        return false;
    }
    else
    {
        const int bottom_line = min(30, get_number_of_lines());
        cgotoxy(1, bottom_line);
        formatted_string::parse_string(
            "Press '<w>!</w>'"
#ifdef USE_TILE_LOCAL
            " or <w>Right-click</w>"
#endif
            " to toggle between the description and quote.").display();

        mouse_control mc(MOUSE_MODE_MORE);
        key = getchm();

        if (key == '!' || key == CK_MOUSE_CMD)
            return true;

        return false;
    }
}

void describe_feature_wide(const coord_def& pos, bool show_quote)
{
    describe_info inf;
    get_feature_desc(pos, inf);

#ifdef USE_TILE_WEB
    tiles_crt_control show_as_menu(CRT_MENU, "describe_feature");
#endif

    if (show_quote)
        _print_quote(inf);
    else
        print_description(inf);

    if (crawl_state.game_is_hints())
        hints_describe_pos(pos.x, pos.y);

    int key;
    if (_print_toggle_message(inf, key))
        describe_feature_wide(pos, !show_quote);
}

void get_item_desc(const item_def &item, describe_info &inf)
{
    // Don't use verbose descriptions if the item contains spells,
    // so we can actually output these spells if space is scarce.
    const bool verbose = !item.has_spells();
    inf.body << get_item_description(item, verbose, false, true);
}

// Returns true if spells can be shown to player.
static bool _can_show_spells(const item_def &item)
{
    return item.has_spells()
           && (item.base_type != OBJ_BOOKS || item_type_known(item)
               || player_can_memorise_from_spellbook(item));
}

static void _show_spells(const item_def &item)
{
    formatted_string fs;
    item_def dup = item;
    spellbook_contents(dup, item.base_type == OBJ_BOOKS ? RBOOK_READ_SPELL
                                                        : RBOOK_USE_ROD,
                       &fs);
    fs.display(2, -2);
}

static void _show_item_description(const item_def &item)
{
    const unsigned int lineWidth = get_number_of_cols() - 1;
    const          int height    = get_number_of_lines();

    string desc = get_item_description(item, true, false,
                                       crawl_state.game_is_hints_tutorial());

    const int num_lines = count_desc_lines(desc, lineWidth) + 1;

    // XXX: hack: Leave room for "Inscribe item?" and the blank line above
    // it by removing item quote.  This should really be taken care of
    // by putting the quotes into a separate DB and treating them as
    // a suffix that can be ignored by print_description().
    if (height - num_lines <= 2)
        desc = get_item_description(item, true, false, true);

    print_description(desc);
    if (crawl_state.game_is_hints())
        hints_describe_item(item);

    if (_can_show_spells(item))
      _show_spells(item);
}

static bool _describe_spells(const item_def &item)
{
    const int c = getchm();
    if (c < 'a' || c > 'h')     //jmf: was 'g', but 8=h
    {
        clear_messages();
        return false;
    }

    const int spell_index = letter_to_index(c);

    const spell_type nthing = which_spell_in_book(item, spell_index);
    if (nthing == SPELL_NO_SPELL)
        return false;

    describe_spell(nthing, &item);
    return item.is_valid();
}

static bool _can_memorise(item_def &item)
{
    return item.base_type == OBJ_BOOKS && in_inventory(item)
           && player_can_memorise_from_spellbook(item);
}

static void _update_inscription(item_def &item)
{
    if (item.base_type == OBJ_BOOKS && in_inventory(item)
        && !_can_memorise(item))
    {
        inscribe_book_highlevel(item);
    }
}

static bool _describe_spellbook(item_def &item)
{
    while (true)
    {
        // Memorised spell while reading a spellbook.
        if (already_learning_spell(-1))
            return false;

        _show_item_description(item);
        _update_inscription(item);

        cgotoxy(1, wherey());
        textcolor(LIGHTGREY);

        if (_can_memorise(item) && !crawl_state.player_is_dead())
        {
            cprintf("Select a spell to read its description, to "
                    "memorise it or to forget it.");
        }
        else
            cprintf("Select a spell to read its description.");

        if (_describe_spells(item))
            continue;

        return true;
    }
}

// it takes a key and a list of commands and it returns
// the command from the list which corresponds to the key
static command_type _get_action(int key, vector<command_type> actions)
{
    static bool act_key_init = true; // Does act_key needs to be initialise?
    static map<command_type, int> act_key;
    if (act_key_init)
    {
        act_key[CMD_WIELD_WEAPON]       = 'w';
        act_key[CMD_UNWIELD_WEAPON]     = 'u';
        act_key[CMD_QUIVER_ITEM]        = 'q';
        act_key[CMD_WEAR_ARMOUR]        = 'w';
        act_key[CMD_REMOVE_ARMOUR]      = 't';
        act_key[CMD_EVOKE]              = 'v';
        act_key[CMD_EAT]                = 'e';
        act_key[CMD_READ]               = 'r';
        act_key[CMD_WEAR_JEWELLERY]     = 'p';
        act_key[CMD_REMOVE_JEWELLERY]   = 'r';
        act_key[CMD_QUAFF]              = 'q';
        act_key[CMD_DROP]               = 'd';
        act_key[CMD_INSCRIBE_ITEM]      = 'i';
        act_key[CMD_ADJUST_INVENTORY]   = '=';
        act_key_init = false;
    }

    for (vector<command_type>::const_iterator at = actions.begin();
         at < actions.end(); ++at)
    {
        if (key == act_key[*at])
            return *at;
    }
    return CMD_NO_CMD;
}

//---------------------------------------------------------------
//
// _actions_prompt
//
// print a list of actions to be performed on the item
static bool _actions_prompt(item_def &item, bool allow_inscribe, bool do_prompt)
{
#ifdef USE_TILE_LOCAL
    PrecisionMenu menu;
    TextItem* tmp = NULL;
    MenuFreeform* freeform = new MenuFreeform();
    menu.set_select_type(PrecisionMenu::PRECISION_SINGLESELECT);
    freeform->init(coord_def(1, 1),
                   coord_def(get_number_of_cols(), get_number_of_lines()),
                   "freeform");
    menu.attach_object(freeform);
    menu.set_active_object(freeform);

    BoxMenuHighlighter* highlighter = new BoxMenuHighlighter(&menu);
    highlighter->init(coord_def(0, 0), coord_def(0, 0), "highlighter");
    menu.attach_object(highlighter);
#endif
    string prompt = "You can ";
    int keyin;
    vector<command_type> actions;
    actions.push_back(CMD_ADJUST_INVENTORY);
    if (item_equip_slot(item) == EQ_WEAPON)
        actions.push_back(CMD_UNWIELD_WEAPON);
    switch (item.base_type)
    {
    case OBJ_WEAPONS:
    case OBJ_STAVES:
    case OBJ_RODS:
    case OBJ_MISCELLANY:
        if (!item_is_equipped(item))
        {
            if (item_is_wieldable(item))
                actions.push_back(CMD_WIELD_WEAPON);
            if (is_throwable(&you, item))
                actions.push_back(CMD_QUIVER_ITEM);
        }
        break;
    case OBJ_MISSILES:
        if (you.species != SP_FELID)
            actions.push_back(CMD_QUIVER_ITEM);
        break;
    case OBJ_ARMOUR:
        if (item_is_equipped(item))
            actions.push_back(CMD_REMOVE_ARMOUR);
        else
            actions.push_back(CMD_WEAR_ARMOUR);
        break;
    case OBJ_FOOD:
        if (can_ingest(item, true, false))
            actions.push_back(CMD_EAT);
        break;
    case OBJ_SCROLLS:
    case OBJ_BOOKS: // only unknown ones
        if (item.sub_type != BOOK_MANUAL)
            actions.push_back(CMD_READ);
        break;
    case OBJ_JEWELLERY:
        if (item_is_equipped(item))
            actions.push_back(CMD_REMOVE_JEWELLERY);
        else
            actions.push_back(CMD_WEAR_JEWELLERY);
        break;
    case OBJ_POTIONS:
        if (you.is_undead != US_UNDEAD) // mummies and lich form only
            actions.push_back(CMD_QUAFF);
        break;
    default:
        ;
    }
#if defined(CLUA_BINDINGS)
    if (clua.callbooleanfn(false, "ch_item_wieldable", "i", &item))
        actions.push_back(CMD_WIELD_WEAPON);
#endif

    if (item_is_evokable(item))
        actions.push_back(CMD_EVOKE);

    actions.push_back(CMD_DROP);

    if (allow_inscribe)
        actions.push_back(CMD_INSCRIBE_ITEM);

    static bool act_str_init = true; // Does act_str needs to be initialised?
    static map<command_type, string> act_str;
    if (act_str_init)
    {
        act_str[CMD_WIELD_WEAPON]       = "(w)ield";
        act_str[CMD_UNWIELD_WEAPON]     = "(u)nwield";
        act_str[CMD_QUIVER_ITEM]        = "(q)uiver";
        act_str[CMD_WEAR_ARMOUR]        = "(w)ear";
        act_str[CMD_REMOVE_ARMOUR]      = "(t)ake off";
        act_str[CMD_EVOKE]              = "e(v)oke";
        act_str[CMD_EAT]                = "(e)at";
        act_str[CMD_READ]               = "(r)ead";
        act_str[CMD_WEAR_JEWELLERY]     = "(p)ut on";
        act_str[CMD_REMOVE_JEWELLERY]   = "(r)emove";
        act_str[CMD_QUAFF]              = "(q)uaff";
        act_str[CMD_DROP]               = "(d)rop";
        act_str[CMD_INSCRIBE_ITEM]      = "(i)nscribe";
        act_str[CMD_ADJUST_INVENTORY]   = "(=)adjust";
        act_str_init = false;
    }

    for (vector<command_type>::const_iterator at = actions.begin();
         at < actions.end(); ++at)
    {
#ifdef USE_TILE_LOCAL
        tmp = new TextItem();
        tmp->set_id(*at);
        tmp->set_text(act_str[*at]);
        tmp->set_fg_colour(CYAN);
        tmp->set_bg_colour(BLACK);
        tmp->set_highlight_colour(LIGHTGRAY);
        tmp->set_description_text(act_str[*at]);
        tmp->set_bounds(coord_def(prompt.size() + 1, wherey()),
                        coord_def(prompt.size() + act_str[*at].size() + 1,
                                  wherey() + 1));
        freeform->attach_item(tmp);
        tmp->set_visible(true);
#endif
        prompt += act_str[*at];
        if (at < actions.end() - 2)
            prompt += ", ";
        else if (at == actions.end() - 2)
            prompt += " or ";
    }
    prompt += " the " + item.name(DESC_BASENAME) + ".";

    prompt = "<cyan>" + prompt + "</cyan>";
    if (do_prompt)
        formatted_string::parse_string(prompt).display();

#ifdef TOUCH_UI

    //draw menu over the top of the prompt text
    tiles.get_crt()->attach_menu(&menu);
    freeform->set_visible(true);
    highlighter->set_visible(true);
    menu.draw_menu();
#endif

    keyin = toalower(getch_ck());
    command_type action = _get_action(keyin, actions);

#ifdef TOUCH_UI
    if (menu.process_key(keyin))
    {
        vector<MenuItem*> selection = menu.get_selected_items();
        if (selection.size() == 1)
            action = (command_type) selection.at(0)->get_id();
    }
#endif

    const int slot = item.link;
    ASSERT_RANGE(slot, 0, ENDOFPACK);

    switch (action)
    {
    case CMD_WIELD_WEAPON:
        redraw_screen();
        wield_weapon(true, slot);
        return false;
    case CMD_UNWIELD_WEAPON:
        redraw_screen();
        wield_weapon(true, SLOT_BARE_HANDS);
        return false;
    case CMD_QUIVER_ITEM:
        redraw_screen();
        quiver_item(slot);
        return false;
    case CMD_WEAR_ARMOUR:
        redraw_screen();
        wear_armour(slot);
        return false;
    case CMD_REMOVE_ARMOUR:
        redraw_screen();
        takeoff_armour(slot);
        return false;
    case CMD_EVOKE:
        redraw_screen();
        evoke_item(slot);
        return false;
    case CMD_EAT:
        redraw_screen();
        eat_food(slot);
        return false;
    case CMD_READ:
        if (item.base_type != OBJ_BOOKS || item.sub_type == BOOK_DESTRUCTION)
            redraw_screen();
        read_scroll(slot);
        // In case of a book, stay in the inventory to see the content.
        return item.base_type == OBJ_BOOKS && item.sub_type != BOOK_DESTRUCTION;
    case CMD_WEAR_JEWELLERY:
        redraw_screen();
        puton_ring(slot);
        return false;
    case CMD_REMOVE_JEWELLERY:
        redraw_screen();
        remove_ring(slot, true);
        return false;
    case CMD_QUAFF:
        redraw_screen();
        drink(slot);
        return false;
    case CMD_DROP:
        redraw_screen();
        drop_item(slot, you.inv[slot].quantity);
        return false;
    case CMD_INSCRIBE_ITEM:
        inscribe_item(item, false);
        break;
    case CMD_ADJUST_INVENTORY:
        _adjust_item(item);
        return false;
    case CMD_NO_CMD:
    default:
        return true;
    }
    return true;
}

//---------------------------------------------------------------
//
// describe_item
//
// Describes all items in the game.
// Returns false if we should break out of the inventory loop.
//---------------------------------------------------------------
bool describe_item(item_def &item, bool allow_inscribe, bool shopping)
{
    if (!item.defined())
        return true;

#ifdef USE_TILE_WEB
    tiles_crt_control show_as_menu(CRT_MENU, "describe_item");
#endif

    if (_can_show_spells(item))
        return _describe_spellbook(item);

    _show_item_description(item);
    _update_inscription(item);

    if (allow_inscribe && crawl_state.game_is_tutorial())
        allow_inscribe = false;

    // Don't ask if we're dead.
    if (in_inventory(item) && crawl_state.prev_cmd != CMD_RESISTS_SCREEN
        && !(you.dead || crawl_state.updating_scores))
    {
        // Don't draw the prompt if there aren't enough rows left.
        const bool do_prompt = wherey() <= get_number_of_lines() - 2;
        if (do_prompt)
            cgotoxy(1, wherey() + 2);
        return _actions_prompt(item, allow_inscribe, do_prompt);
    }
    else
        getchm();

    return true;
}

static void _safe_newline()
{
    if (wherey() == get_number_of_lines())
    {
        cgotoxy(1, wherey());
        formatted_string::parse_string(string(80, ' ')).display();
        cgotoxy(1, wherey());
    }
    else
        formatted_string::parse_string("\n").display();
}

// There are currently two ways to inscribe an item:
// * using the inscribe command ('{') -> msgwin = true
// * from the inventory when viewing an item -> msgwin = false
//
// msgwin also controls whether a hints mode explanation can be
// shown, or whether the pre- and post-inscription item names need to be
// printed.
void inscribe_item(item_def &item, bool msgwin)
{
    if (msgwin)
        mprf_nocap(MSGCH_EQUIPMENT, "%s", item.name(DESC_INVENTORY).c_str());

    const bool is_inscribed = !item.inscription.empty();
    string prompt = is_inscribed ? "Replace inscription with what? "
                                 : "Inscribe with what? ";

    char buf[79];
    int ret;
    if (msgwin)
        ret = msgwin_get_line(prompt, buf, sizeof buf, NULL, item.inscription);
    else
    {
        _safe_newline();
        prompt = "<cyan>" + prompt + "</cyan>";
        formatted_string::parse_string(prompt).display();
        ret = cancellable_get_line(buf, sizeof buf, NULL, NULL,
                                  item.inscription);
    }

    if (ret)
    {
        if (msgwin)
            canned_msg(MSG_OK);
        return;
    }

    // Strip spaces from the end.
    for (int i = strlen(buf) - 1; i >= 0; --i)
    {
        if (isspace(buf[i]))
            buf[i] = 0;
        else
            break;
    }

    if (item.inscription == buf)
    {
        if (msgwin)
            canned_msg(MSG_OK);
        return;
    }

    item.inscription = buf;

    if (msgwin)
    {
        mprf_nocap(MSGCH_EQUIPMENT, "%s", item.name(DESC_INVENTORY).c_str());
        you.wield_change  = true;
        you.redraw_quiver = true;
    }
}

static void _adjust_item(item_def &item)
{
    _safe_newline();
    string prompt = "<cyan>Adjust to which letter? </cyan>";
    formatted_string::parse_string(prompt).display();
    const int keyin = getch_ck();

    if (isaalpha(keyin))
    {
        const int a = letter_to_index(item.slot);
        const int b = letter_to_index(keyin);
        swap_inv_slots(a,b,true);
    }
}

static void _append_spell_stats(const spell_type spell,
                                string &description,
                                bool rod)
{
    if (rod)
    {
        snprintf(info, INFO_SIZE,
                 "\nLevel: %d",
                 spell_difficulty(spell));
    }
    else
    {
        const string schools = spell_schools_string(spell);
        char* failure = failure_rate_to_string(spell_fail(spell));
        snprintf(info, INFO_SIZE,
                 "\nLevel: %d        School%s: %s        Fail: %s",
                 spell_difficulty(spell),
                 schools.find("/") != string::npos ? "s" : "",
                 schools.c_str(),
                 failure);
        free(failure);
    }
    description += info;
    description += "\n\nPower : ";
    description += spell_power_string(spell, rod);
    description += "\nRange : ";
    description += spell_range_string(spell, rod);
    description += "\nHunger: ";
    description += spell_hunger_string(spell, rod);
    description += "\nNoise : ";
    description += spell_noise_string(spell);
    description += "\n";
}

// Returns BOOK_MEM if you can memorise the spell BOOK_FORGET if you can
// forget it and BOOK_NEITHER if you can do neither
static int _get_spell_description(const spell_type spell,
                                   string &description,
                                   const item_def* item = NULL)
{
    description.reserve(500);

    description  = spell_title(spell);
    description += "\n\n";
    const string long_descrip = getLongDescription(string(spell_title(spell))
                                                   + " spell");

    if (!long_descrip.empty())
        description += long_descrip;
    else
    {
        description += "This spell has no description. "
                       "Casting it may therefore be unwise. "
#ifdef DEBUG
                       "Instead, go fix it. ";
#else
                       "Please file a bug report.";
#endif
    }

    // Report summon cap
    if (const int limit = summons_limit(spell))
    {
        description += "You can sustain at most " + number_in_words(limit)
                       + " creature" + (limit > 1 ? "s" : "") + " summoned by this spell.\n";
    }

    const bool rod = item && item->base_type == OBJ_RODS;

    if (god_hates_spell(spell, you.religion, rod))
    {
        description += uppercase_first(god_name(you.religion))
                       + " frowns upon the use of this spell.\n";
        if (god_loathes_spell(spell, you.religion))
            description += "You'd be excommunicated if you dared to cast it!\n";
    }
    else if (god_likes_spell(spell, you.religion))
    {
        description += uppercase_first(god_name(you.religion))
                       + " supports the use of this spell.\n";
    }
    if (item && !player_can_memorise_from_spellbook(*item))
    {
        description += "The spell is scrawled in ancient runes that are beyond "
                       "your current level of understanding.\n";
    }
    if (spell_is_useless(spell))
        description += "This spell will have no effect right now.\n";

    _append_spell_stats(spell, description, rod);

    if (crawl_state.player_is_dead())
        return BOOK_NEITHER;

    const string quote = getQuoteString(string(spell_title(spell)) + " spell");
    if (!quote.empty())
        description += "\n" + quote;

    bool form = false;
    if (you_cannot_memorise(spell, form))
        description += "\n" + desc_cannot_memorise_reason(form) + "\n";

    if (item && item->base_type == OBJ_BOOKS && in_inventory(*item))
    {
        if (you.has_spell(spell))
        {
            description += "\n(F)orget this spell by destroying the book.\n";
            if (you_worship(GOD_SIF_MUNA))
                description +="Sif Muna frowns upon the destroying of books.\n";
            return BOOK_FORGET;
        }
        else if (player_can_memorise_from_spellbook(*item)
                 && !you_cannot_memorise(spell, form))
        {
            description += "\n(M)emorise this spell.\n";
            return BOOK_MEM;
        }
    }

    return BOOK_NEITHER;
}

void get_spell_desc(const spell_type spell, describe_info &inf)
{
    string desc;
    _get_spell_description(spell, desc);
    inf.body << desc;
}

//---------------------------------------------------------------
//
// describe_spell
//
// Describes (most) every spell in the game.
//
//---------------------------------------------------------------
void describe_spell(spell_type spelled, const item_def* item)
{
#ifdef USE_TILE_WEB
    tiles_crt_control show_as_menu(CRT_MENU, "describe_spell");
#endif

    string desc;
    const int mem_or_forget = _get_spell_description(spelled, desc, item);
    print_description(desc);

    mouse_control mc(MOUSE_MODE_MORE);
    char ch;
    if ((ch = getchm()) == 0)
        ch = getchm();

    if (mem_or_forget == BOOK_MEM && toupper(ch) == 'M')
    {
        redraw_screen();
        if (!learn_spell(spelled) || !you.turn_is_over)
            more();
        redraw_screen();
    }
    else if (mem_or_forget == BOOK_FORGET && toupper(ch) == 'F')
    {
        redraw_screen();
        if (!forget_spell_from_book(spelled, item) || !you.turn_is_over)
            more();
        redraw_screen();
    }
}

static string _describe_draconian(const monster_info& mi)
{
    string description;
    const int subsp = mi.draco_or_demonspawn_subspecies();

    if (subsp != mi.type)
    {
        description += "It has ";

        switch (subsp)
        {
        case MONS_BLACK_DRACONIAN:      description += "black ";   break;
        case MONS_MOTTLED_DRACONIAN:    description += "mottled "; break;
        case MONS_YELLOW_DRACONIAN:     description += "yellow ";  break;
        case MONS_GREEN_DRACONIAN:      description += "green ";   break;
        case MONS_PURPLE_DRACONIAN:     description += "purple ";  break;
        case MONS_RED_DRACONIAN:        description += "red ";     break;
        case MONS_WHITE_DRACONIAN:      description += "white ";   break;
        case MONS_GREY_DRACONIAN:       description += "grey ";    break;
        case MONS_PALE_DRACONIAN:       description += "pale ";    break;
        default:
            break;
        }

        description += "scales. ";
    }

    switch (subsp)
    {
    case MONS_BLACK_DRACONIAN:
        description += "Sparks flare out of its mouth and nostrils.";
        break;
    case MONS_MOTTLED_DRACONIAN:
        description += "Liquid flames drip from its mouth.";
        break;
    case MONS_YELLOW_DRACONIAN:
        description += "Acidic fumes swirl around it.";
        break;
    case MONS_GREEN_DRACONIAN:
        description += "Venom drips from its jaws.";
        break;
    case MONS_PURPLE_DRACONIAN:
        description += "Its outline shimmers with magical energy.";
        break;
    case MONS_RED_DRACONIAN:
        description += "Smoke pours from its nostrils.";
        break;
    case MONS_WHITE_DRACONIAN:
        description += "Frost pours from its nostrils.";
        break;
    case MONS_GREY_DRACONIAN:
        description += "Its scales and tail are adapted to the water.";
        break;
    case MONS_PALE_DRACONIAN:
        description += "It is cloaked in a pall of superheated steam.";
        break;
    default:
        break;
    }

    return description;
}

static string _describe_chimera(const monster_info& mi)
{
    string description = "It has the head of ";

    description += apply_description(DESC_A, get_monster_data(mi.base_type)->name);

    monster_type part2 = get_chimera_part(&mi,2);
    description += ", the head of ";
    if (part2 == mi.base_type)
    {
        description += "another ";
        description += apply_description(DESC_PLAIN,
                                         get_monster_data(part2)->name);
    }
    else
        description += apply_description(DESC_A, get_monster_data(part2)->name);

    monster_type part3 = get_chimera_part(&mi,3);
    description += ", and the head of ";
    if (part3 == mi.base_type || part3 == part2)
    {
        if (part2 == mi.base_type)
            description += "yet ";
        description += "another ";
        description += apply_description(DESC_PLAIN,
                                         get_monster_data(part3)->name);
    }
    else
        description += apply_description(DESC_A, get_monster_data(part3)->name);

    description += ". It has the body of ";
    description += apply_description(DESC_A,
                                     get_monster_data(mi.base_type)->name);

    const bool has_wings = mi.props.exists("chimera_batty")
                           || mi.props.exists("chimera_wings");
    if (mi.props.exists("chimera_legs"))
    {
        const monster_type leggy_part =
            get_chimera_part(&mi, mi.props["chimera_legs"].get_int());
        if (has_wings)
            description += ", ";
        else
            description += ", and ";
        description += "the legs of ";
        description += apply_description(DESC_A,
                                         get_monster_data(leggy_part)->name);
    }

    if (has_wings)
    {
        monster_type wing_part = mi.props.exists("chimera_batty") ?
            get_chimera_part(&mi, mi.props["chimera_batty"].get_int())
            : get_chimera_part(&mi, mi.props["chimera_wings"].get_int());

        switch (mons_class_flies(wing_part))
        {
        case FL_WINGED:
            description += " and the wings of ";
            break;
        case FL_LEVITATE:
            description += " and it hovers like ";
            break;
        case FL_NONE:
            description += " and it moves like "; // Unseen horrors
            break;
        }
        description += apply_description(DESC_A,
                                         get_monster_data(wing_part)->name);
    }
    description += ".";
    return description;
}

static string _describe_demonspawn_role(monster_type type)
{
    switch (type)
    {
    case MONS_BLOOD_SAINT:
        return "It weaves powerful and unpredictable spells of devastation.";
    case MONS_CHAOS_CHAMPION:
        return "It possesses chaotic, reality-warping powers.";
    case MONS_WARMONGER:
        return "It is devoted to combat, disrupting the magic of its foes as "
               "it battles endlessly.";
    case MONS_CORRUPTER:
        return "It corrupts space around itself, and can twist even the very "
               "flesh of its opponents.";
    case MONS_BLACK_SUN:
        return "It shines with an unholy radiance, and wields powers of "
               "darkness from its devotion to the deities of death.";
    default:
        return "";
    }
}

static string _describe_demonspawn_base(int species)
{
    switch (species)
    {
    case MONS_MONSTROUS_DEMONSPAWN:
        return "It is more beast now than whatever species it is descended from.";
    case MONS_GELID_DEMONSPAWN:
        return "It is covered in icy armour.";
    case MONS_INFERNAL_DEMONSPAWN:
        return "It gives off an intense heat.";
    case MONS_PUTRID_DEMONSPAWN:
        return "It is surrounded by sickly fumes and gases.";
    case MONS_TORTUROUS_DEMONSPAWN:
        return "It menaces with bony spines.";
    }
    return "";
}

static string _describe_demonspawn(const monster_info& mi)
{
    string description;
    const int subsp = mi.draco_or_demonspawn_subspecies();

    description += _describe_demonspawn_base(subsp);

    if (subsp != mi.type)
    {
        const string demonspawn_role = _describe_demonspawn_role(mi.type);
        if (!demonspawn_role.empty())
            description += " " + demonspawn_role;
    }

    return description;
}

static const char* _get_resist_name(mon_resist_flags res_type)
{
    switch (res_type)
    {
    case MR_RES_ELEC:
        return "electricity";
    case MR_RES_POISON:
        return "poison";
    case MR_RES_FIRE:
        return "fire";
    case MR_RES_STEAM:
        return "steam";
    case MR_RES_COLD:
        return "cold";
    case MR_RES_ACID:
        return "acid";
    case MR_RES_ROTTING:
        return "rotting";
    case MR_RES_NEG:
        return "negative energy";
    default:
        return "buggy resistance";
    }
}

static const char* _get_threat_desc(mon_threat_level_type threat)
{
    switch (threat)
    {
    case MTHRT_TRIVIAL: return "harmless";
    case MTHRT_EASY:    return "easy";
    case MTHRT_TOUGH:   return "dangerous";
    case MTHRT_NASTY:   return "extremely dangerous";
    case MTHRT_UNDEF:
    default:            return "buggily threatening";
    }
}

static const char* _describe_attack_flavour(attack_flavour flavour)
{
    switch (flavour)
    {
    case AF_ACID:            return "deal extra acid damage";
    case AF_BLINK:           return "blink self";
    case AF_COLD:            return "deal extra cold damage";
    case AF_CONFUSE:         return "cause confusion";
    case AF_DRAIN_STR:       return "drain strength";
    case AF_DRAIN_INT:       return "drain intelligence";
    case AF_DRAIN_DEX:       return "drain dexterity";
    case AF_DRAIN_STAT:      return "drain strength, intelligence or dexterity";
    case AF_DRAIN_XP:        return "drain skills";
    case AF_ELEC:            return "cause electrocution";
    case AF_FIRE:            return "deal extra fire damage";
    case AF_HUNGER:          return "cause hungering";
    case AF_MUTATE:          return "cause mutations";
    case AF_PARALYSE:        return "cause paralysis";
    case AF_POISON:          return "cause poisoning";
    case AF_POISON_STRONG:   return "cause strong poisoning through resistance";
    case AF_ROT:             return "cause rotting";
    case AF_VAMPIRIC:        return "drain health";
    case AF_KLOWN:           return "cause random powerful effects";
    case AF_DISTORT:         return "cause wild translocation effects";
    case AF_RAGE:            return "cause berserking";
    case AF_STICKY_FLAME:    return "apply sticky flame";
    case AF_CHAOS:           return "cause unpredictable effects";
    case AF_STEAL:           return "steal items";
    case AF_CRUSH:           return "constrict";
    case AF_REACH:           return "deal damage from a distance";
    case AF_HOLY:            return "deal extra damage to undead and demons";
    case AF_ANTIMAGIC:       return "drain magic";
    case AF_PAIN:            return "cause pain to the living";
    case AF_ENSNARE:         return "ensnare with webbing";
    case AF_ENGULF:          return "engulf with water";
    case AF_PURE_FIRE:       return "deal pure fire damage";
    case AF_DRAIN_SPEED:     return "drain speed";
    case AF_VULN:            return "reduce resistance to hostile enchantments";
    case AF_WEAKNESS_POISON: return "cause poison and weakness";
    case AF_SHADOWSTAB:      return "deal extra damage from the shadows";
    case AF_DROWN:           return "deal drowning damage";
    case AF_FIREBRAND:       return "deal extra fire damage and surround the defender with flames";
    default:                 return "";
    }
}

static string _monster_attacks_description(const monster_info& mi)
{
    ostringstream result;
    vector<attack_flavour> attack_flavours;
    vector<string> attack_descs;
    // Weird attack types that act like attack flavours.
    bool trample = false;
    bool reach_sting = false;

    for (int i = 0; i < MAX_NUM_ATTACKS; ++i)
    {
        attack_flavour af = mi.attack[i].flavour;

        bool match = false;
        for (unsigned int k = 0; k < attack_flavours.size(); ++k)
            if (attack_flavours[k] == af)
                match = true;

        if (!match)
        {
            attack_flavours.push_back(af);
            const char* desc = _describe_attack_flavour(af);
            if (*desc)
                attack_descs.push_back(desc);
        }

        if (mi.attack[i].type == AT_TRAMPLE)
            trample = true;

        if (mi.attack[i].type == AT_REACH_STING)
            reach_sting = true;
    }

    if (trample)
        attack_descs.push_back("knock back the defender");

    // Assumes nothing has both AT_REACH_STING and AF_REACH.
    if (reach_sting)
        attack_descs.push_back(_describe_attack_flavour(AF_REACH));

    if (!attack_descs.empty())
    {
        result << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE));
        result << " may attack to " << comma_separated_line(attack_descs.begin(), attack_descs.end());
        result << ".\n";
    }

    return result.str();
}

static string _monster_spells_description(const monster_info& mi)
{
    // Show a generic message for pan lords, since they're secret.
    if (mi.type == MONS_PANDEMONIUM_LORD)
        return "It may possess any of a vast number of diabolical powers.\n";

    // Show monster spells and spell-like abilities.
    if (!mi.is_spellcaster() || !mi.has_spells())
        return "";

    unique_books books = get_unique_spells(mi);
    const size_t num_books = books.size();

    const bool caster  = mi.is_actual_spellcaster();
    const bool priest  = mi.is_priest();
    const bool natural = mi.is_natural_caster();
    string adj = priest ? "divine" : natural ? "special" : "magical";

    ostringstream result;
    result << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE));

    // cjo: the division here gets really arbitrary. For example, wretched
    // stars cast mystic blast, but are not flagged with M_ACTUAL_SPELLS.
    // Possibly these should be combined.
    if (caster && num_books > 1)
        result << " has mastered one of the following spellbooks:\n";
    else if (caster)
        result << " has mastered the following spells: ";
    else if (num_books == 1)
        result << " possesses the following " << adj << " abilities: ";
    else
    {
        result << " possesses one of the following sets of " << adj
               << " abilities: \n";
    }

    // Loop through books and display spells/abilities for each of them
    for (size_t i = 0; i < num_books; ++i)
    {
        vector<spell_type> &book_spells = books[i];

        // Display spells for this book
        if (num_books > 1)
            result << (caster ? " Book " : " Set ") << i+1 << ": ";

        for (size_t j = 0; j < book_spells.size(); ++j)
        {
            const spell_type spell = book_spells[j];
            if (j > 0)
                result << ", ";
            result << spell_title(spell);
        }
        result << "\n";
    }

    return result.str();
}

static const char *_speed_description(int speed)
{
    // These thresholds correspond to the player mutations for fast and slow.
    ASSERT(speed != 10);
    if (speed < 7)
        return "extremely slowly";
    else if (speed < 8)
        return "very slowly";
    else if (speed < 10)
        return "slowly";
    else if (speed > 15)
        return "extremely quickly";
    else if (speed > 13)
        return "very quickly";
    else if (speed > 10)
        return "quickly";

    return "buggily";
}

static void _add_energy_to_string(int speed, int energy, string what,
                                  vector<string> &fast, vector<string> &slow)
{
    if (energy == 10)
        return;

    const int act_speed = (speed * 10) / energy;
    if (act_speed > 10)
        fast.push_back(what + " " + _speed_description(act_speed));
    if (act_speed < 10)
        slow.push_back(what + " " + _speed_description(act_speed));
}

// Describe a monster's (intrinsic) resistances, speed and a few other
// attributes.
static string _monster_stat_description(const monster_info& mi)
{
    ostringstream result;

    resists_t resist = mi.resists();

    const mon_resist_flags resists[] =
    {
        MR_RES_ELEC,    MR_RES_POISON, MR_RES_FIRE,
        MR_RES_STEAM,   MR_RES_COLD,   MR_RES_ACID,
        MR_RES_ROTTING, MR_RES_NEG,
    };

    vector<string> extreme_resists;
    vector<string> high_resists;
    vector<string> base_resists;
    vector<string> suscept;

    for (unsigned int i = 0; i < ARRAYSZ(resists); ++i)
    {
        int level = get_resist(resist, resists[i]);

        if (level != 0)
        {
            const char* attackname = _get_resist_name(resists[i]);
            level = max(level, -1);
            level = min(level,  3);
            switch (level)
            {
                case -1:
                    suscept.push_back(attackname);
                    break;
                case 1:
                    base_resists.push_back(attackname);
                    break;
                case 2:
                    high_resists.push_back(attackname);
                    break;
                case 3:
                    extreme_resists.push_back(attackname);
                    break;
            }
        }
    }

    vector<string> resist_descriptions;
    if (!extreme_resists.empty())
    {
        const string tmp = "immune to "
            + comma_separated_line(extreme_resists.begin(),
                                   extreme_resists.end());
        resist_descriptions.push_back(tmp);
    }
    if (!high_resists.empty())
    {
        const string tmp = "very resistant to "
            + comma_separated_line(high_resists.begin(), high_resists.end());
        resist_descriptions.push_back(tmp);
    }
    if (!base_resists.empty())
    {
        const string tmp = "resistant to "
            + comma_separated_line(base_resists.begin(), base_resists.end());
        resist_descriptions.push_back(tmp);
    }

    const char* pronoun = mi.pronoun(PRONOUN_SUBJECTIVE);

    if (mi.threat != MTHRT_UNDEF)
    {
        result << uppercase_first(pronoun) << " looks "
               << _get_threat_desc(mi.threat) << ".\n";
    }

    if (!resist_descriptions.empty())
    {
        result << uppercase_first(pronoun) << " is "
               << comma_separated_line(resist_descriptions.begin(),
                                       resist_descriptions.end(),
                                       "; and ", "; ")
               << ".\n";
    }

    // Is monster susceptible to anything? (On a new line.)
    if (!suscept.empty())
    {
        result << uppercase_first(pronoun) << " is susceptible to "
               << comma_separated_line(suscept.begin(), suscept.end())
               << ".\n";
    }

    const int mr = mi.res_magic();
    // How resistant is it? Same scale as the player.
    if (mr >= 40)
    {
        result << uppercase_first(pronoun)
               << make_stringf(" is %s to hostile enchantments.\n",
                               magic_res_adjective(mr).c_str());
    }

    if (mons_class_flag(mi.type, M_STATIONARY)
        && !mons_is_tentacle_or_tentacle_segment(mi.type))
    {
        result << uppercase_first(pronoun) << " cannot move.\n";
    }

    if (mons_class_flag(mi.type, M_BLINKER))
        result << uppercase_first(pronoun) << " blinks uncontrollably.\n";

    // Monsters can glow from both light and radiation.
    if (mons_class_flag(mi.type, M_GLOWS_LIGHT))
        result << uppercase_first(pronoun) << " is outlined in light.\n";
    if (mons_class_flag(mi.type, M_GLOWS_RADIATION))
        result << uppercase_first(pronoun) << " is glowing with mutagenic radiation.\n";
    if (mons_class_flag(mi.type, M_SHADOW))
        result << uppercase_first(pronoun) << " is wreathed in shadows.\n";

    // Seeing/sensing invisible.
    if (mons_class_flag(mi.type, M_SEE_INVIS)
            || ((mons_is_pghost(mi.type) || mi.type == MONS_PANDEMONIUM_LORD)
                && mi.u.ghost.can_sinv))
    {
        result << uppercase_first(pronoun) << " can see invisible.\n";
    }
    else if (mons_class_flag(mi.type, M_SENSE_INVIS))
        result << uppercase_first(pronoun) << " can sense the presence of invisible creatures.\n";

    // Unusual monster speed.
    const int speed = mi.base_speed();
    bool did_speed = false;
    if (speed != 10 && speed != 0)
    {
        did_speed = true;
        result << uppercase_first(pronoun) << " is ";
        if (speed < 7)
            result << "very slow";
        else if (speed < 10)
            result << "slow";
        else if (speed > 20)
            result << "extremely fast";
        else if (speed > 15)
            result << "very fast";
        else if (speed > 10)
            result << "fast";
    }
    const mon_energy_usage def = DEFAULT_ENERGY;
    if (!(mi.menergy == def))
    {
        const mon_energy_usage me = mi.menergy;
        vector<string> fast, slow;
        if (!did_speed)
            result << uppercase_first(pronoun) << " ";
        _add_energy_to_string(speed, me.move, "covers ground", fast, slow);
        // since MOVE_ENERGY also sets me.swim
        if (me.swim != me.move)
            _add_energy_to_string(speed, me.swim, "swims", fast, slow);
        _add_energy_to_string(speed, me.attack, "attacks", fast, slow);
        _add_energy_to_string(speed, me.missile, "shoots", fast, slow);
        _add_energy_to_string(
            speed, me.spell,
            mi.is_actual_spellcaster() ? "casts spells" :
            mi.is_priest()             ? "uses invocations"
                                       : "uses natural abilities", fast, slow);
        _add_energy_to_string(speed, me.special, "uses special abilities",
                              fast, slow);
        _add_energy_to_string(speed, me.item, "uses items", fast, slow);

        if (speed >= 10)
        {
            if (did_speed && fast.size() == 1)
                result << " and " << fast[0];
            else if (!fast.empty())
            {
                if (did_speed)
                    result << ", ";
                result << comma_separated_line(fast.begin(), fast.end());
            }
            if (!slow.empty())
            {
                if (did_speed || !fast.empty())
                    result << ", but ";
                result << comma_separated_line(slow.begin(), slow.end());
            }
        }
        else if (speed < 10)
        {
            if (did_speed && slow.size() == 1)
                result << " and " << slow[0];
            else if (!slow.empty())
            {
                if (did_speed)
                    result << ", ";
                result << comma_separated_line(slow.begin(), slow.end());
            }
            if (!fast.empty())
            {
                if (did_speed || !slow.empty())
                    result << ", but ";
                result << comma_separated_line(fast.begin(), fast.end());
            }
        }
        result << ".\n";
    }
    else if (did_speed)
        result << ".\n";

    // Can the monster fly, and how?
    // This doesn't give anything away since no (very) ugly things can
    // fly, all ghosts can fly, and for demons it's already mentioned in
    // their flavour description.
    switch (mi.fly)
    {
    case FL_NONE:
        break;
    case FL_WINGED:
        result << uppercase_first(pronoun) << " can fly.\n";
        break;
    case FL_LEVITATE:
        result << uppercase_first(pronoun) << " can fly magically.\n";
        break;
    }

    // Unusual regeneration rates.
    if (!mi.can_regenerate())
        result << uppercase_first(pronoun) << " cannot regenerate.\n";
    else if (mons_class_fast_regen(mi.type))
        result << uppercase_first(pronoun) << " regenerates quickly.\n";

    // Size
    static const char * const sizes[] =
    {
        "tiny",
        "very small",
        "small",
        NULL,     // don't display anything for 'medium'
        "large",
        "very large",
        "giant",
    };
    COMPILE_CHECK(ARRAYSZ(sizes) == NUM_SIZE_LEVELS);

    if (mons_is_feat_mimic(mi.type))
    {
        result << uppercase_first(pronoun) << " is as big as "
               << thing_do_grammar(DESC_A, true, false,
                                   feat_type_name(mi.get_mimic_feature()))
               << "\n";
    }
    else if (sizes[mi.body_size()])
        result << uppercase_first(pronoun) << " is " << sizes[mi.body_size()] << ".\n";

    result << _monster_attacks_description(mi);
    result << _monster_spells_description(mi);

    return result.str();
}

static string _serpent_of_hell_flavour(monster_type m)
{
    switch (m)
    {
    case MONS_SERPENT_OF_HELL_COCYTUS:
        return "cocytus";
    case MONS_SERPENT_OF_HELL_DIS:
        return "dis";
    case MONS_SERPENT_OF_HELL_TARTARUS:
        return "tartarus";
    default:
        return "gehenna";
    }
}

// Fetches the monster's database description and reads it into inf.
void get_monster_db_desc(const monster_info& mi, describe_info &inf,
                         bool &has_stat_desc, bool force_seen)
{
    if (inf.title.empty())
        inf.title = getMiscString(mi.common_name(DESC_DBNAME) + " title");
    if (inf.title.empty())
        inf.title = uppercase_first(mi.full_name(DESC_A, true)) + ".";

    string db_name;

    if (mi.props.exists("dbname"))
        db_name = mi.props["dbname"].get_string();
    else if (mi.mname.empty())
        db_name = mi.db_name();
    else
        db_name = mi.full_name(DESC_PLAIN, true);

    if (mons_species(mi.type) == MONS_SERPENT_OF_HELL)
        db_name += " " + _serpent_of_hell_flavour(mi.type);

    // This is somewhat hackish, but it's a good way of over-riding monsters'
    // descriptions in Lua vaults by using MonPropsMarker. This is also the
    // method used by set_feature_desc_long, etc. {due}
    if (!mi.description.empty())
        inf.body << mi.description;
    // Don't get description for player ghosts.
    else if (mi.type != MONS_PLAYER_GHOST
             && mi.type != MONS_PLAYER_ILLUSION)
    {
        inf.body << getLongDescription(db_name);
    }

    // And quotes {due}
    if (!mi.quote.empty())
        inf.quote = mi.quote;
    else
        inf.quote = getQuoteString(db_name);

    string symbol;
    symbol += get_monster_data(mi.type)->basechar;
    if (isaupper(symbol[0]))
        symbol = "cap-" + symbol;

    string quote2;
    if (!mons_is_unique(mi.type))
    {
        string symbol_prefix = "__" + symbol + "_prefix";
        inf.prefix = getLongDescription(symbol_prefix);

        string symbol_suffix = "__" + symbol + "_suffix";
        quote2 = getQuoteString(symbol_suffix);
    }

    if (!inf.quote.empty() && !quote2.empty())
        inf.quote += "\n";
    inf.quote += quote2;

    switch (mi.type)
    {
    case MONS_VAMPIRE:
    case MONS_VAMPIRE_KNIGHT:
    case MONS_VAMPIRE_MAGE:
        if (you.is_undead == US_ALIVE && mi.attitude == ATT_HOSTILE)
            inf.body << "\nIt wants to drink your blood!\n";
        break;

    case MONS_REAPER:
        if (you.is_undead == US_ALIVE && mi.attitude == ATT_HOSTILE)
            inf.body <<  "\nIt has come for your soul!\n";
        break;

    case MONS_RED_DRACONIAN:
    case MONS_WHITE_DRACONIAN:
    case MONS_GREEN_DRACONIAN:
    case MONS_PALE_DRACONIAN:
    case MONS_MOTTLED_DRACONIAN:
    case MONS_BLACK_DRACONIAN:
    case MONS_YELLOW_DRACONIAN:
    case MONS_PURPLE_DRACONIAN:
    case MONS_GREY_DRACONIAN:
    case MONS_DRACONIAN_SHIFTER:
    case MONS_DRACONIAN_SCORCHER:
    case MONS_DRACONIAN_ZEALOT:
    case MONS_DRACONIAN_ANNIHILATOR:
    case MONS_DRACONIAN_CALLER:
    case MONS_DRACONIAN_MONK:
    case MONS_DRACONIAN_KNIGHT:
    {
        inf.body << "\n" << _describe_draconian(mi) << "\n";
        break;
    }

    case MONS_MONSTROUS_DEMONSPAWN:
    case MONS_GELID_DEMONSPAWN:
    case MONS_INFERNAL_DEMONSPAWN:
    case MONS_PUTRID_DEMONSPAWN:
    case MONS_TORTUROUS_DEMONSPAWN:
    case MONS_BLOOD_SAINT:
    case MONS_CHAOS_CHAMPION:
    case MONS_WARMONGER:
    case MONS_CORRUPTER:
    case MONS_BLACK_SUN:
    {
        inf.body << "\n" << _describe_demonspawn(mi) << "\n";
        break;
    }

    case MONS_PLAYER_GHOST:
        inf.body << "The apparition of " << get_ghost_description(mi) << ".\n";
        break;

    case MONS_PLAYER_ILLUSION:
        inf.body << "An illusion of " << get_ghost_description(mi) << ".\n";
        break;

    case MONS_PANDEMONIUM_LORD:
        inf.body << _describe_demon(mi.mname, mi.fly) << "\n";
        break;

    case MONS_CHIMERA:
        inf.body << "\n" << _describe_chimera(mi) << "\n";
        break;

    case MONS_PROGRAM_BUG:
        inf.body << "If this monster is a \"program bug\", then it's "
                "recommended that you save your game and reload.  Please report "
                "monsters who masquerade as program bugs or run around the "
                "dungeon without a proper description to the authorities.\n";
        break;

    default:
        break;
    }

    if (!mons_is_unique(mi.type))
    {
        string symbol_suffix = "__";
        symbol_suffix += symbol;
        symbol_suffix += "_suffix";

        string suffix = getLongDescription(symbol_suffix);
              suffix += getLongDescription(symbol_suffix + "_examine");

        if (!suffix.empty())
            inf.body << "\n" << suffix;
    }

    // Get information on resistances, speed, etc.
    string result = _monster_stat_description(mi);
    if (!result.empty())
    {
        inf.body << "\n" << result;
        has_stat_desc = true;
    }

    bool stair_use = false;
    if (!mons_class_can_use_stairs(mi.type))
    {
        inf.body << "\n" << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE))
                 << " is incapable of using stairs.\n";
        stair_use = true;
    }

    if (mi.intel() <= I_PLANT)
    {
        inf.body << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE))
                 << " is mindless.\n";
    }
    else if (mi.intel() <= I_INSECT && you_worship(GOD_ELYVILON))
    {
        inf.body << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE))
                 << " is not intelligent enough to pacify.\n";
    }


    if (mi.is(MB_CHAOTIC))
    {
        inf.body << uppercase_first(mi.pronoun(PRONOUN_SUBJECTIVE))
                 << " is vulnerable to silver and hated by Zin.\n";
    }

    if (mi.is(MB_SUMMONED))
    {
        inf.body << "\n" << "This monster has been summoned, and is thus only "
                       "temporary. Killing it yields no experience, nutrition "
                       "or items";
        if (!stair_use && mi.is(MB_SUMMONED_NO_STAIRS))
            inf.body << ", and it is incapable of using stairs";
        inf.body << ".\n";
    }

    if (mi.is(MB_PERM_SUMMON))
    {
        inf.body << "\n" << "This monster has been summoned in a durable "
                       "way, and only partially exists. Killing it yields no "
                       "experience, nutrition or items. You cannot easily "
                       "abjure it, though.\n";
    }

    if (mi.is(MB_SUMMONED_CAPPED))
    {
        inf.body << "\n" << "You have summoned too many monsters of this kind "
                            "to sustain them all, and thus this one will "
                            "shortly expire.\n";
    }

    if (!inf.quote.empty())
        inf.quote += "\n";

#ifdef DEBUG_DIAGNOSTICS
    if (mi.pos.origin() || !monster_at(mi.pos))
        return; // not a real monster
    monster& mons = *monster_at(mi.pos);

    if (mons.has_originating_map())
    {
        inf.body << make_stringf("\nPlaced by map: %s",
                                 mons.originating_map().c_str());
    }

    inf.body << "\nMonster health: "
             << mons.hit_points << "/" << mons.max_hit_points << "\n";

    const actor *mfoe = mons.get_foe();
    inf.body << "Monster foe: "
             << (mfoe? mfoe->name(DESC_PLAIN, true)
                 : "(none)");

    vector<string> attitude;
    if (mons.friendly())
        attitude.push_back("friendly");
    if (mons.neutral())
        attitude.push_back("neutral");
    if (mons.good_neutral())
        attitude.push_back("good_neutral");
    if (mons.strict_neutral())
        attitude.push_back("strict_neutral");
    if (mons.pacified())
        attitude.push_back("pacified");
    if (mons.wont_attack())
        attitude.push_back("wont_attack");
    if (!attitude.empty())
    {
        inf.body << "; " << comma_separated_line(attitude.begin(),
                                                 attitude.end(),
                                                 "; ", "; ");
    }

    if (mons.can_use_spells())
    {
        const monster_spells &hspell_pass = mons.spells;
        bool found_spell = false;

        for (int i = 0; i < NUM_MONSTER_SPELL_SLOTS; ++i)
        {
            if (hspell_pass[i] != SPELL_NO_SPELL)
            {
                if (!found_spell)
                {
                    inf.body << "\n\nMonster Spells:\n";
                    found_spell = true;
                }

                inf.body << "    " << i << ": "
                         << spell_title(hspell_pass[i])
                         << " (" << static_cast<int>(hspell_pass[i])
                         << ")";
            }
        }
    }

    bool has_item = false;
    for (int i = 0; i < NUM_MONSTER_SLOTS; ++i)
    {
        if (mons.inv[i] != NON_ITEM)
        {
            if (!has_item)
            {
                inf.body << "\n\nMonster Inventory:\n";
                has_item = true;
            }
            inf.body << "    " << i << ": "
                     << mitm[mons.inv[i]].name(DESC_A, false, true);
        }
    }

    if (mons.props.exists("blame"))
    {
        inf.body << "\n\nMonster blame chain:\n";

        const CrawlVector& blame = mons.props["blame"].get_vector();

        for (CrawlVector::const_iterator it = blame.begin();
             it != blame.end(); ++it)
        {
            inf.body << "    " << it->get_string() << "\n";
        }
    }
#endif
}

int describe_monsters(const monster_info &mi, bool force_seen,
                      const string &footer)
{
    describe_info inf;
    bool has_stat_desc = false;
    get_monster_db_desc(mi, inf, has_stat_desc, force_seen);

    bool show_quote = false;

    if (!footer.empty())
    {
        if (inf.footer.empty())
            inf.footer = footer;
        else
            inf.footer += "\n" + footer;
    }

#ifdef USE_TILE_WEB
    tiles_crt_control show_as_menu(CRT_MENU, "describe_monster");
#endif

    int key;
    do
    {
        if (show_quote)
            _print_quote(inf);
        else
        {
            print_description(inf);

            // TODO enne - this should really move into get_monster_db_desc
            // and an additional tutorial string added to describe_info.
            if (crawl_state.game_is_hints())
                hints_describe_monster(mi, has_stat_desc);
        }

        show_quote = !show_quote;
    }
    while (_print_toggle_message(inf, key));

    return key;
}

static const char* xl_rank_names[] =
{
    "weakling",
    "average",
    "experienced",
    "powerful",
    "mighty",
    "great",
    "awesomely powerful",
    "legendary"
};

static string _xl_rank_name(const int xl_rank)
{
    const string rank = xl_rank_names[xl_rank];

    return article_a(rank);
}

string short_ghost_description(const monster *mon, bool abbrev)
{
    ASSERT(mons_is_pghost(mon->type));

    const ghost_demon &ghost = *(mon->ghost);
    const char* rank = xl_rank_names[ghost_level_to_rank(ghost.xl)];

    string desc = make_stringf("%s %s %s", rank,
                               species_name(ghost.species).c_str(),
                               get_job_name(ghost.job));

    if (abbrev || strwidth(desc) > 40)
    {
        desc = make_stringf("%s %s%s",
                            rank,
                            get_species_abbrev(ghost.species),
                            get_job_abbrev(ghost.job));
    }

    return desc;
}

// Describes the current ghost's previous owner. The caller must
// prepend "The apparition of" or whatever and append any trailing
// punctuation that's wanted.
string get_ghost_description(const monster_info &mi, bool concise)
{
    ostringstream gstr;

    const species_type gspecies = mi.u.ghost.species;

    // We're fudging stats so that unarmed combat gets based off
    // of the ghost's species, not the player's stats... exact
    // stats aren't required anyway, all that matters is whether
    // dex >= str. -- bwr
    const int dex = 10;
    int str = 5;

    switch (gspecies)
    {
    case SP_MOUNTAIN_DWARF:
    case SP_DEEP_DWARF:
    case SP_TROLL:
    case SP_OGRE:
    case SP_MINOTAUR:
    case SP_HILL_ORC:
#if TAG_MAJOR_VERSION == 34
    case SP_LAVA_ORC:
#endif
    case SP_CENTAUR:
    case SP_NAGA:
    case SP_MUMMY:
    case SP_GHOUL:
    case SP_FORMICID:
    case SP_VINE_STALKER:
        str += 10;
        break;

    case SP_HUMAN:
    case SP_DEMIGOD:
    case SP_DEMONSPAWN:
        str += 5;
        break;

    default:
        break;
    }

    gstr << mi.mname << " the "
         << skill_title_by_rank(mi.u.ghost.best_skill,
                        mi.u.ghost.best_skill_rank,
                        gspecies,
                        str, dex, mi.u.ghost.religion)
         << ", " << _xl_rank_name(mi.u.ghost.xl_rank) << " ";

    if (concise)
    {
        gstr << get_species_abbrev(gspecies)
             << get_job_abbrev(mi.u.ghost.job);
    }
    else
    {
        gstr << species_name(gspecies)
             << " "
             << get_job_name(mi.u.ghost.job);
    }

    if (mi.u.ghost.religion != GOD_NO_GOD)
    {
        gstr << " of "
             << god_name(mi.u.ghost.religion);
    }

    return gstr.str();
}

extern ability_type god_abilities[NUM_GODS][MAX_GOD_ABILITIES];

static bool _print_final_god_abil_desc(int god, const string &final_msg,
                                       const ability_type abil)
{
    // If no message then no power.
    if (final_msg.empty())
        return false;

    string buf = final_msg;

    // For ability slots that give more than one ability, display
    // "Various" instead of the cost of the first ability.
    const string cost =
        "(" +
              ((abil == ABIL_ELYVILON_LESSER_HEALING_SELF
                || abil == ABIL_ELYVILON_GREATER_HEALING_OTHERS
                || abil == ABIL_YRED_RECALL_UNDEAD_SLAVES) ?
                    "Various" : make_cost_description(abil))
            + ")";

    if (cost != "(None)")
    {
        // XXX: Handle the display better when the description and cost
        // are too long for the screen.
        buf = chop_string(buf, get_number_of_cols() - 1 - strwidth(cost));
        buf += cost;
    }

    cprintf("%s\n", buf.c_str());

    return true;
}

static bool _print_god_abil_desc(int god, int numpower)
{
    // Combine the two lesser healing powers together.
    if (god == GOD_ELYVILON && numpower == 0)
    {
        _print_final_god_abil_desc(god,
                                   "You can provide lesser healing for yourself and others.",
                                   ABIL_ELYVILON_LESSER_HEALING_SELF);
        return true;
    }
    const char* pmsg = god_gain_power_messages[god][numpower];

    // If no message then no power.
    if (!pmsg[0])
        return false;

    // Don't display ability upgrades here.
    string buf = adjust_abil_message(pmsg, false);
    if (buf.empty())
        return false;

    if (!isupper(pmsg[0])) // Complete sentence given?
        buf = "You can " + buf + ".";

    // This might be ABIL_NON_ABILITY for passive abilities.
    const ability_type abil = god_abilities[god][numpower];
    _print_final_god_abil_desc(god, buf, abil);

    return true;
}

static int _piety_level(int piety)
{
    return (piety >= piety_breakpoint(5)) ? 7 :
           (piety >= piety_breakpoint(4)) ? 6 :
           (piety >= piety_breakpoint(3)) ? 5 :
           (piety >= piety_breakpoint(2)) ? 4 :
           (piety >= piety_breakpoint(1)) ? 3 :
           (piety >= piety_breakpoint(0)) ? 2 :
           (piety >                    0) ? 1
                                          : 0;
}

static int _gold_level()
{
    return (you.gold >= 50000) ? 7 :
           (you.gold >= 10000) ? 6 :
           (you.gold >=  5000) ? 5 :
           (you.gold >=  1000) ? 4 :
           (you.gold >=   500) ? 3 :
           (you.gold >=   100) ? 2
                               : 1;
}

//---------------------------------------------------------------
//
// describe_god
//
// Describes the player's standing with his deity.
//
//---------------------------------------------------------------

static string _describe_favour(god_type which_god)
{
    if (player_under_penance())
    {
        const int penance = you.penance[which_god];
        return (penance >= 50) ? "Godly wrath is upon you!" :
               (penance >= 20) ? "You've transgressed heavily! Be penitent!" :
               (penance >=  5) ? "You are under penance."
                               : "You should show more discipline.";
    }

    if (which_god == GOD_XOM)
        return uppercase_first(describe_xom_favour());

    const int rank = which_god == GOD_GOZAG ? _gold_level()
                                            : _piety_level(you.piety);

    const string godname = god_name(which_god);
    switch (rank)
    {
        case 7:  return "A prized avatar of " + godname;
        case 6:  return "A favoured servant of " + godname + ".";
        case 5:

        if (you_worship(GOD_DITHMENOS))
            return "A glorious shadow in the eyes of " + godname + ".";
        else
            return "A shining star in the eyes of " + godname + ".";

        case 4:

        if (you_worship(GOD_DITHMENOS))
            return "A rising shadow in the eyes of " + godname + ".";
        else
            return "A rising star in the eyes of " + godname + ".";

        case 3:  return uppercase_first(godname) + " is most pleased with you.";
        case 2:  return uppercase_first(godname) + " is pleased with you.";
        default: return uppercase_first(godname) + " is noncommittal.";
    }
}

static string _religion_help(god_type god)
{
    string result = "";

    switch (god)
    {
    case GOD_ZIN:
        if (!player_under_penance()
            && you.piety >= piety_breakpoint(5)
            && !you.one_time_ability_used[god])
        {
            result += "You can have all your mutations cured.\n";
        }
        result += "You can pray at an altar to donate money.";
        break;

    case GOD_SHINING_ONE:
    {
        const int halo_size = you.halo_radius2();
        if (halo_size >= 0)
        {
            if (!result.empty())
                result += " ";

            result += "You radiate a ";

            if (halo_size > 37)
                result += "large ";
            else if (halo_size > 10)
                result += "";
            else
                result += "small ";

            result += "righteous aura, and all beings within it are "
                      "easier to hit.";
        }
        if (!player_under_penance()
            && you.piety >= piety_breakpoint(5)
            && !you.one_time_ability_used[god])
        {
            if (!result.empty())
                result += " ";

            result += "You can pray at an altar to have your weapon "
                      "blessed, especially a long blade or demon "
                      "weapon.";
        }
        break;
    }

    case GOD_ELYVILON:
        result += "You can pray to destroy weapons on the ground in "
                + apostrophise(god_name(god)) + " name. Inscribe them "
                + "with !p, !* or =p to avoid sacrificing them accidentally.";
        break;

    case GOD_LUGONU:
        if (!player_under_penance()
            && you.piety >= piety_breakpoint(5)
            && !you.one_time_ability_used[god])
        {
            result += "You can pray at an altar to have your weapon "
                      "corrupted.";
        }
        break;

    case GOD_KIKUBAAQUDGHA:
        if (!player_under_penance()
            && you.piety >= piety_breakpoint(5)
            && !you.one_time_ability_used[god])
        {
            result += "You can pray at an altar to have your necromancy "
                      "enhanced.";
        }
        break;

    case GOD_BEOGH:
        result += "You can pray to sacrifice all orcish remains on your "
                  "square.";
        break;

    case GOD_FEDHAS:
        if (you.piety >= piety_breakpoint(0))
        {
            result += "Evolving plants requires fruit, and evolving "
                      "fungi requires piety.";
        }
        break;

    case GOD_GOZAG:
        if (!player_under_penance()
            && !you.one_time_ability_used[god])
        {
            result += "You can place a non-artefact item on an altar and pray "
                      "to duplicate that item.";
        }
        break;

    default:
        break;
    }

    if (god_likes_fresh_corpses(god))
    {
        if (!result.empty())
            result += " ";

        result += "You can pray to sacrifice all fresh corpses on your "
                  "square.";
    }

    return result;
}

// The various titles granted by the god of your choice.  Note that Xom
// doesn't use piety the same way as the other gods, so these are just
// placeholders.
static const char *divine_title[NUM_GODS][8] =
{
    // No god.
    {"Buglet",             "Firebug",               "Bogeybug",                 "Bugger",
     "Bugbear",            "Bugged One",            "Giant Bug",                "Lord of the Bugs"},

    // Zin.
    {"Blasphemer",         "Anchorite",             "Apologist",                "Pious",
     "Devout",             "Orthodox",              "Immaculate",               "Bringer of Law"},

    // The Shining One.
    {"Honourless",         "Acolyte",               "Righteous",                "Unflinching",
     "Holy Warrior",       "Exorcist",              "Demon Slayer",             "Bringer of Light"},

    // Kikubaaqudgha -- scholarly death.
    {"Tormented",          "Purveyor of Pain",      "Death's Scholar",          "Merchant of Misery",
     "Death's Artisan",    "Dealer of Despair",     "Black Sun",                "Lord of Darkness"},

    // Yredelemnul -- zombie death.
    {"Traitor",            "Zealot",                "Exhumer",                  "Fey %s",
     "Soul Tainter",       "Sculptor of Flesh",     "Harbinger of Death",       "Grim Reaper"},

    // Xom.
    {"Toy",                "Toy",                   "Toy",                      "Toy",
     "Toy",                "Toy",                   "Toy",                      "Toy"},

    // Vehumet -- battle mage theme.
    {"Meek",               "Sorcerer's Apprentice", "Scholar of Destruction",   "Caster of Ruination",
     "Battle Magician",    "Warlock",               "Annihilator",              "Luminary of Lethal Lore"},

    // Okawaru -- battle theme.
    {"Coward",             "Struggler",             "Combatant",                "Warrior",
     "Knight",             "Warmonger",             "Commander",                "Victor of a Thousand Battles"},

    // Makhleb -- chaos theme.
    {"Orderly",            "Spawn of Chaos",        "Disciple of Annihilation", "Fanfare of Bloodshed",
     "Fiendish",           "Demolition %s",         "Pandemonic",               "Champion of Chaos"},

    // Sif Muna -- scholarly theme.
    {"Ignorant",           "Disciple",              "Student",                  "Adept",
     "Scribe",             "Scholar",               "Sage",                     "Genius of the Arcane"},

    // Trog -- anger theme.
    {"Puny",               "Troglodyte",            "Angry Troglodyte",         "Frenzied",
     "%s of Prey",         "Rampant",               "Wild %s",                  "Bane of Scribes"},

    // Nemelex Xobeh -- alluding to Tarot and cards.
    {"Unlucky %s",         "Pannier",               "Jester",                   "Fortune-Teller",
     "Soothsayer",         "Magus",                 "Cardsharp",                "Hand of Fortune"},

    // Elyvilon.
    {"Sinner",             "Comforter",             "Caregiver",                "Practitioner",
     "Pacifier",           "Purifying %s",          "Faith Healer",             "Bringer of Life"},

    // Lugonu -- distortion theme.
    {"Pure",               "Abyss-Baptised",        "Unweaver",                 "Distorting %s",
     "Agent of Entropy",   "Schismatic",            "Envoy of Void",            "Corrupter of Planes"},

    // Beogh -- messiah theme.
    {"Apostate",           "Messenger",             "Proselytiser",             "Priest",
     "Missionary",         "Evangelist",            "Apostle",                  "Messiah"},

    // Jiyva -- slime and jelly theme.
    {"Scum",               "Jelly",                 "Squelcher",                "Dissolver",
     "Putrid Slime",       "Consuming %s",          "Archjelly",                "Royal Jelly"},

    // Fedhas Madash -- nature theme.
    {"Walking Fertiliser", "Green %s",              "Inciter",                  "Photosynthesist",
     "Cultivator",         "Green Death",           "Nimbus",                   "Force of Nature"},

    // Cheibriados -- slow theme
    {"Unwound %s",         "Timekeeper",            "Righteous Timekeeper",     "Chronographer",
     "Splendid Chronographer", "Chronicler",        "Eternal Chronicler",       "Ticktocktomancer"},

    // Ashenzari -- divination theme
    {"Star-crossed",       "Cursed",                "Initiated",                "Seer",
     "Soothsayer",         "Oracle",                "Illuminatus",              "Omniscient"},

    // Dithmenos -- darkness theme
    {"Illuminated",        "Gloomy",                "Aphotic",                  "Caliginous",
     "Darkened",           "Shadowed",              "Eclipsing",                "Eternal Night"},

    // Gozag -- entrepreneur theme
    {"Profligate",         "Pauper",                "Entrepreneur",             "Capitalist",
     "Rich",               "Opulent",               "Tycoon",                   "Plutocrat"},

    // Qazlal -- natural disaster theme
    {"Unspoiled",          "%s Mishap",             "Lightning Rod",            "%s Disaster",
     "Eye of the Storm",   "%s Catastrophe",        "%s Cataclysm",             "End of an Era"},
};

string god_title(god_type which_god, species_type which_species, int piety)
{
    string title;
    if (player_under_penance(which_god))
        title = divine_title[which_god][0];
    else if (which_god == GOD_GOZAG)
        title = divine_title[which_god][_gold_level()];
    else
        title = divine_title[which_god][_piety_level(piety)];

    title = replace_all(title, "%s",
                        which_god == GOD_QAZLAL
                        ? species_name(which_species, false, true)
                        : species_name(which_species, true, false));

    return title;
}

static string _describe_ash_skill_boost()
{
    if (!you.bondage_level)
    {
        return "Ashenzari won't support your skills until you bind yourself "
               "with cursed items.";
    }

    static const char* bondage_parts[NUM_ET] = { "Weapon hand", "Shield hand",
                                                 "Armour", "Jewellery" };
    static const char* bonus_level[3] = { "Low", "Medium", "High" };
    ostringstream desc;
    desc.setf(ios::left);
    desc << setw(18) << "Bound part";
    desc << setw(30) << "Boosted skills";
    desc << "Bonus\n";

    for (int i = ET_WEAPON; i < NUM_ET; i++)
    {
        if (you.bondage[i] <= 0 || i == ET_SHIELD && you.bondage[i] == 3)
            continue;

        desc << setw(18);
        if (i == ET_WEAPON && you.bondage[i] == 3)
            desc << "Hands";
        else
            desc << bondage_parts[i];

        string skills;
        map<skill_type, int8_t> boosted_skills = ash_get_boosted_skills(eq_type(i));
        const int8_t bonus = boosted_skills.begin()->second;
        map<skill_type, int8_t>::iterator it = boosted_skills.begin();

        // First, we keep only one magic school skill (conjuration).
        // No need to list all of them since we boost all or none.
        while (it != boosted_skills.end())
        {
            if (it->first > SK_CONJURATIONS && it->first <= SK_LAST_MAGIC)
            {
                boosted_skills.erase(it);
                it = boosted_skills.begin();
            }
            else
                ++it;
        }

        it = boosted_skills.begin();
        while (!boosted_skills.empty())
        {
            // For now, all the bonuses from the same bounded part have
            // the same level.
            ASSERT(bonus == it->second);
            if (it->first == SK_CONJURATIONS)
                skills += "Magic schools";
            else
                skills += skill_name(it->first);

            if (boosted_skills.size() > 2)
                skills += ", ";
            else if (boosted_skills.size() == 2)
                skills += " and ";

            boosted_skills.erase(it);
            ++it;
        }

        desc << setw(30) << skills;
        desc << bonus_level[bonus -1] << "\n";
    }

    return desc.str();
}

// from dgn-overview.cc
extern map<branch_type, set<level_id> > stair_level;

static string _describe_branch_bribability()
{
    string ret = "You can bribe the following branches:\n";
    vector<branch_type> targets;
    size_t width = 0;
    for (branch_iterator it; it; ++it)
    {
        const branch_type br = it->id;
        if (!gozag_branch_bribable(br))
            continue;

        // If you don't know the branch exists, don't list it;
        // this mainly plugs info leaks about Lair branch structure.
        if (!stair_level.count(br) && is_random_subbranch(br))
            continue;

        targets.push_back(br);
        width = max(width, strlen(it->longname));
    }

    for (unsigned int i = 0; i < targets.size(); i++)
    {
        string line(branches[targets[i]].longname);
        line += string(width + 1 - strwidth(line), ' ');
        // XXX: move this elsewhere?
        switch (targets[i])
        {
            case BRANCH_ORC:
                line += "(orcs)              ";
                break;
            case BRANCH_ELF:
                line += "(elves)             ";
                break;
            case BRANCH_SNAKE:
                line += "(nagas/salamanders) ";
                break;
            case BRANCH_SHOALS:
                line += "(merfolk)           ";
                break;
            case BRANCH_VAULTS:
                line += "(humans)            ";
                break;
            case BRANCH_ZOT:
                line += "(draconians)        ";
                break;
            case BRANCH_COCYTUS:
            case BRANCH_DIS:
            case BRANCH_GEHENNA:
            case BRANCH_TARTARUS:
                line += "(demons)            ";
                break;
            default:
                line += "(buggy)             ";
                break;
        }
        line += "Susceptibility: ";
        switch (gozag_branch_bribe_susceptibility(targets[i]))
        {
            case 0:
                line += "none       ";
                break;
            case 1:
                line += "very low   ";
                break;
            case 2:
                line += "low        ";
                break;
            case 3:
                line += "moderate   ";
                break;
            case 4:
                line += "high       ";
                break;
            case 5:
            default:
                line += "very high  ";
                break;
        }
        if (!branch_bribe[targets[i]])
            line += "not bribed";
        else
            line += make_stringf("$%d", branch_bribe[targets[i]]);

        ret += line + "\n";
    }

    return ret;
}

static void _detailed_god_description(god_type which_god)
{
    clrscr();

    const int width = min(80, get_number_of_cols());

    const string godname = uppercase_first(god_name(which_god, true));
    const int len = get_number_of_cols() - strwidth(godname);
    textcolor(god_colour(which_god));
    cprintf("%s%s\n", string(len / 2, ' ').c_str(), godname.c_str());
    textcolor(LIGHTGREY);
    cprintf("\n");

    string broken = get_god_powers(which_god);
    if (!broken.empty())
    {
        linebreak_string(broken, width);
        display_tagged_block(broken);
        cprintf("\n");
        cprintf("\n");
    }

    if (which_god != GOD_XOM)
    {
        broken = get_god_likes(which_god, true);
        linebreak_string(broken, width);
        display_tagged_block(broken);

        broken = get_god_dislikes(which_god, true);
        if (!broken.empty())
        {
            cprintf("\n");
            cprintf("\n");
            linebreak_string(broken, width);
            display_tagged_block(broken);
        }
        // Some special handling.
        broken = "";
        switch (which_god)
        {
        case GOD_ASHENZARI:
        case GOD_JIYVA:
        case GOD_TROG:
            broken = "Note that " + god_name(which_god) + " does not demand "
                     "training of the Invocations skill. All abilities are "
                     "purely based on piety.";

            if (which_god == GOD_ASHENZARI
                && which_god == you.religion
                && piety_rank() > 1)
            {
                broken += "\n\n";
                broken += _describe_ash_skill_boost();
            }
            break;

        case GOD_KIKUBAAQUDGHA:
            broken = "The power of Kikubaaqudgha's abilities is governed by "
                     "Necromancy skill instead of Invocations.";
            break;

        case GOD_ELYVILON:
            broken = "Healing hostile monsters may pacify them, turning them "
                     "neutral. Pacification works best on natural beasts, "
                     "worse on monsters of your species, worse on other "
                     "species, worst of all on demons and undead, and not at "
                     "all on sleeping or mindless monsters. If it succeeds, "
                     "you gain half of the monster's experience value and "
                     "possibly some piety. Pacified monsters try to leave the "
                     "level.";
            break;

        case GOD_NEMELEX_XOBEH:
            if (which_god == you.religion)
            {
                broken = "The power of Nemelex Xobeh's abilities and of the "
                         "cards' effects is governed by Evocations skill "
                         "instead of Invocations.";
            }
            break;

        case GOD_GOZAG:
            broken = _describe_branch_bribability();
            break;

        default:
            break;
        }

        if (!broken.empty())
        {
            cprintf("\n");
            cprintf("\n");
            linebreak_string(broken, width);
            display_tagged_block(broken);
        }
    }

    const int bottom_line = min(30, get_number_of_lines());

    cgotoxy(1, bottom_line);
    formatted_string::parse_string(
        "Press '<w>!</w>' or '<w>^</w>'"
#ifdef USE_TILE_LOCAL
        " or <w>Right-click</w>"
#endif
        " to toggle between the overview and the detailed "
        "description.").display();

    mouse_control mc(MOUSE_MODE_MORE);

    const int keyin = getchm();
    if (keyin == '!' || keyin == CK_MOUSE_CMD || keyin == '^')
        describe_god(which_god, true);
}

void describe_god(god_type which_god, bool give_title)
{
    int colour;              // Colour used for some messages.

    clrscr();

    if (give_title)
    {
        textcolor(WHITE);
        cprintf("                                  Religion\n");
        textcolor(LIGHTGREY);
    }

    if (which_god == GOD_NO_GOD) //mv: No god -> say it and go away.
    {
        cprintf("\nYou are not religious.");
        get_ch();
        return;
    }

    colour = god_colour(which_god);

    // Print long god's name.
    textcolor(colour);
    cprintf("%s", uppercase_first(god_name(which_god, true)).c_str());
    cprintf("\n\n");

    // Print god's description.
    textcolor(LIGHTGREY);

    string god_desc = getLongDescription(god_name(which_god));
    const int numcols = get_number_of_cols() - 1;
    cprintf("%s", get_linebreak_string(god_desc.c_str(), numcols).c_str());

    // Title only shown for our own god.
    if (you_worship(which_god))
    {
        // Print title based on piety.
        cprintf("\nTitle - ");
        textcolor(colour);

        string title = god_title(which_god, you.species, you.piety);
        cprintf("%s", title.c_str());
    }

    // mv: Now let's print favour as Brent suggested.
    // I know these messages aren't perfect so if you can think up
    // something better, do it.

    textcolor(LIGHTGREY);
    cprintf("\n\nFavour - ");
    textcolor(colour);

    //mv: Player is praying at altar without appropriate religion.
    // It means player isn't checking his own religion and so we only
    // display favour and go out.
    if (!you_worship(which_god))
    {
        textcolor(colour);
        int which_god_penance = you.penance[which_god];

        // Give more appropriate message for the good gods.
        if (which_god_penance > 0 && is_good_god(which_god))
        {
            if (is_good_god(you.religion))
                which_god_penance = 0;
            else if (!god_hates_your_god(which_god) && which_god_penance >= 5)
                which_god_penance = 2; // == "Come back to the one true church!"
        }

        cprintf((which_god == GOD_NEMELEX_XOBEH
                     && which_god_penance > 0 && which_god_penance <= 100)
                                             ? "%s doesn't play fair with you." :
                 (which_god_penance >= 50)   ? "%s's wrath is upon you!" :
                 (which_god_penance >= 20)   ? "%s is annoyed with you." :
                 (which_god_penance >=  5)   ? "%s well remembers your sins." :
                 (which_god_penance >   0)   ? "%s is ready to forgive your sins." :
                 (you.worshipped[which_god]) ? "%s is ambivalent towards you."
                                             : "%s is neutral towards you.",
                 uppercase_first(god_name(which_god)).c_str());
    }
    else
    {
        cprintf(_describe_favour(which_god).c_str());
        if (which_god == GOD_ASHENZARI)
            cprintf("\n%s", ash_describe_bondage(ETF_ALL, true).c_str());

        //mv: The following code shows abilities given by your god (if any).

        textcolor(LIGHTGREY);
        const char *header = "Granted powers:";
        const char *cost   = "(Cost)";
        cprintf("\n\n%s%*s%s\n", header,
                get_number_of_cols() - 1 - strwidth(header) - strwidth(cost),
                "", cost);
        textcolor(colour);

        // mv: Some gods can protect you from harm.
        // The god isn't really protecting the player - only sometimes saving
        // his life.
        bool have_any = false;

        if (god_can_protect_from_harm(which_god))
        {
            have_any = true;

            int prot_chance = 10 + you.piety/10; // chance * 100
            const char *when = "";

            switch (elyvilon_lifesaving())
            {
            case 1:
                when = ", especially when called upon";
                prot_chance += 100 - 3000/you.piety;
                break;
            case 2:
                when = ", and always does so when called upon";
                prot_chance = 100;
            }

            const char *how = (prot_chance >= 85) ? "carefully" :
                              (prot_chance >= 55) ? "often" :
                              (prot_chance >= 25) ? "sometimes"
                                                  : "occasionally";

            string buf = uppercase_first(god_name(which_god));
            buf += " ";
            buf += how;
            buf += " watches over you";
            buf += when;
            buf += ".";

            _print_final_god_abil_desc(which_god, buf, ABIL_NON_ABILITY);
        }

        if (which_god == GOD_ZIN)
        {
            have_any = true;
            const char *how =
                (you.piety >= piety_breakpoint(5)) ? "carefully" :
                (you.piety >= piety_breakpoint(3)) ? "often" :
                (you.piety >= piety_breakpoint(1)) ? "sometimes" :
                                                     "occasionally";

            cprintf("%s %s shields you from chaos.\n",
                    uppercase_first(god_name(which_god)).c_str(), how);
        }
        else if (which_god == GOD_SHINING_ONE)
        {
            if (you.piety >= piety_breakpoint(1))
            {
                have_any = true;
                const char *how =
                    (you.piety >= piety_breakpoint(5)) ? "carefully" :
                    (you.piety >= piety_breakpoint(3)) ? "often" :
                                                         "sometimes";

                cprintf("%s %s shields you from negative energy.\n",
                        uppercase_first(god_name(which_god)).c_str(), how);
            }
        }
        else if (which_god == GOD_TROG)
        {
            have_any = true;
            string buf = "You can call upon "
                         + god_name(which_god)
                         + " to burn spellbooks in your surroundings.";
            _print_final_god_abil_desc(which_god, buf,
                                       ABIL_TROG_BURN_SPELLBOOKS);
        }
        else if (which_god == GOD_JIYVA)
        {
            if (you.piety >= piety_breakpoint(2))
            {
                have_any = true;
                cprintf("%s shields you from corrosive effects.\n",
                        uppercase_first(god_name(which_god)).c_str());
            }
            if (you.piety >= piety_breakpoint(1))
            {
                have_any = true;
                string buf = "You gain nutrition";
                if (you.piety >= piety_breakpoint(4))
                    buf += ", power and health";
                else if (you.piety >= piety_breakpoint(3))
                    buf += " and power";
                buf += " when your fellow slimes consume items.\n";
                _print_final_god_abil_desc(which_god, buf,
                                           ABIL_NON_ABILITY);
            }
        }
        else if (which_god == GOD_FEDHAS)
        {
            have_any = true;
            _print_final_god_abil_desc(which_god,
                                       "You can pray to speed up decomposition.",
                                       ABIL_NON_ABILITY);
            _print_final_god_abil_desc(which_god,
                                       "You can walk through plants and "
                                       "fire through allied plants.",
                                       ABIL_NON_ABILITY);
        }
        else if (which_god == GOD_ASHENZARI)
        {
            have_any = true;
            _print_final_god_abil_desc(which_god,
                "You are provided with a bounty of information.",
                ABIL_NON_ABILITY);
            _print_final_god_abil_desc(which_god,
                "You can pray to corrupt scrolls of remove curse on your square.",
                                       ABIL_NON_ABILITY);
        }
        else if (which_god == GOD_CHEIBRIADOS)
        {
            if (you.piety >= piety_breakpoint(0))
            {
                have_any = true;
                _print_final_god_abil_desc(which_god,
                                           uppercase_first(god_name(which_god))
                                           + " slows and strengthens your metabolism.",
                                           ABIL_NON_ABILITY);
            }
        }
        else if (which_god == GOD_ELYVILON)
        {
            // Only print this here if we don't have lesser self-healing.
            if (you.piety < piety_breakpoint(0) || player_under_penance())
            {
                have_any = true;
                _print_final_god_abil_desc(which_god,
                                           "You can provide lesser healing for others.",
                                           ABIL_ELYVILON_LESSER_HEALING_OTHERS);
            }
        }
        else if (which_god == GOD_VEHUMET)
        {
            set<spell_type>::iterator it = you.vehumet_gifts.begin();
            if (it != you.vehumet_gifts.end())
            {
                have_any = true;

                string offer = spell_title(*it);
                // If we have multiple offers, just summarise.
                if (++it != you.vehumet_gifts.end())
                    offer = "some of Vehumet's most lethal spells";

                _print_final_god_abil_desc(which_god,
                                           "You can memorise " + offer + ".",
                                           ABIL_NON_ABILITY);
            }
        }
        else if (which_god == GOD_GOZAG)
        {
            have_any = true;
            _print_final_god_abil_desc(which_god,
                                       "You passively detect gold.",
                                       ABIL_NON_ABILITY);
            _print_final_god_abil_desc(which_god,
                                       uppercase_first(god_name(which_god))
                                       + " turns your defeated foes' bodies"
                                       + " to gold.",
                                       ABIL_NON_ABILITY);
            _print_final_god_abil_desc(which_god,
                                       "Your enemies may become distracted by "
                                       "glittering piles of gold.",
                                       ABIL_NON_ABILITY);
        }
        else if (which_god == GOD_QAZLAL)
        {
            have_any = true;
            _print_final_god_abil_desc(which_god,
                                       "You are immune to your own clouds.",
                                       ABIL_NON_ABILITY);
        }

        // mv: No abilities (except divine protection) under penance
        if (!player_under_penance())
        {
            vector<ability_type> abilities = get_god_abilities(true, true);
            for (int i = 0; i < MAX_GOD_ABILITIES; ++i)
                if ((you_worship(GOD_GOZAG)
                     && you.gold >= get_gold_cost(abilities[i])
                     || !you_worship(GOD_GOZAG)
                        && you.piety >= piety_breakpoint(i))
                    && _print_god_abil_desc(which_god, i))
                {
                    have_any = true;
                }
        }

        string extra = get_linebreak_string(_religion_help(which_god),
                                            numcols).c_str();
        if (!extra.empty())
        {
            have_any = true;
            _print_final_god_abil_desc(which_god, extra, ABIL_NON_ABILITY);
        }

        if (!have_any)
            cprintf("None.\n");
    }

    const int bottom_line = min(30, get_number_of_lines());

    cgotoxy(1, bottom_line);
    textcolor(LIGHTGREY);
    formatted_string::parse_string(
        "Press '<w>!</w>' or '<w>^</w>'"
#ifdef USE_TILE_LOCAL
        " or <w>Right-click</w>"
#endif
        " to toggle between the overview and the detailed "
        "description.").display();

    mouse_control mc(MOUSE_MODE_MORE);
    const int keyin = getchm();
    if (keyin == '!' || keyin == CK_MOUSE_CMD || keyin == '^')
        _detailed_god_description(which_god);
}

string get_skill_description(skill_type skill, bool need_title)
{
    string lookup = skill_name(skill);
    string result = "";

    if (need_title)
    {
        result = lookup;
        result += "\n\n";
    }

    result += getLongDescription(lookup);

    switch (skill)
    {
    case SK_INVOCATIONS:
        if (you.species == SP_DEMIGOD)
        {
            result += "\n";
            result += "How on earth did you manage to pick this up?";
        }
        else if (you_worship(GOD_TROG))
        {
            result += "\n";
            result += "Note that Trog doesn't use Invocations, due to its "
                      "close connection to magic.";
        }
        else if (you_worship(GOD_NEMELEX_XOBEH))
        {
            result += "\n";
            result += "Note that Nemelex uses Evocations rather than "
                      "Invocations.";
        }
        break;

    case SK_EVOCATIONS:
        if (you_worship(GOD_NEMELEX_XOBEH))
        {
            result += "\n";
            result += "This is the skill all of Nemelex's abilities rely on.";
        }
        break;

    case SK_SPELLCASTING:
        if (you_worship(GOD_TROG))
        {
            result += "\n";
            result += "Keep in mind, though, that Trog will greatly disapprove "
                      "of this.";
        }
        break;
    default:
        // No further information.
        break;
    }

    return result;
}

void describe_skill(skill_type skill)
{
    ostringstream data;

#ifdef USE_TILE_WEB
    tiles_crt_control show_as_menu(CRT_MENU, "describe_skill");
#endif

    data << get_skill_description(skill, true);

    print_description(data.str());
    getchm();
}

#ifdef USE_TILE
string get_command_description(const command_type cmd, bool terse)
{
    string lookup = command_to_name(cmd);

    if (!terse)
        lookup += " verbose";

    string result = getLongDescription(lookup);
    if (result.empty())
    {
        if (!terse)
        {
            // Try for the terse description.
            result = get_command_description(cmd, true);
            if (!result.empty())
                return result + ".";
        }
        return command_to_name(cmd);
    }

    return result.substr(0, result.length() - 1);
}
#endif

void alt_desc_proc::nextline()
{
    ostr << "\n";
}

void alt_desc_proc::print(const string &str)
{
    ostr << str;
}

int alt_desc_proc::count_newlines(const string &str)
{
    int count = 0;
    for (size_t i = 0; i < str.size(); i++)
    {
        if (str[i] == '\n')
            count++;
    }
    return count;
}

void alt_desc_proc::trim(string &str)
{
    int idx = str.size();
    while (--idx >= 0)
    {
        if (str[idx] != '\n')
            break;
    }
    str.resize(idx + 1);
}

bool alt_desc_proc::chop(string &str)
{
    int loc = -1;
    for (size_t i = 1; i < str.size(); i++)
        if (str[i] == '\n' && str[i-1] == '\n')
            loc = i;

    if (loc == -1)
        return false;

    str.resize(loc);
    return true;
}

void alt_desc_proc::get_string(string &str)
{
    str = replace_all(ostr.str(), "\n\n\n\n", "\n\n");
    str = replace_all(str, "\n\n\n", "\n\n");

    trim(str);
    while (count_newlines(str) > h)
    {
        if (!chop(str))
            break;
    }
}