Source:NetHack 5.0.0/src/shk.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to shk.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/shk.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	shk.c	$NHDT-Date: 1736516428 2025/01/10 05:40:28 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.306 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2012. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. /*
9.  * FIXME:
10.  *  The normal shop messages are verbal.  There are a lot of cases
11.  *  where an alternate message is given if the hero is deaf or shk
12.  *  is mute (when poly'd), but that is usually visual-based.  It is
13.  *  possible for hero to pay for items while blind (only if adjacent
14.  *  to shk) and the alternate messages fail to account for that.
15.  */
16. 
17. #define PAY_BUY 1
18. #define PAY_CANT 0 /* too poor */
19. #define PAY_SKIP (-1)
20. #define PAY_BROKE (-2)
21. 
22. enum billitem_status {
23.     FullyUsedUp   = 1, /* completely used up; obj->where==OBJ_ONBILL */
24.     PartlyUsedUp  = 2, /* partly used up; obj->where==OBJ_INVENT or similar */
25.     PartlyIntact  = 3, /* intact portion of partly used up item */
26.     FullyIntact   = 4, /* normal unpaid item */
27.     KnownContainer = 5, /* container->cknown==1, holding unpaid item(s) */
28.     UndisclosedContainer = 6, /* container->cknown==0 */
29. };
30. /* this is similar to sortloot; the shop bill gets converted into an array of
31.    struct sortbill_item so that sorting and traversal don't need to access
32.    the original bill or even the shk; the array gets sorted by usedup vs
33.    unpaid and by cost within each of those two categories */
34. struct sortbill_item {
35.     struct obj *obj;
36.     long cost;   /* full amount for current quantity, not per-unit amount */
37.     long quan;   /* count for this entry; subset if this is partly used or
38.                   * partly intact */
39.     int bidx;    /* index into ESHK(shkp)->bill_p[]; hero-owned container,
40.                   * which isn't in bill_p[], uses bidx == -1 */
41.     int8 usedup; /* billitem_status, small but needs to be signed for qsort()
42.                   * [for an earlier edition; 'signed' no longer necessary] */
43.     boolean queuedpay; /* buy without asking when containers are involved
44.                         * or purchase targets have been picked via menu */
45. };
46. typedef struct sortbill_item Bill;
47. 
48. staticfn void makekops(coord *);
49. staticfn void getcad(struct monst *, const char *, coordxy, coordxy, boolean,
50.                      boolean, boolean);
51. staticfn void call_kops(struct monst *, boolean);
52. staticfn void kops_gone(boolean);
53. 
54. #define NOTANGRY(mon) ((mon)->mpeaceful)
55. #define ANGRY(mon) (!NOTANGRY(mon))
56. #define IS_SHOP(x) (svr.rooms[x].rtype >= SHOPBASE)
57. 
58. #define muteshk(shkp) (helpless(shkp) || (shkp)->data->msound <= MS_ANIMAL)
59. 
60. extern const struct shclass shtypes[]; /* defined in shknam.c */
61. 
62. static const char and_its_contents[] = " and its contents";
63. static const char the_contents_of[] = "the contents of ";
64. 
65. staticfn void append_honorific(char *);
66. staticfn long addupbill(struct monst *);
67. staticfn void pacify_shk(struct monst *, boolean);
68. staticfn struct bill_x *onbill(struct obj *, struct monst *, boolean);
69. staticfn struct monst *next_shkp(struct monst *, boolean);
70. staticfn long shop_debt(struct eshk *);
71. staticfn char *shk_owns(char *, struct obj *);
72. staticfn char *mon_owns(char *, struct obj *);
73. staticfn void clear_unpaid_obj(struct monst *, struct obj *);
74. staticfn void clear_unpaid(struct monst *, struct obj *);
75. staticfn void clear_no_charge_obj(struct monst *, struct obj *);
76. staticfn void clear_no_charge(struct monst *, struct obj *);
77. staticfn void clear_no_charge_pets(struct monst *);
78. staticfn long check_credit(long, struct monst *);
79. staticfn void pay(long, struct monst *);
80. staticfn long get_cost(struct obj *, struct monst *);
81. staticfn long set_cost(struct obj *, struct monst *);
82. staticfn const char *shk_embellish(struct obj *, long);
83. staticfn long cost_per_charge(struct monst *, struct obj *, boolean);
84. 
85. staticfn int QSORTCALLBACK sortbill_cmp(const genericptr, const genericptr)
86.                                                                   NONNULLPTRS;
87. staticfn long cheapest_item(int, Bill *) NONNULLPTRS;
88. staticfn int make_itemized_bill(struct monst *shkp, Bill **ibill) NONNULLPTRS;
89. staticfn int menu_pick_pay_items(int, Bill *) NONNULLPTRS;
90. staticfn boolean pay_billed_items(struct monst *, int, Bill *, boolean,
91.                                   boolean *) NONNULLPTRS;
92. staticfn void update_bill(int, int, Bill *, struct eshk *, struct bill_x *,
93.                           struct obj *) NONNULLPTRS;
94. staticfn int dopayobj(struct monst *, struct bill_x *, struct obj *, int,
95.                       boolean, boolean) NONNULLPTRS;
96. staticfn int buy_container(struct monst *, int, int, Bill *) NONNULLPTRS;
97. staticfn void reject_purchase(struct monst *, struct obj *, long) NONNULLPTRS;
98. staticfn boolean insufficient_funds(struct monst *, struct obj *, long)
99.                                                                   NONNULLPTRS;
100. staticfn long stolen_container(struct obj *, struct monst *, long, boolean);
101. staticfn long corpsenm_price_adj(struct obj *);
102. staticfn long getprice(struct obj *, boolean);
103. staticfn void shk_names_obj(struct monst *, struct obj *, const char *, long,
104.                           const char *);
105. staticfn boolean inherits(struct monst *, int, int, boolean);
106. staticfn void set_repo_loc(struct monst *);
107. staticfn struct obj *bp_to_obj(struct bill_x *);
108. staticfn long get_pricing_units(struct obj *);
109. staticfn boolean angry_shk_exists(void);
110. staticfn void home_shk(struct monst *, boolean);
111. staticfn void rile_shk(struct monst *);
112. staticfn void rouse_shk(struct monst *, boolean);
113. staticfn boolean shk_impaired(struct monst *);
114. staticfn boolean repairable_damage(struct damage *, struct monst *);
115. staticfn struct damage *find_damage(struct monst *);
116. staticfn void discard_damage_struct(struct damage *);
117. staticfn void discard_damage_owned_by(struct monst *);
118. staticfn void shk_fixes_damage(struct monst *);
119. staticfn uint8 litter_getpos(uint8 *, coordxy, coordxy, struct monst *);
120. staticfn void litter_scatter(uint8 *, coordxy, coordxy, struct monst *);
121. staticfn void litter_newsyms(uint8 *, coordxy, coordxy);
122. staticfn int repair_damage(struct monst *, struct damage *, boolean);
123. staticfn void sub_one_frombill(struct obj *, struct monst *) NONNULLPTRS;
124. staticfn void add_one_tobill(struct obj *, boolean, struct monst *);
125. staticfn void dropped_container(struct obj *, struct monst *, boolean);
126. staticfn void add_to_billobjs(struct obj *);
127. staticfn void bill_box_content(struct obj *, boolean, boolean,
128.                              struct monst *);
129. staticfn boolean rob_shop(struct monst *);
130. staticfn void deserted_shop(char *);
131. staticfn boolean special_stock(struct obj *, struct monst *, boolean);
132. staticfn const char *cad(boolean);
133. 
134. /*
135.         invariants: obj->unpaid iff onbill(obj) [unless bp->useup]
136.                     obj->quan <= bp->bquan
137.  */
138. 
139. static const char *const angrytexts[] = {
140.     "quite upset", "ticked off", "furious"
141. };
142. 
143. /*
144.  *  Transfer money from inventory to monster when paying
145.  *  shopkeepers, priests, oracle, succubus, and other demons.
146.  *  Simple with only gold coins.
147.  *  This routine will handle money changing when multiple
148.  *  coin types is implemented, only appropriate
149.  *  monsters will pay change.  (Peaceful shopkeepers, priests
150.  *  and the oracle try to maintain goodwill while selling
151.  *  their wares or services.  Angry monsters and all demons
152.  *  will keep anything they get their hands on.
153.  *  Returns the amount actually paid, so we can know
154.  *  if the monster kept the change.
155.  */
156. long
157. money2mon(struct monst *mon, long amount)
158. {
159.     struct obj *ygold = findgold(gi.invent);
160. 
161.     if (amount <= 0) {
162.         impossible("%s payment in money2mon!", amount ? "negative" : "zero");
163.         return 0L;
164.     }
165.     if (!ygold || ygold->quan < amount) {
166.         impossible("Paying without %s gold?", ygold ? "enough" : "");
167.         return 0L;
168.     }
169. 
170.     if (ygold->quan > amount)
171.         ygold = splitobj(ygold, amount);
172.     else if (ygold->owornmask)
173.         remove_worn_item(ygold, FALSE); /* quiver */
174.     freeinv(ygold);
175.     add_to_minv(mon, ygold);
176.     disp.botl = TRUE;
177.     return amount;
178. }
179. 
180. /*
181.  *  Transfer money from monster to inventory.
182.  *  Used when the shopkeeper pay for items, and when
183.  *  the priest gives you money for an ale.
184.  */
185. void
186. money2u(struct monst *mon, long amount)
187. {
188.     struct obj *mongold = findgold(mon->minvent);
189. 
190.     if (amount <= 0) {
191.         impossible("%s payment in money2u!", amount ? "negative" : "zero");
192.         return;
193.     }
194.     if (!mongold || mongold->quan < amount) {
195.         impossible("%s paying without %s gold?", a_monnam(mon),
196.                    mongold ? "enough" : "");
197.         return;
198.     }
199. 
200.     if (mongold->quan > amount)
201.         mongold = splitobj(mongold, amount);
202.     obj_extract_self(mongold);
203. 
204.     if (!merge_choice(gi.invent, mongold)
205.             && inv_cnt(FALSE) >= invlet_basic) {
206.         You("have no room for the gold!");
207.         dropy(mongold);
208.     } else {
209.         addinv(mongold);
210.         disp.botl = TRUE;
211.     }
212. }
213. 
214. staticfn struct monst *
215. next_shkp(struct monst *shkp, boolean withbill)
216. {
217.     for (; shkp; shkp = shkp->nmon) {
218.         if (DEADMONSTER(shkp))
219.             continue;
220.         if (shkp->isshk && (ESHK(shkp)->billct || !withbill))
221.             break;
222.     }
223. 
224.     if (shkp) {
225.         if (ANGRY(shkp)) {
226.             if (!ESHK(shkp)->surcharge)
227.                 rile_shk(shkp);
228.         }
229.     }
230.     return shkp;
231. }
232. 
233. /* called in mon.c */
234. void
235. shkgone(struct monst *mtmp)
236. {
237.     struct eshk *eshk = ESHK(mtmp);
238.     struct mkroom *sroom = &svr.rooms[eshk->shoproom - ROOMOFFSET];
239.     struct obj *otmp;
240.     char *p;
241.     int sx, sy;
242. 
243.     /* [BUG: some of this should be done on the shop level */
244.     /*       even when the shk dies on a different level.] */
245.     if (on_level(&eshk->shoplevel, &u.uz)) {
246.         discard_damage_owned_by(mtmp);
247.         sroom->resident = (struct monst *) 0;
248.         if (!search_special(ANY_SHOP))
249.             svl.level.flags.has_shop = 0;
250. 
251.         /* items on shop floor revert to ordinary objects */
252.         for (sx = sroom->lx; sx <= sroom->hx; sx++)
253.             for (sy = sroom->ly; sy <= sroom->hy; sy++)
254.                 for (otmp = svl.level.objects[sx][sy]; otmp;
255.                      otmp = otmp->nexthere)
256.                     otmp->no_charge = 0;
257. 
258.         /* Make sure bill is set only when the
259.            dead shk is the resident shk. */
260.         if ((p = strchr(u.ushops, eshk->shoproom)) != 0) {
261.             setpaid(mtmp);
262.             eshk->bill_p = (struct bill_x *) 0;
263.             /* remove eshk->shoproom from u.ushops */
264.             do {
265.                 *p = *(p + 1);
266.             } while (*++p);
267.         }
268.     }
269. }
270. 
271. void
272. set_residency(struct monst *shkp, boolean zero_out)
273. {
274.     if (on_level(&(ESHK(shkp)->shoplevel), &u.uz))
275.         svr.rooms[ESHK(shkp)->shoproom - ROOMOFFSET].resident =
276.             (zero_out) ? (struct monst *) 0 : shkp;
277. }
278. 
279. void
280. replshk(struct monst *mtmp, struct monst *mtmp2)
281. {
282.     svr.rooms[ESHK(mtmp2)->shoproom - ROOMOFFSET].resident = mtmp2;
283.     if (inhishop(mtmp) && *u.ushops == ESHK(mtmp)->shoproom) {
284.         ESHK(mtmp2)->bill_p = &(ESHK(mtmp2)->bill[0]);
285.     }
286. }
287. 
288. /* do shopkeeper specific structure munging -dlc */
289. void
290. restshk(struct monst *shkp, boolean ghostly)
291. {
292.     if (u.uz.dlevel) {
293.         struct eshk *eshkp = ESHK(shkp);
294. 
295.         if (eshkp->bill_p != (struct bill_x *) -1000)
296.             eshkp->bill_p = &eshkp->bill[0];
297.         /* shoplevel can change as dungeons move around */
298.         /* savebones guarantees that non-homed shk's will be gone */
299.         if (ghostly) {
300.             assign_level(&eshkp->shoplevel, &u.uz);
301.             if (ANGRY(shkp) && strncmpi(eshkp->customer, svp.plname, PL_NSIZ))
302.                 pacify_shk(shkp, TRUE);
303.         }
304.     }
305. }
306. 
307. /* clear the unpaid bit on a single object and its contents */
308. staticfn void
309. clear_unpaid_obj(struct monst *shkp, struct obj *otmp)
310. {
311.     if (Has_contents(otmp))
312.         clear_unpaid(shkp, otmp->cobj);
313.     if (onbill(otmp, shkp, TRUE))
314.         otmp->unpaid = 0;
315. }
316. 
317. /* clear the unpaid bit on all of the objects in the list */
318. staticfn void
319. clear_unpaid(struct monst *shkp, struct obj *list)
320. {
321.     while (list) {
322.         clear_unpaid_obj(shkp, list);
323.         list = list->nobj;
324.     }
325. }
326. 
327. /* clear the no_charge bit on a single object and its contents */
328. staticfn void
329. clear_no_charge_obj(
330.     struct monst *shkp, /* if null, clear regardless of shop */
331.     struct obj *otmp)
332. {
333.     if (Has_contents(otmp))
334.         clear_no_charge(shkp, otmp->cobj);
335.     if (otmp->no_charge) {
336.         struct monst *rm_shkp;
337.         int rno;
338.         coordxy x, y;
339. 
340.         /*
341.          * Clear no_charge if
342.          *  shkp is Null (clear all items on specified list)
343.          *  or not located somewhere that we expect no_charge (which is
344.          *    floor [of shop] or inside container [on shop floor])
345.          *  or can't find object's map coordinates (should never happen
346.          *    for floor or contained; conceivable if on shop bill somehow
347.          *    but would have failed the floor-or-contained test since
348.          *    containers get emptied before going onto bill)
349.          *  or fails location sanity check (should always be good when
350.          *    location successfully found)
351.          *  or not inside any room
352.          *  or the room isn't a shop
353.          *  or the shop has no shopkeeper (deserted)
354.          *  or shopkeeper is the current one (to avoid clearing no_charge
355.          *    for items located in some rival's shop).
356.          *
357.          * no_charge items in a shop which is only temporarily deserted
358.          * become owned by the shop now and will be for-sale once the shk
359.          * returns.
360.          */
361.         if (!shkp
362.             || (otmp->where != OBJ_FLOOR
363.                 && otmp->where != OBJ_CONTAINED
364.                 && otmp->where != OBJ_BURIED)
365.             || !get_obj_location(otmp, &x, &y, OBJ_CONTAINED | OBJ_BURIED)
366.             || !isok(x, y)
367.             || (rno = levl[x][y].roomno) < ROOMOFFSET
368.             || !IS_SHOP(rno - ROOMOFFSET)
369.             || (rm_shkp = svr.rooms[rno - ROOMOFFSET].resident) == 0
370.             || rm_shkp == shkp)
371.             otmp->no_charge = 0;
372.     }
373. }
374. 
375. /* clear the no_charge bit on all of the objects in the list */
376. staticfn void
377. clear_no_charge(struct monst *shkp, struct obj *list)
378. {
379.     while (list) {
380.         /* handle first element of list and any contents it may have */
381.         clear_no_charge_obj(shkp, list);
382.         /* move on to next element of list */
383.         list = list->nobj;
384.     }
385. }
386. 
387. /* clear no_charge from objects in pets' inventories belonging to shkp */
388. staticfn void
389. clear_no_charge_pets(struct monst *shkp)
390. {
391.     struct monst *mtmp;
392. 
393.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
394.         if (mtmp->mtame && mtmp->minvent)
395.             clear_no_charge(shkp, mtmp->minvent);
396. }
397. 
398. /* either you paid or left the shop or the shopkeeper died */
399. void
400. setpaid(struct monst *shkp)
401. {
402.     struct obj *obj;
403.     struct monst *mtmp;
404. 
405.     clear_unpaid(shkp, gi.invent);
406.     clear_unpaid(shkp, fobj);
407.     if (svl.level.buriedobjlist)
408.         clear_unpaid(shkp, svl.level.buriedobjlist);
409.     if (gt.thrownobj)
410.         clear_unpaid_obj(shkp, gt.thrownobj);
411.     if (gk.kickedobj)
412.         clear_unpaid_obj(shkp, gk.kickedobj);
413.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
414.         if (mtmp->minvent)
415.             clear_unpaid(shkp, mtmp->minvent);
416.     for (mtmp = gm.migrating_mons; mtmp; mtmp = mtmp->nmon)
417.         if (mtmp->minvent)
418.             clear_unpaid(shkp, mtmp->minvent);
419. 
420.     /* clear obj->no_charge for all obj in shkp's shop */
421.     clear_no_charge(shkp, fobj);
422.     clear_no_charge(shkp, svl.level.buriedobjlist);
423. 
424.     while ((obj = gb.billobjs) != 0) {
425.         obj_extract_self(obj);
426.         dealloc_obj(obj);
427.     }
428.     if (shkp) {
429.         ESHK(shkp)->billct = 0;
430.         ESHK(shkp)->credit = 0L;
431.         ESHK(shkp)->debit = 0L;
432.         ESHK(shkp)->loan = 0L;
433.     }
434. }
435. 
436. /* Remembers that a shopkeeper has quoted a particular price for a
437.    particular type of object. */
438. void
439. record_price_quote(int otyp, unsigned long price, boolean buyprice) {
440.     struct objclass *oc = &objects[otyp];
441.     if (buyprice) {
442.         if (price > oc->oc_buy_maxseen) oc->oc_buy_maxseen = price;
443.         if (price < oc->oc_buy_minseen) oc->oc_buy_minseen = price;
444.     } else {
445.         if (price > oc->oc_sell_maxseen) oc->oc_sell_maxseen = price;
446.         if (price < oc->oc_sell_minseen) oc->oc_sell_minseen = price;
447.     }
448. }
449. 
450. /* Appends price-quote information to the given buffer, updating the
451.    given end of string position. *eos mut be buf + strlen(buf). If the
452.    update would make bug longer than BUFSZ, instead does nothing. */
453. void
454. append_price_quote(char *buf, char **eos, int otyp) {
455.     char buf2[BUFSZ];
456.     char *eos2 = buf2;
457.     const char *sep = "";
458.     size_t len = *eos - buf;
459.     size_t len2;
460. 
461.     if (objects[otyp].oc_sell_minseen > objects[otyp].oc_sell_maxseen &&
462.         objects[otyp].oc_buy_minseen > objects[otyp].oc_buy_maxseen)
463.         return;
464. 
465.     eos2 += sprintf(eos2, " {");
466. 
467.     if (objects[otyp].oc_buy_minseen < objects[otyp].oc_buy_maxseen) {
468.         eos2 += sprintf(eos2, "buy %lu-%lu",
469.                         objects[otyp].oc_buy_minseen,
470.                         objects[otyp].oc_buy_maxseen);
471.         sep = " ";
472.     } else if (objects[otyp].oc_buy_minseen == objects[otyp].oc_buy_maxseen) {
473.         eos2 += sprintf(eos2, "buy %lu",
474.                         objects[otyp].oc_buy_minseen);
475.         sep = " ";
476.     }
477. 
478.     if (objects[otyp].oc_sell_minseen < objects[otyp].oc_sell_maxseen) {
479.         eos2 += sprintf(eos2, "%ssell %lu-%lu", sep,
480.                         objects[otyp].oc_sell_minseen,
481.                         objects[otyp].oc_sell_maxseen);
482.     } else if (objects[otyp].oc_sell_minseen == objects[otyp].oc_sell_maxseen) {
483.         eos2 += sprintf(eos2, "%ssell %lu", sep,
484.                         objects[otyp].oc_sell_minseen);
485.     }
486. 
487.     eos2 += sprintf(eos2, "}");
488.     len2 = eos2 - buf2;
489.     if (len2 < BUFSZ - len - 1) {
490.         Strcpy(*eos, buf2);
491.         *eos += len2;
492.     }
493. }
494. 
495. staticfn long
496. addupbill(struct monst *shkp)
497. {
498.     int ct = ESHK(shkp)->billct;
499.     struct bill_x *bp = ESHK(shkp)->bill_p;
500.     long total = 0L;
501. 
502.     while (ct--) {
503.         total += bp->price * bp->bquan;
504.         bp++;
505.     }
506.     return total;
507. }
508. 
509. staticfn void
510. call_kops(struct monst *shkp, boolean nearshop)
511. {
512.     /* Keystone Kops srt@ucla */
513.     boolean nokops;
514. 
515.     if (!shkp)
516.         return;
517. 
518.     Soundeffect(se_alarm, 80);
519.     if (!Deaf)
520.         pline("An alarm sounds!");
521. 
522.     nokops = ((svm.mvitals[PM_KEYSTONE_KOP].mvflags & G_GONE)
523.               && (svm.mvitals[PM_KOP_SERGEANT].mvflags & G_GONE)
524.               && (svm.mvitals[PM_KOP_LIEUTENANT].mvflags & G_GONE)
525.               && (svm.mvitals[PM_KOP_KAPTAIN].mvflags & G_GONE));
526. 
527.     if (!angry_guards(!!Deaf) && nokops) {
528.         if (flags.verbose && !Deaf)
529.             pline("But no one seems to respond to it.");
530.         return;
531.     }
532. 
533.     if (nokops)
534.         return;
535. 
536.     {
537.         coord mm;
538.         coordxy sx = 0, sy = 0;
539. 
540.         choose_stairs(&sx, &sy, TRUE);
541. 
542.         if (nearshop) {
543.             /* Create swarm around you, if you merely "stepped out" */
544.             if (flags.verbose)
545.                 pline_The("Keystone Kops appear!");
546.             mm.x = u.ux;
547.             mm.y = u.uy;
548.             makekops(&mm);
549.             return;
550.         }
551.         if (flags.verbose)
552.             pline_The("Keystone Kops are after you!");
553.         /* Create swarm near down staircase (hinders return to level) */
554.         if (isok(sx, sy)) {
555.             mm.x = sx;
556.             mm.y = sy;
557.             makekops(&mm);
558.         }
559.         /* Create swarm near shopkeeper (hinders return to shop) */
560.         mm.x = shkp->mx;
561.         mm.y = shkp->my;
562.         makekops(&mm);
563.     }
564. }
565. 
566. /* x,y is strictly inside shop */
567. char
568. inside_shop(coordxy x, coordxy y)
569. {
570.     char rno;
571. 
572.     rno = levl[x][y].roomno;
573.     if ((rno < ROOMOFFSET) || levl[x][y].edge || !IS_SHOP(rno - ROOMOFFSET))
574.         rno = NO_ROOM;
575.     return rno;
576. }
577. 
578. void
579. u_left_shop(char *leavestring, boolean newlev)
580. {
581.     struct monst *shkp;
582.     struct eshk *eshkp;
583. 
584.     /*
585.      * IF player
586.      * ((didn't leave outright) AND
587.      *  ((he is now strictly-inside the shop) OR
588.      *   (he wasn't strictly-inside last turn anyway)))
589.      * THEN (there's nothing to do, so just return)
590.      */
591.     if (!*leavestring && (!levl[u.ux][u.uy].edge || levl[u.ux0][u.uy0].edge))
592.         return;
593. 
594.     shkp = shop_keeper(*leavestring ? *leavestring : *u.ushops0);
595.     if (!shkp || !inhishop(shkp))
596.         return; /* shk died, teleported, changed levels... */
597. 
598.     eshkp = ESHK(shkp);
599.     if (!eshkp->billct && !eshkp->debit) /* bill is settled */
600.         return;
601. 
602.     if (!*leavestring && !muteshk(shkp)) {
603.         /*
604.          * Player just stepped onto shop-boundary (known from above logic).
605.          * Try to intimidate him into paying his bill
606.          */
607.         boolean not_upset = !eshkp->surcharge;
608.         if (!Deaf && !muteshk(shkp)) {
609.             SetVoice(shkp, 0, 80, 0);
610.             verbalize(not_upset ? "%s!  Please pay before leaving."
611.                                 : "%s!  Don't you leave without paying!",
612.                       svp.plname);
613.         } else {
614.             pline("%s %s that you need to pay before leaving%s",
615.                   Shknam(shkp),
616.                   not_upset ? "points out" : "makes it clear",
617.                   not_upset ? "." : "!");
618.         }
619.         return;
620.     }
621. 
622.     if (rob_shop(shkp)) {
623.         call_kops(shkp, (!newlev && levl[u.ux0][u.uy0].edge));
624.     }
625. }
626. 
627. void
628. credit_report(struct monst *shkp, int idx, boolean silent)
629. {
630.     struct eshk *eshkp = ESHK(shkp);
631.     static long credit_snap[2][3] = {{0L, 0L, 0L}, {0L, 0L, 0L}};
632. 
633.     if (!idx) {
634.         credit_snap[BEFORE][0] = credit_snap[NOW][0] = 0L;
635.         credit_snap[BEFORE][1] = credit_snap[NOW][1] = 0L;
636.         credit_snap[BEFORE][2] = credit_snap[NOW][2] = 0L;
637.     } else {
638.         idx = 1;
639.     }
640. 
641.     credit_snap[idx][0] = eshkp->credit;
642.     credit_snap[idx][1] = eshkp->debit;
643.     credit_snap[idx][2] = eshkp->loan;
644. 
645.     if (idx && !silent) {
646.         long amt = 0L;
647.         const char *msg = "debt has increased";
648. 
649.         if (credit_snap[NOW][0] < credit_snap[BEFORE][0]) {
650.             amt = credit_snap[BEFORE][0] - credit_snap[NOW][0];
651.             msg = "credit has been reduced";
652.         } else if (credit_snap[NOW][1] > credit_snap[BEFORE][1]) {
653.             amt = credit_snap[NOW][1] - credit_snap[BEFORE][1];
654.         } else if (credit_snap[NOW][2] > credit_snap[BEFORE][2]) {
655.             amt = credit_snap[NOW][2] - credit_snap[BEFORE][2];
656.         }
657.         if (amt)
658.             Your("%s by %ld %s.", msg, amt, currency(amt));
659. 
660.     }
661. }
662. 
663. /* robbery from outside the shop via telekinesis or grappling hook */
664. void
665. remote_burglary(coordxy x, coordxy y)
666. {
667.     struct monst *shkp;
668.     struct eshk *eshkp;
669. 
670.     shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
671.     if (!shkp || !inhishop(shkp))
672.         return; /* shk died, teleported, changed levels... */
673. 
674.     eshkp = ESHK(shkp);
675.     if (!eshkp->billct && !eshkp->debit) /* bill is settled */
676.         return;
677. 
678.     if (rob_shop(shkp)) {
679.         /*[might want to set 2nd arg based on distance from shop doorway]*/
680.         call_kops(shkp, FALSE);
681.     }
682. }
683. 
684. /* shop merchandise has been taken; pay for it with any credit available;
685.    return false if the debt is fully covered by credit, true otherwise */
686. staticfn boolean
687. rob_shop(struct monst *shkp)
688. {
689.     struct eshk *eshkp;
690.     long total;
691. 
692.     eshkp = ESHK(shkp);
693.     rouse_shk(shkp, TRUE);
694.     total = (addupbill(shkp) + eshkp->debit);
695.     if (eshkp->credit >= total) {
696.         Your("credit of %ld %s is used to cover your shopping bill.",
697.              eshkp->credit, currency(eshkp->credit));
698.         total = 0L; /* credit gets cleared by setpaid() */
699.     } else {
700.         You("escaped the shop without paying!");
701.         total -= eshkp->credit;
702.     }
703.     setpaid(shkp);
704.     if (!total)
705.         return FALSE;
706. 
707.     /* by this point, we know an actual robbery has taken place */
708.     eshkp->robbed += total;
709.     You("stole %ld %s worth of merchandise.", total, currency(total));
710.     livelog_printf(LL_ACHIEVE, "stole %ld %s worth of merchandise from %s %s",
711.                    total, currency(total), s_suffix(shkname(shkp)),
712.                    shtypes[eshkp->shoptype - SHOPBASE].name);
713. 
714.     if (!Role_if(PM_ROGUE)) /* stealing is unlawful */
715.         adjalign(-sgn(u.ualign.type));
716. 
717.     hot_pursuit(shkp);
718.     return TRUE;
719. }
720. 
721. /* give a message when entering an untended shop (caller has verified that) */
722. staticfn void
723. deserted_shop(/*const*/ char *enterstring)
724. {
725.     struct monst *mtmp;
726.     struct mkroom *r = &svr.rooms[(int) *enterstring - ROOMOFFSET];
727.     int x, y, m = 0, n = 0;
728. 
729.     for (x = r->lx; x <= r->hx; ++x)
730.         for (y = r->ly; y <= r->hy; ++y) {
731.             if (u_at(x, y))
732.                 continue;
733.             if ((mtmp = m_at(x, y)) != 0) {
734.                 ++n;
735.                 if (sensemon(mtmp) || ((M_AP_TYPE(mtmp) == M_AP_NOTHING
736.                                         || M_AP_TYPE(mtmp) == M_AP_MONSTER)
737.                                        && canseemon(mtmp)))
738.                     ++m;
739.             }
740.         }
741. 
742.     if (Blind && !(Blind_telepat || Detect_monsters))
743.         ++n; /* force feedback to be less specific */
744. 
745.     pline("This shop %s %s.", (m < n) ? "seems to be" : "is",
746.           !n ? "deserted" : "untended");
747. }
748. 
749. /* called from check_special_room(hack.c) */
750. void
751. u_entered_shop(char *enterstring)
752. {
753.     static char empty_shops[5];
754.     struct monst *shkp;
755.     struct eshk *eshkp;
756.     int rt;
757. 
758.     if (!*enterstring)
759.         return;
760. 
761.     shkp = shop_keeper(*enterstring);
762.     if (!shkp) {
763.         if (!strchr(empty_shops, *enterstring)
764.             && (in_rooms(u.ux, u.uy, SHOPBASE)
765.                 != in_rooms(u.ux0, u.uy0, SHOPBASE)))
766.             deserted_shop(enterstring);
767.         Strcpy(empty_shops, u.ushops);
768.         u.ushops[0] = '\0';
769.         return;
770.     }
771. 
772.     eshkp = ESHK(shkp);
773. 
774.     if (!inhishop(shkp)) {
775.         /* dump core when referenced */
776.         eshkp->bill_p = (struct bill_x *) -1000;
777.         if (!strchr(empty_shops, *enterstring))
778.             deserted_shop(enterstring);
779.         Strcpy(empty_shops, u.ushops);
780.         u.ushops[0] = '\0';
781.         return;
782.     }
783.     record_achievement(ACH_SHOP);
784. 
785.     eshkp->bill_p = &(eshkp->bill[0]);
786. 
787.     if ((!eshkp->visitct || *eshkp->customer)
788.         && strncmpi(eshkp->customer, svp.plname, PL_NSIZ)) {
789.         /* You seem to be new here */
790.         eshkp->visitct = 0;
791.         eshkp->following = 0;
792.         (void) strncpy(eshkp->customer, svp.plname, PL_NSIZ);
793.         pacify_shk(shkp, TRUE);
794.     }
795. 
796.     if (muteshk(shkp) || eshkp->following)
797.         return; /* no dialog */
798. 
799.     if (Invis) {
800.         pline("%s senses your presence.", Shknam(shkp));
801.         if (!Deaf && !muteshk(shkp)) {
802.             SetVoice(shkp, 0, 80, 0);
803.             verbalize("Invisible customers are not welcome!");
804.         } else {
805.             pline("%s stands firm as if %s knows you are there.",
806.                   Shknam(shkp), noit_mhe(shkp));
807.         }
808.         return;
809.     }
810. 
811.     rt = svr.rooms[*enterstring - ROOMOFFSET].rtype;
812. 
813.     if (ANGRY(shkp)) {
814.         if (!Deaf && !muteshk(shkp)) {
815.             SetVoice(shkp, 0, 80, 0);
816.             verbalize("So, %s, you dare return to %s %s?!", svp.plname,
817.                       s_suffix(shkname(shkp)), shtypes[rt - SHOPBASE].name);
818.         } else {
819.             pline("%s seems %s over your return to %s %s!",
820.                   Shknam(shkp), ROLL_FROM(angrytexts),
821.                   noit_mhis(shkp), shtypes[rt - SHOPBASE].name);
822.         }
823.     } else if (eshkp->surcharge) {
824.         if (!Deaf && !muteshk(shkp)) {
825.             SetVoice(shkp, 0, 80, 0);
826.             verbalize("Back again, %s?  I've got my %s on you.",
827.                       svp.plname, mbodypart(shkp, EYE));
828.         } else {
829.             pline_The("atmosphere at %s %s seems unwelcoming.",
830.                       s_suffix(shkname(shkp)), shtypes[rt - SHOPBASE].name);
831.         }
832.     } else if (eshkp->robbed) {
833.         if (!Deaf) {
834.             Soundeffect(se_mutter_imprecations, 50);
835.             pline("%s mutters imprecations against shoplifters.",
836.                   Shknam(shkp));
837.         } else {
838.             pline("%s is combing through %s inventory list.",
839.                   Shknam(shkp), noit_mhis(shkp));
840.         }
841.     } else {
842.         if (!Deaf && !muteshk(shkp)) {
843.             set_voice(shkp, 0, 80, 0);
844.             verbalize("%s, %s!  Welcome%s to %s %s!", Hello(shkp), svp.plname,
845.                       eshkp->visitct++ ? " again" : "",
846.                       s_suffix(shkname(shkp)), shtypes[rt - SHOPBASE].name);
847.         } else {
848.             You("enter %s %s%s!",
849.                 s_suffix(shkname(shkp)),
850.                 shtypes[rt - SHOPBASE].name,
851.                 eshkp->visitct++ ? " again" : "");
852.         }
853.     }
854.     /* can't do anything about blocking if teleported in */
855.     if (!inside_shop(u.ux, u.uy)) {
856.         boolean should_block, not_upset = !eshkp->surcharge;
857.         int cnt;
858.         const char *tool;
859.         struct obj *pick = carrying(PICK_AXE),
860.                    *mattock = carrying(DWARVISH_MATTOCK);
861. 
862.         if (pick || mattock) {
863.             cnt = 1;               /* so far */
864.             if (pick && mattock) { /* carrying both types */
865.                 tool = "digging tool";
866.                 cnt = 2; /* `more than 1' is all that matters */
867.             } else if (pick) {
868.                 tool = "pick-axe";
869.                 /* hack: `pick' already points somewhere into inventory */
870.                 while ((pick = pick->nobj) != 0)
871.                     if (pick->otyp == PICK_AXE)
872.                         ++cnt;
873.             } else { /* assert(mattock != 0) */
874.                 tool = "mattock";
875.                 while ((mattock = mattock->nobj) != 0)
876.                     if (mattock->otyp == DWARVISH_MATTOCK)
877.                         ++cnt;
878.                 /* [ALI] Shopkeeper identifies mattock(s) */
879.                 if (!Blind)
880.                     makeknown(DWARVISH_MATTOCK);
881.             }
882.             if (!Deaf && !muteshk(shkp)) {
883.                 SetVoice(shkp, 0, 80, 0);
884.                 verbalize(not_upset
885.                               ? "Will you please leave your %s%s outside?"
886.                               : "Leave the %s%s outside.",
887.                           tool, plur(cnt));
888.             } else {
889.                 pline("%s %s to let you in with your %s%s.",
890.                       Shknam(shkp),
891.                       not_upset ? "is hesitant" : "refuses",
892.                       tool, plur(cnt));
893.             }
894.             should_block = TRUE;
895.         } else if (u.usteed) {
896.             if (!Deaf && !muteshk(shkp)) {
897.                 SetVoice(shkp, 0, 80, 0);
898.                 verbalize(not_upset ? "Will you please leave %s outside?"
899.                                     : "Leave %s outside.",
900.                           y_monnam(u.usteed));
901.             } else {
902.                 pline("%s %s to let you in while you're riding %s.",
903.                       Shknam(shkp),
904.                       not_upset ? "doesn't want" : "refuses",
905.                       y_monnam(u.usteed));
906.             }
907.             should_block = TRUE;
908.         } else {
909.             should_block =
910.                 (Fast && (sobj_at(PICK_AXE, u.ux, u.uy)
911.                           || sobj_at(DWARVISH_MATTOCK, u.ux, u.uy)));
912.         }
913.         if (should_block)
914.             (void) dochug(shkp); /* shk gets extra move */
915.     }
916.     return;
917. }
918. 
919. /* called when removing a pick-axe or mattock from a container */
920. void
921. pick_pick(struct obj *obj)
922. {
923.     struct monst *shkp;
924. 
925.     if (obj->unpaid || !is_pick(obj))
926.         return;
927.     shkp = shop_keeper(*u.ushops);
928.     if (shkp && inhishop(shkp)) {
929.         static NEARDATA long pickmovetime = 0L;
930. 
931.         /* if you bring a sack of N picks into a shop to sell,
932.            don't repeat this N times when they're taken out */
933.         if (svm.moves != pickmovetime) {
934.             if (!Deaf && !muteshk(shkp)) {
935.                 SetVoice(shkp, 0, 80, 0);
936.                 verbalize("You sneaky %s!  Get out of here with that pick!",
937.                       cad(FALSE));
938.             } else {
939.                 pline("%s %s your pick!",
940.                       Shknam(shkp),
941.                       haseyes(shkp->data) ? "glares at"
942.                                           : "is dismayed because of");
943.             }
944.         }
945.         pickmovetime = svm.moves;
946.     }
947. }
948. 
949. /*
950.    Decide whether two unpaid items are mergeable; caller is responsible for
951.    making sure they're unpaid and the same type of object; we check the price
952.    quoted by the shopkeeper and also that they both belong to the same shk.
953.  */
954. boolean
955. same_price(struct obj *obj1, struct obj *obj2)
956. {
957.     struct monst *shkp1, *shkp2;
958.     struct bill_x *bp1 = 0, *bp2 = 0;
959.     boolean are_mergable = FALSE;
960. 
961.     /* look up the first object by finding shk whose bill it's on */
962.     for (shkp1 = next_shkp(fmon, TRUE); shkp1;
963.          shkp1 = next_shkp(shkp1->nmon, TRUE))
964.         if ((bp1 = onbill(obj1, shkp1, TRUE)) != 0)
965.             break;
966.     /* second object is probably owned by same shk; if not, look harder */
967.     if (shkp1 && (bp2 = onbill(obj2, shkp1, TRUE)) != 0) {
968.         shkp2 = shkp1;
969.     } else {
970.         for (shkp2 = next_shkp(fmon, TRUE); shkp2;
971.              shkp2 = next_shkp(shkp2->nmon, TRUE))
972.             if ((bp2 = onbill(obj2, shkp2, TRUE)) != 0)
973.                 break;
974.     }
975. 
976.     if (!bp1 || !bp2)
977.         impossible("same_price: object wasn't on any bill!");
978.     else
979.         are_mergable = (shkp1 == shkp2 && bp1->price == bp2->price);
980.     return are_mergable;
981. }
982. 
983. /*
984.  * Figure out how much is owed to a given shopkeeper.
985.  * At present, we ignore any amount robbed from the shop, to avoid
986.  * turning the `$' command into a way to discover that the current
987.  * level is bones data which has a shk on the warpath.
988.  */
989. staticfn long
990. shop_debt(struct eshk *eshkp)
991. {
992.     struct bill_x *bp;
993.     int ct;
994.     long debt = eshkp->debit;
995. 
996.     for (bp = eshkp->bill_p, ct = eshkp->billct; ct > 0; bp++, ct--)
997.         debt += bp->price * bp->bquan;
998.     return debt;
999. }
1000. 
1001. /* called in response to the `$' command */
1002. void
1003. shopper_financial_report(void)
1004. {
1005.     struct monst *shkp, *this_shkp = shop_keeper(inside_shop(u.ux, u.uy));
1006.     struct eshk *eshkp;
1007.     long amt;
1008.     int pass;
1009. 
1010.     eshkp = this_shkp ? ESHK(this_shkp) : 0;
1011.     if (eshkp && !(eshkp->credit || shop_debt(eshkp))) {
1012.         You("have no credit or debt in here.");
1013.         this_shkp = 0; /* skip first pass */
1014.     }
1015. 
1016.     /* pass 0: report for the shop we're currently in, if any;
1017.        pass 1: report for all other shops on this level. */
1018.     for (pass = this_shkp ? 0 : 1; pass <= 1; pass++)
1019.         for (shkp = next_shkp(fmon, FALSE); shkp;
1020.              shkp = next_shkp(shkp->nmon, FALSE)) {
1021.             if ((shkp != this_shkp) ^ pass)
1022.                 continue;
1023.             eshkp = ESHK(shkp);
1024.             if ((amt = eshkp->credit) != 0)
1025.                 You("have %ld %s credit at %s %s.", amt, currency(amt),
1026.                     s_suffix(shkname(shkp)),
1027.                     shtypes[eshkp->shoptype - SHOPBASE].name);
1028.             else if (shkp == this_shkp)
1029.                 You("have no credit in here.");
1030.             if ((amt = shop_debt(eshkp)) != 0)
1031.                 You("owe %s %ld %s.", shkname(shkp), amt, currency(amt));
1032.             else if (shkp == this_shkp)
1033.                 You("don't owe any gold here.");
1034.         }
1035. }
1036. 
1037. /* 1: shopkeeper is currently in her shop or its boundary; 0: not */
1038. int
1039. inhishop(struct monst *shkp)
1040. {
1041.     char *shkrooms;
1042.     struct eshk *eshkp = ESHK(shkp);
1043. 
1044.     if (!on_level(&eshkp->shoplevel, &u.uz))
1045.         return FALSE;
1046.     shkrooms = in_rooms(shkp->mx, shkp->my, SHOPBASE);
1047.     return (strchr(shkrooms, eshkp->shoproom) != 0);
1048. }
1049. 
1050. /* return the shopkeeper for rooms[rmno-2]; returns Null if there isn't one */
1051. struct monst *
1052. shop_keeper(char rmno)
1053. {
1054.     struct monst *shkp;
1055. 
1056.     shkp = (rmno >= ROOMOFFSET) ? svr.rooms[rmno - ROOMOFFSET].resident : 0;
1057.     if (shkp) {
1058.         if (has_eshk(shkp)) {
1059.             if (ANGRY(shkp)) {
1060.                 if (!ESHK(shkp)->surcharge)
1061.                     rile_shk(shkp);
1062.             }
1063.         } else {
1064.             /* would have segfaulted on ESHK dereference previously */
1065.             impossible("%s? (rmno=%d, rtype=%d, mnum=%d, \"%s\")",
1066.                        shkp->isshk ? "shopkeeper career change"
1067.                                    : "shop resident not shopkeeper",
1068.                        (int) rmno,
1069.                        (int) svr.rooms[rmno - ROOMOFFSET].rtype,
1070.                        shkp->mnum,
1071.                        /* [real shopkeeper name is kept in ESHK,
1072.                           not MGIVENNAME] */
1073.                        has_mgivenname(shkp) ? MGIVENNAME(shkp) : "anonymous");
1074.             /* not sure if this is appropriate, because it does nothing to
1075.                correct the underlying svr.rooms[].resident issue but... */
1076.             return (struct monst *) 0;
1077.         }
1078.     }
1079.     return shkp;
1080. }
1081. 
1082. /* find the shopkeeper who owns 'obj'; needed to handle shared shop walls */
1083. struct monst *
1084. find_objowner(
1085.     struct obj *obj,
1086.     coordxy x, coordxy y) /* caller passes obj's location since obj->ox,oy
1087.                            * might be stale; don't update coordinates here
1088.                            * because if we're called during sanity checking
1089.                            * they shouldn't be modified */
1090. {
1091.     struct monst *shkp, *deflt_shkp = 0;
1092. 
1093.     if (obj->where == OBJ_ONBILL) {
1094.         /* used up item; bill obj coordinates are useless and so are x,y */
1095.         for (shkp = next_shkp(fmon, TRUE); shkp;
1096.              shkp = next_shkp(shkp->nmon, TRUE))
1097.             if (onshopbill(obj, shkp, TRUE))
1098.                 return shkp;
1099.     } else {
1100.         char *roomindx, *where = in_rooms(x, y, SHOPBASE);
1101. 
1102.         /* conceptually object could be inside up to 4 rooms simultaneously;
1103.            in practice it will usually be one room but can sometimes be two;
1104.            check shk and bill for each room rather than just the first;
1105.            fallback to the first shk if obj isn't on the relevant bill(s) */
1106.         for (roomindx = where; *roomindx; ++roomindx)
1107.             if ((shkp = shop_keeper(*roomindx)) != 0) {
1108.                 if (onshopbill(obj, shkp, TRUE))
1109.                     return shkp;
1110.                 if (!deflt_shkp)
1111.                     deflt_shkp = shkp;
1112.             }
1113.     }
1114.     return deflt_shkp;
1115. }
1116. 
1117. boolean
1118. tended_shop(struct mkroom *sroom)
1119. {
1120.     struct monst *mtmp = sroom->resident;
1121. 
1122.     return !mtmp ? FALSE : (boolean) inhishop(mtmp);
1123. }
1124. 
1125. void
1126. noisy_shop(struct mkroom *sroom)
1127. {
1128.     struct monst *mtmp = sroom->resident;
1129. 
1130.     if (mtmp && inhishop(mtmp)) {
1131.         wake_nearto(mtmp->mx, mtmp->my, 11 * 11);
1132.     }
1133. }
1134. 
1135. staticfn struct bill_x *
1136. onbill(struct obj *obj, struct monst *shkp, boolean silent)
1137. {
1138.     if (shkp) {
1139.         struct bill_x *bp;
1140.         int ct;
1141. 
1142.         for (ct = ESHK(shkp)->billct, bp = ESHK(shkp)->bill_p;
1143.              ct > 0; --ct, ++bp) {
1144.             if (bp->bo_id == obj->o_id) {
1145.                 if (!obj->unpaid)
1146.                     impossible("onbill: paid obj on bill?");
1147.                 return bp;
1148.             }
1149.         }
1150.     }
1151.     if (obj->unpaid && !silent)
1152.         impossible("onbill: unpaid obj %s?",
1153.                    !shkp ? "without shopkeeper" : "not on shk's bill");
1154.     return (struct bill_x *) 0;
1155. }
1156. 
1157. /* used outside of shk.c when caller wants to know whether item is on bill
1158.    but doesn't need to know any details about the bill itself */
1159. boolean
1160. onshopbill(struct obj *obj, struct monst *shkp, boolean silent)
1161. {
1162.     return onbill(obj, shkp, silent) ? TRUE : FALSE;
1163. }
1164. 
1165. /* check whether an object or any of its contents belongs to a shop */
1166. boolean
1167. is_unpaid(struct obj *obj)
1168. {
1169.     return (boolean) (obj->unpaid
1170.                       || (Has_contents(obj) && count_unpaid(obj->cobj)));
1171. }
1172. 
1173. /* Delete the contents of the given object. */
1174. void
1175. delete_contents(struct obj *obj)
1176. {
1177.     struct obj *curr;
1178. 
1179.     while ((curr = obj->cobj) != 0) {
1180.         obj_extract_self(curr);
1181.         obfree(curr, (struct obj *) 0);
1182.     }
1183. }
1184. 
1185. /* called with two args on merge */
1186. void
1187. obfree(struct obj *obj, struct obj *merge)
1188. {
1189.     struct bill_x *bp;
1190.     struct bill_x *bpm;
1191.     struct monst *shkp;
1192. 
1193.     if (obj->otyp == LEASH && obj->leashmon)
1194.         o_unleash(obj);
1195.     if (obj->oclass == FOOD_CLASS)
1196.         food_disappears(obj);
1197.     if (obj->oclass == SPBOOK_CLASS)
1198.         book_disappears(obj);
1199.     if (Has_contents(obj))
1200.         delete_contents(obj);
1201.     if (Is_container(obj))
1202.         maybe_reset_pick(obj);
1203.     if (obj->otyp == BOULDER)
1204.         obj->next_boulder = 0;
1205. 
1206.     shkp = 0;
1207.     if (obj->unpaid) {
1208.         /* look for a shopkeeper who owns this object */
1209.         for (shkp = next_shkp(fmon, TRUE); shkp;
1210.              shkp = next_shkp(shkp->nmon, TRUE))
1211.             if (onbill(obj, shkp, TRUE))
1212.                 break;
1213.     }
1214.     /* sanity check, in case obj is on bill but not marked 'unpaid' */
1215.     if (!shkp)
1216.         shkp = shop_keeper(*u.ushops);
1217.     /*
1218.      * Note:  `shkp = shop_keeper(*u.ushops)' used to be
1219.      *    unconditional.  But obfree() is used all over
1220.      *    the place, so making its behavior be dependent
1221.      *    upon player location doesn't make much sense.
1222.      */
1223. 
1224.     if ((bp = onbill(obj, shkp, FALSE)) != 0) {
1225.         if (!merge) {
1226.             bp->useup = TRUE;
1227.             obj->unpaid = 0; /* only for doinvbill */
1228.             /* for used up glob, put back original weight in case it gets
1229.                formatted ('I x' or itemized billing) with 'wizweight' On */
1230.             if (obj->globby && !obj->owt && has_omid(obj))
1231.                 obj->owt = OMID(obj);
1232.             add_to_billobjs(obj);
1233.             return;
1234.         }
1235.         bpm = onbill(merge, shkp, FALSE);
1236.         if (!bpm) {
1237.             /* this used to be a rename */
1238.             /* !merge already returned */
1239.             impossible(
1240.                    "obfree: not on bill, %s = (%d,%d,%ld,%d) (%d,%d,%ld,%d)?",
1241.                        "otyp,where,quan,unpaid",
1242.                        obj->otyp, obj->where, obj->quan, obj->unpaid ? 1 : 0,
1243.                        merge->otyp, merge->where, merge->quan,
1244.                        merge->unpaid ? 1 : 0);
1245.             return;
1246.         } else {
1247.             struct eshk *eshkp = ESHK(shkp);
1248. 
1249.             /* this was a merger */
1250.             bpm->bquan += bp->bquan;
1251.             eshkp->billct--;
1252.             *bp = eshkp->bill_p[eshkp->billct];
1253.         }
1254.     } else {
1255.         /* not on bill; if the item is being merged away rather than
1256.            just deleted and has a higher price adjustment than the stack
1257.            being merged into, give the latter the former's obj->o_id so
1258.            that the merged stack takes on higher price; matters if hero
1259.            eventually buys them from a shop, but doesn't matter if hero
1260.            owns them and intends to sell (unless he subsequently buys
1261.            them back) or if no shopping activity ever involves them */
1262.         if (merge && (oid_price_adjustment(obj, obj->o_id)
1263.                       > oid_price_adjustment(merge, merge->o_id)))
1264.             merge->o_id = obj->o_id;
1265.     }
1266.     if (obj->owornmask) {
1267.         impossible("obfree: deleting worn obj (%d: %ld)", obj->otyp,
1268.                    obj->owornmask);
1269.         /* unfortunately at this point we don't know whether worn mask
1270.            applied to hero or a monster or perhaps something bogus, so
1271.            can't call remove_worn_item() to get <X>_off() side-effects */
1272.         setnotworn(obj);
1273.     }
1274.     dealloc_obj(obj);
1275. }
1276. 
1277. staticfn long
1278. check_credit(long  tmp, struct monst *shkp)
1279. {
1280.     long credit = ESHK(shkp)->credit;
1281. 
1282.     if (credit == 0L) {
1283.         ; /* nothing to do; just 'return tmp;' */
1284.     } else if (credit >= tmp) {
1285.         pline_The("price is deducted from your credit.");
1286.         ESHK(shkp)->credit -= tmp;
1287.         tmp = 0L;
1288.     } else {
1289.         pline_The("price is partially covered by your credit.");
1290.         ESHK(shkp)->credit = 0L;
1291.         tmp -= credit;
1292.     }
1293.     return tmp;
1294. }
1295. 
1296. staticfn void
1297. pay(long tmp, struct monst *shkp)
1298. {
1299.     long robbed = ESHK(shkp)->robbed;
1300.     long balance = ((tmp <= 0L) ? tmp : check_credit(tmp, shkp));
1301. 
1302.     if (balance > 0)
1303.         money2mon(shkp, balance);
1304.     else if (balance < 0)
1305.         money2u(shkp, -balance);
1306.     disp.botl = TRUE;
1307.     if (robbed) {
1308.         robbed -= tmp;
1309.         if (robbed < 0)
1310.             robbed = 0L;
1311.         ESHK(shkp)->robbed = robbed;
1312.     }
1313. }
1314. 
1315. /* return shkp to home position */
1316. staticfn void
1317. home_shk(struct monst *shkp, boolean killkops)
1318. {
1319.     coordxy x = ESHK(shkp)->shk.x, y = ESHK(shkp)->shk.y;
1320. 
1321.     (void) mnearto(shkp, x, y, TRUE, RLOC_NOMSG);
1322.     svl.level.flags.has_shop = 1;
1323.     if (killkops) {
1324.         kops_gone(TRUE);
1325.         pacify_guards();
1326.     }
1327.     after_shk_move(shkp);
1328. }
1329. 
1330. staticfn boolean
1331. angry_shk_exists(void)
1332. {
1333.     struct monst *shkp;
1334. 
1335.     for (shkp = next_shkp(fmon, FALSE); shkp;
1336.          shkp = next_shkp(shkp->nmon, FALSE))
1337.         if (ANGRY(shkp))
1338.             return TRUE;
1339.     return FALSE;
1340. }
1341. 
1342. /* remove previously applied surcharge from all billed items */
1343. staticfn void
1344. pacify_shk(struct monst *shkp, boolean clear_surcharge)
1345. {
1346.     NOTANGRY(shkp) = TRUE; /* make peaceful */
1347.     if (clear_surcharge && ESHK(shkp)->surcharge) {
1348.         struct bill_x *bp = ESHK(shkp)->bill_p;
1349.         int ct = ESHK(shkp)->billct;
1350. 
1351.         ESHK(shkp)->surcharge = FALSE;
1352.         while (ct-- > 0) {
1353.             long reduction = (bp->price + 3L) / 4L;
1354.             bp->price -= reduction; /* undo 33% increase */
1355.             bp++;
1356.         }
1357.     }
1358. }
1359. 
1360. /* add aggravation surcharge to all billed items */
1361. staticfn void
1362. rile_shk(struct monst *shkp)
1363. {
1364.     NOTANGRY(shkp) = FALSE; /* make angry */
1365.     if (!ESHK(shkp)->surcharge) {
1366.         long surcharge;
1367.         struct bill_x *bp = ESHK(shkp)->bill_p;
1368.         int ct = ESHK(shkp)->billct;
1369. 
1370.         ESHK(shkp)->surcharge = TRUE;
1371.         while (ct-- > 0) {
1372.             surcharge = (bp->price + 2L) / 3L;
1373.             bp->price += surcharge;
1374.             bp++;
1375.         }
1376.     }
1377. }
1378. 
1379. /* wakeup and/or unparalyze shopkeeper */
1380. staticfn void
1381. rouse_shk(struct monst *shkp, boolean verbosely)
1382. {
1383.     if (helpless(shkp)) {
1384.         /* greed induced recovery... */
1385.         if (verbosely && canspotmon(shkp))
1386.             pline("%s %s.", Shknam(shkp),
1387.                   shkp->msleeping ? "wakes up" : "can move again");
1388.         shkp->msleeping = 0;
1389.         shkp->mfrozen = 0;
1390.         shkp->mcanmove = 1;
1391.     }
1392. }
1393. 
1394. void
1395. make_happy_shk(struct monst *shkp, boolean silentkops)
1396. {
1397.     boolean wasmad = ANGRY(shkp);
1398.     struct eshk *eshkp = ESHK(shkp);
1399. 
1400.     pacify_shk(shkp, FALSE);
1401.     eshkp->following = 0;
1402.     eshkp->robbed = 0L;
1403.     if (!Role_if(PM_ROGUE))
1404.         adjalign(sgn(u.ualign.type));
1405.     if (!inhishop(shkp)) {
1406.         char shk_nam[BUFSZ];
1407.         boolean vanished = canseemon(shkp);
1408. 
1409.         Strcpy(shk_nam, shkname(shkp));
1410.         if (on_level(&eshkp->shoplevel, &u.uz)) {
1411.             home_shk(shkp, FALSE);
1412.             if (canspotmon(shkp)) {
1413.                 pline("%s returns to %s shop.", Shknam(shkp),
1414.                       noit_mhis(shkp));
1415.                 vanished = FALSE; /* don't give 'Shk disappears' message */
1416.             }
1417.         } else {
1418.             /* if sensed, does disappear regardless whether seen */
1419.             if (sensemon(shkp))
1420.                 vanished = TRUE;
1421.             /* can't act as porter for the Amulet, even if shk
1422.                happens to be going farther down rather than up */
1423.             mdrop_special_objs(shkp);
1424.             /* arrive near shop's door */
1425.             migrate_to_level(shkp, ledger_no(&eshkp->shoplevel),
1426.                              MIGR_APPROX_XY, &eshkp->shd);
1427.             /* dismiss kops on that level when shk arrives */
1428.             eshkp->dismiss_kops = TRUE;
1429.         }
1430.         if (vanished)
1431.             pline("Satisfied, %s suddenly disappears!", shk_nam);
1432.     } else if (wasmad)
1433.         pline("%s calms down.", Shknam(shkp));
1434. 
1435.     make_happy_shoppers(silentkops);
1436. }
1437. 
1438. /* called by make_happy_shk() and also by losedogs() for migrating shk */
1439. void
1440. make_happy_shoppers(boolean silentkops)
1441. {
1442.     if (!angry_shk_exists()) {
1443.         kops_gone(silentkops);
1444.         pacify_guards();
1445.     }
1446. }
1447. 
1448. void
1449. hot_pursuit(struct monst *shkp)
1450. {
1451.     if (!shkp->isshk)
1452.         return;
1453. 
1454.     rile_shk(shkp);
1455.     (void) strncpy(ESHK(shkp)->customer, svp.plname, PL_NSIZ);
1456.     ESHK(shkp)->following = 1;
1457. 
1458.     /* shopkeeper networking:  clear obj->no_charge for all obj on the
1459.        floor of this level (including inside containers on floor), even
1460.        those that are in other shopkeepers' shops */
1461.     clear_no_charge((struct monst *) NULL, fobj);
1462.     clear_no_charge_pets(shkp);
1463. }
1464. 
1465. /* Used when the shkp is teleported or falls (ox == 0) out of his shop, or
1466.    when the player is not on a costly_spot and he damages something inside
1467.    the shop.  These conditions must be checked by the calling function. */
1468. /*ARGSUSED*/
1469. void
1470. make_angry_shk(
1471.     struct monst *shkp,
1472.     coordxy ox UNUSED, coordxy oy UNUSED)
1473.     /* <ox,oy> predate 'noit_Monnam()', let alone Shknam() */
1474. {
1475.     struct eshk *eshkp = ESHK(shkp);
1476. 
1477.     /* all pending shop transactions are now "past due" */
1478.     if (eshkp->billct || eshkp->debit || eshkp->loan || eshkp->credit) {
1479.         eshkp->robbed += (addupbill(shkp) + eshkp->debit + eshkp->loan);
1480.         eshkp->robbed -= eshkp->credit;
1481.         if (eshkp->robbed < 0L)
1482.             eshkp->robbed = 0L;
1483.         /* billct, debit, loan, and credit will be cleared by setpaid */
1484.         setpaid(shkp);
1485.     }
1486. 
1487.     pline("%s %s!", Shknam(shkp), !ANGRY(shkp) ? "gets angry" : "is furious");
1488.     hot_pursuit(shkp);
1489. }
1490. 
1491. static const char
1492.         no_money[] = "Moreover, you%s have no gold.",
1493.         not_enough_money[] = "Besides, you don't have enough to interest %s.";
1494. 
1495. /* if one item is used-up and the other isn't, the used-up one comes first;
1496.    otherwise, if their costs differ, the more expensive one comes first;
1497.    if costs are the same, use internal index as tie-breaker for stable sort */
1498. staticfn int QSORTCALLBACK
1499. sortbill_cmp(const genericptr vptr1, const genericptr vptr2)
1500. {
1501.     const struct sortbill_item *sbi1 = (struct sortbill_item *) vptr1,
1502.                                *sbi2 = (struct sortbill_item *) vptr2;
1503.     long cost1 = sbi1->cost, cost2 = sbi2->cost;
1504.     int bidx1 = sbi1->bidx, bidx2 = sbi2->bidx,
1505.         /* sort such that FullyUsedUp and PartlyUsedUp come before
1506.             PartlyIntact, FullyIntact, KnownContainer, UndisclosedContainer */
1507.         used1 = sbi1->usedup <= PartlyUsedUp, /* 0=>unpaid, 1=>used */
1508.         used2 = sbi2->usedup <= PartlyUsedUp;
1509. 
1510.     if (used1 != used2)
1511.         return (used2 - used1); /* bigger comes before smaller here */
1512.     if (cost1 != cost2)
1513.         return (cost2 - cost1); /* bigger comes before smaller here too */
1514.     /* index into eshkp->bill_p[] isn't unique (an item that is partly
1515.        used and partly intact will have two ibill[] entries indexing same
1516.        bill_p[] element) but duplicates won't reach here (used1 vs used2) */
1517.     return (bidx1 - bidx2);
1518. }
1519. 
1520. /* delivers the cheapest item on the list */
1521. staticfn long
1522. cheapest_item(int ibillct, Bill *ibill)
1523. {
1524.     int i;
1525.     long gmin = ibill[0].cost;
1526. 
1527.     /*
1528.      * 5.0: old version didn't determine cheapest item correctly if it
1529.      * was either the partly used or partly intact portion of a partially
1530.      * used stack.  Rather than modify it to use bp_to_obj() in order to
1531.      * obtain quanities for every entry on eshkp->bill_p[], switch to
1532.      * ibill[] which has already split such items into separate entries.
1533.      */
1534. 
1535.     for (i = 1; i < ibillct; ++i)
1536.         if (ibill[i].cost < gmin)
1537.             gmin = ibill[i].cost;
1538.     return gmin;
1539. }
1540. 
1541. 
1542. /* for itemized purchasing, create an alternate shop bill that hides
1543.    container contents */
1544. staticfn int /* returns number of entries */
1545. make_itemized_bill(
1546.     struct monst *shkp,
1547.     Bill **ibill_p) /* output, augmented bill similar to a 'sortloot array' */
1548. {
1549.     static Bill zerosbi; /* Null sortbill item */
1550.     Bill *ibill;
1551.     struct bill_x *bp;
1552.     struct obj *otmp;
1553.     struct eshk *eshkp = ESHK(shkp);
1554.     int i, n, bidx, ebillct = eshkp->billct;
1555.     int8 used;
1556.     long quan, cost;
1557. 
1558.     /* this overallocates unless there happens to be a used-up portion
1559.        and an intact potion for every object on the bill; doing it this
1560.        way avoids the need to look up every object on the bill an extra
1561.        time; (the +1 for a terminator isn't actually needed) */
1562.     n = 2 * ebillct + 1;
1563.     ibill = *ibill_p = (Bill *) alloc(n * sizeof *ibill);
1564.     for (i = 0; i < n; ++i)
1565.         ibill[i] = zerosbi;
1566. 
1567.     n = 0; /* number of entries in ibill[]; won't necessary match ebillct */
1568.     for (i = 0; i < ebillct; ++i) {
1569.         bp = &eshkp->bill_p[i];
1570.         /* find the object on the bill */
1571.         otmp = bp_to_obj(bp);
1572.         if (!otmp) {
1573.             impossible("Can't find shop bill entry for #%d", bp->bo_id);
1574.             continue;
1575.         }
1576.         bidx = i; /* index into bill_p[], except for hero-owner container */
1577. 
1578.         if (otmp->quan == 0L || otmp->where == OBJ_ONBILL) {
1579.             /* item is completely used up; restore quantity from when it
1580.                was first unpaid; otmp is on billobjs list where it can
1581.                only be seen via Ix and itemized billing while paying shk */
1582.             otmp->quan = bp->bquan;
1583.             bp->useup = TRUE; /* (expected to be set already) */
1584.         } else if (otmp->quan < bp->bquan) {
1585.             /* item is partly used up; we will create two entries in the
1586.                augmented bill: one for the used up part here, another for
1587.                the intact part (which might be inside a container if put in
1588.                after using part of a stack; used up part isn't) below */
1589.             ibill[n].obj = otmp;
1590.             ibill[n].quan = bp->bquan - otmp->quan;
1591.             ibill[n].cost = bp->price * ibill[n].quan;
1592.             ibill[n].bidx = bidx; /* duplicate index into eshkp->bill_p[] */
1593.             ibill[n].usedup = PartlyUsedUp; /* for sorting */
1594.             ++n; /* intact portion will be a separate entry, next */
1595.         }
1596. 
1597.         if (otmp->where == OBJ_ONBILL) {
1598.             /* completely used up */
1599.             quan = bp->bquan;
1600.             cost = bp->price * quan;
1601.             used = FullyUsedUp;
1602.         } else if (otmp->where == OBJ_CONTAINED || Has_contents(otmp)) {
1603.             int j;
1604.             struct obj *item = otmp;
1605.             boolean cknown = TRUE; /* assume container contents are known */
1606. 
1607.             /* when it's in a container, put the container rather than the
1608.                specific object into ibill[]; find outermost container */
1609.             while (otmp->where == OBJ_CONTAINED) {
1610.                 otmp = otmp->ocontainer;
1611.                 if (!otmp->cknown)
1612.                     cknown = FALSE;
1613.             }
1614.             /* this container might already be in ibill[] if it is unpaid
1615.                itself or if it holds more than one unpaid item and another
1616.                besides this one has already been processed; only include
1617.                first instance */
1618.             for (j = 0; j < n; ++j)
1619.                 if (otmp == ibill[j].obj)
1620.                     break;
1621.             if (j < n) {
1622.                 /* when already on bill as FullyIntact, update; the cost
1623.                    saved in ibill[j] is based on the container even if the
1624.                    entry was initially created for an item of its contents */
1625.                 if (ibill[j].usedup == FullyIntact)
1626.                     ibill[j].usedup = cknown ? KnownContainer
1627.                                              : UndisclosedContainer;
1628.                 continue; /* 'i' loop */
1629.             }
1630.             /* include 1 container containing unpaid item(s) */
1631.             quan = 1L;
1632.             cost = unpaid_cost(otmp, COST_CONTENTS);
1633.             if (!otmp->unpaid)
1634.                 bidx = -1;
1635.             /* an unpaid container without any unpaid contents is classified
1636.                as 'FullyIntact'; a container with unpaid contents will be
1637.                '*Container' regardless of whether it is unpaid itself */
1638.             used = (otmp == item) ? FullyIntact
1639.                    : cknown ? KnownContainer
1640.                      : UndisclosedContainer;
1641.         } else {
1642.             /* ordinary unpaid; when partly used, these are values for the
1643.                intact portion; might be an empty shop-owned container */
1644.             quan = otmp->quan;
1645.             cost = bp->price * quan;
1646.             used = (quan < bp->bquan) ? PartlyIntact : FullyIntact;
1647.         }
1648. 
1649.         ibill[n].obj = otmp;
1650.         ibill[n].quan = quan;
1651.         ibill[n].cost = cost;
1652.         ibill[n].bidx = bidx;
1653.         ibill[n].usedup = used;
1654.         ++n;
1655.     }
1656.     ibill[n].bidx = -1; /* end of list; not strictly needed */
1657. 
1658.     /* ibill[0..n-1] contains data, ibill[n] has Null obj and -1 bidx and
1659.        is excluded from the sort */
1660.     if (n > 1)
1661.         qsort((genericptr_t) ibill, n, sizeof *ibill, sortbill_cmp);
1662.     return n;
1663. }
1664. 
1665. /* show items on your bill in a menu, and ask which to pay.
1666.    returns the number of entries selected. */
1667. staticfn int
1668. menu_pick_pay_items(
1669.     int ibillct, /* number of entries in ibill[] */
1670.     Bill *ibill) /* all used up items, if any, precede all intact items */
1671. {
1672.     struct obj *otmp;
1673.     winid win;
1674.     anything any;
1675.     menu_item *pick_list = (menu_item *) 0;
1676.     char *p, buf[BUFSZ];
1677.     long amt, largest_amt, save_quan;
1678.     int i, j, n, amt_width;
1679. 
1680.     any = cg.zeroany;
1681.     win = create_nhwindow(NHW_MENU);
1682.     start_menu(win, MENU_BEHAVE_STANDARD);
1683. 
1684.     /* we go through ibill[] twice, first time to control price formatting
1685.        during the second */
1686.     largest_amt = 0L;
1687.     for (i = 0; i < ibillct; ++i)
1688.         if (ibill[i].cost > largest_amt)
1689.             largest_amt = ibill[i].cost;
1690.     Sprintf(buf, "%ld", largest_amt);
1691.     amt_width = (int) strlen(buf);
1692. 
1693.     /* show the "used up items" header if there are any used up items on
1694.        the bill, no matter whether there are also any intact items;
1695.        note: ibill[] has been sorted to hold used-up items first */
1696.     if (ibill[0].usedup <= PartlyUsedUp) {
1697.         Sprintf(buf, "Used up item%s:",
1698.                 (ibillct > 1 && ibill[1].usedup <= PartlyUsedUp) ? "s" : "");
1699.         add_menu_heading(win, buf);
1700.     }
1701.     for (i = 0; i < ibillct; ++i) {
1702.         /* the "unpaid items" header is only shown if the "used up items"
1703.            one was shown before the first menu entry */
1704.         if (i > 0 && ibill[i - 1].usedup <= PartlyUsedUp
1705.             && ibill[i].usedup >= PartlyIntact) {
1706.             Sprintf(buf, "Unpaid item%s:", (i < ibillct - 1) ? "s" : "");
1707.             add_menu_heading(win, buf);
1708.         }
1709.         otmp = ibill[i].obj;
1710.         save_quan = otmp->quan;
1711.         otmp->quan = ibill[i].quan; /* in case it's partly used */
1712.         p = paydoname(otmp);
1713.         otmp->quan = save_quan;
1714.         amt = ibill[i].cost;
1715.         /* this doesn't support hallucinatory currency because shopkeeper
1716.            isn't hallucinating; also, that would mess up the alignment */
1717.         Snprintf(buf, sizeof buf, "%*ld Zm, %s", amt_width, amt, p);
1718.         any.a_int = i + 1; /* +1: avoid 0 */
1719.         add_menu(win, &nul_glyphinfo, &any, 0, 0, ATR_NONE, NO_COLOR, buf,
1720.                  MENU_ITEMFLAGS_NONE);
1721.     }
1722. 
1723.     end_menu(win, "Pay for which items?");
1724.     n = select_menu(win, PICK_ANY, &pick_list);
1725.     destroy_nhwindow(win);
1726. 
1727.     for (j = 0; j < n; ++j) {
1728.         /*
1729.          * FIXME:
1730.          *  The menu will accept a subset count for each entry but buying
1731.          *  doesn't have any support for that.
1732.          */
1733.         i = pick_list[j].item.a_int - 1; /* -1: reverse +1 above */
1734.         ibill[i].queuedpay = TRUE;
1735.     }
1736.     free(pick_list);
1737.     /* for ESC, return 0 instead of usual -1 */
1738.     return max(n, 0);
1739. }
1740. 
1741. /* the #pay command */
1742. int
1743. dopay(void)
1744. {
1745.     struct eshk *eshkp;
1746.     struct monst *shkp;
1747.     struct monst *nxtm, *resident;
1748.     Bill *ibill = (Bill *) NULL;
1749.     long ltmp;
1750.     long umoney;
1751.     int sk = 0, seensk = 0, nexttosk = 0;
1752.     boolean paid = FALSE, stashed_gold = (hidden_gold(TRUE) > 0L),
1753.             pay_done;
1754. 
1755.     gm.multi = 0;
1756. 
1757.     /* Find how many shk's there are, how many are in
1758.      * sight, and are you in a shop room with one.
1759.      */
1760.     nxtm = resident = 0;
1761.     for (shkp = next_shkp(fmon, FALSE); shkp;
1762.          shkp = next_shkp(shkp->nmon, FALSE)) {
1763.         sk++;
1764.         if (m_next2u(shkp)) {
1765.             /* next to an irate shopkeeper? prioritize that */
1766.             if (nxtm && ANGRY(nxtm))
1767.                 continue;
1768.             nexttosk++;
1769.             nxtm = shkp;
1770.         }
1771.         if (canspotmon(shkp))
1772.             seensk++;
1773.         if (inhishop(shkp) && (*u.ushops == ESHK(shkp)->shoproom))
1774.             resident = shkp;
1775.     }
1776. 
1777.     if (nxtm && nexttosk == 1) {
1778.         shkp = nxtm;
1779.         goto proceed;
1780.     }
1781. 
1782.     if ((!sk && (!Blind || Blind_telepat)) || (!Blind && !seensk)) {
1783.         There("appears to be no shopkeeper here to receive your payment.");
1784.         return ECMD_OK;
1785.     }
1786. 
1787.     if (!seensk) {
1788.         You_cant("see...");
1789.         return ECMD_OK;
1790.     }
1791. 
1792.     /* The usual case.  Allow paying at a distance when
1793.      * inside a tended shop.  Should we change that?
1794.      */
1795.     if (sk == 1 && resident) {
1796.         shkp = resident;
1797.         goto proceed;
1798.     }
1799. 
1800.     if (seensk == 1) {
1801.         for (shkp = next_shkp(fmon, FALSE); shkp;
1802.              shkp = next_shkp(shkp->nmon, FALSE))
1803.             if (canspotmon(shkp))
1804.                 break;
1805.         assert(shkp != NULL); /* seensk==1 =>  traversal will spot one shk */
1806.         if (shkp != resident && !m_next2u(shkp)) {
1807.             pline("%s is not near enough to receive your payment.",
1808.                   Shknam(shkp));
1809.             return ECMD_OK;
1810.         }
1811.     } else {
1812.         struct monst *mtmp;
1813.         coord cc;
1814.         int cx, cy;
1815. 
1816.         pline("Pay whom?");
1817.         cc.x = u.ux;
1818.         cc.y = u.uy;
1819.         if (getpos(&cc, TRUE, "the creature you want to pay") < 0)
1820.             return ECMD_CANCEL; /* player pressed ESC */
1821.         cx = cc.x;
1822.         cy = cc.y;
1823.         if (cx < 0) {
1824.             pline("Try again...");
1825.             return ECMD_OK;
1826.         }
1827.         if (u_at(cx, cy)) {
1828.             You("are generous to yourself.");
1829.             return ECMD_OK;
1830.         }
1831.         mtmp = m_at(cx, cy);
1832.         if (!cansee(cx, cy) && (!mtmp || !canspotmon(mtmp))) {
1833.             You("can't %s anyone there.", !Blind ? "see" : "sense");
1834.             return ECMD_OK;
1835.         }
1836.         if (!mtmp) {
1837.             There("is no one there to receive your payment.");
1838.             return ECMD_OK;
1839.         }
1840.         if (!mtmp->isshk) {
1841.             pline("%s is not interested in your payment.", Monnam(mtmp));
1842.             return ECMD_OK;
1843.         }
1844.         if (mtmp != resident && !m_next2u(mtmp)) {
1845.             pline("%s is too far to receive your payment.", Shknam(mtmp));
1846.             return ECMD_OK;
1847.         }
1848.         shkp = mtmp;
1849.     }
1850. 
1851.     if (!shkp) {
1852.         debugpline0("dopay: null shkp.");
1853.         return ECMD_OK;
1854.     }
1855.  proceed:
1856.     eshkp = ESHK(shkp);
1857.     ltmp = eshkp->robbed;
1858. 
1859.     /* wake sleeping shk when someone who owes money offers payment */
1860.     if (ltmp || eshkp->billct || eshkp->debit)
1861.         rouse_shk(shkp, TRUE);
1862. 
1863.     if (helpless(shkp)) { /* still asleep/paralyzed */
1864.         pline("%s %s.", Shknam(shkp),
1865.               rn2(2) ? "seems to be napping" : "doesn't respond");
1866.         return ECMD_OK;
1867.     }
1868. 
1869.     if (shkp != resident && NOTANGRY(shkp)) {
1870.         umoney = money_cnt(gi.invent);
1871.         if (!ltmp) {
1872.             You("do not owe %s anything.", shkname(shkp));
1873.         } else if (!umoney) {
1874.             You("%shave no gold.", stashed_gold ? "seem to " : "");
1875.             if (stashed_gold)
1876.                 pline("But you have some gold stashed away.");
1877.         } else {
1878.             if (umoney > ltmp) {
1879.                 You("give %s the %ld gold piece%s %s asked for.",
1880.                     shkname(shkp), ltmp, plur(ltmp), noit_mhe(shkp));
1881.                 pay(ltmp, shkp);
1882.             } else {
1883.                 You("give %s all your%s gold.", shkname(shkp),
1884.                     stashed_gold ? " openly kept" : "");
1885.                 pay(umoney, shkp);
1886.                 if (stashed_gold)
1887.                     pline("But you have hidden gold!");
1888.             }
1889.             if ((umoney < ltmp / 2L) || (umoney < ltmp && stashed_gold))
1890.                 pline("Unfortunately, %s doesn't look satisfied.",
1891.                       noit_mhe(shkp));
1892.             else
1893.                 make_happy_shk(shkp, FALSE);
1894.         }
1895.         return ECMD_TIME;
1896.     }
1897. 
1898.     /* ltmp is still eshkp->robbed here */
1899.     if (!eshkp->billct && !eshkp->debit) {
1900.         umoney = money_cnt(gi.invent);
1901.         if (!ltmp && NOTANGRY(shkp)) {
1902.             You("do not owe %s anything.", shkname(shkp));
1903.             if (!umoney)
1904.                 pline(no_money, stashed_gold ? " seem to" : "");
1905.         } else if (ltmp) {
1906.             pline("%s is after blood, not gold!", shkname(shkp));
1907.             if (umoney < ltmp / 2L || (umoney < ltmp && stashed_gold)) {
1908.                 if (!umoney)
1909.                     pline(no_money, stashed_gold ? " seem to" : "");
1910.                 else
1911.                     pline(not_enough_money, noit_mhim(shkp));
1912.                 return ECMD_TIME;
1913.             }
1914.             pline("But since %s shop has been robbed recently,",
1915.                   noit_mhis(shkp));
1916.             pline("you %scompensate %s for %s losses.",
1917.                   (umoney < ltmp) ? "partially " : "", shkname(shkp),
1918.                   noit_mhis(shkp));
1919.             pay(umoney < ltmp ? umoney : ltmp, shkp);
1920.             make_happy_shk(shkp, FALSE);
1921.         } else {
1922.             /* shopkeeper is angry, but has not been robbed --
1923.              * door broken, attacked, etc. */
1924.             pline("%s is after your hide, not your gold!", Shknam(shkp));
1925.             if (umoney < 1000L) {
1926.                 if (!umoney)
1927.                     pline(no_money, stashed_gold ? " seem to" : "");
1928.                 else
1929.                     pline(not_enough_money, noit_mhim(shkp));
1930.                 return ECMD_TIME;
1931.             }
1932.             You("try to appease %s by giving %s 1000 gold pieces.",
1933.                 canspotmon(shkp)
1934.                     ? x_monnam(shkp, ARTICLE_THE, "angry", 0, FALSE)
1935.                     : shkname(shkp),
1936.                 noit_mhim(shkp));
1937.             pay(1000L, shkp);
1938.             if (strncmp(eshkp->customer, svp.plname, PL_NSIZ) || rn2(3))
1939.                 make_happy_shk(shkp, FALSE);
1940.             else
1941.                 pline("But %s is as angry as ever.", shkname(shkp));
1942.         }
1943.         return ECMD_TIME;
1944.     }
1945.     if (shkp != resident) {
1946.         impossible("dopay: not to shopkeeper?");
1947.         if (resident)
1948.             setpaid(resident);
1949.         return ECMD_OK;
1950.     }
1951.     /* pay debt, if any, first */
1952.     if (eshkp->debit) {
1953.         long dtmp = eshkp->debit;
1954.         long loan = eshkp->loan;
1955.         char sbuf[BUFSZ];
1956. 
1957.         umoney = money_cnt(gi.invent);
1958.         Sprintf(sbuf, "You owe %s %ld %s ", shkname(shkp), dtmp,
1959.                 currency(dtmp));
1960.         if (loan) {
1961.             if (loan == dtmp)
1962.                 Strcat(sbuf, "you picked up in the store.");
1963.             else
1964.                 Strcat(sbuf,
1965.                        "for gold picked up and the use of merchandise.");
1966.         } else {
1967.             Strcat(sbuf, "for the use of merchandise.");
1968.         }
1969.         pline1(sbuf);
1970.         if (umoney + eshkp->credit < dtmp) {
1971.             pline("But you don't%s have enough gold%s.",
1972.                   stashed_gold ? " seem to" : "",
1973.                   eshkp->credit ? " or credit" : "");
1974.             return ECMD_TIME;
1975.         } else {
1976.             if (eshkp->credit >= dtmp) {
1977.                 eshkp->credit -= dtmp;
1978.                 eshkp->debit = 0L;
1979.                 eshkp->loan = 0L;
1980.                 Your("debt is covered by your credit.");
1981.             } else if (!eshkp->credit) {
1982.                 money2mon(shkp, dtmp);
1983.                 eshkp->debit = 0L;
1984.                 eshkp->loan = 0L;
1985.                 You("pay that debt.");
1986.                 disp.botl = TRUE;
1987.             } else {
1988.                 dtmp -= eshkp->credit;
1989.                 eshkp->credit = 0L;
1990.                 money2mon(shkp, dtmp);
1991.                 eshkp->debit = 0L;
1992.                 eshkp->loan = 0L;
1993.                 pline("That debt is partially offset by your credit.");
1994.                 You("pay the remainder.");
1995.                 disp.botl = TRUE;
1996.             }
1997.             paid = TRUE;
1998.         }
1999.     }
2000. 
2001.     /* now check items on bill */
2002.     pay_done = TRUE; /* assume success */
2003.     if (eshkp->billct) {
2004.         int ibillct = make_itemized_bill(shkp, &ibill);
2005. 
2006.         if (!pay_billed_items(shkp, ibillct, ibill, stashed_gold, &paid))
2007.             pay_done = FALSE; /* skip thank you message */
2008.     }
2009. 
2010.     /* {mute shk,deaf hero}-aware thank you message */
2011.     if (pay_done && !ANGRY(shkp) && paid) {
2012.         if (!Deaf && !muteshk(shkp)) {
2013.             SetVoice(shkp, 0, 80, 0);
2014.             verbalize("Thank you for shopping in %s %s%s",
2015.                       s_suffix(shkname(shkp)),
2016.                       shtypes[eshkp->shoptype - SHOPBASE].name,
2017.                       !eshkp->surcharge ? "!" : ".");
2018.         } else {
2019.             pline("%s nods%s at you for shopping in %s %s%s",
2020.                   Shknam(shkp), !eshkp->surcharge ? " appreciatively" : "",
2021.                   noit_mhis(shkp), shtypes[eshkp->shoptype - SHOPBASE].name,
2022.                   !eshkp->surcharge ? "!" : ".");
2023.         }
2024.     }
2025. 
2026.     if (paid)
2027.         update_inventory();
2028.     iflags.menu_requested = FALSE; /* reset */
2029.     /* free the sortbill array used for itemized billing */
2030.     if (ibill) {
2031.         free((genericptr_t) ibill), ibill = NULL;
2032.         nhUse(ibill);
2033.     }
2034.     return paid ? ECMD_TIME : ECMD_OK;
2035. }
2036. 
2037. /* for menustyle=Traditional, choose between paying for everything (by
2038.    declining to itemize), asking item-by-item (by accepting itemization),
2039.    or switch to selecting via menu (special 'm' answer at "Itemize? [ynq m]"
2040.    prompt); for other menustyles, always select via menu;
2041.    player can use 'm' prefix before 'p' command to invert those behaviors;
2042.    once the method is chosen, actually pay for the selected items, item by
2043.    item for as long as hero has enough credit+cash */
2044. staticfn boolean
2045. pay_billed_items(
2046.     struct monst *shkp,
2047.     int ibillct,
2048.     Bill *ibill,
2049.     boolean stashed_gold,
2050.     boolean *paid_p) /* output */
2051. {
2052.     struct bill_x *bp;
2053.     struct obj *otmp;
2054.     long umoney;
2055.     boolean itemize, more_than_one;
2056.     boolean queuedpay = FALSE, via_menu;
2057.     int buy, indx, bidx, pass, iprompt, ebillct;
2058.     struct eshk *eshkp = ESHK(shkp);
2059. 
2060.     umoney = money_cnt(gi.invent);
2061.     if (!umoney && !eshkp->credit) {
2062.         You("%shave no gold or credit%s.",
2063.             stashed_gold ? "seem to " : "", *paid_p ? " left" : "");
2064.         return TRUE;
2065.     }
2066.     bp = eshkp->bill_p;
2067.     otmp = bp_to_obj(bp);
2068.     ebillct = eshkp->billct;
2069.     more_than_one = (ebillct > 1 || otmp->quan < bp->bquan
2070.                      /* note: will only get here for a single item, so
2071.                         we can deduce that it is ibill[0] */
2072.                      || ibill[0].usedup == UndisclosedContainer);
2073.     if ((umoney + eshkp->credit) < cheapest_item(ibillct, ibill)) {
2074.         You("don't have enough gold to buy%s the item%s %s.",
2075.             more_than_one ? " any of" : "", plur(more_than_one ? 2 : 1),
2076.             (ebillct > 1) ? "you've picked" : "on your bill");
2077.         if (stashed_gold)
2078.             pline("Maybe you have some gold stashed away?");
2079.         return TRUE;
2080.     }
2081. 
2082.     via_menu = (flags.menu_style != MENU_TRADITIONAL);
2083.     /* allow 'm p' to request a menu for menustyle:traditional;
2084.        for other styles, it will do the opposite; that doesn't make
2085.        a whole lot of sense for a 'request-menu' prefix, but otherwise
2086.        it would simply be redundant and there wouldn't be any way to
2087.        skip the menu when hero owes for multiple items */
2088.     if (iflags.menu_requested)
2089.         via_menu = !via_menu;
2090.     /* this will loop for a second iteration iff not initially using a
2091.        menu and player answers 'm' at custom ynq prompt */
2092.     do {
2093.         if (via_menu /*&& more_than_one*/ ) {
2094.             if (!menu_pick_pay_items(ibillct, ibill))
2095.                 return TRUE;
2096.             queuedpay = TRUE;
2097.             itemize = FALSE;
2098.             via_menu = FALSE; /* reset so that we don't loop */
2099.         } else {
2100.             iprompt = !more_than_one ? 'y'
2101.                       : yn_function("Itemized billing?", "ynq m", 'q', TRUE);
2102.             if (iprompt == 'q')
2103.                 return TRUE;
2104.             itemize = (iprompt == 'y');
2105.             via_menu = (iprompt == 'm');
2106.         }
2107.     } while (via_menu);
2108. 
2109.     /*
2110.      * 5.0:  this used to make two passes through eshkp->bill_p[],
2111.      * the first for used up items and the second for unpaid ones.
2112.      * Items which were partly used were processed on both passes.
2113.      *
2114.      * Now it makes one pass through ibill[], which has all used up
2115.      * items sorted to the beginning and unpaid ones sorted to the end.
2116.      * Partly used items have two entries for same base item, one in
2117.      * each section.
2118.      */
2119.     for (indx = 0; indx < ibillct; ++indx) {
2120.         if (queuedpay && !ibill[indx].queuedpay)
2121.             continue;
2122. 
2123.         otmp = ibill[indx].obj; /* ordinary object or outermost container */
2124.         if (ibill[indx].usedup >= KnownContainer) {
2125.             /* when successfull, buy_container() will call both
2126.                dopayobj() and update_bill(), possibly multiple times */
2127.             int boxbag_result = buy_container(shkp, indx, ibillct, ibill);
2128. 
2129.             if (boxbag_result == 0) {
2130.                 buy = PAY_BUY;
2131.             } else { /* buy_container() failed... */
2132.                 if (boxbag_result == 2)    /* ... but didn't explain why */
2133.                     verbalize("You need to remove any unpaid items from"
2134.                               " that %s and buy them separately.",
2135.                               simpleonames(otmp));
2136.                 buy = PAY_CANT;
2137.             }
2138.         } else {
2139.             bidx = ibill[indx].bidx;
2140.             bp = &eshkp->bill_p[bidx];
2141.             pass = (ibill[indx].usedup <= PartlyUsedUp) ? 0 : 1;
2142. 
2143.             buy = dopayobj(shkp, bp, otmp, pass, itemize, FALSE);
2144. 
2145.             if (buy == PAY_BUY)
2146.                 update_bill(indx, ibillct, ibill, eshkp, bp, otmp);
2147.         }
2148.         switch (buy) {
2149.         case PAY_CANT:
2150.             return FALSE;
2151.         case PAY_BROKE:
2152.             *paid_p = TRUE;
2153.             return TRUE;
2154.         case PAY_SKIP:
2155.             continue;
2156.      /* case PAY_SOME: //no longer used */
2157.         case PAY_BUY:
2158.             *paid_p = TRUE;
2159.             if (itemize || queuedpay) {
2160.                 update_inventory();
2161.                 bot();
2162.             }
2163.             break;
2164.         }
2165.     }
2166.     return TRUE;
2167. }
2168. 
2169. /* update shk's bill and augmented bill after an item has been purchased */
2170. staticfn void
2171. update_bill(
2172.     int indx, /* index into ibill[]; -1 for unpaid contained item */
2173.     int ibillct,
2174.     Bill *ibill,
2175.     struct eshk *eshkp,
2176.     struct bill_x *bp,
2177.     struct obj *paiditem)
2178. {
2179.     int j, newebillct;
2180. 
2181.     /* remove from eshkp->bill_p[] unless this was the used up portion
2182.        of partly used item (since removal would take out both; note:
2183.        can't buy PartlyIntact until PartlyUsedUp has been paid for) */
2184.     if (indx >= 0 && ibill[indx].usedup == PartlyUsedUp) {
2185.         /* 'paiditem' points to the partly intact portion still in invent or
2186.            inside a container (ibill[indx].obj points to the container) */
2187.         bp->bquan = paiditem->quan;
2188.         for (j = 0; j < ibillct; ++j)
2189.             if (ibill[j].obj == paiditem && ibill[j].usedup == PartlyIntact) {
2190.                 ibill[j].usedup = FullyIntact;
2191.                 break;
2192.             }
2193.     } else {
2194.         /* if we get here, something was bought and needs to be removed
2195.            from shop bill; if it was used up, remove it from the billobjs
2196.            list and delete it; update shop's bill by moving last bill_p[]
2197.            entry into vacated slot; also update ibill[] indices for that */
2198.         paiditem->unpaid = 0; /* clear before maybe deallocating */
2199.         if (paiditem->where == OBJ_ONBILL) {
2200.             obj_extract_self(paiditem);
2201.             dealloc_obj(paiditem);
2202.         }
2203.         newebillct = eshkp->billct - 1;
2204.         *bp = eshkp->bill_p[newebillct];
2205.         for (j = 0; j < ibillct; ++j)
2206.             if (ibill[j].bidx == newebillct)
2207.                 ibill[j].bidx = (int) (bp - eshkp->bill_p);
2208.         eshkp->billct = newebillct; /* eshkp->billct - 1 */
2209.     }
2210.     return;
2211. }
2212. 
2213. /* return 2 if used-up portion paid
2214.  *        1 if paid successfully
2215.  *        0 if not enough money
2216.  *       -1 if skip this object
2217.  *       -2 if no money/credit left
2218.  */
2219. staticfn int
2220. dopayobj(
2221.     struct monst *shkp,
2222.     struct bill_x *bp,
2223.     struct obj *obj,
2224.     int which, /* 0 => used-up item, 1 => other (unpaid or lost) */
2225.     boolean itemize,
2226.     boolean unseen)
2227. {
2228.     long ltmp, quan, save_quan;
2229.     int buy;
2230.     boolean consumed = (which == 0);
2231. 
2232.     if (!obj->unpaid && !bp->useup
2233.         && !(Has_contents(obj) && unpaid_cost(obj, COST_CONTENTS))) {
2234.         impossible("Paid object on bill??");
2235.         return PAY_BUY;
2236.     }
2237.     if (itemize && insufficient_funds(shkp, obj, 0L)) {
2238.         return PAY_BROKE;
2239.     }
2240.     /* we may need to temporarily adjust the object, if part of the
2241.        original quantity has been used up but part remains unpaid; [note:
2242.        this predates 'ibill[]' and feels redundant but still works] */
2243.     save_quan = obj->quan;
2244.     if (consumed) {
2245.         /* either completely used up (simple), or split needed */
2246.         quan = bp->bquan;
2247.         if (quan > obj->quan) /* difference is amount used up */
2248.             quan -= obj->quan;
2249.     } else {
2250.         /* dealing with ordinary unpaid item */
2251.         quan = obj->quan;
2252.     }
2253.     ltmp = bp->price * quan;
2254. 
2255.     obj->quan = quan;        /* to be used by doname() */
2256.     iflags.suppress_price++; /* affects containers */
2257.     buy = PAY_BUY; /* flag; if changed then return early */
2258. 
2259.     if (itemize) {
2260.         char qbuf[BUFSZ], qsfx[BUFSZ];
2261. 
2262.         /*
2263.          * TODO:
2264.          *  This should also accept 'a' and 'q' to end itemized paying:
2265.          *  'a' to buy the rest without asking, 'q' to just stop.
2266.          */
2267. 
2268.         Sprintf(qsfx, " for %ld %s.  Pay?", ltmp, currency(ltmp));
2269.         (void) safe_qbuf(qbuf, (char *) 0, qsfx, obj,
2270.                          (quan == 1L) ? Doname2 : doname, ansimpleoname,
2271.                          (quan == 1L) ? "that" : "those");
2272.         if (y_n(qbuf) == 'n') {
2273.             buy = PAY_SKIP;                         /* don't want to buy */
2274.         }
2275.     } /* itemize */
2276. 
2277.     if (quan < bp->bquan && !consumed) { /* partly used goods */
2278.         /* shk won't sell the intact portion until the used up portion has
2279.            been paid for (once it has been, bp->bquan will match quan) */
2280.         reject_purchase(shkp, obj, bp->bquan);
2281.         buy = PAY_SKIP;
2282.     }
2283.     if (buy == PAY_BUY && insufficient_funds(shkp, obj, ltmp)) {
2284.         buy = itemize ? PAY_SKIP : PAY_CANT;
2285.     }
2286. 
2287.     if (buy == PAY_BUY) {
2288.         pay(ltmp, shkp);
2289.         if (!unseen)
2290.             shk_names_obj(shkp, obj,
2291.                           consumed
2292.                               ? "paid for %s at a cost of %ld gold piece%s.%s"
2293.                               : "bought %s for %ld gold piece%s.%s",
2294.                           ltmp, "");
2295.     }
2296. 
2297.     /* restore obj to original state */
2298.     obj->quan = save_quan; /* restore original count */
2299.     iflags.suppress_price--;
2300. 
2301.     return buy;
2302. }
2303. 
2304. /* pay for the unpaid contents of a container without itemizing,
2305.    and for the container itself if it is unpaid too;
2306.    returns 0==successfully bought; 1==rejected, message given here;
2307.    2=rejected, caller should issue message */
2308. staticfn int
2309. buy_container(
2310.     struct monst *shkp,
2311.     int indx,
2312.     int ibillct,
2313.     Bill *ibill)
2314. {
2315.     unsigned boid, boids[BILLSZ];
2316.     int i, j, buy, buycount = 0, boidsct = 0;
2317.     struct eshk *eshkp = ESHK(shkp);
2318.     int ebillct = eshkp->billct;
2319.     struct bill_x *bp;
2320.     struct obj *otmp, *otop,
2321.                *container = ibill[indx].obj;
2322.     unsigned unpaidcontainer = container->unpaid;
2323.     long totalcost = ibill[indx].cost;
2324.     boolean sightunseen = ibill[indx].usedup == UndisclosedContainer
2325.                           /* give feedback just for container+contents rather
2326.                              than for individiual contents even when those
2327.                              contents are known */
2328.                           || ibill[indx].usedup == KnownContainer;
2329. 
2330.     /* check for no-gold first, then for not-enough-gold; feedback is
2331.        different for the two cases */
2332.     if (insufficient_funds(shkp, container, 0L)
2333.         || insufficient_funds(shkp, container, totalcost))
2334.         return 1; /* message given by insufficent_funds() */
2335. 
2336.     /* check for partly intact portion of a not-yet-paid partly used item */
2337.     for (i = 0; i < ebillct; ++i) {
2338.         bp = &eshkp->bill_p[i];
2339.         otmp = bp_to_obj(bp); /* ibill[bidx].obj is the container */
2340.         if (!otmp) {
2341.             impossible("Can't find contained item on shop bill (#%d).",
2342.                        bp->bo_id);
2343.             return 2; /* failure; have caller give a generic message */
2344.         }
2345.         if (otmp->where != OBJ_CONTAINED && !Has_contents(otmp))
2346.             continue;
2347.         /* otmp is contained, but possibly inside a different container */
2348.         for (otop = otmp; otop->where == OBJ_CONTAINED;
2349.              otop = otop->ocontainer)
2350.             continue; /* where==OBJ_CONTAINED loop */
2351.         if (otop != container)
2352.             continue; /* 'i' loop */
2353.         /* now check for partly intact portion of partly used item */
2354.         if (otmp->quan < bp->bquan) {
2355.             reject_purchase(shkp, otmp, bp->bquan);
2356.             return 1; /* message given by reject_purchase() */
2357.         }
2358.         /* record this for the second pass; unless it's the container--that
2359.            will be deferred until after the loop so that it will be last */
2360.         if (bp->bo_id != container->o_id)
2361.             boids[boidsct++] = bp->bo_id;
2362.     }
2363.     if (unpaidcontainer)
2364.         boids[boidsct++] = container->o_id;
2365. 
2366.     /* now make the actual purchasing pass; we've collected a set of
2367.        o_id values in order to avoid traversing the shk's bill while it
2368.        undergoes updates */
2369.     for (j = 0; j < boidsct; ++j) {
2370.         boid = boids[j];
2371.         for (i = 0, bp = eshkp->bill_p; i < ebillct; ++i, ++bp)
2372.             if (bp->bo_id == boid)
2373.                 break;
2374.         if (i == ebillct) {
2375.             impossible("Buying %s contents: item #%u disappeared from bill.",
2376.                        simpleonames(container), boid);
2377.             return 2;
2378.         }
2379.         otmp = bp_to_obj(bp);
2380. 
2381.         buy = dopayobj(shkp, bp, otmp, 1, FALSE, sightunseen);
2382.         if (buy != PAY_BUY) {
2383.             impossible("Buying %s contents failed unexpectedly (#%u %d).",
2384.                        simpleonames(container), otmp->o_id, buy);
2385.             continue;
2386.         }
2387.         /* [updating cost here is not necessary but useful when debugging] */
2388.         ibill[indx].cost -= (bp->price * bp->bquan); /* update container */
2389.         update_bill((boid == container->o_id) ? indx : -1,
2390.                     ibillct, ibill, eshkp, bp, otmp);
2391.         ++buycount;
2392.     }
2393.     if (buycount && sightunseen) {
2394.         /* if the container was unpaid, the hero has just purchased it;
2395.            normally paydoname()--called by shk_names_obj()--would give
2396.            "contents of your <container>" when it's hero-owned but we
2397.            want it to reflect container's state before purchase;
2398.            since paydoname() isn't called for no_charge items, we use
2399.            obj->no_charge as a hack to avoid that phrasing in favor of
2400.            "a/an <container> and its contents"; temporarily set
2401.            obj->unpaid to reflect the before-purchase state too */
2402.         if (unpaidcontainer)
2403.             container->unpaid = container->no_charge = 1;
2404.         shk_names_obj(shkp, container,
2405.                       "bought %s for %ld gold piece%s.%s",
2406.                       totalcost, "");
2407.         container->unpaid = container->no_charge = 0;
2408.     }
2409. 
2410.     return buycount ? 0 : 2; /* we don't expect buycount to be 0 */
2411. }
2412. 
2413. /* called if an item on shop bill is partly used up and partly intact and
2414.    player tries to buy the intact portion before paying for used up portion
2415.    (not actually very effective since player can just drop the unpaid
2416.    portion then pick it back up to have it get its own distinct bill entry;
2417.    the former partly used up portion becomes a fully used up separate item) */
2418. staticfn void
2419. reject_purchase(
2420.     struct monst *shkp,
2421.     struct obj *obj,
2422.     long billed_quan)
2423. {
2424.     long intact_quan = obj->quan;
2425. 
2426.     assert(intact_quan < billed_quan);
2427.     /* temporarily change obj to refer to the used up portion */
2428.     obj->quan = billed_quan - intact_quan;
2429.     if (!Deaf && !muteshk(shkp)) {
2430.         char which[BUFSZ];
2431. 
2432.         if (obj->where == OBJ_CONTAINED)
2433.             Snprintf(which, sizeof which, "the one%s in %s",
2434.                      plur(intact_quan), thesimpleoname(obj->ocontainer));
2435.         else
2436.             Sprintf(which, "%s", (intact_quan > 1L) ? "these" : "this one");
2437. 
2438.         SetVoice(shkp, 0, 80, 0);
2439.         verbalize("%s for the other %s before buying %s.",
2440.                   ANGRY(shkp) ? "Pay" : "Please pay",
2441.                   simpleonames(obj), /* short name suffices */
2442.                   which);
2443.     } else {
2444.         pline("%s %s%s your bill for the other %s first.",
2445.               Shknam(shkp),
2446.               ANGRY(shkp) ? "angrily " : "",
2447.               nolimbs(shkp->data) ? "motions to" : "points out",
2448.               simpleonames(obj));
2449.     }
2450.     obj->quan = intact_quan;
2451. }
2452. 
2453. /* gold+credit checking+feedback common to dopayobj() and buy_container() */
2454. staticfn boolean
2455. insufficient_funds(
2456.     struct monst *shkp,
2457.     struct obj *item,
2458.     long cost) /* 0: check for no-gold; >0: check for specified amount */
2459. {
2460.     long stashed_gold;
2461.     long umoney = money_cnt(gi.invent),
2462.          ecredit = ESHK(shkp)->credit;
2463. 
2464.     /* dopayobj() checks for no-gold early and not-enough-gold later;
2465.        buy_container() checks for both early but uses separate calls to us */
2466.     if (!cost && umoney + ecredit == 0L) {
2467.         stashed_gold = hidden_gold(TRUE);
2468.         You("%shave no gold or credit left.",
2469.             (stashed_gold > 0) ? "seem to " : "");
2470.         return TRUE;
2471.     }
2472.     if (cost && umoney + ecredit < cost) {
2473.         stashed_gold = hidden_gold(TRUE);
2474.         You("don't%s have gold%s enough to pay for %s.",
2475.             (stashed_gold > 0L) ? " seem to" : "",
2476.             (ecredit > 0L) ? " or credit" : "",
2477.             paydoname(item));
2478.         return TRUE;
2479.     }
2480.     return FALSE;
2481. }
2482. 
2483. /* routine called after dying (or quitting) */
2484. boolean
2485. paybill(
2486.     int croaked, /* -1: escaped dungeon; 0: quit; 1: died */
2487.     boolean silently) /* maybe avoid messages */
2488. {
2489.     struct monst *mtmp, *mtmp2, *firstshk, *resident, *creditor, *hostile,
2490.         *localshk;
2491.     struct eshk *eshkp;
2492.     boolean taken = FALSE, local;
2493.     int numsk = 0;
2494. 
2495.     /* if we escaped from the dungeon, shopkeepers can't reach us;
2496.        shops don't occur on level 1, but this could happen if hero
2497.        level teleports out of the dungeon and manages not to die */
2498.     if (croaked < 0)
2499.         return FALSE;
2500.     /* [should probably also return false when dead hero has been
2501.         petrified since shk shouldn't be able to grab inventory
2502.         which has been shut inside a statue] */
2503. 
2504.     /* this is where inventory will end up if any shk takes it */
2505.     gr.repo.location.x = gr.repo.location.y = 0;
2506.     gr.repo.shopkeeper = 0;
2507. 
2508.     /*
2509.      * Scan all shopkeepers on the level, to prioritize them:
2510.      * 1) keeper of shop hero is inside and who is owed money,
2511.      * 2) keeper of shop hero is inside who isn't owed any money,
2512.      * 3) other shk who is owed money, 4) other shk who is angry,
2513.      * 5) any shk local to this level, and if none is found,
2514.      * 6) first shk on monster list (last resort; unlikely, since
2515.      * any nonlocal shk will probably be in the owed category
2516.      * and almost certainly be in the angry category).
2517.      */
2518.     resident = creditor = hostile = localshk = (struct monst *) 0;
2519.     for (mtmp = next_shkp(fmon, FALSE); mtmp;
2520.          mtmp = next_shkp(mtmp2, FALSE)) {
2521.         mtmp2 = mtmp->nmon;
2522.         eshkp = ESHK(mtmp);
2523.         local = on_level(&eshkp->shoplevel, &u.uz);
2524.         if (local && strchr(u.ushops, eshkp->shoproom)) {
2525.             /* inside this shk's shop [there might be more than one
2526.                resident shk if hero is standing in a breech of a shared
2527.                wall, so give priority to one who's also owed money] */
2528.             if (!resident || eshkp->billct || eshkp->debit || eshkp->robbed)
2529.                 resident = mtmp;
2530.         } else if (eshkp->billct || eshkp->debit || eshkp->robbed) {
2531.             /* owe this shopkeeper money (might also owe others) */
2532.             if (!creditor)
2533.                 creditor = mtmp;
2534.         } else if (eshkp->following || ANGRY(mtmp)) {
2535.             /* this shopkeeper is antagonistic (others might be too) */
2536.             if (!hostile)
2537.                 hostile = mtmp;
2538.         } else if (local) {
2539.             /* this shopkeeper's shop is on current level */
2540.             if (!localshk)
2541.                 localshk = mtmp;
2542.         }
2543.     }
2544. 
2545.     /* give highest priority shopkeeper first crack */
2546.     firstshk = resident ? resident
2547.                         : creditor ? creditor
2548.                                    : hostile ? hostile
2549.                                              : localshk;
2550.     if (firstshk) {
2551.         numsk++;
2552.         taken = inherits(firstshk, numsk, croaked, silently);
2553.     }
2554. 
2555.     /* now handle the rest */
2556.     for (mtmp = next_shkp(fmon, FALSE); mtmp;
2557.          mtmp = next_shkp(mtmp2, FALSE)) {
2558.         mtmp2 = mtmp->nmon;
2559.         eshkp = ESHK(mtmp);
2560.         local = on_level(&eshkp->shoplevel, &u.uz);
2561.         if (mtmp != firstshk) {
2562.             numsk++;
2563.             taken |= inherits(mtmp, numsk, croaked, silently);
2564.         }
2565.         /* for bones: we don't want a shopless shk around */
2566.         if (!local)
2567.             mongone(mtmp);
2568.     }
2569.     return taken;
2570. }
2571. 
2572. /* decide whether a shopkeeper will take possession of dying hero's invent;
2573.    when this returns True, it should call set_repo_loc() before returning;
2574.    when it returns False, it should not do such because that might have
2575.    already been called for some shopkeeper */
2576. staticfn boolean
2577. inherits(
2578.     struct monst *shkp,
2579.     int numsk,
2580.     int croaked,
2581.     boolean silently)
2582. {
2583.     long loss = 0L;
2584.     long umoney;
2585.     struct eshk *eshkp = ESHK(shkp);
2586.     boolean take = FALSE, taken = FALSE,
2587.             uinshop = (strchr(u.ushops, eshkp->shoproom) != (char *) 0);
2588.     char takes[BUFSZ];
2589. 
2590.     /* not strictly consistent; affects messages and prevents next player
2591.        (if bones are saved) from blundering into or being ambushed by an
2592.        invisible shopkeeper */
2593.     shkp->minvis = shkp->perminvis = 0;
2594. 
2595.     /* The simplifying principle is that first-come
2596.        already took everything you had. */
2597.     if (numsk > 1) {
2598.         if (cansee(shkp->mx, shkp->my) && croaked && !silently) {
2599.             takes[0] = '\0';
2600.             if (has_head(shkp->data) && !rn2(2))
2601.                 Sprintf(takes, ", shakes %s %s,", noit_mhis(shkp),
2602.                         mbodypart(shkp, HEAD));
2603.             pline("%s %slooks at your corpse%s and %s.", Shknam(shkp),
2604.                   helpless(shkp) ? "wakes up, " : "",
2605.                   takes, !inhishop(shkp) ? "disappears" : "sighs");
2606.         }
2607.         taken = uinshop;
2608.         goto skip;
2609.     }
2610. 
2611.     /* get one case out of the way: you die in the shop, the
2612.        shopkeeper is peaceful, nothing stolen, nothing owed */
2613.     if (uinshop && inhishop(shkp) && !eshkp->billct
2614.         && !eshkp->robbed && !eshkp->debit && NOTANGRY(shkp)
2615.         && !eshkp->following && u.ugrave_arise < LOW_PM) {
2616.         taken = (gi.invent != 0);
2617.         if (taken && !silently)
2618.             pline("%s gratefully inherits all your possessions.",
2619.                   Shknam(shkp));
2620.         goto clear;
2621.     }
2622. 
2623.     if (eshkp->billct || eshkp->debit || eshkp->robbed) {
2624.         if (uinshop && inhishop(shkp))
2625.             loss = addupbill(shkp) + eshkp->debit;
2626.         if (loss < eshkp->robbed)
2627.             loss = eshkp->robbed;
2628.         take = TRUE;
2629.     }
2630. 
2631.     if (eshkp->following || ANGRY(shkp) || take) {
2632.         if (!gi.invent)
2633.             goto skip;
2634.         umoney = money_cnt(gi.invent);
2635.         takes[0] = '\0';
2636.         if (helpless(shkp))
2637.             Strcat(takes, "wakes up and ");
2638.         if (!m_next2u(shkp))
2639.             Strcat(takes, "comes and ");
2640.         Strcat(takes, "takes");
2641. 
2642.         if (loss > umoney || !loss || uinshop) {
2643.             eshkp->robbed -= umoney;
2644.             if (eshkp->robbed < 0L)
2645.                 eshkp->robbed = 0L;
2646.             if (umoney > 0L) {
2647.                 money2mon(shkp, umoney);
2648.                 disp.botl = TRUE;
2649.             }
2650.             if (!silently)
2651.                 pline("%s %s all your possessions.", Shknam(shkp), takes);
2652.             taken = TRUE;
2653.         } else {
2654.             money2mon(shkp, loss);
2655.             disp.botl = TRUE;
2656.             if (!silently)
2657.                 pline("%s %s the %ld %s %sowed %s.", Shknam(shkp),
2658.                       takes, loss, currency(loss),
2659.                       strncmp(eshkp->customer, svp.plname, PL_NSIZ) ? ""
2660.                         : "you ",
2661.                       noit_mhim(shkp));
2662.             /* shopkeeper has now been paid in full */
2663.             pacify_shk(shkp, FALSE);
2664.             eshkp->following = 0;
2665.             eshkp->robbed = 0L;
2666.         }
2667.  skip:
2668.         /* in case we create bones */
2669.         rouse_shk(shkp, FALSE); /* wake up */
2670.         if (!inhishop(shkp))
2671.             home_shk(shkp, FALSE);
2672.     }
2673.  clear:
2674.     setpaid(shkp); /* clear this shk's bill */
2675.     /* where to put player's invent (after disclosure) */
2676.     if (taken)
2677.         set_repo_loc(shkp);
2678.     return taken;
2679. }
2680. 
2681. staticfn void
2682. set_repo_loc(struct monst *shkp)
2683. {
2684.     coordxy ox, oy;
2685.     struct eshk *eshkp = ESHK(shkp);
2686. 
2687.     /* when multiple shopkeepers are present, we might get called more
2688.        than once; don't override previous setting */
2689.     if (gr.repo.shopkeeper)
2690.         return;
2691. 
2692.     /* savebones() sets u.ux,u.uy to 0,0 to remove hero from map but that
2693.        takes place after finish_paybill() has been called so we expect
2694.        u.ux,u.uy to be valid; however, there has been a report of
2695.        impossible "place_object: \"<item>\" off map <0,0>" when hero died
2696.        in a gap in a shop's wall (in Minetown, so multiple shopkeepers in
2697.        play, and prior to adding 'if (gr.repo.shopkeeper) return' above) */
2698.     ox = u.ux ? u.ux : u.ux0;
2699.     oy = u.ux ? u.uy : u.uy0; /* [testing u.ux when setting oy is correct] */
2700. 
2701.     /* if you're not in this shk's shop room, or if you're in its doorway
2702.        or entry spot or one of its walls (temporary gap or Passes_walls),
2703.        then your gear gets dumped all the way inside */
2704.     if (!strchr(u.ushops, eshkp->shoproom) || costly_adjacent(shkp, ox, oy)) {
2705.         /* shk.x,shk.y is the position immediately in front of the door;
2706.            move in one more space */
2707.         ox = eshkp->shk.x;
2708.         oy = eshkp->shk.y;
2709.         ox += sgn(ox - eshkp->shd.x);
2710.         oy += sgn(oy - eshkp->shd.y);
2711.     } else {
2712.         ; /* already inside this shk's shop so use ox,oy as-is */
2713.     }
2714.     /* finish_paybill will deposit invent here */
2715.     gr.repo.location.x = ox;
2716.     gr.repo.location.y = oy;
2717.     gr.repo.shopkeeper = shkp;
2718. }
2719. 
2720. /* called at game exit, after inventory disclosure but before making bones;
2721.    shouldn't issue any messages */
2722. void
2723. finish_paybill(void)
2724. {
2725.     struct monst *shkp = gr.repo.shopkeeper;
2726.     int ox = gr.repo.location.x, oy = gr.repo.location.y;
2727. 
2728.     /*
2729.      * If set_repo_loc() didn't get called for some reason (good luck
2730.      * untangling inherits() to figure out why...), ox,oy will be 0,0
2731.      * and shkp will be Null.  Fix coordinates if that happens.
2732.      */
2733. 
2734.     if (!isok(ox, oy)) {
2735.         /* this used to be suppressed as "don't bother" (too late to matter)
2736.            but that led to "place_object: \"<item>\" off map <0,0>" warning */
2737.         if (shkp)
2738.             impossible("finish_paybill: bad location <%d,%d>.", ox, oy);
2739.         /* force a valid location */
2740.         ox = u.ux ? u.ux : u.ux0;
2741.         oy = u.ux ? u.uy : u.uy0; /* [note: testing u.ux when setting oy
2742.                                    *  is correct here]*/
2743.     }
2744.     /* normally done by savebones(), but that's too late in this case */
2745.     unleash_all();
2746.     /* if hero has any gold left, take it into shopkeeper's possession */
2747.     if (shkp) {
2748.         long umoney = money_cnt(gi.invent);
2749. 
2750.         if (umoney)
2751.             money2mon(shkp, umoney);
2752.     }
2753.     /* transfer rest of the character's inventory to the shop floor */
2754.     drop_upon_death((struct monst *) 0, (struct obj *) 0, ox, oy);
2755. }
2756. 
2757. /* find obj on one of the lists */
2758. staticfn struct obj *
2759. bp_to_obj(struct bill_x *bp)
2760. {
2761.     struct obj *obj;
2762.     unsigned int id = bp->bo_id;
2763. 
2764.     if (bp->useup)
2765.         obj = o_on(id, gb.billobjs);
2766.     else
2767.         obj = find_oid(id);
2768.     return obj;
2769. }
2770. 
2771. /*
2772.  * Look for o_id on all lists but billobj.  Return obj or NULL if not found.
2773.  * Its OK for restore_timers() to call this function, there should not
2774.  * be any timeouts on the gb.billobjs chain.
2775.  */
2776. struct obj *
2777. find_oid(unsigned int id)
2778. {
2779.     struct obj *obj;
2780.     struct monst *mon, *mmtmp[3];
2781.     int i;
2782. 
2783.     /* first check various obj lists directly */
2784.     if ((obj = o_on(id, gi.invent)) != 0)
2785.         return obj;
2786.     if ((obj = o_on(id, fobj)) != 0)
2787.         return obj;
2788.     if ((obj = o_on(id, svl.level.buriedobjlist)) != 0)
2789.         return obj;
2790.     if ((obj = o_on(id, gm.migrating_objs)) != 0)
2791.         return obj;
2792. 
2793.     /* not found yet; check inventory for members of various monst lists */
2794.     mmtmp[0] = fmon;
2795.     mmtmp[1] = gm.migrating_mons;
2796.     mmtmp[2] = gm.mydogs; /* for use during level changes */
2797.     for (i = 0; i < 3; i++)
2798.         for (mon = mmtmp[i]; mon; mon = mon->nmon)
2799.             if ((obj = o_on(id, mon->minvent)) != 0)
2800.                 return obj;
2801. 
2802.     /* not found at all */
2803.     return (struct obj *) 0;
2804. }
2805. 
2806. /* Returns the price of an arbitrary item in the shop,
2807.    0 if the item doesn't belong to a shopkeeper or hero is not in the shop. */
2808. long
2809. get_cost_of_shop_item(
2810.     struct obj *obj,
2811.     int *nochrg) /* alternate return value: 1: no charge, 0: shop owned,
2812.                   * -1: not in a shop (so don't format as "no charge") */
2813. {
2814.     struct monst *shkp;
2815.     struct obj *top;
2816.     coordxy x, y;
2817.     boolean freespot;
2818.     long cost = 0L;
2819. 
2820.     *nochrg = -1; /* assume 'not applicable' */
2821.     if (*u.ushops && obj->oclass != COIN_CLASS
2822.         && obj != uball && obj != uchain
2823.         && get_obj_location(obj, &x, &y, CONTAINED_TOO)
2824.         && *in_rooms(x, y, SHOPBASE) == *u.ushops
2825.         && (shkp = shop_keeper(inside_shop(x, y))) != 0 && inhishop(shkp)) {
2826.         for (top = obj; top->where == OBJ_CONTAINED; top = top->ocontainer)
2827.             continue;
2828.         freespot = (top->where == OBJ_FLOOR
2829.                     && x == ESHK(shkp)->shk.x && y == ESHK(shkp)->shk.y);
2830.         /* no_charge is only set for floor items inside shop proper;
2831.            items on freespot are implicitly 'no charge' */
2832.         *nochrg = (top->where == OBJ_FLOOR && (obj->no_charge || freespot));
2833. 
2834.         if (carried(top) ? (int) obj->unpaid : !*nochrg) {
2835.             long per_unit_cost = get_cost(obj, shkp);
2836. 
2837.             cost = get_pricing_units(obj) * per_unit_cost;
2838.         }
2839.         if (Has_contents(obj) && !freespot)
2840.             cost += contained_cost(obj, shkp, 0L, FALSE, TRUE);
2841.     }
2842.     return cost;
2843. }
2844. 
2845. staticfn long
2846. get_pricing_units(struct obj *obj)
2847. {
2848.     long units = obj->quan;
2849. 
2850.     if (obj->globby) {
2851.         /* globs must be sold by weight not by volume */
2852.         long unit_weight = (long) objects[obj->otyp].oc_weight,
2853.              wt = (obj->owt > 0) ? (long) obj->owt : (long) weight(obj);
2854. 
2855.         if (unit_weight)
2856.             units = (wt + unit_weight - 1L) / unit_weight;
2857.     }
2858.     return units;
2859. }
2860. 
2861. /* decide whether to apply a surcharge (or hypothetically, a discount) to obj
2862.    if it had ID number 'oid'; returns 1: increase, 0: normal, -1: decrease */
2863. int
2864. oid_price_adjustment(struct obj *obj, unsigned int oid)
2865. {
2866.     int res = 0, otyp = obj->otyp;
2867. 
2868.     if (!(obj->dknown && objects[otyp].oc_name_known)
2869.         && (obj->oclass != GEM_CLASS || objects[otyp].oc_material != GLASS)) {
2870.         res = ((oid % 4) == 0); /* id%4 ==0 -> +1, ==1..3 -> 0 */
2871.     }
2872.     return res;
2873. }
2874. 
2875. /* calculate the value that the shk will charge for [one of] an object */
2876. staticfn long
2877. get_cost(
2878.     struct obj *obj,
2879.     struct monst *shkp) /* if angry, impose a surcharge */
2880. {
2881.     /*
2882.      * FIXME:
2883.      *  If this obj is already on the shop's bill, use the price which
2884.      *  has been set there.  Otherwise, the amount could be different
2885.      *  (if billed while undiscovered and now become discovered or
2886.      *  hero's charisma and/or visible worn gear have changed).
2887.      */
2888.     long tmp = getprice(obj, FALSE),
2889.          /* used to perform a single calculation even when multiple
2890.             adjustments (unID'd, dunce/tourist, charisma) are made */
2891.         multiplier = 1L, divisor = 1L;
2892. 
2893.     if (!tmp)
2894.         tmp = 5L;
2895.     /* shopkeeper may notice if the player isn't very knowledgeable -
2896.        especially when gem prices are concerned */
2897.     if (!obj->dknown || !objects[obj->otyp].oc_name_known) {
2898.         if (obj->oclass == GEM_CLASS
2899.             && objects[obj->otyp].oc_material == GLASS) {
2900.             int i;
2901.             /* get a value that's 'random' from game to game, but the
2902.                same within the same game */
2903.             boolean pseudorand =
2904.                 (((int) ubirthday % obj->otyp) >= obj->otyp / 2);
2905. 
2906.             /* all gems are priced high - real or not */
2907.             switch (obj->otyp - FIRST_GLASS_GEM) {
2908.             case 0: /* white */
2909.                 i = pseudorand ? DIAMOND : OPAL;
2910.                 break;
2911.             case 1: /* blue */
2912.                 i = pseudorand ? SAPPHIRE : AQUAMARINE;
2913.                 break;
2914.             case 2: /* red */
2915.                 i = pseudorand ? RUBY : JASPER;
2916.                 break;
2917.             case 3: /* yellowish brown */
2918.                 i = pseudorand ? AMBER : TOPAZ;
2919.                 break;
2920.             case 4: /* orange */
2921.                 i = pseudorand ? JACINTH : AGATE;
2922.                 break;
2923.             case 5: /* yellow */
2924.                 i = pseudorand ? CITRINE : CHRYSOBERYL;
2925.                 break;
2926.             case 6: /* black */
2927.                 i = pseudorand ? BLACK_OPAL : JET;
2928.                 break;
2929.             case 7: /* green */
2930.                 i = pseudorand ? EMERALD : JADE;
2931.                 break;
2932.             case 8: /* violet */
2933.                 i = pseudorand ? AMETHYST : FLUORITE;
2934.                 break;
2935.             default:
2936.                 impossible("bad glass gem %d?", obj->otyp);
2937.                 i = STRANGE_OBJECT;
2938.                 break;
2939.             }
2940.             tmp = (long) objects[i].oc_cost;
2941.         } else if (oid_price_adjustment(obj, obj->o_id) > 0) {
2942.             /* unid'd, arbitrarily impose surcharge: tmp *= 4/3 */
2943.             multiplier *= 4L;
2944.             divisor *= 3L;
2945.         }
2946.     }
2947.     if (uarmh && uarmh->otyp == DUNCE_CAP)
2948.         multiplier *= 4L, divisor *= 3L;
2949.     else if ((Role_if(PM_TOURIST) && u.ulevel < (MAXULEV / 2))
2950.              || (uarmu && !uarm && !uarmc)) /* touristy shirt visible */
2951.         multiplier *= 4L, divisor *= 3L;
2952. 
2953.     if (ACURR(A_CHA) > 18)
2954.         divisor *= 2L;
2955.     else if (ACURR(A_CHA) == 18)
2956.         multiplier *= 2L, divisor *= 3L;
2957.     else if (ACURR(A_CHA) >= 16)
2958.         multiplier *= 3L, divisor *= 4L;
2959.     else if (ACURR(A_CHA) <= 5)
2960.         multiplier *= 2L;
2961.     else if (ACURR(A_CHA) <= 7)
2962.         multiplier *= 3L, divisor *= 2L;
2963.     else if (ACURR(A_CHA) <= 10)
2964.         multiplier *= 4L, divisor *= 3L;
2965. 
2966.     /* tmp = (tmp * multiplier) / divisor [with roundoff tweak] */
2967.     tmp *= multiplier;
2968.     if (divisor > 1L) {
2969.         /* tmp = (((tmp * 10) / divisor) + 5) / 10 */
2970.         tmp *= 10L;
2971.         tmp /= divisor;
2972.         tmp += 5L;
2973.         tmp /= 10L;
2974.     }
2975. 
2976.     if (tmp <= 0L)
2977.         tmp = 1L;
2978.     /* the artifact prices in artilist[] are also used as a score bonus;
2979.        inflate their shop price here without affecting score calculation */
2980.     if (obj->oartifact)
2981.         tmp *= 4L;
2982. 
2983.     /* anger surcharge should match rile_shk's, so we do it separately
2984.        from the multiplier/divisor calculation */
2985.     if (shkp && ESHK(shkp)->surcharge)
2986.         tmp += (tmp + 2L) / 3L;
2987.     return tmp;
2988. }
2989. 
2990. /* returns the price of a container's content.  the price
2991.  * of the "top" container is added in the calling functions.
2992.  * a different price quoted for selling as vs. buying.
2993.  */
2994. long
2995. contained_cost(
2996.     struct obj *obj,
2997.     struct monst *shkp,
2998.     long price,
2999.     boolean usell,
3000.     boolean unpaid_only)
3001. {
3002.     struct obj *otmp, *top;
3003.     coordxy x, y;
3004.     boolean on_floor, freespot;
3005. 
3006.     for (top = obj; top->where == OBJ_CONTAINED; top = top->ocontainer)
3007.         continue;
3008.     /* pick_obj() removes item from floor, adds it to shop bill, then
3009.        puts it in inventory; behave as if it is still on the floor
3010.        during the add-to-bill portion of that situation */
3011.     on_floor = (top->where == OBJ_FLOOR || top->where == OBJ_FREE);
3012.     if (top->where == OBJ_FREE || !get_obj_location(top, &x, &y, 0))
3013.         x = u.ux, y = u.uy;
3014.     freespot = (on_floor && x == ESHK(shkp)->shk.x && y == ESHK(shkp)->shk.y);
3015. 
3016.     /* price of contained objects; "top" container handled by caller */
3017.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3018.         if (otmp->oclass == COIN_CLASS)
3019.             continue;
3020. 
3021.         if (usell) {
3022.             if (saleable(shkp, otmp) && !otmp->unpaid
3023.                 && otmp->oclass != BALL_CLASS
3024.                 && !(otmp->oclass == FOOD_CLASS && otmp->oeaten)
3025.                 && !(Is_candle(otmp)
3026.                      && otmp->age < 20L * (long) objects[otmp->otyp].oc_cost))
3027.                 price += set_cost(otmp, shkp);
3028.         } else {
3029.             /* no_charge is only set for floor items (including
3030.                contents of floor containers) inside shop proper;
3031.                items on freespot are implicitly 'no charge' */
3032.             if (on_floor ? (!otmp->no_charge && !freespot)
3033.                          : (otmp->unpaid || !unpaid_only))
3034.                 price += get_cost(otmp, shkp) * get_pricing_units(otmp);
3035.         }
3036. 
3037.         if (Has_contents(otmp))
3038.             price = contained_cost(otmp, shkp, price, usell, unpaid_only);
3039.     }
3040. 
3041.     return price;
3042. }
3043. 
3044. /* count amount of gold inside container 'obj' and any nested containers */
3045. long
3046. contained_gold(
3047.     struct obj *obj,
3048.     boolean even_if_unknown) /* T: all gold; F: limit to known contents */
3049. {
3050.     struct obj *otmp;
3051.     long value = 0L;
3052. 
3053.     /* accumulate contained gold */
3054.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj)
3055.         if (otmp->oclass == COIN_CLASS)
3056.             value += otmp->quan;
3057.         else if (Has_contents(otmp) && (otmp->cknown || even_if_unknown))
3058.             value += contained_gold(otmp, even_if_unknown);
3059. 
3060.     return value;
3061. }
3062. 
3063. staticfn void
3064. dropped_container(
3065.     struct obj *obj,
3066.     struct monst *shkp,
3067.     boolean sale)
3068. {
3069.     struct obj *otmp;
3070. 
3071.     /* the "top" container is treated in the calling fn */
3072.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3073.         if (otmp->oclass == COIN_CLASS)
3074.             continue;
3075. 
3076.         if (!otmp->unpaid && !(sale && saleable(shkp, otmp)))
3077.             otmp->no_charge = 1;
3078. 
3079.         if (Has_contents(otmp))
3080.             dropped_container(otmp, shkp, sale);
3081.     }
3082. }
3083. 
3084. void
3085. picked_container(struct obj *obj)
3086. {
3087.     struct obj *otmp;
3088. 
3089.     /* the "top" container is treated in the calling fn */
3090.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3091.         if (otmp->oclass == COIN_CLASS)
3092.             continue;
3093. 
3094.         if (otmp->no_charge)
3095.             otmp->no_charge = 0;
3096. 
3097.         if (Has_contents(otmp))
3098.             picked_container(otmp);
3099.     }
3100. }
3101. 
3102. staticfn boolean
3103. special_stock(
3104.     struct obj *obj,
3105.     struct monst *shkp,
3106.     boolean quietly)
3107. {
3108.     /* for unique situations */
3109.     if (ESHK(shkp)->shoptype == CANDLESHOP
3110.         && obj->otyp == CANDELABRUM_OF_INVOCATION) {
3111.         if (!quietly) {
3112.             if (is_izchak(shkp, TRUE) && !u.uevent.invoked) {
3113.                 if (Deaf || muteshk(shkp)) {
3114.                     pline("%s seems %s that you want to sell that.",
3115.                           Shknam(shkp),
3116.                           (obj->spe < 7) ? "horrified" : "concerned");
3117.                 } else {
3118.                     SetVoice(shkp, 0, 80, 0);
3119.                     verbalize("No thanks, I'd hang onto that if I were you.");
3120.                     if (obj->spe < 7) {
3121.                         SetVoice(shkp, 0, 80, 0);
3122.                         verbalize(
3123.                              "You'll need %d%s candle%s to go along with it.",
3124.                                 (7 - obj->spe), (obj->spe > 0) ? " more" : "",
3125.                                   plur(7 - obj->spe));
3126.                     }
3127.                     /* [what if hero is already carrying enough candles?
3128.                        should Izchak explain how to attach them instead?] */
3129.                 }
3130.             } else {
3131.                 if (!Deaf && !muteshk(shkp)) {
3132.                     SetVoice(shkp, 0, 80, 0);
3133.                     verbalize("I won't stock that.  Take it out of here!");
3134.                 } else {
3135.                     pline("%s shakes %s %s in refusal.",
3136.                           Shknam(shkp), noit_mhis(shkp),
3137.                           mbodypart(shkp, HEAD));
3138.                 }
3139.             }
3140.         }
3141.         return TRUE;
3142.     }
3143.     return FALSE;
3144. }
3145. 
3146. /* calculate how much the shk will pay when buying [all of] an object */
3147. staticfn long
3148. set_cost(struct obj *obj, struct monst *shkp)
3149. {
3150.     long tmp, unit_price = getprice(obj, TRUE), multiplier = 1L, divisor = 1L;
3151. 
3152.     tmp = get_pricing_units(obj) * unit_price;
3153. 
3154.     if (uarmh && uarmh->otyp == DUNCE_CAP)
3155.         divisor *= 3L;
3156.     else if ((Role_if(PM_TOURIST) && u.ulevel < (MAXULEV / 2))
3157.              || (uarmu && !uarm && !uarmc)) /* touristy shirt visible */
3158.         divisor *= 3L;
3159.     else
3160.         divisor *= 2L;
3161. 
3162.     /* shopkeeper may notice if the player isn't very knowledgeable -
3163.        especially when gem prices are concerned */
3164.     if (!obj->dknown || !objects[obj->otyp].oc_name_known) {
3165.         if (obj->oclass == GEM_CLASS) {
3166.             /* different shop keepers give different prices */
3167.             if (objects[obj->otyp].oc_material == GEMSTONE
3168.                 || objects[obj->otyp].oc_material == GLASS) {
3169.                 tmp = ((obj->otyp - FIRST_REAL_GEM) % (6 - shkp->m_id % 3));
3170.                 tmp = (tmp + 3) * obj->quan;
3171.                 divisor = 1L;
3172.             }
3173.         } else if (tmp > 1L && !(shkp->m_id % 4))
3174.             multiplier *= 3L, divisor *= 4L;
3175.     }
3176. 
3177.     if (tmp >= 1L) {
3178.         /* [see get_cost()] */
3179.         tmp *= multiplier;
3180.         if (divisor > 1L) {
3181.             tmp *= 10L;
3182.             tmp /= divisor;
3183.             tmp += 5L;
3184.             tmp /= 10L;
3185.         }
3186.         /* avoid adjusting nonzero to zero */
3187.         if (tmp < 1L)
3188.             tmp = 1L;
3189.     }
3190. 
3191.     /* (no adjustment for angry shk here) */
3192.     return tmp;
3193. }
3194. 
3195. /* unlike alter_cost() which operates on a specific item, identifying or
3196.    forgetting a gem causes all unpaid gems of its type to change value */
3197. void
3198. gem_learned(int oindx)
3199. {
3200.     struct obj *obj;
3201.     struct monst *shkp;
3202.     struct bill_x *bp;
3203.     int ct;
3204. 
3205.     /*
3206.      * Unfortunately, shop bill doesn't have object type included,
3207.      * just obj->oid for each unpaid stack, so we have to go through
3208.      * every bill and every item on that bill and match up against
3209.      * every unpaid stack on the level....
3210.      *
3211.      * Fortunately, there's no need to catch up when changing dungeon
3212.      * levels even if we ID'd or forget some gems while gone from a
3213.      * level.  There won't be any shop bills when arriving; they were
3214.      * either paid before leaving or got treated as robbery and it's
3215.      * too late to adjust pricing.
3216.      */
3217.     for (shkp = next_shkp(fmon, TRUE); shkp;
3218.          shkp = next_shkp(shkp->nmon, TRUE)) {
3219.         ct = ESHK(shkp)->billct;
3220.         bp = ESHK(shkp)->bill_p;
3221.         while (--ct >= 0) {
3222.             obj = find_oid(bp->bo_id);
3223.             if (!obj) /* shouldn't happen */
3224.                 continue;
3225.             if ((oindx != STRANGE_OBJECT) ? (obj->otyp == oindx)
3226.                                           : (obj->oclass == GEM_CLASS))
3227.                 bp->price = get_cost(obj, shkp);
3228.             ++bp;
3229.         }
3230.     }
3231. }
3232. 
3233. /* called when an item's value has been enhanced; if it happens to be
3234.    on any shop bill, update that bill to reflect the new higher price
3235.    [if the new price drops for some reason, keep the old one in place] */
3236. void
3237. alter_cost(
3238.     struct obj *obj,
3239.     long amt) /* if 0, use regular shop pricing, otherwise force amount;
3240.                  if negative, use abs(amt) even if it's less than old cost */
3241. {
3242.     struct bill_x *bp = 0;
3243.     struct monst *shkp;
3244.     long new_price;
3245. 
3246.     for (shkp = next_shkp(fmon, TRUE); shkp; shkp = next_shkp(shkp, TRUE))
3247.         if ((bp = onbill(obj, shkp, TRUE)) != 0) {
3248.             new_price = !amt ? get_cost(obj, shkp) : (amt < 0L) ? -amt : amt;
3249.             if (new_price > bp->price || amt < 0L) {
3250.                 bp->price = new_price;
3251.                 update_inventory();
3252.             }
3253.             break; /* done */
3254.         }
3255.     return;
3256. }
3257. 
3258. /* called from doinv(invent.c) for inventory of unpaid objects */
3259. long
3260. unpaid_cost(
3261.     struct obj *unp_obj, /* known to be unpaid or contain unpaid */
3262.     uchar cost_type) /* COST_NOCONTENTS, COST_CONTENTS, or COST_SINGLEOBJ */
3263. {
3264.     struct bill_x *bp = (struct bill_x *) 0;
3265.     struct monst *shkp = 0;
3266.     char *shop;
3267.     long amt = 0L;
3268. 
3269. #if 0   /* if two shops share a wall, this might find wrong shk */
3270.     coordxy ox, oy;
3271. 
3272.     if (!get_obj_location(unp_obj, &ox, &oy, BURIED_TOO | CONTAINED_TOO))
3273.         ox = u.ux, oy = u.uy; /* (shouldn't happen) */
3274.     if ((shkp = shop_keeper(*in_rooms(ox, oy, SHOPBASE))) != 0) {
3275.         bp = onbill(unp_obj, shkp, TRUE);
3276.     } else {
3277.         /* didn't find shk?  try searching bills */
3278.         for (shkp = next_shkp(fmon, TRUE); shkp;
3279.              shkp = next_shkp(shkp->nmon, TRUE))
3280.             if ((bp = onbill(unp_obj, shkp, TRUE)) != 0)
3281.                 break;
3282.     }
3283. #endif
3284.     for (shop = u.ushops; *shop; shop++) {
3285.         if ((shkp = shop_keeper(*shop)) != 0) {
3286.             if ((bp = onbill(unp_obj, shkp, TRUE))) {
3287.                 amt = bp->price;
3288.                 if (cost_type != COST_SINGLEOBJ) {
3289.                     /* use quan rather than get_pricing_units -- glob weight
3290.                        should already be factored into bp->price */
3291.                     amt *= unp_obj->quan;
3292.                 }
3293.             }
3294.             if (cost_type == COST_CONTENTS && Has_contents(unp_obj))
3295.                 amt = contained_cost(unp_obj, shkp, amt, FALSE, TRUE);
3296.             if (bp || (!unp_obj->unpaid && amt))
3297.                 break;
3298.         }
3299.     }
3300. 
3301.     /* onbill() gave no message if unexpected problem occurred */
3302.     if (!shkp || (unp_obj->unpaid && !bp))
3303.         impossible("unpaid_cost: object wasn't on any bill.");
3304.     return amt;
3305. }
3306. 
3307. /* add 'obj' to 'shkp's bill */
3308. staticfn void
3309. add_one_tobill(
3310.     struct obj *obj,
3311.     boolean dummy, /* True: obj is used up so goes on bill differently */
3312.     struct monst *shkp)
3313. {
3314.     struct eshk *eshkp;
3315.     struct bill_x *bp;
3316.     int bct;
3317.     boolean unbilled = FALSE;
3318. 
3319.     eshkp = ESHK(shkp);
3320.     /* normally bill_p gets set up whenever you enter the shop, but obj
3321.        might be going onto the bill because hero just snagged it with
3322.        a grappling hook from outside without ever having been inside */
3323.     if (!eshkp->bill_p)
3324.         eshkp->bill_p = &eshkp->bill[0];
3325. 
3326.     if (!billable(&shkp, obj, *u.ushops, TRUE)) {
3327.         /* shk doesn't want it */
3328.         unbilled = TRUE;
3329.     } else if (eshkp->billct == BILLSZ) {
3330.         /* shk's bill is completely full */
3331.         You("got that for free!");
3332.         unbilled = TRUE;
3333.     }
3334.     /* if not on any list (probably from bill_dummy_object() which creates
3335.        a new OBJ_FREE object), don't leave unmanaged object hanging around */
3336.     if (unbilled) {
3337.         if (obj->where == OBJ_FREE)
3338.             dealloc_obj(obj); /* change to obj->where==OBJ_DELETED */
3339.         return;
3340.     }
3341. 
3342.     bct = eshkp->billct;
3343.     bp = &eshkp->bill_p[bct];
3344.     bp->bo_id = obj->o_id;
3345.     bp->bquan = obj->quan;
3346.     if (dummy) {              /* a dummy object must be inserted into  */
3347.         bp->useup = TRUE;     /* the gb.billobjs chain here.  crucial for */
3348.         add_to_billobjs(obj); /* eating floorfood in shop.  see eat.c  */
3349.     } else
3350.         bp->useup = FALSE;
3351.     bp->price = get_cost(obj, shkp);
3352.     if (obj->globby) {
3353.         /* for globs, the amt charged for quan 1 depends on owt */
3354.         bp->price *= get_pricing_units(obj);
3355.         /* remember the weight this glob had when it was added to bill;
3356.            glob oextra_owt field overlays corpse omid field */
3357.         newomid(obj);
3358.         OMID(obj) = obj->owt;
3359.     }
3360.     eshkp->billct++;
3361.     obj->unpaid = 1;
3362.     record_price_quote(obj->otyp, bp->price, TRUE);
3363. }
3364. 
3365. staticfn void
3366. add_to_billobjs(struct obj *obj)
3367. {
3368.     if (obj->where != OBJ_FREE)
3369.         panic("add_to_billobjs: obj not free");
3370.     if (obj->timed)
3371.         obj_stop_timers(obj);
3372. 
3373.     obj->nobj = gb.billobjs;
3374.     gb.billobjs = obj;
3375.     obj->where = OBJ_ONBILL;
3376. 
3377.     /* if hero drinks a shop-owned potion, it will have been flagged
3378.        in_use by dodrink/dopotion but isn't being used up yet because
3379.        it stays on the bill; only object sanity checking actually cares */
3380.     obj->in_use = 0;
3381.     /* ... same for bypass by destroy_items */
3382.     obj->bypass = 0;
3383. }
3384. 
3385. /* recursive billing of objects within containers. */
3386. staticfn void
3387. bill_box_content(
3388.     struct obj *obj,
3389.     boolean ininv,
3390.     boolean dummy,
3391.     struct monst *shkp)
3392. {
3393.     struct obj *otmp;
3394. 
3395.     if (SchroedingersBox(obj))
3396.         return;
3397.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3398.         if (otmp->oclass == COIN_CLASS)
3399.             continue;
3400. 
3401.         /* the "top" box is added in addtobill() */
3402.         if (!otmp->no_charge)
3403.             add_one_tobill(otmp, dummy, shkp);
3404.         if (Has_contents(otmp))
3405.             bill_box_content(otmp, ininv, dummy, shkp);
3406.     }
3407. }
3408. 
3409. DISABLE_WARNING_FORMAT_NONLITERAL
3410. 
3411. /* shopkeeper tells you what you bought or sold, sometimes partly IDing it */
3412. staticfn void
3413. shk_names_obj(
3414.     struct monst *shkp,
3415.     struct obj *obj,
3416.     const char *fmt, /* "%s %ld %s %s", doname(obj), amt, plur(amt), arg */
3417.     long amt,
3418.     const char *arg)
3419. {
3420.     char *obj_name, fmtbuf[BUFSZ];
3421.     boolean was_unknown = !obj->dknown;
3422. 
3423.     observe_object(obj);
3424.     /* Use real name for ordinary weapons/armor, and spell-less
3425.      * scrolls/books (that is, blank and mail), but only if the
3426.      * object is within the shk's area of interest/expertise.
3427.      */
3428.     if (!objects[obj->otyp].oc_magic && saleable(shkp, obj)
3429.         && (obj->oclass == WEAPON_CLASS || obj->oclass == ARMOR_CLASS
3430.             || obj->oclass == SCROLL_CLASS || obj->oclass == SPBOOK_CLASS
3431.             || obj->otyp == MIRROR)) {
3432.         was_unknown |= !objects[obj->otyp].oc_name_known;
3433.         makeknown(obj->otyp);
3434.     }
3435.     obj_name = paydoname(obj);
3436.     /* Use an alternate message when extra information is being provided */
3437.     if (was_unknown) {
3438.         Sprintf(fmtbuf, "%%s; you %s", fmt);
3439.         obj_name[0] = highc(obj_name[0]);
3440.         pline(fmtbuf, obj_name, (obj->quan > 1L) ? "them" : "it", amt,
3441.               plur(amt), arg);
3442.     } else {
3443.         You(fmt, obj_name, amt, plur(amt), arg);
3444.     }
3445. }
3446. 
3447. RESTORE_WARNING_FORMAT_NONLITERAL
3448. 
3449. /* decide whether a shopkeeper thinks an item belongs to her */
3450. boolean
3451. billable(
3452.     struct monst **shkpp, /* in: non-null if shk has been validated;
3453.                            * out: shk */
3454.     struct obj *obj,
3455.     char roomno,
3456.     boolean reset_nocharge)
3457. {
3458.     struct monst *shkp = *shkpp;
3459. 
3460.     /* if caller hasn't supplied a shopkeeper, look one up now */
3461.     if (!shkp) {
3462.         if (!roomno)
3463.             return FALSE;
3464.         shkp = shop_keeper(roomno);
3465.         if (!shkp || !inhishop(shkp))
3466.             return FALSE;
3467.         *shkpp = shkp;
3468.     }
3469.     /* perhaps we threw it away earlier */
3470.     if (onbill(obj, shkp, FALSE)
3471.         || (obj->oclass == FOOD_CLASS && obj->oeaten))
3472.         return FALSE;
3473.     /* outer container might be marked no_charge but still have contents
3474.        which should be charged for; clear no_charge when picking things up */
3475.     if (obj->no_charge) {
3476.         if (!Has_contents(obj) || (contained_gold(obj, TRUE) == 0L
3477.                                    && contained_cost(obj, shkp, 0L, FALSE,
3478.                                                      !reset_nocharge) == 0L))
3479.             shkp = 0; /* not billable */
3480.         if (reset_nocharge && !shkp && obj->oclass != COIN_CLASS) {
3481.             obj->no_charge = 0;
3482.             if (Has_contents(obj))
3483.                 picked_container(obj); /* clear no_charge */
3484.         }
3485.     }
3486.     return shkp ? TRUE : FALSE;
3487. }
3488. 
3489. void
3490. addtobill(
3491.     struct obj *obj,
3492.     boolean ininv,
3493.     boolean dummy,
3494.     boolean silent)
3495. {
3496.     struct monst *shkp = 0;
3497.     long ltmp, cltmp, gltmp;
3498.     int contentscount;
3499.     boolean container;
3500. 
3501.     if (!billable(&shkp, obj, *u.ushops, TRUE))
3502.         return;
3503. 
3504.     if (obj->oclass == COIN_CLASS) {
3505.         costly_gold(obj->ox, obj->oy, obj->quan, silent);
3506.         return;
3507.     } else if (ESHK(shkp)->billct == BILLSZ) {
3508.         if (!silent)
3509.             You("got that for free!");
3510.         return;
3511.     }
3512. 
3513.     ltmp = cltmp = gltmp = 0L;
3514.     container = Has_contents(obj);
3515. 
3516.     if (!obj->no_charge) {
3517.         ltmp = get_cost(obj, shkp);
3518.         if (obj->globby)
3519.             ltmp *= get_pricing_units(obj);
3520.     }
3521.     if (obj->no_charge && !container) {
3522.         obj->no_charge = 0;
3523.         return;
3524.     }
3525. 
3526.     if (container) {
3527.         cltmp = contained_cost(obj, shkp, cltmp, FALSE, FALSE);
3528.         gltmp = contained_gold(obj, TRUE);
3529. 
3530.         if (ltmp)
3531.             add_one_tobill(obj, dummy, shkp);
3532.         if (cltmp)
3533.             bill_box_content(obj, ininv, dummy, shkp);
3534.         picked_container(obj); /* reset contained obj->no_charge */
3535. 
3536.         ltmp += cltmp;
3537. 
3538.         if (gltmp) {
3539.             costly_gold(obj->ox, obj->oy, gltmp, silent);
3540.             if (!ltmp)
3541.                 return;
3542.         }
3543. 
3544.         if (obj->no_charge)
3545.             obj->no_charge = 0;
3546.         contentscount = count_unpaid(obj->cobj);
3547.     } else { /* !container */
3548.         add_one_tobill(obj, dummy, shkp);
3549.         contentscount = 0;
3550.     }
3551. 
3552.     if (!Deaf && !muteshk(shkp) && !silent) {
3553.         char buf[BUFSZ];
3554. 
3555.         /* no need to update price quotes here; it was done by
3556.            add_one_tobill above */
3557. 
3558.         if (!ltmp) {
3559.             pline("%s has no interest in %s.", Shknam(shkp), the(xname(obj)));
3560.             return;
3561.         }
3562.         if (!ininv) {
3563.             pline("%s will cost you %ld %s%s.", The(xname(obj)), ltmp,
3564.                   currency(ltmp), (obj->quan > 1L) ? " each" : "");
3565.         } else {
3566.             long save_quan = obj->quan;
3567. 
3568.             Strcpy(buf, "\"For you,");
3569.             if (ANGRY(shkp)) {
3570.                 Strcat(buf, " scum;");
3571.             } else if (!ESHK(shkp)->surcharge) {
3572.                 Strcat(buf, " ");
3573.                 append_honorific(buf);
3574.                 Strcat(buf, "; only");
3575.             }
3576.             obj->quan = 1L; /* fool xname() into giving singular */
3577.             set_voice(shkp, 0, 80, 0);
3578.             pline("%s %ld %s %s %s%s.\"", buf, ltmp, currency(ltmp),
3579.                   (save_quan > 1L) ? "per"
3580.                                    : (contentscount && !obj->unpaid)
3581.                                        ? "for the contents of this"
3582.                                        : "for this",
3583.                   xname(obj),
3584.                   (contentscount && obj->unpaid) ? and_its_contents : "");
3585.             obj->quan = save_quan;
3586.         }
3587.     } else if (!silent) {
3588.         if (ltmp) {
3589.             set_voice(shkp, 0, 80, 0);
3590.             pline_The("list price of %s%s%s is %ld %s%s.",
3591.                       (contentscount && !obj->unpaid) ? the_contents_of : "",
3592.                       the(xname(obj)),
3593.                       (contentscount && obj->unpaid) ? and_its_contents : "",
3594.                       ltmp, currency(ltmp), (obj->quan > 1L) ? " each" : "");
3595.         } else {
3596.             pline("%s does not notice.", Shknam(shkp));
3597.         }
3598.     }
3599. }
3600. 
3601. staticfn void
3602. append_honorific(char *buf)
3603. {
3604.     /* (chooses among [0]..[3] normally; [1]..[4] after the
3605.        Wizard has been killed or invocation ritual performed) */
3606.     static const char *const honored[] = {
3607.         "good", "honored", "most gracious", "esteemed",
3608.         "most renowned and sacred"
3609.     };
3610. 
3611.     Strcat(buf, honored[rn2(SIZE(honored) - 1) + u.uevent.udemigod]);
3612.     if (is_vampire(gy.youmonst.data))
3613.         Strcat(buf, (flags.female) ? " dark lady" : " dark lord");
3614.     else if (maybe_polyd(is_elf(gy.youmonst.data), Race_if(PM_ELF)))
3615.         Strcat(buf, (flags.female) ? " hiril" : " hir");
3616.     else
3617.         Strcat(buf, !is_human(gy.youmonst.data) ? " creature"
3618.                       : (flags.female) ? " lady"
3619.                         : " sir");
3620. }
3621. 
3622. void
3623. splitbill(struct obj *obj, struct obj *otmp)
3624. {
3625.     /* otmp has been split off from obj */
3626.     struct bill_x *bp;
3627.     long tmp;
3628.     struct monst *shkp = shop_keeper(*u.ushops);
3629. 
3630.     if (!shkp || !inhishop(shkp)) {
3631.         impossible("splitbill: no resident shopkeeper??");
3632.         return;
3633.     }
3634.     bp = onbill(obj, shkp, FALSE);
3635.     if (!bp) {
3636.         impossible("splitbill: not on bill?");
3637.         return;
3638.     }
3639.     if (bp->bquan < otmp->quan) {
3640.         impossible("Negative quantity on bill??");
3641.     }
3642.     if (bp->bquan == otmp->quan) {
3643.         impossible("Zero quantity on bill??");
3644.     }
3645.     bp->bquan -= otmp->quan;
3646. 
3647.     if (ESHK(shkp)->billct == BILLSZ) {
3648.         otmp->unpaid = 0;
3649.     } else {
3650.         tmp = bp->price;
3651.         bp = &(ESHK(shkp)->bill_p[ESHK(shkp)->billct]);
3652.         bp->bo_id = otmp->o_id;
3653.         bp->bquan = otmp->quan;
3654.         bp->useup = FALSE;
3655.         bp->price = tmp;
3656.         ESHK(shkp)->billct++;
3657.     }
3658. }
3659. 
3660. staticfn void
3661. sub_one_frombill(struct obj *obj, struct monst *shkp)
3662. {
3663.     struct bill_x *bp;
3664.     struct eshk *eshkp;
3665. 
3666.     if ((bp = onbill(obj, shkp, FALSE)) != 0) {
3667.         struct obj *otmp;
3668. 
3669.         obj->unpaid = 0;
3670.         if (bp->bquan > obj->quan) {
3671.             otmp = newobj();
3672.             *otmp = *obj;
3673.             otmp->oextra = (struct oextra *) 0;
3674.             bp->bo_id = otmp->o_id = next_ident(); /* svc.context.ident++ */
3675.             otmp->where = OBJ_FREE;
3676.             otmp->quan = (bp->bquan -= obj->quan);
3677.             otmp->owt = 0; /* superfluous */
3678.             bp->useup = TRUE;
3679.             add_to_billobjs(otmp);
3680.             return;
3681.         }
3682.         eshkp = ESHK(shkp);
3683.         eshkp->billct--;
3684.         *bp = eshkp->bill_p[eshkp->billct];
3685.         return;
3686.     } else if (obj->unpaid) {
3687.         impossible("sub_one_frombill: unpaid object not on bill");
3688.         obj->unpaid = 0;
3689.     }
3690. }
3691. 
3692. /* recursive check of unpaid objects within nested containers. */
3693. void
3694. subfrombill(struct obj *obj, struct monst *shkp)
3695. {
3696.     struct obj *otmp;
3697. 
3698.     sub_one_frombill(obj, shkp);
3699. 
3700.     if (Has_contents(obj))
3701.         for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3702.             if (otmp->oclass == COIN_CLASS)
3703.                 continue;
3704. 
3705.             if (Has_contents(otmp))
3706.                 subfrombill(otmp, shkp);
3707.             else
3708.                 sub_one_frombill(otmp, shkp);
3709.         }
3710. }
3711. 
3712. staticfn long
3713. stolen_container(
3714.     struct obj *obj,
3715.     struct monst *shkp,
3716.     long price,
3717.     boolean ininv)
3718. {
3719.     struct obj *otmp;
3720.     struct bill_x *bp;
3721.     long billamt;
3722. 
3723.     /* the price of contained objects; caller handles top container */
3724.     for (otmp = obj->cobj; otmp; otmp = otmp->nobj) {
3725.         if (otmp->oclass == COIN_CLASS)
3726.             continue;
3727.         billamt = 0L;
3728.         if (!billable(&shkp, otmp, ESHK(shkp)->shoproom, TRUE)) {
3729.             /* billable() returns false for objects already on bill */
3730.             if ((bp = onbill(otmp, shkp, FALSE)) == 0)
3731.                 continue;
3732.             assert(shkp != NULL); /* onbill() found shkp so it's not Null */
3733.             /* this assumes that we're being called by stolen_value()
3734.                (or by a recursive call to self on behalf of it) where
3735.                the cost of this object is about to be added to shop
3736.                debt in place of having it remain on the current bill */
3737.             billamt = bp->bquan * bp->price;
3738.             sub_one_frombill(otmp, shkp); /* avoid double billing */
3739.         }
3740. 
3741.         if (billamt)
3742.             price += billamt;
3743.         else if (ininv ? otmp->unpaid : !otmp->no_charge)
3744.             price += get_pricing_units(otmp) * get_cost(otmp, shkp);
3745. 
3746.         if (Has_contents(otmp))
3747.             price = stolen_container(otmp, shkp, price, ininv);
3748.     }
3749. 
3750.     return price;
3751. }
3752. 
3753. long
3754. stolen_value(
3755.     struct obj *obj,
3756.     coordxy x,
3757.     coordxy y,
3758.     boolean peaceful,
3759.     boolean silent)
3760. {
3761.     long value = 0L, gvalue = 0L, billamt = 0L;
3762.     char roomno;
3763.     struct bill_x *bp;
3764.     struct monst *shkp;
3765.     boolean was_unpaid;
3766.     long c_count = 0L, u_count = 0L;
3767. 
3768.     if ((shkp = find_objowner(obj, x, y)) != (struct monst *) 0) {
3769.         roomno = ESHK(shkp)->shoproom;
3770.     } else {
3771.         roomno = *in_rooms(x, y, SHOPBASE);
3772.     }
3773. 
3774.     /* gather information for message(s) prior to manipulating bill */
3775.     was_unpaid = obj->unpaid ? TRUE : FALSE;
3776.     if (Has_contents(obj)) {
3777.         c_count = count_contents(obj, TRUE, FALSE, TRUE, FALSE);
3778.         u_count = count_contents(obj, TRUE, FALSE, FALSE, FALSE);
3779.     }
3780. 
3781.     shkp = (struct monst *) 0;
3782.     if (!billable(&shkp, obj, roomno, TRUE)) {
3783.         /* things already on the bill yield a not-billable result, so
3784.            we need to check bill before deciding that shk doesn't care */
3785.         if ((bp = onbill(obj, shkp, FALSE)) != 0) {
3786.             assert(shkp != NULL); /* onbill() found shkp so it's not Null */
3787.             /* shk does care; take obj off bill to avoid double billing */
3788.             billamt = bp->bquan * bp->price;
3789.             sub_one_frombill(obj, shkp);
3790.         }
3791.         if (!bp && !u_count)
3792.             return 0L;
3793.     }
3794. 
3795.     if (obj->oclass == COIN_CLASS) {
3796.         gvalue += obj->quan;
3797.     } else {
3798.         if (billamt)
3799.             value += billamt;
3800.         else if (!obj->no_charge)
3801.             value += get_pricing_units(obj) * get_cost(obj, shkp);
3802. 
3803.         if (Has_contents(obj)) {
3804.             boolean ininv =
3805.                 (obj->where == OBJ_INVENT || obj->where == OBJ_FREE);
3806. 
3807.             value += stolen_container(obj, shkp, 0L, ininv);
3808.             if (!ininv)
3809.                 gvalue += contained_gold(obj, TRUE);
3810.         }
3811.     }
3812. 
3813.     if (gvalue + value == 0L)
3814.         return 0L;
3815. 
3816.     value += gvalue;
3817. 
3818.     if (peaceful) {
3819.         boolean credit_use = !!ESHK(shkp)->credit;
3820. 
3821.         value = check_credit(value, shkp);
3822.         /* 'peaceful' affects general treatment, but doesn't affect
3823.          * the fact that other code expects that all charges after the
3824.          * shopkeeper is angry are included in robbed, not debit */
3825.         if (ANGRY(shkp))
3826.             ESHK(shkp)->robbed += value;
3827.         else
3828.             ESHK(shkp)->debit += value;
3829. 
3830.         if (!silent) {
3831.             char buf[BUFSZ];
3832.             const char *still = "";
3833. 
3834.             if (credit_use) {
3835.                 if (ESHK(shkp)->credit) {
3836.                     You("have %ld %s credit remaining.", ESHK(shkp)->credit,
3837.                         currency(ESHK(shkp)->credit));
3838.                     return value;
3839.                 } else if (!value) {
3840.                     You("have no credit remaining.");
3841.                     return 0;
3842.                 }
3843.                 still = "still ";
3844.             }
3845.             Sprintf(buf, "%sowe %s %ld %s", still, shkname(shkp),
3846.                     value, currency(value));
3847.             if (u_count) /* u_count > 0 implies Has_contents(obj) */
3848.                 Sprintf(eos(buf), " for %s%sits contents",
3849.                         was_unpaid ? "it and " : "",
3850.                         (c_count > u_count) ? "some of " : "");
3851.             else if (obj->oclass != COIN_CLASS)
3852.                 Sprintf(eos(buf), " for %s",
3853.                         (obj->quan > 1L) ? "them" : "it");
3854. 
3855.             You("%s!", buf); /* "You owe <shk> N zorkmids for it!" */
3856.         }
3857.     } else {
3858.         ESHK(shkp)->robbed += value;
3859. 
3860.         if (!silent) {
3861.             if (canseemon(shkp)) {
3862.                 Norep("%s booms: \"%s, you are a thief!\"",
3863.                       Shknam(shkp), svp.plname);
3864.             } else if (!Deaf) {
3865.                 Norep("You hear a scream, \"Thief!\"");  /* Deaf-aware */
3866.             }
3867.         }
3868.         hot_pursuit(shkp);
3869.         (void) angry_guards(FALSE);
3870.     }
3871.     return value;
3872. }
3873. 
3874. /* opposite of costly_gold(); hero has dropped gold in a shop;
3875.    called from sellobj(); ought to be called from subfrombill() too */
3876. void
3877. donate_gold(
3878.     long gltmp,
3879.     struct monst *shkp,
3880.     boolean selling) /* T: dropped in shop; F: kicked and landed in shop */
3881. {
3882.     struct eshk *eshkp = ESHK(shkp);
3883. 
3884.     if (eshkp->debit >= gltmp) {
3885.         if (eshkp->loan) { /* you carry shop's gold */
3886.             if (eshkp->loan > gltmp)
3887.                 eshkp->loan -= gltmp;
3888.             else
3889.                 eshkp->loan = 0L;
3890.         }
3891.         eshkp->debit -= gltmp;
3892.         Your("debt is %spaid off.", eshkp->debit ? "partially " : "");
3893.     } else {
3894.         long delta = gltmp - eshkp->debit;
3895. 
3896.         eshkp->credit += delta;
3897.         if (eshkp->debit) {
3898.             eshkp->debit = 0L;
3899.             eshkp->loan = 0L;
3900.             Your("debt is paid off.");
3901.         }
3902.         if (eshkp->credit == delta)
3903.             You("have %sestablished %ld %s credit.",
3904.                 !selling ? "re-" : "", delta, currency(delta));
3905.         else
3906.             pline("%ld %s added%s to your credit; total is now %ld %s.",
3907.                   delta, currency(delta), !selling ? " back" : "",
3908.                   eshkp->credit, currency(eshkp->credit));
3909.     }
3910. }
3911. 
3912. void
3913. sellobj_state(int deliberate)
3914. {
3915.     /* If we're deliberately dropping something, there's no automatic
3916.        response to the shopkeeper's "want to sell" query; however, if we
3917.        accidentally drop anything, the shk will buy it/them without asking.
3918.        This retains the old pre-query risk that slippery fingers while in
3919.        shops entailed:  you drop it, you've lost it.
3920.      */
3921.     gs.sell_response = (deliberate != SELL_NORMAL) ? '\0' : 'a';
3922.     gs.sell_how = deliberate;
3923.     ga.auto_credit = FALSE;
3924. }
3925. 
3926. void
3927. sellobj(
3928.     struct obj *obj,
3929.     coordxy x, coordxy y)
3930. {
3931.     struct monst *shkp;
3932.     struct eshk *eshkp;
3933.     long ltmp = 0L, cltmp = 0L, gltmp = 0L, offer, shkmoney;
3934.     boolean saleitem, cgold = FALSE, container = Has_contents(obj);
3935.     boolean isgold = (obj->oclass == COIN_CLASS);
3936.     boolean only_partially_your_contents = FALSE;
3937. 
3938.     if (!*u.ushops) /* do cheapest exclusion test first */
3939.         return;
3940.     shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
3941.     if (!shkp || !inhishop(shkp))
3942.         return;
3943.     if (!costly_spot(x, y))
3944.         return;
3945. 
3946.     if (obj->unpaid && !container && !isgold) {
3947.         sub_one_frombill(obj, shkp);
3948.         return;
3949.     }
3950.     if (container) {
3951.         /* find the price of content before subfrombill */
3952.         cltmp = contained_cost(obj, shkp, cltmp, TRUE, FALSE);
3953.         /* find the value of contained gold */
3954.         gltmp += contained_gold(obj, TRUE);
3955.         cgold = (gltmp > 0L);
3956.     }
3957. 
3958.     saleitem = saleable(shkp, obj);
3959.     if (!isgold && !obj->unpaid && saleitem)
3960.         ltmp = set_cost(obj, shkp);
3961. 
3962.     offer = ltmp + cltmp;
3963. 
3964.     /* you dropped something of your own - probably want to sell it */
3965.     rouse_shk(shkp, TRUE); /* wake up sleeping or paralyzed shk */
3966.     eshkp = ESHK(shkp);
3967. 
3968.     if (ANGRY(shkp)) { /* they become shop-objects, no pay */
3969.         if (!Deaf && !muteshk(shkp)) {
3970.             SetVoice(shkp, 0, 80, 0);
3971.             verbalize("Thank you, scum!");
3972.         } else {
3973.             pline("%s smirks with satisfaction.", Shknam(shkp));
3974.         }
3975.         subfrombill(obj, shkp);
3976.         return;
3977.     }
3978. 
3979.     /* get one case out of the way: nothing to sell, and no gold */
3980.     if (!(isgold || cgold)
3981.         && ((offer + gltmp) == 0L || gs.sell_how == SELL_DONTSELL)) {
3982.         boolean unpaid = is_unpaid(obj);
3983. 
3984.         if (container) {
3985.             dropped_container(obj, shkp, FALSE);
3986.             if (!obj->unpaid)
3987.                 obj->no_charge = 1;
3988.             if (unpaid)
3989.                 subfrombill(obj, shkp);
3990.         } else
3991.             obj->no_charge = 1;
3992. 
3993.         if (!unpaid && (gs.sell_how != SELL_DONTSELL)
3994.             && !special_stock(obj, shkp, FALSE))
3995.             pline("%s seems uninterested.", Shknam(shkp));
3996.         return;
3997.     }
3998. 
3999.     if (eshkp->robbed) { /* bones; shop robbed by previous customer */
4000.         if (isgold)
4001.             offer = obj->quan;
4002.         else if (cgold)
4003.             offer += cgold;
4004.         if ((eshkp->robbed -= offer < 0L))
4005.             eshkp->robbed = 0L;
4006.         if (offer && !Deaf && !muteshk(shkp)) {
4007.             SetVoice(shkp, 0, 80, 0);
4008.             verbalize(
4009.   "Thank you for your contribution to restock this recently plundered shop.");
4010.         }
4011.         subfrombill(obj, shkp);
4012.         return;
4013.     }
4014. 
4015.     if (isgold || cgold) {
4016.         if (!cgold)
4017.             gltmp = obj->quan;
4018. 
4019.         donate_gold(gltmp, shkp, TRUE);
4020. 
4021.         if (!offer || gs.sell_how == SELL_DONTSELL) {
4022.             if (!isgold) {
4023.                 if (container)
4024.                     dropped_container(obj, shkp, FALSE);
4025.                 if (!obj->unpaid)
4026.                     obj->no_charge = 1;
4027.                 subfrombill(obj, shkp);
4028.             }
4029.             return;
4030.         }
4031.     }
4032. 
4033.     if ((!saleitem && !(container && cltmp > 0L)) || eshkp->billct == BILLSZ
4034.         || obj->oclass == BALL_CLASS || obj->oclass == CHAIN_CLASS
4035.         || offer == 0L || (obj->oclass == FOOD_CLASS && obj->oeaten)
4036.         || (Is_candle(obj)
4037.             && obj->age < 20L * (long) objects[obj->otyp].oc_cost)) {
4038.         pline("%s seems uninterested%s.", Shknam(shkp),
4039.               cgold ? " in the rest" : "");
4040.         if (container)
4041.             dropped_container(obj, shkp, FALSE);
4042.         obj->no_charge = 1;
4043.         return;
4044.     }
4045. 
4046.     shkmoney = money_cnt(shkp->minvent);
4047.     if (!shkmoney) {
4048.         char c, qbuf[BUFSZ];
4049.         long tmpcr = ((offer * 9L) / 10L) + (offer <= 1L);
4050. 
4051.         if (gs.sell_how == SELL_NORMAL || ga.auto_credit) {
4052.             c = gs.sell_response = 'y';
4053.         } else if (gs.sell_response != 'n') {
4054.             pline("%s cannot pay you at present.", Shknam(shkp));
4055.             Sprintf(qbuf, "Will you accept %ld %s in credit for ", tmpcr,
4056.                     currency(tmpcr));
4057.             record_price_quote(obj->otyp, tmpcr / obj->quan, FALSE);
4058.             c = ynaq(safe_qbuf(qbuf, qbuf, "?", obj, doname, thesimpleoname,
4059.                                (obj->quan == 1L) ? "that" : "those"));
4060.             if (c == 'a') {
4061.                 c = 'y';
4062.                 ga.auto_credit = TRUE;
4063.             }
4064.         } else /* previously specified "quit" */
4065.             c = 'n';
4066. 
4067.         if (c == 'y') {
4068.             shk_names_obj(shkp, obj,
4069.                           ((gs.sell_how != SELL_NORMAL)
4070.                            ? "traded %s for %ld zorkmid%s in %scredit."
4071.                     : "relinquish %s and acquire %ld zorkmid%s in %scredit."),
4072.                           tmpcr, (eshkp->credit > 0L) ? "additional " : "");
4073.             eshkp->credit += tmpcr;
4074.             if (container)
4075.                 dropped_container(obj, shkp, TRUE);
4076.             subfrombill(obj, shkp);
4077.         } else {
4078.             if (c == 'q')
4079.                 gs.sell_response = 'n';
4080.             if (container)
4081.                 dropped_container(obj, shkp, FALSE);
4082.             if (!obj->unpaid)
4083.                 obj->no_charge = 1;
4084.             subfrombill(obj, shkp);
4085.         }
4086.     } else {
4087.         char qbuf[BUFSZ], qsfx[BUFSZ];
4088.         boolean short_funds = (offer > shkmoney), one;
4089. 
4090.         if (short_funds)
4091.             offer = shkmoney;
4092.         if (!gs.sell_response) {
4093.             long yourc = 0L, shksc;
4094. 
4095.             if (container) {
4096.                 /* number of items owned by shk */
4097.                 shksc = count_contents(obj, TRUE, TRUE, FALSE, TRUE);
4098.                 /* number of items owned by you (total - shksc) */
4099.                 yourc = count_contents(obj, TRUE, TRUE, TRUE, TRUE) - shksc;
4100.                 only_partially_your_contents = shksc && yourc;
4101.             }
4102.             /*
4103.                "<shk> offers * for ..." query formatting.
4104.                Normal item(s):
4105.                 "... your <object>.  Sell it?"
4106.                 "... your <objects>.  Sell them?"
4107.                A container is either owned by the hero, or already
4108.                owned by the shk (!ltmp), or the shk isn't interested
4109.                in buying it (also !ltmp).  It's either empty (!cltmp)
4110.                or it has contents owned by the hero or it has some
4111.                contents owned by the hero and others by the shk.
4112.                (The case where it has contents already entirely owned
4113.                by the shk is treated the same was if it were empty
4114.                since the hero isn't selling any of those contents.)
4115.                Your container and shk is willing to buy it:
4116.                 "... your <empty bag>.  Sell it?"
4117.                 "... your <bag> and its contents.  Sell them?"
4118.                 "... your <bag> and item inside.  Sell them?"
4119.                 "... your <bag> and items inside.  Sell them?"
4120.                Your container but shk only cares about the contents:
4121.                 "... your item in your <bag>.  Sell it?"
4122.                 "... your items in your <bag>.  Sell them?"
4123.                Shk's container:
4124.                 "... your item in the <bag>.  Sell it?"
4125.                 "... your items in the <bag>.  Sell them?"
4126.               FIXME:
4127.                "your items" should sometimes be "some of your items"
4128.                (when container has some stuff the shk is willing to buy
4129.                and other stuff he or she doesn't care about); likewise,
4130.                "your item" should sometimes be "one of your items".
4131.                That would make the prompting even more verbose so
4132.                living without it might be a good thing.
4133.               FIXME too:
4134.                when container's contents are unknown, plural "items"
4135.                should be used to not give away information.
4136.              */
4137.             Sprintf(qbuf, "%s offers%s %ld gold piece%s for %s%s ",
4138.                     Shknam(shkp), short_funds ? " only" : "", offer,
4139.                     plur(offer),
4140.                     (cltmp && !ltmp)
4141.                         ? ((yourc == 1L) ? "your item in " : "your items in ")
4142.                         : "",
4143.                     obj->unpaid ? "the" : "your");
4144.             one = !ltmp ? (yourc == 1L) : (obj->quan == 1L && !cltmp);
4145.             Sprintf(qsfx, "%s.  Sell %s?",
4146.                     (cltmp && ltmp)
4147.                         ? (only_partially_your_contents
4148.                                ? ((yourc == 1L) ? " and item inside"
4149.                                                 : " and items inside")
4150.                                : and_its_contents)
4151.                         : "",
4152.                     one ? "it" : "them");
4153.             record_price_quote(obj->otyp, offer / obj->quan, FALSE);
4154.             (void) safe_qbuf(qbuf, qbuf, qsfx, obj, xname, simpleonames,
4155.                              one ? "that" : "those");
4156.         } else
4157.             qbuf[0] = '\0'; /* just to pacify lint */
4158. 
4159.         switch (gs.sell_response ? gs.sell_response : nyaq(qbuf)) {
4160.         case 'q':
4161.             gs.sell_response = 'n';
4162.             FALLTHROUGH;
4163.             /*FALLTHRU*/
4164.         case 'n':
4165.             if (container)
4166.                 dropped_container(obj, shkp, FALSE);
4167.             if (!obj->unpaid)
4168.                 obj->no_charge = 1;
4169.             subfrombill(obj, shkp);
4170.             break;
4171.         case 'a':
4172.             gs.sell_response = 'y';
4173.             FALLTHROUGH;
4174.             /*FALLTHRU*/
4175.         case 'y':
4176.             if (container)
4177.                 dropped_container(obj, shkp, TRUE);
4178.             if (!obj->unpaid && !saleitem)
4179.                 obj->no_charge = 1;
4180.             subfrombill(obj, shkp);
4181.             pay(-offer, shkp);
4182.             shk_names_obj(shkp, obj,
4183.                           (gs.sell_how != SELL_NORMAL)
4184.                            ? ((!ltmp && cltmp && only_partially_your_contents)
4185.                          ? "sold some items inside %s for %ld gold piece%s.%s"
4186.                          : "sold %s for %ld gold piece%s.%s")
4187.             : "relinquish %s and receive %ld gold piece%s in compensation.%s",
4188.                           offer, "");
4189.             break;
4190.         default:
4191.             impossible("invalid sell response");
4192.         }
4193.     }
4194. }
4195. 
4196. int
4197. doinvbill(
4198.     int mode) /* 0: deliver count 1: paged */
4199. {
4200.     struct monst *shkp;
4201.     struct eshk *eshkp;
4202.     struct bill_x *bp, *end_bp;
4203.     struct obj *obj;
4204.     long totused;
4205.     char *buf_p;
4206.     winid datawin;
4207. 
4208.     shkp = shop_keeper(*u.ushops);
4209.     if (!shkp || !inhishop(shkp)) {
4210.         if (mode != 0)
4211.             impossible("doinvbill: no shopkeeper?");
4212.         return 0;
4213.     }
4214.     eshkp = ESHK(shkp);
4215. 
4216.     if (mode == 0) {
4217.         /* count expended items, so that the `I' command can decide
4218.            whether to include 'x' in its prompt string */
4219.         int cnt = !eshkp->debit ? 0 : 1;
4220. 
4221.         for (bp = eshkp->bill_p, end_bp = &eshkp->bill_p[eshkp->billct];
4222.              bp < end_bp; bp++)
4223.             if (bp->useup
4224.                 || ((obj = bp_to_obj(bp)) != 0 && obj->quan < bp->bquan))
4225.                 cnt++;
4226.         return cnt;
4227.     }
4228. 
4229.     datawin = create_nhwindow(NHW_MENU);
4230.     putstr(datawin, 0, "Unpaid articles already used up:");
4231.     putstr(datawin, 0, "");
4232. 
4233.     totused = 0L;
4234.     for (bp = eshkp->bill_p, end_bp = &eshkp->bill_p[eshkp->billct];
4235.          bp < end_bp; bp++) {
4236.         obj = bp_to_obj(bp);
4237.         if (!obj) {
4238.             impossible("Bad shopkeeper administration.");
4239.             goto quit;
4240.         }
4241.         if (bp->useup || bp->bquan > obj->quan) {
4242.             long oquan, uquan, thisused;
4243. 
4244.             oquan = obj->quan;
4245.             uquan = (bp->useup ? bp->bquan : bp->bquan - oquan);
4246.             thisused = bp->price * uquan;
4247.             totused += thisused;
4248.             iflags.suppress_price++; /* suppress "(unpaid)" suffix */
4249.             /* Why 'x'?  To match `I x', more or less. */
4250.             buf_p = xprname(obj, (char *) 0, 'x', FALSE, thisused, uquan);
4251.             iflags.suppress_price--;
4252.             putstr(datawin, 0, buf_p);
4253.         }
4254.     }
4255.     if (eshkp->debit) {
4256.         /* additional shop debt which has no itemization available */
4257.         if (totused)
4258.             putstr(datawin, 0, "");
4259.         totused += eshkp->debit;
4260.         buf_p = xprname((struct obj *) 0, "usage charges and/or other fees",
4261.                         GOLD_SYM, FALSE, eshkp->debit, 0L);
4262.         putstr(datawin, 0, buf_p);
4263.     }
4264.     buf_p = xprname((struct obj *) 0, "Total:", '*', FALSE, totused, 0L);
4265.     putstr(datawin, 0, "");
4266.     putstr(datawin, 0, buf_p);
4267.     display_nhwindow(datawin, FALSE);
4268.  quit:
4269.     destroy_nhwindow(datawin);
4270.     return 0;
4271. }
4272. 
4273. /* adjust tin, egg, or corpse price based on monster data */
4274. staticfn long
4275. corpsenm_price_adj(struct obj *obj)
4276. {
4277.     long val = 0L;
4278. 
4279.     if ((obj->otyp == TIN || obj->otyp == EGG || obj->otyp == CORPSE)
4280.         && ismnum(obj->corpsenm)) {
4281.         int i;
4282.         long tmp = 1L;
4283.         struct permonst *ptr = &mons[obj->corpsenm];
4284.         struct {
4285.             int trinsic;
4286.             int cost;
4287.         } const icost[] = {
4288.             { FIRE_RES,   2 },
4289.             { SLEEP_RES,  3 },
4290.             { COLD_RES,   2 },
4291.             { DISINT_RES, 5 },
4292.             { SHOCK_RES,  4 },
4293.             { POISON_RES, 2 },
4294.             { ACID_RES,   1 },
4295.             { STONE_RES,  3 },
4296.             { TELEPORT,   2 },
4297.             { TELEPORT_CONTROL,  3 },
4298.             { TELEPAT,  5 }
4299.         };
4300. 
4301.         for (i = 0; i < SIZE(icost); i++)
4302.             if (intrinsic_possible(icost[i].trinsic, ptr))
4303.                 tmp += icost[i].cost;
4304.         if (unique_corpstat(ptr))
4305.             tmp += 50;
4306. 
4307. 
4308.         val = max(1, ((ptr->mlevel - 1) * 2));
4309.         if (obj->otyp == CORPSE)
4310.             val += max(1, (ptr->cnutrit / 30));
4311. 
4312.         val = val * tmp;
4313.     }
4314. 
4315.     return val;
4316. }
4317. 
4318. staticfn long
4319. getprice(struct obj *obj, boolean shk_buying)
4320. {
4321.     long tmp = (long) objects[obj->otyp].oc_cost;
4322. 
4323.     if (obj->oartifact) {
4324.         tmp = arti_cost(obj);
4325.         if (shk_buying)
4326.             tmp /= 4;
4327.     }
4328.     switch (obj->oclass) {
4329.     case FOOD_CLASS:
4330.         tmp += corpsenm_price_adj(obj);
4331. 
4332.         /* simpler hunger check, (2-4)*cost */
4333.         if (u.uhs >= HUNGRY && !shk_buying)
4334.             tmp *= (long) u.uhs;
4335.         if (obj->oeaten)
4336.             tmp = 0L;
4337.         break;
4338.     case WAND_CLASS:
4339.         if (obj->spe == -1)
4340.             tmp = 0L;
4341.         break;
4342.     case POTION_CLASS:
4343.         if (obj->otyp == POT_WATER && !obj->blessed && !obj->cursed)
4344.             tmp = 0L;
4345.         break;
4346.     case ARMOR_CLASS:
4347.     case WEAPON_CLASS:
4348.         if (obj->spe > 0)
4349.             tmp += 10L * (long) obj->spe;
4350.         break;
4351.     case TOOL_CLASS:
4352.         if (Is_candle(obj)
4353.             && obj->age < 20L * (long) objects[obj->otyp].oc_cost)
4354.             tmp /= 2L;
4355.         break;
4356.     }
4357.     return tmp;
4358. }
4359. 
4360. /* shk catches thrown pick-axe */
4361. struct monst *
4362. shkcatch(
4363.     struct obj *obj,
4364.     coordxy x, coordxy y)
4365. {
4366.     struct monst *shkp;
4367. 
4368.     shkp = shop_keeper(inside_shop(x, y));
4369.     if (!shkp || !inhishop(shkp))
4370.         return 0;
4371. 
4372.     if (!helpless(shkp)
4373.         && (*u.ushops != ESHK(shkp)->shoproom || !inside_shop(u.ux, u.uy))
4374.         && dist2(shkp->mx, shkp->my, x, y) < 3
4375.         /* if it is the shk's pos, you hit and anger him */
4376.         && (shkp->mx != x || shkp->my != y)) {
4377.         if (mnearto(shkp, x, y, TRUE, RLOC_NOMSG) == 2
4378.             && !Deaf && !muteshk(shkp)) {
4379.             SetVoice(shkp, 0, 80, 0);
4380.             verbalize("Out of my way, scum!");
4381.         }
4382.         if (cansee(x, y)) {
4383.             pline("%s nimbly%s catches %s.", Shknam(shkp),
4384.                   (x == shkp->mx && y == shkp->my) ? "" : " reaches over and",
4385.                   the(xname(obj)));
4386.             if (!canspotmon(shkp))
4387.                 map_invisible(x, y);
4388.             nh_delay_output();
4389.             mark_synch();
4390.         }
4391.         subfrombill(obj, shkp);
4392.         (void) mpickobj(shkp, obj);
4393.         return shkp;
4394.     }
4395.     return (struct monst *) 0;
4396. }
4397. 
4398. void
4399. add_damage(
4400.     coordxy x,
4401.     coordxy y,
4402.     long cost)
4403. {
4404.     struct damage *tmp_dam;
4405.     char *shops;
4406. 
4407.     if (IS_DOOR(levl[x][y].typ)) {
4408.         struct monst *mtmp;
4409. 
4410.         /* Don't schedule for repair unless it's a real shop entrance */
4411.         for (shops = in_rooms(x, y, SHOPBASE); *shops; shops++)
4412.             if ((mtmp = shop_keeper(*shops)) != 0
4413.                 && x == ESHK(mtmp)->shd.x && y == ESHK(mtmp)->shd.y)
4414.                 break;
4415.         if (!*shops)
4416.             return;
4417.     }
4418.     for (tmp_dam = svl.level.damagelist; tmp_dam; tmp_dam = tmp_dam->next)
4419.         if (tmp_dam->place.x == x && tmp_dam->place.y == y) {
4420.             tmp_dam->cost += cost;
4421.             tmp_dam->when = svm.moves; /* needed by pay_for_damage() */
4422.             return;
4423.         }
4424.     tmp_dam = (struct damage *) alloc((unsigned) sizeof *tmp_dam);
4425.     (void) memset((genericptr_t) tmp_dam, 0, sizeof *tmp_dam);
4426.     tmp_dam->when = svm.moves;
4427.     tmp_dam->place.x = x;
4428.     tmp_dam->place.y = y;
4429.     tmp_dam->cost = cost;
4430.     tmp_dam->typ = levl[x][y].typ;
4431.     tmp_dam->flags = levl[x][y].flags;
4432.     tmp_dam->next = svl.level.damagelist;
4433.     svl.level.damagelist = tmp_dam;
4434.     /* If player saw damage, display walls post-repair as walls, not stone */
4435.     if (cansee(x, y))
4436.         levl[x][y].seenv = SVALL;
4437. }
4438. 
4439. /* is shopkeeper impaired, so they cannot act? */
4440. staticfn boolean
4441. shk_impaired(struct monst *shkp)
4442. {
4443.     if (!shkp || !shkp->isshk || !inhishop(shkp))
4444.         return TRUE;
4445.     if (helpless(shkp) || ESHK(shkp)->following)
4446.         return TRUE;
4447.     return FALSE;
4448. }
4449. 
4450. /* is damage dam repairable by shopkeeper shkp? */
4451. staticfn boolean
4452. repairable_damage(struct damage *dam, struct monst *shkp)
4453. {
4454.     coordxy x, y;
4455.     struct trap *ttmp;
4456.     struct monst *mtmp;
4457. 
4458.     if (!dam || shk_impaired(shkp))
4459.         return FALSE;
4460. 
4461.     x = dam->place.x;
4462.     y = dam->place.y;
4463. 
4464.     /* too soon to fix it? */
4465.     if ((svm.moves - dam->when) < REPAIR_DELAY)
4466.         return FALSE;
4467.     /* is it a wall? don't fix if anyone is in the way */
4468.     if (!IS_ROOM(dam->typ)) {
4469.         if ((u_at(x, y) && !Passes_walls)
4470.             || (x == shkp->mx && y == shkp->my)
4471.             || ((mtmp = m_at(x, y)) != 0 && !passes_walls(mtmp->data)))
4472.             return FALSE;
4473.     }
4474.     /* is it a trap? don't fix if hero or monster is in it */
4475.     ttmp = t_at(x, y);
4476.     if (ttmp) {
4477.         if (u_at(x, y))
4478.             return FALSE;
4479.         if ((mtmp = m_at(x,y)) != 0 && mtmp->mtrapped)
4480.             return FALSE;
4481.     }
4482.     /* does it belong to shkp? */
4483.     if (!strchr(in_rooms(x, y, SHOPBASE), ESHK(shkp)->shoproom))
4484.         return FALSE;
4485. 
4486.     return TRUE;
4487. }
4488. 
4489. /* find any damage shopkeeper shkp could repair. returns NULL is none found */
4490. staticfn struct damage *
4491. find_damage(struct monst *shkp)
4492. {
4493.     struct damage *dam = svl.level.damagelist;
4494. 
4495.     if (shk_impaired(shkp))
4496.         return NULL;
4497. 
4498.     while (dam) {
4499.         if (repairable_damage(dam, shkp))
4500.             return dam;
4501. 
4502.         dam = dam->next;
4503.     }
4504. 
4505.     return NULL;
4506. }
4507. 
4508. staticfn void
4509. discard_damage_struct(struct damage *dam)
4510. {
4511.     if (!dam)
4512.         return;
4513. 
4514.     if (dam == svl.level.damagelist) {
4515.         svl.level.damagelist = dam->next;
4516.     } else {
4517.         struct damage *prev = svl.level.damagelist;
4518. 
4519.         while (prev && prev->next != dam)
4520.             prev = prev->next;
4521.         if (prev)
4522.             prev->next = dam->next;
4523.     }
4524.     (void) memset(dam, 0, sizeof *dam);
4525.     free((genericptr_t) dam);
4526. }
4527. 
4528. /* discard all damage structs owned by shopkeeper */
4529. staticfn void
4530. discard_damage_owned_by(struct monst *shkp)
4531. {
4532.     struct damage *dam = svl.level.damagelist, *dam2, *prevdam = NULL;
4533. 
4534.     while (dam) {
4535.         coordxy x = dam->place.x, y = dam->place.y;
4536. 
4537.         if (strchr(in_rooms(x, y, SHOPBASE), ESHK(shkp)->shoproom)) {
4538.             dam2 = dam->next;
4539.             if (prevdam)
4540.                 prevdam->next = dam2;
4541.             if (dam == svl.level.damagelist)
4542.                 svl.level.damagelist = dam2;
4543.             (void) memset(dam, 0, sizeof *dam);
4544.             free((genericptr_t) dam), dam = (struct damage *) NULL;
4545.         } else {
4546.             prevdam = dam;
4547.             dam2 = dam->next;
4548.         }
4549. 
4550.         dam = dam2;
4551.     }
4552. }
4553. 
4554. /* Shopkeeper tries to repair damage belonging to them */
4555. staticfn void
4556. shk_fixes_damage(struct monst *shkp)
4557. {
4558.     struct damage *dam = find_damage(shkp);
4559.     boolean shk_closeby;
4560. 
4561.     if (!dam)
4562.         return;
4563. 
4564.     shk_closeby = (mdistu(shkp) <= (BOLT_LIM / 2) * (BOLT_LIM / 2));
4565. 
4566.     if (canseemon(shkp)) {
4567.         pline("%s whispers %s.", Shknam(shkp),
4568.               shk_closeby ? "an incantation" : "something");
4569.     } else if (!Deaf && shk_closeby) {
4570.         Soundeffect(se_mutter_incantation, 100);
4571.         You_hear("someone muttering an incantation.");
4572.     }
4573. 
4574.     (void) repair_damage(shkp, dam, FALSE);
4575. 
4576.     discard_damage_struct(dam);
4577. }
4578. 
4579. #define LITTER_UPDATE 0x01U
4580. #define LITTER_OPEN   0x02U
4581. #define LITTER_INSHOP 0x04U
4582. #define horiz(i) ((i % 3) - 1)
4583. #define vert(i) ((i / 3) - 1)
4584. 
4585. /* find eligible spots to move items from a gap in a shop's wall that is
4586.    being repaired; this guarantees that items will end up inside shkp's
4587.    shop (possibly in the "free spot" or even in doorway or an adjacent
4588.    wall gap), but if they are in a gap in a wall shared by two shops
4589.    they might have started in the other shop */
4590. staticfn uint8
4591. litter_getpos(
4592.     uint8 *litter, /* array of 9 uint8's */
4593.     coordxy x, coordxy y,
4594.     struct monst *shkp)
4595. {
4596.     int i, ix, iy;
4597.     uint8 k = 0; /* number of adjacent shop spots */
4598. 
4599.     (void) memset((genericptr_t) litter, 0, 9 * sizeof *litter);
4600. 
4601.     if (svl.level.objects[x][y] && !IS_ROOM(levl[x][y].typ)) {
4602.         for (i = 0; i < 9; i++) {
4603.             ix = x + horiz(i);
4604.             iy = y + vert(i);
4605.             if (i == 4 || !isok(ix, iy) || !ZAP_POS(levl[ix][iy].typ))
4606.                 continue;
4607.             litter[i] = LITTER_OPEN;
4608.             if (inside_shop(ix, iy) == ESHK(shkp)->shoproom) {
4609.                 litter[i] |= LITTER_INSHOP;
4610.                 ++k;
4611.             }
4612.         }
4613.     }
4614.     return k;
4615. }
4616. 
4617. /* move items from a gap in a shop's wall that is being repaired;
4618.    litter[] guarantees that items will end up inside shkp's shop, but
4619.    if the wall being repaired is shared by two shops the items might
4620.    have started in the other shop */
4621. staticfn void
4622. litter_scatter(
4623.     uint8 *litter,
4624.     coordxy x, coordxy y,
4625.     struct monst *shkp)
4626. {
4627.     struct obj *otmp;
4628. 
4629.     /* placement below assumes there is always at least one adjacent spot
4630.        that's inside the shop; caller guarantees that */
4631.     {
4632.         /* Scatter objects haphazardly into the shop */
4633.         if (Punished && !u.uswallow
4634.             && ((uchain->ox == x && uchain->oy == y)
4635.                 || (uball->where == OBJ_FLOOR
4636.                     && uball->ox == x && uball->oy == y))) {
4637.             /*
4638.              * Either the ball or chain is in the repair location.
4639.              * Take the easy way out and put ball&chain under hero.
4640.              *
4641.              * FIXME: message should be reworded; this might be the
4642.              * shop's doorway rather than a wall, there might be some
4643.              * other stuff here which isn't junk, and "your junk" has
4644.              * a slang connotation which could be applicable if hero
4645.              * has Passes_walls ability.
4646.              */
4647.             if (!Deaf && !muteshk(shkp)) {
4648.                 SetVoice(shkp, 0, 80, 0);
4649.                 verbalize("Get your junk out of my wall!");
4650.             }
4651.             unplacebc(); /* pick 'em up */
4652.             placebc();   /* put 'em down */
4653.         }
4654.         while ((otmp = svl.level.objects[x][y]) != 0) {
4655.             /* Don't mess w/ boulders -- just merge into wall */
4656.             if (otmp->otyp == BOULDER || otmp->otyp == ROCK) {
4657.                 obj_extract_self(otmp);
4658.                 obfree(otmp, (struct obj *) 0);
4659.             } else {
4660.                 int trylimit = 10;
4661.                 int i = rn2(9), ix, iy;
4662. 
4663.                 /* otmp must be moved otherwise svl.level.objects[x][y] will
4664.                    never become Null and while-loop won't terminate */
4665.                 do {
4666.                     i = (i + 1) % 9;
4667.                 } while (--trylimit && !(litter[i] & LITTER_INSHOP));
4668.                 if ((litter[i] & (LITTER_OPEN | LITTER_INSHOP)) != 0) {
4669.                     ix = x + horiz(i);
4670.                     iy = y + vert(i);
4671.                 } else {
4672.                     /* we know shk isn't at <x,y> because repair
4673.                        is deferred in that situation */
4674.                     ix = shkp->mx;
4675.                     iy = shkp->my;
4676.                 }
4677.                 /* if the wall being repaired is shared by two adjacent
4678.                    shops, <ix,iy> might be in a different shop than the
4679.                    one that is billing for otmp or decided it was free;
4680.                    control of the item goes to the shk repairing the wall
4681.                    but otmp->no_charge isn't recalculated for new shop */
4682.                 if (otmp->unpaid) {
4683.                     struct monst *oshk = shkp;
4684. 
4685.                     /* !costly_spot() happens if otmp is moved from wall
4686.                        to shop's "free spot", still costly_adjacent() and
4687.                        still unpaid/on-bill; otherwise, it is being moved
4688.                        all the way into the shop so take it off the bill */
4689.                     if (costly_spot(ix, iy)
4690.                         && ((onbill(otmp, oshk, TRUE)
4691.                              || ((oshk = find_objowner(otmp, ix, iy)) != 0
4692.                                  && onbill(otmp, oshk, FALSE)))))
4693.                         subfrombill(otmp, oshk);
4694.                 }
4695.                 if (otmp->no_charge) {
4696.                     /* not strictly necessary; destination is inside a
4697.                        shop so existing no_charge remains relevant */
4698.                     if (!costly_spot(ix, iy)
4699.                         && !costly_adjacent(shkp, ix, iy))
4700.                         otmp->no_charge = 0;
4701.                 }
4702. 
4703.                 remove_object(otmp);
4704.                 place_object(otmp, ix, iy);
4705.                 litter[i] |= LITTER_UPDATE;
4706.             }
4707.         } /* while level.objects[x][y] != 0 */
4708.     }
4709. }
4710. 
4711. staticfn void
4712. litter_newsyms(uint8 *litter, coordxy x, coordxy y)
4713. {
4714.     int i;
4715. 
4716.     for (i = 0; i < 9; i++)
4717.         if (litter[i] & LITTER_UPDATE)
4718.             newsym(x + horiz(i), y + vert(i));
4719. }
4720. 
4721. #undef LITTER_UPDATE
4722. #undef LITTER_OPEN
4723. #undef LITTER_INSHOP
4724. #undef vert
4725. #undef horiz
4726. 
4727. /*
4728.  * 0: repair postponed, 1: silent repair (no messages), 2: normal repair
4729.  * 3: untrap
4730.  */
4731. staticfn int
4732. repair_damage(
4733.     struct monst *shkp,
4734.     struct damage *tmp_dam,
4735.     boolean catchup)
4736. {
4737.     coordxy x, y;
4738.     uint8 litter[9];
4739.     struct obj *otmp;
4740.     struct trap *ttmp;
4741.     int disposition = 1;
4742.     boolean seeit, stop_picking = FALSE;
4743. 
4744.     if (!repairable_damage(tmp_dam, shkp))
4745.         return 0;
4746. 
4747.     x = tmp_dam->place.x;
4748.     y = tmp_dam->place.y;
4749.     seeit = cansee(x, y);
4750. 
4751.     ttmp = t_at(x, y);
4752.     if (ttmp) {
4753.         switch (ttmp->ttyp) {
4754.         case LANDMINE:
4755.         case BEAR_TRAP:
4756.             /* convert to an object */
4757.             otmp = mksobj((ttmp->ttyp == LANDMINE) ? LAND_MINE : BEARTRAP,
4758.                           TRUE, FALSE);
4759.             otmp->quan = 1L;
4760.             otmp->owt = weight(otmp);
4761.             if (!catchup) {
4762.                 if (canseemon(shkp) && dist2(x, y, shkp->mx, shkp->my) <= 2)
4763.                     pline("%s untraps %s.", Shknam(shkp), ansimpleoname(otmp));
4764.                 else if (ttmp->tseen && cansee(ttmp->tx, ttmp->ty))
4765.                     pline("The %s vanishes.", trapname(ttmp->ttyp, TRUE));
4766.             }
4767.             (void) mpickobj(shkp, otmp);
4768.             break;
4769.         case HOLE:
4770.         case PIT:
4771.         case SPIKED_PIT:
4772.             if (!catchup && ttmp->tseen && cansee(ttmp->tx, ttmp->ty))
4773.                 pline("The %s is filled in.", trapname(ttmp->ttyp, TRUE));
4774.             break;
4775.         default:
4776.             if (!catchup && ttmp->tseen && cansee(ttmp->tx, ttmp->ty))
4777.                 pline("The %s vanishes.", trapname(ttmp->ttyp, TRUE));
4778.             break;
4779.         }
4780.         deltrap(ttmp);
4781.         del_engr_at(x, y);
4782.         if (seeit)
4783.             newsym(x, y);
4784.         if (!catchup)
4785.             disposition = 3;
4786.     }
4787.     if (IS_ROOM(tmp_dam->typ)
4788.         || (tmp_dam->typ == levl[x][y].typ
4789.             && (!IS_DOOR(tmp_dam->typ) || levl[x][y].doormask > D_BROKEN)))
4790.         /* no terrain fix necessary (trap removal or manually repaired) */
4791.         return disposition;
4792. 
4793.     if (closed_door(x, y))
4794.         stop_picking = picking_at(x, y);
4795. 
4796.     /* door or wall repair; trap, if any, is now gone;
4797.        restore original terrain type and move any items away;
4798.        rm.doormask and rm.wall_info are both overlaid on rm.flags
4799.        so the new flags value needs to match the restored typ */
4800.     levl[x][y].typ = tmp_dam->typ;
4801.     if (IS_DOOR(tmp_dam->typ))
4802.         levl[x][y].doormask = D_CLOSED; /* arbitrary */
4803.     else /* not a door; set rm.wall_info or whatever old flags are relevant */
4804.         levl[x][y].flags = tmp_dam->flags;
4805. 
4806.     if (litter_getpos(litter, x, y, shkp))
4807.         litter_scatter(litter, x, y, shkp);
4808.     del_engr_at(x, y);
4809. 
4810.     /* needed if hero has line-of-sight to the former gap from outside
4811.        the shop but is farther than one step away; once the light inside
4812.        the shop is blocked, the other newsym() below won't redraw the
4813.        spot showing its repaired wall */
4814.     if (seeit)
4815.         newsym(x, y);
4816.     block_point(x, y);
4817. 
4818.     if (catchup)
4819.         return 1; /* repair occurred while off level so no messages */
4820. 
4821.     if (seeit) {
4822.         if (IS_WALL(tmp_dam->typ)) {
4823.             /* player sees actual repair process, so KNOWS it's a wall */
4824.             levl[x][y].seenv = SVALL;
4825.             pline("Suddenly, a section of the wall closes up!");
4826.         } else if (IS_DOOR(tmp_dam->typ)) {
4827.             pline("Suddenly, the shop door reappears!");
4828.         }
4829.         newsym(x, y);
4830.     } else if (IS_WALL(tmp_dam->typ)) {
4831.         if (inside_shop(u.ux, u.uy) == ESHK(shkp)->shoproom)
4832.             You_feel("more claustrophobic than before.");
4833.         else if (!Deaf && !rn2(10))
4834.             Norep("The dungeon acoustics noticeably change.");
4835.     }
4836. 
4837.     if (stop_picking)
4838.         stop_occupation();
4839. 
4840.     litter_newsyms(litter, x, y);
4841. 
4842.     if (disposition < 3)
4843.         disposition = 2;
4844.     return disposition;
4845. }
4846. 
4847. /* normally repair is done when a shopkeeper moves, but we also try to
4848.    catch up for lost time when reloading a previously visited level */
4849. void
4850. fix_shop_damage(void)
4851. {
4852.     struct monst *shkp;
4853.     struct damage *damg, *nextdamg;
4854. 
4855.     /* if this level has no shop damage, there's nothing to do */
4856.     if (!svl.level.damagelist)
4857.         return;
4858. 
4859.     /* go through all shopkeepers on the level */
4860.     for (shkp = next_shkp(fmon, FALSE); shkp;
4861.          shkp = next_shkp(shkp->nmon, FALSE)) {
4862.         /* if this shopkeeper isn't in his shop or can't move, skip */
4863.         if (shk_impaired(shkp))
4864.             continue;
4865.         /* go through all damage data trying to have this shopkeeper
4866.            fix it; repair_damage() will only make repairs for damage
4867.            matching shop controlled by specified shopkeeper */
4868.         for (damg = svl.level.damagelist; damg; damg = nextdamg) {
4869.             nextdamg = damg->next;
4870.             if (repair_damage(shkp, damg, TRUE))
4871.                 discard_damage_struct(damg);
4872.         }
4873.     }
4874. }
4875. 
4876. /*
4877.  * shk_move: return 1: moved  0: didn't  -1: let m_move do it  -2: died
4878.  */
4879. int
4880. shk_move(struct monst *shkp)
4881. {
4882.     coordxy gtx, gty, omx, omy;
4883.     int udist;
4884.     schar appr;
4885.     struct eshk *eshkp = ESHK(shkp);
4886.     int z;
4887.     boolean uondoor = FALSE, satdoor, avoid = FALSE, badinv;
4888. 
4889.     omx = shkp->mx;
4890.     omy = shkp->my;
4891. 
4892.     if (inhishop(shkp))
4893.         shk_fixes_damage(shkp);
4894. 
4895.     if ((udist = distu(omx, omy)) < 3 && (shkp->data != &mons[PM_GRID_BUG]
4896.                                           || (omx == u.ux || omy == u.uy))) {
4897.         if (ANGRY(shkp) || (Conflict && !resist_conflict(shkp))) {
4898.             if (Displaced)
4899.                 Your("displaced image doesn't fool %s!", shkname(shkp));
4900.             (void) mattacku(shkp);
4901.             return 0;
4902.         }
4903.         if (eshkp->following) {
4904.             if (strncmp(eshkp->customer, svp.plname, PL_NSIZ)) {
4905.                 if (!Deaf && !muteshk(shkp)) {
4906.                     SetVoice(shkp, 0, 80, 0);
4907.                     verbalize("%s, %s!  I was looking for %s.", Hello(shkp),
4908.                               svp.plname, eshkp->customer);
4909.                 }
4910.                 eshkp->following = 0;
4911.                 return 0;
4912.             }
4913.             if (svm.moves > gf.followmsg + 4) {
4914.                 if (!Deaf && !muteshk(shkp)) {
4915.                     SetVoice(shkp, 0, 80, 0);
4916.                     verbalize("%s, %s!  Didn't you forget to pay?",
4917.                               Hello(shkp), svp.plname);
4918.                 } else {
4919.                     pline("%s holds out %s upturned %s.",
4920.                           Shknam(shkp), noit_mhis(shkp),
4921.                           mbodypart(shkp, HAND));
4922.                 }
4923.                 gf.followmsg = svm.moves;
4924.                 if (!rn2(9)) {
4925.                     pline("%s doesn't like customers who don't pay.",
4926.                           Shknam(shkp));
4927.                     rile_shk(shkp);
4928.                 }
4929.             }
4930.             if (udist < 2)
4931.                 return 0;
4932.         }
4933.     }
4934. 
4935.     appr = 1;
4936.     gtx = eshkp->shk.x;
4937.     gty = eshkp->shk.y;
4938.     satdoor = (gtx == omx && gty == omy);
4939.     if (eshkp->following || ((z = holetime()) >= 0 && z * z <= udist)) {
4940.         /* [This distance check used to apply regardless of
4941.             whether the shk was following, but that resulted in
4942.             m_move() sometimes taking the shk out of the shop if
4943.             the player had fenced him in with boulders or traps.
4944.             Such voluntary abandonment left unpaid objects in
4945.             invent, triggering billing impossibilities on the
4946.             next level once the character fell through the hole.] */
4947.         if (udist > 4 && eshkp->following && !eshkp->billct)
4948.             return -1; /* leave it to m_move */
4949.         gtx = u.ux;
4950.         gty = u.uy;
4951.     } else if (ANGRY(shkp)) {
4952.         /* Move towards the hero if the shopkeeper can see him. */
4953.         if (shkp->mcansee && m_canseeu(shkp)) {
4954.             gtx = u.ux;
4955.             gty = u.uy;
4956.         }
4957.         avoid = FALSE;
4958.     } else {
4959. #define GDIST(x, y) (dist2(x, y, gtx, gty))
4960.         if (Invis || u.usteed) {
4961.             avoid = FALSE;
4962.         } else {
4963.             uondoor = u_at(eshkp->shd.x, eshkp->shd.y);
4964.             if (uondoor) {
4965.                 badinv = (carrying(PICK_AXE) || carrying(DWARVISH_MATTOCK)
4966.                           || (Fast && (sobj_at(PICK_AXE, u.ux, u.uy)
4967.                                   || sobj_at(DWARVISH_MATTOCK, u.ux, u.uy))));
4968.                 if (satdoor && badinv)
4969.                     return 0;
4970.                 avoid = !badinv;
4971.             } else {
4972.                 avoid = (*u.ushops && distu(gtx, gty) > 8);
4973.                 badinv = FALSE;
4974.             }
4975. 
4976.             if (((!eshkp->robbed && !eshkp->billct && !eshkp->debit) || avoid)
4977.                 && GDIST(omx, omy) < 3) {
4978.                 if (!badinv && !onlineu(omx, omy))
4979.                     return 0;
4980.                 if (satdoor)
4981.                     appr = gtx = gty = 0;
4982.             }
4983.         }
4984. #undef GDIST
4985.     }
4986. 
4987.     z = move_special(shkp, inhishop(shkp), appr, uondoor, avoid, omx, omy,
4988.                      gtx, gty);
4989.     if (z > 0)
4990.         after_shk_move(shkp);
4991. 
4992.     return z;
4993. }
4994. 
4995. /* called after shopkeeper moves, in case move causes re-entry into shop */
4996. void
4997. after_shk_move(struct monst *shkp)
4998. {
4999.     struct eshk *eshkp = ESHK(shkp);
5000. 
5001.     if (eshkp->bill_p == (struct bill_x *) -1000 && inhishop(shkp)) {
5002.         /* reset bill_p, need to re-calc player's occupancy too */
5003.         eshkp->bill_p = &eshkp->bill[0];
5004.         /* only re-check occupancy if game hasn't just ended */
5005.         if (!program_state.gameover)
5006.             check_special_room(FALSE);
5007.     }
5008. }
5009. 
5010. /* for use in levl_follower (mondata.c) */
5011. boolean
5012. is_fshk(struct monst *mtmp)
5013. {
5014.     return (boolean) (mtmp->isshk && ESHK(mtmp)->following);
5015. }
5016. 
5017. /* You are digging in the shop. */
5018. void
5019. shopdig(int fall)
5020. {
5021.     struct monst *shkp = shop_keeper(*u.ushops);
5022.     int lang;
5023.     const char *grabs = "grabs";
5024. 
5025.     if (!shkp)
5026.         return;
5027.     if (!inhishop(shkp)) {
5028.         if (Role_if(PM_KNIGHT)) {
5029.             You_feel("like a common thief.");
5030.             adjalign(-sgn(u.ualign.type));
5031.         }
5032.         return;
5033.     }
5034.     /* 0 == can't speak, 1 == makes animal noises, 2 == speaks */
5035.     lang = 0;
5036.     if (helpless(shkp) || is_silent(shkp->data))
5037.         ; /* lang stays 0 */
5038.     else if (shkp->data->msound <= MS_ANIMAL)
5039.         lang = 1;
5040.     else if (shkp->data->msound >= MS_HUMANOID)
5041.         lang = 2;
5042. 
5043.     if (!fall) {
5044.         if (lang == 2) {
5045.             if (!Deaf && !muteshk(shkp)) {
5046.                 SetVoice(shkp, 0, 80, 0);
5047.                 if (u.utraptype == TT_PIT) {
5048.                     verbalize(
5049.                        "Be careful, %s, or you might fall through the floor.",
5050.                               flags.female ? "madam" : "sir");
5051.                 } else {
5052.                     verbalize("%s, do not damage the floor here!",
5053.                               flags.female ? "Madam" : "Sir");
5054.                 }
5055.             }
5056.         }
5057.         if (Role_if(PM_KNIGHT)) {
5058.             You_feel("like a common thief.");
5059.             adjalign(-sgn(u.ualign.type));
5060.         }
5061.     } else if (!um_dist(shkp->mx, shkp->my, 5)
5062.                && !helpless(shkp)
5063.                && (ESHK(shkp)->billct || ESHK(shkp)->debit)) {
5064.         struct obj *obj, *obj2;
5065. 
5066.         if (nolimbs(shkp->data)) {
5067.             grabs = "knocks off";
5068. #if 0
5069.             /* This is what should happen, but for balance
5070.              * reasons, it isn't currently.
5071.              */
5072.             if (lang == 2)
5073.                 pline("%s curses %s inability to grab your backpack!",
5074.                       Shknam(shkp), noit_mhim(shkp));
5075.             rile_shk(shkp);
5076.             return;
5077. #endif
5078.         }
5079.         if (!m_next2u(shkp)) {
5080.             mnexto(shkp, RLOC_MSG);
5081.             /* for some reason the shopkeeper can't come next to you */
5082.             if (!m_next2u(shkp)) {
5083.                 if (lang == 2)
5084.                     pline("%s curses you in anger and frustration!",
5085.                           Shknam(shkp));
5086.                 else if (lang == 1)
5087.                     growl(shkp);
5088.                 rile_shk(shkp);
5089.                 return;
5090.             } else
5091.                 pline("%s %s, and %s your backpack!", Shknam(shkp),
5092.                       makeplural(locomotion(shkp->data, "leap")), grabs);
5093.         } else
5094.             pline("%s %s your backpack!", Shknam(shkp), grabs);
5095. 
5096.         for (obj = gi.invent; obj; obj = obj2) {
5097.             obj2 = obj->nobj;
5098.             if ((obj->owornmask & ~(W_SWAPWEP | W_QUIVER)) != 0
5099.                 || (obj == uswapwep && u.twoweap)
5100.                 || (obj->otyp == LEASH && obj->leashmon))
5101.                 continue;
5102.             if (obj == gc.current_wand)
5103.                 continue;
5104.             setnotworn(obj);
5105.             freeinv(obj);
5106.             subfrombill(obj, shkp);
5107.             (void) add_to_minv(shkp, obj); /* may free obj */
5108.         }
5109.     }
5110. }
5111. 
5112. staticfn void
5113. makekops(coord *mm)
5114. {
5115.     static const short k_mndx[4] = { PM_KEYSTONE_KOP, PM_KOP_SERGEANT,
5116.                                      PM_KOP_LIEUTENANT, PM_KOP_KAPTAIN };
5117.     int k_cnt[4], cnt, mndx, k;
5118. 
5119.     k_cnt[0] = cnt = abs(depth(&u.uz)) + rnd(5);
5120.     k_cnt[1] = (cnt / 3) + 1; /* at least one sarge */
5121.     k_cnt[2] = (cnt / 6);     /* maybe a lieutenant */
5122.     k_cnt[3] = (cnt / 9);     /* and maybe a kaptain */
5123. 
5124.     for (k = 0; k < 4; k++) {
5125.         if ((cnt = k_cnt[k]) == 0)
5126.             break;
5127.         mndx = k_mndx[k];
5128.         if (svm.mvitals[mndx].mvflags & G_GONE)
5129.             continue;
5130. 
5131.         while (cnt--)
5132.             if (enexto(mm, mm->x, mm->y, &mons[mndx]))
5133.                 (void) makemon(&mons[mndx], mm->x, mm->y, MM_NOMSG);
5134.     }
5135. }
5136. 
5137. staticfn void
5138. getcad(
5139.     struct monst *shkp, const char *dmgstr, coordxy x, coordxy y,
5140.     boolean uinshp, boolean animal, boolean pursue)
5141. {
5142.     boolean dugwall = (!strcmp(dmgstr, "dig into")    /* wand */
5143.                     || !strcmp(dmgstr, "damage")); /* pick-axe */
5144. 
5145.     if (muteshk(shkp)) {
5146.         if (animal && !helpless(shkp))
5147.             yelp(shkp);
5148.     } else if (pursue || uinshp || !um_dist(x, y, 1)) {
5149.         if (!Deaf) {
5150.             SetVoice(shkp, 0, 80, 0);
5151.             verbalize("How dare you %s my %s?", dmgstr,
5152.                         dugwall ? "shop" : "door");
5153.         } else {
5154.             pline("%s is %s that you decided to %s %s %s!",
5155.                     Shknam(shkp), ROLL_FROM(angrytexts),
5156.                     dmgstr, noit_mhis(shkp), dugwall ? "shop" : "door");
5157.         }
5158.     } else {
5159.         if (!Deaf) {
5160.             pline("%s shouts:", Shknam(shkp));
5161.             SetVoice(shkp, 0, 80, 0);
5162.             verbalize("Who dared %s my %s?", dmgstr,
5163.                         dugwall ? "shop" : "door");
5164.         } else {
5165.             pline("%s is %s that someone decided to %s %s %s!",
5166.                     Shknam(shkp), ROLL_FROM(angrytexts),
5167.                     dmgstr, noit_mhis(shkp), dugwall ? "shop" : "door");
5168.         }
5169.     }
5170.     hot_pursuit(shkp);
5171. }
5172. 
5173. void
5174. pay_for_damage(const char *dmgstr, boolean cant_mollify)
5175. {
5176.     struct monst *shkp = (struct monst *) 0;
5177.     char shops_affected[5];
5178.     boolean uinshp = (*u.ushops != '\0');
5179.     char qbuf[80];
5180.     coordxy x, y;
5181.     boolean animal, pursue;
5182.     struct damage *tmp_dam, *appear_here = 0;
5183.     long cost_of_damage = 0L;
5184.     unsigned int nearest_shk = (ROWNO * ROWNO) + (COLNO * COLNO),
5185.                  nearest_damage = nearest_shk;
5186.     int picks = 0;
5187. 
5188.     for (tmp_dam = svl.level.damagelist; tmp_dam; tmp_dam = tmp_dam->next) {
5189.         char *shp;
5190. 
5191.         if (tmp_dam->when != svm.moves || !tmp_dam->cost)
5192.             continue;
5193.         cost_of_damage += tmp_dam->cost;
5194.         Strcpy(shops_affected,
5195.                in_rooms(tmp_dam->place.x, tmp_dam->place.y, SHOPBASE));
5196.         for (shp = shops_affected; *shp; shp++) {
5197.             struct monst *tmp_shk;
5198.             unsigned int shk_distance;
5199. 
5200.             if (!(tmp_shk = shop_keeper(*shp)))
5201.                 continue;
5202.             if (tmp_shk == shkp) {
5203.                 unsigned int damage_distance =
5204.                     distu(tmp_dam->place.x, tmp_dam->place.y);
5205. 
5206.                 if (damage_distance < nearest_damage) {
5207.                     nearest_damage = damage_distance;
5208.                     appear_here = tmp_dam;
5209.                 }
5210.                 continue;
5211.             }
5212.             if (!inhishop(tmp_shk))
5213.                 continue;
5214.             shk_distance = mdistu(tmp_shk);
5215.             if (shk_distance > nearest_shk)
5216.                 continue;
5217.             if ((shk_distance == nearest_shk) && picks) {
5218.                 if (rn2(++picks))
5219.                     continue;
5220.             } else
5221.                 picks = 1;
5222.             shkp = tmp_shk;
5223.             nearest_shk = shk_distance;
5224.             appear_here = tmp_dam;
5225.             nearest_damage = distu(tmp_dam->place.x, tmp_dam->place.y);
5226.         }
5227.     }
5228. 
5229.     if (!cost_of_damage || !shkp)
5230.         return;
5231. 
5232.     animal = (shkp->data->msound <= MS_ANIMAL);
5233.     pursue = FALSE;
5234.     x = appear_here->place.x;
5235.     y = appear_here->place.y;
5236. 
5237.     /* not the best introduction to the shk... */
5238.     (void) strncpy(ESHK(shkp)->customer, svp.plname, PL_NSIZ);
5239. 
5240.     /* if the shk is already on the war path, be sure it's all out */
5241.     if (ANGRY(shkp) || ESHK(shkp)->following) {
5242.         hot_pursuit(shkp);
5243.         return;
5244.     }
5245. 
5246.     /* if the shk is not in their shop.. */
5247.     if (!*in_rooms(shkp->mx, shkp->my, SHOPBASE)) {
5248.         if (!cansee(shkp->mx, shkp->my))
5249.             return;
5250.         pursue = TRUE;
5251.         getcad(shkp, dmgstr, x, y, uinshp, animal, pursue);
5252.         return;
5253.     }
5254. 
5255.     if (uinshp) {
5256.         if (um_dist(shkp->mx, shkp->my, 1)
5257.             && !um_dist(shkp->mx, shkp->my, 3)) {
5258.             pline("%s leaps towards you!", Shknam(shkp));
5259.             mnexto(shkp, RLOC_NOMSG);
5260.         }
5261.         pursue = um_dist(shkp->mx, shkp->my, 1);
5262.         if (pursue) {
5263.             getcad(shkp, dmgstr, x, y, uinshp, animal, pursue);
5264.             return;
5265.         }
5266.     } else {
5267.         /*
5268.          * Make shkp show up at the door.  Effect:  If there is a monster
5269.          * in the doorway, have the hero hear the shopkeeper yell a bit,
5270.          * pause, then have the shopkeeper appear at the door, having
5271.          * yanked the hapless critter out of the way.
5272.          */
5273.         if (MON_AT(x, y)) {
5274.             if (!animal) {
5275.                 if (!Deaf && !muteshk(shkp)) {
5276.                     /* Soundeffect(se_angry_voice, 75); */
5277.                     You_hear("an angry voice:");
5278.                     SetVoice(shkp, 0, 80, 0);
5279.                     verbalize("Out of my way, scum!");
5280.                 }
5281.                 wait_synch();
5282. #if defined(UNIX) || defined(VMS)
5283. #if defined(SYSV) || defined(ULTRIX) || defined(VMS)
5284.                 (void)
5285. #endif
5286.                     sleep(1);
5287. #endif
5288.             } else {
5289.                 growl(shkp);
5290.             }
5291.         }
5292.         (void) mnearto(shkp, x, y, TRUE, RLOC_MSG);
5293.     }
5294. 
5295.     if ((um_dist(x, y, 1) && !uinshp) || cant_mollify
5296.         || (money_cnt(gi.invent) + ESHK(shkp)->credit) < cost_of_damage
5297.         || !rn2(50)) {
5298.         getcad(shkp, dmgstr, x, y, uinshp, animal, pursue);
5299.         return;
5300.     }
5301. 
5302.     if (Invis)
5303.         Your("invisibility does not fool %s!", shkname(shkp));
5304.     Sprintf(qbuf, "%sYou did %ld %s worth of damage!%s  Pay?",
5305.             !animal ? cad(TRUE) : "", cost_of_damage,
5306.             currency(cost_of_damage), !animal ? "\"" : "");
5307.     if (y_n(qbuf) != 'n') {
5308.         boolean is_seen, was_seen = canseemon(shkp),
5309.                 was_outside = !inhishop(shkp);
5310.         coordxy sx = shkp->mx, sy = shkp->my;
5311. 
5312.         cost_of_damage = check_credit(cost_of_damage, shkp);
5313.         if (cost_of_damage > 0L) {
5314.             money2mon(shkp, cost_of_damage);
5315.             disp.botl = TRUE;
5316.         }
5317.         pline("Mollified, %s accepts your restitution.", shkname(shkp));
5318.         /* move shk back to his home loc */
5319.         home_shk(shkp, FALSE);
5320.         pacify_shk(shkp, FALSE);
5321.         /* home_shk() suppresses rloc()'s vanish/appear messages */
5322.         if (shkp->mx != sx || shkp->my != sy) {
5323.             if (was_outside && canspotmon(shkp))
5324.                 pline("%s returns to %s shop.", Shknam(shkp),
5325.                       noit_mhis(shkp));
5326.             else if ((is_seen = canseemon(shkp)) == TRUE || was_seen)
5327.                 pline("%s %s.", Shknam(shkp), !was_seen ? "appears"
5328.                                               : is_seen ? "shifts location"
5329.                                                 : "disappears");
5330.         }
5331.     } else {
5332.         if (!animal) {
5333.             if (!Deaf && !muteshk(shkp)) {
5334.                 SetVoice(shkp, 0, 80, 0);
5335.                 verbalize("Oh, yes!  You'll pay!");
5336.             } else {
5337.                 pline("%s lunges %s %s toward your %s!",
5338.                       Shknam(shkp), noit_mhis(shkp),
5339.                       mbodypart(shkp, HAND), body_part(NECK));
5340.             }
5341.         } else
5342.             growl(shkp);
5343.         hot_pursuit(shkp);
5344.         adjalign(-sgn(u.ualign.type));
5345.     }
5346. }
5347. 
5348. /* called in dokick.c when we kick an object that might be in a store */
5349. boolean
5350. costly_spot(coordxy x, coordxy y)
5351. {
5352.     struct monst *shkp;
5353.     struct eshk *eshkp;
5354. 
5355.     if (!svl.level.flags.has_shop)
5356.         return FALSE;
5357.     shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
5358.     if (!shkp || !inhishop(shkp))
5359.         return FALSE;
5360.     eshkp = ESHK(shkp);
5361.     return  (boolean) (inside_shop(x, y)
5362.                        && !(x == eshkp->shk.x && y == eshkp->shk.y));
5363. }
5364. 
5365. /* called by sanity checking when an unpaid or no_charge item is not at a
5366.    costly_spot; it might still be within the boundary of the shop; if so,
5367.    those flags are still valid */
5368. boolean
5369. costly_adjacent(
5370.     struct monst *shkp,
5371.     coordxy x, coordxy y)
5372. {
5373.     struct eshk *eshkp;
5374. 
5375.     if (!shkp || !inhishop(shkp) || !isok(x, y))
5376.         return FALSE;
5377.     eshkp = ESHK(shkp);
5378.     /* adjacent if <x,y> is a shop wall spot, including door;
5379.        also treat "free spot" one step inside the door as adjacent */
5380.     return (levl[x][y].edge || (x == eshkp->shk.x && y == eshkp->shk.y));
5381. }
5382. 
5383. /* called by dotalk(sounds.c) when #chatting; returns obj if location
5384.    contains shop goods and shopkeeper is willing & able to speak */
5385. struct obj *
5386. shop_object(coordxy x, coordxy y)
5387. {
5388.     struct obj *otmp;
5389.     struct monst *shkp;
5390. 
5391.     shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
5392.     if (!shkp || !inhishop(shkp))
5393.         return (struct obj *) 0;
5394. 
5395.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp->nexthere)
5396.         if (otmp->oclass != COIN_CLASS)
5397.             break;
5398.     /* note: otmp might have ->no_charge set, but that's ok */
5399.     return (otmp && costly_spot(x, y) && NOTANGRY(shkp) && !muteshk(shkp))
5400.                ? otmp
5401.                : (struct obj *) 0;
5402. }
5403. 
5404. /* give price quotes for all objects linked to this one (ie, on this spot) */
5405. void
5406. price_quote(struct obj *first_obj)
5407. {
5408.     struct obj *otmp;
5409.     char buf[BUFSZ], price[40];
5410.     long cost = 0L;
5411.     int cnt = 0;
5412.     boolean contentsonly = FALSE;
5413.     winid tmpwin;
5414.     struct monst *shkp;
5415. 
5416.     shkp = shop_keeper(inside_shop(u.ux, u.uy));
5417.     /* caller has verified that there is a shopkeeper, but the static
5418.        analyzer doesn't realize it */
5419.     if (!shkp || !inhishop(shkp))
5420.         return;
5421. 
5422.     tmpwin = create_nhwindow(NHW_MENU);
5423.     putstr(tmpwin, 0, "Fine goods for sale:");
5424.     putstr(tmpwin, 0, "");
5425.     for (otmp = first_obj; otmp; otmp = otmp->nexthere) {
5426.         if (otmp->oclass == COIN_CLASS)
5427.             continue;
5428.         cost = (otmp->no_charge || otmp == uball || otmp == uchain) ? 0L
5429.                  : get_cost(otmp, shkp);
5430.         contentsonly = !cost;
5431.         if (Has_contents(otmp))
5432.             cost += contained_cost(otmp, shkp, 0L, FALSE, FALSE);
5433.         if (otmp->globby)
5434.             cost *= get_pricing_units(otmp);  /* always quan 1, vary by wt */
5435.         if (!cost) {
5436.             Strcpy(price, "no charge");
5437.             contentsonly = FALSE;
5438.         } else {
5439.             Sprintf(price, "%ld %s%s", cost, currency(cost),
5440.                     (otmp->quan) > 1L ? " each" : "");
5441.         }
5442.         Sprintf(buf, "%s%s, %s", contentsonly ? the_contents_of : "",
5443.                 doname(otmp), price);
5444.         putstr(tmpwin, 0, buf), cnt++;
5445.     }
5446.     if (cnt > 1) {
5447.         display_nhwindow(tmpwin, TRUE);
5448.     } else if (cnt == 1) {
5449.         if (!cost) {
5450.             /* "<doname(obj)>, no charge" */
5451.             SetVoice(shkp, 0, 80, 0);
5452.             verbalize("%s!", upstart(buf)); /* buf contains the string */
5453.         } else {
5454.             /* print cost in slightly different format, so can't reuse buf;
5455.                cost and contentsonly are already set up */
5456.             Sprintf(buf, "%s%s", contentsonly ? the_contents_of : "",
5457.                     doname(first_obj));
5458.             SetVoice(shkp, 0, 80, 0);
5459.             verbalize("%s, price %ld %s%s%s", upstart(buf), cost,
5460.                       currency(cost), (first_obj->quan > 1L) ? " each" : "",
5461.                       contentsonly ? "." : shk_embellish(first_obj, cost));
5462.         }
5463.     }
5464.     destroy_nhwindow(tmpwin);
5465. }
5466. 
5467. staticfn const char *
5468. shk_embellish(struct obj *itm, long cost)
5469. {
5470.     if (!rn2(3)) {
5471.         int o, choice = rn2(5);
5472. 
5473.         if (choice == 0)
5474.             choice = (cost < 100L ? 1 : cost < 500L ? 2 : 3);
5475.         switch (choice) {
5476.         case 4:
5477.             if (cost < 10L)
5478.                 break;
5479.             else
5480.                 o = itm->oclass;
5481.             if (o == FOOD_CLASS)
5482.                 return ", gourmets' delight!";
5483.             if (objects[itm->otyp].oc_name_known
5484.                     ? objects[itm->otyp].oc_magic
5485.                     : (o == AMULET_CLASS || o == RING_CLASS || o == WAND_CLASS
5486.                        || o == POTION_CLASS || o == SCROLL_CLASS
5487.                        || o == SPBOOK_CLASS))
5488.                 return ", painstakingly developed!";
5489.             return ", superb craftsmanship!";
5490.         case 3:
5491.             return ", finest quality.";
5492.         case 2:
5493.             return ", an excellent choice.";
5494.         case 1:
5495.             return ", a real bargain.";
5496.         default:
5497.             break;
5498.         }
5499.     } else if (itm->oartifact) {
5500.         return ", one of a kind!";
5501.     }
5502.     return ".";
5503. }
5504. 
5505. DISABLE_WARNING_FORMAT_NONLITERAL
5506. 
5507. /* First 4 supplied by Ronen and Tamar, remainder by development team */
5508. static const char *Izchak_speaks[] = {
5509.     "%s says: 'These shopping malls give me a headache.'",
5510.     "%s says: 'Slow down.  Think clearly.'",
5511.     "%s says: 'You need to take things one at a time.'",
5512.     "%s says: 'I don't like poofy coffee... give me Colombian Supremo.'",
5513.     "%s says that getting the devteam's agreement on anything is difficult.",
5514.     "%s says that he has noticed those who serve their deity will prosper.",
5515.     "%s says: 'Don't try to steal from me - I have friends in high places!'",
5516.     "%s says: 'You may well need something from this shop in the future.'",
5517.     "%s comments about the Valley of the Dead as being a gateway."
5518. };
5519. 
5520. void
5521. shk_chat(struct monst *shkp)
5522. {
5523.     struct eshk *eshk;
5524.     long shkmoney;
5525. 
5526.     if (!shkp->isshk) {
5527.         /* The monster type is shopkeeper, but this monster is
5528.            not actually a shk, which could happen if someone
5529.            wishes for a shopkeeper statue and then animates it.
5530.            (Note: shkname() would be "" in a case like this.) */
5531.         pline("%s asks whether you've seen any untended shops recently.",
5532.               Monnam(shkp));
5533.         /* [Perhaps we ought to check whether this conversation
5534.            is taking place inside an untended shop, but a shopless
5535.            shk can probably be expected to be rather disoriented.] */
5536.         return;
5537.     }
5538. 
5539.     eshk = ESHK(shkp);
5540.     if (ANGRY(shkp)) {
5541.         pline("%s %s how much %s dislikes %s customers.",
5542.               Shknam(shkp),
5543.               (!Deaf && !muteshk(shkp)) ? "mentions" : "indicates",
5544.               noit_mhe(shkp), eshk->robbed ? "non-paying" : "rude");
5545.     } else if (eshk->following) {
5546.         if (strncmp(eshk->customer, svp.plname, PL_NSIZ)) {
5547.             if (!Deaf && !muteshk(shkp)) {
5548.                 SetVoice(shkp, 0, 80, 0);
5549.                 verbalize("%s %s!  I was looking for %s.",
5550.                       Hello(shkp), svp.plname, eshk->customer);
5551.             }
5552.             eshk->following = 0;
5553.         } else {
5554.             if (!Deaf && !muteshk(shkp)) {
5555.                 SetVoice(shkp, 0, 80, 0);
5556.                 verbalize("%s %s!  Didn't you forget to pay?",
5557.                           Hello(shkp), svp.plname);
5558.             } else {
5559.                 pline("%s taps you on the %s.",
5560.                       Shknam(shkp), body_part(ARM));
5561.             }
5562.         }
5563.     } else if (eshk->billct) {
5564.         long total = addupbill(shkp) + eshk->debit;
5565. 
5566.         pline("%s %s that your bill comes to %ld %s.",
5567.               Shknam(shkp),
5568.               (!Deaf && !muteshk(shkp)) ? "says" : "indicates",
5569.               total, currency(total));
5570.     } else if (eshk->debit) {
5571.         pline("%s %s that you owe %s %ld %s.",
5572.               Shknam(shkp),
5573.               (!Deaf && !muteshk(shkp)) ? "reminds you" : "indicates",
5574.               noit_mhim(shkp), eshk->debit, currency(eshk->debit));
5575.     } else if (eshk->credit) {
5576.         pline("%s encourages you to use your %ld %s of credit.",
5577.               Shknam(shkp), eshk->credit, currency(eshk->credit));
5578.     } else if (eshk->robbed) {
5579.         pline("%s %s about a recent robbery.",
5580.               Shknam(shkp),
5581.               (!Deaf && !muteshk(shkp)) ? "complains" : "indicates concern");
5582.     } else if (eshk->surcharge) {
5583.         pline("%s %s that %s is watching you carefully.", Shknam(shkp),
5584.               (!Deaf && !muteshk(shkp)) ? "warns you" : "indicates",
5585.               noit_mhe(shkp));
5586.     } else if ((shkmoney = money_cnt(shkp->minvent)) < 50L) {
5587.         pline("%s %s that business is bad.",
5588.               Shknam(shkp),
5589.               (!Deaf && !muteshk(shkp)) ? "complains" : "indicates");
5590.     } else if (shkmoney > 4000) {
5591.         pline("%s %s that business is good.",
5592.               Shknam(shkp),
5593.               (!Deaf && !muteshk(shkp)) ? "says" : "indicates");
5594.     } else if (is_izchak(shkp, FALSE)) {
5595.         if (!Deaf && !muteshk(shkp))
5596.             pline(ROLL_FROM(Izchak_speaks), shkname(shkp));
5597.     } else {
5598.         if (!Deaf && !muteshk(shkp))
5599.             pline("%s talks about the problem of shoplifters.", Shknam(shkp));
5600.     }
5601. }
5602. 
5603. RESTORE_WARNING_FORMAT_NONLITERAL
5604. 
5605. staticfn void
5606. kops_gone(boolean silent)
5607. {
5608.     int cnt = 0;
5609.     struct monst *mtmp, *mtmp2;
5610. 
5611.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
5612.         mtmp2 = mtmp->nmon;
5613.         if (DEADMONSTER(mtmp))
5614.             continue;
5615.         if (mtmp->data->mlet == S_KOP) {
5616.             if (canspotmon(mtmp))
5617.                 cnt++;
5618.             mongone(mtmp);
5619.         }
5620.     }
5621.     if (cnt && !silent)
5622.         pline_The("Kop%s (disappointed) vanish%s into thin air.",
5623.                   plur(cnt), (cnt == 1) ? "es" : "");
5624. }
5625. 
5626. staticfn long
5627. cost_per_charge(
5628.     struct monst *shkp,
5629.     struct obj *otmp,
5630.     boolean altusage) /* some items have "alternate" use with different cost */
5631. {
5632.     long tmp = 0L;
5633. 
5634.     if (!shkp || !inhishop(shkp))
5635.         return 0L; /* insurance */
5636.     tmp = get_cost(otmp, shkp);
5637. 
5638.     /* The idea is to make the exhaustive use of an unpaid item
5639.      * more expensive than buying it outright.
5640.      */
5641.     if (otmp->otyp == MAGIC_LAMP) { /* 1 */
5642.         /* normal use (ie, as light source) of a magic lamp never
5643.            degrades its value, but not charging anything would make
5644.            identification too easy; charge an amount comparable to
5645.            what is charged for an ordinary lamp (don't bother with
5646.            angry shk surcharge) */
5647.         if (!altusage)
5648.             tmp = (long) objects[OIL_LAMP].oc_cost;
5649.         else
5650.             tmp += tmp / 3L;                 /* djinni is being released */
5651.     } else if (otmp->otyp == MAGIC_MARKER) { /* 70 - 100 */
5652.         /* No way to determine in advance how many charges will be
5653.          * wasted.  So, arbitrarily, one half of the price per use.
5654.          */
5655.         tmp /= 2L;
5656.     } else if (otmp->otyp == BAG_OF_TRICKS /* 1 - 20 */
5657.                || otmp->otyp == HORN_OF_PLENTY) {
5658.         /* altusage: emptying of all the contents at once */
5659.         if (!altusage)
5660.             tmp /= 5L;
5661.     } else if (otmp->otyp == CRYSTAL_BALL               /* 1 - 5 */
5662.                || otmp->otyp == OIL_LAMP                /* 1 - 10 */
5663.                || otmp->otyp == BRASS_LANTERN
5664.                || (otmp->otyp >= MAGIC_FLUTE
5665.                    && otmp->otyp <= DRUM_OF_EARTHQUAKE) /* 5 - 9 */
5666.                || otmp->oclass == WAND_CLASS) {         /* 3 - 11 */
5667.         if (otmp->spe > 1)
5668.             tmp /= 4L;
5669.     } else if (otmp->oclass == SPBOOK_CLASS) {
5670.         tmp -= tmp / 5L;
5671.     } else if (otmp->otyp == CAN_OF_GREASE || otmp->otyp == TINNING_KIT
5672.                || otmp->otyp == EXPENSIVE_CAMERA) {
5673.         tmp /= 10L;
5674.     } else if (otmp->otyp == POT_OIL) {
5675.         tmp /= 5L;
5676.     }
5677.     return tmp;
5678. }
5679. 
5680. DISABLE_WARNING_FORMAT_NONLITERAL
5681. 
5682. /* Charge the player for partial use of an unpaid object.
5683.  *
5684.  * Note that bill_dummy_object() should be used instead
5685.  * when an object is completely used.
5686.  */
5687. void
5688. check_unpaid_usage(struct obj *otmp, boolean altusage)
5689. {
5690.     struct monst *shkp;
5691.     const char *fmt, *arg1, *arg2;
5692.     char buf[BUFSZ];
5693.     long tmp;
5694. 
5695.     if (!otmp->unpaid || !*u.ushops
5696.         || (otmp->spe <= 0 && objects[otmp->otyp].oc_charged))
5697.         return;
5698.     shkp = shop_keeper(*u.ushops);
5699.     if (!shkp || !inhishop(shkp))
5700.         return;
5701.     if ((tmp = cost_per_charge(shkp, otmp, altusage)) == 0L)
5702.         return;
5703. 
5704.     arg1 = arg2 = "";
5705.     if (otmp->oclass == SPBOOK_CLASS) {
5706.         fmt = "%sYou owe%s %ld %s.";
5707.         Sprintf(buf, "This is no free library, %s!  ", cad(FALSE));
5708.         arg1 = rn2(2) ? buf : "";
5709.         arg2 = ESHK(shkp)->debit > 0L ? " an additional" : "";
5710.     } else if (otmp->otyp == POT_OIL) {
5711.         fmt = "%s%sThat will cost you %ld %s (Yendorian Fuel Tax).";
5712.     } else if (altusage && (otmp->otyp == BAG_OF_TRICKS
5713.                             || otmp->otyp == HORN_OF_PLENTY)) {
5714.         fmt = "%s%sEmptying that will cost you %ld %s.";
5715.         if (!rn2(3))
5716.             arg1 = "Whoa!  ";
5717.         if (!rn2(3))
5718.             arg1 = "Watch it!  ";
5719.     } else {
5720.         fmt = "%s%sUsage fee, %ld %s.";
5721.         if (!rn2(3))
5722.             arg1 = "Hey!  ";
5723.         if (!rn2(3))
5724.             arg2 = "Ahem.  ";
5725.     }
5726. 
5727.     if (!Deaf && !muteshk(shkp)) {
5728.         SetVoice(shkp, 0, 80, 0);
5729.         verbalize(fmt, arg1, arg2, tmp, currency(tmp));
5730.         exercise(A_WIS, TRUE); /* you just got info */
5731.     }
5732.     ESHK(shkp)->debit += tmp;
5733. }
5734. 
5735. RESTORE_WARNING_FORMAT_NONLITERAL
5736. 
5737. /* for using charges of unpaid objects "used in the normal manner" */
5738. void
5739. check_unpaid(struct obj *otmp)
5740. {
5741.     check_unpaid_usage(otmp, FALSE); /* normal item use */
5742. }
5743. 
5744. void
5745. costly_gold(
5746.     coordxy x, coordxy y,
5747.     long amount,
5748.     boolean silent)
5749. {
5750.     long delta;
5751.     struct monst *shkp;
5752.     struct eshk *eshkp;
5753. 
5754.     if (!costly_spot(x, y))
5755.         return;
5756.     /* shkp is guaranteed to exist after successful costly_spot(), but
5757.        the static analyzer isn't smart enough to realize that, so follow
5758.        the shkp assignment with a redundant test that will always fail */
5759.     shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
5760.     if (!shkp)
5761.         return;
5762. 
5763.     eshkp = ESHK(shkp);
5764.     if (eshkp->credit >= amount) {
5765.         if (!silent) {
5766.             if (eshkp->credit > amount)
5767.                 Your("credit is reduced by %ld %s.", amount, currency(amount));
5768.             else
5769.                 Your("credit is erased.");
5770.         }
5771.         eshkp->credit -= amount;
5772.     } else {
5773.         delta = amount - eshkp->credit;
5774.         if (!silent) {
5775.             if (eshkp->credit)
5776.                 Your("credit is erased.");
5777.             if (eshkp->debit)
5778.                 Your("debt increases by %ld %s.", delta, currency(delta));
5779.             else
5780.                 You("owe %s %ld %s.", shkname(shkp), delta, currency(delta));
5781.         }
5782.         eshkp->debit += delta;
5783.         eshkp->loan += delta;
5784.         eshkp->credit = 0L;
5785.     }
5786. }
5787. 
5788. /* used in domove to block diagonal shop-exit */
5789. /* x,y should always be a door */
5790. boolean
5791. block_door(coordxy x, coordxy y)
5792. {
5793.     int roomno = *in_rooms(x, y, SHOPBASE);
5794.     struct monst *shkp;
5795. 
5796.     if (roomno < 0 || !IS_SHOP(roomno))
5797.         return FALSE;
5798.     if (!IS_DOOR(levl[x][y].typ))
5799.         return FALSE;
5800.     if (roomno != *u.ushops)
5801.         return FALSE;
5802. 
5803.     shkp = shop_keeper((char) roomno);
5804.     if (!shkp || !inhishop(shkp))
5805.         return FALSE;
5806. 
5807.     if (shkp->mx == ESHK(shkp)->shk.x && shkp->my == ESHK(shkp)->shk.y
5808.         /* Actually, the shk should be made to block _any_
5809.          * door, including a door the player digs, if the
5810.          * shk is within a 'jumping' distance.
5811.          */
5812.         && ESHK(shkp)->shd.x == x
5813.         && ESHK(shkp)->shd.y == y
5814.         && !helpless(shkp)
5815.         && (ESHK(shkp)->debit || ESHK(shkp)->billct || ESHK(shkp)->robbed)) {
5816.         pline("%s%s blocks your way!", Shknam(shkp),
5817.               Invis ? " senses your motion and" : "");
5818.         return TRUE;
5819.     }
5820.     return FALSE;
5821. }
5822. 
5823. /* used in domove to block diagonal shop-entry;
5824.    u.ux, u.uy should always be a door */
5825. boolean
5826. block_entry(coordxy x, coordxy y)
5827. {
5828.     coordxy sx, sy;
5829.     int roomno;
5830.     struct monst *shkp;
5831. 
5832.     if (!(IS_DOOR(levl[u.ux][u.uy].typ)
5833.           && levl[u.ux][u.uy].doormask == D_BROKEN))
5834.         return FALSE;
5835. 
5836.     roomno = *in_rooms(x, y, SHOPBASE);
5837.     if (roomno < 0 || !IS_SHOP(roomno))
5838.         return FALSE;
5839.     shkp = shop_keeper((char) roomno);
5840.     if (!shkp || !inhishop(shkp))
5841.         return FALSE;
5842. 
5843.     if (ESHK(shkp)->shd.x != u.ux || ESHK(shkp)->shd.y != u.uy)
5844.         return FALSE;
5845. 
5846.     sx = ESHK(shkp)->shk.x;
5847.     sy = ESHK(shkp)->shk.y;
5848. 
5849.     if (shkp->mx == sx && shkp->my == sy && !helpless(shkp)
5850.         && (x == sx - 1 || x == sx + 1 || y == sy - 1 || y == sy + 1)
5851.         && (Invis || carrying(PICK_AXE) || carrying(DWARVISH_MATTOCK)
5852.             || u.usteed)) {
5853.         pline("%s%s blocks your way!", Shknam(shkp),
5854.               Invis ? " senses your motion and" : "");
5855.         return TRUE;
5856.     }
5857.     return FALSE;
5858. }
5859. 
5860. /* "your " or "Foobar's " (note the trailing space) */
5861. char *
5862. shk_your(char *buf, struct obj *obj)
5863. {
5864.     boolean chk_pm = obj->otyp == CORPSE && ismnum(obj->corpsenm);
5865. 
5866.     buf[0] = '\0';
5867.     if (chk_pm && type_is_pname(&mons[obj->corpsenm]))
5868.         return buf; /* skip ownership prefix and space: "Medusa's corpse" */
5869.     else if (chk_pm && the_unique_pm(&mons[obj->corpsenm]))
5870.         Strcpy(buf, "the"); /* override ownership: "the Oracle's corpse" */
5871.     else if (!shk_owns(buf, obj) && !mon_owns(buf, obj))
5872.         Strcpy(buf, the_your[carried(obj) ? 1 : 0]);
5873.     return strcat(buf, " ");
5874. }
5875. 
5876. char *
5877. Shk_Your(char *buf, struct obj *obj)
5878. {
5879.     (void) shk_your(buf, obj);
5880.     *buf = highc(*buf);
5881.     return buf;
5882. }
5883. 
5884. staticfn char *
5885. shk_owns(char *buf, struct obj *obj)
5886. {
5887.     struct monst *shkp;
5888.     coordxy x, y;
5889. 
5890.     if (get_obj_location(obj, &x, &y, 0)
5891.         && (obj->unpaid || (obj->where == OBJ_FLOOR && !obj->no_charge
5892.                             && costly_spot(x, y)))) {
5893.         shkp = shop_keeper(inside_shop(x, y));
5894.         return strcpy(buf, shkp ? s_suffix(shkname(shkp)) : the_your[0]);
5895.     }
5896.     return (char *) 0;
5897. }
5898. 
5899. staticfn char *
5900. mon_owns(char *buf, struct obj *obj)
5901. {
5902.     if (obj->where == OBJ_MINVENT)
5903.         return strcpy(buf, s_suffix(y_monnam(obj->ocarry)));
5904.     return (char *) 0;
5905. }
5906. 
5907. staticfn const char *
5908. cad(
5909.     boolean altusage) /* used as a verbalized exclamation:  \"Cad! ...\" */
5910. {
5911.     const char *res = 0;
5912. 
5913.     switch (is_demon(gy.youmonst.data) ? 3 : poly_gender()) {
5914.     case 0:
5915.         res = "cad";
5916.         break;
5917.     case 1:
5918.         res = "minx";
5919.         break;
5920.     case 2:
5921.         res = "beast";
5922.         break;
5923.     case 3:
5924.         res = "fiend";
5925.         break;
5926.     default:
5927.         impossible("cad: unknown gender");
5928.         res = "thing";
5929.         break;
5930.     }
5931.     if (altusage) {
5932.         char *cadbuf = mon_nam(&gy.youmonst); /* snag an output buffer */
5933. 
5934.         /* alternate usage adds a leading double quote and trailing
5935.            exclamation point plus sentence separating spaces */
5936.         Sprintf(cadbuf, "\"%s!  ", res);
5937.         cadbuf[1] = highc(cadbuf[1]);
5938.         res = cadbuf;
5939.     }
5940.     return res;
5941. }
5942. 
5943. #ifdef __SASC
5944. void
5945. sasc_bug(struct obj *op, unsigned x)
5946. {
5947.     op->unpaid = x;
5948. }
5949. #endif
5950. 
5951. /*
5952.  * The caller is about to make obj_absorbed go away.
5953.  *
5954.  * There's no way for you (or a shopkeeper) to prevent globs
5955.  * from merging with each other on the floor due to the
5956.  * inherent nature of globs so it irretrievably becomes part
5957.  * of the floor glob mass. When one glob is absorbed by another
5958.  * glob, the two become indistinguishable and the remaining
5959.  * glob object grows in mass, the product of both.
5960.  *
5961.  * billing admin, player compensation, shopkeeper compensation
5962.  * all need to be considered.
5963.  *
5964.  * Any original billed item is lost to the absorption so the
5965.  * original billed amount for the object being absorbed must
5966.  * get added to the cost owing for the absorber, and the
5967.  * separate cost for the object being absorbed goes away.
5968.  *
5969.  * There are four scenarios to deal with:
5970.  *     1. shop_owned glob merging into shop_owned glob
5971.  *     2. player_owned glob merging into shop_owned glob
5972.  *     3. shop_owned glob merging into player_owned glob
5973.  *     4. player_owned glob merging into player_owned glob
5974.  */
5975. void
5976. globby_bill_fixup(struct obj *obj_absorber, struct obj *obj_absorbed)
5977. {
5978.     int x = 0, y = 0;
5979.     struct bill_x *bp, *bp_absorber = (struct bill_x *) 0;
5980.     struct monst *shkp = 0;
5981.     struct eshk *eshkp;
5982.     long amount, per_unit_cost;
5983.     boolean floor_absorber = (obj_absorber->where == OBJ_FLOOR);
5984. 
5985.     if (!obj_absorber->globby)
5986.         impossible("globby_bill_fixup called for non-globby object");
5987. 
5988.     if (floor_absorber) {
5989.         x = obj_absorber->ox, y = obj_absorber->oy;
5990.     }
5991.     if (obj_absorber->unpaid) {
5992.         /* look for a shopkeeper who owns this object */
5993.         for (shkp = next_shkp(fmon, TRUE); shkp;
5994.              shkp = next_shkp(shkp->nmon, TRUE))
5995.             if (onbill(obj_absorber, shkp, TRUE))
5996.                 break;
5997.     } else if (obj_absorbed->unpaid) {
5998.         if (obj_absorbed->where == OBJ_FREE
5999.              && floor_absorber && costly_spot(x, y)) {
6000.             shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
6001.         }
6002.     }
6003.     /* sanity check, in case obj is on bill but not marked 'unpaid' */
6004.     if (!shkp)
6005.         shkp = shop_keeper(*u.ushops);
6006.     if (!shkp)
6007.         return;
6008.     bp_absorber = onbill(obj_absorber, shkp, FALSE);
6009.     bp = onbill(obj_absorbed, shkp, FALSE);
6010.     eshkp = ESHK(shkp);
6011.     per_unit_cost = set_cost(obj_absorbed, shkp);
6012. 
6013.     /**************************************************************
6014.      * Scenario 1. Shop-owned glob absorbing into shop-owned glob
6015.      **************************************************************/
6016.     if (bp && (!obj_absorber->no_charge
6017.                || billable(&shkp, obj_absorber, eshkp->shoproom, FALSE))) {
6018.         /* the glob being absorbed has a billing record */
6019.         amount = bp->price;
6020.         eshkp->billct--;
6021.         *bp = eshkp->bill_p[eshkp->billct];
6022.         clear_unpaid_obj(shkp, obj_absorbed);
6023. 
6024.         if (bp_absorber) {
6025.             /* the absorber has a billing record */
6026.             bp_absorber->price += amount;
6027.         } else {
6028.             /* the absorber has no billing record */
6029.             ;
6030.         }
6031.         return;
6032.     }
6033.     /**************************************************************
6034.      * Scenario 2. Player-owned glob absorbing into shop-owned glob
6035.      **************************************************************/
6036.     if (!bp_absorber && !bp && !obj_absorber->no_charge) {
6037.         /* there are no billing records */
6038.         amount = get_pricing_units(obj_absorbed) * per_unit_cost;
6039.         if (saleable(shkp, obj_absorbed)) {
6040.             if (eshkp->debit >= amount) {
6041.                 if (eshkp->loan) { /* you carry shop's gold */
6042.                    if (eshkp->loan >= amount)
6043.                         eshkp->loan -= amount;
6044.                    else
6045.                         eshkp->loan = 0L;
6046.                 }
6047.                 eshkp->debit -= amount;
6048.                 pline_The("donated %s %spays off your debt.",
6049.                           obj_typename(obj_absorbed->otyp),
6050.                           eshkp->debit ? "partially " : "");
6051.             } else {
6052.                 long delta = amount - eshkp->debit;
6053. 
6054.                 eshkp->credit += delta;
6055.                 if (eshkp->debit) {
6056.                     eshkp->debit = 0L;
6057.                     eshkp->loan = 0L;
6058.                     Your("debt is paid off.");
6059.                 }
6060.                 if (eshkp->credit == delta)
6061.                     pline_The("%s established %ld %s credit.",
6062.                               obj_typename(obj_absorbed->otyp),
6063.                               delta, currency(delta));
6064.                 else
6065.                     pline_The("%s added %ld %s %s %ld %s.",
6066.                               obj_typename(obj_absorbed->otyp),
6067.                               delta, currency(delta),
6068.                               "to your credit; total is now",
6069.                               eshkp->credit, currency(eshkp->credit));
6070.             }
6071.         }
6072.         return;
6073.     } else if (bp_absorber) {
6074.         /* absorber has a billing record */
6075.         bp_absorber->price += per_unit_cost * get_pricing_units(obj_absorbed);
6076.         return;
6077.     }
6078.     /**************************************************************
6079.      * Scenario 3. shop_owned glob merging into player_owned glob
6080.      **************************************************************/
6081.     if (bp && (obj_absorber->no_charge
6082.                || (floor_absorber && !costly_spot(x, y)))) {
6083.         amount = bp->price;
6084.         bill_dummy_object(obj_absorbed);
6085.         SetVoice(shkp, 0, 80, 0);
6086.         verbalize("You owe me %ld %s for my %s that you %s with your%s",
6087.                   amount, currency(amount), obj_typename(obj_absorbed->otyp),
6088.                   ANGRY(shkp) ? "had the audacity to mix" : "just mixed",
6089.                   ANGRY(shkp) ? " stinking batch!" : "s.");
6090.         return;
6091.     }
6092.     /**************************************************************
6093.      * Scenario 4. player_owned glob merging into player_owned glob
6094.      **************************************************************/
6095. 
6096.     return;
6097. }
6098. 
6099. /* Shopkeeper bills for use of a land mine or bear trap they own */
6100. void
6101. use_unpaid_trapobj(struct obj *otmp, coordxy x, coordxy y)
6102. {
6103.     if (otmp->unpaid) {
6104.         if (!Deaf) {
6105.             struct monst *shkp = find_objowner(otmp, x, y);
6106. 
6107.             if (shkp && !muteshk(shkp)) {
6108.                 SetVoice(shkp, 0, 80, 0);
6109.                 verbalize("You set it, you buy it!");
6110.             }
6111.         }
6112.         bill_dummy_object(otmp);
6113.     }
6114. }
6115. 
6116. #undef PAY_BUY
6117. #undef PAY_CANT
6118. #undef PAY_SKIP
6119. #undef PAY_BROKE
6120. #undef NOTANGRY
6121. #undef ANGRY
6122. #undef IS_SHOP
6123. #undef muteshk
6124. 
6125. /*shk.c*/