xref: /dragonfly/games/hack/hack.rumors.c (revision cd1c6085)
1 /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
2 /* hack.rumors.c - version 1.0.3 */
3 /* $FreeBSD: src/games/hack/hack.rumors.c,v 1.3 1999/11/16 02:57:10 billf Exp $ */
4 
5 #include "hack.h"			/* for RUMORFILE and BSD (index) */
6 #define	CHARSZ	8			/* number of bits in a char */
7 int n_rumors = 0;
8 int n_used_rumors = -1;
9 char *usedbits;
10 
11 static void init_rumors(FILE *);
12 static bool skipline(FILE *);
13 static void outline(FILE *);
14 static bool used(int);
15 
16 static void
17 init_rumors(FILE *rumf)
18 {
19 	int i;
20 
21 	n_used_rumors = 0;
22 	while (skipline(rumf))
23 		n_rumors++;
24 	rewind(rumf);
25 	i = n_rumors / CHARSZ;
26 	usedbits = alloc((unsigned)(i + 1));
27 	for (; i >= 0; i--)
28 		usedbits[i] = 0;
29 }
30 
31 static bool
32 skipline(FILE *rumf)
33 {
34 	char line[COLNO];
35 
36 	for (;;) {
37 		if (!fgets(line, sizeof(line), rumf))
38 			return (0);
39 		if (strchr(line, '\n'))
40 			return (1);
41 	}
42 }
43 
44 static void
45 outline(FILE *rumf)
46 {
47 	char line[COLNO];
48 	char *ep;
49 
50 	if (!fgets(line, sizeof(line), rumf))
51 		return;
52 	if ((ep = strchr(line, '\n')) != NULL)
53 		*ep = 0;
54 	pline("This cookie has a scrap of paper inside! It reads: ");
55 	pline("%s", line);
56 }
57 
58 void
59 outrumor(void)
60 {
61 	int rn, i;
62 	FILE *rumf;
63 
64 	if (n_rumors <= n_used_rumors ||
65 	    (rumf = fopen(RUMORFILE, "r")) == NULL)
66 		return;
67 	if (n_used_rumors < 0)
68 		init_rumors(rumf);
69 	if (!n_rumors)
70 		goto none;
71 	rn = rn2(n_rumors - n_used_rumors);
72 	i = 0;
73 	while (rn || used(i)) {
74 		skipline(rumf);
75 		if (!used(i))
76 			rn--;
77 		i++;
78 	}
79 	usedbits[i / CHARSZ] |= (1 << (i % CHARSZ));
80 	n_used_rumors++;
81 	outline(rumf);
82 none:
83 	fclose(rumf);
84 }
85 
86 static bool
87 used(int i)
88 {
89 	return (usedbits[i / CHARSZ] & (1 << (i % CHARSZ)));
90 }
91