/* 
  random.c
  
  Copyright (C) 2001 Arthur de Jong
  
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2, or (at your option)
  any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software Foundation,
  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  
*/


#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

#include "rl.h"


/* the device that is used to seed the rand() function */
/* #define RANDOMDEV "/dev/urandom" */
/* TODO: this shlould probably be moved to configure */


/* initialize the random number generator with a sensible value
   this calls srand() so rand() can be used */
void randomize()
{
/*  unsigned int seed;
  FILE *fp;*/
  struct timeval tv;
  
  /* this is probably slow on systems that don't have /dev/urandom */
/*  if ( (fp=fopen(RANDOMDEV,"r"))==NULL)
  {*/
    /* seed the random generator with the time */
    gettimeofday(&tv,NULL);
    srand(((unsigned int)(tv.tv_usec))^((unsigned int)getpid()));
/*  }
  else
  {
    fread(&seed,sizeof(int),1,fp);
    fclose(fp);
    srand(seed);
  }*/
}


/* returns a random number x where 0 <= x < max */
int random_below(int max)
{
  int i;
  int j;
  i=RAND_MAX/max;
  /* there realy should be a better way for this */
  /* TODO: fix with something smart so that this even works for large values
           (on systems with a low RAND_MAX maybe two calls 
            to rand() could be used) */
  /* TODO: add range checking 0<max<RAND_MAX */
  do
  {
    j=rand()/i;
  }
  while (j>=max);
  return j;
}


/* thow the dice and return true (1)
   with a chance of x/y (false=0) */
int random_draw(int x,int y)
{
  /* TODO: add checking for large values of x and y */
  return (rand()/x<=RAND_MAX/y);
}

