Merge from vendor branch GDB:
[dragonfly.git] / games / fortune / strfile / strfile.c
1 /*-
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Ken Arnold.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD: src/games/fortune/strfile/strfile.c,v 1.15.2.2 2001/03/05 11:52:37 kris Exp $
37  * $DragonFly: src/games/fortune/strfile/strfile.c,v 1.4 2005/09/01 22:45:35 liamfoy Exp $
38  *
39  * @(#) Copyright (c) 1989, 1993 The Regents of the University of California.  All rights reserved.
40  * @(#)strfile.c   8.1 (Berkeley) 5/31/93
41  * $FreeBSD: src/games/fortune/strfile/strfile.c,v 1.15.2.2 2001/03/05 11:52:37 kris Exp $
42  */
43
44 # include       <sys/param.h>
45 # include       <stdio.h>
46 # include       <stdlib.h>
47 # include       <ctype.h>
48 # include       <string.h>
49 # include       <time.h>
50 # include       <locale.h>
51 # include       <unistd.h>
52 # include       "strfile.h"
53
54 /*
55  *      This program takes a file composed of strings separated by
56  * lines starting with two consecutive delimiting character (default
57  * character is '%') and creates another file which consists of a table
58  * describing the file (structure from "strfile.h"), a table of seek
59  * pointers to the start of the strings, and the strings, each terminated
60  * by a null byte.  Usage:
61  *
62  *      % strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
63  *
64  *      C - Allow comments marked by a double delimiter at line's beginning
65  *      c - Change delimiting character from '%' to 'C'
66  *      s - Silent.  Give no summary of data processed at the end of
67  *          the run.
68  *      o - order the strings in alphabetic order
69  *      i - if ordering, ignore case
70  *      r - randomize the order of the strings
71  *      x - set rotated bit
72  *
73  *              Ken Arnold      Sept. 7, 1978 --
74  *
75  *      Added ordering options.
76  */
77
78 # define        TRUE    1
79 # define        FALSE   0
80
81 # define        STORING_PTRS    (Oflag || Rflag)
82 # define        CHUNKSIZE       512
83
84 # define        ALLOC(ptr,sz) { \
85                         if (ptr == NULL) \
86                                 ptr = malloc((unsigned int) (CHUNKSIZE * sizeof *ptr)); \
87                         else if (((sz) + 1) % CHUNKSIZE == 0) \
88                                 ptr = realloc((void *) ptr, ((unsigned int) ((sz) + CHUNKSIZE) * sizeof *ptr)); \
89                         if (ptr == NULL) { \
90                                 fprintf(stderr, "out of space\n"); \
91                                 exit(1); \
92                         } \
93                 }
94
95 #ifdef NO_VOID
96 # define        void    char
97 #endif
98
99 typedef struct {
100         char    first;
101         long    pos;
102 } STR;
103
104 char    *Infile         = NULL,         /* input file name */
105         Outfile[MAXPATHLEN] = "",       /* output file name */
106         Delimch         = '%';          /* delimiting character */
107
108 int     Cflag           = FALSE;        /* embedded comments */
109 int     Sflag           = FALSE;        /* silent run flag */
110 int     Oflag           = FALSE;        /* ordering flag */
111 int     Iflag           = FALSE;        /* ignore case flag */
112 int     Rflag           = FALSE;        /* randomize order flag */
113 int     Xflag           = FALSE;        /* set rotated bit */
114 long    Num_pts         = 0;            /* number of pointers/strings */
115
116 long    *Seekpts;
117
118 FILE    *Sort_1, *Sort_2;               /* pointers for sorting */
119
120 STRFILE Tbl;                            /* statistics table */
121
122 STR     *Firstch;                       /* first chars of each string */
123
124 void    add_offset (FILE *, long);
125 int     cmp_str (const void *, const void *);
126 static int      collate_range_cmp  (int, int);
127 void    do_order (void);
128 void    getargs (int, char **);
129 void    randomize (void);
130 void    usage (void);
131
132 /*
133  * main:
134  *      Drive the sucker.  There are two main modes -- either we store
135  *      the seek pointers, if the table is to be sorted or randomized,
136  *      or we write the pointer directly to the file, if we are to stay
137  *      in file order.  If the former, we allocate and re-allocate in
138  *      CHUNKSIZE blocks; if the latter, we just write each pointer,
139  *      and then seek back to the beginning to write in the table.
140  */
141 int
142 main(int ac, char **av)
143 {
144         char            *sp, dc;
145         FILE            *inf, *outf;
146         long           last_off, length, pos, *p;
147         int             first, cnt;
148         char            *nsp;
149         STR             *fp;
150         static char             string[257];
151
152         (void) setlocale(LC_ALL, "");
153
154         getargs(ac, av);                /* evalute arguments */
155         dc = Delimch;
156         if ((inf = fopen(Infile, "r")) == NULL) {
157                 perror(Infile);
158                 exit(1);
159         }
160
161         if ((outf = fopen(Outfile, "w")) == NULL) {
162                 perror(Outfile);
163                 exit(1);
164         }
165         if (!STORING_PTRS)
166                 (void) fseek(outf, (long) sizeof Tbl, 0);
167
168         /*
169          * Write the strings onto the file
170          */
171
172         Tbl.str_longlen = 0;
173         Tbl.str_shortlen = ~((unsigned long) 0);
174         Tbl.str_delim = dc;
175         Tbl.str_version = VERSION;
176         first = Oflag;
177         add_offset(outf, ftell(inf));
178         last_off = 0;
179         do {
180                 sp = fgets(string, 256, inf);
181                 if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
182                         pos = ftell(inf);
183                         length = pos - last_off - (sp ? strlen(sp) : 0);
184                         last_off = pos;
185                         if (!length)
186                                 continue;
187                         add_offset(outf, pos);
188                         if (Tbl.str_longlen < length)
189                                 Tbl.str_longlen = length;
190                         if (Tbl.str_shortlen > length)
191                                 Tbl.str_shortlen = length;
192                         first = Oflag;
193                 }
194                 else if (first) {
195                         for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
196                                 continue;
197                         ALLOC(Firstch, Num_pts);
198                         fp = &Firstch[Num_pts - 1];
199                         if (Iflag && isupper((unsigned char)*nsp))
200                                 fp->first = tolower((unsigned char)*nsp);
201                         else
202                                 fp->first = *nsp;
203                         fp->pos = Seekpts[Num_pts - 1];
204                         first = FALSE;
205                 }
206         } while (sp != NULL);
207
208         /*
209          * write the tables in
210          */
211
212         (void) fclose(inf);
213         Tbl.str_numstr = Num_pts - 1;
214
215         if (Cflag)
216                 Tbl.str_flags |= STR_COMMENTS;
217
218         if (Oflag)
219                 do_order();
220         else if (Rflag)
221                 randomize();
222
223         if (Xflag)
224                 Tbl.str_flags |= STR_ROTATED;
225
226         if (!Sflag) {
227                 printf("\"%s\" created\n", Outfile);
228                 if (Num_pts == 2)
229                         puts("There was 1 string");
230                 else
231                         printf("There were %ld strings\n", Num_pts - 1);
232                 printf("Longest string: %lu byte%s\n", Tbl.str_longlen,
233                        Tbl.str_longlen == 1 ? "" : "s");
234                 printf("Shortest string: %lu byte%s\n", Tbl.str_shortlen,
235                        Tbl.str_shortlen == 1 ? "" : "s");
236         }
237
238         rewind(outf);
239         Tbl.str_version = htonl(Tbl.str_version);
240         Tbl.str_numstr = htonl(Tbl.str_numstr);
241         Tbl.str_longlen = htonl(Tbl.str_longlen);
242         Tbl.str_shortlen = htonl(Tbl.str_shortlen);
243         Tbl.str_flags = htonl(Tbl.str_flags);
244         (void) fwrite((char *) &Tbl, sizeof Tbl, 1, outf);
245         if (STORING_PTRS) {
246                 for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
247                         *p = htonl(*p);
248                 (void) fwrite((char *) Seekpts, sizeof *Seekpts, (int) Num_pts, outf);
249         }
250         (void) fclose(outf);
251         exit(0);
252 }
253
254 /*
255  *      This routine evaluates arguments from the command line
256  */
257 void
258 getargs(int argc, char **argv)
259 {
260         int     ch;
261
262         while ((ch = getopt(argc, argv, "Cc:iorsx")) != EOF)
263                 switch(ch) {
264                 case 'C':                       /* embedded comments */
265                         Cflag++;
266                         break;
267                 case 'c':                       /* new delimiting char */
268                         Delimch = *optarg;
269                         if (!isascii(Delimch)) {
270                                 printf("bad delimiting character: '\\%o\n'",
271                                        (unsigned char)Delimch);
272                         }
273                         break;
274                 case 'i':                       /* ignore case in ordering */
275                         Iflag++;
276                         break;
277                 case 'o':                       /* order strings */
278                         Oflag++;
279                         break;
280                 case 'r':                       /* randomize pointers */
281                         Rflag++;
282                         break;
283                 case 's':                       /* silent */
284                         Sflag++;
285                         break;
286                 case 'x':                       /* set the rotated bit */
287                         Xflag++;
288                         break;
289                 case '?':
290                 default:
291                         usage();
292                 }
293         argv += optind;
294
295         if (*argv) {
296                 Infile = *argv;
297                 if (*++argv)
298                         (void) strcpy(Outfile, *argv);
299         }
300         if (!Infile) {
301                 puts("No input file name");
302                 usage();
303         }
304         if (*Outfile == '\0') {
305                 (void) strcpy(Outfile, Infile);
306                 (void) strcat(Outfile, ".dat");
307         }
308 }
309
310 void
311 usage(void)
312 {
313         (void) fprintf(stderr,
314             "strfile [-Ciorsx] [-c char] sourcefile [datafile]\n");
315         exit(1);
316 }
317
318 /*
319  * add_offset:
320  *      Add an offset to the list, or write it out, as appropriate.
321  */
322 void
323 add_offset(FILE *fp, long off)
324 {
325         long net;
326
327         if (!STORING_PTRS) {
328                 net = htonl(off);
329                 fwrite(&net, 1, sizeof net, fp);
330         } else {
331                 ALLOC(Seekpts, Num_pts + 1);
332                 Seekpts[Num_pts] = off;
333         }
334         Num_pts++;
335 }
336
337 /*
338  * do_order:
339  *      Order the strings alphabetically (possibly ignoring case).
340  */
341 void
342 do_order(void)
343 {
344         int     i;
345         long   *lp;
346         STR     *fp;
347
348         Sort_1 = fopen(Infile, "r");
349         Sort_2 = fopen(Infile, "r");
350         qsort((char *) Firstch, (int) Tbl.str_numstr, sizeof *Firstch, cmp_str);
351         i = Tbl.str_numstr;
352         lp = Seekpts;
353         fp = Firstch;
354         while (i--)
355                 *lp++ = fp++->pos;
356         (void) fclose(Sort_1);
357         (void) fclose(Sort_2);
358         Tbl.str_flags |= STR_ORDERED;
359 }
360
361 static int
362 collate_range_cmp (int c1, int c2)
363 {
364         static char s1[2], s2[2];
365         int ret;
366
367         c1 &= UCHAR_MAX;
368         c2 &= UCHAR_MAX;
369         if (c1 == c2)
370                 return (0);
371         s1[0] = c1;
372         s2[0] = c2;
373         if ((ret = strcoll(s1, s2)) != 0)
374                 return (ret);
375         return (c1 - c2);
376 }
377
378 /*
379  * cmp_str:
380  *      Compare two strings in the file
381  */
382 int
383 cmp_str(const void *s1, const void  *s2)
384 {
385         const STR       *p1, *p2;
386         int     c1, c2;
387         int     n1, n2;
388         int r;
389
390 # define        SET_N(nf,ch)    (nf = (ch == '\n'))
391 # define        IS_END(ch,nf)   (ch == EOF || (ch == (unsigned char) Delimch && nf))
392
393         p1 = (const STR *) s1;
394         p2 = (const STR *) s2;
395         
396         c1 = (unsigned char) p1->first;
397         c2 = (unsigned char) p2->first;
398         if ((r = collate_range_cmp(c1, c2)) != 0)
399                 return r;
400
401         (void) fseek(Sort_1, p1->pos, 0);
402         (void) fseek(Sort_2, p2->pos, 0);
403
404         n1 = FALSE;
405         n2 = FALSE;
406         while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0' && c1 != EOF)
407                 SET_N(n1, c1);
408         while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0' && c2 != EOF)
409                 SET_N(n2, c2);
410
411         while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
412                 if (Iflag) {
413                         if (isupper(c1))
414                                 c1 = tolower(c1);
415                         if (isupper(c2))
416                                 c2 = tolower(c2);
417                 }
418                 if ((r = collate_range_cmp(c1, c2)) != 0)
419                         return r;
420                 SET_N(n1, c1);
421                 SET_N(n2, c2);
422                 c1 = getc(Sort_1);
423                 c2 = getc(Sort_2);
424         }
425         if (IS_END(c1, n1))
426                 c1 = 0;
427         if (IS_END(c2, n2))
428                 c2 = 0;
429         return collate_range_cmp(c1, c2);
430 }
431
432 /*
433  * randomize:
434  *      Randomize the order of the string table.  We must be careful
435  *      not to randomize across delimiter boundaries.  All
436  *      randomization is done within each block.
437  */
438 void
439 randomize(void)
440 {
441         int     cnt, i;
442         long   tmp;
443         long   *sp;
444
445         srandomdev();
446
447         Tbl.str_flags |= STR_RANDOM;
448         cnt = Tbl.str_numstr;
449
450         /*
451          * move things around randomly
452          */
453
454         for (sp = Seekpts; cnt > 0; cnt--, sp++) {
455                 i = random() % cnt;
456                 tmp = sp[0];
457                 sp[0] = sp[i];
458                 sp[i] = tmp;
459         }
460 }