/*
    Some of this comes from the TCL 8.0 unix/tclUnixTime.c:TclpGetClicks
*/

#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#ifdef GLIBC2
#include <sys/time.h>
#endif

/*
    Program to run to get some randomness
*/
#ifndef USE_CPU
#define USE_CPU "/bin/false"
#endif

unsigned long GetClicks(void) {
    unsigned long now;
#ifdef NO_GETTOD
    struct tms dummy;
    now = (unsigned long) times(&dummy);
#else
    struct timeval date;
    struct timezone tz;
    gettimeofday(&date, &tz);
    now = date.tv_sec*1000000 + date.tv_usec;
#endif /* NO_GETTOD */
    return now;
}

/* 
    Max is the highest value you want to be returned
    returns a number between 0 and max that is virtually really random
*/

unsigned long generate_random_number(unsigned long max) {
  unsigned long tmp1;
  unsigned long startt,endt, ourrand;
  startt=GetClicks();
  system(USE_CPU);
  endt=GetClicks();
  srand(endt-startt);
  tmp1=(getpid()*((endt-startt)+1))^rand();
#ifndef GO32
  srand48(tmp1);
  ourrand=lrand48() % (max+1);
#else
  rand(tmp1);
  ourrand=rand() % (max+1);
#endif
  return (ourrand);
}

