Source:NetHack 3.6.3/src/end.c

From NetHackWiki
Jump to navigation Jump to search

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

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

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

1. /* NetHack 3.6	end.c	$NHDT-Date: 1575245059 2019/12/02 00:04:19 $  $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.181 $ */
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. #define NEED_VARARGS /* comment line for pre-compiled headers */
7. 
8. #include "hack.h"
9. #include "lev.h"
10. #ifndef NO_SIGNAL
11. #include <signal.h>
12. #endif
13. #include <ctype.h>
14. #ifndef LONG_MAX
15. #include <limits.h>
16. #endif
17. #include "dlb.h"
18. 
19. /* add b to long a, convert wraparound to max value */
20. #define nowrap_add(a, b) (a = ((a + b) < 0 ? LONG_MAX : (a + b)))
21. 
22. /* these probably ought to be generated by makedefs, like LAST_GEM */
23. #define FIRST_GEM DILITHIUM_CRYSTAL
24. #define FIRST_AMULET AMULET_OF_ESP
25. #define LAST_AMULET AMULET_OF_YENDOR
26. 
27. struct valuable_data {
28.     long count;
29.     int typ;
30. };
31. 
32. static struct valuable_data
33.     gems[LAST_GEM + 1 - FIRST_GEM + 1], /* 1 extra for glass */
34.     amulets[LAST_AMULET + 1 - FIRST_AMULET];
35. 
36. static struct val_list {
37.     struct valuable_data *list;
38.     int size;
39. } valuables[] = { { gems, sizeof gems / sizeof *gems },
40.                   { amulets, sizeof amulets / sizeof *amulets },
41.                   { 0, 0 } };
42. 
43. #ifndef NO_SIGNAL
44. STATIC_PTR void FDECL(done_intr, (int));
45. #if defined(UNIX) || defined(VMS) || defined(__EMX__)
46. static void FDECL(done_hangup, (int));
47. #endif
48. #endif
49. STATIC_DCL void FDECL(disclose, (int, BOOLEAN_P));
50. STATIC_DCL void FDECL(get_valuables, (struct obj *));
51. STATIC_DCL void FDECL(sort_valuables, (struct valuable_data *, int));
52. STATIC_DCL void NDECL(done_object_cleanup);
53. STATIC_DCL void FDECL(artifact_score, (struct obj *, BOOLEAN_P, winid));
54. STATIC_DCL void FDECL(really_done, (int)) NORETURN;
55. STATIC_DCL void FDECL(savelife, (int));
56. STATIC_PTR int FDECL(CFDECLSPEC vanqsort_cmp, (const genericptr,
57.                                                const genericptr));
58. STATIC_DCL int NDECL(set_vanq_order);
59. STATIC_DCL void FDECL(list_vanquished, (CHAR_P, BOOLEAN_P));
60. STATIC_DCL void FDECL(list_genocided, (CHAR_P, BOOLEAN_P));
61. STATIC_DCL boolean FDECL(should_query_disclose_option, (int, char *));
62. #ifdef DUMPLOG
63. STATIC_DCL void NDECL(dump_plines);
64. #endif
65. STATIC_DCL void FDECL(dump_everything, (int, time_t));
66. STATIC_DCL int NDECL(num_extinct);
67. 
68. #if defined(__BEOS__) || defined(MICRO) || defined(OS2)
69. extern void FDECL(nethack_exit, (int));
70. #else
71. #define nethack_exit exit
72. #endif
73. 
74. #define done_stopprint program_state.stopprint
75. 
76. #ifndef PANICTRACE
77. #define NH_abort NH_abort_
78. #endif
79. 
80. #ifdef AMIGA
81. #define NH_abort_() Abort(0)
82. #else
83. #ifdef SYSV
84. #define NH_abort_() (void) abort()
85. #else
86. #ifdef WIN32
87. #define NH_abort_() win32_abort()
88. #else
89. #define NH_abort_() abort()
90. #endif
91. #endif /* !SYSV */
92. #endif /* !AMIGA */
93. 
94. #ifdef PANICTRACE
95. #include <errno.h>
96. #ifdef PANICTRACE_LIBC
97. #include <execinfo.h>
98. #endif
99. 
100. /* What do we try and in what order?  Tradeoffs:
101.  * libc: +no external programs required
102.  *        -requires newish libc/glibc
103.  *        -requires -rdynamic
104.  * gdb:   +gives more detailed information
105.  *        +works on more OS versions
106.  *        -requires -g, which may preclude -O on some compilers
107.  */
108. #ifdef SYSCF
109. #define SYSOPT_PANICTRACE_GDB sysopt.panictrace_gdb
110. #ifdef PANICTRACE_LIBC
111. #define SYSOPT_PANICTRACE_LIBC sysopt.panictrace_libc
112. #else
113. #define SYSOPT_PANICTRACE_LIBC 0
114. #endif
115. #else
116. #define SYSOPT_PANICTRACE_GDB (nh_getenv("NETHACK_USE_GDB") == 0 ? 0 : 2)
117. #ifdef PANICTRACE_LIBC
118. #define SYSOPT_PANICTRACE_LIBC 1
119. #else
120. #define SYSOPT_PANICTRACE_LIBC 0
121. #endif
122. #endif
123. 
124. static void NDECL(NH_abort);
125. #ifndef NO_SIGNAL
126. static void FDECL(panictrace_handler, (int));
127. #endif
128. static boolean NDECL(NH_panictrace_libc);
129. static boolean NDECL(NH_panictrace_gdb);
130. 
131. #ifndef NO_SIGNAL
132. /* called as signal() handler, so sent at least one arg */
133. /*ARGUSED*/
134. void
135. panictrace_handler(sig_unused)
136. int sig_unused UNUSED;
137. {
138. #define SIG_MSG "\nSignal received.\n"
139.     int f2;
140.     
141.     f2 = (int) write(2, SIG_MSG, sizeof SIG_MSG - 1);
142.     nhUse(f2);  /* what could we do if write to fd#2 (stderr) fails  */
143.     NH_abort(); /* ... and we're already in the process of quitting? */
144. }
145. 
146. void
147. panictrace_setsignals(set)
148. boolean set;
149. {
150. #define SETSIGNAL(sig) \
151.     (void) signal(sig, set ? (SIG_RET_TYPE) panictrace_handler : SIG_DFL);
152. #ifdef SIGILL
153.     SETSIGNAL(SIGILL);
154. #endif
155. #ifdef SIGTRAP
156.     SETSIGNAL(SIGTRAP);
157. #endif
158. #ifdef SIGIOT
159.     SETSIGNAL(SIGIOT);
160. #endif
161. #ifdef SIGBUS
162.     SETSIGNAL(SIGBUS);
163. #endif
164. #ifdef SIGFPE
165.     SETSIGNAL(SIGFPE);
166. #endif
167. #ifdef SIGSEGV
168.     SETSIGNAL(SIGSEGV);
169. #endif
170. #ifdef SIGSTKFLT
171.     SETSIGNAL(SIGSTKFLT);
172. #endif
173. #ifdef SIGSYS
174.     SETSIGNAL(SIGSYS);
175. #endif
176. #ifdef SIGEMT
177.     SETSIGNAL(SIGEMT);
178. #endif
179. #undef SETSIGNAL
180. }
181. #endif /* NO_SIGNAL */
182. 
183. static void
184. NH_abort()
185. {
186.     int gdb_prio = SYSOPT_PANICTRACE_GDB;
187.     int libc_prio = SYSOPT_PANICTRACE_LIBC;
188.     static boolean aborting = FALSE;
189. 
190.     if (aborting)
191.         return;
192.     aborting = TRUE;
193. 
194. #ifndef VMS
195.     if (gdb_prio == libc_prio && gdb_prio > 0)
196.         gdb_prio++;
197. 
198.     if (gdb_prio > libc_prio) {
199.         (void) (NH_panictrace_gdb() || (libc_prio && NH_panictrace_libc()));
200.     } else {
201.         (void) (NH_panictrace_libc() || (gdb_prio && NH_panictrace_gdb()));
202.     }
203. 
204. #else /* VMS */
205.     /* overload otherwise unused priority for debug mode: 1 = show
206.        traceback and exit; 2 = show traceback and stay in debugger */
207.     /* if (wizard && gdb_prio == 1) gdb_prio = 2; */
208.     vms_traceback(gdb_prio);
209.     nhUse(libc_prio);
210. 
211. #endif /* ?VMS */
212. 
213. #ifndef NO_SIGNAL
214.     panictrace_setsignals(FALSE);
215. #endif
216.     NH_abort_();
217. }
218. 
219. static boolean
220. NH_panictrace_libc()
221. {
222. #ifdef PANICTRACE_LIBC
223.     void *bt[20];
224.     size_t count, x;
225.     char **info;
226. 
227.     raw_print("Generating more information you may report:\n");
228.     count = backtrace(bt, SIZE(bt));
229.     info = backtrace_symbols(bt, count);
230.     for (x = 0; x < count; x++) {
231.         raw_printf("[%lu] %s", (unsigned long) x, info[x]);
232.     }
233.     /* free(info);   -- Don't risk it. */
234.     return TRUE;
235. #else
236.     return FALSE;
237. #endif /* !PANICTRACE_LIBC */
238. }
239. 
240. /*
241.  *   fooPATH  file system path for foo
242.  *   fooVAR   (possibly const) variable containing fooPATH
243.  */
244. #ifdef PANICTRACE_GDB
245. #ifdef SYSCF
246. #define GDBVAR sysopt.gdbpath
247. #define GREPVAR sysopt.greppath
248. #else /* SYSCF */
249. #define GDBVAR GDBPATH
250. #define GREPVAR GREPPATH
251. #endif /* SYSCF */
252. #endif /* PANICTRACE_GDB */
253. 
254. static boolean
255. NH_panictrace_gdb()
256. {
257. #ifdef PANICTRACE_GDB
258.     /* A (more) generic method to get a stack trace - invoke
259.      * gdb on ourself. */
260.     const char *gdbpath = GDBVAR;
261.     const char *greppath = GREPVAR;
262.     char buf[BUFSZ];
263.     FILE *gdb;
264. 
265.     if (gdbpath == NULL || gdbpath[0] == 0)
266.         return FALSE;
267.     if (greppath == NULL || greppath[0] == 0)
268.         return FALSE;
269. 
270.     sprintf(buf, "%s -n -q %s %d 2>&1 | %s '^#'",
271.             gdbpath, ARGV0, getpid(), greppath);
272.     gdb = popen(buf, "w");
273.     if (gdb) {
274.         raw_print("Generating more information you may report:\n");
275.         fprintf(gdb, "bt\nquit\ny");
276.         fflush(gdb);
277.         sleep(4); /* ugly */
278.         pclose(gdb);
279.         return TRUE;
280.     } else {
281.         return FALSE;
282.     }
283. #else
284.     return FALSE;
285. #endif /* !PANICTRACE_GDB */
286. }
287. #endif /* PANICTRACE */
288. 
289. /*
290.  * The order of these needs to match the macros in hack.h.
291.  */
292. static NEARDATA const char *deaths[] = {
293.     /* the array of death */
294.     "died", "choked", "poisoned", "starvation", "drowning", "burning",
295.     "dissolving under the heat and pressure", "crushed", "turned to stone",
296.     "turned into slime", "genocided", "panic", "trickery", "quit",
297.     "escaped", "ascended"
298. };
299. 
300. static NEARDATA const char *ends[] = {
301.     /* "when you %s" */
302.     "died", "choked", "were poisoned",
303.     "starved", "drowned", "burned",
304.     "dissolved in the lava",
305.     "were crushed", "turned to stone",
306.     "turned into slime", "were genocided",
307.     "panicked", "were tricked", "quit",
308.     "escaped", "ascended"
309. };
310. 
311. static boolean Schroedingers_cat = FALSE;
312. 
313. /*ARGSUSED*/
314. void
315. done1(sig_unused) /* called as signal() handler, so sent at least one arg */
316. int sig_unused UNUSED;
317. {
318. #ifndef NO_SIGNAL
319.     (void) signal(SIGINT, SIG_IGN);
320. #endif
321.     if (flags.ignintr) {
322. #ifndef NO_SIGNAL
323.         (void) signal(SIGINT, (SIG_RET_TYPE) done1);
324. #endif
325.         clear_nhwindow(WIN_MESSAGE);
326.         curs_on_u();
327.         wait_synch();
328.         if (multi > 0)
329.             nomul(0);
330.     } else {
331.         (void) done2();
332.     }
333. }
334. 
335. /* "#quit" command or keyboard interrupt */
336. int
337. done2()
338. {
339.     if (iflags.debug_fuzzer)
340.         return 0;
341.     if (!paranoid_query(ParanoidQuit, "Really quit?")) {
342. #ifndef NO_SIGNAL
343.         (void) signal(SIGINT, (SIG_RET_TYPE) done1);
344. #endif
345.         clear_nhwindow(WIN_MESSAGE);
346.         curs_on_u();
347.         wait_synch();
348.         if (multi > 0)
349.             nomul(0);
350.         if (multi == 0) {
351.             u.uinvulnerable = FALSE; /* avoid ctrl-C bug -dlc */
352.             u.usleep = 0;
353.         }
354.         return 0;
355.     }
356. #if (defined(UNIX) || defined(VMS) || defined(LATTICE))
357.     if (wizard) {
358.         int c;
359. #ifdef VMS
360.         extern int debuggable; /* sys/vms/vmsmisc.c, vmsunix.c */
361. 
362.         c = !debuggable ? 'n' : ynq("Enter debugger?");
363. #else
364. #ifdef LATTICE
365.         c = ynq("Create SnapShot?");
366. #else
367.         c = ynq("Dump core?");
368. #endif
369. #endif
370.         if (c == 'y') {
371. #ifndef NO_SIGNAL
372.             (void) signal(SIGINT, (SIG_RET_TYPE) done1);
373. #endif
374.             exit_nhwindows((char *) 0);
375.             NH_abort();
376.         } else if (c == 'q')
377.             done_stopprint++;
378.     }
379. #endif
380. #ifndef LINT
381.     done(QUIT);
382. #endif
383.     return 0;
384. }
385. 
386. #ifndef NO_SIGNAL
387. /*ARGSUSED*/
388. STATIC_PTR void
389. done_intr(sig_unused) /* called as signal() handler, so sent at least 1 arg */
390. int sig_unused UNUSED;
391. {
392.     done_stopprint++;
393.     (void) signal(SIGINT, SIG_IGN);
394. #if defined(UNIX) || defined(VMS)
395.     (void) signal(SIGQUIT, SIG_IGN);
396. #endif
397.     return;
398. }
399. 
400. #if defined(UNIX) || defined(VMS) || defined(__EMX__)
401. /* signal() handler */
402. static void
403. done_hangup(sig)
404. int sig;
405. {
406.     program_state.done_hup++;
407.     sethanguphandler((void FDECL((*), (int) )) SIG_IGN);
408.     done_intr(sig);
409.     return;
410. }
411. #endif
412. #endif /* NO_SIGNAL */
413. 
414. void
415. done_in_by(mtmp, how)
416. struct monst *mtmp;
417. int how;
418. {
419.     char buf[BUFSZ];
420.     struct permonst *mptr = mtmp->data,
421.                     *champtr = ((mtmp->cham >= LOW_PM)
422.                                    ? &mons[mtmp->cham]
423.                                    : mptr);
424.     boolean distorted = (boolean) (Hallucination && canspotmon(mtmp)),
425.             mimicker = (M_AP_TYPE(mtmp) == M_AP_MONSTER),
426.             imitator = (mptr != champtr || mimicker);
427. 
428.     You((how == STONING) ? "turn to stone..." : "die...");
429.     mark_synch(); /* flush buffered screen output */
430.     buf[0] = '\0';
431.     killer.format = KILLED_BY_AN;
432.     /* "killed by the high priest of Crom" is okay,
433.        "killed by the high priest" alone isn't */
434.     if ((mptr->geno & G_UNIQ) != 0 && !(imitator && !mimicker)
435.         && !(mptr == &mons[PM_HIGH_PRIEST] && !mtmp->ispriest)) {
436.         if (!type_is_pname(mptr))
437.             Strcat(buf, "the ");
438.         killer.format = KILLED_BY;
439.     }
440.     /* _the_ <invisible> <distorted> ghost of Dudley */
441.     if (mptr == &mons[PM_GHOST] && has_mname(mtmp)) {
442.         Strcat(buf, "the ");
443.         killer.format = KILLED_BY;
444.     }
445.     if (mtmp->minvis)
446.         Strcat(buf, "invisible ");
447.     if (distorted)
448.         Strcat(buf, "hallucinogen-distorted ");
449. 
450.     if (imitator) {
451.         char shape[BUFSZ];
452.         const char *realnm = champtr->mname, *fakenm = mptr->mname;
453.         boolean alt = is_vampshifter(mtmp);
454. 
455.         if (mimicker) {
456.             /* realnm is already correct because champtr==mptr;
457.                set up fake mptr for type_is_pname/the_unique_pm */
458.             mptr = &mons[mtmp->mappearance];
459.             fakenm = mptr->mname;
460.         } else if (alt && strstri(realnm, "vampire")
461.                    && !strcmp(fakenm, "vampire bat")) {
462.             /* special case: use "vampire in bat form" in preference
463.                to redundant looking "vampire in vampire bat form" */
464.             fakenm = "bat";
465.         }
466.         /* for the alternate format, always suppress any article;
467.            pname and the_unique should also have s_suffix() applied,
468.            but vampires don't take on any shapes which warrant that */
469.         if (alt || type_is_pname(mptr)) /* no article */
470.             Strcpy(shape, fakenm);
471.         else if (the_unique_pm(mptr)) /* "the"; don't use the() here */
472.             Sprintf(shape, "the %s", fakenm);
473.         else /* "a"/"an" */
474.             Strcpy(shape, an(fakenm));
475.         /* omit "called" to avoid excessive verbosity */
476.         Sprintf(eos(buf),
477.                 alt ? "%s in %s form"
478.                     : mimicker ? "%s disguised as %s"
479.                                : "%s imitating %s",
480.                 realnm, shape);
481.         mptr = mtmp->data; /* reset for mimicker case */
482.     } else if (mptr == &mons[PM_GHOST]) {
483.         Strcat(buf, "ghost");
484.         if (has_mname(mtmp))
485.             Sprintf(eos(buf), " of %s", MNAME(mtmp));
486.     } else if (mtmp->isshk) {
487.         const char *shknm = shkname(mtmp),
488.                    *honorific = shkname_is_pname(mtmp) ? ""
489.                                    : mtmp->female ? "Ms. " : "Mr. ";
490. 
491.         Sprintf(eos(buf), "%s%s, the shopkeeper", honorific, shknm);
492.         killer.format = KILLED_BY;
493.     } else if (mtmp->ispriest || mtmp->isminion) {
494.         /* m_monnam() suppresses "the" prefix plus "invisible", and
495.            it overrides the effect of Hallucination on priestname() */
496.         Strcat(buf, m_monnam(mtmp));
497.     } else {
498.         Strcat(buf, mptr->mname);
499.         if (has_mname(mtmp))
500.             Sprintf(eos(buf), " called %s", MNAME(mtmp));
501.     }
502. 
503.     Strcpy(killer.name, buf);
504.     /*
505.      * Chicken and egg issue:
506.      *  Ordinarily Unchanging ought to override something like this,
507.      *  but the transformation occurs at death.  With the current code,
508.      *  the effectiveness of Unchanging stops first, but a case could
509.      *  be made that it should last long enough to prevent undead
510.      *  transformation.  (Turning to slime isn't an issue here because
511.      *  Unchanging prevents that from happening.)
512.      */
513.     if (mptr->mlet == S_WRAITH)
514.         u.ugrave_arise = PM_WRAITH;
515.     else if (mptr->mlet == S_MUMMY && urace.mummynum != NON_PM)
516.         u.ugrave_arise = urace.mummynum;
517.     else if (mptr->mlet == S_VAMPIRE && Race_if(PM_HUMAN))
518.         u.ugrave_arise = PM_VAMPIRE;
519.     else if (mptr == &mons[PM_GHOUL])
520.         u.ugrave_arise = PM_GHOUL;
521.     /* this could happen if a high-end vampire kills the hero
522.        when ordinary vampires are genocided; ditto for wraiths */
523.     if (u.ugrave_arise >= LOW_PM
524.         && (mvitals[u.ugrave_arise].mvflags & G_GENOD))
525.         u.ugrave_arise = NON_PM;
526. 
527.     done(how);
528.     return;
529. }
530. 
531. /* some special cases for overriding while-helpless reason */
532. static const struct {
533.     int why, unmulti;
534.     const char *exclude, *include;
535. } death_fixups[] = {
536.     /* "petrified by <foo>, while getting stoned" -- "while getting stoned"
537.        prevented any last-second recovery, but it was not the cause of
538.        "petrified by <foo>" */
539.     { STONING, 1, "getting stoned", (char *) 0 },
540.     /* "died of starvation, while fainted from lack of food" is accurate
541.        but sounds a fairly silly (and doesn't actually appear unless you
542.        splice together death and while-helpless from xlogfile) */
543.     { STARVING, 0, "fainted from lack of food", "fainted" },
544. };
545. 
546. /* clear away while-helpless when the cause of death caused that
547.    helplessness (ie, "petrified by <foo> while getting stoned") */
548. STATIC_DCL void
549. fixup_death(how)
550. int how;
551. {
552.     int i;
553. 
554.     if (multi_reason) {
555.         for (i = 0; i < SIZE(death_fixups); ++i)
556.             if (death_fixups[i].why == how
557.                 && !strcmp(death_fixups[i].exclude, multi_reason)) {
558.                 if (death_fixups[i].include) /* substitute alternate reason */
559.                     multi_reason = death_fixups[i].include;
560.                 else /* remove the helplessness reason */
561.                     multi_reason = (char *) 0;
562.                 if (death_fixups[i].unmulti) /* possibly hide helplessness */
563.                     multi = 0L;
564.                 break;
565.             }
566.     }
567. }
568. 
569. #if defined(WIN32) && !defined(SYSCF)
570. #define NOTIFY_NETHACK_BUGS
571. #endif
572. 
573. /*VARARGS1*/
574. void panic
575. VA_DECL(const char *, str)
576. {
577.     VA_START(str);
578.     VA_INIT(str, char *);
579. 
580.     if (program_state.panicking++)
581.         NH_abort(); /* avoid loops - this should never happen*/
582. 
583.     if (iflags.window_inited) {
584.         raw_print("\r\nOops...");
585.         wait_synch(); /* make sure all pending output gets flushed */
586.         exit_nhwindows((char *) 0);
587.         iflags.window_inited = 0; /* they're gone; force raw_print()ing */
588.     }
589. 
590.     raw_print(program_state.gameover
591.                   ? "Postgame wrapup disrupted."
592.                   : !program_state.something_worth_saving
593.                         ? "Program initialization has failed."
594.                         : "Suddenly, the dungeon collapses.");
595. #ifndef MICRO
596. #ifdef NOTIFY_NETHACK_BUGS
597.     if (!wizard)
598.         raw_printf("Report the following error to \"%s\" or at \"%s\".",
599.                    DEVTEAM_EMAIL, DEVTEAM_URL);
600.     else if (program_state.something_worth_saving)
601.         raw_print("\nError save file being written.\n");
602. #else /* !NOTIFY_NETHACK_BUGS */
603.     if (!wizard) {
604.         const char *maybe_rebuild = !program_state.something_worth_saving
605.                                      ? "."
606.                                      : "\nand it may be possible to rebuild.";
607. 
608.         if (sysopt.support)
609.             raw_printf("To report this error, %s%s", sysopt.support,
610.                        maybe_rebuild);
611.         else if (sysopt.fmtd_wizard_list) /* formatted SYSCF WIZARDS */
612.             raw_printf("To report this error, contact %s%s",
613.                        sysopt.fmtd_wizard_list, maybe_rebuild);
614.         else
615.             raw_printf("Report error to \"%s\"%s", WIZARD_NAME,
616.                        maybe_rebuild);
617.     }
618. #endif /* ?NOTIFY_NETHACK_BUGS */
619.     /* XXX can we move this above the prints?  Then we'd be able to
620.      * suppress "it may be possible to rebuild" based on dosave0()
621.      * or say it's NOT possible to rebuild. */
622.     if (program_state.something_worth_saving && !iflags.debug_fuzzer) {
623.         set_error_savefile();
624.         if (dosave0()) {
625.             /* os/win port specific recover instructions */
626.             if (sysopt.recover)
627.                 raw_printf("%s", sysopt.recover);
628.         }
629.     }
630. #endif /* !MICRO */
631.     {
632.         char buf[BUFSZ];
633. 
634.         Vsprintf(buf, str, VA_ARGS);
635.         raw_print(buf);
636.         paniclog("panic", buf);
637.     }
638. #ifdef WIN32
639.     interject(INTERJECT_PANIC);
640. #endif
641. #if defined(UNIX) || defined(VMS) || defined(LATTICE) || defined(WIN32)
642.     if (wizard)
643.         NH_abort(); /* generate core dump */
644. #endif
645.     VA_END();
646.     really_done(PANICKED);
647. }
648. 
649. STATIC_OVL boolean
650. should_query_disclose_option(category, defquery)
651. int category;
652. char *defquery;
653. {
654.     int idx;
655.     char disclose, *dop;
656. 
657.     *defquery = 'n';
658.     if ((dop = index(disclosure_options, category)) != 0) {
659.         idx = (int) (dop - disclosure_options);
660.         if (idx < 0 || idx >= NUM_DISCLOSURE_OPTIONS) {
661.             impossible(
662.                    "should_query_disclose_option: bad disclosure index %d %c",
663.                        idx, category);
664.             *defquery = DISCLOSE_PROMPT_DEFAULT_YES;
665.             return TRUE;
666.         }
667.         disclose = flags.end_disclose[idx];
668.         if (disclose == DISCLOSE_YES_WITHOUT_PROMPT) {
669.             *defquery = 'y';
670.             return FALSE;
671.         } else if (disclose == DISCLOSE_SPECIAL_WITHOUT_PROMPT) {
672.             *defquery = 'a';
673.             return FALSE;
674.         } else if (disclose == DISCLOSE_NO_WITHOUT_PROMPT) {
675.             *defquery = 'n';
676.             return FALSE;
677.         } else if (disclose == DISCLOSE_PROMPT_DEFAULT_YES) {
678.             *defquery = 'y';
679.             return TRUE;
680.         } else if (disclose == DISCLOSE_PROMPT_DEFAULT_SPECIAL) {
681.             *defquery = 'a';
682.             return TRUE;
683.         } else {
684.             *defquery = 'n';
685.             return TRUE;
686.         }
687.     }
688.     impossible("should_query_disclose_option: bad category %c", category);
689.     return TRUE;
690. }
691. 
692. #ifdef DUMPLOG
693. STATIC_OVL void
694. dump_plines()
695. {
696.     int i, j;
697.     char buf[BUFSZ], **strp;
698.     extern char *saved_plines[];
699.     extern unsigned saved_pline_index;
700. 
701.     Strcpy(buf, " "); /* one space for indentation */
702.     putstr(0, 0, "Latest messages:");
703.     for (i = 0, j = (int) saved_pline_index; i < DUMPLOG_MSG_COUNT;
704.          ++i, j = (j + 1) % DUMPLOG_MSG_COUNT) {
705.         strp = &saved_plines[j];
706.         if (*strp) {
707.             copynchars(&buf[1], *strp, BUFSZ - 1 - 1);
708.             putstr(0, 0, buf);
709. #ifdef FREE_ALL_MEMORY
710.             free(*strp), *strp = 0;
711. #endif
712.         }
713.     }
714. }
715. #endif
716. 
717. /*ARGSUSED*/
718. STATIC_OVL void
719. dump_everything(how, when)
720. int how;
721. time_t when; /* date+time at end of game */
722. {
723. #ifdef DUMPLOG
724.     char pbuf[BUFSZ], datetimebuf[24]; /* [24]: room for 64-bit bogus value */
725. 
726.     dump_redirect(TRUE);
727.     if (!iflags.in_dumplog)
728.         return;
729. 
730.     init_symbols(); /* revert to default symbol set */
731. 
732.     /* one line version ID, which includes build date+time;
733.        it's conceivable that the game started with a different
734.        build date+time or even with an older nethack version,
735.        but we only have access to the one it finished under */
736.     putstr(0, 0, getversionstring(pbuf));
737.     putstr(0, 0, "");
738. 
739.     /* game start and end date+time to disambiguate version date+time */
740.     Strcpy(datetimebuf, yyyymmddhhmmss(ubirthday));
741.     Sprintf(pbuf, "Game began %4.4s-%2.2s-%2.2s %2.2s:%2.2s:%2.2s",
742.             &datetimebuf[0], &datetimebuf[4], &datetimebuf[6],
743.             &datetimebuf[8], &datetimebuf[10], &datetimebuf[12]);
744.     Strcpy(datetimebuf, yyyymmddhhmmss(when));
745.     Sprintf(eos(pbuf), ", ended %4.4s-%2.2s-%2.2s %2.2s:%2.2s:%2.2s.",
746.             &datetimebuf[0], &datetimebuf[4], &datetimebuf[6],
747.             &datetimebuf[8], &datetimebuf[10], &datetimebuf[12]);
748.     putstr(0, 0, pbuf);
749.     putstr(0, 0, "");
750. 
751.     /* character name and basic role info */
752.     Sprintf(pbuf, "%s, %s %s %s %s", plname,
753.             aligns[1 - u.ualign.type].adj,
754.             genders[flags.female].adj,
755.             urace.adj,
756.             (flags.female && urole.name.f) ? urole.name.f : urole.name.m);
757.     putstr(0, 0, pbuf);
758.     putstr(0, 0, "");
759. 
760.     dump_map();
761.     putstr(0, 0, do_statusline1());
762.     putstr(0, 0, do_statusline2());
763.     putstr(0, 0, "");
764. 
765.     dump_plines();
766.     putstr(0, 0, "");
767.     putstr(0, 0, "Inventory:");
768.     (void) display_inventory((char *) 0, TRUE);
769.     container_contents(invent, TRUE, TRUE, FALSE);
770.     enlightenment((BASICENLIGHTENMENT | MAGICENLIGHTENMENT),
771.                   (how >= PANICKED) ? ENL_GAMEOVERALIVE : ENL_GAMEOVERDEAD);
772.     putstr(0, 0, "");
773.     list_vanquished('d', FALSE); /* 'd' => 'y' */
774.     putstr(0, 0, "");
775.     list_genocided('d', FALSE); /* 'd' => 'y' */
776.     putstr(0, 0, "");
777.     show_conduct((how >= PANICKED) ? 1 : 2);
778.     putstr(0, 0, "");
779.     show_overview((how >= PANICKED) ? 1 : 2, how);
780.     putstr(0, 0, "");
781.     dump_redirect(FALSE);
782. #else
783.     nhUse(how);
784.     nhUse(when);
785. #endif
786. }
787. 
788. STATIC_OVL void
789. disclose(how, taken)
790. int how;
791. boolean taken;
792. {
793.     char c = '\0', defquery;
794.     char qbuf[QBUFSZ];
795.     boolean ask = FALSE;
796. 
797.     if (invent && !done_stopprint) {
798.         if (taken)
799.             Sprintf(qbuf, "Do you want to see what you had when you %s?",
800.                     (how == QUIT) ? "quit" : "died");
801.         else
802.             Strcpy(qbuf, "Do you want your possessions identified?");
803. 
804.         ask = should_query_disclose_option('i', &defquery);
805.         c = ask ? yn_function(qbuf, ynqchars, defquery) : defquery;
806.         if (c == 'y') {
807.             /* caller has already ID'd everything */
808.             (void) display_inventory((char *) 0, TRUE);
809.             container_contents(invent, TRUE, TRUE, FALSE);
810.         }
811.         if (c == 'q')
812.             done_stopprint++;
813.     }
814. 
815.     if (!done_stopprint) {
816.         ask = should_query_disclose_option('a', &defquery);
817.         c = ask ? yn_function("Do you want to see your attributes?", ynqchars,
818.                               defquery)
819.                 : defquery;
820.         if (c == 'y')
821.             enlightenment((BASICENLIGHTENMENT | MAGICENLIGHTENMENT),
822.                           (how >= PANICKED) ? ENL_GAMEOVERALIVE
823.                                             : ENL_GAMEOVERDEAD);
824.         if (c == 'q')
825.             done_stopprint++;
826.     }
827. 
828.     if (!done_stopprint) {
829.         ask = should_query_disclose_option('v', &defquery);
830.         list_vanquished(defquery, ask);
831.     }
832. 
833.     if (!done_stopprint) {
834.         ask = should_query_disclose_option('g', &defquery);
835.         list_genocided(defquery, ask);
836.     }
837. 
838.     if (!done_stopprint) {
839.         ask = should_query_disclose_option('c', &defquery);
840.         c = ask ? yn_function("Do you want to see your conduct?", ynqchars,
841.                               defquery)
842.                 : defquery;
843.         if (c == 'y')
844.             show_conduct((how >= PANICKED) ? 1 : 2);
845.         if (c == 'q')
846.             done_stopprint++;
847.     }
848. 
849.     if (!done_stopprint) {
850.         ask = should_query_disclose_option('o', &defquery);
851.         c = ask ? yn_function("Do you want to see the dungeon overview?",
852.                               ynqchars, defquery)
853.                 : defquery;
854.         if (c == 'y')
855.             show_overview((how >= PANICKED) ? 1 : 2, how);
856.         if (c == 'q')
857.             done_stopprint++;
858.     }
859. }
860. 
861. /* try to get the player back in a viable state after being killed */
862. STATIC_OVL void
863. savelife(how)
864. int how;
865. {
866.     int uhpmin = max(2 * u.ulevel, 10);
867. 
868.     if (u.uhpmax < uhpmin)
869.         u.uhpmax = uhpmin;
870.     u.uhp = u.uhpmax;
871.     if (Upolyd) /* Unchanging, or death which bypasses losing hit points */
872.         u.mh = u.mhmax;
873.     if (u.uhunger < 500 || how == CHOKING) {
874.         init_uhunger();
875.     }
876.     /* cure impending doom of sickness hero won't have time to fix */
877.     if ((Sick & TIMEOUT) == 1L) {
878.         make_sick(0L, (char *) 0, FALSE, SICK_ALL);
879.     }
880.     nomovemsg = "You survived that attempt on your life.";
881.     context.move = 0;
882.     if (multi > 0)
883.         multi = 0;
884.     else
885.         multi = -1;
886.     if (u.utrap && u.utraptype == TT_LAVA)
887.         reset_utrap(FALSE);
888.     context.botl = 1;
889.     u.ugrave_arise = NON_PM;
890.     HUnchanging = 0L;
891.     curs_on_u();
892.     if (!context.mon_moving)
893.         endmultishot(FALSE);
894.     if (u.uswallow) {
895.         /* might drop hero onto a trap that kills her all over again */
896.         expels(u.ustuck, u.ustuck->data, TRUE);
897.     } else if (u.ustuck) {
898.         if (Upolyd && sticks(youmonst.data))
899.             You("release %s.", mon_nam(u.ustuck));
900.         else
901.             pline("%s releases you.", Monnam(u.ustuck));
902.         unstuck(u.ustuck);
903.     }
904. }
905. 
906. /*
907.  * Get valuables from the given list.  Revised code: the list always remains
908.  * intact.
909.  */
910. STATIC_OVL void
911. get_valuables(list)
912. struct obj *list; /* inventory or container contents */
913. {
914.     register struct obj *obj;
915.     register int i;
916. 
917.     /* find amulets and gems, ignoring all artifacts */
918.     for (obj = list; obj; obj = obj->nobj)
919.         if (Has_contents(obj)) {
920.             get_valuables(obj->cobj);
921.         } else if (obj->oartifact) {
922.             continue;
923.         } else if (obj->oclass == AMULET_CLASS) {
924.             i = obj->otyp - FIRST_AMULET;
925.             if (!amulets[i].count) {
926.                 amulets[i].count = obj->quan;
927.                 amulets[i].typ = obj->otyp;
928.             } else
929.                 amulets[i].count += obj->quan; /* always adds one */
930.         } else if (obj->oclass == GEM_CLASS && obj->otyp < LUCKSTONE) {
931.             i = min(obj->otyp, LAST_GEM + 1) - FIRST_GEM;
932.             if (!gems[i].count) {
933.                 gems[i].count = obj->quan;
934.                 gems[i].typ = obj->otyp;
935.             } else
936.                 gems[i].count += obj->quan;
937.         }
938.     return;
939. }
940. 
941. /*
942.  *  Sort collected valuables, most frequent to least.  We could just
943.  *  as easily use qsort, but we don't care about efficiency here.
944.  */
945. STATIC_OVL void
946. sort_valuables(list, size)
947. struct valuable_data list[];
948. int size; /* max value is less than 20 */
949. {
950.     register int i, j;
951.     struct valuable_data ltmp;
952. 
953.     /* move greater quantities to the front of the list */
954.     for (i = 1; i < size; i++) {
955.         if (list[i].count == 0)
956.             continue;   /* empty slot */
957.         ltmp = list[i]; /* structure copy */
958.         for (j = i; j > 0; --j)
959.             if (list[j - 1].count >= ltmp.count)
960.                 break;
961.             else {
962.                 list[j] = list[j - 1];
963.             }
964.         list[j] = ltmp;
965.     }
966.     return;
967. }
968. 
969. #if 0
970. /*
971.  * odds_and_ends() was used for 3.6.0 and 3.6.1.
972.  * Schroedinger's Cat is handled differently as of 3.6.2.
973.  */
974. STATIC_DCL boolean FDECL(odds_and_ends, (struct obj *, int));
975. 
976. #define CAT_CHECK 2
977. 
978. STATIC_OVL boolean
979. odds_and_ends(list, what)
980. struct obj *list;
981. int what;
982. {
983.     struct obj *otmp;
984. 
985.     for (otmp = list; otmp; otmp = otmp->nobj) {
986.         switch (what) {
987.         case CAT_CHECK: /* Schroedinger's Cat */
988.             /* Ascending is deterministic */
989.             if (SchroedingersBox(otmp))
990.                 return rn2(2);
991.             break;
992.         }
993.         if (Has_contents(otmp))
994.             return odds_and_ends(otmp->cobj, what);
995.     }
996.     return FALSE;
997. }
998. #endif
999. 
1000. /* deal with some objects which may be in an abnormal state at end of game */
1001. STATIC_OVL void
1002. done_object_cleanup()
1003. {
1004.     int ox, oy;
1005. 
1006.     /* might have been killed while using a disposable item, so make sure
1007.        it's gone prior to inventory disclosure and creation of bones */
1008.     inven_inuse(TRUE);
1009.     /*
1010.      * Hero can die when throwing an object (by hitting an adjacent
1011.      * gas spore, for instance, or being hit by mis-returning Mjollnir),
1012.      * or while in transit (from falling down stairs).  If that happens,
1013.      * some object(s) might be in limbo rather than on the map or in
1014.      * any inventory.  Saving bones with an active light source in limbo
1015.      * would trigger an 'object not local' panic.
1016.      *
1017.      * We used to use dealloc_obj() on thrownobj and kickedobj but
1018.      * that keeps them out of bones and could leave uball in a confused
1019.      * state (gone but still attached).  Place them on the map but
1020.      * bypass flooreffects().  That could lead to minor anomalies in
1021.      * bones, like undamaged paper at water or lava locations or piles
1022.      * not being knocked down holes, but it seems better to get this
1023.      * game over with than risk being tangled up in more and more details.
1024.      */
1025.     ox = u.ux + u.dx, oy = u.uy + u.dy;
1026.     if (!isok(ox, oy) || !accessible(ox, oy))
1027.         ox = u.ux, oy = u.uy;
1028.     /* put thrown or kicked object on map (for bones); location might
1029.        be incorrect (perhaps killed by divine lightning when throwing at
1030.        a temple priest?) but this should be better than just vanishing
1031.        (fragile stuff should be taken care of before getting here) */
1032.     if (thrownobj && thrownobj->where == OBJ_FREE) {
1033.         place_object(thrownobj, ox, oy);
1034.         stackobj(thrownobj), thrownobj = 0;
1035.     }
1036.     if (kickedobj && kickedobj->where == OBJ_FREE) {
1037.         place_object(kickedobj, ox, oy);
1038.         stackobj(kickedobj), kickedobj = 0;
1039.     }
1040.     /* if Punished hero dies during level change or dies or quits while
1041.        swallowed, uball and uchain will be in limbo; put them on floor
1042.        so bones will have them and object list cleanup finds them */
1043.     if (uchain && uchain->where == OBJ_FREE) {
1044.         /* placebc(); */
1045.         lift_covet_and_placebc(override_restriction);
1046.     }
1047.     /* persistent inventory window now obsolete since disclosure uses
1048.        a normal popup one; avoids "Bad fruit #n" when saving bones */
1049.     if (iflags.perm_invent) {
1050.         iflags.perm_invent = FALSE;
1051.         update_inventory(); /* make interface notice the change */
1052.     }
1053.     return;
1054. }
1055. 
1056. /* called twice; first to calculate total, then to list relevant items */
1057. STATIC_OVL void
1058. artifact_score(list, counting, endwin)
1059. struct obj *list;
1060. boolean counting; /* true => add up points; false => display them */
1061. winid endwin;
1062. {
1063.     char pbuf[BUFSZ];
1064.     struct obj *otmp;
1065.     long value, points;
1066.     short dummy; /* object type returned by artifact_name() */
1067. 
1068.     for (otmp = list; otmp; otmp = otmp->nobj) {
1069.         if (otmp->oartifact || otmp->otyp == BELL_OF_OPENING
1070.             || otmp->otyp == SPE_BOOK_OF_THE_DEAD
1071.             || otmp->otyp == CANDELABRUM_OF_INVOCATION) {
1072.             value = arti_cost(otmp); /* zorkmid value */
1073.             points = value * 5 / 2;  /* score value */
1074.             if (counting) {
1075.                 nowrap_add(u.urexp, points);
1076.             } else {
1077.                 discover_object(otmp->otyp, TRUE, FALSE);
1078.                 otmp->known = otmp->dknown = otmp->bknown = otmp->rknown = 1;
1079.                 /* assumes artifacts don't have quan > 1 */
1080.                 Sprintf(pbuf, "%s%s (worth %ld %s and %ld points)",
1081.                         the_unique_obj(otmp) ? "The " : "",
1082.                         otmp->oartifact ? artifact_name(xname(otmp), &dummy)
1083.                                         : OBJ_NAME(objects[otmp->otyp]),
1084.                         value, currency(value), points);
1085.                 putstr(endwin, 0, pbuf);
1086.             }
1087.         }
1088.         if (Has_contents(otmp))
1089.             artifact_score(otmp->cobj, counting, endwin);
1090.     }
1091. }
1092. 
1093. /* Be careful not to call panic from here! */
1094. void
1095. done(how)
1096. int how;
1097. {
1098.     boolean survive = FALSE;
1099. 
1100.     if (how == TRICKED) {
1101.         if (killer.name[0]) {
1102.             paniclog("trickery", killer.name);
1103.             killer.name[0] = '\0';
1104.         }
1105.         if (wizard) {
1106.             You("are a very tricky wizard, it seems.");
1107.             killer.format = KILLED_BY_AN; /* reset to 0 */
1108.             return;
1109.         }
1110.     }
1111.     if (program_state.panicking
1112. #ifdef HANGUPHANDLING
1113.         || program_state.done_hup
1114. #endif
1115.         ) {
1116.         /* skip status update if panicking or disconnected */
1117.         context.botl = context.botlx = iflags.time_botl = FALSE;
1118.     } else {
1119.         /* otherwise force full status update */
1120.         context.botlx = TRUE;
1121.         bot();
1122.     }
1123. 
1124.     if (iflags.debug_fuzzer) {
1125.         if (!(program_state.panicking || how == PANICKED)) {
1126.             savelife(how);
1127.             /* periodically restore characteristics and lost exp levels
1128.                or cure lycanthropy */
1129.             if (!rn2(10)) {
1130.                 struct obj *potion = mksobj((u.ulycn > LOW_PM && !rn2(3))
1131.                                             ? POT_WATER : POT_RESTORE_ABILITY,
1132.                                             TRUE, FALSE);
1133. 
1134.                 bless(potion);
1135.                 (void) peffects(potion); /* always -1 for restore ability */
1136.                 /* not useup(); we haven't put this potion into inventory */
1137.                 obfree(potion, (struct obj *) 0);
1138.             }
1139.             killer.name[0] = '\0';
1140.             killer.format = 0;
1141.             return;
1142.         }
1143.     } else
1144.     if (how == ASCENDED || (!killer.name[0] && how == GENOCIDED))
1145.         killer.format = NO_KILLER_PREFIX;
1146.     /* Avoid killed by "a" burning or "a" starvation */
1147.     if (!killer.name[0] && (how == STARVING || how == BURNING))
1148.         killer.format = KILLED_BY;
1149.     if (!killer.name[0] || how >= PANICKED)
1150.         Strcpy(killer.name, deaths[how]);
1151. 
1152.     if (how < PANICKED) {
1153.         u.umortality++;
1154.         /* in case caller hasn't already done this */
1155.         if (u.uhp != 0 || (Upolyd && u.mh != 0)) {
1156.             /* force HP to zero in case it is still positive (some
1157.                deaths aren't triggered by loss of hit points), or
1158.                negative (-1 is used as a flag in some circumstances
1159.                which don't apply when actually dying due to HP loss) */
1160.             u.uhp = u.mh = 0;
1161.             context.botl = 1;
1162.         }
1163.     }
1164.     if (Lifesaved && (how <= GENOCIDED)) {
1165.         pline("But wait...");
1166.         makeknown(AMULET_OF_LIFE_SAVING);
1167.         Your("medallion %s!", !Blind ? "begins to glow" : "feels warm");
1168.         if (how == CHOKING)
1169.             You("vomit ...");
1170.         You_feel("much better!");
1171.         pline_The("medallion crumbles to dust!");
1172.         if (uamul)
1173.             useup(uamul);
1174. 
1175.         (void) adjattrib(A_CON, -1, TRUE);
1176.         savelife(how);
1177.         if (how == GENOCIDED) {
1178.             pline("Unfortunately you are still genocided...");
1179.         } else {
1180.             survive = TRUE;
1181.         }
1182.     }
1183.     /* explore and wizard modes offer player the option to keep playing */
1184.     if (!survive && (wizard || discover) && how <= GENOCIDED
1185.         && !paranoid_query(ParanoidDie, "Die?")) {
1186.         pline("OK, so you don't %s.", (how == CHOKING) ? "choke" : "die");
1187.         iflags.last_msg = PLNMSG_OK_DONT_DIE;
1188.         savelife(how);
1189.         survive = TRUE;
1190.     }
1191. 
1192.     if (survive) {
1193.         killer.name[0] = '\0';
1194.         killer.format = KILLED_BY_AN; /* reset to 0 */
1195.         return;
1196.     }
1197.     really_done(how);
1198.     /*NOTREACHED*/
1199. }
1200. 
1201. /* separated from done() in order to specify the __noreturn__ attribute */
1202. STATIC_OVL void
1203. really_done(how)
1204. int how;
1205. {
1206.     boolean taken;
1207.     char pbuf[BUFSZ];
1208.     winid endwin = WIN_ERR;
1209.     boolean bones_ok, have_windows = iflags.window_inited;
1210.     struct obj *corpse = (struct obj *) 0;
1211.     time_t endtime;
1212.     long umoney;
1213.     long tmp;
1214. 
1215.     /*
1216.      *  The game is now over...
1217.      */
1218.     program_state.gameover = 1;
1219.     /* in case of a subsequent panic(), there's no point trying to save */
1220.     program_state.something_worth_saving = 0;
1221. #ifdef HANGUPHANDLING
1222.     if (program_state.done_hup)
1223.         done_stopprint++;
1224. #endif
1225.     /* render vision subsystem inoperative */
1226.     iflags.vision_inited = 0;
1227. 
1228.     /* maybe use up active invent item(s), place thrown/kicked missile,
1229.        deal with ball and chain possibly being temporarily off the map */
1230.     if (!program_state.panicking)
1231.         done_object_cleanup();
1232.     /* in case we're panicking; normally cleared by done_object_cleanup() */
1233.     iflags.perm_invent = FALSE;
1234. 
1235.     /* remember time of death here instead of having bones, rip, and
1236.        topten figure it out separately and possibly getting different
1237.        time or even day if player is slow responding to --More-- */
1238.     urealtime.finish_time = endtime = getnow();
1239.     urealtime.realtime += (long) (endtime - urealtime.start_timing);
1240.     /* collect these for end of game disclosure (not used during play) */
1241.     iflags.at_night = night();
1242.     iflags.at_midnight = midnight();
1243. 
1244.     dump_open_log(endtime);
1245.     /* Sometimes you die on the first move.  Life's not fair.
1246.      * On those rare occasions you get hosed immediately, go out
1247.      * smiling... :-)  -3.
1248.      */
1249.     if (moves <= 1 && how < PANICKED && !done_stopprint)
1250.         pline("Do not pass Go.  Do not collect 200 %s.", currency(200L));
1251. 
1252.     if (have_windows)
1253.         wait_synch(); /* flush screen output */
1254. #ifndef NO_SIGNAL
1255.     (void) signal(SIGINT, (SIG_RET_TYPE) done_intr);
1256. #if defined(UNIX) || defined(VMS) || defined(__EMX__)
1257.     (void) signal(SIGQUIT, (SIG_RET_TYPE) done_intr);
1258.     sethanguphandler(done_hangup);
1259. #endif
1260. #endif /* NO_SIGNAL */
1261. 
1262.     bones_ok = (how < GENOCIDED) && can_make_bones();
1263. 
1264.     if (bones_ok && launch_in_progress())
1265.         force_launch_placement();
1266. 
1267.     /* maintain ugrave_arise even for !bones_ok */
1268.     if (how == PANICKED)
1269.         u.ugrave_arise = (NON_PM - 3); /* no corpse, no grave */
1270.     else if (how == BURNING || how == DISSOLVED) /* corpse burns up too */
1271.         u.ugrave_arise = (NON_PM - 2); /* leave no corpse */
1272.     else if (how == STONING)
1273.         u.ugrave_arise = (NON_PM - 1); /* statue instead of corpse */
1274.     else if (how == TURNED_SLIME
1275.              /* it's possible to turn into slime even though green slimes
1276.                 have been genocided:  genocide could occur after hero is
1277.                 already infected or hero could eat a glob of one created
1278.                 before genocide; don't try to arise as one if they're gone */
1279.              && !(mvitals[PM_GREEN_SLIME].mvflags & G_GENOD))
1280.         u.ugrave_arise = PM_GREEN_SLIME;
1281. 
1282.     if (how == QUIT) {
1283.         killer.format = NO_KILLER_PREFIX;
1284.         if (u.uhp < 1) {
1285.             how = DIED;
1286.             u.umortality++; /* skipped above when how==QUIT */
1287.             Strcpy(killer.name, "quit while already on Charon's boat");
1288.         }
1289.     }
1290.     if (how == ESCAPED || how == PANICKED)
1291.         killer.format = NO_KILLER_PREFIX;
1292. 
1293.     fixup_death(how); /* actually, fixup multi_reason */
1294. 
1295.     if (how != PANICKED) {
1296.         boolean silently = done_stopprint ? TRUE : FALSE;
1297. 
1298.         /* these affect score and/or bones, but avoid them during panic */
1299.         taken = paybill((how == ESCAPED) ? -1 : (how != QUIT), silently);
1300.         paygd(silently);
1301.         clearpriests();
1302.     } else
1303.         taken = FALSE; /* lint; assert( !bones_ok ); */
1304. 
1305.     clearlocks();
1306. 
1307.     if (have_windows)
1308.         display_nhwindow(WIN_MESSAGE, FALSE);
1309. 
1310.     if (how != PANICKED) {
1311.         struct obj *obj;
1312. 
1313.         /*
1314.          * This is needed for both inventory disclosure and dumplog.
1315.          * Both are optional, so do it once here instead of duplicating
1316.          * it in both of those places.
1317.          */
1318.         for (obj = invent; obj; obj = obj->nobj) {
1319.             discover_object(obj->otyp, TRUE, FALSE);
1320.             obj->known = obj->bknown = obj->dknown = obj->rknown = 1;
1321.             if (Is_container(obj) || obj->otyp == STATUE)
1322.                 obj->cknown = obj->lknown = 1;
1323.             /* we resolve Schroedinger's cat now in case of both
1324.                disclosure and dumplog, where the 50:50 chance for
1325.                live cat has to be the same both times */
1326.             if (SchroedingersBox(obj)) {
1327.                 if (!Schroedingers_cat) {
1328.                     /* tell observe_quantum_cat() not to create a cat; if it
1329.                        chooses live cat in this situation, it will leave the
1330.                        SchroedingersBox flag set (for container_contents()) */
1331.                     observe_quantum_cat(obj, FALSE, FALSE);
1332.                     if (SchroedingersBox(obj))
1333.                         Schroedingers_cat = TRUE;
1334.                 } else
1335.                     obj->spe = 0; /* ordinary box with cat corpse in it */
1336.             }
1337.         }
1338. 
1339.         if (strcmp(flags.end_disclose, "none"))
1340.             disclose(how, taken);
1341. 
1342.         dump_everything(how, endtime);
1343.     }
1344. 
1345.     /* if pets will contribute to score, populate mydogs list now
1346.        (bones creation isn't a factor, but pline() messaging is; used to
1347.        be done even sooner, but we need it to come after dump_everything()
1348.        so that any accompanying pets are still on the map during dump) */
1349.     if (how == ESCAPED || how == ASCENDED)
1350.         keepdogs(TRUE);
1351. 
1352.     /* finish_paybill should be called after disclosure but before bones */
1353.     if (bones_ok && taken)
1354.         finish_paybill();
1355. 
1356.     /* grave creation should be after disclosure so it doesn't have
1357.        this grave in the current level's features for #overview */
1358.     if (bones_ok && u.ugrave_arise == NON_PM
1359.         && !(mvitals[u.umonnum].mvflags & G_NOCORPSE)) {
1360.         int mnum = u.umonnum;
1361. 
1362.         if (!Upolyd) {
1363.             /* Base corpse on race when not poly'd since original u.umonnum
1364.                is based on role, and all role monsters are human. */
1365.             mnum = (flags.female && urace.femalenum != NON_PM)
1366.                        ? urace.femalenum
1367.                        : urace.malenum;
1368.         }
1369.         corpse = mk_named_object(CORPSE, &mons[mnum], u.ux, u.uy, plname);
1370.         Sprintf(pbuf, "%s, ", plname);
1371.         formatkiller(eos(pbuf), sizeof pbuf - strlen(pbuf), how, TRUE);
1372.         make_grave(u.ux, u.uy, pbuf);
1373.     }
1374.     pbuf[0] = '\0'; /* clear grave text; also lint suppression */
1375. 
1376.     /* calculate score, before creating bones [container gold] */
1377.     {
1378.         int deepest = deepest_lev_reached(FALSE);
1379. 
1380.         umoney = money_cnt(invent);
1381.         tmp = u.umoney0;
1382.         umoney += hidden_gold(); /* accumulate gold from containers */
1383.         tmp = umoney - tmp;      /* net gain */
1384. 
1385.         if (tmp < 0L)
1386.             tmp = 0L;
1387.         if (how < PANICKED)
1388.             tmp -= tmp / 10L;
1389.         tmp += 50L * (long) (deepest - 1);
1390.         if (deepest > 20)
1391.             tmp += 1000L * (long) ((deepest > 30) ? 10 : deepest - 20);
1392.         nowrap_add(u.urexp, tmp);
1393. 
1394.         /* ascension gives a score bonus iff offering to original deity */
1395.         if (how == ASCENDED && u.ualign.type == u.ualignbase[A_ORIGINAL]) {
1396.             /* retaining original alignment: score *= 2;
1397.                converting, then using helm-of-OA to switch back: *= 1.5 */
1398.             tmp = (u.ualignbase[A_CURRENT] == u.ualignbase[A_ORIGINAL])
1399.                       ? u.urexp
1400.                       : (u.urexp / 2L);
1401.             nowrap_add(u.urexp, tmp);
1402.         }
1403.     }
1404. 
1405.     if (u.ugrave_arise >= LOW_PM && !done_stopprint) {
1406.         /* give this feedback even if bones aren't going to be created,
1407.            so that its presence or absence doesn't tip off the player to
1408.            new bones or their lack; it might be a lie if makemon fails */
1409.         Your("%s as %s...",
1410.              (u.ugrave_arise != PM_GREEN_SLIME)
1411.                  ? "body rises from the dead"
1412.                  : "revenant persists",
1413.              an(mons[u.ugrave_arise].mname));
1414.         display_nhwindow(WIN_MESSAGE, FALSE);
1415.     }
1416. 
1417.     if (bones_ok) {
1418.         if (!wizard || paranoid_query(ParanoidBones, "Save bones?"))
1419.             savebones(how, endtime, corpse);
1420.         /* corpse may be invalid pointer now so
1421.             ensure that it isn't used again */
1422.         corpse = (struct obj *) 0;
1423.     }
1424. 
1425.     /* update gold for the rip output, which can't use hidden_gold()
1426.        (containers will be gone by then if bones just got saved...) */
1427.     done_money = umoney;
1428. 
1429.     /* clean up unneeded windows */
1430.     if (have_windows) {
1431.         wait_synch();
1432.         free_pickinv_cache(); /* extra persistent window if perm_invent */
1433.         if (WIN_INVEN != WIN_ERR) {
1434.             destroy_nhwindow(WIN_INVEN),  WIN_INVEN = WIN_ERR;
1435.             /* precaution in case any late update_inventory() calls occur */
1436.             iflags.perm_invent = 0;
1437.         }
1438.         display_nhwindow(WIN_MESSAGE, TRUE);
1439.         destroy_nhwindow(WIN_MAP),  WIN_MAP = WIN_ERR;
1440.         if (WIN_STATUS != WIN_ERR)
1441.             destroy_nhwindow(WIN_STATUS),  WIN_STATUS = WIN_ERR;
1442.         destroy_nhwindow(WIN_MESSAGE),  WIN_MESSAGE = WIN_ERR;
1443. 
1444.         if (!done_stopprint || flags.tombstone)
1445.             endwin = create_nhwindow(NHW_TEXT);
1446. 
1447.         if (how < GENOCIDED && flags.tombstone && endwin != WIN_ERR)
1448.             outrip(endwin, how, endtime);
1449.     } else
1450.         done_stopprint = 1; /* just avoid any more output */
1451. 
1452. #ifdef DUMPLOG
1453.     /* 'how' reasons beyond genocide shouldn't show tombstone;
1454.        for normal end of game, genocide doesn't either */
1455.     if (how <= GENOCIDED) {
1456.         dump_redirect(TRUE);
1457.         if (iflags.in_dumplog)
1458.             genl_outrip(0, how, endtime);
1459.         dump_redirect(FALSE);
1460.     }
1461. #endif
1462.     if (u.uhave.amulet) {
1463.         Strcat(killer.name, " (with the Amulet)");
1464.     } else if (how == ESCAPED) {
1465.         if (Is_astralevel(&u.uz)) /* offered Amulet to wrong deity */
1466.             Strcat(killer.name, " (in celestial disgrace)");
1467.         else if (carrying(FAKE_AMULET_OF_YENDOR))
1468.             Strcat(killer.name, " (with a fake Amulet)");
1469.         /* don't bother counting to see whether it should be plural */
1470.     }
1471. 
1472.     Sprintf(pbuf, "%s %s the %s...", Goodbye(), plname,
1473.             (how != ASCENDED)
1474.                 ? (const char *) ((flags.female && urole.name.f)
1475.                     ? urole.name.f
1476.                     : urole.name.m)
1477.                 : (const char *) (flags.female ? "Demigoddess" : "Demigod"));
1478.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1479.     dump_forward_putstr(endwin, 0, "", done_stopprint);
1480. 
1481.     if (how == ESCAPED || how == ASCENDED) {
1482.         struct monst *mtmp;
1483.         struct obj *otmp;
1484.         register struct val_list *val;
1485.         register int i;
1486. 
1487.         for (val = valuables; val->list; val++)
1488.             for (i = 0; i < val->size; i++) {
1489.                 val->list[i].count = 0L;
1490.             }
1491.         get_valuables(invent);
1492. 
1493.         /* add points for collected valuables */
1494.         for (val = valuables; val->list; val++)
1495.             for (i = 0; i < val->size; i++)
1496.                 if (val->list[i].count != 0L) {
1497.                     tmp = val->list[i].count
1498.                           * (long) objects[val->list[i].typ].oc_cost;
1499.                     nowrap_add(u.urexp, tmp);
1500.                 }
1501. 
1502.         /* count the points for artifacts */
1503.         artifact_score(invent, TRUE, endwin);
1504. 
1505.         viz_array[0][0] |= IN_SIGHT; /* need visibility for naming */
1506.         mtmp = mydogs;
1507.         Strcpy(pbuf, "You");
1508.         if (mtmp || Schroedingers_cat) {
1509.             while (mtmp) {
1510.                 Sprintf(eos(pbuf), " and %s", mon_nam(mtmp));
1511.                 if (mtmp->mtame)
1512.                     nowrap_add(u.urexp, mtmp->mhp);
1513.                 mtmp = mtmp->nmon;
1514.             }
1515.             /* [it might be more robust to create a housecat and add it to
1516.                mydogs; it doesn't have to be placed on the map for that] */
1517.             if (Schroedingers_cat) {
1518.                 int mhp, m_lev = adj_lev(&mons[PM_HOUSECAT]);
1519. 
1520.                 mhp = d(m_lev, 8);
1521.                 nowrap_add(u.urexp, mhp);
1522.                 Strcat(eos(pbuf), " and Schroedinger's cat");
1523.             }
1524.             dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1525.             pbuf[0] = '\0';
1526.         } else {
1527.             Strcat(pbuf, " ");
1528.         }
1529.         Sprintf(eos(pbuf), "%s with %ld point%s,",
1530.                 how == ASCENDED ? "went to your reward"
1531.                                  : "escaped from the dungeon",
1532.                 u.urexp, plur(u.urexp));
1533.         dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1534. 
1535.         if (!done_stopprint)
1536.             artifact_score(invent, FALSE, endwin); /* list artifacts */
1537. #ifdef DUMPLOG
1538.         dump_redirect(TRUE);
1539.         if (iflags.in_dumplog)
1540.             artifact_score(invent, FALSE, 0);
1541.         dump_redirect(FALSE);
1542. #endif
1543. 
1544.         /* list valuables here */
1545.         for (val = valuables; val->list; val++) {
1546.             sort_valuables(val->list, val->size);
1547.             for (i = 0; i < val->size && !done_stopprint; i++) {
1548.                 int typ = val->list[i].typ;
1549.                 long count = val->list[i].count;
1550. 
1551.                 if (count == 0L)
1552.                     continue;
1553.                 if (objects[typ].oc_class != GEM_CLASS || typ <= LAST_GEM) {
1554.                     otmp = mksobj(typ, FALSE, FALSE);
1555.                     discover_object(otmp->otyp, TRUE, FALSE);
1556.                     otmp->known = 1;  /* for fake amulets */
1557.                     otmp->dknown = 1; /* seen it (blindness fix) */
1558.                     if (has_oname(otmp))
1559.                         free_oname(otmp);
1560.                     otmp->quan = count;
1561.                     Sprintf(pbuf, "%8ld %s (worth %ld %s),", count,
1562.                             xname(otmp), count * (long) objects[typ].oc_cost,
1563.                             currency(2L));
1564.                     obfree(otmp, (struct obj *) 0);
1565.                 } else {
1566.                     Sprintf(pbuf, "%8ld worthless piece%s of colored glass,",
1567.                             count, plur(count));
1568.                 }
1569.                 dump_forward_putstr(endwin, 0, pbuf, 0);
1570.             }
1571.         }
1572. 
1573.     } else {
1574.         /* did not escape or ascend */
1575.         if (u.uz.dnum == 0 && u.uz.dlevel <= 0) {
1576.             /* level teleported out of the dungeon; `how' is DIED,
1577.                due to falling or to "arriving at heaven prematurely" */
1578.             Sprintf(pbuf, "You %s beyond the confines of the dungeon",
1579.                     (u.uz.dlevel < 0) ? "passed away" : ends[how]);
1580.         } else {
1581.             /* more conventional demise */
1582.             const char *where = dungeons[u.uz.dnum].dname;
1583. 
1584.             if (Is_astralevel(&u.uz))
1585.                 where = "The Astral Plane";
1586.             Sprintf(pbuf, "You %s in %s", ends[how], where);
1587.             if (!In_endgame(&u.uz) && !Is_knox(&u.uz))
1588.                 Sprintf(eos(pbuf), " on dungeon level %d",
1589.                         In_quest(&u.uz) ? dunlev(&u.uz) : depth(&u.uz));
1590.         }
1591. 
1592.         Sprintf(eos(pbuf), " with %ld point%s,", u.urexp, plur(u.urexp));
1593.         dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1594.     }
1595. 
1596.     Sprintf(pbuf, "and %ld piece%s of gold, after %ld move%s.", umoney,
1597.             plur(umoney), moves, plur(moves));
1598.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1599.     Sprintf(pbuf,
1600.             "You were level %d with a maximum of %d hit point%s when you %s.",
1601.             u.ulevel, u.uhpmax, plur(u.uhpmax), ends[how]);
1602.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1603.     dump_forward_putstr(endwin, 0, "", done_stopprint);
1604.     if (!done_stopprint)
1605.         display_nhwindow(endwin, TRUE);
1606.     if (endwin != WIN_ERR)
1607.         destroy_nhwindow(endwin);
1608. 
1609.     dump_close_log();
1610.     /* "So when I die, the first thing I will see in Heaven is a
1611.      * score list?" */
1612.     if (have_windows && !iflags.toptenwin)
1613.         exit_nhwindows((char *) 0), have_windows = FALSE;
1614.     topten(how, endtime);
1615.     if (have_windows)
1616.         exit_nhwindows((char *) 0);
1617. 
1618.     if (done_stopprint) {
1619.         raw_print("");
1620.         raw_print("");
1621.     }
1622.     nh_terminate(EXIT_SUCCESS);
1623. }
1624. 
1625. void
1626. container_contents(list, identified, all_containers, reportempty)
1627. struct obj *list;
1628. boolean identified, all_containers, reportempty;
1629. {
1630.     register struct obj *box, *obj;
1631.     char buf[BUFSZ];
1632.     boolean cat, dumping = iflags.in_dumplog;
1633. 
1634.     for (box = list; box; box = box->nobj) {
1635.         if (Is_container(box) || box->otyp == STATUE) {
1636.             if (!box->cknown || (identified && !box->lknown)) {
1637.                 box->cknown = 1; /* we're looking at the contents now */
1638.                 if (identified)
1639.                     box->lknown = 1;
1640.                 update_inventory();
1641.             }
1642.             if (box->otyp == BAG_OF_TRICKS) {
1643.                 continue; /* wrong type of container */
1644.             } else if (box->cobj) {
1645.                 winid tmpwin = create_nhwindow(NHW_MENU);
1646.                 Loot *sortedcobj, *srtc;
1647.                 unsigned sortflags;
1648. 
1649.                 /* at this stage, the SchroedingerBox() flag is only set
1650.                    if the cat inside the box is alive; the box actually
1651.                    contains a cat corpse that we'll pretend is not there;
1652.                    for dead cat, the flag will be clear and there'll be
1653.                    a cat corpse inside the box; either way, inventory
1654.                    reports the box as containing "1 item" */
1655.                 cat = SchroedingersBox(box);
1656. 
1657.                 Sprintf(buf, "Contents of %s:", the(xname(box)));
1658.                 putstr(tmpwin, 0, buf);
1659.                 if (!dumping)
1660.                     putstr(tmpwin, 0, "");
1661.                 buf[0] = buf[1] = ' '; /* two leading spaces */
1662.                 if (box->cobj && !cat) {
1663.                     sortflags = (((flags.sortloot == 'l'
1664.                                    || flags.sortloot == 'f')
1665.                                      ? SORTLOOT_LOOT : 0)
1666.                                  | (flags.sortpack ? SORTLOOT_PACK : 0));
1667.                     sortedcobj = sortloot(&box->cobj, sortflags, FALSE,
1668.                                           (boolean FDECL((*), (OBJ_P))) 0);
1669.                     for (srtc = sortedcobj; ((obj = srtc->obj) != 0); ++srtc) {
1670.                         if (identified) {
1671.                             discover_object(obj->otyp, TRUE, FALSE);
1672.                             obj->known = obj->bknown = obj->dknown
1673.                                 = obj->rknown = 1;
1674.                             if (Is_container(obj) || obj->otyp == STATUE)
1675.                                 obj->cknown = obj->lknown = 1;
1676.                         }
1677.                         Strcpy(&buf[2], doname_with_price(obj));
1678.                         putstr(tmpwin, 0, buf);
1679.                     }
1680.                     unsortloot(&sortedcobj);
1681.                 } else if (cat) {
1682.                     Strcpy(&buf[2], "Schroedinger's cat!");
1683.                     putstr(tmpwin, 0, buf);
1684.                 }
1685.                 if (dumping)
1686.                     putstr(0, 0, "");
1687.                 display_nhwindow(tmpwin, TRUE);
1688.                 destroy_nhwindow(tmpwin);
1689.                 if (all_containers)
1690.                     container_contents(box->cobj, identified, TRUE,
1691.                                        reportempty);
1692.             } else if (reportempty) {
1693.                 pline("%s is empty.", upstart(thesimpleoname(box)));
1694.                 display_nhwindow(WIN_MESSAGE, FALSE);
1695.             }
1696.         }
1697.         if (!all_containers)
1698.             break;
1699.     }
1700. }
1701. 
1702. /* should be called with either EXIT_SUCCESS or EXIT_FAILURE */
1703. void
1704. nh_terminate(status)
1705. int status;
1706. {
1707.     program_state.in_moveloop = 0; /* won't be returning to normal play */
1708. #ifdef MAC
1709.     getreturn("to exit");
1710. #endif
1711.     /* don't bother to try to release memory if we're in panic mode, to
1712.        avoid trouble in case that happens to be due to memory problems */
1713.     if (!program_state.panicking) {
1714.         freedynamicdata();
1715.         dlb_cleanup();
1716.     }
1717. 
1718. #ifdef VMS
1719.     /*
1720.      *  This is liable to draw a warning if compiled with gcc, but it's
1721.      *  more important to flag panic() -> really_done() -> nh_terminate()
1722.      *  as __noreturn__ then to avoid the warning.
1723.      */
1724.     /* don't call exit() if already executing within an exit handler;
1725.        that would cancel any other pending user-mode handlers */
1726.     if (program_state.exiting)
1727.         return;
1728. #endif
1729.     program_state.exiting = 1;
1730.     nethack_exit(status);
1731. }
1732. 
1733. enum vanq_order_modes {
1734.     VANQ_MLVL_MNDX = 0,
1735.     VANQ_MSTR_MNDX,
1736.     VANQ_ALPHA_SEP,
1737.     VANQ_ALPHA_MIX,
1738.     VANQ_MCLS_HTOL,
1739.     VANQ_MCLS_LTOH,
1740.     VANQ_COUNT_H_L,
1741.     VANQ_COUNT_L_H,
1742. 
1743.     NUM_VANQ_ORDER_MODES
1744. };
1745. 
1746. static const char *vanqorders[NUM_VANQ_ORDER_MODES] = {
1747.     "traditional: by monster level, by internal monster index",
1748.     "by monster toughness, by internal monster index",
1749.     "alphabetically, first unique monsters, then others",
1750.     "alphabetically, unique monsters and others intermixed",
1751.     "by monster class, high to low level within class",
1752.     "by monster class, low to high level within class",
1753.     "by count, high to low, by internal index within tied count",
1754.     "by count, low to high, by internal index within tied count",
1755. };
1756. static int vanq_sortmode = VANQ_MLVL_MNDX;
1757. 
1758. STATIC_PTR int CFDECLSPEC
1759. vanqsort_cmp(vptr1, vptr2)
1760. const genericptr vptr1;
1761. const genericptr vptr2;
1762. {
1763.     int indx1 = *(short *) vptr1, indx2 = *(short *) vptr2,
1764.         mlev1, mlev2, mstr1, mstr2, uniq1, uniq2, died1, died2, res;
1765.     const char *name1, *name2, *punct;
1766.     schar mcls1, mcls2;
1767. 
1768.     switch (vanq_sortmode) {
1769.     default:
1770.     case VANQ_MLVL_MNDX:
1771.         /* sort by monster level */
1772.         mlev1 = mons[indx1].mlevel, mlev2 = mons[indx2].mlevel;
1773.         res = mlev2 - mlev1; /* mlevel high to low */
1774.         break;
1775.     case VANQ_MSTR_MNDX:
1776.         /* sort by monster toughness */
1777.         mstr1 = mons[indx1].difficulty, mstr2 = mons[indx2].difficulty;
1778.         res = mstr2 - mstr1; /* monstr high to low */
1779.         break;
1780.     case VANQ_ALPHA_SEP:
1781.         uniq1 = ((mons[indx1].geno & G_UNIQ) && indx1 != PM_HIGH_PRIEST);
1782.         uniq2 = ((mons[indx2].geno & G_UNIQ) && indx2 != PM_HIGH_PRIEST);
1783.         if (uniq1 ^ uniq2) { /* one or other uniq, but not both */
1784.             res = uniq2 - uniq1;
1785.             break;
1786.         } /* else both unique or neither unique */
1787.         /*FALLTHRU*/
1788.     case VANQ_ALPHA_MIX:
1789.         name1 = mons[indx1].mname, name2 = mons[indx2].mname;
1790.         res = strcmpi(name1, name2); /* caseblind alhpa, low to high */
1791.         break;
1792.     case VANQ_MCLS_HTOL:
1793.     case VANQ_MCLS_LTOH:
1794.         /* mons[].mlet is a small integer, 1..N, of type plain char;
1795.            if 'char' happens to be unsigned, (mlet1 - mlet2) would yield
1796.            an inappropriate result when mlet2 is greater than mlet1,
1797.            so force our copies (mcls1, mcls2) to be signed */
1798.         mcls1 = (schar) mons[indx1].mlet, mcls2 = (schar) mons[indx2].mlet;
1799.         /* S_ANT through S_ZRUTY correspond to lowercase monster classes,
1800.            S_ANGEL through S_ZOMBIE correspond to uppercase, and various
1801.            punctuation characters are used for classes beyond those */
1802.         if (mcls1 > S_ZOMBIE && mcls2 > S_ZOMBIE) {
1803.             /* force a specific order to the punctuation classes that's
1804.                different from the internal order;
1805.                internal order is ok if neither or just one is punctuation
1806.                since letters have lower values so come out before punct */
1807.             static const char punctclasses[] = {
1808.                 S_LIZARD, S_EEL, S_GOLEM, S_GHOST, S_DEMON, S_HUMAN, '\0'
1809.             };
1810. 
1811.             if ((punct = index(punctclasses, mcls1)) != 0)
1812.                 mcls1 = (schar) (S_ZOMBIE + 1 + (int) (punct - punctclasses));
1813.             if ((punct = index(punctclasses, mcls2)) != 0)
1814.                 mcls2 = (schar) (S_ZOMBIE + 1 + (int) (punct - punctclasses));
1815.         }
1816.         res = mcls1 - mcls2; /* class */
1817.         if (res == 0) {
1818.             mlev1 = mons[indx1].mlevel, mlev2 = mons[indx2].mlevel;
1819.             res = mlev1 - mlev2; /* mlevel low to high */
1820.             if (vanq_sortmode == VANQ_MCLS_HTOL)
1821.                 res = -res; /* mlevel high to low */
1822.         }
1823.         break;
1824.     case VANQ_COUNT_H_L:
1825.     case VANQ_COUNT_L_H:
1826.         died1 = mvitals[indx1].died, died2 = mvitals[indx2].died;
1827.         res = died2 - died1; /* dead count high to low */
1828.         if (vanq_sortmode == VANQ_COUNT_L_H)
1829.             res = -res; /* dead count low to high */
1830.         break;
1831.     }
1832.     /* tiebreaker: internal mons[] index */
1833.     if (res == 0)
1834.         res = indx1 - indx2; /* mndx low to high */
1835.     return res;
1836. }
1837. 
1838. /* returns -1 if cancelled via ESC */
1839. STATIC_OVL int
1840. set_vanq_order()
1841. {
1842.     winid tmpwin;
1843.     menu_item *selected;
1844.     anything any;
1845.     int i, n, choice;
1846. 
1847.     tmpwin = create_nhwindow(NHW_MENU);
1848.     start_menu(tmpwin);
1849.     any = zeroany; /* zero out all bits */
1850.     for (i = 0; i < SIZE(vanqorders); i++) {
1851.         if (i == VANQ_ALPHA_MIX || i == VANQ_MCLS_HTOL) /* skip these */
1852.             continue;
1853.         any.a_int = i + 1;
1854.         add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE, vanqorders[i],
1855.                  (i == vanq_sortmode) ? MENU_SELECTED : MENU_UNSELECTED);
1856.     }
1857.     end_menu(tmpwin, "Sort order for vanquished monster counts");
1858. 
1859.     n = select_menu(tmpwin, PICK_ONE, &selected);
1860.     destroy_nhwindow(tmpwin);
1861.     if (n > 0) {
1862.         choice = selected[0].item.a_int - 1;
1863.         /* skip preselected entry if we have more than one item chosen */
1864.         if (n > 1 && choice == vanq_sortmode)
1865.             choice = selected[1].item.a_int - 1;
1866.         free((genericptr_t) selected);
1867.         vanq_sortmode = choice;
1868.     }
1869.     return (n < 0) ? -1 : vanq_sortmode;
1870. }
1871. 
1872. /* #vanquished command */
1873. int
1874. dovanquished()
1875. {
1876.     list_vanquished('a', FALSE);
1877.     return 0;
1878. }
1879. 
1880. /* high priests aren't unique but are flagged as such to simplify something */
1881. #define UniqCritterIndx(mndx) ((mons[mndx].geno & G_UNIQ) \
1882.                                && mndx != PM_HIGH_PRIEST)
1883. 
1884. STATIC_OVL void
1885. list_vanquished(defquery, ask)
1886. char defquery;
1887. boolean ask;
1888. {
1889.     register int i;
1890.     int pfx, nkilled;
1891.     unsigned ntypes, ni;
1892.     long total_killed = 0L;
1893.     winid klwin;
1894.     short mindx[NUMMONS];
1895.     char c, buf[BUFSZ], buftoo[BUFSZ];
1896.     boolean dumping; /* for DUMPLOG; doesn't need to be conditional */
1897. 
1898.     dumping = (defquery == 'd');
1899.     if (dumping)
1900.         defquery = 'y';
1901. 
1902.     /* get totals first */
1903.     ntypes = 0;
1904.     for (i = LOW_PM; i < NUMMONS; i++) {
1905.         if ((nkilled = (int) mvitals[i].died) == 0)
1906.             continue;
1907.         mindx[ntypes++] = i;
1908.         total_killed += (long) nkilled;
1909.     }
1910. 
1911.     /* vanquished creatures list;
1912.      * includes all dead monsters, not just those killed by the player
1913.      */
1914.     if (ntypes != 0) {
1915.         char mlet, prev_mlet = 0; /* used as small integer, not character */
1916.         boolean class_header, uniq_header, was_uniq = FALSE;
1917. 
1918.         c = ask ? yn_function(
1919.                             "Do you want an account of creatures vanquished?",
1920.                               ynaqchars, defquery)
1921.                 : defquery;
1922.         if (c == 'q')
1923.             done_stopprint++;
1924.         if (c == 'y' || c == 'a') {
1925.             if (c == 'a') { /* ask player to choose sort order */
1926.                 /* choose value for vanq_sortmode via menu; ESC cancels list
1927.                    of vanquished monsters but does not set 'done_stopprint' */
1928.                 if (set_vanq_order() < 0)
1929.                     return;
1930.             }
1931.             uniq_header = (vanq_sortmode == VANQ_ALPHA_SEP);
1932.             class_header = (vanq_sortmode == VANQ_MCLS_LTOH
1933.                             || vanq_sortmode == VANQ_MCLS_HTOL);
1934. 
1935.             klwin = create_nhwindow(NHW_MENU);
1936.             putstr(klwin, 0, "Vanquished creatures:");
1937.             if (!dumping)
1938.                 putstr(klwin, 0, "");
1939. 
1940.             qsort((genericptr_t) mindx, ntypes, sizeof *mindx, vanqsort_cmp);
1941.             for (ni = 0; ni < ntypes; ni++) {
1942.                 i = mindx[ni];
1943.                 nkilled = mvitals[i].died;
1944.                 mlet = mons[i].mlet;
1945.                 if (class_header && mlet != prev_mlet) {
1946.                     Strcpy(buf, def_monsyms[(int) mlet].explain);
1947.                     putstr(klwin, ask ? 0 : iflags.menu_headings,
1948.                            upstart(buf));
1949.                     prev_mlet = mlet;
1950.                 }
1951.                 if (UniqCritterIndx(i)) {
1952.                     Sprintf(buf, "%s%s",
1953.                             !type_is_pname(&mons[i]) ? "the " : "",
1954.                             mons[i].mname);
1955.                     if (nkilled > 1) {
1956.                         switch (nkilled) {
1957.                         case 2:
1958.                             Sprintf(eos(buf), " (twice)");
1959.                             break;
1960.                         case 3:
1961.                             Sprintf(eos(buf), " (thrice)");
1962.                             break;
1963.                         default:
1964.                             Sprintf(eos(buf), " (%d times)", nkilled);
1965.                             break;
1966.                         }
1967.                     }
1968.                     was_uniq = TRUE;
1969.                 } else {
1970.                     if (uniq_header && was_uniq) {
1971.                         putstr(klwin, 0, "");
1972.                         was_uniq = FALSE;
1973.                     }
1974.                     /* trolls or undead might have come back,
1975.                        but we don't keep track of that */
1976.                     if (nkilled == 1)
1977.                         Strcpy(buf, an(mons[i].mname));
1978.                     else
1979.                         Sprintf(buf, "%3d %s", nkilled,
1980.                                 makeplural(mons[i].mname));
1981.                 }
1982.                 /* number of leading spaces to match 3 digit prefix */
1983.                 pfx = !strncmpi(buf, "the ", 3) ? 0
1984.                       : !strncmpi(buf, "an ", 3) ? 1
1985.                         : !strncmpi(buf, "a ", 2) ? 2
1986.                           : !digit(buf[2]) ? 4 : 0;
1987.                 if (class_header)
1988.                     ++pfx;
1989.                 Sprintf(buftoo, "%*s%s", pfx, "", buf);
1990.                 putstr(klwin, 0, buftoo);
1991.             }
1992.             /*
1993.              * if (Hallucination)
1994.              *     putstr(klwin, 0, "and a partridge in a pear tree");
1995.              */
1996.             if (ntypes > 1) {
1997.                 if (!dumping)
1998.                     putstr(klwin, 0, "");
1999.                 Sprintf(buf, "%ld creatures vanquished.", total_killed);
2000.                 putstr(klwin, 0, buf);
2001.             }
2002.             display_nhwindow(klwin, TRUE);
2003.             destroy_nhwindow(klwin);
2004.         }
2005.     } else if (defquery == 'a') {
2006.         /* #dovanquished rather than final disclosure, so pline() is ok */
2007.         pline("No creatures have been vanquished.");
2008. #ifdef DUMPLOG
2009.     } else if (dumping) {
2010.         putstr(0, 0, "No creatures were vanquished."); /* not pline() */
2011. #endif
2012.     }
2013. }
2014. 
2015. /* number of monster species which have been genocided */
2016. int
2017. num_genocides()
2018. {
2019.     int i, n = 0;
2020. 
2021.     for (i = LOW_PM; i < NUMMONS; ++i) {
2022.         if (mvitals[i].mvflags & G_GENOD) {
2023.             ++n;
2024.             if (UniqCritterIndx(i))
2025.                 impossible("unique creature '%d: %s' genocided?",
2026.                            i, mons[i].mname);
2027.         }
2028.     }
2029.     return n;
2030. }
2031. 
2032. STATIC_OVL int
2033. num_extinct()
2034. {
2035.     int i, n = 0;
2036. 
2037.     for (i = LOW_PM; i < NUMMONS; ++i) {
2038.         if (UniqCritterIndx(i))
2039.             continue;
2040.         if ((mvitals[i].mvflags & G_GONE) == G_EXTINCT)
2041.             ++n;
2042.     }
2043.     return n;
2044. }
2045. 
2046. STATIC_OVL void
2047. list_genocided(defquery, ask)
2048. char defquery;
2049. boolean ask;
2050. {
2051.     register int i;
2052.     int ngenocided, nextinct;
2053.     char c;
2054.     winid klwin;
2055.     char buf[BUFSZ];
2056.     boolean dumping; /* for DUMPLOG; doesn't need to be conditional */
2057. 
2058.     dumping = (defquery == 'd');
2059.     if (dumping)
2060.         defquery = 'y';
2061. 
2062.     ngenocided = num_genocides();
2063.     nextinct = num_extinct();
2064. 
2065.     /* genocided or extinct species list */
2066.     if (ngenocided != 0 || nextinct != 0) {
2067.         Sprintf(buf, "Do you want a list of %sspecies%s%s?",
2068.                 (nextinct && !ngenocided) ? "extinct " : "",
2069.                 (ngenocided) ? " genocided" : "",
2070.                 (nextinct && ngenocided) ? " and extinct" : "");
2071.         c = ask ? yn_function(buf, ynqchars, defquery) : defquery;
2072.         if (c == 'q')
2073.             done_stopprint++;
2074.         if (c == 'y') {
2075.             klwin = create_nhwindow(NHW_MENU);
2076.             Sprintf(buf, "%s%s species:",
2077.                     (ngenocided) ? "Genocided" : "Extinct",
2078.                     (nextinct && ngenocided) ? " or extinct" : "");
2079.             putstr(klwin, 0, buf);
2080.             if (!dumping)
2081.                 putstr(klwin, 0, "");
2082. 
2083.             for (i = LOW_PM; i < NUMMONS; i++) {
2084.                 /* uniques can't be genocided but can become extinct;
2085.                    however, they're never reported as extinct, so skip them */
2086.                 if (UniqCritterIndx(i))
2087.                     continue;
2088.                 if (mvitals[i].mvflags & G_GONE) {
2089.                     Sprintf(buf, " %s", makeplural(mons[i].mname));
2090.                     /*
2091.                      * "Extinct" is unfortunate terminology.  A species
2092.                      * is marked extinct when its birth limit is reached,
2093.                      * but there might be members of the species still
2094.                      * alive, contradicting the meaning of the word.
2095.                      */
2096.                     if ((mvitals[i].mvflags & G_GONE) == G_EXTINCT)
2097.                         Strcat(buf, " (extinct)");
2098.                     putstr(klwin, 0, buf);
2099.                 }
2100.             }
2101.             if (!dumping)
2102.                 putstr(klwin, 0, "");
2103.             if (ngenocided > 0) {
2104.                 Sprintf(buf, "%d species genocided.", ngenocided);
2105.                 putstr(klwin, 0, buf);
2106.             }
2107.             if (nextinct > 0) {
2108.                 Sprintf(buf, "%d species extinct.", nextinct);
2109.                 putstr(klwin, 0, buf);
2110.             }
2111. 
2112.             display_nhwindow(klwin, TRUE);
2113.             destroy_nhwindow(klwin);
2114.         }
2115. #ifdef DUMPLOG
2116.     } else if (dumping) {
2117.         putstr(0, 0, "No species were genocided or became extinct.");
2118. #endif
2119.     }
2120. }
2121. 
2122. /* set a delayed killer, ensure non-delayed killer is cleared out */
2123. void
2124. delayed_killer(id, format, killername)
2125. int id;
2126. int format;
2127. const char *killername;
2128. {
2129.     struct kinfo *k = find_delayed_killer(id);
2130. 
2131.     if (!k) {
2132.         /* no match, add a new delayed killer to the list */
2133.         k = (struct kinfo *) alloc(sizeof (struct kinfo));
2134.         (void) memset((genericptr_t) k, 0, sizeof (struct kinfo));
2135.         k->id = id;
2136.         k->next = killer.next;
2137.         killer.next = k;
2138.     }
2139. 
2140.     k->format = format;
2141.     Strcpy(k->name, killername ? killername : "");
2142.     killer.name[0] = 0;
2143. }
2144. 
2145. struct kinfo *
2146. find_delayed_killer(id)
2147. int id;
2148. {
2149.     struct kinfo *k;
2150. 
2151.     for (k = killer.next; k != (struct kinfo *) 0; k = k->next) {
2152.         if (k->id == id)
2153.             break;
2154.     }
2155.     return k;
2156. }
2157. 
2158. void
2159. dealloc_killer(kptr)
2160. struct kinfo *kptr;
2161. {
2162.     struct kinfo *prev = &killer, *k;
2163. 
2164.     if (kptr == (struct kinfo *) 0)
2165.         return;
2166.     for (k = killer.next; k != (struct kinfo *) 0; k = k->next) {
2167.         if (k == kptr)
2168.             break;
2169.         prev = k;
2170.     }
2171. 
2172.     if (k == (struct kinfo *) 0) {
2173.         impossible("dealloc_killer (#%d) not on list", kptr->id);
2174.     } else {
2175.         prev->next = k->next;
2176.         free((genericptr_t) k);
2177.         debugpline1("freed delayed killer #%d", kptr->id);
2178.     }
2179. }
2180. 
2181. void
2182. save_killers(fd, mode)
2183. int fd;
2184. int mode;
2185. {
2186.     struct kinfo *kptr;
2187. 
2188.     if (perform_bwrite(mode)) {
2189.         for (kptr = &killer; kptr != (struct kinfo *) 0; kptr = kptr->next) {
2190.             bwrite(fd, (genericptr_t) kptr, sizeof (struct kinfo));
2191.         }
2192.     }
2193.     if (release_data(mode)) {
2194.         while (killer.next) {
2195.             kptr = killer.next->next;
2196.             free((genericptr_t) killer.next);
2197.             killer.next = kptr;
2198.         }
2199.     }
2200. }
2201. 
2202. void
2203. restore_killers(fd)
2204. int fd;
2205. {
2206.     struct kinfo *kptr;
2207. 
2208.     for (kptr = &killer; kptr != (struct kinfo *) 0; kptr = kptr->next) {
2209.         mread(fd, (genericptr_t) kptr, sizeof (struct kinfo));
2210.         if (kptr->next) {
2211.             kptr->next = (struct kinfo *) alloc(sizeof (struct kinfo));
2212.         }
2213.     }
2214. }
2215. 
2216. static int
2217. wordcount(p)
2218. char *p;
2219. {
2220.     int words = 0;
2221. 
2222.     while (*p) {
2223.         while (*p && isspace((uchar) *p))
2224.             p++;
2225.         if (*p)
2226.             words++;
2227.         while (*p && !isspace((uchar) *p))
2228.             p++;
2229.     }
2230.     return words;
2231. }
2232. 
2233. static void
2234. bel_copy1(inp, out)
2235. char **inp, *out;
2236. {
2237.     char *in = *inp;
2238. 
2239.     out += strlen(out); /* eos() */
2240.     while (*in && isspace((uchar) *in))
2241.         in++;
2242.     while (*in && !isspace((uchar) *in))
2243.         *out++ = *in++;
2244.     *out = '\0';
2245.     *inp = in;
2246. }
2247. 
2248. char *
2249. build_english_list(in)
2250. char *in;
2251. {
2252.     char *out, *p = in;
2253.     int len = (int) strlen(p), words = wordcount(p);
2254. 
2255.     /* +3: " or " - " "; +(words - 1): (N-1)*(", " - " ") */
2256.     if (words > 1)
2257.         len += 3 + (words - 1);
2258.     out = (char *) alloc(len + 1);
2259.     *out = '\0'; /* bel_copy1() appends */
2260. 
2261.     switch (words) {
2262.     case 0:
2263.         impossible("no words in list");
2264.         break;
2265.     case 1:
2266.         /* "single" */
2267.         bel_copy1(&p, out);
2268.         break;
2269.     default:
2270.         if (words == 2) {
2271.             /* "first or second" */
2272.             bel_copy1(&p, out);
2273.             Strcat(out, " ");
2274.         } else {
2275.             /* "first, second, or third */
2276.             do {
2277.                 bel_copy1(&p, out);
2278.                 Strcat(out, ", ");
2279.             } while (--words > 1);
2280.         }
2281.         Strcat(out, "or ");
2282.         bel_copy1(&p, out);
2283.         break;
2284.     }
2285.     return out;
2286. }
2287. 
2288. /*end.c*/