#include <stdio.h>
#include <stdlib.h>				/* for rand */

#include <gh.h>

#include "c_builtins.h"

/* a random number function, made callable by Scheme */

SCM c_rand(SCM s_n)
{
  unsigned long result;
  unsigned long n;

  n = gh_scm2ulong (s_n);

#if 1
  result = (unsigned long)((double)rand() / ((double)RAND_MAX + 1) * n);
#endif

#if 0
  /* If you're worried about using floating point, you could use */

  result = (unsigned long) (rand() / (RAND_MAX / n + 1));
#endif

  /* Both methods obviously require knowing RAND_MAX (which ANSI
     #defines in <stdlib.h>), and assume that N is much less than
     RAND_MAX. */

  /* References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172. */

  return (gh_ulong2scm(result));
}

/* A function to seed the random number generator with the time of
   day.  Callable by Scheme. */

SCM
c_srand (void)
{
  time_t t;

  /* grab the time, and seed the generator */
  time (&t);
  srand ((unsigned int) t);

  return (SCM_BOOL_T);
}
