#define NTAB 32
#define EPS 1.2e-7
#define RNMX (1.0-EPS)
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define NDIV (1+(IM-1)/NTAB)

double rand1(long *idum)    /* Minimal random number generator.  */
                           /* Initialise with idum a pointer to */
                           /* a ***negative*** integer */
{
  int j;
  long k;
  static long iy=0;
  static long iv[NTAB];
  double temp;

  if (*idum <= 0 || !iy) {      /* Initialise */
    if (-(*idum)<1)*idum =1;    /* Prevents idum = 0 */
    else *idum = -(*idum);
    for (j=NTAB+7;j>=0;j--) {   /* Load the shuffle table (after 8 warm-ups) */
      k=(*idum)/IQ;
      *idum=IA*(*idum-k*IQ)-IR*k;
      if (*idum <0) *idum += IM;
      if (j < NTAB) iv[j] = *idum;
    }
    iy=iv[0];
  }
  k=(*idum)/IQ;                 /* Start here when not initialising */
  *idum=IA*(*idum-k*IQ)-IR*k;   /* Compute idum=(IA*idum)%IM without */
  if (*idum <0) *idum += IM;    /*   overflowing by Schrage's method */
  j=iy/NDIV;                    /* Will be in range 0..NTAB-1 */
  iy=iv[j];                     /* Output previously stored value and */
  iv[j] = *idum;                /*   refill the shuffle table */
  if ((temp=AM*iy)>RNMX) return RNMX;  /* Users don't expect endpoint values */
  else return temp;
}
