/************************************************************************/
/*				rnds.c                                  */
/*                                                                      */
/*    This module contains functions used to generate random numbers.   */
/* First call srand() with the seed values and then you can use rand()  */
/* to get a random number.                                              */
/*                                                                      */
/* Thurdsay- March    19, 1987  5:19pm  new changes from April 87 BYTE  */
/* Tuesday - February 17, 1987  8:30pm  change randx from UWORD to WORD */
/* Monday  - December 29, 1986  7:00pm                                  */
/*                                                          Gene Toole  */
/************************************************************************/

/* ====================== Standard Amiga Includes ===================== */
#include <exec/types.h>
#include <math.h>

/* ====================== Functions for THIS Program ================== */
VOID  srand();
LONG rand();
FLOAT random();

/* =========================== WORD Variables ========================= */
STATIC WORD
   x = 1,              /* default: global seeds */
   y = 10000, 
   z = 3000;

/* --------------------------------------------------------------------
 * Here is the random number seed function.  You must send it 3 WORD
 * values between 1 and 30000.  It will then set the global seed 
 * values used by rand().
 * If you do not call this function, the 3 default global seed values 
 * will be used.
 */
VOID srand(xv, yv, zv)
WORD
   xv,
   yv,
   zv;
{
   x = xv;
   y = yv;
   z = zv;
}

/* --------------------------------------------------------------------
 * This is the actual random function.  It will return a random number 
 * within the range of LONG min to max inclusive.  You must pass to it
 * the min and max UWORD values for the range you wish returned.
 */
LONG rand(min, max)
UWORD 
   min, 
   max;
{
   return ( (LONG)( random() * (FLOAT)(max - min + 1) + min ) );
}

/* -------------------------------------------------------------------- 
 * This is the function from the April 87 issue of BYTE, page 128.
 * It returns a FLOAT in the range: 0 - (almost 1).
 */
FLOAT random()
{
   FLOAT
      temp;

   if ( (x = 171 * (x % 177) - 2 * (x / 177)) < 0 )
      x += 30269;
      
   if ( (y = 172 * (y % 176) - 35 * (y / 176)) < 0 )
      y += 30307;
   
   if ( (z = 170 * (z % 178) - 63 * (z / 178)) < 0 )
      z += 30323;
      
   temp = x/30269.0 + y/30307.0 + z/30323.0;
   
   return (temp - trunc(temp));
}
