Fix up copyright notices. SPDX wants only one per file.
[open-adventure.git] / main.c
1 /*
2  * SPDX-FileCopyrightText: Copyright 1977, 2005 by Will Crowther and Don Woods, Copyright 2017 by Eric S. Raymond
3  * SPDX-License-Identifier: BSD-2-Clause
4  */
5
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <stdbool.h>
9 #include <getopt.h>
10 #include <signal.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <unistd.h>
14 #include <editline/readline.h>
15 #include "advent.h"
16
17 #define DIM(a) (sizeof(a)/sizeof(a[0]))
18
19 #if defined ADVENT_AUTOSAVE
20 static FILE* autosave_fp;
21 void autosave(void)
22 {
23     if (autosave_fp != NULL) {
24         rewind(autosave_fp);
25         savefile(autosave_fp);
26         fflush(autosave_fp);
27     }
28 }
29 #endif
30
31 // LCOV_EXCL_START
32 // exclude from coverage analysis because it requires interactivity to test
33 static void sig_handler(int signo)
34 {
35     if (signo == SIGINT) {
36         if (settings.logfp != NULL)
37             fflush(settings.logfp);
38     }
39
40 #if defined ADVENT_AUTOSAVE
41     if (signo == SIGHUP || signo == SIGTERM)
42         autosave();
43 #endif
44     exit(EXIT_FAILURE);
45 }
46 // LCOV_EXCL_STOP
47
48 char *myreadline(const char *prompt)
49 {
50     /*
51      * This function isn't required for gameplay, readline() straight
52      * up would suffice for that.  It's where we interpret command-line
53      * logfiles for testing purposes.
54      */
55     /* Normal case - no script arguments */
56     if (settings.argc == 0) {
57         char *ln = readline(prompt);
58         if (ln == NULL) {
59             fputs(prompt, stdout);
60         }
61         return ln;
62     }
63
64     char *buf = malloc(LINESIZE + 1);
65     for (;;) {
66         if (settings.scriptfp == NULL || feof(settings.scriptfp)) {
67             if (settings.optind >= settings.argc) {
68                 free(buf);
69                 return NULL;
70             }
71
72             char *next = settings.argv[settings.optind++];
73
74             if (settings.scriptfp != NULL && feof(settings.scriptfp))
75                 fclose(settings.scriptfp);
76             if (strcmp(next, "-") == 0)
77                 settings.scriptfp = stdin; // LCOV_EXCL_LINE
78             else
79                 settings.scriptfp = fopen(next, "r");
80         }
81
82         if (isatty(fileno(settings.scriptfp))) {
83             free(buf); // LCOV_EXCL_LINE
84             return readline(prompt); // LCOV_EXCL_LINE
85         } else {
86             char *ln = fgets(buf, LINESIZE, settings.scriptfp);
87             if (ln != NULL) {
88                 fputs(prompt, stdout);
89                 fputs(ln, stdout);
90                 return ln;
91             }
92         }
93     }
94
95     return NULL;
96 }
97
98 /*  Check if this loc is eligible for any hints.  If been here int
99  *  enough, display.  Ignore "HINTS" < 4 (special stuff, see database
100  *  notes). */
101 static void checkhints(void)
102 {
103     if (conditions[game.loc] >= game.conds) {
104         for (int hint = 0; hint < NHINTS; hint++) {
105             if (game.hints[hint].used)
106                 continue;
107             if (!CNDBIT(game.loc, hint + 1 + COND_HBASE))
108                 game.hints[hint].lc = -1;
109             ++game.hints[hint].lc;
110             /*  Come here if he's been int enough at required loc(s) for some
111              *  unused hint. */
112             if (game.hints[hint].lc >= hints[hint].turns) {
113                 int i;
114
115                 switch (hint) {
116                 case 0:
117                     /* cave */
118                     if (game.objects[GRATE].prop == GRATE_CLOSED && !HERE(KEYS))
119                         break;
120                     game.hints[hint].lc = 0;
121                     return;
122                 case 1: /* bird */
123                     if (game.objects[BIRD].place == game.loc && TOTING(ROD) && game.oldobj == BIRD)
124                         break;
125                     return;
126                 case 2: /* snake */
127                     if (HERE(SNAKE) && !HERE(BIRD))
128                         break;
129                     game.hints[hint].lc = 0;
130                     return;
131                 case 3: /* maze */
132                     if (game.locs[game.loc].atloc == NO_OBJECT &&
133                         game.locs[game.oldloc].atloc == NO_OBJECT &&
134                         game.locs[game.oldlc2].atloc == NO_OBJECT &&
135                         game.holdng > 1)
136                         break;
137                     game.hints[hint].lc = 0;
138                     return;
139                 case 4: /* dark */
140                     if (!PROP_IS_NOTFOUND(EMERALD) && PROP_IS_NOTFOUND(PYRAMID))
141                         break;
142                     game.hints[hint].lc = 0;
143                     return;
144                 case 5: /* witt */
145                     break;
146                 case 6: /* urn */
147                     if (game.dflag == 0)
148                         break;
149                     game.hints[hint].lc = 0;
150                     return;
151                 case 7: /* woods */
152                     if (game.locs[game.loc].atloc == NO_OBJECT &&
153                         game.locs[game.oldloc].atloc == NO_OBJECT &&
154                         game.locs[game.oldlc2].atloc == NO_OBJECT)
155                         break;
156                     return;
157                 case 8: /* ogre */
158                     i = atdwrf(game.loc);
159                     if (i < 0) {
160                         game.hints[hint].lc = 0;
161                         return;
162                     }
163                     if (HERE(OGRE) && i == 0)
164                         break;
165                     return;
166                 case 9: /* jade */
167                     if (game.tally == 1 && PROP_IS_STASHED_OR_UNSEEN(JADE))
168                         break;
169                     game.hints[hint].lc = 0;
170                     return;
171                 default: // LCOV_EXCL_LINE
172                     // Should never happen
173                     BUG(HINT_NUMBER_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
174                 }
175
176                 /* Fall through to hint display */
177                 game.hints[hint].lc = 0;
178                 if (!yes_or_no(hints[hint].question, arbitrary_messages[NO_MESSAGE], arbitrary_messages[OK_MAN]))
179                     return;
180                 rspeak(HINT_COST, hints[hint].penalty, hints[hint].penalty);
181                 game.hints[hint].used = yes_or_no(arbitrary_messages[WANT_HINT], hints[hint].hint, arbitrary_messages[OK_MAN]);
182                 if (game.hints[hint].used && game.limit > WARNTIME)
183                     game.limit += WARNTIME * hints[hint].penalty;
184             }
185         }
186     }
187 }
188
189 static bool spotted_by_pirate(int i)
190 {
191     if (i != PIRATE)
192         return false;
193
194     /*  The pirate's spotted him.  Pirate leaves him alone once we've
195      *  found chest.  K counts if a treasure is here.  If not, and
196      *  tally=1 for an unseen chest, let the pirate be spotted.  Note
197      *  that game.objexts,place[CHEST] = LOC_NOWHERE might mean that he's thrown
198      *  it to the troll, but in that case he's seen the chest
199      *  PROP_IS_FOUND(CHEST) == true. */
200     if (game.loc == game.chloc || !PROP_IS_NOTFOUND(CHEST))
201         return true;
202     int snarfed = 0;
203     bool movechest = false, robplayer = false;
204     for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
205         if (!objects[treasure].is_treasure)
206             continue;
207         /*  Pirate won't take pyramid from plover room or dark
208          *  room (too easy!). */
209         if (treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
210                                     game.loc == objects[EMERALD].plac)) {
211             continue;
212         }
213         if (TOTING(treasure) || HERE(treasure))
214             ++snarfed;
215         if (TOTING(treasure)) {
216             movechest = true;
217             robplayer = true;
218         }
219     }
220     /* Force chest placement before player finds last treasure */
221     if (game.tally == 1 && snarfed == 0 && game.objects[CHEST].place == LOC_NOWHERE && HERE(LAMP) && game.objects[LAMP].prop == LAMP_BRIGHT) {
222         rspeak(PIRATE_SPOTTED);
223         movechest = true;
224     }
225     /* Do things in this order (chest move before robbery) so chest is listed
226      * last at the maze location. */
227     if (movechest) {
228         move(CHEST, game.chloc);
229         move(MESSAG, game.chloc2);
230         game.dwarves[PIRATE].loc = game.chloc;
231         game.dwarves[PIRATE].oldloc = game.chloc;
232         game.dwarves[PIRATE].seen = false;
233     } else {
234         /* You might get a hint of the pirate's presence even if the
235          * chest doesn't move... */
236         if (game.dwarves[PIRATE].oldloc != game.dwarves[PIRATE].loc && PCT(20))
237             rspeak(PIRATE_RUSTLES);
238     }
239     if (robplayer) {
240         rspeak(PIRATE_POUNCES);
241         for (int treasure = 1; treasure <= NOBJECTS; treasure++) {
242             if (!objects[treasure].is_treasure)
243                 continue;
244             if (!(treasure == PYRAMID && (game.loc == objects[PYRAMID].plac ||
245                                           game.loc == objects[EMERALD].plac))) {
246                 if (AT(treasure) && game.objects[treasure].fixed == IS_FREE)
247                     carry(treasure, game.loc);
248                 if (TOTING(treasure))
249                     drop(treasure, game.chloc);
250             }
251         }
252     }
253
254     return true;
255 }
256
257 static bool dwarfmove(void)
258 /* Dwarves move.  Return true if player survives, false if he dies. */
259 {
260     int kk, stick, attack;
261     loc_t tk[21];
262
263     /*  Dwarf stuff.  See earlier comments for description of
264      *  variables.  Remember sixth dwarf is pirate and is thus
265      *  very different except for motion rules. */
266
267     /*  First off, don't let the dwarves follow him into a pit or a
268      *  wall.  Activate the whole mess the first time he gets as far
269      *  as the Hall of Mists (what INDEEP() tests).  If game.newloc
270      *  is forbidden to pirate (in particular, if it's beyond the
271      *  troll bridge), bypass dwarf stuff.  That way pirate can't
272      *  steal return toll, and dwarves can't meet the bear.  Also
273      *  means dwarves won't follow him into dead end in maze, but
274      *  c'est la vie.  They'll wait for him outside the dead end. */
275     if (game.loc == LOC_NOWHERE || FORCED(game.loc) || CNDBIT(game.newloc, COND_NOARRR))
276         return true;
277
278     /* Dwarf activity level ratchets up */
279     if (game.dflag == 0) {
280         if (INDEEP(game.loc))
281             game.dflag = 1;
282         return true;
283     }
284
285     /*  When we encounter the first dwarf, we kill 0, 1, or 2 of
286      *  the 5 dwarves.  If any of the survivors is at game.loc,
287      *  replace him with the alternate. */
288     if (game.dflag == 1) {
289         if (!INDEEP(game.loc) ||
290             (PCT(95) && (!CNDBIT(game.loc, COND_NOBACK) || PCT(85))))
291             return true;
292         game.dflag = 2;
293         for (int i = 1; i <= 2; i++) {
294             int j = 1 + randrange(NDWARVES - 1);
295             if (PCT(50))
296                 game.dwarves[j].loc = 0;
297         }
298
299         /* Alternate initial loc for dwarf, in case one of them
300         *  starts out on top of the adventurer. */
301         for (int i = 1; i <= NDWARVES - 1; i++) {
302             if (game.dwarves[i].loc == game.loc)
303                 game.dwarves[i].loc = DALTLC; //
304             game.dwarves[i].oldloc = game.dwarves[i].loc;
305         }
306         rspeak(DWARF_RAN);
307         drop(AXE, game.loc);
308         return true;
309     }
310
311     /*  Things are in full swing.  Move each dwarf at random,
312      *  except if he's seen us he sticks with us.  Dwarves stay
313      *  deep inside.  If wandering at random, they don't back up
314      *  unless there's no alternative.  If they don't have to
315      *  move, they attack.  And, of course, dead dwarves don't do
316      *  much of anything. */
317     game.dtotal = 0;
318     attack = 0;
319     stick = 0;
320     for (int i = 1; i <= NDWARVES; i++) {
321         if (game.dwarves[i].loc == 0)
322             continue;
323         /*  Fill tk array with all the places this dwarf might go. */
324         unsigned int j = 1;
325         kk = tkey[game.dwarves[i].loc];
326         if (kk != 0)
327             do {
328                 enum desttype_t desttype = travel[kk].desttype;
329                 game.newloc = travel[kk].destval;
330                 /* Have we avoided a dwarf encounter? */
331                 if (desttype != dest_goto)
332                     continue;
333                 else if (!INDEEP(game.newloc))
334                     continue;
335                 else if (game.newloc == game.dwarves[i].oldloc)
336                     continue;
337                 else if (j > 1 && game.newloc == tk[j - 1])
338                     continue;
339                 else if (j >= DIM(tk) - 1)
340                     /* This can't actually happen. */
341                     continue; // LCOV_EXCL_LINE
342                 else if (game.newloc == game.dwarves[i].loc)
343                     continue;
344                 else if (FORCED(game.newloc))
345                     continue;
346                 else if (i == PIRATE && CNDBIT(game.newloc, COND_NOARRR))
347                     continue;
348                 else if (travel[kk].nodwarves)
349                     continue;
350                 tk[j++] = game.newloc;
351             } while
352             (!travel[kk++].stop);
353         tk[j] = game.dwarves[i].oldloc;
354         if (j >= 2)
355             --j;
356         j = 1 + randrange(j);
357         game.dwarves[i].oldloc = game.dwarves[i].loc;
358         game.dwarves[i].loc = tk[j];
359         game.dwarves[i].seen = (game.dwarves[i].seen && INDEEP(game.loc)) ||
360                         (game.dwarves[i].loc == game.loc ||
361                          game.dwarves[i].oldloc == game.loc);
362         if (!game.dwarves[i].seen)
363             continue;
364         game.dwarves[i].loc = game.loc;
365         if (spotted_by_pirate(i))
366             continue;
367         /* This threatening little dwarf is in the room with him! */
368         ++game.dtotal;
369         if (game.dwarves[i].oldloc == game.dwarves[i].loc) {
370             ++attack;
371             if (game.knfloc >= LOC_NOWHERE)
372                 game.knfloc = game.loc;
373             if (randrange(1000) < 95 * (game.dflag - 2))
374                 ++stick;
375         }
376     }
377
378     /*  Now we know what's happening.  Let's tell the poor sucker about it. */
379     if (game.dtotal == 0)
380         return true;
381     rspeak(game.dtotal == 1 ? DWARF_SINGLE : DWARF_PACK, game.dtotal);
382     if (attack == 0)
383         return true;
384     if (game.dflag == 2)
385         game.dflag = 3;
386     if (attack > 1) {
387         rspeak(THROWN_KNIVES, attack);
388         rspeak(stick > 1 ? MULTIPLE_HITS : (stick == 1 ? ONE_HIT : NONE_HIT), stick);
389     } else {
390         rspeak(KNIFE_THROWN);
391         rspeak(stick ? GETS_YOU : MISSES_YOU);
392     }
393     if (stick == 0)
394         return true;
395     game.oldlc2 = game.loc;
396     return false;
397 }
398
399 /*  "You're dead, Jim."
400  *
401  *  If the current loc is zero, it means the clown got himself killed.
402  *  We'll allow this maxdie times.  NDEATHS is automatically set based
403  *  on the number of snide messages available.  Each death results in
404  *  a message (obituaries[n]) which offers reincarnation; if accepted,
405  *  this results in message obituaries[0], obituaries[2], etc.  The
406  *  last time, if he wants another chance, he gets a snide remark as
407  *  we exit.  When reincarnated, all objects being carried get dropped
408  *  at game.oldlc2 (presumably the last place prior to being killed)
409  *  without change of props.  The loop runs backwards to assure that
410  *  the bird is dropped before the cage.  (This kluge could be changed
411  *  once we're sure all references to bird and cage are done by
412  *  keywords.)  The lamp is a special case (it wouldn't do to leave it
413  *  in the cave). It is turned off and left outside the building (only
414  *  if he was carrying it, of course).  He himself is left inside the
415  *  building (and heaven help him if he tries to xyzzy back into the
416  *  cave without the lamp!).  game.oldloc is zapped so he can't just
417  *  "retreat". */
418 static void croak(void)
419 /*  Okay, he's dead.  Let's get on with it. */
420 {
421     const char* query = obituaries[game.numdie].query;
422     const char* yes_response = obituaries[game.numdie].yes_response;
423
424     ++game.numdie;
425
426     if (game.closng) {
427         /*  He died during closing time.  No resurrection.  Tally up a
428          *  death and exit. */
429         rspeak(DEATH_CLOSING);
430         terminate(endgame);
431     } else if (!yes_or_no(query, yes_response, arbitrary_messages[OK_MAN])
432                || game.numdie == NDEATHS) {
433         /* Player is asked if he wants to try again. If not, or if
434          * he's already used all of his lives, we end the game */
435         terminate(endgame);
436     } else {
437         /* If player wishes to continue, we empty the liquids in the
438          * user's inventory, turn off the lamp, and drop all items
439          * where he died. */
440         game.objects[WATER].place = game.objects[OIL].place = LOC_NOWHERE;
441         if (TOTING(LAMP))
442             game.objects[LAMP].prop = LAMP_DARK;
443         for (int j = 1; j <= NOBJECTS; j++) {
444             int i = NOBJECTS + 1 - j;
445             if (TOTING(i)) {
446                 /* Always leave lamp where it's accessible aboveground */
447                 drop(i, (i == LAMP) ? LOC_START : game.oldlc2);
448             }
449         }
450         game.oldloc = game.loc = game.newloc = LOC_BUILDING;
451     }
452 }
453
454 static void describe_location(void)
455 /* Describe the location to the user */
456 {
457     const char* msg = locations[game.loc].description.small;
458
459     if (MOD(game.locs[game.loc].abbrev, game.abbnum) == 0 || msg == NO_MESSAGE)
460         msg = locations[game.loc].description.big;
461
462     if (!FORCED(game.loc) && DARK(game.loc)) {
463         msg = arbitrary_messages[PITCH_DARK];
464     }
465
466     if (TOTING(BEAR))
467         rspeak(TAME_BEAR);
468
469     speak(msg);
470
471     if (game.loc == LOC_Y2 && PCT(25) && !game.closng)
472         rspeak(SAYS_PLUGH);
473 }
474
475
476 static bool traveleq(int a, int b)
477 /* Are two travel entries equal for purposes of skip after failed condition? */
478 {
479     return (travel[a].condtype == travel[b].condtype)
480            && (travel[a].condarg1 == travel[b].condarg1)
481            && (travel[a].condarg2 == travel[b].condarg2)
482            && (travel[a].desttype == travel[b].desttype)
483            && (travel[a].destval == travel[b].destval);
484 }
485
486 /*  Given the current location in "game.loc", and a motion verb number in
487  *  "motion", put the new location in "game.newloc".  The current loc is saved
488  *  in "game.oldloc" in case he wants to retreat.  The current
489  *  game.oldloc is saved in game.oldlc2, in case he dies.  (if he
490  *  does, game.newloc will be limbo, and game.oldloc will be what killed
491  *  him, so we need game.oldlc2, which is the last place he was
492  *  safe.) */
493 static void playermove(int motion)
494 {
495     int scratchloc, travel_entry = tkey[game.loc];
496     game.newloc = game.loc;
497     if (travel_entry == 0)
498         BUG(LOCATION_HAS_NO_TRAVEL_ENTRIES); // LCOV_EXCL_LINE
499     if (motion == NUL)
500         return;
501     else if (motion == BACK) {
502         /*  Handle "go back".  Look for verb which goes from game.loc to
503          *  game.oldloc, or to game.oldlc2 If game.oldloc has forced-motion.
504          *  te_tmp saves entry -> forced loc -> previous loc. */
505         motion = game.oldloc;
506         if (FORCED(motion))
507             motion = game.oldlc2;
508         game.oldlc2 = game.oldloc;
509         game.oldloc = game.loc;
510         if (CNDBIT(game.loc, COND_NOBACK)) {
511             rspeak(TWIST_TURN);
512             return;
513         }
514         if (motion == game.loc) {
515             rspeak(FORGOT_PATH);
516             return;
517         }
518
519         int te_tmp = 0;
520         for (;;) {
521             enum desttype_t desttype = travel[travel_entry].desttype;
522             scratchloc = travel[travel_entry].destval;
523             if (desttype != dest_goto || scratchloc != motion) {
524                 if (desttype == dest_goto) {
525                     if (FORCED(scratchloc) && travel[tkey[scratchloc]].destval == motion)
526                         te_tmp = travel_entry;
527                 }
528                 if (!travel[travel_entry].stop) {
529                     ++travel_entry;     /* go to next travel entry for this location */
530                     continue;
531                 }
532                 /* we've reached the end of travel entries for game.loc */
533                 travel_entry = te_tmp;
534                 if (travel_entry == 0) {
535                     rspeak(NOT_CONNECTED);
536                     return;
537                 }
538             }
539
540             motion = travel[travel_entry].motion;
541             travel_entry = tkey[game.loc];
542             break; /* fall through to ordinary travel */
543         }
544     } else if (motion == LOOK) {
545         /*  Look.  Can't give more detail.  Pretend it wasn't dark
546          *  (though it may now be dark) so he won't fall into a
547          *  pit while staring into the gloom. */
548         if (game.detail < 3)
549             rspeak(NO_MORE_DETAIL);
550         ++game.detail;
551         game.wzdark = false;
552         game.locs[game.loc].abbrev = 0;
553         return;
554     } else if (motion == CAVE) {
555         /*  Cave.  Different messages depending on whether above ground. */
556         rspeak((OUTSID(game.loc) && game.loc != LOC_GRATE) ? FOLLOW_STREAM : NEED_DETAIL);
557         return;
558     } else {
559         /* none of the specials */
560         game.oldlc2 = game.oldloc;
561         game.oldloc = game.loc;
562     }
563
564     /* Look for a way to fulfil the motion verb passed in - travel_entry indexes
565      * the beginning of the motion entries for here (game.loc). */
566     for (;;) {
567         if ((travel[travel_entry].motion == HERE) || travel[travel_entry].motion == motion)
568             break;
569         if (travel[travel_entry].stop) {
570             /*  Couldn't find an entry matching the motion word passed
571              *  in.  Various messages depending on word given. */
572             switch (motion) {
573             case EAST:
574             case WEST:
575             case SOUTH:
576             case NORTH:
577             case NE:
578             case NW:
579             case SW:
580             case SE:
581             case UP:
582             case DOWN:
583                 rspeak(BAD_DIRECTION);
584                 break;
585             case FORWARD:
586             case LEFT:
587             case RIGHT:
588                 rspeak(UNSURE_FACING);
589                 break;
590             case OUTSIDE:
591             case INSIDE:
592                 rspeak(NO_INOUT_HERE);
593                 break;
594             case XYZZY:
595             case PLUGH:
596                 rspeak(NOTHING_HAPPENS);
597                 break;
598             case CRAWL:
599                 rspeak(WHICH_WAY);
600                 break;
601             default:
602                 rspeak(CANT_APPLY);
603             }
604             return;
605         }
606         ++travel_entry;
607     }
608
609     /* (ESR) We've found a destination that goes with the motion verb.
610      * Next we need to check any conditional(s) on this destination, and
611      * possibly on following entries. */
612     do {
613         for (;;) { /* L12 loop */
614             for (;;) {
615                 enum condtype_t condtype = travel[travel_entry].condtype;
616                 int condarg1 = travel[travel_entry].condarg1;
617                 int condarg2 = travel[travel_entry].condarg2;
618                 if (condtype < cond_not) {
619                     /* YAML N and [pct N] conditionals */
620                     if (condtype == cond_goto || condtype == cond_pct) {
621                         if (condarg1 == 0 || PCT(condarg1))
622                             break;
623                         /* else fall through */
624                     }
625                     /* YAML [with OBJ] clause */
626                     else if (TOTING(condarg1) || (condtype == cond_with && AT(condarg1)))
627                         break;
628                     /* else fall through to check [not OBJ STATE] */
629                 } else if (game.objects[condarg1].prop != condarg2)
630                     break;
631
632                 /* We arrive here on conditional failure.
633                  * Skip to next non-matching destination */
634                 int te_tmp = travel_entry;
635                 do {
636                     if (travel[te_tmp].stop)
637                         BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
638                     ++te_tmp;
639                 } while
640                 (traveleq(travel_entry, te_tmp));
641                 travel_entry = te_tmp;
642             }
643
644             /* Found an eligible rule, now execute it */
645             enum desttype_t desttype = travel[travel_entry].desttype;
646             game.newloc = travel[travel_entry].destval;
647             if (desttype == dest_goto)
648                 return;
649
650             if (desttype == dest_speak) {
651                 /* Execute a speak rule */
652                 rspeak(game.newloc);
653                 game.newloc = game.loc;
654                 return;
655             } else {
656                 switch (game.newloc) {
657                 case 1:
658                     /* Special travel 1.  Plover-alcove passage.  Can carry only
659                      * emerald.  Note: travel table must include "useless"
660                      * entries going through passage, which can never be used
661                      * for actual motion, but can be spotted by "go back". */
662                     game.newloc = (game.loc == LOC_PLOVER)
663                                   ? LOC_ALCOVE
664                                   : LOC_PLOVER;
665                     if (game.holdng > 1 || (game.holdng == 1 && !TOTING(EMERALD))) {
666                         game.newloc = game.loc;
667                         rspeak(MUST_DROP);
668                     }
669                     return;
670                 case 2:
671                     /* Special travel 2.  Plover transport.  Drop the
672                      * emerald (only use special travel if toting
673                      * it), so he's forced to use the plover-passage
674                      * to get it out.  Having dropped it, go back and
675                      * pretend he wasn't carrying it after all. */
676                     drop(EMERALD, game.loc);
677                     {
678                         int te_tmp = travel_entry;
679                         do {
680                             if (travel[te_tmp].stop)
681                                 BUG(CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION); // LCOV_EXCL_LINE
682                             ++te_tmp;
683                         } while
684                         (traveleq(travel_entry, te_tmp));
685                         travel_entry = te_tmp;
686                     }
687                     continue; /* goto L12 */
688                 case 3:
689                     /* Special travel 3.  Troll bridge.  Must be done
690                      * only as special motion so that dwarves won't
691                      * wander across and encounter the bear.  (They
692                      * won't follow the player there because that
693                      * region is forbidden to the pirate.)  If
694                      * game.prop[TROLL]=TROLL_PAIDONCE, he's crossed
695                      * since paying, so step out and block him.
696                      * (standard travel entries check for
697                      * game.prop[TROLL]=TROLL_UNPAID.)  Special stuff
698                      * for bear. */
699                     if (game.objects[TROLL].prop == TROLL_PAIDONCE) {
700                         pspeak(TROLL, look, true, TROLL_PAIDONCE);
701                         game.objects[TROLL].prop = TROLL_UNPAID;
702                         DESTROY(TROLL2);
703                         move(TROLL2 + NOBJECTS, IS_FREE);
704                         move(TROLL, objects[TROLL].plac);
705                         move(TROLL + NOBJECTS, objects[TROLL].fixd);
706                         juggle(CHASM);
707                         game.newloc = game.loc;
708                         return;
709                     } else {
710                         game.newloc = objects[TROLL].plac + objects[TROLL].fixd - game.loc;
711                         if (game.objects[TROLL].prop == TROLL_UNPAID)
712                             game.objects[TROLL].prop = TROLL_PAIDONCE;
713                         if (!TOTING(BEAR))
714                             return;
715                         state_change(CHASM, BRIDGE_WRECKED);
716                         game.objects[TROLL].prop = TROLL_GONE;
717                         drop(BEAR, game.newloc);
718                         game.objects[BEAR].fixed = IS_FIXED;
719                         game.objects[BEAR].prop = BEAR_DEAD;
720                         game.oldlc2 = game.newloc;
721                         croak();
722                         return;
723                     }
724                 default: // LCOV_EXCL_LINE
725                     BUG(SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST); // LCOV_EXCL_LINE
726                 }
727             }
728             break; /* Leave L12 loop */
729         }
730     } while
731     (false);
732 }
733
734 static void lampcheck(void)
735 /* Check game limit and lamp timers */
736 {
737     if (game.objects[LAMP].prop == LAMP_BRIGHT)
738         --game.limit;
739
740     /*  Another way we can force an end to things is by having the
741      *  lamp give out.  When it gets close, we come here to warn him.
742      *  First following arm checks if the lamp and fresh batteries are
743      *  here, in which case we replace the batteries and continue.
744      *  Second is for other cases of lamp dying.  Even after it goes
745      *  out, he can explore outside for a while if desired. */
746     if (game.limit <= WARNTIME) {
747         if (HERE(BATTERY) && game.objects[BATTERY].prop == FRESH_BATTERIES && HERE(LAMP)) {
748             rspeak(REPLACE_BATTERIES);
749             game.objects[BATTERY].prop = DEAD_BATTERIES;
750 #ifdef __unused__
751             /* This code from the original game seems to have been faulty.
752              * No tests ever passed the guard, and with the guard removed
753              * the game hangs when the lamp limit is reached.
754              */
755             if (TOTING(BATTERY))
756                 drop(BATTERY, game.loc);
757 #endif
758             game.limit += BATTERYLIFE;
759             game.lmwarn = false;
760         } else if (!game.lmwarn && HERE(LAMP)) {
761             game.lmwarn = true;
762             if (game.objects[BATTERY].prop == DEAD_BATTERIES)
763                 rspeak(MISSING_BATTERIES);
764             else if (game.objects[BATTERY].place == LOC_NOWHERE)
765                 rspeak(LAMP_DIM);
766             else
767                 rspeak(GET_BATTERIES);
768         }
769     }
770     if (game.limit == 0) {
771         game.limit = -1;
772         game.objects[LAMP].prop = LAMP_DARK;
773         if (HERE(LAMP))
774             rspeak(LAMP_OUT);
775     }
776 }
777
778 static bool closecheck(void)
779 /*  Handle the closing of the cave.  The cave closes "clock1" turns
780  *  after the last treasure has been located (including the pirate's
781  *  chest, which may of course never show up).  Note that the
782  *  treasures need not have been taken yet, just located.  Hence
783  *  clock1 must be large enough to get out of the cave (it only ticks
784  *  while inside the cave).  When it hits zero, we start closing the
785  *  cave, and then sit back and wait for him to try to get out.  If he
786  *  doesn't within clock2 turns, we close the cave; if he does try, we
787  *  assume he panics, and give him a few additional turns to get
788  *  frantic before we close.  When clock2 hits zero, we transport him
789  *  into the final puzzle.  Note that the puzzle depends upon all
790  *  sorts of random things.  For instance, there must be no water or
791  *  oil, since there are beanstalks which we don't want to be able to
792  *  water, since the code can't handle it.  Also, we can have no keys,
793  *  since there is a grate (having moved the fixed object!)  there
794  *  separating him from all the treasures.  Most of these problems
795  *  arise from the use of negative prop numbers to suppress the object
796  *  descriptions until he's actually moved the objects. */
797 {
798     /* If a turn threshold has been met, apply penalties and tell
799      * the player about it. */
800     for (int i = 0; i < NTHRESHOLDS; ++i) {
801         if (game.turns == turn_thresholds[i].threshold + 1) {
802             game.trnluz += turn_thresholds[i].point_loss;
803             speak(turn_thresholds[i].message);
804         }
805     }
806
807     /*  Don't tick game.clock1 unless well into cave (and not at Y2). */
808     if (game.tally == 0 && INDEEP(game.loc) && game.loc != LOC_Y2)
809         --game.clock1;
810
811     /*  When the first warning comes, we lock the grate, destroy
812      *  the bridge, kill all the dwarves (and the pirate), remove
813      *  the troll and bear (unless dead), and set "closng" to
814      *  true.  Leave the dragon; too much trouble to move it.
815      *  from now until clock2 runs out, he cannot unlock the
816      *  grate, move to any location outside the cave, or create
817      *  the bridge.  Nor can he be resurrected if he dies.  Note
818      *  that the snake is already gone, since he got to the
819      *  treasure accessible only via the hall of the mountain
820      *  king. Also, he's been in giant room (to get eggs), so we
821      *  can refer to it.  Also also, he's gotten the pearl, so we
822      *  know the bivalve is an oyster.  *And*, the dwarves must
823      *  have been activated, since we've found chest. */
824     if (game.clock1 == 0) {
825         game.objects[GRATE].prop = GRATE_CLOSED;
826         game.objects[FISSURE].prop = UNBRIDGED;
827         for (int i = 1; i <= NDWARVES; i++) {
828             game.dwarves[i].seen = false;
829             game.dwarves[i].loc = LOC_NOWHERE;
830         }
831         DESTROY(TROLL);
832         move(TROLL + NOBJECTS, IS_FREE);
833         move(TROLL2, objects[TROLL].plac);
834         move(TROLL2 + NOBJECTS, objects[TROLL].fixd);
835         juggle(CHASM);
836         if (game.objects[BEAR].prop != BEAR_DEAD)
837             DESTROY(BEAR);
838         game.objects[CHAIN].prop = CHAIN_HEAP;
839         game.objects[CHAIN].fixed = IS_FREE;
840         game.objects[AXE].prop = AXE_HERE;
841         game.objects[AXE].fixed = IS_FREE;
842         rspeak(CAVE_CLOSING);
843         game.clock1 = -1;
844         game.closng = true;
845         return game.closed;
846     } else if (game.clock1 < 0)
847         --game.clock2;
848     if (game.clock2 == 0) {
849         /*  Once he's panicked, and clock2 has run out, we come here
850          *  to set up the storage room.  The room has two locs,
851          *  hardwired as LOC_NE and LOC_SW.  At the ne end, we
852          *  place empty bottles, a nursery of plants, a bed of
853          *  oysters, a pile of lamps, rods with stars, sleeping
854          *  dwarves, and him.  At the sw end we place grate over
855          *  treasures, snake pit, covey of caged birds, more rods, and
856          *  pillows.  A mirror stretches across one wall.  Many of the
857          *  objects come from known locations and/or states (e.g. the
858          *  snake is known to have been destroyed and needn't be
859          *  carried away from its old "place"), making the various
860          *  objects be handled differently.  We also drop all other 
861          *  objects he might be carrying (lest he has some which
862          *  could cause trouble, such as the keys).  We describe the
863          *  flash of light and trundle back. */
864         put(BOTTLE, LOC_NE, EMPTY_BOTTLE);
865         put(PLANT, LOC_NE, PLANT_THIRSTY);
866         put(OYSTER, LOC_NE, STATE_FOUND);
867         put(LAMP, LOC_NE, LAMP_DARK);
868         put(ROD, LOC_NE, STATE_FOUND);
869         put(DWARF, LOC_NE, STATE_FOUND);
870         game.loc = LOC_NE;
871         game.oldloc = LOC_NE;
872         game.newloc = LOC_NE;
873         /*  Leave the grate with normal (non-negative) property.
874          *  Reuse sign. */
875         move(GRATE, LOC_SW);
876         move(SIGN, LOC_SW);
877         game.objects[SIGN].prop = ENDGAME_SIGN;
878         put(SNAKE, LOC_SW, SNAKE_CHASED);
879         put(BIRD, LOC_SW, BIRD_CAGED);
880         put(CAGE, LOC_SW, STATE_FOUND);
881         put(ROD2, LOC_SW, STATE_FOUND);
882         put(PILLOW, LOC_SW, STATE_FOUND);
883
884         put(MIRROR, LOC_NE, STATE_FOUND);
885         game.objects[MIRROR].fixed = LOC_SW;
886
887         for (int i = 1; i <= NOBJECTS; i++) {
888             if (TOTING(i))
889                 DESTROY(i);
890         }
891
892         rspeak(CAVE_CLOSED);
893         game.closed = true;
894         return game.closed;
895     }
896
897     lampcheck();
898     return false;
899 }
900
901 static void listobjects(void)
902 /*  Print out descriptions of objects at this location.  If
903  *  not closing and property value is negative, tally off
904  *  another treasure.  Rug is special case; once seen, its
905  *  game.prop is RUG_DRAGON (dragon on it) till dragon is killed.
906  *  Similarly for chain; game.prop is initially CHAINING_BEAR (locked to
907  *  bear).  These hacks are because game.prop=0 is needed to
908  *  get full score. */
909 {
910     if (!DARK(game.loc)) {
911         ++game.locs[game.loc].abbrev;
912         for (int i = game.locs[game.loc].atloc; i != 0; i = game.link[i]) {
913             obj_t obj = i;
914             if (obj > NOBJECTS)
915                 obj = obj - NOBJECTS;
916             if (obj == STEPS && TOTING(NUGGET))
917                 continue;
918             /* (ESR) Warning: it looks like you could get away with
919              * running this code only on objects with the treasure
920              * property set. Nope.  There is mystery here.
921              */
922             if (PROP_IS_STASHED_OR_UNSEEN(obj)) {
923                 if (game.closed)
924                     continue;
925                 PROP_SET_FOUND(obj);
926                 if (obj == RUG)
927                     game.objects[RUG].prop = RUG_DRAGON;
928                 if (obj == CHAIN)
929                     game.objects[CHAIN].prop = CHAINING_BEAR;
930                 if (obj == EGGS)
931                     game.seenbigwords = true;
932                 --game.tally;
933                 /*  Note: There used to be a test here to see whether the
934                  *  player had blown it so badly that he could never ever see
935                  *  the remaining treasures, and if so the lamp was zapped to
936                  *  35 turns.  But the tests were too simple-minded; things
937                  *  like killing the bird before the snake was gone (can never
938                  *  see jewelry), and doing it "right" was hopeless.  E.G.,
939                  *  could cross troll bridge several times, using up all
940                  *  available treasures, breaking vase, using coins to buy
941                  *  batteries, etc., and eventually never be able to get
942                  *  across again.  If bottle were left on far side, could then
943                  *  never get eggs or trident, and the effects propagate.  So
944                  *  the whole thing was flushed.  anyone who makes such a
945                  *  gross blunder isn't likely to find everything else anyway
946                  *  (so goes the rationalisation). */
947             }
948             int kk = game.objects[obj].prop;
949             if (obj == STEPS)
950                 kk = (game.loc == game.objects[STEPS].fixed)
951                      ? STEPS_UP
952                      : STEPS_DOWN;
953             pspeak(obj, look, true, kk);
954         }
955     }
956 }
957
958 static bool preprocess_command(command_t *command)
959 /* Pre-processes a command input to see if we need to tease out a few specific cases:
960  * - "enter water" or "enter stream":
961  *   weird specific case that gets the user wet, and then kicks us back to get another command
962  * - <object> <verb>:
963  *   Irregular form of input, but should be allowed. We switch back to <verb> <object> form for
964  *   further processing.
965  * - "grate":
966  *   If in location with grate, we move to that grate. If we're in a number of other places,
967  *   we move to the entrance.
968  * - "water plant", "oil plant", "water door", "oil door":
969  *   Change to "pour water" or "pour oil" based on context
970  * - "cage bird":
971  *   If bird is present, we change to "carry bird"
972  *
973  * Returns true if pre-processing is complete, and we're ready to move to the primary command
974  * processing, false otherwise. */
975 {
976     if (command->word[0].type == MOTION && command->word[0].id == ENTER
977         && (command->word[1].id == STREAM || command->word[1].id == WATER)) {
978         if (LIQLOC(game.loc) == WATER)
979             rspeak(FEET_WET);
980         else
981             rspeak(WHERE_QUERY);
982     } else {
983         if (command->word[0].type == OBJECT) {
984             /* From OV to VO form */
985             if (command->word[1].type == ACTION) {
986                 command_word_t stage = command->word[0];
987                 command->word[0] = command->word[1];
988                 command->word[1] = stage;
989             }
990
991             if (command->word[0].id == GRATE) {
992                 command->word[0].type = MOTION;
993                 if (game.loc == LOC_START ||
994                     game.loc == LOC_VALLEY ||
995                     game.loc == LOC_SLIT) {
996                     command->word[0].id = DEPRESSION;
997                 }
998                 if (game.loc == LOC_COBBLE ||
999                     game.loc == LOC_DEBRIS ||
1000                     game.loc == LOC_AWKWARD ||
1001                     game.loc == LOC_BIRDCHAMBER ||
1002                     game.loc == LOC_PITTOP) {
1003                     command->word[0].id = ENTRANCE;
1004                 }
1005             }
1006             if ((command->word[0].id == WATER || command->word[0].id == OIL) &&
1007                 (command->word[1].id == PLANT || command->word[1].id == DOOR)) {
1008                 if (AT(command->word[1].id)) {
1009                     command->word[1] = command->word[0];
1010                     command->word[0].id = POUR;
1011                     command->word[0].type = ACTION;
1012                     strncpy(command->word[0].raw, "pour", LINESIZE - 1);
1013                 }
1014             }
1015             if (command->word[0].id == CAGE && command->word[1].id == BIRD && HERE(CAGE) && HERE(BIRD)) {
1016                 command->word[0].id = CARRY;
1017                 command->word[0].type = ACTION;
1018             }
1019         }
1020
1021         /* If no word type is given for the first word, we assume it's a motion. */
1022         if (command->word[0].type == NO_WORD_TYPE)
1023             command->word[0].type = MOTION;
1024
1025         command->state = PREPROCESSED;
1026         return true;
1027     }
1028     return false;
1029 }
1030
1031 static bool do_move(void)
1032 /* Actually execute the move to the new location and dwarf movement */
1033 {
1034     /*  Can't leave cave once it's closing (except by main office). */
1035     if (OUTSID(game.newloc) && game.newloc != 0 && game.closng) {
1036         rspeak(EXIT_CLOSED);
1037         game.newloc = game.loc;
1038         if (!game.panic)
1039             game.clock2 = PANICTIME;
1040         game.panic = true;
1041     }
1042
1043     /*  See if a dwarf has seen him and has come from where he
1044      *  wants to go.  If so, the dwarf's blocking his way.  If
1045      *  coming from place forbidden to pirate (dwarves rooted in
1046      *  place) let him get out (and attacked). */
1047     if (game.newloc != game.loc && !FORCED(game.loc) && !CNDBIT(game.loc, COND_NOARRR)) {
1048         for (size_t i = 1; i <= NDWARVES - 1; i++) {
1049             if (game.dwarves[i].oldloc == game.newloc && game.dwarves[i].seen) {
1050                 game.newloc = game.loc;
1051                 rspeak(DWARF_BLOCK);
1052                 break;
1053             }
1054         }
1055     }
1056     game.loc = game.newloc;
1057
1058     if (!dwarfmove())
1059         croak();
1060
1061     if (game.loc == LOC_NOWHERE)
1062         croak();
1063
1064     /* The easiest way to get killed is to fall into a pit in
1065      * pitch darkness. */
1066     if (!FORCED(game.loc) && DARK(game.loc) && game.wzdark && PCT(PIT_KILL_PROB)) {
1067         rspeak(PIT_FALL);
1068         game.oldlc2 = game.loc;
1069         croak();
1070         return false;
1071     }
1072
1073     return true;
1074 }
1075
1076 static bool do_command(void)
1077 /* Get and execute a command */
1078 {
1079     static command_t command;
1080     clear_command(&command);
1081
1082     /* Describe the current location and (maybe) get next command. */
1083     while (command.state != EXECUTED) {
1084         describe_location();
1085
1086         if (FORCED(game.loc)) {
1087             playermove(HERE);
1088             return true;
1089         }
1090
1091         listobjects();
1092
1093         /* Command not yet given; keep getting commands from user
1094          * until valid command is both given and executed. */
1095         clear_command(&command);
1096         while (command.state <= GIVEN) {
1097
1098             if (game.closed) {
1099                 /*  If closing time, check for any stashed objects
1100                  *  being toted and unstash them.  This way objects
1101                  *  won't be described until they've been picked up
1102                  *  and put down separate from their respective
1103                  *  piles. */
1104                 if ((PROP_IS_NOTFOUND(OYSTER) || PROP_IS_STASHED(OYSTER)) && TOTING(OYSTER))
1105                     pspeak(OYSTER, look, true, 1);
1106                 for (size_t i = 1; i <= NOBJECTS; i++) {
1107                     if (TOTING(i) && (PROP_IS_NOTFOUND(i) || PROP_IS_STASHED(i)))
1108                         game.objects[i].prop = PROP_STASHED(i);
1109                 }
1110             }
1111
1112             /* Check to see if the room is dark. If the knife is here,
1113              * and it's dark, the knife permanently disappears */
1114             game.wzdark = DARK(game.loc);
1115             if (game.knfloc != LOC_NOWHERE && game.knfloc != game.loc)
1116                 game.knfloc = LOC_NOWHERE;
1117
1118             /* Check some for hints, get input from user, increment
1119              * turn, and pre-process commands. Keep going until
1120              * pre-processing is done. */
1121             while ( command.state < PREPROCESSED ) {
1122                 checkhints();
1123
1124                 /* Get command input from user */
1125                 if (!get_command_input(&command))
1126                     return false;
1127
1128                 /* Every input, check "foobar" flag. If zero, nothing's going
1129                  * on. If pos, make neg. If neg, he skipped a word, so make it
1130                  * zero.
1131                  */
1132                 game.foobar = (game.foobar > WORD_EMPTY) ? -game.foobar : WORD_EMPTY;
1133
1134                 ++game.turns;
1135                 preprocess_command(&command);
1136             }
1137
1138             /* check if game is closed, and exit if it is */
1139             if (closecheck() )
1140                 return true;
1141
1142             /* loop until all words in command are processed */
1143             while (command.state == PREPROCESSED ) {
1144                 command.state = PROCESSING;
1145
1146                 if (command.word[0].id == WORD_NOT_FOUND) {
1147                     /* Gee, I don't understand. */
1148                     sspeak(DONT_KNOW, command.word[0].raw);
1149                     clear_command(&command);
1150                     continue;
1151                 }
1152
1153                 /* Give user hints of shortcuts */
1154                 if (strncasecmp(command.word[0].raw, "west", sizeof("west")) == 0) {
1155                     if (++game.iwest == 10)
1156                         rspeak(W_IS_WEST);
1157                 }
1158                 if (strncasecmp(command.word[0].raw, "go", sizeof("go")) == 0 && command.word[1].id != WORD_EMPTY) {
1159                     if (++game.igo == 10)
1160                         rspeak(GO_UNNEEDED);
1161                 }
1162
1163                 switch (command.word[0].type) {
1164                 case MOTION:
1165                     playermove(command.word[0].id);
1166                     command.state = EXECUTED;
1167                     continue;
1168                 case OBJECT:
1169                     command.part = unknown;
1170                     command.obj = command.word[0].id;
1171                     break;
1172                 case ACTION:
1173                     if (command.word[1].type == NUMERIC)
1174                         command.part = transitive;
1175                     else
1176                         command.part = intransitive;
1177                     command.verb = command.word[0].id;
1178                     break;
1179                 case NUMERIC:
1180                     if (!settings.oldstyle) {
1181                         sspeak(DONT_KNOW, command.word[0].raw);
1182                         clear_command(&command);
1183                         continue;
1184                     }
1185                     break;// LCOV_EXCL_LINE
1186                 default: // LCOV_EXCL_LINE
1187                 case NO_WORD_TYPE: // LCOV_EXCL_LINE
1188                     BUG(VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3); // LCOV_EXCL_LINE
1189                 }
1190
1191                 switch (action(command)) {
1192                 case GO_TERMINATE:
1193                     command.state = EXECUTED;
1194                     break;
1195                 case GO_MOVE:
1196                     playermove(NUL);
1197                     command.state = EXECUTED;
1198                     break;
1199                 case GO_WORD2:
1200 #ifdef GDEBUG
1201                     printf("Word shift\n");
1202 #endif /* GDEBUG */
1203                     /* Get second word for analysis. */
1204                     command.word[0] = command.word[1];
1205                     command.word[1] = empty_command_word;
1206                     command.state = PREPROCESSED;
1207                     break;
1208                 case GO_UNKNOWN:
1209                     /*  Random intransitive verbs come here.  Clear obj just in case
1210                      *  (see attack()). */
1211                     command.word[0].raw[0] = toupper(command.word[0].raw[0]);
1212                     sspeak(DO_WHAT, command.word[0].raw);
1213                     command.obj = NO_OBJECT;
1214
1215                     /* object cleared; we need to go back to the preprocessing step */
1216                     command.state = GIVEN;
1217                     break;
1218                 case GO_CHECKHINT: // FIXME: re-name to be more contextual; this was previously a label
1219                     command.state = GIVEN;
1220                     break;
1221                 case GO_DWARFWAKE:
1222                     /*  Oh dear, he's disturbed the dwarves. */
1223                     rspeak(DWARVES_AWAKEN);
1224                     terminate(endgame);
1225                 case GO_CLEAROBJ: // FIXME: re-name to be more contextual; this was previously a label
1226                     clear_command(&command);
1227                     break;
1228                 case GO_TOP: // FIXME: re-name to be more contextual; this was previously a label
1229                     break;
1230                 default: // LCOV_EXCL_LINE
1231                     BUG(ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH); // LCOV_EXCL_LINE
1232                 }
1233             } /* while command has not been fully processed */
1234         } /* while command is not yet given */
1235     } /* while command is not executed */
1236
1237     /* command completely executed; we return true. */
1238     return true;
1239 }
1240
1241 /*
1242  * MAIN PROGRAM
1243  *
1244  *  Adventure (rev 2: 20 treasures)
1245  *  History: Original idea & 5-treasure version (adventures) by Willie Crowther
1246  *           15-treasure version (adventure) by Don Woods, April-June 1977
1247  *           20-treasure version (rev 2) by Don Woods, August 1978
1248  *              Errata fixed: 78/12/25
1249  *           Revived 2017 as Open Adventure.
1250  */
1251
1252 int main(int argc, char *argv[])
1253 {
1254     int ch;
1255
1256     /*  Options. */
1257
1258 #if defined ADVENT_AUTOSAVE
1259     const char* opts = "dl:oa:";
1260     const char* usage = "Usage: %s [-l logfilename] [-o] [-a filename] [script...]\n";
1261     FILE *rfp = NULL;
1262     const char* autosave_filename = NULL;
1263 #elif !defined ADVENT_NOSAVE
1264     const char* opts = "dl:or:";
1265     const char* usage = "Usage: %s [-l logfilename] [-o] [-r restorefilename] [script...]\n";
1266     FILE *rfp = NULL;
1267 #else
1268     const char* opts = "dl:o";
1269     const char* usage = "Usage: %s [-l logfilename] [-o] [script...]\n";
1270 #endif
1271     while ((ch = getopt(argc, argv, opts)) != EOF) {
1272         switch (ch) {
1273         case 'd': // LCOV_EXCL_LINE
1274             settings.debug +=1; // LCOV_EXCL_LINE
1275             break; // LCOV_EXCL_LINE
1276         case 'l':
1277             settings.logfp = fopen(optarg, "w");
1278             if (settings.logfp == NULL)
1279                 fprintf(stderr,
1280                         "advent: can't open logfile %s for write\n",
1281                         optarg);
1282             signal(SIGINT, sig_handler);
1283             break;
1284         case 'o':
1285             settings.oldstyle = true;
1286             settings.prompt = false;
1287             break;
1288 #ifdef ADVENT_AUTOSAVE
1289         case 'a':
1290             rfp = fopen(optarg, READ_MODE);
1291             autosave_filename = optarg;
1292             signal(SIGHUP, sig_handler);
1293             signal(SIGTERM, sig_handler);
1294             break;
1295 #elif !defined ADVENT_NOSAVE
1296         case 'r':
1297             rfp = fopen(optarg, "r");
1298             if (rfp == NULL)
1299                 fprintf(stderr,
1300                         "advent: can't open save file %s for read\n",
1301                         optarg);
1302             break;
1303 #endif
1304         default:
1305             fprintf(stderr,
1306                     usage, argv[0]);
1307             fprintf(stderr,
1308                     "        -l create a log file of your game named as specified'\n");
1309             fprintf(stderr,
1310                     "        -o 'oldstyle' (no prompt, no command editing, displays 'Initialising...')\n");
1311 #if defined ADVENT_AUTOSAVE
1312             fprintf(stderr,
1313                     "        -a automatic save/restore from specified saved game file\n");
1314 #elif !defined ADVENT_NOSAVE
1315             fprintf(stderr,
1316                     "        -r restore from specified saved game file\n");
1317 #endif
1318             exit(EXIT_FAILURE);
1319             break;
1320         }
1321     }
1322
1323     /* copy invocation line part after switches */
1324     settings.argc = argc - optind;
1325     settings.argv = argv + optind;
1326     settings.optind = 0;
1327
1328     /*  Initialize game variables */
1329     int seedval = initialise();
1330
1331 #if !defined ADVENT_NOSAVE
1332     if (!rfp) {
1333         game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1334         if (game.novice)
1335             game.limit = NOVICELIMIT;
1336     } else {
1337         restore(rfp);
1338 #if defined ADVENT_AUTOSAVE
1339         score(scoregame);
1340 #endif
1341     }
1342 #if defined ADVENT_AUTOSAVE
1343     if (autosave_filename != NULL) {
1344         if ((autosave_fp = fopen(autosave_filename, WRITE_MODE)) == NULL) {
1345             perror(autosave_filename);
1346             return EXIT_FAILURE;
1347         }
1348         autosave();
1349     }
1350 #endif
1351 #else
1352     game.novice = yes_or_no(arbitrary_messages[WELCOME_YOU], arbitrary_messages[CAVE_NEARBY], arbitrary_messages[NO_MESSAGE]);
1353     if (game.novice)
1354         game.limit = NOVICELIMIT;
1355 #endif
1356
1357     if (settings.logfp)
1358         fprintf(settings.logfp, "seed %d\n", seedval);
1359
1360     /* interpret commands until EOF or interrupt */
1361     for (;;) {
1362         // if we're supposed to move, move
1363         if (!do_move())
1364             continue;
1365
1366         // get command
1367         if (!do_command())
1368             break;
1369     }
1370     /* show score and exit */
1371     terminate(quitgame);
1372 }
1373
1374 /* end */