Source:NetHack 3.6.2/src/invent.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to invent.c from the source code of NetHack 3.6.2. To link to a particular line, write [[Source:NetHack 3.6.2/src/invent.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 3.6	invent.c	$NHDT-Date: 1555196229 2019/04/13 22:57:09 $  $NHDT-Branch: NetHack-3.6.2-beta01 $:$NHDT-Revision: 1.253 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. #ifndef C /* same as cmd.c */
9. #define C(c) (0x1f & (c))
10. #endif
11. 
12. #define NOINVSYM '#'
13. #define CONTAINED_SYM '>' /* designator for inside a container */
14. #define HANDS_SYM '-'
15. 
16. STATIC_DCL void FDECL(loot_classify, (Loot *, struct obj *));
17. STATIC_DCL char *FDECL(loot_xname, (struct obj *));
18. STATIC_DCL int FDECL(CFDECLSPEC sortloot_cmp, (const genericptr,
19.                                                const genericptr));
20. STATIC_DCL void NDECL(reorder_invent);
21. STATIC_DCL void FDECL(noarmor, (BOOLEAN_P));
22. STATIC_DCL void FDECL(invdisp_nothing, (const char *, const char *));
23. STATIC_DCL boolean FDECL(worn_wield_only, (struct obj *));
24. STATIC_DCL boolean FDECL(only_here, (struct obj *));
25. STATIC_DCL void FDECL(compactify, (char *));
26. STATIC_DCL boolean FDECL(taking_off, (const char *));
27. STATIC_DCL boolean FDECL(putting_on, (const char *));
28. STATIC_PTR int FDECL(ckvalidcat, (struct obj *));
29. STATIC_PTR int FDECL(ckunpaid, (struct obj *));
30. STATIC_PTR char *FDECL(safeq_xprname, (struct obj *));
31. STATIC_PTR char *FDECL(safeq_shortxprname, (struct obj *));
32. STATIC_DCL char FDECL(display_pickinv, (const char *, const char *,
33.                                         const char *, BOOLEAN_P, long *));
34. STATIC_DCL char FDECL(display_used_invlets, (CHAR_P));
35. STATIC_DCL boolean FDECL(this_type_only, (struct obj *));
36. STATIC_DCL void NDECL(dounpaid);
37. STATIC_DCL struct obj *FDECL(find_unpaid, (struct obj *, struct obj **));
38. STATIC_DCL void FDECL(menu_identify, (int));
39. STATIC_DCL boolean FDECL(tool_in_use, (struct obj *));
40. STATIC_DCL char FDECL(obj_to_let, (struct obj *));
41. 
42. static int lastinvnr = 51; /* 0 ... 51 (never saved&restored) */
43. 
44. /* wizards can wish for venom, which will become an invisible inventory
45.  * item without this.  putting it in inv_order would mean venom would
46.  * suddenly become a choice for all the inventory-class commands, which
47.  * would probably cause mass confusion.  the test for inventory venom
48.  * is only WIZARD and not wizard because the wizard can leave venom lying
49.  * around on a bones level for normal players to find.  [Note to the
50.  * confused:  'WIZARD' used to be a compile-time conditional so this was
51.  * guarded by #ifdef WIZARD/.../#endif.]
52.  */
53. static char venom_inv[] = { VENOM_CLASS, 0 }; /* (constant) */
54. 
55. /* sortloot() classification; called at most once [per sort] for each object */
56. STATIC_OVL void
57. loot_classify(sort_item, obj)
58. Loot *sort_item;
59. struct obj *obj;
60. {
61.     /* we may eventually make this a settable option to always use
62.        with sortloot instead of only when the 'sortpack' option isn't
63.        set; it is similar to sortpack's inv_order but items most
64.        likely to be picked up are moved to the front */
65.     static char def_srt_order[MAXOCLASSES] = {
66.         COIN_CLASS, AMULET_CLASS, RING_CLASS, WAND_CLASS, POTION_CLASS,
67.         SCROLL_CLASS, SPBOOK_CLASS, GEM_CLASS, FOOD_CLASS, TOOL_CLASS,
68.         WEAPON_CLASS, ARMOR_CLASS, ROCK_CLASS, BALL_CLASS, CHAIN_CLASS, 0,
69.     };
70.     static char armcat[8];
71.     const char *classorder;
72.     char *p;
73.     int k, otyp = obj->otyp, oclass = obj->oclass;
74.     boolean seen, discovered = objects[otyp].oc_name_known ? TRUE : FALSE;
75. 
76.     /*
77.      * For the value types assigned by this classification, sortloot()
78.      * will put lower valued ones before higher valued ones.
79.      */
80.     if (!Blind)
81.         obj->dknown = 1; /* xname(obj) does this; we want it sooner */
82.     seen = obj->dknown ? TRUE : FALSE,
83.     /* class order */
84.     classorder = flags.sortpack ? flags.inv_order : def_srt_order;
85.     p = index(classorder, oclass);
86.     if (p)
87.         k = 1 + (int) (p - classorder);
88.     else
89.         k = 1 + (int) strlen(classorder) + (oclass != VENOM_CLASS);
90.     sort_item->orderclass = (xchar) k;
91.     /* subclass designation; only a few classes have subclasses
92.        and the non-armor ones we use are fairly arbitrary */
93.     switch (oclass) {
94.     case ARMOR_CLASS:
95.         if (!armcat[7]) {
96.             /* one-time init; we use a different order than the subclass
97.                values defined by objclass.h */
98.             armcat[ARM_HELM]   = 1; /* [2] */
99.             armcat[ARM_GLOVES] = 2; /* [3] */
100.             armcat[ARM_BOOTS]  = 3; /* [4] */
101.             armcat[ARM_SHIELD] = 4; /* [1] */
102.             armcat[ARM_CLOAK]  = 5; /* [5] */
103.             armcat[ARM_SHIRT]  = 6; /* [6] */
104.             armcat[ARM_SUIT]   = 7; /* [0] */
105.             armcat[7]          = 8; /* sanity protection */
106.         }
107.         k = objects[otyp].oc_armcat;
108.         /* oc_armcat overloads oc_subtyp which is an 'schar' so guard
109.            against somebody assigning something unexpected to it */
110.         if (k < 0 || k >= 7)
111.             k = 7;
112.         k = armcat[k];
113.         break;
114.     case WEAPON_CLASS:
115.         /* for weapons, group by ammo (arrows, bolts), launcher (bows),
116.            missile (darts, boomerangs), stackable (daggers, knives, spears),
117.            'other' (swords, axes, &c), polearms */
118.         k = objects[otyp].oc_skill;
119.         k = (k < 0) ? ((k >= -P_CROSSBOW && k <= -P_BOW) ? 1 : 3)
120.                     : ((k >= P_BOW && k <= P_CROSSBOW) ? 2
121.                        : (k == P_SPEAR || k == P_DAGGER || k == P_KNIFE) ? 4
122.                           : !is_pole(obj) ? 5 : 6);
123.         break;
124.     case TOOL_CLASS:
125.         if (seen && discovered
126.             && (otyp == BAG_OF_TRICKS || otyp == HORN_OF_PLENTY))
127.             k = 2; /* known pseudo-container */
128.         else if (Is_container(obj))
129.             k = 1; /* regular container or unknown bag of tricks */
130.         else
131.             switch (otyp) {
132.             case WOODEN_FLUTE:
133.             case MAGIC_FLUTE:
134.             case TOOLED_HORN:
135.             case FROST_HORN:
136.             case FIRE_HORN:
137.             case WOODEN_HARP:
138.             case MAGIC_HARP:
139.             case BUGLE:
140.             case LEATHER_DRUM:
141.             case DRUM_OF_EARTHQUAKE:
142.             case HORN_OF_PLENTY: /* not a musical instrument */
143.                 k = 3; /* instrument or unknown horn of plenty */
144.             default:
145.                 k = 4; /* 'other' tool */
146.             }
147.         break;
148.     case FOOD_CLASS:
149.         /* [what about separating "partly eaten" within each group?] */
150.         switch (otyp) {
151.         case SLIME_MOLD:
152.             k = 1;
153.             break;
154.         default:
155.             /* [maybe separate one-bite foods from rations and such?] */
156.             k = obj->globby ? 6 : 2;
157.             break;
158.         case TIN:
159.             k = 3;
160.             break;
161.         case EGG:
162.             k = 4;
163.             break;
164.         case CORPSE:
165.             k = 5;
166.             break;
167.         }
168.         break;
169.     case GEM_CLASS:
170.         /*
171.          * Normally subclass takes priority over discovery status, but
172.          * that would give away information for gems (assuming we'll
173.          * group them as valuable gems, next glass, then gray stones,
174.          * and finally rocks once they're all fully identified).
175.          *
176.          * Order:
177.          *  1) unseen gems and glass ("gem")
178.          *  2) seen but undiscovered gems and glass ("blue gem"),
179.          *  3) discovered gems ("sapphire"),
180.          *  4) discovered glass ("worthless pieced of blue glass"),
181.          *  5) unseen gray stones and rocks ("stone"),
182.          *  6) seen but undiscovered gray stones ("gray stone"),
183.          *  7) discovered gray stones ("touchstone"),
184.          *  8) seen rocks ("rock").
185.          */
186.         switch (objects[obj->otyp].oc_material) {
187.         case GEMSTONE:
188.             k = !seen ? 1 : !discovered ? 2 : 3;
189.             break;
190.         case GLASS:
191.             k = !seen ? 1 : !discovered ? 2 : 4;
192.             break;
193.         default: /* MINERAL */
194.             k = !seen ? 5 : (obj->otyp != ROCK) ? (!discovered ? 6 : 7) : 8;
195.             break;
196.         }
197.         break;
198.     default:
199.         /* other classes don't have subclasses; we assign a nonzero
200.            value because sortloot() uses 0 to mean 'not yet classified' */
201.         k = 1; /* any non-zero would do */
202.         break;
203.     }
204.     sort_item->subclass = (xchar) k;
205.     /* discovery status */
206.     k = !seen ? 1 /* unseen */
207.         : (discovered || !OBJ_DESCR(objects[otyp])) ? 4
208.           : (objects[otyp].oc_uname) ? 3 /* named (partially discovered) */
209.             : 2; /* undiscovered */
210.     sort_item->disco = (xchar) k;
211. }
212. 
213. /* sortloot() formatting routine; for alphabetizing, not shown to user */
214. STATIC_OVL char *
215. loot_xname(obj)
216. struct obj *obj;
217. {
218.     struct obj saveo;
219.     boolean save_debug;
220.     char *res, *save_oname;
221. 
222.     /*
223.      * Deal with things that xname() includes as a prefix.  We don't
224.      * want such because they change alphabetical ordering.  First,
225.      * remember 'obj's current settings.
226.      */
227.     saveo.odiluted = obj->odiluted;
228.     saveo.blessed = obj->blessed, saveo.cursed = obj->cursed;
229.     saveo.spe = obj->spe;
230.     saveo.owt = obj->owt;
231.     save_oname = has_oname(obj) ? ONAME(obj) : 0;
232.     save_debug = flags.debug;
233.     /* suppress "diluted" for potions and "holy/unholy" for water;
234.        sortloot() will deal with them using other criteria than name */
235.     if (obj->oclass == POTION_CLASS) {
236.         obj->odiluted = 0;
237.         if (obj->otyp == POT_WATER)
238.             obj->blessed = 0, obj->cursed = 0;
239.     }
240.     /* make "wet towel" and "moist towel" format as "towel" so that all
241.        three group together */
242.     if (obj->otyp == TOWEL)
243.         obj->spe = 0;
244.     /* group "<size> glob of <foo>" by <foo> rather than by <size> */
245.     if (obj->globby)
246.         obj->owt = 200; /* 200: weight of combined glob from ten creatures
247.                            (five or fewer is "small", more than fifteen is
248.                            "large", in between has no prefix) */
249.     /* suppress user-assigned name */
250.     if (save_oname && !obj->oartifact)
251.         ONAME(obj) = 0;
252.     /* avoid wizard mode formatting variations */
253.     if (wizard) { /* flags.debug */
254.         /* paranoia:  before toggling off wizard mode, guard against a
255.            panic in xname() producing a normal mode panic save file */
256.         program_state.something_worth_saving = 0;
257.         flags.debug = FALSE;
258.     }
259. 
260.     res = cxname_singular(obj);
261. 
262.     if (save_debug) {
263.         flags.debug = TRUE;
264.         program_state.something_worth_saving = 1;
265.     }
266.     /* restore the object */
267.     if (obj->oclass == POTION_CLASS) {
268.         obj->odiluted = saveo.odiluted;
269.         if (obj->otyp == POT_WATER)
270.             obj->blessed = saveo.blessed, obj->cursed = saveo.cursed;
271.     }
272.     if (obj->otyp == TOWEL) {
273.         obj->spe = saveo.spe;
274.         /* give "towel" a suffix that will force wet ones to come first,
275.            moist ones next, and dry ones last regardless of whether
276.            they've been flagged as having spe known */
277.         Strcat(res, is_wet_towel(obj) ? ((obj->spe >= 3) ? "x" : "y") : "z");
278.     }
279.     if (obj->globby) {
280.         obj->owt = saveo.owt;
281.         /* we've suppressed the size prefix (above); there normally won't
282.            be more than one of a given creature type because they coalesce,
283.            but globs with different bless/curse state won't merge so it is
284.            feasible to have multiple at the same location; add a suffix to
285.            get such sorted by size (small first) */
286.         Strcat(res, (obj->owt <= 100) ? "a"
287.                     : (obj->owt <= 300) ? "b"
288.                       : (obj->owt <= 500) ? "c"
289.                         : "d");
290.     }
291.     if (save_oname && !obj->oartifact)
292.         ONAME(obj) = save_oname;
293. 
294.     return res;
295. }
296. 
297. /* set by sortloot() for use by sortloot_cmp(); reset by sortloot when done */
298. static unsigned sortlootmode = 0;
299. 
300. /* qsort comparison routine for sortloot() */
301. STATIC_OVL int CFDECLSPEC
302. sortloot_cmp(vptr1, vptr2)
303. const genericptr vptr1;
304. const genericptr vptr2;
305. {
306.     struct sortloot_item *sli1 = (struct sortloot_item *) vptr1,
307.                          *sli2 = (struct sortloot_item *) vptr2;
308.     struct obj *obj1 = sli1->obj,
309.                *obj2 = sli2->obj;
310.     char *nam1, *nam2;
311.     int val1, val2, c, namcmp;
312. 
313.     /* order by object class unless we're doing by-invlet without sortpack */
314.     if ((sortlootmode & (SORTLOOT_PACK | SORTLOOT_INVLET))
315.         != SORTLOOT_INVLET) {
316.         /* Classify each object at most once no matter how many
317.            comparisons it is involved in. */
318.         if (!sli1->orderclass)
319.             loot_classify(sli1, obj1);
320.         if (!sli2->orderclass)
321.             loot_classify(sli2, obj2);
322. 
323.         /* Sort by class. */
324.         val1 = sli1->orderclass;
325.         val2 = sli2->orderclass;
326.         if (val1 != val2)
327.             return (int) (val1 - val2);
328. 
329.         /* skip sub-classes when ordering by sortpack+invlet */
330.         if ((sortlootmode & SORTLOOT_INVLET) == 0) {
331.             /* Class matches; sort by subclass. */
332.             val1 = sli1->subclass;
333.             val2 = sli2->subclass;
334.             if (val1 != val2)
335.                 return val1 - val2;
336. 
337.             /* Class and subclass match; sort by discovery status:
338.              * first unseen, then seen but not named or discovered,
339.              * then named, lastly discovered.
340.              * 1) potion
341.              * 2) pink potion
342.              * 3) dark green potion called confusion
343.              * 4) potion of healing
344.              * Multiple entries within each group will be put into
345.              * alphabetical order below.
346.              */
347.             val1 = sli1->disco;
348.             val2 = sli2->disco;
349.             if (val1 != val2)
350.                 return val1 - val2;
351.         }
352.     }
353. 
354.     /* order by assigned inventory letter */
355.     if ((sortlootmode & SORTLOOT_INVLET) != 0) {
356.         c = obj1->invlet;
357.         val1 = ('a' <= c && c <= 'z') ? (c - 'a' + 2)
358.                : ('A' <= c && c <= 'Z') ? (c - 'A' + 2 + 26)
359.                  : (c == '$') ? 1
360.                    : (c == '#') ? 1 + 52 + 1
361.                      : 1 + 52 + 1 + 1; /* none of the above */
362.         c = obj2->invlet;
363.         val2 = ('a' <= c && c <= 'z') ? (c - 'a' + 2)
364.                : ('A' <= c && c <= 'Z') ? (c - 'A' + 2 + 26)
365.                  : (c == '$') ? 1
366.                    : (c == '#') ? 1 + 52 + 1
367.                      : 1 + 52 + 1 + 1; /* none of the above */
368.         if (val1 != val2)
369.             return val1 - val2;
370.     }
371. 
372.     if ((sortlootmode & SORTLOOT_LOOT) == 0)
373.         goto tiebreak;
374. 
375.     /*
376.      * Sort object names in lexicographical order, ignoring quantity.
377.      *
378.      * Each obj gets formatted at most once (per sort) no matter how many
379.      * comparisons it gets subjected to.
380.      */
381.     nam1 = sli1->str;
382.     if (!nam1)
383.         nam1 = sli1->str = dupstr(loot_xname(obj1));
384.     nam2 = sli2->str;
385.     if (!nam2)
386.         nam2 = sli2->str = dupstr(loot_xname(obj2));
387.     if ((namcmp = strcmpi(nam1, nam2)) != 0)
388.         return namcmp;
389. 
390.     /* Sort by BUCX. */
391.     val1 = obj1->bknown ? (obj1->blessed ? 3 : !obj1->cursed ? 2 : 1) : 0;
392.     val2 = obj2->bknown ? (obj2->blessed ? 3 : !obj2->cursed ? 2 : 1) : 0;
393.     if (val1 != val2)
394.         return val2 - val1; /* bigger is better */
395. 
396.     /* Sort by greasing.  This will put the objects in degreasing order. */
397.     val1 = obj1->greased;
398.     val2 = obj2->greased;
399.     if (val1 != val2)
400.         return val2 - val1; /* bigger is better */
401. 
402.     /* Sort by erosion.  The effective amount is what matters. */
403.     val1 = greatest_erosion(obj1);
404.     val2 = greatest_erosion(obj2);
405.     if (val1 != val2)
406.         return val1 - val2; /* bigger is WORSE */
407. 
408.     /* Sort by erodeproofing.  Map known-invulnerable to 1, and both
409.        known-vulnerable and unknown-vulnerability to 0, because that's
410.        how they're displayed. */
411.     val1 = obj1->rknown && obj1->oerodeproof;
412.     val2 = obj2->rknown && obj2->oerodeproof;
413.     if (val1 != val2)
414.         return val2 - val1; /* bigger is better */
415. 
416.     /* Sort by enchantment.  Map unknown to -1000, which is comfortably
417.        below the range of obj->spe.  oc_uses_known means that obj->known
418.        matters, which usually indirectly means that obj->spe is relevant.
419.        Lots of objects use obj->spe for some other purpose (see obj.h). */
420.     if (objects[obj1->otyp].oc_uses_known
421.         /* exclude eggs (laid by you) and tins (homemade, pureed, &c) */
422.         && obj1->oclass != FOOD_CLASS) {
423.         val1 = obj1->known ? obj1->spe : -1000;
424.         val2 = obj2->known ? obj2->spe : -1000;
425.         if (val1 != val2)
426.             return val2 - val1; /* bigger is better */
427.     }
428. 
429.  tiebreak:
430.     /* They're identical, as far as we're concerned.  We want
431.        to force a deterministic order, and do so by producing a
432.        stable sort: maintain the original order of equal items. */
433.     return (sli1->indx - sli2->indx);
434. }
435. 
436. /*
437.  * sortloot() - the story so far...
438.  *
439.  *      The original implementation constructed and returned an array
440.  *      of pointers to objects in the requested order.  Callers had to
441.  *      count the number of objects, allocate the array, pass one
442.  *      object at a time to the routine which populates it, traverse
443.  *      the objects via stepping through the array, then free the
444.  *      array.  The ordering process used a basic insertion sort which
445.  *      is fine for short lists but inefficient for long ones.
446.  *
447.  *      3.6.0 (and continuing with 3.6.1) changed all that so that
448.  *      sortloot was self-contained as far as callers were concerned.
449.  *      It reordered the linked list into the requested order and then
450.  *      normal list traversal was used to process it.  It also switched
451.  *      to qsort() on the assumption that the C library implementation
452.  *      put some effort into sorting efficiently.  It also checked
453.  *      whether the list was already sorted as it got ready to do the
454.  *      sorting, so re-examining inventory or a pile of objects without
455.  *      having changed anything would gobble up less CPU than a full
456.  *      sort.  But it had at least two problems (aside from the ordinary
457.  *      complement of bugs):
458.  *      1) some players wanted to get the original order back when they
459.  *      changed the 'sortloot' option back to 'none', but the list
460.  *      reordering made that infeasible;
461.  *      2) object identification giving the 'ID whole pack' result
462.  *      would call makeknown() on each newly ID'd object, that would
463.  *      call update_inventory() to update the persistent inventory
464.  *      window if one existed, the interface would call the inventory
465.  *      display routine which would call sortloot() which might change
466.  *      the order of the list being traversed by the identify code,
467.  *      possibly skipping the ID of some objects.  That could have been
468.  *      avoided by suppressing 'perm_invent' during identification
469.  *      (fragile) or by avoiding sortloot() during inventory display
470.  *      (more robust).
471.  *
472.  *      3.6.2 reverts to the temporary array of ordered obj pointers
473.  *      but has sortloot() do the counting and allocation.  Callers
474.  *      need to use array traversal instead of linked list traversal
475.  *      and need to free the temporary array when done.  And the
476.  *      array contains 'struct sortloot_item' (aka 'Loot') entries
477.  *      instead of simple 'struct obj *' entries.
478.  */
479. Loot *
480. sortloot(olist, mode, by_nexthere, filterfunc)
481. struct obj **olist; /* previous version might have changed *olist, we don't */
482. unsigned mode; /* flags for sortloot_cmp() */
483. boolean by_nexthere; /* T: traverse via obj->nexthere, F: via obj->nobj */
484. boolean FDECL((*filterfunc), (OBJ_P));
485. {
486.     Loot *sliarray;
487.     struct obj *o;
488.     unsigned n, i;
489.     boolean augment_filter;
490. 
491.     for (n = 0, o = *olist; o; o = by_nexthere ? o->nexthere : o->nobj)
492.         ++n;
493.     /* note: if there is a filter function, this might overallocate */
494.     sliarray = (Loot *) alloc((n + 1) * sizeof *sliarray);
495. 
496.     /* the 'keep cockatrice corpses' flag is overloaded with sort mode */
497.     augment_filter = (mode & SORTLOOT_PETRIFY) ? TRUE : FALSE;
498.     mode &= ~SORTLOOT_PETRIFY; /* remove flag, leaving mode */
499.     /* populate aliarray[0..n-1] */
500.     for (i = 0, o = *olist; o; o = by_nexthere ? o->nexthere : o->nobj) {
501.         if (filterfunc && !(*filterfunc)(o)
502.             /* caller may be asking us to override filterfunc (in order
503.                to do a cockatrice corpse touch check during pickup even
504.                if/when the filter rejects food class) */
505.             && (!augment_filter || o->otyp != CORPSE
506.                 || !touch_petrifies(&mons[o->corpsenm])))
507.             continue;
508.         sliarray[i].obj = o, sliarray[i].indx = (int) i;
509.         sliarray[i].str = (char *) 0;
510.         sliarray[i].orderclass = sliarray[i].subclass = sliarray[i].disco = 0;
511.         ++i;
512.     }
513.     n = i;
514.     /* add a terminator so that we don't have to pass 'n' back to caller */
515.     sliarray[n].obj = (struct obj *) 0, sliarray[n].indx = -1;
516.     sliarray[n].str = (char *) 0;
517.     sliarray[n].orderclass = sliarray[n].subclass = sliarray[n].disco = 0;
518. 
519.     /* do the sort; if no sorting is requested, we'll just return
520.        a sortloot_item array reflecting the current ordering */
521.     if (mode && n > 1) {
522.         sortlootmode = mode; /* extra input for sortloot_cmp() */
523.         qsort((genericptr_t) sliarray, n, sizeof *sliarray, sortloot_cmp);
524.         sortlootmode = 0; /* reset static mode flags */
525.         /* if sortloot_cmp formatted any objects, discard their strings now */
526.         for (i = 0; i < n; ++i)
527.             if (sliarray[i].str)
528.                 free((genericptr_t) sliarray[i].str), sliarray[i].str = 0;
529.     }
530.     return sliarray;
531. }
532. 
533. /* sortloot() callers should use this to free up memory it allocates */
534. void
535. unsortloot(loot_array_p)
536. Loot **loot_array_p;
537. {
538.     if (*loot_array_p)
539.         free((genericptr_t) *loot_array_p), *loot_array_p = (Loot *) 0;
540. }
541. 
542. #if 0 /* 3.6.0 'revamp' */
543. void
544. sortloot(olist, mode, by_nexthere)
545. struct obj **olist;
546. unsigned mode; /* flags for sortloot_cmp() */
547. boolean by_nexthere; /* T: traverse via obj->nexthere, F: via obj->nobj */
548. {
549.     struct sortloot_item *sliarray, osli, nsli;
550.     struct obj *o, **nxt_p;
551.     unsigned n, i;
552.     boolean already_sorted = TRUE;
553. 
554.     sortlootmode = mode; /* extra input for sortloot_cmp() */
555.     for (n = osli.indx = 0, osli.obj = *olist; (o = osli.obj) != 0;
556.          osli = nsli) {
557.         nsli.obj = by_nexthere ? o->nexthere : o->nobj;
558.         nsli.indx = (int) ++n;
559.         if (nsli.obj && already_sorted
560.             && sortloot_cmp((genericptr_t) &osli, (genericptr_t) &nsli) > 0)
561.             already_sorted = FALSE;
562.     }
563.     if (n > 1 && !already_sorted) {
564.         sliarray = (struct sortloot_item *) alloc(n * sizeof *sliarray);
565.         for (i = 0, o = *olist; o;
566.              ++i, o = by_nexthere ? o->nexthere : o->nobj)
567.             sliarray[i].obj = o, sliarray[i].indx = (int) i;
568. 
569.         qsort((genericptr_t) sliarray, n, sizeof *sliarray, sortloot_cmp);
570.         for (i = 0; i < n; ++i) {
571.             o = sliarray[i].obj;
572.             nxt_p = by_nexthere ? &(o->nexthere) : &(o->nobj);
573.             *nxt_p = (i < n - 1) ? sliarray[i + 1].obj : (struct obj *) 0;
574.         }
575.         *olist = sliarray[0].obj;
576.         free((genericptr_t) sliarray);
577.     }
578.     sortlootmode = 0;
579. }
580. #endif /*0*/
581. 
582. void
583. assigninvlet(otmp)
584. register struct obj *otmp;
585. {
586.     boolean inuse[52];
587.     register int i;
588.     register struct obj *obj;
589. 
590.     /* there should be at most one of these in inventory... */
591.     if (otmp->oclass == COIN_CLASS) {
592.         otmp->invlet = GOLD_SYM;
593.         return;
594.     }
595. 
596.     for (i = 0; i < 52; i++)
597.         inuse[i] = FALSE;
598.     for (obj = invent; obj; obj = obj->nobj)
599.         if (obj != otmp) {
600.             i = obj->invlet;
601.             if ('a' <= i && i <= 'z')
602.                 inuse[i - 'a'] = TRUE;
603.             else if ('A' <= i && i <= 'Z')
604.                 inuse[i - 'A' + 26] = TRUE;
605.             if (i == otmp->invlet)
606.                 otmp->invlet = 0;
607.         }
608.     if ((i = otmp->invlet)
609.         && (('a' <= i && i <= 'z') || ('A' <= i && i <= 'Z')))
610.         return;
611.     for (i = lastinvnr + 1; i != lastinvnr; i++) {
612.         if (i == 52) {
613.             i = -1;
614.             continue;
615.         }
616.         if (!inuse[i])
617.             break;
618.     }
619.     otmp->invlet =
620.         (inuse[i] ? NOINVSYM : (i < 26) ? ('a' + i) : ('A' + i - 26));
621.     lastinvnr = i;
622. }
623. 
624. /* note: assumes ASCII; toggling a bit puts lowercase in front of uppercase */
625. #define inv_rank(o) ((o)->invlet ^ 040)
626. 
627. /* sort the inventory; used by addinv() and doorganize() */
628. STATIC_OVL void
629. reorder_invent()
630. {
631.     struct obj *otmp, *prev, *next;
632.     boolean need_more_sorting;
633. 
634.     do {
635.         /*
636.          * We expect at most one item to be out of order, so this
637.          * isn't nearly as inefficient as it may first appear.
638.          */
639.         need_more_sorting = FALSE;
640.         for (otmp = invent, prev = 0; otmp;) {
641.             next = otmp->nobj;
642.             if (next && inv_rank(next) < inv_rank(otmp)) {
643.                 need_more_sorting = TRUE;
644.                 if (prev)
645.                     prev->nobj = next;
646.                 else
647.                     invent = next;
648.                 otmp->nobj = next->nobj;
649.                 next->nobj = otmp;
650.                 prev = next;
651.             } else {
652.                 prev = otmp;
653.                 otmp = next;
654.             }
655.         }
656.     } while (need_more_sorting);
657. }
658. 
659. #undef inv_rank
660. 
661. /* scan a list of objects to see whether another object will merge with
662.    one of them; used in pickup.c when all 52 inventory slots are in use,
663.    to figure out whether another object could still be picked up */
664. struct obj *
665. merge_choice(objlist, obj)
666. struct obj *objlist, *obj;
667. {
668.     struct monst *shkp;
669.     int save_nocharge;
670. 
671.     if (obj->otyp == SCR_SCARE_MONSTER) /* punt on these */
672.         return (struct obj *) 0;
673.     /* if this is an item on the shop floor, the attributes it will
674.        have when carried are different from what they are now; prevent
675.        that from eliciting an incorrect result from mergable() */
676.     save_nocharge = obj->no_charge;
677.     if (objlist == invent && obj->where == OBJ_FLOOR
678.         && (shkp = shop_keeper(inside_shop(obj->ox, obj->oy))) != 0) {
679.         if (obj->no_charge)
680.             obj->no_charge = 0;
681.         /* A billable object won't have its `unpaid' bit set, so would
682.            erroneously seem to be a candidate to merge with a similar
683.            ordinary object.  That's no good, because once it's really
684.            picked up, it won't merge after all.  It might merge with
685.            another unpaid object, but we can't check that here (depends
686.            too much upon shk's bill) and if it doesn't merge it would
687.            end up in the '#' overflow inventory slot, so reject it now. */
688.         else if (inhishop(shkp))
689.             return (struct obj *) 0;
690.     }
691.     while (objlist) {
692.         if (mergable(objlist, obj))
693.             break;
694.         objlist = objlist->nobj;
695.     }
696.     obj->no_charge = save_nocharge;
697.     return objlist;
698. }
699. 
700. /* merge obj with otmp and delete obj if types agree */
701. int
702. merged(potmp, pobj)
703. struct obj **potmp, **pobj;
704. {
705.     register struct obj *otmp = *potmp, *obj = *pobj;
706. 
707.     if (mergable(otmp, obj)) {
708.         /* Approximate age: we do it this way because if we were to
709.          * do it "accurately" (merge only when ages are identical)
710.          * we'd wind up never merging any corpses.
711.          * otmp->age = otmp->age*(1-proportion) + obj->age*proportion;
712.          *
713.          * Don't do the age manipulation if lit.  We would need
714.          * to stop the burn on both items, then merge the age,
715.          * then restart the burn.  Glob ages are averaged in the
716.          * absorb routine, which uses weight rather than quantity
717.          * to adjust for proportion (glob quantity is always 1).
718.          */
719.         if (!obj->lamplit && !obj->globby)
720.             otmp->age = ((otmp->age * otmp->quan) + (obj->age * obj->quan))
721.                         / (otmp->quan + obj->quan);
722. 
723.         otmp->quan += obj->quan;
724.         /* temporary special case for gold objects!!!! */
725.         if (otmp->oclass == COIN_CLASS)
726.             otmp->owt = weight(otmp), otmp->bknown = 0;
727.         /* and puddings!!!1!!one! */
728.         else if (!Is_pudding(otmp))
729.             otmp->owt += obj->owt;
730.         if (!has_oname(otmp) && has_oname(obj))
731.             otmp = *potmp = oname(otmp, ONAME(obj));
732.         obj_extract_self(obj);
733. 
734.         /* really should merge the timeouts */
735.         if (obj->lamplit)
736.             obj_merge_light_sources(obj, otmp);
737.         if (obj->timed)
738.             obj_stop_timers(obj); /* follows lights */
739. 
740.         /* fixup for `#adjust' merging wielded darts, daggers, &c */
741.         if (obj->owornmask && carried(otmp)) {
742.             long wmask = otmp->owornmask | obj->owornmask;
743. 
744.             /* Both the items might be worn in competing slots;
745.                merger preference (regardless of which is which):
746.              primary weapon + alternate weapon -> primary weapon;
747.              primary weapon + quiver -> primary weapon;
748.              alternate weapon + quiver -> alternate weapon.
749.                (Prior to 3.3.0, it was not possible for the two
750.                stacks to be worn in different slots and `obj'
751.                didn't need to be unworn when merging.) */
752.             if (wmask & W_WEP)
753.                 wmask = W_WEP;
754.             else if (wmask & W_SWAPWEP)
755.                 wmask = W_SWAPWEP;
756.             else if (wmask & W_QUIVER)
757.                 wmask = W_QUIVER;
758.             else {
759.                 impossible("merging strangely worn items (%lx)", wmask);
760.                 wmask = otmp->owornmask;
761.             }
762.             if ((otmp->owornmask & ~wmask) != 0L)
763.                 setnotworn(otmp);
764.             setworn(otmp, wmask);
765.             setnotworn(obj);
766. #if 0
767.         /* (this should not be necessary, since items
768.             already in a monster's inventory don't ever get
769.             merged into other objects [only vice versa]) */
770.         } else if (obj->owornmask && mcarried(otmp)) {
771.             if (obj == MON_WEP(otmp->ocarry)) {
772.                 MON_WEP(otmp->ocarry) = otmp;
773.                 otmp->owornmask = W_WEP;
774.             }
775. #endif /*0*/
776.         }
777. 
778.         /* handle puddings a bit differently; absorption will free the
779.            other object automatically so we can just return out from here */
780.         if (obj->globby) {
781.             pudding_merge_message(otmp, obj);
782.             obj_absorb(potmp, pobj);
783.             return 1;
784.         }
785. 
786.         obfree(obj, otmp); /* free(obj), bill->otmp */
787.         return 1;
788.     }
789.     return 0;
790. }
791. 
792. /*
793.  * Adjust hero intrinsics as if this object was being added to the hero's
794.  * inventory.  Called _before_ the object has been added to the hero's
795.  * inventory.
796.  *
797.  * This is called when adding objects to the hero's inventory normally (via
798.  * addinv) or when an object in the hero's inventory has been polymorphed
799.  * in-place.
800.  *
801.  * It may be valid to merge this code with with addinv_core2().
802.  */
803. void
804. addinv_core1(obj)
805. struct obj *obj;
806. {
807.     if (obj->oclass == COIN_CLASS) {
808.         context.botl = 1;
809.     } else if (obj->otyp == AMULET_OF_YENDOR) {
810.         if (u.uhave.amulet)
811.             impossible("already have amulet?");
812.         u.uhave.amulet = 1;
813.         u.uachieve.amulet = 1;
814.     } else if (obj->otyp == CANDELABRUM_OF_INVOCATION) {
815.         if (u.uhave.menorah)
816.             impossible("already have candelabrum?");
817.         u.uhave.menorah = 1;
818.         u.uachieve.menorah = 1;
819.     } else if (obj->otyp == BELL_OF_OPENING) {
820.         if (u.uhave.bell)
821.             impossible("already have silver bell?");
822.         u.uhave.bell = 1;
823.         u.uachieve.bell = 1;
824.     } else if (obj->otyp == SPE_BOOK_OF_THE_DEAD) {
825.         if (u.uhave.book)
826.             impossible("already have the book?");
827.         u.uhave.book = 1;
828.         u.uachieve.book = 1;
829.     } else if (obj->oartifact) {
830.         if (is_quest_artifact(obj)) {
831.             if (u.uhave.questart)
832.                 impossible("already have quest artifact?");
833.             u.uhave.questart = 1;
834.             artitouch(obj);
835.         }
836.         set_artifact_intrinsic(obj, 1, W_ART);
837.     }
838. 
839.     /* "special achievements" aren't discoverable during play, they
840.        end up being recorded in XLOGFILE at end of game, nowhere else;
841.        record_achieve_special overloads corpsenm which is ordinarily
842.        initialized to NON_PM (-1) rather than to 0; any special prize
843.        must never be a corpse, egg, tin, figurine, or statue because
844.        their use of obj->corpsenm for monster type would conflict,
845.        nor be a leash (corpsenm overloaded for m_id of leashed
846.        monster) or a novel (corpsenm overloaded for novel index) */
847.     if (is_mines_prize(obj)) {
848.         u.uachieve.mines_luckstone = 1;
849.         obj->record_achieve_special = NON_PM;
850.         obj->nomerge = 0;
851.     } else if (is_soko_prize(obj)) {
852.         u.uachieve.finish_sokoban = 1;
853.         obj->record_achieve_special = NON_PM;
854.         obj->nomerge = 0;
855.     }
856. }
857. 
858. /*
859.  * Adjust hero intrinsics as if this object was being added to the hero's
860.  * inventory.  Called _after_ the object has been added to the hero's
861.  * inventory.
862.  *
863.  * This is called when adding objects to the hero's inventory normally (via
864.  * addinv) or when an object in the hero's inventory has been polymorphed
865.  * in-place.
866.  */
867. void
868. addinv_core2(obj)
869. struct obj *obj;
870. {
871.     if (confers_luck(obj)) {
872.         /* new luckstone must be in inventory by this point
873.          * for correct calculation */
874.         set_moreluck();
875.     }
876. }
877. 
878. /*
879.  * Add obj to the hero's inventory.  Make sure the object is "free".
880.  * Adjust hero attributes as necessary.
881.  */
882. struct obj *
883. addinv(obj)
884. struct obj *obj;
885. {
886.     struct obj *otmp, *prev;
887.     int saved_otyp = (int) obj->otyp; /* for panic */
888.     boolean obj_was_thrown;
889. 
890.     if (obj->where != OBJ_FREE)
891.         panic("addinv: obj not free");
892.     /* normally addtobill() clears no_charge when items in a shop are
893.        picked up, but won't do so if the shop has become untended */
894.     obj->no_charge = 0; /* should not be set in hero's invent */
895.     if (Has_contents(obj))
896.         picked_container(obj); /* clear no_charge */
897.     obj_was_thrown = obj->was_thrown;
898.     obj->was_thrown = 0;       /* not meaningful for invent */
899. 
900.     addinv_core1(obj);
901. 
902.     /* merge with quiver in preference to any other inventory slot
903.        in case quiver and wielded weapon are both eligible; adding
904.        extra to quivered stack is more useful than to wielded one */
905.     if (uquiver && merged(&uquiver, &obj)) {
906.         obj = uquiver;
907.         if (!obj)
908.             panic("addinv: null obj after quiver merge otyp=%d", saved_otyp);
909.         goto added;
910.     }
911.     /* merge if possible; find end of chain in the process */
912.     for (prev = 0, otmp = invent; otmp; prev = otmp, otmp = otmp->nobj)
913.         if (merged(&otmp, &obj)) {
914.             obj = otmp;
915.             if (!obj)
916.                 panic("addinv: null obj after merge otyp=%d", saved_otyp);
917.             goto added;
918.         }
919.     /* didn't merge, so insert into chain */
920.     assigninvlet(obj);
921.     if (flags.invlet_constant || !prev) {
922.         obj->nobj = invent; /* insert at beginning */
923.         invent = obj;
924.         if (flags.invlet_constant)
925.             reorder_invent();
926.     } else {
927.         prev->nobj = obj; /* insert at end */
928.         obj->nobj = 0;
929.     }
930.     obj->where = OBJ_INVENT;
931. 
932.     /* fill empty quiver if obj was thrown */
933.     if (flags.pickup_thrown && !uquiver && obj_was_thrown
934.         /* if Mjollnir is thrown and fails to return, we want to
935.            auto-pick it when we move to its spot, but not into quiver;
936.            aklyses behave like Mjollnir when thrown while wielded, but
937.            we lack sufficient information here make them exceptions */
938.         && obj->oartifact != ART_MJOLLNIR
939.         && (throwing_weapon(obj) || is_ammo(obj)))
940.         setuqwep(obj);
941.  added:
942.     addinv_core2(obj);
943.     carry_obj_effects(obj); /* carrying affects the obj */
944.     update_inventory();
945.     return obj;
946. }
947. 
948. /*
949.  * Some objects are affected by being carried.
950.  * Make those adjustments here. Called _after_ the object
951.  * has been added to the hero's or monster's inventory,
952.  * and after hero's intrinsics have been updated.
953.  */
954. void
955. carry_obj_effects(obj)
956. struct obj *obj;
957. {
958.     /* Cursed figurines can spontaneously transform when carried. */
959.     if (obj->otyp == FIGURINE) {
960.         if (obj->cursed && obj->corpsenm != NON_PM
961.             && !dead_species(obj->corpsenm, TRUE)) {
962.             attach_fig_transform_timeout(obj);
963.         }
964.     }
965. }
966. 
967. /* Add an item to the inventory unless we're fumbling or it refuses to be
968.  * held (via touch_artifact), and give a message.
969.  * If there aren't any free inventory slots, we'll drop it instead.
970.  * If both success and failure messages are NULL, then we're just doing the
971.  * fumbling/slot-limit checking for a silent grab.  In any case,
972.  * touch_artifact will print its own messages if they are warranted.
973.  */
974. struct obj *
975. hold_another_object(obj, drop_fmt, drop_arg, hold_msg)
976. struct obj *obj;
977. const char *drop_fmt, *drop_arg, *hold_msg;
978. {
979.     char buf[BUFSZ];
980. 
981.     if (!Blind)
982.         obj->dknown = 1; /* maximize mergibility */
983.     if (obj->oartifact) {
984.         /* place_object may change these */
985.         boolean crysknife = (obj->otyp == CRYSKNIFE);
986.         int oerode = obj->oerodeproof;
987.         boolean wasUpolyd = Upolyd;
988. 
989.         /* in case touching this object turns out to be fatal */
990.         place_object(obj, u.ux, u.uy);
991. 
992.         if (!touch_artifact(obj, &youmonst)) {
993.             obj_extract_self(obj); /* remove it from the floor */
994.             dropy(obj);            /* now put it back again :-) */
995.             return obj;
996.         } else if (wasUpolyd && !Upolyd) {
997.             /* loose your grip if you revert your form */
998.             if (drop_fmt)
999.                 pline(drop_fmt, drop_arg);
1000.             obj_extract_self(obj);
1001.             dropy(obj);
1002.             return obj;
1003.         }
1004.         obj_extract_self(obj);
1005.         if (crysknife) {
1006.             obj->otyp = CRYSKNIFE;
1007.             obj->oerodeproof = oerode;
1008.         }
1009.     }
1010.     if (Fumbling) {
1011.         obj->nomerge = 1;
1012.         obj = addinv(obj); /* dropping expects obj to be in invent */
1013.         goto drop_it;
1014.     } else {
1015.         long oquan = obj->quan;
1016.         int prev_encumbr = near_capacity(); /* before addinv() */
1017. 
1018.         /* encumbrance only matters if it would now become worse
1019.            than max( current_value, stressed ) */
1020.         if (prev_encumbr < MOD_ENCUMBER)
1021.             prev_encumbr = MOD_ENCUMBER;
1022.         /* addinv() may redraw the entire inventory, overwriting
1023.            drop_arg when it comes from something like doname() */
1024.         if (drop_arg)
1025.             drop_arg = strcpy(buf, drop_arg);
1026. 
1027.         obj = addinv(obj);
1028.         if (inv_cnt(FALSE) > 52 || ((obj->otyp != LOADSTONE || !obj->cursed)
1029.                                     && near_capacity() > prev_encumbr)) {
1030.             /* undo any merge which took place */
1031.             if (obj->quan > oquan)
1032.                 obj = splitobj(obj, oquan);
1033.             goto drop_it;
1034.         } else {
1035.             if (flags.autoquiver && !uquiver && !obj->owornmask
1036.                 && (is_missile(obj) || ammo_and_launcher(obj, uwep)
1037.                     || ammo_and_launcher(obj, uswapwep)))
1038.                 setuqwep(obj);
1039.             if (hold_msg || drop_fmt)
1040.                 prinv(hold_msg, obj, oquan);
1041.         }
1042.     }
1043.     return obj;
1044. 
1045.  drop_it:
1046.     if (drop_fmt)
1047.         pline(drop_fmt, drop_arg);
1048.     obj->nomerge = 0;
1049.     if (can_reach_floor(TRUE)) {
1050.         dropx(obj);
1051.     } else {
1052.         freeinv(obj);
1053.         hitfloor(obj, FALSE);
1054.     }
1055.     return (struct obj *) 0; /* might be gone */
1056. }
1057. 
1058. /* useup() all of an item regardless of its quantity */
1059. void
1060. useupall(obj)
1061. struct obj *obj;
1062. {
1063.     setnotworn(obj);
1064.     freeinv(obj);
1065.     obfree(obj, (struct obj *) 0); /* deletes contents also */
1066. }
1067. 
1068. void
1069. useup(obj)
1070. register struct obj *obj;
1071. {
1072.     /* Note:  This works correctly for containers because they (containers)
1073.        don't merge. */
1074.     if (obj->quan > 1L) {
1075.         obj->in_use = FALSE; /* no longer in use */
1076.         obj->quan--;
1077.         obj->owt = weight(obj);
1078.         update_inventory();
1079.     } else {
1080.         useupall(obj);
1081.     }
1082. }
1083. 
1084. /* use one charge from an item and possibly incur shop debt for it */
1085. void
1086. consume_obj_charge(obj, maybe_unpaid)
1087. struct obj *obj;
1088. boolean maybe_unpaid; /* false if caller handles shop billing */
1089. {
1090.     if (maybe_unpaid)
1091.         check_unpaid(obj);
1092.     obj->spe -= 1;
1093.     if (obj->known)
1094.         update_inventory();
1095. }
1096. 
1097. /*
1098.  * Adjust hero's attributes as if this object was being removed from the
1099.  * hero's inventory.  This should only be called from freeinv() and
1100.  * where we are polymorphing an object already in the hero's inventory.
1101.  *
1102.  * Should think of a better name...
1103.  */
1104. void
1105. freeinv_core(obj)
1106. struct obj *obj;
1107. {
1108.     if (obj->oclass == COIN_CLASS) {
1109.         context.botl = 1;
1110.         return;
1111.     } else if (obj->otyp == AMULET_OF_YENDOR) {
1112.         if (!u.uhave.amulet)
1113.             impossible("don't have amulet?");
1114.         u.uhave.amulet = 0;
1115.     } else if (obj->otyp == CANDELABRUM_OF_INVOCATION) {
1116.         if (!u.uhave.menorah)
1117.             impossible("don't have candelabrum?");
1118.         u.uhave.menorah = 0;
1119.     } else if (obj->otyp == BELL_OF_OPENING) {
1120.         if (!u.uhave.bell)
1121.             impossible("don't have silver bell?");
1122.         u.uhave.bell = 0;
1123.     } else if (obj->otyp == SPE_BOOK_OF_THE_DEAD) {
1124.         if (!u.uhave.book)
1125.             impossible("don't have the book?");
1126.         u.uhave.book = 0;
1127.     } else if (obj->oartifact) {
1128.         if (is_quest_artifact(obj)) {
1129.             if (!u.uhave.questart)
1130.                 impossible("don't have quest artifact?");
1131.             u.uhave.questart = 0;
1132.         }
1133.         set_artifact_intrinsic(obj, 0, W_ART);
1134.     }
1135. 
1136.     if (obj->otyp == LOADSTONE) {
1137.         curse(obj);
1138.     } else if (confers_luck(obj)) {
1139.         set_moreluck();
1140.         context.botl = 1;
1141.     } else if (obj->otyp == FIGURINE && obj->timed) {
1142.         (void) stop_timer(FIG_TRANSFORM, obj_to_any(obj));
1143.     }
1144. }
1145. 
1146. /* remove an object from the hero's inventory */
1147. void
1148. freeinv(obj)
1149. register struct obj *obj;
1150. {
1151.     extract_nobj(obj, &invent);
1152.     freeinv_core(obj);
1153.     update_inventory();
1154. }
1155. 
1156. void
1157. delallobj(x, y)
1158. int x, y;
1159. {
1160.     struct obj *otmp, *otmp2;
1161. 
1162.     for (otmp = level.objects[x][y]; otmp; otmp = otmp2) {
1163.         if (otmp == uball)
1164.             unpunish();
1165.         /* after unpunish(), or might get deallocated chain */
1166.         otmp2 = otmp->nexthere;
1167.         if (otmp == uchain)
1168.             continue;
1169.         delobj(otmp);
1170.     }
1171. }
1172. 
1173. /* destroy object in fobj chain (if unpaid, it remains on the bill) */
1174. void
1175. delobj(obj)
1176. register struct obj *obj;
1177. {
1178.     boolean update_map;
1179. 
1180.     if (obj->otyp == AMULET_OF_YENDOR
1181.         || obj->otyp == CANDELABRUM_OF_INVOCATION
1182.         || obj->otyp == BELL_OF_OPENING
1183.         || obj->otyp == SPE_BOOK_OF_THE_DEAD) {
1184.         /* player might be doing something stupid, but we
1185.          * can't guarantee that.  assume special artifacts
1186.          * are indestructible via drawbridges, and exploding
1187.          * chests, and golem creation, and ...
1188.          */
1189.         return;
1190.     }
1191.     update_map = (obj->where == OBJ_FLOOR);
1192.     obj_extract_self(obj);
1193.     if (update_map)
1194.         newsym(obj->ox, obj->oy);
1195.     obfree(obj, (struct obj *) 0); /* frees contents also */
1196. }
1197. 
1198. /* try to find a particular type of object at designated map location */
1199. struct obj *
1200. sobj_at(otyp, x, y)
1201. int otyp;
1202. int x, y;
1203. {
1204.     register struct obj *otmp;
1205. 
1206.     for (otmp = level.objects[x][y]; otmp; otmp = otmp->nexthere)
1207.         if (otmp->otyp == otyp)
1208.             break;
1209. 
1210.     return otmp;
1211. }
1212. 
1213. /* sobj_at(&c) traversal -- find next object of specified type */
1214. struct obj *
1215. nxtobj(obj, type, by_nexthere)
1216. struct obj *obj;
1217. int type;
1218. boolean by_nexthere;
1219. {
1220.     register struct obj *otmp;
1221. 
1222.     otmp = obj; /* start with the object after this one */
1223.     do {
1224.         otmp = !by_nexthere ? otmp->nobj : otmp->nexthere;
1225.         if (!otmp)
1226.             break;
1227.     } while (otmp->otyp != type);
1228. 
1229.     return otmp;
1230. }
1231. 
1232. struct obj *
1233. carrying(type)
1234. register int type;
1235. {
1236.     register struct obj *otmp;
1237. 
1238.     for (otmp = invent; otmp; otmp = otmp->nobj)
1239.         if (otmp->otyp == type)
1240.             return  otmp;
1241.     return (struct obj *) 0;
1242. }
1243. 
1244. /* Fictional and not-so-fictional currencies.
1245.  * http://concord.wikia.com/wiki/List_of_Fictional_Currencies
1246.  */
1247. static const char *const currencies[] = {
1248.     "Altarian Dollar",       /* The Hitchhiker's Guide to the Galaxy */
1249.     "Ankh-Morpork Dollar",   /* Discworld */
1250.     "auric",                 /* The Domination of Draka */
1251.     "buckazoid",             /* Space Quest */
1252.     "cirbozoid",             /* Starslip */
1253.     "credit chit",           /* Deus Ex */
1254.     "cubit",                 /* Battlestar Galactica */
1255.     "Flanian Pobble Bead",   /* The Hitchhiker's Guide to the Galaxy */
1256.     "fretzer",               /* Jules Verne */
1257.     "imperial credit",       /* Star Wars */
1258.     "Hong Kong Luna Dollar", /* The Moon is a Harsh Mistress */
1259.     "kongbuck",              /* Snow Crash */
1260.     "nanite",                /* System Shock 2 */
1261.     "quatloo",               /* Star Trek, Sim City */
1262.     "simoleon",              /* Sim City */
1263.     "solari",                /* Spaceballs */
1264.     "spacebuck",             /* Spaceballs */
1265.     "sporebuck",             /* Spore */
1266.     "Triganic Pu",           /* The Hitchhiker's Guide to the Galaxy */
1267.     "woolong",               /* Cowboy Bebop */
1268.     "zorkmid",               /* Zork, NetHack */
1269. };
1270. 
1271. const char *
1272. currency(amount)
1273. long amount;
1274. {
1275.     const char *res;
1276. 
1277.     res = Hallucination ? currencies[rn2(SIZE(currencies))] : "zorkmid";
1278.     if (amount != 1L)
1279.         res = makeplural(res);
1280.     return res;
1281. }
1282. 
1283. boolean
1284. have_lizard()
1285. {
1286.     register struct obj *otmp;
1287. 
1288.     for (otmp = invent; otmp; otmp = otmp->nobj)
1289.         if (otmp->otyp == CORPSE && otmp->corpsenm == PM_LIZARD)
1290.             return  TRUE;
1291.     return FALSE;
1292. }
1293. 
1294. /* 3.6 tribute */
1295. struct obj *
1296. u_have_novel()
1297. {
1298.     register struct obj *otmp;
1299. 
1300.     for (otmp = invent; otmp; otmp = otmp->nobj)
1301.         if (otmp->otyp == SPE_NOVEL)
1302.             return otmp;
1303.     return (struct obj *) 0;
1304. }
1305. 
1306. struct obj *
1307. o_on(id, objchn)
1308. unsigned int id;
1309. register struct obj *objchn;
1310. {
1311.     struct obj *temp;
1312. 
1313.     while (objchn) {
1314.         if (objchn->o_id == id)
1315.             return objchn;
1316.         if (Has_contents(objchn) && (temp = o_on(id, objchn->cobj)))
1317.             return temp;
1318.         objchn = objchn->nobj;
1319.     }
1320.     return (struct obj *) 0;
1321. }
1322. 
1323. boolean
1324. obj_here(obj, x, y)
1325. register struct obj *obj;
1326. int x, y;
1327. {
1328.     register struct obj *otmp;
1329. 
1330.     for (otmp = level.objects[x][y]; otmp; otmp = otmp->nexthere)
1331.         if (obj == otmp)
1332.             return TRUE;
1333.     return FALSE;
1334. }
1335. 
1336. struct obj *
1337. g_at(x, y)
1338. register int x, y;
1339. {
1340.     register struct obj *obj = level.objects[x][y];
1341. 
1342.     while (obj) {
1343.         if (obj->oclass == COIN_CLASS)
1344.             return obj;
1345.         obj = obj->nexthere;
1346.     }
1347.     return (struct obj *) 0;
1348. }
1349. 
1350. /* compact a string of inventory letters by dashing runs of letters */
1351. STATIC_OVL void
1352. compactify(buf)
1353. register char *buf;
1354. {
1355.     register int i1 = 1, i2 = 1;
1356.     register char ilet, ilet1, ilet2;
1357. 
1358.     ilet2 = buf[0];
1359.     ilet1 = buf[1];
1360.     buf[++i2] = buf[++i1];
1361.     ilet = buf[i1];
1362.     while (ilet) {
1363.         if (ilet == ilet1 + 1) {
1364.             if (ilet1 == ilet2 + 1)
1365.                 buf[i2 - 1] = ilet1 = '-';
1366.             else if (ilet2 == '-') {
1367.                 buf[i2 - 1] = ++ilet1;
1368.                 buf[i2] = buf[++i1];
1369.                 ilet = buf[i1];
1370.                 continue;
1371.             }
1372.         } else if (ilet == NOINVSYM) {
1373.             /* compact three or more consecutive '#'
1374.                characters into "#-#" */
1375.             if (i2 >= 2 && buf[i2 - 2] == NOINVSYM && buf[i2 - 1] == NOINVSYM)
1376.                 buf[i2 - 1] = '-';
1377.             else if (i2 >= 3 && buf[i2 - 3] == NOINVSYM && buf[i2 - 2] == '-'
1378.                      && buf[i2 - 1] == NOINVSYM)
1379.                 --i2;
1380.         }
1381.         ilet2 = ilet1;
1382.         ilet1 = ilet;
1383.         buf[++i2] = buf[++i1];
1384.         ilet = buf[i1];
1385.     }
1386. }
1387. 
1388. /* some objects shouldn't be split when count given to getobj or askchain */
1389. boolean
1390. splittable(obj)
1391. struct obj *obj;
1392. {
1393.     return !((obj->otyp == LOADSTONE && obj->cursed)
1394.              || (obj == uwep && welded(uwep)));
1395. }
1396. 
1397. /* match the prompt for either 'T' or 'R' command */
1398. STATIC_OVL boolean
1399. taking_off(action)
1400. const char *action;
1401. {
1402.     return !strcmp(action, "take off") || !strcmp(action, "remove");
1403. }
1404. 
1405. /* match the prompt for either 'W' or 'P' command */
1406. STATIC_OVL boolean
1407. putting_on(action)
1408. const char *action;
1409. {
1410.     return !strcmp(action, "wear") || !strcmp(action, "put on");
1411. }
1412. 
1413. /*
1414.  * getobj returns:
1415.  *      struct obj *xxx:        object to do something with.
1416.  *      (struct obj *) 0        error return: no object.
1417.  *      &zeroobj                explicitly no object (as in w-).
1418. !!!! test if gold can be used in unusual ways (eaten etc.)
1419. !!!! may be able to remove "usegold"
1420.  */
1421. struct obj *
1422. getobj(let, word)
1423. register const char *let, *word;
1424. {
1425.     register struct obj *otmp;
1426.     register char ilet = 0;
1427.     char buf[BUFSZ], qbuf[QBUFSZ];
1428.     char lets[BUFSZ], altlets[BUFSZ], *ap;
1429.     register int foo = 0;
1430.     register char *bp = buf;
1431.     xchar allowcnt = 0; /* 0, 1 or 2 */
1432.     boolean usegold = FALSE; /* can't use gold because its illegal */
1433.     boolean allowall = FALSE;
1434.     boolean allownone = FALSE;
1435.     boolean useboulder = FALSE;
1436.     xchar foox = 0;
1437.     long cnt;
1438.     boolean cntgiven = FALSE;
1439.     boolean msggiven = FALSE;
1440.     boolean oneloop = FALSE;
1441.     long dummymask;
1442.     Loot *sortedinvent, *srtinv;
1443. 
1444.     if (*let == ALLOW_COUNT)
1445.         let++, allowcnt = 1;
1446.     if (*let == COIN_CLASS)
1447.         let++, usegold = TRUE;
1448. 
1449.     /* Equivalent of an "ugly check" for gold */
1450.     if (usegold && !strcmp(word, "eat")
1451.         && (!metallivorous(youmonst.data)
1452.             || youmonst.data == &mons[PM_RUST_MONSTER]))
1453.         usegold = FALSE;
1454. 
1455.     if (*let == ALL_CLASSES)
1456.         let++, allowall = TRUE;
1457.     if (*let == ALLOW_NONE)
1458.         let++, allownone = TRUE;
1459.     /* "ugly check" for reading fortune cookies, part 1.
1460.      * The normal 'ugly check' keeps the object on the inventory list.
1461.      * We don't want to do that for shirts/cookies, so the check for
1462.      * them is handled a bit differently (and also requires that we set
1463.      * allowall in the caller).
1464.      */
1465.     if (allowall && !strcmp(word, "read"))
1466.         allowall = FALSE;
1467. 
1468.     /* another ugly check: show boulders (not statues) */
1469.     if (*let == WEAPON_CLASS && !strcmp(word, "throw")
1470.         && throws_rocks(youmonst.data))
1471.         useboulder = TRUE;
1472. 
1473.     if (allownone)
1474.         *bp++ = HANDS_SYM, *bp++ = ' '; /* '-' */
1475.     ap = altlets;
1476. 
1477.     if (!flags.invlet_constant)
1478.         reassign();
1479. 
1480.     /* force invent to be in invlet order before collecting candidate
1481.        inventory letters */
1482.     sortedinvent = sortloot(&invent, SORTLOOT_INVLET, FALSE,
1483.                             (boolean FDECL((*), (OBJ_P))) 0);
1484. 
1485.     for (srtinv = sortedinvent; (otmp = srtinv->obj) != 0; ++srtinv) {
1486.         if (&bp[foo] == &buf[sizeof buf - 1]
1487.             || ap == &altlets[sizeof altlets - 1]) {
1488.             /* we must have a huge number of NOINVSYM items somehow */
1489.             impossible("getobj: inventory overflow");
1490.             break;
1491.         }
1492. 
1493.         if (!*let || index(let, otmp->oclass)
1494.             || (usegold && otmp->invlet == GOLD_SYM)
1495.             || (useboulder && otmp->otyp == BOULDER)) {
1496.             register int otyp = otmp->otyp;
1497. 
1498.             bp[foo++] = otmp->invlet;
1499. /* clang-format off */
1500. /* *INDENT-OFF* */
1501.             /* ugly check: remove inappropriate things */
1502.             if (
1503.                 (taking_off(word) /* exclude if not worn */
1504.                  && !(otmp->owornmask & (W_ARMOR | W_ACCESSORY)))
1505.              || (putting_on(word) /* exclude if already worn */
1506.                  && (otmp->owornmask & (W_ARMOR | W_ACCESSORY)))
1507. #if 0 /* 3.4.1 -- include currently wielded weapon among 'wield' choices */
1508.              || (!strcmp(word, "wield")
1509.                  && (otmp->owornmask & W_WEP))
1510. #endif
1511.              || (!strcmp(word, "ready")    /* exclude when wielded... */
1512.                  && ((otmp == uwep || (otmp == uswapwep && u.twoweap))
1513.                      && otmp->quan == 1L)) /* ...unless more than one */
1514.              || ((!strcmp(word, "dip") || !strcmp(word, "grease"))
1515.                  && inaccessible_equipment(otmp, (const char *) 0, FALSE))
1516.              ) {
1517.                 foo--;
1518.                 foox++;
1519.             }
1520.             /* Second ugly check; unlike the first it won't trigger an
1521.              * "else" in "you don't have anything else to ___".
1522.              */
1523.             else if (
1524.                 (putting_on(word)
1525.                  && ((otmp->oclass == FOOD_CLASS && otmp->otyp != MEAT_RING)
1526.                      || (otmp->oclass == TOOL_CLASS && otyp != BLINDFOLD
1527.                          && otyp != TOWEL && otyp != LENSES)))
1528.              || (!strcmp(word, "wield")
1529.                  && (otmp->oclass == TOOL_CLASS && !is_weptool(otmp)))
1530.              || (!strcmp(word, "eat") && !is_edible(otmp))
1531.              || (!strcmp(word, "sacrifice")
1532.                  && (otyp != CORPSE && otyp != AMULET_OF_YENDOR
1533.                      && otyp != FAKE_AMULET_OF_YENDOR))
1534.              || (!strcmp(word, "write with")
1535.                  && (otmp->oclass == TOOL_CLASS
1536.                      && otyp != MAGIC_MARKER && otyp != TOWEL))
1537.              || (!strcmp(word, "tin")
1538.                  && (otyp != CORPSE || !tinnable(otmp)))
1539.              || (!strcmp(word, "rub")
1540.                  && ((otmp->oclass == TOOL_CLASS && otyp != OIL_LAMP
1541.                       && otyp != MAGIC_LAMP && otyp != BRASS_LANTERN)
1542.                      || (otmp->oclass == GEM_CLASS && !is_graystone(otmp))))
1543.              || (!strcmp(word, "use or apply")
1544.                  /* Picks, axes, pole-weapons, bullwhips */
1545.                  && ((otmp->oclass == WEAPON_CLASS
1546.                       && !is_pick(otmp) && !is_axe(otmp)
1547.                       && !is_pole(otmp) && otyp != BULLWHIP)
1548.                      || (otmp->oclass == POTION_CLASS
1549.                          /* only applicable potion is oil, and it will only
1550.                             be offered as a choice when already discovered */
1551.                          && (otyp != POT_OIL || !otmp->dknown
1552.                              || !objects[POT_OIL].oc_name_known))
1553.                      || (otmp->oclass == FOOD_CLASS
1554.                          && otyp != CREAM_PIE && otyp != EUCALYPTUS_LEAF)
1555.                      || (otmp->oclass == GEM_CLASS && !is_graystone(otmp))))
1556.              || (!strcmp(word, "invoke")
1557.                  && !otmp->oartifact
1558.                  && !objects[otyp].oc_unique
1559.                  && (otyp != FAKE_AMULET_OF_YENDOR || otmp->known)
1560.                  && otyp != CRYSTAL_BALL /* synonym for apply */
1561.                  /* note: presenting the possibility of invoking non-artifact
1562.                     mirrors and/or lamps is simply a cruel deception... */
1563.                  && otyp != MIRROR
1564.                  && otyp != MAGIC_LAMP
1565.                  && (otyp != OIL_LAMP /* don't list known oil lamp */
1566.                      || (otmp->dknown && objects[OIL_LAMP].oc_name_known)))
1567.              || (!strcmp(word, "untrap with")
1568.                  && ((otmp->oclass == TOOL_CLASS && otyp != CAN_OF_GREASE)
1569.                      || (otmp->oclass == POTION_CLASS
1570.                          /* only applicable potion is oil, and it will only
1571.                             be offered as a choice when already discovered */
1572.                          && (otyp != POT_OIL || !otmp->dknown
1573.                              || !objects[POT_OIL].oc_name_known))))
1574.              || (!strcmp(word, "tip") && !Is_container(otmp)
1575.                  /* include horn of plenty if sufficiently discovered */
1576.                  && (otmp->otyp != HORN_OF_PLENTY || !otmp->dknown
1577.                      || !objects[HORN_OF_PLENTY].oc_name_known))
1578.              || (!strcmp(word, "charge") && !is_chargeable(otmp))
1579.              || (!strcmp(word, "open") && otyp != TIN)
1580.              || (!strcmp(word, "call") && !objtyp_is_callable(otyp))
1581.              || (!strcmp(word, "adjust") && otmp->oclass == COIN_CLASS
1582.                  && !usegold)
1583.              ) {
1584.                 foo--;
1585.             }
1586.             /* Third ugly check:  acceptable but not listed as likely
1587.              * candidates in the prompt or in the inventory subset if
1588.              * player responds with '?'.
1589.              */
1590.             else if (
1591.              /* ugly check for unworn armor that can't be worn */
1592.                 (putting_on(word) && *let == ARMOR_CLASS
1593.                  && !canwearobj(otmp, &dummymask, FALSE))
1594.              /* or armor with 'P' or 'R' or accessory with 'W' or 'T' */
1595.              || ((putting_on(word) || taking_off(word))
1596.                  && ((*let == ARMOR_CLASS) ^ (otmp->oclass == ARMOR_CLASS)))
1597.              /* or unsuitable items rubbed on known touchstone */
1598.              || (!strncmp(word, "rub on the stone", 16)
1599.                  && *let == GEM_CLASS && otmp->dknown
1600.                  && objects[otyp].oc_name_known)
1601.              /* suppress corpses on astral, amulets elsewhere */
1602.              || (!strcmp(word, "sacrifice")
1603.                  /* (!astral && amulet) || (astral && !amulet) */
1604.                  && (!Is_astralevel(&u.uz) ^ (otmp->oclass != AMULET_CLASS)))
1605.              /* suppress container being stashed into */
1606.              || (!strcmp(word, "stash") && !ck_bag(otmp))
1607.              /* worn armor (shirt, suit) covered by worn armor (suit, cloak)
1608.                 or accessory (ring) covered by cursed worn armor (gloves) */
1609.              || (taking_off(word)
1610.                  && inaccessible_equipment(otmp, (const char *) 0,
1611.                                       (boolean) (otmp->oclass == RING_CLASS)))
1612.              || (!strcmp(word, "write on")
1613.                  && (!(otyp == SCR_BLANK_PAPER || otyp == SPE_BLANK_PAPER)
1614.                      || !otmp->dknown || !objects[otyp].oc_name_known))
1615.              ) {
1616.                 /* acceptable but not listed as likely candidate */
1617.                 foo--;
1618.                 allowall = TRUE;
1619.                 *ap++ = otmp->invlet;
1620.             }
1621. /* *INDENT-ON* */
1622. /* clang-format on */
1623.         } else {
1624.             /* "ugly check" for reading fortune cookies, part 2 */
1625.             if ((!strcmp(word, "read") && is_readable(otmp)))
1626.                 allowall = usegold = TRUE;
1627.         }
1628.     }
1629.     unsortloot(&sortedinvent);
1630. 
1631.     bp[foo] = 0;
1632.     if (foo == 0 && bp > buf && bp[-1] == ' ')
1633.         *--bp = 0;
1634.     Strcpy(lets, bp); /* necessary since we destroy buf */
1635.     if (foo > 5)      /* compactify string */
1636.         compactify(bp);
1637.     *ap = '\0';
1638. 
1639.     if (!foo && !allowall && !allownone) {
1640.         You("don't have anything %sto %s.", foox ? "else " : "", word);
1641.         return (struct obj *) 0;
1642.     } else if (!strcmp(word, "write on")) { /* ugly check for magic marker */
1643.         /* we wanted all scrolls and books in altlets[], but that came with
1644.            'allowall' which we don't want since it prevents "silly thing"
1645.            result if anything other than scroll or spellbook is chosen */
1646.         allowall = FALSE;
1647.     }
1648.     for (;;) {
1649.         cnt = 0;
1650.         cntgiven = FALSE;
1651.         Sprintf(qbuf, "What do you want to %s?", word);
1652.         if (in_doagain)
1653.             ilet = readchar();
1654.         else if (iflags.force_invmenu) {
1655.             /* don't overwrite a possible quitchars */
1656.             if (!oneloop)
1657.                 ilet = *let ? '?' : '*';
1658.             if (!msggiven)
1659.                 putmsghistory(qbuf, FALSE);
1660.             msggiven = TRUE;
1661.             oneloop = TRUE;
1662.         } else {
1663.             if (!buf[0])
1664.                 Strcat(qbuf, " [*]");
1665.             else
1666.                 Sprintf(eos(qbuf), " [%s or ?*]", buf);
1667.             ilet = yn_function(qbuf, (char *) 0, '\0');
1668.         }
1669.         if (digit(ilet)) {
1670.             long tmpcnt = 0;
1671. 
1672.             if (!allowcnt) {
1673.                 pline("No count allowed with this command.");
1674.                 continue;
1675.             }
1676.             ilet = get_count(NULL, ilet, LARGEST_INT, &tmpcnt, TRUE);
1677.             if (tmpcnt) {
1678.                 cnt = tmpcnt;
1679.                 cntgiven = TRUE;
1680.             }
1681.         }
1682.         if (index(quitchars, ilet)) {
1683.             if (flags.verbose)
1684.                 pline1(Never_mind);
1685.             return (struct obj *) 0;
1686.         }
1687.         if (ilet == HANDS_SYM) { /* '-' */
1688.             if (!allownone) {
1689.                 char *suf = (char *) 0;
1690. 
1691.                 strcpy(buf, word);
1692.                 if ((bp = strstr(buf, " on the ")) != 0) {
1693.                     /* rub on the stone[s] */
1694.                     *bp = '\0';
1695.                     suf = (bp + 1);
1696.                 }
1697.                 if ((bp = strstr(buf, " or ")) != 0) {
1698.                     *bp = '\0';
1699.                     bp = (rn2(2) ? buf : (bp + 4));
1700.                 } else
1701.                     bp = buf;
1702.                 You("mime %s something%s%s.", ing_suffix(bp), suf ? " " : "",
1703.                     suf ? suf : "");
1704.             }
1705.             return (allownone ? (struct obj *) &zeroobj : (struct obj *) 0);
1706.         }
1707.  redo_menu:
1708.         /* since gold is now kept in inventory, we need to do processing for
1709.            select-from-invent before checking whether gold has been picked */
1710.         if (ilet == '?' || ilet == '*') {
1711.             char *allowed_choices = (ilet == '?') ? lets : (char *) 0;
1712.             long ctmp = 0;
1713.             char menuquery[QBUFSZ];
1714. 
1715.             menuquery[0] = qbuf[0] = '\0';
1716.             if (iflags.force_invmenu)
1717.                 Sprintf(menuquery, "What do you want to %s?", word);
1718.             if (!strcmp(word, "grease"))
1719.                 Sprintf(qbuf, "your %s", makeplural(body_part(FINGER)));
1720.             else if (!strcmp(word, "write with"))
1721.                 Sprintf(qbuf, "your %s", body_part(FINGERTIP));
1722.             else if (!strcmp(word, "wield"))
1723.                 Sprintf(qbuf, "your %s %s%s", uarmg ? "gloved" : "bare",
1724.                         makeplural(body_part(HAND)),
1725.                         !uwep ? " (wielded)" : "");
1726.             else if (!strcmp(word, "ready"))
1727.                 Sprintf(qbuf, "empty quiver%s",
1728.                         !uquiver ? " (nothing readied)" : "");
1729. 
1730.             if (ilet == '?' && !*lets && *altlets)
1731.                 allowed_choices = altlets;
1732.             ilet = display_pickinv(allowed_choices, *qbuf ? qbuf : (char *) 0,
1733.                                    menuquery,
1734.                                    TRUE, allowcnt ? &ctmp : (long *) 0);
1735.             if (!ilet)
1736.                 continue;
1737.             if (ilet == HANDS_SYM)
1738.                 return (struct obj *) &zeroobj; /* cast away 'const' */
1739.             if (ilet == '\033') {
1740.                 if (flags.verbose)
1741.                     pline1(Never_mind);
1742.                 return (struct obj *) 0;
1743.             }
1744.             if (ilet == '*')
1745.                 goto redo_menu;
1746.             if (allowcnt && ctmp >= 0) {
1747.                 cnt = ctmp;
1748.                 cntgiven = TRUE;
1749.             }
1750.             /* they typed a letter (not a space) at the prompt */
1751.         }
1752.         /* find the item which was picked */
1753.         for (otmp = invent; otmp; otmp = otmp->nobj)
1754.             if (otmp->invlet == ilet)
1755.                 break;
1756.         /* some items have restrictions */
1757.         if (ilet == def_oc_syms[COIN_CLASS].sym
1758.             /* guard against the [hypothetical] chace of having more
1759.                than one invent slot of gold and picking the non-'$' one */
1760.             || (otmp && otmp->oclass == COIN_CLASS)) {
1761.             if (!usegold) {
1762.                 You("cannot %s gold.", word);
1763.                 return (struct obj *) 0;
1764.             }
1765.             /* Historic note: early Nethack had a bug which was
1766.              * first reported for Larn, where trying to drop 2^32-n
1767.              * gold pieces was allowed, and did interesting things
1768.              * to your money supply.  The LRS is the tax bureau
1769.              * from Larn.
1770.              */
1771.             if (cntgiven && cnt <= 0) {
1772.                 if (cnt < 0)
1773.                     pline_The(
1774.                   "LRS would be very interested to know you have that much.");
1775.                 return (struct obj *) 0;
1776.             }
1777.         }
1778.         if (cntgiven && !strcmp(word, "throw")) {
1779.             /* permit counts for throwing gold, but don't accept
1780.              * counts for other things since the throw code will
1781.              * split off a single item anyway */
1782.             if (cnt == 0)
1783.                 return (struct obj *) 0;
1784.             if (cnt > 1 && (ilet != def_oc_syms[COIN_CLASS].sym
1785.                 && !(otmp && otmp->oclass == COIN_CLASS))) {
1786.                 You("can only throw one item at a time.");
1787.                 continue;
1788.             }
1789.         }
1790.         context.botl = 1; /* May have changed the amount of money */
1791.         savech(ilet);
1792.         /* [we used to set otmp (by finding ilet in invent) here, but
1793.            that's been moved above so that otmp can be checked earlier] */
1794.         /* verify the chosen object */
1795.         if (!otmp) {
1796.             You("don't have that object.");
1797.             if (in_doagain)
1798.                 return (struct obj *) 0;
1799.             continue;
1800.         } else if (cnt < 0 || otmp->quan < cnt) {
1801.             You("don't have that many!  You have only %ld.", otmp->quan);
1802.             if (in_doagain)
1803.                 return (struct obj *) 0;
1804.             continue;
1805.         }
1806.         break;
1807.     }
1808.     if (!allowall && let && !index(let, otmp->oclass)
1809.         && !(usegold && otmp->oclass == COIN_CLASS)) {
1810.         silly_thing(word, otmp);
1811.         return (struct obj *) 0;
1812.     }
1813.     if (cntgiven) {
1814.         if (cnt == 0)
1815.             return (struct obj *) 0;
1816.         if (cnt != otmp->quan) {
1817.             /* don't split a stack of cursed loadstones */
1818.             if (splittable(otmp))
1819.                 otmp = splitobj(otmp, cnt);
1820.             else if (otmp->otyp == LOADSTONE && otmp->cursed)
1821.                 /* kludge for canletgo()'s can't-drop-this message */
1822.                 otmp->corpsenm = (int) cnt;
1823.         }
1824.     }
1825.     return otmp;
1826. }
1827. 
1828. void
1829. silly_thing(word, otmp)
1830. const char *word;
1831. struct obj *otmp;
1832. {
1833. #if 1 /* 'P','R' vs 'W','T' handling is obsolete */
1834.     nhUse(otmp);
1835. #else
1836.     const char *s1, *s2, *s3;
1837.     int ocls = otmp->oclass, otyp = otmp->otyp;
1838. 
1839.     s1 = s2 = s3 = 0;
1840.     /* check for attempted use of accessory commands ('P','R') on armor
1841.        and for corresponding armor commands ('W','T') on accessories */
1842.     if (ocls == ARMOR_CLASS) {
1843.         if (!strcmp(word, "put on"))
1844.             s1 = "W", s2 = "wear", s3 = "";
1845.         else if (!strcmp(word, "remove"))
1846.             s1 = "T", s2 = "take", s3 = " off";
1847.     } else if ((ocls == RING_CLASS || otyp == MEAT_RING)
1848.                || ocls == AMULET_CLASS
1849.                || (otyp == BLINDFOLD || otyp == TOWEL || otyp == LENSES)) {
1850.         if (!strcmp(word, "wear"))
1851.             s1 = "P", s2 = "put", s3 = " on";
1852.         else if (!strcmp(word, "take off"))
1853.             s1 = "R", s2 = "remove", s3 = "";
1854.     }
1855.     if (s1)
1856.         pline("Use the '%s' command to %s %s%s.", s1, s2,
1857.               !(is_plural(otmp) || pair_of(otmp)) ? "that" : "those", s3);
1858.     else
1859. #endif
1860.         pline(silly_thing_to, word);
1861. }
1862. 
1863. STATIC_PTR int
1864. ckvalidcat(otmp)
1865. struct obj *otmp;
1866. {
1867.     /* use allow_category() from pickup.c */
1868.     return (int) allow_category(otmp);
1869. }
1870. 
1871. STATIC_PTR int
1872. ckunpaid(otmp)
1873. struct obj *otmp;
1874. {
1875.     return (otmp->unpaid || (Has_contents(otmp) && count_unpaid(otmp->cobj)));
1876. }
1877. 
1878. boolean
1879. wearing_armor()
1880. {
1881.     return (boolean) (uarm || uarmc || uarmf || uarmg
1882.                       || uarmh || uarms || uarmu);
1883. }
1884. 
1885. boolean
1886. is_worn(otmp)
1887. struct obj *otmp;
1888. {
1889.     return (otmp->owornmask & (W_ARMOR | W_ACCESSORY | W_SADDLE | W_WEAPON))
1890.             ? TRUE
1891.             : FALSE;
1892. }
1893. 
1894. /* extra xprname() input that askchain() can't pass through safe_qbuf() */
1895. STATIC_VAR struct xprnctx {
1896.     char let;
1897.     boolean dot;
1898. } safeq_xprn_ctx;
1899. 
1900. /* safe_qbuf() -> short_oname() callback */
1901. STATIC_PTR char *
1902. safeq_xprname(obj)
1903. struct obj *obj;
1904. {
1905.     return xprname(obj, (char *) 0, safeq_xprn_ctx.let, safeq_xprn_ctx.dot,
1906.                    0L, 0L);
1907. }
1908. 
1909. /* alternate safe_qbuf() -> short_oname() callback */
1910. STATIC_PTR char *
1911. safeq_shortxprname(obj)
1912. struct obj *obj;
1913. {
1914.     return xprname(obj, ansimpleoname(obj), safeq_xprn_ctx.let,
1915.                    safeq_xprn_ctx.dot, 0L, 0L);
1916. }
1917. 
1918. static NEARDATA const char removeables[] = { ARMOR_CLASS, WEAPON_CLASS,
1919.                                              RING_CLASS,  AMULET_CLASS,
1920.                                              TOOL_CLASS,  0 };
1921. 
1922. /* Interactive version of getobj - used for Drop, Identify, and Takeoff (A).
1923.    Return the number of times fn was called successfully.
1924.    If combo is TRUE, we just use this to get a category list. */
1925. int
1926. ggetobj(word, fn, mx, combo, resultflags)
1927. const char *word;
1928. int FDECL((*fn), (OBJ_P)), mx;
1929. boolean combo; /* combination menu flag */
1930. unsigned *resultflags;
1931. {
1932.     int FDECL((*ckfn), (OBJ_P)) = (int FDECL((*), (OBJ_P))) 0;
1933.     boolean FDECL((*ofilter), (OBJ_P)) = (boolean FDECL((*), (OBJ_P))) 0;
1934.     boolean takeoff, ident, allflag, m_seen;
1935.     int itemcount;
1936.     int oletct, iletct, unpaid, oc_of_sym;
1937.     char sym, *ip, olets[MAXOCLASSES + 5], ilets[MAXOCLASSES + 10];
1938.     char extra_removeables[3 + 1]; /* uwep,uswapwep,uquiver */
1939.     char buf[BUFSZ] = DUMMY, qbuf[QBUFSZ];
1940. 
1941.     if (!invent) {
1942.         You("have nothing to %s.", word);
1943.         if (resultflags)
1944.             *resultflags = ALL_FINISHED;
1945.         return 0;
1946.     }
1947.     if (resultflags)
1948.         *resultflags = 0;
1949.     takeoff = ident = allflag = m_seen = FALSE;
1950.     add_valid_menu_class(0); /* reset */
1951.     if (taking_off(word)) {
1952.         takeoff = TRUE;
1953.         ofilter = is_worn;
1954.     } else if (!strcmp(word, "identify")) {
1955.         ident = TRUE;
1956.         ofilter = not_fully_identified;
1957.     }
1958. 
1959.     iletct = collect_obj_classes(ilets, invent, FALSE, ofilter, &itemcount);
1960.     unpaid = count_unpaid(invent);
1961. 
1962.     if (ident && !iletct) {
1963.         return -1; /* no further identifications */
1964.     } else if (invent) {
1965.         ilets[iletct++] = ' ';
1966.         if (unpaid)
1967.             ilets[iletct++] = 'u';
1968.         if (count_buc(invent, BUC_BLESSED, ofilter))
1969.             ilets[iletct++] = 'B';
1970.         if (count_buc(invent, BUC_UNCURSED, ofilter))
1971.             ilets[iletct++] = 'U';
1972.         if (count_buc(invent, BUC_CURSED, ofilter))
1973.             ilets[iletct++] = 'C';
1974.         if (count_buc(invent, BUC_UNKNOWN, ofilter))
1975.             ilets[iletct++] = 'X';
1976.         ilets[iletct++] = 'a';
1977.     }
1978.     ilets[iletct++] = 'i';
1979.     if (!combo)
1980.         ilets[iletct++] = 'm'; /* allow menu presentation on request */
1981.     ilets[iletct] = '\0';
1982. 
1983.     for (;;) {
1984.         Sprintf(qbuf, "What kinds of thing do you want to %s? [%s]",
1985.                 word, ilets);
1986.         getlin(qbuf, buf);
1987.         if (buf[0] == '\033')
1988.             return 0;
1989.         if (index(buf, 'i')) {
1990.             char ailets[1+26+26+1+5+1]; /* $ + a-z + A-Z + # + slop + \0 */
1991.             struct obj *otmp;
1992. 
1993.             /* applicable inventory letters; if empty, show entire invent */
1994.             ailets[0] = '\0';
1995.             if (ofilter)
1996.                 for (otmp = invent; otmp; otmp = otmp->nobj)
1997.                     /* index() check: limit overflow items to one '#' */
1998.                     if ((*ofilter)(otmp) && !index(ailets, otmp->invlet))
1999.                         (void) strkitten(ailets, otmp->invlet);
2000.             if (display_inventory(ailets, TRUE) == '\033')
2001.                 return 0;
2002.         } else
2003.             break;
2004.     }
2005. 
2006.     extra_removeables[0] = '\0';
2007.     if (takeoff) {
2008.         /* arbitrary types of items can be placed in the weapon slots
2009.            [any duplicate entries in extra_removeables[] won't matter] */
2010.         if (uwep)
2011.             (void) strkitten(extra_removeables, uwep->oclass);
2012.         if (uswapwep)
2013.             (void) strkitten(extra_removeables, uswapwep->oclass);
2014.         if (uquiver)
2015.             (void) strkitten(extra_removeables, uquiver->oclass);
2016.     }
2017. 
2018.     ip = buf;
2019.     olets[oletct = 0] = '\0';
2020.     while ((sym = *ip++) != '\0') {
2021.         if (sym == ' ')
2022.             continue;
2023.         oc_of_sym = def_char_to_objclass(sym);
2024.         if (takeoff && oc_of_sym != MAXOCLASSES) {
2025.             if (index(extra_removeables, oc_of_sym)) {
2026.                 ; /* skip rest of takeoff checks */
2027.             } else if (!index(removeables, oc_of_sym)) {
2028.                 pline("Not applicable.");
2029.                 return 0;
2030.             } else if (oc_of_sym == ARMOR_CLASS && !wearing_armor()) {
2031.                 noarmor(FALSE);
2032.                 return 0;
2033.             } else if (oc_of_sym == WEAPON_CLASS && !uwep && !uswapwep
2034.                        && !uquiver) {
2035.                 You("are not wielding anything.");
2036.                 return 0;
2037.             } else if (oc_of_sym == RING_CLASS && !uright && !uleft) {
2038.                 You("are not wearing rings.");
2039.                 return 0;
2040.             } else if (oc_of_sym == AMULET_CLASS && !uamul) {
2041.                 You("are not wearing an amulet.");
2042.                 return 0;
2043.             } else if (oc_of_sym == TOOL_CLASS && !ublindf) {
2044.                 You("are not wearing a blindfold.");
2045.                 return 0;
2046.             }
2047.         }
2048. 
2049.         if (oc_of_sym == COIN_CLASS && !combo) {
2050.             context.botl = 1;
2051.         } else if (sym == 'a') {
2052.             allflag = TRUE;
2053.         } else if (sym == 'A') {
2054.             ; /* same as the default */
2055.         } else if (sym == 'u') {
2056.             add_valid_menu_class('u');
2057.             ckfn = ckunpaid;
2058.         } else if (index("BUCX", sym)) {
2059.             add_valid_menu_class(sym); /* 'B','U','C',or 'X' */
2060.             ckfn = ckvalidcat;
2061.         } else if (sym == 'm') {
2062.             m_seen = TRUE;
2063.         } else if (oc_of_sym == MAXOCLASSES) {
2064.             You("don't have any %c's.", sym);
2065.         } else if (oc_of_sym != VENOM_CLASS) { /* suppress venom */
2066.             if (!index(olets, oc_of_sym)) {
2067.                 add_valid_menu_class(oc_of_sym);
2068.                 olets[oletct++] = oc_of_sym;
2069.                 olets[oletct] = 0;
2070.             }
2071.         }
2072.     }
2073. 
2074.     if (m_seen) {
2075.         return (allflag
2076.                 || (!oletct && ckfn != ckunpaid && ckfn != ckvalidcat))
2077.                ? -2 : -3;
2078.     } else if (flags.menu_style != MENU_TRADITIONAL && combo && !allflag) {
2079.         return 0;
2080. #if 0
2081.     /* !!!! test gold dropping */
2082.     } else if (allowgold == 2 && !oletct) {
2083.         return 1; /* you dropped gold (or at least tried to)  */
2084. #endif
2085.     } else {
2086.         int cnt = askchain(&invent, olets, allflag, fn, ckfn, mx, word);
2087.         /*
2088.          * askchain() has already finished the job in this case
2089.          * so set a special flag to convey that back to the caller
2090.          * so that it won't continue processing.
2091.          * Fix for bug C331-1 reported by Irina Rempt-Drijfhout.
2092.          */
2093.         if (combo && allflag && resultflags)
2094.             *resultflags |= ALL_FINISHED;
2095.         return cnt;
2096.     }
2097. }
2098. 
2099. /*
2100.  * Walk through the chain starting at objchn and ask for all objects
2101.  * with olet in olets (if nonNULL) and satisfying ckfn (if nonnull)
2102.  * whether the action in question (i.e., fn) has to be performed.
2103.  * If allflag then no questions are asked.  Mx gives the max number
2104.  * of objects to be treated.  Return the number of objects treated.
2105.  */
2106. int
2107. askchain(objchn, olets, allflag, fn, ckfn, mx, word)
2108. struct obj **objchn; /* *objchn might change */
2109. int allflag, mx;
2110. const char *olets, *word; /* olets is an Obj Class char array */
2111. int FDECL((*fn), (OBJ_P)), FDECL((*ckfn), (OBJ_P));
2112. {
2113.     struct obj *otmp, *otmpo;
2114.     register char sym, ilet;
2115.     int cnt = 0, dud = 0, tmp;
2116.     boolean takeoff, nodot, ident, take_out, put_in, first, ininv, bycat;
2117.     char qbuf[QBUFSZ], qpfx[QBUFSZ];
2118.     Loot *sortedchn = 0;
2119. 
2120.     takeoff = taking_off(word);
2121.     ident = !strcmp(word, "identify");
2122.     take_out = !strcmp(word, "take out");
2123.     put_in = !strcmp(word, "put in");
2124.     nodot = (!strcmp(word, "nodot") || !strcmp(word, "drop") || ident
2125.              || takeoff || take_out || put_in);
2126.     ininv = (*objchn == invent);
2127.     bycat = (menu_class_present('u')
2128.              || menu_class_present('B') || menu_class_present('U')
2129.              || menu_class_present('C') || menu_class_present('X'));
2130. 
2131.     /* someday maybe we'll sort by 'olets' too (temporarily replace
2132.        flags.packorder and pass SORTLOOT_PACK), but not yet... */
2133.     sortedchn = sortloot(objchn, SORTLOOT_INVLET, FALSE,
2134.                          (boolean FDECL((*), (OBJ_P))) 0);
2135. 
2136.     first = TRUE;
2137.     /*
2138.      * Interrogate in the object class order specified.
2139.      * For example, if a person specifies =/ then first all rings
2140.      * will be asked about followed by all wands.  -dgk
2141.      */
2142.  nextclass:
2143.     ilet = 'a' - 1;
2144.     if (*objchn && (*objchn)->oclass == COIN_CLASS)
2145.         ilet--;                     /* extra iteration */
2146.     /*
2147.      * Multiple Drop can change the invent chain while it operates
2148.      * (dropping a burning potion of oil while levitating creates
2149.      * an explosion which can destroy inventory items), so simple
2150.      * list traversal
2151.      *  for (otmp = *objchn; otmp; otmp = otmp2) {
2152.      *      otmp2 = otmp->nobj;
2153.      *      ...
2154.      *  }
2155.      * is inadequate here.  Use each object's bypass bit to keep
2156.      * track of which list elements have already been processed.
2157.      */
2158.     bypass_objlist(*objchn, FALSE); /* clear chain's bypass bits */
2159.     while ((otmp = nxt_unbypassed_loot(sortedchn, *objchn)) != 0) {
2160.         if (ilet == 'z')
2161.             ilet = 'A';
2162.         else if (ilet == 'Z')
2163.             ilet = NOINVSYM; /* '#' */
2164.         else
2165.             ilet++;
2166.         if (olets && *olets && otmp->oclass != *olets)
2167.             continue;
2168.         if (takeoff && !is_worn(otmp))
2169.             continue;
2170.         if (ident && !not_fully_identified(otmp))
2171.             continue;
2172.         if (ckfn && !(*ckfn)(otmp))
2173.             continue;
2174.         if (bycat && !ckvalidcat(otmp))
2175.             continue;
2176.         if (!allflag) {
2177.             safeq_xprn_ctx.let = ilet;
2178.             safeq_xprn_ctx.dot = !nodot;
2179.             *qpfx = '\0';
2180.             if (first) {
2181.                 /* traditional_loot() skips prompting when only one
2182.                    class of objects is involved, so prefix the first
2183.                    object being queried here with an explanation why */
2184.                 if (take_out || put_in)
2185.                     Sprintf(qpfx, "%s: ", word), *qpfx = highc(*qpfx);
2186.                 first = FALSE;
2187.             }
2188.             (void) safe_qbuf(qbuf, qpfx, "?", otmp,
2189.                              ininv ? safeq_xprname : doname,
2190.                              ininv ? safeq_shortxprname : ansimpleoname,
2191.                              "item");
2192.             sym = (takeoff || ident || otmp->quan < 2L) ? nyaq(qbuf)
2193.                                                         : nyNaq(qbuf);
2194.         } else
2195.             sym = 'y';
2196. 
2197.         otmpo = otmp;
2198.         if (sym == '#') {
2199.             /* Number was entered; split the object unless it corresponds
2200.                to 'none' or 'all'.  2 special cases: cursed loadstones and
2201.                welded weapons (eg, multiple daggers) will remain as merged
2202.                unit; done to avoid splitting an object that won't be
2203.                droppable (even if we're picking up rather than dropping). */
2204.             if (!yn_number) {
2205.                 sym = 'n';
2206.             } else {
2207.                 sym = 'y';
2208.                 if (yn_number < otmp->quan && splittable(otmp))
2209.                     otmp = splitobj(otmp, yn_number);
2210.             }
2211.         }
2212.         switch (sym) {
2213.         case 'a':
2214.             allflag = 1;
2215.             /*FALLTHRU*/
2216.         case 'y':
2217.             tmp = (*fn)(otmp);
2218.             if (tmp < 0) {
2219.                 if (container_gone(fn)) {
2220.                     /* otmp caused magic bag to explode;
2221.                        both are now gone */
2222.                     otmp = 0; /* and return */
2223.                 } else if (otmp && otmp != otmpo) {
2224.                     /* split occurred, merge again */
2225.                     (void) merged(&otmpo, &otmp);
2226.                 }
2227.                 goto ret;
2228.             }
2229.             cnt += tmp;
2230.             if (--mx == 0)
2231.                 goto ret;
2232.             /*FALLTHRU*/
2233.         case 'n':
2234.             if (nodot)
2235.                 dud++;
2236.         default:
2237.             break;
2238.         case 'q':
2239.             /* special case for seffects() */
2240.             if (ident)
2241.                 cnt = -1;
2242.             goto ret;
2243.         }
2244.     }
2245.     if (olets && *olets && *++olets)
2246.         goto nextclass;
2247. 
2248.     if (!takeoff && (dud || cnt))
2249.         pline("That was all.");
2250.     else if (!dud && !cnt)
2251.         pline("No applicable objects.");
2252.  ret:
2253.     unsortloot(&sortedchn);
2254.     bypass_objlist(*objchn, FALSE);
2255.     return cnt;
2256. }
2257. 
2258. /*
2259.  *      Object identification routines:
2260.  */
2261. 
2262. /* make an object actually be identified; no display updating */
2263. void
2264. fully_identify_obj(otmp)
2265. struct obj *otmp;
2266. {
2267.     makeknown(otmp->otyp);
2268.     if (otmp->oartifact)
2269.         discover_artifact((xchar) otmp->oartifact);
2270.     otmp->known = otmp->dknown = otmp->bknown = otmp->rknown = 1;
2271.     if (Is_container(otmp) || otmp->otyp == STATUE)
2272.         otmp->cknown = otmp->lknown = 1;
2273.     if (otmp->otyp == EGG && otmp->corpsenm != NON_PM)
2274.         learn_egg_type(otmp->corpsenm);
2275. }
2276. 
2277. /* ggetobj callback routine; identify an object and give immediate feedback */
2278. int
2279. identify(otmp)
2280. struct obj *otmp;
2281. {
2282.     fully_identify_obj(otmp);
2283.     prinv((char *) 0, otmp, 0L);
2284.     return 1;
2285. }
2286. 
2287. /* menu of unidentified objects; select and identify up to id_limit of them */
2288. STATIC_OVL void
2289. menu_identify(id_limit)
2290. int id_limit;
2291. {
2292.     menu_item *pick_list;
2293.     int n, i, first = 1, tryct = 5;
2294.     char buf[BUFSZ];
2295.     /* assumptions:  id_limit > 0 and at least one unID'd item is present */
2296. 
2297.     while (id_limit) {
2298.         Sprintf(buf, "What would you like to identify %s?",
2299.                 first ? "first" : "next");
2300.         n = query_objlist(buf, &invent, (SIGNAL_NOMENU | SIGNAL_ESCAPE
2301.                                          | USE_INVLET | INVORDER_SORT),
2302.                           &pick_list, PICK_ANY, not_fully_identified);
2303. 
2304.         if (n > 0) {
2305.             if (n > id_limit)
2306.                 n = id_limit;
2307.             for (i = 0; i < n; i++, id_limit--)
2308.                 (void) identify(pick_list[i].item.a_obj);
2309.             free((genericptr_t) pick_list);
2310.             mark_synch(); /* Before we loop to pop open another menu */
2311.             first = 0;
2312.         } else if (n == -2) { /* player used ESC to quit menu */
2313.             break;
2314.         } else if (n == -1) { /* no eligible items found */
2315.             pline("That was all.");
2316.             break;
2317.         } else if (!--tryct) { /* stop re-prompting */
2318.             pline1(thats_enough_tries);
2319.             break;
2320.         } else { /* try again */
2321.             pline("Choose an item; use ESC to decline.");
2322.         }
2323.     }
2324. }
2325. /* count the unidentified items */
2326. int
2327. count_unidentified(objchn)
2328. struct obj *objchn;
2329. {
2330.     int unid_cnt = 0;
2331.     struct obj *obj;
2332. 
2333.     for (obj = objchn; obj; obj = obj->nobj)
2334.         if (not_fully_identified(obj))
2335.             ++unid_cnt;
2336.     return unid_cnt;
2337. }
2338. 
2339. /* dialog with user to identify a given number of items; 0 means all */
2340. void
2341. identify_pack(id_limit, learning_id)
2342. int id_limit;
2343. boolean learning_id; /* true if we just read unknown identify scroll */
2344. {
2345.     struct obj *obj;
2346.     int n, unid_cnt = count_unidentified(invent);
2347. 
2348.     if (!unid_cnt) {
2349.         You("have already identified all %sof your possessions.",
2350.             learning_id ? "the rest " : "");
2351.     } else if (!id_limit || id_limit >= unid_cnt) {
2352.         /* identify everything */
2353.         /* TODO:  use fully_identify_obj and cornline/menu/whatever here */
2354.         for (obj = invent; obj; obj = obj->nobj) {
2355.             if (not_fully_identified(obj)) {
2356.                 (void) identify(obj);
2357.                 if (unid_cnt == 1)
2358.                     break;
2359.             }
2360.         }
2361.     } else {
2362.         /* identify up to `id_limit' items */
2363.         n = 0;
2364.         if (flags.menu_style == MENU_TRADITIONAL)
2365.             do {
2366.                 n = ggetobj("identify", identify, id_limit, FALSE,
2367.                             (unsigned *) 0);
2368.                 if (n < 0)
2369.                     break; /* quit or no eligible items */
2370.             } while ((id_limit -= n) > 0);
2371.         if (n == 0 || n < -1)
2372.             menu_identify(id_limit);
2373.     }
2374.     update_inventory();
2375. }
2376. 
2377. /* called when regaining sight; mark inventory objects which were picked
2378.    up while blind as now having been seen */
2379. void
2380. learn_unseen_invent()
2381. {
2382.     struct obj *otmp;
2383. 
2384.     if (Blind)
2385.         return; /* sanity check */
2386. 
2387.     for (otmp = invent; otmp; otmp = otmp->nobj) {
2388.         if (otmp->dknown)
2389.             continue; /* already seen */
2390.         /* set dknown, perhaps bknown (for priest[ess]) */
2391.         (void) xname(otmp);
2392.         /*
2393.          * If object->eknown gets implemented (see learnwand(zap.c)),
2394.          * handle deferred discovery here.
2395.          */
2396.     }
2397.     update_inventory();
2398. }
2399. 
2400. /* should of course only be called for things in invent */
2401. STATIC_OVL char
2402. obj_to_let(obj)
2403. struct obj *obj;
2404. {
2405.     if (!flags.invlet_constant) {
2406.         obj->invlet = NOINVSYM;
2407.         reassign();
2408.     }
2409.     return obj->invlet;
2410. }
2411. 
2412. /*
2413.  * Print the indicated quantity of the given object.  If quan == 0L then use
2414.  * the current quantity.
2415.  */
2416. void
2417. prinv(prefix, obj, quan)
2418. const char *prefix;
2419. struct obj *obj;
2420. long quan;
2421. {
2422.     if (!prefix)
2423.         prefix = "";
2424.     pline("%s%s%s", prefix, *prefix ? " " : "",
2425.           xprname(obj, (char *) 0, obj_to_let(obj), TRUE, 0L, quan));
2426. }
2427. 
2428. char *
2429. xprname(obj, txt, let, dot, cost, quan)
2430. struct obj *obj;
2431. const char *txt; /* text to print instead of obj */
2432. char let;        /* inventory letter */
2433. boolean dot;     /* append period; (dot && cost => Iu) */
2434. long cost;       /* cost (for inventory of unpaid or expended items) */
2435. long quan;       /* if non-0, print this quantity, not obj->quan */
2436. {
2437. #ifdef LINT /* handle static char li[BUFSZ]; */
2438.     char li[BUFSZ];
2439. #else
2440.     static char li[BUFSZ];
2441. #endif
2442.     boolean use_invlet = (flags.invlet_constant
2443.                           && let != CONTAINED_SYM && let != HANDS_SYM);
2444.     long savequan = 0;
2445. 
2446.     if (quan && obj) {
2447.         savequan = obj->quan;
2448.         obj->quan = quan;
2449.     }
2450.     /*
2451.      * If let is:
2452.      *  -  Then obj == null and 'txt' refers to hands or fingers.
2453.      *  *  Then obj == null and we are printing a total amount.
2454.      *  >  Then the object is contained and doesn't have an inventory letter.
2455.      */
2456.     if (cost != 0 || let == '*') {
2457.         /* if dot is true, we're doing Iu, otherwise Ix */
2458.         Sprintf(li,
2459.                 iflags.menu_tab_sep ? "%c - %s\t%6ld %s"
2460.                                     : "%c - %-45s %6ld %s",
2461.                 (dot && use_invlet ? obj->invlet : let),
2462.                 (txt ? txt : doname(obj)), cost, currency(cost));
2463.     } else {
2464.         /* ordinary inventory display or pickup message */
2465.         Sprintf(li, "%c - %s%s", (use_invlet ? obj->invlet : let),
2466.                 (txt ? txt : doname(obj)), (dot ? "." : ""));
2467.     }
2468.     if (savequan)
2469.         obj->quan = savequan;
2470. 
2471.     return li;
2472. }
2473. 
2474. /* the 'i' command */
2475. int
2476. ddoinv()
2477. {
2478.     (void) display_inventory((char *) 0, FALSE);
2479.     return 0;
2480. }
2481. 
2482. /*
2483.  * find_unpaid()
2484.  *
2485.  * Scan the given list of objects.  If last_found is NULL, return the first
2486.  * unpaid object found.  If last_found is not NULL, then skip over unpaid
2487.  * objects until last_found is reached, then set last_found to NULL so the
2488.  * next unpaid object is returned.  This routine recursively follows
2489.  * containers.
2490.  */
2491. STATIC_OVL struct obj *
2492. find_unpaid(list, last_found)
2493. struct obj *list, **last_found;
2494. {
2495.     struct obj *obj;
2496. 
2497.     while (list) {
2498.         if (list->unpaid) {
2499.             if (*last_found) {
2500.                 /* still looking for previous unpaid object */
2501.                 if (list == *last_found)
2502.                     *last_found = (struct obj *) 0;
2503.             } else
2504.                 return ((*last_found = list));
2505.         }
2506.         if (Has_contents(list)) {
2507.             if ((obj = find_unpaid(list->cobj, last_found)) != 0)
2508.                 return obj;
2509.         }
2510.         list = list->nobj;
2511.     }
2512.     return (struct obj *) 0;
2513. }
2514. 
2515. /* for perm_invent when operating on a partial inventory display, so that
2516.    the persistent one doesn't get shrunk during filtering for item selection
2517.    then regrown to full inventory, possibly being resized in the process */
2518. static winid cached_pickinv_win = WIN_ERR;
2519. 
2520. void
2521. free_pickinv_cache()
2522. {
2523.     if (cached_pickinv_win != WIN_ERR) {
2524.         destroy_nhwindow(cached_pickinv_win);
2525.         cached_pickinv_win = WIN_ERR;
2526.     }
2527. }
2528. 
2529. /*
2530.  * Internal function used by display_inventory and getobj that can display
2531.  * inventory and return a count as well as a letter. If out_cnt is not null,
2532.  * any count returned from the menu selection is placed here.
2533.  */
2534. STATIC_OVL char
2535. display_pickinv(lets, xtra_choice, query, want_reply, out_cnt)
2536. register const char *lets;
2537. const char *xtra_choice; /* "fingers", pick hands rather than an object */
2538. const char *query;
2539. boolean want_reply;
2540. long *out_cnt;
2541. {
2542.     static const char not_carrying_anything[] = "Not carrying anything";
2543.     struct obj *otmp, wizid_fakeobj;
2544.     char ilet, ret;
2545.     char *invlet = flags.inv_order;
2546.     int n, classcount;
2547.     winid win;                        /* windows being used */
2548.     anything any;
2549.     menu_item *selected;
2550.     unsigned sortflags;
2551.     Loot *sortedinvent, *srtinv;
2552.     boolean wizid = FALSE;
2553. 
2554.     if (lets && !*lets)
2555.         lets = 0; /* simplify tests: (lets) instead of (lets && *lets) */
2556. 
2557.     if (iflags.perm_invent && (lets || xtra_choice)) {
2558.         /* partial inventory in perm_invent setting; don't operate on
2559.            full inventory window, use an alternate one instead; create
2560.            the first time needed and keep it for re-use as needed later */
2561.         if (cached_pickinv_win == WIN_ERR)
2562.             cached_pickinv_win = create_nhwindow(NHW_MENU);
2563.         win = cached_pickinv_win;
2564.     } else
2565.         win = WIN_INVEN;
2566. 
2567.     /*
2568.      * Exit early if no inventory -- but keep going if we are doing
2569.      * a permanent inventory update.  We need to keep going so the
2570.      * permanent inventory window updates itself to remove the last
2571.      * item(s) dropped.  One down side:  the addition of the exception
2572.      * for permanent inventory window updates _can_ pop the window
2573.      * up when it's not displayed -- even if it's empty -- because we
2574.      * don't know at this level if its up or not.  This may not be
2575.      * an issue if empty checks are done before hand and the call
2576.      * to here is short circuited away.
2577.      *
2578.      * 2: our count here is only to distinguish between 0 and 1 and
2579.      * more than 1; for the last one, we don't need a precise number.
2580.      * For perm_invent update we force 'more than 1'.
2581.      */
2582.     n = (iflags.perm_invent && !lets && !want_reply) ? 2
2583.         : lets ? (int) strlen(lets)
2584.                : !invent ? 0 : !invent->nobj ? 1 : 2;
2585.     /* for xtra_choice, there's another 'item' not included in initial 'n';
2586.        for !lets (full invent) and for override_ID (wizard mode identify),
2587.        skip message_menu handling of single item even if item count was 1 */
2588.     if (xtra_choice || (n == 1 && (!lets || iflags.override_ID)))
2589.         ++n;
2590. 
2591.     if (n == 0) {
2592.         pline("%s.", not_carrying_anything);
2593.         return 0;
2594.     }
2595. 
2596.     /* oxymoron? temporarily assign permanent inventory letters */
2597.     if (!flags.invlet_constant)
2598.         reassign();
2599. 
2600.     if (n == 1 && !iflags.force_invmenu) {
2601.         /* when only one item of interest, use pline instead of menus;
2602.            we actually use a fake message-line menu in order to allow
2603.            the user to perform selection at the --More-- prompt for tty */
2604.         ret = '\0';
2605.         if (xtra_choice) {
2606.             /* xtra_choice is "bare hands" (wield), "fingertip" (Engrave),
2607.                "nothing" (ready Quiver), or "fingers" (apply grease) */
2608.             ret = message_menu(HANDS_SYM, PICK_ONE,
2609.                                xprname((struct obj *) 0, xtra_choice,
2610.                                        HANDS_SYM, TRUE, 0L, 0L)); /* '-' */
2611.         } else {
2612.             for (otmp = invent; otmp; otmp = otmp->nobj)
2613.                 if (!lets || otmp->invlet == lets[0])
2614.                     break;
2615.             if (otmp)
2616.                 ret = message_menu(otmp->invlet,
2617.                                    want_reply ? PICK_ONE : PICK_NONE,
2618.                                    xprname(otmp, (char *) 0, lets[0],
2619.                                            TRUE, 0L, 0L));
2620.         }
2621.         if (out_cnt)
2622.             *out_cnt = -1L; /* select all */
2623.         return ret;
2624.     }
2625. 
2626.     sortflags = (flags.sortloot == 'f') ? SORTLOOT_LOOT : SORTLOOT_INVLET;
2627.     if (flags.sortpack)
2628.         sortflags |= SORTLOOT_PACK;
2629.     sortedinvent = sortloot(&invent, sortflags, FALSE,
2630.                             (boolean FDECL((*), (OBJ_P))) 0);
2631. 
2632.     start_menu(win);
2633.     any = zeroany;
2634.     if (wizard && iflags.override_ID) {
2635.         int unid_cnt;
2636.         char prompt[QBUFSZ];
2637. 
2638.         unid_cnt = count_unidentified(invent);
2639.         Sprintf(prompt, "Debug Identify"); /* 'title' rather than 'prompt' */
2640.         if (unid_cnt)
2641.             Sprintf(eos(prompt),
2642.                     " -- unidentified or partially identified item%s",
2643.                     plur(unid_cnt));
2644.         add_menu(win, NO_GLYPH, &any, 0, 0, ATR_NONE, prompt, MENU_UNSELECTED);
2645.         if (!unid_cnt) {
2646.             add_menu(win, NO_GLYPH, &any, 0, 0, ATR_NONE,
2647.                      "(all items are permanently identified already)",
2648.                      MENU_UNSELECTED);
2649.         } else {
2650.             any.a_obj = &wizid_fakeobj;
2651.             Sprintf(prompt, "select %s to permanently identify",
2652.                     (unid_cnt == 1) ? "it": "any or all of them");
2653.             /* wiz_identify stuffed the wiz_identify command character (^I)
2654.                into iflags.override_ID for our use as an accelerator;
2655.                it could be ambiguous if player has assigned a letter to
2656.                the #wizidentify command */
2657.             if (unid_cnt > 1)
2658.                 Sprintf(eos(prompt), " (%s for all)",
2659.                         visctrl(iflags.override_ID));
2660.             add_menu(win, NO_GLYPH, &any, '_', iflags.override_ID, ATR_NONE,
2661.                      prompt, MENU_UNSELECTED);
2662.             wizid = TRUE;
2663.         }
2664.    } else if (xtra_choice) {
2665.         /* wizard override ID and xtra_choice are mutually exclusive */
2666.         if (flags.sortpack)
2667.             add_menu(win, NO_GLYPH, &any, 0, 0, iflags.menu_headings,
2668.                      "Miscellaneous", MENU_UNSELECTED);
2669.         any.a_char = HANDS_SYM; /* '-' */
2670.         add_menu(win, NO_GLYPH, &any, HANDS_SYM, 0, ATR_NONE,
2671.                  xtra_choice, MENU_UNSELECTED);
2672.     }
2673.  nextclass:
2674.     classcount = 0;
2675.     for (srtinv = sortedinvent; (otmp = srtinv->obj) != 0; ++srtinv) {
2676.         if (lets && !index(lets, otmp->invlet))
2677.             continue;
2678.         if (!flags.sortpack || otmp->oclass == *invlet) {
2679.             if (wizid && !not_fully_identified(otmp))
2680.                 continue;
2681.             any = zeroany; /* all bits zero */
2682.             ilet = otmp->invlet;
2683.             if (flags.sortpack && !classcount) {
2684.                 add_menu(win, NO_GLYPH, &any, 0, 0, iflags.menu_headings,
2685.                          let_to_name(*invlet, FALSE,
2686.                                      (want_reply && iflags.menu_head_objsym)),
2687.                          MENU_UNSELECTED);
2688.                 classcount++;
2689.             }
2690.             if (wizid)
2691.                 any.a_obj = otmp;
2692.             else
2693.                 any.a_char = ilet;
2694.             add_menu(win, obj_to_glyph(otmp, rn2_on_display_rng), &any, ilet,
2695.                      wizid ? def_oc_syms[(int) otmp->oclass].sym : 0,
2696.                      ATR_NONE, doname(otmp), MENU_UNSELECTED);
2697.         }
2698.     }
2699.     if (flags.sortpack) {
2700.         if (*++invlet)
2701.             goto nextclass;
2702.         if (--invlet != venom_inv) {
2703.             invlet = venom_inv;
2704.             goto nextclass;
2705.         }
2706.     }
2707.     if (iflags.force_invmenu && lets && want_reply) {
2708.         any = zeroany;
2709.         add_menu(win, NO_GLYPH, &any, 0, 0, iflags.menu_headings,
2710.                  "Special", MENU_UNSELECTED);
2711.         any.a_char = '*';
2712.         add_menu(win, NO_GLYPH, &any, '*', 0, ATR_NONE,
2713.                  "(list everything)", MENU_UNSELECTED);
2714.     }
2715.     unsortloot(&sortedinvent);
2716.     /* for permanent inventory where we intend to show everything but
2717.        nothing has been listed (because there isn't anyhing to list;
2718.        recognized via any.a_char still being zero; the n==0 case above
2719.        gets skipped for perm_invent), put something into the menu */
2720.     if (iflags.perm_invent && !lets && !any.a_char) {
2721.         any = zeroany;
2722.         add_menu(win, NO_GLYPH, &any, 0, 0, 0,
2723.                  not_carrying_anything, MENU_UNSELECTED);
2724.         want_reply = FALSE;
2725.     }
2726.     end_menu(win, query && *query ? query : (char *) 0);
2727. 
2728.     n = select_menu(win,
2729.                     wizid ? PICK_ANY : want_reply ? PICK_ONE : PICK_NONE,
2730.                     &selected);
2731.     if (n > 0) {
2732.         if (wizid) {
2733.             int i;
2734. 
2735.             ret = '\0';
2736.             for (i = 0; i < n; ++i) {
2737.                 otmp = selected[i].item.a_obj;
2738.                 if (otmp == &wizid_fakeobj) {
2739.                     identify_pack(0, FALSE);
2740.                 } else {
2741.                     if (not_fully_identified(otmp))
2742.                         (void) identify(otmp);
2743.                 }
2744.             }
2745.         } else {
2746.             ret = selected[0].item.a_char;
2747.             if (out_cnt)
2748.                 *out_cnt = selected[0].count;
2749.         }
2750.         free((genericptr_t) selected);
2751.     } else
2752.         ret = !n ? '\0' : '\033'; /* cancelled */
2753. 
2754.     return ret;
2755. }
2756. 
2757. /*
2758.  * If lets == NULL or "", list all objects in the inventory.  Otherwise,
2759.  * list all objects with object classes that match the order in lets.
2760.  *
2761.  * Returns the letter identifier of a selected item, or 0 if nothing
2762.  * was selected.
2763.  */
2764. char
2765. display_inventory(lets, want_reply)
2766. const char *lets;
2767. boolean want_reply;
2768. {
2769.     return display_pickinv(lets, (char *) 0, (char *) 0,
2770.                            want_reply, (long *) 0);
2771. }
2772. 
2773. /*
2774.  * Show what is current using inventory letters.
2775.  *
2776.  */
2777. STATIC_OVL char
2778. display_used_invlets(avoidlet)
2779. char avoidlet;
2780. {
2781.     struct obj *otmp;
2782.     char ilet, ret = 0;
2783.     char *invlet = flags.inv_order;
2784.     int n, classcount, invdone = 0;
2785.     winid win;
2786.     anything any;
2787.     menu_item *selected;
2788. 
2789.     if (invent) {
2790.         win = create_nhwindow(NHW_MENU);
2791.         start_menu(win);
2792.         while (!invdone) {
2793.             any = zeroany; /* set all bits to zero */
2794.             classcount = 0;
2795.             for (otmp = invent; otmp; otmp = otmp->nobj) {
2796.                 ilet = otmp->invlet;
2797.                 if (ilet == avoidlet)
2798.                     continue;
2799.                 if (!flags.sortpack || otmp->oclass == *invlet) {
2800.                     if (flags.sortpack && !classcount) {
2801.                         any = zeroany; /* zero */
2802.                         add_menu(win, NO_GLYPH, &any, 0, 0,
2803.                                  iflags.menu_headings,
2804.                                  let_to_name(*invlet, FALSE, FALSE),
2805.                                  MENU_UNSELECTED);
2806.                         classcount++;
2807.                     }
2808.                     any.a_char = ilet;
2809.                     add_menu(win, obj_to_glyph(otmp, rn2_on_display_rng),
2810.                              &any, ilet, 0, ATR_NONE,
2811.                              doname(otmp), MENU_UNSELECTED);
2812.                 }
2813.             }
2814.             if (flags.sortpack && *++invlet)
2815.                 continue;
2816.             invdone = 1;
2817.         }
2818.         end_menu(win, "Inventory letters used:");
2819. 
2820.         n = select_menu(win, PICK_ONE, &selected);
2821.         if (n > 0) {
2822.             ret = selected[0].item.a_char;
2823.             free((genericptr_t) selected);
2824.         } else
2825.             ret = !n ? '\0' : '\033'; /* cancelled */
2826.         destroy_nhwindow(win);
2827.     }
2828.     return ret;
2829. }
2830. 
2831. /*
2832.  * Returns the number of unpaid items within the given list.  This includes
2833.  * contained objects.
2834.  */
2835. int
2836. count_unpaid(list)
2837. struct obj *list;
2838. {
2839.     int count = 0;
2840. 
2841.     while (list) {
2842.         if (list->unpaid)
2843.             count++;
2844.         if (Has_contents(list))
2845.             count += count_unpaid(list->cobj);
2846.         list = list->nobj;
2847.     }
2848.     return count;
2849. }
2850. 
2851. /*
2852.  * Returns the number of items with b/u/c/unknown within the given list.
2853.  * This does NOT include contained objects.
2854.  *
2855.  * Assumes that the hero sees or touches or otherwise senses the objects
2856.  * at some point:  bknown is forced for priest[ess], like in xname().
2857.  */
2858. int
2859. count_buc(list, type, filterfunc)
2860. struct obj *list;
2861. int type;
2862. boolean FDECL((*filterfunc), (OBJ_P));
2863. {
2864.     int count = 0;
2865. 
2866.     for (; list; list = list->nobj) {
2867.         /* priests always know bless/curse state */
2868.         if (Role_if(PM_PRIEST))
2869.             list->bknown = (list->oclass != COIN_CLASS);
2870.         /* some actions exclude some or most items */
2871.         if (filterfunc && !(*filterfunc)(list))
2872.             continue;
2873. 
2874.         /* coins are either uncursed or unknown based upon option setting */
2875.         if (list->oclass == COIN_CLASS) {
2876.             if (type == (iflags.goldX ? BUC_UNKNOWN : BUC_UNCURSED))
2877.                 ++count;
2878.             continue;
2879.         }
2880.         /* check whether this object matches the requested type */
2881.         if (!list->bknown
2882.                 ? (type == BUC_UNKNOWN)
2883.                 : list->blessed ? (type == BUC_BLESSED)
2884.                                 : list->cursed ? (type == BUC_CURSED)
2885.                                                : (type == BUC_UNCURSED))
2886.             ++count;
2887.     }
2888.     return count;
2889. }
2890. 
2891. /* similar to count_buc(), but tallies all states at once
2892.    rather than looking for a specific type */
2893. void
2894. tally_BUCX(list, by_nexthere, bcp, ucp, ccp, xcp, ocp)
2895. struct obj *list;
2896. boolean by_nexthere;
2897. int *bcp, *ucp, *ccp, *xcp, *ocp;
2898. {
2899.     /* Future extensions:
2900.      *  Skip current_container when list is invent, uchain when
2901.      *  first object of list is located on the floor.  'ocp' will then
2902.      *  have a function again (it was a counter for having skipped gold,
2903.      *  but that's not skipped anymore).
2904.      */
2905.     *bcp = *ucp = *ccp = *xcp = *ocp = 0;
2906.     for ( ; list; list = (by_nexthere ? list->nexthere : list->nobj)) {
2907.         /* priests always know bless/curse state */
2908.         if (Role_if(PM_PRIEST))
2909.             list->bknown = (list->oclass != COIN_CLASS);
2910.         /* coins are either uncursed or unknown based upon option setting */
2911.         if (list->oclass == COIN_CLASS) {
2912.             if (iflags.goldX)
2913.                 ++(*xcp);
2914.             else
2915.                 ++(*ucp);
2916.             continue;
2917.         }
2918.         /* ordinary items */
2919.         if (!list->bknown)
2920.             ++(*xcp);
2921.         else if (list->blessed)
2922.             ++(*bcp);
2923.         else if (list->cursed)
2924.             ++(*ccp);
2925.         else /* neither blessed nor cursed => uncursed */
2926.             ++(*ucp);
2927.     }
2928. }
2929. 
2930. /* count everything inside a container, or just shop-owned items inside */
2931. long
2932. count_contents(container, nested, quantity, everything)
2933. struct obj *container;
2934. boolean nested, /* include contents of any nested containers */
2935.     quantity,   /* count all vs count separate stacks */
2936.     everything; /* all objects vs only unpaid objects */
2937. {
2938.     struct obj *otmp, *topc;
2939.     boolean shoppy = FALSE;
2940.     long count = 0L;
2941. 
2942.     if (!everything) {
2943.         for (topc = container; topc->where == OBJ_CONTAINED;
2944.              topc = topc->ocontainer)
2945.             continue;
2946.         if (topc->where == OBJ_FLOOR) {
2947.             xchar x, y;
2948. 
2949.             (void) get_obj_location(topc, &x, &y, CONTAINED_TOO);
2950.             shoppy = costly_spot(x, y);
2951.         }
2952.     }
2953.     for (otmp = container->cobj; otmp; otmp = otmp->nobj) {
2954.         if (nested && Has_contents(otmp))
2955.             count += count_contents(otmp, nested, quantity, everything);
2956.         if (everything || otmp->unpaid || (shoppy && !otmp->no_charge))
2957.             count += quantity ? otmp->quan : 1L;
2958.     }
2959.     return count;
2960. }
2961. 
2962. STATIC_OVL void
2963. dounpaid()
2964. {
2965.     winid win;
2966.     struct obj *otmp, *marker, *contnr;
2967.     register char ilet;
2968.     char *invlet = flags.inv_order;
2969.     int classcount, count, num_so_far;
2970.     long cost, totcost;
2971. 
2972.     count = count_unpaid(invent);
2973.     otmp = marker = contnr = (struct obj *) 0;
2974. 
2975.     if (count == 1) {
2976.         otmp = find_unpaid(invent, &marker);
2977.         contnr = unknwn_contnr_contents(otmp);
2978.     }
2979.     if  (otmp && !contnr) {
2980.         /* 1 item; use pline instead of popup menu */
2981.         cost = unpaid_cost(otmp, FALSE);
2982.         iflags.suppress_price++; /* suppress "(unpaid)" suffix */
2983.         pline1(xprname(otmp, distant_name(otmp, doname),
2984.                        carried(otmp) ? otmp->invlet : CONTAINED_SYM,
2985.                        TRUE, cost, 0L));
2986.         iflags.suppress_price--;
2987.         return;
2988.     }
2989. 
2990.     win = create_nhwindow(NHW_MENU);
2991.     cost = totcost = 0;
2992.     num_so_far = 0; /* count of # printed so far */
2993.     if (!flags.invlet_constant)
2994.         reassign();
2995. 
2996.     do {
2997.         classcount = 0;
2998.         for (otmp = invent; otmp; otmp = otmp->nobj) {
2999.             ilet = otmp->invlet;
3000.             if (otmp->unpaid) {
3001.                 if (!flags.sortpack || otmp->oclass == *invlet) {
3002.                     if (flags.sortpack && !classcount) {
3003.                         putstr(win, 0, let_to_name(*invlet, TRUE, FALSE));
3004.                         classcount++;
3005.                     }
3006. 
3007.                     totcost += cost = unpaid_cost(otmp, FALSE);
3008.                     iflags.suppress_price++; /* suppress "(unpaid)" suffix */
3009.                     putstr(win, 0, xprname(otmp, distant_name(otmp, doname),
3010.                                            ilet, TRUE, cost, 0L));
3011.                     iflags.suppress_price--;
3012.                     num_so_far++;
3013.                 }
3014.             }
3015.         }
3016.     } while (flags.sortpack && (*++invlet));
3017. 
3018.     if (count > num_so_far) {
3019.         /* something unpaid is contained */
3020.         if (flags.sortpack)
3021.             putstr(win, 0, let_to_name(CONTAINED_SYM, TRUE, FALSE));
3022.         /*
3023.          * Search through the container objects in the inventory for
3024.          * unpaid items.  The top level inventory items have already
3025.          * been listed.
3026.          */
3027.         for (otmp = invent; otmp; otmp = otmp->nobj) {
3028.             if (Has_contents(otmp)) {
3029.                 long contcost = 0L;
3030. 
3031.                 marker = (struct obj *) 0; /* haven't found any */
3032.                 while (find_unpaid(otmp->cobj, &marker)) {
3033.                     totcost += cost = unpaid_cost(marker, FALSE);
3034.                     contcost += cost;
3035.                     if (otmp->cknown) {
3036.                         iflags.suppress_price++; /* suppress "(unpaid)" sfx */
3037.                         putstr(win, 0,
3038.                                xprname(marker, distant_name(marker, doname),
3039.                                        CONTAINED_SYM, TRUE, cost, 0L));
3040.                         iflags.suppress_price--;
3041.                     }
3042.                 }
3043.                 if (!otmp->cknown) {
3044.                     char contbuf[BUFSZ];
3045. 
3046.                     /* Shopkeeper knows what to charge for contents */
3047.                     Sprintf(contbuf, "%s contents", s_suffix(xname(otmp)));
3048.                     putstr(win, 0,
3049.                            xprname((struct obj *) 0, contbuf, CONTAINED_SYM,
3050.                                    TRUE, contcost, 0L));
3051.                 }
3052.             }
3053.         }
3054.     }
3055. 
3056.     putstr(win, 0, "");
3057.     putstr(win, 0,
3058.            xprname((struct obj *) 0, "Total:", '*', FALSE, totcost, 0L));
3059.     display_nhwindow(win, FALSE);
3060.     destroy_nhwindow(win);
3061. }
3062. 
3063. /* query objlist callback: return TRUE if obj type matches "this_type" */
3064. static int this_type;
3065. 
3066. STATIC_OVL boolean
3067. this_type_only(obj)
3068. struct obj *obj;
3069. {
3070.     boolean res = (obj->oclass == this_type);
3071. 
3072.     if (obj->oclass == COIN_CLASS) {
3073.         /* if filtering by bless/curse state, gold is classified as
3074.            either unknown or uncursed based on user option setting */
3075.         if (this_type && index("BUCX", this_type))
3076.             res = (this_type == (iflags.goldX ? 'X' : 'U'));
3077.     } else {
3078.         switch (this_type) {
3079.         case 'B':
3080.             res = (obj->bknown && obj->blessed);
3081.             break;
3082.         case 'U':
3083.             res = (obj->bknown && !(obj->blessed || obj->cursed));
3084.             break;
3085.         case 'C':
3086.             res = (obj->bknown && obj->cursed);
3087.             break;
3088.         case 'X':
3089.             res = !obj->bknown;
3090.             break;
3091.         default:
3092.             break; /* use 'res' as-is */
3093.         }
3094.     }
3095.     return res;
3096. }
3097. 
3098. /* the 'I' command */
3099. int
3100. dotypeinv()
3101. {
3102.     char c = '\0';
3103.     int n, i = 0;
3104.     char *extra_types, types[BUFSZ];
3105.     int class_count, oclass, unpaid_count, itemcount;
3106.     int bcnt, ccnt, ucnt, xcnt, ocnt;
3107.     boolean billx = *u.ushops && doinvbill(0);
3108.     menu_item *pick_list;
3109.     boolean traditional = TRUE;
3110.     const char *prompt = "What type of object do you want an inventory of?";
3111. 
3112.     if (!invent && !billx) {
3113.         You("aren't carrying anything.");
3114.         return 0;
3115.     }
3116.     unpaid_count = count_unpaid(invent);
3117.     tally_BUCX(invent, FALSE, &bcnt, &ucnt, &ccnt, &xcnt, &ocnt);
3118. 
3119.     if (flags.menu_style != MENU_TRADITIONAL) {
3120.         if (flags.menu_style == MENU_FULL
3121.             || flags.menu_style == MENU_PARTIAL) {
3122.             traditional = FALSE;
3123.             i = UNPAID_TYPES;
3124.             if (billx)
3125.                 i |= BILLED_TYPES;
3126.             if (bcnt)
3127.                 i |= BUC_BLESSED;
3128.             if (ucnt)
3129.                 i |= BUC_UNCURSED;
3130.             if (ccnt)
3131.                 i |= BUC_CURSED;
3132.             if (xcnt)
3133.                 i |= BUC_UNKNOWN;
3134.             n = query_category(prompt, invent, i, &pick_list, PICK_ONE);
3135.             if (!n)
3136.                 return 0;
3137.             this_type = c = pick_list[0].item.a_int;
3138.             free((genericptr_t) pick_list);
3139.         }
3140.     }
3141.     if (traditional) {
3142.         /* collect a list of classes of objects carried, for use as a prompt
3143.          */
3144.         types[0] = 0;
3145.         class_count = collect_obj_classes(types, invent, FALSE,
3146.                                           (boolean FDECL((*), (OBJ_P))) 0,
3147.                                           &itemcount);
3148.         if (unpaid_count || billx || (bcnt + ccnt + ucnt + xcnt) != 0)
3149.             types[class_count++] = ' ';
3150.         if (unpaid_count)
3151.             types[class_count++] = 'u';
3152.         if (billx)
3153.             types[class_count++] = 'x';
3154.         if (bcnt)
3155.             types[class_count++] = 'B';
3156.         if (ucnt)
3157.             types[class_count++] = 'U';
3158.         if (ccnt)
3159.             types[class_count++] = 'C';
3160.         if (xcnt)
3161.             types[class_count++] = 'X';
3162.         types[class_count] = '\0';
3163.         /* add everything not already included; user won't see these */
3164.         extra_types = eos(types);
3165.         *extra_types++ = '\033';
3166.         if (!unpaid_count)
3167.             *extra_types++ = 'u';
3168.         if (!billx)
3169.             *extra_types++ = 'x';
3170.         if (!bcnt)
3171.             *extra_types++ = 'B';
3172.         if (!ucnt)
3173.             *extra_types++ = 'U';
3174.         if (!ccnt)
3175.             *extra_types++ = 'C';
3176.         if (!xcnt)
3177.             *extra_types++ = 'X';
3178.         *extra_types = '\0'; /* for index() */
3179.         for (i = 0; i < MAXOCLASSES; i++)
3180.             if (!index(types, def_oc_syms[i].sym)) {
3181.                 *extra_types++ = def_oc_syms[i].sym;
3182.                 *extra_types = '\0';
3183.             }
3184. 
3185.         if (class_count > 1) {
3186.             c = yn_function(prompt, types, '\0');
3187.             savech(c);
3188.             if (c == '\0') {
3189.                 clear_nhwindow(WIN_MESSAGE);
3190.                 return 0;
3191.             }
3192.         } else {
3193.             /* only one thing to itemize */
3194.             if (unpaid_count)
3195.                 c = 'u';
3196.             else if (billx)
3197.                 c = 'x';
3198.             else
3199.                 c = types[0];
3200.         }
3201.     }
3202.     if (c == 'x' || (c == 'X' && billx && !xcnt)) {
3203.         if (billx)
3204.             (void) doinvbill(1);
3205.         else
3206.             pline("No used-up objects%s.",
3207.                   unpaid_count ? " on your shopping bill" : "");
3208.         return 0;
3209.     }
3210.     if (c == 'u' || (c == 'U' && unpaid_count && !ucnt)) {
3211.         if (unpaid_count)
3212.             dounpaid();
3213.         else
3214.             You("are not carrying any unpaid objects.");
3215.         return 0;
3216.     }
3217.     if (traditional) {
3218.         if (index("BUCX", c))
3219.             oclass = c; /* not a class but understood by this_type_only() */
3220.         else
3221.             oclass = def_char_to_objclass(c); /* change to object class */
3222. 
3223.         if (oclass == COIN_CLASS)
3224.             return doprgold();
3225.         if (index(types, c) > index(types, '\033')) {
3226.             /* '> ESC' => hidden choice, something known not to be carried */
3227.             const char *before = "", *after = "";
3228. 
3229.             switch (c) {
3230.             case 'B':
3231.                 before = "known to be blessed ";
3232.                 break;
3233.             case 'U':
3234.                 before = "known to be uncursed ";
3235.                 break;
3236.             case 'C':
3237.                 before = "known to be cursed ";
3238.                 break;
3239.             case 'X':
3240.                 after = " whose blessed/uncursed/cursed status is unknown";
3241.                 break; /* better phrasing is desirable */
3242.             default:
3243.                 /* 'c' is an object class, because we've already handled
3244.                    all the non-class letters which were put into 'types[]';
3245.                    could/should move object class names[] array from below
3246.                    to somewhere above so that we can access it here (via
3247.                    lcase(strcpy(classnamebuf, names[(int) c]))), but the
3248.                    game-play value of doing so is low... */
3249.                 before = "such ";
3250.                 break;
3251.             }
3252.             You("have no %sobjects%s.", before, after);
3253.             return 0;
3254.         }
3255.         this_type = oclass;
3256.     }
3257.     if (query_objlist((char *) 0, &invent,
3258.                       ((flags.invlet_constant ? USE_INVLET : 0)
3259.                        | INVORDER_SORT),
3260.                       &pick_list, PICK_NONE, this_type_only) > 0)
3261.         free((genericptr_t) pick_list);
3262.     return 0;
3263. }
3264. 
3265. /* return a string describing the dungeon feature at <x,y> if there
3266.    is one worth mentioning at that location; otherwise null */
3267. const char *
3268. dfeature_at(x, y, buf)
3269. int x, y;
3270. char *buf;
3271. {
3272.     struct rm *lev = &levl[x][y];
3273.     int ltyp = lev->typ, cmap = -1;
3274.     const char *dfeature = 0;
3275.     static char altbuf[BUFSZ];
3276. 
3277.     if (IS_DOOR(ltyp)) {
3278.         switch (lev->doormask) {
3279.         case D_NODOOR:
3280.             cmap = S_ndoor;
3281.             break; /* "doorway" */
3282.         case D_ISOPEN:
3283.             cmap = S_vodoor;
3284.             break; /* "open door" */
3285.         case D_BROKEN:
3286.             dfeature = "broken door";
3287.             break;
3288.         default:
3289.             cmap = S_vcdoor;
3290.             break; /* "closed door" */
3291.         }
3292.         /* override door description for open drawbridge */
3293.         if (is_drawbridge_wall(x, y) >= 0)
3294.             dfeature = "open drawbridge portcullis", cmap = -1;
3295.     } else if (IS_FOUNTAIN(ltyp))
3296.         cmap = S_fountain; /* "fountain" */
3297.     else if (IS_THRONE(ltyp))
3298.         cmap = S_throne; /* "opulent throne" */
3299.     else if (is_lava(x, y))
3300.         cmap = S_lava; /* "molten lava" */
3301.     else if (is_ice(x, y))
3302.         cmap = S_ice; /* "ice" */
3303.     else if (is_pool(x, y))
3304.         dfeature = "pool of water";
3305.     else if (IS_SINK(ltyp))
3306.         cmap = S_sink; /* "sink" */
3307.     else if (IS_ALTAR(ltyp)) {
3308.         Sprintf(altbuf, "%saltar to %s (%s)",
3309.                 ((lev->altarmask & AM_SHRINE)
3310.                  && (Is_astralevel(&u.uz) || Is_sanctum(&u.uz)))
3311.                     ? "high "
3312.                     : "",
3313.                 a_gname(),
3314.                 align_str(Amask2align(lev->altarmask & ~AM_SHRINE)));
3315.         dfeature = altbuf;
3316.     } else if ((x == xupstair && y == yupstair)
3317.                || (x == sstairs.sx && y == sstairs.sy && sstairs.up))
3318.         cmap = S_upstair; /* "staircase up" */
3319.     else if ((x == xdnstair && y == ydnstair)
3320.              || (x == sstairs.sx && y == sstairs.sy && !sstairs.up))
3321.         cmap = S_dnstair; /* "staircase down" */
3322.     else if (x == xupladder && y == yupladder)
3323.         cmap = S_upladder; /* "ladder up" */
3324.     else if (x == xdnladder && y == ydnladder)
3325.         cmap = S_dnladder; /* "ladder down" */
3326.     else if (ltyp == DRAWBRIDGE_DOWN)
3327.         cmap = S_vodbridge; /* "lowered drawbridge" */
3328.     else if (ltyp == DBWALL)
3329.         cmap = S_vcdbridge; /* "raised drawbridge" */
3330.     else if (IS_GRAVE(ltyp))
3331.         cmap = S_grave; /* "grave" */
3332.     else if (ltyp == TREE)
3333.         cmap = S_tree; /* "tree" */
3334.     else if (ltyp == IRONBARS)
3335.         dfeature = "set of iron bars";
3336. 
3337.     if (cmap >= 0)
3338.         dfeature = defsyms[cmap].explanation;
3339.     if (dfeature)
3340.         Strcpy(buf, dfeature);
3341.     return dfeature;
3342. }
3343. 
3344. /* look at what is here; if there are many objects (pile_limit or more),
3345.    don't show them unless obj_cnt is 0 */
3346. int
3347. look_here(obj_cnt, picked_some)
3348. int obj_cnt; /* obj_cnt > 0 implies that autopickup is in progress */
3349. boolean picked_some;
3350. {
3351.     struct obj *otmp;
3352.     struct trap *trap;
3353.     const char *verb = Blind ? "feel" : "see";
3354.     const char *dfeature = (char *) 0;
3355.     char fbuf[BUFSZ], fbuf2[BUFSZ];
3356.     winid tmpwin;
3357.     boolean skip_objects, felt_cockatrice = FALSE;
3358. 
3359.     /* default pile_limit is 5; a value of 0 means "never skip"
3360.        (and 1 effectively forces "always skip") */
3361.     skip_objects = (flags.pile_limit > 0 && obj_cnt >= flags.pile_limit);
3362.     if (u.uswallow && u.ustuck) {
3363.         struct monst *mtmp = u.ustuck;
3364. 
3365.         Sprintf(fbuf, "Contents of %s %s", s_suffix(mon_nam(mtmp)),
3366.                 mbodypart(mtmp, STOMACH));
3367.         /* Skip "Contents of " by using fbuf index 12 */
3368.         You("%s to %s what is lying in %s.", Blind ? "try" : "look around",
3369.             verb, &fbuf[12]);
3370.         otmp = mtmp->minvent;
3371.         if (otmp) {
3372.             for (; otmp; otmp = otmp->nobj) {
3373.                 /* If swallower is an animal, it should have become stone
3374.                  * but... */
3375.                 if (otmp->otyp == CORPSE)
3376.                     feel_cockatrice(otmp, FALSE);
3377.             }
3378.             if (Blind)
3379.                 Strcpy(fbuf, "You feel");
3380.             Strcat(fbuf, ":");
3381.             (void) display_minventory(mtmp, MINV_ALL | PICK_NONE, fbuf);
3382.         } else {
3383.             You("%s no objects here.", verb);
3384.         }
3385.         return !!Blind;
3386.     }
3387.     if (!skip_objects && (trap = t_at(u.ux, u.uy)) && trap->tseen)
3388.         There("is %s here.",
3389.               an(defsyms[trap_to_defsym(trap->ttyp)].explanation));
3390. 
3391.     otmp = level.objects[u.ux][u.uy];
3392.     dfeature = dfeature_at(u.ux, u.uy, fbuf2);
3393.     if (dfeature && !strcmp(dfeature, "pool of water") && Underwater)
3394.         dfeature = 0;
3395. 
3396.     if (Blind) {
3397.         boolean drift = Is_airlevel(&u.uz) || Is_waterlevel(&u.uz);
3398. 
3399.         if (dfeature && !strncmp(dfeature, "altar ", 6)) {
3400.             /* don't say "altar" twice, dfeature has more info */
3401.             You("try to feel what is here.");
3402.         } else {
3403.             const char *where = (Blind && !can_reach_floor(TRUE))
3404.                                     ? "lying beneath you"
3405.                                     : "lying here on the ",
3406.                        *onwhat = (Blind && !can_reach_floor(TRUE))
3407.                                      ? ""
3408.                                      : surface(u.ux, u.uy);
3409. 
3410.             You("try to feel what is %s%s.", drift ? "floating here" : where,
3411.                 drift ? "" : onwhat);
3412.         }
3413.         if (dfeature && !drift && !strcmp(dfeature, surface(u.ux, u.uy)))
3414.             dfeature = 0; /* ice already identified */
3415.         if (!can_reach_floor(TRUE)) {
3416.             pline("But you can't reach it!");
3417.             return 0;
3418.         }
3419.     }
3420. 
3421.     if (dfeature)
3422.         Sprintf(fbuf, "There is %s here.", an(dfeature));
3423. 
3424.     if (!otmp || is_lava(u.ux, u.uy)
3425.         || (is_pool(u.ux, u.uy) && !Underwater)) {
3426.         if (dfeature)
3427.             pline1(fbuf);
3428.         read_engr_at(u.ux, u.uy); /* Eric Backus */
3429.         if (!skip_objects && (Blind || !dfeature))
3430.             You("%s no objects here.", verb);
3431.         return !!Blind;
3432.     }
3433.     /* we know there is something here */
3434. 
3435.     if (skip_objects) {
3436.         if (dfeature)
3437.             pline1(fbuf);
3438.         read_engr_at(u.ux, u.uy); /* Eric Backus */
3439.         if (obj_cnt == 1 && otmp->quan == 1L)
3440.             There("is %s object here.", picked_some ? "another" : "an");
3441.         else
3442.             There("are %s%s objects here.",
3443.                   (obj_cnt < 5)
3444.                       ? "a few"
3445.                       : (obj_cnt < 10)
3446.                           ? "several"
3447.                           : "many",
3448.                   picked_some ? " more" : "");
3449.         for (; otmp; otmp = otmp->nexthere)
3450.             if (otmp->otyp == CORPSE && will_feel_cockatrice(otmp, FALSE)) {
3451.                 pline("%s %s%s.",
3452.                       (obj_cnt > 1)
3453.                           ? "Including"
3454.                           : (otmp->quan > 1L)
3455.                               ? "They're"
3456.                               : "It's",
3457.                       corpse_xname(otmp, (const char *) 0, CXN_ARTICLE),
3458.                       poly_when_stoned(youmonst.data)
3459.                           ? ""
3460.                           : ", unfortunately");
3461.                 feel_cockatrice(otmp, FALSE);
3462.                 break;
3463.             }
3464.     } else if (!otmp->nexthere) {
3465.         /* only one object */
3466.         if (dfeature)
3467.             pline1(fbuf);
3468.         read_engr_at(u.ux, u.uy); /* Eric Backus */
3469.         You("%s here %s.", verb, doname_with_price(otmp));
3470.         iflags.last_msg = PLNMSG_ONE_ITEM_HERE;
3471.         if (otmp->otyp == CORPSE)
3472.             feel_cockatrice(otmp, FALSE);
3473.     } else {
3474.         char buf[BUFSZ];
3475. 
3476.         display_nhwindow(WIN_MESSAGE, FALSE);
3477.         tmpwin = create_nhwindow(NHW_MENU);
3478.         if (dfeature) {
3479.             putstr(tmpwin, 0, fbuf);
3480.             putstr(tmpwin, 0, "");
3481.         }
3482.         Sprintf(buf, "%s that %s here:",
3483.                 picked_some ? "Other things" : "Things",
3484.                 Blind ? "you feel" : "are");
3485.         putstr(tmpwin, 0, buf);
3486.         for (; otmp; otmp = otmp->nexthere) {
3487.             if (otmp->otyp == CORPSE && will_feel_cockatrice(otmp, FALSE)) {
3488.                 felt_cockatrice = TRUE;
3489.                 Sprintf(buf, "%s...", doname(otmp));
3490.                 putstr(tmpwin, 0, buf);
3491.                 break;
3492.             }
3493.             putstr(tmpwin, 0, doname_with_price(otmp));
3494.         }
3495.         display_nhwindow(tmpwin, TRUE);
3496.         destroy_nhwindow(tmpwin);
3497.         if (felt_cockatrice)
3498.             feel_cockatrice(otmp, FALSE);
3499.         read_engr_at(u.ux, u.uy); /* Eric Backus */
3500.     }
3501.     return !!Blind;
3502. }
3503. 
3504. /* the ':' command - explicitly look at what is here, including all objects */
3505. int
3506. dolook()
3507. {
3508.     int res;
3509. 
3510.     /* don't let
3511.        MSGTYPE={norep,noshow} "You see here"
3512.        interfere with feedback from the look-here command */
3513.     hide_unhide_msgtypes(TRUE, MSGTYP_MASK_REP_SHOW);
3514.     res = look_here(0, FALSE);
3515.     /* restore normal msgtype handling */
3516.     hide_unhide_msgtypes(FALSE, MSGTYP_MASK_REP_SHOW);
3517.     return res;
3518. }
3519. 
3520. boolean
3521. will_feel_cockatrice(otmp, force_touch)
3522. struct obj *otmp;
3523. boolean force_touch;
3524. {
3525.     if ((Blind || force_touch) && !uarmg && !Stone_resistance
3526.         && (otmp->otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm])))
3527.         return TRUE;
3528.     return FALSE;
3529. }
3530. 
3531. void
3532. feel_cockatrice(otmp, force_touch)
3533. struct obj *otmp;
3534. boolean force_touch;
3535. {
3536.     char kbuf[BUFSZ];
3537. 
3538.     if (will_feel_cockatrice(otmp, force_touch)) {
3539.         /* "the <cockatrice> corpse" */
3540.         Strcpy(kbuf, corpse_xname(otmp, (const char *) 0, CXN_PFX_THE));
3541. 
3542.         if (poly_when_stoned(youmonst.data))
3543.             You("touched %s with your bare %s.", kbuf,
3544.                 makeplural(body_part(HAND)));
3545.         else
3546.             pline("Touching %s is a fatal mistake...", kbuf);
3547.         /* normalize body shape here; hand, not body_part(HAND) */
3548.         Sprintf(kbuf, "touching %s bare-handed", killer_xname(otmp));
3549.         /* will call polymon() for the poly_when_stoned() case */
3550.         instapetrify(kbuf);
3551.     }
3552. }
3553. 
3554. void
3555. stackobj(obj)
3556. struct obj *obj;
3557. {
3558.     struct obj *otmp;
3559. 
3560.     for (otmp = level.objects[obj->ox][obj->oy]; otmp; otmp = otmp->nexthere)
3561.         if (otmp != obj && merged(&obj, &otmp))
3562.             break;
3563.     return;
3564. }
3565. 
3566. /* returns TRUE if obj & otmp can be merged; used in invent.c and mkobj.c */
3567. boolean
3568. mergable(otmp, obj)
3569. register struct obj *otmp, *obj;
3570. {
3571.     int objnamelth = 0, otmpnamelth = 0;
3572. 
3573.     /* fail if already the same object, if different types, if either is
3574.        explicitly marked to prevent merge, or if not mergable in general */
3575.     if (obj == otmp || obj->otyp != otmp->otyp
3576.         || obj->nomerge || otmp->nomerge || !objects[obj->otyp].oc_merge)
3577.         return FALSE;
3578. 
3579.     /* coins of the same kind will always merge */
3580.     if (obj->oclass == COIN_CLASS)
3581.         return TRUE;
3582. 
3583.     if (obj->unpaid != otmp->unpaid || obj->spe != otmp->spe
3584.         || obj->cursed != otmp->cursed || obj->blessed != otmp->blessed
3585.         || obj->no_charge != otmp->no_charge || obj->obroken != otmp->obroken
3586.         || obj->otrapped != otmp->otrapped || obj->lamplit != otmp->lamplit
3587.         || obj->bypass != otmp->bypass)
3588.         return FALSE;
3589. 
3590.     if (obj->globby)
3591.         return TRUE;
3592.     /* Checks beyond this point either aren't applicable to globs
3593.      * or don't inhibit their merger.
3594.      */
3595. 
3596.     if (obj->oclass == FOOD_CLASS
3597.         && (obj->oeaten != otmp->oeaten || obj->orotten != otmp->orotten))
3598.         return FALSE;
3599. 
3600.     if (obj->dknown != otmp->dknown
3601.         || (obj->bknown != otmp->bknown && !Role_if(PM_PRIEST))
3602.         || obj->oeroded != otmp->oeroded || obj->oeroded2 != otmp->oeroded2
3603.         || obj->greased != otmp->greased)
3604.         return FALSE;
3605. 
3606.     if ((obj->oclass == WEAPON_CLASS || obj->oclass == ARMOR_CLASS)
3607.         && (obj->oerodeproof != otmp->oerodeproof
3608.             || obj->rknown != otmp->rknown))
3609.         return FALSE;
3610. 
3611.     if (obj->otyp == CORPSE || obj->otyp == EGG || obj->otyp == TIN) {
3612.         if (obj->corpsenm != otmp->corpsenm)
3613.             return FALSE;
3614.     }
3615. 
3616.     /* hatching eggs don't merge; ditto for revivable corpses */
3617.     if ((obj->otyp == EGG && (obj->timed || otmp->timed))
3618.         || (obj->otyp == CORPSE && otmp->corpsenm >= LOW_PM
3619.             && is_reviver(&mons[otmp->corpsenm])))
3620.         return FALSE;
3621. 
3622.     /* allow candle merging only if their ages are close */
3623.     /* see begin_burn() for a reference for the magic "25" */
3624.     if (Is_candle(obj) && obj->age / 25 != otmp->age / 25)
3625.         return FALSE;
3626. 
3627.     /* burning potions of oil never merge */
3628.     if (obj->otyp == POT_OIL && obj->lamplit)
3629.         return FALSE;
3630. 
3631.     /* don't merge surcharged item with base-cost item */
3632.     if (obj->unpaid && !same_price(obj, otmp))
3633.         return FALSE;
3634. 
3635.     /* if they have names, make sure they're the same */
3636.     objnamelth = strlen(safe_oname(obj));
3637.     otmpnamelth = strlen(safe_oname(otmp));
3638.     if ((objnamelth != otmpnamelth
3639.          && ((objnamelth && otmpnamelth) || obj->otyp == CORPSE))
3640.         || (objnamelth && otmpnamelth
3641.             && strncmp(ONAME(obj), ONAME(otmp), objnamelth)))
3642.         return FALSE;
3643. 
3644.     /* for the moment, any additional information is incompatible */
3645.     if (has_omonst(obj) || has_omid(obj) || has_olong(obj) || has_omonst(otmp)
3646.         || has_omid(otmp) || has_olong(otmp))
3647.         return FALSE;
3648. 
3649.     if (obj->oartifact != otmp->oartifact)
3650.         return FALSE;
3651. 
3652.     if (obj->known == otmp->known || !objects[otmp->otyp].oc_uses_known) {
3653.         return (boolean) objects[obj->otyp].oc_merge;
3654.     } else
3655.         return FALSE;
3656. }
3657. 
3658. /* the '$' command */
3659. int
3660. doprgold()
3661. {
3662.     /* the messages used to refer to "carrying gold", but that didn't
3663.        take containers into account */
3664.     long umoney = money_cnt(invent);
3665. 
3666.     if (!umoney)
3667.         Your("wallet is empty.");
3668.     else
3669.         Your("wallet contains %ld %s.", umoney, currency(umoney));
3670.     shopper_financial_report();
3671.     return 0;
3672. }
3673. 
3674. /* the ')' command */
3675. int
3676. doprwep()
3677. {
3678.     if (!uwep) {
3679.         You("are empty %s.", body_part(HANDED));
3680.     } else {
3681.         prinv((char *) 0, uwep, 0L);
3682.         if (u.twoweap)
3683.             prinv((char *) 0, uswapwep, 0L);
3684.     }
3685.     return 0;
3686. }
3687. 
3688. /* caller is responsible for checking !wearing_armor() */
3689. STATIC_OVL void
3690. noarmor(report_uskin)
3691. boolean report_uskin;
3692. {
3693.     if (!uskin || !report_uskin) {
3694.         You("are not wearing any armor.");
3695.     } else {
3696.         char *p, *uskinname, buf[BUFSZ];
3697. 
3698.         uskinname = strcpy(buf, simpleonames(uskin));
3699.         /* shorten "set of <color> dragon scales" to "<color> scales"
3700.            and "<color> dragon scale mail" to "<color> scale mail" */
3701.         if (!strncmpi(uskinname, "set of ", 7))
3702.             uskinname += 7;
3703.         if ((p = strstri(uskinname, " dragon ")) != 0)
3704.             while ((p[1] = p[8]) != '\0')
3705.                 ++p;
3706. 
3707.         You("are not wearing armor but have %s embedded in your skin.",
3708.             uskinname);
3709.     }
3710. }
3711. 
3712. /* the '[' command */
3713. int
3714. doprarm()
3715. {
3716.     char lets[8];
3717.     register int ct = 0;
3718.     /*
3719.      * Note:  players sometimes get here by pressing a function key which
3720.      * transmits ESC [ <something> rather than by pressing '[';
3721.      * there's nothing we can--or should-do about that here.
3722.      */
3723. 
3724.     if (!wearing_armor()) {
3725.         noarmor(TRUE);
3726.     } else {
3727.         if (uarmu)
3728.             lets[ct++] = obj_to_let(uarmu);
3729.         if (uarm)
3730.             lets[ct++] = obj_to_let(uarm);
3731.         if (uarmc)
3732.             lets[ct++] = obj_to_let(uarmc);
3733.         if (uarmh)
3734.             lets[ct++] = obj_to_let(uarmh);
3735.         if (uarms)
3736.             lets[ct++] = obj_to_let(uarms);
3737.         if (uarmg)
3738.             lets[ct++] = obj_to_let(uarmg);
3739.         if (uarmf)
3740.             lets[ct++] = obj_to_let(uarmf);
3741.         lets[ct] = 0;
3742.         (void) display_inventory(lets, FALSE);
3743.     }
3744.     return 0;
3745. }
3746. 
3747. /* the '=' command */
3748. int
3749. doprring()
3750. {
3751.     if (!uleft && !uright)
3752.         You("are not wearing any rings.");
3753.     else {
3754.         char lets[3];
3755.         register int ct = 0;
3756. 
3757.         if (uleft)
3758.             lets[ct++] = obj_to_let(uleft);
3759.         if (uright)
3760.             lets[ct++] = obj_to_let(uright);
3761.         lets[ct] = 0;
3762.         (void) display_inventory(lets, FALSE);
3763.     }
3764.     return 0;
3765. }
3766. 
3767. /* the '"' command */
3768. int
3769. dopramulet()
3770. {
3771.     if (!uamul)
3772.         You("are not wearing an amulet.");
3773.     else
3774.         prinv((char *) 0, uamul, 0L);
3775.     return 0;
3776. }
3777. 
3778. STATIC_OVL boolean
3779. tool_in_use(obj)
3780. struct obj *obj;
3781. {
3782.     if ((obj->owornmask & (W_TOOL | W_SADDLE)) != 0L)
3783.         return TRUE;
3784.     if (obj->oclass != TOOL_CLASS)
3785.         return FALSE;
3786.     return (boolean) (obj == uwep || obj->lamplit
3787.                       || (obj->otyp == LEASH && obj->leashmon));
3788. }
3789. 
3790. /* the '(' command */
3791. int
3792. doprtool()
3793. {
3794.     struct obj *otmp;
3795.     int ct = 0;
3796.     char lets[52 + 1];
3797. 
3798.     for (otmp = invent; otmp; otmp = otmp->nobj)
3799.         if (tool_in_use(otmp))
3800.             lets[ct++] = obj_to_let(otmp);
3801.     lets[ct] = '\0';
3802.     if (!ct)
3803.         You("are not using any tools.");
3804.     else
3805.         (void) display_inventory(lets, FALSE);
3806.     return 0;
3807. }
3808. 
3809. /* '*' command; combines the ')' + '[' + '=' + '"' + '(' commands;
3810.    show inventory of all currently wielded, worn, or used objects */
3811. int
3812. doprinuse()
3813. {
3814.     struct obj *otmp;
3815.     int ct = 0;
3816.     char lets[52 + 1];
3817. 
3818.     for (otmp = invent; otmp; otmp = otmp->nobj)
3819.         if (is_worn(otmp) || tool_in_use(otmp))
3820.             lets[ct++] = obj_to_let(otmp);
3821.     lets[ct] = '\0';
3822.     if (!ct)
3823.         You("are not wearing or wielding anything.");
3824.     else
3825.         (void) display_inventory(lets, FALSE);
3826.     return 0;
3827. }
3828. 
3829. /*
3830.  * uses up an object that's on the floor, charging for it as necessary
3831.  */
3832. void
3833. useupf(obj, numused)
3834. register struct obj *obj;
3835. long numused;
3836. {
3837.     register struct obj *otmp;
3838.     boolean at_u = (obj->ox == u.ux && obj->oy == u.uy);
3839. 
3840.     /* burn_floor_objects() keeps an object pointer that it tries to
3841.      * useupf() multiple times, so obj must survive if plural */
3842.     if (obj->quan > numused)
3843.         otmp = splitobj(obj, numused);
3844.     else
3845.         otmp = obj;
3846.     if (costly_spot(otmp->ox, otmp->oy)) {
3847.         if (index(u.urooms, *in_rooms(otmp->ox, otmp->oy, 0)))
3848.             addtobill(otmp, FALSE, FALSE, FALSE);
3849.         else
3850.             (void) stolen_value(otmp, otmp->ox, otmp->oy, FALSE, FALSE);
3851.     }
3852.     delobj(otmp);
3853.     if (at_u && u.uundetected && hides_under(youmonst.data))
3854.         (void) hideunder(&youmonst);
3855. }
3856. 
3857. /*
3858.  * Conversion from a class to a string for printing.
3859.  * This must match the object class order.
3860.  */
3861. STATIC_VAR NEARDATA const char *names[] = {
3862.     0, "Illegal objects", "Weapons", "Armor", "Rings", "Amulets", "Tools",
3863.     "Comestibles", "Potions", "Scrolls", "Spellbooks", "Wands", "Coins",
3864.     "Gems/Stones", "Boulders/Statues", "Iron balls", "Chains", "Venoms"
3865. };
3866. STATIC_VAR NEARDATA const char oth_symbols[] = { CONTAINED_SYM, '\0' };
3867. STATIC_VAR NEARDATA const char *oth_names[] = { "Bagged/Boxed items" };
3868. 
3869. STATIC_VAR NEARDATA char *invbuf = (char *) 0;
3870. STATIC_VAR NEARDATA unsigned invbufsiz = 0;
3871. 
3872. char *
3873. let_to_name(let, unpaid, showsym)
3874. char let;
3875. boolean unpaid, showsym;
3876. {
3877.     const char *ocsymfmt = "  ('%c')";
3878.     const int invbuf_sympadding = 8; /* arbitrary */
3879.     const char *class_name;
3880.     const char *pos;
3881.     int oclass = (let >= 1 && let < MAXOCLASSES) ? let : 0;
3882.     unsigned len;
3883. 
3884.     if (oclass)
3885.         class_name = names[oclass];
3886.     else if ((pos = index(oth_symbols, let)) != 0)
3887.         class_name = oth_names[pos - oth_symbols];
3888.     else
3889.         class_name = names[0];
3890. 
3891.     len = strlen(class_name) + (unpaid ? sizeof "unpaid_" : sizeof "")
3892.           + (oclass ? (strlen(ocsymfmt) + invbuf_sympadding) : 0);
3893.     if (len > invbufsiz) {
3894.         if (invbuf)
3895.             free((genericptr_t) invbuf);
3896.         invbufsiz = len + 10; /* add slop to reduce incremental realloc */
3897.         invbuf = (char *) alloc(invbufsiz);
3898.     }
3899.     if (unpaid)
3900.         Strcat(strcpy(invbuf, "Unpaid "), class_name);
3901.     else
3902.         Strcpy(invbuf, class_name);
3903.     if ((oclass != 0) && showsym) {
3904.         char *bp = eos(invbuf);
3905.         int mlen = invbuf_sympadding - strlen(class_name);
3906.         while (--mlen > 0) {
3907.             *bp = ' ';
3908.             bp++;
3909.         }
3910.         *bp = '\0';
3911.         Sprintf(eos(invbuf), ocsymfmt, def_oc_syms[oclass].sym);
3912.     }
3913.     return invbuf;
3914. }
3915. 
3916. /* release the static buffer used by let_to_name() */
3917. void
3918. free_invbuf()
3919. {
3920.     if (invbuf)
3921.         free((genericptr_t) invbuf), invbuf = (char *) 0;
3922.     invbufsiz = 0;
3923. }
3924. 
3925. /* give consecutive letters to every item in inventory (for !fixinv mode);
3926.    gold is always forced to '$' slot at head of list */
3927. void
3928. reassign()
3929. {
3930.     int i;
3931.     struct obj *obj, *prevobj, *goldobj;
3932. 
3933.     /* first, remove [first instance of] gold from invent, if present */
3934.     prevobj = goldobj = 0;
3935.     for (obj = invent; obj; prevobj = obj, obj = obj->nobj)
3936.         if (obj->oclass == COIN_CLASS) {
3937.             goldobj = obj;
3938.             if (prevobj)
3939.                 prevobj->nobj = goldobj->nobj;
3940.             else
3941.                 invent = goldobj->nobj;
3942.             break;
3943.         }
3944.     /* second, re-letter the rest of the list */
3945.     for (obj = invent, i = 0; obj; obj = obj->nobj, i++)
3946.         obj->invlet =
3947.             (i < 26) ? ('a' + i) : (i < 52) ? ('A' + i - 26) : NOINVSYM;
3948.     /* third, assign gold the "letter" '$' and re-insert it at head */
3949.     if (goldobj) {
3950.         goldobj->invlet = GOLD_SYM;
3951.         goldobj->nobj = invent;
3952.         invent = goldobj;
3953.     }
3954.     if (i >= 52)
3955.         i = 52 - 1;
3956.     lastinvnr = i;
3957. }
3958. 
3959. /* #adjust command
3960.  *
3961.  *      User specifies a 'from' slot for inventory stack to move,
3962.  *      then a 'to' slot for its destination.  Open slots and those
3963.  *      filled by compatible stacks are listed as likely candidates
3964.  *      but user can pick any inventory letter (including 'from').
3965.  *
3966.  *  to == from, 'from' has a name
3967.  *      All compatible items (same name or no name) are gathered
3968.  *      into the 'from' stack.  No count is allowed.
3969.  *  to == from, 'from' does not have a name
3970.  *      All compatible items without a name are gathered into the
3971.  *      'from' stack.  No count is allowed.  Compatible stacks with
3972.  *      names are left as-is.
3973.  *  to != from, no count
3974.  *      Move 'from' to 'to'.  If 'to' is not empty, merge 'from'
3975.  *      into it if possible, otherwise swap it with the 'from' slot.
3976.  *  to != from, count given
3977.  *      If the user specifies a count when choosing the 'from' slot,
3978.  *      and that count is less than the full size of the stack,
3979.  *      then the stack will be split.  The 'count' portion is moved
3980.  *      to the destination, and the only candidate for merging with
3981.  *      it is the stack already at the 'to' slot, if any.  When the
3982.  *      destination is non-empty but won't merge, whatever is there
3983.  *      will be moved to an open slot; if there isn't any open slot
3984.  *      available, the adjustment attempt fails.
3985.  *
3986.  *      To minimize merging for 'from == to', unnamed stacks will
3987.  *      merge with named 'from' but named ones won't merge with
3988.  *      unnamed 'from'.  Otherwise attempting to collect all unnamed
3989.  *      stacks would lump the first compatible named stack with them
3990.  *      and give them its name.
3991.  *
3992.  *      To maximize merging for 'from != to', compatible stacks will
3993.  *      merge when either lacks a name (or they already have the same
3994.  *      name).  When no count is given and one stack has a name and
3995.  *      the other doesn't, the merged result will have that name.
3996.  *      However, when splitting results in a merger, the name of the
3997.  *      destination overrides that of the source, even if destination
3998.  *      is unnamed and source is named.
3999.  */
4000. int
4001. doorganize() /* inventory organizer by Del Lamb */
4002. {
4003.     struct obj *obj, *otmp, *splitting, *bumped;
4004.     int ix, cur, trycnt, goldstacks;
4005.     char let;
4006. #define GOLD_INDX   0
4007. #define GOLD_OFFSET 1
4008. #define OVRFLW_INDX (GOLD_OFFSET + 52) /* past gold and 2*26 letters */
4009.     char lets[1 + 52 + 1 + 1]; /* room for '$a-zA-Z#\0' */
4010.     char qbuf[QBUFSZ];
4011.     char allowall[4]; /* { ALLOW_COUNT, ALL_CLASSES, 0, 0 } */
4012.     char *objname, *otmpname;
4013.     const char *adj_type;
4014.     boolean ever_mind = FALSE, collect;
4015. 
4016.     if (!invent) {
4017.         You("aren't carrying anything to adjust.");
4018.         return 0;
4019.     }
4020. 
4021.     if (!flags.invlet_constant)
4022.         reassign();
4023.     /* get object the user wants to organize (the 'from' slot) */
4024.     allowall[0] = ALLOW_COUNT;
4025.     allowall[1] = ALL_CLASSES;
4026.     allowall[2] = '\0';
4027.     for (goldstacks = 0, otmp = invent; otmp; otmp = otmp->nobj) {
4028.         /* gold should never end up in a letter slot, nor should two '$'
4029.            slots occur, but if they ever do, allow #adjust to handle them
4030.            (in the past, things like this have happened, usually due to
4031.            bknown being erroneously set on one stack, clear on another;
4032.            object merger isn't fooled by that anymore) */
4033.         if (otmp->oclass == COIN_CLASS
4034.             && (otmp->invlet != GOLD_SYM || ++goldstacks > 1)) {
4035.             allowall[1] = COIN_CLASS;
4036.             allowall[2] = ALL_CLASSES;
4037.             allowall[3] = '\0';
4038.             break;
4039.         }
4040.     }
4041.     if (!(obj = getobj(allowall, "adjust")))
4042.         return 0;
4043. 
4044.     /* figure out whether user gave a split count to getobj() */
4045.     splitting = bumped = 0;
4046.     for (otmp = invent; otmp; otmp = otmp->nobj)
4047.         if (otmp->nobj == obj) { /* knowledge of splitobj() operation */
4048.             if (otmp->invlet == obj->invlet)
4049.                 splitting = otmp;
4050.             break;
4051.         }
4052. 
4053.     /* initialize the list with all lower and upper case letters */
4054.     lets[GOLD_INDX] = (obj->oclass == COIN_CLASS) ? GOLD_SYM : ' ';
4055.     for (ix = GOLD_OFFSET, let = 'a'; let <= 'z';)
4056.         lets[ix++] = let++;
4057.     for (let = 'A'; let <= 'Z';)
4058.         lets[ix++] = let++;
4059.     lets[OVRFLW_INDX] = ' ';
4060.     lets[sizeof lets - 1] = '\0';
4061.     /* for floating inv letters, truncate list after the first open slot */
4062.     if (!flags.invlet_constant && (ix = inv_cnt(FALSE)) < 52)
4063.         lets[ix + (splitting ? 0 : 1)] = '\0';
4064. 
4065.     /* blank out all the letters currently in use in the inventory
4066.        except those that will be merged with the selected object */
4067.     for (otmp = invent; otmp; otmp = otmp->nobj)
4068.         if (otmp != obj && !mergable(otmp, obj)) {
4069.             let = otmp->invlet;
4070.             if (let >= 'a' && let <= 'z')
4071.                 lets[GOLD_OFFSET + let - 'a'] = ' ';
4072.             else if (let >= 'A' && let <= 'Z')
4073.                 lets[GOLD_OFFSET + let - 'A' + 26] = ' ';
4074.             /* overflow defaults to off, but it we find a stack using that
4075.                slot, switch to on -- the opposite of normal invlet handling */
4076.             else if (let == NOINVSYM)
4077.                 lets[OVRFLW_INDX] = NOINVSYM;
4078.         }
4079. 
4080.     /* compact the list by removing all the blanks */
4081.     for (ix = cur = 0; lets[ix]; ix++)
4082.         if (lets[ix] != ' ' && cur++ < ix)
4083.             lets[cur - 1] = lets[ix];
4084.     lets[cur] = '\0';
4085.     /* and by dashing runs of letters */
4086.     if (cur > 5)
4087.         compactify(lets);
4088. 
4089.     /* get 'to' slot to use as destination */
4090.     Sprintf(qbuf, "Adjust letter to what [%s]%s?", lets,
4091.             invent ? " (? see used letters)" : "");
4092.     for (trycnt = 1; ; ++trycnt) {
4093.         let = yn_function(qbuf, (char *) 0, '\0');
4094.         if (let == '?' || let == '*') {
4095.             let = display_used_invlets(splitting ? obj->invlet : 0);
4096.             if (!let)
4097.                 continue;
4098.             if (let == '\033')
4099.                 goto noadjust;
4100.         }
4101.         if (index(quitchars, let)
4102.             /* adjusting to same slot is meaningful since all
4103.                compatible stacks get collected along the way,
4104.                but splitting to same slot is not */
4105.             || (splitting && let == obj->invlet)) {
4106.  noadjust:
4107.             if (splitting)
4108.                 (void) merged(&splitting, &obj);
4109.             if (!ever_mind)
4110.                 pline1(Never_mind);
4111.             return 0;
4112.         } else if (let == GOLD_SYM && obj->oclass != COIN_CLASS) {
4113.             pline("Only gold coins may be moved into the '%c' slot.",
4114.                   GOLD_SYM);
4115.             ever_mind = TRUE;
4116.             goto noadjust;
4117.         }
4118.         /* letter() classifies '@' as one; compactify() can put '-' in lets;
4119.            the only thing of interest that index() might find is '$' or '#'
4120.            since letter() catches everything else that we put into lets[] */
4121.         if ((letter(let) && let != '@') || (index(lets, let) && let != '-'))
4122.             break; /* got one */
4123.         if (trycnt == 5)
4124.             goto noadjust;
4125.         pline("Select an inventory slot letter."); /* else try again */
4126.     }
4127. 
4128.     collect = (let == obj->invlet);
4129.     /* change the inventory and print the resulting item */
4130.     adj_type = collect ? "Collecting" : !splitting ? "Moving:" : "Splitting:";
4131. 
4132.     /*
4133.      * don't use freeinv/addinv to avoid double-touching artifacts,
4134.      * dousing lamps, losing luck, cursing loadstone, etc.
4135.      */
4136.     extract_nobj(obj, &invent);
4137. 
4138.     for (otmp = invent; otmp;) {
4139.         /* it's tempting to pull this outside the loop, but merged() could
4140.            free ONAME(obj) [via obfree()] and replace it with ONAME(otmp) */
4141.         objname = has_oname(obj) ? ONAME(obj) : (char *) 0;
4142. 
4143.         if (collect) {
4144.             /* Collecting: #adjust an inventory stack into its same slot;
4145.                keep it there and merge other compatible stacks into it.
4146.                Traditional inventory behavior is to merge unnamed stacks
4147.                with compatible named ones; we only want that if it is
4148.                the 'from' stack (obj) with a name and candidate (otmp)
4149.                without one, not unnamed 'from' with named candidate. */
4150.             otmpname = has_oname(otmp) ? ONAME(otmp) : (char *) 0;
4151.             if ((!otmpname || (objname && !strcmp(objname, otmpname)))
4152.                 && merged(&otmp, &obj)) {
4153.                 adj_type = "Merging:";
4154.                 obj = otmp;
4155.                 otmp = otmp->nobj;
4156.                 extract_nobj(obj, &invent);
4157.                 continue; /* otmp has already been updated */
4158.             }
4159.         } else if (otmp->invlet == let) {
4160.             /* Moving or splitting: don't merge extra compatible stacks.
4161.                Found 'otmp' in destination slot; merge if compatible,
4162.                otherwise bump whatever is there to an open slot. */
4163.             if (!splitting) {
4164.                 adj_type = "Swapping:";
4165.                 otmp->invlet = obj->invlet;
4166.             } else {
4167.                 /* strip 'from' name if it has one */
4168.                 if (objname && !obj->oartifact)
4169.                     ONAME(obj) = (char *) 0;
4170.                 if (!mergable(otmp, obj)) {
4171.                     /* won't merge; put 'from' name back */
4172.                     if (objname)
4173.                         ONAME(obj) = objname;
4174.                 } else {
4175.                     /* will merge; discard 'from' name */
4176.                     if (objname)
4177.                         free((genericptr_t) objname), objname = 0;
4178.                 }
4179. 
4180.                 if (merged(&otmp, &obj)) {
4181.                     adj_type = "Splitting and merging:";
4182.                     obj = otmp;
4183.                     extract_nobj(obj, &invent);
4184.                 } else if (inv_cnt(FALSE) >= 52) {
4185.                     (void) merged(&splitting, &obj); /* undo split */
4186.                     /* "knapsack cannot accommodate any more items" */
4187.                     Your("pack is too full.");
4188.                     return 0;
4189.                 } else {
4190.                     bumped = otmp;
4191.                     extract_nobj(bumped, &invent);
4192.                 }
4193.             } /* moving vs splitting */
4194.             break; /* not collecting and found 'to' slot */
4195.         } /* collect */
4196.         otmp = otmp->nobj;
4197.     }
4198. 
4199.     /* inline addinv; insert loose object at beginning of inventory */
4200.     obj->invlet = let;
4201.     obj->nobj = invent;
4202.     obj->where = OBJ_INVENT;
4203.     invent = obj;
4204.     reorder_invent();
4205.     if (bumped) {
4206.         /* splitting the 'from' stack is causing an incompatible
4207.            stack in the 'to' slot to be moved into an open one;
4208.            we need to do another inline insertion to inventory */
4209.         assigninvlet(bumped);
4210.         bumped->nobj = invent;
4211.         bumped->where = OBJ_INVENT;
4212.         invent = bumped;
4213.         reorder_invent();
4214.     }
4215. 
4216.     /* messages deferred until inventory has been fully reestablished */
4217.     prinv(adj_type, obj, 0L);
4218.     if (bumped)
4219.         prinv("Moving:", bumped, 0L);
4220.     if (splitting)
4221.         clear_splitobjs(); /* reset splitobj context */
4222.     update_inventory();
4223.     return 0;
4224. }
4225. 
4226. /* common to display_minventory and display_cinventory */
4227. STATIC_OVL void
4228. invdisp_nothing(hdr, txt)
4229. const char *hdr, *txt;
4230. {
4231.     winid win;
4232.     anything any;
4233.     menu_item *selected;
4234. 
4235.     any = zeroany;
4236.     win = create_nhwindow(NHW_MENU);
4237.     start_menu(win);
4238.     add_menu(win, NO_GLYPH, &any, 0, 0, iflags.menu_headings, hdr,
4239.              MENU_UNSELECTED);
4240.     add_menu(win, NO_GLYPH, &any, 0, 0, ATR_NONE, "", MENU_UNSELECTED);
4241.     add_menu(win, NO_GLYPH, &any, 0, 0, ATR_NONE, txt, MENU_UNSELECTED);
4242.     end_menu(win, (char *) 0);
4243.     if (select_menu(win, PICK_NONE, &selected) > 0)
4244.         free((genericptr_t) selected);
4245.     destroy_nhwindow(win);
4246.     return;
4247. }
4248. 
4249. /* query_objlist callback: return things that are worn or wielded */
4250. STATIC_OVL boolean
4251. worn_wield_only(obj)
4252. struct obj *obj;
4253. {
4254. #if 1
4255.     /* check for things that *are* worn or wielded (only used for monsters,
4256.        so we don't worry about excluding W_CHAIN, W_ARTI and the like) */
4257.     return (boolean) (obj->owornmask != 0L);
4258. #else
4259.     /* this used to check for things that *might* be worn or wielded,
4260.        but that's not particularly interesting */
4261.     if (is_weptool(obj) || is_wet_towel(obj) || obj->otyp == MEAT_RING)
4262.         return TRUE;
4263.     return (boolean) (obj->oclass == WEAPON_CLASS
4264.                       || obj->oclass == ARMOR_CLASS
4265.                       || obj->oclass == AMULET_CLASS
4266.                       || obj->oclass == RING_CLASS);
4267. #endif
4268. }
4269. 
4270. /*
4271.  * Display a monster's inventory.
4272.  * Returns a pointer to the object from the monster's inventory selected
4273.  * or NULL if nothing was selected.
4274.  *
4275.  * By default, only worn and wielded items are displayed.  The caller
4276.  * can pick one.  Modifier flags are:
4277.  *
4278.  *      PICK_NONE, PICK_ONE - standard menu control
4279.  *      PICK_ANY            - allowed, but we only return a single object
4280.  *      MINV_NOLET          - nothing selectable
4281.  *      MINV_ALL            - display all inventory
4282.  */
4283. struct obj *
4284. display_minventory(mon, dflags, title)
4285. register struct monst *mon;
4286. int dflags;
4287. char *title;
4288. {
4289.     struct obj *ret;
4290.     char tmp[QBUFSZ];
4291.     int n;
4292.     menu_item *selected = 0;
4293.     int do_all = (dflags & MINV_ALL) != 0,
4294.         incl_hero = (do_all && u.uswallow && mon == u.ustuck),
4295.         have_inv = (mon->minvent != 0), have_any = (have_inv || incl_hero),
4296.         pickings = (dflags & MINV_PICKMASK);
4297. 
4298.     Sprintf(tmp, "%s %s:", s_suffix(noit_Monnam(mon)),
4299.             do_all ? "possessions" : "armament");
4300. 
4301.     if (do_all ? have_any : (mon->misc_worn_check || MON_WEP(mon))) {
4302.         /* Fool the 'weapon in hand' routine into
4303.          * displaying 'weapon in claw', etc. properly.
4304.          */
4305.         youmonst.data = mon->data;
4306.         /* in case inside a shop, don't append "for sale" prices */
4307.         iflags.suppress_price++;
4308. 
4309.         n = query_objlist(title ? title : tmp, &(mon->minvent),
4310.                           (INVORDER_SORT | (incl_hero ? INCLUDE_HERO : 0)),
4311.                           &selected, pickings,
4312.                           do_all ? allow_all : worn_wield_only);
4313. 
4314.         iflags.suppress_price--;
4315.         /* was 'set_uasmon();' but that potentially has side-effects */
4316.         youmonst.data = &mons[u.umonnum]; /* most basic part of set_uasmon */
4317.     } else {
4318.         invdisp_nothing(title ? title : tmp, "(none)");
4319.         n = 0;
4320.     }
4321. 
4322.     if (n > 0) {
4323.         ret = selected[0].item.a_obj;
4324.         free((genericptr_t) selected);
4325.     } else
4326.         ret = (struct obj *) 0;
4327.     return ret;
4328. }
4329. 
4330. /*
4331.  * Display the contents of a container in inventory style.
4332.  * Currently, this is only used for statues, via wand of probing.
4333.  */
4334. struct obj *
4335. display_cinventory(obj)
4336. register struct obj *obj;
4337. {
4338.     struct obj *ret;
4339.     char qbuf[QBUFSZ];
4340.     int n;
4341.     menu_item *selected = 0;
4342. 
4343.     (void) safe_qbuf(qbuf, "Contents of ", ":", obj, doname, ansimpleoname,
4344.                      "that");
4345. 
4346.     if (obj->cobj) {
4347.         n = query_objlist(qbuf, &(obj->cobj), INVORDER_SORT,
4348.                           &selected, PICK_NONE, allow_all);
4349.     } else {
4350.         invdisp_nothing(qbuf, "(empty)");
4351.         n = 0;
4352.     }
4353.     if (n > 0) {
4354.         ret = selected[0].item.a_obj;
4355.         free((genericptr_t) selected);
4356.     } else
4357.         ret = (struct obj *) 0;
4358.     obj->cknown = 1;
4359.     return ret;
4360. }
4361. 
4362. /* query objlist callback: return TRUE if obj is at given location */
4363. static coord only;
4364. 
4365. STATIC_OVL boolean
4366. only_here(obj)
4367. struct obj *obj;
4368. {
4369.     return (obj->ox == only.x && obj->oy == only.y);
4370. }
4371. 
4372. /*
4373.  * Display a list of buried items in inventory style.  Return a non-zero
4374.  * value if there were items at that spot.
4375.  *
4376.  * Currently, this is only used with a wand of probing zapped downwards.
4377.  */
4378. int
4379. display_binventory(x, y, as_if_seen)
4380. int x, y;
4381. boolean as_if_seen;
4382. {
4383.     struct obj *obj;
4384.     menu_item *selected = 0;
4385.     int n;
4386. 
4387.     /* count # of objects here */
4388.     for (n = 0, obj = level.buriedobjlist; obj; obj = obj->nobj)
4389.         if (obj->ox == x && obj->oy == y) {
4390.             if (as_if_seen)
4391.                 obj->dknown = 1;
4392.             n++;
4393.         }
4394. 
4395.     if (n) {
4396.         only.x = x;
4397.         only.y = y;
4398.         if (query_objlist("Things that are buried here:",
4399.                           &level.buriedobjlist, INVORDER_SORT,
4400.                           &selected, PICK_NONE, only_here) > 0)
4401.             free((genericptr_t) selected);
4402.         only.x = only.y = 0;
4403.     }
4404.     return n;
4405. }
4406. 
4407. /*invent.c*/