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