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