Source:NetHack 5.0.0/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 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/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 5.0	end.c	$NHDT-Date: 1720397752 2024/07/08 00:15:52 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.315 $ */
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. #ifndef NO_SIGNAL
10. #include <signal.h>
11. #endif
12. #include "dlb.h"
13. 
14. #ifndef SFCTOOL
15. #ifndef NO_SIGNAL
16. staticfn void done_intr(int);
17. # if defined(UNIX) || defined(VMS) || defined(__EMX__)
18. staticfn void done_hangup(int);
19. # endif
20. #endif
21. staticfn void disclose(int, boolean);
22. staticfn void get_valuables(struct obj *) NO_NNARGS;
23. staticfn void sort_valuables(struct valuable_data *, int);
24. staticfn void artifact_score(struct obj *, boolean, winid);
25. staticfn boolean fuzzer_savelife(int);
26. ATTRNORETURN staticfn void really_done(int) NORETURN;
27. staticfn void savelife(int);
28. staticfn boolean should_query_disclose_option(int, char *);
29. #ifdef DUMPLOG
30. staticfn void dump_plines(void);
31. #endif
32. staticfn void dump_everything(int, time_t);
33. staticfn void fixup_death(int);
34. #endif /* SFCTOOL */
35. staticfn int wordcount(char *);
36. staticfn void bel_copy1(char **, char *);
37. 
38. #ifndef SFCTOOL
39. #define done_stopprint program_state.stopprint
40. 
41. /*
42.  * The order of these needs to match the macros in hack.h.
43.  */
44. static NEARDATA const char *deaths[] = {
45.     /* the array of death */
46.     "died", "choked", "poisoned", "starvation", "drowning", "burning",
47.     "dissolving under the heat and pressure", "crushed", "turned to stone",
48.     "turned into slime", "genocided", "panic", "trickery", "quit",
49.     "escaped", "ascended"
50. };
51. 
52. static NEARDATA const char *ends[] = {
53.     /* "when you %s" */
54.     "died", "choked", "were poisoned",
55.     "starved", "drowned", "burned",
56.     "dissolved in the lava",
57.     "were crushed", "turned to stone",
58.     "turned into slime", "were genocided",
59.     "panicked", "were tricked", "quit",
60.     "escaped", "ascended"
61. };
62. 
63. static boolean Schroedingers_cat = FALSE;
64. 
65. /* called as signal() handler, so sent at least one arg */
66. /*ARGSUSED*/
67. void
68. done1(int sig_unused UNUSED)
69. {
70. #ifndef NO_SIGNAL
71.     (void) signal(SIGINT, SIG_IGN);
72. #endif
73.     iflags.debug_fuzzer = fuzzer_off;
74.     if (flags.ignintr) {
75. #ifndef NO_SIGNAL
76.         (void) signal(SIGINT, (SIG_RET_TYPE) done1);
77. #endif
78.         clear_nhwindow(WIN_MESSAGE);
79.         curs_on_u();
80.         wait_synch();
81.         if (gm.multi > 0)
82.             nomul(0);
83.     } else {
84.         (void) done2();
85.     }
86. }
87. 
88. /* "#quit" command or keyboard interrupt */
89. int
90. done2(void)
91. {
92.     boolean abandon_tutorial = FALSE;
93. 
94.     if (In_tutorial(&u.uz)
95.         && y_n("Switch from the tutorial back to regular play?") == 'y')
96.         abandon_tutorial = TRUE;
97. 
98.     if (abandon_tutorial || !paranoid_query(
99.             ParanoidQuit, "Really quit without saving?")) {
100. #ifndef NO_SIGNAL
101.         (void) signal(SIGINT, (SIG_RET_TYPE) done1);
102. #endif
103.         clear_nhwindow(WIN_MESSAGE);
104.         curs_on_u();
105.         wait_synch();
106.         if (gm.multi > 0)
107.             nomul(0);
108.         if (gm.multi == 0) {
109.             u.uinvulnerable = FALSE; /* avoid ctrl-C bug -dlc */
110.             u.usleep = 0;
111.         }
112. 
113.         if (abandon_tutorial)
114.             schedule_goto(&u.ucamefrom, UTOTYPE_ATSTAIRS,
115.                           "Resuming regular play.", (char *) 0);
116.         return ECMD_OK;
117.     }
118. 
119. #if (defined(UNIX) || defined(VMS) || defined(LATTICE))
120.     if (wizard) {
121.         int c;
122. #ifdef VMS
123.         extern int debuggable; /* sys/vms/vmsmisc.c, vmsunix.c */
124. 
125.         c = !debuggable ? 'n' : ynq("Enter debugger?");
126. #else
127. #ifdef LATTICE
128.         c = ynq("Create SnapShot?");
129. #else
130.         c = ynq("Dump core?");
131. #endif
132. #endif
133.         if (c == 'y') {
134. #ifndef NO_SIGNAL
135.             (void) signal(SIGINT, (SIG_RET_TYPE) done1);
136. #endif
137.             if (soundprocs.sound_exit_nhsound)
138.                 (*soundprocs.sound_exit_nhsound)("done2");
139. 
140.             exit_nhwindows((char *) 0);
141.             NH_abort(NULL);
142.         } else if (c == 'q')
143.             done_stopprint++;
144.     }
145. #endif
146.     done(QUIT);
147.     return ECMD_OK;
148. }
149. 
150. #ifndef NO_SIGNAL
151. /* called as signal() handler, so sent at least 1 arg */
152. /*ARGSUSED*/
153. staticfn void
154. done_intr(int sig_unused UNUSED)
155. {
156.     done_stopprint++;
157.     (void) signal(SIGINT, SIG_IGN);
158. #if defined(UNIX) || defined(VMS)
159. #ifndef VMSVSI
160.     (void) signal(SIGQUIT, SIG_IGN);
161. #endif
162. #endif
163.     return;
164. }
165. 
166. #if defined(UNIX) || defined(VMS) || defined(__EMX__)
167. /* signal() handler */
168. staticfn void
169. done_hangup(int sig)
170. {
171. #ifdef HANGUPHANDLING
172.     program_state.done_hup++;
173. #endif
174.     sethanguphandler((void (*)(int)) SIG_IGN);
175.     done_intr(sig);
176.     return;
177. }
178. #endif
179. #endif /* NO_SIGNAL */
180. 
181. DISABLE_WARNING_FORMAT_NONLITERAL /* one compiler warns if the format
182.                                      string is the result of a ? x : y */
183. 
184. void
185. done_in_by(struct monst *mtmp, int how)
186. {
187.     char buf[BUFSZ];
188.     struct permonst *mptr = mtmp->data,
189.                     *champtr = ismnum(mtmp->cham) ? &mons[mtmp->cham]
190.                                                   : mptr;
191.     boolean distorted = (boolean) (Hallucination && canspotmon(mtmp)),
192.             mimicker = (M_AP_TYPE(mtmp) == M_AP_MONSTER),
193.             imitator = (mptr != champtr || mimicker);
194. 
195.     You((how == STONING) ? "turn to stone..." : "die...");
196.     mark_synch(); /* flush buffered screen output */
197.     buf[0] = '\0';
198.     svk.killer.format = KILLED_BY_AN;
199.     /* "killed by the high priest of Crom" is okay,
200.        "killed by the high priest" alone isn't */
201.     if ((mptr->geno & G_UNIQ) != 0 && !(imitator && !mimicker)
202.         && !(mptr == &mons[PM_HIGH_CLERIC] && !mtmp->ispriest)) {
203.         if (!type_is_pname(mptr))
204.             Strcat(buf, "the ");
205.         svk.killer.format = KILLED_BY;
206.     }
207.     /* _the_ <invisible> <distorted> ghost of Dudley */
208. #if 0
209.     /* hardfought */
210.     if (has_ebones(mtmp)) {
211. #else
212.     if (mptr == &mons[PM_GHOST] && has_mgivenname(mtmp)) {
213. #endif
214.         Strcat(buf, "the ");
215.         svk.killer.format = KILLED_BY;
216.     }
217.     (void) monhealthdescr(mtmp, TRUE, eos(buf));
218.     if (mtmp->minvis)
219.         Strcat(buf, "invisible ");
220.     if (distorted)
221.         Strcat(buf, "hallucinogen-distorted ");
222. 
223.     if (imitator) {
224.         char shape[BUFSZ];
225.         const char *realnm = pmname(champtr, Mgender(mtmp)),
226.                    *fakenm = pmname(mptr, Mgender(mtmp));
227.         boolean alt = is_vampshifter(mtmp);
228. 
229.         if (mimicker) {
230.             /* realnm is already correct because champtr==mptr;
231.                set up fake mptr for type_is_pname/the_unique_pm */
232.             mptr = &mons[mtmp->mappearance];
233.             fakenm = pmname(mptr, Mgender(mtmp));
234.         } else if (alt && strstri(realnm, "vampire")
235.                    && !strcmp(fakenm, "vampire bat")) {
236.             /* special case: use "vampire in bat form" in preference
237.                to redundant looking "vampire in vampire bat form" */
238.             fakenm = "bat";
239.         }
240.         /* for the alternate format, always suppress any article;
241.            pname and the_unique should also have s_suffix() applied,
242.            but vampires don't take on any shapes which warrant that */
243.         if (alt || type_is_pname(mptr)) /* no article */
244.             Strcpy(shape, fakenm);
245.         else if (the_unique_pm(mptr)) /* "the"; don't use the() here */
246.             Sprintf(shape, "the %s", fakenm);
247.         else /* "a"/"an" */
248.             Strcpy(shape, an(fakenm));
249.         /* omit "called" to avoid excessive verbosity */
250.         Sprintf(eos(buf),
251.                 alt ? "%s in %s form"
252.                     : mimicker ? "%s disguised as %s"
253.                                : "%s imitating %s",
254.                 realnm, shape);
255.         mptr = mtmp->data; /* reset for mimicker case */
256. #if 0  /* hardfought */
257.     } else if (has_ebones(mtmp)) {
258.         Strcpy(buf, m_monnam(mtmp));
259. #endif
260.     } else if (mptr == &mons[PM_GHOST]) {
261.         Strcat(buf, "ghost");
262.         if (has_mgivenname(mtmp))
263.             Sprintf(eos(buf), " of %s", MGIVENNAME(mtmp));
264.     } else if (mtmp->isshk) {
265.         const char *shknm = shkname(mtmp),
266.                    *honorific = shkname_is_pname(mtmp) ? ""
267.                                    : mtmp->female ? "Ms. " : "Mr. ";
268. 
269.         Sprintf(eos(buf), "%s%s, the shopkeeper", honorific, shknm);
270.         svk.killer.format = KILLED_BY;
271.     } else if (mtmp->ispriest || mtmp->isminion) {
272.         /* m_monnam() suppresses "the" prefix plus "invisible", and
273.            it overrides the effect of Hallucination on priestname() */
274.         Strcat(buf, m_monnam(mtmp));
275.     } else {
276.         Strcat(buf, pmname(mptr, Mgender(mtmp)));
277.         if (has_mgivenname(mtmp)) {
278.             Sprintf(eos(buf), " %s %s",
279.                     has_ebones(mtmp) ? "of" : "called",
280.                     MGIVENNAME(mtmp));
281.         }
282.     }
283. 
284.     Strcpy(svk.killer.name, buf);
285. 
286.     /* might need to fix up multi_reason if 'mtmp' caused the reason */
287.     if (gm.multi_reason
288.         && gm.multi_reason > gm.multireasonbuf
289.         && gm.multi_reason
290.            < gm.multireasonbuf + sizeof gm.multireasonbuf - 1) {
291.         char reasondummy, *p;
292.         unsigned reasonmid = 0;
293. 
294.         /*
295.          * multireasonbuf[] contains 'm_id:reason' and multi_reason
296.          * points at the text past the colon, so we have something
297.          * like "42:paralyzed by a ghoul"; if mtmp->m_id matches 42
298.          * then we truncate 'reason' at its first space so that final
299.          * death reason becomes "Killed by a ghoul, while paralyzed."
300.          * instead of "Killed by a ghoul, while paralyzed by a ghoul."
301.          * (3.6.x gave "Killed by a ghoul, while paralyzed by a monster."
302.          * which is potentially misleading when the monster is also
303.          * the killer.)
304.          *
305.          * Note that if the hero is life-saved and then killed again
306.          * before the helplessness has cleared, the second death will
307.          * report the truncated helplessness reason even if some other
308.          * monster performs the /coup de grace/.
309.          */
310.         if (sscanf(gm.multireasonbuf, "%u:%c", &reasonmid, &reasondummy) == 2
311.             && mtmp->m_id == reasonmid) {
312.             if ((p = strchr(gm.multireasonbuf, ' ')) != 0)
313.                 *p = '\0';
314.         }
315.     }
316. 
317.     /*
318.      * Chicken and egg issue:
319.      *  Ordinarily Unchanging ought to override something like this,
320.      *  but the transformation occurs at death.  With the current code,
321.      *  the effectiveness of Unchanging stops first, but a case could
322.      *  be made that it should last long enough to prevent undead
323.      *  transformation.  (Turning to slime isn't an issue here because
324.      *  Unchanging prevents that from happening.)
325.      */
326.     if (mptr->mlet == S_WRAITH)
327.         u.ugrave_arise = PM_WRAITH;
328.     else if (mptr->mlet == S_MUMMY && gu.urace.mummynum != NON_PM)
329.         u.ugrave_arise = gu.urace.mummynum;
330.     else if (zombie_maker(mtmp) && gu.urace.zombienum != NON_PM)
331.         u.ugrave_arise = gu.urace.zombienum;
332.     else if (mptr->mlet == S_VAMPIRE && Race_if(PM_HUMAN))
333.         u.ugrave_arise = PM_VAMPIRE;
334.     else if (mptr == &mons[PM_GHOUL])
335.         u.ugrave_arise = PM_GHOUL;
336.     /* this could happen if a high-end vampire kills the hero
337.        when ordinary vampires are genocided; ditto for wraiths */
338.     if (u.ugrave_arise >= LOW_PM
339.         && (svm.mvitals[u.ugrave_arise].mvflags & G_GENOD))
340.         u.ugrave_arise = NON_PM;
341. 
342.     done(how);
343.     return;
344. }
345. 
346. RESTORE_WARNING_FORMAT_NONLITERAL
347. 
348. /* some special cases for overriding while-helpless reason */
349. static const struct {
350.     int why, unmulti;
351.     const char *exclude, *include;
352. } death_fixups[] = {
353.     /* "petrified by <foo>, while getting stoned" -- "while getting stoned"
354.        prevented any last-second recovery, but it was not the cause of
355.        "petrified by <foo>" */
356.     { STONING, 1, "getting stoned", (char *) 0 },
357.     /* "died of starvation, while fainted from lack of food" is accurate
358.        but sounds a fairly silly (and doesn't actually appear unless you
359.        splice together death and while-helpless from xlogfile) */
360.     { STARVING, 0, "fainted from lack of food", "fainted" },
361. };
362. 
363. /* clear away while-helpless when the cause of death caused that
364.    helplessness (ie, "petrified by <foo> while getting stoned") */
365. staticfn void
366. fixup_death(int how)
367. {
368.     int i;
369. 
370.     if (gm.multi_reason) {
371.         for (i = 0; i < SIZE(death_fixups); ++i)
372.             if (death_fixups[i].why == how
373.                 && !strcmp(death_fixups[i].exclude, gm.multi_reason)) {
374.                 if (death_fixups[i].include) /* substitute alternate reason */
375.                     gm.multi_reason = death_fixups[i].include;
376.                 else /* remove the helplessness reason */
377.                     gm.multi_reason = (char *) 0;
378.                 gm.multireasonbuf[0] = '\0'; /* dynamic buf stale either way */
379.                 if (death_fixups[i].unmulti) /* possibly hide helplessness */
380.                     gm.multi = 0L;
381.                 break;
382.             }
383.     }
384. }
385. 
386. #if defined(WIN32) && !defined(SYSCF)
387. #define NOTIFY_NETHACK_BUGS
388. #endif
389. 
390. DISABLE_WARNING_FORMAT_NONLITERAL
391. 
392. /*VARARGS1*/
393. ATTRNORETURN void
394. panic VA_DECL(const char *, str)
395. {
396.     char buf[BUFSZ];
397.     VA_START(str);
398.     VA_INIT(str, char *);
399. 
400.     if (program_state.panicking++)
401.         NH_abort(NULL); /* avoid loops - this should never happen*/
402. 
403.     gb.bot_disabled = TRUE;
404.     if (iflags.window_inited) {
405.         raw_print("\r\nOops...");
406.         wait_synch(); /* make sure all pending output gets flushed */
407.         if (soundprocs.sound_exit_nhsound)
408.             (*soundprocs.sound_exit_nhsound)("panic");
409.         exit_nhwindows((char *) 0);
410.         iflags.window_inited = FALSE; /* they're gone; force raw_print()ing */
411.     }
412. 
413.     raw_print(program_state.gameover
414.                   ? "Postgame wrapup disrupted."
415.                   : !program_state.something_worth_saving
416.                         ? "Program initialization has failed."
417.                         : "Suddenly, the dungeon collapses.");
418. #ifndef MICRO
419. #ifdef NOTIFY_NETHACK_BUGS
420.     if (!wizard)
421.         raw_printf("Report the following error to \"%s\" or at \"%s\".",
422.                    DEVTEAM_EMAIL, DEVTEAM_URL);
423.     else if (program_state.something_worth_saving)
424.         raw_print("\nError save file being written.\n");
425. #else /* !NOTIFY_NETHACK_BUGS */
426.     if (!wizard) {
427.         const char *maybe_rebuild = !program_state.something_worth_saving
428.                                      ? "."
429.                                      : "\nand it may be possible to rebuild.";
430. 
431. // XXX this may need an update if defined(CRASHREPORT) TBD
432.         if (sysopt.support)
433.             raw_printf("To report this error, %s%s", sysopt.support,
434.                        maybe_rebuild);
435.         else if (sysopt.fmtd_wizard_list) /* formatted SYSCF WIZARDS */
436.             raw_printf("To report this error, contact %s%s",
437.                        sysopt.fmtd_wizard_list, maybe_rebuild);
438.         else
439.             raw_printf("Report error to \"%s\"%s", WIZARD_NAME,
440.                        maybe_rebuild);
441.     }
442. #endif /* ?NOTIFY_NETHACK_BUGS */
443.     /* XXX can we move this above the prints?  Then we'd be able to
444.      * suppress "it may be possible to rebuild" based on dosave0()
445.      * or say it's NOT possible to rebuild. */
446.     if (program_state.something_worth_saving && !iflags.debug_fuzzer) {
447.         set_error_savefile();
448.         if (dosave0()) {
449.             /* os/win port specific recover instructions */
450.             if (sysopt.recover)
451.                 raw_printf("%s", sysopt.recover);
452.         }
453.     }
454. #endif /* !MICRO */
455. 
456.     (void) vsnprintf(buf, sizeof buf, str, VA_ARGS);
457.     raw_print(buf);
458.     paniclog("panic", buf);
459. 
460. #ifdef WIN32
461.     interject(INTERJECT_PANIC);
462. #endif
463. #if defined(UNIX) || defined(VMS) || defined(LATTICE) || defined(WIN32)
464. # ifndef CRASHREPORT
465.     if (wizard)
466. # endif
467.         NH_abort(buf); /* generate core dump */
468. #endif
469.     VA_END();
470.     really_done(PANICKED);
471. }
472. 
473. RESTORE_WARNING_FORMAT_NONLITERAL
474. 
475. staticfn boolean
476. should_query_disclose_option(int category, char *defquery)
477. {
478.     int idx;
479.     char disclose;
480.     const char *dop;
481. 
482.     *defquery = 'n';
483.     if ((dop = strchr(disclosure_options, category)) != 0) {
484.         idx = (int) (dop - disclosure_options);
485.         if (idx < 0 || idx >= NUM_DISCLOSURE_OPTIONS) {
486.             impossible(
487.                    "should_query_disclose_option: bad disclosure index %d %c",
488.                        idx, category);
489.             *defquery = DISCLOSE_PROMPT_DEFAULT_YES;
490.             return TRUE;
491.         }
492.         disclose = flags.end_disclose[idx];
493.         if (disclose == DISCLOSE_YES_WITHOUT_PROMPT) {
494.             *defquery = 'y';
495.             return FALSE;
496.         } else if (disclose == DISCLOSE_SPECIAL_WITHOUT_PROMPT) {
497.             *defquery = 'a';
498.             return FALSE;
499.         } else if (disclose == DISCLOSE_NO_WITHOUT_PROMPT) {
500.             *defquery = 'n';
501.             return FALSE;
502.         } else if (disclose == DISCLOSE_PROMPT_DEFAULT_YES) {
503.             *defquery = 'y';
504.             return TRUE;
505.         } else if (disclose == DISCLOSE_PROMPT_DEFAULT_SPECIAL) {
506.             *defquery = 'a';
507.             return TRUE;
508.         } else {
509.             *defquery = 'n';
510.             return TRUE;
511.         }
512.     }
513.     impossible("should_query_disclose_option: bad category %c", category);
514.     return TRUE;
515. }
516. 
517. #ifdef DUMPLOG
518. staticfn void
519. dump_plines(void)
520. {
521.     int i, j;
522.     char buf[BUFSZ], **strp;
523. 
524.     Strcpy(buf, " "); /* one space for indentation */
525.     putstr(0, 0, "Latest messages:");
526.     for (i = 0, j = (int) gs.saved_pline_index; i < DUMPLOG_MSG_COUNT;
527.          ++i, j = (j + 1) % DUMPLOG_MSG_COUNT) {
528.         strp = &gs.saved_plines[j];
529.         if (*strp) {
530.             copynchars(&buf[1], *strp, BUFSZ - 1 - 1);
531.             putstr(0, 0, buf);
532. #ifdef FREE_ALL_MEMORY
533.             free(*strp), *strp = 0;
534. #endif
535.         }
536.     }
537. }
538. #endif  /* DUMPLOG */
539. 
540. /*ARGSUSED*/
541. staticfn void
542. dump_everything(
543.     int how,     /* ASCENDED, ESCAPED, QUIT, etc */
544.     time_t when) /* date+time at end of game */
545. {
546. #ifdef DUMPLOG
547.     char pbuf[BUFSZ], datetimebuf[24]; /* [24]: room for 64-bit bogus value */
548. 
549.     dump_redirect(TRUE);
550.     if (!iflags.in_dumplog)
551.         return;
552. 
553.     init_symbols(); /* revert to default symbol set */
554. 
555.     /* one line version ID, which includes build date+time;
556.        it's conceivable that the game started with a different
557.        build date+time or even with an older nethack version,
558.        but we only have access to the one it finished under */
559.     putstr(0, 0, getversionstring(pbuf, sizeof pbuf));
560.     putstr(0, 0, "");
561. 
562.     /* game start and end date+time to disambiguate version date+time */
563.     Strcpy(datetimebuf, yyyymmddhhmmss(ubirthday));
564.     Sprintf(pbuf, "Game began %4.4s-%2.2s-%2.2s %2.2s:%2.2s:%2.2s",
565.             &datetimebuf[0], &datetimebuf[4], &datetimebuf[6],
566.             &datetimebuf[8], &datetimebuf[10], &datetimebuf[12]);
567.     Strcpy(datetimebuf, yyyymmddhhmmss(when));
568.     Sprintf(eos(pbuf), ", ended %4.4s-%2.2s-%2.2s %2.2s:%2.2s:%2.2s.",
569.             &datetimebuf[0], &datetimebuf[4], &datetimebuf[6],
570.             &datetimebuf[8], &datetimebuf[10], &datetimebuf[12]);
571.     putstr(0, 0, pbuf);
572.     putstr(0, 0, "");
573. 
574.     /* character name and basic role info */
575.     Sprintf(pbuf, "%s, %s %s %s %s",
576.             svp.plname, aligns[1 - u.ualign.type].adj,
577.             genders[flags.female].adj, gu.urace.adj,
578.             (flags.female && gu.urole.name.f) ? gu.urole.name.f
579.                                              : gu.urole.name.m);
580.     putstr(0, 0, pbuf);
581.     putstr(0, 0, "");
582. 
583.     /* info about current game state */
584.     dump_map();
585.     putstr(0, 0, do_statusline1());
586.     putstr(0, 0, do_statusline2());
587.     putstr(0, 0, "");
588. 
589.     dump_plines();
590.     putstr(0, 0, "");
591.     putstr(0, 0, "Inventory:");
592.     (void) display_inventory((char *) 0, TRUE);
593.     container_contents(gi.invent, TRUE, TRUE, FALSE);
594.     enlightenment((BASICENLIGHTENMENT | MAGICENLIGHTENMENT),
595.                   (how >= PANICKED) ? ENL_GAMEOVERALIVE : ENL_GAMEOVERDEAD);
596.     putstr(0, 0, "");
597. 
598.     /* overview of the game up to this point */
599.     show_gamelog((how >= PANICKED) ? ENL_GAMEOVERALIVE : ENL_GAMEOVERDEAD);
600.     putstr(0, 0, "");
601.     show_spells(); /* ends with a blank line */
602.     show_skills(); /* ends with a blank line */
603.     show_conduct((how >= PANICKED) ? 1 : 2);
604.     putstr(0, 0, "");
605.     show_overview((how >= PANICKED) ? 1 : 2, how);
606.     putstr(0, 0, "");
607.     list_vanquished('d', FALSE); /* 'd' => 'y' */
608.     putstr(0, 0, "");
609.     list_genocided('d', FALSE); /* 'd' => 'y' */
610.     putstr(0, 0, "");
611.     dump_redirect(FALSE);
612. #else
613.     nhUse(how);
614.     nhUse(when);
615. #endif
616. }
617. 
618. staticfn void
619. disclose(int how, boolean taken)
620. {
621.     char c = '\0', defquery;
622.     char qbuf[QBUFSZ];
623.     boolean ask = FALSE;
624. 
625.     if (gi.invent && !done_stopprint) {
626.         if (taken)
627.             Sprintf(qbuf, "Do you want to see what you had when you %s?",
628.                     (how == QUIT) ? "quit" : "died");
629.         else
630.             Strcpy(qbuf, "Do you want your possessions identified?");
631. 
632.         ask = should_query_disclose_option('i', &defquery);
633.         c = ask ? yn_function(qbuf, ynqchars, defquery, TRUE) : defquery;
634.         if (c == 'y') {
635.             /* caller has already ID'd everything; we pass 'want_reply=True'
636.                to force display_pickinv() to avoid using WIN_INVENT */
637.             iflags.force_invmenu = FALSE;
638.             (void) display_inventory((char *) 0, TRUE);
639.             container_contents(gi.invent, TRUE, TRUE, FALSE);
640.         }
641.         if (c == 'q')
642.             done_stopprint++;
643.     }
644. 
645.     if (!done_stopprint) {
646.         ask = should_query_disclose_option('a', &defquery);
647.         c = ask ? yn_function("Do you want to see your attributes?", ynqchars,
648.                               defquery, TRUE)
649.                 : defquery;
650.         if (c == 'y')
651.             enlightenment((BASICENLIGHTENMENT | MAGICENLIGHTENMENT),
652.                           (how >= PANICKED) ? ENL_GAMEOVERALIVE
653.                                             : ENL_GAMEOVERDEAD);
654.         if (c == 'q')
655.             done_stopprint++;
656.     }
657. 
658.     if (!done_stopprint) {
659.         ask = should_query_disclose_option('v', &defquery);
660.         list_vanquished(defquery, ask);
661.     }
662. 
663.     if (!done_stopprint) {
664.         ask = should_query_disclose_option('g', &defquery);
665.         list_genocided(defquery, ask);
666.     }
667. 
668.     if (!done_stopprint) {
669.         if (should_query_disclose_option('c', &defquery)) {
670.             int acnt = count_achievements();
671. 
672.             Sprintf(qbuf, "Do you want to see your conduct%s?",
673.                     /* this was distinguishing between one achievement and
674.                        multiple achievements, but "conduct and achievement"
675.                        looked strange if multiple conducts got shown (which
676.                        is usual for an early game death); we could switch
677.                        to plural vs singular for conducts but the less
678.                        specific "conduct and achievements" is sufficient */
679.                     (acnt > 0) ? " and achievements" : "");
680.             c = yn_function(qbuf, ynqchars, defquery, TRUE);
681.         } else {
682.             c = defquery;
683.         }
684.         if (c == 'y')
685.             show_conduct((how >= PANICKED) ? 1 : 2);
686.         if (c == 'q')
687.             done_stopprint++;
688.     }
689. 
690.     if (!done_stopprint) {
691.         ask = should_query_disclose_option('o', &defquery);
692.         c = ask ? yn_function("Do you want to see the dungeon overview?",
693.                               ynqchars, defquery, TRUE)
694.                 : defquery;
695.         if (c == 'y')
696.             show_overview((how >= PANICKED) ? 1 : 2, how);
697.         if (c == 'q')
698.             done_stopprint++;
699.     }
700. }
701. 
702. /* try to get the player back in a viable state after being killed */
703. staticfn void
704. savelife(int how)
705. {
706.     int uhpmin;
707.     int givehp = 50 + 10 * (ACURR(A_CON) / 2);
708. 
709.     /* life-drain/level-loss to experience level 0 kills without actually
710.        reducing ulevel below 1, but include this for bulletproofing */
711.     if (u.ulevel < 1)
712.         u.ulevel = 1;
713.     uhpmin = minuhpmax(10);
714.     if (u.uhpmax < uhpmin)
715.         setuhpmax(uhpmin, TRUE);
716.     u.uhp = min(u.uhpmax, givehp);
717.     if (Upolyd) /* Unchanging, or death which bypasses losing hit points */
718.         u.mh = min(u.mhmax, givehp);
719.     if (u.uhunger < 500 || how == CHOKING) {
720.         init_uhunger();
721.     }
722.     /* cure impending doom of sickness hero won't have time to fix
723.        [shouldn't this also be applied to other fatal timeouts?] */
724.     if ((Sick & TIMEOUT) == 1L) {
725.         make_sick(0L, (char *) 0, FALSE, SICK_ALL);
726.     }
727.     gn.nomovemsg = "You survived that attempt on your life.";
728.     svc.context.move = 0;
729. 
730.     gm.multi = -1; /* can't move again during the current turn */
731.     /* in case being life-saved is immediately followed by being killed
732.        again (perhaps due to zap rebound); this text will be appended to
733.           "killed by <something>, while "
734.        in high scores entry, if any, and in logfile (but not on tombstone) */
735.     gm.multi_reason = Role_if(PM_TOURIST) ? "being toyed with by Fate"
736.                                           : "attempting to cheat Death";
737. 
738.     if (u.utrap && u.utraptype == TT_LAVA)
739.         reset_utrap(FALSE);
740.     disp.botl = TRUE;
741.     u.ugrave_arise = NON_PM;
742.     HUnchanging = 0L;
743.     curs_on_u();
744.     if (!svc.context.mon_moving)
745.         endmultishot(FALSE);
746.     if (u.uswallow) {
747.         /* might drop hero onto a trap that kills her all over again */
748.         expels(u.ustuck, u.ustuck->data, TRUE);
749.     } else if (u.ustuck) {
750.         if (Upolyd && sticks(gy.youmonst.data))
751.             You("release %s.", mon_nam(u.ustuck));
752.         else
753.             pline("%s releases you.", Monnam(u.ustuck));
754.         unstuck(u.ustuck);
755.     }
756. }
757. 
758. /*
759.  * Get valuables from the given list.  Revised code: the list always remains
760.  * intact.
761.  */
762. staticfn void
763. get_valuables(struct obj *list) /* inventory or container contents */
764. {
765.     struct obj *obj;
766.     int i;
767. 
768.     /* find amulets and gems, ignoring all artifacts */
769.     for (obj = list; obj; obj = obj->nobj)
770.         if (Has_contents(obj)) {
771.             get_valuables(obj->cobj);
772.         } else if (obj->oartifact) {
773.             continue;
774.         } else if (obj->oclass == AMULET_CLASS) {
775.             i = obj->otyp - FIRST_AMULET;
776.             if (!ga.amulets[i].count) {
777.                 ga.amulets[i].count = obj->quan;
778.                 ga.amulets[i].typ = obj->otyp;
779.             } else
780.                 ga.amulets[i].count += obj->quan; /* always adds one */
781.         } else if (obj->oclass == GEM_CLASS && obj->otyp <= LAST_GLASS_GEM) {
782.             /* last+1: combine all glass gems into one slot */
783.             i = min(obj->otyp, LAST_REAL_GEM + 1) - FIRST_REAL_GEM;
784.             if (!gg.gems[i].count) {
785.                 gg.gems[i].count = obj->quan;
786.                 gg.gems[i].typ = obj->otyp;
787.             } else
788.                 gg.gems[i].count += obj->quan;
789.         }
790.     return;
791. }
792. 
793. /*
794.  *  Sort collected valuables, most frequent to least.  We could just
795.  *  as easily use qsort, but we don't care about efficiency here.
796.  */
797. staticfn void
798. sort_valuables(
799.     struct valuable_data list[],
800.     int size) /* max value is less than 20 */
801. {
802.     int i, j;
803.     struct valuable_data ltmp;
804. 
805.     /* move greater quantities to the front of the list */
806.     for (i = 1; i < size; i++) {
807.         if (list[i].count == 0)
808.             continue;   /* empty slot */
809.         ltmp = list[i]; /* structure copy */
810.         for (j = i; j > 0; --j) {
811.             if (list[j - 1].count >= ltmp.count)
812.                 break;
813.             list[j] = list[j - 1];
814.         }
815.         list[j] = ltmp;
816.     }
817.     return;
818. }
819. 
820. #if 0
821. /*
822.  * odds_and_ends() was used for 3.6.0 and 3.6.1.
823.  * Schroedinger's Cat is handled differently as of 3.6.2.
824.  */
825. staticfn boolean odds_and_ends(struct obj *, int);
826. 
827. #define CAT_CHECK 2
828. 
829. staticfn boolean
830. odds_and_ends(struct obj *list, int what)
831. {
832.     struct obj *otmp;
833. 
834.     for (otmp = list; otmp; otmp = otmp->nobj) {
835.         switch (what) {
836.         case CAT_CHECK: /* Schroedinger's Cat */
837.             /* Ascending is deterministic */
838.             if (SchroedingersBox(otmp))
839.                 return rn2(2);
840.             break;
841.         }
842.         if (Has_contents(otmp))
843.             return odds_and_ends(otmp->cobj, what);
844.     }
845.     return FALSE;
846. }
847. #endif
848. 
849. /* deal with some objects which may be in an abnormal state at end of game */
850. void
851. done_object_cleanup(void)
852. {
853.     int ox, oy;
854. 
855.     /* might have been killed while using a disposable item, so make sure
856.        it's gone prior to inventory disclosure and creation of bones */
857.     inven_inuse(TRUE);
858.     /*
859.      * Hero can die when throwing an object (by hitting an adjacent
860.      * gas spore, for instance, or being hit by mis-returning Mjollnir),
861.      * or while in transit (from falling down stairs).  If that happens,
862.      * some object(s) might be in limbo rather than on the map or in
863.      * any inventory.  Saving bones with an active light source in limbo
864.      * would trigger an 'object not local' panic.
865.      *
866.      * We used to use dealloc_obj() on gt.thrownobj and gk.kickedobj but
867.      * that keeps them out of bones and could leave uball in a confused
868.      * state (gone but still attached).  Place them on the map but
869.      * bypass flooreffects().  That could lead to minor anomalies in
870.      * bones, like undamaged paper at water or lava locations or piles
871.      * not being knocked down holes, but it seems better to get this
872.      * game over with than risk being tangled up in more and more details.
873.      */
874.     ox = u.ux + u.dx, oy = u.uy + u.dy;
875.     if (!isok(ox, oy) || !accessible(ox, oy))
876.         ox = u.ux, oy = u.uy;
877.     /* put thrown or kicked object on map (for bones); location might
878.        be incorrect (perhaps killed by divine lightning when throwing at
879.        a temple priest?) but this should be better than just vanishing
880.        (fragile stuff should be taken care of before getting here) */
881.     if (gt.thrownobj && gt.thrownobj->where == OBJ_FREE) {
882.         place_object(gt.thrownobj, ox, oy);
883.         stackobj(gt.thrownobj), gt.thrownobj = 0;
884.     }
885.     if (gk.kickedobj && gk.kickedobj->where == OBJ_FREE) {
886.         place_object(gk.kickedobj, ox, oy);
887.         stackobj(gk.kickedobj), gk.kickedobj = 0;
888.     }
889.     /* if Punished hero dies during level change or dies or quits while
890.        swallowed, uball and uchain will be in limbo; put them on floor
891.        so bones will have them and object list cleanup finds them */
892.     if (uchain && uchain->where == OBJ_FREE) {
893.         /* placebc(); */
894.         lift_covet_and_placebc(override_restriction);
895.     }
896.     /* persistent inventory window now obsolete since disclosure uses
897.        a normal popup one; avoids "Bad fruit #n" when saving bones */
898.     if (iflags.perm_invent) {
899.         iflags.perm_invent = FALSE;
900.         perm_invent_toggled(TRUE); /* make interface notice the change */
901.     }
902.     return;
903. }
904. 
905. /* called twice; first to calculate total, then to list relevant items */
906. staticfn void
907. artifact_score(
908.     struct obj *list,
909.     boolean counting, /* true => add up points; false => display them */
910.     winid endwin)
911. {
912.     char pbuf[BUFSZ];
913.     struct obj *otmp;
914.     long value, points;
915. 
916.     for (otmp = list; otmp; otmp = otmp->nobj) {
917.         if (otmp->oartifact || otmp->otyp == BELL_OF_OPENING
918.             || otmp->otyp == SPE_BOOK_OF_THE_DEAD
919.             || otmp->otyp == CANDELABRUM_OF_INVOCATION) {
920.             value = arti_cost(otmp); /* zorkmid value */
921.             points = value * 5 / 2;  /* score value */
922.             if (counting) {
923.                 u.urexp = nowrap_add(u.urexp, points);
924.             } else {
925.                 discover_object(otmp->otyp, TRUE, TRUE, FALSE);
926.                 /* not observe_object; dead characters don't observe */
927.                 otmp->known = otmp->dknown = otmp->bknown = otmp->rknown = 1;
928.                 /* assumes artifacts don't have quan > 1 */
929.                 Sprintf(pbuf, "%s%s (worth %ld %s and %ld points)",
930.                         the_unique_obj(otmp) ? "The " : "",
931.                         otmp->oartifact ? artiname(otmp->oartifact)
932.                                         : OBJ_NAME(objects[otmp->otyp]),
933.                         value, currency(value), points);
934.                 putstr(endwin, 0, pbuf);
935.             }
936.         }
937.         if (Has_contents(otmp))
938.             artifact_score(otmp->cobj, counting, endwin);
939.     }
940. }
941. 
942. /* when dying while running the debug fuzzer, [almost] always keep going;
943.    True: forced survival; False: doomed unless wearing life-save amulet */
944. staticfn boolean
945. fuzzer_savelife(int how)
946. {
947.     /*
948.      * Some debugging code pulled out of done() to unclutter it.
949.      * 'done_seq' is maintained in done().
950.      */
951.     if (!program_state.panicking && how != PANICKED && how != TRICKED) {
952.         savelife(how);
953. 
954.         /* periodically restore characteristics plus lost experience
955.            levels or cure lycanthropy or both; those conditions make the
956.            hero vulnerable to repeat deaths (often by becoming surrounded
957.            while being too encumbered to do anything) */
958.         if (!rn2((gd.done_seq > gh.hero_seq + 2L) ? 2 : 10)) {
959.             struct obj *potion;
960.             int propidx, proptim, remedies = 0;
961. 
962.             /* get rid of temporary potion with obfree() rather than useup()
963.                because it doesn't get entered into inventory */
964.             if (ismnum(u.ulycn) && !rn2(3)) {
965.                 potion = mksobj(POT_WATER, TRUE, FALSE);
966.                 bless(potion);
967.                 (void) peffects(potion);
968.                 obfree(potion, (struct obj *) 0);
969.                 ++remedies;
970.             }
971.             if (!remedies || rn2(3)) {
972.                 potion = mksobj(POT_RESTORE_ABILITY, TRUE, FALSE);
973.                 bless(potion);
974.                 (void) peffects(potion);
975.                 obfree(potion, (struct obj *) 0);
976.                 ++remedies;
977.             }
978.             if (!rn2(3 + 3 * remedies)) {
979.                 /* confer temporary resistances for first 8 properties:
980.                    fire, cold, sleep, disint, shock, poison, acid, stone */
981.                 for (propidx = 1; propidx <= 8; ++propidx) {
982.                     if (!u.uprops[propidx].intrinsic
983.                         && !u.uprops[propidx].extrinsic
984.                         && (proptim = rn2(3)) > 0) /* 0..2 */
985.                         set_itimeout(&u.uprops[propidx].intrinsic,
986.                                      (long) (2 * proptim + 1)); /* 3 or 5 */
987.                 }
988.                 ++remedies;
989.             }
990.             if (!rn2(5 + 5 * remedies)) {
991.                 ; /* might confer temporary Antimagic (magic resistance)
992.                    * or even Invulnerable */
993.             }
994.         }
995.         /* clear stale cause of death info after life-saving */
996.         svk.killer.name[0] = '\0';
997.         svk.killer.format = 0;
998. 
999.         /*
1000.          * Guard against getting stuck in a loop if we die in one of
1001.          * the few ways where life-saving isn't effective (cited case
1002.          * was burning in lava when the level was too full to allow
1003.          * teleporting to safety).  Deal with it by recreating the level
1004.          * if we're in wizmode (always the case for debug_fuzzer unless
1005.          * player has used a debugger to fiddle with 'iflags' bits).
1006.          */
1007.         if (gd.done_seq++ > gh.hero_seq + 100L) {
1008.             if (!wizard)
1009.                 return FALSE; /* can't deal with it */
1010.             cmdq_add_ec(CQ_CANNED, wiz_makemap);
1011.         }
1012. 
1013.         return TRUE;
1014.     }
1015.     return FALSE; /* panic or too many consecutive deaths */
1016. }
1017. 
1018. /* Be careful not to call panic from here! */
1019. void
1020. done(int how)
1021. {
1022.     boolean survive = FALSE;
1023. 
1024.     if (how == TRICKED) {
1025.         if (svk.killer.name[0]) {
1026.             paniclog("trickery", svk.killer.name);
1027.             svk.killer.name[0] = '\0';
1028.         }
1029.         if (wizard) {
1030.             You("are a very tricky wizard, it seems.");
1031.             svk.killer.format = KILLED_BY_AN; /* reset to 0 */
1032.             return;
1033.         }
1034.     }
1035.     if (program_state.panicking
1036. #ifdef HANGUPHANDLING
1037.         || program_state.done_hup
1038. #endif
1039.         || (how == QUIT && done_stopprint)) {
1040.         /* skip status update if panicking or disconnected
1041.            or answer of 'q' to "Really quit?" */
1042.         disp.botl = disp.botlx = disp.time_botl = FALSE;
1043.     } else {
1044.         /* otherwise force full status update */
1045.         disp.botlx = TRUE;
1046.         bot();
1047.     }
1048. 
1049.     /* hero_seq is (moves<<3 + n) where n is number of moves made
1050.        by the hero on the current turn (since the 'moves' variable
1051.        actually counts turns); its details shouldn't matter here;
1052.        used by fuzzer_savelife() and for hangup below */
1053.     if (gd.done_seq < gh.hero_seq)
1054.         gd.done_seq = gh.hero_seq;
1055. 
1056.     if (iflags.debug_fuzzer) {
1057.         if (fuzzer_savelife(how))
1058.             return;
1059.     }
1060. 
1061.     if (how == ASCENDED || (!svk.killer.name[0] && how == GENOCIDED))
1062.         svk.killer.format = NO_KILLER_PREFIX;
1063.     /* Avoid killed by "a" burning or "a" starvation */
1064.     if (!svk.killer.name[0] && (how == STARVING || how == BURNING))
1065.         svk.killer.format = KILLED_BY;
1066.     if (!svk.killer.name[0] || how >= PANICKED)
1067.         Strcpy(svk.killer.name, deaths[how]);
1068. 
1069.     if (how < PANICKED) {
1070.         u.umortality++;
1071.         /* in case caller hasn't already done this */
1072.         if (u.uhp != 0 || (Upolyd && u.mh != 0)) {
1073.             /* force HP to zero in case it is still positive (some
1074.                deaths aren't triggered by loss of hit points), or
1075.                negative (-1 is used as a flag in some circumstances
1076.                which don't apply when actually dying due to HP loss) */
1077.             u.uhp = u.mh = 0;
1078.             disp.botl = TRUE;
1079.         }
1080.     }
1081.     if (Lifesaved && (how <= GENOCIDED)) {
1082.         pline("But wait...");
1083.         /* assumes that only one type of item confers LifeSaved property */
1084.         makeknown(AMULET_OF_LIFE_SAVING);
1085.         Your("medallion %s!", !Blind ? "begins to glow" : "feels warm");
1086.         if (how == CHOKING)
1087.             You("vomit ...");
1088.         You_feel("much better!");
1089.         pline_The("medallion crumbles to dust!");
1090.         if (uamul)
1091.             useup(uamul);
1092. 
1093.         (void) adjattrib(A_CON, -1, TRUE);
1094.         savelife(how);
1095.         if (how == GENOCIDED) {
1096.             pline("Unfortunately you are still genocided...");
1097.         } else {
1098.             char killbuf[BUFSZ];
1099.             formatkiller(killbuf, BUFSZ, how, FALSE);
1100.             livelog_printf(LL_LIFESAVE, "averted death (%s)", killbuf);
1101.             survive = TRUE;
1102.         }
1103.     }
1104.     /* explore and wizard modes offer player the option to keep playing */
1105.     if (!survive && (wizard || discover) && how <= GENOCIDED
1106. #ifdef HANGUPHANDLING
1107.         /* if hangup has occurred, the only possible answer to a paranoid
1108.            query is 'no'; we want 'no' as the default for "Die?" but can't
1109.            accept it more than once if there's no user supplying it */
1110.         && !(program_state.done_hup && gd.done_seq++ == gh.hero_seq)
1111. #endif
1112.         && !paranoid_query(ParanoidDie, "Die?")) {
1113.         pline("OK, so you don't %s.", (how == CHOKING) ? "choke" : "die");
1114.         iflags.last_msg = PLNMSG_OK_DONT_DIE;
1115.         savelife(how);
1116.         survive = TRUE;
1117.     }
1118. 
1119.     if (survive) {
1120.         svk.killer.name[0] = '\0';
1121.         svk.killer.format = KILLED_BY_AN; /* reset to 0 */
1122.         return;
1123.     }
1124.     really_done(how);
1125.     /*NOTREACHED*/
1126. }
1127. 
1128. /* separated from done() in order to specify the __noreturn__ attribute */
1129. staticfn void
1130. really_done(int how)
1131. {
1132.     boolean taken;
1133.     char pbuf[BUFSZ];
1134.     winid endwin = WIN_ERR;
1135.     boolean bones_ok, have_windows = iflags.window_inited;
1136.     struct obj *corpse = (struct obj *) 0;
1137.     time_t endtime;
1138.     long umoney;
1139.     long tmp;
1140. 
1141.     /*
1142.      *  The game is now over...
1143.      */
1144.     program_state.gameover = 1;
1145.     /* in case of a subsequent panic(), there's no point trying to save */
1146.     program_state.something_worth_saving = 0;
1147. #ifdef HANGUPHANDLING
1148.     if (program_state.done_hup)
1149.         done_stopprint++;
1150. #endif
1151.     /* render vision subsystem inoperative */
1152.     iflags.vision_inited = FALSE;
1153. 
1154.     /* maybe use up active invent item(s), place thrown/kicked missile,
1155.        deal with ball and chain possibly being temporarily off the map */
1156.     if (!program_state.panicking)
1157.         done_object_cleanup();
1158.     /* in case we're panicking; normally cleared by done_object_cleanup() */
1159.     iflags.perm_invent = FALSE;
1160. 
1161.     /* remember time of death here instead of having bones, rip, and
1162.        topten figure it out separately and possibly getting different
1163.        time or even day if player is slow responding to --More-- */
1164.     urealtime.finish_time = endtime = getnow();
1165.     urealtime.realtime += timet_delta(endtime, urealtime.start_timing);
1166.     /* collect these for end of game disclosure (not used during play) */
1167.     iflags.at_night = night();
1168.     iflags.at_midnight = midnight();
1169. 
1170.     /* final achievement tracking; only show blind and nudist if some
1171.        tangible progress has been made; always show ascension last */
1172.     if (u.uachieved[0] || !flags.beginner) {
1173.         if (u.uroleplay.blind)
1174.             record_achievement(ACH_BLND); /* blind the whole game */
1175.         if (u.uroleplay.nudist)
1176.             record_achievement(ACH_NUDE); /* never wore armor */
1177.     }
1178.     if (how == ASCENDED)
1179.         record_achievement(ACH_UWIN);
1180. 
1181.     dump_open_log(endtime);
1182.     /* Sometimes you die on the first move.  Life's not fair.
1183.      * On those rare occasions you get hosed immediately, go out
1184.      * smiling... :-)  -3.
1185.      */
1186.     if (svm.moves <= 1 && how < PANICKED && !done_stopprint)
1187.         pline("Do not pass Go.  Do not collect 200 %s.", currency(200L));
1188. 
1189.     if (have_windows)
1190.         wait_synch(); /* flush screen output */
1191. #ifndef NO_SIGNAL
1192.     (void) signal(SIGINT, (SIG_RET_TYPE) done_intr);
1193. #if defined(UNIX) || defined(VMS) || defined(__EMX__)
1194. #ifndef VMSVSI
1195.     (void) signal(SIGQUIT, (SIG_RET_TYPE) done_intr);
1196. #endif
1197.     sethanguphandler(done_hangup);
1198. #endif
1199. #endif /* NO_SIGNAL */
1200. 
1201.     bones_ok = (how < GENOCIDED) && can_make_bones();
1202. 
1203.     if (bones_ok && launch_in_progress())
1204.         force_launch_placement();
1205. 
1206.     /* maintain ugrave_arise even for !bones_ok */
1207.     if (how == PANICKED)
1208.         u.ugrave_arise = (NON_PM - 3); /* no corpse, no grave */
1209.     else if (how == BURNING || how == DISSOLVED) /* corpse burns up too */
1210.         u.ugrave_arise = (NON_PM - 2); /* leave no corpse */
1211.     else if (how == STONING)
1212.         u.ugrave_arise = LEAVESTATUE; /* statue instead of corpse */
1213.     else if (how == TURNED_SLIME
1214.              /* it's possible to turn into slime even though green slimes
1215.                 have been genocided:  genocide could occur after hero is
1216.                 already infected or hero could eat a glob of one created
1217.                 before genocide; don't try to arise as one if they're gone */
1218.              && !(svm.mvitals[PM_GREEN_SLIME].mvflags & G_GENOD))
1219.         u.ugrave_arise = PM_GREEN_SLIME;
1220. 
1221.     if (how == QUIT) {
1222.         svk.killer.format = NO_KILLER_PREFIX;
1223.         if (u.uhp < 1) {
1224.             how = DIED;
1225.             u.umortality++; /* skipped above when how==QUIT */
1226.             Strcpy(svk.killer.name, "quit while already on Charon's boat");
1227.         }
1228.     }
1229.     if (how == ESCAPED || how == PANICKED)
1230.         svk.killer.format = NO_KILLER_PREFIX;
1231. 
1232.     fixup_death(how); /* actually, fixup gm.multi_reason */
1233. 
1234.     if (how != PANICKED) {
1235.         boolean silently = done_stopprint ? TRUE : FALSE;
1236. 
1237.         /* these affect score and/or bones, but avoid them during panic */
1238.         taken = paybill((how == ESCAPED) ? -1 : (how != QUIT), silently);
1239.         paygd(silently);
1240.         clearpriests();
1241.     } else
1242.         taken = FALSE; /* lint; assert( !bones_ok ); */
1243. 
1244.     clearlocks();
1245. 
1246.     if (have_windows)
1247.         display_nhwindow(WIN_MESSAGE, FALSE);
1248. 
1249.     if (how != PANICKED) {
1250.         struct obj *obj, *nextobj;
1251. 
1252.         /*
1253.          * This is needed for both inventory disclosure and dumplog.
1254.          * Both are optional, so do it once here instead of duplicating
1255.          * it in both of those places.
1256.          */
1257.         for (obj = gi.invent; obj; obj = nextobj) {
1258.             nextobj = obj->nobj;
1259.             discover_object(obj->otyp, TRUE, TRUE, FALSE);
1260.             /* observe_object not necessary after discover_object */
1261.             obj->known = obj->bknown = obj->dknown = obj->rknown = 1;
1262.             set_cknown_lknown(obj); /* set flags when applicable */
1263.             /* we resolve Schroedinger's cat now in case of both
1264.                disclosure and dumplog, where the 50:50 chance for
1265.                live cat has to be the same both times */
1266.             if (SchroedingersBox(obj)) {
1267.                 if (!Schroedingers_cat) {
1268.                     /* tell observe_quantum_cat() not to create a cat; if it
1269.                        chooses live cat in this situation, it will leave the
1270.                        SchroedingersBox flag set (for container_contents()) */
1271.                     observe_quantum_cat(obj, FALSE, FALSE);
1272.                     if (SchroedingersBox(obj))
1273.                         Schroedingers_cat = TRUE;
1274.                 } else
1275.                     obj->spe = 0; /* ordinary box with cat corpse in it */
1276.             }
1277.         }
1278. 
1279.         if (strcmp(flags.end_disclose, "none"))
1280.             disclose(how, taken);
1281. 
1282.         /* it would be better to do this after killer.name fixups but
1283.            that comes too late; included in final dumplog but might be
1284.            excluded by active livelog */
1285.         formatkiller(pbuf, (unsigned) sizeof pbuf, how, TRUE);
1286.         if (!*pbuf)
1287.             Strcpy(pbuf, deaths[how]);
1288.         livelog_printf(LL_DUMP, "%s", pbuf);
1289. 
1290.         dump_everything(how, endtime);
1291.     }
1292. 
1293.     /* if pets will contribute to score, populate gm.mydogs list now
1294.        (bones creation isn't a factor, but pline() messaging is; used to
1295.        be done even sooner, but we need it to come after dump_everything()
1296.        so that any accompanying pets are still on the map during dump) */
1297.     if (how == ESCAPED || how == ASCENDED)
1298.         keepdogs(TRUE);
1299. 
1300.     /* finish_paybill should be called after disclosure but before bones */
1301.     if (bones_ok && taken)
1302.         finish_paybill();
1303. 
1304.     /* grave creation should be after disclosure so it doesn't have
1305.        this grave in the current level's features for #overview */
1306.     if (bones_ok && u.ugrave_arise == NON_PM
1307.         && !(svm.mvitals[u.umonnum].mvflags & G_NOCORPSE)) {
1308.         /* Base corpse on race when not poly'd since original u.umonnum
1309.            is based on role, and all role monsters are human. */
1310.         int mnum = !Upolyd ? gu.urace.mnum : u.umonnum,
1311.             was_already_grave = IS_GRAVE(levl[u.ux][u.uy].typ);
1312. 
1313.         corpse = mk_named_object(CORPSE, &mons[mnum], u.ux, u.uy, svp.plname);
1314.         Sprintf(pbuf, "%s, ", svp.plname);
1315.         formatkiller(eos(pbuf), sizeof pbuf - Strlen(pbuf), how, TRUE);
1316.         make_grave(u.ux, u.uy, pbuf);
1317.         if (IS_GRAVE(levl[u.ux][u.uy].typ) && !was_already_grave)
1318.             levl[u.ux][u.uy].emptygrave = 1; /* corpse isn't buried */
1319.     }
1320.     pbuf[0] = '\0'; /* clear grave text; also lint suppression */
1321. 
1322.     /* calculate score, before creating bones [container gold] */
1323.     {
1324.         int deepest = deepest_lev_reached(FALSE);
1325. 
1326.         umoney = money_cnt(gi.invent);
1327.         tmp = u.umoney0;
1328.         umoney += hidden_gold(TRUE); /* accumulate gold from containers */
1329.         tmp = umoney - tmp;          /* net gain */
1330. 
1331.         if (tmp < 0L)
1332.             tmp = 0L;
1333.         if (how < PANICKED)
1334.             tmp -= tmp / 10L;
1335.         tmp += 50L * (long) (deepest - 1);
1336.         if (deepest > 20)
1337.             tmp += 1000L * (long) ((deepest > 30) ? 10 : deepest - 20);
1338.         u.urexp = nowrap_add(u.urexp, tmp);
1339. 
1340.         /* ascension gives a score bonus iff offering to original deity */
1341.         if (how == ASCENDED && u.ualign.type == u.ualignbase[A_ORIGINAL]) {
1342.             /* retaining original alignment: score *= 2;
1343.                converting, then using helm-of-OA to switch back: *= 1.5 */
1344.             tmp = (u.ualignbase[A_CURRENT] == u.ualignbase[A_ORIGINAL])
1345.                       ? u.urexp
1346.                       : (u.urexp / 2L);
1347.             u.urexp = nowrap_add(u.urexp, tmp);
1348.         }
1349.     }
1350. 
1351.     if (ismnum(u.ugrave_arise) && !done_stopprint) {
1352.         /* give this feedback even if bones aren't going to be created,
1353.            so that its presence or absence doesn't tip off the player to
1354.            new bones or their lack; it might be a lie if makemon fails */
1355.         Your("%s as %s...",
1356.              (u.ugrave_arise != PM_GREEN_SLIME)
1357.                  ? "body rises from the dead"
1358.                  : "revenant persists",
1359.              an(pmname(&mons[u.ugrave_arise], Ugender)));
1360.         display_nhwindow(WIN_MESSAGE, FALSE);
1361.     }
1362. 
1363.     if (bones_ok) {
1364.         if (!wizard || paranoid_query(ParanoidBones, "Save bones?"))
1365.             savebones(how, endtime, corpse);
1366.         /* corpse may be invalid pointer now so
1367.             ensure that it isn't used again */
1368.         corpse = (struct obj *) 0;
1369.     }
1370. 
1371.     /* update gold for the rip output, which can't use hidden_gold()
1372.        (containers will be gone by then if bones just got saved...) */
1373.     gd.done_money = umoney;
1374. 
1375.     /* clean up unneeded windows */
1376.     if (have_windows) {
1377.         wait_synch();
1378.         free_pickinv_cache(); /* extra persistent window if perm_invent */
1379.         if (WIN_INVEN != WIN_ERR) {
1380.             destroy_nhwindow(WIN_INVEN),  WIN_INVEN = WIN_ERR;
1381.             /* precaution in case any late update_inventory() calls occur */
1382.             iflags.perm_invent = FALSE;
1383.         }
1384.         display_nhwindow(WIN_MESSAGE, TRUE);
1385.         destroy_nhwindow(WIN_MAP),  WIN_MAP = WIN_ERR;
1386.         if (WIN_STATUS != WIN_ERR)
1387.             destroy_nhwindow(WIN_STATUS),  WIN_STATUS = WIN_ERR;
1388.         destroy_nhwindow(WIN_MESSAGE),  WIN_MESSAGE = WIN_ERR;
1389. 
1390.         if (!done_stopprint || flags.tombstone)
1391.             endwin = create_nhwindow(NHW_TEXT);
1392. 
1393.         if (how < GENOCIDED && flags.tombstone && endwin != WIN_ERR)
1394.             outrip(endwin, how, endtime);
1395.     } else
1396.         done_stopprint = 1; /* just avoid any more output */
1397. 
1398. #ifdef DUMPLOG
1399.     /* 'how' reasons beyond genocide shouldn't show tombstone;
1400.        for normal end of game, genocide doesn't either */
1401.     if (how <= GENOCIDED) {
1402.         dump_redirect(TRUE);
1403.         if (iflags.in_dumplog)
1404.             genl_outrip(0, how, endtime);
1405.         dump_redirect(FALSE);
1406.     }
1407. #endif
1408.     if (u.uhave.amulet) {
1409.         Strcat(svk.killer.name, " (with the Amulet)");
1410.     } else if (how == ESCAPED) {
1411.         if (Is_astralevel(&u.uz)) /* offered Amulet to wrong deity */
1412.             Strcat(svk.killer.name, " (in celestial disgrace)");
1413.         else if (carrying(FAKE_AMULET_OF_YENDOR))
1414.             Strcat(svk.killer.name, " (with a fake Amulet)");
1415.         /* don't bother counting to see whether it should be plural */
1416.     }
1417. 
1418.     Sprintf(pbuf, "%s %s the %s...", Goodbye(), svp.plname,
1419.             (how != ASCENDED)
1420.                 ? (const char *) ((flags.female && gu.urole.name.f)
1421.                     ? gu.urole.name.f
1422.                     : gu.urole.name.m)
1423.                 : (const char *) (flags.female ? "Demigoddess" : "Demigod"));
1424.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1425.     dump_forward_putstr(endwin, 0, "", done_stopprint);
1426. 
1427.     if (how == ESCAPED || how == ASCENDED) {
1428.         struct monst *mtmp;
1429.         struct obj *otmp;
1430.         struct val_list *val;
1431.         int i;
1432. 
1433.         for (val = gv.valuables; val->list; val++)
1434.             for (i = 0; i < val->size; i++) {
1435.                 val->list[i].count = 0L;
1436.             }
1437.         get_valuables(gi.invent);
1438. 
1439.         /* add points for collected valuables */
1440.         for (val = gv.valuables; val->list; val++)
1441.             for (i = 0; i < val->size; i++)
1442.                 if (val->list[i].count != 0L) {
1443.                     tmp = val->list[i].count
1444.                           * (long) objects[val->list[i].typ].oc_cost;
1445.                     u.urexp = nowrap_add(u.urexp, tmp);
1446.                 }
1447. 
1448.         /* count the points for artifacts */
1449.         artifact_score(gi.invent, TRUE, endwin);
1450. 
1451.         gv.viz_array[0][0] |= IN_SIGHT; /* need visibility for naming */
1452.         mtmp = gm.mydogs;
1453.         Strcpy(pbuf, "You");
1454.         if (mtmp || Schroedingers_cat) {
1455.             while (mtmp) {
1456.                 Sprintf(eos(pbuf), " and %s", mon_nam(mtmp));
1457.                 if (mtmp->mtame)
1458.                     u.urexp = nowrap_add(u.urexp, mtmp->mhp);
1459.                 mtmp = mtmp->nmon;
1460.             }
1461.             /* [it might be more robust to create a housecat and add it to
1462.                gm.mydogs; it doesn't have to be placed on the map for that] */
1463.             if (Schroedingers_cat) {
1464.                 int mhp, m_lev = adj_lev(&mons[PM_HOUSECAT]);
1465. 
1466.                 mhp = d(m_lev, 8);
1467.                 u.urexp = nowrap_add(u.urexp, mhp);
1468.                 Strcat(eos(pbuf), " and Schroedinger's cat");
1469.             }
1470.             dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1471.             pbuf[0] = '\0';
1472.         } else {
1473.             Strcat(pbuf, " ");
1474.         }
1475.         Sprintf(eos(pbuf), "%s with %ld point%s,",
1476.                 (how == ASCENDED) ? "went to your reward"
1477.                                   : "escaped from the dungeon",
1478.                 u.urexp, plur(u.urexp));
1479.         dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1480. 
1481.         if (!done_stopprint)
1482.             artifact_score(gi.invent, FALSE, endwin); /* list artifacts */
1483. #ifdef DUMPLOG
1484.         dump_redirect(TRUE);
1485.         if (iflags.in_dumplog)
1486.             artifact_score(gi.invent, FALSE, 0);
1487.         dump_redirect(FALSE);
1488. #endif
1489. 
1490.         /* list valuables here */
1491.         for (val = gv.valuables; val->list; val++) {
1492.             sort_valuables(val->list, val->size);
1493.             for (i = 0; i < val->size && !done_stopprint; i++) {
1494.                 int typ = val->list[i].typ;
1495.                 long count = val->list[i].count;
1496. 
1497.                 if (count == 0L)
1498.                     continue;
1499.                 if (objects[typ].oc_class != GEM_CLASS
1500.                     || typ <= LAST_REAL_GEM) {
1501.                     otmp = mksobj(typ, FALSE, FALSE);
1502.                     discover_object(otmp->otyp, TRUE, TRUE, FALSE);
1503.                     otmp->dknown = 1; /* seen it (blindness fix) */
1504.                     /* observe_object not necessary after discover_object */
1505.                     otmp->known = 1;  /* for fake amulets */
1506.                     if (has_oname(otmp))
1507.                         free_oname(otmp);
1508.                     otmp->quan = count;
1509.                     Sprintf(pbuf, "%8ld %s (worth %ld %s),", count,
1510.                             xname(otmp), count * (long) objects[typ].oc_cost,
1511.                             currency(2L));
1512.                     obfree(otmp, (struct obj *) 0);
1513.                 } else {
1514.                     Sprintf(pbuf, "%8ld worthless piece%s of colored glass,",
1515.                             count, plur(count));
1516.                 }
1517.                 dump_forward_putstr(endwin, 0, pbuf, 0);
1518.             }
1519.         }
1520. 
1521.     } else {
1522.         /* did not escape or ascend */
1523.         if (u.uz.dnum == 0 && u.uz.dlevel <= 0) {
1524.             /* level teleported out of the dungeon; `how' is DIED,
1525.                due to falling or to "arriving at heaven prematurely" */
1526.             Sprintf(pbuf, "You %s beyond the confines of the dungeon",
1527.                     (u.uz.dlevel < 0) ? "passed away" : ends[how]);
1528.         } else {
1529.             /* more conventional demise */
1530.             const char *where = svd.dungeons[u.uz.dnum].dname;
1531. 
1532.             if (Is_astralevel(&u.uz))
1533.                 where = "The Astral Plane";
1534.             Sprintf(pbuf, "You %s in %s", ends[how], where);
1535.             if (!In_endgame(&u.uz) && !single_level_branch(&u.uz))
1536.                 Sprintf(eos(pbuf), " on dungeon level %d",
1537.                         In_quest(&u.uz) ? dunlev(&u.uz) : depth(&u.uz));
1538.         }
1539. 
1540.         Sprintf(eos(pbuf), " with %ld point%s,", u.urexp, plur(u.urexp));
1541.         dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1542.     }
1543. 
1544.     Sprintf(pbuf, "and %ld piece%s of gold, after %ld move%s.", umoney,
1545.             plur(umoney), svm.moves, plur(svm.moves));
1546.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1547.     Sprintf(pbuf,
1548.             "You were level %d with a maximum of %d hit point%s when you %s.",
1549.             u.ulevel, u.uhpmax, plur(u.uhpmax), ends[how]);
1550.     dump_forward_putstr(endwin, 0, pbuf, done_stopprint);
1551.     dump_forward_putstr(endwin, 0, "", done_stopprint);
1552.     if (!done_stopprint)
1553.         display_nhwindow(endwin, TRUE);
1554.     if (endwin != WIN_ERR)
1555.         destroy_nhwindow(endwin);
1556. 
1557.     dump_close_log();
1558. 
1559.     /* shut down soundlib */
1560.     if (soundprocs.sound_exit_nhsound)
1561.         (*soundprocs.sound_exit_nhsound)("really_done");
1562. 
1563.     /*
1564.      * "So when I die, the first thing I will see in Heaven is a score list?"
1565.      *
1566.      * topten() updates 'logfile' and 'xlogfile', when they're enabled.
1567.      * Then the current game's score is shown in its relative position
1568.      * within high scores, and 'record' is updated if that makes the cut.
1569.      *
1570.      * FIXME!
1571.      *  If writing topten with raw_print(), which will usually be sent to
1572.      *  stdout, we call exit_nhwindows() first in case it erases the screen.
1573.      *  But when writing topten to a window, we call exit_nhwindows()
1574.      *  after topten() because that needs the windowing system to still
1575.      *  be up.  This sequencing is absurd; we need something like
1576.      *  raw_prompt("--More--") (or "Press <return> to continue.") that
1577.      *  topten() can call for !toptenwin before returning here.
1578.      */
1579.     if (have_windows && !iflags.toptenwin)
1580.         exit_nhwindows((char *) 0), have_windows = FALSE;
1581.     topten(how, endtime);
1582.     if (have_windows)
1583.         exit_nhwindows((char *) 0);
1584. 
1585.     if (done_stopprint) {
1586.         raw_print("");
1587.         raw_print("");
1588.     }
1589.     nh_terminate(EXIT_SUCCESS);
1590. }
1591. 
1592. /* used for disclosure and for the ':' choice when looting a container */
1593. void
1594. container_contents(
1595.     struct obj *list,
1596.     boolean identified,
1597.     boolean all_containers,
1598.     boolean reportempty)
1599. {
1600.     struct obj *box, *obj;
1601.     char buf[BUFSZ];
1602.     boolean cat, dumping = iflags.in_dumplog;
1603. 
1604.     for (box = list; box; box = box->nobj) {
1605.         if (Is_container(box) || box->otyp == STATUE) {
1606.             if (!box->cknown || (identified && !box->lknown)) {
1607.                 box->cknown = 1; /* we're looking at the contents now */
1608.                 if (identified)
1609.                     box->lknown = 1;
1610.                 update_inventory();
1611.             }
1612.             if (box->otyp == BAG_OF_TRICKS) {
1613.                 continue; /* wrong type of container */
1614.             } else if (box->cobj) {
1615.                 winid tmpwin = create_nhwindow(NHW_MENU);
1616.                 Loot *sortedcobj, *srtc;
1617.                 unsigned sortflags;
1618. 
1619.                 /* at this stage, the SchroedingerBox() flag is only set
1620.                    if the cat inside the box is alive; the box actually
1621.                    contains a cat corpse that we'll pretend is not there;
1622.                    for dead cat, the flag will be clear and there'll be
1623.                    a cat corpse inside the box; either way, inventory
1624.                    reports the box as containing "1 item" */
1625.                 cat = SchroedingersBox(box);
1626. 
1627.                 Sprintf(buf, "Contents of %s:", the(xname(box)));
1628.                 putstr(tmpwin, 0, buf);
1629.                 if (!dumping)
1630.                     putstr(tmpwin, 0, "");
1631.                 buf[0] = buf[1] = ' '; /* two leading spaces */
1632.                 if (box->cobj && !cat) {
1633.                     sortflags = (((flags.sortloot == 'l'
1634.                                    || flags.sortloot == 'f')
1635.                                      ? SORTLOOT_LOOT : 0)
1636.                                  | (flags.sortpack ? SORTLOOT_PACK : 0));
1637.                     sortedcobj = sortloot(&box->cobj, sortflags, FALSE,
1638.                                           (boolean (*)(OBJ_P)) 0);
1639.                     for (srtc = sortedcobj; (obj = srtc->obj) != 0; ++srtc) {
1640.                         if (identified) {
1641.                             discover_object(obj->otyp, TRUE, TRUE, FALSE);
1642.                             obj->dknown = 1; /* observe_object unnecessary */
1643.                             obj->known = obj->bknown = obj->rknown = 1;
1644.                             if (Is_container(obj) || obj->otyp == STATUE)
1645.                                 obj->cknown = obj->lknown = 1;
1646.                         }
1647.                         Strcpy(&buf[2], doname_with_price(obj));
1648.                         putstr(tmpwin, 0, buf);
1649.                     }
1650.                     unsortloot(&sortedcobj);
1651.                 } else if (cat) {
1652.                     Strcpy(&buf[2], "Schroedinger's cat!");
1653.                     putstr(tmpwin, 0, buf);
1654.                 }
1655.                 if (dumping)
1656.                     putstr(0, 0, "");
1657.                 display_nhwindow(tmpwin, TRUE);
1658.                 destroy_nhwindow(tmpwin);
1659.                 if (all_containers)
1660.                     container_contents(box->cobj, identified, TRUE,
1661.                                        reportempty);
1662.             } else if (reportempty) {
1663.                 pline("%s is empty.", upstart(thesimpleoname(box)));
1664.                 display_nhwindow(WIN_MESSAGE, FALSE);
1665.             }
1666.         }
1667.         if (!all_containers)
1668.             break;
1669.     }
1670. }
1671. 
1672. /* should be called with either EXIT_SUCCESS or EXIT_FAILURE */
1673. ATTRNORETURN void
1674. nh_terminate(int status)
1675. {
1676.     program_state.in_moveloop = 0; /* won't be returning to normal play */
1677. 
1678.     l_nhcore_call(NHCORE_GAME_EXIT);
1679. #ifdef MACOS9
1680.     getreturn("to exit");
1681. #endif
1682.     /* don't bother to try to release memory if we're in panic mode, to
1683.        avoid trouble in case that happens to be due to memory problems */
1684.     if (!program_state.panicking) {
1685.         freedynamicdata();
1686.         dlb_cleanup();
1687.         l_nhcore_done();
1688.     }
1689. 
1690. #ifdef VMS
1691.     /*
1692.      *  This is liable to draw a warning if compiled with gcc, but it's
1693.      *  more important to flag panic() -> really_done() -> nh_terminate()
1694.      *  as __noreturn__ then to avoid the warning.
1695.      */
1696.     /* don't call exit() if already executing within an exit handler;
1697.        that would cancel any other pending user-mode handlers */
1698.     if (program_state.exiting)
1699.         return;
1700. #endif
1701.     program_state.exiting = 1;
1702.     nethack_exit(status);
1703. }
1704. 
1705. /* set a delayed killer, ensure non-delayed killer is cleared out */
1706. void
1707. delayed_killer(int id, int format, const char *killername)
1708. {
1709.     struct kinfo *k = find_delayed_killer(id);
1710. 
1711.     if (!k) {
1712.         /* no match, add a new delayed killer to the list */
1713.         k = (struct kinfo *) alloc(sizeof (struct kinfo));
1714.         (void) memset((genericptr_t) k, 0, sizeof (struct kinfo));
1715.         k->id = id;
1716.         k->next = svk.killer.next;
1717.         svk.killer.next = k;
1718.     }
1719. 
1720.     k->format = format;
1721.     Strcpy(k->name, killername ? killername : "");
1722.     svk.killer.name[0] = 0;
1723. }
1724. 
1725. struct kinfo *
1726. find_delayed_killer(int id)
1727. {
1728.     struct kinfo *k;
1729. 
1730.     for (k = svk.killer.next; k != (struct kinfo *) 0; k = k->next) {
1731.         if (k->id == id)
1732.             break;
1733.     }
1734.     return k;
1735. }
1736. 
1737. void
1738. dealloc_killer(struct kinfo *kptr)
1739. {
1740.     struct kinfo *prev = &svk.killer, *k;
1741. 
1742.     if (kptr == (struct kinfo *) 0)
1743.         return;
1744.     for (k = svk.killer.next; k != (struct kinfo *) 0; k = k->next) {
1745.         if (k == kptr)
1746.             break;
1747.         prev = k;
1748.     }
1749. 
1750.     if (k == (struct kinfo *) 0) {
1751.         impossible("dealloc_killer (#%d) not on list", kptr->id);
1752.     } else {
1753.         prev->next = k->next;
1754.         free((genericptr_t) k);
1755.         debugpline1("freed delayed killer #%d", kptr->id);
1756.     }
1757. }
1758. 
1759. void
1760. save_killers(NHFILE *nhfp)
1761. {
1762.     struct kinfo *kptr;
1763. 
1764.     if (update_file(nhfp)) {
1765.         for (kptr = &svk.killer; kptr; kptr = kptr->next) {
1766.             Sfo_kinfo(nhfp, kptr, "kinfo");
1767.         }
1768.     }
1769.     if (release_data(nhfp)) {
1770.         while (svk.killer.next) {
1771.             kptr = svk.killer.next->next;
1772.             free((genericptr_t) svk.killer.next);
1773.             svk.killer.next = kptr;
1774.         }
1775.     }
1776. }
1777. #endif /* !SFCTOOL */
1778. 
1779. void
1780. restore_killers(NHFILE *nhfp)
1781. {
1782.     struct kinfo *kptr;
1783. 
1784.     for (kptr = &svk.killer; kptr != (struct kinfo *) 0; kptr = kptr->next) {
1785.         Sfi_kinfo(nhfp, kptr, "kinfo");
1786.         if (kptr->next) {
1787.             kptr->next = (struct kinfo *) alloc(sizeof (struct kinfo));
1788.         }
1789.     }
1790. }
1791. 
1792. staticfn int
1793. wordcount(char *p)
1794. {
1795.     int words = 0;
1796. 
1797.     while (*p) {
1798.         while (*p && isspace((uchar) *p))
1799.             p++;
1800.         if (*p)
1801.             words++;
1802.         while (*p && !isspace((uchar) *p))
1803.             p++;
1804.     }
1805.     return words;
1806. }
1807. 
1808. staticfn void
1809. bel_copy1(char **inp, char *out)
1810. {
1811.     char *in = *inp;
1812. 
1813.     out += strlen(out); /* eos() */
1814.     while (*in && isspace((uchar) *in))
1815.         in++;
1816.     while (*in && !isspace((uchar) *in))
1817.         *out++ = *in++;
1818.     *out = '\0';
1819.     *inp = in;
1820. }
1821. 
1822. char *
1823. build_english_list(char *in)
1824. {
1825.     char *out, *p = in;
1826.     int len = (int) strlen(p), words = wordcount(p);
1827. 
1828.     /* +3: " or " - " "; +(words - 1): (N-1)*(", " - " ") */
1829.     if (words > 1)
1830.         len += 3 + (words - 1);
1831.     out = (char *) alloc(len + 1);
1832.     *out = '\0'; /* bel_copy1() appends */
1833. 
1834.     switch (words) {
1835.     case 0:
1836.         impossible("no words in list");
1837.         break;
1838.     case 1:
1839.         /* "single" */
1840.         bel_copy1(&p, out);
1841.         break;
1842.     default:
1843.         if (words == 2) {
1844.             /* "first or second" */
1845.             bel_copy1(&p, out);
1846.             Strcat(out, " ");
1847.         } else {
1848.             /* "first, second, or third */
1849.             do {
1850.                 bel_copy1(&p, out);
1851.                 Strcat(out, ", ");
1852.             } while (--words > 1);
1853.         }
1854.         Strcat(out, "or ");
1855.         bel_copy1(&p, out);
1856.         break;
1857.     }
1858.     return out;
1859. }
1860. 
1861. /* What do we try to in what order?  Tradeoffs:
1862.  * libc: +no external programs required
1863.  *        -requires newish libc/glibc
1864.  *        -requires -rdynamic
1865.  * gdb:   +gives more detailed information
1866.  *        +works on more OS versions
1867.  *        -requires -g, which may preclude -O on some compilers
1868.  *
1869.  * And the UI: if sysopt.crashreporturl, and defined(CRASHREPORT)
1870.  * we gather the stacktrace (etc) and launch a browser to submit a bug report
1871.  * otherwise we just use stdout.  Requires libc for now.
1872.  */
1873. # ifdef SYSCF
1874. # define SYSOPT_PANICTRACE_GDB sysopt.panictrace_gdb
1875. #  ifdef PANICTRACE_LIBC
1876. #  define SYSOPT_PANICTRACE_LIBC sysopt.panictrace_libc
1877. #  else
1878. #  define SYSOPT_PANICTRACE_LIBC 0
1879. #  endif
1880. # else
1881. # define SYSOPT_PANICTRACE_GDB (nh_getenv("NETHACK_USE_GDB") == 0 ? 0 : 2)
1882. #  ifdef PANICTRACE_LIBC
1883. #  define SYSOPT_PANICTRACE_LIBC 1
1884. #  else
1885. #  define SYSOPT_PANICTRACE_LIBC 0
1886. #  endif
1887. # endif
1888. 
1889. # ifdef CRASHREPORT
1890. #define USED_FOR_CRASHREPORT
1891. # else
1892. #define USED_FOR_CRASHREPORT UNUSED
1893. # endif
1894. 
1895. void
1896. NH_abort(char *why USED_FOR_CRASHREPORT)
1897. {
1898. #ifdef PANICTRACE
1899.     int gdb_prio = SYSOPT_PANICTRACE_GDB;
1900.     int libc_prio = SYSOPT_PANICTRACE_LIBC;
1901. #endif
1902.     static volatile boolean aborting = FALSE;
1903. 
1904.     /* don't execute this code recursively if a second abort is requested
1905.        while this routine or the code it calls is executing */
1906.     if (aborting)
1907.         return;
1908.     aborting = TRUE;
1909. 
1910. #ifdef PANICTRACE
1911. #ifdef CRASHREPORT
1912.     if(!submit_web_report(1, "Panic", why))
1913. #endif
1914.     {
1915. #ifndef VMS
1916.         if (gdb_prio == libc_prio && gdb_prio > 0)
1917.             gdb_prio++;
1918. 
1919.         if (gdb_prio > libc_prio) {
1920.             (void) (NH_panictrace_gdb()
1921.                     || (libc_prio && NH_panictrace_libc()));
1922.         } else {
1923.             (void) (NH_panictrace_libc()
1924.                     || (gdb_prio && NH_panictrace_gdb()));
1925.         }
1926. 
1927. #else /* VMS */
1928.         /* overload otherwise unused priority for debug mode: 1 = show
1929.            traceback and exit; 2 = show traceback and stay in debugger */
1930.         /* if (wizard && gdb_prio == 1) gdb_prio = 2; */
1931.         vms_traceback(gdb_prio);
1932.         nhUse(libc_prio);
1933. 
1934. #endif /* ?VMS */
1935.     }
1936. #ifndef NO_SIGNAL
1937.     panictrace_setsignals(FALSE);
1938. #endif
1939. #endif /* PANICTRACE */
1940. #if defined(WIN32)
1941.     win32_abort();
1942. #else
1943.     abort();
1944. #endif
1945. }
1946. 
1947. #undef USED_FOR_CRASHREPORT
1948. /*end.c*/