/* $Id: random.c,v 1.2 2000/05/28 20:55:45 jhall Exp $ */

/* GNU Robots */

/* Copyright (C) 1998 Jim Hall, jhall1@isd.net */

/*
   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 of the License, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


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

#include <guile/gh.h>

/* Guile 1.2 does not include the "random" or "randomize" Scheme
   primitives, so I need to fake it here. */

SCM scm_random (SCM s_n)
{
  int result;
  int n;

  n = gh_scm2int (s_n);

  /* If you don't mind using floating point, you can use */
  /*  result = (int) ((double) rand () / ((double) RAND_MAX + 1.0) * n); */

  /* If you're worried about using floating point, you could use */
  result = (int) (rand () / (RAND_MAX / n + 1));

  /* 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_int2scm (result));
}

SCM scm_randomize (void)
{
  time_t t;

  time (&t);
  srand ((int) t);

  return (SCM_BOOL_T);
}
