1/*
2 * Copyright 2001-2004 Brandon Long
3 * All Rights Reserved.
4 *
5 * ClearSilver Templating System
6 *
7 * This code is made available under the terms of the ClearSilver License.
8 * http://www.clearsilver.net/license.hdf
9 *
10 */
11
12#include "cs_config.h"
13
14#include <stdlib.h>
15#include <stdio.h>
16#include <time.h>
17#include <string.h>
18#include "neo_misc.h"
19#include "neo_err.h"
20#include "neo_rand.h"
21#include "ulist.h"
22
23static int RandomInit = 0;
24
25void neo_seed_rand (long int seed)
26{
27#ifdef HAVE_DRAND48
28  srand48(seed);
29#elif HAVE_RANDOM
30  srandom(seed);
31#else
32  srand(seed);
33#endif
34  RandomInit = 1;
35}
36
37int neo_rand (int max)
38{
39  int r;
40
41  if (RandomInit == 0)
42  {
43    neo_seed_rand (time(NULL));
44  }
45#ifdef HAVE_DRAND48
46  r = drand48() * max;
47#elif HAVE_RANDOM
48  r = random() * max;
49#else
50  r = rand() * max;
51#endif
52  return r;
53}
54
55int neo_rand_string (char *s, int max)
56{
57  int size;
58  int x = 0;
59
60  size = neo_rand(max-1);
61  for (x = 0; x < size; x++)
62  {
63    s[x] = (char)(32 + neo_rand(127-32));
64    if (s[x] == '/') s[x] = ' ';
65  }
66  s[x] = '\0';
67
68  return 0;
69}
70
71static ULIST *Words = NULL;
72
73int neo_rand_word (char *s, int max)
74{
75  NEOERR *err;
76  int x;
77  char *word;
78
79  if (Words == NULL)
80  {
81    FILE *fp;
82    char buf[256];
83
84    err = uListInit(&Words, 40000, 0);
85    if (err)
86    {
87      nerr_log_error(err);
88      return -1;
89    }
90    fp = fopen ("/usr/dict/words", "r");
91    if (fp == NULL) {
92      fp = fopen ("/usr/share/dict/words", "r");
93      if (fp == NULL) {
94        ne_warn("Unable to find dict/words file (looked in /usr/dict/words and /usr/share/dict/words)");
95        return -1;
96      }
97    }
98    while (fgets (buf, sizeof(buf), fp) != NULL)
99    {
100      x = strlen (buf);
101      if (buf[x-1] == '\n')
102	buf[x-1] = '\0';
103      uListAppend(Words, strdup(buf));
104    }
105    fclose (fp);
106  }
107  x = neo_rand (uListLength(Words));
108  uListGet(Words, x, (void *)&word);
109  strncpy (s, word, max);
110  s[max-1] = '\0';
111
112  return 0;
113}
114
115