Working first draft of newspeak().
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <sys/time.h>
6 #include <ctype.h>
7
8 #include "advent.h"
9 #include "database.h"
10 #include "linenoise/linenoise.h"
11 #include "newdb.h"
12
13 void* xmalloc(size_t size)
14 {
15   void* ptr = malloc(size);
16   if (ptr == NULL)
17     {
18       fprintf(stderr, "Out of memory!\n");
19       exit(EXIT_FAILURE);
20     }
21   return(ptr);
22 }
23
24 void packed_to_token(long packed, char token[6])
25 {
26   for (int i = 0; i < 5; ++i)
27     {
28       char advent = (packed >> i * 6) & 63;
29       token[i] = advent_to_ascii[advent];
30     }
31   token[5] = '\0';
32 }
33
34 /*  I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
35
36 void newspeak(char* msg)
37 {
38   // Do nothing if we got a null pointer.
39   if (msg == NULL)
40     return;
41
42   // Do nothing if we got an empty string.
43   if (strlen(msg) == 0)
44     return;
45
46   // Print a newline if the global game.blklin says to.
47   if (game.blklin == true)
48     printf("\n");
49
50   // Create a copy of our string, so we can edit it.
51   char* copy = (char*) xmalloc(strlen(msg) + 1);
52   strncpy(copy, msg, strlen(msg) + 1);
53
54   // Staging area for stringified parameters.
55   char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
56  
57   // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
58   int pi = 0; // parameter index
59   for (int i = 0; i < strlen(msg); ++i)
60     {
61       if (msg[i] == '%')
62         {
63           ++pi;
64
65           // 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.
66           if (msg[i + 1] == 'd')
67             {
68               copy[i + 1] = 's';
69               sprintf(parameters[pi], "%d", PARMS[pi]);
70             }
71
72           // Unmodified string specifier.
73           if (msg[i + 1] == 's')
74             {
75               packed_to_token(PARMS[pi], parameters[pi]);
76             }
77
78           // Singular/plural specifier.
79           if (msg[i + 1] == 'S')
80             {
81               copy[i + 1] = 's';
82               if (PARMS[pi - 1] > 1) // look at the *previous* parameter (which by necessity must be numeric)
83                 {
84                   sprintf(parameters[pi], "%s", "s");
85                 }
86               else
87                 {
88                   sprintf(parameters[pi], "%s", "");
89                 }
90             }
91
92           // All-lowercase specifier.
93           if (msg[i + 1] == 'L')
94             {
95               copy[i + 1] = 's';
96               packed_to_token(PARMS[pi], parameters[pi]);
97               for (int i = 0; i < strlen(parameters[pi]); ++i)
98                 {
99                   parameters[pi][i] = tolower(parameters[pi][i]);
100                 }
101             }
102
103           // First char uppercase, rest lowercase.
104           if (msg[i + 1] == 'C')
105             {
106               copy[i + 1] = 's';
107               packed_to_token(PARMS[pi], parameters[pi]);
108               for (int i = 0; i < strlen(parameters[pi]); ++i)
109                 {
110                   parameters[pi][i] = tolower(parameters[pi][i]);
111                 }
112               parameters[pi][0] = toupper(parameters[pi][0]);
113             }
114         }
115     }
116
117   // Render the final string.
118   char rendered[2000]; // FIXME: to be replaced with dynamic allocation
119   sprintf(&rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
120
121   // Print the message.
122   printf("%s\n", rendered);
123
124   free(copy);
125 }
126
127 void SPEAK(vocab_t msg)
128 /*  Print the message which starts at LINES[N].  Precede it with a blank line
129  *  unless game.blklin is false. */
130 {
131     long blank, casemake, i, nxt, neg, nparms, param, prmtyp, state;
132
133     if (msg == 0)
134         return;
135     blank=game.blklin;
136     nparms=1;
137     do {
138         nxt=labs(LINES[msg])-1;
139         ++msg;
140         LNLENG=0;
141         LNPOSN=1;
142         state=0;
143         for (i = msg; i <= nxt; i++) {
144             PUTTXT(LINES[i],&state,2);
145         }
146         LNPOSN=0;
147         ++LNPOSN;
148
149         while (LNPOSN <= LNLENG) { 
150             if (INLINE[LNPOSN] != ascii_to_advent['%']) {
151                 ++LNPOSN;
152                 continue;
153             }
154             prmtyp = INLINE[LNPOSN+1];
155             /*  A "%"; the next character determine the type of
156              *  parameter: 1 (!) = suppress message completely, 29 (S) = NULL
157              *  If PARAM=1, else 'S' (optional plural ending), 33 (W) = word
158              *  (two 30-bit values) with trailing spaces suppressed, 22 (L) or
159              *  31 (U) = word but map to lower/upper case, 13 (C) = word in
160              *  lower case with first letter capitalised, 65-73 (1-9) =
161              *  number using that many characters. */
162             if (prmtyp == ascii_to_advent['!'])
163                 return;
164             if (prmtyp == ascii_to_advent['S']) {
165                 SHFTXT(LNPOSN+2,-1);
166                 INLINE[LNPOSN] = ascii_to_advent['s'];
167                 if (PARMS[nparms] == 1)
168                     SHFTXT(LNPOSN+1,-1);
169                 ++nparms;
170                 continue;
171             }
172             if (prmtyp == ascii_to_advent['W'] || prmtyp == ascii_to_advent['L'] || prmtyp == ascii_to_advent['U'] || prmtyp == ascii_to_advent['C']) {
173                 SHFTXT(LNPOSN+2,-2);
174                 state = 0;
175                 casemake = -1;
176                 if (prmtyp == ascii_to_advent['U'])
177                     casemake=1;
178                 if (prmtyp == ascii_to_advent['W'])
179                     casemake=0;
180                 i = LNPOSN;
181                 PUTTXT(PARMS[nparms],&state,casemake);
182                 PUTTXT(PARMS[nparms+1],&state,casemake);
183                 if (prmtyp == ascii_to_advent['C'] && INLINE[i] >= ascii_to_advent['a'] && INLINE[i] <= ascii_to_advent['z'])
184                   {
185                     // Convert to uppercase.
186                     // Round-trip to ASCII and back so that this code doesn't break when the mapping changes.
187                     // This can be simplified when mapping goes away.
188                     char this = advent_to_ascii[INLINE[i]];
189                     char uc_this = toupper(this);
190                     INLINE[i] = ascii_to_advent[uc_this];
191                   }
192                 nparms += 2;
193                 continue;
194             }
195
196             prmtyp=prmtyp-64;
197             if (prmtyp < ascii_to_advent['!'] || prmtyp > ascii_to_advent['-']) {
198                 ++LNPOSN;
199                 continue;
200             }
201             SHFTXT(LNPOSN+2,prmtyp-2);
202             LNPOSN += prmtyp;
203             param=labs(PARMS[nparms]);
204             neg=0;
205             if (PARMS[nparms] < 0)
206                 neg=9;
207             for (i=1; i <= prmtyp; i++) {
208                 --LNPOSN;
209                 INLINE[LNPOSN]=MOD(param,10)+64;
210                 if (i != 1 && param == 0) {
211                     INLINE[LNPOSN]=neg;
212                     neg=0;
213                 }
214                 param=param/10;
215             }
216             LNPOSN += prmtyp;
217             ++nparms;
218             continue;
219         }
220
221         if (blank)
222             TYPE0();
223         blank=false;
224         TYPE();
225         msg = nxt + 1;
226     } while
227         (LINES[msg] >= 0);
228 }
229
230 void PSPEAK(vocab_t msg,int skip)
231 /*  Find the skip+1st message from msg and print it.  msg should be
232  *  the index of the inventory message for object.  (INVEN+N+1 message
233  *  is game.prop=N message). */
234 {
235   if (skip >= 0)
236     newspeak(object_descriptions[msg].longs[skip]);
237   else
238     newspeak(object_descriptions[msg].inventory);
239 }
240
241 void RSPEAK(vocab_t i)
242 /* Print the i-th "random" message (section 6 of database). */
243 {
244   newspeak(arbitrary_messages[i]);
245 }
246
247 void SETPRM(long first, long p1, long p2)
248 /*  Stores parameters into the PRMCOM parms array for use by speak.  P1 and P2
249  *  are stored into PARMS(first) and PARMS(first+1). */
250 {
251     if (first >= MAXPARMS)
252         BUG(29);
253     else {
254         PARMS[first] = p1;
255         PARMS[first+1] = p2;
256     }
257 }
258
259 bool GETIN(FILE *input,
260             long *pword1, long *pword1x, 
261             long *pword2, long *pword2x) 
262 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
263  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
264  *  case we need to print out the whole word in an error message.  Any number of
265  *  blanks may follow the word.  If a second word appears, it is returned in
266  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
267 {
268     long junk;
269
270     for (;;) {
271         if (game.blklin)
272             TYPE0();
273         if (!MAPLIN(input))
274             return false;
275         *pword1=GETTXT(true,true,true);
276         if (game.blklin && *pword1 < 0)
277             continue;
278         *pword1x=GETTXT(false,true,true);
279         do {    
280             junk=GETTXT(false,true,true);
281         } while 
282             (junk > 0);
283         *pword2=GETTXT(true,true,true);
284         *pword2x=GETTXT(false,true,true);
285         do {
286             junk=GETTXT(false,true,true);
287         } while 
288             (junk > 0);
289         if (GETTXT(true,true,true) <= 0)
290             return true;
291         RSPEAK(53);
292     }
293 }
294
295 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
296 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
297  *  if no, print Z and return false. */
298 {
299     token_t reply, junk1, junk2, junk3;
300
301     for (;;) {
302         RSPEAK(x);
303         GETIN(input, &reply, &junk1, &junk2, &junk3);
304         if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
305             RSPEAK(y);
306             return true;
307         }
308         if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
309             RSPEAK(z);
310             return false;
311         }
312         RSPEAK(185);
313     }
314 }
315
316 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
317
318 long GETTXT(bool skip, bool onewrd, bool upper)
319 /*  Take characters from an input line and pack them into 30-bit words.
320  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
321  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
322  *  end of the line, the word is filled up with blanks (which encode as 0's).
323  *  If we're already at end of line when TEXT is called, we return -1. */
324 {
325     long text;
326     static long splitting = -1;
327
328     if (LNPOSN != splitting)
329         splitting = -1;
330     text= -1;
331     while (true) {
332         if (LNPOSN > LNLENG)
333             return(text);
334         if ((!skip) || INLINE[LNPOSN] != 0)
335             break;
336         ++LNPOSN;
337     }
338
339     text=0;
340     for (int I=1; I<=TOKLEN; I++) {
341         text=text*64;
342         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
343             continue;
344         char current=INLINE[LNPOSN];
345         if (current < ascii_to_advent['%']) {
346             splitting = -1;
347             if (upper && current >= ascii_to_advent['a'])
348                 current=current-26;
349             text=text+current;
350             ++LNPOSN;
351             continue;
352         }
353         if (splitting != LNPOSN) {
354             text=text+ascii_to_advent['%'];
355             splitting = LNPOSN;
356             continue;
357         }
358
359         text=text+current-ascii_to_advent['%'];
360         splitting = -1;
361         ++LNPOSN;
362     }
363
364     return text;
365 }
366
367 token_t MAKEWD(long letters)
368 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
369  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
370  *  the one that GETTXT would return given those characters plus
371  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
372  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
373  *  increment a letter by 5 by adding 50 to the next pair of
374  *  digits. */
375 {
376     long i = 1, word = 0;
377
378     for (long k=letters; k != 0; k=k/100) {
379         word=word+i*(MOD(k,50)+10);
380         i=i*64;
381         if (MOD(k,100) > 50)word=word+i*5;
382     }
383     i=64L*64L*64L*64L*64L/i;
384     word=word*i;
385     return word;
386 }
387
388 void PUTTXT(token_t word, long *state, long casemake)
389 /*  Unpack the 30-bit value in word to obtain up to TOKLEN (currently
390  *  5) integer-encoded chars, and store them in inline starting at
391  *  LNPOSN.  If LNLENG>=LNPOSN, shift existing characters to the right
392  *  to make room.  STATE will be zero when puttxt is called with the
393  *  first of a sequence of words, but is thereafter unchanged by the
394  *  caller, so PUTTXT can use it to maintain state across calls.
395  *  LNPOSN and LNLENG are incremented by the number of chars stored.
396  *  If CASEMAKE=1, all letters are made uppercase; if -1, lowercase; if 0,
397  *  as is.  any other value for case is the same as 0 but also causes
398  *  trailing blanks to be included (in anticipation of subsequent
399  *  additional text). */
400 {
401     long alph1, alph2, byte, div, i, w;
402
403     alph1=13*casemake+24;
404     alph2=26*labs(casemake)+alph1;
405     if (labs(casemake) > 1)
406         alph1=alph2;
407     /*  alph1&2 define range of wrong-case chars, 11-36 or 37-62 or empty. */
408     div=64L*64L*64L*64L;
409     w=word;
410     for (i=1; i<=TOKLEN; i++) 
411     {
412         if (w <= 0 && *state == 0 && labs(casemake) <= 1)
413             return;
414         byte=w/div;
415         w=(w-byte*div)*64;
416         if (!(*state != 0 || byte != ascii_to_advent['%'])) {
417             *state=ascii_to_advent['%'];
418             continue;
419         }
420         SHFTXT(LNPOSN,1);
421         *state=*state+byte;
422         if (*state < alph2 && *state >= alph1)*state=*state-26*casemake;
423         INLINE[LNPOSN]=*state;
424         ++LNPOSN;
425         *state=0;
426     }
427 }
428 #define PUTTXT(WORD,STATE,CASE) fPUTTXT(WORD,&STATE,CASE)
429
430 void SHFTXT(long from, long delta) 
431 /*  Move INLINE(N) to INLINE(N+DELTA) for N=FROM,LNLENG.  Delta can be
432  *  negative.  LNLENG is updated; LNPOSN is not changed. */
433 {
434     long I, k, j;
435
436     if (!(LNLENG < from || delta == 0)) {
437         for (I=from; I<=LNLENG; I++) {
438             k=I;
439             if (delta > 0)
440                 k=from+LNLENG-I;
441             j=k+delta;
442             INLINE[j]=INLINE[k];
443         }
444     }
445     LNLENG=LNLENG+delta;
446 }
447
448 void TYPE0(void)
449 /*  Type a blank line.  This procedure is provided as a convenience for callers
450  *  who otherwise have no use for MAPCOM. */
451 {
452     long temp;
453
454     temp=LNLENG;
455     LNLENG=0;
456     TYPE();
457     LNLENG=temp;
458     return;
459 }
460
461 /*  Data structure  routines */
462
463 long VOCAB(long id, long init) 
464 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
465  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
466  *  up a keyword variable, and not finding it constitutes a bug.  It also means
467  *  that only KTAB values which taken over 1000 equal INIT may be considered.
468  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
469  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
470 {
471     long i, lexeme;
472
473     for (i=1; i<=TABSIZ; i++) {
474         if (KTAB[i] == -1) {
475             lexeme= -1;
476             if (init < 0)
477                 return(lexeme);
478             BUG(5);
479         }
480         if (init >= 0 && KTAB[i]/1000 != init) 
481             continue;
482         if (ATAB[i] == id) {
483             lexeme=KTAB[i];
484             if (init >= 0)
485                 lexeme=MOD(lexeme,1000);
486             return(lexeme);
487         }
488     }
489     BUG(21);
490 }
491
492 void DSTROY(long object)
493 /*  Permanently eliminate "object" by moving to a non-existent location. */
494 {
495     MOVE(object,0);
496 }
497
498 void JUGGLE(long object)
499 /*  Juggle an object by picking it up and putting it down again, the purpose
500  *  being to get the object to the front of the chain of things at its loc. */
501 {
502     long i, j;
503
504     i=game.place[object];
505     j=game.fixed[object];
506     MOVE(object,i);
507     MOVE(object+NOBJECTS,j);
508 }
509
510 void MOVE(long object, long where)
511 /*  Place any object anywhere by picking it up and dropping it.  May
512  *  already be toting, in which case the carry is a no-op.  Mustn't
513  *  pick up objects which are not at any loc, since carry wants to
514  *  remove objects from game.atloc chains. */
515 {
516     long from;
517
518     if (object > NOBJECTS) 
519         from=game.fixed[object-NOBJECTS];
520     else
521         from=game.place[object];
522     if (from > 0 && from <= 300)
523         CARRY(object,from);
524     DROP(object,where);
525 }
526
527 long PUT(long object, long where, long pval)
528 /*  PUT is the same as MOVE, except it returns a value used to set up the
529  *  negated game.prop values for the repository objects. */
530 {
531     MOVE(object,where);
532     return (-1)-pval;;
533 }
534
535 void CARRY(long object, long where) 
536 /*  Start toting an object, removing it from the list of things at its former
537  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
538  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
539 {
540     long temp;
541
542     if (object <= NOBJECTS) {
543         if (game.place[object] == -1)
544             return;
545         game.place[object]= -1;
546         ++game.holdng;
547     }
548     if (game.atloc[where] == object) {
549         game.atloc[where]=game.link[object];
550         return;
551     }
552     temp=game.atloc[where];
553     while (game.link[temp] != object) {
554         temp=game.link[temp];
555     }
556     game.link[temp]=game.link[object];
557 }
558
559 void DROP(long object, long where)
560 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
561  *  game.holdng if the object was being toted. */
562 {
563     if (object > NOBJECTS)
564         game.fixed[object-NOBJECTS] = where;
565     else
566     {
567         if (game.place[object] == -1)
568             --game.holdng;
569         game.place[object] = where;
570     }
571     if (where <= 0)
572         return;
573     game.link[object] = game.atloc[where];
574     game.atloc[where] = object;
575 }
576
577 long ATDWRF(long where)
578 /*  Return the index of first dwarf at the given location, zero if no dwarf is
579  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
580  *  the pirate (6th dwarf). */
581 {
582     long at, i;
583
584     at =0;
585     if (game.dflag < 2)
586         return(at);
587     at = -1;
588     for (i=1; i<=NDWARVES-1; i++) {
589         if (game.dloc[i] == where)
590             return i;
591         if (game.dloc[i] != 0)
592             at=0;
593     }
594     return(at);
595 }
596
597 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
598  *  randrange, RNDVOC, BUG) */
599
600 long SETBIT(long bit)
601 /*  Returns 2**bit for use in constructing bit-masks. */
602 {
603     return(1 << bit);
604 }
605
606 bool TSTBIT(long mask, int bit)
607 /*  Returns true if the specified bit is set in the mask. */
608 {
609     return (mask & (1 << bit)) != 0;
610 }
611
612 void set_seed(long seedval)
613 /* Set the LCG seed */
614 {
615     lcgstate.x = (unsigned long) seedval % lcgstate.m;
616 }
617
618 unsigned long get_next_lcg_value(void)
619 /* Return the LCG's current value, and then iterate it. */
620 {
621     unsigned long old_x = lcgstate.x;
622     lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
623     return old_x;
624 }
625
626 long randrange(long range)
627 /* Return a random integer from [0, range). */
628 {
629     return range * get_next_lcg_value() / lcgstate.m;
630 }
631
632 long RNDVOC(long second, long force)
633 /*  Searches the vocabulary ATAB for a word whose second character is
634  *  char, and changes that word such that each of the other four
635  *  characters is a random letter.  If force is non-zero, it is used
636  *  as the new word.  Returns the new word. */
637 {
638     long rnd = force;
639
640     if (rnd == 0) {
641         for (int i = 1; i <= 5; i++) {
642             long j = 11 + randrange(26);
643             if (i == 2)
644                 j = second;
645             rnd = rnd * 64 + j;
646         }
647     }
648
649     long div = 64L * 64L * 64L;
650     for (int i = 1; i <= TABSIZ; i++) {
651         if (MOD(ATAB[i]/div, 64L) == second)
652         {
653             ATAB[i] = rnd;
654             break;
655         }
656     }
657
658     return rnd;
659 }
660
661 void BUG(long num)
662 /*  The following conditions are currently considered fatal bugs.  Numbers < 20
663  *  are detected while reading the database; the others occur at "run time".
664  *      0       Message line > 70 characters
665  *      1       Null line in message
666  *      2       Too many words of messages
667  *      3       Too many travel options
668  *      4       Too many vocabulary words
669  *      5       Required vocabulary word not found
670  *      6       Too many RTEXT messages
671  *      7       Too many hints
672  *      8       Location has cond bit being set twice
673  *      9       Invalid section number in database
674  *      10      Too many locations
675  *      11      Too many class or turn messages
676  *      20      Special travel (500>L>300) exceeds goto list
677  *      21      Ran off end of vocabulary table
678  *      22      Vocabulary type (N/1000) not between 0 and 3
679  *      23      Intransitive action verb exceeds goto list
680  *      24      Transitive action verb exceeds goto list
681  *      25      Conditional travel entry with no alternative
682  *      26      Location has no travel entries
683  *      27      Hint number exceeds goto list
684  *      28      Invalid month returned by date function
685  *      29      Too many parameters given to SETPRM */
686 {
687
688     printf("Fatal error %ld.  See source code for interpretation.\n", num);
689     exit(0);
690 }
691
692 /*  Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
693
694 bool MAPLIN(FILE *fp)
695 {
696     long i, val;
697     bool eof;
698
699     /*  Read a line of input, from the specified input source,
700      *  translate the chars to integers in the range 0-126 and store
701      *  them in the common array "INLINE".  Integer values are as follows:
702      *     0   = space [ASCII CODE 40 octal, 32 decimal]
703      *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
704      *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
705      *   11-36 = upper-case letters
706      *   37-62 = lower-case letters
707      *    63   = percent (%) [ASCII 45 octal, 37 decimal]
708      *   64-73 = digits, 0 through 9
709      *  Remaining characters can be translated any way that is convenient;
710      *  The "TYPE" routine below is used to map them back to characters when
711      *  necessary.  The above mappings are required so that certain special
712      *  characters are known to fit in 6 bits and/or can be easily spotted.
713      *  Array elements beyond the end of the line should be filled with 0,
714      *  and LNLENG should be set to the index of the last character.
715      *
716      *  If the data file uses a character other than space (e.g., tab) to
717      *  separate numbers, that character should also translate to 0.
718      *
719      *  This procedure may use the map1,map2 arrays to maintain static data for
720      *  the mapping.  MAP2(1) is set to 0 when the program starts
721      *  and is not changed thereafter unless the routines on this page choose
722      *  to do so. */
723
724     if (!oldstyle && !isatty(1))
725         fputs("> ", stdout);
726     do {
727         if (oldstyle) {
728             IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
729             eof = (feof(fp));
730         } else {
731             char *cp = linenoise("> ");
732             eof = (cp == NULL);
733             if (!eof) {
734                 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
735                 linenoiseHistoryAdd(rawbuf);
736                 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
737                 linenoiseFree(cp);
738             }
739         }
740     } while
741             (!eof && rawbuf[0] == '#');
742     if (eof) {
743         if (logfp && fp == stdin)
744             fclose(logfp);
745         return false;
746     } else {
747         if (logfp && fp == stdin)
748             IGNORE(fputs(rawbuf, logfp));
749         else if (!isatty(0))
750             IGNORE(fputs(rawbuf, stdout));
751         strcpy(INLINE+1, rawbuf);
752         LNLENG=0;
753         for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
754             val=INLINE[i];
755             INLINE[i]=ascii_to_advent[val];
756             if (INLINE[i] != 0)
757                 LNLENG=i;
758         }
759         LNPOSN=1;
760         return true;
761     }
762 }
763
764 void TYPE(void)
765 /*  Type the first "LNLENG" characters stored in inline, mapping them
766  *  from integers to text per the rules described above.  INLINE
767  *  may be changed by this routine. */
768 {
769     long i;
770
771     if (LNLENG == 0) {
772         printf("\n");
773         return;
774     }
775
776     for (i=1; i<=LNLENG; i++) {
777         INLINE[i]=advent_to_ascii[INLINE[i]];
778     }
779     INLINE[LNLENG+1]=0;
780     printf("%s\n", INLINE+1);
781     return;
782 }
783
784 void DATIME(long* d, long* t)
785 {
786     struct timeval tv;
787     gettimeofday(&tv, NULL);
788     *d = (long) tv.tv_sec;
789     *t = (long) tv.tv_usec;
790 }
791
792 long MOD(long n, long m) 
793 {
794     return(n%m);
795 }