/////////////////////////////////////////////////////////////////////////////////////////////////
//    This function is from 'Numerical Recipes in C: The Art of Scientific Computing         
//    William H. Press, Brian P. Flannery, Saul A. Teulosky, William T. Vetteling; New York:
//    Cambridge University Press, 1990.' 
//
//    It returns uniform random numbers between 0 and 1.
//
////////////////////////////////////////////////////////////////////////////////////////////////// 

#define MBIG 1000000000
#define MSEED 161803398
#define MZ 0
#define FAC (1.0/MBIG)


// According to Knuth, any large MBIG, and any smaller ( but still large ) MSEED can be substituted for the above values.

float rand_un_gen(long *idum_local)
  
  //Returns a uniform random deviate between 0.0 and 1.0. Set idum_local to any negative value to initialize or reanitialize the sequence.
  
{
  
  
  static int inext, inextp;
  static long ma[56];                  //The value 56 is special and should not be modified
  static int iff=0;
  long mj, mk;
  int i, ii, k;
  
 
  if (*idum_local < 0 || iff == 0) {                //Initialization
    iff=1;
    mj=MSEED-(*idum_local > 0 ? -*idum_local : *idum_local);      // Initialize ma[55] using the seed idum_local and the large number MSEED.
    mj %= MBIG;
    ma[55]=mj;
    mk=1;
    
    //Now initialize the rest of the table, in a slightly random order, with numbers that are not specially random.
    
    
    
    for (i=1; i<=54; i++) {  
      ii=(21*i) % 55;
      ma[ii]=mk;
      mk=mj-mk;
      if ( mk < MZ ) mk += MBIG;
      mj=ma[ii];
    }
    
    for (k=1;k<=4;k++)
      for(i=1;i<=55;i++){
	ma[i] -= ma[1+(i+30) % 5];
	if(ma[i] <MZ) ma[i] +=MBIG;
      }
    
    
    
    
    // Prepare indices for our first generated number. The constant 31 is special.
    
    inext=0;
    inextp=31;
    *idum_local=1;
  }
  // Here is where we start, excep on initialization.
  // Increment inext and inextp, wrapping around 56 to 1.
  
  if (++inext == 56) inext=1;
  if (++inextp == 56) inextp=1;
  
  // Generate a new random number subtractively.
  
  mj=ma[inext]-ma[inextp];
  
  // Be sure that it is in range.
  
  if(mj < MZ) mj += MBIG;
  
  //Store it and output the derived uniform deviate.
  
  ma[inext]=mj;


  return mj*FAC;
}






