File: apply.c

package info (click to toggle)
crossfire 1.11.0-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 24,456 kB
  • ctags: 7,800
  • sloc: ansic: 80,483; sh: 11,825; perl: 2,327; lex: 1,946; makefile: 1,149
file content (4084 lines) | stat: -rw-r--r-- 127,751 bytes parent folder | download
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
/*
 * static char *rcsid_apply_c =
 *   "$Id: apply.c 8300 2008-01-28 07:06:14Z mwedel $";
 */
/*
    CrossFire, A Multiplayer game for X-windows

    Copyright (C) 2006 Mark Wedel & Crossfire Development Team
    Copyright (C) 1992 Frank Tore Johansen

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    The authors can be reached via e-mail to crossfire-devel@real-time.com
*/

#include <global.h>
#include <living.h>
#include <spells.h>
#include <skills.h>
#include <tod.h>

#ifndef __CEXTRACT__
#include <sproto.h>
#endif

/* Want this regardless of rplay. */
#include <sounds.h>

/* need math lib for double-precision and pow() in dragon_eat_flesh() */
#include <math.h>

static int dragon_eat_flesh(object *op, object *meal);
static void apply_item_transformer(object *pl, object *transformer);
static void apply_lighter(object *who, object *lighter);
static void scroll_failure(object *op, int failure, int power);

/** Can transport hold object op?
 * This is a pretty trivial function,
 * but in the future, possible transport may have more restrictions
 * or weight reduction like containers
 */
int transport_can_hold(const object *transport, const object *op, int nrof)
{
    if ((op->weight *nrof + transport->carrying) > transport->weight_limit)
	return 0;
    else
	return 1;
}


/**
 * Player is trying to use a transport.  This returns same values as
 * manual_apply() does.  This function basically checks to see if
 * the player can use the transport, and if so, sets up the appropriate
 * pointers.
 */
int apply_transport(object *pl, object *transport, int aflag) {

    /* Only players can use transports right now */
    if (pl->type != PLAYER) return 0;

    /* If player is currently on a transport but not this transport, they need
     * to exit first.  Perhaps transport to transport transfers should be
     * allowed.
     */
    if (pl->contr->transport && pl->contr->transport != transport) {
	new_draw_info_format(NDI_UNIQUE, 0, pl,
		"You must exit %s before you can board %s.",
			     query_name(pl->contr->transport), 
			     query_name(transport));
	return 1;
    }

    /* player is currently on a transport.  This must mean he
     * wants to exit.
     */
    if (pl->contr->transport) {
	object *old_transport = pl->contr->transport, *inv;

	/* Should we print a message if the player only wants to
	 * apply?
	 */
	if (aflag & AP_APPLY) return 1;
	new_draw_info_format(NDI_UNIQUE, 0, pl,
		"You disembark from %s.",
			     query_name(old_transport));
	remove_ob(pl);
	pl->map = old_transport->map;
	pl->x = old_transport->x;
	pl->y = old_transport->y;
	if (pl->contr == old_transport->contr)
	    old_transport->contr = NULL;

	pl->contr->transport = NULL;
	insert_ob_in_map(pl, pl->map, pl, 0);
	sum_weight(old_transport);

	/* Possible for more than one player to be using a transport.
	 * if that is the case, we don't want to reset the face, as the
	 * transport is still occupied.
	 */
	for (inv=old_transport->inv; inv; inv=inv->below)
	    if (inv->type == PLAYER) break;
	if (!inv) {
	    old_transport->face = old_transport->arch->clone.face;
	    old_transport->animation_id = old_transport->arch->clone.animation_id;
	} else {
	    old_transport->contr = inv->contr;
	    new_draw_info_format(NDI_UNIQUE, 0, inv,
				 "%s has disembarked.  You are now the captain of %s",
				 pl->name, query_name(old_transport));
	}
	return 1;
    } 
    else {
	/* player is trying to board a transport */
	int pc=0, p_limit;
	object *inv, *old_transport;
	const char *kv;
	sint16 ox, oy;

	if (aflag & AP_UNAPPLY) return 1;
        
	/* Can this transport hold the weight of this player? */
	if (!transport_can_hold(transport, pl, 1)) {
	    new_draw_info_format(NDI_UNIQUE, 0, pl,
		"The %s is unable to hold your weight!",
			     query_name(transport));
	    return 1;
	}
        
        /* If the player is holding the transport, drop it. */
        if (transport->env == pl) {
            old_transport = transport;
            /* Don't drop transports in shops. */
            if (!is_in_shop(pl)) {
                transport = drop_object(pl, transport, 1);
            } else {
                new_draw_info_format(NDI_UNIQUE, 0, pl,
                    "You cannot drop the %s in a shop to use it.",
                    query_name(old_transport));
                return 1;
            }
            /* Did it fail to drop? */
            if(!transport) {
                new_draw_info_format(NDI_UNIQUE, 0, pl,
                    "You need to drop the %s to use it.",
                    query_name(old_transport));
                return 1;
            }
        }

	/* Does this transport have space for more players? */
	for (inv=transport->inv; inv; inv=inv->below) {
	    if (inv->type == PLAYER) pc++;
	}
	kv = get_ob_key_value(transport, "passenger_limit");
	if (!kv) p_limit=1;
	else p_limit = atoi(kv);
	if (pc >= p_limit) {
	    new_draw_info_format(NDI_UNIQUE, 0, pl,
		"The %s does not have space for any more people",
			     query_name(transport));
	    return 1;
	}

	/* Everything checks out OK - player can get on the transport */
	pl->contr->transport = transport;
	if (transport->contr) {
	    new_draw_info_format(NDI_UNIQUE, 0, pl, "The %s's captain is currently %s", query_name(transport), transport->contr->ob->name);
	}
	else {
	    new_draw_info_format(NDI_UNIQUE, 0, pl, "You're the %s's captain", query_name(transport));
	    transport->contr = pl->contr;
	}
	ox = pl->x;
	oy = pl->y;

	remove_ob(pl);
	insert_ob_in_ob(pl, transport);
	sum_weight(transport);
	pl->map = transport->map;
        if (ox != transport->x || oy != transport->y) {
            esrv_map_scroll(&pl->contr->socket, (ox - transport->x), (oy - transport->y));
	}
	pl->contr->socket.update_look=1;
	pl->contr->socket.look_position=0;
	pl->x = transport->x;
	pl->y = transport->y;

	/* Might need to update face, animation info */
	if (!pc) {
	    const char *str;

	    str = get_ob_key_value(transport, "face_full");
	    if (str)
		transport->face = &new_faces[find_face(str, 
					      transport->face->number)];
	    str = get_ob_key_value(transport, "anim_full");
	    if (str)
		transport->animation_id = find_animation(str);
	}

	/* Does speed of this object change based on weight? */
	kv = get_ob_key_value(transport, "weight_speed_ratio");
	if (kv) {
	    int wsr = atoi(kv);
	    float base_speed;

	    kv = get_ob_key_value(transport, "base_speed");
	    if (kv) base_speed = atof(kv);
	    else base_speed = transport->arch->clone.speed;

	    transport->speed = base_speed - (base_speed * transport->carrying * 
			     wsr) / (transport->weight_limit * 100);

	    /* Put some limits on min/max speeds */
	    if (transport->speed < 0.10) transport->speed = 0.10;
	    if (transport->speed > 1.0) transport->speed = 1.0;
	}
    } /* else if player is boarding the transport */

    return 1;
}

	

/**
 * Check if op should abort moving victim because of it's race or slaying.
 * Returns 1 if it should abort, returns 0 if it should continue.
 */
int should_director_abort(object *op, object *victim)
{
   int arch_flag, name_flag, race_flag;
   /* Get flags to determine what of arch, name, and race should be checked.
    * This is stored in subtype, and is a bitmask, the LSB is the arch flag,
    * the next is the name flag, and the last is the race flag. Also note,
    * if subtype is set to zero, that also goes to defaults of all affecting
    * it. Examples:
    * subtype 1: only arch
    * subtype 3: arch or name
    * subtype 5: arch or race
    * subtype 7: all three
    */
   if (op->subtype)
   {
     arch_flag = (op->subtype & 1);
     name_flag = (op->subtype & 2);
     race_flag = (op->subtype & 4);
   } else {
     arch_flag = 1;
     name_flag = 1;
     race_flag = 1;
   }
   /* If the director has race set, only affect objects with a arch, 
    * name or race that matches.
    */
   if ( (op->race) && 
     ((!(victim->arch && arch_flag && victim->arch->name) || strcmp(op->race, victim->arch->name))) &&
     ((!(victim->name && name_flag) || strcmp(op->race, victim->name))) &&
     ((!(victim->race && race_flag) || strcmp(op->race, victim->race))) ) {
     return 1;
   }
    /* If the director has slaying set, only affect objects where none
     * of arch, name, or race match.
     */
   if ( (op->slaying) && (
     ((victim->arch && arch_flag && victim->arch->name && !strcmp(op->slaying, victim->arch->name))) ||
     ((victim->name && name_flag && !strcmp(op->slaying, victim->name))) ||
     ((victim->race && race_flag && !strcmp(op->slaying, victim->race)))) ) {
     return 1;
   }
   return 0;
}

/**
 * This handles a player dropping money on an altar to identify stuff.
 * It'll identify marked item, if none all items up to dropped money.
 * Return value: 1 if money was destroyed, 0 if not.
 */
static int apply_id_altar (object *money, object *altar, object *pl)
{
    object *id, *marked;
    int success=0;

    if (pl == NULL || pl->type != PLAYER)
      return 0;

    /* Check for MONEY type is a special hack - it prevents 'nothing needs
     * identifying' from being printed out more than it needs to be.
     */
    if ( ! check_altar_sacrifice (altar, money) || money->type != MONEY)
      return 0;

    marked = find_marked_object (pl);
    /* if the player has a marked item, identify that if it needs to be
     * identified.  IF it doesn't, then go through the player inventory.
     */
    if (marked && ! QUERY_FLAG (marked, FLAG_IDENTIFIED)
        && need_identify (marked))
    {
	if (operate_altar (altar, &money)) {
	    identify (marked);
	    new_draw_info_format(NDI_UNIQUE, 0, pl,
		"You have %s.", long_desc(marked, pl));
            if (marked->msg) {
	        new_draw_info(NDI_UNIQUE, 0,pl, "The item has a story:");
	        new_draw_info(NDI_UNIQUE, 0,pl, marked->msg);
	    }
	    return money == NULL;
	} 
    }

    for (id=pl->inv; id; id=id->below) {
	if (!QUERY_FLAG(id, FLAG_IDENTIFIED) && !id->invisible && 
	    need_identify(id)) {
		if (operate_altar(altar,&money)) {
		    identify(id);
		    new_draw_info_format(NDI_UNIQUE, 0, pl,
			"You have %s.", long_desc(id, pl));
	            if (id->msg) {
		        new_draw_info(NDI_UNIQUE, 0,pl, "The item has a story:");
		        new_draw_info(NDI_UNIQUE, 0,pl, id->msg);
		    }
		    success=1;
		    /* If no more money, might as well quit now */
		    if (money == NULL || ! check_altar_sacrifice (altar,money))
			 break;
		}
		else {
		    LOG(llevError,"check_id_altar:  Couldn't do sacrifice when we should have been able to\n");
		    break;
		}
	}
    }
    if (!success) new_draw_info(NDI_UNIQUE, 0,pl,"You have nothing that needs identifying");
    return money == NULL;
}

/**
 * This checks whether the object has a "on_use_yield" field, and if so generated and drops
 * matching item.
 **/
static void handle_apply_yield(object* tmp)
{
    const char* yield;

    yield = get_ob_key_value(tmp,"on_use_yield");
    if (yield != NULL)
    {
        object* drop = create_archetype(yield);
        if (tmp->env)
        {
            drop = insert_ob_in_ob(drop,tmp->env);
        }
        else
        {
            drop->x = tmp->x;
            drop->y = tmp->y;
            insert_ob_in_map(drop,tmp->map,tmp,INS_BELOW_ORIGINATOR);
        }
    }
}

/**
 * Handles applying a potion.
 */
int apply_potion(object *op, object *tmp)
{
    int got_one=0,i;
    object *force;

    if(op->type==PLAYER) { 
      if (!QUERY_FLAG(tmp, FLAG_IDENTIFIED))
        identify(tmp);
    }

    handle_apply_yield(tmp);

    /* Potion of restoration - only for players */
    if (op->type==PLAYER&&(tmp->attacktype & AT_DEPLETE)) {
	object *depl;
	archetype *at;

	if (QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)) {
	    drain_stat(op);
	    fix_player(op);
	    decrease_ob(tmp);
	    return 1;
	}
	if ((at = find_archetype(ARCH_DEPLETION))==NULL) {
	    LOG(llevError,"Could not find archetype depletion\n");
	    return 0;
	}
	depl = present_arch_in_ob(at, op);
	if (depl!=NULL && (tmp->level != 0 && tmp->level >= op->level)) {
	    for (i = 0; i < NUM_STATS; i++)
		if (get_attr_value(&depl->stats, i)) {
		    new_draw_info(NDI_UNIQUE,0,op, restore_msg[i]);
		}
	    remove_ob(depl);
	    free_object(depl);
	    fix_player(op);
	}
	else
	    new_draw_info(NDI_UNIQUE,0,op, "You potion had no effect.");

	decrease_ob(tmp);
	return 1;
    }

    /* improvement potion - only for players */
    if(op->type==PLAYER&&tmp->attacktype&AT_GODPOWER) {

	for(i=1;i<MIN(11,op->level);i++) {
	    if (QUERY_FLAG(tmp,FLAG_CURSED) || QUERY_FLAG(tmp,FLAG_DAMNED)) {
		if (op->contr->levhp[i]!=1) {
		    op->contr->levhp[i]=1;
		    break;
		}
		if (op->contr->levsp[i]!=1) {
		    op->contr->levsp[i]=1;
		    break;
		}
		if (op->contr->levgrace[i]!=1) {
		    op->contr->levgrace[i]=1;
		    break;
		}
	    }
	    else {
		if(op->contr->levhp[i]<9) { 
		    op->contr->levhp[i]=9;
		    break;
		}
		if(op->contr->levsp[i]<6) { 
		    op->contr->levsp[i]=6;
		    break;
		}
		if(op->contr->levgrace[i]<3) {
		    op->contr->levgrace[i]=3;
		    break;
		}
	    }
	}
	/* Just makes checking easier */
	if (i<MIN(11, op->level)) got_one=1;
	if (!QUERY_FLAG(tmp,FLAG_CURSED) && !QUERY_FLAG(tmp,FLAG_DAMNED)) {
	    if (got_one) {
		fix_player(op);
		new_draw_info(NDI_UNIQUE,0,op,"The Gods smile upon you and remake you");
		new_draw_info(NDI_UNIQUE,0,op,"a little more in their image.");
        	new_draw_info(NDI_UNIQUE,0,op,"You feel a little more perfect.");
	    }
	    else
		new_draw_info(NDI_UNIQUE,0,op,"The potion had no effect - you are already perfect");
	}
	else {	/* cursed potion */
	    if (got_one) {
		fix_player(op);
		new_draw_info(NDI_UNIQUE,0,op,"The Gods are angry and punish you.");
	    }
	    else 
		new_draw_info(NDI_UNIQUE,0,op,"You are fortunate that you are so pathetic.");
	}
	decrease_ob(tmp);
	return 1;
    }


    /* A potion that casts a spell.  Healing, restore spellpoint (power potion)
     * and heroism all fit into this category.  Given the spell object code,
     * there is no limit to the number of spells that potions can be cast,
     * but direction is problematic to try and imbue fireball potions for example.
     */
    if (tmp->inv) {
	if(QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)) {
	    object *fball;

	    new_draw_info(NDI_UNIQUE,0,op, "Yech!  Your lungs are on fire!");
            /* Explodes a fireball centered at player */
            fball = create_archetype(EXPLODING_FIREBALL);
            fball->dam_modifier=random_roll(1, op->level, op, PREFER_LOW)/5+1;
            fball->stats.maxhp=random_roll(1, op->level, op, PREFER_LOW)/10+2;
            fball->x = op->x;
            fball->y = op->y;
            insert_ob_in_map(fball, op->map, NULL, 0);
	} else
	    cast_spell(op,tmp, op->facing, tmp->inv, NULL);

	decrease_ob(tmp);
	/* if youre dead, no point in doing this... */
	if(!QUERY_FLAG(op,FLAG_REMOVED)) fix_player(op);
	return 1;
    }

    /* Deal with protection potions */
    force=NULL;
    for (i=0; i<NROFATTACKS; i++) {
	if (tmp->resist[i]) {
	    if (!force) force=create_archetype(FORCE_NAME);
	    memcpy(force->resist, tmp->resist, sizeof(tmp->resist));
	    force->type=POTION_EFFECT;
	    break;  /* Only need to find one protection since we copy entire batch */
	}
    }
    /* This is a protection potion */
    if (force) {
	/* cursed items last longer */
	if(QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)) {
	  force->stats.food*=10;
	  for (i=0; i<NROFATTACKS; i++)
	    if (force->resist[i] > 0)
	      force->resist[i] = -force->resist[i];  /* prot => vuln */ 
	}
	force->speed_left= -1;
	force = insert_ob_in_ob(force,op);
	CLEAR_FLAG(tmp, FLAG_APPLIED);
	SET_FLAG(force,FLAG_APPLIED);
	change_abil(op,force);
	decrease_ob(tmp);
	return 1;
    }

    /* Only thing left are the stat potions */
    if(op->type==PLAYER) { /* only for players */
	if((QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)) && tmp->value!=0)
	    CLEAR_FLAG(tmp, FLAG_APPLIED);
	else
	    SET_FLAG(tmp, FLAG_APPLIED);
	if(!change_abil(op,tmp))
	    new_draw_info(NDI_UNIQUE,0,op,"Nothing happened.");
    }

    /* CLEAR_FLAG is so that if the character has other potions
     * that were grouped with the one consumed, his
     * stat will not be raised by them.  fix_player just clears
     * up all the stats.
     */
    CLEAR_FLAG(tmp, FLAG_APPLIED);
    fix_player(op);
    decrease_ob(tmp);
    return 1;
}

/****************************************************************************
 * Weapon improvement code follows
 ****************************************************************************/

/**
 * This returns the sum of nrof of item (arch name).
 */
static int check_item(object *op, const char *item)
{
  int count=0;


  if (item==NULL) return 0;
  op=op->below;
  while(op!=NULL) {
    if (strcmp(op->arch->name,item)==0){
	  if (!QUERY_FLAG (op, FLAG_CURSED) && !QUERY_FLAG (op, FLAG_DAMNED)
             /* Loophole bug? -FD- */ && !QUERY_FLAG (op, FLAG_UNPAID) )
	    {
	      if (op->nrof == 0)/* this is necessary for artifact sacrifices --FD-- */
		count++;
	      else
		count += op->nrof;
	    }
    }
    op=op->below;
  }
  return count;
}

/**
 * This removes 'nrof' of what item->slaying says to remove.
 * op is typically the player, which is only
 * really used to determine what space to look at.
 * Modified to only eat 'nrof' of objects.
 */
static void eat_item(object *op,const char *item, uint32 nrof)
{
    object *prev;

    prev = op;
    op=op->below;

    while(op!=NULL) {
	if (strcmp(op->arch->name,item)==0) {
	    if (op->nrof >= nrof) {
		decrease_ob_nr(op,nrof);
		return;
	    } else {
		decrease_ob_nr(op,op->nrof);
		nrof -= op->nrof;
	    }
	    op=prev;
	}
	prev = op;
	op=op->below;
    }
}

/**
 * This checks to see of the player (who) is sufficient level to use a weapon
 * with improvs improvements (typically last_eat).  We take an int here
 * instead of the object so that the improvement code can pass along the
 * increased value to see if the object is usuable.
 * we return 1 (true) if the player can use the weapon.
 */
static int check_weapon_power(const object *who, int improvs)
{
/* Old code is below (commented out).  Basically, since weapons are the only
 * object players really have any control to improve, it's a bit harsh to
 * require high level in some combat skill, so we just use overall level.
 */
#if 1
    if (((who->level/5)+5) >= improvs) return 1;
    else return 0;

#else
    int level=0;

    /* The skill system hands out wc and dam bonuses to fighters
     * more generously than the old system (see fix_player). Thus
     * we need to curtail the power of player enchanted weapons. 
     * I changed this to 1 improvement per "fighter" level/5 -b.t. 
     * Note:  Nothing should break by allowing this ratio to be different or
     * using normal level - it is just a matter of play balance.
     */
    if(who->type==PLAYER) { 
	object *wc_obj=NULL;

	for(wc_obj=who->inv;wc_obj;wc_obj=wc_obj->below)
	    if (wc_obj->type == SKILL && IS_COMBAT_SKILL(wc_obj->subtype) && wc_obj->level > level)
		level  = wc_obj->level;

	if (!level )  {
	    LOG(llevError,"Error: Player: %s lacks wc experience object\n",who->name);
	    level = who->level;
	}
    }
    else
	level=who->level;

    return (improvs <= ((level/5)+5));
#endif
}

/**
 * Returns how many items of type improver->slaying there are under op.
 * Will display a message if none found, and 1 if improver->slaying is NULL.
 */
static int check_sacrifice(object *op, const object *improver)
{
    int count=0;

    if (improver->slaying!=NULL) {
	count = check_item(op,improver->slaying);
	if (count<1) {
	    char buf[200];
	    sprintf(buf,"The gods want more %ss",improver->slaying);
	    new_draw_info(NDI_UNIQUE,0,op,buf);
	    return 0;
	}
    }
    else
	count=1;

    return count;
}

/**
 * Actually improves the weapon, and tells user.
 */
static int improve_weapon_stat(object *op,object *improver,object *weapon,
			signed char *stat,int sacrifice_count,const char *statname)
{

  new_draw_info(NDI_UNIQUE,0,op,"Your sacrifice was accepted.");
  *stat += sacrifice_count;
  weapon->last_eat++;
  new_draw_info_format(NDI_UNIQUE,0,op,
	"Weapon's bonus to %s improved by %d",statname,sacrifice_count);
  decrease_ob(improver);

  /* So it updates the players stats and the window */
  fix_player(op);
  return 1;
}

/* Types of improvements, hidden in the sp field. */
#define IMPROVE_PREPARE 1
#define IMPROVE_DAMAGE 2
#define IMPROVE_WEIGHT 3
#define IMPROVE_ENCHANT 4
#define IMPROVE_STR 5
#define IMPROVE_DEX 6
#define IMPROVE_CON 7
#define IMPROVE_WIS 8
#define IMPROVE_CHA 9
#define IMPROVE_INT 10
#define IMPROVE_POW 11


/**
 * This does the prepare weapon scroll.
 * Checks for sacrifice, and so on.
 */

static int prepare_weapon(object *op, object *improver, object *weapon)
{
    int sacrifice_count,i;
    char buf[MAX_BUF];

    if (weapon->level!=0) {
      new_draw_info(NDI_UNIQUE,0,op,"Weapon already prepared.");
      return 0;
    }
    for (i=0; i<NROFATTACKS; i++)
	if (weapon->resist[i]) break;

    /* If we break out, i will be less than nrofattacks, preventing
     * improvement of items that already have protections.
     */
    if (i<NROFATTACKS || 
	weapon->stats.hp ||	/* regeneration */
	(weapon->stats.sp && weapon->type == WEAPON) ||	/* sp regeneration */
	weapon->stats.exp ||	/* speed */
	weapon->stats.ac)	/* AC - only taifu's I think */
    {
      new_draw_info(NDI_UNIQUE,0,op,"Cannot prepare magic weapons.");
      return 0;
    }
    sacrifice_count=check_sacrifice(op,improver);
    if (sacrifice_count<=0)
      return 0;
    weapon->level=isqrt(sacrifice_count);
    new_draw_info(NDI_UNIQUE,0,op,"Your sacrifice was accepted.");
    eat_item(op, improver->slaying, sacrifice_count);

    new_draw_info_format(NDI_UNIQUE, 0, op,"Your *%s may be improved %d times.",
	    weapon->name,weapon->level);

    sprintf(buf,"%s's %s",op->name,weapon->name);
    FREE_AND_COPY(weapon->name, buf);
    FREE_AND_COPY(weapon->name_pl, buf);
    weapon->nrof=0;  /*  prevents preparing n weapons in the same
			 slot at once! */
    decrease_ob(improver);
    weapon->last_eat=0;
    return 1;
}


/**
 * Does the dirty job for 'improve weapon' scroll, prepare or add something.
 * This is the new improve weapon code.
 * Returns 0 if it was not able to work for some reason.
 *
 * Checks if weapon was prepared, if enough potions on the floor, ...
 *
 * We are hiding extra information about the weapon in the level and
 * last_eat numbers for an object.  Hopefully this won't break anything ?? 
 * level == max improve last_eat == current improve
 */
static int improve_weapon(object *op,object *improver,object *weapon)
{
  int sacrifice_count, sacrifice_needed=0;

  if(improver->stats.sp==IMPROVE_PREPARE) {
	return prepare_weapon(op, improver, weapon);
  }
  if (weapon->level==0) {
    new_draw_info(NDI_UNIQUE, 0,op,"This weapon has not been prepared.");
    return 0;
  }
  if (weapon->level==weapon->last_eat && weapon->item_power >=MAX_WEAPON_ITEM_POWER) {
    new_draw_info(NDI_UNIQUE, 0,op,"This weapon cannot be improved any more.");
    return 0;
  }
  if (QUERY_FLAG(weapon, FLAG_APPLIED) &&
      !check_weapon_power(op, weapon->last_eat+1)) {
	new_draw_info(NDI_UNIQUE, 0,op,"Improving the weapon will make it too");
	new_draw_info(NDI_UNIQUE, 0,op,"powerful for you to use.  Unready it if you");
	new_draw_info(NDI_UNIQUE, 0,op,"really want to improve it.");
	return 0;
  }
  /* This just increases damage by 5 points, no matter what.  No sacrifice
   * is needed.  Since stats.dam is now a 16 bit value and not 8 bit,
   * don't put any maximum value on damage - the limit is how much the
   * weapon  can be improved.
   */
  if (improver->stats.sp==IMPROVE_DAMAGE) {
	weapon->stats.dam += 5;
	weapon->weight += 5000;		/* 5 KG's */
	new_draw_info_format(NDI_UNIQUE, 0, op,
	    "Damage has been increased by 5 to %d", weapon->stats.dam);
	weapon->last_eat++;

	weapon->item_power++;
	decrease_ob(improver);
	return 1;
  }
  if (improver->stats.sp == IMPROVE_WEIGHT) {
	/* Reduce weight by 20% */
	weapon->weight = (weapon->weight * 8)/10;
	if (weapon->weight < 1) weapon->weight = 1;
	new_draw_info_format(NDI_UNIQUE, 0, op,
		"Weapon weight reduced to %6.1f kg",
		(float)weapon->weight/1000.0);
	weapon->last_eat++;
	weapon->item_power++;
	decrease_ob(improver);
	return 1;
  }
  if (improver->stats.sp == IMPROVE_ENCHANT) {
	weapon->magic++;
	weapon->last_eat++;
	new_draw_info_format(NDI_UNIQUE, 0, op
		,"Weapon magic increased to %d",weapon->magic);
	decrease_ob(improver);
	weapon->item_power++;
	return 1;
  }

  sacrifice_needed = weapon->stats.Str + weapon->stats.Int + weapon->stats.Dex+
	weapon->stats.Pow + weapon->stats.Con + weapon->stats.Cha +
	weapon->stats.Wis;

  if (sacrifice_needed<1)
	sacrifice_needed =1;
  sacrifice_needed *=2;

  sacrifice_count = check_sacrifice(op,improver);
  if (sacrifice_count < sacrifice_needed) {
	new_draw_info_format(NDI_UNIQUE, 0, op,
	    "You need at least %d %s", sacrifice_needed, improver->slaying);
	return 0;
  }
  eat_item(op,improver->slaying, sacrifice_needed);
  weapon->item_power++;

  switch (improver->stats.sp) {
   case IMPROVE_STR:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Str),
			       1, "strength");
   case IMPROVE_DEX:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Dex),
			       1, "dexterity");
   case IMPROVE_CON:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Con),
			       1, "constitution");
   case IMPROVE_WIS:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Wis),
			       1, "wisdom");
   case IMPROVE_CHA:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Cha),
			       1, "charisma");
   case IMPROVE_INT:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Int),
			       1, "intelligence");
   case IMPROVE_POW:
    return improve_weapon_stat(op,improver,weapon,
                               (signed char *) &(weapon->stats.Pow),
                               1, "power");
   default:
    new_draw_info(NDI_UNIQUE, 0,op,"Unknown improvement type.");
  }
  LOG(llevError,"improve_weapon: Got to end of function\n");
  return 0;
}

/**
 * Handles the applying of improve/prepare/enchant weapon scroll.
 * Checks a few things (not on a non-magic square, marked weapon, ...),
 * then calls improve_weapon to do the dirty work.
 */
static int check_improve_weapon (object *op, object *tmp)
{
    object *otmp;

    if(op->type!=PLAYER)
      return 0;
    if (!QUERY_FLAG(op, FLAG_WIZCAST) && (get_map_flags(op->map, NULL, op->x, op->y, NULL, NULL) & P_NO_MAGIC)) {
	new_draw_info(NDI_UNIQUE, 0,op,"Something blocks the magic of the scroll.");
	return 0;
    }
    otmp=find_marked_object(op);
    if(!otmp) {
      new_draw_info(NDI_UNIQUE, 0, op, "You need to mark a weapon object.");
      return 0;
    }
    if (otmp->type != WEAPON && otmp->type != BOW) {
      new_draw_info(NDI_UNIQUE, 0,op,"Marked item is not a weapon or bow");
      return 0;
    }
    new_draw_info(NDI_UNIQUE, 0,op,"Applied weapon builder.");
    improve_weapon(op,tmp,otmp);
    esrv_update_item(UPD_NAME | UPD_NROF | UPD_FLAGS, op, otmp);
    return 1;
}

/**
 * This code deals with the armour improvment scrolls.
 * Change limits on improvement - let players go up to
 * +5 no matter what level, but they are limited by item
 * power.
 * Try to use same improvement code as in the common/treasure.c
 * file, so that if you make a +2 full helm, it will be just
 * the same as one you find in a shop.
 *
 * deprecated comment:
 * this code is by b.t. (thomas@nomad.astro.psu.edu) -
 * only 'enchantment' of armour is possible - improving
 * the stats of a player w/ armour as well as a weapon
 * will probably horribly unbalance the game. Magic enchanting
 * depends on the level of the character - ie the plus
 * value (magic) of the armour can never be increased beyond
 * the level of the character / 10 -- rounding upish, nor may
 * the armour value of the piece of equipment exceed either 
 * the users level or 90)
 * Modified by MSW for partial resistance.  Only support
 * changing of physical area right now.
 */
static int improve_armour(object *op, object *improver, object *armour)
{
    object *tmp;
    int oldmagic = armour->magic;

    if (armour->magic >= settings.armor_max_enchant) {
        new_draw_info(NDI_UNIQUE, 0,op,"This armour can not be enchanted any further.");
	return 0;
    }
    /* Dealing with random artifact armor is a lot trickier (in terms of value, weight,
     * etc), so take the easy way out and don't worry about it.
     * Note - maybe add scrolls which make the random artifact versions (eg, armour
     * of gnarg and what not?)
     */
    if (armour->title) {
	new_draw_info(NDI_UNIQUE, 0, op, "This armour will not accept further enchantment.");
	return 0;
    }
	
    /* Split objects if needed.  Can't insert tmp until the
     * end of this function - otherwise it will just re-merge.
     */
    if(armour->nrof > 1)
	tmp = get_split_ob(armour,armour->nrof - 1);
    else
	tmp = NULL;

    armour->magic++;

    if ( !settings.armor_speed_linear )
        {
        int base = 100;
        int pow = 0;
        while ( pow < armour->magic )
            {
            base = base - ( base * settings.armor_speed_improvement ) / 100;
            pow++;
            }

        ARMOUR_SPEED( armour ) = ( ARMOUR_SPEED( &armour->arch->clone ) * base ) / 100;
        }
    else
        ARMOUR_SPEED( armour ) = ( ARMOUR_SPEED( &armour->arch->clone ) * ( 100 + armour->magic * settings.armor_speed_improvement ) )/100;

    if ( !settings.armor_weight_linear )
        {
        int base = 100;
        int pow = 0;
        while ( pow < armour->magic )
            {
            base = base - ( base * settings.armor_weight_reduction ) / 100;
            pow++;
            }

        armour->weight = ( armour->arch->clone.weight * base ) / 100;
        }
    else
        armour->weight = ( armour->arch->clone.weight * ( 100 - armour->magic * settings.armor_weight_reduction ) ) / 100;

    if ( armour->weight <= 0 )
        {
        LOG( llevInfo, "Warning: enchanted armours can have negative weight\n." );
        armour->weight = 1;
        }

    armour->item_power += (armour->magic-oldmagic)*3;
    if (armour->item_power < 0) armour->item_power = 0;

    if (op->type == PLAYER) {
        esrv_send_item(op, armour);
        if(QUERY_FLAG(armour, FLAG_APPLIED))
            fix_player(op);
    }
    decrease_ob(improver);
    if (tmp) {
	insert_ob_in_ob(tmp, op);
	esrv_send_item(op, tmp);
    }
    return 1;
}


/*
 * convert_item() returns 1 if anything was converted, 0 if the item was not
 * what the converter wants, -1 if the converter is broken.
 */
#define CONV_FROM(xyz)	xyz->slaying
#define CONV_TO(xyz)	xyz->other_arch
#define CONV_NR(xyz)	(unsigned char) xyz->stats.sp
#define CONV_NEED(xyz)	(unsigned long) xyz->stats.food

/* Takes one items and makes another.
 * converter is the object that is doing the conversion.
 * item is the object that triggered the converter - if it is not
 * what the converter wants, this will not do anything.
 */
static int convert_item(object *item, object *converter) {
    int nr=0;
    uint32 price_in;

    /* We make some assumptions - we assume if it takes money as it type,
     * it wants some amount.  We don't make change (ie, if something costs
     * 3 gp and player drops a platinum, tough luck)
     */
    if (!strcmp(CONV_FROM(converter),"money")) {
	int cost;

	if(item->type!=MONEY)
	    return 0;

	nr=(item->nrof*item->value)/CONV_NEED(converter);
	if (!nr) return 0;
	cost=nr*CONV_NEED(converter)/item->value;
	/* take into account rounding errors */
	if (nr*CONV_NEED(converter)%item->value) cost++;
	decrease_ob_nr(item, cost);

	price_in = cost*item->value;
    }
    else {
	if(item->type==PLAYER||CONV_FROM(converter)!=item->arch->name||
	   (CONV_NEED(converter)&&CONV_NEED(converter)>item->nrof))
	    return 0;

        /* silently burn unpaid items (only if they match what we want) */
        if(QUERY_FLAG(item, FLAG_UNPAID)) {
	    remove_ob(item);
	    free_object(item);
            item = create_archetype("burnout");
            if (item != NULL)
                insert_ob_in_map_at(item, converter->map, converter,
                                    0, converter->x, converter->y);
            return 1;
        }

	if(CONV_NEED(converter)) {
	    nr=item->nrof/CONV_NEED(converter);
	    decrease_ob_nr(item,nr*CONV_NEED(converter));
	    price_in = nr*CONV_NEED(converter)*item->value;
	} else {
	    price_in = item->value;
	    remove_ob(item);
	    free_object(item);
	}
    }

    if (converter->inv != NULL) {
	object *ob;
	int i;
	object *ob_to_copy;

	/* select random object from inventory to copy */
	ob_to_copy = converter->inv;
	for (ob = converter->inv->below, i = 1; ob != NULL; ob = ob->below, i++) {
	    if (rndm(0, i) == 0) {
		ob_to_copy = ob;
	    }
	}
	item = object_create_clone(ob_to_copy);
	CLEAR_FLAG(item, FLAG_IS_A_TEMPLATE);
	unflag_inv(item, FLAG_IS_A_TEMPLATE);
    } else {
	if (converter->other_arch == NULL) {
	    LOG(llevError,"move_creator: Converter doesn't have other arch set: %s (%s, %d, %d)\n", converter->name ? converter->name : "(null)", converter->map->path, converter->x, converter->y);
	    return -1;
	}

	item = object_create_arch(converter->other_arch);
	fix_generated_item(item, converter, 0, 0, GT_MINIMAL);
    }

    if(CONV_NR(converter))
	item->nrof=CONV_NR(converter);
    if(nr)
	item->nrof*=nr;
    if(is_in_shop(converter))
	SET_FLAG(item,FLAG_UNPAID);
    else if(price_in < item->nrof*item->value && settings.allow_broken_converters == FALSE) {
	LOG(llevError, "Broken converter %s at %s (%d, %d) in value %d, out value %d for %s\n",
	    converter->name, converter->map->path, converter->x, converter->y, price_in,
	    item->nrof*item->value, item->name);
	free_object(item);
	return -1;
    }
    insert_ob_in_map_at(item, converter->map, converter, 0, converter->x, converter->y);
    return 1;
}
  
/**
 * Handle apply on containers. 
 * By Eneq(@csd.uu.se).
 * Moved to own function and added many features [Tero.Haatanen@lut.fi]
 * added the alchemical cauldron to the code -b.t.
 */

static int apply_container (object *op, object *sack)
{
    char buf[MAX_BUF];
    object *tmp;

    if(op->type!=PLAYER)
	return 0; /* This might change */

    if (sack==NULL || sack->type != CONTAINER) {
	LOG (llevError, "apply_container: %s is not container!\n",sack?sack->name:"NULL");
	return 0;
    }
    op->contr->last_used = NULL;
    op->contr->last_used_id = 0;

    if (sack->env!=op) {
	if (sack->other_arch == NULL || sack->env != NULL) {
	    new_draw_info(NDI_UNIQUE, 0,op,"You must get it first.");
	    return 1;
	}
	/* It's on the ground, the problems begin */
	if (op->container != sack) {
	    /* it's closed OR some player has opened it */
	    if (QUERY_FLAG(sack, FLAG_APPLIED)) {
		for(tmp=get_map_ob(sack->map, sack->x, sack->y); 
		    tmp && tmp->container != sack; tmp=tmp->above);
		if (tmp) {
		    /* some other player have opened it */
		    new_draw_info_format(NDI_UNIQUE, 0, op,
			"%s is already occupied.", query_name(sack));
		    return 1;
		}
	    }
	}
	if ( QUERY_FLAG(sack, FLAG_APPLIED)) {
	    if (op->container == NULL) {
		tmp = arch_to_object (sack->other_arch);
		/* not good, but insert_ob_in_ob() is too smart */
		CLEAR_FLAG (tmp, FLAG_REMOVED);
		tmp->x= tmp->y = tmp->ox = tmp->oy = 0;
		tmp->map = NULL;
		tmp->env = sack;
		if (sack->inv)
		    sack->inv->above = tmp;
		tmp->below = sack->inv;
		tmp->above = NULL;
		sack->inv = tmp;
		sack->move_off = MOVE_ALL;	/* trying force closing it */
	    } else {
		sack->move_off = 0;
		tmp = sack->inv;
		if (tmp && tmp->type ==  CLOSE_CON) {
		    remove_ob(tmp);
		    free_object (tmp);
		}
	    }
	}
    }

    if (QUERY_FLAG (sack, FLAG_APPLIED)) {
	if (op->container) {
	    if (op->container != sack) {
		tmp = op->container;
		apply_container (op, tmp);
		sprintf (buf, "You close %s and open ", query_name(tmp));
		op->container = sack;
		strcat (buf, query_name(sack));
		strcat (buf, ".");
	    } else {
		CLEAR_FLAG (sack, FLAG_APPLIED);
		op->container = NULL;
		sprintf (buf, "You close %s.", query_name(sack));
	    }
	} else {
	    CLEAR_FLAG (sack, FLAG_APPLIED);
	    sprintf (buf, "You open %s.", query_name(sack));
	    SET_FLAG (sack, FLAG_APPLIED);
	    op->container = sack;
	}
    } else { /* not applied */
	if (sack->slaying) { /* it's locked */
	  tmp = find_key(op, op, sack);
	  if (tmp) {
	    sprintf (buf, "You unlock %s with %s.", query_name(sack), query_name(tmp));
	    SET_FLAG (sack, FLAG_APPLIED);
	    if (sack->env == NULL) { /* if it's on ground,open it also */
	      new_draw_info (NDI_UNIQUE,0,op, buf);
	      apply_container (op, sack);
	      return 1;
	    }
	  } else {
	    sprintf (buf, "You don't have the key to unlock %s.",
		     query_name(sack));
	  }
	} else {
	    sprintf (buf, "You readied %s.", query_name(sack));
	    SET_FLAG (sack, FLAG_APPLIED);
	    if (sack->env == NULL) {  /* if it's on ground,open it also */
		new_draw_info (NDI_UNIQUE, 0, op, buf);
		apply_container (op, sack);
		return 1;
	    }
	}
    }
    new_draw_info (NDI_UNIQUE, 0, op, buf);
    if (op->contr) op->contr->socket.update_look=1;
    return 1;
}

/**
 * Eneq(@csd.uu.se): Handle apply on containers.  This is for containers
 * the player has in their inventory, eg, sacks, luggages, etc.
 *
 * Moved to own function and added many features [Tero.Haatanen@lut.fi]
 * This version is for client/server mode.
 * op is the player, sack is the container the player is opening or closing.
 * return 1 if an object is apllied somehow or another, 0 if error/no apply
 *
 * Reminder - there are three states for any container - closed (non applied),
 * applied (not open, but objects that match get tossed into it), and open
 * (applied flag set, and op->container points to the open container)
 */

int esrv_apply_container (object *op, object *sack)
{
    object *tmp=op->container;
    if(op->type!=PLAYER)
	return 0; /* This might change */

    if (sack==NULL || sack->type != CONTAINER) {
        LOG (llevError,
             "esrv_apply_container: %s is not container!\n",sack?sack->name:"NULL");
	return 0;
    }

    /* If we have a currently open container, then it needs to be closed in all cases
     * if we are opening this one up.  We then fall through if appropriate for
     * openening the new container.
     */

    if (op->container && QUERY_FLAG(sack, FLAG_APPLIED)) {
	if (op->container->env != op) { /* if container is on the ground */
	    op->container->move_off = 0;
	}
        /* Lauwenmark: Handle for plugin close event */
        if (execute_event(tmp, EVENT_CLOSE,op,NULL,NULL,SCRIPT_FIX_ALL)!=0)
            return 1;

	new_draw_info_format(NDI_UNIQUE, 0, op, "You close %s.",
		      query_name(op->container));
	CLEAR_FLAG(op->container, FLAG_APPLIED);
	op->container=NULL;
	esrv_update_item (UPD_FLAGS, op, tmp);
	if (tmp == sack) return 1;
    }


    /* If the player is trying to open it (which he must be doing if we got here),
     * and it is locked, check to see if player has the equipment to open it.
     */

    if (sack->slaying) { /* it's locked */
      tmp=find_key(op, op, sack);
      if (tmp) {
	new_draw_info_format(NDI_UNIQUE, 0, op, "You unlock %s with %s.", query_name(sack), query_name(tmp));
      } else {
	new_draw_info_format(NDI_UNIQUE, 0, op,  "You don't have the key to unlock %s.",
			     query_name(sack));
	return 0;
      }
    }

    /* By the time we get here, we have made sure any other container has been closed and
     * if this is a locked container, the player they key to open it.
     */

    /* There are really two cases - the sack is either on the ground, or the sack is
     * part of the players inventory.  If on the ground, we assume that the player is
     * opening it, since if it was being closed, that would have been taken care of above.
     */


    if (sack->env != op) {
	/* Hypothetical case - the player is trying to open a sack that belong to someone
	 * else.  This normally should not happen, but a misbehaving client/player could
	 * try to do it, so lets handle it gracefully.
	 */
	if (sack->env) {
	    new_draw_info_format(NDI_UNIQUE, 0, op, "You can't open %s",
				 query_name(sack));
	    return 0;
	}
	/* set these so when the player walks off, we can unapply the sack */
	sack->move_off = MOVE_ALL;	/* trying force closing it */

	CLEAR_FLAG (sack, FLAG_APPLIED);
	new_draw_info_format(NDI_UNIQUE, 0, op, "You open %s.", query_name(sack));
	SET_FLAG (sack, FLAG_APPLIED);
	op->container = sack;
	esrv_update_item (UPD_FLAGS, op, sack);
	esrv_send_inventory (op, sack);

    } else { /* sack is in players inventory */
	if (QUERY_FLAG (sack, FLAG_APPLIED)) { /* readied sack becoming open */
	    CLEAR_FLAG (sack, FLAG_APPLIED);
	    new_draw_info_format(NDI_UNIQUE, 0, op, "You open %s.", query_name(sack));
	    SET_FLAG (sack, FLAG_APPLIED);
	    op->container = sack;
	    esrv_update_item (UPD_FLAGS, op, sack);
	    esrv_send_inventory (op, sack);
	}
	else {
	    CLEAR_FLAG (sack, FLAG_APPLIED);
	    new_draw_info_format(NDI_UNIQUE, 0, op, "You readied %s.", query_name(sack));
	    SET_FLAG (sack, FLAG_APPLIED);
	    esrv_update_item (UPD_FLAGS, op, sack);
	}
    }
    return 1;
}


/**
 * Handles dropping things on altar.
 * Returns true if sacrifice was accepted.
 */
static int apply_altar (object *altar, object *sacrifice, object *originator)
{
    /* Only players can make sacrifices on spell casting altars. */
    if (altar->inv && ( ! originator || originator->type != PLAYER))
	return 0;

    if (operate_altar (altar, &sacrifice)) {
	/* Simple check.  Unfortunately, it means you can't cast magic bullet
	 * with an altar.  We call it a Potion - altars are stationary - it
	 * is up to map designers to use them properly.
	 */
	if (altar->inv && altar->inv->type==SPELL) {
	    new_draw_info_format (NDI_BLACK, 0, originator, "The altar casts %s.",
				  altar->inv->name);
	    cast_spell (originator, altar, 0, altar->inv, NULL);
	    /* If it is connected, push the button.  Fixes some problems with
	     * old maps.
	     */
/*	    push_button (altar);*/
	} else {
	    altar->value = 1;  /* works only once */
	    push_button (altar);
	}
	return sacrifice == NULL;
    } else {
	return 0;
    }
}


/**
 * Handles 'movement' of shop mats.
 * Returns 1 if 'op' was destroyed, 0 if not.
 * Largely re-written to not use nearly as many gotos, plus
 * some of this code just looked plain out of date.
 * MSW 2001-08-29
 */
static int apply_shop_mat (object *shop_mat, object *op)
{
    int rv = 0;
    double opinion;
    object *tmp, *next;

    SET_FLAG (op,FLAG_NO_APPLY);   /* prevent loops */

    if (op->type != PLAYER) {
	/* Remove all the unpaid objects that may be carried here.
	 * This could be pets or monsters that are somehow in
	 * the shop.
	 */
	for (tmp=op->inv; tmp; tmp=next) {
	    next = tmp->below;
	    if (QUERY_FLAG(tmp, FLAG_UNPAID)) {
		int i = find_free_spot (tmp, op->map, op->x, op->y, 1, 9);

		remove_ob(tmp);
		if (i==-1) i=0;
		tmp->map = op->map;
		tmp->x = op->x + freearr_x[i];
		tmp->y = op->y + freearr_y[i];
		insert_ob_in_map(tmp, op->map, op, 0);
	    }
	}

	/* Don't teleport things like spell effects */
	if (QUERY_FLAG(op, FLAG_NO_PICK)) return 0;

	/* unpaid objects, or non living objects, can't transfer by
	 * shop mats.  Instead, put it on a nearby space.
	 */
	if (QUERY_FLAG(op, FLAG_UNPAID) || !QUERY_FLAG(op, FLAG_ALIVE)) {

	    /* Somebody dropped an unpaid item, just move to an adjacent place. */
	    int i = find_free_spot (op, op->map, op->x, op->y, 1, 9);
	    if (i != -1) {
		rv = transfer_ob (op, op->x + freearr_x[i], op->y + freearr_y[i], 0,
                       shop_mat);
	    }
	    return 0;
	}
	/* Removed code that checked for multipart objects - it appears that
	 * the teleport function should be able to handle this just fine.
	 */
	rv = teleport (shop_mat, SHOP_MAT, op);
    }
    /* immediate block below is only used for players */
    else if (can_pay(op)) {
	get_payment (op, op->inv);
	rv = teleport (shop_mat, SHOP_MAT, op);
	if (shop_mat->msg) {
	    new_draw_info (NDI_UNIQUE, 0, op, shop_mat->msg);
	}
	/* This check below is a bit simplistic - generally it should be correct,
	 * but there is never a guarantee that the bottom space on the map is
	 * actually the shop floor.
	 */
	else if ( !rv && !is_in_shop(op)) {
	    opinion = shopkeeper_approval(op->map, op);
	    if ( opinion > 0.9)
		new_draw_info (NDI_UNIQUE, 0, op, "The shopkeeper gives you a friendly wave.");
	    else if ( opinion > 0.75)
		new_draw_info (NDI_UNIQUE, 0, op, "The shopkeeper waves to you.");
	    else if ( opinion > 0.5)
		new_draw_info (NDI_UNIQUE, 0, op, "The shopkeeper ignores you.");
	    else
		new_draw_info (NDI_UNIQUE, 0, op, "The shopkeeper glares at you with contempt.");
	}
    }
    else {
	/* if we get here, a player tried to leave a shop but was not able
	 * to afford the items he has.  We try to move the player so that
	 * they are not on the mat anymore
	 */

	int i = find_free_spot (op, op->map, op->x, op->y, 1, 9);
	if(i == -1) {
	    LOG (llevError, "Internal shop-mat problem.\n");
	} else {
	    remove_ob (op);
	    op->x += freearr_x[i];
	    op->y += freearr_y[i];
	    rv = insert_ob_in_map (op, op->map, shop_mat,0) == NULL;
	    esrv_map_scroll(&op->contr->socket, freearr_x[i],freearr_y[i]);
	    op->contr->socket.update_look=1;
	    op->contr->socket.look_position=0;
	}
    }
    CLEAR_FLAG (op, FLAG_NO_APPLY);
    return rv;
}

/**
 * Handles applying a sign.
 */
static void apply_sign (object *op, object *sign, int autoapply)
{
    readable_message_type* msgType;
    char newbuf[HUGE_BUF];
    if (sign->msg == NULL) {
        new_draw_info (NDI_UNIQUE, 0, op, "Nothing is written on it.");
        return;
    }

    if (sign->stats.food) {
	if (sign->last_eat >= sign->stats.food) {
	    if (!sign->move_on)
		new_draw_info (NDI_UNIQUE, 0, op, "You cannot read it anymore.");
	    return;
	}

	if (!QUERY_FLAG(op, FLAG_WIZPASS))
	    sign->last_eat++;
    }

    /* Sign or magic mouth?  Do we need to see it, or does it talk to us?
     * No way to know for sure.  The presumption is basically that if
     * move_on is zero, it needs to be manually applied (doesn't talk
     * to us).  
     */
    if (QUERY_FLAG (op, FLAG_BLIND) && ! QUERY_FLAG (op, FLAG_WIZ) && !sign->move_on) {
        new_draw_info (NDI_UNIQUE, 0, op,
                       "You are unable to read while blind.");
        return;
    }
    msgType=get_readable_message_type(sign);
    snprintf(newbuf,sizeof(newbuf),"%hhu %s", autoapply?1:0,sign->msg);
    draw_ext_info(NDI_UNIQUE | NDI_NAVY, 0, op, msgType->message_type, msgType->message_subtype, newbuf, sign->msg);
}


/**
 * 'victim' moves onto 'trap'
 * 'victim' leaves 'trap'
 * effect is determined by move_on/move_off of trap and move_type of victime.
 *
 * originator: Player, monster or other object that caused 'victim' to move
 * onto 'trap'.  Will receive messages caused by this action.  May be NULL.
 * However, some types of traps require an originator to function.
 */
void move_apply (object *trap, object *victim, object *originator)
{
  static int recursion_depth = 0;

  /* If player is DM, only 2 cases to consider:
   * exits
   * opened containers on the ground, which should be closed.
   */
  if (QUERY_FLAG(victim, FLAG_WIZPASS) && trap->type != EXIT && trap->type != SIGN && trap->type != CONTAINER && !QUERY_FLAG(trap, FLAG_APPLIED))
    return;

  /* move_apply() is the most likely candidate for causing unwanted and
   * possibly unlimited recursion. 
   */
  /* The following was changed because it was causing perfeclty correct
   * maps to fail.  1)  it's not an error to recurse:
   * rune detonates, summoning monster.  monster lands on nearby rune.
   * nearby rune detonates.  This sort of recursion is expected and
   * proper.  This code was causing needless crashes. 
   */
    if (recursion_depth >= 500) {
	LOG (llevDebug, "WARNING: move_apply(): aborting recursion "
	     "[trap arch %s, name %s; victim arch %s, name %s]\n",
	     trap->arch->name, trap->name, victim->arch->name, victim->name);
	return;
    }
    recursion_depth++;
    if (trap->head) trap=trap->head;

    /* Lauwenmark: Handle for plugin trigger event */
    if (execute_event(trap, EVENT_TRIGGER,originator,victim,NULL,SCRIPT_FIX_ALL)!=0)
        goto leave;

    switch (trap->type) {
	case PLAYERMOVER:
	    if (trap->attacktype && (trap->level || victim->type!=PLAYER) && 
	      !should_director_abort(trap, victim)) {
		if (!trap->stats.maxsp) trap->stats.maxsp=2.0;

		/* Is this correct?  From the docs, it doesn't look like it
		 * should be divided by trap->speed
		 */
		victim->speed_left = -FABS(trap->stats.maxsp*victim->speed/trap->speed);

		/* Just put in some sanity check.  I think there is a bug in the
		 * above with some objects have zero speed, and thus the player
		 * getting permanently paralyzed.
		 */
		if (victim->speed_left<-50.0) victim->speed_left=-50.0;
		/*	LOG(llevDebug, "apply, playermove, player speed_left=%f\n", victim->speed_left);*/
	    }
	    goto leave;

	case SPINNER:
	    if(victim->direction) {
		victim->direction=absdir(victim->direction-trap->stats.sp);
		update_turn_face(victim);
	    }
	    goto leave;

	case DIRECTOR:
	    if(victim->direction && !should_director_abort(trap, victim)) {
		victim->direction=trap->stats.sp;
		update_turn_face(victim);
	    }
	    goto leave;

	case BUTTON:
	case PEDESTAL:
	    update_button(trap);
	    goto leave;

	case ALTAR:
	    /* sacrifice victim on trap */
	    apply_altar (trap, victim, originator);
	    goto leave;

	case THROWN_OBJ:
	    if (trap->inv == NULL)
		goto leave;
	    /* fallthrough */

	case ARROW:

	    /* bad bug: monster throw a object, make a step forwards, step on object ,
	     * trigger this here and get hit by own missile - and will be own enemy.
	     * Victim then is his own enemy and will start to kill herself (this is
	     * removed) but we have not synced victim and his missile. To avoid senseless
	     * action, we avoid hits here 
	     */
	    if ((QUERY_FLAG (victim, FLAG_ALIVE) && trap->speed) && trap->owner != victim)
		hit_with_arrow (trap, victim);
	    goto leave;

	case SPELL_EFFECT:
	    apply_spell_effect(trap, victim);
	    goto leave;

	case TRAPDOOR: 
	{
	    int max, sound_was_played;
	    object *ab, *ab_next;
	    if(!trap->value) {
		int tot;
		for(ab=trap->above,tot=0;ab!=NULL;ab=ab->above)
		    if ((ab->move_type && trap->move_on) || ab->move_type==0)
			tot += (ab->nrof ? ab->nrof : 1) * ab->weight + ab->carrying;

		if(!(trap->value=(tot>trap->weight)?1:0))
		    goto leave;

		SET_ANIMATION(trap, trap->value);
		update_object(trap,UP_OBJ_FACE);
	    }

	    for (ab = trap->above, max=100, sound_was_played = 0; --max && ab; ab=ab_next) {
		/* need to set this up, since if we do transfer the object,
		 * ab->above would be bogus 
		 */
		ab_next = ab->above;

		if ((ab->move_type && trap->move_on) || ab->move_type==0) {
		    if ( ! sound_was_played) {
			play_sound_map(trap->map, trap->x, trap->y, SOUND_FALL_HOLE);
			sound_was_played = 1;
		    }
		    new_draw_info(NDI_UNIQUE, 0,ab,"You fall into a trapdoor!");
		    transfer_ob(ab,(int)EXIT_X(trap),(int)EXIT_Y(trap),0,ab);
		}
	    }
	    goto leave;
	}


	case CONVERTER:
	    if (convert_item (victim, trap) < 0) {
		object *op;

		new_draw_info_format(NDI_UNIQUE, 0, originator, "The %s seems to be broken!", query_name(trap));

		op = create_archetype("burnout");
		if (op != NULL) {
		    op->x = trap->x;
		    op->y = trap->y;
		    insert_ob_in_map(op, trap->map, trap, 0);
		}
	    }
	    goto leave;

	case TRIGGER_BUTTON:
	case TRIGGER_PEDESTAL:
	case TRIGGER_ALTAR:
	    check_trigger (trap, victim);
	    goto leave;

	case DEEP_SWAMP:
	    walk_on_deep_swamp (trap, victim);
	    goto leave;

	case CHECK_INV:
	    check_inv (victim, trap);
	    goto leave;

	case HOLE:
	    /* Hole not open? */
	    if(trap->stats.wc > 0)
		goto leave;

	    /* Is this a multipart monster and not the head?  If so, return.
	     * Processing will happen if the head runs into the pit
	     */
	    if (victim->head)
		goto leave;

	    play_sound_map (victim->map, victim->x, victim->y, SOUND_FALL_HOLE);
	    new_draw_info (NDI_UNIQUE, 0, victim, "You fall through the hole!\n");
	    transfer_ob (victim, EXIT_X (trap), EXIT_Y (trap), 1, victim);
	    goto leave;

	case EXIT:
	    if (victim->type == PLAYER && EXIT_PATH (trap)) {
		/* Basically, don't show exits leading to random maps the
		 * players output.
		 */
		if (trap->msg && strncmp(EXIT_PATH(trap),"/!",2) && strncmp(EXIT_PATH(trap), "/random/", 8))
		    new_draw_info (NDI_NAVY, 0, victim, trap->msg);
		enter_exit (victim, trap);
	    }
	    goto leave;

	case ENCOUNTER:
	    /* may be some leftovers on this */
	    goto leave;

	case SHOP_MAT:
	    apply_shop_mat (trap, victim);
	    goto leave;

	/* Drop a certain amount of gold, and have one item identified */
	case IDENTIFY_ALTAR:
	    apply_id_altar (victim, trap, originator);
	    goto leave;

	case SIGN:
	    if (victim->type != PLAYER && trap->stats.food > 0)
		goto leave; /* monsters musn't apply magic_mouths with counters */

	    apply_sign (victim, trap, 1);
	    goto leave;

	case CONTAINER:
	    if (victim->type==PLAYER)
		(void) esrv_apply_container (victim, trap);
	    else
		(void) apply_container (victim, trap);
	    goto leave;

	case RUNE:
	case TRAP:
	    if (trap->level && QUERY_FLAG (victim, FLAG_ALIVE)) {
		spring_trap(trap, victim);
	    }
	    goto leave;

	default:
	    LOG (llevDebug, "name %s, arch %s, type %d with fly/walk on/off not "
		 "handled in move_apply()\n", trap->name, trap->arch->name,
		 trap->type);
	    goto leave;
    }

    leave:
	recursion_depth--;
}

/**
 * Handles reading a regular (ie not containing a spell) book.
 */
static void apply_book (object *op, object *tmp)
{
    int lev_diff;
    object *skill_ob;

    if(QUERY_FLAG(op, FLAG_BLIND)&&!QUERY_FLAG(op,FLAG_WIZ)) {
      new_draw_info(NDI_UNIQUE, 0,op,"You are unable to read while blind.");
      return;
    }
    if(tmp->msg==NULL) {
      new_draw_info_format(NDI_UNIQUE, 0, op,
	"You open the %s and find it empty.", tmp->name);
      return;
    }

    /* need a literacy skill to read stuff! */
    skill_ob = find_skill_by_name(op, tmp->skill);
    if ( ! skill_ob) {
	new_draw_info(NDI_UNIQUE, 0,op,
		      "You are unable to decipher the strange symbols.");
	return;
    }
    lev_diff = tmp->level - (skill_ob->level + 5);
    if ( ! QUERY_FLAG (op, FLAG_WIZ) && lev_diff > 0) {
	if (lev_diff < 2)
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is just barely beyond your comprehension.");
	else if (lev_diff < 3)
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is slightly beyond your comprehension.");
	else if (lev_diff < 5)
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is beyond your comprehension.");
	else if (lev_diff < 8)
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is quite a bit beyond your comprehension.");
	else if (lev_diff < 15)
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is way beyond your comprehension.");
	else
	    new_draw_info(NDI_UNIQUE, 0,op,"This book is totally beyond your comprehension.");
	return;
    }


    /* Lauwenmark: Handle for plugin book event */
    /*printf("Book apply: %s\n", tmp->name);
    execute_event(tmp, EVENT_APPLY,op,NULL,SCRIPT_FIX_ALL);
    printf("Book applied: %s\n", tmp->name);*/
    {
    	readable_message_type* msgType = get_readable_message_type(tmp);
    	draw_ext_info_format(NDI_UNIQUE | NDI_NAVY, 0, op,
                msgType->message_type, msgType->message_subtype,
                "%s\n%s",
                "You open the %s and start reading.\n%s", 
                long_desc(tmp,op), tmp->msg);
    }

    /* gain xp from reading */
    if(!QUERY_FLAG(tmp,FLAG_NO_SKILL_IDENT)) { /* only if not read before */
	int exp_gain=calc_skill_exp(op,tmp, skill_ob);
      if(!QUERY_FLAG(tmp,FLAG_IDENTIFIED)) {
        /*exp_gain *= 2; because they just identified it too */
        SET_FLAG(tmp,FLAG_IDENTIFIED);
        /* If in a container, update how it looks */
        if(tmp->env) esrv_update_item(UPD_FLAGS|UPD_NAME, op,tmp);
        else op->contr->socket.update_look=1;
      }
      change_exp(op,exp_gain, skill_ob->skill, 0);
      SET_FLAG(tmp,FLAG_NO_SKILL_IDENT); /* so no more xp gained from this book */
    }
}

/**
 * Handles the applying of a skill scroll, calling learn_skill straight.
 * op is the person learning the skill, tmp is the skill scroll object
 */
static void apply_skillscroll (object *op, object *tmp)
{
    switch ((int) learn_skill (op, tmp)) {
	case 0:
	    new_draw_info(NDI_UNIQUE, 0,op,"You already possess the knowledge ");
	    new_draw_info_format(NDI_UNIQUE, 0,op,"held within the %s.\n",query_name(tmp));
	    return;

	case 1:
	    new_draw_info_format(NDI_UNIQUE, 0,op,"You succeed in learning %s",
			 tmp->skill);
	    new_draw_info_format(NDI_UNIQUE, 0, op,
			 "Type 'bind ready_skill %s",tmp->skill);
	    new_draw_info(NDI_UNIQUE, 0,op,"to store the skill in a key.");
	    decrease_ob(tmp);
	    return;

	default:
	    new_draw_info_format(NDI_UNIQUE,0,op,
		    "You fail to learn the knowledge of the %s.\n",query_name(tmp));
	    decrease_ob(tmp);
	    return;
    }
}

/**
 * Actually makes op learn spell.
 * Informs player of what happens.
 */
void do_learn_spell (object *op, object *spell, int special_prayer)
{
    object *tmp;

    if (op->type != PLAYER) {
        LOG (llevError, "BUG: do_learn_spell(): not a player\n");
        return;
    }

    /* Upgrade special prayers to normal prayers */
    if ((tmp=check_spell_known (op, spell->name))!=NULL) {
        if (special_prayer && !QUERY_FLAG(tmp, FLAG_STARTEQUIP)) {
            LOG (llevError, "BUG: do_learn_spell(): spell already known, but not marked as startequip\n");
            return;
        }
        return;
    }

    play_sound_player_only (op->contr, SOUND_LEARN_SPELL, 0, 0);
    tmp = get_object();
    copy_object(spell, tmp);
    insert_ob_in_ob(tmp, op);
    
    if (special_prayer) {
	SET_FLAG(tmp, FLAG_STARTEQUIP);
    }

    new_draw_info_format (NDI_UNIQUE, 0, op, 
            "Type 'bind cast %s", spell->name);
    new_draw_info (NDI_UNIQUE, 0, op, "to store the spell in a key.");
    esrv_add_spells(op->contr, tmp);
}

/**
 * Erases spell from player's inventory.
 */
void do_forget_spell (object *op, const char *spell)
{
    object *spob;

    if (op->type != PLAYER) {
        LOG (llevError, "BUG: do_forget_spell(): not a player\n");
        return;
    }
    if ( (spob=check_spell_known (op, spell)) == NULL) {
        LOG (llevError, "BUG: do_forget_spell(): spell not known\n");
        return;
    }
    
    new_draw_info_format (NDI_UNIQUE|NDI_NAVY, 0, op,
			  "You lose knowledge of %s.", spell);
    player_unready_range_ob(op->contr, spob);
    esrv_remove_spell(op->contr, spob);
    remove_ob(spob);
    free_object(spob);
}

/**
 * Handles player applying a spellbook.
 * Checks whether player has knowledge of required skill, doesn't already know the spell,
 * stuff like that. Random learning failure too.
 */
static void apply_spellbook (object *op, object *tmp)
{
    object *skop, *spell, *spell_skill;

    if(QUERY_FLAG(op, FLAG_BLIND)&&!QUERY_FLAG(op,FLAG_WIZ)) {
	new_draw_info(NDI_UNIQUE, 0,op,"You are unable to read while blind.");
	return;
    }

    skop = find_skill_by_name(op, tmp->skill);

    /* need a literacy skill to learn spells. Also, having a literacy level
     * lower than the spell will make learning the spell more difficult */
    if ( !skop) {
	new_draw_info(NDI_UNIQUE, 0,op,"You can't read! Your attempt fails.");
	return;
    }

    spell = tmp->inv;
    if (!spell) {
	LOG(llevError,"apply_spellbook: Book %s has no spell in it!\n", tmp->name);
	new_draw_info(NDI_UNIQUE, 0,op,"The spellbook symbols make no sense.");
    return;
    }
    if (spell->level > (skop->level+10)) {
	new_draw_info(NDI_UNIQUE, 0,op,"You are unable to decipher the strange symbols.");
	return;
    } 

    new_draw_info_format(NDI_UNIQUE, 0, op, 
	"The spellbook contains the %s level spell %s.",
            get_levelnumber(spell->level), spell->name);

    if (!QUERY_FLAG(tmp, FLAG_IDENTIFIED)) {
	identify(tmp);
	if (tmp->env)
	    esrv_update_item(UPD_FLAGS|UPD_NAME,op,tmp);
	else
	    op->contr->socket.update_look=1;
    }

    /* I removed the check for special_prayer_mark here - it didn't make
     * a lot of sense - special prayers are not found in spellbooks, and
     * if the player doesn't know the spell, doesn't make a lot of sense that
     * they would have a special prayer mark.
     */
    if (check_spell_known (op, spell->name)) {
	new_draw_info(NDI_UNIQUE, 0,op,"You already know that spell.\n");
	return;
    }

    if (spell->skill) {
	spell_skill = find_skill_by_name(op, spell->skill);
	if (!spell_skill) {
	    new_draw_info_format(NDI_UNIQUE, 0, op, 
				 "You lack the skill %s to use this spell",
				 spell->skill);
	    return;
	}
	if (spell_skill->level < spell->level) {
	    new_draw_info_format(NDI_UNIQUE, 0, op, 
				 "You need to be level %d in %s to learn this spell.",
				 spell->level, spell->skill);
	    return;
	}
    }

    /* Logic as follows
     *
     *  1- MU spells use Int to learn, Cleric spells use Wisdom
     *
     *  2- The learner's skill level in literacy adjusts the chance to learn
     *     a spell.
     *
     *  3 -Automatically fail to learn if you read while confused
     * 
     * Overall, chances are the same but a player will find having a high 
     * literacy rate very useful!  -b.t. 
     */ 
    if(QUERY_FLAG(op,FLAG_CONFUSED)) { 
	new_draw_info(NDI_UNIQUE,0,op,"In your confused state you flub the wording of the text!");
	scroll_failure(op, 0 - random_roll(0, spell->level, op, PREFER_LOW), MAX(spell->stats.sp, spell->stats.grace));
    } else if(QUERY_FLAG(tmp,FLAG_STARTEQUIP) || 
	(random_roll(0, 100, op, PREFER_LOW)-(5*skop->level)) <
	      learn_spell[spell->stats.grace ? op->stats.Wis : op->stats.Int]) {

	new_draw_info(NDI_UNIQUE, 0,op,"You succeed in learning the spell!");
	do_learn_spell (op, spell, 0);

	/* xp gain to literacy for spell learning */
	if ( ! QUERY_FLAG (tmp, FLAG_STARTEQUIP))
	    change_exp(op,calc_skill_exp(op,tmp,skop), skop->skill, 0);
    } else {
	play_sound_player_only(op->contr, SOUND_FUMBLE_SPELL,0,0);
	new_draw_info(NDI_UNIQUE, 0,op,"You fail to learn the spell.\n");
    }
    decrease_ob(tmp);
}

/**
 * Handles applying a spell scroll.
 */
void apply_scroll (object *op, object *tmp, int dir)
{
    object *skop;

    if(QUERY_FLAG(op, FLAG_BLIND)&&!QUERY_FLAG(op,FLAG_WIZ)) {
	new_draw_info(NDI_UNIQUE, 0,op, "You are unable to read while blind.");
	return;
    }

    if (!tmp->inv || tmp->inv->type != SPELL) {
        new_draw_info (NDI_UNIQUE, 0, op,
                       "The scroll just doesn't make sense!");
        return;
    }

    if(op->type==PLAYER) {
	/* players need a literacy skill to read stuff! */
	int exp_gain=0;

	/* hard code literacy - tmp->skill points to where the exp
	 * should go for anything killed by the spell.
	 */
	skop = find_skill_by_name(op, skill_names[SK_LITERACY]);

        if ( ! skop) {
	    new_draw_info(NDI_UNIQUE, 0,op,
		  "You are unable to decipher the strange symbols.");
	    return;
        } 

	if((exp_gain = calc_skill_exp(op,tmp, skop)))
	    change_exp(op,exp_gain, skop->skill, 0);
    }

    if (!QUERY_FLAG(tmp, FLAG_IDENTIFIED)) 
	identify(tmp);

    new_draw_info_format(NDI_BLACK, 0, op,
		     "The scroll of %s turns to dust.", tmp->inv->name);


    cast_spell(op,tmp,dir,tmp->inv, NULL);
    decrease_ob(tmp);
}

/**
 * Applies a treasure object - by default, chest.  op
 * is the person doing the applying, tmp is the treasure
 * chest.
 */
static void apply_treasure (object *op, object *tmp)
{
    object *treas;
    tag_t tmp_tag = tmp->count, op_tag = op->count;


    /* Nice side effect of new treasure creation method is that the treasure
     * for the chest is done when the chest is created, and put into the chest
     * inventory.  So that when the chest burns up, the items still exist.  Also
     * prevents people fromt moving chests to more difficult maps to get better
     * treasure
     */

    treas = tmp->inv;
    if(treas==NULL) {
	new_draw_info(NDI_UNIQUE, 0,op,"The chest was empty.");
	decrease_ob(tmp);
	return;
    }
    while (tmp->inv) {
	treas = tmp->inv;

	remove_ob(treas);
	new_draw_info_format(NDI_UNIQUE, 0, op, "You find %s in the chest.",
			   query_name(treas));

	treas->x=op->x;
	treas->y=op->y;
	treas = insert_ob_in_map (treas, op->map, op,INS_BELOW_ORIGINATOR);

	if (treas && (treas->type == RUNE || treas->type == TRAP) && treas->level
	    && QUERY_FLAG (op, FLAG_ALIVE))
	    spring_trap (treas, op);
	/* If either player or container was destroyed, no need to do
	 * further processing.  I think this should be enclused with
	 * spring trap above, as I don't think there is otherwise
	 * any way for the treasure chest or player to get killed
	 */
	if (was_destroyed (op, op_tag) || was_destroyed (tmp, tmp_tag))
	    break;
    }

    if ( ! was_destroyed (tmp, tmp_tag) && tmp->inv == NULL)
      decrease_ob (tmp);

}

/**
 * op eats food.
 * If player, takes care of messages and dragon special food.
 */
static void apply_food (object *op, object *tmp)
{
    int capacity_remaining;

    if (QUERY_FLAG(tmp, FLAG_NO_PICK)) {
        draw_ext_info_format(NDI_UNIQUE, 0, op, MSG_TYPE_APPLY, MSG_TYPE_APPLY_FAILURE, "You can't %s that!", NULL, tmp->type == DRINK ? "drink" : "eat");
        return;
    }

    if(op->type!=PLAYER)
      op->stats.hp=op->stats.maxhp;
    else {
      /* check if this is a dragon (player), eating some flesh */
      if (tmp->type==FLESH && is_dragon_pl(op) && dragon_eat_flesh(op, tmp))
	;
      else {
	/* usual case - no dragon meal: */
	if(op->stats.food+tmp->stats.food>999) {
	  if(tmp->type==FOOD || tmp->type==FLESH)
	    new_draw_info(NDI_UNIQUE, 0,op,"You feel full, but what a waste of food!");
	  else
	    new_draw_info(NDI_UNIQUE, 0,op,"Most of the drink goes down your face not your throat!");
	}
      
	if(!QUERY_FLAG(tmp, FLAG_CURSED)) {
	  char buf[MAX_BUF];
	  
	  if (!is_dragon_pl(op)) {
	    /* eating message for normal players*/
	    if(tmp->type==DRINK)
	      sprintf(buf,"Ahhh...that %s tasted good.",tmp->name);
	    else 
	      sprintf(buf,"The %s tasted %s",tmp->name,
		      tmp->type==FLESH?"terrible!":"good.");
	  }
	  else {
	    /* eating message for dragon players*/
	    sprintf(buf,"The %s tasted terrible!",tmp->name);
	  }

	  new_draw_info(NDI_UNIQUE, 0,op,buf);
	  capacity_remaining = 999 - op->stats.food;
	  op->stats.food+=tmp->stats.food;
	  if(capacity_remaining < tmp->stats.food)
	    op->stats.hp += capacity_remaining / 50;
	  else
	    op->stats.hp+=tmp->stats.food/50;
	  if(op->stats.hp>op->stats.maxhp)
	    op->stats.hp=op->stats.maxhp;
	  if (op->stats.food > 999)
	    op->stats.food = 999;
	}
      
	/* special food hack -b.t. */
	if(tmp->title || QUERY_FLAG(tmp,FLAG_CURSED))
	  eat_special_food(op,tmp);
      }
    }
    handle_apply_yield(tmp);
    decrease_ob(tmp);
}

/**
 * A dragon is eating some flesh. If the flesh contains resistances,
 * there is a chance for the dragon's skin to get improved.
 *
 * attributes:
 *     object *op        the object (dragon player) eating the flesh
 *     object *meal      the flesh item, getting chewed in dragon's mouth
 * return:
 *     int               1 if eating successful, 0 if it doesn't work
 */
static int dragon_eat_flesh(object *op, object *meal) {
  object *skin = NULL;    /* pointer to dragon skin force*/
  object *abil = NULL;    /* pointer to dragon ability force*/
  object *tmp = NULL;     /* tmp. object */
  
  char buf[MAX_BUF];            /* tmp. string buffer */
  double chance;                /* improvement-chance of one resistance type */
  double totalchance=1;         /* total chance of gaining one resistance */
  double bonus=0;               /* level bonus (improvement is easier at lowlevel) */
  double mbonus=0;              /* monster bonus */
  int atnr_winner[NROFATTACKS]; /* winning candidates for resistance improvement */
  int winners=0;                /* number of winners */
  int i;                        /* index */
  
  /* let's make sure and doublecheck the parameters */
  if (meal->type!=FLESH || !is_dragon_pl(op))
    return 0;
  
  /* now grab the 'dragon_skin'- and 'dragon_ability'-forces
     from the player's inventory */
  for (tmp=op->inv; tmp!=NULL; tmp=tmp->below) {
    if (tmp->type == FORCE) {
      if (strcmp(tmp->arch->name, "dragon_skin_force")==0)
	skin = tmp;
      else if (strcmp(tmp->arch->name, "dragon_ability_force")==0)
	abil = tmp;
    }
  }
  
  /* if either skin or ability are missing, this is an old player
     which is not to be considered a dragon -> bail out */
  if (skin == NULL || abil == NULL) return 0;
  
  /* now start by filling stomache and health, according to food-value */
  if((999 - op->stats.food) < meal->stats.food)
    op->stats.hp += (999 - op->stats.food) / 50;
  else
    op->stats.hp += meal->stats.food/50;
  if(op->stats.hp>op->stats.maxhp)
    op->stats.hp=op->stats.maxhp;
  
  op->stats.food = MIN(999, op->stats.food + meal->stats.food);
  
  /*LOG(llevDebug, "-> player: %d, flesh: %d\n", op->level, meal->level);*/
  
  /* on to the interesting part: chances for adding resistance */
  for (i=0; i<NROFATTACKS; i++) {
    if (meal->resist[i] > 0 && atnr_is_dragon_enabled(i)) {
      /* got positive resistance, now calculate improvement chance (0-100) */
      
      /* this bonus makes resistance increase easier at lower levels */
      bonus = (settings.max_level - op->level) * 30. / ((double)settings.max_level);
      if (i == abil->stats.exp)
	bonus += 5;  /* additional bonus for resistance of ability-focus */
      
      /* monster bonus increases with level, because high-level
         flesh is too rare */
      mbonus = op->level * 20. / ((double)settings.max_level);
      
      chance = (((double)MIN(op->level+bonus, meal->level+bonus+mbonus))*100. /
		((double)settings.max_level)) - skin->resist[i];
      
      if (chance >= 0.)
	chance += 1.;
      else
	chance = (chance < -12) ? 0. : 1./pow(2., -chance);
      
      /* chance is proportional to amount of resistance (max. 50) */
      chance *= ((double)(MIN(meal->resist[i], 50)))/50.;
      
      /* doubled chance for resistance of ability-focus */
      if (i == abil->stats.exp)
	chance = MIN(100., chance*2.);
      
      /* now make the throw and save all winners (Don't insert luck bonus here!) */
      if (RANDOM()%10000 < (int)(chance*100)) {
	atnr_winner[winners] = i;
	winners++;
      }
      
      if (chance >= 0.01 ) totalchance *= 1 - chance/100;
      
      /*LOG(llevDebug, "   %s: bonus %.1f, chance %.1f\n", attacks[i], bonus, chance);*/
    }
  }
  
  /* inverse totalchance as until now we have the failure-chance   */
  totalchance = 100 - totalchance*100;
  /* print message according to totalchance */
  if (totalchance > 50.)
    sprintf(buf, "Hmm! The %s tasted delicious!", meal->name);
  else if (totalchance > 10.)
    sprintf(buf, "The %s tasted very good.", meal->name);
  else if (totalchance > 1.)
    sprintf(buf, "The %s tasted good.", meal->name);
  else if (totalchance > 0.1)
    sprintf(buf, "The %s tasted bland.", meal->name);
  else if (totalchance >= 0.01)
    sprintf(buf, "The %s had a boring taste.", meal->name);
  else if (meal->last_eat > 0 && atnr_is_dragon_enabled(meal->last_eat))
    sprintf(buf, "The %s tasted strange.", meal->name);
  else
    sprintf(buf, "The %s had no taste.", meal->name);
  new_draw_info(NDI_UNIQUE, 0, op, buf);
  
  /* now choose a winner if we have any */
  i = -1;
  if (winners>0)
    i = atnr_winner[RANDOM()%winners];
  
  if (i >= 0 && i < NROFATTACKS && skin->resist[i] < 95) {
    /* resistance increased! */
    skin->resist[i]++;
    fix_player(op);
    
    sprintf(buf, "Your skin is now more resistant to %s!", change_resist_msg[i]);
    new_draw_info(NDI_UNIQUE|NDI_RED, 0, op, buf);
  }
  
  /* if this flesh contains a new ability focus, we mark it
     into the ability_force and it will take effect on next level */
  if (meal->last_eat > 0 && atnr_is_dragon_enabled(meal->last_eat)
      && meal->last_eat != abil->last_eat) {
    abil->last_eat = meal->last_eat; /* write: last_eat <new attnr focus> */
    
    if (meal->last_eat != abil->stats.exp) {
      sprintf(buf, "Your metabolism prepares to focus on %s!",
	      change_resist_msg[meal->last_eat]);
      new_draw_info(NDI_UNIQUE, 0, op, buf);
      sprintf(buf, "The change will happen at level %d", abil->level + 1);
      new_draw_info(NDI_UNIQUE, 0, op, buf);
    }
    else {
      sprintf(buf, "Your metabolism will continue to focus on %s.",
	      change_resist_msg[meal->last_eat]);
      new_draw_info(NDI_UNIQUE, 0, op, buf);
      abil->last_eat = 0;
    }
  }
  return 1;
}

static void apply_savebed (object *pl)
{
    /* Lauwenmark : Here we handle the LOGOUT global event */
    execute_global_event(EVENT_LOGOUT, pl->contr, pl->contr->socket.host);

    /* Need to call terminate_all_pets()  before we remove the player ob */
    terminate_all_pets(pl);
    remove_ob(pl);
    pl->direction=0;

    new_draw_info_format(NDI_UNIQUE | NDI_ALL | NDI_DK_ORANGE, 5, pl,
	"%s leaves the game.",pl->name);
    
    /* update respawn position */
    strcpy(pl->contr->savebed_map, pl->map->path);
    pl->contr->bed_x = pl->x;
    pl->contr->bed_y = pl->y;
    
    strcpy(pl->contr->killer,"left");
    check_score(pl,0); /* Always check score */
    (void)save_player(pl,0);
#if MAP_MAXTIMEOUT 
    MAP_SWAP_TIME(pl->map) = MAP_TIMEOUT(pl->map);
#endif
    play_again(pl);
    pl->speed = 0;
    update_ob_speed(pl);
}

/**
 * Handles applying an improve armor scroll.
 * Does some sanity checks, then calls improve_armour.
 */
static void apply_armour_improver (object *op, object *tmp)
{
    object *armor;

    if (!QUERY_FLAG(op, FLAG_WIZCAST) && (get_map_flags(op->map, NULL, op->x, op->y, NULL, NULL) & P_NO_MAGIC)) {
        new_draw_info(NDI_UNIQUE, 0,op,"Something blocks the magic of the scroll.");
        return;
    }
    armor=find_marked_object(op);
    if ( ! armor) {
      new_draw_info(NDI_UNIQUE, 0, op, "You need to mark an armor object.");
      return;
    }
    if (armor->type != ARMOUR
	&& armor->type != CLOAK
	&& armor->type != BOOTS && armor->type != GLOVES
	&& armor->type != BRACERS && armor->type != SHIELD
	&& armor->type != HELMET)
    {
        new_draw_info(NDI_UNIQUE, 0,op,"Your marked item is not armour!\n");
        return;
    }

    new_draw_info(NDI_UNIQUE, 0,op,"Applying armour enchantment.");
    improve_armour(op,tmp,armor);
}


extern void apply_poison (object *op, object *tmp)
{
    if (op->type == PLAYER) {
      play_sound_player_only(op->contr, SOUND_DRINK_POISON,0,0);
      new_draw_info(NDI_UNIQUE, 0,op,"Yech!  That tasted poisonous!");
      strcpy(op->contr->killer,"poisonous booze");
    }
    if (tmp->stats.hp > 0) {
      LOG(llevDebug,"Trying to poison player/monster for %d hp\n",
          tmp->stats.hp);
      hit_player(op, tmp->stats.hp, tmp, AT_POISON, 1);
    }
    op->stats.food-=op->stats.food/4;
    handle_apply_yield(tmp);
    decrease_ob(tmp);
}

/**
 * This fonction return true if the exit is not a 2 ways one or it is 2 ways, valid exit.
 * A valid 2 way exit means:
 *   -You can come back (there is another exit at the other side)
 *   -You are
 *          the owner of the exit
 *          or in the same party as the owner
 *
 * Note: a owner in a 2 way exit is saved as the owner's name
 * in the field exit->name cause the field exit->owner doesn't
 * survive in the swapping (in fact the whole exit doesn't survive).
 */
static int is_legal_2ways_exit (object* op, object *exit)
   {
   object * tmp;
   object * exit_owner;
   player * pp;
   mapstruct * exitmap;
   if (exit->stats.exp!=1) return 1; /*This is not a 2 way, so it is legal*/
   if (!has_been_loaded(EXIT_PATH(exit)) && exit->race) return 0; /* This is a reset town portal */
    /* To know if an exit has a correspondant, we look at
     * all the exits in destination and try to find one with same path as
     * the current exit's position */
   if (!strncmp(EXIT_PATH (exit), settings.localdir, strlen(settings.localdir)))
      exitmap = ready_map_name(EXIT_PATH (exit), MAP_PLAYER_UNIQUE);
   else exitmap = ready_map_name(EXIT_PATH (exit), 0);
   if (exitmap)
     {
     tmp=get_map_ob (exitmap,EXIT_X(exit),EXIT_Y(exit));
     if (!tmp) return 0;
     for ( (tmp=get_map_ob(exitmap,EXIT_X(exit),EXIT_Y(exit)));tmp;tmp=tmp->above)
       {
       if (tmp->type!=EXIT) continue;  /*Not an exit*/
       if (!EXIT_PATH (tmp)) continue; /*Not a valid exit*/
       if ( (EXIT_X(tmp)!=exit->x) || (EXIT_Y(tmp)!=exit->y)) continue; /*Not in the same place*/
       if (strcmp(exit->map->path,EXIT_PATH(tmp))!=0) continue; /*Not in the same map*/

       /* From here we have found the exit is valid. However we do
        * here the check of the exit owner. It is important for the
        * town portals to prevent strangers from visiting your appartments
        */
       if (!exit->race) return 1;  /*No owner, free for all!*/
       exit_owner=NULL;
       for (pp=first_player;pp;pp=pp->next)
         {
         if (!pp->ob) continue;
         if (pp->ob->name!=exit->race) continue;
         exit_owner= pp->ob; /*We found a player which correspond to the player name*/
         break;
         }
       if (!exit_owner) return 0;    /* No more owner*/
       if (exit_owner->contr==op->contr) return 1;  /*It is your exit*/
       if  ( exit_owner &&                          /*There is a owner*/
            (op->contr) &&                          /*A player tries to pass */
            ( (exit_owner->contr->party==NULL) || /*No pass if controller has no party*/
              (exit_owner->contr->party!=op->contr->party)) ) /* Or not the same as op*/
           return 0;
       return 1;
       }
     }
   return 0;
   }


/**
 * Main apply handler.
 *
 * Checks for unpaid items before applying.
 *
 * Return value:
 *   0: player or monster can't apply objects of that type
 *   1: has been applied, or there was an error applying the object
 *   2: objects of that type can't be applied if not in inventory
 *
 * op is the object that is causing object to be applied, tmp is the object
 * being applied.
 *
 * aflag is special (always apply/unapply) flags.  Nothing is done with
 * them in this function - they are passed to apply_special
 */

int manual_apply (object *op, object *tmp, int aflag)
{
    if (tmp->head) tmp=tmp->head;

    if (QUERY_FLAG (tmp, FLAG_UNPAID) && ! QUERY_FLAG (tmp, FLAG_APPLIED)) {
	if (op->type == PLAYER) {
	    new_draw_info (NDI_UNIQUE, 0, op, "You should pay for it first.");
	    return 1;
	} else {
	    return 0;   /* monsters just skip unpaid items */
	}
    }


    /* Lauwenmark: Handle for plugin apply event */
    if (execute_event(tmp, EVENT_APPLY,op,NULL,NULL,SCRIPT_FIX_ALL)!=0)
        return 1;

    switch (tmp->type) {

	case TRANSPORT:
	    return apply_transport(op, tmp, aflag);

	case CF_HANDLE:
	    new_draw_info(NDI_UNIQUE, 0,op,"You turn the handle.");
	    play_sound_map(op->map, op->x, op->y, SOUND_TURN_HANDLE);
	    tmp->value=tmp->value?0:1;
	    SET_ANIMATION(tmp, tmp->value);
	    update_object(tmp,UP_OBJ_FACE);
	    push_button(tmp);
	    return 1;

	case TRIGGER:
	    if (check_trigger (tmp, op)) {
		new_draw_info (NDI_UNIQUE, 0, op, "You turn the handle.");
		play_sound_map (tmp->map, tmp->x, tmp->y, SOUND_TURN_HANDLE);
	    } else {
		new_draw_info (NDI_UNIQUE, 0, op, "The handle doesn't move.");
	    }
	    return 1;

	case EXIT:
	    if (op->type != PLAYER)
		return 0;
	    if( ! EXIT_PATH (tmp) || !is_legal_2ways_exit(op,tmp)) {
		new_draw_info_format(NDI_UNIQUE, 0, op, "The %s is closed.",
                                 query_name(tmp));
	    } else {
		/* Don't display messages for random maps. */
		if (tmp->msg && strncmp(EXIT_PATH(tmp),"/!",2) &&
		    strncmp(EXIT_PATH(tmp), "/random/", 8))
		new_draw_info (NDI_NAVY, 0, op, tmp->msg);
		enter_exit(op,tmp);
	    }
	    return 1;

	case SIGN:
	    apply_sign (op, tmp, 0);
	    return 1;

	case BOOK:
	    if (op->type == PLAYER) {
		apply_book (op, tmp);
		return 1;
	    } else {
		return 0;
	    }

	case SKILLSCROLL:
	    if (op->type == PLAYER) {
		apply_skillscroll (op, tmp);
		return 1;
	    }
	    return 0;

	case SPELLBOOK:
	    if (op->type == PLAYER) {
		apply_spellbook (op, tmp);
		return 1;
	    }
	    return 0;

	case SCROLL:
	    apply_scroll (op, tmp, 0);
	    return 1;

	case POTION:
	    (void) apply_potion(op, tmp);
	    return 1;

	/* Eneq(@csd.uu.se): Handle apply on containers. */
	case CLOSE_CON:
	    if (op->type==PLAYER)
		(void) esrv_apply_container (op, tmp->env);
	    else
		(void) apply_container (op, tmp->env);
	    return 1;

	case CONTAINER:
	    if (op->type==PLAYER)
		(void) esrv_apply_container (op, tmp);
	    else
		(void) apply_container (op, tmp);
	    return 1;

	case TREASURE:
	    if (op->type == PLAYER) {
		apply_treasure (op, tmp);
		return 1;
	    } else {
		return 0;
	    }

	case WEAPON:
	case ARMOUR:
	case BOOTS:
	case GLOVES:
	case AMULET:
	case GIRDLE:
	case BRACERS:
	case SHIELD:
	case HELMET:
	case RING:
	case CLOAK:
	case WAND:
	case ROD:
	case HORN:
	case SKILL:
	case BOW:
	case LAMP:
	case BUILDER:
	case SKILL_TOOL:
	    if (tmp->env != op)
		return 2;   /* not in inventory */
	    (void) apply_special (op, tmp, aflag);
	    return 1;

	case DRINK:
	case FOOD:
	case FLESH:
	    apply_food (op, tmp);
	    return 1;

	case POISON:
	    apply_poison (op, tmp);
	    return 1;

	case SAVEBED:
	    if (op->type == PLAYER) {
		apply_savebed (op);
		return 1;
	    } else {
		return 0;
	    }

	case ARMOUR_IMPROVER:
	    if (op->type == PLAYER) {
		apply_armour_improver (op, tmp);
		return 1;
	    } else {
		return 0;
	    }

	case WEAPON_IMPROVER:
	    (void) check_improve_weapon(op, tmp);
	    return 1;

	case CLOCK:
	    if (op->type == PLAYER) {
		char buf[MAX_BUF];
		timeofday_t tod;

		get_tod(&tod);
		sprintf(buf, "It is %d minute%s past %d o'clock %s",
			tod.minute+1, ((tod.minute+1 < 2) ? "" : "s"),
			((tod.hour % 14 == 0) ? 14 : ((tod.hour)%14)),
			((tod.hour >= 14) ? "pm" : "am"));
		play_sound_player_only(op->contr, SOUND_CLOCK,0,0);
		new_draw_info(NDI_UNIQUE, 0,op, buf);
		return 1;
	    } else {
		return 0;
	    }

	case MENU: 
	    if (op->type == PLAYER) {
		shop_listing (op);
		return 1;
	    } else {
		return 0;
	    }

	case POWER_CRYSTAL:
	    apply_power_crystal(op,tmp);  /*  see egoitem.c */
	    return 1;

	case LIGHTER:		/* for lighting torches/lanterns/etc */ 
	    if (op->type == PLAYER) {
		apply_lighter(op,tmp);
		return 1;
	    } else {
		return 0;
	    }

	case ITEM_TRANSFORMER:
	    apply_item_transformer( op, tmp );
	    return 1;

	default:
	    return 0;
    }
}


/** quiet suppresses the "don't know how to apply" and "you must get it first"
 * messages as needed by player_apply_below().  But there can still be
 * "but you are floating high above the ground" messages.
 *
 * Same return value as apply() function.
 */
int player_apply (object *pl, object *op, int aflag, int quiet)
{
    int tmp;

    if (op->env == NULL && (pl->move_type & MOVE_FLYING)) {
        /* player is flying and applying object not in inventory */
        if ( ! QUERY_FLAG (pl, FLAG_WIZ) && !(op->move_type & MOVE_FLYING)) {
            new_draw_info (NDI_UNIQUE, 0, pl, "But you are floating high "
                           "above the ground!");
            return 0;
	}
    }

    /* Check for PLAYER to avoid a DM to disappear in a puff of smoke if
     * applied.
     */
    if (op->type != PLAYER && QUERY_FLAG (op, FLAG_WAS_WIZ) && ! QUERY_FLAG (pl, FLAG_WAS_WIZ))
    {
        play_sound_map (pl->map, pl->x, pl->y, SOUND_OB_EVAPORATE);
        new_draw_info (NDI_UNIQUE, 0, pl, "The object disappears in a puff "
                       "of smoke!");
        new_draw_info (NDI_UNIQUE, 0, pl, "It must have been an illusion.");
        remove_ob (op);
        free_object (op);
        return 1;
    }

    pl->contr->last_used = op;
    pl->contr->last_used_id = op->count;

    tmp = manual_apply (pl, op, aflag);
    if ( ! quiet) {
        if (tmp == 0)
            new_draw_info_format (NDI_UNIQUE, 0, pl,
                                  "I don't know how to apply the %s.",
                                  query_name (op));
        else if (tmp == 2)
            new_draw_info_format (NDI_UNIQUE, 0, pl,
                                  "You must get it first!\n");
    }
    return tmp;
}

/**
 * player_apply_below attempts to apply the object 'below' the player.
 * If the player has an open container, we use that for below, otherwise
 * we use the ground.
 */

void player_apply_below (object *pl)
{
    object *tmp, *next;
    int floors;

    if (pl->contr->transport && pl->contr->transport->type == TRANSPORT) {
	apply_transport(pl, pl->contr->transport, 0);
	return;
    }

    /* If using a container, set the starting item to be the top
     * item in the container.  Otherwise, use the map.
     */
    tmp = (pl->container != NULL) ? pl->container->inv : pl->below;

    /* This is perhaps more complicated.  However, I want to make sure that
     * we don't use a corrupt pointer for the next object, so we get the
     * next object in the stack before applying.  This is can only be a
     * problem if player_apply() has a bug in that it uses the object but does
     * not return a proper value.
     */
    for (floors = 0; tmp!=NULL; tmp=next) {
	next = tmp->below;
        if (QUERY_FLAG (tmp, FLAG_IS_FLOOR))
            floors++;
        else if (floors > 0)
            return;   /* process only floor objects after first floor object */

	/* If it is visible, player can apply it.  If it is applied by
	 * person moving on it, also activate.  Added code to make it
	 * so that at least one of players movement types be that which
	 * the item needs.
	 */
	if ( ! tmp->invisible || (tmp->move_on & pl->move_type)) {
            if (player_apply (pl, tmp, 0, 1) == 1)
                return;
        }
        if (floors >= 2)
            return;   /* process at most two floor objects */
    }
}

/**
 * Unapplies specified item.
 * No check done on cursed/damned.
 * Break this out of apply_special - this is just done
 * to keep the size of apply_special to a more managable size.
 */
static int unapply_special (object *who, object *op, int aflags)
{
    object *tmp2;

    CLEAR_FLAG(op, FLAG_APPLIED);
    switch(op->type) {
	case WEAPON:
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You unwield %s.",query_name(op));

	    (void) change_abil (who,op);
	    if(QUERY_FLAG(who,FLAG_READY_WEAPON))
		CLEAR_FLAG(who,FLAG_READY_WEAPON);
	    who->current_weapon = NULL;
	    clear_skill(who);
	    break;

	case SKILL:         /* allows objects to impart skills */
	case SKILL_TOOL:
	    if (op != who->chosen_skill) {
		LOG (llevError, "BUG: apply_special(): applied skill is not a chosen skill\n");
	    }
	    if (who->type==PLAYER) {
		if (who->contr->shoottype == range_skill)
		    who->contr->shoottype = range_none;
		if ( ! op->invisible) {
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format (NDI_UNIQUE, 0, who,
                                    "You stop using the %s.", query_name(op));
		} else {
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format (NDI_UNIQUE, 0, who,
                                    "You can no longer use the skill: %s.",
                                    op->skill);
		}
	    }
	    (void) change_abil (who, op);
	    who->chosen_skill = NULL;
	    CLEAR_FLAG (who, FLAG_READY_SKILL);
	    break;

	case ARMOUR:
	case HELMET:
	case SHIELD:
	case RING:
	case BOOTS:
	case GLOVES:
	case AMULET:
	case GIRDLE:
	case BRACERS:
	case CLOAK:
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You unwear %s.",query_name(op));
	    (void) change_abil (who,op);
	    break;
        case LAMP:
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You turn off your %s.",
				 op->name);
	    tmp2 = arch_to_object(op->other_arch);
	    tmp2->x = op->x;
	    tmp2->y = op->y;
	    tmp2->map = op->map;
	    tmp2->below = op->below;
	    tmp2->above = op->above;
	    tmp2->stats.food = op->stats.food;
	    CLEAR_FLAG(tmp2, FLAG_APPLIED);
	    if (QUERY_FLAG(op, FLAG_INV_LOCKED))
		SET_FLAG(tmp2, FLAG_INV_LOCKED);
	    if (who->type == PLAYER)
		esrv_del_item(who->contr, (tag_t)op->count);
	    remove_ob(op);
	    free_object(op);
	    insert_ob_in_ob(tmp2, who);
	    fix_player(who);
	    if (QUERY_FLAG(op, FLAG_CURSED) || QUERY_FLAG(op, FLAG_DAMNED)) {
		if (who->type == PLAYER) {
		    if (!(aflags & AP_NOPRINT))
			new_draw_info(NDI_UNIQUE, 0,who, "Oops, it feels deadly cold!");
		    SET_FLAG(tmp2, FLAG_KNOWN_CURSED);
		}
	    }
	    if(who->type==PLAYER)
		esrv_send_item(who, tmp2);
            if (who->map) {
                SET_MAP_FLAGS(who->map, who->x, who->y,  P_NEED_UPDATE);
                update_position(who->map, who->x, who->y);
                update_all_los(who->map, who->x, who->y);
            }

	    return 1; /* otherwise, an attempt to drop causes problems */
	    break;
	case BOW:

        case WAND:
	case ROD:
	case HORN:
	    clear_skill(who);
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You unready %s.",query_name(op));
	    if(who->type==PLAYER) {
		who->contr->shoottype = range_none;
	    } else {
		if (op->type == BOW)
		    CLEAR_FLAG (who, FLAG_READY_BOW);
		else 
		    CLEAR_FLAG(who, FLAG_READY_RANGE);
	    }
	    break;

    case BUILDER:
	if (!(aflags & AP_NOPRINT))
	    new_draw_info_format(NDI_UNIQUE, 0, who, "You unready %s.",query_name(op));
        who->contr->shoottype = range_none;
        who->contr->ranges[ range_builder ] = NULL;
        break;

	default:
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You unapply %s.",query_name(op));
	    break;
    }

    fix_player(who);

    if ( ! (aflags & AP_NO_MERGE)) {
	object *tmp;

        tmp = merge_ob (op, NULL);
        if (who->type == PLAYER) {
            if (tmp) {  /* it was merged */
                op = tmp;
            }
            esrv_update_item (UPD_FLAGS, who, op);
	}
    }
    return 0;
}

/**
 * Returns the object that is using location 'loc'.
 * Note that 'start' is the first object to start examing - we
 * then go through the below of this.  In this way, you can do
 * something like:
 * tmp = get_item_from_body_location(who->inv, 1);
 * if (tmp) tmp1 = get_item_from_body_location(tmp->below, 1);
 * to find the second object that may use this location, etc.
 * Returns NULL if no match is found.
 * loc is the index into the array we are looking for a match.
 * don't return invisible objects unless they are skill objects
 * invisible other objects that use
 * up body locations can be used as restrictions.
 */
static object *get_item_from_body_location(object *start, int loc)
{
    object *tmp;

    if (!start) return NULL;

    for (tmp=start; tmp; tmp=tmp->below)
	if (QUERY_FLAG(tmp, FLAG_APPLIED) && tmp->body_info[loc] && 
	    (!tmp->invisible || tmp->type==SKILL)) return tmp;

    return NULL;
}



/**
 * 'op' wants to apply an object, but can't because of other equipment.
 * This should only be called when it is known
 * that there are objects to unapply.  This makes pretty heavy
 * use of get_item_from_body_location.  It makes no intelligent choice
 * on objects - rather, the first that is matched is used.
 * Returns 0 on success, returns 1 if there is some problem.
 * if aflags is AP_PRINT, we instead print out waht to unapply
 * instead of doing it.  This is a lot less code than having
 * another function that does just that.
 */
static int unapply_for_ob(object *who, object *op, int aflags)
{
    int i;
    object *tmp=NULL, *last;

    /* If we are applying a shield or weapon, unapply any equipped shield
     * or weapons first - only allowed to use one weapon/shield at a time.
     */
    if (op->type == WEAPON || op->type == SHIELD) {
        for (tmp=who->inv; tmp; tmp=tmp->below) {
	    if (QUERY_FLAG(tmp, FLAG_APPLIED) && tmp->type == op->type) {
		if ((aflags & AP_IGNORE_CURSE) ||  (aflags & AP_PRINT) ||
		    (!QUERY_FLAG(tmp, FLAG_CURSED) && !QUERY_FLAG(tmp, FLAG_DAMNED))) {
		    if (aflags & AP_PRINT) 
			new_draw_info(NDI_UNIQUE, 0, who, query_name(tmp));
		    else
			unapply_special(who, tmp, aflags);
		}
		else {
		    /* In this case, we want to try and remove a cursed item.
		     * While we know it won't work, we want unapply_special to
		     * at least generate the message.
		     */
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format(NDI_UNIQUE, 0, who,
				 "No matter how hard you try, you just can't\nremove %s.",
				 query_name(tmp));
		    return 1;
		}

	    }
	}
    }

    for (i=0; i<NUM_BODY_LOCATIONS; i++) {
	/* this used up a slot that we need to free */
	if (op->body_info[i]) {
	    last = who->inv;

	    /* We do a while loop - may need to remove several items in order
	     * to free up enough slots.
	     */
	    while ((who->body_used[i] + op->body_info[i]) < 0) {
		tmp = get_item_from_body_location(last, i);
		if (!tmp) {
#if 0
		    /* Not a bug - we'll get this if the player has cursed items
		     * equipped.
		     */
		    LOG(llevError,"Can't find object using location %d (%s) on %s\n", 
			i, body_locations[i].save_name, who->name);
#endif
		    return 1;
		}
		/* If we are just printing, we don't care about cursed status */
		if ((aflags & AP_IGNORE_CURSE) ||  (aflags & AP_PRINT) ||
		    (!(QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)))) {
		    if (aflags & AP_PRINT) 
			new_draw_info(NDI_UNIQUE, 0, who, query_name(tmp));
		    else
			unapply_special(who, tmp, aflags);
		}
		else {
		    /* Cursed item that we can't unequip - tell the player.
		     * Note this could be annoying if this is just one of a few,
		     * so it may not be critical (eg, putting on a ring and you have
		     * one cursed ring.)
		     */
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format(NDI_UNIQUE, 0, who, "The %s just won't come off", query_name(tmp));
		}
		last = tmp->below;
	    }
	    /* if we got here, this slot is freed up - otherwise, if it wasn't freed up, the
	     * return in the !tmp would have kicked in.
	     */
	} /* if op is using this body location */
    } /* for body lcoations */
    return 0;
}

/**
 * Checks to see if 'who' can apply object 'op'.
 * Returns 0 if apply can be done without anything special.
 * Otherwise returns a bitmask - potentially several of these may be
 * set, but largely depends on circumstance - in the future, processing
 * may be  pruned once we know some status (eg, once CAN_APPLY_NEVER
 * is set, do we really are what the other flags may be?)
 *
 * See include/define.h for detailed description of the meaning of
 * these return values.
 */
int can_apply_object(object *who, object *op)
{
    int i, retval=0;
    object *tmp=NULL, *ws=NULL;

    /* Players have 2 'arm's, so they could in theory equip 2 shields or
     * 2 weapons, but we don't want to let them do that.  So if they are
     * trying to equip a weapon or shield, see if they already have one
     * in place and store that way.
     */
    if (op->type == WEAPON || op->type == SHIELD) {
        for (tmp=who->inv; tmp && !ws; tmp=tmp->below) {
	    if (QUERY_FLAG(tmp, FLAG_APPLIED) && tmp->type == op->type) {
		retval = CAN_APPLY_UNAPPLY;
		ws = tmp;
	    }
	}
    }
	

    for (i=0; i<NUM_BODY_LOCATIONS; i++) {
	if (op->body_info[i]) {
	    /* Item uses more slots than we have */
	    if (FABS(op->body_info[i]) > who->body_info[i]) {
		/* Could return now for efficiently - rest of info below isn't
		 * really needed.
		 */
		retval |= CAN_APPLY_NEVER;
	    } else if ((who->body_used[i] + op->body_info[i]) < 0) {
		/* in this case, equipping this would use more free spots than
		 * we have.
		 */
		object *tmp1;


		/* if we have an applied weapon/shield, and unapply it would free
		 * enough slots to equip the new item, then just set this can
		 * continue.  We don't care about the logic below - if you have
		 * shield equipped and try to equip another shield, there is only
		 * one choice.  However, the check for the number of body locations 
		 * does take into the account cases where what is being applied
		 * may be two handed for example.
		 */
		if (ws) {
		    if ((who->body_used[i] - ws->body_info[i] + op->body_info[i]) >=0) {
			retval |= CAN_APPLY_UNAPPLY;
			continue;
		    }
		}

		tmp1 = get_item_from_body_location(who->inv, i);
		if (!tmp1) {
#if 0
		    /* This is sort of an error, but happens a lot when old players
		     * join in with more stuff equipped than they are now allowed.
		     */
		    LOG(llevError,"Can't find object using location %d on %s\n",
			i, who->name);
#endif
		    retval |= CAN_APPLY_NEVER;
		} else {
		    /* need to unapply something.  However, if this something
		     * is different than we had found before, it means they need
		     * to apply multiple objects
		     */
		    retval |= CAN_APPLY_UNAPPLY;
		    if (!tmp) tmp = tmp1;
		    else if (tmp != tmp1) {
			retval |= CAN_APPLY_UNAPPLY_MULT;
		    }
		    /* This object isn't using up all the slots, so there must
		     * be another.  If so, and it the new item doesn't need all
		     * the slots, the player then has a choice.  
		     */
		    if (((who->body_used[i] - tmp1->body_info[i]) != who->body_info[i]) &&
			(FABS(op->body_info[i]) < who->body_info[i]))
			retval |= CAN_APPLY_UNAPPLY_CHOICE;

		    /* Does unequippint 'tmp1' free up enough slots for this to be
		     * equipped?  If not, there must be something else to unapply.
		     */
		    if ((who->body_used[i] + op->body_info[i] - tmp1->body_info[i]) < 0)
			retval |= CAN_APPLY_UNAPPLY_MULT;

		}
	    } /* if not enough free slots */
	} /* if this object uses location i */
    } /* for i -> num_body_locations loop */

    /* Do checks for can_use_weapon/shield/armour. */
    if (IS_WEAPON(op) && !QUERY_FLAG(who,FLAG_USE_WEAPON))
        retval |= CAN_APPLY_RESTRICTION;
    if (IS_SHIELD(op) && !QUERY_FLAG(who,FLAG_USE_SHIELD))
        retval |= CAN_APPLY_RESTRICTION;
    if (IS_ARMOR(op) && !QUERY_FLAG(who,FLAG_USE_ARMOUR))
        retval |= CAN_APPLY_RESTRICTION;

    if (who->type != PLAYER) {
	if ((op->type == WAND || op->type == HORN || op->type==ROD)
	    && !QUERY_FLAG(who, FLAG_USE_RANGE))
		retval |= CAN_APPLY_RESTRICTION;
	if (op->type == BOW && !QUERY_FLAG(who, FLAG_USE_BOW))
	    retval |= CAN_APPLY_RESTRICTION;
	if (op->type == RING && !QUERY_FLAG(who, FLAG_USE_RING))
	    retval |= CAN_APPLY_RESTRICTION;
	if (op->type == BOW && !QUERY_FLAG(who, FLAG_USE_BOW))
	    retval |= CAN_APPLY_RESTRICTION;
    }
    return retval;
}

		

/**
 * who is the object using the object.  It can be a monster
 * op is the object they are using.  op is an equipment type item,
 * eg, one which you put on and keep on for a while, and not something
 * like a potion or scroll.
 *
 * function returns 1 if the action could not be completed, 0 on
 * success.  However, success is a matter of meaning - if the
 * user passes the 'apply' flag to an object already applied,
 * nothing is done, and 0 is returned.
 *
 * aflags is special flags (0 - normal/toggle, AP_APPLY=always apply,
 * AP_UNAPPLY=always unapply).
 *
 * Optional flags:
 *   AP_NO_MERGE: don't merge an unapplied object with other objects
 *   AP_IGNORE_CURSE: unapply cursed items
 *
 * Usage example:  apply_special (who, op, AP_UNAPPLY | AP_IGNORE_CURSE)
 *
 * apply_special() doesn't check for unpaid items.
 */
int apply_special (object *who, object *op, int aflags)
{
    int basic_flag = aflags & AP_BASIC_FLAGS;
    object *tmp, *tmp2, *skop=NULL;
    int i;

    if(who==NULL) {
	LOG(llevError,"apply_special() from object without environment.\n");
	return 1;
    }

    if(op->env!=who)
	return 1;   /* op is not in inventory */

    /* trying to unequip op */
    if (QUERY_FLAG(op,FLAG_APPLIED)) {
	/* always apply, so no reason to unapply */
	if (basic_flag == AP_APPLY) return 0;

	if ( ! (aflags & AP_IGNORE_CURSE)
	    && (QUERY_FLAG(op, FLAG_CURSED) || QUERY_FLAG(op, FLAG_DAMNED))) {
		if (!(aflags & AP_NOPRINT))
		    new_draw_info_format(NDI_UNIQUE, 0, who,
				 "No matter how hard you try, you just can't\nremove %s.",
				 query_name(op));
	    return 1;
	}
	return unapply_special(who, op, aflags);
    }

    if (basic_flag == AP_UNAPPLY) return 0;

    i = can_apply_object(who, op);

    /* Can't just apply this object.  Lets see what not and what to do */
    if (i) {
	if (i & CAN_APPLY_NEVER) {
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You don't have the body to use a %s\n", query_name(op));
	    return 1;
	} else if (i & CAN_APPLY_RESTRICTION) {
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You have a prohibition against using a %s\n", query_name(op));
	    return 1;
	}
	if (who->type != PLAYER) {
	    /* Some error, so don't try to equip something more */
	    if (unapply_for_ob(who, op, aflags)) return 1;
	} else {
	    if (who->contr->unapply == unapply_never || 
		(i & CAN_APPLY_UNAPPLY_CHOICE && who->contr->unapply == unapply_nochoice)) {
		if (!(aflags & AP_NOPRINT))
		    new_draw_info(NDI_UNIQUE, 0, who, "You need to unapply some item(s):");
		unapply_for_ob(who, op, AP_PRINT);
		return 1;
	    }
	    else if (who->contr->unapply == unapply_always || !(i & CAN_APPLY_UNAPPLY_CHOICE)) {
		i = unapply_for_ob(who, op, aflags);
		if (i) return 1;
	    }
	}
    }
    if (op->skill && op->type != SKILL && op->type != SKILL_TOOL) {
	skop=find_skill_by_name(who, op->skill);
	if (!skop) {
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You need the %s skill to use this item!", op->skill);
	    return 1;
	} else {
	    /* While experience will be credited properly, we want to change the
	     * skill so that the dam and wc get updated 
	     */
	    change_skill(who, skop, aflags & AP_NOPRINT);
	}
    }
	
    if (who->type == PLAYER && op->item_power && 
	(op->item_power + who->contr->item_power) > (settings.item_power_factor * who->level)) {
	    if (!(aflags & AP_NOPRINT))
		new_draw_info(NDI_UNIQUE, 0, who, "Equipping that combined with other items would consume your soul!");
	return 1;
    }
	

    /* Ok.  We are now at the state where we can apply the new object.
     * Note that we don't have the checks for can_use_...
     * below - that is already taken care of by can_apply_object. 
     */
			  

    if(op->nrof > 1)
	tmp = get_split_ob(op,op->nrof - 1);
    else
	tmp = NULL;

    switch(op->type) {
        case WEAPON:
        {
            int ownerlen=0;
            char* quotepos=NULL;
            if (!check_weapon_power(who, op->last_eat)) {
		if (!(aflags & AP_NOPRINT)) {
		    new_draw_info(NDI_UNIQUE, 0,who,
				  "That weapon is too powerful for you to use.");
		    new_draw_info(NDI_UNIQUE, 0, who,
				  "It would consume your soul!.");
		}
                if(tmp!=NULL)
                    (void) insert_ob_in_ob(tmp,who);
                return 1;
            }
            if ((quotepos=strstr(op->name, "'"))!=NULL)
            {
                ownerlen = (strstr(op->name, "'")-op->name);
                if( op->level &&  (strncmp(op->name,who->name,ownerlen))) {
                    /* if the weapon does not have the name as the character,
                     * can't use it. (Ragnarok's sword attempted to be used by
                     * Foo: won't work) */
		    if (!(aflags & AP_NOPRINT))
			new_draw_info(NDI_UNIQUE, 0,who,
			      "The weapon does not recognize you as its owner.");
                    if(tmp!=NULL)
                        (void) insert_ob_in_ob(tmp,who);
                    return 1;
                }
            }
            SET_FLAG(op, FLAG_APPLIED);

            if (skop) change_skill(who, skop, 1);
            if(!QUERY_FLAG(who,FLAG_READY_WEAPON))
                SET_FLAG(who, FLAG_READY_WEAPON);

	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You wield %s.",
			     query_name(op));

            (void) change_abil (who,op);
            break;
        }
	case ARMOUR:
	case HELMET:
	case SHIELD:
	case BOOTS:
	case GLOVES:
	case GIRDLE:
	case BRACERS:
	case CLOAK:
	case RING:
	case AMULET:
	    SET_FLAG(op, FLAG_APPLIED);
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You wear %s.",query_name(op));
	    (void) change_abil (who,op);
	    break;
        case LAMP:
	    if (op->stats.food < 1) {
		if (!(aflags & AP_NOPRINT))
		    new_draw_info_format(NDI_UNIQUE, 0, who, "Your %s is out of"
				     " fuel!", op->name);
		return 1;
	    }
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format(NDI_UNIQUE, 0, who, "You turn on your %s.",
				 op->name);
	    tmp2 = arch_to_object(op->other_arch);
	    tmp2->stats.food = op->stats.food;
	    SET_FLAG(tmp2, FLAG_APPLIED);
	    if (QUERY_FLAG(op, FLAG_INV_LOCKED))
		SET_FLAG(tmp2, FLAG_INV_LOCKED);
	    insert_ob_in_ob(tmp2, who);

	    /* Remove the old lantern */
	    if (who->type == PLAYER)
		esrv_del_item(who->contr, (tag_t)op->count);
	    remove_ob(op);
	    free_object(op);

	    /* insert the portion that was split off */
	    if(tmp!=NULL) {
		(void) insert_ob_in_ob(tmp,who);
		if(who->type==PLAYER)
		    esrv_send_item(who, tmp);
	    }
	    fix_player(who);
	    if (QUERY_FLAG(op, FLAG_CURSED) || QUERY_FLAG(op, FLAG_DAMNED)) {
		if (who->type == PLAYER) {
		    if (!(aflags & AP_NOPRINT))
			new_draw_info(NDI_UNIQUE, 0,who, "Oops, it feels deadly cold!");
		    SET_FLAG(tmp2, FLAG_KNOWN_CURSED);
		}
	    }
	    if(who->type==PLAYER)
		esrv_send_item(who, tmp2);
            if (who->map) {
                SET_MAP_FLAGS(who->map, who->x, who->y,  P_NEED_UPDATE);
                update_position(who->map, who->x, who->y);
                update_all_los(who->map, who->x, who->y);
            }

	    return 0;
	    break;

	/* this part is needed for skill-tools */ 
	case SKILL:
	case SKILL_TOOL:
	    if (who->chosen_skill) {
		LOG (llevError, "BUG: apply_special(): can't apply two skills\n");
		return 1;
	    }
	    if (who->type == PLAYER) {
		who->contr->shoottype = range_skill;
		who->contr->ranges[range_skill] = op;
		if ( ! op->invisible) {
		    if (!(aflags & AP_NOPRINT)) {
			new_draw_info_format (NDI_UNIQUE, 0, who, "You ready %s.",
                                  query_name (op));
			new_draw_info_format (NDI_UNIQUE, 0, who,
			      "You can now use the skill: %s.",
				op->skill);
		    }
		} else {
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format (NDI_UNIQUE, 0, who, "Readied skill: %s.",
				      op->skill? op->skill:op->name);
		}
	    }
	    SET_FLAG (op, FLAG_APPLIED);
	    (void) change_abil (who, op);
	    who->chosen_skill = op;
	    SET_FLAG (who, FLAG_READY_SKILL);
	    break;
	
	case BOW:
	    if (!check_weapon_power(who, op->last_eat)) {
		if (!(aflags & AP_NOPRINT)) {
		    new_draw_info(NDI_UNIQUE, 0, who,
			  "That item is too powerful for you to use.");
		    new_draw_info(NDI_UNIQUE, 0, who, "It would consume your soul!.");
		}
		if(tmp != NULL)
		    (void)insert_ob_in_ob(tmp,who);
		return 1;
	    }
	    if( op->level && (strncmp(op->name,who->name,strlen(who->name)))) {
		if (!(aflags & AP_NOPRINT)) {
		    new_draw_info(NDI_UNIQUE, 0, who,
				  "The weapon does not recognize you as its owner.");
		}
		if(tmp != NULL)
		    (void)insert_ob_in_ob(tmp,who);
		return 1;
	    }
	    /*FALLTHROUGH*/
	case WAND:
	case ROD:
	case HORN:
	    /* check for skill, alter player status */ 
	    SET_FLAG(op, FLAG_APPLIED);
	    if (skop) change_skill(who, skop, 0);
	    if (!(aflags & AP_NOPRINT))
		new_draw_info_format (NDI_UNIQUE, 0, who, "You ready %s.", query_name(op));

	    if(who->type==PLAYER) {
		if (op->type == BOW) {
		    (void)change_abil(who, op);
		    if (!(aflags & AP_NOPRINT))
			new_draw_info_format (NDI_UNIQUE, 0, who,
                              "You will now fire %s with %s.",
	                      op->race ? op->race : "nothing", query_name(op));
		    who->contr->shoottype = range_bow;
		} else {
		    who->contr->shoottype = range_misc;
		}
	    } else {
		if (op->type == BOW)
		    SET_FLAG (who, FLAG_READY_BOW);
		else
		    SET_FLAG (who, FLAG_READY_RANGE);
	    }
	    break;

    case BUILDER:
        if ( who->contr->ranges[ range_builder ] )
            unapply_special( who, who->contr->ranges[ range_builder ], 0 );
        who->contr->shoottype = range_builder;
        who->contr->ranges[ range_builder ] = op;
	if (!(aflags & AP_NOPRINT))
	    new_draw_info_format( NDI_UNIQUE, 0, who, "You ready your %s.", query_name( op ) );
        break;

	default:
	    new_draw_info_format(NDI_UNIQUE, 0, who, "You apply %s.",query_name(op));
    } /* end of switch op->type */

    SET_FLAG(op, FLAG_APPLIED);

    if(tmp!=NULL)
	tmp = insert_ob_in_ob(tmp,who);

    fix_player(who);

    /* We exclude spell casting objects.  The fire code will set the
     * been applied flag when they are used - until that point,
     * you don't know anything about them.
     */
    if (who->type == PLAYER && op->type!=WAND && op->type!=HORN &&
	op->type!=ROD)
	SET_FLAG(op,FLAG_BEEN_APPLIED);

    if (QUERY_FLAG(op, FLAG_CURSED) || QUERY_FLAG(op, FLAG_DAMNED)) {
	if (who->type == PLAYER) {
	    new_draw_info(NDI_UNIQUE, 0,who, "Oops, it feels deadly cold!");
	    SET_FLAG(op,FLAG_KNOWN_CURSED);
	}
    }
    if(who->type==PLAYER) {
        esrv_update_item(UPD_NROF | UPD_FLAGS | UPD_WEIGHT, who, op);
    }
    return 0;
}


#if 0
/* monster_apply_special is no longer used - should probably be
 * removed if in fact it won't be used by anything.
 * MSW 2006-06-02
 */
static int monster_apply_special (object *who, object *op, int aflags)
{
  if (QUERY_FLAG (op, FLAG_UNPAID) && ! QUERY_FLAG (op, FLAG_APPLIED))
    return 1;
  return apply_special (who, op, aflags);
}
#endif

/**
 * Map was just loaded, handle op's initialisation.
 *
 * Generates shop floor's item, and treasures.
 */
int auto_apply (object *op) {
    object *tmp = NULL, *tmp2;
    int i;

    switch(op->type) {
	case SHOP_FLOOR:
	    if (!HAS_RANDOM_ITEMS(op)) return 0;
	    do {
		i=10; /* let's give it 10 tries */
		while((tmp=generate_treasure(op->randomitems,
					     op->stats.exp?(int)op->stats.exp:MAX(op->map->difficulty, 5)))==NULL&&--i);
		if(tmp==NULL)
		    return 0;
		if(QUERY_FLAG(tmp, FLAG_CURSED) || QUERY_FLAG(tmp, FLAG_DAMNED)) {
		    free_object(tmp);
		    tmp = NULL;
		}
	    } while(!tmp);
	    tmp->x=op->x;
	    tmp->y=op->y;
	    SET_FLAG(tmp,FLAG_UNPAID);
	    insert_ob_in_map(tmp,op->map,NULL,0);
	    CLEAR_FLAG(op,FLAG_AUTO_APPLY);
	    identify(tmp);
	    break;

	case TREASURE:
	    if (QUERY_FLAG(op,FLAG_IS_A_TEMPLATE))
		return 0;
	    while ((op->stats.hp--)>0)
		create_treasure(op->randomitems, op, op->map?GT_ENVIRONMENT:0,
				op->stats.exp ? (int)op->stats.exp : 
				op->map == NULL ?  14: op->map->difficulty,0);

	    /* If we generated an object and put it in this object inventory,
	     * move it to the parent object as the current object is about
	     * to disappear.  An example of this item is the random_* stuff
	     * that is put inside other objects.
	     */
	    for (tmp=op->inv; tmp; tmp=tmp2) {
		tmp2 = tmp->below;
		remove_ob(tmp);
		if (op->env) insert_ob_in_ob(tmp, op->env);
		else free_object(tmp);
	    }
	    remove_ob(op);
	    free_object(op);
	    break;
    }
    return tmp ? 1 : 0;
}

/**
 * fix_auto_apply goes through the entire map (only the first time
 * when an original map is loaded) and performs special actions for
 * certain objects (most initialization of chests and creation of
 * treasures and stuff).  Calls auto_apply if appropriate.
 */

void fix_auto_apply(mapstruct *m) {
    object *tmp,*above=NULL;
    int x,y;

    if(m==NULL) return;

    for(x=0;x<MAP_WIDTH(m);x++)
	for(y=0;y<MAP_HEIGHT(m);y++)
	    for(tmp=get_map_ob(m,x,y);tmp!=NULL;tmp=above) {
		above=tmp->above;

		if (tmp->inv) {
		    object *invtmp, *invnext;

		    for (invtmp=tmp->inv; invtmp != NULL; invtmp = invnext) {
			invnext = invtmp->below;

			if(QUERY_FLAG(invtmp,FLAG_AUTO_APPLY))
			    auto_apply(invtmp);
			else if(invtmp->type==TREASURE && HAS_RANDOM_ITEMS(invtmp)) {
			    while ((invtmp->stats.hp--)>0)
				create_treasure(invtmp->randomitems, invtmp, 0,
						m->difficulty,0);
				invtmp->randomitems = NULL;
			}
			else if (invtmp && invtmp->arch && 
				invtmp->type!=TREASURE &&
				invtmp->type != SPELL && 
				invtmp->type != CLASS &&
				HAS_RANDOM_ITEMS(invtmp)) {
				    create_treasure(invtmp->randomitems, invtmp, 0,
						    m->difficulty,0);
				/* Need to clear this so that we never try to create 
				 * treasure again for this object
				 */
				invtmp->randomitems = NULL;
			}
		    }
		    /* This is really temporary - the code at the bottom will
		     * also set randomitems to null.  The problem is there are bunches
		     * of maps/players already out there with items that have spells
		     * which haven't had the randomitems set to null yet.
		     * MSW 2004-05-13
		     *
		     * And if it's a spellbook, it's better to set randomitems to NULL too,
		     * else you get two spells in the book ^_-
		     * Ryo 2004-08-16
		     */
		    if (tmp->type == WAND || tmp->type == ROD || tmp->type == SCROLL ||
			tmp->type == HORN || tmp->type == FIREWALL || tmp->type == POTION ||
			tmp->type == ALTAR || tmp->type == SPELLBOOK)
			    tmp->randomitems = NULL;

		}

		if(QUERY_FLAG(tmp,FLAG_AUTO_APPLY))
		    auto_apply(tmp);
		else if((tmp->type==TREASURE || (tmp->type==CONTAINER))&& HAS_RANDOM_ITEMS(tmp)) {
		    while ((tmp->stats.hp--)>0)
			create_treasure(tmp->randomitems, tmp, 0,
                            m->difficulty,0);
		    tmp->randomitems = NULL;
		}
		else if(tmp->type==TIMED_GATE) {
		    object *head = tmp->head != NULL ? tmp->head : tmp;
		    if (QUERY_FLAG(head, FLAG_IS_LINKED)) {
			tmp->speed = 0;
			update_ob_speed(tmp);
		    }
		}
		/* This function can be called everytime a map is loaded, even when
		 * swapping back in.  As such, we don't want to create the treasure
		 * over and ove again, so after we generate the treasure, blank out
		 * randomitems so if it is swapped in again, it won't make anything.
		 * This is a problem for the above objects, because they have counters
		 * which say how many times to make the treasure.
		 */
		else if(tmp && tmp->arch && tmp->type!=PLAYER && tmp->type!=TREASURE &&
		   tmp->type != SPELL && tmp->type != PLAYER_CHANGER && tmp->type != CLASS &&
		   HAS_RANDOM_ITEMS(tmp)) {
		    create_treasure(tmp->randomitems, tmp, GT_APPLY,
                            m->difficulty,0);
		    tmp->randomitems = NULL;
		}
	    }

    for(x=0;x<MAP_WIDTH(m);x++)
	for(y=0;y<MAP_HEIGHT(m);y++)
	    for(tmp=get_map_ob(m,x,y);tmp!=NULL;tmp=tmp->above)
		if (tmp->above &&
		    (tmp->type == TRIGGER_BUTTON || tmp->type == TRIGGER_PEDESTAL))
			check_trigger (tmp, tmp->above);
}

/**
 * Handles player eating food that temporarily changes status (resistances, stats).
 * This used to call cast_change_attr(), but
 * that doesn't work with the new spell code.  Since we know what
 * the food changes, just grab a force and use that instead.
 */

void eat_special_food(object *who, object *food) {
    object *force;
    int i, did_one=0; 
    sint8 k;

    force = create_archetype(FORCE_NAME);

    for (i=0; i < NUM_STATS; i++) {
	k = get_attr_value(&food->stats, i);
	if (k) {
	    set_attr_value(&force->stats, i, k);
	    did_one = 1;
	}
    }

    /* check if we can protect the eater */
    for (i=0; i<NROFATTACKS; i++) {
	if (food->resist[i]>0) {
	    force->resist[i] = food->resist[i] / 2;
	    did_one = 1;
	}
    }
    if (did_one) {
	force->speed = 0.1;
	update_ob_speed(force);
	/* bigger morsel of food = longer effect time */
	force->stats.food = food->stats.food / 5;
	SET_FLAG(force, FLAG_IS_USED_UP);   
	SET_FLAG(force, FLAG_APPLIED);
	change_abil(who, force);
	insert_ob_in_ob(force, who);
    } else {
	free_object(force);
    }

    /* check for hp, sp change */
    if(food->stats.hp!=0) {
	if(QUERY_FLAG(food, FLAG_CURSED)) { 
	    strcpy(who->contr->killer,food->name);
	    hit_player(who, food->stats.hp, food, AT_POISON, 1);
	    new_draw_info(NDI_UNIQUE, 0,who,"Eck!...that was poisonous!");
	} else { 
	    if(food->stats.hp>0) 
		new_draw_info(NDI_UNIQUE, 0,who,"You begin to feel better.");
	    else 
		new_draw_info(NDI_UNIQUE, 0,who,"Eck!...that was poisonous!");
	    who->stats.hp += food->stats.hp;
	}
    }
    if(food->stats.sp!=0) {
	if(QUERY_FLAG(food, FLAG_CURSED)) { 
	    new_draw_info(NDI_UNIQUE, 0,who,"You are drained of mana!");
	    who->stats.sp -= food->stats.sp; 
	    if(who->stats.sp<0) who->stats.sp=0;
	    } else { 
		new_draw_info(NDI_UNIQUE, 0,who,"You feel a rush of magical energy!");
		who->stats.sp += food->stats.sp; 
		/* place limit on max sp from food? */
	    }
    }
    fix_player(who);
}


/**
 * Designed primarily to light torches/lanterns/etc.
 * Also burns up burnable material too. First object in the inventory is
 * the selected object to "burn". -b.t.
 */

static void apply_lighter(object *who, object *lighter) {
    object *item;
    int is_player_env=0;
    uint32 nrof;
    tag_t count;
    char item_name[MAX_BUF];

    item=find_marked_object(who);
    if(item) {
        if(lighter->last_eat && lighter->stats.food) { /* lighter gets used up */
        /* Split multiple lighters if they're being used up.  Otherwise	*
	 * one charge from each would be used up.  --DAMN		*/
	  if(lighter->nrof > 1) {
	    object *oneLighter = get_object();
	    copy_object(lighter, oneLighter);
	    lighter->nrof -= 1;
	    oneLighter->nrof = 1;
	    oneLighter->stats.food--;
	    esrv_send_item(who, lighter);
	    oneLighter=insert_ob_in_ob(oneLighter, who);
	    esrv_send_item(who, oneLighter);
	  } else {
	    lighter->stats.food--;
	  }

	} else if(lighter->last_eat) { /* no charges left in lighter */
	     new_draw_info_format(NDI_UNIQUE, 0,who,
				  "You attempt to light the %s with a used up %s.",
				  item->name, lighter->name);
	     return;
        }
	/* Perhaps we should split what we are trying to light on fire?
	 * I can't see many times when you would want to light multiple
	 * objects at once.
	 */
	nrof=item->nrof;
	count=item->count;
	/* If the item is destroyed, we don't have a valid pointer to the
	 * name object, so make a copy so the message we print out makes
	 * some sense.
	 */
	strcpy(item_name, item->name);
	if (who == get_player_container(item)) is_player_env=1;

	save_throw_object(item,AT_FIRE,who);
	/* Change to check count and not freed, since the object pointer
	 * may have gotten recycled
	 */
	if ((nrof != item->nrof ) || (count != item->count)) {
	    new_draw_info_format(NDI_UNIQUE, 0,who,
		 "You light the %s with the %s.",item_name,lighter->name);
	    /* Need to update the player so that the players glow radius
	     * gets changed.
	     */
	    if (is_player_env) fix_player(who);
	} else {
	    new_draw_info_format(NDI_UNIQUE, 0,who,
		 "You attempt to light the %s with the %s and fail.",item->name,lighter->name);
	}

   } else /* nothing to light */
	new_draw_info(NDI_UNIQUE, 0,who,"You need to mark a lightable object.");

}

/**
 * op made some mistake with a scroll, this takes care of punishment.
 * scroll_failure()- hacked directly from spell_failure
 */
static void scroll_failure(object *op, int failure, int power)
{
    if(abs(failure/4)>power) power=abs(failure/4); /* set minimum effect */

    if(failure<= -1&&failure > -15) {/* wonder */
	object *tmp;

	new_draw_info(NDI_UNIQUE, 0,op,"Your spell warps!.");
	tmp=create_archetype(SPELL_WONDER);
	cast_wonder(op, op, 0, tmp);
	free_object(tmp);
    } else if (failure <= -15&&failure > -35) {/* drain mana */
	new_draw_info(NDI_UNIQUE, 0,op,"Your mana is drained!.");
	op->stats.sp -= random_roll(0, power-1, op, PREFER_LOW);
	if(op->stats.sp<0) op->stats.sp = 0;
    } else if (settings.spell_failure_effects == TRUE) {
	if (failure <= -35&&failure > -60) { /* confusion */
	    new_draw_info(NDI_UNIQUE, 0,op,"The magic recoils on you!");
	    confuse_player(op,op,power);
	} else if (failure <= -60&&failure> -70) {/* paralysis */
	    new_draw_info(NDI_UNIQUE, 0,op,"The magic recoils and paralyzes "
		"you!");
	    paralyze_player(op,op,power);
	} else if (failure <= -70&&failure> -80) {/* blind */
	    new_draw_info(NDI_UNIQUE, 0,op,"The magic recoils on you!");
	    blind_player(op,op,power);
	} else if (failure <= -80) {/* blast the immediate area */
	    object *tmp;
	    tmp=create_archetype(LOOSE_MANA);
	    cast_magic_storm(op,tmp, power);
	    new_draw_info(NDI_UNIQUE, 0,op,"You unlease uncontrolled mana!");
	    free_object(tmp);
	}
    }
}

/**
 * Applies (race) changes to a player.
 */
void apply_changes_to_player(object *pl, object *change) {
    int excess_stat=0;  /* if the stat goes over the maximum
                         for the race, put the excess stat some
                         where else. */

    switch (change->type) {
	case CLASS: {
	    living *stats = &(pl->contr->orig_stats);
	    living *ns = &(change->stats);
	    object *walk;
	    int flag_change_face=1;

	    /* the following code assigns stats up to the stat max
	     * for the race, and if the stat max is exceeded,
	     * tries to randomly reassign the excess stat
	     */
	    int i,j;
	    for(i=0;i<NUM_STATS;i++) {
		sint8 stat=get_attr_value(stats,i);
		int race_bonus = get_attr_value(&(pl->arch->clone.stats),i);
		stat += get_attr_value(ns,i);
		if(stat > 20 + race_bonus) {
		    excess_stat++;
		    stat = 20+race_bonus;
		}
		set_attr_value(stats,i,stat);
	    }

	    for(j=0;excess_stat >0 && j<100;j++)  {/* try 100 times to assign excess stats */
		int i = rndm(0, 6);
		int stat=get_attr_value(stats,i);
		int race_bonus = get_attr_value(&(pl->arch->clone.stats),i);
		if(i==CHA) continue;  /* exclude cha from this */
		if( stat < 20 + race_bonus) {
		    change_attr_value(stats,i,1);
		    excess_stat--;
		}
	    }

	    /* insert the randomitems from the change's treasurelist into
	     * the player ref: player.c
	     */
	    if(change->randomitems!=NULL)
		give_initial_items(pl,change->randomitems);


	    /* set up the face, for some races. */

	    /* first, look for the force object banning
	     * changing the face.  Certain races never change face with class.
	     */
	    for(walk=pl->inv;walk!=NULL;walk=walk->below)
		if (!strcmp(walk->name,"NOCLASSFACECHANGE")) flag_change_face=0;

	    if(flag_change_face) {
		pl->animation_id = GET_ANIM_ID(change);
		pl->face = change->face;

		if(QUERY_FLAG(change,FLAG_ANIMATE)) 
		    SET_FLAG(pl,FLAG_ANIMATE);
		else
		    CLEAR_FLAG(pl,FLAG_ANIMATE);
	    }

	    /* check the special case of can't use weapons */
	    /*if(QUERY_FLAG(change,FLAG_USE_WEAPON)) CLEAR_FLAG(pl,FLAG_USE_WEAPON);*/
	    if(!strcmp(change->name,"monk")) CLEAR_FLAG(pl,FLAG_USE_WEAPON);

	    break;
	}
    }
}

/**
 * This handles items of type 'transformer'.
 * Basically those items, used with a marked item, transform both items into something
 * else.
 * "Transformer" item has food decreased by 1, removed if 0 (0 at start means illimited)..
 * Change information is contained in the 'slaying' field of the marked item.
 * The format is as follow: transformer:[number ]yield[;transformer:...].
 * This way an item can be transformed in many things, and/or many objects.
 * The 'slaying' field for transformer is used as verb for the action.
 */
static void apply_item_transformer( object* pl, object* transformer )
    {
    object* marked;
    object* new_item;
    char* find;
    char* separator;
    int yield;
    char got[ MAX_BUF ];
    int len;

    if ( !pl || !transformer )
        return;
    marked = find_marked_object( pl );
    if ( !marked )
        {
        new_draw_info_format( NDI_UNIQUE, 0, pl, "Use the %s with what item?", query_name( transformer ) );
        return;
        }
    if ( !marked->slaying )
        {
        new_draw_info_format( NDI_UNIQUE, 0, pl, "You can't use the %s with your %s!", query_name( transformer ), query_name( marked ) );
        return;
        }
    /* check whether they are compatible or not */
    find = strstr( marked->slaying, transformer->arch->name );
    if ( !find || ( *( find + strlen( transformer->arch->name ) ) != ':' ) )
        {
        new_draw_info_format( NDI_UNIQUE, 0, pl, "You can't use the %s with your %s!", query_name( transformer ), query_name( marked ) );
        return;
        }
    find += strlen( transformer->arch->name ) + 1;
    /* Item can be used, now find how many and what it yields */
    if ( isdigit( *( find ) ) )
        {
        yield = atoi( find );
        if ( yield < 1 )
            {
            LOG( llevDebug, "apply_item_transformer: item %s has slaying-yield %d.\n", query_base_name( marked, 0 ), yield );
            yield = 1;
            }
        }
    else
        yield = 1;

    while ( isdigit( *find ) )
        find++;
    while ( *find == ' ' )
        find++;
    memset( got, 0, MAX_BUF );
    if ( (separator = strchr( find, ';' ))!=NULL)
        {
	len = separator - find;
        }
    else
        {
	len = strlen(find);
        }
    if ( len > MAX_BUF-1)
	len = MAX_BUF-1;
    strcpy( got, find );
    got[len] = '\0';

    /* Now create new item, remove used ones when required. */
    new_item = create_archetype( got );
    if ( !new_item )
        {
        new_draw_info_format( NDI_UNIQUE, 0, pl, "This %s is strange, better to not use it.", query_base_name( marked, 0 ) );
        return;
        }
    new_item->nrof = yield;
    new_draw_info_format( NDI_UNIQUE, 0, pl, "You %s the %s.", transformer->slaying, query_base_name( marked, 0 ) );
    insert_ob_in_ob( new_item, pl );
    esrv_send_inventory( pl, pl );
    /* Eat up one item */
    decrease_ob_nr( marked, 1 );
    /* Eat one transformer if needed */
    if ( transformer->stats.food )
        if ( --transformer->stats.food == 0 )
            decrease_ob_nr( transformer, 1 );
    }