#include <stream.h>
#include <math.h>
#include <sys/time.h>
#include "Rand.h"

/* Random number generation routines based on system 48-bit LC RNG:
 * Written by Thomas Kammeyer, UCSD
 *
 * double real_rand() automatically seeds itself if need be
 *                    and returns random numbers from [0,1)
 * int flip_p(double pr) flips a biased coin... returns non-zero
 *                       with probability pr, 0 otherwise.
 * int rand_betw_inc( int lo, int hi ) returns a random integer in [lo,hi].
 *
 * 05/22/96 jcm Correction to use of gettimeofday
 */
extern "C" {
   extern double drand48();
   extern void srand48(long);
   /*extern int gettimeofday(struct timeval *tp);*/
}

double real_rand()
{
   static int seed_me = 1;  /* "...Seymour, seed me all night long..." */

   if (seed_me) {
      struct timeval tp;
      seed_me = 0;
      gettimeofday(&tp,NULL);
      srand48( tp.tv_sec );
   }

   return drand48();
}

int rand_betw_inc( int lo, int hi )
{
   return (int) ( lo + (hi-lo+1)*real_rand() );
}

void rand_betw_vec( int vec[ ], int n, int lo, int hi )
{

   if (lo == 0) {
       double HiP1 = hi+1;
       for (int i = 0 ; i < n ; i++)
	  vec[i] = (int) HiP1*real_rand();
   }
   else{
       double HiMLoP1 = (hi-lo)+1;
       for (int i = 0 ; i < n ; i++)
	  vec[i] = lo +(int)  (HiMLoP1*real_rand());
   }
}
