Debian Codegraph @

terps/advsys/advmsg.c

raw symbols SCIP
1
2 /* advmsg.c - adventure interpreter message routines */
3 /*
4 Copyright (c) 1986, by David Michael Betz
5 All rights reserved
6 */
7 #include "header.h"
8
9 /* cache size */
10 #define CSIZE 8
11
12
13 /* message block cache */
14 static char *mbuffer[CSIZE]; /* message text block cache buffers */
15 static int mblock[CSIZE]; /* message text block cache block numbers */
16 static int mnext[CSIZE]; /* next most recently used block */
17 static int mhead,mtail; /* head and tail of lru list */
18
19 /* message file variables */
20 static int mbase; /* message base block */
21 static strid_t mfd; /* message file descriptor */
22
23 /* current message variables */
24 static int mblk; /* current block */
25 static char *mbuf; /* current buffer */
26 static int moff; /* current buffer offset */
27
28
29 /* Headers */
30 void get_block(unsigned int blk);
31 int decode(int ch);
32
33
34
35 /* msg_init - initialize the message routines */
36 void msg_init(strid_t fd,int base)
37 {
38 char *p;
39 int i;
40
41 /* remember the message file descriptor and base */
42 mbase = base;
43 mfd = fd;
44
45 /* initialize the cache */
46 if ((p = malloc(CSIZE * 512)) == NULL)
47 error("insufficient memory");
48
49 for (i = 0; i < CSIZE; i++) {
50 mbuffer[i] = p; p += 512;
51 mblock[i] = -1;
52 mnext[i] = i+1;
53 }
54 mhead = 0; mtail = CSIZE-1; mnext[mtail] = -1;
55 }
56
57 /* msg_open - open a message */
58 void msg_open(unsigned int msg)
59 {
60 /* save the current message block */
61 mblk = msg >> 7;
62
63 /* make sure the first block is in a buffer */
64 get_block(mblk);
65
66 /* setup the initial offset into the block */
67 moff = (msg & 0x7F) << 2;
68 }
69
70 /* msg_byte - get a byte from a message */
71 int msg_byte()
72 {
73 /* check for end of block and get next block */
74 if (moff >= 512) {
75 get_block(++mblk);
76 moff = 0;
77 }
78
79 /* return the next message byte */
80 return (decode(mbuf[moff++]));
81 }
82
83 /* decode - decode a character */
84 int decode(int ch)
85 {
86 return ((ch + 30) & 0xFF);
87 }
88
89 /* get_block - get a block of message text */
90 void get_block(unsigned int blk)
91 {
92 int last,n;
93 long loff;
94
95 /* first check the cache */
96 for (n = mhead; n != -1; last = n, n = mnext[n])
97 if (blk == mblock[n]) {
98 if (n != mhead) {
99 if ((mnext[last] = mnext[n]) == -1)
100 mtail = last;
101 mnext[n] = mhead;
102 mhead = n;
103 }
104 mbuf = mbuffer[n];
105 return;
106 }
107
108 /* overwrite the least recently used buffer */
109 mblock[mtail] = blk;
110 loff = ((long) mbase + (long) blk) << 9;
111 glk_stream_set_position(mfd,loff,seekmode_Start);
112 if (glk_get_buffer_stream(mfd,mbuffer[mtail],512) != 512)
113 error("error reading message text");
114
115 /* get the block */
116 get_block(blk);
117 }