Source:NetHack 5.0.0/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 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/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 5.0	invent.c	$NHDT-Date: 1762680996 2025/11/09 01:36:36 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.543 $ */
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. staticfn void inuse_classify(Loot *, struct obj *);
9. staticfn char *loot_xname(struct obj *);
10. staticfn int invletter_value(char);
11. staticfn int QSORTCALLBACK sortloot_cmp(const genericptr, const genericptr);
12. staticfn void reorder_invent(void);
13. staticfn struct obj *addinv_core0(struct obj *, struct obj *,
14.                                                          boolean) NONNULLARG1;
15. staticfn void noarmor(boolean);
16. staticfn void invdisp_nothing(const char *, const char *);
17. staticfn boolean worn_wield_only(struct obj *);
18. staticfn char *cinv_doname(struct obj *);
19. staticfn char *cinv_ansimpleoname(struct obj *);
20. staticfn boolean only_here(struct obj *);
21. staticfn void compactify(char *);
22. staticfn boolean taking_off(const char *);
23. staticfn void mime_action(const char *);
24. staticfn char *getobj_hands_txt(const char *, char *);
25. staticfn int ckvalidcat(struct obj *);
26. staticfn int ckunpaid(struct obj *);
27. staticfn char *safeq_xprname(struct obj *);
28. staticfn char *safeq_shortxprname(struct obj *);
29. staticfn char display_pickinv(const char *, const char *, const char *,
30.                             boolean, boolean, long *);
31. staticfn char display_used_invlets(char);
32. staticfn boolean this_type_only(struct obj *);
33. staticfn void dounpaid(int, int, int);
34. staticfn struct obj *find_unpaid(struct obj *, struct obj **);
35. staticfn void menu_identify(int);
36. staticfn boolean tool_being_used(struct obj *);
37. staticfn int adjust_ok(struct obj *);
38. staticfn int adjust_gold_ok(struct obj *);
39. staticfn int doorganize_core(struct obj *);
40. staticfn char obj_to_let(struct obj *);
41. staticfn int dispinv_with_action(char *, boolean, const char *);
42. 
43. /* enum and structs are defined in wintype.h */
44. static win_request_info wri_info;
45. static int perminv_flags = InvOptNone;
46. static boolean in_perm_invent_toggled;
47. 
48. /* wizards can wish for venom, which will become an invisible inventory
49.  * item without this.  putting it in inv_order would mean venom would
50.  * suddenly become a choice for all the inventory-class commands, which
51.  * would probably cause mass confusion.  the test for inventory venom
52.  * is only WIZARD and not wizard because the wizard can leave venom lying
53.  * around on a bones level for normal players to find.  [Note to the
54.  * confused:  'WIZARD' used to be a compile-time conditional so this was
55.  * guarded by #ifdef WIZARD/.../#endif.]
56.  */
57. static const char venom_inv[] = { VENOM_CLASS, 0 }; /* (constant) */
58. 
59. /* menu heading lines used instead of object classes when sorting by in-use;
60.    pointers aren't const because dispinv_with_action() might temporarily
61.    change "Accessories" to "Rings" or "Amulet", then back again */
62. static const char *inuse_headers[] = { /* [4] shown first, [1] last */
63.     "", "Miscellaneous", "Worn Armor",
64.     "Wielded/Readied Weapons", "Accessories",
65. };
66. 
67. /* sortloot() classification for in-use sort;
68.    called at most once [per sort] for each object */
69. staticfn void
70. inuse_classify(Loot *sort_item, struct obj *obj)
71. {
72.     long w_mask = (obj->owornmask & (W_ACCESSORY | W_WEAPONS | W_ARMOR));
73.     int rating = 0, altclass = 0;
74. 
75. #define USE_RATING(test) \
76.     do {                                                        \
77.         /* 'rating' advances for each USE_RATING() call */      \
78.         ++rating;                                               \
79.         if ((test) != 0)                                        \
80.             goto assign_rating;                                 \
81.     } while (0)
82. 
83.     /*
84.      * In order of importance, least to most, somewhat arbitrarily.
85.      *
86.      * For instance, all accessories are grouped together even
87.      * though they're usually less important than other stuff, so
88.      * that they appear earlier within displayed list of used items.
89.      * Amulet is rated as most important primarily because the
90.      * default 'packorder' puts amulets first (possibly because one
91.      * might be The Amulet).  Non-wielded alternate weapon and
92.      * quiver are grouped with primary weapon.  Weapons are rated
93.      * above armor because of default 'packorder'.
94.      *
95.      * These ratings don't match either subclasses or 'packorder'.
96.      *
97.      * USE_RATING() sets up 'rating' then jumps to 'assign_rating'
98.      * if 'obj' warrants that.
99.      */
100.     /* "Miscellaneous" */
101.     ++altclass; /* 1 */
102.     /* lamp and leash might be used doubly, as a tool and also wielded
103.        or readied-in-quiver; these tests for used-as-tool only pass
104.        when owornmask is 0 so that used-as-weapon takes precedence */
105.     USE_RATING(!w_mask && obj->otyp == LEASH && obj->leashmon);
106.     USE_RATING(!w_mask && obj->oclass == TOOL_CLASS && obj->lamplit);
107.     /* "Armor" */
108.     ++altclass; /* 2 */
109.     USE_RATING(w_mask & WORN_SHIRT);
110.     USE_RATING(w_mask & WORN_BOOTS);
111.     USE_RATING(w_mask & WORN_GLOVES);
112.     USE_RATING(w_mask & WORN_HELMET);
113.     USE_RATING(w_mask & WORN_SHIELD);
114.     USE_RATING(w_mask & WORN_CLOAK);
115.     USE_RATING(w_mask & WORN_ARMOR);
116.     /* "Weapons" */
117.     ++altclass; /* 3 */
118.     /* could get more complicated:  if uswapwep is just alternate weapon
119.        rather than wielded secondary, swap order with quiver (unless
120.        quiver is ammo for uswapwep without also being ammo for uwep) */
121.     USE_RATING(w_mask & W_QUIVER);
122.     USE_RATING(w_mask & W_SWAPWEP);
123.     USE_RATING(w_mask & W_WEP);
124.     /* "Accessories" */
125.     ++altclass; /* 4 */
126.     USE_RATING(w_mask & WORN_BLINDF);
127.     USE_RATING(w_mask & (ULEFTY ? RIGHT_RING : LEFT_RING)); /* off hand */
128.     USE_RATING(w_mask & (URIGHTY ? RIGHT_RING : LEFT_RING)); /* main hand */
129.     USE_RATING(w_mask & WORN_AMUL);
130. 
131.     /* if we get here, the USE_RATING() checks failed to find a match */
132.     rating = 0;
133.     altclass = -1; /* 'orderclass' must end up non-zero */
134. 
135.  assign_rating:
136.     sort_item->inuse = rating;
137.     sort_item->orderclass = altclass; /* used for alternate headings */
138. 
139.     /* not applicable for in-use */
140.     sort_item->subclass = 0;
141.     sort_item->disco = 0;
142. 
143. #undef USE_RATING
144. }
145. 
146. /* sortloot() classification; called at most once [per sort] for each object;
147.    also called by '\' command if discoveries use sortloot order */
148. void
149. loot_classify(Loot *sort_item, struct obj *obj)
150. {
151.     /* we may eventually make this a settable option to always use
152.        with sortloot instead of only when the 'sortpack' option isn't
153.        set; it is similar to sortpack's inv_order but items most
154.        likely to be picked up are moved to the front */
155.     static char def_srt_order[MAXOCLASSES] = {
156.         COIN_CLASS, AMULET_CLASS, RING_CLASS, WAND_CLASS, POTION_CLASS,
157.         SCROLL_CLASS, SPBOOK_CLASS, GEM_CLASS, FOOD_CLASS, TOOL_CLASS,
158.         WEAPON_CLASS, ARMOR_CLASS, ROCK_CLASS, BALL_CLASS, CHAIN_CLASS, 0,
159.     };
160.     static char armcat[8];
161.     const char *classorder;
162.     const char *p;
163.     int k, otyp = obj->otyp, oclass = obj->oclass;
164.     boolean seen, discovered = objects[otyp].oc_name_known ? TRUE : FALSE;
165. 
166.     /*
167.      * For the value types assigned by this classification, sortloot()
168.      * will put lower valued ones before higher valued ones.
169.      */
170.     if (!Blind)
171.         observe_object(obj); /* xname(obj) does this; we want it sooner */
172.     seen = obj->dknown ? TRUE : FALSE,
173.     /* class order */
174.     classorder = flags.sortpack ? flags.inv_order : def_srt_order;
175.     p = strchr(classorder, oclass);
176.     if (p)
177.         k = 1 + (int) (p - classorder);
178.     else
179.         k = 1 + (int) strlen(classorder) + (oclass != VENOM_CLASS);
180.     sort_item->orderclass = k;
181.     /* subclass designation; only a few classes have subclasses
182.        and the non-armor ones we use are fairly arbitrary */
183.     switch (oclass) {
184.     case ARMOR_CLASS:
185.         if (!armcat[7]) {
186.             /* one-time init; we use a different order than the subclass
187.                values defined by objclass.h */
188.             armcat[ARM_HELM]   = 1; /* [2] */
189.             armcat[ARM_GLOVES] = 2; /* [3] */
190.             armcat[ARM_BOOTS]  = 3; /* [4] */
191.             armcat[ARM_SHIELD] = 4; /* [1] */
192.             armcat[ARM_CLOAK]  = 5; /* [5] */
193.             armcat[ARM_SHIRT]  = 6; /* [6] */
194.             armcat[ARM_SUIT]   = 7; /* [0] */
195.             armcat[7]          = 8; /* sanity protection */
196.         }
197.         k = objects[otyp].oc_armcat;
198.         /* oc_armcat overloads oc_subtyp which is an 'schar' so guard
199.            against somebody assigning something unexpected to it */
200.         if (k < 0 || k >= 7)
201.             k = 7;
202.         k = armcat[k];
203.         break;
204.     case WEAPON_CLASS:
205.         /* for weapons, group by ammo (arrows, bolts), launcher (bows),
206.            missile (darts, boomerangs), stackable (daggers, knives, spears),
207.            'other' (swords, axes, &c), polearms */
208.         k = objects[otyp].oc_skill;
209.         k = (k < 0) ? ((k >= -P_CROSSBOW && k <= -P_BOW) ? 1 : 3)
210.                     : ((k >= P_BOW && k <= P_CROSSBOW) ? 2
211.                        : (k == P_SPEAR || k == P_DAGGER || k == P_KNIFE) ? 4
212.                           : !is_pole(obj) ? 5 : 6);
213.         break;
214.     case TOOL_CLASS:
215.         if (seen && discovered
216.             && (otyp == BAG_OF_TRICKS || otyp == HORN_OF_PLENTY))
217.             k = 2; /* known pseudo-container */
218.         else if (Is_container(obj))
219.             k = 1; /* regular container or unknown bag of tricks */
220.         else
221.             switch (otyp) {
222.             case WOODEN_FLUTE:
223.             case MAGIC_FLUTE:
224.             case TOOLED_HORN:
225.             case FROST_HORN:
226.             case FIRE_HORN:
227.             case WOODEN_HARP:
228.             case MAGIC_HARP:
229.             case BUGLE:
230.             case LEATHER_DRUM:
231.             case DRUM_OF_EARTHQUAKE:
232.             case HORN_OF_PLENTY: /* not a musical instrument */
233.                 k = 3; /* instrument or unknown horn of plenty */
234.                 break;
235.             default:
236.                 k = 4; /* 'other' tool */
237.                 break;
238.             }
239.         break;
240.     case FOOD_CLASS:
241.         /* [what about separating "partly eaten" within each group?] */
242.         switch (otyp) {
243.         case SLIME_MOLD:
244.             k = 1;
245.             break;
246.         default:
247.             /* [maybe separate one-bite foods from rations and such?] */
248.             k = obj->globby ? 6 : 2;
249.             break;
250.         case TIN:
251.             k = 3;
252.             break;
253.         case EGG:
254.             k = 4;
255.             break;
256.         case CORPSE:
257.             k = 5;
258.             break;
259.         }
260.         break;
261.     case GEM_CLASS:
262.         /*
263.          * Normally subclass takes priority over discovery status, but
264.          * that would give away information for gems (assuming we'll
265.          * group them as valuable gems, next glass, then gray stones,
266.          * and finally rocks once they're all fully identified).
267.          *
268.          * Order:
269.          *  1) unseen gems and glass ("gem")
270.          *  2) seen but undiscovered gems and glass ("blue gem"),
271.          *  3) discovered gems ("sapphire"),
272.          *  4) discovered glass ("worthless pieced of blue glass"),
273.          *  5) unseen gray stones and rocks ("stone"),
274.          *  6) seen but undiscovered gray stones ("gray stone"),
275.          *  7) discovered gray stones ("touchstone"),
276.          *  8) seen rocks ("rock").
277.          */
278.         switch (objects[obj->otyp].oc_material) {
279.         case GEMSTONE:
280.             k = !seen ? 1 : !discovered ? 2 : 3;
281.             break;
282.         case GLASS:
283.             k = !seen ? 1 : !discovered ? 2 : 4;
284.             break;
285.         default: /* MINERAL */
286.             k = !seen ? 5 : (obj->otyp != ROCK) ? (!discovered ? 6 : 7) : 8;
287.             break;
288.         }
289.         break;
290.     default:
291.         /* other classes don't have subclasses; we assign a nonzero
292.            value because sortloot() uses 0 to mean 'not yet classified' */
293.         k = 1; /* any non-zero would do */
294.         break;
295.     }
296.     sort_item->subclass = k;
297.     /* discovery status */
298.     k = !seen ? 1 /* unseen */
299.         : (discovered || !OBJ_DESCR(objects[otyp])) ? 4
300.           : (objects[otyp].oc_uname) ? 3 /* named (partially discovered) */
301.             : 2; /* undiscovered */
302.     sort_item->disco = k;
303.     /* not applicable */
304.     sort_item->inuse = 0;
305. }
306. 
307. /* sortloot() formatting routine; for alphabetizing, not shown to user */
308. staticfn char *
309. loot_xname(struct obj *obj)
310. {
311.     struct obj saveo;
312.     boolean save_debug;
313.     char *res, *save_oname;
314. 
315.     /*
316.      * Deal with things that xname() includes as a prefix.  We don't
317.      * want such because they change alphabetical ordering.  First,
318.      * remember 'obj's current settings.
319.      */
320.     saveo.odiluted = obj->odiluted;
321.     saveo.blessed = obj->blessed, saveo.cursed = obj->cursed;
322.     saveo.spe = obj->spe;
323.     saveo.owt = obj->owt;
324.     save_oname = has_oname(obj) ? ONAME(obj) : 0;
325.     save_debug = flags.debug;
326.     /* suppress "diluted" for potions and "holy/unholy" for water;
327.        sortloot() will deal with them using other criteria than name */
328.     if (obj->oclass == POTION_CLASS) {
329.         obj->odiluted = 0;
330.         if (obj->otyp == POT_WATER)
331.             obj->blessed = 0, obj->cursed = 0;
332.     }
333.     /* make "wet towel" and "moist towel" format as "towel" so that all
334.        three group together */
335.     if (obj->otyp == TOWEL)
336.         obj->spe = 0;
337.     /* group globs by monster type rather than by size:  force all to
338.        have the same size adjective hence same "small glob of " prefix */
339.     if (obj->globby)
340.         obj->owt = 20; /* weight of a fresh glob (one pudding's worth) */
341.     /* suppress user-assigned name */
342.     if (save_oname && !obj->oartifact)
343.         ONAME(obj) = 0;
344.     /* avoid wizard mode formatting variations */
345.     if (wizard) { /* flags.debug */
346.         /* paranoia:  before toggling off wizard mode, guard against a
347.            panic in xname() producing a normal mode panic save file */
348.         program_state.something_worth_saving = 0;
349.         flags.debug = FALSE;
350.     }
351. 
352.     res = cxname_singular(obj);
353. 
354.     if (save_debug) {
355.         flags.debug = TRUE;
356.         program_state.something_worth_saving = 1;
357.     }
358.     /* restore the object */
359.     if (obj->oclass == POTION_CLASS) {
360.         obj->odiluted = saveo.odiluted;
361.         if (obj->otyp == POT_WATER)
362.             obj->blessed = saveo.blessed, obj->cursed = saveo.cursed;
363.     }
364.     if (obj->otyp == TOWEL) {
365.         obj->spe = saveo.spe;
366.         /* give "towel" a suffix that will force wet ones to come first,
367.            moist ones next, and dry ones last regardless of whether
368.            they've been flagged as having spe known */
369.         Strcat(res, is_wet_towel(obj) ? ((obj->spe >= 3) ? "x" : "y") : "z");
370.     }
371.     if (obj->globby) {
372.         obj->owt = saveo.owt;
373.         /* we've suppressed the size prefix (above); there normally won't
374.            be more than one of a given creature type because they coalesce,
375.            but globs with different bless/curse state won't merge so it is
376.            feasible to have multiple at the same location; add a suffix to
377.            get such sorted by size (small first) */
378.         Strcat(res, (obj->owt <= 100) ? "a"
379.                     : (obj->owt <= 300) ? "b"
380.                       : (obj->owt <= 500) ? "c"
381.                         : "d");
382.     }
383.     if (save_oname && !obj->oartifact)
384.         ONAME(obj) = save_oname;
385. 
386.     return res;
387. }
388. 
389. /* '$'==1, 'a'-'z'==2..27, 'A'-'Z'==28..53, '#'==54, catchall 55 */
390. staticfn int
391. invletter_value(char c)
392. {
393.     return ('a' <= c && c <= 'z') ? (c - 'a' + 2)
394.            : ('A' <= c && c <= 'Z') ? (c - 'A' + 2 + 26)
395.              : (c == '$') ? 1
396.                : (c == '#') ? 1 + invlet_basic + 1
397.                  : 1 + invlet_basic + 1 + 1; /* none of the above
398.                                               * (shouldn't happen) */
399. }
400. 
401. /* qsort comparison routine for sortloot() */
402. staticfn int QSORTCALLBACK
403. sortloot_cmp(const genericptr vptr1, const genericptr vptr2)
404. {
405.     struct sortloot_item *sli1 = (struct sortloot_item *) vptr1,
406.                          *sli2 = (struct sortloot_item *) vptr2;
407.     struct obj *obj1 = sli1->obj,
408.                *obj2 = sli2->obj;
409.     char *nam1, *nam2, *tmpstr;
410.     int val1, val2, namcmp;
411. 
412.     /* in-use takes precedence over all others */
413.     if ((gs.sortlootmode & SORTLOOT_INUSE) != 0) {
414.         /* Classify each object at most once no matter how many
415.            comparisons it is involved in. */
416.         if (!sli1->orderclass)
417.             inuse_classify(sli1, obj1);
418.         if (!sli2->orderclass)
419.             inuse_classify(sli2, obj2);
420. 
421.         val1 = sli1->inuse;
422.         val2 = sli2->inuse;
423.         if (val1 != val2)
424.             return val2 - val1; /* bigger value comes before smaller */
425.         /* neither item in use (or both are lit lamps/candles or both are
426.            attached leashes; items using owornmask don't produce ties) */
427.         goto tiebreak;
428.     }
429. 
430.     /* order by object class unless we're doing by-invlet without sortpack */
431.     if ((gs.sortlootmode & (SORTLOOT_PACK | SORTLOOT_INVLET))
432.         != SORTLOOT_INVLET) {
433.         /* Classify each object at most once no matter how many
434.            comparisons it is involved in. */
435.         if (!sli1->orderclass)
436.             loot_classify(sli1, obj1);
437.         if (!sli2->orderclass)
438.             loot_classify(sli2, obj2);
439. 
440.         /* Sort by class. */
441.         val1 = sli1->orderclass;
442.         val2 = sli2->orderclass;
443.         if (val1 != val2)
444.             return val1 - val2;
445. 
446.         /* skip sub-classes when ordering by sortpack+invlet */
447.         if ((gs.sortlootmode & SORTLOOT_INVLET) == 0) {
448.             /* Class matches; sort by subclass. */
449.             val1 = sli1->subclass;
450.             val2 = sli2->subclass;
451.             if (val1 != val2)
452.                 return val1 - val2;
453. 
454.             /* Class and subclass match; sort by discovery status:
455.              * first unseen, then seen but not named or discovered,
456.              * then named, lastly discovered.
457.              * 1) potion
458.              * 2) pink potion
459.              * 3) dark green potion called confusion
460.              * 4) potion of healing
461.              * Multiple entries within each group will be put into
462.              * alphabetical order below.
463.              */
464.             val1 = sli1->disco;
465.             val2 = sli2->disco;
466.             if (val1 != val2)
467.                 return val1 - val2;
468.         }
469.     }
470. 
471.     /* order by assigned inventory letter */
472.     if ((gs.sortlootmode & SORTLOOT_INVLET) != 0) {
473.         val1 = invletter_value(obj1->invlet);
474.         val2 = invletter_value(obj2->invlet);
475.         if (val1 != val2)
476.             return val1 - val2;
477.     }
478. 
479.     if ((gs.sortlootmode & SORTLOOT_LOOT) == 0)
480.         goto tiebreak;
481. 
482.     /*
483.      * Sort object names in lexicographical order, ignoring quantity.
484.      *
485.      * Each obj gets formatted at most once (per sort) no matter how many
486.      * comparisons it gets subjected to.
487.      */
488.     nam1 = sli1->str;
489.     if (!nam1) {
490.         tmpstr = loot_xname(obj1);
491.         nam1 = sli1->str = dupstr(tmpstr);
492.         maybereleaseobuf(tmpstr);
493.     }
494.     nam2 = sli2->str;
495.     if (!nam2) {
496.         tmpstr = loot_xname(obj2);
497.         nam2 = sli2->str = dupstr(tmpstr);
498.         maybereleaseobuf(tmpstr);
499.     }
500.     if ((namcmp = strcmpi(nam1, nam2)) != 0)
501.         return namcmp;
502. 
503.     /* Sort by BUCX. */
504.     val1 = obj1->bknown ? (obj1->blessed ? 3 : !obj1->cursed ? 2 : 1) : 0;
505.     val2 = obj2->bknown ? (obj2->blessed ? 3 : !obj2->cursed ? 2 : 1) : 0;
506.     if (val1 != val2)
507.         return val2 - val1; /* bigger is better */
508. 
509.     /* Sort by greasing.  This will put the objects in degreasing order. */
510.     val1 = obj1->greased;
511.     val2 = obj2->greased;
512.     if (val1 != val2)
513.         return val2 - val1; /* bigger is better */
514. 
515.     /* Sort by erosion.  The effective amount is what matters. */
516.     val1 = greatest_erosion(obj1);
517.     val2 = greatest_erosion(obj2);
518.     if (val1 != val2)
519.         return val1 - val2; /* bigger is WORSE */
520. 
521.     /* Sort by erodeproofing.  Map known-invulnerable to 1, and both
522.        known-vulnerable and unknown-vulnerability to 0, because that's
523.        how they're displayed. */
524.     val1 = obj1->rknown && obj1->oerodeproof;
525.     val2 = obj2->rknown && obj2->oerodeproof;
526.     if (val1 != val2)
527.         return val2 - val1; /* bigger is better */
528. 
529.     /* Sort by enchantment.  Map unknown to -1000, which is comfortably
530.        below the range of obj->spe.  oc_uses_known means that obj->known
531.        matters, which usually indirectly means that obj->spe is relevant.
532.        Lots of objects use obj->spe for some other purpose (see obj.h). */
533.     if (objects[obj1->otyp].oc_uses_known
534.         /* exclude eggs (laid by you) and tins (homemade, pureed, &c) */
535.         && obj1->oclass != FOOD_CLASS) {
536.         val1 = obj1->known ? obj1->spe : -1000;
537.         val2 = obj2->known ? obj2->spe : -1000;
538.         if (val1 != val2)
539.             return val2 - val1; /* bigger is better */
540.     }
541. 
542.  tiebreak:
543.     /* They're identical, as far as we're concerned.  We want
544.        to force a deterministic order, and do so by producing a
545.        stable sort: maintain the original order of equal items. */
546.     return (sli1->indx - sli2->indx);
547. }
548. 
549. /*
550.  * sortloot() - the story so far...
551.  *
552.  *      The original implementation constructed and returned an array
553.  *      of pointers to objects in the requested order.  Callers had to
554.  *      count the number of objects, allocate the array, pass one
555.  *      object at a time to the routine which populates it, traverse
556.  *      the objects via stepping through the array, then free the
557.  *      array.  The ordering process used a basic insertion sort which
558.  *      is fine for short lists but inefficient for long ones.
559.  *
560.  *      3.6.0 (and continuing with 3.6.1) changed all that so that
561.  *      sortloot was self-contained as far as callers were concerned.
562.  *      It reordered the linked list into the requested order and then
563.  *      normal list traversal was used to process it.  It also switched
564.  *      to qsort() on the assumption that the C library implementation
565.  *      put some effort into sorting efficiently.  It also checked
566.  *      whether the list was already sorted as it got ready to do the
567.  *      sorting, so re-examining inventory or a pile of objects without
568.  *      having changed anything would gobble up less CPU than a full
569.  *      sort.  But it had at least two problems (aside from the ordinary
570.  *      complement of bugs):
571.  *      1) some players wanted to get the original order back when they
572.  *      changed the 'sortloot' option back to 'none', but the list
573.  *      reordering made that infeasible;
574.  *      2) object identification giving the 'ID whole pack' result
575.  *      would call makeknown() on each newly ID'd object, that would
576.  *      call update_inventory() to update the persistent inventory
577.  *      window if one existed, the interface would call the inventory
578.  *      display routine which would call sortloot() which might change
579.  *      the order of the list being traversed by the identify code,
580.  *      possibly skipping the ID of some objects.  That could have been
581.  *      avoided by suppressing 'perm_invent' during identification
582.  *      (fragile) or by avoiding sortloot() during inventory display
583.  *      (more robust).
584.  *
585.  *      As of 3.6.2: revert to the temporary array of ordered obj pointers
586.  *      but have sortloot() do the counting and allocation.  Callers
587.  *      need to use array traversal instead of linked list traversal
588.  *      and need to free the temporary array when done.  And the
589.  *      array contains 'struct sortloot_item' (aka 'Loot') entries
590.  *      instead of simple 'struct obj *' entries.
591.  */
592. Loot *
593. sortloot(
594.     struct obj **olist,  /* old version might have changed *olist, we don't */
595.     unsigned mode,       /* flags for sortloot_cmp() */
596.     boolean by_nexthere, /* T: traverse via obj->nexthere, F: via obj->nobj */
597.     boolean (*filterfunc)(struct obj *)) /* optional filter */
598. {
599.     static Loot zerosli;
600.     Loot *sliarray;
601.     struct obj *o;
602.     unsigned n, i;
603.     boolean augment_filter;
604. 
605.     for (n = 0, o = *olist; o; o = by_nexthere ? o->nexthere : o->nobj)
606.         ++n;
607.     /* note: if there is a filter function, this might overallocate */
608.     sliarray = (Loot *) alloc((n + 1) * sizeof *sliarray);
609. 
610.     /* the 'keep cockatrice corpses' flag is overloaded with sort mode */
611.     augment_filter = (mode & SORTLOOT_PETRIFY) ? TRUE : FALSE;
612.     mode &= ~SORTLOOT_PETRIFY; /* remove flag, leaving mode */
613.     /* populate aliarray[0..n-1] */
614.     for (i = 0, o = *olist; o; o = by_nexthere ? o->nexthere : o->nobj) {
615.         if (filterfunc && !(*filterfunc)(o)
616.             /* caller may be asking us to override filterfunc (in order
617.                to do a cockatrice corpse touch check during pickup even
618.                if/when the filter rejects food class) */
619.             && (!augment_filter || o->otyp != CORPSE
620.                 || !touch_petrifies(&mons[o->corpsenm])))
621.             continue;
622.         sliarray[i] = zerosli;
623.         sliarray[i].obj = o, sliarray[i].indx = (int) i;
624.         ++i;
625.     }
626.     n = i;
627.     /* add a terminator so that we don't have to pass 'n' back to caller */
628.     sliarray[n] = zerosli;
629.     sliarray[n].indx = -1;
630. 
631.     /* do the sort; if no sorting is requested, we'll just return
632.        a sortloot_item array reflecting the current ordering */
633.     if (mode && n > 1) {
634.         gs.sortlootmode = mode; /* extra input for sortloot_cmp() */
635.         qsort((genericptr_t) sliarray, n, sizeof *sliarray, sortloot_cmp);
636.         gs.sortlootmode = 0; /* reset static mode flags */
637.         /* if sortloot_cmp formatted any objects, discard their strings now */
638.         for (i = 0; i < n; ++i)
639.             if (sliarray[i].str)
640.                 free((genericptr_t) sliarray[i].str), sliarray[i].str = 0;
641.     }
642.     return sliarray;
643. }
644. 
645. /* sortloot() callers should use this to free up memory it allocates */
646. void
647. unsortloot(Loot **loot_array_p)
648. {
649.     if (*loot_array_p)
650.         free((genericptr_t) *loot_array_p), *loot_array_p = (Loot *) 0;
651. }
652. 
653. #if 0 /* 3.6.0 'revamp' -- simpler than current, but ultimately too simple */
654. void
655. sortloot(
656.     struct obj **olist,
657.     unsigned mode,       /* flags for sortloot_cmp() */
658.     boolean by_nexthere) /* T: traverse via obj->nexthere, F: via obj->nobj */
659. {
660.     struct sortloot_item *sliarray, osli, nsli;
661.     struct obj *o, **nxt_p;
662.     unsigned n, i;
663.     boolean already_sorted = TRUE;
664. 
665.     gs.sortlootmode = mode; /* extra input for sortloot_cmp() */
666.     for (n = osli.indx = 0, osli.obj = *olist; (o = osli.obj) != 0;
667.          osli = nsli) {
668.         nsli.obj = by_nexthere ? o->nexthere : o->nobj;
669.         nsli.indx = (int) ++n;
670.         if (nsli.obj && already_sorted
671.             && sortloot_cmp((genericptr_t) &osli, (genericptr_t) &nsli) > 0)
672.             already_sorted = FALSE;
673.     }
674.     if (n > 1 && !already_sorted) {
675.         sliarray = (struct sortloot_item *) alloc(n * sizeof *sliarray);
676.         for (i = 0, o = *olist; o;
677.              ++i, o = by_nexthere ? o->nexthere : o->nobj)
678.             sliarray[i].obj = o, sliarray[i].indx = (int) i;
679. 
680.         qsort((genericptr_t) sliarray, n, sizeof *sliarray, sortloot_cmp);
681.         for (i = 0; i < n; ++i) {
682.             o = sliarray[i].obj;
683.             nxt_p = by_nexthere ? &(o->nexthere) : &(o->nobj);
684.             *nxt_p = (i < n - 1) ? sliarray[i + 1].obj : (struct obj *) 0;
685.         }
686.         *olist = sliarray[0].obj;
687.         free((genericptr_t) sliarray);
688.     }
689.     gs.sortlootmode = 0;
690. }
691. #endif /*0*/
692. 
693. void
694. assigninvlet(struct obj *otmp)
695. {
696.     boolean inuse[invlet_basic];
697.     int i;
698.     struct obj *obj;
699. 
700.     /* there should be at most one of these in inventory... */
701.     if (otmp->oclass == COIN_CLASS) {
702.         otmp->invlet = GOLD_SYM;
703.         return;
704.     }
705. 
706.     for (i = 0; i < invlet_basic; i++)
707.         inuse[i] = FALSE;
708.     for (obj = gi.invent; obj; obj = obj->nobj)
709.         if (obj != otmp) {
710.             i = obj->invlet;
711.             if ('a' <= i && i <= 'z')
712.                 inuse[i - 'a'] = TRUE;
713.             else if ('A' <= i && i <= 'Z')
714.                 inuse[i - 'A' + 26] = TRUE;
715.             if (i == otmp->invlet)
716.                 otmp->invlet = 0;
717.         }
718.     if ((i = otmp->invlet)
719.         && (('a' <= i && i <= 'z') || ('A' <= i && i <= 'Z')))
720.         return;
721.     for (i = gl.lastinvnr + 1; i != gl.lastinvnr; i++) {
722.         if (i == invlet_basic) {
723.             i = -1;
724.             continue;
725.         }
726.         if (!inuse[i])
727.             break;
728.     }
729.     otmp->invlet =
730.         (inuse[i] ? NOINVSYM : (i < 26) ? ('a' + i) : ('A' + i - 26));
731.     gl.lastinvnr = i;
732. }
733. 
734. /* note: assumes ASCII; toggling a bit puts lowercase in front of uppercase */
735. #define inv_rank(o) ((o)->invlet ^ 040)
736. 
737. /* sort the inventory; used by addinv() and doorganize() */
738. staticfn void
739. reorder_invent(void)
740. {
741.     struct obj *otmp, *prev, *next;
742.     boolean need_more_sorting;
743. 
744.     do {
745.         /*
746.          * We expect at most one item to be out of order, so this
747.          * isn't nearly as inefficient as it may first appear.
748.          */
749.         need_more_sorting = FALSE;
750.         for (otmp = gi.invent, prev = 0; otmp; ) {
751.             next = otmp->nobj;
752.             if (next && inv_rank(next) < inv_rank(otmp)) {
753.                 need_more_sorting = TRUE;
754.                 if (prev)
755.                     prev->nobj = next;
756.                 else
757.                     gi.invent = next;
758.                 otmp->nobj = next->nobj;
759.                 next->nobj = otmp;
760.                 prev = next;
761.             } else {
762.                 prev = otmp;
763.                 otmp = next;
764.             }
765.         }
766.     } while (need_more_sorting);
767. }
768. 
769. #undef inv_rank
770. 
771. /* scan a list of objects to see whether another object will merge with
772.    one of them; used in pickup.c when all 52 inventory slots are in use,
773.    to figure out whether another object could still be picked up */
774. struct obj *
775. merge_choice(struct obj *objlist, struct obj *obj)
776. {
777.     struct monst *shkp;
778.     unsigned save_nocharge;
779. 
780.     if (!objlist) /* might be checking 'obj' against empty inventory */
781.         return (struct obj *) 0;
782.     if (obj->otyp == SCR_SCARE_MONSTER) /* punt on these */
783.         return (struct obj *) 0;
784.     /* if this is an item on the shop floor, the attributes it will
785.        have when carried are different from what they are now; prevent
786.        that from eliciting an incorrect result from mergable() */
787.     save_nocharge = obj->no_charge;
788.     if (objlist == gi.invent && obj->where == OBJ_FLOOR
789.         && (shkp = shop_keeper(inside_shop(obj->ox, obj->oy))) != 0) {
790.         if (obj->no_charge)
791.             obj->no_charge = 0;
792.         /* A billable object won't have its `unpaid' bit set, so would
793.            erroneously seem to be a candidate to merge with a similar
794.            ordinary object.  That's no good, because once it's really
795.            picked up, it won't merge after all.  It might merge with
796.            another unpaid object, but we can't check that here (depends
797.            too much upon shk's bill) and if it doesn't merge it would
798.            end up in the '#' overflow inventory slot, so reject it now. */
799.         else if (inhishop(shkp))
800.             return (struct obj *) 0;
801.     }
802.     do {
803.         /*assert(objlist != NULL);*/
804.         if (mergable(objlist, obj))
805.             break;
806.         objlist = objlist->nobj;
807.     } while (objlist);
808.     obj->no_charge = save_nocharge;
809.     return objlist;
810. }
811. 
812. /* merge obj with otmp and delete obj if types agree */
813. int
814. merged(struct obj **potmp, struct obj **pobj)
815. {
816.     struct obj *otmp = *potmp, *obj = *pobj;
817.     boolean discovered = FALSE;
818. 
819.     if (mergable(otmp, obj)) {
820.         /* Approximate age: we do it this way because if we were to
821.          * do it "accurately" (merge only when ages are identical)
822.          * we'd wind up never merging any corpses.
823.          * otmp->age = otmp->age*(1-proportion) + obj->age*proportion;
824.          *
825.          * Don't do the age manipulation if lit.  We would need
826.          * to stop the burn on both items, then merge the age,
827.          * then restart the burn.  Glob ages are averaged in the
828.          * absorb routine, which uses weight rather than quantity
829.          * to adjust for proportion (glob quantity is always 1).
830.          */
831.         if (!obj->lamplit && !obj->globby)
832.             otmp->age = ((otmp->age * otmp->quan) + (obj->age * obj->quan))
833.                         / (otmp->quan + obj->quan);
834. 
835.         if (!otmp->globby)
836.             otmp->quan += obj->quan;
837.         /* temporary special case for gold objects!!!! */
838.         if (otmp->oclass == COIN_CLASS)
839.             otmp->owt = weight(otmp), otmp->bknown = 0;
840.         /* and puddings!!!1!!one! */
841.         else if (!Is_pudding(otmp))
842.             otmp->owt = weight(otmp);
843.         if (!has_oname(otmp) && has_oname(obj))
844.             otmp = *potmp = oname(otmp, ONAME(obj), ONAME_SKIP_INVUPD);
845.         obj_extract_self(obj);
846. 
847.         if (obj->pickup_prev && otmp->where == OBJ_INVENT)
848.             otmp->pickup_prev = 1;
849. 
850.         /* really should merge the timeouts */
851.         if (obj->lamplit)
852.             obj_merge_light_sources(obj, otmp);
853.         if (obj->timed)
854.             obj_stop_timers(obj); /* follows lights */
855. 
856.         /* objects can be identified by comparing them (unless Blind,
857.            but that is handled in mergable()); the object becomes
858.            identified in a particular dimension if either object was
859.            previously identified in that dimension, and if the
860.            identification states don't match, one of them must have
861.            previously been identified */
862.         if (obj->known != otmp->known) {
863.             otmp->known = 1;
864.             discovered = TRUE;
865.         }
866.         if (obj->rknown != otmp->rknown) {
867.             otmp->rknown = 1;
868.             if (otmp->oerodeproof)
869.                 discovered = TRUE;
870.         }
871.         if (obj->bknown != otmp->bknown) {
872.             otmp->bknown = 1;
873.             if (!Role_if(PM_CLERIC))
874.                 discovered = TRUE;
875.         }
876. 
877.         /* fixup for `#adjust' merging wielded darts, daggers, &c */
878.         if (obj->owornmask && carried(otmp)) {
879.             long wmask = otmp->owornmask | obj->owornmask;
880. 
881.             /* Both the items might be worn in competing slots;
882.                merger preference (regardless of which is which):
883.              primary weapon + alternate weapon -> primary weapon;
884.              primary weapon + quiver -> primary weapon;
885.              alternate weapon + quiver -> alternate weapon.
886.                (Prior to 3.3.0, it was not possible for the two
887.                stacks to be worn in different slots and `obj'
888.                didn't need to be unworn when merging.) */
889.             if ((wmask & W_WEP) != 0L) {
890.                 wmask = W_WEP;
891.             } else if ((wmask & W_SWAPWEP) != 0L) {
892.                 wmask = W_SWAPWEP;
893.             } else if ((wmask & W_QUIVER) != 0L) {
894.                 wmask = W_QUIVER;
895.             } else {
896.                 impossible("merging strangely worn items (%lx)", wmask);
897.                 wmask = otmp->owornmask;
898.             }
899.             if ((otmp->owornmask & ~wmask) != 0L)
900.                 setnotworn(otmp);
901.             setworn(otmp, wmask);
902.             setnotworn(obj);
903. #if 0
904.         /* (this should not be necessary, since items
905.             already in a monster's inventory don't ever get
906.             merged into other objects [only vice versa]) */
907.         } else if (obj->owornmask && mcarried(otmp)) {
908.             if (obj == MON_WEP(otmp->ocarry)) {
909.                 MON_WEP(otmp->ocarry) = otmp;
910.                 otmp->owornmask = W_WEP;
911.             }
912. #endif /*0*/
913.         }
914. 
915.         /* mergable() no longer requires 'bypass' to match; if 'obj' has
916.            the bypass bit set, force the combined stack to have that too;
917.            primarily in case this merge is occurring because stackobj()
918.            is operating on an object just dropped by a monster that was
919.            zapped with polymorph, we want bypass set in order to inhibit
920.            the same zap from affecting the new combined stack when it hits
921.            objects at the monster's spot (but also in case we're called by
922.            code that's using obj->bypass to track 'already processed') */
923.         if (obj->bypass)
924.             otmp->bypass = 1;
925. 
926.         /* handle puddings a bit differently; absorption will free the
927.            other object automatically so we can just return out from here */
928.         if (obj->globby) {
929.             pudding_merge_message(otmp, obj);
930.             obj_absorb(potmp, pobj);
931.             return 1;
932.         }
933. 
934.         /* Print a message if item comparison discovers more
935.            information about the items (with the exception of thrown
936.            items, where this would be too spammy as such items get
937.            unidentified by monsters very frequently). */
938.         if (discovered && otmp->where == OBJ_INVENT
939.             && obj->how_lost != LOST_THROWN
940.             && otmp->how_lost != LOST_THROWN) {
941.             pline("You learn more about your items by comparing them.");
942.         }
943. 
944.         obfree(obj, otmp); /* free(obj), bill->otmp */
945.         return 1;
946.     }
947.     return 0;
948. }
949. 
950. /*
951.  * Adjust hero intrinsics as if this object was being added to the hero's
952.  * inventory.  Called _before_ the object has been added to the hero's
953.  * inventory.
954.  *
955.  * This is called when adding objects to the hero's inventory normally (via
956.  * addinv) or when an object in the hero's inventory has been polymorphed
957.  * in-place.
958.  */
959. void
960. addinv_core1(struct obj *obj)
961. {
962.     if (obj->oclass == COIN_CLASS) {
963.         disp.botl = TRUE;
964.     } else if (obj->otyp == AMULET_OF_YENDOR) {
965.         if (u.uhave.amulet)
966.             impossible("already have amulet?");
967.         u.uhave.amulet = 1;
968.         record_achievement(ACH_AMUL);
969.     } else if (obj->otyp == CANDELABRUM_OF_INVOCATION) {
970.         if (u.uhave.menorah)
971.             impossible("already have candelabrum?");
972.         u.uhave.menorah = 1;
973.         record_achievement(ACH_CNDL);
974.     } else if (obj->otyp == BELL_OF_OPENING) {
975.         if (u.uhave.bell)
976.             impossible("already have silver bell?");
977.         u.uhave.bell = 1;
978.         record_achievement(ACH_BELL);
979.     } else if (obj->otyp == SPE_BOOK_OF_THE_DEAD) {
980.         if (u.uhave.book)
981.             impossible("already have the book?");
982.         u.uhave.book = 1;
983.         record_achievement(ACH_BOOK);
984.     } else if (obj->oartifact) {
985.         if (is_quest_artifact(obj)) {
986.             if (u.uhave.questart)
987.                 impossible("already have quest artifact?");
988.             u.uhave.questart = 1;
989.             artitouch(obj);
990.         }
991.         set_artifact_intrinsic(obj, 1, W_ART);
992.     }
993. 
994.     /* "special achievements"; revealed in end of game disclosure and
995.        dumplog, originally just recorded in XLOGFILE */
996.     if (is_mines_prize(obj)) {
997.         record_achievement(ACH_MINE_PRIZE);
998.         svc.context.achieveo.mines_prize_oid = 0; /* done w/ luckstone o_id */
999.         obj->nomerge = 0; /* was set in create_object(sp_lev.c) */
1000.     } else if (is_soko_prize(obj)) {
1001.         record_achievement(ACH_SOKO_PRIZE);
1002.         svc.context.achieveo.soko_prize_oid = 0; /* done w/ bag/amulet o_id */
1003.         obj->nomerge = 0; /* (got set in sp_lev.c) */
1004.     }
1005. }
1006. 
1007. /*
1008.  * Adjust hero intrinsics (and perform other side effects) as if this
1009.  * object was being added to the hero's inventory.  Called _after_ the
1010.  * object has been added to the hero's inventory.
1011.  *
1012.  * This can be used either for updating intrinsics, or to allow the hero to
1013.  * react to objects that are now in inventory.
1014.  *
1015.  * This is called when adding objects to the hero's inventory normally (via
1016.  * addinv), when an object in the hero's inventory has been polymorphed
1017.  * in-place, or when the hero re-examines objects that they picked up while
1018.  * blind.
1019.  *
1020.  * This may occasionally be called on an item that was already in inventory,
1021.  * so it should be written to work even if called multiple times in a row
1022.  * (e.g. do not assume that the object was not in inventory already).
1023.  */
1024. void
1025. addinv_core2(struct obj *obj)
1026. {
1027.     if (confers_luck(obj)) {
1028.         /* new luckstone must be in inventory by this point
1029.            for correct calculation */
1030.         set_moreluck();
1031.     }
1032. 
1033.     /* Archeologists can decipher the writing on a scroll label to work out
1034.        what they are (exception: unlabeled scrolls don't have a label to
1035.        decipher) */
1036.     if (Role_if(PM_ARCHEOLOGIST) && obj->oclass == SCROLL_CLASS &&
1037.         obj->otyp != SCR_BLANK_PAPER && !Blind &&
1038.         !objects[obj->otyp].oc_name_known) {
1039.         observe_object(obj);
1040.         pline("You decipher the label on %s.", yname(obj));
1041.         makeknown(obj->otyp);
1042. 
1043.         /* conduct: this is avoidable via not picking up / wishing for
1044.            scrolls */
1045.         if (!u.uconduct.literate++)
1046.             livelog_printf(LL_CONDUCT,
1047.                            "became literate by deciphering a scroll label");
1048.     }
1049. }
1050. 
1051. /*
1052.  * Add obj to the hero's inventory.  Make sure the object is "free".
1053.  * Adjust hero attributes as necessary.
1054.  */
1055. staticfn struct obj *
1056. addinv_core0(
1057.     struct obj *obj, struct obj *other_obj,
1058.     boolean update_perm_invent)
1059. {
1060.     struct obj *otmp, *prev;
1061.     int saved_otyp = (int) obj->otyp; /* for panic */
1062.     boolean obj_was_thrown;
1063. 
1064.     if (obj->where != OBJ_FREE)
1065.         panic("addinv: obj not free");
1066.     if (obj->how_lost == LOST_EXPLODING)
1067.         return (struct obj *) NULL;
1068. 
1069.     /* normally addtobill() clears no_charge when items in a shop are
1070.        picked up, but won't do so if the shop has become untended */
1071.     obj->no_charge = 0; /* should not be set in hero's invent */
1072.     if (Has_contents(obj))
1073.         picked_container(obj); /* clear no_charge */
1074.     obj_was_thrown = (obj->how_lost == LOST_THROWN);
1075.     obj->how_lost = LOST_NONE;
1076. 
1077.     if (gl.loot_reset_justpicked) {
1078.         gl.loot_reset_justpicked = FALSE;
1079.         reset_justpicked(gi.invent);
1080.     }
1081. 
1082.     addinv_core1(obj); /* handle most side effects of carrying obj */
1083. 
1084.     /* for addinv_before(); if something has been removed and is now being
1085.        reinserted, try to put it in the same place instead of merging or
1086.        placing at end; for thrown-and-return weapon with !fixinv setting */
1087.     if (other_obj) {
1088.         for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
1089.             if (otmp->nobj == other_obj) {
1090.                 obj->nobj = other_obj;
1091.                 otmp->nobj = obj;
1092.                 obj->where = OBJ_INVENT;
1093.                 goto added;
1094.             }
1095.         }
1096.     }
1097. 
1098.     /* merge with quiver in preference to any other inventory slot
1099.        in case quiver and wielded weapon are both eligible; adding
1100.        extra to quivered stack is more useful than to wielded one */
1101.     if (uquiver && merged(&uquiver, &obj)) {
1102.         obj = uquiver;
1103.         if (!obj)
1104.             panic("addinv: null obj after quiver merge otyp=%d", saved_otyp);
1105.         goto added;
1106.     }
1107.     /* merge if possible; find end of chain in the process */
1108.     for (prev = 0, otmp = gi.invent; otmp; prev = otmp, otmp = otmp->nobj)
1109.         if (merged(&otmp, &obj)) {
1110.             obj = otmp;
1111.             if (!obj)
1112.                 panic("addinv: null obj after merge otyp=%d", saved_otyp);
1113.             goto added;
1114.         }
1115.     /* didn't merge, so insert into chain */
1116.     assigninvlet(obj);
1117.     if (flags.invlet_constant || !prev) {
1118.         obj->nobj = gi.invent; /* insert at beginning */
1119.         gi.invent = obj;
1120.         if (flags.invlet_constant)
1121.             reorder_invent();
1122.     } else {
1123.         prev->nobj = obj; /* insert at end */
1124.         obj->nobj = 0;
1125.     }
1126.     obj->where = OBJ_INVENT;
1127. 
1128.     /* fill empty quiver if obj was thrown */
1129.     if (obj_was_thrown && flags.pickup_thrown && !uquiver
1130.         /* if Mjollnir is thrown and fails to return, we want to
1131.            auto-pick it when we move to its spot, but not into quiver
1132.            because it needs to be wielded to be re-thrown;
1133.            aklys likewise because player using 'f' to throw it might
1134.            not notice that it isn't wielded until it fails to return
1135.            several times; we never auto-wield, just omit from quiver
1136.            so that player will be prompted for what to throw and
1137.            possibly realize that re-wielding is necessary */
1138.         && obj->oartifact != ART_MJOLLNIR && obj->otyp != AKLYS
1139.         && (throwing_weapon(obj) || is_ammo(obj)))
1140.         setuqwep(obj);
1141.  added:
1142.     obj->pickup_prev = 1;
1143.     addinv_core2(obj); /* handle extrinsics conferred by carrying obj */
1144.     carry_obj_effects(obj); /* carrying affects the obj */
1145.     if (update_perm_invent)
1146.         update_inventory();
1147.     return obj;
1148. }
1149. 
1150. /* add obj to the hero's inventory in the default fashion */
1151. struct obj *
1152. addinv(struct obj *obj)
1153. {
1154.     return addinv_core0(obj, (struct obj *) 0, TRUE);
1155. }
1156. 
1157. /* add obj to the hero's inventory by inserting in front of a specific item;
1158.    used for throw-and-return in case '!fixinv' is in effect */
1159. struct obj *
1160. addinv_before(
1161.     struct obj *obj, struct obj *other_obj)
1162. {
1163.     /* if 'other_obj' is present this will implicitly be 'nomerge' */
1164.     return addinv_core0(obj, other_obj, TRUE);
1165. }
1166. 
1167. /* return value will always be 'obj' */
1168. struct obj *
1169. addinv_nomerge(struct obj *obj)
1170. {
1171.     struct obj *result;
1172.     unsigned save_nomerge = obj->nomerge;
1173. 
1174.     obj->nomerge = 1;
1175.     result = addinv(obj);
1176.     obj->nomerge = save_nomerge;
1177.     return result;
1178. }
1179. 
1180. /*
1181.  * Some objects are affected by being carried.
1182.  * Make those adjustments here. Called _after_ the object
1183.  * has been added to the hero's or monster's inventory,
1184.  * and after hero's intrinsics have been updated.
1185.  */
1186. void
1187. carry_obj_effects(struct obj *obj)
1188. {
1189.     /* Cursed figurines can spontaneously transform when carried. */
1190.     if (obj->otyp == FIGURINE) {
1191.         if (obj->cursed && obj->corpsenm != NON_PM
1192.             && !dead_species(obj->corpsenm, TRUE)) {
1193.             attach_fig_transform_timeout(obj);
1194.         }
1195.     }
1196. }
1197. 
1198. DISABLE_WARNING_FORMAT_NONLITERAL
1199. 
1200. /* Add an item to the inventory unless we're fumbling or it refuses to be
1201.  * held (via touch_artifact), and give a message.
1202.  * If there aren't any free inventory slots, we'll drop it instead.
1203.  * If both success and failure messages are NULL, then we're just doing the
1204.  * fumbling/slot-limit checking for a silent grab.  In any case,
1205.  * touch_artifact will print its own messages if they are warranted.
1206.  */
1207. struct obj *
1208. hold_another_object(
1209.     struct obj *obj, /* object to be held */
1210.     const char *drop_fmt, /* format string for message if it can't be held */
1211.     const char *drop_arg, /* argument to use when formatting message */
1212.     const char *hold_msg) /* message to display if successfully held */
1213. {
1214.     char buf[BUFSZ];
1215. 
1216.     if (!Blind)
1217.         observe_object(obj); /* maximize mergeability */
1218.     if (obj->oartifact) {
1219.         /* place_object may change these */
1220.         boolean crysknife = (obj->otyp == CRYSKNIFE);
1221.         int oerode = obj->oerodeproof;
1222.         boolean wasUpolyd = Upolyd;
1223. 
1224.         /* in case touching this object turns out to be fatal */
1225.         place_object(obj, u.ux, u.uy);
1226. 
1227.         if (!touch_artifact(obj, &gy.youmonst)) {
1228.             obj_extract_self(obj); /* remove it from the floor */
1229.             dropy(obj);            /* now put it back again :-) */
1230.             return obj;
1231.         } else if (wasUpolyd && !Upolyd) {
1232.             /* lose your grip if you revert your form */
1233.             if (drop_fmt)
1234.                 pline(drop_fmt, drop_arg);
1235.             obj_extract_self(obj);
1236.             dropy(obj);
1237.             return obj;
1238.         }
1239.         obj_extract_self(obj);
1240.         if (crysknife) {
1241.             obj->otyp = CRYSKNIFE;
1242.             obj->oerodeproof = oerode;
1243.         }
1244.     }
1245.     if (Fumbling) {
1246.         obj->nomerge = 1;
1247.         /* dropping expects obj to be in invent; since it's going to be
1248.            dropped, avoid perminv update when temporarily adding it */
1249.         obj = addinv_core0(obj, (struct obj *) 0, FALSE);
1250.         goto drop_it;
1251.     } else if (obj->otyp == CORPSE
1252.                && !u_safe_from_fatal_corpse(obj, st_all)
1253.                && obj->wishedfor) {
1254.         obj->wishedfor = 0;
1255.         obj = addinv_core0(obj, (struct obj *) 0, FALSE);
1256.         goto drop_it;
1257.     } else {
1258.         long oquan = obj->quan;
1259.         int prev_encumbr = near_capacity(); /* before addinv() */
1260. 
1261.         /* encumbrance limit is max( current_state, pickup_burden );
1262.            this used to use hardcoded MOD_ENCUMBER (stressed) instead
1263.            of the 'pickup_burden' option (which defaults to stressed) */
1264.         if (prev_encumbr < flags.pickup_burden)
1265.             prev_encumbr = flags.pickup_burden;
1266.         /* addinv() may redraw the entire inventory, overwriting
1267.            drop_arg when it is kept in an 'obuf' from doname();
1268.            [should no longer be necessary now that perm_invent update is
1269.            suppressed, but it's cheap to keep as a paranoid precaution] */
1270.         if (drop_arg)
1271.             drop_arg = strcpy(buf, drop_arg);
1272. 
1273.         obj = addinv_core0(obj, (struct obj *) 0, FALSE);
1274.         if (inv_cnt(FALSE) > invlet_basic
1275.                 || ((obj->otyp != LOADSTONE || !obj->cursed)
1276.                        && near_capacity() > prev_encumbr)) {
1277.             /* undo any merge which took place */
1278.             if (obj->quan > oquan)
1279.                 obj = splitobj(obj, oquan);
1280.             goto drop_it;
1281.         } else {
1282.             if (flags.autoquiver && !uquiver && !obj->owornmask
1283.                 && (is_missile(obj) || ammo_and_launcher(obj, uwep)
1284.                     || ammo_and_launcher(obj, uswapwep)))
1285.                 setuqwep(obj);
1286.             if (hold_msg || drop_fmt)
1287.                 prinv(hold_msg, obj, oquan);
1288.             /* obj made it into inventory and is staying there */
1289.             update_inventory();
1290.             encumber_msg();
1291.         }
1292.     }
1293.     return obj;
1294. 
1295.  drop_it:
1296.     if (drop_fmt)
1297.         pline(drop_fmt, drop_arg);
1298.     obj->nomerge = 0;
1299.     if (can_reach_floor(TRUE) || u.uswallow) {
1300.         dropx(obj);
1301.     } else {
1302.         freeinv(obj);
1303.         hitfloor(obj, FALSE);
1304.     }
1305.     return (struct obj *) 0; /* might be gone */
1306. }
1307. 
1308. RESTORE_WARNING_FORMAT_NONLITERAL
1309. 
1310. /* useup() all of an item regardless of its quantity */
1311. void
1312. useupall(struct obj *obj)
1313. {
1314.     setnotworn(obj);
1315.     freeinv(obj);
1316.     obfree(obj, (struct obj *) 0); /* deletes contents also */
1317. }
1318. 
1319. /* an item in inventory is going away after being used */
1320. void
1321. useup(struct obj *obj)
1322. {
1323.     /* Note:  This works correctly for containers because they (containers)
1324.        don't merge. */
1325.     if (obj->quan > 1L) {
1326.         obj->in_use = FALSE; /* no longer in use */
1327.         obj->quan--;
1328.         obj->owt = weight(obj);
1329.         update_inventory();
1330.     } else {
1331.         useupall(obj);
1332.     }
1333. }
1334. 
1335. /* use one charge from an item and possibly incur shop debt for it */
1336. void
1337. consume_obj_charge(
1338.     struct obj *obj,
1339.     boolean maybe_unpaid) /* false if caller handles shop billing */
1340. {
1341.     if (maybe_unpaid)
1342.         check_unpaid(obj);
1343.     obj->spe -= 1;
1344.     if (obj->known)
1345.         update_inventory();
1346. }
1347. 
1348. /*
1349.  * Adjust hero's attributes as if this object was being removed from the
1350.  * hero's inventory.  This should only be called from freeinv() and
1351.  * where we are polymorphing an object already in the hero's inventory.
1352.  *
1353.  * Should think of a better name...
1354.  */
1355. void
1356. freeinv_core(struct obj *obj)
1357. {
1358.     if (obj->oclass == COIN_CLASS) {
1359.         disp.botl = TRUE;
1360.         return;
1361.     } else if (obj->otyp == AMULET_OF_YENDOR) {
1362.         if (!u.uhave.amulet)
1363.             impossible("don't have amulet?");
1364.         u.uhave.amulet = 0;
1365.     } else if (obj->otyp == CANDELABRUM_OF_INVOCATION) {
1366.         if (!u.uhave.menorah)
1367.             impossible("don't have candelabrum?");
1368.         u.uhave.menorah = 0;
1369.     } else if (obj->otyp == BELL_OF_OPENING) {
1370.         if (!u.uhave.bell)
1371.             impossible("don't have silver bell?");
1372.         u.uhave.bell = 0;
1373.     } else if (obj->otyp == SPE_BOOK_OF_THE_DEAD) {
1374.         if (!u.uhave.book)
1375.             impossible("don't have the book?");
1376.         u.uhave.book = 0;
1377.     } else if (obj->oartifact) {
1378.         if (is_quest_artifact(obj)) {
1379.             if (!u.uhave.questart)
1380.                 impossible("don't have quest artifact?");
1381.             u.uhave.questart = 0;
1382.         }
1383.         set_artifact_intrinsic(obj, 0, W_ART);
1384.     }
1385. 
1386.     if (obj->otyp == LOADSTONE) {
1387.         curse(obj);
1388.     } else if (confers_luck(obj)) {
1389.         set_moreluck();
1390.         disp.botl = TRUE;
1391.     } else if (obj->otyp == FIGURINE && obj->timed) {
1392.         (void) stop_timer(FIG_TRANSFORM, obj_to_any(obj));
1393.     }
1394. 
1395.     if (obj == svc.context.tin.tin) {
1396.         svc.context.tin.tin = (struct obj *) 0;
1397.         svc.context.tin.o_id = 0;
1398.     }
1399. }
1400. 
1401. /* remove an object from the hero's inventory */
1402. void
1403. freeinv(struct obj *obj)
1404. {
1405.     extract_nobj(obj, &gi.invent);
1406.     obj->pickup_prev = 0;
1407.     freeinv_core(obj);
1408.     update_inventory();
1409. }
1410. 
1411. /* drawbridge is destroying all objects at <x,y> */
1412. void
1413. delallobj(coordxy x, coordxy y)
1414. {
1415.     struct obj *otmp, *otmp2;
1416. 
1417.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp2) {
1418.         if (otmp == uball)
1419.             unpunish();
1420.         /* after unpunish(), or might get deallocated chain */
1421.         otmp2 = otmp->nexthere;
1422.         if (otmp == uchain)
1423.             continue;
1424.         delobj(otmp);
1425.     }
1426. }
1427. 
1428. /* normal object deletion (if unpaid, it remains on the bill) */
1429. void
1430. delobj(struct obj *obj)
1431. {
1432.     delobj_core(obj, FALSE);
1433. }
1434. 
1435. /* destroy object; caller has control over whether to destroy something
1436.    that ordinarily shouldn't be destroyed */
1437. void
1438. delobj_core(
1439.     struct obj *obj,
1440.     boolean force) /* 'force==TRUE' used when reviving Rider corpses */
1441. {
1442.     boolean update_map;
1443. 
1444.     /* obj_resists(obj,0,0) protects the Amulet, the invocation tools,
1445.        and Rider corpses */
1446.     if (!force && obj_resists(obj, 0, 0)) {
1447.         /* player might be doing something stupid, but we
1448.          * can't guarantee that.  assume special artifacts
1449.          * are indestructible via drawbridges, and exploding
1450.          * chests, and golem creation, and ...
1451.          */
1452.         obj->in_use = 0; /* in case caller has set this to 1 */
1453.         return;
1454.     }
1455.     update_map = (obj->where == OBJ_FLOOR);
1456.     obj_extract_self(obj);
1457.     if (update_map) { /* floor object's coordinates are always up to date */
1458.         maybe_unhide_at(obj->ox, obj->oy);
1459.         newsym(obj->ox, obj->oy);
1460.     }
1461.     obfree(obj, (struct obj *) 0); /* frees contents also */
1462. }
1463. 
1464. /* try to find a particular type of object at designated map location */
1465. struct obj *
1466. sobj_at(int otyp, coordxy x, coordxy y)
1467. {
1468.     struct obj *otmp;
1469. 
1470.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp->nexthere)
1471.         if (otmp->otyp == otyp)
1472.             break;
1473. 
1474.     return otmp;
1475. }
1476. 
1477. /* sobj_at(&c) traversal -- find next object of specified type */
1478. struct obj *
1479. nxtobj(struct obj *obj, int type, boolean by_nexthere)
1480. {
1481.     struct obj *otmp;
1482. 
1483.     otmp = obj; /* start with the object after this one */
1484.     do {
1485.         otmp = !by_nexthere ? otmp->nobj : otmp->nexthere;
1486.         if (!otmp)
1487.             break;
1488.     } while (otmp->otyp != type);
1489. 
1490.     return otmp;
1491. }
1492. 
1493. /* return inventory object of type 'type' if hero has one, otherwise Null */
1494. struct obj *
1495. carrying(int type)
1496. {
1497.     struct obj *otmp;
1498. 
1499.     /* this could be replaced by 'return m_carrying(&gy.youmonst, type);' */
1500.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
1501.         if (otmp->otyp == type)
1502.             break;
1503.     return otmp;
1504. }
1505. 
1506. /* return inventory object of type that will petrify on touch */
1507. struct obj *
1508. carrying_stoning_corpse(void)
1509. {
1510.     struct obj *otmp;
1511. 
1512.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
1513.         if (otmp->otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm]))
1514.             break;
1515.     return otmp;
1516. }
1517. 
1518. /* Fictional and not-so-fictional currencies.
1519.  * http://concord.wikia.com/wiki/List_of_Fictional_Currencies
1520.  */
1521. static const char *const currencies[] = {
1522.     "Altarian Dollar",       /* The Hitchhiker's Guide to the Galaxy */
1523.     "Ankh-Morpork Dollar",   /* Discworld */
1524.     "auric",                 /* The Domination of Draka */
1525.     "buckazoid",             /* Space Quest */
1526.     "cirbozoid",             /* Starslip */
1527.     "credit chit",           /* Deus Ex */
1528.     "cubit",                 /* Battlestar Galactica */
1529.     "Flanian Pobble Bead",   /* The Hitchhiker's Guide to the Galaxy */
1530.     "fretzer",               /* Jules Verne */
1531.     "imperial credit",       /* Star Wars */
1532.     "Hong Kong Luna Dollar", /* The Moon is a Harsh Mistress */
1533.     "kongbuck",              /* Snow Crash */
1534.     "nanite",                /* System Shock 2 */
1535.     "quatloo",               /* Star Trek, Sim City */
1536.     "simoleon",              /* Sim City */
1537.     "solari",                /* Spaceballs */
1538.     "spacebuck",             /* Spaceballs */
1539.     "sporebuck",             /* Spore */
1540.     "Triganic Pu",           /* The Hitchhiker's Guide to the Galaxy */
1541.     "woolong",               /* Cowboy Bebop */
1542.     "zorkmid",               /* Zork, NetHack */
1543. };
1544. 
1545. const char *
1546. currency(long amount)
1547. {
1548.     const char *res;
1549. 
1550.     res = Hallucination ? ROLL_FROM(currencies) : "zorkmid";
1551.     if (amount != 1L)
1552.         res = makeplural(res);
1553.     return res;
1554. }
1555. 
1556. struct obj *
1557. u_carried_gloves(void)
1558. {
1559.     struct obj *otmp, *gloves = (struct obj *) 0;
1560. 
1561.     if (uarmg) {
1562.         gloves = uarmg;
1563.     } else {
1564.         for (otmp = gi.invent; otmp; otmp = otmp->nobj)
1565.             if (is_gloves(otmp)) {
1566.                 gloves = otmp;
1567.                 break;
1568.             }
1569.     }
1570.     return gloves;
1571. }
1572. 
1573. 
1574. /* 3.6 tribute */
1575. struct obj *
1576. u_have_novel(void)
1577. {
1578.     struct obj *otmp;
1579. 
1580.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
1581.         if (otmp->otyp == SPE_NOVEL)
1582.             return otmp;
1583.     return (struct obj *) 0;
1584. }
1585. 
1586. struct obj *
1587. o_on(unsigned int id, struct obj *objchn)
1588. {
1589.     struct obj *temp;
1590. 
1591.     while (objchn) {
1592.         if (objchn->o_id == id)
1593.             return objchn;
1594.         if (Has_contents(objchn) && (temp = o_on(id, objchn->cobj)))
1595.             return temp;
1596.         objchn = objchn->nobj;
1597.     }
1598.     return (struct obj *) 0;
1599. }
1600. 
1601. boolean
1602. obj_here(struct obj *obj, coordxy x, coordxy y)
1603. {
1604.     struct obj *otmp;
1605. 
1606.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp->nexthere)
1607.         if (obj == otmp)
1608.             return TRUE;
1609.     return FALSE;
1610. }
1611. 
1612. struct obj *
1613. g_at(coordxy x, coordxy y)
1614. {
1615.     struct obj *obj = svl.level.objects[x][y];
1616. 
1617.     while (obj) {
1618.         if (obj->oclass == COIN_CLASS)
1619.             return obj;
1620.         obj = obj->nexthere;
1621.     }
1622.     return (struct obj *) 0;
1623. }
1624. 
1625. /* compact a string of inventory letters by dashing runs of letters */
1626. staticfn void
1627. compactify(char *buf)
1628. {
1629.     int i1 = 1, i2 = 1;
1630.     char ilet, ilet1, ilet2;
1631. 
1632.     ilet2 = buf[0];
1633.     ilet1 = buf[1];
1634.     buf[++i2] = buf[++i1];
1635.     ilet = buf[i1];
1636.     while (ilet) {
1637.         if (ilet == ilet1 + 1) {
1638.             if (ilet1 == ilet2 + 1)
1639.                 buf[i2 - 1] = ilet1 = '-';
1640.             else if (ilet2 == '-') {
1641.                 buf[i2 - 1] = ++ilet1;
1642.                 buf[i2] = buf[++i1];
1643.                 ilet = buf[i1];
1644.                 continue;
1645.             }
1646.         } else if (ilet == NOINVSYM) {
1647.             /* compact three or more consecutive '#'
1648.                characters into "#-#" */
1649.             if (i2 >= 2 && buf[i2 - 2] == NOINVSYM && buf[i2 - 1] == NOINVSYM)
1650.                 buf[i2 - 1] = '-';
1651.             else if (i2 >= 3 && buf[i2 - 3] == NOINVSYM && buf[i2 - 2] == '-'
1652.                      && buf[i2 - 1] == NOINVSYM)
1653.                 --i2;
1654.         }
1655.         ilet2 = ilet1;
1656.         ilet1 = ilet;
1657.         buf[++i2] = buf[++i1];
1658.         ilet = buf[i1];
1659.     }
1660. }
1661. 
1662. /* some objects shouldn't be split when count given to getobj or askchain */
1663. boolean
1664. splittable(struct obj *obj)
1665. {
1666.     return !((obj->otyp == LOADSTONE && obj->cursed)
1667.              || (obj == uwep && welded(uwep)));
1668. }
1669. 
1670. /* match the prompt for either 'T' or 'R' command */
1671. staticfn boolean
1672. taking_off(const char *action)
1673. {
1674.     return !strcmp(action, "take off") || !strcmp(action, "remove");
1675. }
1676. 
1677. staticfn void
1678. mime_action(const char *word)
1679. {
1680.     char buf[BUFSZ];
1681.     char *bp, *pfx, *sfx;
1682. 
1683.     Strcpy(buf, word);
1684.     bp = pfx = sfx = (char *) 0;
1685. 
1686.     if ((bp = strstr(buf, " on the ")) != 0) {
1687.         /* rub on the stone[s] */
1688.         *bp = '\0';
1689.         sfx = (bp + 1); /* "something <sfx>" */
1690.     }
1691.     if ((!strncmp(buf, "rub the ", 8) && strstr(buf + 8, " on"))
1692.         || (!strncmp(buf, "dip ", 4) && strstr(buf + 4, " into"))) {
1693.         /* "rub the royal jelly on" -> "rubbing the royal jelly on", or
1694.            "dip <foo> into" => "dipping <foo> into" */
1695.         buf[3] = '\0';
1696.         pfx = &buf[3 + 1]; /* "<pfx> something" */
1697.     }
1698.     if ((bp = strstr(buf, " or ")) != 0) {
1699.         *bp = '\0';
1700.         bp = (rn2(2) ? buf : (bp + 4));
1701.     } else
1702.         bp = buf;
1703. 
1704.     You("mime %s%s%s something%s%s.", ing_suffix(bp),
1705.         pfx ? " " : "", pfx ? pfx : "", sfx ? " " : "", sfx ? sfx : "");
1706. }
1707. 
1708. /* getobj callback that allows any object - but not hands. */
1709. int
1710. any_obj_ok(struct obj *obj)
1711. {
1712.     if (obj)
1713.         return GETOBJ_SUGGEST;
1714.     return GETOBJ_EXCLUDE;
1715. }
1716. 
1717. /* return string describing your hands based on action. */
1718. staticfn char *
1719. getobj_hands_txt(const char *action, char *qbuf)
1720. {
1721.     if (!strcmp(action, "grease")) {
1722.         Sprintf(qbuf, "your %s", fingers_or_gloves(FALSE));
1723.     } else if (!strcmp(action, "write with")) {
1724.         Sprintf(qbuf, "your %s", body_part(FINGERTIP));
1725.     } else if (!strcmp(action, "wield")) {
1726.         Sprintf(qbuf, "your %s %s%s", uarmg ? "gloved" : "bare",
1727.                 makeplural(body_part(HAND)),
1728.                 !uwep ? " (wielded)" : "");
1729.     } else if (!strcmp(action, "ready")) {
1730.         Sprintf(qbuf, "empty quiver%s",
1731.                 !uquiver ? " (nothing readied)" : "");
1732.     } else {
1733.         Sprintf(qbuf, "your %s", makeplural(body_part(HAND)));
1734.     }
1735.     return qbuf;
1736. }
1737. 
1738. /*
1739.  * getobj returns:
1740.  *      struct obj *xxx:        object to do something with.
1741.  *      (struct obj *) 0        error return: no object.
1742.  *      &hands_obj              explicitly no object (as in w-).
1743.  * The obj_ok callback should not have side effects (apart from
1744.  * abnormal-behavior things like impossible calls); it can be called multiple
1745.  * times on the same object during the execution of this function.
1746.  * Callbacks' argument is either a valid object pointer or a null pointer,
1747.  * which represents the validity of doing that action on HANDS_SYM. getobj
1748.  * won't call it with &hands_obj, so its behavior can be undefined in that
1749.  * case.
1750.  */
1751. struct obj *
1752. getobj(
1753.     const char *word,       /* usually a direct verb such as "drop" */
1754.     int (*obj_ok)(OBJ_P),   /* callback to classify an object's suitability */
1755.     unsigned int ctrlflags) /* some control to fine-tune the behavior */
1756. {
1757.     struct obj *otmp;
1758.     char ilet = 0;
1759.     char buf[BUFSZ], qbuf[QBUFSZ];
1760.     char lets[BUFSZ], altlets[BUFSZ];
1761.     int suggested = 0;
1762.     char *bp = buf, *ap = altlets;
1763.     boolean allowcnt = (ctrlflags & GETOBJ_ALLOWCNT),
1764.             forceprompt = (ctrlflags & GETOBJ_PROMPT),
1765.             allownone = FALSE;
1766.     int inaccess = 0; /* counts GETOBJ_EXCLUDE_INACCESS items to decide
1767.                        * between "you don't have anything to <foo>"
1768.                        * versus "you don't have anything _else_ to <foo>"
1769.                        * (also used for GETOBJ_EXCLUDE_NONINVENT) */
1770.     long cnt = 0L;
1771.     boolean cntgiven = FALSE;
1772.     boolean msggiven = FALSE;
1773.     boolean oneloop = FALSE;
1774.     Loot *sortedinvent, *srtinv;
1775.     struct _cmd_queue cq, *cmdq;
1776.     boolean need_more_cq = FALSE;
1777. 
1778.  need_more_cq:
1779.     if ((cmdq = cmdq_pop()) != 0) {
1780.         cq = *cmdq;
1781.         free(cmdq);
1782.         /* user-input means pick something interactively now, with more
1783.            in the command queue for after that; if not user-input, it
1784.            has to be a key here */
1785.         if (cq.typ != CMDQ_USER_INPUT) {
1786.             otmp = 0; /* in case of non-key or lookup failure */
1787.             if (cq.typ == CMDQ_KEY) {
1788.                 int v;
1789. 
1790.                 if (cq.key == HANDS_SYM) {
1791.                     /* check whether the hands/self choice is suitable */
1792.                     v = (*obj_ok)((struct obj *) 0);
1793.                     if (v == GETOBJ_SUGGEST || v == GETOBJ_DOWNPLAY)
1794.                         otmp = &hands_obj;
1795.                 } else {
1796.                     /* there could be more than one match if key is '#';
1797.                        take first one which passes the obj_ok callback */
1798.                     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
1799.                         if (otmp->invlet == cq.key) {
1800.                             v = (*obj_ok)(otmp);
1801.                             if (v == GETOBJ_SUGGEST || v == GETOBJ_DOWNPLAY)
1802.                                 break;
1803.                         }
1804.                 }
1805.             } else if (cq.typ == CMDQ_INT) {
1806.                 /* getting a partial stack */
1807.                 if (!cntgiven && allowcnt) {
1808.                     cnt = (long) cq.intval;
1809.                     cntgiven = TRUE;
1810.                     goto need_more_cq; /* now, get CMDQ_KEY */
1811.                 } else {
1812.                     cmdq_clear(CQ_CANNED);
1813.                     /* should maybe clear the CQ_REPEAT too? */
1814.                     return NULL;
1815.                 }
1816.             }
1817.             if (!otmp) {           /* didn't find what we were looking for, */
1818.                 cmdq_clear(CQ_CANNED); /* so discard any other queued cmnds */
1819.             } else if (cntgiven) {
1820.                 /* if stack is smaller than count, drop the whole stack */
1821.                 if (cnt < 1L || otmp->quan <= cnt)
1822.                     cntgiven = FALSE;
1823.                 goto split_otmp;
1824.             }
1825.             return otmp;
1826.         } /* !CMDQ_USER_INPUT */
1827.     } else if (need_more_cq) {
1828.         return NULL;
1829.     }
1830. 
1831.     /* is "hands"/"self" a valid thing to do this action on? */
1832.     switch ((*obj_ok)((struct obj *) 0)) {
1833.     case GETOBJ_SUGGEST: /* treat as likely candidate */
1834.         allownone = TRUE;
1835.         *bp++ = HANDS_SYM;
1836.         *bp++ = ' '; /* put a space after the '-' in the prompt */
1837.         break;
1838.     case GETOBJ_DOWNPLAY: /* acceptable but not shown as likely choice */
1839.     case GETOBJ_EXCLUDE_INACCESS:   /* nothing currently gives this for '-'
1840.                                      * but theoretically could if wearing
1841.                                      * gloves */
1842.     case GETOBJ_EXCLUDE_SELECTABLE: /* ditto, I think... */
1843.         allownone = TRUE;
1844.         *ap++ = HANDS_SYM;
1845.         break;
1846.     case GETOBJ_EXCLUDE_NONINVENT: /* player skipped some alternative that's
1847.                                     * not in inventory, now the hands/self
1848.                                     * possibility is telling us so */
1849.         forceprompt = FALSE;
1850.         inaccess++;
1851.         break;
1852.     default:
1853.         break;
1854.     }
1855. 
1856.     if (!flags.invlet_constant)
1857.         reassign();
1858. 
1859.     /* force invent to be in invlet order before collecting candidate
1860.        inventory letters */
1861.     sortedinvent = sortloot(&gi.invent, SORTLOOT_INVLET, FALSE,
1862.                             (boolean (*)(OBJ_P)) 0);
1863. 
1864.     for (srtinv = sortedinvent; (otmp = srtinv->obj) != 0; ++srtinv) {
1865.         if (&bp[suggested] == &buf[sizeof buf - 1]
1866.             || ap == &altlets[sizeof altlets - 1]) {
1867.             /* we must have a huge number of noinvsym items somehow */
1868.             impossible("getobj: inventory overflow");
1869.             break;
1870.         }
1871. 
1872.         bp[suggested++] = otmp->invlet;
1873.         switch ((*obj_ok)(otmp)) {
1874.         case GETOBJ_EXCLUDE_INACCESS:
1875.             /* remove inaccessible things */
1876.             suggested--;
1877.             inaccess++;
1878.             break;
1879.         case GETOBJ_EXCLUDE:
1880.         case GETOBJ_EXCLUDE_SELECTABLE:
1881.             /* remove more inappropriate things, but unlike the first it won't
1882.                trigger an "else" in "you don't have anything else to ___" */
1883.             suggested--;
1884.             break;
1885.         case GETOBJ_DOWNPLAY:
1886.             /* acceptable but not listed as likely candidates in the prompt
1887.                or in the inventory subset if player responds with '?' - thus,
1888.                don't add it to lets with bp, but add it to altlets with ap */
1889.             suggested--;
1890.             forceprompt = TRUE;
1891.             *ap++ = otmp->invlet;
1892.             break;
1893.         case GETOBJ_SUGGEST:
1894.             break; /* adding otmp->invlet is all that's needed */
1895.         case GETOBJ_EXCLUDE_NONINVENT: /* not applicable for invent items */
1896.         default:
1897.             impossible("bad return from getobj callback");
1898.         }
1899.     }
1900.     unsortloot(&sortedinvent);
1901. 
1902.     bp[suggested] = '\0';
1903.     /* If no objects were suggested but we added '- ' at the beginning for
1904.      * hands, destroy the trailing space */
1905.     if (suggested == 0 && bp > buf && bp[-1] == ' ')
1906.         *--bp = '\0';
1907.     Strcpy(lets, bp); /* necessary since we destroy buf */
1908.     if (suggested > 5)      /* compactify string */
1909.         compactify(bp);
1910.     *ap = '\0';
1911. 
1912.     if (suggested == 0 && !forceprompt && !allownone) {
1913.         You("don't have anything %sto %s.", inaccess ? "else " : "", word);
1914.         return (struct obj *) 0;
1915.     }
1916.     for (;;) {
1917.         cnt = 0L;
1918.         cntgiven = FALSE;
1919.         Sprintf(qbuf, "What do you want to %s?", word);
1920.         if (gi.in_doagain) {
1921.             ilet = readchar();
1922.         } else if (iflags.force_invmenu) {
1923.             /* don't overwrite a possible quitchars */
1924.             if (!oneloop)
1925.                 ilet = (*lets || *altlets) ? '?' : '*';
1926.             if (!msggiven)
1927.                 putmsghistory(qbuf, FALSE);
1928.             msggiven = TRUE;
1929.             oneloop = TRUE;
1930.         } else {
1931.             if (!buf[0])
1932.                 Strcat(qbuf, " [*]");
1933.             else
1934.                 Sprintf(eos(qbuf), " [%s or ?*]", buf);
1935.             ilet = yn_function(qbuf, (char *) 0, '\0', FALSE);
1936.         }
1937.         if (digit(ilet)) {
1938.             long tmpcnt = 0L;
1939. 
1940.             if (!allowcnt) {
1941.                 pline("No count allowed with this command.");
1942.                 continue;
1943.             }
1944.             ilet = get_count(NULL, ilet, LARGEST_INT, &tmpcnt, GC_SAVEHIST);
1945.             if (tmpcnt) {
1946.                 cnt = tmpcnt;
1947.                 cntgiven = TRUE;
1948.             }
1949.         }
1950.         if (strchr(quitchars, ilet)) {
1951.             if (flags.verbose)
1952.                 pline1(Never_mind);
1953.             return (struct obj *) 0;
1954.         }
1955.         if (ilet == HANDS_SYM) { /* '-' */
1956.             if (!allownone)
1957.                 mime_action(word);
1958.             return (allownone ? &hands_obj : (struct obj *) 0);
1959.         }
1960.  redo_menu:
1961.         /* since gold is now kept in inventory, we need to do processing for
1962.            select-from-invent before checking whether gold has been picked */
1963.         if (ilet == '?' || ilet == '*') {
1964.             char *allowed_choices = (ilet == '?') ? lets : (char *) 0;
1965.             long ctmp = 0L;
1966.             char menuquery[QBUFSZ];
1967.             char *handsbuf = (char *) 0;
1968. 
1969.             if (ilet == '?' && !*lets && *altlets)
1970.                 allowed_choices = altlets;
1971. 
1972.             menuquery[0] = qbuf[0] = '\0';
1973.             if (iflags.force_invmenu)
1974.                 Snprintf(menuquery, sizeof menuquery,
1975.                          "What do you want to %s?", word);
1976.             if (!allowed_choices || *allowed_choices == HANDS_SYM
1977.                 || *buf == HANDS_SYM)
1978.                 handsbuf = getobj_hands_txt(word, qbuf);
1979.             ilet = display_pickinv(allowed_choices, handsbuf,
1980.                                    menuquery, allownone, TRUE,
1981.                                    allowcnt ? &ctmp : (long *) 0);
1982.             if (!ilet) {
1983.                 if (oneloop)
1984.                     return (struct obj *) 0;
1985.                 continue;
1986.             }
1987.             if (ilet == HANDS_SYM)
1988.                 return &hands_obj;
1989.             if (ilet == '\033') {
1990.                 if (flags.verbose)
1991.                     pline1(Never_mind);
1992.                 return (struct obj *) 0;
1993.             }
1994.             if (ilet == '*' || ilet == '?')
1995.                 goto redo_menu;
1996.             if (allowcnt && ctmp >= 0L) {
1997.                 cnt = ctmp;
1998.                 cntgiven = TRUE;
1999.             }
2000.             /* they typed a letter (not a space) at the prompt */
2001.         }
2002.         /* find the item which was picked */
2003.         for (otmp = gi.invent; otmp; otmp = otmp->nobj)
2004.             if (otmp->invlet == ilet)
2005.                 break;
2006.         /* some items have restrictions */
2007.         if (ilet == GOLD_SYM
2008.             /* guard against the [hypothetical] chance of having more
2009.                than one invent slot of gold and picking the non-'$' one */
2010.             || (otmp && otmp->oclass == COIN_CLASS)) {
2011.             if (otmp && obj_ok(otmp) <= GETOBJ_EXCLUDE) {
2012.                 You("cannot %s gold.", word);
2013.                 return (struct obj *) 0;
2014.             }
2015.             /*
2016.              * Historical note: early Nethack had a bug which was
2017.              * first reported for Larn, where trying to drop 2^32-n
2018.              * gold pieces was allowed, and did interesting things to
2019.              * your money supply.  The LRS is the tax bureau from Larn.
2020.              */
2021.             if (cntgiven && cnt <= 0L) {
2022.                 if (cnt < 0L)
2023.                     pline_The("LRS would be very interested to know"
2024.                               " you have that much.");
2025.                 return (struct obj *) 0;
2026.             }
2027.         }
2028.         if (cntgiven && !strcmp(word, "throw")) {
2029.             static const char only_one[] = "can only throw one at a time";
2030.             boolean coins;
2031. 
2032.             /* permit counts for throwing gold, but don't accept counts
2033.                for other things since the throw code will split off a
2034.                single item anyway; if populating quiver, 'word' will be
2035.                "ready" or "fire" and this restriction doesn't apply */
2036.             if (cnt == 0L || !otmp)
2037.                 return (struct obj *) 0;
2038.             coins = (otmp->oclass == COIN_CLASS);
2039.             if (cnt > 1L && (!coins || cnt > otmp->quan)) {
2040.                 if (cnt > otmp->quan)
2041.                     You("only have %ld%s%s.", otmp->quan,
2042.                         (!coins && otmp->quan > 1L) ? " and " : "",
2043.                         (!coins && otmp->quan > 1L) ? only_one : "");
2044.                 else
2045.                     You("%s.", only_one);
2046.                 continue;
2047.             }
2048.         }
2049.         disp.botl = TRUE; /* May have changed the amount of money */
2050.         if (otmp && !gi.in_doagain) {
2051.             if (cntgiven && cnt > 0L)
2052.                 cmdq_add_int(CQ_REPEAT, cnt);
2053.             cmdq_add_key(CQ_REPEAT, ilet);
2054.         }
2055.         /* [we used to set otmp (by finding ilet in invent) here, but
2056.            that's been moved above so that otmp can be checked earlier] */
2057.         /* verify the chosen object */
2058.         if (!otmp) {
2059.             You("don't have that object.");
2060.             if (gi.in_doagain)
2061.                 return (struct obj *) 0;
2062.             continue;
2063.         } else if (cnt < 0L || otmp->quan < cnt) {
2064.             You("don't have that many!  You have only %ld.", otmp->quan);
2065.             if (gi.in_doagain)
2066.                 return (struct obj *) 0;
2067.             continue;
2068.         }
2069.         break;
2070.     }
2071.     if (obj_ok(otmp) == GETOBJ_EXCLUDE) {
2072.         silly_thing(word, otmp);
2073.         return (struct obj *) 0;
2074.     }
2075.  split_otmp:
2076.     if (cntgiven) {
2077.         if (cnt == 0L)
2078.             return (struct obj *) 0;
2079.         if (cnt != otmp->quan) {
2080.             /* don't split a stack of cursed loadstones */
2081.             if (splittable(otmp))
2082.                 otmp = splitobj(otmp, cnt);
2083.             else if (otmp->otyp == LOADSTONE && otmp->cursed)
2084.                 /* kludge for canletgo()'s can't-drop-this message */
2085.                 otmp->corpsenm = (int) cnt;
2086.         }
2087.     }
2088.     return otmp;
2089. }
2090. 
2091. DISABLE_WARNING_FORMAT_NONLITERAL
2092. 
2093. void
2094. silly_thing(const char *word,
2095.             struct obj *otmp)
2096. {
2097. #ifdef OBSOLETE_HANDLING
2098.     /* 'P','R' vs 'W','T' handling is obsolete */
2099.     const char *s1, *s2, *s3;
2100.     int ocls = otmp->oclass, otyp = otmp->otyp;
2101. 
2102.     s1 = s2 = s3 = 0;
2103.     /* check for attempted use of accessory commands ('P','R') on armor
2104.        and for corresponding armor commands ('W','T') on accessories */
2105.     if (ocls == ARMOR_CLASS) {
2106.         if (!strcmp(word, "put on"))
2107.             s1 = "W", s2 = "wear", s3 = "";
2108.         else if (!strcmp(word, "remove"))
2109.             s1 = "T", s2 = "take", s3 = " off";
2110.     } else if ((ocls == RING_CLASS || otyp == MEAT_RING)
2111.                || ocls == AMULET_CLASS
2112.                || (otyp == BLINDFOLD || otyp == TOWEL || otyp == LENSES)) {
2113.         if (!strcmp(word, "wear"))
2114.             s1 = "P", s2 = "put", s3 = " on";
2115.         else if (!strcmp(word, "take off"))
2116.             s1 = "R", s2 = "remove", s3 = "";
2117.     }
2118.     if (s1)
2119.         pline("Use the '%s' command to %s %s%s.", s1, s2,
2120.               !(is_plural(otmp) || pair_of(otmp)) ? "that" : "those", s3);
2121.     else
2122. #endif
2123.     /* see comment about Amulet of Yendor in objtyp_is_callable(do_name.c);
2124.        known fakes yield the silly thing feedback */
2125.     if (!strcmp(word, "call")
2126.         && (otmp->otyp == AMULET_OF_YENDOR
2127.             || (otmp->otyp == FAKE_AMULET_OF_YENDOR && !otmp->known)))
2128.         pline_The("Amulet doesn't like being called names.");
2129.     else
2130.         pline(silly_thing_to, word);
2131. }
2132. 
2133. RESTORE_WARNING_FORMAT_NONLITERAL
2134. 
2135. staticfn int
2136. ckvalidcat(struct obj *otmp)
2137. {
2138.     /* use allow_category() from pickup.c */
2139.     return (int) allow_category(otmp);
2140. }
2141. 
2142. staticfn int
2143. ckunpaid(struct obj *otmp)
2144. {
2145.     return (otmp->unpaid || (Has_contents(otmp) && count_unpaid(otmp->cobj)));
2146. }
2147. 
2148. boolean
2149. wearing_armor(void)
2150. {
2151.     return (boolean) (uarm || uarmc || uarmf || uarmg
2152.                       || uarmh || uarms || uarmu);
2153. }
2154. 
2155. boolean
2156. is_worn(struct obj *otmp)
2157. {
2158.     return (otmp->owornmask & (W_ARMOR | W_ACCESSORY | W_SADDLE | W_WEAPONS))
2159.             ? TRUE
2160.             : FALSE;
2161. }
2162. 
2163. /* is 'obj' being used by the hero?  worn, wielded, active lamp or leash;
2164.    not to be confused with obj->in_use, which finishes using up an item
2165.    (destroys it) if restoring a save file finds that bit set */
2166. boolean
2167. is_inuse(struct obj *obj)
2168. {
2169.     return (carried(obj) && (is_worn(obj) || tool_being_used(obj)));
2170. }
2171. 
2172. /* extra xprname() input that askchain() can't pass through safe_qbuf() */
2173. static struct xprnctx {
2174.     char let;
2175.     boolean dot;
2176. } safeq_xprn_ctx;
2177. 
2178. /* safe_qbuf() -> short_oname() callback */
2179. staticfn char *
2180. safeq_xprname(struct obj *obj)
2181. {
2182.     return xprname(obj, (char *) 0, safeq_xprn_ctx.let, safeq_xprn_ctx.dot,
2183.                    0L, 0L);
2184. }
2185. 
2186. /* alternate safe_qbuf() -> short_oname() callback */
2187. staticfn char *
2188. safeq_shortxprname(struct obj *obj)
2189. {
2190.     return xprname(obj, ansimpleoname(obj), safeq_xprn_ctx.let,
2191.                    safeq_xprn_ctx.dot, 0L, 0L);
2192. }
2193. 
2194. static NEARDATA const char removeables[] = { ARMOR_CLASS, WEAPON_CLASS,
2195.                                              RING_CLASS,  AMULET_CLASS,
2196.                                              TOOL_CLASS,  0 };
2197. 
2198. /* Interactive version of getobj - used for Drop, Identify, and Takeoff (A).
2199.    Return the number of times fn was called successfully.
2200.    If combo is TRUE, we just use this to get a category list. */
2201. int
2202. ggetobj(const char *word, int (*fn)(OBJ_P), int mx,
2203.         boolean combo, /* combination menu flag */
2204.         unsigned *resultflags)
2205. {
2206.     int (*ckfn)(OBJ_P) = (int (*)(OBJ_P)) 0;
2207.     boolean (*ofilter)(OBJ_P) = (boolean (*)(OBJ_P)) 0;
2208.     boolean takeoff, ident, allflag, m_seen;
2209.     int itemcount;
2210.     int oletct, iletct, unpaid, oc_of_sym;
2211.     char sym, *ip, olets[MAXOCLASSES + 6], ilets[MAXOCLASSES + 11];
2212.     char extra_removeables[3 + 1]; /* uwep,uswapwep,uquiver */
2213.     char buf[BUFSZ] = DUMMY, qbuf[QBUFSZ];
2214. 
2215.     if (!gi.invent) {
2216.         You("have nothing to %s.", word);
2217.         if (resultflags)
2218.             *resultflags = ALL_FINISHED;
2219.         return 0;
2220.     }
2221.     if (resultflags)
2222.         *resultflags = 0;
2223.     takeoff = ident = allflag = m_seen = FALSE;
2224.     add_valid_menu_class(0); /* reset */
2225.     if (taking_off(word)) {
2226.         takeoff = TRUE;
2227.         ofilter = is_worn;
2228.     } else if (!strcmp(word, "identify")) {
2229.         ident = TRUE;
2230.         ofilter = not_fully_identified;
2231.     }
2232. 
2233.     iletct = collect_obj_classes(ilets, gi.invent, FALSE, ofilter,
2234.                                  &itemcount);
2235.     unpaid = count_unpaid(gi.invent);
2236. 
2237.     if (ident && !iletct) {
2238.         return -1; /* no further identifications */
2239.     } else if (gi.invent) {
2240.         ilets[iletct++] = ' ';
2241.         if (unpaid)
2242.             ilets[iletct++] = 'u';
2243.         if (count_buc(gi.invent, BUC_BLESSED, ofilter))
2244.             ilets[iletct++] = 'B';
2245.         if (count_buc(gi.invent, BUC_UNCURSED, ofilter))
2246.             ilets[iletct++] = 'U';
2247.         if (count_buc(gi.invent, BUC_CURSED, ofilter))
2248.             ilets[iletct++] = 'C';
2249.         if (count_buc(gi.invent, BUC_UNKNOWN, ofilter))
2250.             ilets[iletct++] = 'X';
2251.         if (count_justpicked(gi.invent))
2252.             ilets[iletct++] = 'P';
2253.         ilets[iletct++] = 'a';
2254.     }
2255.     ilets[iletct++] = 'i';
2256.     if (!combo)
2257.         ilets[iletct++] = 'm'; /* allow menu presentation on request */
2258.     ilets[iletct] = '\0';
2259. 
2260.     for (;;) {
2261.         Sprintf(qbuf, "What kinds of thing do you want to %s? [%s]",
2262.                 word, ilets);
2263.         getlin(qbuf, buf);
2264.         if (buf[0] == '\033')
2265.             return 0;
2266.         if (strchr(buf, 'i')) {
2267.             char ailets[1+26+26+1+5+1]; /* $ + a-z + A-Z + # + slop + \0 */
2268.             struct obj *otmp, *nextobj;
2269. 
2270.             /* applicable inventory letters; if empty, show entire invent */
2271.             ailets[0] = '\0';
2272.             if (ofilter)
2273.                 for (otmp = gi.invent; otmp; otmp = nextobj) {
2274.                     nextobj = otmp->nobj;
2275.                     /* strchr() check: limit overflow items to one '#' */
2276.                     if ((*ofilter)(otmp) && !strchr(ailets, otmp->invlet))
2277.                         (void) strkitten(ailets, otmp->invlet);
2278.                 }
2279.             if (display_inventory(ailets, TRUE) == '\033')
2280.                 return 0;
2281.         } else
2282.             break;
2283.     }
2284. 
2285.     extra_removeables[0] = '\0';
2286.     if (takeoff) {
2287.         /* arbitrary types of items can be placed in the weapon slots
2288.            [any duplicate entries in extra_removeables[] won't matter] */
2289.         if (uwep)
2290.             (void) strkitten(extra_removeables, uwep->oclass);
2291.         if (uswapwep)
2292.             (void) strkitten(extra_removeables, uswapwep->oclass);
2293.         if (uquiver)
2294.             (void) strkitten(extra_removeables, uquiver->oclass);
2295.     }
2296. 
2297.     ip = buf;
2298.     olets[oletct = 0] = '\0';
2299.     while ((sym = *ip++) != '\0') {
2300.         if (sym == ' ')
2301.             continue;
2302.         oc_of_sym = def_char_to_objclass(sym);
2303.         if (takeoff && oc_of_sym != MAXOCLASSES) {
2304.             if (strchr(extra_removeables, oc_of_sym)) {
2305.                 ; /* skip rest of takeoff checks */
2306.             } else if (!strchr(removeables, oc_of_sym)) {
2307.                 pline("Not applicable.");
2308.                 return 0;
2309.             } else if (oc_of_sym == ARMOR_CLASS && !wearing_armor()) {
2310.                 noarmor(FALSE);
2311.                 return 0;
2312.             } else if (oc_of_sym == WEAPON_CLASS && !uwep && !uswapwep
2313.                        && !uquiver) {
2314.                 You("are not wielding anything.");
2315.                 return 0;
2316.             } else if (oc_of_sym == RING_CLASS && !uright && !uleft) {
2317.                 You("are not wearing rings.");
2318.                 return 0;
2319.             } else if (oc_of_sym == AMULET_CLASS && !uamul) {
2320.                 You("are not wearing an amulet.");
2321.                 return 0;
2322.             } else if (oc_of_sym == TOOL_CLASS && !ublindf) {
2323.                 You("are not wearing a blindfold.");
2324.                 return 0;
2325.             }
2326.         }
2327. 
2328.         if (sym == 'a') {
2329.             allflag = TRUE;
2330.         } else if (sym == 'A') {
2331.             ; /* same as the default */
2332.         } else if (sym == 'u') {
2333.             add_valid_menu_class('u');
2334.             ckfn = ckunpaid;
2335.         } else if (strchr("BUCXP", sym)) {
2336.             add_valid_menu_class(sym); /* 'B','U','C','X', or 'P' */
2337.             ckfn = ckvalidcat;
2338.         } else if (sym == 'm') {
2339.             m_seen = TRUE;
2340.         } else if (oc_of_sym == MAXOCLASSES) {
2341.             You("don't have any %c's.", sym);
2342.         } else {
2343.             if (!strchr(olets, oc_of_sym)) {
2344.                 add_valid_menu_class(oc_of_sym);
2345.                 olets[oletct++] = oc_of_sym;
2346.                 olets[oletct] = '\0';
2347.             }
2348.         }
2349.     }
2350. 
2351.     if (m_seen) {
2352.         return (allflag
2353.                 || (!oletct && ckfn != ckunpaid && ckfn != ckvalidcat))
2354.                ? -2 : -3;
2355.     } else if (flags.menu_style != MENU_TRADITIONAL && combo && !allflag) {
2356.         return 0;
2357.     } else {
2358.         int cnt = askchain(&gi.invent, olets, allflag, fn, ckfn, mx, word);
2359.         /*
2360.          * askchain() has already finished the job in this case
2361.          * so set a special flag to convey that back to the caller
2362.          * so that it won't continue processing.
2363.          * Fix for bug C331-1 reported by Irina Rempt-Drijfhout.
2364.          */
2365.         if (combo && allflag && resultflags)
2366.             *resultflags |= ALL_FINISHED;
2367.         return cnt;
2368.     }
2369. }
2370. 
2371. /*
2372.  * Walk through the chain starting at objchn and ask for all objects
2373.  * with olet in olets (if nonNULL) and satisfying ckfn (if nonnull)
2374.  * whether the action in question (i.e., fn) has to be performed.
2375.  */
2376. int
2377. askchain(
2378.     struct obj **objchn, /* *objchn might change */
2379.     const char *olets,   /* olets is an Obj Class char array */
2380.     int allflag,         /* bypass prompting about individual items */
2381.     int (*fn)(OBJ_P),    /* action to perform on selected items */
2382.     int (*ckfn)(OBJ_P),  /* callback to decided if an item is selectable */
2383.     int mx,              /* if non-0, maximum number of objects to process */
2384.     const char *word)    /* name of the action */
2385. {
2386.     struct obj *otmp, *otmpo;
2387.     char sym, ilet;
2388.     int cnt = 0, dud = 0, tmp;
2389.     boolean takeoff, nodot, ident, take_out, put_in, first, ininv, bycat;
2390.     char qbuf[QBUFSZ], qpfx[QBUFSZ];
2391.     Loot *sortedchn = 0;
2392. 
2393.     takeoff = taking_off(word);
2394.     ident = !strcmp(word, "identify");
2395.     take_out = !strcmp(word, "take out");
2396.     put_in = !strcmp(word, "put in");
2397.     nodot = (!strcmp(word, "nodot") || !strcmp(word, "drop") || ident
2398.              || takeoff || take_out || put_in);
2399.     ininv = (*objchn == gi.invent);
2400.     bycat = (menu_class_present('u')
2401.              || menu_class_present('B') || menu_class_present('U')
2402.              || menu_class_present('C') || menu_class_present('X')
2403.              || menu_class_present('P'));
2404. 
2405.     /* someday maybe we'll sort by 'olets' too (temporarily replace
2406.        flags.packorder and pass SORTLOOT_PACK), but not yet... */
2407.     sortedchn = sortloot(objchn, SORTLOOT_INVLET, FALSE,
2408.                          (boolean (*)(OBJ_P)) 0);
2409. 
2410.     first = TRUE;
2411.     /*
2412.      * Interrogate in the object class order specified.
2413.      * For example, if a person specifies =/ then first all rings
2414.      * will be asked about followed by all wands.  -dgk
2415.      */
2416.  nextclass:
2417.     ilet = 'a' - 1;
2418.     if (*objchn && (*objchn)->oclass == COIN_CLASS)
2419.         ilet--;                     /* extra iteration */
2420.     /*
2421.      * Multiple Drop can change the gi.invent chain while it operates
2422.      * (dropping a burning potion of oil while levitating creates
2423.      * an explosion which can destroy inventory items), so simple
2424.      * list traversal
2425.      *  for (otmp = *objchn; otmp; otmp = otmp2) {
2426.      *      otmp2 = otmp->nobj;
2427.      *      ...
2428.      *  }
2429.      * is inadequate here.  Use each object's bypass bit to keep
2430.      * track of which list elements have already been processed.
2431.      */
2432.     bypass_objlist(*objchn, FALSE); /* clear chain's bypass bits */
2433.     while ((otmp = nxt_unbypassed_loot(sortedchn, *objchn)) != 0) {
2434.         if (ilet == 'z')
2435.             ilet = 'A';
2436.         else if (ilet == 'Z')
2437.             ilet = NOINVSYM; /* '#' */
2438.         else
2439.             ilet++;
2440.         if (olets && *olets && otmp->oclass != *olets)
2441.             continue;
2442.         if (takeoff && !is_worn(otmp))
2443.             continue;
2444.         if (ident && !not_fully_identified(otmp))
2445.             continue;
2446.         if (ckfn && !(*ckfn)(otmp))
2447.             continue;
2448.         if (bycat && !ckvalidcat(otmp))
2449.             continue;
2450.         if (!allflag) {
2451.             safeq_xprn_ctx.let = ilet;
2452.             safeq_xprn_ctx.dot = !nodot;
2453.             *qpfx = '\0';
2454.             if (first) {
2455.                 /* traditional_loot() skips prompting when only one
2456.                    class of objects is involved, so prefix the first
2457.                    object being queried here with an explanation why */
2458.                 if (take_out || put_in)
2459.                     Sprintf(qpfx, "%s: ", word), *qpfx = highc(*qpfx);
2460.                 first = FALSE;
2461.             }
2462.             (void) safe_qbuf(qbuf, qpfx, "?", otmp,
2463.                              ininv ? safeq_xprname : doname,
2464.                              ininv ? safeq_shortxprname : ansimpleoname,
2465.                              "item");
2466.             /* nyaq(qbuf) or nyNaq(qbuf), bypassing canned input for ^A */
2467.             sym = yn_function(qbuf,
2468.                               (takeoff || ident || otmp->quan < 2L)
2469.                                 ? ynaqchars : ynNaqchars,
2470.                               'n', FALSE);
2471.         } else
2472.             sym = 'y';
2473. 
2474.         otmpo = otmp;
2475.         if (sym == '#') {
2476.             /* Number was entered; split the object unless it corresponds
2477.                to 'none' or 'all'.  2 special cases: cursed loadstones and
2478.                welded weapons (eg, multiple daggers) will remain as merged
2479.                unit; done to avoid splitting an object that won't be
2480.                droppable (even if we're picking up rather than dropping). */
2481.             if (!yn_number) {
2482.                 sym = 'n';
2483.             } else {
2484.                 sym = 'y';
2485.                 if (yn_number < otmp->quan && splittable(otmp))
2486.                     otmp = splitobj(otmp, yn_number);
2487.             }
2488.         }
2489.         switch (sym) {
2490.         case 'a':
2491.             allflag = 1;
2492.             FALLTHROUGH;
2493.             /*FALLTHRU*/
2494.         case 'y':
2495.             tmp = (*fn)(otmp);
2496.             if (tmp <= 0) {
2497.                 if (container_gone(fn)) {
2498.                     /* otmp caused magic bag to explode;
2499.                        both are now gone */
2500.                     otmp = 0; /* and return */
2501.                 } else if (otmp && otmp != otmpo) {
2502.                     /* split occurred, merge again */
2503.                     (void) unsplitobj(otmp);
2504.                 }
2505.                 if (tmp < 0)
2506.                     goto ret;
2507.             }
2508.             cnt += tmp;
2509.             if (--mx == 0)
2510.                 goto ret;
2511.             FALLTHROUGH;
2512.             /*FALLTHRU*/
2513.         case 'n':
2514.             if (nodot)
2515.                 dud++;
2516.             FALLTHROUGH;
2517.             /*FALLTHRU*/
2518.         default:
2519.             break;
2520.         case 'q':
2521.             /* special case for seffects() */
2522.             if (ident)
2523.                 cnt = -1;
2524.             goto ret;
2525.         }
2526.     }
2527.     if (olets && *olets && *++olets)
2528.         goto nextclass;
2529. 
2530.     if (!takeoff && (dud || cnt))
2531.         pline("That was all.");
2532.     else if (!dud && !cnt)
2533.         pline("No applicable objects.");
2534.  ret:
2535.     unsortloot(&sortedchn);
2536.     /* can't just clear bypass bit of items in objchn because the action
2537.        applied to selected ones might move them to a different chain */
2538.     /*bypass_objlist(*objchn, FALSE);*/
2539.     clear_bypasses();
2540.     return cnt;
2541. }
2542. 
2543. 
2544. /* The menu for rerolling attributes and inventory.
2545. 
2546.    This is similar to the other inventory menus, but simpler to help it fit on
2547.    the screen (there's more text around it and rerolling is difficult if you
2548.    can't see the whole list at once).
2549. 
2550.    Returns TRUE (and increases numrerolls) if a reroll was requested. */
2551. boolean
2552. reroll_menu(void)
2553. {
2554.     winid win;
2555.     anything any;
2556.     menu_item *pick_list = NULL;
2557.     struct obj *otmp;
2558.     int tmpglyph;
2559.     glyph_info tmpglyphinfo;
2560.     char option;
2561.     char buf[BUFSZ];
2562. 
2563.     win = create_nhwindow(NHW_MENU);
2564.     start_menu(win, MENU_BEHAVE_STANDARD);
2565.     any = cg.zeroany;
2566. 
2567.     any.a_char = 'n';
2568.     add_menu(win, &nul_glyphinfo, &any, flags.lootabc ? 0 : 'p', 0,
2569.              ATR_NONE, NO_COLOR, "start the game with this character",
2570.              MENU_ITEMFLAGS_NONE);
2571.     any.a_char = 'y';
2572.     add_menu(win, &nul_glyphinfo, &any, flags.lootabc ? 0 : 'r', 0,
2573.              ATR_NONE, NO_COLOR, "reroll another character",
2574.              MENU_ITEMFLAGS_NONE);
2575.     any.a_char = 0;
2576.     add_menu(win, &nul_glyphinfo, &any, 0, 0, ATR_NONE, NO_COLOR, "",
2577.              MENU_ITEMFLAGS_NONE);
2578. 
2579.     ++gd.distantname;     /* avoid adding items to discoveries */
2580.     ++iflags.override_ID; /* identify them */
2581.     for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
2582.         tmpglyph = obj_to_glyph(otmp, rn2_on_display_rng);
2583.         map_glyphinfo(0, 0, tmpglyph, 0U, &tmpglyphinfo);
2584.         add_menu(win, &tmpglyphinfo, &any, 0, 0,
2585.                  ATR_NONE, NO_COLOR, doname(otmp), MENU_ITEMFLAGS_NONE);
2586.     }
2587.     --iflags.override_ID;
2588.     --gd.distantname;
2589. 
2590.     add_menu(win, &nul_glyphinfo, &any, 0, 0, ATR_NONE, NO_COLOR, "",
2591.              MENU_ITEMFLAGS_NONE);
2592.     Sprintf(buf, "St:%s Dx:%-1d Co:%-1d In:%-1d Wi:%-1d Ch:%-1d",
2593.             get_strength_str(),
2594.             ACURR(A_DEX), ACURR(A_CON), ACURR(A_INT), ACURR(A_WIS),
2595.             ACURR(A_CHA));
2596.     add_menu(win, &nul_glyphinfo, &any, 0, 0, ATR_NONE, NO_COLOR,
2597.              buf, MENU_ITEMFLAGS_NONE);
2598. 
2599.     end_menu(win, "Reroll this character?");
2600.     if (select_menu(win, PICK_ONE, &pick_list) > 0) {
2601.         option = pick_list[0].item.a_char;
2602.         free((genericptr_t) pick_list);
2603.     } else {
2604.         /* user closed the menu without selecting; unclear what their choice
2605.            is here so ask again; but (e.g. for hangup handling) stop asking if
2606.            the user cancels out again */
2607.         option = y_n("Reroll this character?");
2608.     }
2609.     destroy_nhwindow(win);
2610. 
2611.     if (option == 'y') {
2612.         ++u.uroleplay.numrerolls;
2613.         return TRUE;
2614.     }
2615.     return FALSE;
2616. }
2617. 
2618. /*
2619.  *      Object identification routines:
2620.  */
2621. 
2622. /* set the cknown and lknown flags on an object if they're applicable */
2623. void
2624. set_cknown_lknown(struct obj *obj)
2625. {
2626.     if (Is_container(obj) || obj->otyp == STATUE)
2627.         obj->cknown = obj->lknown = 1;
2628.     else if (obj->otyp == TIN)
2629.         obj->cknown = 1;
2630.     /* TODO? cknown might be extended to candy bar, where it would mean that
2631.        wrapper's text was known which in turn indicates candy bar's content */
2632.     return;
2633. }
2634. 
2635. /* make an object actually be identified; no display updating */
2636. void
2637. fully_identify_obj(struct obj *otmp)
2638. {
2639.     makeknown(otmp->otyp);
2640.     if (otmp->oartifact)
2641.         discover_artifact((xint16) otmp->oartifact);
2642.     observe_object(otmp);
2643.     otmp->known = otmp->bknown = otmp->rknown = 1;
2644.     set_cknown_lknown(otmp); /* set otmp->{cknown,lknown} if applicable */
2645.     if (otmp->otyp == EGG && otmp->corpsenm != NON_PM)
2646.         learn_egg_type(otmp->corpsenm);
2647. }
2648. 
2649. /* ggetobj callback routine; identify an object and give immediate feedback */
2650. int
2651. identify(struct obj *otmp)
2652. {
2653.     fully_identify_obj(otmp);
2654.     prinv((char *) 0, otmp, 0L);
2655.     return 1;
2656. }
2657. 
2658. /* menu of unidentified objects; select and identify up to id_limit of them */
2659. staticfn void
2660. menu_identify(int id_limit)
2661. {
2662.     menu_item *pick_list;
2663.     int n, i, first = 1, tryct = 5;
2664.     char buf[BUFSZ];
2665.     /* assumptions:  id_limit > 0 and at least one unID'd item is present */
2666. 
2667.     while (id_limit) {
2668.         Sprintf(buf, "What would you like to identify %s?",
2669.                 first ? "first" : "next");
2670.         n = query_objlist(buf, &gi.invent, (SIGNAL_NOMENU | SIGNAL_ESCAPE
2671.                                            | USE_INVLET | INVORDER_SORT),
2672.                           &pick_list, PICK_ANY, not_fully_identified);
2673. 
2674.         if (n > 0) {
2675.             if (n > id_limit)
2676.                 n = id_limit;
2677.             for (i = 0; i < n; i++, id_limit--)
2678.                 (void) identify(pick_list[i].item.a_obj);
2679.             free((genericptr_t) pick_list);
2680.             if (id_limit)
2681.                 wait_synch(); /* Before we loop to pop open another menu */
2682.             first = 0;
2683.         } else if (n == -2) { /* player used ESC to quit menu */
2684.             break;
2685.         } else if (n == -1) { /* no eligible items found */
2686.             pline("That was all.");
2687.             break;
2688.         } else if (!--tryct) { /* stop re-prompting */
2689.             pline1(thats_enough_tries);
2690.             break;
2691.         } else { /* try again */
2692.             pline("Choose an item; use ESC to decline.");
2693.         }
2694.     }
2695. }
2696. /* count the unidentified items */
2697. int
2698. count_unidentified(struct obj *objchn)
2699. {
2700.     int unid_cnt = 0;
2701.     struct obj *obj;
2702. 
2703.     for (obj = objchn; obj; obj = obj->nobj)
2704.         if (not_fully_identified(obj))
2705.             ++unid_cnt;
2706.     return unid_cnt;
2707. }
2708. 
2709. /* dialog with user to identify a given number of items; 0 means all */
2710. void
2711. identify_pack(
2712.     int id_limit,
2713.     boolean learning_id) /* T: just read unknown identify scroll */
2714. {
2715.     struct obj *obj;
2716.     int n, unid_cnt = count_unidentified(gi.invent);
2717. 
2718.     if (!unid_cnt) {
2719.         You("have already identified %s of your possessions.",
2720.             !learning_id ? "all" : "the rest");
2721.     } else if (!id_limit || id_limit >= unid_cnt) {
2722.         /* identify everything */
2723.         /* TODO:  use fully_identify_obj and cornline/menu/whatever here */
2724.         for (obj = gi.invent; obj; obj = obj->nobj) {
2725.             if (not_fully_identified(obj)) {
2726.                 (void) identify(obj);
2727.                 if (--unid_cnt < 1)
2728.                     break;
2729.             }
2730.         }
2731.     } else {
2732.         /* identify up to `id_limit' items */
2733.         n = 0;
2734.         if (flags.menu_style == MENU_TRADITIONAL)
2735.             do {
2736.                 n = ggetobj("identify", identify, id_limit, FALSE,
2737.                             (unsigned *) 0);
2738.                 if (n < 0)
2739.                     break; /* quit or no eligible items */
2740.             } while ((id_limit -= n) > 0);
2741.         if (n == 0 || n < -1)
2742.             menu_identify(id_limit);
2743.     }
2744.     update_inventory();
2745. }
2746. 
2747. /* called when regaining sight; mark inventory objects which were picked
2748.    up while blind as now having been seen */
2749. void
2750. learn_unseen_invent(void)
2751. {
2752.     struct obj *otmp;
2753.     boolean invupdated = FALSE;
2754. 
2755.     if (Blind)
2756.         return; /* sanity check */
2757. 
2758.     for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
2759.         if (otmp->dknown && (otmp->bknown || !Role_if(PM_CLERIC)) &&
2760.             (otmp->oclass != SCROLL_CLASS || !Role_if(PM_ARCHEOLOGIST)))
2761.             continue; /* already seen */
2762.         invupdated = TRUE;
2763.         /* xname() will set dknown, perhaps bknown (for priest[ess]);
2764.            result from xname() is immediately released for re-use */
2765.         maybereleaseobuf(xname(otmp));
2766.         addinv_core2(otmp); /* you react to seeing the object */
2767. 
2768.         /*
2769.          * If object->eknown gets implemented (see learnwand(zap.c)),
2770.          * handle deferred discovery here.
2771.          */
2772.     }
2773.     if (invupdated)
2774.         update_inventory();
2775. }
2776. 
2777. /* persistent inventory window is maintained by interface code;
2778.    'update_inventory' used to be a macro for
2779.    (*windowprocs.win_update_inventory) but the restore hackery to suppress
2780.    screen updates was getting out of hand; this is now a central call point */
2781. void
2782. update_inventory(void)
2783. {
2784.     int save_suppress_price;
2785. 
2786.     if (!program_state.in_moveloop) /* not covered by suppress_map_output */
2787.         return;
2788.     if (suppress_map_output()) /* despite name, used for perm_invent too */
2789.         return;
2790. 
2791.     /*
2792.      * Ought to check (windowprocs.wincap & WC_PERM_INVENT) here....
2793.      *
2794.      * We currently don't skip this call when iflags.perm_invent is False
2795.      * because curses uses that to disable a previous perm_invent window
2796.      * (after toggle via 'O'; perhaps the options code should handle that).
2797.      *
2798.      * perm_invent might get updated while some code is avoiding price
2799.      * feedback during obj name formatting for messages.  Temporarily
2800.      * force 'normal' formatting during the perm_invent update.  (Cited
2801.      * example was an update triggered by change in invent gold when
2802.      * transferring some to shk during itemized billing.  A previous fix
2803.      * attempt in the shop code handled it for unpaid items but not for
2804.      * paying for used-up shop items; that follows a different code path.)
2805.      */
2806.     save_suppress_price = iflags.suppress_price;
2807.     iflags.suppress_price = 0;
2808.     (*windowprocs.win_update_inventory)(0);
2809.     iflags.suppress_price = save_suppress_price;
2810. }
2811. 
2812. /* the #perminv command - call interface's persistent inventory routine */
2813. int
2814. doperminv(void)
2815. {
2816.     /*
2817.      * If persistent inventory window is enabled, interact with it.
2818.      *
2819.      * Depending on interface, might accept and execute one scrolling
2820.      * request (MENU_{FIRST,NEXT,PREVIOUS,LAST}_PAGE) then return,
2821.      * or might stay and handle multiple requests until user finishes
2822.      * (typically by typing <return> or <esc> but that's up to interface).
2823.      */
2824. 
2825. #if 0
2826.     /* [currently this would redraw the persistent inventory window
2827.        whether that's needed or not, so also reset any previous
2828.        scrolling; we don't want that if the interface only accepts
2829.        one scroll command at a time] */
2830.     update_inventory(); /* make sure that it's up to date */
2831. #endif
2832. 
2833.     if ((windowprocs.wincap & WC_PERM_INVENT) == 0) {
2834.         /* [TODO? perhaps omit "by <interface>" if all the window ports
2835.            compiled into this binary lack support for perm_invent...] */
2836.         pline("Persistent inventory display is not supported by '%s'.",
2837.               windowprocs.name);
2838. 
2839.     } else if (!iflags.perm_invent) {
2840.         pline(
2841.      "Persistent inventory ('perm_invent' option) is not presently enabled.");
2842. 
2843.     } else if (!gi.invent) {
2844.         /* [should this be left for the interface to decide?] */
2845.         pline("Persistent inventory display is empty.");
2846. 
2847.     } else {
2848.         /* note: we used to request a scrolling key here and pass that to
2849.            (*win_update_inventory)(key), but that limited the functionality
2850.            and also cluttered message history with prompt and response so
2851.            just send non-zero and have the interface be responsible for it */
2852.         (*windowprocs.win_update_inventory)(1);
2853. 
2854.     } /* iflags.perm_invent */
2855. 
2856.     return ECMD_OK;
2857. }
2858. 
2859. /* should of course only be called for things in invent */
2860. staticfn char
2861. obj_to_let(struct obj *obj)
2862. {
2863.     if (!flags.invlet_constant) {
2864.         obj->invlet = NOINVSYM;
2865.         reassign();
2866.     }
2867.     return obj->invlet;
2868. }
2869. 
2870. /*
2871.  * Print the indicated quantity of the given object.  If quan == 0L then use
2872.  * the current quantity.
2873.  */
2874. void
2875. prinv(const char *prefix, struct obj *obj, long quan)
2876. {
2877.     boolean total_of = (quan && (quan < obj->quan));
2878.     char totalbuf[QBUFSZ];
2879. 
2880.     if (!prefix)
2881.         prefix = "";
2882. 
2883.     totalbuf[0] = '\0';
2884.     if (total_of)
2885.         Snprintf(totalbuf, sizeof totalbuf,
2886.                  " (%ld in total).", obj->quan);
2887.     pline("%s%s%s%s", prefix, *prefix ? " " : "",
2888.           xprname(obj, (char *) 0, obj_to_let(obj), !total_of, 0L, quan),
2889.           flags.verbose ? totalbuf : "");
2890. }
2891. 
2892. DISABLE_WARNING_FORMAT_NONLITERAL
2893. 
2894. char *
2895. xprname(
2896.     struct obj *obj,
2897.     const char *txt, /* text to print instead of obj */
2898.     char let,        /* inventory letter */
2899.     boolean dot,     /* append period; (dot && cost => Iu) */
2900.     long cost,       /* cost (for inventory of unpaid or expended items) */
2901.     long quan)       /* if non-0, print this quantity, not obj->quan */
2902. {
2903.     static char li[BUFSZ];
2904.     char suffix[80]; /* plenty of room for count and hallucinatory currency */
2905.     int sfxlen, txtlen; /* signed int for %*s formatting */
2906.     const char *fmt;
2907.     boolean use_invlet = (flags.invlet_constant && obj != NULL
2908.                           && let != CONTAINED_SYM && let != HANDS_SYM);
2909.     long savequan = 0L;
2910. 
2911.     if (quan && obj) {
2912.         savequan = obj->quan;
2913.         obj->quan = quan;
2914.     }
2915.     /*
2916.      * If let is:
2917.      *  -  Then obj == null and 'txt' refers to hands or fingers.
2918.      *  *  Then obj == null and we are printing a total amount.
2919.      *  >  Then the object is contained and doesn't have an inventory letter.
2920.      */
2921.     fmt = "%c - %.*s%s";
2922.     if (!txt) {
2923.         assert(obj != NULL);
2924.         txt = doname(obj);
2925.     }
2926.     txtlen = (int) strlen(txt);
2927. 
2928.     if (cost != 0L || let == '*') {
2929.         /* if dot is true, we're doing Iu, otherwise Ix */
2930.         if (dot && use_invlet)
2931.             let = obj->invlet;
2932.         Sprintf(suffix, "%c%6ld %.50s", iflags.menu_tab_sep ? '\t' : ' ',
2933.                 cost, currency(cost));
2934.         if (!iflags.menu_tab_sep) {
2935.             fmt = "%c - %-45.*s%s";
2936.             if (txtlen < 45)
2937.                 txtlen = 45;
2938.         }
2939.     } else {
2940.         /* ordinary inventory display or pickup message */
2941.         if (use_invlet)
2942.             let = obj->invlet;
2943.         Strcpy(suffix, dot ? "." : "");
2944.     }
2945.     sfxlen = (int) strlen(suffix);
2946.     if (txtlen > BUFSZ - 1 - (4 + sfxlen)) /* 4: "c - " prefix */
2947.         txtlen = BUFSZ - 1 - (4 + sfxlen);
2948.     Sprintf(li, fmt, let, txtlen, txt, suffix);
2949. 
2950.     if (savequan)
2951.         obj->quan = savequan;
2952. 
2953.     return li;
2954. }
2955. 
2956. RESTORE_WARNING_FORMAT_NONLITERAL
2957. 
2958. 
2959. /* show some or all of inventory while allowing the picking of an item in
2960.    order to preform context-sensitive item action on it; always returns 'ok';
2961.    invent subsets specified by the ')', '[', '(', '=', '"', or '*' commands
2962.    when they're invoked with the 'm' prefix (or without it for '*') */
2963. staticfn int
2964. dispinv_with_action(
2965.     char *lets,                 /* list of invlet values to include */
2966.     boolean use_inuse_ordering, /* affects sortloot() and header labels */
2967.     const char *alt_label)      /* alternate value for in-use "Accessories" */
2968. {
2969.     struct obj *otmp, *nextobj;
2970.     const char *save_accessories = 0;
2971.     char c, save_sortloot = 0;
2972.     unsigned len = lets ? (unsigned) strlen(lets) : 0U;
2973.     boolean menumode = (len != 1 || iflags.menu_requested) ? TRUE : FALSE,
2974.             save_force_invmenu = iflags.force_invmenu;
2975. 
2976.     if (use_inuse_ordering) {
2977.         save_accessories = inuse_headers[4];
2978.         save_sortloot = flags.sortloot;
2979. 
2980.         flags.sortloot = 'i'; /* checked by display_pickinv() */
2981.         if (alt_label)
2982.             inuse_headers[4] = alt_label;
2983.     }
2984.     iflags.force_invmenu = FALSE;
2985. 
2986.     c = display_inventory(lets, menumode);
2987. 
2988.     if (use_inuse_ordering) {
2989.         flags.sortloot = save_sortloot;
2990.         inuse_headers[4] = save_accessories;
2991.     }
2992.     iflags.force_invmenu = save_force_invmenu;
2993. 
2994.     if (c && c != '\033') {
2995.         for (otmp = gi.invent; otmp; otmp = nextobj) {
2996.             nextobj = otmp->nobj;
2997.             if (otmp->invlet == c)
2998.                 return itemactions(otmp);
2999.         }
3000.     }
3001.     return ECMD_OK;
3002. }
3003. 
3004. /* the #inventory command (not much left...) */
3005. int
3006. ddoinv(void)
3007. {
3008.     return dispinv_with_action((char *) 0, FALSE, NULL);
3009. }
3010. 
3011. /*
3012.  * find_unpaid()
3013.  *
3014.  * Scan the given list of objects.  If last_found is NULL, return the first
3015.  * unpaid object found.  If last_found is not NULL, then skip over unpaid
3016.  * objects until last_found is reached, then set last_found to NULL so the
3017.  * next unpaid object is returned.  This routine recursively follows
3018.  * containers.
3019.  */
3020. staticfn struct obj *
3021. find_unpaid(struct obj *list, struct obj **last_found)
3022. {
3023.     struct obj *obj;
3024. 
3025.     while (list) {
3026.         if (list->unpaid) {
3027.             if (*last_found) {
3028.                 /* still looking for previous unpaid object */
3029.                 if (list == *last_found)
3030.                     *last_found = (struct obj *) 0;
3031.             } else
3032.                 return ((*last_found = list));
3033.         }
3034.         if (Has_contents(list)) {
3035.             if ((obj = find_unpaid(list->cobj, last_found)) != 0)
3036.                 return obj;
3037.         }
3038.         list = list->nobj;
3039.     }
3040.     return (struct obj *) 0;
3041. }
3042. 
3043. void
3044. free_pickinv_cache(void)
3045. {
3046.     if (gc.cached_pickinv_win != WIN_ERR) {
3047.         destroy_nhwindow(gc.cached_pickinv_win);
3048.         gc.cached_pickinv_win = WIN_ERR;
3049.     }
3050. }
3051. 
3052. /*
3053.  * Internal function used by display_inventory and getobj that can display
3054.  * inventory and return a count as well as a letter.
3055.  */
3056. staticfn char
3057. display_pickinv(
3058.     const char *lets,        /* non-compacted list of invlet values */
3059.     const char *xtra_choice, /* non-object "bare hands" or "fingers" */
3060.     const char *query,       /* optional; prompt string for menu */
3061.     boolean allowxtra,       /* hands are allowed (maybe alternate) choice */
3062.     boolean want_reply,      /* True: select an item, False: just display */
3063.     long *out_cnt) /* optional; count player entered when selecting an item */
3064. {
3065.     static const char /* potential entries for perm_invent window */
3066.         not_carrying_anything[] = "Not carrying anything",
3067.         not_using_anything[] = "Not using any items",
3068.         only_carrying_gold[] = "Only carrying gold";
3069.     struct obj *otmp, wizid_fakeobj, inuse_fakeobj;
3070.     char ilet, ret, *formattedobj;
3071.     const char *invlet = flags.inv_order;
3072.     int n, classcount, inusecount = 0;
3073.     winid win; /* windows being used */
3074.     anything any;
3075.     menu_item *selected;
3076.     unsigned sortflags;
3077.     Loot *sortedinvent, *srtinv;
3078.     int8_t prevorderclass;
3079.     boolean (*filter)(struct obj *) = (boolean (*)(OBJ_P)) 0;
3080.     boolean wizid = (wizard && iflags.override_ID), gotsomething = FALSE;
3081.     int clr = NO_COLOR, menu_behavior = MENU_BEHAVE_STANDARD;
3082.     boolean show_gold = TRUE, inuse_only = FALSE, skipped_gold = FALSE,
3083.             doing_perm_invent = FALSE, save_flags_sortpack,
3084.             usextra = (xtra_choice && allowxtra);
3085. 
3086.     if (lets && !*lets)
3087.         lets = 0; /* simplify tests: (lets) instead of (lets && *lets) */
3088. 
3089. #ifdef DUMPLOG
3090.     if (iflags.in_dumplog) {
3091.         win = 0; /* passed to dump_putstr() which ignores it... */
3092.     } else
3093. #endif
3094.     if (lets || usextra || wizid || want_reply
3095. #ifdef TTY_PERM_INVENT
3096.         /*|| !gi.in_sync_perminvent*/
3097. #endif
3098.         || WIN_INVEN == WIN_ERR) {
3099.         /* partial inventory in perm_invent setting; don't operate on
3100.            full inventory window, use an alternate one instead; create
3101.            the first time needed and keep it for re-use as needed later */
3102.         if (gc.cached_pickinv_win == WIN_ERR)
3103.             gc.cached_pickinv_win = create_nhwindow(NHW_MENU);
3104.         win = gc.cached_pickinv_win;
3105.         if (flags.sortloot == 'i')
3106.             inuse_only = TRUE;
3107.     } else {
3108.         win = WIN_INVEN;
3109.         menu_behavior = MENU_BEHAVE_PERMINV;
3110.         prepare_perminvent(win);
3111.         show_gold = ((wri_info.fromcore.invmode & (enum inv_modes) InvShowGold) != 0);
3112.         inuse_only = ((wri_info.fromcore.invmode & (enum inv_modes) InvInUse) != 0);
3113.         doing_perm_invent = TRUE;
3114.     }
3115.     /*
3116.      * Exit early if no inventory -- but keep going if we are doing
3117.      * a permanent inventory update.  We need to keep going so the
3118.      * permanent inventory window updates itself to remove the last
3119.      * item(s) dropped.  One down side:  the addition of the exception
3120.      * for permanent inventory window updates _can_ pop the window
3121.      * up when it's not displayed -- even if it's empty -- because we
3122.      * don't know at this level if its up or not.  This may not be
3123.      * an issue if empty checks are done before hand and the call
3124.      * to here is short circuited away.
3125.      *
3126.      * 2: our count here is only to distinguish between 0 or 1 or
3127.      * more than 1; for the last case, we don't need a precise number.
3128.      * For perm_invent update we force 'more than 1'.
3129.      */
3130.     n = (doing_perm_invent && !lets && !want_reply) ? 2
3131.         : lets ? (int) strlen(lets)
3132.                : !gi.invent ? 0 : !gi.invent->nobj ? 1 : 2;
3133.     /* for xtra_choice, there's another 'item' not included in initial 'n';
3134.        for !lets (full invent or inuse_only) and for override_ID (wizard
3135.        mode identify), skip message_menu handling of single item even if
3136.        item count was 1 */
3137.     if (usextra || (n == 1 && (!lets || wizid)))
3138.         ++n;
3139. 
3140.     if (n == 0) {
3141.         pline("%s.", not_carrying_anything);
3142.         return 0;
3143.     }
3144. 
3145.     /* oxymoron? temporarily assign permanent inventory letters */
3146.     if (!flags.invlet_constant)
3147.         reassign();
3148. 
3149.     if (n == 1 && !iflags.force_invmenu && !iflags.menu_requested) {
3150.         /* when only one item of interest, use pline instead of menus;
3151.            we actually use a fake message-line menu in order to allow
3152.            the user to perform selection at the --More-- prompt for tty */
3153.         ret = '\0';
3154.         if (usextra) {
3155.             /* xtra_choice is "bare hands" (wield), "fingertip" (Engrave),
3156.                "nothing" (prepare Quiver), "fingers" (apply grease), or
3157.                "hands" (default) */
3158.             ret = message_menu(HANDS_SYM, PICK_ONE,
3159.                                xprname((struct obj *) 0, xtra_choice,
3160.                                        HANDS_SYM, TRUE, 0L, 0L)); /* '-' */
3161.         } else {
3162.             for (otmp = gi.invent; otmp; otmp = otmp->nobj)
3163.                 if (!lets || otmp->invlet == lets[0])
3164.                     break;
3165.             if (otmp)
3166.                 ret = message_menu(otmp->invlet,
3167.                                    want_reply ? PICK_ONE : PICK_NONE,
3168.                                    xprname(otmp, (char *) 0, lets[0],
3169.                                            TRUE, 0L, 0L));
3170.         }
3171.         if (out_cnt)
3172.             *out_cnt = -1L; /* select all */
3173.         return ret;
3174.     }
3175. 
3176.     sortflags = (flags.sortloot == 'f') ? SORTLOOT_LOOT : SORTLOOT_INVLET;
3177.     if (flags.sortpack)
3178.         sortflags |= SORTLOOT_PACK;
3179.     save_flags_sortpack = flags.sortpack;
3180. #ifdef TTY_PERM_INVENT
3181.     if (doing_perm_invent && WINDOWPORT(tty)) {
3182.         flags.sortpack = FALSE;
3183.         sortflags = SORTLOOT_INVLET;
3184.     }
3185. #endif
3186.     if (inuse_only) {
3187.         flags.sortpack = FALSE;
3188.         sortflags = SORTLOOT_INUSE; /* override */
3189.         filter = is_inuse;
3190.         if (!uwep) {
3191.             /*
3192.              * inuse_only and not wielding anything: insert "bare hands"
3193.              * into primary weapon slot.  Unlike adding an extra menu
3194.              * entry for 'xtra_choice' at top of menu, we need an object
3195.              * in invent for it to be sorted into desired position.
3196.              * It will need custom formatting below.
3197.              */
3198.             inuse_fakeobj = cg.zeroobj; /* STRANGE_OBJECT, ILLOBJ_CLASS */
3199.             inuse_fakeobj.invlet = HANDS_SYM; /* '-' */
3200.             inuse_fakeobj.owornmask = W_WEP;  /* inuse_classify needs this */
3201.             inuse_fakeobj.where = OBJ_INVENT; /* is_inuse filter needs this */
3202.             inuse_fakeobj.nobj = gi.invent;
3203.             gi.invent = &inuse_fakeobj;
3204.         }
3205.     }
3206. 
3207.     sortedinvent = sortloot(&gi.invent, sortflags, FALSE, filter);
3208.     /* inuse_only: if we inserted bare hands as a fake weapon, remove them;
3209.        although the fake object will no longer be in invent, sortedinvent
3210.        will still contain a pointer to it */
3211.     if (gi.invent == &inuse_fakeobj) {
3212.         gi.invent = inuse_fakeobj.nobj;
3213.         inuse_fakeobj.nobj = (struct obj *) 0;
3214.         /* if inuse_fakeobj is the only thing present in sortedinvent, get
3215.            rid of it in order to produce "not using any items" */
3216.         if (sortedinvent[0].obj == &inuse_fakeobj && !sortedinvent[1].obj)
3217.             sortedinvent[0].obj = (struct obj *) 0;
3218.     }
3219. 
3220.     start_menu(win, menu_behavior);
3221.     any = cg.zeroany;
3222.     if (wizid) {
3223.         int unid_cnt;
3224.         char prompt[QBUFSZ];
3225. 
3226.         unid_cnt = count_unidentified(gi.invent);
3227.         Sprintf(prompt, "Debug Identify"); /* 'title' rather than 'prompt' */
3228.         if (unid_cnt)
3229.             Sprintf(eos(prompt),
3230.                     " -- unidentified or partially identified item%s",
3231.                     plur(unid_cnt));
3232.         add_menu_str(win, prompt);
3233.         if (!unid_cnt) {
3234.             add_menu_str(win,
3235.                          "(all items are permanently identified already)");
3236.             gotsomething = TRUE;
3237.         } else {
3238.             any.a_obj = &wizid_fakeobj;
3239.             Sprintf(prompt, "select %s to permanently identify",
3240.                     (unid_cnt == 1) ? "it": "any or all of them");
3241.             /* wiz_identify stuffed the wiz_identify command character (^I)
3242.                into iflags.override_ID for our use as an accelerator;
3243.                it could be ambiguous if player has assigned a letter to
3244.                the #wizidentify command, so include it as a group accelerator
3245.                but use '_' as the primary selector */
3246.             if (unid_cnt > 1)
3247.                 Sprintf(eos(prompt), " (%s for all)",
3248.                         visctrl(iflags.override_ID));
3249.             add_menu(win, &nul_glyphinfo, &any, '_', iflags.override_ID,
3250.                      ATR_NONE, clr, prompt, MENU_ITEMFLAGS_SKIPINVERT);
3251.             gotsomething = TRUE;
3252.         }
3253.    } else if (usextra) {
3254.         /* wizard override ID and xtra_choice are mutually exclusive */
3255.         if (flags.sortpack)
3256.             add_menu_heading(win, "Miscellaneous");
3257.         any.a_char = HANDS_SYM; /* '-' */
3258.         add_menu(win, &nul_glyphinfo, &any, HANDS_SYM, 0, ATR_NONE,
3259.                  clr, xtra_choice, MENU_ITEMFLAGS_NONE);
3260.         gotsomething = TRUE;
3261.     }
3262. 
3263.  nextclass:
3264.     classcount = 0;
3265.     prevorderclass = 0;
3266.     for (srtinv = sortedinvent; (otmp = srtinv->obj) != 0; ++srtinv) {
3267.         int tmpglyph;
3268.         glyph_info tmpglyphinfo = nul_glyphinfo;
3269. 
3270.         /* for showing a set of specific letters, skip ones not in the set */
3271.         if (lets && !strchr(lets, otmp->invlet))
3272.             continue;
3273.         if (!flags.sortpack || otmp->oclass == *invlet) {
3274.             if (wizid && !not_fully_identified(otmp))
3275.                 continue;
3276.             if (inuse_only) {
3277.                 /* for inuse-only, start with an extra header */
3278.                 if (!inusecount++)
3279.                     add_menu_heading(win, doing_perm_invent ? "In use"
3280.                                             : "Inventory in use");
3281.             } else if (doing_perm_invent && !show_gold) {
3282.                 /* don't skip gold if it is quivered, even for !show_gold */
3283.                 if (otmp->invlet == GOLD_SYM && !otmp->owornmask) {
3284.                     skipped_gold = TRUE;
3285.                     continue;
3286.                 }
3287.             }
3288.             /* maybe insert a class header */
3289.             if (inuse_only ? (srtinv->orderclass != prevorderclass)
3290.                            : (flags.sortpack && !classcount)) {
3291.                 boolean withsym = (want_reply && iflags.menu_head_objsym);
3292.                 const char *class_header = inuse_only
3293.                         ? inuse_headers[(int) srtinv->orderclass]
3294.                         : (const char *) let_to_name(*invlet, FALSE, withsym);
3295. 
3296.                 add_menu_heading(win, class_header);
3297.                 classcount++;
3298.                 prevorderclass = srtinv->orderclass;
3299.             }
3300. 
3301.             ilet = otmp->invlet;
3302.             any = cg.zeroany; /* all bits zero */
3303.             if (wizid)
3304.                 any.a_obj = otmp;
3305.             else
3306.                 any.a_char = ilet;
3307. 
3308.             if (otmp == &inuse_fakeobj) {
3309.                 /* fake item to format as "bare|gloved hands" */
3310.                 char barehands[QBUFSZ];
3311. 
3312.                 /* like doname() below, makeplural() returns an obuf[] */
3313.                 formattedobj = makeplural(body_part(HAND));
3314.                 Sprintf(barehands, "%s %s (no weapon)",
3315.                         uarmg ? "gloved" : "bare", formattedobj);
3316.                 add_menu(win, &nul_glyphinfo, &any, ilet, 0,
3317.                          ATR_NONE, clr, barehands, MENU_ITEMFLAGS_NONE);
3318.             } else {
3319.                 /* normal inventory item */
3320.                 tmpglyph = obj_to_glyph(otmp, rn2_on_display_rng);
3321.                 map_glyphinfo(0, 0, tmpglyph, 0U, &tmpglyphinfo);
3322.                 formattedobj = doname(otmp);
3323.                 add_menu(win, &tmpglyphinfo, &any, ilet,
3324.                          wizid ? def_oc_syms[(int) otmp->oclass].sym : 0,
3325.                          ATR_NONE, clr, formattedobj, MENU_ITEMFLAGS_NONE);
3326.             }
3327.             /* doname() uses a static pool of obuf[] output buffers and
3328.                we don't want inventory display to overwrite all of them,
3329.                so when we've used one we release it for re-use */
3330.             maybereleaseobuf(formattedobj);
3331.             gotsomething = TRUE;
3332.         }
3333.     }
3334.     if (flags.sortpack) {
3335.         if (*++invlet)
3336.             goto nextclass;
3337.         if (--invlet != venom_inv) {
3338.             invlet = venom_inv;
3339.             goto nextclass;
3340.         }
3341.     }
3342.     if (save_flags_sortpack != flags.sortpack)
3343.         flags.sortpack = save_flags_sortpack;
3344. 
3345.     /* default for force_invmenu is a menu listing likely candidates;
3346.        add '*' for 'list all' as an extra choice unless the menu already
3347.        includes everything; when reissuing the menu after player has
3348.        picked '*', add '?' for 'list likely candidates' to reverse that */
3349.     if (iflags.force_invmenu && want_reply) {
3350.         const char *menutext = NULL;
3351. 
3352.         any = cg.zeroany;
3353.         if ((allowxtra && !usextra)
3354.             || (lets && (int) strlen(lets) < inv_cnt(TRUE))) {
3355.             any.a_char = '*';
3356.             menutext = "(list everything)";
3357.         } else if (!lets) {
3358.             any.a_char = '?';
3359.             menutext = "(list likely candidates)";
3360.         }
3361.         if (menutext) {
3362.             add_menu_heading(win, "Special");
3363.             add_menu(win, &nul_glyphinfo, &any, any.a_char, 0, ATR_NONE, clr,
3364.                      menutext, MENU_ITEMFLAGS_NONE);
3365.             gotsomething = TRUE; /* menu isn't empty */
3366.         }
3367.     }
3368.     unsortloot(&sortedinvent);
3369.     /* for permanent inventory where nothing has been listed (because
3370.        there isn't anything applicable to list; the n==0 case above
3371.        gets skipped for perm_invent), put something into the menu */
3372.     if (doing_perm_invent && !lets && !gotsomething) {
3373.         add_menu_str(win, inuse_only ? not_using_anything
3374.                           : (!show_gold && skipped_gold) ? only_carrying_gold
3375.                             : not_carrying_anything);
3376.         want_reply = FALSE;
3377.     }
3378.     end_menu(win, (query && *query) ? query : (char *) 0);
3379. 
3380.     n = select_menu(win,
3381.                     wizid ? PICK_ANY : want_reply ? PICK_ONE : PICK_NONE,
3382.                     &selected);
3383.     if (n > 0) {
3384.         if (wizid) {
3385.             boolean all_id = FALSE;
3386.             int i;
3387. 
3388.             /* identifying items will update perm_invent, calling this
3389.                routine recursively, and we don't want the nested call
3390.                to filter on unID'd items */
3391.             iflags.override_ID = 0;
3392.             ret = '\0';
3393.             for (i = 0; i < n; ++i) {
3394.                 otmp = selected[i].item.a_obj;
3395.                 if (otmp == &wizid_fakeobj) {
3396.                     identify_pack(0, FALSE);
3397.                     /* identify_pack() performs update_inventory() */
3398.                     all_id = TRUE;
3399.                     break;
3400.                 } else {
3401.                     if (not_fully_identified(otmp))
3402.                         (void) identify(otmp);
3403.                     /* identify() does not perform update_inventory() */
3404.                 }
3405.             }
3406.             if (!all_id)
3407.                 update_inventory();
3408.         } else {
3409.             ret = selected[0].item.a_char;
3410.             if (out_cnt)
3411.                 *out_cnt = selected[0].count;
3412.         }
3413.         free((genericptr_t) selected);
3414.     } else
3415.         ret = !n ? '\0' : '\033'; /* cancelled */
3416. 
3417.     return ret;
3418. }
3419. 
3420. /*
3421.  * If lets == NULL or "", list all objects in the inventory.  Otherwise,
3422.  * list all objects with object classes that match the order in lets.
3423.  *
3424.  * Returns the letter identifier of a selected item, or 0 if nothing
3425.  * was selected.
3426.  */
3427. char
3428. display_inventory(const char *lets, boolean want_reply)
3429. {
3430.     struct _cmd_queue *cmdq = cmdq_pop();
3431. 
3432.     if (cmdq) {
3433.         if (cmdq->typ == CMDQ_KEY) {
3434.             struct obj *otmp;
3435. 
3436.             for (otmp = gi.invent; otmp; otmp = otmp->nobj)
3437.                 if (otmp->invlet == cmdq->key
3438.                     && (!lets || !*lets
3439.                         || strchr(lets,
3440.                                   def_oc_syms[(int) otmp->oclass].sym))) {
3441.                     free(cmdq);
3442.                     return otmp->invlet;
3443.                 }
3444.         }
3445. 
3446.         /* cmdq not a key, or did not find the object, abort */
3447.         free(cmdq);
3448.         cmdq_clear(CQ_CANNED);
3449.         return '\0';
3450.     }
3451.     return display_pickinv(lets, (char *) 0, (char *) 0,
3452.                            FALSE, want_reply, (long *) 0);
3453. }
3454. 
3455. void
3456. repopulate_perminvent(void)
3457. {
3458.         (void) display_pickinv(NULL, (char *) 0, (char *) 0,
3459.                                FALSE, FALSE, (long *) 0);
3460. }
3461. 
3462. /*
3463.  * Show what is current using inventory letters.
3464.  *
3465.  */
3466. staticfn char
3467. display_used_invlets(char avoidlet)
3468. {
3469.     struct obj *otmp;
3470.     char ilet, ret = 0;
3471.     char *invlet = flags.inv_order;
3472.     int n, classcount, invdone = 0, tmpglyph;
3473.     glyph_info tmpglyphinfo = nul_glyphinfo;
3474.     winid win;
3475.     anything any;
3476.     menu_item *selected;
3477.     int clr = NO_COLOR;
3478. 
3479.     if (gi.invent) {
3480.         win = create_nhwindow(NHW_MENU);
3481.         start_menu(win, MENU_BEHAVE_STANDARD);
3482.         while (!invdone) {
3483.             any = cg.zeroany; /* set all bits to zero */
3484.             classcount = 0;
3485.             for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
3486.                 ilet = otmp->invlet;
3487.                 if (ilet == avoidlet)
3488.                     continue;
3489.                 if (!flags.sortpack || otmp->oclass == *invlet) {
3490.                     if (flags.sortpack && !classcount) {
3491.                         any = cg.zeroany; /* zero */
3492.                         add_menu_heading(win,
3493.                                          let_to_name(*invlet, FALSE, FALSE));
3494.                         classcount++;
3495.                     }
3496.                     any.a_char = ilet;
3497.                     tmpglyph = obj_to_glyph(otmp, rn2_on_display_rng);
3498.                     map_glyphinfo(0, 0, tmpglyph, 0U, &tmpglyphinfo);
3499.                     add_menu(win, &tmpglyphinfo, &any, ilet, 0,
3500.                              ATR_NONE, clr, doname(otmp),
3501.                              MENU_ITEMFLAGS_NONE);
3502.                 }
3503.             }
3504.             if (flags.sortpack && *++invlet)
3505.                 continue;
3506.             invdone = 1;
3507.         }
3508.         end_menu(win, "Inventory letters used:");
3509. 
3510.         n = select_menu(win, PICK_ONE, &selected);
3511.         if (n > 0) {
3512.             ret = selected[0].item.a_char;
3513.             free((genericptr_t) selected);
3514.         } else
3515.             ret = !n ? '\0' : '\033'; /* cancelled */
3516.         destroy_nhwindow(win);
3517.     }
3518.     return ret;
3519. }
3520. 
3521. /*
3522.  * Returns the number of unpaid items within the given list.  This includes
3523.  * contained objects.
3524.  */
3525. int
3526. count_unpaid(struct obj *list)
3527. {
3528.     int count = 0;
3529. 
3530.     while (list) {
3531.         if (list->unpaid)
3532.             count++;
3533.         if (Has_contents(list))
3534.             count += count_unpaid(list->cobj);
3535.         list = list->nobj;
3536.     }
3537.     return count;
3538. }
3539. 
3540. /*
3541.  * Returns the number of items with b/u/c/unknown within the given list.
3542.  * This does NOT include contained objects.
3543.  *
3544.  * Assumes that the hero sees or touches or otherwise senses the objects
3545.  * at some point:  bknown is forced for priest[ess], like in xname().
3546.  */
3547. int
3548. count_buc(struct obj *list, int type, boolean (*filterfunc)(OBJ_P))
3549. {
3550.     int count = 0;
3551. 
3552.     for (; list; list = list->nobj) {
3553.         /* priests always know bless/curse state */
3554.         if (Role_if(PM_CLERIC))
3555.             list->bknown = (list->oclass != COIN_CLASS);
3556.         /* some actions exclude some or most items */
3557.         if (filterfunc && !(*filterfunc)(list))
3558.             continue;
3559. 
3560.         /* coins are either uncursed or unknown based upon option setting */
3561.         if (list->oclass == COIN_CLASS) {
3562.             if (type == (flags.goldX ? BUC_UNKNOWN : BUC_UNCURSED))
3563.                 ++count;
3564.             continue;
3565.         }
3566.         /* check whether this object matches the requested type */
3567.         if (!list->bknown
3568.                 ? (type == BUC_UNKNOWN)
3569.                 : list->blessed ? (type == BUC_BLESSED)
3570.                                 : list->cursed ? (type == BUC_CURSED)
3571.                                                : (type == BUC_UNCURSED))
3572.             ++count;
3573.     }
3574.     return count;
3575. }
3576. 
3577. /* similar to count_buc(), but tallies all states at once
3578.    rather than looking for a specific type */
3579. void
3580. tally_BUCX(
3581.     struct obj *list,
3582.     boolean by_nexthere,
3583.     int *bcp, int *ucp, int *ccp, int *xcp, int *ocp, int *jcp)
3584. {
3585.     /* Future extensions:
3586.      *  Skip current_container when list is invent, uchain when
3587.      *  first object of list is located on the floor.  'ocp' will then
3588.      *  have a function again (it was a counter for having skipped gold,
3589.      *  but that's not skipped anymore).
3590.      */
3591.     *bcp = *ucp = *ccp = *xcp = *ocp = *jcp = 0;
3592.     for ( ; list; list = (by_nexthere ? list->nexthere : list->nobj)) {
3593.         /* priests always know bless/curse state */
3594.         if (Role_if(PM_CLERIC))
3595.             list->bknown = (list->oclass != COIN_CLASS);
3596.         if (list->pickup_prev)
3597.             ++(*jcp);
3598.         /* coins are either uncursed or unknown based upon option setting */
3599.         if (list->oclass == COIN_CLASS) {
3600.             if (flags.goldX)
3601.                 ++(*xcp);
3602.             else
3603.                 ++(*ucp);
3604.             continue;
3605.         }
3606.         /* ordinary items */
3607.         if (!list->bknown)
3608.             ++(*xcp);
3609.         else if (list->blessed)
3610.             ++(*bcp);
3611.         else if (list->cursed)
3612.             ++(*ccp);
3613.         else /* neither blessed nor cursed => uncursed */
3614.             ++(*ucp);
3615.     }
3616. }
3617. 
3618. /* count everything inside a container, or just shop-owned items inside */
3619. long
3620. count_contents(
3621.     struct obj *container,
3622.     boolean nested,     /* include contents of any nested containers */
3623.     boolean quantity,   /* count all vs count separate stacks        */
3624.     boolean everything, /* all objects vs only unpaid objects        */
3625.     boolean newdrop)    /* on floor, but hero-owned items haven't
3626.                          * been marked no_charge yet and shop-owned
3627.                          * items are still marked unpaid -- used
3628.                          * when asking the player whether to sell    */
3629. {
3630.     struct obj *otmp, *topc;
3631.     boolean shoppy = FALSE;
3632.     long count = 0L;
3633. 
3634.     if (!everything && !newdrop) {
3635.         coordxy x, y;
3636. 
3637.         for (topc = container; topc->where == OBJ_CONTAINED;
3638.              topc = topc->ocontainer)
3639.             continue;
3640.         if (topc->where == OBJ_FLOOR && get_obj_location(topc, &x, &y, 0))
3641.             shoppy = costly_spot(x, y);
3642.     }
3643.     for (otmp = container->cobj; otmp; otmp = otmp->nobj) {
3644.         if (nested && Has_contents(otmp))
3645.             count += count_contents(otmp, nested, quantity, everything,
3646.                                     newdrop);
3647.         if (everything || otmp->unpaid || (shoppy && !otmp->no_charge))
3648.             count += quantity ? otmp->quan : 1L;
3649.     }
3650.     return count;
3651. }
3652. 
3653. staticfn void
3654. dounpaid(
3655.     int count,       /* unpaid items in inventory */
3656.     int floorcount,  /* unpaid items on floor (rare) */
3657.     int buriedcount) /* unpaid items under the floor (extremely rare) */
3658. {
3659.     winid win;
3660.     struct obj *otmp, *marker, *contnr;
3661.     char ilet;
3662.     char *invlet = flags.inv_order;
3663.     int classcount, num_so_far, xtracount;
3664.     long cost, totcost;
3665. 
3666.     otmp = marker = contnr = (struct obj *) 0;
3667.     xtracount = floorcount + buriedcount;
3668. 
3669.     if (count == 1 && !xtracount) {
3670.         otmp = find_unpaid(gi.invent, &marker);
3671.         contnr = unknwn_contnr_contents(otmp);
3672.     }
3673.     if  (otmp && !contnr) {
3674.         /* 1 item; use pline instead of popup menu */
3675.         cost = unpaid_cost(otmp, COST_NOCONTENTS);
3676.         iflags.suppress_price++; /* suppress "(unpaid)" suffix */
3677.         pline1(xprname(otmp, distant_name(otmp, doname),
3678.                        carried(otmp) ? otmp->invlet : CONTAINED_SYM,
3679.                        TRUE, cost, 0L));
3680.         iflags.suppress_price--;
3681.         return;
3682.     }
3683. 
3684.     win = create_nhwindow(NHW_MENU);
3685.     totcost = 0L;
3686.     num_so_far = 0; /* count of # printed so far */
3687.     if (!flags.invlet_constant)
3688.         reassign();
3689. 
3690.     do {
3691.         classcount = 0;
3692.         for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
3693.             ilet = otmp->invlet;
3694.             if (otmp->unpaid) {
3695.                 if (!flags.sortpack || otmp->oclass == *invlet) {
3696.                     if (flags.sortpack && !classcount) {
3697.                         putstr(win, 0, let_to_name(*invlet, TRUE, FALSE));
3698.                         classcount++;
3699.                     }
3700. 
3701.                     totcost += cost = unpaid_cost(otmp, COST_NOCONTENTS);
3702.                     iflags.suppress_price++; /* suppress "(unpaid)" suffix */
3703.                     putstr(win, 0, xprname(otmp, distant_name(otmp, doname),
3704.                                            ilet, TRUE, cost, 0L));
3705.                     iflags.suppress_price--;
3706.                     num_so_far++;
3707.                 }
3708.             }
3709.         }
3710.     } while (flags.sortpack && (*++invlet));
3711. 
3712.     if (count > num_so_far) {
3713.         /* something unpaid is contained */
3714.         if (flags.sortpack)
3715.             putstr(win, 0, let_to_name(CONTAINED_SYM, TRUE, FALSE));
3716.         /*
3717.          * Search through the container objects in the inventory for
3718.          * unpaid items.  The top level inventory items have already
3719.          * been listed.
3720.          */
3721.         for (otmp = gi.invent; otmp; otmp = otmp->nobj) {
3722.             if (Has_contents(otmp)) {
3723.                 long contcost = 0L;
3724. 
3725.                 marker = (struct obj *) 0; /* haven't found any */
3726.                 while (find_unpaid(otmp->cobj, &marker)) {
3727.                     totcost += cost = unpaid_cost(marker, COST_NOCONTENTS);
3728.                     contcost += cost;
3729.                     if (otmp->cknown) {
3730.                         iflags.suppress_price++; /* suppress "(unpaid)" sfx */
3731.                         putstr(win, 0,
3732.                                xprname(marker, distant_name(marker, doname),
3733.                                        CONTAINED_SYM, TRUE, cost, 0L));
3734.                         iflags.suppress_price--;
3735.                     }
3736.                 }
3737.                 if (!otmp->cknown) {
3738.                     char contbuf[BUFSZ];
3739. 
3740.                     /* Shopkeeper knows what to charge for contents */
3741.                     Sprintf(contbuf, "%s contents", s_suffix(xname(otmp)));
3742.                     putstr(win, 0,
3743.                            xprname((struct obj *) 0, contbuf, CONTAINED_SYM,
3744.                                    TRUE, contcost, 0L));
3745.                 }
3746.             }
3747.         }
3748.     }
3749. 
3750.     if (count > 0) {
3751.         putstr(win, 0, "");
3752.         putstr(win, 0,
3753.                xprname((struct obj *) 0, "Total:", '*', FALSE, totcost, 0L));
3754.     }
3755. 
3756.     /* an unpaid item can be on the floor if dropped on the shop boundary
3757.        (then possibly moved all the way into the shop during wall repair);
3758.        one can be buried if it started that way and a pit was dug at its
3759.        spot then filled by a boulder (or perhaps a theme room with a pool
3760.        and an unpaid item moved into that by wall repair, then freezing) */
3761.     if (xtracount > 0) { /* floorcount + buriedcount > 0 */
3762.         char buf[BUFSZ];
3763.         const char
3764.             *floorverb = (xtracount > 1) ? "are" : "is",
3765.             /* "under the floor" might actually be "under the floor
3766.                beneath a wall" when shop repair is involved but that seems
3767.                too nit-picky to bother trying to handle here (even more
3768.                extreme description-wise:  "under the floor beneath the
3769.                door/doorway") */
3770.             *where = (buriedcount == 0) ? "on the floor"
3771.                      : (floorcount == 0) ? "under the floor"
3772.                        : "on or under the floor";
3773. 
3774.         if (!count) {
3775.             You("aren't carrying any unpaid items but there %s %d %s.",
3776.                 floorverb, xtracount, where);
3777.         } else {
3778.             putstr(win, 0, "");
3779.             Sprintf(buf, "(There %s %d more unpaid object%s %s.)",
3780.                     floorverb, xtracount, plur(xtracount), where);
3781.             putstr(win, 0, buf);
3782.         }
3783.     }
3784. 
3785.     if (count > 0)
3786.         display_nhwindow(win, FALSE);
3787.     destroy_nhwindow(win);
3788.     return;
3789. }
3790. 
3791. 
3792. staticfn boolean
3793. this_type_only(struct obj *obj)
3794. {
3795.     boolean res = (obj->oclass == gt.this_type);
3796. 
3797.     if (gt.this_type == 'P') {
3798.         res = obj->pickup_prev;
3799.     } else if (obj->oclass == COIN_CLASS) {
3800.         /* if filtering by bless/curse state, gold is classified as
3801.            either unknown or uncursed based on user option setting */
3802.         if (gt.this_type && strchr("BUCX", gt.this_type))
3803.             res = (gt.this_type == (flags.goldX ? 'X' : 'U'));
3804.     } else {
3805.         switch (gt.this_type) {
3806.         case 'B':
3807.             res = (obj->bknown && obj->blessed);
3808.             break;
3809.         case 'U':
3810.             res = (obj->bknown && !(obj->blessed || obj->cursed));
3811.             break;
3812.         case 'C':
3813.             res = (obj->bknown && obj->cursed);
3814.             break;
3815.         case 'X':
3816.             res = !obj->bknown;
3817.             break;
3818.         default:
3819.             break; /* use 'res' as-is */
3820.         }
3821.     }
3822.     return res;
3823. }
3824. 
3825. /* the #inventtype command */
3826. int
3827. dotypeinv(void)
3828. {
3829.     static const char
3830.         prompt[] = "What type of object do you want an inventory of?";
3831.     char c = '\0';
3832.     int n, i = 0;
3833.     char *extra_types, types[BUFSZ], title[QBUFSZ];
3834.     const char *before = "", *after = "";
3835.     int class_count, oclass, itemcount,
3836.         any_unpaid, u_carried, u_floor, u_buried;
3837.     int bcnt, ccnt, ucnt, xcnt, ocnt, jcnt;
3838.     boolean billx = *u.ushops && doinvbill(0);
3839.     menu_item *pick_list;
3840.     boolean traditional = TRUE;
3841. 
3842.     gt.this_type = 0;
3843.     gt.this_title = NULL;
3844.     if (!gi.invent && !billx) {
3845.         You("aren't carrying anything.");
3846.         goto doI_done;
3847.     }
3848.     title[0] = '\0';
3849.     u_carried = count_unpaid(gi.invent);
3850.     u_floor = count_unpaid(fobj);
3851.     u_buried = count_unpaid(svl.level.buriedobjlist);
3852.     any_unpaid = u_carried + u_floor + u_buried;
3853.     tally_BUCX(gi.invent, FALSE, &bcnt, &ucnt, &ccnt, &xcnt, &ocnt, &jcnt);
3854. 
3855.     if (flags.menu_style != MENU_TRADITIONAL) {
3856.         if (flags.menu_style == MENU_FULL
3857.             || flags.menu_style == MENU_PARTIAL) {
3858.             traditional = FALSE;
3859.             i = UNPAID_TYPES;
3860.             if (billx)
3861.                 i |= BILLED_TYPES;
3862.             if (bcnt)
3863.                 i |= BUC_BLESSED;
3864.             if (ucnt)
3865.                 i |= BUC_UNCURSED;
3866.             if (ccnt)
3867.                 i |= BUC_CURSED;
3868.             if (xcnt)
3869.                 i |= BUC_UNKNOWN;
3870.             if (jcnt)
3871.                 i |= JUSTPICKED;
3872.             i |= INCLUDE_VENOM;
3873.             n = query_category(prompt, gi.invent, i, &pick_list, PICK_ONE);
3874.             if (!n)
3875.                 goto doI_done;
3876.             gt.this_type = c = pick_list[0].item.a_int;
3877.             free((genericptr_t) pick_list);
3878.         }
3879.     }
3880.     if (traditional) {
3881.         /* collect list of classes of objects carried, for use as a prompt */
3882.         types[0] = 0;
3883.         class_count = collect_obj_classes(types, gi.invent, FALSE,
3884.                                           (boolean (*)(OBJ_P)) 0,
3885.                                           &itemcount);
3886.         if (any_unpaid || billx || (bcnt + ccnt + ucnt + xcnt) != 0 || jcnt)
3887.             types[class_count++] = ' ';
3888.         if (any_unpaid)
3889.             types[class_count++] = 'u';
3890.         if (billx)
3891.             types[class_count++] = 'x';
3892.         if (bcnt)
3893.             types[class_count++] = 'B';
3894.         if (ucnt)
3895.             types[class_count++] = 'U';
3896.         if (ccnt)
3897.             types[class_count++] = 'C';
3898.         if (xcnt)
3899.             types[class_count++] = 'X';
3900.         if (jcnt)
3901.             types[class_count++] = 'P';
3902.         types[class_count] = '\0';
3903.         /* add everything not already included; user won't see these */
3904.         extra_types = eos(types);
3905.         *extra_types++ = '\033';
3906.         if (!any_unpaid)
3907.             *extra_types++ = 'u';
3908.         if (!billx)
3909.             *extra_types++ = 'x';
3910.         if (!bcnt)
3911.             *extra_types++ = 'B';
3912.         if (!ucnt)
3913.             *extra_types++ = 'U';
3914.         if (!ccnt)
3915.             *extra_types++ = 'C';
3916.         if (!xcnt)
3917.             *extra_types++ = 'X';
3918.         if (!jcnt)
3919.             *extra_types++ = 'P';
3920.         *extra_types = '\0'; /* for strchr() */
3921.         for (i = 0; i < MAXOCLASSES; i++)
3922.             if (!strchr(types, def_oc_syms[i].sym)) {
3923.                 *extra_types++ = def_oc_syms[i].sym;
3924.                 *extra_types = '\0';
3925.             }
3926. 
3927.         if (class_count > 1) {
3928.             c = yn_function(prompt, types, '\0', TRUE);
3929.             if (c == '\0') {
3930.                 clear_nhwindow(WIN_MESSAGE);
3931.                 goto doI_done;
3932.             }
3933.         } else {
3934.             /* only one thing to itemize */
3935.             if (any_unpaid)
3936.                 c = 'u';
3937.             else if (billx)
3938.                 c = 'x';
3939.             else
3940.                 c = types[0];
3941.         }
3942.     }
3943.     if (c == 'x' || (c == 'X' && billx && !xcnt)) {
3944.         if (billx)
3945.             (void) doinvbill(1);
3946.         else
3947.             pline("No used-up objects%s.",
3948.                   any_unpaid ? " on your shopping bill" : "");
3949.         goto doI_done;
3950.     }
3951.     if (c == 'u' || (c == 'U' && any_unpaid && !ucnt)) {
3952.         if (any_unpaid)
3953.             dounpaid(u_carried, u_floor, u_buried);
3954.         else
3955.             You("are not carrying any unpaid objects.");
3956.         goto doI_done;
3957.     }
3958. 
3959.     if (strchr("BUCXP", c))
3960.         oclass = c; /* not a class but understood by this_type_only() */
3961.     else
3962.         oclass = def_char_to_objclass(c); /* change to object class */
3963. #if 0
3964.     /* this used to be done for the 'if traditional' case but not for the
3965.        menu case; also unlike '$', 'I$' explicitly asks about inventory,
3966.        so we no longer handle coin class differently from other classes */
3967.     if (oclass == COIN_CLASS) {
3968.         return doprgold();
3969.     }
3970. #endif
3971.     /* these are used for traditional when not applicable and also for
3972.        constructing a title to be used by query_objlist() */
3973.     switch (c) {
3974.     case 'B':
3975.         before = "known to be blessed ";
3976.         break;
3977.     case 'U':
3978.         before = "known to be uncursed ";
3979.         break;
3980.     case 'C':
3981.         before = "known to be cursed ";
3982.         break;
3983.     case 'X':
3984.         after = " whose blessed/uncursed/cursed status is unknown";
3985.         break; /* better phrasing is desirable */
3986.     case 'P':
3987.         after = " that were just picked up";
3988.         break;
3989.     default:
3990.         /* 'c' is an object class, because we've already handled
3991.            all the non-class letters which were put into 'types[]';
3992.            could/should move object class names[] array from below
3993.            to somewhere above so that we can access it here (via
3994.            lcase(strcpy(classnamebuf, names[(int) c]))), but the
3995.            game-play value of doing so is low... */
3996.         before = "such ";
3997.         break;
3998.     }
3999. 
4000.     if (traditional) {
4001.         if (strchr(types, c) > strchr(types, '\033')) {
4002.             You("have no %sobjects%s.", before, after);
4003.             goto doI_done;
4004.         }
4005.         gt.this_type = oclass; /* extra input for this_type_only() */
4006.     }
4007.     if (strchr("BUCXP", c)) {
4008.         /* the before and after phrases for "you have no..." can both be
4009.            treated as mutually-exclusive suffices when creating a title */
4010.         Sprintf(title, "Items %s", (before && *before) ? before : after);
4011.         /* get rid of trailing space from 'before' and double-space from
4012.            'after's leading space */
4013.         (void) mungspaces(title);
4014.         Strcat(title, ":"); /* after removing unwanted trailing space */
4015.         gt.this_title = title;
4016.     }
4017. 
4018.     if (query_objlist((char *) 0, &gi.invent,
4019.                       ((flags.invlet_constant ? USE_INVLET : 0)
4020.                        | INVORDER_SORT | INCLUDE_VENOM),
4021.                       &pick_list, PICK_ONE, this_type_only) > 0) {
4022.         struct obj *otmp = pick_list[0].item.a_obj;
4023. 
4024.         free((genericptr_t) pick_list);
4025.         (void) itemactions(otmp); /* always returns ECMD_OK */
4026.     }
4027. 
4028.  doI_done:
4029.     gt.this_type = 0;
4030.     gt.this_title = NULL;
4031.     return ECMD_OK;
4032. }
4033. 
4034. /* return a string describing the dungeon feature at <x,y> if there
4035.    is one worth mentioning at that location; otherwise null */
4036. const char *
4037. dfeature_at(coordxy x, coordxy y, char *buf)
4038. {
4039.     struct rm *lev = &levl[x][y];
4040.     int ltyp = lev->typ, cmap = -1;
4041.     const char *dfeature = 0;
4042.     static char altbuf[BUFSZ];
4043.     stairway *stway = stairway_at(x, y);
4044. 
4045.     if (IS_DOOR(ltyp)) {
4046.         switch (lev->doormask) {
4047.         case D_NODOOR:
4048.             cmap = S_ndoor;
4049.             break; /* "doorway" */
4050.         case D_ISOPEN:
4051.             cmap = S_vodoor;
4052.             break; /* "open door" */
4053.         case D_BROKEN:
4054.             dfeature = "broken door";
4055.             break;
4056.         default:
4057.             cmap = S_vcdoor;
4058.             break; /* "closed door" */
4059.         }
4060.         /* override door description for open drawbridge */
4061.         if (is_drawbridge_wall(x, y) >= 0)
4062.             dfeature = "open drawbridge portcullis", cmap = -1;
4063.     } else if (IS_FOUNTAIN(ltyp))
4064.         cmap = S_fountain; /* "fountain" */
4065.     else if (IS_THRONE(ltyp))
4066.         cmap = S_throne; /* "opulent throne" */
4067.     else if (is_lava(x, y))
4068.         cmap = S_lava; /* "molten lava" */
4069.     else if (is_ice(x, y))
4070.         dfeature = ice_descr(x, y, altbuf), cmap = -1; /* "ice" */
4071.     else if (is_pool(x, y))
4072.         dfeature = "pool of water";
4073.     else if (IS_SINK(ltyp))
4074.         cmap = S_sink; /* "sink" */
4075.     else if (IS_ALTAR(ltyp)) {
4076.         Sprintf(altbuf, "%saltar to %s (%s)",
4077.                 (lev->altarmask & AM_SANCTUM) ? "high " : "",
4078.                 a_gname(),
4079.                 align_str(Amask2align(lev->altarmask & ~AM_SHRINE)));
4080.         dfeature = altbuf;
4081.     } else if (stway) {
4082.         dfeature = stairs_description(stway, altbuf, TRUE);
4083.     } else if (ltyp == DRAWBRIDGE_DOWN)
4084.         cmap = S_vodbridge; /* "lowered drawbridge" */
4085.     else if (ltyp == DBWALL)
4086.         cmap = S_vcdbridge; /* "raised drawbridge" */
4087.     else if (IS_GRAVE(ltyp))
4088.         cmap = S_grave; /* "grave" */
4089.     else if (ltyp == TREE)
4090.         cmap = S_tree; /* "tree" */
4091.     else if (ltyp == IRONBARS)
4092.         dfeature = "set of iron bars";
4093. 
4094.     if (cmap >= 0)
4095.         dfeature = defsyms[cmap].explanation;
4096.     if (dfeature)
4097.         Strcpy(buf, dfeature);
4098.     return dfeature;
4099. }
4100. 
4101. /* look at what is here; if there are many objects (pile_limit or more),
4102.    don't show them unless obj_cnt is 0 */
4103. int
4104. look_here(
4105.     int obj_cnt, /* obj_cnt > 0 implies that autopickup is in progress */
4106.     unsigned lookhere_flags)
4107. {
4108.     struct obj *otmp;
4109.     struct trap *trap;
4110.     const char *verb = Blind ? "feel" : "see";
4111.     const char *dfeature = (char *) 0;
4112.     char fbuf[BUFSZ], fbuf2[BUFSZ];
4113.     winid tmpwin;
4114.     boolean skip_objects, felt_cockatrice = FALSE,
4115.             picked_some = (lookhere_flags & LOOKHERE_PICKED_SOME) != 0,
4116.             /* skip 'dfeature' if caller used describe_decor() to show it */
4117.             skip_dfeature = (lookhere_flags & LOOKHERE_SKIP_DFEATURE) != 0;
4118. 
4119.     /* default pile_limit is 5; a value of 0 means "never skip"
4120.        (and 1 effectively forces "always skip") */
4121.     skip_objects = (flags.pile_limit > 0 && obj_cnt >= flags.pile_limit);
4122.     if (u.uswallow) {
4123.         struct monst *mtmp = u.ustuck;
4124. 
4125.         /*
4126.          * FIXME?
4127.          *  Engulfer's inventory can include worn items (specific case is
4128.          *  Juiblex being created with an amulet as random defensive item)
4129.          *  which will be flagged as "(being worn)".  This code includes
4130.          *  such a worn item under the header "Contents of <mon>'s stomach",
4131.          *  a nifty trick for how/where to wear stuff.  The situation is
4132.          *  rare enough to turn a blind eye.
4133.          *
4134.          *  3.6.3:  Pickup has been changed to decline to pick up a worn
4135.          *  item from inside an engulfer, but if player tries, it just
4136.          *  says "you can't" without giving a reason why (which would be
4137.          *  something along the lines of "because it's worn on the outside
4138.          *  so is unreachable from in here...").
4139.          */
4140.         Sprintf(fbuf, "Contents of %s %s", s_suffix(mon_nam(mtmp)),
4141.                 mbodypart(mtmp, STOMACH));
4142.         /* Skip "Contents of " by using fbuf index 12 */
4143.         You("%s to %s what is lying in %s.", Blind ? "try" : "look around",
4144.             verb, &fbuf[12]);
4145.         otmp = mtmp->minvent;
4146.         if (otmp) {
4147.             for (; otmp; otmp = otmp->nobj) {
4148.                 /* If swallower is an animal, it should have become stone
4149.                  * but... */
4150.                 if (otmp->otyp == CORPSE)
4151.                     feel_cockatrice(otmp, FALSE);
4152.             }
4153.             if (Blind)
4154.                 Strcpy(fbuf, "You feel");
4155.             Strcat(fbuf, ":");
4156.             (void) display_minventory(mtmp, MINV_ALL | PICK_NONE, fbuf);
4157.         } else {
4158.             You("%s no objects here.", verb);
4159.         }
4160.         return (!!Blind ? ECMD_TIME : ECMD_OK);
4161.     }
4162.     if (!skip_objects) {
4163.         NhRegion *reg;
4164.         char regbuf[QBUFSZ];
4165. 
4166.         regbuf[0] = '\0';
4167.         if ((reg = visible_region_at(u.ux, u.uy)) != 0)
4168.             Sprintf(regbuf, "a %s cloud",
4169.                     reg_damg(reg) ? "poison gas" : "vapor");
4170.         if ((trap = t_at(u.ux, u.uy)) != 0 && !trap->tseen)
4171.             trap = (struct trap *) NULL;
4172. 
4173.         if (reg || trap)
4174.             There("is %s%s%s here.",
4175.                   reg ? regbuf : "",
4176.                   (reg && trap) ? " and " : "",
4177.                   trap ? an(trapname(trap->ttyp, FALSE)) : "");
4178.     }
4179. 
4180.     otmp = svl.level.objects[u.ux][u.uy];
4181.     dfeature = dfeature_at(u.ux, u.uy, fbuf2);
4182.     if (dfeature && !strcmp(dfeature, "pool of water") && Underwater)
4183.         dfeature = 0;
4184. 
4185.     if (Blind) {
4186.         boolean drift = Is_airlevel(&u.uz) || Is_waterlevel(&u.uz);
4187. 
4188.         if (dfeature && !strncmp(dfeature, "altar ", 6)) {
4189.             /* don't say "altar" twice, dfeature has more info */
4190.             You("try to feel what is here.");
4191.         } else if (SURFACE_AT(u.ux, u.uy) == ICE) {
4192.             /* using describe_decor() to handle ice is simpler than
4193.                replicating it in the conditional message construction */
4194.             if (!flags.mention_decor || iflags.prev_decor == ICE)
4195.                 force_decor(FALSE);
4196.             /* plain "ice" if blind and levitating, otherwise "solid ice" &c;
4197.               "There is [thin ]ice here.  You try to feel what is on it." */
4198.             You("try to feel what is on it.");
4199.             skip_dfeature = TRUE; /* ice already described */
4200.         } else {
4201.             boolean cant_reach = !can_reach_floor(TRUE);
4202.             const char *surf = surface(u.ux, u.uy),
4203.                        *where = cant_reach ? "lying beneath you"
4204.                                            : "lying here on the ",
4205.                        *onwhat = cant_reach ? "" : surf;
4206. 
4207.             You("try to feel what is %s%s.", drift ? "floating here" : where,
4208.                 drift ? "" : onwhat);
4209. 
4210.             if (dfeature && !drift && !strcmp(dfeature, surf))
4211.                 skip_dfeature = TRUE; /* terrain feature already identified */
4212.         }
4213.         trap = t_at(u.ux, u.uy);
4214.         if (!can_reach_floor(trap && is_pit(trap->ttyp))) {
4215.             pline("But you can't reach it!");
4216.             return ECMD_OK;
4217.         }
4218.     }
4219. 
4220.     if (dfeature && !skip_dfeature) {
4221.         const char *p;
4222.         int article = 1; /* 0 => none, 1 => a/an, 2 => the (not used here) */
4223. 
4224.         /* "molten lava", "iron bars", and plain "ice" are handled as special
4225.            cases in an() but probably shouldn't be; don't rely on that */
4226.         if (!strcmp(dfeature, "molten lava")
4227.             || !strcmp(dfeature, "iron bars")
4228.             || !strcmp(dfeature, "ice")
4229.             || !strncmp(dfeature, "frozen ", 7) /* ice while hallucinating */
4230.             /* thawing ice ("solid ice", "thin ice", &c) */
4231.             || ((p = strchr(dfeature, ' ')) != 0 && !strcmpi(p, " ice")))
4232.             article = 0;
4233.         if (article == 1)
4234.             dfeature = an(dfeature);
4235. 
4236.         /* hardcoded "is" worked here because "iron bars" is actually
4237.            "set of iron bars"; use vtense() instead of relying on that */
4238.         Sprintf(fbuf, "There %s %s here.", vtense(dfeature, "are"), dfeature);
4239.     }
4240. 
4241.     if (!otmp || is_lava(u.ux, u.uy)
4242.         || (is_pool(u.ux, u.uy) && !Underwater)) {
4243.         if (dfeature && !skip_dfeature)
4244.             pline1(fbuf);
4245.         read_engr_at(u.ux, u.uy); /* Eric Backus */
4246.         if (!skip_objects && (Blind || !dfeature))
4247.             You("%s no objects here.", verb);
4248.         return (!!Blind ? ECMD_TIME : ECMD_OK);
4249.     }
4250.     /* we know there is something here */
4251. 
4252.     if (skip_objects) {
4253.         if (dfeature && !skip_dfeature)
4254.             pline1(fbuf);
4255.         read_engr_at(u.ux, u.uy); /* Eric Backus */
4256.         if (obj_cnt == 1 && otmp->quan == 1L)
4257.             There("is %s object here.", picked_some ? "another" : "an");
4258.         else
4259.             There("are %s%s objects here.",
4260.                   (obj_cnt == 2) ? "two"
4261.                   : (obj_cnt < 5) ? "a few"
4262.                     : (obj_cnt < 10) ? "several"
4263.                       : "many",
4264.                   picked_some ? " more" : "");
4265.         for (; otmp; otmp = otmp->nexthere)
4266.             if (otmp->otyp == CORPSE && will_feel_cockatrice(otmp, FALSE)) {
4267.                 pline("%s %s%s.",
4268.                       (obj_cnt > 1) ? "Including"
4269.                       : (otmp->quan > 1L) ? "They're"
4270.                         : "It's",
4271.                       corpse_xname(otmp, (const char *) 0, CXN_ARTICLE),
4272.                       poly_when_stoned(gy.youmonst.data) ? ""
4273.                       : ", unfortunately");
4274.                 feel_cockatrice(otmp, FALSE);
4275.                 break;
4276.             }
4277.     } else if (!otmp->nexthere) {
4278.         /* only one object */
4279.         if (dfeature && !skip_dfeature)
4280.             pline1(fbuf);
4281.         read_engr_at(u.ux, u.uy); /* Eric Backus */
4282.         You("%s here %s.", verb, doname_with_price(otmp));
4283.         iflags.last_msg = PLNMSG_ONE_ITEM_HERE;
4284.         if (otmp->otyp == CORPSE)
4285.             feel_cockatrice(otmp, FALSE);
4286.     } else {
4287.         char buf[BUFSZ];
4288. 
4289.         display_nhwindow(WIN_MESSAGE, FALSE);
4290.         tmpwin = create_nhwindow(NHW_MENU);
4291.         if (dfeature && !skip_dfeature) {
4292.             putstr(tmpwin, 0, fbuf);
4293.             putstr(tmpwin, 0, "");
4294.         }
4295.         Sprintf(buf, "%s that %s here:",
4296.                 picked_some ? "Other things" : "Things",
4297.                 Blind ? "you feel" : "are");
4298.         putstr(tmpwin, 0, buf);
4299.         for (; otmp; otmp = otmp->nexthere) {
4300.             if (otmp->otyp == CORPSE && will_feel_cockatrice(otmp, FALSE)) {
4301.                 felt_cockatrice = TRUE;
4302.                 Sprintf(buf, "%s...", doname(otmp));
4303.                 putstr(tmpwin, 0, buf);
4304.                 break;
4305.             }
4306.             putstr(tmpwin, 0, doname_with_price(otmp));
4307.         }
4308.         display_nhwindow(tmpwin, TRUE);
4309.         destroy_nhwindow(tmpwin);
4310.         if (felt_cockatrice)
4311.             feel_cockatrice(otmp, FALSE);
4312.         read_engr_at(u.ux, u.uy); /* Eric Backus */
4313.     }
4314.     return (!!Blind ? ECMD_TIME : ECMD_OK);
4315. }
4316. 
4317. /* #look command - explicitly look at what is here, including all objects */
4318. int
4319. dolook(void)
4320. {
4321.     int res;
4322. 
4323.     /* don't let
4324.        MSGTYPE={norep,noshow} "You see here"
4325.        interfere with feedback from the look-here command */
4326.     hide_unhide_msgtypes(TRUE, MSGTYP_MASK_REP_SHOW);
4327.     res = look_here(0, LOOKHERE_NOFLAGS);
4328.     /* restore normal msgtype handling */
4329.     hide_unhide_msgtypes(FALSE, MSGTYP_MASK_REP_SHOW);
4330.     return res;
4331. }
4332. 
4333. boolean
4334. will_feel_cockatrice(struct obj *otmp, boolean force_touch)
4335. {
4336.     if ((Blind || force_touch) && !uarmg && !Stone_resistance
4337.         && (otmp->otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm])))
4338.         return TRUE;
4339.     return FALSE;
4340. }
4341. 
4342. void
4343. feel_cockatrice(struct obj *otmp, boolean force_touch)
4344. {
4345.     char kbuf[BUFSZ];
4346. 
4347.     if (will_feel_cockatrice(otmp, force_touch)) {
4348.         /* "the <cockatrice> corpse" */
4349.         Strcpy(kbuf, corpse_xname(otmp, (const char *) 0, CXN_PFX_THE));
4350. 
4351.         if (poly_when_stoned(gy.youmonst.data))
4352.             You("touched %s with your bare %s.", kbuf,
4353.                 makeplural(body_part(HAND)));
4354.         else
4355.             pline("Touching %s is a fatal mistake...", kbuf);
4356.         /* normalize body shape here; hand, not body_part(HAND) */
4357.         Sprintf(kbuf, "touching %s bare-handed", killer_xname(otmp));
4358.         /* will call polymon() for the poly_when_stoned() case */
4359.         instapetrify(kbuf);
4360.     }
4361. }
4362. 
4363. /* 'obj' is being placed on the floor; if it can merge with something that
4364.    is already there, combine them and discard obj as a separate object */
4365. void
4366. stackobj(struct obj *obj)
4367. {
4368.     struct obj *otmp;
4369. 
4370.     for (otmp = svl.level.objects[obj->ox][obj->oy]; otmp;
4371.          otmp = otmp->nexthere)
4372.         if (otmp != obj && merged(&obj, &otmp))
4373.             break;
4374.     return;
4375. }
4376. 
4377. /* returns TRUE if obj & otmp can be merged; used in invent.c and mkobj.c */
4378. boolean
4379. mergable(
4380.     struct obj *otmp, /* potential 'into' stack */
4381.     struct obj *obj)  /* 'combine' stack */
4382. {
4383.     size_t objnamelth = 0, otmpnamelth = 0;
4384. 
4385.     /* fail if already the same object, if different types, if either is
4386.        explicitly marked to prevent merge, or if not mergable in general */
4387.     if (obj == otmp || obj->otyp != otmp->otyp
4388.         || obj->nomerge || otmp->nomerge || !objects[obj->otyp].oc_merge)
4389.         return FALSE;
4390. 
4391.     /* coins of the same kind will always merge */
4392.     if (obj->oclass == COIN_CLASS)
4393.         return TRUE;
4394. 
4395.     if (obj->cursed != otmp->cursed || obj->blessed != otmp->blessed)
4396.         return FALSE;
4397. 
4398.     if (obj->how_lost == LOST_EXPLODING
4399.         || otmp->how_lost == LOST_EXPLODING)
4400.         return FALSE;
4401.     if (otmp->how_lost != LOST_NONE && (obj->how_lost != otmp->how_lost))
4402.         return FALSE;
4403. #if 0   /* don't require 'bypass' to match; that results in items dropped
4404.          * via 'D' not stacking with compatible items already on the floor;
4405.          * caller who wants that behavior should use 'nomerge' instead */
4406.     if (obj->bypass != otmp->bypass)
4407.         return FALSE;
4408. #endif
4409. 
4410.     if (obj->globby)
4411.         return TRUE;
4412.     /* Checks beyond this point either aren't applicable to globs
4413.      * or don't inhibit their merger.
4414.      */
4415. 
4416.     if (obj->unpaid != otmp->unpaid || obj->spe != otmp->spe
4417.         || obj->no_charge != otmp->no_charge || obj->obroken != otmp->obroken
4418.         || obj->otrapped != otmp->otrapped || obj->lamplit != otmp->lamplit)
4419.         return FALSE;
4420. 
4421.     if (obj->oclass == FOOD_CLASS
4422.         && (obj->oeaten != otmp->oeaten || obj->orotten != otmp->orotten))
4423.         return FALSE;
4424. 
4425.     if (obj->dknown != otmp->dknown
4426.         || (obj->bknown != otmp->bknown && !Role_if(PM_CLERIC) &&
4427.             (Blind || Hallucination))
4428.         || obj->oeroded != otmp->oeroded || obj->oeroded2 != otmp->oeroded2
4429.         || obj->greased != otmp->greased)
4430.         return FALSE;
4431. 
4432.     if ((erosion_matters(obj))
4433.         && (obj->oerodeproof != otmp->oerodeproof
4434.             || (obj->rknown != otmp->rknown && (Blind || Hallucination))))
4435.         return FALSE;
4436. 
4437.     if (obj->otyp == CORPSE || obj->otyp == EGG || obj->otyp == TIN) {
4438.         if (obj->corpsenm != otmp->corpsenm)
4439.             return FALSE;
4440.     }
4441. 
4442.     /* hatching eggs don't merge; ditto for revivable corpses */
4443.     if ((obj->otyp == EGG && (obj->timed || otmp->timed))
4444.         || (obj->otyp == CORPSE && otmp->corpsenm >= LOW_PM
4445.             && is_reviver(&mons[otmp->corpsenm])))
4446.         return FALSE;
4447. 
4448.     /* allow candle merging only if their ages are close */
4449.     /* see begin_burn() for a reference for the magic "25" */
4450.     if (Is_candle(obj) && obj->age / 25 != otmp->age / 25)
4451.         return FALSE;
4452. 
4453.     /* burning potions of oil never merge */
4454.     if (obj->otyp == POT_OIL && obj->lamplit)
4455.         return FALSE;
4456. 
4457.     /* don't merge surcharged item with base-cost item */
4458.     if (obj->unpaid && !same_price(obj, otmp))
4459.         return FALSE;
4460. 
4461.     /* some additional information is always incompatible */
4462.     if (has_omonst(obj) || has_omid(obj)
4463.         || has_omonst(otmp) || has_omid(otmp))
4464.         return FALSE;
4465. 
4466.     /* if they have names, make sure they're the same */
4467.     objnamelth = strlen(safe_oname(obj));
4468.     otmpnamelth = strlen(safe_oname(otmp));
4469.     if ((objnamelth != otmpnamelth
4470.          && ((objnamelth && otmpnamelth) || obj->otyp == CORPSE))
4471.         || (objnamelth && otmpnamelth
4472.            /* verify pointers before deref for static analyzer */
4473.             && has_oname(obj) && has_oname(otmp)
4474.                && strncmp(ONAME(obj), ONAME(otmp), objnamelth)))
4475.         return FALSE;
4476. 
4477.     /* if one has an attached mail command, other must have same command */
4478.     if (!has_omailcmd(obj) ? has_omailcmd(otmp)
4479.         : (!has_omailcmd(otmp) || strcmp(OMAILCMD(obj), OMAILCMD(otmp)) != 0))
4480.         return FALSE;
4481. 
4482. #ifdef MAIL_STRUCTURES
4483.     if (obj->otyp == SCR_MAIL
4484.         /* wished or bones mail and hand written stamped scrolls
4485.            each have two flavors; spe keeps them separate from each
4486.            other but we want to keep their flavors separate too */
4487.         && obj->spe > 0 && (obj->o_id % 2) != (otmp->o_id % 2))
4488.         return FALSE;
4489. #endif
4490. 
4491.     /* should be moot since matching artifacts wouldn't be unique */
4492.     if (obj->oartifact != otmp->oartifact)
4493.         return FALSE;
4494. 
4495.     if (obj->known != otmp->known && (Blind || Hallucination))
4496.         return FALSE;
4497. 
4498.     return TRUE;
4499. }
4500. 
4501. /* the #showgold command */
4502. int
4503. doprgold(void)
4504. {
4505.     /* Command takes containers into account. */
4506.     long umoney = money_cnt(gi.invent);
4507. 
4508.     /* Only list the money you know about.  Guards and shopkeepers
4509.        can somehow tell if there is any gold anywhere on your
4510.        person, but you have no such preternatural gold-sense. */
4511.     long hmoney = hidden_gold(FALSE);
4512. 
4513.     if (flags.verbose) {
4514.         char buf[BUFSZ];
4515. 
4516.         if (!umoney) {
4517.             Strcpy(buf, "Your wallet is empty");
4518.         } else {
4519.             Sprintf(buf, "Your wallet contains %ld %s",
4520.                     umoney, currency(umoney));
4521.         }
4522.         if (hmoney) {
4523.             Sprintf(eos(buf),
4524.                     ", %s you have %ld %s stashed away in your pack",
4525.                     umoney ? "and" : "but", hmoney,
4526.                     umoney ? "more" : currency(hmoney));
4527.         }
4528.         pline("%s.", buf);
4529.     } else {
4530.         long total = umoney + hmoney;
4531.         if (total)
4532.             You("are carrying a total of %ld %s.", total, currency(total));
4533.         else
4534.             You("have no money.");
4535.     }
4536.     shopper_financial_report();
4537. 
4538.     if (umoney && iflags.menu_requested) {
4539.         char dollarsign[] = "$";
4540. 
4541.         /* mustn't use TRUE or gold wouldn't show up unless it was quivered */
4542.         (void) dispinv_with_action(dollarsign, FALSE, NULL);
4543.     }
4544. 
4545.     return ECMD_OK;
4546. }
4547. 
4548. /* the #seeweapon command */
4549. int
4550. doprwep(void)
4551. {
4552.     if (!uwep) {
4553.         You("are %s.", empty_handed());
4554.     } else if (!iflags.menu_requested) {
4555.         prinv((char *) 0, uwep, 0L);
4556.         if (u.twoweap)
4557.             prinv((char *) 0, uswapwep, 0L);
4558.     } else {
4559.         char lets[4]; /* 4: uwep, uswapwep, uquiver, terminator */
4560.         int ct = 0;
4561. 
4562.         /* obj_to_let() will assign letters to all of invent if necessary
4563.            (for '!fixinv') so doesn't need to be repeated once called here */
4564.         lets[ct++] = obj_to_let(uwep);
4565.         if (uswapwep)
4566.             lets[ct++] = uswapwep->invlet;
4567.         if (uquiver)
4568.             lets[ct++] = uquiver->invlet;
4569.         lets[ct] = '\0';
4570. 
4571.         (void) dispinv_with_action(lets, TRUE, NULL);
4572.     }
4573.     return ECMD_OK;
4574. }
4575. 
4576. /* caller is responsible for checking !wearing_armor() */
4577. staticfn void
4578. noarmor(boolean report_uskin)
4579. {
4580.     if (!uskin || !report_uskin) {
4581.         You("are not wearing any armor.");
4582.     } else {
4583.         char *p, *uskinname, buf[BUFSZ];
4584. 
4585.         uskinname = strcpy(buf, simpleonames(uskin));
4586.         /* shorten "set of <color> dragon scales" to "<color> scales"
4587.            and "<color> dragon scale mail" to "<color> scale mail" */
4588.         if (!strncmpi(uskinname, "set of ", 7))
4589.             uskinname += 7;
4590.         if ((p = strstri(uskinname, " dragon ")) != 0)
4591.             while ((p[1] = p[8]) != '\0')
4592.                 ++p;
4593. 
4594.         You("are not wearing armor but have %s embedded in your skin.",
4595.             uskinname);
4596.     }
4597. }
4598. 
4599. /* the #seearmor command */
4600. int
4601. doprarm(void)
4602. {
4603.     /*
4604.      * Note:  players sometimes get here by pressing a function key which
4605.      * transmits ESC [ <something> rather than by pressing '[';
4606.      * there's nothing we can--or should-do about that here.
4607.      */
4608. 
4609.     if (!wearing_armor()) {
4610.         noarmor(TRUE);
4611.     } else {
4612.         char lets[8]; /* 8: up to 7 pieces of armor plus terminator */
4613.         int ct = 0;
4614. 
4615.         /* obj_to_let() will assign letters to all of invent if necessary
4616.            (for '!fixinv') so doesn't need to be repeated once called, but
4617.            each armor slot doesn't know whether any that precede have made
4618.            that call so just do it for each one; use SORTPACK_INUSE order */
4619.         if (uarm)
4620.             lets[ct++] = obj_to_let(uarm);
4621.         if (uarmc)
4622.             lets[ct++] = obj_to_let(uarmc);
4623.         if (uarms)
4624.             lets[ct++] = obj_to_let(uarms);
4625.         if (uarmh)
4626.             lets[ct++] = obj_to_let(uarmh);
4627.         if (uarmg)
4628.             lets[ct++] = obj_to_let(uarmg);
4629.         if (uarmf)
4630.             lets[ct++] = obj_to_let(uarmf);
4631.         if (uarmu)
4632.             lets[ct++] = obj_to_let(uarmu);
4633.         lets[ct] = 0;
4634. 
4635.         (void) dispinv_with_action(lets, TRUE, NULL);
4636.     }
4637.     return ECMD_OK;
4638. }
4639. 
4640. /* the #seerings command */
4641. int
4642. doprring(void)
4643. {
4644.     if (!uleft && !uright) {
4645.         You("are not wearing any rings.");
4646.     } else {
4647.         char lets[3]; /* 3: uright, uleft, terminator */
4648.         boolean use_inuse_mode = FALSE;
4649.         int ct = 0;
4650. 
4651.         /* if either ring is a meat ring, switch to use_inuse_mode in order
4652.            to label it/them as "Rings" rather than "Comestibles" */
4653.         if (uright) {
4654.             lets[ct++] = obj_to_let(uright);
4655.             if (uright->oclass != RING_CLASS)
4656.                 use_inuse_mode = TRUE;
4657.         }
4658.         if (uleft) {
4659.             lets[ct++] = obj_to_let(uleft);
4660.             if (uleft->oclass != RING_CLASS)
4661.                 use_inuse_mode = TRUE;
4662.         }
4663.         lets[ct] = '\0';
4664.         /* also switch to use_inuse_mode if there are two rings or player
4665.            used the 'm' prefix */
4666.         if (ct > 1 || iflags.menu_requested)
4667.             use_inuse_mode = TRUE;
4668. 
4669.         (void) dispinv_with_action(lets, use_inuse_mode,
4670.                                    /* note; alternate label will be ignored
4671.                                       if 'use_inuse_mode' is False */
4672.                                    (ct == 1) ? "Ring" : "Rings");
4673.     }
4674.     return ECMD_OK;
4675. }
4676. 
4677. /* the #seeamulet command */
4678. int
4679. dopramulet(void)
4680. {
4681.     if (!uamul) {
4682.         You("are not wearing an amulet.");
4683.     } else {
4684.         char lets[2];
4685. 
4686.         /* using display_inventory() instead of prinv() allows player
4687.            to use 'm "' to force and menu and be able to choose amulet
4688.            in order to perform a context-sensitive item action */
4689.         lets[0] = obj_to_let(uamul), lets[1] = '\0';
4690. 
4691.         (void) dispinv_with_action(lets, TRUE, "Amulet");
4692.     }
4693.     return ECMD_OK;
4694. }
4695. 
4696. /* is 'obj' a tool that's in use?  can't simply check obj->owornmask */
4697. staticfn boolean
4698. tool_being_used(struct obj *obj)
4699. {
4700.     /*
4701.      * [Should this also include lit potions of oil?  They're not tools
4702.      *  but they are "in use" without being noticeable via obj->owornmask.]
4703.      */
4704.     if ((obj->owornmask & (W_TOOL | W_SADDLE)) != 0L)
4705.         return TRUE;
4706.     if (obj->oclass != TOOL_CLASS)
4707.         return FALSE;
4708.     /* [don't actually need to check uwep here; caller catches it] */
4709.     return (boolean) (obj == uwep || obj->lamplit
4710.                       || (obj->otyp == LEASH && obj->leashmon));
4711. }
4712. 
4713. /* the #seetools command */
4714. int
4715. doprtool(void)
4716. {
4717.     struct obj *otmp;
4718.     int ct = 0;
4719.     char lets[invlet_basic + 1];
4720. 
4721.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
4722.         if (tool_being_used(otmp)) {
4723.             /* we could be carrying more than 52 items; theoretically they
4724.                might all be lit candles so avoid potential lets[] overflow */
4725.             if (ct >= (int) sizeof lets - 1)
4726.                 break;
4727.             lets[ct++] = obj_to_let(otmp);
4728.         }
4729.     lets[ct] = '\0';
4730.     if (!ct)
4731.         You("are not using any tools.");
4732.     else
4733.         (void) dispinv_with_action(lets, TRUE, NULL);
4734.     return ECMD_OK;
4735. }
4736. 
4737. /* the #seeall command; combines the ')' + '[' + '=' + '"' + '(' commands;
4738.    show inventory of all currently wielded, worn, or used objects */
4739. int
4740. doprinuse(void)
4741. {
4742.     struct obj *otmp;
4743.     int ct = 0;
4744. 
4745.     /* no longer need to collect letters; sortloot() takes care of it, but
4746.        still want to count far enough to know whether anything is in use */
4747.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
4748.         if (is_inuse(otmp)) {
4749.             ++ct;
4750.             break;
4751.         }
4752.     if (!ct)
4753.         You("are not wearing or wielding anything.");
4754.     else
4755.         (void) dispinv_with_action((char *) 0, TRUE, NULL);
4756.     return ECMD_OK;
4757. }
4758. 
4759. /*
4760.  * uses up an object that's on the floor, charging for it as necessary
4761.  */
4762. void
4763. useupf(struct obj *obj, long numused)
4764. {
4765.     struct obj *otmp;
4766.     boolean at_u = u_at(obj->ox, obj->oy);
4767. 
4768.     /* burn_floor_objects() keeps an object pointer that it tries to
4769.      * useupf() multiple times, so obj must survive if plural */
4770.     if (obj->quan > numused)
4771.         otmp = splitobj(obj, numused);
4772.     else
4773.         otmp = obj;
4774.     if (!svc.context.mon_moving && costly_spot(otmp->ox, otmp->oy)) {
4775.         if (strchr(u.urooms, *in_rooms(otmp->ox, otmp->oy, 0)))
4776.             addtobill(otmp, FALSE, FALSE, FALSE);
4777.         else
4778.             (void) stolen_value(otmp, otmp->ox, otmp->oy, FALSE, FALSE);
4779.     }
4780.     delobj(otmp);
4781.     if (at_u && u.uundetected && hides_under(gy.youmonst.data))
4782.         (void) hideunder(&gy.youmonst);
4783. }
4784. 
4785. /*
4786.  * Conversion from a class to a string for printing.
4787.  * This must match the object class order.
4788.  */
4789. static NEARDATA const char *names[] = {
4790.     0, "Illegal objects", "Weapons", "Armor", "Rings", "Amulets", "Tools",
4791.     "Comestibles", "Potions", "Scrolls", "Spellbooks", "Wands", "Coins",
4792.     "Gems/Stones", "Boulders/Statues", "Iron balls", "Chains", "Venoms"
4793. };
4794. static NEARDATA const char oth_symbols[] = { CONTAINED_SYM, '\0' };
4795. static NEARDATA const char *oth_names[] = { "Bagged/Boxed items" };
4796. 
4797. DISABLE_WARNING_FORMAT_NONLITERAL
4798. 
4799. char *
4800. let_to_name(char let, boolean unpaid, boolean showsym)
4801. {
4802.     const char *ocsymfmt = "  ('%c')";
4803.     const int invbuf_sympadding = 8; /* arbitrary */
4804.     const char *class_name;
4805.     const char *pos;
4806.     int oclass = (let >= 1 && let < MAXOCLASSES) ? let : 0;
4807.     unsigned len;
4808. 
4809.     if (oclass)
4810.         class_name = names[oclass];
4811.     else if ((pos = strchr(oth_symbols, let)) != 0)
4812.         class_name = oth_names[pos - oth_symbols];
4813.     else
4814.         class_name = names[ILLOBJ_CLASS];
4815. 
4816.     len = Strlen(class_name) + (unpaid ? sizeof "unpaid_" : sizeof "")
4817.           + (oclass ? (Strlen(ocsymfmt) + invbuf_sympadding) : 0);
4818.     if (len > gi.invbufsiz) {
4819.         if (gi.invbuf)
4820.             free((genericptr_t) gi.invbuf);
4821.         gi.invbufsiz = len + 10; /* add slop to reduce incremental realloc */
4822.         gi.invbuf = (char *) alloc(gi.invbufsiz);
4823.     }
4824.     if (unpaid)
4825.         Strcat(strcpy(gi.invbuf, "Unpaid "), class_name);
4826.     else
4827.         Strcpy(gi.invbuf, class_name);
4828.     if ((oclass != 0) && showsym) {
4829.         char *bp = eos(gi.invbuf);
4830.         int mlen = invbuf_sympadding - Strlen(class_name);
4831.         while (--mlen > 0) {
4832.             *bp = ' ';
4833.             bp++;
4834.         }
4835.         *bp = '\0';
4836.         Sprintf(eos(gi.invbuf), ocsymfmt, def_oc_syms[oclass].sym);
4837.     }
4838.     return gi.invbuf;
4839. }
4840. 
4841. RESTORE_WARNING_FORMAT_NONLITERAL
4842. 
4843. /* release the static buffer used by let_to_name() */
4844. void
4845. free_invbuf(void)
4846. {
4847.     if (gi.invbuf)
4848.         free((genericptr_t) gi.invbuf), gi.invbuf = (char *) 0;
4849.     gi.invbufsiz = 0;
4850. }
4851. 
4852. /* give consecutive letters to every item in inventory (for !fixinv mode);
4853.    gold is always forced to '$' slot at head of list */
4854. void
4855. reassign(void)
4856. {
4857.     int i;
4858.     struct obj *obj, *prevobj, *goldobj;
4859. 
4860.     /* first, remove [first instance of] gold from invent, if present */
4861.     prevobj = goldobj = 0;
4862.     for (obj = gi.invent; obj; prevobj = obj, obj = obj->nobj)
4863.         if (obj->oclass == COIN_CLASS) {
4864.             goldobj = obj;
4865.             if (prevobj)
4866.                 prevobj->nobj = goldobj->nobj;
4867.             else
4868.                 gi.invent = goldobj->nobj;
4869.             break;
4870.         }
4871.     /* second, re-letter the rest of the list */
4872.     for (obj = gi.invent, i = 0; obj; obj = obj->nobj, i++)
4873.         obj->invlet =
4874.             (i < 26) ? ('a' + i) : (i < 52) ? ('A' + i - 26) : NOINVSYM;
4875.     /* third, assign gold the "letter" '$' and re-insert it at head */
4876.     if (goldobj) {
4877.         goldobj->invlet = GOLD_SYM;
4878.         goldobj->nobj = gi.invent;
4879.         gi.invent = goldobj;
4880.     }
4881.     if (i >= 52)
4882.         i = 52 - 1;
4883.     gl.lastinvnr = i;
4884. }
4885. 
4886. /* invent gold sanity check; used by doorganize() to control how getobj()
4887.    deals with gold and also by wizard mode sanity_check() */
4888. boolean
4889. check_invent_gold(const char *why) /* 'why' == caller in case of warning */
4890. {
4891.     struct obj *otmp;
4892.     int goldstacks = 0, wrongslot = 0;
4893. 
4894.     /* there should be at most one stack of gold in invent, in slot '$' */
4895.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
4896.         if (otmp->oclass == COIN_CLASS) {
4897.             ++goldstacks;
4898.             if (otmp->invlet != GOLD_SYM)
4899.                 ++wrongslot;
4900.         }
4901. 
4902.     if (goldstacks > 1 || wrongslot > 0) {
4903.         impossible("%s: %s%s%s", why,
4904.                    (wrongslot > 1) ? "gold in wrong slots"
4905.                       : (wrongslot > 0) ? "gold in wrong slot"
4906.                            : "",
4907.                    (wrongslot > 0 && goldstacks > 1) ? " and " : "",
4908.                    (goldstacks > 1) ? "multiple gold stacks" : "");
4909.         return TRUE; /* gold can be #adjusted */
4910.     }
4911. 
4912.     return FALSE; /* gold can't be #adjusted */
4913. }
4914. 
4915. /* normal getobj callback for item to #adjust; excludes gold */
4916. staticfn int
4917. adjust_ok(struct obj *obj)
4918. {
4919.     if (!obj || obj->oclass == COIN_CLASS)
4920.         return GETOBJ_EXCLUDE;
4921. 
4922.     return GETOBJ_SUGGEST;
4923. }
4924. 
4925. /* getobj callback for item to #adjust if gold is wonky; allows gold */
4926. staticfn int
4927. adjust_gold_ok(struct obj *obj)
4928. {
4929.     if (!obj)
4930.         return GETOBJ_EXCLUDE;
4931. 
4932.     return GETOBJ_SUGGEST;
4933. }
4934. 
4935. /* #adjust command
4936.  *
4937.  *      User specifies a 'from' slot for inventory stack to move,
4938.  *      then a 'to' slot for its destination.  Open slots and those
4939.  *      filled by compatible stacks are listed as likely candidates
4940.  *      but user can pick any inventory letter (including 'from').
4941.  *
4942.  *  to == from, 'from' has a name
4943.  *      All compatible items (same name or no name) are gathered
4944.  *      into the 'from' stack.  No count is allowed.
4945.  *  to == from, 'from' does not have a name
4946.  *      All compatible items without a name are gathered into the
4947.  *      'from' stack.  No count is allowed.  Compatible stacks with
4948.  *      names are left as-is.
4949.  *  to != from, no count
4950.  *      Move 'from' to 'to'.  If 'to' is not empty, merge 'from'
4951.  *      into it if possible, otherwise swap it with the 'from' slot.
4952.  *  to != from, count given
4953.  *      If the user specifies a count when choosing the 'from' slot,
4954.  *      and that count is less than the full size of the stack,
4955.  *      then the stack will be split.  The 'count' portion is moved
4956.  *      to the destination, and the only candidate for merging with
4957.  *      it is the stack already at the 'to' slot, if any.  When the
4958.  *      destination is non-empty but won't merge, whatever is there
4959.  *      will be moved to an open slot; if there isn't any open slot
4960.  *      available, the adjustment attempt fails.
4961.  *
4962.  *      To minimize merging for 'from == to', unnamed stacks will
4963.  *      merge with named 'from' but named ones won't merge with
4964.  *      unnamed 'from'.  Otherwise attempting to collect all unnamed
4965.  *      stacks would lump the first compatible named stack with them
4966.  *      and give them its name.
4967.  *
4968.  *      To maximize merging for 'from != to', compatible stacks will
4969.  *      merge when either lacks a name (or they already have the same
4970.  *      name).  When no count is given and one stack has a name and
4971.  *      the other doesn't, the merged result will have that name.
4972.  *      However, when splitting results in a merger, the name of the
4973.  *      destination overrides that of the source, even if destination
4974.  *      is unnamed and source is named.
4975.  *
4976.  *      Gold is only a candidate to adjust if we've somehow managed
4977.  *      to get multiple stacks and/or it is in a slot other than '$'.
4978.  *      Specifying a count to split it into two stacks is not allowed.
4979.  */
4980. int
4981. doorganize(void) /* inventory organizer by Del Lamb */
4982. {
4983.     int (*adjust_filter)(struct obj *);
4984.     struct obj *obj;
4985. 
4986.     /* when no invent, or just gold in '$' slot, there's nothing to adjust */
4987.     if (!gi.invent || (gi.invent->oclass == COIN_CLASS
4988.                       && gi.invent->invlet == GOLD_SYM && !gi.invent->nobj)) {
4989.         You("aren't carrying anything %s.",
4990.             !gi.invent ? "to adjust" : "adjustable");
4991.         return ECMD_OK;
4992.     }
4993. 
4994.     if (!flags.invlet_constant)
4995.         reassign();
4996. 
4997.     /* filter passed to getobj() depends upon gold sanity */
4998.     adjust_filter = check_invent_gold("adjust") ? adjust_gold_ok : adjust_ok;
4999. 
5000.     /* get object the user wants to organize (the 'from' slot) */
5001.     obj = getobj("adjust", adjust_filter, GETOBJ_PROMPT | GETOBJ_ALLOWCNT);
5002. 
5003.     return doorganize_core(obj);
5004. }
5005. 
5006. /* alternate version of #adjust used by itemactions() for splitting */
5007. int
5008. adjust_split(void)
5009. {
5010.     struct obj *obj;
5011.     cmdcount_nht splitamount = 0L;
5012.     char let, dig = '\0';
5013. 
5014.     /* invlet should be queued so no getobj prompting is expected */
5015.     obj = getobj("split", adjust_ok, GETOBJ_NOFLAGS);
5016.     if (!obj || obj->quan < 2L || obj->otyp == GOLD_PIECE)
5017.         return ECMD_FAIL; /* caller has set things up to avoid this */
5018. 
5019.     if (obj->quan == 2L) {
5020.         splitamount = 1L;
5021.     } else {
5022.         /* get first digit; doesn't wait for <return> */
5023.         dig = yn_function("Split off how many?", (char *) 0, '\0', TRUE);
5024.         if (!digit(dig)) {
5025.             pline1(Never_mind);
5026.             return ECMD_CANCEL;
5027.         }
5028.         /* got first digit, get more until next non-digit (except for
5029.            backspace/delete which will take away most recent digit and
5030.            keep going; we expect one of ' ', '\n', or '\r') */
5031.         let = get_count(NULL, dig, 0L, &splitamount,
5032.                         /* yn_function() added the first digit to the
5033.                            prompt when recording message history; have
5034.                            get_count() display "Count: N" when waiting
5035.                            for additional digits (ordinarily that won't be
5036.                            shown until a second digit is entered) and also
5037.                            add "Count: N" to message history if more than
5038.                            one digit gets entered or the original N is
5039.                            deleted and replaced with different digit */
5040.                         GC_ECHOFIRST | GC_CONDHIST);
5041.         /* \033 is in quitchars[] so we need to check for it separately
5042.            in order to treat it as cancel rather than as accept */
5043.         if (!let || let == '\033' || !strchr(quitchars, let)) {
5044.             pline1(Never_mind);
5045.             return ECMD_CANCEL;
5046.         }
5047.     }
5048.     if (splitamount < 1L || splitamount >= obj->quan) {
5049.         static const char
5050.             Amount[] = "Amount to split from current stack must be";
5051. 
5052.         if (splitamount < 1L)
5053.             pline("%s at least 1.", Amount);
5054.         else
5055.             pline("%s less than %ld.", Amount, obj->quan);
5056.         return ECMD_CANCEL;
5057.     }
5058. 
5059.     /* normally a split would take place in getobj() if player supplies
5060.        a count there, so doorganize_core() figures out 'splitamount'
5061.        from the object; it will undo the split if player cancels while
5062.        selecting the destination slot */
5063.     obj = splitobj(obj, (long) splitamount);
5064.     return doorganize_core(obj);
5065. }
5066. 
5067. staticfn int
5068. doorganize_core(struct obj *obj)
5069. {
5070.     struct obj *otmp, *splitting, *bumped;
5071.     int ix, cur, trycnt;
5072.     char let;
5073. #define GOLD_INDX   0
5074. #define GOLD_OFFSET 1
5075. #define OVRFLW_INDX (GOLD_OFFSET + invlet_basic) /* past gold+2*26 letters */
5076.     char lets[1 + invlet_basic + 1 + 1]; /* room for '$a-zA-Z#\0' */
5077.     char qbuf[QBUFSZ];
5078.     char *objname, *otmpname;
5079.     const char *adj_type;
5080.     boolean ever_mind = FALSE, collect, isgold;
5081. 
5082.     if (!obj)
5083.         return ECMD_CANCEL;
5084. 
5085.     /* can only be gold if check_invent_gold() found a problem:  multiple '$'
5086.        stacks and/or gold in some other slot, otherwise (*adjust_filter)()
5087.        won't allow gold to be picked; if player has picked any stack of gold
5088.        as #adjust 'from' slot, we'll force the 'to' slot to be '$' below */
5089.     isgold = (obj->oclass == COIN_CLASS);
5090. 
5091.     /* figure out whether user gave a split count to getobj() */
5092.     splitting = bumped = 0;
5093.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
5094.         if (otmp->nobj == obj) { /* knowledge of splitobj() operation */
5095.             if (otmp->invlet == obj->invlet)
5096.                 splitting = otmp;
5097.             break;
5098.         }
5099. 
5100.     /* initialize the list with all lower and upper case letters */
5101.     lets[GOLD_INDX] = (obj->oclass == COIN_CLASS) ? GOLD_SYM : ' ';
5102.     for (ix = GOLD_OFFSET, let = 'a'; let <= 'z';)
5103.         lets[ix++] = let++;
5104.     for (let = 'A'; let <= 'Z';)
5105.         lets[ix++] = let++;
5106.     lets[OVRFLW_INDX] = ' ';
5107.     lets[sizeof lets - 1] = '\0';
5108.     /* for floating inv letters, truncate list after the first open slot */
5109.     if (!flags.invlet_constant && (ix = inv_cnt(FALSE)) < invlet_basic)
5110.         lets[ix + (splitting ? 1 : 2)] = '\0';
5111. 
5112.     /* blank out all the letters currently in use in the inventory
5113.        except those that will be merged with the selected object */
5114.     for (otmp = gi.invent; otmp; otmp = otmp->nobj)
5115.         if (otmp != obj && !mergable(otmp, obj)) {
5116.             let = otmp->invlet;
5117.             if (let >= 'a' && let <= 'z')
5118.                 lets[GOLD_OFFSET + let - 'a'] = ' ';
5119.             else if (let >= 'A' && let <= 'Z')
5120.                 lets[GOLD_OFFSET + let - 'A' + 26] = ' ';
5121.             /* overflow defaults to off, but it we find a stack using that
5122.                slot, switch to on -- the opposite of normal invlet handling */
5123.             else if (let == NOINVSYM)
5124.                 lets[OVRFLW_INDX] = NOINVSYM;
5125.         }
5126. 
5127.     /* compact the list by removing all the blanks */
5128.     for (ix = cur = 0; lets[ix]; ix++)
5129.         if (lets[ix] != ' ' && cur++ < ix)
5130.             lets[cur - 1] = lets[ix];
5131.     lets[cur] = '\0';
5132.     /* and by dashing runs of letters */
5133.     if (cur > 5)
5134.         compactify(lets);
5135. 
5136.     /* get 'to' slot to use as destination */
5137.     if (!splitting)
5138.         Strcpy(qbuf, "Adjust letter");
5139.     else /* note: splitting->quan is the amount being left in original slot */
5140.         Sprintf(qbuf, "Split %ld", obj->quan);
5141.     Sprintf(eos(qbuf), " to what [%s]%s?", lets,
5142.             gi.invent ? " (? see used letters)" : "");
5143.     for (trycnt = 1; ; ++trycnt) {
5144.         let = !isgold ? yn_function(qbuf, (char *) 0, '\0', TRUE) : GOLD_SYM;
5145.         if (let == '?' || let == '*') {
5146.             let = display_used_invlets(splitting ? obj->invlet : 0);
5147.             if (!let)
5148.                 continue;
5149.             if (let == '\033')
5150.                 goto noadjust;
5151.         }
5152.         if (strchr(quitchars, let)
5153.             /* adjusting to same slot is meaningful since all
5154.                compatible stacks get collected along the way,
5155.                but splitting to same slot is not */
5156.             || (splitting && let == obj->invlet)) {
5157.  noadjust:
5158.             if (splitting)
5159.                 (void) merged(&splitting, &obj);
5160.             if (!ever_mind)
5161.                 pline1(Never_mind);
5162.             return ECMD_OK;
5163.         } else if (let == GOLD_SYM && obj->oclass != COIN_CLASS) {
5164.             pline("Only gold coins may be moved into the '%c' slot.",
5165.                   GOLD_SYM);
5166.             ever_mind = TRUE;
5167.             goto noadjust;
5168.         }
5169.         /* letter() classifies '@' as one; compactify() can put '-' in lets;
5170.            the only thing of interest that strchr() might find is '$' or '#'
5171.            since letter() catches everything else that we put into lets[] */
5172.         if ((letter(let) && let != '@') || (strchr(lets, let) && let != '-'))
5173.             break; /* got one */
5174.         if (trycnt == 5)
5175.             goto noadjust;
5176.         pline("Select an inventory slot letter."); /* else try again */
5177.     }
5178. 
5179.     collect = (let == obj->invlet);
5180.     /* change the inventory and print the resulting item */
5181.     adj_type = collect ? "Collecting:"
5182.                : !splitting ? "Moving:"
5183.                  : "Splitting:";
5184. 
5185.     /*
5186.      * don't use freeinv/addinv to avoid double-touching artifacts,
5187.      * dousing lamps, losing luck, cursing loadstone, etc.
5188.      */
5189.     extract_nobj(obj, &gi.invent);
5190. 
5191.     for (otmp = gi.invent; otmp; ) {
5192.         otmpname = has_oname(otmp) ? ONAME(otmp) : (char *) 0;
5193.         /* it's tempting to pull this outside the loop, but merged() could
5194.            free ONAME(obj) [via obfree()] and replace it with ONAME(otmp) */
5195.         objname = has_oname(obj) ? ONAME(obj) : (char *) 0;
5196. 
5197.         if (collect) {
5198.             /* Collecting: #adjust an inventory stack into its same slot;
5199.                keep it there and merge other compatible stacks into it.
5200.                Traditional inventory behavior is to merge unnamed stacks
5201.                with compatible named ones; we only want that if it is
5202.                the 'from' stack (obj) with a name and candidate (otmp)
5203.                without one, not unnamed 'from' with named candidate. */
5204.             if ((!otmpname || (objname && !strcmp(objname, otmpname)))
5205.                 && merged(&otmp, &obj)) {
5206.                 /*adj_type = "Collecting:"; //already set to this*/
5207.                 obj = otmp;
5208.                 otmp = otmp->nobj;
5209.                 extract_nobj(obj, &gi.invent);
5210.                 continue; /* otmp has already been updated */
5211.             }
5212.         } else if (otmp->invlet == let) {
5213.             /* Merging: when from and to are compatible */
5214.             if ((!otmpname || (objname && !strcmp(objname, otmpname)))
5215.                 && merged(&otmp, &obj)) {
5216.                 adj_type = "Merging:";
5217.                 obj = otmp;
5218.                 otmp = otmp->nobj;
5219.                 extract_nobj(obj, &gi.invent);
5220.                 break; /* otmp has been updated and we're done merging */
5221.             }
5222.             /* Moving or splitting: don't merge extra compatible stacks.
5223.                Found 'otmp' in destination slot; merge if compatible,
5224.                otherwise bump whatever is there to an open slot. */
5225.             if (!splitting) {
5226.                 adj_type = "Swapping:";
5227.                 otmp->invlet = obj->invlet;
5228.             } else {
5229.                 /* strip 'from' name if it has one */
5230.                 if (objname && !obj->oartifact)
5231.                     ONAME(obj) = (char *) 0;
5232.                 if (!mergable(otmp, obj)) {
5233.                     /* won't merge; put 'from' name back */
5234.                     if (objname)
5235.                         ONAME(obj) = objname;
5236.                 } else {
5237.                     /* will merge; discard 'from' name */
5238.                     if (objname)
5239.                         free((genericptr_t) objname), objname = 0;
5240.                 }
5241. 
5242.                 if (merged(&otmp, &obj)) {
5243.                     adj_type = "Splitting and merging:";
5244.                     obj = otmp;
5245.                     extract_nobj(obj, &gi.invent);
5246.                 } else if (inv_cnt(FALSE) >= invlet_basic) {
5247.                     (void) merged(&splitting, &obj); /* undo split */
5248.                     /* "knapsack cannot accommodate any more items" */
5249.                     Your("pack is too full.");
5250.                     return ECMD_OK;
5251.                 } else {
5252.                     bumped = otmp;
5253.                     extract_nobj(bumped, &gi.invent);
5254.                 }
5255.             } /* moving vs splitting */
5256.             break; /* not collecting and found 'to' slot */
5257.         } /* collect */
5258.         otmp = otmp->nobj;
5259.     }
5260. 
5261.     /* inline addinv; insert loose object at beginning of inventory */
5262.     obj->invlet = let;
5263.     obj->nobj = gi.invent;
5264.     obj->where = OBJ_INVENT;
5265.     gi.invent = obj;
5266.     reorder_invent();
5267.     if (bumped) {
5268.         /* splitting the 'from' stack is causing an incompatible
5269.            stack in the 'to' slot to be moved into an open one;
5270.            we need to do another inline insertion to inventory */
5271.         assigninvlet(bumped);
5272.         bumped->nobj = gi.invent;
5273.         bumped->where = OBJ_INVENT;
5274.         gi.invent = bumped;
5275.         reorder_invent();
5276.     }
5277. 
5278.     /* messages deferred until inventory has been fully reestablished */
5279.     prinv(adj_type, obj, 0L);
5280.     if (bumped)
5281.         prinv("Moving:", bumped, 0L);
5282.     if (splitting)
5283.         clear_splitobjs(); /* reset splitobj context */
5284.     update_inventory();
5285.     return ECMD_OK;
5286. }
5287. 
5288. /* common to display_minventory and display_cinventory */
5289. staticfn void
5290. invdisp_nothing(const char *hdr, const char *txt)
5291. {
5292.     winid win;
5293.     menu_item *selected;
5294. 
5295.     win = create_nhwindow(NHW_MENU);
5296.     start_menu(win, MENU_BEHAVE_STANDARD);
5297.     add_menu_heading(win, hdr);
5298.     add_menu_str(win, "");
5299.     add_menu_str(win, txt);
5300.     end_menu(win, (char *) 0);
5301.     if (select_menu(win, PICK_NONE, &selected) > 0)
5302.         free((genericptr_t) selected);
5303.     destroy_nhwindow(win);
5304.     return;
5305. }
5306. 
5307. /* query_objlist callback: return things that are worn or wielded */
5308. staticfn boolean
5309. worn_wield_only(struct obj *obj)
5310. {
5311. #if 1
5312.     /* check for things that *are* worn or wielded (only used for monsters,
5313.        so we don't worry about excluding W_CHAIN, W_ARTI and the like) */
5314.     return (boolean) (obj->owornmask != 0L);
5315. #else
5316.     /* this used to check for things that *might* be worn or wielded,
5317.        but that's not particularly interesting */
5318.     if (is_weptool(obj) || is_wet_towel(obj) || obj->otyp == MEAT_RING)
5319.         return TRUE;
5320.     return (boolean) (obj->oclass == WEAPON_CLASS
5321.                       || obj->oclass == ARMOR_CLASS
5322.                       || obj->oclass == AMULET_CLASS
5323.                       || obj->oclass == RING_CLASS);
5324. #endif
5325. }
5326. 
5327. /*
5328.  * Display a monster's inventory.
5329.  * Returns a pointer to the object from the monster's inventory selected
5330.  * or NULL if nothing was selected.
5331.  *
5332.  * By default, only worn and wielded items are displayed.  The caller
5333.  * can pick one.  Modifier flags are:
5334.  *
5335.  *      PICK_NONE, PICK_ONE - standard menu control
5336.  *      PICK_ANY            - allowed, but we only return a single object
5337.  *      MINV_NOLET          - nothing selectable
5338.  *      MINV_ALL            - display all inventory
5339.  */
5340. struct obj *
5341. display_minventory(
5342.     struct monst *mon, /* monster whose minvent we're showing */
5343.     int dflags,        /* control over what to display */
5344.     char *title)       /* menu title */
5345. {
5346.     struct obj *ret;
5347.     char tmp[QBUFSZ];
5348.     int n;
5349.     menu_item *selected = 0;
5350.     int do_all = (dflags & MINV_ALL) != 0,
5351.         incl_hero = (do_all && engulfing_u(mon)),
5352.         have_inv = (mon->minvent != 0),
5353.         have_any = (have_inv || incl_hero),
5354.         pickings = (dflags & MINV_PICKMASK);
5355. 
5356.     Sprintf(tmp, "%s %s:", s_suffix(noit_Monnam(mon)),
5357.             do_all ? "possessions" : "armament");
5358. 
5359.     if (do_all ? have_any : (mon->misc_worn_check || MON_WEP(mon))) {
5360.         /* Fool the 'weapon in hand' routine into
5361.          * displaying 'weapon in claw', etc. properly.
5362.          */
5363.         gy.youmonst.data = mon->data;
5364.         /* in case inside a shop, don't append "for sale" prices */
5365.         iflags.suppress_price++;
5366. 
5367.         n = query_objlist(title ? title : tmp, &(mon->minvent),
5368.                           (INVORDER_SORT | (incl_hero ? INCLUDE_HERO : 0)),
5369.                           &selected, pickings,
5370.                           do_all ? allow_all : worn_wield_only);
5371. 
5372.         iflags.suppress_price--;
5373.         /* was 'set_uasmon();' but that potentially has side-effects */
5374.         gy.youmonst.data = &mons[u.umonnum]; /* basic part of set_uasmon() */
5375.     } else {
5376.         invdisp_nothing(title ? title : tmp, "(none)");
5377.         n = 0;
5378.     }
5379. 
5380.     if (n > 0) {
5381.         ret = selected[0].item.a_obj;
5382.         free((genericptr_t) selected);
5383.     } else
5384.         ret = (struct obj *) 0;
5385.     return ret;
5386. }
5387. 
5388. /* format a container name for cinventory_display(), inserting "trapped"
5389.    if that's appropriate */
5390. staticfn char *
5391. cinv_doname(struct obj *obj)
5392. {
5393.     char *result = doname(obj);
5394. 
5395.     /*
5396.      * If obj->tknown ever gets implemented, doname() will handle this.
5397.      * Assumes that probing reveals the trap prior to calling us.  Since
5398.      * we lack that flag, hero forgets about it as soon as we're done....
5399.      */
5400. 
5401.     /* 'result' is an obuf[] but might point into the middle (&buf[PREFIX])
5402.        rather than the beginning and we don't have access to that;
5403.        assume that there is at least QBUFSZ available when reusing it */
5404.     if (obj->otrapped && strlen(result) + sizeof "trapped " <= QBUFSZ) {
5405.         /* obj->lknown has been set before calling us so either "locked" or
5406.            "unlocked" should always be present (for a trapped container) */
5407.         char *p = strstri(result, " locked"),
5408.              *q = strstri(result, " unlocked");
5409. 
5410.         if (p && (!q || p < q))
5411.             (void) strsubst(p, " locked ", " trapped locked ");
5412.         else if (q)
5413.             (void) strsubst(q, " unlocked ", " trapped unlocked ");
5414.         /* might need to change "an" to "a"; when no BUC is present,
5415.            "an unlocked" yielded "an trapped unlocked" above */
5416.         (void) strsubst(result, "an trapped ", "a trapped ");
5417.     }
5418.     return result;
5419. }
5420. 
5421. /* used by safe_qbuf() if the full doname() result is too long */
5422. staticfn char *
5423. cinv_ansimpleoname(struct obj *obj)
5424. {
5425.     char *result = ansimpleoname(obj);
5426. 
5427.     /* result is an obuf[] so we know this will always fit */
5428.     if (obj->otrapped) {
5429.         if (strncmp(result, "a ", 2))
5430.             (void) strsubst(result, "a ", "a trapped ");
5431.         else if (strncmp(result, "an ", 3))
5432.             (void) strsubst(result, "an ", "an trapped ");
5433.         /* unique container? nethack doesn't have any */
5434.         else if (strncmp(result, "the ", 4))
5435.             (void) strsubst(result, "the ", "the trapped ");
5436.         /* no leading article at all? shouldn't happen with ansimpleoname() */
5437.         else
5438.             (void) strsubst(result, "", "trapped "); /* insert at beginning */
5439.     }
5440.     return result;
5441. }
5442. 
5443. /* Display the contents of a container in inventory style.
5444.    Used for wand of probing of non-empty containers and statues. */
5445. struct obj *
5446. display_cinventory(struct obj *obj)
5447. {
5448.     struct obj *ret;
5449.     char qbuf[QBUFSZ];
5450.     int n;
5451.     menu_item *selected = 0;
5452. 
5453.     (void) safe_qbuf(qbuf, "Contents of ", ":", obj,
5454.                      /* custom formatting routines to insert "trapped"
5455.                         into the object's name when appropriate;
5456.                         last resort "that" won't ever get used */
5457.                      cinv_doname, cinv_ansimpleoname, "that");
5458. 
5459.     if (obj->cobj) {
5460.         n = query_objlist(qbuf, &(obj->cobj), INVORDER_SORT,
5461.                           &selected, PICK_NONE, allow_all);
5462.     } else {
5463.         invdisp_nothing(qbuf, "(empty)");
5464.         n = 0;
5465.     }
5466.     if (n > 0) {
5467.         ret = selected[0].item.a_obj;
5468.         free((genericptr_t) selected);
5469.     } else
5470.         ret = (struct obj *) 0;
5471.     obj->cknown = 1;
5472.     return ret;
5473. }
5474. 
5475. 
5476. staticfn boolean
5477. only_here(struct obj *obj)
5478. {
5479.     return (obj->ox == go.only.x && obj->oy == go.only.y);
5480. }
5481. 
5482. /*
5483.  * Display a list of buried or underwater items in inventory style.
5484.  * Return a non-zero value if there were items at that spot.
5485.  *
5486.  * Currently, this is only used with a wand of probing zapped downwards.
5487.  */
5488. int
5489. display_binventory(coordxy x, coordxy y, boolean as_if_seen)
5490. {
5491.     struct obj *obj;
5492.     char qbuf[QBUFSZ];
5493.     const char *underwhat = "here";
5494.     menu_item *selected = 0;
5495.     int n, n2 = 0;
5496. 
5497.     /* if hero is levitating or flying over water or lava, list any items
5498.        below (the map won't be showing them); if hero is underwater, player
5499.        should use the normal look_here command instead of probing (caller
5500.        has already used bhitpile() which will have set dknown on all items) */
5501.     if (is_pool_or_lava(x, y) && !Underwater
5502.         && (obj = svl.level.objects[x][y]) != 0) {
5503.         const char *real_liquid = is_pool(x, y) ? "water" : "lava",
5504.                    *seen_liquid = hliquid(real_liquid);
5505. 
5506.         if (!obj->nexthere) {
5507.             boolean more_than_1 = is_plural(obj);
5508. 
5509.             There("%s %s under the %s here.", more_than_1 ? "are" : "is",
5510.                   doname(obj), seen_liquid);
5511.             n2 = 1;
5512.             /* "pair of boots" is singular but "beneath it" sounds strange */
5513.             if (pair_of(obj))
5514.                 more_than_1 = TRUE;
5515.             underwhat = more_than_1 ? "under them" : "beneath it";
5516.         } else {
5517.             Sprintf(qbuf, "Things that are under the %s here:", seen_liquid);
5518.             if (query_objlist(qbuf, &svl.level.objects[x][y], BY_NEXTHERE,
5519.                               &selected, PICK_NONE, allow_all) > 0)
5520.                 free((genericptr_t) selected), selected = 0;
5521.             for (n2 = 0; obj; obj = obj->nexthere)
5522.                 ++n2;
5523.             underwhat = "beneath them";
5524.         }
5525.     }
5526. 
5527.     /* count # of buried objects here */
5528.     for (n = 0, obj = svl.level.buriedobjlist; obj; obj = obj->nobj)
5529.         if (obj->ox == x && obj->oy == y) {
5530.             if (as_if_seen)
5531.                 observe_object(obj);
5532.             n++;
5533.         }
5534. 
5535.     if (n) {
5536.         go.only.x = x;
5537.         go.only.y = y;
5538.         /* "buried here", but vary if we've already shown underwater items */
5539.         Sprintf(qbuf, "Things that are buried %s:", underwhat);
5540.         if (query_objlist(qbuf, &svl.level.buriedobjlist, INVORDER_SORT,
5541.                           &selected, PICK_NONE, only_here) > 0)
5542.             free((genericptr_t) selected);
5543.         go.only.x = go.only.y = 0;
5544.     }
5545.     return n + n2;
5546. }
5547. 
5548. void
5549. prepare_perminvent(winid window)
5550. {
5551.     win_request_info *wri;
5552.     int invmode = (int) iflags.perminv_mode;
5553. 
5554.     if (perminv_flags != invmode) {
5555.         wri_info = zerowri;
5556.         wri_info.fromcore.invmode = invmode;
5557.         /*  relay the mode settings to the window port */
5558.         wri = ctrl_nhwindow(window, set_mode, &wri_info);
5559.         perminv_flags = invmode;
5560.         nhUse(wri);
5561.     }
5562. }
5563. 
5564. void
5565. sync_perminvent(void)
5566. {
5567.     static win_request_info *wri = 0;
5568.     const char *wport_id;
5569. 
5570.     if (WIN_INVEN == WIN_ERR) {
5571.         if ((gc.core_invent_state
5572.              || (wri_info.tocore.tocore_flags & prohibited))
5573.             && !(in_perm_invent_toggled
5574.                  && gp.perm_invent_toggling_direction == toggling_on))
5575.             return;
5576.     }
5577.     prepare_perminvent(WIN_INVEN);
5578. 
5579.     if ((!iflags.perm_invent && gc.core_invent_state)) {
5580.         /* Odd - but this could be end-of-game disclosure
5581.          * which just sets boolean iflags.perm_invent to
5582.          * FALSE without actually doing anything else.
5583.          */
5584. #ifdef TTY_PERM_INVENT
5585.         if (WINDOWPORT(tty))
5586.             perm_invent_toggled(TRUE); /* TRUE means negated */
5587. #endif
5588.         docrt();
5589.         return;
5590.     }
5591. 
5592.     /*
5593.      * The following conditions can bring us to here:
5594.      * 1. iflags.perm_invent is on
5595.      *      AND
5596.      *    gc.core_invent_state is still zero.
5597.      * OR
5598.      * 2. iflags.perm_invent is off, but we're in the
5599.      *    midst of toggling it on.
5600.      * OR
5601.      * 3. iflags.perminv_mode has been changed via 'm O'.
5602.      */
5603. 
5604.     if ((iflags.perm_invent && !gc.core_invent_state)
5605.         || (!iflags.perm_invent
5606.             && (in_perm_invent_toggled
5607.                 && gp.perm_invent_toggling_direction == toggling_on))) {
5608.         /* Send windowport a request to return the related settings to us */
5609.         if ((iflags.perm_invent && !gc.core_invent_state)
5610.             || in_perm_invent_toggled) {
5611.             wri = ctrl_nhwindow(WIN_INVEN, request_settings, &wri_info);
5612.             if (wri != 0) {
5613.                 if ((wri->tocore.tocore_flags & (too_early)) != 0) {
5614.                     /* don't be too noisy about this as it's really
5615.                      * a startup timing issue. Just set a marker. */
5616.                     iflags.perm_invent_pending = TRUE;
5617.                     return;
5618.                 }
5619.                 if ((wri->tocore.tocore_flags & (too_small | prohibited))
5620.                     != 0) {
5621.                     /* sizes aren't good enough */
5622.                     if ((wri->tocore.tocore_flags & prohibited) != 0) {
5623.                         set_option_mod_status("perm_invent", set_gameview);
5624.                         set_option_mod_status("perminv_mode", set_gameview);
5625.                     }
5626.                     iflags.perm_invent = FALSE;
5627.                     if (WIN_INVEN != WIN_ERR)
5628.                         destroy_nhwindow(WIN_INVEN), WIN_INVEN = WIN_ERR;
5629.                     wport_id = WINDOWPORT(tty) ? "tty perm_invent"
5630.                                                : "perm_invent";
5631.                     pline("%s could not be enabled.", wport_id);
5632.                     pline("%s needs a terminal that is at least %dx%d, yours "
5633.                           "is %dx%d.",
5634.                           wport_id, wri->tocore.needrows,
5635.                           wri->tocore.needcols, wri->tocore.haverows,
5636.                           wri->tocore.havecols);
5637.                     wait_synch();
5638.                     return;
5639.                 }
5640.             }
5641.             gc.core_invent_state++;
5642.         }
5643.     }
5644. 
5645.     if (!wri || wri->tocore.maxslot == 0)
5646.         return;
5647. 
5648.     if (in_perm_invent_toggled
5649.         && gp.perm_invent_toggling_direction == toggling_on) {
5650.         WIN_INVEN = create_nhwindow(NHW_MENU);
5651.     }
5652. 
5653.     if (WIN_INVEN != WIN_ERR && program_state.beyond_savefile_load) {
5654.         gi.in_sync_perminvent = 1;
5655.         (void) display_inventory((char *) 0, FALSE);
5656.         gi.in_sync_perminvent = 0;
5657.     }
5658. }
5659. 
5660. void
5661. perm_invent_toggled(boolean negated)
5662. {
5663.     in_perm_invent_toggled = TRUE;
5664.     if (negated) {
5665.         gp.perm_invent_toggling_direction = toggling_off;
5666.         if (WIN_INVEN != WIN_ERR)
5667.             destroy_nhwindow(WIN_INVEN), WIN_INVEN = WIN_ERR;
5668.         gc.core_invent_state = 0;
5669.     } else {
5670.         gp.perm_invent_toggling_direction = toggling_on;
5671.         if (iflags.perminv_mode == InvOptNone)
5672.             iflags.perminv_mode = InvOptOn; /* all inventory except gold */
5673.         sync_perminvent();
5674.     }
5675.     gp.perm_invent_toggling_direction = toggling_not;
5676.     in_perm_invent_toggled = FALSE;
5677. }
5678. 
5679. /*invent.c*/