/*
 *	File: lex_random.c
 *
 *      (C) IWTS
 *          KU Nijmegen
 *          The Netherlands
 *
 *      Author: K. Behnke
 *
 *      History:
 *
 *      - mar 1999, version 1.0
 *      - feb 2000, version 1.1 (debugged and brought back in line with NumRec
 *      						by RHB)
 *
 *      Description:
 *
 *	Random function which returns a uniform random deviate
 *	between 0.0 and 1.0. Set the argument variable 'idum'
 *	to any negative value to initialize or reinitialize
 *	the sequence.
 *
 *	Copied from W.H. Press, B.P. Flannery, S.A. Teukolsky,
 *	W.T. Vetterling (1990). "Numerical Recipes in C", Cambridge
 *	University Press, pp. 210-211.
 *
 */

#include <stdio.h>
#include "lex_rand.h"


double uniformRandom (idum)
int	*idum;

{
  static long	ix1, ix2, ix3;
  static float	r[98];
  float		    temp;
  static int	iff=0;
  int		    j;

  if ((*idum < 0) || (iff == 0)) {
    iff = 1;
    ix1 = (IC1 - (*idum)) % M1;
    ix1 = (IA1 * ix1 + IC1) % M1;
    ix2 = ix1 % M2;
    ix1 = (IA1 * ix1 + IC1) % M1;
    ix3 = ix1 % M3;

    for (j = 1; j < 97; j++) {
      ix1 = (IA1 * ix1 + IC1) % M1;
      ix2 = (IA2 * ix2 + IC2) % M2;
      r[j] = (ix1 + ix2 * RM2) * RM1;
    }

    *idum = 1;
  }

  ix1 = (IA1 * ix1 + IC1) % M1;
  ix2 = (IA2 * ix2 + IC2) % M2;
  ix3 = (IA3 * ix3 + IC3) % M3;
  j = 1 + ((97 * ix3) / M3);

  if ((j > 97) || (j < 1)) {
    fprintf (stderr, "uniformRandom (): impossible value for variable j!\n");
  }

  temp = r[j];
  r[j] = (ix1 + ix2 * RM2) * RM1;

  return ((double) temp);
}
