//----------------------------------------------------------------------
//  IMPLEMENTATION FILE (rand.cpp)
//  This module exports facilities for pseudorandom number generation.
//  Machine dependency: long ints must be at least 32 bits (4 bytes).
//----------------------------------------------------------------------
#include "rand.h"

static long currentSeed;          // Updated as a global variable

const long MULTIPLIER = 16807;
const long MAX =  2147483647;
const long QUOT = 127773;         // Quotient of MAX / MULTIPLIER
const long REM  = 2836;           // Remainder of MAX / MULTIPLIER

void SetSeed( /* in */ long initSeed )
    //..................................................................
    // PRE:  initSeed >= 1
    // POST: 1 <= currentSeed < MAX
    // NOTE: This routine MUST be called prior to NextRand()
    //..................................................................
{
    initSeed = initSeed % MAX;
    currentSeed = (initSeed > 0) ? initSeed : 1;
}

float NextRand()
    //..................................................................
    // PRE:  1 <= currentSeed < MAX
    // POST: currentSeed == (currentSeed<entry> * MULTIPLIER) modulo MAX
    //    && FCTVAL == currentSeed / MAX
    // NOTE: This is a prime modulus multiplicative linear congruential
    //       generator that uses the global variable currentSeed
    //..................................................................
{
    long temp = MULTIPLIER*(currentSeed%QUOT) - REM*(currentSeed/QUOT);

    currentSeed = (temp > 0) ? temp : temp + MAX;
    return float(currentSeed) / float(MAX);
}

