Merge from vendor branch LIBPCAP:
[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.3 2003/11/12 14:53:53 eirikn 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 main(ac, av)
142 int     ac;
143 char    **av;
144 {
145         char            *sp, dc;
146         FILE            *inf, *outf;
147         long           last_off, length, pos, *p;
148         int             first, cnt;
149         char            *nsp;
150         STR             *fp;
151         static char             string[257];
152
153         (void) setlocale(LC_ALL, "");
154
155         getargs(ac, av);                /* evalute arguments */
156         dc = Delimch;
157         if ((inf = fopen(Infile, "r")) == NULL) {
158                 perror(Infile);
159                 exit(1);
160         }
161
162         if ((outf = fopen(Outfile, "w")) == NULL) {
163                 perror(Outfile);
164                 exit(1);
165         }
166         if (!STORING_PTRS)
167                 (void) fseek(outf, (long) sizeof Tbl, 0);
168
169         /*
170          * Write the strings onto the file
171          */
172
173         Tbl.str_longlen = 0;
174         Tbl.str_shortlen = ~((unsigned long) 0);
175         Tbl.str_delim = dc;
176         Tbl.str_version = VERSION;
177         first = Oflag;
178         add_offset(outf, ftell(inf));
179         last_off = 0;
180         do {
181                 sp = fgets(string, 256, inf);
182                 if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
183                         pos = ftell(inf);
184                         length = pos - last_off - (sp ? strlen(sp) : 0);
185                         last_off = pos;
186                         if (!length)
187                                 continue;
188                         add_offset(outf, pos);
189                         if (Tbl.str_longlen < length)
190                                 Tbl.str_longlen = length;
191                         if (Tbl.str_shortlen > length)
192                                 Tbl.str_shortlen = length;
193                         first = Oflag;
194                 }
195                 else if (first) {
196                         for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
197                                 continue;
198                         ALLOC(Firstch, Num_pts);
199                         fp = &Firstch[Num_pts - 1];
200                         if (Iflag && isupper((unsigned char)*nsp))
201                                 fp->first = tolower((unsigned char)*nsp);
202                         else
203                                 fp->first = *nsp;
204                         fp->pos = Seekpts[Num_pts - 1];
205                         first = FALSE;
206                 }
207         } while (sp != NULL);
208
209         /*
210          * write the tables in
211          */
212
213         (void) fclose(inf);
214         Tbl.str_numstr = Num_pts - 1;
215
216         if (Cflag)
217                 Tbl.str_flags |= STR_COMMENTS;
218
219         if (Oflag)
220                 do_order();
221         else if (Rflag)
222                 randomize();
223
224         if (Xflag)
225                 Tbl.str_flags |= STR_ROTATED;
226
227         if (!Sflag) {
228                 printf("\"%s\" created\n", Outfile);
229                 if (Num_pts == 2)
230                         puts("There was 1 string");
231                 else
232                         printf("There were %ld strings\n", Num_pts - 1);
233                 printf("Longest string: %lu byte%s\n", Tbl.str_longlen,
234                        Tbl.str_longlen == 1 ? "" : "s");
235                 printf("Shortest string: %lu byte%s\n", Tbl.str_shortlen,
236                        Tbl.str_shortlen == 1 ? "" : "s");
237         }
238
239         rewind(outf);
240         Tbl.str_version = htonl(Tbl.str_version);
241         Tbl.str_numstr = htonl(Tbl.str_numstr);
242         Tbl.str_longlen = htonl(Tbl.str_longlen);
243         Tbl.str_shortlen = htonl(Tbl.str_shortlen);
244         Tbl.str_flags = htonl(Tbl.str_flags);
245         (void) fwrite((char *) &Tbl, sizeof Tbl, 1, outf);
246         if (STORING_PTRS) {
247                 for (p = Seekpts, cnt = Num_pts; cnt--; ++p)
248                         *p = htonl(*p);
249                 (void) fwrite((char *) Seekpts, sizeof *Seekpts, (int) Num_pts, outf);
250         }
251         (void) fclose(outf);
252         exit(0);
253 }
254
255 /*
256  *      This routine evaluates arguments from the command line
257  */
258 void getargs(argc, argv)
259 int     argc;
260 char    **argv;
261 {
262         int     ch;
263
264         while ((ch = getopt(argc, argv, "Cc:iorsx")) != EOF)
265                 switch(ch) {
266                 case 'C':                       /* embedded comments */
267                         Cflag++;
268                         break;
269                 case 'c':                       /* new delimiting char */
270                         Delimch = *optarg;
271                         if (!isascii(Delimch)) {
272                                 printf("bad delimiting character: '\\%o\n'",
273                                        (unsigned char)Delimch);
274                         }
275                         break;
276                 case 'i':                       /* ignore case in ordering */
277                         Iflag++;
278                         break;
279                 case 'o':                       /* order strings */
280                         Oflag++;
281                         break;
282                 case 'r':                       /* randomize pointers */
283                         Rflag++;
284                         break;
285                 case 's':                       /* silent */
286                         Sflag++;
287                         break;
288                 case 'x':                       /* set the rotated bit */
289                         Xflag++;
290                         break;
291                 case '?':
292                 default:
293                         usage();
294                 }
295         argv += optind;
296
297         if (*argv) {
298                 Infile = *argv;
299                 if (*++argv)
300                         (void) strcpy(Outfile, *argv);
301         }
302         if (!Infile) {
303                 puts("No input file name");
304                 usage();
305         }
306         if (*Outfile == '\0') {
307                 (void) strcpy(Outfile, Infile);
308                 (void) strcat(Outfile, ".dat");
309         }
310 }
311
312 void usage()
313 {
314         (void) fprintf(stderr,
315             "strfile [-Ciorsx] [-c char] sourcefile [datafile]\n");
316         exit(1);
317 }
318
319 /*
320  * add_offset:
321  *      Add an offset to the list, or write it out, as appropriate.
322  */
323 void add_offset(fp, off)
324 FILE    *fp;
325 long    off;
326 {
327         long net;
328
329         if (!STORING_PTRS) {
330                 net = htonl(off);
331                 fwrite(&net, 1, sizeof net, fp);
332         } else {
333                 ALLOC(Seekpts, Num_pts + 1);
334                 Seekpts[Num_pts] = off;
335         }
336         Num_pts++;
337 }
338
339 /*
340  * do_order:
341  *      Order the strings alphabetically (possibly ignoring case).
342  */
343 void do_order()
344 {
345         int     i;
346         long   *lp;
347         STR     *fp;
348
349         Sort_1 = fopen(Infile, "r");
350         Sort_2 = fopen(Infile, "r");
351         qsort((char *) Firstch, (int) Tbl.str_numstr, sizeof *Firstch, cmp_str);
352         i = Tbl.str_numstr;
353         lp = Seekpts;
354         fp = Firstch;
355         while (i--)
356                 *lp++ = fp++->pos;
357         (void) fclose(Sort_1);
358         (void) fclose(Sort_2);
359         Tbl.str_flags |= STR_ORDERED;
360 }
361
362 static int collate_range_cmp (c1, c2)
363         int c1, c2;
364 {
365         static char s1[2], s2[2];
366         int ret;
367
368         c1 &= UCHAR_MAX;
369         c2 &= UCHAR_MAX;
370         if (c1 == c2)
371                 return (0);
372         s1[0] = c1;
373         s2[0] = c2;
374         if ((ret = strcoll(s1, s2)) != 0)
375                 return (ret);
376         return (c1 - c2);
377 }
378
379 /*
380  * cmp_str:
381  *      Compare two strings in the file
382  */
383 int cmp_str(s1, s2)
384 const void      *s1, *s2;
385 {
386         const STR       *p1, *p2;
387         int     c1, c2;
388         int     n1, n2;
389         int r;
390
391 # define        SET_N(nf,ch)    (nf = (ch == '\n'))
392 # define        IS_END(ch,nf)   (ch == EOF || (ch == (unsigned char) Delimch && nf))
393
394         p1 = (const STR *) s1;
395         p2 = (const STR *) s2;
396         
397         c1 = (unsigned char) p1->first;
398         c2 = (unsigned char) p2->first;
399         if ((r = collate_range_cmp(c1, c2)) != 0)
400                 return r;
401
402         (void) fseek(Sort_1, p1->pos, 0);
403         (void) fseek(Sort_2, p2->pos, 0);
404
405         n1 = FALSE;
406         n2 = FALSE;
407         while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0' && c1 != EOF)
408                 SET_N(n1, c1);
409         while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0' && c2 != EOF)
410                 SET_N(n2, c2);
411
412         while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
413                 if (Iflag) {
414                         if (isupper(c1))
415                                 c1 = tolower(c1);
416                         if (isupper(c2))
417                                 c2 = tolower(c2);
418                 }
419                 if ((r = collate_range_cmp(c1, c2)) != 0)
420                         return r;
421                 SET_N(n1, c1);
422                 SET_N(n2, c2);
423                 c1 = getc(Sort_1);
424                 c2 = getc(Sort_2);
425         }
426         if (IS_END(c1, n1))
427                 c1 = 0;
428         if (IS_END(c2, n2))
429                 c2 = 0;
430         return collate_range_cmp(c1, c2);
431 }
432
433 /*
434  * randomize:
435  *      Randomize the order of the string table.  We must be careful
436  *      not to randomize across delimiter boundaries.  All
437  *      randomization is done within each block.
438  */
439 void randomize()
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 }