Source:NetHack 3.6.2/src/files.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to files.c from the source code of NetHack 3.6.2. To link to a particular line, write [[Source:NetHack 3.6.2/src/files.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	files.c	$NHDT-Date: 1546144856 2018/12/30 04:40:56 $  $NHDT-Branch: NetHack-3.6.2-beta01 $:$NHDT-Revision: 1.249 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #define NEED_VARARGS
7. 
8. #include "hack.h"
9. #include "dlb.h"
10. 
11. #ifdef TTY_GRAPHICS
12. #include "wintty.h" /* more() */
13. #endif
14. 
15. #if (!defined(MAC) && !defined(O_WRONLY) && !defined(AZTEC_C)) \
16.     || defined(USE_FCNTL)
17. #include <fcntl.h>
18. #endif
19. 
20. #include <errno.h>
21. #ifdef _MSC_VER /* MSC 6.0 defines errno quite differently */
22. #if (_MSC_VER >= 600)
23. #define SKIP_ERRNO
24. #endif
25. #else
26. #ifdef NHSTDC
27. #define SKIP_ERRNO
28. #endif
29. #endif
30. #ifndef SKIP_ERRNO
31. #ifdef _DCC
32. const
33. #endif
34.     extern int errno;
35. #endif
36. 
37. #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */
38. #include "zlib.h"
39. #ifndef COMPRESS_EXTENSION
40. #define COMPRESS_EXTENSION ".gz"
41. #endif
42. #endif
43. 
44. #if defined(UNIX) && defined(QT_GRAPHICS)
45. #include <sys/types.h>
46. #include <dirent.h>
47. #include <stdlib.h>
48. #endif
49. 
50. #if defined(UNIX) || defined(VMS) || !defined(NO_SIGNAL)
51. #include <signal.h>
52. #endif
53. 
54. #if defined(MSDOS) || defined(OS2) || defined(TOS) || defined(WIN32)
55. #ifndef GNUDOS
56. #include <sys\stat.h>
57. #else
58. #include <sys/stat.h>
59. #endif
60. #endif
61. #ifndef O_BINARY /* used for micros, no-op for others */
62. #define O_BINARY 0
63. #endif
64. 
65. #ifdef PREFIXES_IN_USE
66. #define FQN_NUMBUF 4
67. static char fqn_filename_buffer[FQN_NUMBUF][FQN_MAX_FILENAME];
68. #endif
69. 
70. #if !defined(MFLOPPY) && !defined(VMS) && !defined(WIN32)
71. char bones[] = "bonesnn.xxx";
72. char lock[PL_NSIZ + 14] = "1lock"; /* long enough for uid+name+.99 */
73. #else
74. #if defined(MFLOPPY)
75. char bones[FILENAME]; /* pathname of bones files */
76. char lock[FILENAME];  /* pathname of level files */
77. #endif
78. #if defined(VMS)
79. char bones[] = "bonesnn.xxx;1";
80. char lock[PL_NSIZ + 17] = "1lock"; /* long enough for _uid+name+.99;1 */
81. #endif
82. #if defined(WIN32)
83. char bones[] = "bonesnn.xxx";
84. char lock[PL_NSIZ + 25]; /* long enough for username+-+name+.99 */
85. #endif
86. #endif
87. 
88. #if defined(UNIX) || defined(__BEOS__)
89. #define SAVESIZE (PL_NSIZ + 13) /* save/99999player.e */
90. #else
91. #ifdef VMS
92. #define SAVESIZE (PL_NSIZ + 22) /* [.save]<uid>player.e;1 */
93. #else
94. #if defined(WIN32)
95. #define SAVESIZE (PL_NSIZ + 40) /* username-player.NetHack-saved-game */
96. #else
97. #define SAVESIZE FILENAME /* from macconf.h or pcconf.h */
98. #endif
99. #endif
100. #endif
101. 
102. #if !defined(SAVE_EXTENSION)
103. #ifdef MICRO
104. #define SAVE_EXTENSION ".sav"
105. #endif
106. #ifdef WIN32
107. #define SAVE_EXTENSION ".NetHack-saved-game"
108. #endif
109. #endif
110. 
111. char SAVEF[SAVESIZE]; /* holds relative path of save file from playground */
112. #ifdef MICRO
113. char SAVEP[SAVESIZE]; /* holds path of directory for save file */
114. #endif
115. 
116. #ifdef HOLD_LOCKFILE_OPEN
117. struct level_ftrack {
118.     int init;
119.     int fd;    /* file descriptor for level file     */
120.     int oflag; /* open flags                         */
121.     boolean nethack_thinks_it_is_open; /* Does NetHack think it's open? */
122. } lftrack;
123. #if defined(WIN32)
124. #include <share.h>
125. #endif
126. #endif /*HOLD_LOCKFILE_OPEN*/
127. 
128. #define WIZKIT_MAX 128
129. static char wizkit[WIZKIT_MAX];
130. STATIC_DCL FILE *NDECL(fopen_wizkit_file);
131. STATIC_DCL void FDECL(wizkit_addinv, (struct obj *));
132. 
133. #ifdef AMIGA
134. extern char PATH[]; /* see sys/amiga/amidos.c */
135. extern char bbs_id[];
136. static int lockptr;
137. #ifdef __SASC_60
138. #include <proto/dos.h>
139. #endif
140. 
141. #include <libraries/dos.h>
142. extern void FDECL(amii_set_text_font, (char *, int));
143. #endif
144. 
145. #if defined(WIN32) || defined(MSDOS)
146. static int lockptr;
147. #ifdef MSDOS
148. #define Delay(a) msleep(a)
149. #endif
150. #define Close close
151. #ifndef WIN_CE
152. #define DeleteFile unlink
153. #endif
154. #endif
155. 
156. #ifdef MAC
157. #undef unlink
158. #define unlink macunlink
159. #endif
160. 
161. #if (defined(macintosh) && (defined(__SC__) || defined(__MRC__))) \
162.     || defined(__MWERKS__)
163. #define PRAGMA_UNUSED
164. #endif
165. 
166. #ifdef USER_SOUNDS
167. extern char *sounddir;
168. #endif
169. 
170. extern int n_dgns; /* from dungeon.c */
171. 
172. #if defined(UNIX) && defined(QT_GRAPHICS)
173. #define SELECTSAVED
174. #endif
175. 
176. #ifdef SELECTSAVED
177. STATIC_PTR int FDECL(CFDECLSPEC strcmp_wrap, (const void *, const void *));
178. #endif
179. STATIC_DCL char *FDECL(set_bonesfile_name, (char *, d_level *));
180. STATIC_DCL char *NDECL(set_bonestemp_name);
181. #ifdef COMPRESS
182. STATIC_DCL void FDECL(redirect, (const char *, const char *, FILE *,
183.                                  BOOLEAN_P));
184. #endif
185. #if defined(COMPRESS) || defined(ZLIB_COMP)
186. STATIC_DCL void FDECL(docompress_file, (const char *, BOOLEAN_P));
187. #endif
188. #if defined(ZLIB_COMP)
189. STATIC_DCL boolean FDECL(make_compressed_name, (const char *, char *));
190. #endif
191. #ifndef USE_FCNTL
192. STATIC_DCL char *FDECL(make_lockname, (const char *, char *));
193. #endif
194. STATIC_DCL void FDECL(set_configfile_name, (const char *));
195. STATIC_DCL FILE *FDECL(fopen_config_file, (const char *, int));
196. STATIC_DCL int FDECL(get_uchars, (char *, uchar *, BOOLEAN_P,
197.                                   int, const char *));
198. boolean FDECL(proc_wizkit_line, (char *));
199. boolean FDECL(parse_config_line, (char *));
200. STATIC_DCL boolean FDECL(parse_conf_file, (FILE *, boolean (*proc)(char *)));
201. STATIC_DCL FILE *NDECL(fopen_sym_file);
202. boolean FDECL(proc_symset_line, (char *));
203. STATIC_DCL void FDECL(set_symhandling, (char *, int));
204. #ifdef NOCWD_ASSUMPTIONS
205. STATIC_DCL void FDECL(adjust_prefix, (char *, int));
206. #endif
207. STATIC_DCL boolean FDECL(config_error_nextline, (const char *));
208. STATIC_DCL void NDECL(free_config_sections);
209. STATIC_DCL char *FDECL(choose_random_part, (char *, CHAR_P));
210. STATIC_DCL boolean FDECL(is_config_section, (const char *));
211. STATIC_DCL boolean FDECL(handle_config_section, (char *));
212. #ifdef SELF_RECOVER
213. STATIC_DCL boolean FDECL(copy_bytes, (int, int));
214. #endif
215. #ifdef HOLD_LOCKFILE_OPEN
216. STATIC_DCL int FDECL(open_levelfile_exclusively, (const char *, int, int));
217. #endif
218. 
219. 
220. static char *config_section_chosen = (char *) 0;
221. static char *config_section_current = (char *) 0;
222. 
223. /*
224.  * fname_encode()
225.  *
226.  *   Args:
227.  *      legal       zero-terminated list of acceptable file name characters
228.  *      quotechar   lead-in character used to quote illegal characters as
229.  *                  hex digits
230.  *      s           string to encode
231.  *      callerbuf   buffer to house result
232.  *      bufsz       size of callerbuf
233.  *
234.  *   Notes:
235.  *      The hex digits 0-9 and A-F are always part of the legal set due to
236.  *      their use in the encoding scheme, even if not explicitly included in
237.  *      'legal'.
238.  *
239.  *   Sample:
240.  *      The following call:
241.  *  (void)fname_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
242.  *                     '%', "This is a % test!", buf, 512);
243.  *      results in this encoding:
244.  *          "This%20is%20a%20%25%20test%21"
245.  */
246. char *
247. fname_encode(legal, quotechar, s, callerbuf, bufsz)
248. const char *legal;
249. char quotechar;
250. char *s, *callerbuf;
251. int bufsz;
252. {
253.     char *sp, *op;
254.     int cnt = 0;
255.     static char hexdigits[] = "0123456789ABCDEF";
256. 
257.     sp = s;
258.     op = callerbuf;
259.     *op = '\0';
260. 
261.     while (*sp) {
262.         /* Do we have room for one more character or encoding? */
263.         if ((bufsz - cnt) <= 4)
264.             return callerbuf;
265. 
266.         if (*sp == quotechar) {
267.             (void) sprintf(op, "%c%02X", quotechar, *sp);
268.             op += 3;
269.             cnt += 3;
270.         } else if ((index(legal, *sp) != 0) || (index(hexdigits, *sp) != 0)) {
271.             *op++ = *sp;
272.             *op = '\0';
273.             cnt++;
274.         } else {
275.             (void) sprintf(op, "%c%02X", quotechar, *sp);
276.             op += 3;
277.             cnt += 3;
278.         }
279.         sp++;
280.     }
281.     return callerbuf;
282. }
283. 
284. /*
285.  * fname_decode()
286.  *
287.  *   Args:
288.  *      quotechar   lead-in character used to quote illegal characters as
289.  *                  hex digits
290.  *      s           string to decode
291.  *      callerbuf   buffer to house result
292.  *      bufsz       size of callerbuf
293.  */
294. char *
295. fname_decode(quotechar, s, callerbuf, bufsz)
296. char quotechar;
297. char *s, *callerbuf;
298. int bufsz;
299. {
300.     char *sp, *op;
301.     int k, calc, cnt = 0;
302.     static char hexdigits[] = "0123456789ABCDEF";
303. 
304.     sp = s;
305.     op = callerbuf;
306.     *op = '\0';
307.     calc = 0;
308. 
309.     while (*sp) {
310.         /* Do we have room for one more character? */
311.         if ((bufsz - cnt) <= 2)
312.             return callerbuf;
313.         if (*sp == quotechar) {
314.             sp++;
315.             for (k = 0; k < 16; ++k)
316.                 if (*sp == hexdigits[k])
317.                     break;
318.             if (k >= 16)
319.                 return callerbuf; /* impossible, so bail */
320.             calc = k << 4;
321.             sp++;
322.             for (k = 0; k < 16; ++k)
323.                 if (*sp == hexdigits[k])
324.                     break;
325.             if (k >= 16)
326.                 return callerbuf; /* impossible, so bail */
327.             calc += k;
328.             sp++;
329.             *op++ = calc;
330.             *op = '\0';
331.         } else {
332.             *op++ = *sp++;
333.             *op = '\0';
334.         }
335.         cnt++;
336.     }
337.     return callerbuf;
338. }
339. 
340. #ifdef PREFIXES_IN_USE
341. #define UNUSED_if_not_PREFIXES_IN_USE /*empty*/
342. #else
343. #define UNUSED_if_not_PREFIXES_IN_USE UNUSED
344. #endif
345. 
346. /*ARGSUSED*/
347. const char *
348. fqname(basenam, whichprefix, buffnum)
349. const char *basenam;
350. int whichprefix UNUSED_if_not_PREFIXES_IN_USE;
351. int buffnum UNUSED_if_not_PREFIXES_IN_USE;
352. {
353. #ifndef PREFIXES_IN_USE
354.     return basenam;
355. #else
356.     if (!basenam || whichprefix < 0 || whichprefix >= PREFIX_COUNT)
357.         return basenam;
358.     if (!fqn_prefix[whichprefix])
359.         return basenam;
360.     if (buffnum < 0 || buffnum >= FQN_NUMBUF) {
361.         impossible("Invalid fqn_filename_buffer specified: %d", buffnum);
362.         buffnum = 0;
363.     }
364.     if (strlen(fqn_prefix[whichprefix]) + strlen(basenam)
365.         >= FQN_MAX_FILENAME) {
366.         impossible("fqname too long: %s + %s", fqn_prefix[whichprefix],
367.                    basenam);
368.         return basenam; /* XXX */
369.     }
370.     Strcpy(fqn_filename_buffer[buffnum], fqn_prefix[whichprefix]);
371.     return strcat(fqn_filename_buffer[buffnum], basenam);
372. #endif
373. }
374. 
375. int
376. validate_prefix_locations(reasonbuf)
377. char *reasonbuf; /* reasonbuf must be at least BUFSZ, supplied by caller */
378. {
379. #if defined(NOCWD_ASSUMPTIONS)
380.     FILE *fp;
381.     const char *filename;
382.     int prefcnt, failcount = 0;
383.     char panicbuf1[BUFSZ], panicbuf2[BUFSZ];
384.     const char *details;
385. #endif
386. 
387.     if (reasonbuf)
388.         reasonbuf[0] = '\0';
389. #if defined(NOCWD_ASSUMPTIONS)
390.     for (prefcnt = 1; prefcnt < PREFIX_COUNT; prefcnt++) {
391.         /* don't test writing to configdir or datadir; they're readonly */
392.         if (prefcnt == SYSCONFPREFIX || prefcnt == CONFIGPREFIX
393.             || prefcnt == DATAPREFIX)
394.             continue;
395.         filename = fqname("validate", prefcnt, 3);
396.         if ((fp = fopen(filename, "w"))) {
397.             fclose(fp);
398.             (void) unlink(filename);
399.         } else {
400.             if (reasonbuf) {
401.                 if (failcount)
402.                     Strcat(reasonbuf, ", ");
403.                 Strcat(reasonbuf, fqn_prefix_names[prefcnt]);
404.             }
405.             /* the paniclog entry gets the value of errno as well */
406.             Sprintf(panicbuf1, "Invalid %s", fqn_prefix_names[prefcnt]);
407. #if defined(NHSTDC) && !defined(NOTSTDC)
408.             if (!(details = strerror(errno)))
409. #endif
410.                 details = "";
411.             Sprintf(panicbuf2, "\"%s\", (%d) %s", fqn_prefix[prefcnt], errno,
412.                     details);
413.             paniclog(panicbuf1, panicbuf2);
414.             failcount++;
415.         }
416.     }
417.     if (failcount)
418.         return 0;
419.     else
420. #endif
421.         return 1;
422. }
423. 
424. /* fopen a file, with OS-dependent bells and whistles */
425. /* NOTE: a simpler version of this routine also exists in util/dlb_main.c */
426. FILE *
427. fopen_datafile(filename, mode, prefix)
428. const char *filename, *mode;
429. int prefix;
430. {
431.     FILE *fp;
432. 
433.     filename = fqname(filename, prefix, prefix == TROUBLEPREFIX ? 3 : 0);
434.     fp = fopen(filename, mode);
435.     return fp;
436. }
437. 
438. /* ----------  BEGIN LEVEL FILE HANDLING ----------- */
439. 
440. #ifdef MFLOPPY
441. /* Set names for bones[] and lock[] */
442. void
443. set_lock_and_bones()
444. {
445.     if (!ramdisk) {
446.         Strcpy(levels, permbones);
447.         Strcpy(bones, permbones);
448.     }
449.     append_slash(permbones);
450.     append_slash(levels);
451. #ifdef AMIGA
452.     strncat(levels, bbs_id, PATHLEN);
453. #endif
454.     append_slash(bones);
455.     Strcat(bones, "bonesnn.*");
456.     Strcpy(lock, levels);
457. #ifndef AMIGA
458.     Strcat(lock, alllevels);
459. #endif
460.     return;
461. }
462. #endif /* MFLOPPY */
463. 
464. /* Construct a file name for a level-type file, which is of the form
465.  * something.level (with any old level stripped off).
466.  * This assumes there is space on the end of 'file' to append
467.  * a two digit number.  This is true for 'level'
468.  * but be careful if you use it for other things -dgk
469.  */
470. void
471. set_levelfile_name(file, lev)
472. char *file;
473. int lev;
474. {
475.     char *tf;
476. 
477.     tf = rindex(file, '.');
478.     if (!tf)
479.         tf = eos(file);
480.     Sprintf(tf, ".%d", lev);
481. #ifdef VMS
482.     Strcat(tf, ";1");
483. #endif
484.     return;
485. }
486. 
487. int
488. create_levelfile(lev, errbuf)
489. int lev;
490. char errbuf[];
491. {
492.     int fd;
493.     const char *fq_lock;
494. 
495.     if (errbuf)
496.         *errbuf = '\0';
497.     set_levelfile_name(lock, lev);
498.     fq_lock = fqname(lock, LEVELPREFIX, 0);
499. 
500. #if defined(MICRO) || defined(WIN32)
501. /* Use O_TRUNC to force the file to be shortened if it already
502.  * exists and is currently longer.
503.  */
504. #ifdef HOLD_LOCKFILE_OPEN
505.     if (lev == 0)
506.         fd = open_levelfile_exclusively(
507.             fq_lock, lev, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
508.     else
509. #endif
510.         fd = open(fq_lock, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK);
511. #else
512. #ifdef MAC
513.     fd = maccreat(fq_lock, LEVL_TYPE);
514. #else
515.     fd = creat(fq_lock, FCMASK);
516. #endif
517. #endif /* MICRO || WIN32 */
518. 
519.     if (fd >= 0)
520.         level_info[lev].flags |= LFILE_EXISTS;
521.     else if (errbuf) /* failure explanation */
522.         Sprintf(errbuf, "Cannot create file \"%s\" for level %d (errno %d).",
523.                 lock, lev, errno);
524. 
525.     return fd;
526. }
527. 
528. int
529. open_levelfile(lev, errbuf)
530. int lev;
531. char errbuf[];
532. {
533.     int fd;
534.     const char *fq_lock;
535. 
536.     if (errbuf)
537.         *errbuf = '\0';
538.     set_levelfile_name(lock, lev);
539.     fq_lock = fqname(lock, LEVELPREFIX, 0);
540. #ifdef MFLOPPY
541.     /* If not currently accessible, swap it in. */
542.     if (level_info[lev].where != ACTIVE)
543.         swapin_file(lev);
544. #endif
545. #ifdef MAC
546.     fd = macopen(fq_lock, O_RDONLY | O_BINARY, LEVL_TYPE);
547. #else
548. #ifdef HOLD_LOCKFILE_OPEN
549.     if (lev == 0)
550.         fd = open_levelfile_exclusively(fq_lock, lev, O_RDONLY | O_BINARY);
551.     else
552. #endif
553.         fd = open(fq_lock, O_RDONLY | O_BINARY, 0);
554. #endif
555. 
556.     /* for failure, return an explanation that our caller can use;
557.        settle for `lock' instead of `fq_lock' because the latter
558.        might end up being too big for nethack's BUFSZ */
559.     if (fd < 0 && errbuf)
560.         Sprintf(errbuf, "Cannot open file \"%s\" for level %d (errno %d).",
561.                 lock, lev, errno);
562. 
563.     return fd;
564. }
565. 
566. void
567. delete_levelfile(lev)
568. int lev;
569. {
570.     /*
571.      * Level 0 might be created by port specific code that doesn't
572.      * call create_levfile(), so always assume that it exists.
573.      */
574.     if (lev == 0 || (level_info[lev].flags & LFILE_EXISTS)) {
575.         set_levelfile_name(lock, lev);
576. #ifdef HOLD_LOCKFILE_OPEN
577.         if (lev == 0)
578.             really_close();
579. #endif
580.         (void) unlink(fqname(lock, LEVELPREFIX, 0));
581.         level_info[lev].flags &= ~LFILE_EXISTS;
582.     }
583. }
584. 
585. void
586. clearlocks()
587. {
588. #ifdef HANGUPHANDLING
589.     if (program_state.preserve_locks)
590.         return;
591. #endif
592. #if !defined(PC_LOCKING) && defined(MFLOPPY) && !defined(AMIGA)
593.     eraseall(levels, alllevels);
594.     if (ramdisk)
595.         eraseall(permbones, alllevels);
596. #else
597.     {
598.         register int x;
599. 
600. #ifndef NO_SIGNAL
601.         (void) signal(SIGINT, SIG_IGN);
602. #endif
603. #if defined(UNIX) || defined(VMS)
604.         sethanguphandler((void FDECL((*), (int) )) SIG_IGN);
605. #endif
606.         /* can't access maxledgerno() before dungeons are created -dlc */
607.         for (x = (n_dgns ? maxledgerno() : 0); x >= 0; x--)
608.             delete_levelfile(x); /* not all levels need be present */
609.     }
610. #endif /* ?PC_LOCKING,&c */
611. }
612. 
613. #if defined(SELECTSAVED)
614. /* qsort comparison routine */
615. STATIC_OVL int CFDECLSPEC
616. strcmp_wrap(p, q)
617. const void *p;
618. const void *q;
619. {
620. #if defined(UNIX) && defined(QT_GRAPHICS)
621.     return strncasecmp(*(char **) p, *(char **) q, 16);
622. #else
623.     return strncmpi(*(char **) p, *(char **) q, 16);
624. #endif
625. }
626. #endif
627. 
628. #ifdef HOLD_LOCKFILE_OPEN
629. STATIC_OVL int
630. open_levelfile_exclusively(name, lev, oflag)
631. const char *name;
632. int lev, oflag;
633. {
634.     int reslt, fd;
635. 
636.     if (!lftrack.init) {
637.         lftrack.init = 1;
638.         lftrack.fd = -1;
639.     }
640.     if (lftrack.fd >= 0) {
641.         /* check for compatible access */
642.         if (lftrack.oflag == oflag) {
643.             fd = lftrack.fd;
644.             reslt = lseek(fd, 0L, SEEK_SET);
645.             if (reslt == -1L)
646.                 panic("open_levelfile_exclusively: lseek failed %d", errno);
647.             lftrack.nethack_thinks_it_is_open = TRUE;
648.         } else {
649.             really_close();
650.             fd = sopen(name, oflag, SH_DENYRW, FCMASK);
651.             lftrack.fd = fd;
652.             lftrack.oflag = oflag;
653.             lftrack.nethack_thinks_it_is_open = TRUE;
654.         }
655.     } else {
656.         fd = sopen(name, oflag, SH_DENYRW, FCMASK);
657.         lftrack.fd = fd;
658.         lftrack.oflag = oflag;
659.         if (fd >= 0)
660.             lftrack.nethack_thinks_it_is_open = TRUE;
661.     }
662.     return fd;
663. }
664. 
665. void
666. really_close()
667. {
668.     int fd;
669. 
670.     if (lftrack.init) {
671.         fd = lftrack.fd;
672. 
673.         lftrack.nethack_thinks_it_is_open = FALSE;
674.         lftrack.fd = -1;
675.         lftrack.oflag = 0;
676.         if (fd != -1)
677.             (void) close(fd);
678.     }
679.     return;
680. }
681. 
682. int
683. nhclose(fd)
684. int fd;
685. {
686.     if (lftrack.fd == fd) {
687.         really_close(); /* close it, but reopen it to hold it */
688.         fd = open_levelfile(0, (char *) 0);
689.         lftrack.nethack_thinks_it_is_open = FALSE;
690.         return 0;
691.     }
692.     return close(fd);
693. }
694. #else /* !HOLD_LOCKFILE_OPEN */
695. 
696. int
697. nhclose(fd)
698. int fd;
699. {
700.     return close(fd);
701. }
702. #endif /* ?HOLD_LOCKFILE_OPEN */
703. 
704. /* ----------  END LEVEL FILE HANDLING ----------- */
705. 
706. /* ----------  BEGIN BONES FILE HANDLING ----------- */
707. 
708. /* set up "file" to be file name for retrieving bones, and return a
709.  * bonesid to be read/written in the bones file.
710.  */
711. STATIC_OVL char *
712. set_bonesfile_name(file, lev)
713. char *file;
714. d_level *lev;
715. {
716.     s_level *sptr;
717.     char *dptr;
718. 
719.     /*
720.      * "bonD0.nn"   = bones for level nn in the main dungeon;
721.      * "bonM0.T"    = bones for Minetown;
722.      * "bonQBar.n"  = bones for level n in the Barbarian quest;
723.      * "bon3D0.nn"  = \
724.      * "bon3M0.T"   =  > same as above, but for bones pool #3.
725.      * "bon3QBar.n" = /
726.      *
727.      * Return value for content validation skips "bon" and the
728.      * pool number (if present), making it feasible for the admin
729.      * to manually move a bones file from one pool to another by
730.      * renaming it.
731.      */
732.     Strcpy(file, "bon");
733. #ifdef SYSCF
734.     if (sysopt.bones_pools > 1) {
735.         unsigned poolnum = min((unsigned) sysopt.bones_pools, 10);
736. 
737.         poolnum = (unsigned) ubirthday % poolnum; /* 0..9 */
738.         Sprintf(eos(file), "%u", poolnum);
739.     }
740. #endif
741.     dptr = eos(file); /* this used to be after the following Sprintf()
742.                          and the return value was (dptr - 2) */
743.     /* when this naming scheme was adopted, 'filecode' was one letter;
744.        3.3.0 turned it into a three letter string (via roles[] in role.c);
745.        from that version through 3.6.0, 'dptr' pointed past the filecode
746.        and the return value of (dptr - 2)  was wrong for bones produced
747.        in the quest branch, skipping the boneid character 'Q' and the
748.        first letter of the role's filecode; bones loading still worked
749.        because the bonesid used for validation had the same error */
750.     Sprintf(dptr, "%c%s", dungeons[lev->dnum].boneid,
751.             In_quest(lev) ? urole.filecode : "0");
752.     if ((sptr = Is_special(lev)) != 0)
753.         Sprintf(eos(dptr), ".%c", sptr->boneid);
754.     else
755.         Sprintf(eos(dptr), ".%d", lev->dlevel);
756. #ifdef VMS
757.     Strcat(dptr, ";1");
758. #endif
759.     return dptr;
760. }
761. 
762. /* set up temporary file name for writing bones, to avoid another game's
763.  * trying to read from an uncompleted bones file.  we want an uncontentious
764.  * name, so use one in the namespace reserved for this game's level files.
765.  * (we are not reading or writing level files while writing bones files, so
766.  * the same array may be used instead of copying.)
767.  */
768. STATIC_OVL char *
769. set_bonestemp_name()
770. {
771.     char *tf;
772. 
773.     tf = rindex(lock, '.');
774.     if (!tf)
775.         tf = eos(lock);
776.     Sprintf(tf, ".bn");
777. #ifdef VMS
778.     Strcat(tf, ";1");
779. #endif
780.     return lock;
781. }
782. 
783. int
784. create_bonesfile(lev, bonesid, errbuf)
785. d_level *lev;
786. char **bonesid;
787. char errbuf[];
788. {
789.     const char *file;
790.     int fd;
791. 
792.     if (errbuf)
793.         *errbuf = '\0';
794.     *bonesid = set_bonesfile_name(bones, lev);
795.     file = set_bonestemp_name();
796.     file = fqname(file, BONESPREFIX, 0);
797. 
798. #if defined(MICRO) || defined(WIN32)
799.     /* Use O_TRUNC to force the file to be shortened if it already
800.      * exists and is currently longer.
801.      */
802.     fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK);
803. #else
804. #ifdef MAC
805.     fd = maccreat(file, BONE_TYPE);
806. #else
807.     fd = creat(file, FCMASK);
808. #endif
809. #endif
810.     if (fd < 0 && errbuf) /* failure explanation */
811.         Sprintf(errbuf, "Cannot create bones \"%s\", id %s (errno %d).", lock,
812.                 *bonesid, errno);
813. 
814. #if defined(VMS) && !defined(SECURE)
815.     /*
816.        Re-protect bones file with world:read+write+execute+delete access.
817.        umask() doesn't seem very reliable; also, vaxcrtl won't let us set
818.        delete access without write access, which is what's really wanted.
819.        Can't simply create it with the desired protection because creat
820.        ANDs the mask with the user's default protection, which usually
821.        denies some or all access to world.
822.      */
823.     (void) chmod(file, FCMASK | 007); /* allow other users full access */
824. #endif /* VMS && !SECURE */
825. 
826.     return fd;
827. }
828. 
829. #ifdef MFLOPPY
830. /* remove partial bonesfile in process of creation */
831. void
832. cancel_bonesfile()
833. {
834.     const char *tempname;
835. 
836.     tempname = set_bonestemp_name();
837.     tempname = fqname(tempname, BONESPREFIX, 0);
838.     (void) unlink(tempname);
839. }
840. #endif /* MFLOPPY */
841. 
842. /* move completed bones file to proper name */
843. void
844. commit_bonesfile(lev)
845. d_level *lev;
846. {
847.     const char *fq_bones, *tempname;
848.     int ret;
849. 
850.     (void) set_bonesfile_name(bones, lev);
851.     fq_bones = fqname(bones, BONESPREFIX, 0);
852.     tempname = set_bonestemp_name();
853.     tempname = fqname(tempname, BONESPREFIX, 1);
854. 
855. #if (defined(SYSV) && !defined(SVR4)) || defined(GENIX)
856.     /* old SYSVs don't have rename.  Some SVR3's may, but since they
857.      * also have link/unlink, it doesn't matter. :-)
858.      */
859.     (void) unlink(fq_bones);
860.     ret = link(tempname, fq_bones);
861.     ret += unlink(tempname);
862. #else
863.     ret = rename(tempname, fq_bones);
864. #endif
865.     if (wizard && ret != 0)
866.         pline("couldn't rename %s to %s.", tempname, fq_bones);
867. }
868. 
869. int
870. open_bonesfile(lev, bonesid)
871. d_level *lev;
872. char **bonesid;
873. {
874.     const char *fq_bones;
875.     int fd;
876. 
877.     *bonesid = set_bonesfile_name(bones, lev);
878.     fq_bones = fqname(bones, BONESPREFIX, 0);
879.     nh_uncompress(fq_bones); /* no effect if nonexistent */
880. #ifdef MAC
881.     fd = macopen(fq_bones, O_RDONLY | O_BINARY, BONE_TYPE);
882. #else
883.     fd = open(fq_bones, O_RDONLY | O_BINARY, 0);
884. #endif
885.     return fd;
886. }
887. 
888. int
889. delete_bonesfile(lev)
890. d_level *lev;
891. {
892.     (void) set_bonesfile_name(bones, lev);
893.     return !(unlink(fqname(bones, BONESPREFIX, 0)) < 0);
894. }
895. 
896. /* assume we're compressing the recently read or created bonesfile, so the
897.  * file name is already set properly */
898. void
899. compress_bonesfile()
900. {
901.     nh_compress(fqname(bones, BONESPREFIX, 0));
902. }
903. 
904. /* ----------  END BONES FILE HANDLING ----------- */
905. 
906. /* ----------  BEGIN SAVE FILE HANDLING ----------- */
907. 
908. /* set savefile name in OS-dependent manner from pre-existing plname,
909.  * avoiding troublesome characters */
910. void
911. set_savefile_name(regularize_it)
912. boolean regularize_it;
913. {
914. #ifdef VMS
915.     Sprintf(SAVEF, "[.save]%d%s", getuid(), plname);
916.     if (regularize_it)
917.         regularize(SAVEF + 7);
918.     Strcat(SAVEF, ";1");
919. #else
920. #if defined(MICRO)
921.     Strcpy(SAVEF, SAVEP);
922. #ifdef AMIGA
923.     strncat(SAVEF, bbs_id, PATHLEN);
924. #endif
925.     {
926.         int i = strlen(SAVEP);
927. #ifdef AMIGA
928.         /* plname has to share space with SAVEP and ".sav" */
929.         (void) strncat(SAVEF, plname, FILENAME - i - 4);
930. #else
931.         (void) strncat(SAVEF, plname, 8);
932. #endif
933.         if (regularize_it)
934.             regularize(SAVEF + i);
935.     }
936.     Strcat(SAVEF, SAVE_EXTENSION);
937. #else
938. #if defined(WIN32)
939.     {
940.         static const char okchars[] =
941.             "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.";
942.         const char *legal = okchars;
943.         char fnamebuf[BUFSZ], encodedfnamebuf[BUFSZ];
944. 
945.         /* Obtain the name of the logged on user and incorporate
946.          * it into the name. */
947.         Sprintf(fnamebuf, "%s-%s", get_username(0), plname);
948.         if (regularize_it)
949.             ++legal; /* skip '*' wildcard character */
950.         (void) fname_encode(legal, '%', fnamebuf, encodedfnamebuf, BUFSZ);
951.         Sprintf(SAVEF, "%s%s", encodedfnamebuf, SAVE_EXTENSION);
952.     }
953. #else  /* not VMS or MICRO or WIN32 */
954.     Sprintf(SAVEF, "save/%d%s", (int) getuid(), plname);
955.     if (regularize_it)
956.         regularize(SAVEF + 5); /* avoid . or / in name */
957. #endif /* WIN32 */
958. #endif /* MICRO */
959. #endif /* VMS   */
960. }
961. 
962. #ifdef INSURANCE
963. void
964. save_savefile_name(fd)
965. int fd;
966. {
967.     (void) write(fd, (genericptr_t) SAVEF, sizeof(SAVEF));
968. }
969. #endif
970. 
971. #ifndef MICRO
972. /* change pre-existing savefile name to indicate an error savefile */
973. void
974. set_error_savefile()
975. {
976. #ifdef VMS
977.     {
978.         char *semi_colon = rindex(SAVEF, ';');
979. 
980.         if (semi_colon)
981.             *semi_colon = '\0';
982.     }
983.     Strcat(SAVEF, ".e;1");
984. #else
985. #ifdef MAC
986.     Strcat(SAVEF, "-e");
987. #else
988.     Strcat(SAVEF, ".e");
989. #endif
990. #endif
991. }
992. #endif
993. 
994. /* create save file, overwriting one if it already exists */
995. int
996. create_savefile()
997. {
998.     const char *fq_save;
999.     int fd;
1000. 
1001.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1002. #if defined(MICRO) || defined(WIN32)
1003.     fd = open(fq_save, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, FCMASK);
1004. #else
1005. #ifdef MAC
1006.     fd = maccreat(fq_save, SAVE_TYPE);
1007. #else
1008.     fd = creat(fq_save, FCMASK);
1009. #endif
1010. #if defined(VMS) && !defined(SECURE)
1011.     /*
1012.        Make sure the save file is owned by the current process.  That's
1013.        the default for non-privileged users, but for priv'd users the
1014.        file will be owned by the directory's owner instead of the user.
1015.     */
1016. #undef getuid
1017.     (void) chown(fq_save, getuid(), getgid());
1018. #define getuid() vms_getuid()
1019. #endif /* VMS && !SECURE */
1020. #endif /* MICRO */
1021. 
1022.     return fd;
1023. }
1024. 
1025. /* open savefile for reading */
1026. int
1027. open_savefile()
1028. {
1029.     const char *fq_save;
1030.     int fd;
1031. 
1032.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1033. #ifdef MAC
1034.     fd = macopen(fq_save, O_RDONLY | O_BINARY, SAVE_TYPE);
1035. #else
1036.     fd = open(fq_save, O_RDONLY | O_BINARY, 0);
1037. #endif
1038.     return fd;
1039. }
1040. 
1041. /* delete savefile */
1042. int
1043. delete_savefile()
1044. {
1045.     (void) unlink(fqname(SAVEF, SAVEPREFIX, 0));
1046.     return 0; /* for restore_saved_game() (ex-xxxmain.c) test */
1047. }
1048. 
1049. /* try to open up a save file and prepare to restore it */
1050. int
1051. restore_saved_game()
1052. {
1053.     const char *fq_save;
1054.     int fd;
1055. 
1056.     reset_restpref();
1057.     set_savefile_name(TRUE);
1058. #ifdef MFLOPPY
1059.     if (!saveDiskPrompt(1))
1060.         return -1;
1061. #endif /* MFLOPPY */
1062.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1063. 
1064.     nh_uncompress(fq_save);
1065.     if ((fd = open_savefile()) < 0)
1066.         return fd;
1067. 
1068.     if (validate(fd, fq_save) != 0) {
1069.         (void) nhclose(fd), fd = -1;
1070.         (void) delete_savefile();
1071.     }
1072.     return fd;
1073. }
1074. 
1075. #if defined(SELECTSAVED)
1076. char *
1077. plname_from_file(filename)
1078. const char *filename;
1079. {
1080.     int fd;
1081.     char *result = 0;
1082. 
1083.     Strcpy(SAVEF, filename);
1084. #ifdef COMPRESS_EXTENSION
1085.     SAVEF[strlen(SAVEF) - strlen(COMPRESS_EXTENSION)] = '\0';
1086. #endif
1087.     nh_uncompress(SAVEF);
1088.     if ((fd = open_savefile()) >= 0) {
1089.         if (validate(fd, filename) == 0) {
1090.             char tplname[PL_NSIZ];
1091.             get_plname_from_file(fd, tplname);
1092.             result = dupstr(tplname);
1093.         }
1094.         (void) nhclose(fd);
1095.     }
1096.     nh_compress(SAVEF);
1097. 
1098.     return result;
1099. #if 0
1100. /* --------- obsolete - used to be ifndef STORE_PLNAME_IN_FILE ----*/
1101. #if defined(UNIX) && defined(QT_GRAPHICS)
1102.     /* Name not stored in save file, so we have to extract it from
1103.        the filename, which loses information
1104.        (eg. "/", "_", and "." characters are lost. */
1105.     int k;
1106.     int uid;
1107.     char name[64]; /* more than PL_NSIZ */
1108. #ifdef COMPRESS_EXTENSION
1109. #define EXTSTR COMPRESS_EXTENSION
1110. #else
1111. #define EXTSTR ""
1112. #endif
1113. 
1114.     if ( sscanf( filename, "%*[^/]/%d%63[^.]" EXTSTR, &uid, name ) == 2 ) {
1115. #undef EXTSTR
1116.         /* "_" most likely means " ", which certainly looks nicer */
1117.         for (k=0; name[k]; k++)
1118.             if ( name[k] == '_' )
1119.                 name[k] = ' ';
1120.         return dupstr(name);
1121.     } else
1122. #endif /* UNIX && QT_GRAPHICS */
1123.     {
1124.         return 0;
1125.     }
1126. /* --------- end of obsolete code ----*/
1127. #endif /* 0 - WAS STORE_PLNAME_IN_FILE*/
1128. }
1129. #endif /* defined(SELECTSAVED) */
1130. 
1131. char **
1132. get_saved_games()
1133. {
1134. #if defined(SELECTSAVED)
1135.     int n, j = 0;
1136.     char **result = 0;
1137. #ifdef WIN32
1138.     {
1139.         char *foundfile;
1140.         const char *fq_save;
1141. 
1142.         Strcpy(plname, "*");
1143.         set_savefile_name(FALSE);
1144. #if defined(ZLIB_COMP)
1145.         Strcat(SAVEF, COMPRESS_EXTENSION);
1146. #endif
1147.         fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1148. 
1149.         n = 0;
1150.         foundfile = foundfile_buffer();
1151.         if (findfirst((char *) fq_save)) {
1152.             do {
1153.                 ++n;
1154.             } while (findnext());
1155.         }
1156.         if (n > 0) {
1157.             result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */
1158.             (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *));
1159.             if (findfirst((char *) fq_save)) {
1160.                 j = n = 0;
1161.                 do {
1162.                     char *r;
1163.                     r = plname_from_file(foundfile);
1164.                     if (r)
1165.                         result[j++] = r;
1166.                     ++n;
1167.                 } while (findnext());
1168.             }
1169.         }
1170.     }
1171. #endif
1172. #if defined(UNIX) && defined(QT_GRAPHICS)
1173.     /* posixly correct version */
1174.     int myuid = getuid();
1175.     DIR *dir;
1176. 
1177.     if ((dir = opendir(fqname("save", SAVEPREFIX, 0)))) {
1178.         for (n = 0; readdir(dir); n++)
1179.             ;
1180.         closedir(dir);
1181.         if (n > 0) {
1182.             int i;
1183. 
1184.             if (!(dir = opendir(fqname("save", SAVEPREFIX, 0))))
1185.                 return 0;
1186.             result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */
1187.             (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *));
1188.             for (i = 0, j = 0; i < n; i++) {
1189.                 int uid;
1190.                 char name[64]; /* more than PL_NSIZ */
1191.                 struct dirent *entry = readdir(dir);
1192. 
1193.                 if (!entry)
1194.                     break;
1195.                 if (sscanf(entry->d_name, "%d%63s", &uid, name) == 2) {
1196.                     if (uid == myuid) {
1197.                         char filename[BUFSZ];
1198.                         char *r;
1199. 
1200.                         Sprintf(filename, "save/%d%s", uid, name);
1201.                         r = plname_from_file(filename);
1202.                         if (r)
1203.                             result[j++] = r;
1204.                     }
1205.                 }
1206.             }
1207.             closedir(dir);
1208.         }
1209.     }
1210. #endif
1211. #ifdef VMS
1212.     Strcpy(plname, "*");
1213.     set_savefile_name(FALSE);
1214.     j = vms_get_saved_games(SAVEF, &result);
1215. #endif /* VMS */
1216. 
1217.     if (j > 0) {
1218.         if (j > 1)
1219.             qsort(result, j, sizeof (char *), strcmp_wrap);
1220.         result[j] = 0;
1221.         return result;
1222.     } else if (result) { /* could happen if save files are obsolete */
1223.         free_saved_games(result);
1224.     }
1225. #endif /* SELECTSAVED */
1226.     return 0;
1227. }
1228. 
1229. void
1230. free_saved_games(saved)
1231. char **saved;
1232. {
1233.     if (saved) {
1234.         int i = 0;
1235. 
1236.         while (saved[i])
1237.             free((genericptr_t) saved[i++]);
1238.         free((genericptr_t) saved);
1239.     }
1240. }
1241. 
1242. /* ----------  END SAVE FILE HANDLING ----------- */
1243. 
1244. /* ----------  BEGIN FILE COMPRESSION HANDLING ----------- */
1245. 
1246. #ifdef COMPRESS
1247. 
1248. STATIC_OVL void
1249. redirect(filename, mode, stream, uncomp)
1250. const char *filename, *mode;
1251. FILE *stream;
1252. boolean uncomp;
1253. {
1254.     if (freopen(filename, mode, stream) == (FILE *) 0) {
1255.         (void) fprintf(stderr, "freopen of %s for %scompress failed\n",
1256.                        filename, uncomp ? "un" : "");
1257.         nh_terminate(EXIT_FAILURE);
1258.     }
1259. }
1260. 
1261. /*
1262.  * using system() is simpler, but opens up security holes and causes
1263.  * problems on at least Interactive UNIX 3.0.1 (SVR3.2), where any
1264.  * setuid is renounced by /bin/sh, so the files cannot be accessed.
1265.  *
1266.  * cf. child() in unixunix.c.
1267.  */
1268. STATIC_OVL void
1269. docompress_file(filename, uncomp)
1270. const char *filename;
1271. boolean uncomp;
1272. {
1273.     char cfn[80];
1274.     FILE *cf;
1275.     const char *args[10];
1276. #ifdef COMPRESS_OPTIONS
1277.     char opts[80];
1278. #endif
1279.     int i = 0;
1280.     int f;
1281. #ifdef TTY_GRAPHICS
1282.     boolean istty = WINDOWPORT("tty");
1283. #endif
1284. 
1285.     Strcpy(cfn, filename);
1286. #ifdef COMPRESS_EXTENSION
1287.     Strcat(cfn, COMPRESS_EXTENSION);
1288. #endif
1289.     /* when compressing, we know the file exists */
1290.     if (uncomp) {
1291.         if ((cf = fopen(cfn, RDBMODE)) == (FILE *) 0)
1292.             return;
1293.         (void) fclose(cf);
1294.     }
1295. 
1296.     args[0] = COMPRESS;
1297.     if (uncomp)
1298.         args[++i] = "-d"; /* uncompress */
1299. #ifdef COMPRESS_OPTIONS
1300.     {
1301.         /* we can't guarantee there's only one additional option, sigh */
1302.         char *opt;
1303.         boolean inword = FALSE;
1304. 
1305.         Strcpy(opts, COMPRESS_OPTIONS);
1306.         opt = opts;
1307.         while (*opt) {
1308.             if ((*opt == ' ') || (*opt == '\t')) {
1309.                 if (inword) {
1310.                     *opt = '\0';
1311.                     inword = FALSE;
1312.                 }
1313.             } else if (!inword) {
1314.                 args[++i] = opt;
1315.                 inword = TRUE;
1316.             }
1317.             opt++;
1318.         }
1319.     }
1320. #endif
1321.     args[++i] = (char *) 0;
1322. 
1323. #ifdef TTY_GRAPHICS
1324.     /* If we don't do this and we are right after a y/n question *and*
1325.      * there is an error message from the compression, the 'y' or 'n' can
1326.      * end up being displayed after the error message.
1327.      */
1328.     if (istty)
1329.         mark_synch();
1330. #endif
1331.     f = fork();
1332.     if (f == 0) { /* child */
1333. #ifdef TTY_GRAPHICS
1334.         /* any error messages from the compression must come out after
1335.          * the first line, because the more() to let the user read
1336.          * them will have to clear the first line.  This should be
1337.          * invisible if there are no error messages.
1338.          */
1339.         if (istty)
1340.             raw_print("");
1341. #endif
1342.         /* run compressor without privileges, in case other programs
1343.          * have surprises along the line of gzip once taking filenames
1344.          * in GZIP.
1345.          */
1346.         /* assume all compressors will compress stdin to stdout
1347.          * without explicit filenames.  this is true of at least
1348.          * compress and gzip, those mentioned in config.h.
1349.          */
1350.         if (uncomp) {
1351.             redirect(cfn, RDBMODE, stdin, uncomp);
1352.             redirect(filename, WRBMODE, stdout, uncomp);
1353.         } else {
1354.             redirect(filename, RDBMODE, stdin, uncomp);
1355.             redirect(cfn, WRBMODE, stdout, uncomp);
1356.         }
1357.         (void) setgid(getgid());
1358.         (void) setuid(getuid());
1359.         (void) execv(args[0], (char *const *) args);
1360.         perror((char *) 0);
1361.         (void) fprintf(stderr, "Exec to %scompress %s failed.\n",
1362.                        uncomp ? "un" : "", filename);
1363.         nh_terminate(EXIT_FAILURE);
1364.     } else if (f == -1) {
1365.         perror((char *) 0);
1366.         pline("Fork to %scompress %s failed.", uncomp ? "un" : "", filename);
1367.         return;
1368.     }
1369. #ifndef NO_SIGNAL
1370.     (void) signal(SIGINT, SIG_IGN);
1371.     (void) signal(SIGQUIT, SIG_IGN);
1372.     (void) wait((int *) &i);
1373.     (void) signal(SIGINT, (SIG_RET_TYPE) done1);
1374.     if (wizard)
1375.         (void) signal(SIGQUIT, SIG_DFL);
1376. #else
1377.     /* I don't think we can really cope with external compression
1378.      * without signals, so we'll declare that compress failed and
1379.      * go on.  (We could do a better job by forcing off external
1380.      * compression if there are no signals, but we want this for
1381.      * testing with FailSafeC
1382.      */
1383.     i = 1;
1384. #endif
1385.     if (i == 0) {
1386.         /* (un)compress succeeded: remove file left behind */
1387.         if (uncomp)
1388.             (void) unlink(cfn);
1389.         else
1390.             (void) unlink(filename);
1391.     } else {
1392.         /* (un)compress failed; remove the new, bad file */
1393.         if (uncomp) {
1394.             raw_printf("Unable to uncompress %s", filename);
1395.             (void) unlink(filename);
1396.         } else {
1397.             /* no message needed for compress case; life will go on */
1398.             (void) unlink(cfn);
1399.         }
1400. #ifdef TTY_GRAPHICS
1401.         /* Give them a chance to read any error messages from the
1402.          * compression--these would go to stdout or stderr and would get
1403.          * overwritten only in tty mode.  It's still ugly, since the
1404.          * messages are being written on top of the screen, but at least
1405.          * the user can read them.
1406.          */
1407.         if (istty && iflags.window_inited) {
1408.             clear_nhwindow(WIN_MESSAGE);
1409.             more();
1410.             /* No way to know if this is feasible */
1411.             /* doredraw(); */
1412.         }
1413. #endif
1414.     }
1415. }
1416. #endif /* COMPRESS */
1417. 
1418. #if defined(COMPRESS) || defined(ZLIB_COMP)
1419. #define UNUSED_if_not_COMPRESS /*empty*/
1420. #else
1421. #define UNUSED_if_not_COMPRESS UNUSED
1422. #endif
1423. 
1424. /* compress file */
1425. void
1426. nh_compress(filename)
1427. const char *filename UNUSED_if_not_COMPRESS;
1428. {
1429. #if !defined(COMPRESS) && !defined(ZLIB_COMP)
1430. #ifdef PRAGMA_UNUSED
1431. #pragma unused(filename)
1432. #endif
1433. #else
1434.     docompress_file(filename, FALSE);
1435. #endif
1436. }
1437. 
1438. /* uncompress file if it exists */
1439. void
1440. nh_uncompress(filename)
1441. const char *filename UNUSED_if_not_COMPRESS;
1442. {
1443. #if !defined(COMPRESS) && !defined(ZLIB_COMP)
1444. #ifdef PRAGMA_UNUSED
1445. #pragma unused(filename)
1446. #endif
1447. #else
1448.     docompress_file(filename, TRUE);
1449. #endif
1450. }
1451. 
1452. #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */
1453. STATIC_OVL boolean
1454. make_compressed_name(filename, cfn)
1455. const char *filename;
1456. char *cfn;
1457. {
1458. #ifndef SHORT_FILENAMES
1459.     /* Assume free-form filename with no 8.3 restrictions */
1460.     strcpy(cfn, filename);
1461.     strcat(cfn, COMPRESS_EXTENSION);
1462.     return TRUE;
1463. #else
1464. #ifdef SAVE_EXTENSION
1465.     char *bp = (char *) 0;
1466. 
1467.     strcpy(cfn, filename);
1468.     if ((bp = strstri(cfn, SAVE_EXTENSION))) {
1469.         strsubst(bp, SAVE_EXTENSION, ".saz");
1470.         return TRUE;
1471.     } else {
1472.         /* find last occurrence of bon */
1473.         bp = eos(cfn);
1474.         while (bp-- > cfn) {
1475.             if (strstri(bp, "bon")) {
1476.                 strsubst(bp, "bon", "boz");
1477.                 return TRUE;
1478.             }
1479.         }
1480.     }
1481. #endif /* SAVE_EXTENSION */
1482.     return FALSE;
1483. #endif /* SHORT_FILENAMES */
1484. }
1485. 
1486. STATIC_OVL void
1487. docompress_file(filename, uncomp)
1488. const char *filename;
1489. boolean uncomp;
1490. {
1491.     gzFile compressedfile;
1492.     FILE *uncompressedfile;
1493.     char cfn[256];
1494.     char buf[1024];
1495.     unsigned len, len2;
1496. 
1497.     if (!make_compressed_name(filename, cfn))
1498.         return;
1499. 
1500.     if (!uncomp) {
1501.         /* Open the input and output files */
1502.         /* Note that gzopen takes "wb" as its mode, even on systems where
1503.            fopen takes "r" and "w" */
1504. 
1505.         uncompressedfile = fopen(filename, RDBMODE);
1506.         if (!uncompressedfile) {
1507.             pline("Error in zlib docompress_file %s", filename);
1508.             return;
1509.         }
1510.         compressedfile = gzopen(cfn, "wb");
1511.         if (compressedfile == NULL) {
1512.             if (errno == 0) {
1513.                 pline("zlib failed to allocate memory");
1514.             } else {
1515.                 panic("Error in docompress_file %d", errno);
1516.             }
1517.             fclose(uncompressedfile);
1518.             return;
1519.         }
1520. 
1521.         /* Copy from the uncompressed to the compressed file */
1522. 
1523.         while (1) {
1524.             len = fread(buf, 1, sizeof(buf), uncompressedfile);
1525.             if (ferror(uncompressedfile)) {
1526.                 pline("Failure reading uncompressed file");
1527.                 pline("Can't compress %s.", filename);
1528.                 fclose(uncompressedfile);
1529.                 gzclose(compressedfile);
1530.                 (void) unlink(cfn);
1531.                 return;
1532.             }
1533.             if (len == 0)
1534.                 break; /* End of file */
1535. 
1536.             len2 = gzwrite(compressedfile, buf, len);
1537.             if (len2 == 0) {
1538.                 pline("Failure writing compressed file");
1539.                 pline("Can't compress %s.", filename);
1540.                 fclose(uncompressedfile);
1541.                 gzclose(compressedfile);
1542.                 (void) unlink(cfn);
1543.                 return;
1544.             }
1545.         }
1546. 
1547.         fclose(uncompressedfile);
1548.         gzclose(compressedfile);
1549. 
1550.         /* Delete the file left behind */
1551. 
1552.         (void) unlink(filename);
1553. 
1554.     } else { /* uncomp */
1555. 
1556.         /* Open the input and output files */
1557.         /* Note that gzopen takes "rb" as its mode, even on systems where
1558.            fopen takes "r" and "w" */
1559. 
1560.         compressedfile = gzopen(cfn, "rb");
1561.         if (compressedfile == NULL) {
1562.             if (errno == 0) {
1563.                 pline("zlib failed to allocate memory");
1564.             } else if (errno != ENOENT) {
1565.                 panic("Error in zlib docompress_file %s, %d", filename,
1566.                       errno);
1567.             }
1568.             return;
1569.         }
1570.         uncompressedfile = fopen(filename, WRBMODE);
1571.         if (!uncompressedfile) {
1572.             pline("Error in zlib docompress file uncompress %s", filename);
1573.             gzclose(compressedfile);
1574.             return;
1575.         }
1576. 
1577.         /* Copy from the compressed to the uncompressed file */
1578. 
1579.         while (1) {
1580.             len = gzread(compressedfile, buf, sizeof(buf));
1581.             if (len == (unsigned) -1) {
1582.                 pline("Failure reading compressed file");
1583.                 pline("Can't uncompress %s.", filename);
1584.                 fclose(uncompressedfile);
1585.                 gzclose(compressedfile);
1586.                 (void) unlink(filename);
1587.                 return;
1588.             }
1589.             if (len == 0)
1590.                 break; /* End of file */
1591. 
1592.             fwrite(buf, 1, len, uncompressedfile);
1593.             if (ferror(uncompressedfile)) {
1594.                 pline("Failure writing uncompressed file");
1595.                 pline("Can't uncompress %s.", filename);
1596.                 fclose(uncompressedfile);
1597.                 gzclose(compressedfile);
1598.                 (void) unlink(filename);
1599.                 return;
1600.             }
1601.         }
1602. 
1603.         fclose(uncompressedfile);
1604.         gzclose(compressedfile);
1605. 
1606.         /* Delete the file left behind */
1607.         (void) unlink(cfn);
1608.     }
1609. }
1610. #endif /* RLC 09 Mar 1999: End ZLIB patch */
1611. 
1612. /* ----------  END FILE COMPRESSION HANDLING ----------- */
1613. 
1614. /* ----------  BEGIN FILE LOCKING HANDLING ----------- */
1615. 
1616. static int nesting = 0;
1617. 
1618. #if defined(NO_FILE_LINKS) || defined(USE_FCNTL) /* implies UNIX */
1619. static int lockfd; /* for lock_file() to pass to unlock_file() */
1620. #endif
1621. #ifdef USE_FCNTL
1622. struct flock sflock; /* for unlocking, same as above */
1623. #endif
1624. 
1625. #define HUP if (!program_state.done_hup)
1626. 
1627. #ifndef USE_FCNTL
1628. STATIC_OVL char *
1629. make_lockname(filename, lockname)
1630. const char *filename;
1631. char *lockname;
1632. {
1633. #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(WIN32) \
1634.     || defined(MSDOS)
1635. #ifdef NO_FILE_LINKS
1636.     Strcpy(lockname, LOCKDIR);
1637.     Strcat(lockname, "/");
1638.     Strcat(lockname, filename);
1639. #else
1640.     Strcpy(lockname, filename);
1641. #endif
1642. #ifdef VMS
1643.     {
1644.         char *semi_colon = rindex(lockname, ';');
1645.         if (semi_colon)
1646.             *semi_colon = '\0';
1647.     }
1648.     Strcat(lockname, ".lock;1");
1649. #else
1650.     Strcat(lockname, "_lock");
1651. #endif
1652.     return lockname;
1653. #else /* !(UNIX || VMS || AMIGA || WIN32 || MSDOS) */
1654. #ifdef PRAGMA_UNUSED
1655. #pragma unused(filename)
1656. #endif
1657.     lockname[0] = '\0';
1658.     return (char *) 0;
1659. #endif
1660. }
1661. #endif /* !USE_FCNTL */
1662. 
1663. /* lock a file */
1664. boolean
1665. lock_file(filename, whichprefix, retryct)
1666. const char *filename;
1667. int whichprefix;
1668. int retryct;
1669. {
1670. #if defined(PRAGMA_UNUSED) && !(defined(UNIX) || defined(VMS)) \
1671.     && !(defined(AMIGA) || defined(WIN32) || defined(MSDOS))
1672. #pragma unused(retryct)
1673. #endif
1674. #ifndef USE_FCNTL
1675.     char locknambuf[BUFSZ];
1676.     const char *lockname;
1677. #endif
1678. 
1679.     nesting++;
1680.     if (nesting > 1) {
1681.         impossible("TRIED TO NEST LOCKS");
1682.         return TRUE;
1683.     }
1684. 
1685. #ifndef USE_FCNTL
1686.     lockname = make_lockname(filename, locknambuf);
1687. #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */
1688.     lockname = fqname(lockname, LOCKPREFIX, 2);
1689. #endif
1690. #endif
1691.     filename = fqname(filename, whichprefix, 0);
1692. #ifdef USE_FCNTL
1693.     lockfd = open(filename, O_RDWR);
1694.     if (lockfd == -1) {
1695.         HUP raw_printf("Cannot open file %s.  Is NetHack installed correctly?",
1696.                        filename);
1697.         nesting--;
1698.         return FALSE;
1699.     }
1700.     sflock.l_type = F_WRLCK;
1701.     sflock.l_whence = SEEK_SET;
1702.     sflock.l_start = 0;
1703.     sflock.l_len = 0;
1704. #endif
1705. 
1706. #if defined(UNIX) || defined(VMS)
1707. #ifdef USE_FCNTL
1708.     while (fcntl(lockfd, F_SETLK, &sflock) == -1) {
1709. #else
1710. #ifdef NO_FILE_LINKS
1711.     while ((lockfd = open(lockname, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1) {
1712. #else
1713.     while (link(filename, lockname) == -1) {
1714. #endif
1715. #endif
1716. 
1717. #ifdef USE_FCNTL
1718.         if (retryct--) {
1719.             HUP raw_printf(
1720.                "Waiting for release of fcntl lock on %s.  (%d retries left.)",
1721.                            filename, retryct);
1722.             sleep(1);
1723.         } else {
1724.             HUP(void) raw_print("I give up.  Sorry.");
1725.             HUP raw_printf("Some other process has an unnatural grip on %s.",
1726.                            filename);
1727.             nesting--;
1728.             return FALSE;
1729.         }
1730. #else
1731.         register int errnosv = errno;
1732. 
1733.         switch (errnosv) { /* George Barbanis */
1734.         case EEXIST:
1735.             if (retryct--) {
1736.                 HUP raw_printf(
1737.                     "Waiting for access to %s.  (%d retries left).", filename,
1738.                     retryct);
1739. #if defined(SYSV) || defined(ULTRIX) || defined(VMS)
1740.                 (void)
1741. #endif
1742.                     sleep(1);
1743.             } else {
1744.                 HUP(void) raw_print("I give up.  Sorry.");
1745.                 HUP raw_printf("Perhaps there is an old %s around?",
1746.                                lockname);
1747.                 nesting--;
1748.                 return FALSE;
1749.             }
1750. 
1751.             break;
1752.         case ENOENT:
1753.             HUP raw_printf("Can't find file %s to lock!", filename);
1754.             nesting--;
1755.             return FALSE;
1756.         case EACCES:
1757.             HUP raw_printf("No write permission to lock %s!", filename);
1758.             nesting--;
1759.             return FALSE;
1760. #ifdef VMS /* c__translate(vmsfiles.c) */
1761.         case EPERM:
1762.             /* could be misleading, but usually right */
1763.             HUP raw_printf("Can't lock %s due to directory protection.",
1764.                            filename);
1765.             nesting--;
1766.             return FALSE;
1767. #endif
1768.         case EROFS:
1769.             /* take a wild guess at the underlying cause */
1770.             HUP perror(lockname);
1771.             HUP raw_printf("Cannot lock %s.", filename);
1772.             HUP raw_printf(
1773.   "(Perhaps you are running NetHack from inside the distribution package?).");
1774.             nesting--;
1775.             return FALSE;
1776.         default:
1777.             HUP perror(lockname);
1778.             HUP raw_printf("Cannot lock %s for unknown reason (%d).",
1779.                            filename, errnosv);
1780.             nesting--;
1781.             return FALSE;
1782.         }
1783. #endif /* USE_FCNTL */
1784.     }
1785. #endif /* UNIX || VMS */
1786. 
1787. #if (defined(AMIGA) || defined(WIN32) || defined(MSDOS)) \
1788.     && !defined(USE_FCNTL)
1789. #ifdef AMIGA
1790. #define OPENFAILURE(fd) (!fd)
1791.     lockptr = 0;
1792. #else
1793. #define OPENFAILURE(fd) (fd < 0)
1794.     lockptr = -1;
1795. #endif
1796.     while (--retryct && OPENFAILURE(lockptr)) {
1797. #if defined(WIN32) && !defined(WIN_CE)
1798.         lockptr = sopen(lockname, O_RDWR | O_CREAT, SH_DENYRW, S_IWRITE);
1799. #else
1800.         (void) DeleteFile(lockname); /* in case dead process was here first */
1801. #ifdef AMIGA
1802.         lockptr = Open(lockname, MODE_NEWFILE);
1803. #else
1804.         lockptr = open(lockname, O_RDWR | O_CREAT | O_EXCL, S_IWRITE);
1805. #endif
1806. #endif
1807.         if (OPENFAILURE(lockptr)) {
1808.             raw_printf("Waiting for access to %s.  (%d retries left).",
1809.                        filename, retryct);
1810.             Delay(50);
1811.         }
1812.     }
1813.     if (!retryct) {
1814.         raw_printf("I give up.  Sorry.");
1815.         nesting--;
1816.         return FALSE;
1817.     }
1818. #endif /* AMIGA || WIN32 || MSDOS */
1819.     return TRUE;
1820. }
1821. 
1822. #ifdef VMS /* for unlock_file, use the unlink() routine in vmsunix.c */
1823. #ifdef unlink
1824. #undef unlink
1825. #endif
1826. #define unlink(foo) vms_unlink(foo)
1827. #endif
1828. 
1829. /* unlock file, which must be currently locked by lock_file */
1830. void
1831. unlock_file(filename)
1832. const char *filename;
1833. {
1834. #ifndef USE_FCNTL
1835.     char locknambuf[BUFSZ];
1836.     const char *lockname;
1837. #endif
1838. 
1839.     if (nesting == 1) {
1840. #ifdef USE_FCNTL
1841.         sflock.l_type = F_UNLCK;
1842.         if (fcntl(lockfd, F_SETLK, &sflock) == -1) {
1843.             HUP raw_printf("Can't remove fcntl lock on %s.", filename);
1844.             (void) close(lockfd);
1845.         }
1846. #else
1847.         lockname = make_lockname(filename, locknambuf);
1848. #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */
1849.         lockname = fqname(lockname, LOCKPREFIX, 2);
1850. #endif
1851. 
1852. #if defined(UNIX) || defined(VMS)
1853.         if (unlink(lockname) < 0)
1854.             HUP raw_printf("Can't unlink %s.", lockname);
1855. #ifdef NO_FILE_LINKS
1856.         (void) nhclose(lockfd);
1857. #endif
1858. 
1859. #endif /* UNIX || VMS */
1860. 
1861. #if defined(AMIGA) || defined(WIN32) || defined(MSDOS)
1862.         if (lockptr)
1863.             Close(lockptr);
1864.         DeleteFile(lockname);
1865.         lockptr = 0;
1866. #endif /* AMIGA || WIN32 || MSDOS */
1867. #endif /* USE_FCNTL */
1868.     }
1869. 
1870.     nesting--;
1871. }
1872. 
1873. /* ----------  END FILE LOCKING HANDLING ----------- */
1874. 
1875. /* ----------  BEGIN CONFIG FILE HANDLING ----------- */
1876. 
1877. const char *default_configfile =
1878. #ifdef UNIX
1879.     ".nethackrc";
1880. #else
1881. #if defined(MAC) || defined(__BEOS__)
1882.     "NetHack Defaults";
1883. #else
1884. #if defined(MSDOS) || defined(WIN32)
1885.     "defaults.nh";
1886. #else
1887.     "NetHack.cnf";
1888. #endif
1889. #endif
1890. #endif
1891. 
1892. /* used for messaging */
1893. char configfile[BUFSZ];
1894. 
1895. #ifdef MSDOS
1896. /* conflict with speed-dial under windows
1897.  * for XXX.cnf file so support of NetHack.cnf
1898.  * is for backward compatibility only.
1899.  * Preferred name (and first tried) is now defaults.nh but
1900.  * the game will try the old name if there
1901.  * is no defaults.nh.
1902.  */
1903. const char *backward_compat_configfile = "nethack.cnf";
1904. #endif
1905. 
1906. /* remember the name of the file we're accessing;
1907.    if may be used in option reject messages */
1908. STATIC_OVL void
1909. set_configfile_name(fname)
1910. const char *fname;
1911. {
1912.     (void) strncpy(configfile, fname, sizeof configfile - 1);
1913.     configfile[sizeof configfile - 1] = '\0';
1914. }
1915. 
1916. #ifndef MFLOPPY
1917. #define fopenp fopen
1918. #endif
1919. 
1920. STATIC_OVL FILE *
1921. fopen_config_file(filename, src)
1922. const char *filename;
1923. int src;
1924. {
1925.     FILE *fp;
1926. #if defined(UNIX) || defined(VMS)
1927.     char tmp_config[BUFSZ];
1928.     char *envp;
1929. #endif
1930. 
1931.     if (src == SET_IN_SYS) {
1932.         /* SYSCF_FILE; if we can't open it, caller will bail */
1933.         if (filename && *filename) {
1934.             set_configfile_name(fqname(filename, SYSCONFPREFIX, 0));
1935.             fp = fopenp(configfile, "r");
1936.         } else
1937.             fp = (FILE *) 0;
1938.         return  fp;
1939.     }
1940.     /* If src != SET_IN_SYS, "filename" is an environment variable, so it
1941.      * should hang around. If set, it is expected to be a full path name
1942.      * (if relevant)
1943.      */
1944.     if (filename && *filename) {
1945.         set_configfile_name(filename);
1946. #ifdef UNIX
1947.         if (access(configfile, 4) == -1) { /* 4 is R_OK on newer systems */
1948.             /* nasty sneaky attempt to read file through
1949.              * NetHack's setuid permissions -- this is the only
1950.              * place a file name may be wholly under the player's
1951.              * control (but SYSCF_FILE is not under the player's
1952.              * control so it's OK).
1953.              */
1954.             raw_printf("Access to %s denied (%d).", configfile, errno);
1955.             wait_synch();
1956.             /* fall through to standard names */
1957.         } else
1958. #endif
1959.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
1960.             return  fp;
1961. #if defined(UNIX) || defined(VMS)
1962.         } else {
1963.             /* access() above probably caught most problems for UNIX */
1964.             raw_printf("Couldn't open requested config file %s (%d).",
1965.                        configfile, errno);
1966.             wait_synch();
1967. #endif
1968.         }
1969.     }
1970.     /* fall through to standard names */
1971. 
1972. #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32)
1973.     set_configfile_name(fqname(default_configfile, CONFIGPREFIX, 0));
1974.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
1975.         return fp;
1976.     } else if (strcmp(default_configfile, configfile)) {
1977.         set_configfile_name(default_configfile);
1978.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
1979.             return fp;
1980.     }
1981. #ifdef MSDOS
1982.     set_configfile_name(fqname(backward_compat_configfile, CONFIGPREFIX, 0));
1983.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
1984.         return fp;
1985.     } else if (strcmp(backward_compat_configfile, configfile)) {
1986.         set_configfile_name(backward_compat_configfile);
1987.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
1988.             return fp;
1989.     }
1990. #endif
1991. #else
1992. /* constructed full path names don't need fqname() */
1993. #ifdef VMS
1994.     /* no punctuation, so might be a logical name */
1995.     set_configfile_name(fqname("nethackini", CONFIGPREFIX, 0));
1996.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
1997.         return fp;
1998.     set_configfile_name("sys$login:nethack.ini");
1999.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2000.         return fp;
2001. 
2002.     envp = nh_getenv("HOME");
2003.     if (!envp || !*envp)
2004.         Strcpy(tmp_config, "NetHack.cnf");
2005.     else
2006.         Sprintf(tmp_config, "%s%s%s", envp,
2007.                 !index(":]>/", envp[strlen(envp) - 1]) ? "/" : "",
2008.                 "NetHack.cnf");
2009.     set_configfile_name(tmp_config);
2010.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2011.         return fp;
2012. #else /* should be only UNIX left */
2013.     envp = nh_getenv("HOME");
2014.     if (!envp)
2015.         Strcpy(tmp_config, ".nethackrc");
2016.     else
2017.         Sprintf(tmp_config, "%s/%s", envp, ".nethackrc");
2018. 
2019.     set_configfile_name(tmp_config);
2020.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2021.         return fp;
2022. #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX */
2023.     /* try an alternative */
2024.     if (envp) {
2025.         /* OSX-style configuration settings */
2026.         Sprintf(tmp_config, "%s/%s", envp,
2027.                 "Library/Preferences/NetHack Defaults");
2028.         set_configfile_name(tmp_config);
2029.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2030.             return fp;
2031.         /* may be easier for user to edit if filename as '.txt' suffix */
2032.         Sprintf(tmp_config, "%s/%s", envp,
2033.                 "Library/Preferences/NetHack Defaults.txt");
2034.         set_configfile_name(tmp_config);
2035.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2036.             return fp;
2037.     }
2038. #endif /*__APPLE__*/
2039.     if (errno != ENOENT) {
2040.         const char *details;
2041. 
2042.         /* e.g., problems when setuid NetHack can't search home
2043.            directory restricted to user */
2044. #if defined(NHSTDC) && !defined(NOTSTDC)
2045.         if ((details = strerror(errno)) == 0)
2046. #endif
2047.             details = "";
2048.         raw_printf("Couldn't open default config file %s %s(%d).",
2049.                    configfile, details, errno);
2050.         wait_synch();
2051.     }
2052. #endif /* !VMS => Unix */
2053. #endif /* !(MICRO || MAC || __BEOS__ || WIN32) */
2054.     return (FILE *) 0;
2055. }
2056. 
2057. /*
2058.  * Retrieve a list of integers from buf into a uchar array.
2059.  *
2060.  * NOTE: zeros are inserted unless modlist is TRUE, in which case the list
2061.  *  location is unchanged.  Callers must handle zeros if modlist is FALSE.
2062.  */
2063. STATIC_OVL int
2064. get_uchars(bufp, list, modlist, size, name)
2065. char *bufp;       /* current pointer */
2066. uchar *list;      /* return list */
2067. boolean modlist;  /* TRUE: list is being modified in place */
2068. int size;         /* return list size */
2069. const char *name; /* name of option for error message */
2070. {
2071.     unsigned int num = 0;
2072.     int count = 0;
2073.     boolean havenum = FALSE;
2074. 
2075.     while (1) {
2076.         switch (*bufp) {
2077.         case ' ':
2078.         case '\0':
2079.         case '\t':
2080.         case '\n':
2081.             if (havenum) {
2082.                 /* if modifying in place, don't insert zeros */
2083.                 if (num || !modlist)
2084.                     list[count] = num;
2085.                 count++;
2086.                 num = 0;
2087.                 havenum = FALSE;
2088.             }
2089.             if (count == size || !*bufp)
2090.                 return count;
2091.             bufp++;
2092.             break;
2093. 
2094.         case '0':
2095.         case '1':
2096.         case '2':
2097.         case '3':
2098.         case '4':
2099.         case '5':
2100.         case '6':
2101.         case '7':
2102.         case '8':
2103.         case '9':
2104.             havenum = TRUE;
2105.             num = num * 10 + (*bufp - '0');
2106.             bufp++;
2107.             break;
2108. 
2109.         case '\\':
2110.             goto gi_error;
2111.             break;
2112. 
2113.         default:
2114.         gi_error:
2115.             raw_printf("Syntax error in %s", name);
2116.             wait_synch();
2117.             return count;
2118.         }
2119.     }
2120.     /*NOTREACHED*/
2121. }
2122. 
2123. #ifdef NOCWD_ASSUMPTIONS
2124. STATIC_OVL void
2125. adjust_prefix(bufp, prefixid)
2126. char *bufp;
2127. int prefixid;
2128. {
2129.     char *ptr;
2130. 
2131.     if (!bufp)
2132.         return;
2133.     /* Backward compatibility, ignore trailing ;n */
2134.     if ((ptr = index(bufp, ';')) != 0)
2135.         *ptr = '\0';
2136.     if (strlen(bufp) > 0) {
2137.         fqn_prefix[prefixid] = (char *) alloc(strlen(bufp) + 2);
2138.         Strcpy(fqn_prefix[prefixid], bufp);
2139.         append_slash(fqn_prefix[prefixid]);
2140.     }
2141. }
2142. #endif
2143. 
2144. /* Choose at random one of the sep separated parts from str. Mangles str. */
2145. STATIC_OVL char *
2146. choose_random_part(str,sep)
2147. char *str;
2148. char sep;
2149. {
2150.     int nsep = 1;
2151.     int csep;
2152.     int len = 0;
2153.     char *begin = str;
2154. 
2155.     if (!str)
2156.         return (char *) 0;
2157. 
2158.     while (*str) {
2159.         if (*str == sep)
2160.             nsep++;
2161.         str++;
2162.     }
2163.     csep = rn2(nsep);
2164.     str = begin;
2165.     while ((csep > 0) && *str) {
2166.         str++;
2167.         if (*str == sep)
2168.             csep--;
2169.     }
2170.     if (*str) {
2171.         if (*str == sep)
2172.             str++;
2173.         begin = str;
2174.         while (*str && *str != sep) {
2175.             str++;
2176.             len++;
2177.         }
2178.         *str = '\0';
2179.         if (len)
2180.             return begin;
2181.     }
2182.     return (char *) 0;
2183. }
2184. 
2185. STATIC_OVL void
2186. free_config_sections()
2187. {
2188.     if (config_section_chosen) {
2189.         free(config_section_chosen);
2190.         config_section_chosen = NULL;
2191.     }
2192.     if (config_section_current) {
2193.         free(config_section_current);
2194.         config_section_current = NULL;
2195.     }
2196. }
2197. 
2198. STATIC_OVL boolean
2199. is_config_section(str)
2200. const char *str;
2201. {
2202.     const char *a = rindex(str, ']');
2203. 
2204.     return (a && *str == '[' && *(a+1) == '\0' && (int)(a - str) > 0);
2205. }
2206. 
2207. STATIC_OVL boolean
2208. handle_config_section(buf)
2209. char *buf;
2210. {
2211.     if (is_config_section(buf)) {
2212.         char *send;
2213.         if (config_section_current) {
2214.             free(config_section_current);
2215.         }
2216.         config_section_current = dupstr(&buf[1]);
2217.         send = rindex(config_section_current, ']');
2218.         *send = '\0';
2219.         debugpline1("set config section: '%s'", config_section_current);
2220.         return TRUE;
2221.     }
2222. 
2223.     if (config_section_current) {
2224.         if (!config_section_chosen)
2225.             return TRUE;
2226.         if (strcmp(config_section_current, config_section_chosen))
2227.             return TRUE;
2228.     }
2229.     return FALSE;
2230. }
2231. 
2232. #define match_varname(INP, NAM, LEN) match_optname(INP, NAM, LEN, TRUE)
2233. 
2234. /* find the '=' or ':' */
2235. char *
2236. find_optparam(buf)
2237. const char *buf;
2238. {
2239.     char *bufp, *altp;
2240. 
2241.     bufp = index(buf, '=');
2242.     altp = index(buf, ':');
2243.     if (!bufp || (altp && altp < bufp))
2244.         bufp = altp;
2245. 
2246.     return bufp;
2247. }
2248. 
2249. boolean
2250. parse_config_line(origbuf)
2251. char *origbuf;
2252. {
2253. #if defined(MICRO) && !defined(NOCWD_ASSUMPTIONS)
2254.     static boolean ramdisk_specified = FALSE;
2255. #endif
2256. #ifdef SYSCF
2257.     int n;
2258. #endif
2259.     char *bufp, buf[4 * BUFSZ];
2260.     uchar translate[MAXPCHARS];
2261.     int len;
2262.     boolean retval = TRUE;
2263.     int src = iflags.parse_config_file_src;
2264. 
2265.     /* convert any tab to space, condense consecutive spaces into one,
2266.        remove leading and trailing spaces (exception: if there is nothing
2267.        but spaces, one of them will be kept even though it leads/trails) */
2268.     mungspaces(strcpy(buf, origbuf));
2269. 
2270.     /* find the '=' or ':' */
2271.     bufp = find_optparam(buf);
2272.     if (!bufp) {
2273.         config_error_add("Not a config statement, missing '='");
2274.         return FALSE;
2275.     }
2276.     /* skip past '=', then space between it and value, if any */
2277.     ++bufp;
2278.     if (*bufp == ' ')
2279.         ++bufp;
2280. 
2281.     /* Go through possible variables */
2282.     /* some of these (at least LEVELS and SAVE) should now set the
2283.      * appropriate fqn_prefix[] rather than specialized variables
2284.      */
2285.     if (match_varname(buf, "OPTIONS", 4)) {
2286.         /* hack: un-mungspaces to allow consecutive spaces in
2287.            general options until we verify that this is unnecessary;
2288.            '=' or ':' is guaranteed to be present */
2289.         bufp = find_optparam(origbuf);
2290.         ++bufp; /* skip '='; parseoptions() handles spaces */
2291. 
2292.         if (!parseoptions(bufp, TRUE, TRUE))
2293.             retval = FALSE;
2294.     } else if (match_varname(buf, "AUTOPICKUP_EXCEPTION", 5)) {
2295.         add_autopickup_exception(bufp);
2296.     } else if (match_varname(buf, "BINDINGS", 4)) {
2297.         if (!parsebindings(bufp))
2298.             retval = FALSE;
2299.     } else if (match_varname(buf, "AUTOCOMPLETE", 5)) {
2300.         parseautocomplete(bufp, TRUE);
2301.     } else if (match_varname(buf, "MSGTYPE", 7)) {
2302.         if (!msgtype_parse_add(bufp))
2303.             retval = FALSE;
2304. #ifdef NOCWD_ASSUMPTIONS
2305.     } else if (match_varname(buf, "HACKDIR", 4)) {
2306.         adjust_prefix(bufp, HACKPREFIX);
2307.     } else if (match_varname(buf, "LEVELDIR", 4)
2308.                || match_varname(buf, "LEVELS", 4)) {
2309.         adjust_prefix(bufp, LEVELPREFIX);
2310.     } else if (match_varname(buf, "SAVEDIR", 4)) {
2311.         adjust_prefix(bufp, SAVEPREFIX);
2312.     } else if (match_varname(buf, "BONESDIR", 5)) {
2313.         adjust_prefix(bufp, BONESPREFIX);
2314.     } else if (match_varname(buf, "DATADIR", 4)) {
2315.         adjust_prefix(bufp, DATAPREFIX);
2316.     } else if (match_varname(buf, "SCOREDIR", 4)) {
2317.         adjust_prefix(bufp, SCOREPREFIX);
2318.     } else if (match_varname(buf, "LOCKDIR", 4)) {
2319.         adjust_prefix(bufp, LOCKPREFIX);
2320.     } else if (match_varname(buf, "CONFIGDIR", 4)) {
2321.         adjust_prefix(bufp, CONFIGPREFIX);
2322.     } else if (match_varname(buf, "TROUBLEDIR", 4)) {
2323.         adjust_prefix(bufp, TROUBLEPREFIX);
2324. #else /*NOCWD_ASSUMPTIONS*/
2325. #ifdef MICRO
2326.     } else if (match_varname(buf, "HACKDIR", 4)) {
2327.         (void) strncpy(hackdir, bufp, PATHLEN - 1);
2328. #ifdef MFLOPPY
2329.     } else if (match_varname(buf, "RAMDISK", 3)) {
2330. /* The following ifdef is NOT in the wrong
2331.  * place.  For now, we accept and silently
2332.  * ignore RAMDISK */
2333. #ifndef AMIGA
2334.         if (strlen(bufp) >= PATHLEN)
2335.             bufp[PATHLEN - 1] = '\0';
2336.         Strcpy(levels, bufp);
2337.         ramdisk = (strcmp(permbones, levels) != 0);
2338.         ramdisk_specified = TRUE;
2339. #endif
2340. #endif
2341.     } else if (match_varname(buf, "LEVELS", 4)) {
2342.         if (strlen(bufp) >= PATHLEN)
2343.             bufp[PATHLEN - 1] = '\0';
2344.         Strcpy(permbones, bufp);
2345.         if (!ramdisk_specified || !*levels)
2346.             Strcpy(levels, bufp);
2347.         ramdisk = (strcmp(permbones, levels) != 0);
2348.     } else if (match_varname(buf, "SAVE", 4)) {
2349. #ifdef MFLOPPY
2350.         extern int saveprompt;
2351. #endif
2352.         char *ptr;
2353. 
2354.         if ((ptr = index(bufp, ';')) != 0) {
2355.             *ptr = '\0';
2356. #ifdef MFLOPPY
2357.             if (*(ptr + 1) == 'n' || *(ptr + 1) == 'N') {
2358.                 saveprompt = FALSE;
2359.             }
2360. #endif
2361.         }
2362. #if defined(SYSFLAGS) && defined(MFLOPPY)
2363.         else
2364.             saveprompt = sysflags.asksavedisk;
2365. #endif
2366. 
2367.         (void) strncpy(SAVEP, bufp, SAVESIZE - 1);
2368.         append_slash(SAVEP);
2369. #endif /* MICRO */
2370. #endif /*NOCWD_ASSUMPTIONS*/
2371. 
2372.     } else if (match_varname(buf, "NAME", 4)) {
2373.         (void) strncpy(plname, bufp, PL_NSIZ - 1);
2374.     } else if (match_varname(buf, "ROLE", 4)
2375.                || match_varname(buf, "CHARACTER", 4)) {
2376.         if ((len = str2role(bufp)) >= 0)
2377.             flags.initrole = len;
2378.     } else if (match_varname(buf, "DOGNAME", 3)) {
2379.         (void) strncpy(dogname, bufp, PL_PSIZ - 1);
2380.     } else if (match_varname(buf, "CATNAME", 3)) {
2381.         (void) strncpy(catname, bufp, PL_PSIZ - 1);
2382. 
2383. #ifdef SYSCF
2384.     } else if (src == SET_IN_SYS && match_varname(buf, "WIZARDS", 7)) {
2385.         if (sysopt.wizards)
2386.             free((genericptr_t) sysopt.wizards);
2387.         sysopt.wizards = dupstr(bufp);
2388.         if (strlen(sysopt.wizards) && strcmp(sysopt.wizards, "*")) {
2389.             /* pre-format WIZARDS list now; it's displayed during a panic
2390.                and since that panic might be due to running out of memory,
2391.                we don't want to risk attempting to allocate any memory then */
2392.             if (sysopt.fmtd_wizard_list)
2393.                 free((genericptr_t) sysopt.fmtd_wizard_list);
2394.             sysopt.fmtd_wizard_list = build_english_list(sysopt.wizards);
2395.         }
2396.     } else if (src == SET_IN_SYS && match_varname(buf, "SHELLERS", 8)) {
2397.         if (sysopt.shellers)
2398.             free((genericptr_t) sysopt.shellers);
2399.         sysopt.shellers = dupstr(bufp);
2400.     } else if (src == SET_IN_SYS && match_varname(buf, "EXPLORERS", 7)) {
2401.         if (sysopt.explorers)
2402.             free((genericptr_t) sysopt.explorers);
2403.         sysopt.explorers = dupstr(bufp);
2404.     } else if (src == SET_IN_SYS && match_varname(buf, "DEBUGFILES", 5)) {
2405.         /* if showdebug() has already been called (perhaps we've added
2406.            some debugpline() calls to option processing) and has found
2407.            a value for getenv("DEBUGFILES"), don't override that */
2408.         if (sysopt.env_dbgfl <= 0) {
2409.             if (sysopt.debugfiles)
2410.                 free((genericptr_t) sysopt.debugfiles);
2411.             sysopt.debugfiles = dupstr(bufp);
2412.         }
2413.     } else if (src == SET_IN_SYS && match_varname(buf, "DUMPLOGFILE", 7)) {
2414. #ifdef DUMPLOG
2415.         if (sysopt.dumplogfile)
2416.             free((genericptr_t) sysopt.dumplogfile);
2417.         sysopt.dumplogfile = dupstr(bufp);
2418. #endif
2419.     } else if (src == SET_IN_SYS && match_varname(buf, "GENERICUSERS", 12)) {
2420.         if (sysopt.genericusers)
2421.             free((genericptr_t) sysopt.genericusers);
2422.         sysopt.genericusers = dupstr(bufp);
2423.     } else if (src == SET_IN_SYS && match_varname(buf, "BONES_POOLS", 10)) {
2424.         /* max value of 10 guarantees (N % bones.pools) will be one digit
2425.            so we don't lose control of the length of bones file names */
2426.         n = atoi(bufp);
2427.         sysopt.bones_pools = (n <= 0) ? 0 : min(n, 10);
2428.         /* note: right now bones_pools==0 is the same as bones_pools==1,
2429.            but we could change that and make bones_pools==0 become an
2430.            indicator to suppress bones usage altogether */
2431.     } else if (src == SET_IN_SYS && match_varname(buf, "SUPPORT", 7)) {
2432.         if (sysopt.support)
2433.             free((genericptr_t) sysopt.support);
2434.         sysopt.support = dupstr(bufp);
2435.     } else if (src == SET_IN_SYS && match_varname(buf, "RECOVER", 7)) {
2436.         if (sysopt.recover)
2437.             free((genericptr_t) sysopt.recover);
2438.         sysopt.recover = dupstr(bufp);
2439.     } else if (src == SET_IN_SYS
2440.                && match_varname(buf, "CHECK_SAVE_UID", 14)) {
2441.         n = atoi(bufp);
2442.         sysopt.check_save_uid = n;
2443.     } else if (src == SET_IN_SYS
2444.                && match_varname(buf, "CHECK_PLNAME", 12)) {
2445.         n = atoi(bufp);
2446.         sysopt.check_plname = n;
2447.     } else if (match_varname(buf, "SEDUCE", 6)) {
2448.         n = !!atoi(bufp); /* XXX this could be tighter */
2449.         /* allow anyone to turn it off, but only sysconf to turn it on*/
2450.         if (src != SET_IN_SYS && n != 0) {
2451.             config_error_add("Illegal value in SEDUCE");
2452.             return FALSE;
2453.         }
2454.         sysopt.seduce = n;
2455.         sysopt_seduce_set(sysopt.seduce);
2456.     } else if (src == SET_IN_SYS && match_varname(buf, "MAXPLAYERS", 10)) {
2457.         n = atoi(bufp);
2458.         /* XXX to get more than 25, need to rewrite all lock code */
2459.         if (n < 0 || n > 25) {
2460.             config_error_add("Illegal value in MAXPLAYERS (maximum is 25).");
2461.             return FALSE;
2462.         }
2463.         sysopt.maxplayers = n;
2464.     } else if (src == SET_IN_SYS && match_varname(buf, "PERSMAX", 7)) {
2465.         n = atoi(bufp);
2466.         if (n < 1) {
2467.             config_error_add("Illegal value in PERSMAX (minimum is 1).");
2468.             return FALSE;
2469.         }
2470.         sysopt.persmax = n;
2471.     } else if (src == SET_IN_SYS && match_varname(buf, "PERS_IS_UID", 11)) {
2472.         n = atoi(bufp);
2473.         if (n != 0 && n != 1) {
2474.             config_error_add("Illegal value in PERS_IS_UID (must be 0 or 1).");
2475.             return FALSE;
2476.         }
2477.         sysopt.pers_is_uid = n;
2478.     } else if (src == SET_IN_SYS && match_varname(buf, "ENTRYMAX", 8)) {
2479.         n = atoi(bufp);
2480.         if (n < 10) {
2481.             config_error_add("Illegal value in ENTRYMAX (minimum is 10).");
2482.             return FALSE;
2483.         }
2484.         sysopt.entrymax = n;
2485.     } else if ((src == SET_IN_SYS) && match_varname(buf, "POINTSMIN", 9)) {
2486.         n = atoi(bufp);
2487.         if (n < 1) {
2488.             config_error_add("Illegal value in POINTSMIN (minimum is 1).");
2489.             return FALSE;
2490.         }
2491.         sysopt.pointsmin = n;
2492.     } else if (src == SET_IN_SYS
2493.                && match_varname(buf, "MAX_STATUENAME_RANK", 10)) {
2494.         n = atoi(bufp);
2495.         if (n < 1) {
2496.             config_error_add(
2497.                       "Illegal value in MAX_STATUENAME_RANK (minimum is 1).");
2498.             return FALSE;
2499.         }
2500.         sysopt.tt_oname_maxrank = n;
2501. 
2502.     /* SYSCF PANICTRACE options */
2503.     } else if (src == SET_IN_SYS
2504.                && match_varname(buf, "PANICTRACE_LIBC", 15)) {
2505.         n = atoi(bufp);
2506. #if defined(PANICTRACE) && defined(PANICTRACE_LIBC)
2507.         if (n < 0 || n > 2) {
2508.             config_error_add("Illegal value in PANICTRACE_LIBC (not 0,1,2).");
2509.             return FALSE;
2510.         }
2511. #endif
2512.         sysopt.panictrace_libc = n;
2513.     } else if (src == SET_IN_SYS
2514.                && match_varname(buf, "PANICTRACE_GDB", 14)) {
2515.         n = atoi(bufp);
2516. #if defined(PANICTRACE)
2517.         if (n < 0 || n > 2) {
2518.             config_error_add("Illegal value in PANICTRACE_GDB (not 0,1,2).");
2519.             return FALSE;
2520.         }
2521. #endif
2522.         sysopt.panictrace_gdb = n;
2523.     } else if (src == SET_IN_SYS && match_varname(buf, "GDBPATH", 7)) {
2524. #if defined(PANICTRACE) && !defined(VMS)
2525.         if (!file_exists(bufp)) {
2526.             config_error_add("File specified in GDBPATH does not exist.");
2527.             return FALSE;
2528.         }
2529. #endif
2530.         if (sysopt.gdbpath)
2531.             free((genericptr_t) sysopt.gdbpath);
2532.         sysopt.gdbpath = dupstr(bufp);
2533.     } else if (src == SET_IN_SYS && match_varname(buf, "GREPPATH", 7)) {
2534. #if defined(PANICTRACE) && !defined(VMS)
2535.         if (!file_exists(bufp)) {
2536.             config_error_add("File specified in GREPPATH does not exist.");
2537.             return FALSE;
2538.         }
2539. #endif
2540.         if (sysopt.greppath)
2541.             free((genericptr_t) sysopt.greppath);
2542.         sysopt.greppath = dupstr(bufp);
2543. #endif /* SYSCF */
2544. 
2545.     } else if (match_varname(buf, "BOULDER", 3)) {
2546.         (void) get_uchars(bufp, &iflags.bouldersym, TRUE, 1,
2547.                           "BOULDER");
2548.     } else if (match_varname(buf, "MENUCOLOR", 9)) {
2549.         if (!add_menu_coloring(bufp))
2550.             retval = FALSE;
2551.     } else if (match_varname(buf, "HILITE_STATUS", 6)) {
2552. #ifdef STATUS_HILITES
2553.         if (!parse_status_hl1(bufp, TRUE))
2554.             retval = FALSE;
2555. #endif
2556.     } else if (match_varname(buf, "WARNINGS", 5)) {
2557.         (void) get_uchars(bufp, translate, FALSE, WARNCOUNT,
2558.                           "WARNINGS");
2559.         assign_warnings(translate);
2560.     } else if (match_varname(buf, "SYMBOLS", 4)) {
2561.         if (!parsesymbols(bufp)) {
2562.             config_error_add("Error in SYMBOLS definition '%s'", bufp);
2563.             retval = FALSE;
2564.         }
2565.         switch_symbols(TRUE);
2566.     } else if (match_varname(buf, "WIZKIT", 6)) {
2567.         (void) strncpy(wizkit, bufp, WIZKIT_MAX - 1);
2568. #ifdef AMIGA
2569.     } else if (match_varname(buf, "FONT", 4)) {
2570.         char *t;
2571. 
2572.         if (t = strchr(buf + 5, ':')) {
2573.             *t = 0;
2574.             amii_set_text_font(buf + 5, atoi(t + 1));
2575.             *t = ':';
2576.         }
2577.     } else if (match_varname(buf, "PATH", 4)) {
2578.         (void) strncpy(PATH, bufp, PATHLEN - 1);
2579.     } else if (match_varname(buf, "DEPTH", 5)) {
2580.         extern int amii_numcolors;
2581.         int val = atoi(bufp);
2582. 
2583.         amii_numcolors = 1L << min(DEPTH, val);
2584. #ifdef SYSFLAGS
2585.     } else if (match_varname(buf, "DRIPENS", 7)) {
2586.         int i, val;
2587.         char *t;
2588. 
2589.         for (i = 0, t = strtok(bufp, ",/"); t != (char *) 0;
2590.              i < 20 && (t = strtok((char *) 0, ",/")), ++i) {
2591.             sscanf(t, "%d", &val);
2592.             sysflags.amii_dripens[i] = val;
2593.         }
2594. #endif
2595.     } else if (match_varname(buf, "SCREENMODE", 10)) {
2596.         extern long amii_scrnmode;
2597. 
2598.         if (!stricmp(bufp, "req"))
2599.             amii_scrnmode = 0xffffffff; /* Requester */
2600.         else if (sscanf(bufp, "%x", &amii_scrnmode) != 1)
2601.             amii_scrnmode = 0;
2602.     } else if (match_varname(buf, "MSGPENS", 7)) {
2603.         extern int amii_msgAPen, amii_msgBPen;
2604.         char *t = strtok(bufp, ",/");
2605. 
2606.         if (t) {
2607.             sscanf(t, "%d", &amii_msgAPen);
2608.             if (t = strtok((char *) 0, ",/"))
2609.                 sscanf(t, "%d", &amii_msgBPen);
2610.         }
2611.     } else if (match_varname(buf, "TEXTPENS", 8)) {
2612.         extern int amii_textAPen, amii_textBPen;
2613.         char *t = strtok(bufp, ",/");
2614. 
2615.         if (t) {
2616.             sscanf(t, "%d", &amii_textAPen);
2617.             if (t = strtok((char *) 0, ",/"))
2618.                 sscanf(t, "%d", &amii_textBPen);
2619.         }
2620.     } else if (match_varname(buf, "MENUPENS", 8)) {
2621.         extern int amii_menuAPen, amii_menuBPen;
2622.         char *t = strtok(bufp, ",/");
2623. 
2624.         if (t) {
2625.             sscanf(t, "%d", &amii_menuAPen);
2626.             if (t = strtok((char *) 0, ",/"))
2627.                 sscanf(t, "%d", &amii_menuBPen);
2628.         }
2629.     } else if (match_varname(buf, "STATUSPENS", 10)) {
2630.         extern int amii_statAPen, amii_statBPen;
2631.         char *t = strtok(bufp, ",/");
2632. 
2633.         if (t) {
2634.             sscanf(t, "%d", &amii_statAPen);
2635.             if (t = strtok((char *) 0, ",/"))
2636.                 sscanf(t, "%d", &amii_statBPen);
2637.         }
2638.     } else if (match_varname(buf, "OTHERPENS", 9)) {
2639.         extern int amii_otherAPen, amii_otherBPen;
2640.         char *t = strtok(bufp, ",/");
2641. 
2642.         if (t) {
2643.             sscanf(t, "%d", &amii_otherAPen);
2644.             if (t = strtok((char *) 0, ",/"))
2645.                 sscanf(t, "%d", &amii_otherBPen);
2646.         }
2647.     } else if (match_varname(buf, "PENS", 4)) {
2648.         extern unsigned short amii_init_map[AMII_MAXCOLORS];
2649.         int i;
2650.         char *t;
2651. 
2652.         for (i = 0, t = strtok(bufp, ",/");
2653.              i < AMII_MAXCOLORS && t != (char *) 0;
2654.              t = strtok((char *) 0, ",/"), ++i) {
2655.             sscanf(t, "%hx", &amii_init_map[i]);
2656.         }
2657.         amii_setpens(amii_numcolors = i);
2658.     } else if (match_varname(buf, "FGPENS", 6)) {
2659.         extern int foreg[AMII_MAXCOLORS];
2660.         int i;
2661.         char *t;
2662. 
2663.         for (i = 0, t = strtok(bufp, ",/");
2664.              i < AMII_MAXCOLORS && t != (char *) 0;
2665.              t = strtok((char *) 0, ",/"), ++i) {
2666.             sscanf(t, "%d", &foreg[i]);
2667.         }
2668.     } else if (match_varname(buf, "BGPENS", 6)) {
2669.         extern int backg[AMII_MAXCOLORS];
2670.         int i;
2671.         char *t;
2672. 
2673.         for (i = 0, t = strtok(bufp, ",/");
2674.              i < AMII_MAXCOLORS && t != (char *) 0;
2675.              t = strtok((char *) 0, ",/"), ++i) {
2676.             sscanf(t, "%d", &backg[i]);
2677.         }
2678. #endif /*AMIGA*/
2679. #ifdef USER_SOUNDS
2680.     } else if (match_varname(buf, "SOUNDDIR", 8)) {
2681.         sounddir = dupstr(bufp);
2682.     } else if (match_varname(buf, "SOUND", 5)) {
2683.         add_sound_mapping(bufp);
2684. #endif
2685.     } else if (match_varname(buf, "QT_TILEWIDTH", 12)) {
2686. #ifdef QT_GRAPHICS
2687.         extern char *qt_tilewidth;
2688. 
2689.         if (qt_tilewidth == NULL)
2690.             qt_tilewidth = dupstr(bufp);
2691. #endif
2692.     } else if (match_varname(buf, "QT_TILEHEIGHT", 13)) {
2693. #ifdef QT_GRAPHICS
2694.         extern char *qt_tileheight;
2695. 
2696.         if (qt_tileheight == NULL)
2697.             qt_tileheight = dupstr(bufp);
2698. #endif
2699.     } else if (match_varname(buf, "QT_FONTSIZE", 11)) {
2700. #ifdef QT_GRAPHICS
2701.         extern char *qt_fontsize;
2702. 
2703.         if (qt_fontsize == NULL)
2704.             qt_fontsize = dupstr(bufp);
2705. #endif
2706.     } else if (match_varname(buf, "QT_COMPACT", 10)) {
2707. #ifdef QT_GRAPHICS
2708.         extern int qt_compact_mode;
2709. 
2710.         qt_compact_mode = atoi(bufp);
2711. #endif
2712.     } else {
2713.         config_error_add("Unknown config statement");
2714.         return FALSE;
2715.     }
2716.     return retval;
2717. }
2718. 
2719. #ifdef USER_SOUNDS
2720. boolean
2721. can_read_file(filename)
2722. const char *filename;
2723. {
2724.     return (boolean) (access(filename, 4) == 0);
2725. }
2726. #endif /* USER_SOUNDS */
2727. 
2728. struct _config_error_frame {
2729.     int line_num;
2730.     int num_errors;
2731.     boolean origline_shown;
2732.     boolean fromfile;
2733.     boolean secure;
2734.     char origline[4 * BUFSZ];
2735.     char source[BUFSZ];
2736.     struct _config_error_frame *next;
2737. };
2738. 
2739. static struct _config_error_frame *config_error_data = 0;
2740. 
2741. void
2742. config_error_init(from_file, sourcename, secure)
2743. boolean from_file;
2744. const char *sourcename;
2745. boolean secure;
2746. {
2747.     struct _config_error_frame *tmp = (struct _config_error_frame *)
2748.         alloc(sizeof (struct _config_error_frame));
2749. 
2750.     tmp->line_num = 0;
2751.     tmp->num_errors = 0;
2752.     tmp->origline_shown = FALSE;
2753.     tmp->fromfile = from_file;
2754.     tmp->secure = secure;
2755.     tmp->origline[0] = '\0';
2756.     if (sourcename && sourcename[0]) {
2757.         (void) strncpy(tmp->source, sourcename, sizeof (tmp->source) - 1);
2758.         tmp->source[sizeof (tmp->source) - 1] = '\0';
2759.     } else
2760.         tmp->source[0] = '\0';
2761. 
2762.     tmp->next = config_error_data;
2763.     config_error_data = tmp;
2764. }
2765. 
2766. STATIC_OVL boolean
2767. config_error_nextline(line)
2768. const char *line;
2769. {
2770.     struct _config_error_frame *ced = config_error_data;
2771. 
2772.     if (!ced)
2773.         return FALSE;
2774. 
2775.     if (ced->num_errors && ced->secure)
2776.         return FALSE;
2777. 
2778.     ced->line_num++;
2779.     ced->origline_shown = FALSE;
2780.     if (line && line[0]) {
2781.         (void) strncpy(ced->origline, line, sizeof (ced->origline) - 1);
2782.         ced->origline[sizeof (ced->origline) - 1] = '\0';
2783.     } else
2784.         ced->origline[0] = '\0';
2785. 
2786.     return TRUE;
2787. }
2788. 
2789. /* varargs 'config_error_add()' moved to pline.c */
2790. void
2791. config_erradd(buf)
2792. const char *buf;
2793. {
2794.     char lineno[QBUFSZ];
2795. 
2796.     if (!buf || !*buf)
2797.         buf = "Unknown error";
2798. 
2799.     if (!config_error_data) {
2800.         /* either very early, where pline() will use raw_print(), or
2801.            player gave bad value when prompted by interactive 'O' command */
2802.         pline("%s%s.", !iflags.window_inited ? "config_error_add: " : "", buf);
2803.         wait_synch();
2804.         return;
2805.     }
2806. 
2807.     config_error_data->num_errors++;
2808.     if (!config_error_data->origline_shown && !config_error_data->secure) {
2809.         pline("\n%s", config_error_data->origline);
2810.         config_error_data->origline_shown = TRUE;
2811.     }
2812.     if (config_error_data->line_num > 0 && !config_error_data->secure) {
2813.         Sprintf(lineno, "Line %d: ", config_error_data->line_num);
2814.     } else
2815.         lineno[0] = '\0';
2816. 
2817.     pline("%s %s%s.", config_error_data->secure ? "Error:" : " *",
2818.           lineno, buf);
2819. }
2820. 
2821. int
2822. config_error_done()
2823. {
2824.     int n;
2825.     struct _config_error_frame *tmp = config_error_data;
2826. 
2827.     if (!config_error_data)
2828.         return 0;
2829.     n = config_error_data->num_errors;
2830.     if (n) {
2831.         pline("\n%d error%s in %s.\n", n,
2832.                    (n > 1) ? "s" : "",
2833.                    *config_error_data->source
2834.               ? config_error_data->source : configfile);
2835.         wait_synch();
2836.     }
2837.     config_error_data = tmp->next;
2838.     free(tmp);
2839.     return n;
2840. }
2841. 
2842. boolean
2843. read_config_file(filename, src)
2844. const char *filename;
2845. int src;
2846. {
2847.     FILE *fp;
2848.     boolean rv = TRUE;
2849. 
2850.     if (!(fp = fopen_config_file(filename, src)))
2851.         return FALSE;
2852. 
2853.     /* begin detection of duplicate configfile options */
2854.     set_duplicate_opt_detection(1);
2855.     free_config_sections();
2856.     iflags.parse_config_file_src = src;
2857. 
2858.     rv = parse_conf_file(fp, parse_config_line);
2859.     (void) fclose(fp);
2860. 
2861.     free_config_sections();
2862.     /* turn off detection of duplicate configfile options */
2863.     set_duplicate_opt_detection(0);
2864.     return rv;
2865. }
2866. 
2867. STATIC_OVL FILE *
2868. fopen_wizkit_file()
2869. {
2870.     FILE *fp;
2871. #if defined(VMS) || defined(UNIX)
2872.     char tmp_wizkit[BUFSZ];
2873. #endif
2874.     char *envp;
2875. 
2876.     envp = nh_getenv("WIZKIT");
2877.     if (envp && *envp)
2878.         (void) strncpy(wizkit, envp, WIZKIT_MAX - 1);
2879.     if (!wizkit[0])
2880.         return (FILE *) 0;
2881. 
2882. #ifdef UNIX
2883.     if (access(wizkit, 4) == -1) {
2884.         /* 4 is R_OK on newer systems */
2885.         /* nasty sneaky attempt to read file through
2886.          * NetHack's setuid permissions -- this is a
2887.          * place a file name may be wholly under the player's
2888.          * control
2889.          */
2890.         raw_printf("Access to %s denied (%d).", wizkit, errno);
2891.         wait_synch();
2892.         /* fall through to standard names */
2893.     } else
2894. #endif
2895.         if ((fp = fopenp(wizkit, "r")) != (FILE *) 0) {
2896.         return fp;
2897. #if defined(UNIX) || defined(VMS)
2898.     } else {
2899.         /* access() above probably caught most problems for UNIX */
2900.         raw_printf("Couldn't open requested config file %s (%d).", wizkit,
2901.                    errno);
2902.         wait_synch();
2903. #endif
2904.     }
2905. 
2906. #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32)
2907.     if ((fp = fopenp(fqname(wizkit, CONFIGPREFIX, 0), "r")) != (FILE *) 0)
2908.         return fp;
2909. #else
2910. #ifdef VMS
2911.     envp = nh_getenv("HOME");
2912.     if (envp)
2913.         Sprintf(tmp_wizkit, "%s%s", envp, wizkit);
2914.     else
2915.         Sprintf(tmp_wizkit, "%s%s", "sys$login:", wizkit);
2916.     if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0)
2917.         return fp;
2918. #else /* should be only UNIX left */
2919.     envp = nh_getenv("HOME");
2920.     if (envp)
2921.         Sprintf(tmp_wizkit, "%s/%s", envp, wizkit);
2922.     else
2923.         Strcpy(tmp_wizkit, wizkit);
2924.     if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0)
2925.         return fp;
2926.     else if (errno != ENOENT) {
2927.         /* e.g., problems when setuid NetHack can't search home
2928.          * directory restricted to user */
2929.         raw_printf("Couldn't open default wizkit file %s (%d).", tmp_wizkit,
2930.                    errno);
2931.         wait_synch();
2932.     }
2933. #endif
2934. #endif
2935.     return (FILE *) 0;
2936. }
2937. 
2938. /* add to hero's inventory if there's room, otherwise put item on floor */
2939. STATIC_DCL void
2940. wizkit_addinv(obj)
2941. struct obj *obj;
2942. {
2943.     if (!obj || obj == &zeroobj)
2944.         return;
2945. 
2946.     /* subset of starting inventory pre-ID */
2947.     obj->dknown = 1;
2948.     if (Role_if(PM_PRIEST))
2949.         obj->bknown = 1;
2950.     /* same criteria as lift_object()'s check for available inventory slot */
2951.     if (obj->oclass != COIN_CLASS && inv_cnt(FALSE) >= 52
2952.         && !merge_choice(invent, obj)) {
2953.         /* inventory overflow; can't just place & stack object since
2954.            hero isn't in position yet, so schedule for arrival later */
2955.         add_to_migration(obj);
2956.         obj->ox = 0; /* index of main dungeon */
2957.         obj->oy = 1; /* starting level number */
2958.         obj->owornmask =
2959.             (long) (MIGR_WITH_HERO | MIGR_NOBREAK | MIGR_NOSCATTER);
2960.     } else {
2961.         (void) addinv(obj);
2962.     }
2963. }
2964. 
2965. 
2966. boolean
2967. proc_wizkit_line(buf)
2968. char *buf;
2969. {
2970.     struct obj *otmp = readobjnam(buf, (struct obj *) 0);
2971. 
2972.     if (otmp) {
2973.         if (otmp != &zeroobj)
2974.             wizkit_addinv(otmp);
2975.     } else {
2976.         /* .60 limits output line width to 79 chars */
2977.         config_error_add("Bad wizkit item: \"%.60s\"", buf);
2978.         return FALSE;
2979.     }
2980.     return TRUE;
2981. }
2982. 
2983. void
2984. read_wizkit()
2985. {
2986.     FILE *fp;
2987. 
2988.     if (!wizard || !(fp = fopen_wizkit_file()))
2989.         return;
2990. 
2991.     program_state.wizkit_wishing = 1;
2992.     config_error_init(TRUE, "WIZKIT", FALSE);
2993. 
2994.     parse_conf_file(fp, proc_wizkit_line);
2995.     (void) fclose(fp);
2996. 
2997.     config_error_done();
2998.     program_state.wizkit_wishing = 0;
2999. 
3000.     return;
3001. }
3002. 
3003. /* parse_conf_file
3004.  *
3005.  * Read from file fp, handling comments, empty lines, config sections,
3006.  * CHOOSE, and line continuation, calling proc for every valid line.
3007.  *
3008.  * Continued lines are merged together with one space in between.
3009.  */
3010. STATIC_OVL boolean
3011. parse_conf_file(fp, proc)
3012. FILE *fp;
3013. boolean FDECL((*proc), (char *));
3014. {
3015.     char inbuf[4 * BUFSZ];
3016.     boolean rv = TRUE; /* assume successful parse */
3017.     char *ep;
3018.     boolean skip = FALSE, morelines = FALSE;
3019.     char *buf = (char *) 0;
3020.     size_t inbufsz = sizeof inbuf;
3021. 
3022.     free_config_sections();
3023. 
3024.     while (fgets(inbuf, (int) inbufsz, fp)) {
3025.         ep = index(inbuf, '\n');
3026.         if (skip) { /* in case previous line was too long */
3027.             if (ep)
3028.                 skip = FALSE; /* found newline; next line is normal */
3029.         } else {
3030.             if (!ep) {  /* newline missing */
3031.                 if (strlen(inbuf) < (inbufsz - 2)) {
3032.                     /* likely the last line of file is just
3033.                        missing a newline; process it anyway  */
3034.                     ep = eos(inbuf);
3035.                 } else {
3036.                     config_error_add("Line too long, skipping");
3037.                     skip = TRUE; /* discard next fgets */
3038.                 }
3039.             } else {
3040.                 *ep = '\0'; /* remove newline */
3041.             }
3042.             if (ep) {
3043.                 char *tmpbuf = (char *) 0;
3044.                 int len;
3045.                 boolean ignoreline = FALSE;
3046.                 boolean oldline = FALSE;
3047. 
3048.                 /* line continuation (trailing '\') */
3049.                 morelines = (--ep >= inbuf && *ep == '\\');
3050.                 if (morelines)
3051.                     *ep = '\0';
3052. 
3053.                 /* trim off spaces at end of line */
3054.                 while (--ep >= inbuf
3055.                        && (*ep == ' ' || *ep == '\t' || *ep == '\r'))
3056.                     *ep = '\0';
3057. 
3058.                 if (!config_error_nextline(inbuf)) {
3059.                     rv = FALSE;
3060.                     if (buf)
3061.                         free(buf), buf = (char *) 0;
3062.                     break;
3063.                 }
3064. 
3065.                 ep = inbuf;
3066.                 while (*ep == ' ' || *ep == '\t') ep++;
3067. 
3068.                 /* lines beginning with '#' are comments. ignore empty lines. */
3069.                 if (!*ep || *ep == '#')
3070.                     ignoreline = TRUE;
3071. 
3072.                 if (buf)
3073.                     oldline = TRUE;
3074. 
3075.                 /* merge now read line with previous ones, if necessary */
3076.                 if (!ignoreline) {
3077.                     len = strlen(inbuf) + 1;
3078.                     if (buf)
3079.                         len += strlen(buf);
3080.                     tmpbuf = (char *) alloc(len);
3081.                     if (buf) {
3082.                         Sprintf(tmpbuf, "%s %s", buf, inbuf);
3083.                         free(buf);
3084.                     } else
3085.                         Strcpy(tmpbuf, inbuf);
3086.                     buf = tmpbuf;
3087.                 }
3088. 
3089.                 if (morelines || (ignoreline && !oldline))
3090.                     continue;
3091. 
3092.                 if (handle_config_section(ep)) {
3093.                     free(buf);
3094.                     buf = (char *) 0;
3095.                     continue;
3096.                 }
3097. 
3098.                 /* from here onwards, we'll handle buf only */
3099. 
3100.                 if (match_varname(buf, "CHOOSE", 6)) {
3101.                     char *section;
3102.                     char *bufp = find_optparam(buf);
3103.                     if (!bufp) {
3104.                         config_error_add(
3105.                                     "Format is CHOOSE=section1,section2,...");
3106.                         rv = FALSE;
3107.                         free(buf);
3108.                         buf = (char *) 0;
3109.                         continue;
3110.                     }
3111.                     bufp++;
3112.                     if (config_section_chosen)
3113.                         free(config_section_chosen);
3114.                     section = choose_random_part(bufp, ',');
3115.                     if (section)
3116.                         config_section_chosen = dupstr(section);
3117.                     else {
3118.                         config_error_add("No config section to choose");
3119.                         rv = FALSE;
3120.                     }
3121.                     free(buf);
3122.                     buf = (char *) 0;
3123.                     continue;
3124.                 }
3125. 
3126.                 if (!proc(buf))
3127.                     rv = FALSE;
3128. 
3129.                 free(buf);
3130.                 buf = (char *) 0;
3131.             }
3132.         }
3133.     }
3134. 
3135.     if (buf)
3136.         free(buf);
3137. 
3138.     free_config_sections();
3139.     return rv;
3140. }
3141. 
3142. extern struct symsetentry *symset_list;  /* options.c */
3143. extern struct symparse loadsyms[];       /* drawing.c */
3144. extern const char *known_handling[];     /* drawing.c */
3145. extern const char *known_restrictions[]; /* drawing.c */
3146. static int symset_count = 0;             /* for pick-list building only */
3147. static boolean chosen_symset_start = FALSE, chosen_symset_end = FALSE;
3148. static int symset_which_set = 0;
3149. 
3150. STATIC_OVL
3151. FILE *
3152. fopen_sym_file()
3153. {
3154.     FILE *fp;
3155. 
3156.     fp = fopen_datafile(SYMBOLS, "r", HACKPREFIX);
3157.     return fp;
3158. }
3159. 
3160. /*
3161.  * Returns 1 if the chose symset was found and loaded.
3162.  *         0 if it wasn't found in the sym file or other problem.
3163.  */
3164. int
3165. read_sym_file(which_set)
3166. int which_set;
3167. {
3168.     FILE *fp;
3169. 
3170.     if (!(fp = fopen_sym_file()))
3171.         return 0;
3172. 
3173.     symset_count = 0;
3174.     chosen_symset_start = chosen_symset_end = FALSE;
3175.     symset_which_set = which_set;
3176. 
3177.     config_error_init(TRUE, "symbols", FALSE);
3178. 
3179.     parse_conf_file(fp, proc_symset_line);
3180.     (void) fclose(fp);
3181. 
3182.     if (!chosen_symset_start && !chosen_symset_end) {
3183.         /* name caller put in symset[which_set].name was not found;
3184.            if it looks like "Default symbols", null it out and return
3185.            success to use the default; otherwise, return failure */
3186.         if (symset[which_set].name
3187.             && (fuzzymatch(symset[which_set].name, "Default symbols",
3188.                            " -_", TRUE)
3189.                 || !strcmpi(symset[which_set].name, "default")))
3190.             clear_symsetentry(which_set, TRUE);
3191.         config_error_done();
3192.         return (symset[which_set].name == 0) ? 1 : 0;
3193.     }
3194.     if (!chosen_symset_end)
3195.         config_error_add("Missing finish for symset \"%s\"",
3196.                          symset[which_set].name ? symset[which_set].name
3197.                                                 : "unknown");
3198.     config_error_done();
3199.     return 1;
3200. }
3201. 
3202. boolean
3203. proc_symset_line(buf)
3204. char *buf;
3205. {
3206.     return !((boolean) parse_sym_line(buf, symset_which_set));
3207. }
3208. 
3209. /* returns 0 on error */
3210. int
3211. parse_sym_line(buf, which_set)
3212. char *buf;
3213. int which_set;
3214. {
3215.     int val, i;
3216.     struct symparse *symp = (struct symparse *) 0;
3217.     char *bufp, *commentp, *altp;
3218. 
3219.     /* convert each instance of whitespace (tabs, consecutive spaces)
3220.        into a single space; leading and trailing spaces are stripped */
3221.     mungspaces(buf);
3222. 
3223.     /* remove trailing comment, if any (this isn't strictly needed for
3224.        individual symbols, and it won't matter if "X#comment" without
3225.        separating space slips through; for handling or set description,
3226.        symbol set creator is responsible for preceding '#' with a space
3227.        and that comment itself doesn't contain " #") */
3228.     if ((commentp = rindex(buf, '#')) != 0 && commentp[-1] == ' ')
3229.         commentp[-1] = '\0';
3230. 
3231.     /* find the '=' or ':' */
3232.     bufp = index(buf, '=');
3233.     altp = index(buf, ':');
3234.     if (!bufp || (altp && altp < bufp))
3235.         bufp = altp;
3236.     if (!bufp) {
3237.         if (strncmpi(buf, "finish", 6) == 0) {
3238.             /* end current graphics set */
3239.             if (chosen_symset_start)
3240.                 chosen_symset_end = TRUE;
3241.             chosen_symset_start = FALSE;
3242.             return 1;
3243.         }
3244.         config_error_add("No \"finish\"");
3245.         return 0;
3246.     }
3247.     /* skip '=' and space which follows, if any */
3248.     ++bufp;
3249.     if (*bufp == ' ')
3250.         ++bufp;
3251. 
3252.     symp = match_sym(buf);
3253.     if (!symp) {
3254.         config_error_add("Unknown sym keyword");
3255.         return 0;
3256.     }
3257. 
3258.     if (!symset[which_set].name) {
3259.         /* A null symset name indicates that we're just
3260.            building a pick-list of possible symset
3261.            values from the file, so only do that */
3262.         if (symp->range == SYM_CONTROL) {
3263.             struct symsetentry *tmpsp;
3264. 
3265.             switch (symp->idx) {
3266.             case 0:
3267.                 tmpsp = (struct symsetentry *) alloc(sizeof *tmpsp);
3268.                 tmpsp->next = symset_list;
3269.                 symset_list = tmpsp;
3270.                 tmpsp->idx = symset_count++;
3271.                 tmpsp->name = dupstr(bufp);
3272.                 tmpsp->desc = (char *) 0;
3273.                 tmpsp->handling = H_UNK;
3274.                 /* initialize restriction bits */
3275.                 tmpsp->nocolor = 0;
3276.                 tmpsp->primary = 0;
3277.                 tmpsp->rogue = 0;
3278.                 break;
3279.             case 2:
3280.                 /* handler type identified */
3281.                 tmpsp = symset_list; /* most recent symset */
3282.                 for (i = 0; known_handling[i]; ++i)
3283.                     if (!strcmpi(known_handling[i], bufp)) {
3284.                         tmpsp->handling = i;
3285.                         break; /* for loop */
3286.                     }
3287.                 break;
3288.             case 3:                  /* description:something */
3289.                 tmpsp = symset_list; /* most recent symset */
3290.                 if (tmpsp && !tmpsp->desc)
3291.                     tmpsp->desc = dupstr(bufp);
3292.                 break;
3293.             case 5:
3294.                 /* restrictions: xxxx*/
3295.                 tmpsp = symset_list; /* most recent symset */
3296.                 for (i = 0; known_restrictions[i]; ++i) {
3297.                     if (!strcmpi(known_restrictions[i], bufp)) {
3298.                         switch (i) {
3299.                         case 0:
3300.                             tmpsp->primary = 1;
3301.                             break;
3302.                         case 1:
3303.                             tmpsp->rogue = 1;
3304.                             break;
3305.                         }
3306.                         break; /* while loop */
3307.                     }
3308.                 }
3309.                 break;
3310.             }
3311.         }
3312.         return 1;
3313.     }
3314.     if (symp->range) {
3315.         if (symp->range == SYM_CONTROL) {
3316.             switch (symp->idx) {
3317.             case 0:
3318.                 /* start of symset */
3319.                 if (!strcmpi(bufp, symset[which_set].name)) {
3320.                     /* matches desired one */
3321.                     chosen_symset_start = TRUE;
3322.                     /* these init_*() functions clear symset fields too */
3323.                     if (which_set == ROGUESET)
3324.                         init_r_symbols();
3325.                     else if (which_set == PRIMARY)
3326.                         init_l_symbols();
3327.                 }
3328.                 break;
3329.             case 1:
3330.                 /* finish symset */
3331.                 if (chosen_symset_start)
3332.                     chosen_symset_end = TRUE;
3333.                 chosen_symset_start = FALSE;
3334.                 break;
3335.             case 2:
3336.                 /* handler type identified */
3337.                 if (chosen_symset_start)
3338.                     set_symhandling(bufp, which_set);
3339.                 break;
3340.             /* case 3: (description) is ignored here */
3341.             case 4: /* color:off */
3342.                 if (chosen_symset_start) {
3343.                     if (bufp) {
3344.                         if (!strcmpi(bufp, "true") || !strcmpi(bufp, "yes")
3345.                             || !strcmpi(bufp, "on"))
3346.                             symset[which_set].nocolor = 0;
3347.                         else if (!strcmpi(bufp, "false")
3348.                                  || !strcmpi(bufp, "no")
3349.                                  || !strcmpi(bufp, "off"))
3350.                             symset[which_set].nocolor = 1;
3351.                     }
3352.                 }
3353.                 break;
3354.             case 5: /* restrictions: xxxx*/
3355.                 if (chosen_symset_start) {
3356.                     int n = 0;
3357. 
3358.                     while (known_restrictions[n]) {
3359.                         if (!strcmpi(known_restrictions[n], bufp)) {
3360.                             switch (n) {
3361.                             case 0:
3362.                                 symset[which_set].primary = 1;
3363.                                 break;
3364.                             case 1:
3365.                                 symset[which_set].rogue = 1;
3366.                                 break;
3367.                             }
3368.                             break; /* while loop */
3369.                         }
3370.                         n++;
3371.                     }
3372.                 }
3373.                 break;
3374.             }
3375.         } else { /* !SYM_CONTROL */
3376.             val = sym_val(bufp);
3377.             if (chosen_symset_start) {
3378.                 if (which_set == PRIMARY) {
3379.                     update_l_symset(symp, val);
3380.                 } else if (which_set == ROGUESET) {
3381.                     update_r_symset(symp, val);
3382.                 }
3383.             }
3384.         }
3385.     }
3386.     return 1;
3387. }
3388. 
3389. STATIC_OVL void
3390. set_symhandling(handling, which_set)
3391. char *handling;
3392. int which_set;
3393. {
3394.     int i = 0;
3395. 
3396.     symset[which_set].handling = H_UNK;
3397.     while (known_handling[i]) {
3398.         if (!strcmpi(known_handling[i], handling)) {
3399.             symset[which_set].handling = i;
3400.             return;
3401.         }
3402.         i++;
3403.     }
3404. }
3405. 
3406. /* ----------  END CONFIG FILE HANDLING ----------- */
3407. 
3408. /* ----------  BEGIN SCOREBOARD CREATION ----------- */
3409. 
3410. #ifdef OS2_CODEVIEW
3411. #define UNUSED_if_not_OS2_CODEVIEW /*empty*/
3412. #else
3413. #define UNUSED_if_not_OS2_CODEVIEW UNUSED
3414. #endif
3415. 
3416. /* verify that we can write to scoreboard file; if not, try to create one */
3417. /*ARGUSED*/
3418. void
3419. check_recordfile(dir)
3420. const char *dir UNUSED_if_not_OS2_CODEVIEW;
3421. {
3422. #if defined(PRAGMA_UNUSED) && !defined(OS2_CODEVIEW)
3423. #pragma unused(dir)
3424. #endif
3425.     const char *fq_record;
3426.     int fd;
3427. 
3428. #if defined(UNIX) || defined(VMS)
3429.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3430.     fd = open(fq_record, O_RDWR, 0);
3431.     if (fd >= 0) {
3432. #ifdef VMS /* must be stream-lf to use UPDATE_RECORD_IN_PLACE */
3433.         if (!file_is_stmlf(fd)) {
3434.             raw_printf(
3435.                    "Warning: scoreboard file '%s' is not in stream_lf format",
3436.                        fq_record);
3437.             wait_synch();
3438.         }
3439. #endif
3440.         (void) nhclose(fd); /* RECORD is accessible */
3441.     } else if ((fd = open(fq_record, O_CREAT | O_RDWR, FCMASK)) >= 0) {
3442.         (void) nhclose(fd); /* RECORD newly created */
3443. #if defined(VMS) && !defined(SECURE)
3444.         /* Re-protect RECORD with world:read+write+execute+delete access. */
3445.         (void) chmod(fq_record, FCMASK | 007);
3446. #endif /* VMS && !SECURE */
3447.     } else {
3448.         raw_printf("Warning: cannot write scoreboard file '%s'", fq_record);
3449.         wait_synch();
3450.     }
3451. #endif /* !UNIX && !VMS */
3452. #if defined(MICRO) || defined(WIN32)
3453.     char tmp[PATHLEN];
3454. 
3455. #ifdef OS2_CODEVIEW /* explicit path on opening for OS/2 */
3456.     /* how does this work when there isn't an explicit path or fopenp
3457.      * for later access to the file via fopen_datafile? ? */
3458.     (void) strncpy(tmp, dir, PATHLEN - 1);
3459.     tmp[PATHLEN - 1] = '\0';
3460.     if ((strlen(tmp) + 1 + strlen(RECORD)) < (PATHLEN - 1)) {
3461.         append_slash(tmp);
3462.         Strcat(tmp, RECORD);
3463.     }
3464.     fq_record = tmp;
3465. #else
3466.     Strcpy(tmp, RECORD);
3467.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3468. #endif
3469. #ifdef WIN32
3470.     /* If dir is NULL it indicates create but
3471.        only if it doesn't already exist */
3472.     if (!dir) {
3473.         char buf[BUFSZ];
3474. 
3475.         buf[0] = '\0';
3476.         fd = open(fq_record, O_RDWR);
3477.         if (!(fd == -1 && errno == ENOENT)) {
3478.             if (fd >= 0) {
3479.                 (void) nhclose(fd);
3480.             } else {
3481.                 /* explanation for failure other than missing file */
3482.                 Sprintf(buf, "error   \"%s\", (errno %d).",
3483.                         fq_record, errno);
3484.                 paniclog("scorefile", buf);
3485.             }
3486.             return;
3487.         }
3488.         Sprintf(buf, "missing \"%s\", creating new scorefile.",
3489.                 fq_record);
3490.         paniclog("scorefile", buf);
3491.     }
3492. #endif
3493. 
3494.     if ((fd = open(fq_record, O_RDWR)) < 0) {
3495.         /* try to create empty 'record' */
3496. #if defined(AZTEC_C) || defined(_DCC) \
3497.     || (defined(__GNUC__) && defined(__AMIGA__))
3498.         /* Aztec doesn't use the third argument */
3499.         /* DICE doesn't like it */
3500.         fd = open(fq_record, O_CREAT | O_RDWR);
3501. #else
3502.         fd = open(fq_record, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
3503. #endif
3504.         if (fd <= 0) {
3505.             raw_printf("Warning: cannot write record '%s'", tmp);
3506.             wait_synch();
3507.         } else {
3508.             (void) nhclose(fd);
3509.         }
3510.     } else {
3511.         /* open succeeded => 'record' exists */
3512.         (void) nhclose(fd);
3513.     }
3514. #else /* MICRO || WIN32*/
3515. 
3516. #ifdef MAC
3517.     /* Create the "record" file, if necessary */
3518.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3519.     fd = macopen(fq_record, O_RDWR | O_CREAT, TEXT_TYPE);
3520.     if (fd != -1)
3521.         macclose(fd);
3522. #endif /* MAC */
3523. 
3524. #endif /* MICRO || WIN32*/
3525. }
3526. 
3527. /* ----------  END SCOREBOARD CREATION ----------- */
3528. 
3529. /* ----------  BEGIN PANIC/IMPOSSIBLE/TESTING LOG ----------- */
3530. 
3531. /*ARGSUSED*/
3532. void
3533. paniclog(type, reason)
3534. const char *type;   /* panic, impossible, trickery */
3535. const char *reason; /* explanation */
3536. {
3537. #ifdef PANICLOG
3538.     FILE *lfile;
3539.     char buf[BUFSZ];
3540. 
3541.     if (!program_state.in_paniclog) {
3542.         program_state.in_paniclog = 1;
3543.         lfile = fopen_datafile(PANICLOG, "a", TROUBLEPREFIX);
3544.         if (lfile) {
3545. #ifdef PANICLOG_FMT2
3546.             (void) fprintf(lfile, "%ld %s: %s %s\n",
3547.                            ubirthday, (plname ? plname : "(none)"),
3548.                            type, reason);
3549. #else
3550.             time_t now = getnow();
3551.             int uid = getuid();
3552.             char playmode = wizard ? 'D' : discover ? 'X' : '-';
3553. 
3554.             (void) fprintf(lfile, "%s %08ld %06ld %d %c: %s %s\n",
3555.                            version_string(buf), yyyymmdd(now), hhmmss(now),
3556.                            uid, playmode, type, reason);
3557. #endif /* !PANICLOG_FMT2 */
3558.             (void) fclose(lfile);
3559.         }
3560.         program_state.in_paniclog = 0;
3561.     }
3562. #endif /* PANICLOG */
3563.     return;
3564. }
3565. 
3566. void
3567. testinglog(filenm, type, reason)
3568. const char *filenm;   /* ad hoc file name */
3569. const char *type;
3570. const char *reason;   /* explanation */
3571. {
3572.     FILE *lfile;
3573.     char fnbuf[BUFSZ];
3574. 
3575.     if (!filenm)
3576.         return;
3577.     Strcpy(fnbuf, filenm);
3578.     if (index(fnbuf, '.') == 0)
3579.         Strcat(fnbuf, ".log");
3580.     lfile = fopen_datafile(fnbuf, "a", TROUBLEPREFIX);
3581.     if (lfile) {
3582.         (void) fprintf(lfile, "%s\n%s\n", type, reason);
3583.         (void) fclose(lfile);
3584.     }
3585.     return;
3586. }
3587. 
3588. /* ----------  END PANIC/IMPOSSIBLE/TESTING LOG ----------- */
3589. 
3590. #ifdef SELF_RECOVER
3591. 
3592. /* ----------  BEGIN INTERNAL RECOVER ----------- */
3593. boolean
3594. recover_savefile()
3595. {
3596.     int gfd, lfd, sfd;
3597.     int lev, savelev, hpid, pltmpsiz;
3598.     xchar levc;
3599.     struct version_info version_data;
3600.     int processed[256];
3601.     char savename[SAVESIZE], errbuf[BUFSZ];
3602.     struct savefile_info sfi;
3603.     char tmpplbuf[PL_NSIZ];
3604. 
3605.     for (lev = 0; lev < 256; lev++)
3606.         processed[lev] = 0;
3607. 
3608.     /* level 0 file contains:
3609.      *  pid of creating process (ignored here)
3610.      *  level number for current level of save file
3611.      *  name of save file nethack would have created
3612.      *  savefile info
3613.      *  player name
3614.      *  and game state
3615.      */
3616.     gfd = open_levelfile(0, errbuf);
3617.     if (gfd < 0) {
3618.         raw_printf("%s\n", errbuf);
3619.         return FALSE;
3620.     }
3621.     if (read(gfd, (genericptr_t) &hpid, sizeof hpid) != sizeof hpid) {
3622.         raw_printf("\n%s\n%s\n",
3623.             "Checkpoint data incompletely written or subsequently clobbered.",
3624.                    "Recovery impossible.");
3625.         (void) nhclose(gfd);
3626.         return FALSE;
3627.     }
3628.     if (read(gfd, (genericptr_t) &savelev, sizeof(savelev))
3629.         != sizeof(savelev)) {
3630.         raw_printf(
3631.          "\nCheckpointing was not in effect for %s -- recovery impossible.\n",
3632.                    lock);
3633.         (void) nhclose(gfd);
3634.         return FALSE;
3635.     }
3636.     if ((read(gfd, (genericptr_t) savename, sizeof savename)
3637.          != sizeof savename)
3638.         || (read(gfd, (genericptr_t) &version_data, sizeof version_data)
3639.             != sizeof version_data)
3640.         || (read(gfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi)
3641.         || (read(gfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz)
3642.             != sizeof pltmpsiz) || (pltmpsiz > PL_NSIZ)
3643.         || (read(gfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz)) {
3644.         raw_printf("\nError reading %s -- can't recover.\n", lock);
3645.         (void) nhclose(gfd);
3646.         return FALSE;
3647.     }
3648. 
3649.     /* save file should contain:
3650.      *  version info
3651.      *  savefile info
3652.      *  player name
3653.      *  current level (including pets)
3654.      *  (non-level-based) game state
3655.      *  other levels
3656.      */
3657.     set_savefile_name(TRUE);
3658.     sfd = create_savefile();
3659.     if (sfd < 0) {
3660.         raw_printf("\nCannot recover savefile %s.\n", SAVEF);
3661.         (void) nhclose(gfd);
3662.         return FALSE;
3663.     }
3664. 
3665.     lfd = open_levelfile(savelev, errbuf);
3666.     if (lfd < 0) {
3667.         raw_printf("\n%s\n", errbuf);
3668.         (void) nhclose(gfd);
3669.         (void) nhclose(sfd);
3670.         delete_savefile();
3671.         return FALSE;
3672.     }
3673. 
3674.     if (write(sfd, (genericptr_t) &version_data, sizeof version_data)
3675.         != sizeof version_data) {
3676.         raw_printf("\nError writing %s; recovery failed.", SAVEF);
3677.         (void) nhclose(gfd);
3678.         (void) nhclose(sfd);
3679.         (void) nhclose(lfd);
3680.         delete_savefile();
3681.         return FALSE;
3682.     }
3683. 
3684.     if (write(sfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) {
3685.         raw_printf("\nError writing %s; recovery failed (savefile_info).\n",
3686.                    SAVEF);
3687.         (void) nhclose(gfd);
3688.         (void) nhclose(sfd);
3689.         (void) nhclose(lfd);
3690.         delete_savefile();
3691.         return FALSE;
3692.     }
3693. 
3694.     if (write(sfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz)
3695.         != sizeof pltmpsiz) {
3696.         raw_printf("Error writing %s; recovery failed (player name size).\n",
3697.                    SAVEF);
3698.         (void) nhclose(gfd);
3699.         (void) nhclose(sfd);
3700.         (void) nhclose(lfd);
3701.         delete_savefile();
3702.         return FALSE;
3703.     }
3704. 
3705.     if (write(sfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz) {
3706.         raw_printf("Error writing %s; recovery failed (player name).\n",
3707.                    SAVEF);
3708.         (void) nhclose(gfd);
3709.         (void) nhclose(sfd);
3710.         (void) nhclose(lfd);
3711.         delete_savefile();
3712.         return FALSE;
3713.     }
3714. 
3715.     if (!copy_bytes(lfd, sfd)) {
3716.         (void) nhclose(gfd);
3717.         (void) nhclose(sfd);
3718.         (void) nhclose(lfd);
3719.         delete_savefile();
3720.         return FALSE;
3721.     }
3722.     (void) nhclose(lfd);
3723.     processed[savelev] = 1;
3724. 
3725.     if (!copy_bytes(gfd, sfd)) {
3726.         (void) nhclose(gfd);
3727.         (void) nhclose(sfd);
3728.         delete_savefile();
3729.         return FALSE;
3730.     }
3731.     (void) nhclose(gfd);
3732.     processed[0] = 1;
3733. 
3734.     for (lev = 1; lev < 256; lev++) {
3735.         /* level numbers are kept in xchars in save.c, so the
3736.          * maximum level number (for the endlevel) must be < 256
3737.          */
3738.         if (lev != savelev) {
3739.             lfd = open_levelfile(lev, (char *) 0);
3740.             if (lfd >= 0) {
3741.                 /* any or all of these may not exist */
3742.                 levc = (xchar) lev;
3743.                 write(sfd, (genericptr_t) &levc, sizeof(levc));
3744.                 if (!copy_bytes(lfd, sfd)) {
3745.                     (void) nhclose(lfd);
3746.                     (void) nhclose(sfd);
3747.                     delete_savefile();
3748.                     return FALSE;
3749.                 }
3750.                 (void) nhclose(lfd);
3751.                 processed[lev] = 1;
3752.             }
3753.         }
3754.     }
3755.     (void) nhclose(sfd);
3756. 
3757. #ifdef HOLD_LOCKFILE_OPEN
3758.     really_close();
3759. #endif
3760.     /*
3761.      * We have a successful savefile!
3762.      * Only now do we erase the level files.
3763.      */
3764.     for (lev = 0; lev < 256; lev++) {
3765.         if (processed[lev]) {
3766.             const char *fq_lock;
3767. 
3768.             set_levelfile_name(lock, lev);
3769.             fq_lock = fqname(lock, LEVELPREFIX, 3);
3770.             (void) unlink(fq_lock);
3771.         }
3772.     }
3773.     return TRUE;
3774. }
3775. 
3776. boolean
3777. copy_bytes(ifd, ofd)
3778. int ifd, ofd;
3779. {
3780.     char buf[BUFSIZ];
3781.     int nfrom, nto;
3782. 
3783.     do {
3784.         nfrom = read(ifd, buf, BUFSIZ);
3785.         nto = write(ofd, buf, nfrom);
3786.         if (nto != nfrom)
3787.             return FALSE;
3788.     } while (nfrom == BUFSIZ);
3789.     return TRUE;
3790. }
3791. 
3792. /* ----------  END INTERNAL RECOVER ----------- */
3793. #endif /*SELF_RECOVER*/
3794. 
3795. /* ----------  OTHER ----------- */
3796. 
3797. #ifdef SYSCF
3798. #ifdef SYSCF_FILE
3799. void
3800. assure_syscf_file()
3801. {
3802.     int fd;
3803. 
3804.     /*
3805.      * All we really care about is the end result - can we read the file?
3806.      * So just check that directly.
3807.      *
3808.      * Not tested on most of the old platforms (which don't attempt
3809.      * to implement SYSCF).
3810.      * Some ports don't like open()'s optional third argument;
3811.      * VMS overrides open() usage with a macro which requires it.
3812.      */
3813. #ifndef VMS
3814. # if defined(NOCWD_ASSUMPTIONS) && defined(WIN32)
3815.     fd = open(fqname(SYSCF_FILE, SYSCONFPREFIX, 0), O_RDONLY);
3816. # else
3817.     fd = open(SYSCF_FILE, O_RDONLY);
3818. # endif
3819. #else
3820.     fd = open(SYSCF_FILE, O_RDONLY, 0);
3821. #endif
3822.     if (fd >= 0) {
3823.         /* readable */
3824.         close(fd);
3825.         return;
3826.     }
3827.     raw_printf("Unable to open SYSCF_FILE.\n");
3828.     exit(EXIT_FAILURE);
3829. }
3830. 
3831. #endif /* SYSCF_FILE */
3832. #endif /* SYSCF */
3833. 
3834. #ifdef DEBUG
3835. /* used by debugpline() to decide whether to issue a message
3836.  * from a particular source file; caller passes __FILE__ and we check
3837.  * whether it is in the source file list supplied by SYSCF's DEBUGFILES
3838.  *
3839.  * pass FALSE to override wildcard matching; useful for files
3840.  * like dungeon.c and questpgr.c, which generate a ridiculous amount of
3841.  * output if DEBUG is defined and effectively block the use of a wildcard */
3842. boolean
3843. debugcore(filename, wildcards)
3844. const char *filename;
3845. boolean wildcards;
3846. {
3847.     const char *debugfiles, *p;
3848. 
3849.     if (!filename || !*filename)
3850.         return FALSE; /* sanity precaution */
3851. 
3852.     if (sysopt.env_dbgfl == 0) {
3853.         /* check once for DEBUGFILES in the environment;
3854.            if found, it supersedes the sysconf value
3855.            [note: getenv() rather than nh_getenv() since a long value
3856.            is valid and doesn't pose any sort of overflow risk here] */
3857.         if ((p = getenv("DEBUGFILES")) != 0) {
3858.             if (sysopt.debugfiles)
3859.                 free((genericptr_t) sysopt.debugfiles);
3860.             sysopt.debugfiles = dupstr(p);
3861.             sysopt.env_dbgfl = 1;
3862.         } else
3863.             sysopt.env_dbgfl = -1;
3864.     }
3865. 
3866.     debugfiles = sysopt.debugfiles;
3867.     /* usual case: sysopt.debugfiles will be empty */
3868.     if (!debugfiles || !*debugfiles)
3869.         return FALSE;
3870. 
3871. /* strip filename's path if present */
3872. #ifdef UNIX
3873.     if ((p = rindex(filename, '/')) != 0)
3874.         filename = p + 1;
3875. #endif
3876. #ifdef VMS
3877.     filename = vms_basename(filename);
3878.     /* vms_basename strips off 'type' suffix as well as path and version;
3879.        we want to put suffix back (".c" assumed); since it always returns
3880.        a pointer to a static buffer, we can safely modify its result */
3881.     Strcat((char *) filename, ".c");
3882. #endif
3883. 
3884.     /*
3885.      * Wildcard match will only work if there's a single pattern (which
3886.      * might be a single file name without any wildcarding) rather than
3887.      * a space-separated list.
3888.      * [to NOT do: We could step through the space-separated list and
3889.      * attempt a wildcard match against each element, but that would be
3890.      * overkill for the intended usage.]
3891.      */
3892.     if (wildcards && pmatch(debugfiles, filename))
3893.         return TRUE;
3894. 
3895.     /* check whether filename is an element of the list */
3896.     if ((p = strstr(debugfiles, filename)) != 0) {
3897.         int l = (int) strlen(filename);
3898. 
3899.         if ((p == debugfiles || p[-1] == ' ' || p[-1] == '/')
3900.             && (p[l] == ' ' || p[l] == '\0'))
3901.             return TRUE;
3902.     }
3903.     return FALSE;
3904. }
3905. 
3906. #endif /*DEBUG*/
3907. 
3908. /* ----------  BEGIN TRIBUTE ----------- */
3909. 
3910. /* 3.6 tribute code
3911.  */
3912. 
3913. #define SECTIONSCOPE 1
3914. #define TITLESCOPE 2
3915. #define PASSAGESCOPE 3
3916. 
3917. #define MAXPASSAGES SIZE(context.novel.pasg) /* 20 */
3918. 
3919. static int FDECL(choose_passage, (int, unsigned));
3920. 
3921. /* choose a random passage that hasn't been chosen yet; once all have
3922.    been chosen, reset the tracking to make all passages available again */
3923. static int
3924. choose_passage(passagecnt, oid)
3925. int passagecnt; /* total of available passages */
3926. unsigned oid; /* book.o_id, used to determine whether re-reading same book */
3927. {
3928.     int idx, res;
3929. 
3930.     if (passagecnt < 1)
3931.         return 0;
3932. 
3933.     /* if a different book or we've used up all the passages already,
3934.        reset in order to have all 'passagecnt' passages available */
3935.     if (oid != context.novel.id || context.novel.count == 0) {
3936.         int i, range = passagecnt, limit = MAXPASSAGES;
3937. 
3938.         context.novel.id = oid;
3939.         if (range <= limit) {
3940.             /* collect all of the N indices */
3941.             context.novel.count = passagecnt;
3942.             for (idx = 0; idx < MAXPASSAGES; idx++)
3943.                 context.novel.pasg[idx] = (xchar) ((idx < passagecnt)
3944.                                                    ? idx + 1 : 0);
3945.         } else {
3946.             /* collect MAXPASSAGES of the N indices */
3947.             context.novel.count = MAXPASSAGES;
3948.             for (idx = i = 0; i < passagecnt; ++i, --range)
3949.                 if (range > 0 && rn2(range) < limit) {
3950.                     context.novel.pasg[idx++] = (xchar) (i + 1);
3951.                     --limit;
3952.                 }
3953.         }
3954.     }
3955. 
3956.     idx = rn2(context.novel.count);
3957.     res = (int) context.novel.pasg[idx];
3958.     /* move the last slot's passage index into the slot just used
3959.        and reduce the number of passages available */
3960.     context.novel.pasg[idx] = context.novel.pasg[--context.novel.count];
3961.     return res;
3962. }
3963. 
3964. /* Returns True if you were able to read something. */
3965. boolean
3966. read_tribute(tribsection, tribtitle, tribpassage, nowin_buf, bufsz, oid)
3967. const char *tribsection, *tribtitle;
3968. int tribpassage, bufsz;
3969. char *nowin_buf;
3970. unsigned oid; /* book identifier */
3971. {
3972.     dlb *fp;
3973.     char line[BUFSZ], lastline[BUFSZ];
3974. 
3975.     int scope = 0;
3976.     int linect = 0, passagecnt = 0, targetpassage = 0;
3977.     const char *badtranslation = "an incomprehensible foreign translation";
3978.     boolean matchedsection = FALSE, matchedtitle = FALSE;
3979.     winid tribwin = WIN_ERR;
3980.     boolean grasped = FALSE;
3981.     boolean foundpassage = FALSE;
3982. 
3983.     if (nowin_buf)
3984.         *nowin_buf = '\0';
3985. 
3986.     /* check for mandatories */
3987.     if (!tribsection || !tribtitle) {
3988.         if (!nowin_buf)
3989.             pline("It's %s of \"%s\"!", badtranslation, tribtitle);
3990.         return grasped;
3991.     }
3992. 
3993.     debugpline3("read_tribute %s, %s, %d.", tribsection, tribtitle,
3994.                 tribpassage);
3995. 
3996.     fp = dlb_fopen(TRIBUTEFILE, "r");
3997.     if (!fp) {
3998.         /* this is actually an error - cannot open tribute file! */
3999.         if (!nowin_buf)
4000.             pline("You feel too overwhelmed to continue!");
4001.         return grasped;
4002.     }
4003. 
4004.     /*
4005.      * Syntax (not case-sensitive):
4006.      *  %section books
4007.      *
4008.      * In the books section:
4009.      *    %title booktitle (n)
4010.      *          where booktitle=book title without quotes
4011.      *          (n)= total number of passages present for this title
4012.      *    %passage k
4013.      *          where k=sequential passage number
4014.      *
4015.      * %e ends the passage/book/section
4016.      *    If in a passage, it marks the end of that passage.
4017.      *    If in a book, it marks the end of that book.
4018.      *    If in a section, it marks the end of that section.
4019.      *
4020.      *  %section death
4021.      */
4022. 
4023.     *line = *lastline = '\0';
4024.     while (dlb_fgets(line, sizeof line, fp) != 0) {
4025.         linect++;
4026.         (void) strip_newline(line);
4027.         switch (line[0]) {
4028.         case '%':
4029.             if (!strncmpi(&line[1], "section ", sizeof "section " - 1)) {
4030.                 char *st = &line[9]; /* 9 from "%section " */
4031. 
4032.                 scope = SECTIONSCOPE;
4033.                 matchedsection = !strcmpi(st, tribsection) ? TRUE : FALSE;
4034.             } else if (!strncmpi(&line[1], "title ", sizeof "title " - 1)) {
4035.                 char *st = &line[7]; /* 7 from "%title " */
4036.                 char *p1, *p2;
4037. 
4038.                 if ((p1 = index(st, '(')) != 0) {
4039.                     *p1++ = '\0';
4040.                     (void) mungspaces(st);
4041.                     if ((p2 = index(p1, ')')) != 0) {
4042.                         *p2 = '\0';
4043.                         passagecnt = atoi(p1);
4044.                         scope = TITLESCOPE;
4045.                         if (matchedsection && !strcmpi(st, tribtitle)) {
4046.                             matchedtitle = TRUE;
4047.                             targetpassage = !tribpassage
4048.                                              ? choose_passage(passagecnt, oid)
4049.                                              : (tribpassage <= passagecnt)
4050.                                                 ? tribpassage : 0;
4051.                         } else {
4052.                             matchedtitle = FALSE;
4053.                         }
4054.                     }
4055.                 }
4056.             } else if (!strncmpi(&line[1], "passage ",
4057.                                  sizeof "passage " - 1)) {
4058.                 int passagenum = 0;
4059.                 char *st = &line[9]; /* 9 from "%passage " */
4060. 
4061.                 mungspaces(st);
4062.                 passagenum = atoi(st);
4063.                 if (passagenum > 0 && passagenum <= passagecnt) {
4064.                     scope = PASSAGESCOPE;
4065.                     if (matchedtitle && passagenum == targetpassage) {
4066.                         foundpassage = TRUE;
4067.                         if (!nowin_buf) {
4068.                             tribwin = create_nhwindow(NHW_MENU);
4069.                             if (tribwin == WIN_ERR)
4070.                                 goto cleanup;
4071.                         }
4072.                     }
4073.                 }
4074.             } else if (!strncmpi(&line[1], "e ", sizeof "e " - 1)) {
4075.                 if (foundpassage)
4076.                     goto cleanup;
4077.                 if (scope == TITLESCOPE)
4078.                     matchedtitle = FALSE;
4079.                 if (scope == SECTIONSCOPE)
4080.                     matchedsection = FALSE;
4081.                 if (scope)
4082.                     --scope;
4083.             } else {
4084.                 debugpline1("tribute file error: bad %% command, line %d.",
4085.                             linect);
4086.             }
4087.             break;
4088.         case '#':
4089.             /* comment only, next! */
4090.             break;
4091.         default:
4092.             if (foundpassage) {
4093.                 if (!nowin_buf) {
4094.                     /* outputting multi-line passage to text window */
4095.                     putstr(tribwin, 0, line);
4096.                     if (*line)
4097.                         Strcpy(lastline, line);
4098.                 } else {
4099.                     /* fetching one-line passage into buffer */
4100.                     copynchars(nowin_buf, line, bufsz - 1);
4101.                     goto cleanup; /* don't wait for "%e passage" */
4102.                 }
4103.             }
4104.         }
4105.     }
4106. 
4107. cleanup:
4108.     (void) dlb_fclose(fp);
4109.     if (nowin_buf) {
4110.         /* one-line buffer */
4111.         grasped = *nowin_buf ? TRUE : FALSE;
4112.     } else {
4113.         if (tribwin != WIN_ERR) { /* implies 'foundpassage' */
4114.             /* multi-line window, normal case;
4115.                if lastline is empty, there were no non-empty lines between
4116.                "%passage n" and "%e passage" so we leave 'grasped' False */
4117.             if (*lastline) {
4118.                 display_nhwindow(tribwin, FALSE);
4119.                 /* put the final attribution line into message history,
4120.                    analogous to the summary line from long quest messages */
4121.                 if (index(lastline, '['))
4122.                     mungspaces(lastline); /* to remove leading spaces */
4123.                 else /* construct one if necessary */
4124.                     Sprintf(lastline, "[%s, by Terry Pratchett]", tribtitle);
4125.                 putmsghistory(lastline, FALSE);
4126.                 grasped = TRUE;
4127.             }
4128.             destroy_nhwindow(tribwin);
4129.         }
4130.         if (!grasped)
4131.             /* multi-line window, problem */
4132.             pline("It seems to be %s of \"%s\"!", badtranslation, tribtitle);
4133.     }
4134.     return grasped;
4135. }
4136. 
4137. boolean
4138. Death_quote(buf, bufsz)
4139. char *buf;
4140. int bufsz;
4141. {
4142.     unsigned death_oid = 1; /* chance of oid #1 being a novel is negligible */
4143. 
4144.     return read_tribute("Death", "Death Quotes", 0, buf, bufsz, death_oid);
4145. }
4146. 
4147. /* ----------  END TRIBUTE ----------- */
4148. 
4149. /*files.c*/