61d80d888b56246fa6b480f3679057a15ce4bb6f
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8
9 #include "advent.h"
10 #include "database.h"
11 #include "linenoise/linenoise.h"
12 #include "newdb.h"
13
14 char* xstrdup(const char* s)
15 {
16   char* ptr = strdup(s);
17   if (ptr == NULL) {
18     // LCOV_EXCL_START
19     // exclude from coverage analysis because we can't simulate an out of memory error in testing
20     fprintf(stderr, "Out of memory!\n");
21     exit(EXIT_FAILURE);
22   }
23   return(ptr);
24 }
25
26 void* xmalloc(size_t size)
27 {
28     void* ptr = malloc(size);
29     if (ptr == NULL) {
30         // LCOV_EXCL_START
31         // exclude from coverage analysis because we can't simulate an out of memory error in testing
32         fprintf(stderr, "Out of memory!\n");
33         exit(EXIT_FAILURE);
34         // LCOV_EXCL_STOP 
35     }
36     return (ptr);
37 }
38
39 void packed_to_token(long packed, char token[6])
40 {
41     // Unpack and map back to ASCII.
42     for (int i = 0; i < 5; ++i) {
43       char advent = (packed >> i * 6) & 63;
44         token[i] = new_advent_to_ascii[(int) advent];
45     }
46
47     // Ensure the last character is \0.
48     token[5] = '\0';
49
50     // Replace trailing whitespace with \0.
51     for (int i = 4; i >= 0; --i) {
52         if (token[i] == ' ' || token[i] == '\t')
53             token[i] = '\0';
54         else
55             break;
56     }
57 }
58
59 long token_to_packed(const char token[6])
60 {
61   size_t t_len = strlen(token);
62   long packed = 0;
63   for (size_t i = 0; i < t_len; ++i)
64     {
65       char mapped = new_ascii_to_advent[(int) token[i]];
66       packed |= (mapped << (6 * i));
67     }
68   return(packed);
69 }
70
71 void tokenize(char* raw, long tokens[4])
72 {
73   // set each token to 0
74   for (int i = 0; i < 4; ++i)
75     tokens[i] = 0;
76   
77   // grab the first two words
78   char* words[2];
79   words[0] = (char*) xmalloc(strlen(raw));
80   words[1] = (char*) xmalloc(strlen(raw));
81   int word_count = sscanf(raw, "%s%s", words[0], words[1]);
82
83   // make space for substrings and zero it out
84   char chunk_data[][6] = {
85     {"\0\0\0\0\0"},
86     {"\0\0\0\0\0"},
87     {"\0\0\0\0\0"},
88     {"\0\0\0\0\0"},
89   };
90
91   // break the words into up to 4 5-char substrings
92   sscanf(words[0], "%5s%5s", chunk_data[0], chunk_data[1]);
93   if (word_count == 2)
94     sscanf(words[1], "%5s%5s", chunk_data[2], chunk_data[3]);
95   free(words[0]);
96   free(words[1]);
97
98   // uppercase all the substrings
99   for (int i = 0; i < 4; ++i)
100     for (unsigned int j = 0; j < strlen(chunk_data[i]); ++j)
101       chunk_data[i][j] = (char) toupper(chunk_data[i][j]);
102
103   // pack the substrings
104   for (int i = 0; i < 4; ++i)
105     tokens[i] = token_to_packed(chunk_data[i]);
106 }
107
108 /* Hide the fact that wods are corrently packed longs */
109
110 bool wordeq(token_t a, token_t b)
111 {
112     return a == b;
113 }
114
115 bool wordempty(token_t a)
116 {
117     return a == 0;
118 }
119
120 void wordclear(token_t *v)
121 {
122     *v = 0;
123 }
124
125 /*  I/O routines (speak, pspeak, rspeak, GETIN, YES) */
126
127 void vspeak(const char* msg, va_list ap)
128 {
129     // Do nothing if we got a null pointer.
130     if (msg == NULL)
131         return;
132
133     // Do nothing if we got an empty string.
134     if (strlen(msg) == 0)
135         return;
136
137     // Print a newline if the global game.blklin says to.
138     if (game.blklin == true)
139         printf("\n");
140
141     int msglen = strlen(msg);
142
143     // Rendered string
144     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
145     char* rendered = xmalloc(size);
146     char* renderp = rendered;
147
148     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
149     long previous_arg = 0;
150     for (int i = 0; i < msglen; i++) {
151         if (msg[i] != '%') {
152             *renderp++ = msg[i];
153             size--;
154         } else {
155             long arg = va_arg(ap, long);
156             if (arg == -1)
157               arg = 0;
158             i++;
159             // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify everything. Future work may eliminate the need for this.
160             if (msg[i] == 'd') {
161                 int ret = snprintf(renderp, size, "%ld", arg);
162                 if (ret < size) {
163                     renderp += ret;
164                     size -= ret;
165                 }
166             }
167
168             // Unmodified string specifier.
169             if (msg[i] == 's') {
170                 packed_to_token(arg, renderp); /* unpack directly to destination */
171                 size_t len = strlen(renderp);
172                 renderp += len;
173                 size -= len;
174             }
175
176             // Singular/plural specifier.
177             if (msg[i] == 'S') {
178                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
179                     *renderp++ = 's';
180                     size--;
181                 }
182             }
183
184             // All-lowercase specifier.
185             if (msg[i] == 'L' || msg[i] == 'C') {
186                 packed_to_token(arg, renderp); /* unpack directly to destination */
187                 int len = strlen(renderp);
188                 for (int j = 0; j < len; ++j) {
189                     renderp[j] = tolower(renderp[j]);
190                 }
191                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
192                     renderp[0] = toupper(renderp[0]);
193                 renderp += len;
194                 size -= len;
195             }
196
197             previous_arg = arg;
198         }
199     }
200     *renderp = 0;
201
202     // Print the message.
203     printf("%s\n", rendered);
204
205     free(rendered);
206 }
207
208 void speak(const char* msg, ...)
209 {
210     va_list ap;
211     va_start(ap, msg);
212     vspeak(msg, ap);
213     va_end(ap);
214 }
215
216 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
217 /* Find the skip+1st message from msg and print it.  Modes are:
218  * feel = for inventory, what you can touch
219  * look = the long description for the state the object is in
220  * listen = the sound for the state the object is in
221  * study = text on the object. */
222 {
223     va_list ap;
224     va_start(ap, skip);
225     switch (mode) {
226     case touch:
227         vspeak(objects[msg].inventory, ap);
228         break;
229     case look: 
230         vspeak(objects[msg].descriptions[skip], ap);
231         break;
232     case hear:
233         vspeak(objects[msg].sounds[skip], ap);
234         break;
235     case study:
236         vspeak(objects[msg].texts[skip], ap);
237         break;
238     case change:
239         vspeak(objects[msg].changes[skip], ap);
240         break;
241     }
242     va_end(ap);
243 }
244
245 void rspeak(vocab_t i, ...)
246 /* Print the i-th "random" message (section 6 of database). */
247 {
248     va_list ap;
249     va_start(ap, i);
250     vspeak(arbitrary_messages[i], ap);
251     va_end(ap);
252 }
253
254 bool GETIN(FILE *input,
255            long *pword1, long *pword1x,
256            long *pword2, long *pword2x)
257 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
258  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
259  *  case we need to print out the whole word in an error message.  Any number of
260  *  blanks may follow the word.  If a second word appears, it is returned in
261  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
262 {
263     long junk;
264
265     for (;;) {
266         if (game.blklin)
267             fputc('\n', stdout);;
268         if (!MAPLIN(input))
269             return false;
270         *pword1 = GETTXT(true, true, true);
271         if (game.blklin && *pword1 < 0)
272             continue;
273         *pword1x = GETTXT(false, true, true);
274         do {
275             junk = GETTXT(false, true, true);
276         } while
277         (junk > 0);
278         *pword2 = GETTXT(true, true, true);
279         *pword2x = GETTXT(false, true, true);
280         do {
281             junk = GETTXT(false, true, true);
282         } while
283         (junk > 0);
284         if (GETTXT(true, true, true) <= 0)
285             return true;
286         rspeak(TWO_WORDS);
287     }
288 }
289
290 void echo_input(FILE* destination, char* input_prompt, char* input)
291 {
292     size_t len = strlen(input_prompt) + strlen(input) + 1;
293     char* prompt_and_input = (char*) xmalloc(len);
294     strcpy(prompt_and_input, input_prompt);
295     strcat(prompt_and_input, input);
296     fprintf(destination, "%s\n", prompt_and_input);
297     free(prompt_and_input);
298 }
299
300 int word_count(char* s)
301 {
302   char* copy = xstrdup(s);
303   char delims[] = " \t";
304   int count = 0;
305   char* word;
306
307   word = strtok(copy, delims);
308   while(word != NULL)
309     {
310       word = strtok(NULL, delims);
311       ++count;
312     }
313   free(copy);
314   return(count);
315 }
316
317 char* get_input()
318 {
319     // Set up the prompt
320     char input_prompt[] = "> ";
321     if (!prompt)
322         input_prompt[0] = '\0';
323
324     // Print a blank line if game.blklin tells us to.
325     if (game.blklin == true)
326         printf("\n");
327
328     char* input;
329     while (true) {
330         if (editline)
331             input = linenoise(input_prompt);
332         else {
333             input = NULL;
334             size_t n = 0;
335             if (isatty(0))
336             // LCOV_EXCL_START
337             // Should be unreachable in tests, as they will use a non-interactive shell.
338                 printf("%s", input_prompt);
339             // LCOV_EXCL_STOP 
340             ssize_t numread = getline(&input, &n, stdin);
341             if (numread == -1) // Got EOF; return with it.
342               return(NULL);
343         }
344
345         if (input == NULL) // Got EOF; return with it.
346             return(input);
347         else if (input[0] == '#') // Ignore comments.
348             continue;
349         else // We have a 'normal' line; leave the loop.
350             break;
351     }
352
353     // Strip trailing newlines from the input
354     input[strcspn(input, "\n")] = 0;
355
356     linenoiseHistoryAdd(input);
357
358     if (!isatty(0))
359         echo_input(stdout, input_prompt, input);
360
361     if (logfp)
362         echo_input(logfp, input_prompt, input);
363
364     return (input);
365 }
366
367 bool silent_yes()
368 {
369   char* reply;
370   bool outcome;
371   
372   for (;;) {
373     reply = get_input();
374     if (reply == NULL) {
375       // LCOV_EXCL_START
376       // Should be unreachable. Reply should never be NULL
377       linenoiseFree(reply);
378       exit(EXIT_SUCCESS);
379       // LCOV_EXCL_STOP 
380     }
381
382     char* firstword = (char*) xmalloc(strlen(reply)+1);
383     sscanf(reply, "%s", firstword);
384
385     for (int i = 0; i < (int)strlen(firstword); ++i)
386       firstword[i] = tolower(firstword[i]);
387
388     int yes = strncmp("yes", firstword, sizeof("yes") - 1);
389     int y = strncmp("y", firstword, sizeof("y") - 1);
390     int no = strncmp("no", firstword, sizeof("no") - 1);
391     int n = strncmp("n", firstword, sizeof("n") - 1);
392
393     free(firstword);
394
395     if (yes == 0 || y == 0) {
396       outcome = true;
397       break;
398     } else if (no == 0 || n == 0) {
399       outcome = false;
400       break;
401     } else
402       rspeak(PLEASE_ANSWER);
403   }
404   linenoiseFree(reply);
405   return (outcome);
406 }
407
408
409 bool yes(const char* question, const char* yes_response, const char* no_response)
410 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
411  *  if no, print Z and return false. */
412 {
413     char* reply;
414     bool outcome;
415
416     for (;;) {
417         speak(question);
418
419         reply = get_input();
420         if (reply == NULL) {
421             // LCOV_EXCL_START
422             // Should be unreachable. Reply should never be NULL
423             linenoiseFree(reply);
424             exit(EXIT_SUCCESS);
425             // LCOV_EXCL_STOP 
426         }
427
428         char* firstword = (char*) xmalloc(strlen(reply)+1);
429         sscanf(reply, "%s", firstword);
430
431         for (int i = 0; i < (int)strlen(firstword); ++i)
432             firstword[i] = tolower(firstword[i]);
433
434         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
435         int y = strncmp("y", firstword, sizeof("y") - 1);
436         int no = strncmp("no", firstword, sizeof("no") - 1);
437         int n = strncmp("n", firstword, sizeof("n") - 1);
438
439         free(firstword);
440
441         if (yes == 0 || y == 0) {
442             speak(yes_response);
443             outcome = true;
444             break;
445         } else if (no == 0 || n == 0) {
446             speak(no_response);
447             outcome = false;
448             break;
449         } else
450             rspeak(PLEASE_ANSWER);
451     }
452     linenoiseFree(reply);
453     return (outcome);
454 }
455
456 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
457
458 long GETTXT(bool skip, bool onewrd, bool upper)
459 /*  Take characters from an input line and pack them into 30-bit words.
460  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
461  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
462  *  end of the line, the word is filled up with blanks (which encode as 0's).
463  *  If we're already at end of line when TEXT is called, we return -1. */
464 {
465     long text;
466     static long splitting = -1;
467
468     if (LNPOSN != splitting)
469         splitting = -1;
470     text = -1;
471     while (true) {
472         if (LNPOSN > LNLENG)
473             return (text);
474         if ((!skip) || INLINE[LNPOSN] != 0)
475             break;
476         ++LNPOSN;
477     }
478
479     text = 0;
480     for (int I = 1; I <= TOKLEN; I++) {
481         text = text * 64;
482         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
483             continue;
484         char current = INLINE[LNPOSN];
485         if (current < ascii_to_advent['%']) {
486             splitting = -1;
487             if (upper && current >= ascii_to_advent['a'])
488                 current = current - 26;
489             text = text + current;
490             ++LNPOSN;
491             continue;
492         }
493         if (splitting != LNPOSN) {
494             text = text + ascii_to_advent['%'];
495             splitting = LNPOSN;
496             continue;
497         }
498
499         text = text + current - ascii_to_advent['%'];
500         splitting = -1;
501         ++LNPOSN;
502     }
503
504     return text;
505 }
506
507 token_t MAKEWD(long letters)
508 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
509  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
510  *  the one that GETTXT would return given those characters plus
511  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
512  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
513  *  increment a letter by 5 by adding 50 to the next pair of
514  *  digits. */
515 {
516     long i = 1, word = 0;
517
518     for (long k = letters; k != 0; k = k / 100) {
519         word = word + i * (MOD(k, 50) + 10);
520         i = i * 64;
521         if (MOD(k, 100) > 50)word = word + i * 5;
522     }
523     i = 64L * 64L * 64L * 64L * 64L / i;
524     word = word * i;
525     return word;
526 }
527
528 /*  Data structure  routines */
529
530 long vocab(long id, long init)
531 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
532  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
533  *  up a keyword variable, and not finding it constitutes a bug.  It also means
534  *  that only KTAB values which taken over 1000 equal INIT may be considered.
535  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
536  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
537 {
538     long lexeme;
539
540     for (long i = 1; i <= TABSIZ; i++) {
541         if (KTAB[i] == -1) {
542             lexeme = -1;
543             if (init < 0)
544                 return (lexeme);
545             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND); // LCOV_EXCL_LINE
546         }
547         if (init >= 0 && KTAB[i] / 1000 != init)
548             continue;
549         if (ATAB[i] == id) {
550             lexeme = KTAB[i];
551             if (init >= 0)
552                 lexeme = MOD(lexeme, 1000);
553             return (lexeme);
554         }
555     }
556     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE); // LCOV_EXCL_LINE
557 }
558
559 int get_motion_vocab_id(const char* word)
560 // Return the first motion number that has 'word' as one of its words.
561 {
562   for (int i = 0; i < NMOTIONS; ++i)
563     {
564       for (int j = 0; j < motions[i].words.n; ++j)
565         {
566           if (strcasecmp(word, motions[i].words.strs[j]) == 0)
567             return(i);
568         }
569     }
570   // If execution reaches here, we didn't find the word.
571   return(WORD_NOT_FOUND);
572 }
573
574 int get_object_vocab_id(const char* word)
575 // Return the first object number that has 'word' as one of its words.
576 {
577   for (int i = 0; i < NOBJECTS + 1; ++i) // FIXME: the + 1 should go when 1-indexing for objects is removed
578     {
579       for (int j = 0; j < objects[i].words.n; ++j)
580         {
581           if (strcasecmp(word, objects[i].words.strs[j]) == 0)
582             return(i);
583         }
584     }
585   // If execution reaches here, we didn't find the word.
586   return(WORD_NOT_FOUND);
587 }
588
589 int get_action_vocab_id(const char* word)
590 // Return the first motion number that has 'word' as one of its words.
591 {
592   for (int i = 0; i < NACTIONS; ++i)
593     {
594       for (int j = 0; j < actions[i].words.n; ++j)
595         {
596           if (strcasecmp(word, actions[i].words.strs[j]) == 0)
597             return(i);
598         }
599     }
600   // If execution reaches here, we didn't find the word.
601   return(WORD_NOT_FOUND);
602 }
603
604 int get_special_vocab_id(const char* word)
605 // Return the first special number that has 'word' as one of its words.
606 {
607   for (int i = 0; i < NSPECIALS; ++i)
608     {
609       for (int j = 0; j < specials[i].words.n; ++j)
610         {
611           if (strcasecmp(word, specials[i].words.strs[j]) == 0)
612             return(i);
613         }
614     }
615   // If execution reaches here, we didn't find the word.
616   return(WORD_NOT_FOUND);
617 }
618
619 long get_vocab_id(const char* word)
620 // Search the vocab categories in order for the supplied word.
621 {
622   long ref_num;
623   
624   ref_num = get_motion_vocab_id(word);
625   if (ref_num != WORD_NOT_FOUND)
626     return(ref_num + 0); // FIXME: replace with a proper hash
627
628   ref_num = get_object_vocab_id(word);
629   if (ref_num != WORD_NOT_FOUND)
630     return(ref_num + 1000); // FIXME: replace with a proper hash
631
632   ref_num = get_action_vocab_id(word);
633   if (ref_num != WORD_NOT_FOUND)
634     return(ref_num + 2000); // FIXME: replace with a proper hash
635
636   ref_num = get_special_vocab_id(word);
637   if (ref_num != WORD_NOT_FOUND)
638     return(ref_num + 3000); // FIXME: replace with a proper hash
639
640   // Check for the reservoir magic word.
641   if (strcasecmp(word, game.zzword) == 0)
642     return(PART + 2000); // FIXME: replace with a proper hash
643
644   return(WORD_NOT_FOUND);
645 }
646
647 void juggle(long object)
648 /*  Juggle an object by picking it up and putting it down again, the purpose
649  *  being to get the object to the front of the chain of things at its loc. */
650 {
651     long i, j;
652
653     i = game.place[object];
654     j = game.fixed[object];
655     move(object, i);
656     move(object + NOBJECTS, j);
657 }
658
659 void move(long object, long where)
660 /*  Place any object anywhere by picking it up and dropping it.  May
661  *  already be toting, in which case the carry is a no-op.  Mustn't
662  *  pick up objects which are not at any loc, since carry wants to
663  *  remove objects from game.atloc chains. */
664 {
665     long from;
666
667     if (object > NOBJECTS)
668         from = game.fixed[object - NOBJECTS];
669     else
670         from = game.place[object];
671     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
672         carry(object, from);
673     drop(object, where);
674 }
675
676 long put(long object, long where, long pval)
677 /*  PUT is the same as MOVE, except it returns a value used to set up the
678  *  negated game.prop values for the repository objects. */
679 {
680     move(object, where);
681     return (-1) - pval;;
682 }
683
684 void carry(long object, long where)
685 /*  Start toting an object, removing it from the list of things at its former
686  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
687  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
688 {
689     long temp;
690
691     if (object <= NOBJECTS) {
692         if (game.place[object] == CARRIED)
693             return;
694         game.place[object] = CARRIED;
695         ++game.holdng;
696     }
697     if (game.atloc[where] == object) {
698         game.atloc[where] = game.link[object];
699         return;
700     }
701     temp = game.atloc[where];
702     while (game.link[temp] != object) {
703         temp = game.link[temp];
704     }
705     game.link[temp] = game.link[object];
706 }
707
708 void drop(long object, long where)
709 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
710  *  game.holdng if the object was being toted. */
711 {
712     if (object > NOBJECTS)
713         game.fixed[object - NOBJECTS] = where;
714     else {
715         if (game.place[object] == CARRIED)
716             --game.holdng;
717         game.place[object] = where;
718     }
719     if (where <= 0)
720         return;
721     game.link[object] = game.atloc[where];
722     game.atloc[where] = object;
723 }
724
725 long atdwrf(long where)
726 /*  Return the index of first dwarf at the given location, zero if no dwarf is
727  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
728  *  the pirate (6th dwarf). */
729 {
730     long at;
731
732     at = 0;
733     if (game.dflag < 2)
734         return (at);
735     at = -1;
736     for (long i = 1; i <= NDWARVES - 1; i++) {
737         if (game.dloc[i] == where)
738             return i;
739         if (game.dloc[i] != 0)
740             at = 0;
741     }
742     return (at);
743 }
744
745 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
746  *  randrange, RNDVOC) */
747
748 long setbit(long bit)
749 /*  Returns 2**bit for use in constructing bit-masks. */
750 {
751     return (1L << bit);
752 }
753
754 bool tstbit(long mask, int bit)
755 /*  Returns true if the specified bit is set in the mask. */
756 {
757     return (mask & (1 << bit)) != 0;
758 }
759
760 void set_seed(long seedval)
761 /* Set the LCG seed */
762 {
763     game.lcg_x = (unsigned long) seedval % game.lcg_m;
764 }
765
766 unsigned long get_next_lcg_value(void)
767 /* Return the LCG's current value, and then iterate it. */
768 {
769     unsigned long old_x = game.lcg_x;
770     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
771     return old_x;
772 }
773
774 long randrange(long range)
775 /* Return a random integer from [0, range). */
776 {
777     return range * get_next_lcg_value() / game.lcg_m;
778 }
779
780 long rndvoc(long second, long force)
781 /*  Searches the vocabulary ATAB for a word whose second character is
782  *  char, and changes that word such that each of the other four
783  *  characters is a random letter.  If force is non-zero, it is used
784  *  as the new word.  Returns the new word. */
785 {
786     long rnd = force;
787
788     if (rnd == 0) {
789         for (int i = 1; i <= 5; i++) {
790             long j = 11 + randrange(26);
791             if (i == 2)
792                 j = second;
793             rnd = rnd * 64 + j;
794         }
795     }
796
797     long div = 64L * 64L * 64L;
798     for (int i = 1; i <= TABSIZ; i++) {
799         if (MOD(ATAB[i] / div, 64L) == second) {
800             ATAB[i] = rnd;
801             break;
802         }
803     }
804
805     return rnd;
806 }
807
808 void make_zzword(char zzword[6])
809 {
810   for (int i = 0; i < 5; ++i)
811     {
812       zzword[i] = 'A' + randrange(26);
813     }
814   zzword[1] = '\''; // force second char to apostrophe
815   zzword[5] = '\0';
816 }
817
818 /*  Machine dependent routines (MAPLIN, SAVEIO) */
819
820 bool MAPLIN(FILE *fp)
821 {
822     bool eof;
823
824     /* Read a line of input, from the specified input source.
825      * This logic is complicated partly because it has to serve
826      * several cases with different requirements and partly because
827      * of a quirk in linenoise().
828      *
829      * The quirk shows up when you paste a test log from the clipboard
830      * to the program's command prompt.  While fgets (as expected)
831      * consumes it a line at a time, linenoise() returns the first
832      * line and discards the rest.  Thus, there needs to be an
833      * editline (-s) option to fall back to fgets while still
834      * prompting.  Note that linenoise does behave properly when
835      * fed redirected stdin.
836      *
837      * The logging is a bit of a mess because there are two distinct cases
838      * in which you want to echo commands.  One is when shipping them to
839      * a log under the -l option, in which case you want to suppress
840      * prompt generation (so test logs are unadorned command sequences).
841      * On the other hand, if you redirected stdin and are feeding the program
842      * a logfile, you *do* want prompt generation - it makes checkfiles
843      * easier to read when the commands are marked by a preceding prompt.
844      */
845     do {
846         if (!editline) {
847             if (prompt)
848                 fputs("> ", stdout);
849             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
850             eof = (feof(fp));
851         } else {
852             char *cp = linenoise("> ");
853             eof = (cp == NULL);
854             if (!eof) {
855                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
856                 linenoiseHistoryAdd(rawbuf);
857                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
858                 linenoiseFree(cp);
859             }
860         }
861     } while
862     (!eof && rawbuf[0] == '#');
863     if (eof) {
864         if (logfp && fp == stdin)
865             fclose(logfp);
866         return false;
867     } else {
868         FILE *efp = NULL;
869         if (logfp && fp == stdin)
870             efp = logfp;
871         else if (!isatty(0))
872             efp = stdout;
873         if (efp != NULL) {
874             if (prompt && efp == stdout)
875                 fputs("> ", efp);
876             IGNORE(fputs(rawbuf, efp));
877         }
878         strcpy(INLINE + 1, rawbuf);
879         /*  translate the chars to integers in the range 0-126 and store
880          *  them in the common array "INLINE".  Integer values are as follows:
881          *     0   = space [ASCII CODE 40 octal, 32 decimal]
882          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
883          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
884          *   11-36 = upper-case letters
885          *   37-62 = lower-case letters
886          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
887          *   64-73 = digits, 0 through 9
888          *  Remaining characters can be translated any way that is convenient;
889          *  The above mappings are required so that certain special
890          *  characters are known to fit in 6 bits and/or can be easily spotted.
891          *  Array elements beyond the end of the line should be filled with 0,
892          *  and LNLENG should be set to the index of the last character.
893          *
894          *  If the data file uses a character other than space (e.g., tab) to
895          *  separate numbers, that character should also translate to 0.
896          *
897          *  This procedure may use the map1,map2 arrays to maintain
898          *  static data for he mapping.  MAP2(1) is set to 0 when the
899          *  program starts and is not changed thereafter unless the
900          *  routines in this module choose to do so. */
901         LNLENG = 0;
902         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
903             long val = INLINE[i];
904             INLINE[i] = ascii_to_advent[val];
905             if (INLINE[i] != 0)
906                 LNLENG = i;
907         }
908         LNPOSN = 1;
909         return true;
910     }
911 }
912
913 void datime(long* d, long* t)
914 {
915     struct timeval tv;
916     gettimeofday(&tv, NULL);
917     *d = (long) tv.tv_sec;
918     *t = (long) tv.tv_usec;
919 }
920
921 // LCOV_EXCL_START
922 void bug(enum bugtype num, const char *error_string)
923 {
924     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
925     exit(EXIT_FAILURE);
926 }
927 // LCOV_EXCL_STOP
928
929 /* end */