/***************************************************************************
 *   Copyright (C) 2007 by Faubet Pierre   *
 *   pierre.faubet@e.ujf-grenoble.fr   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

// MersenneTwister.h
// Mersenne Twister random number generator -- a C++ class MTRand
// Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
// Richard J. Wagner  v1.0  15 May 2003  rjwagner@writeme.com

// The Mersenne Twister is an algorithm for generating random numbers.  It
// was designed with consideration of the flaws in various other generators.
// The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
// are far greater.  The generator is also fast; it avoids multiplication and
// division, and it benefits from caches and pipelines.  For more information
// see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html

// Reference
// M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
// Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
// Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.

// Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
// Copyright (C) 2000 - 2003, Richard J. Wagner
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//   1. Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//   3. The names of its contributors may not be used to endorse or promote
//      products derived from this software without specific prior written
//      permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// The original code included the following notice:
//
//     When you use this, send an email to: matumoto@math.keio.ac.jp
//     with an appropriate reference to your work.
//
// It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu
// when you write.

#ifndef MTRAND_H
#define MTRAND_H

// Not thread safe (unless auto-initialization is avoided and each thread has
// its own MTRand object)

#define repeat for(;;)

#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <time.h>
#include <math.h>

#include <gsl/gsl_sf_gamma.h>

/**
* Mersenne Twister random number generator
*/
class MTRand
  {
    // Data
  public:
    typedef unsigned long uint32;  /**< unsigned integer type, at least 32 bits */

    /**
    * length of state vector
    */
    enum { N = 624 };

    /**
    * length of array for save()
    */
    enum { SAVE = N + 1 };

  protected:
    /**
    * period parameter
    */
    enum { M = 397 };

    uint32 state[N];   /**< internal state */
    uint32 *pNext;     /**< next value to get from state */
    int left;          /**< number of values left before reload needed */


    //Methods
  public:
    /**
    * initialize with a simple uint32
    */
    MTRand( const uint32& oneSeed );
    /**
    * or an array
    */
    MTRand( uint32 *const bigSeed, uint32 const seedLength = N );

    /**
     * auto-initialize with /dev/urandom or time() and clock()
    */
    MTRand();  // auto-initialize with /dev/urandom or time() and clock()

    // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
    // values together, otherwise the generator state can be learned after
    // reading 624 consecutive values.

    // Access to 32-bit random numbers
    /**
     * real number in [0,1]
    */
    double rand();                          // real number in [0,1]

    /**
     * real number in [0,n]
    */
    double rand( const double& n );         // real number in [0,n]

    /**
     * real number in [0,1)
    */
    double randExc();                       // real number in [0,1)

    /**
     * real number in [0,n)
    */
    double randExc( const double& n );      // real number in [0,n)

    /**
     * real number in (0,1)
    */
    double randDblExc();                    // real number in (0,1)

    /**
     * real number in (0,n)
    */
    double randDblExc( const double& n );   // real number in (0,n)

    /**
     * integer in [0,2^32-1]
    */
    uint32 randInt();                       // integer in [0,2^32-1]

    /**
     * integer in [0,n] for n < 2^32
    */
    uint32 randInt( const uint32& n );      // integer in [0,n] for n < 2^32

    /**
     * same as rand()
    */
    double operator()()
    {
      return rand();
    }  // same as rand()

    /**
    * real number in (a,b)
    * @param a lower bound
    * @param b upper bound
    */
    double runiform(const double& a,const double& b); // real number in (a,b)

    /**
    * Integer in [0,size-1]
    * @param size
    */
    int runif_int (const int& size);

    /**
    * Return i with probability p_i
    */
    int rnunif_int(double *const p,const int& size);

    /**
    * Exponential deviate
    * @param lambda rate
    */
    double rexp (const double& lambda);

    /**
    * Standard gaussian deviate
    */
    double gasdev ();

    /**
    * Normal deviate
    * @param mu mean
    * @param sigma2 variance
    */
    double rnorm (const double& mu,const double& sigma2);

    /**
    * Gamma deviate
    * @param a shape parameter
    * @param scale scale parameter
    */
    double rstgam(const double& a,const double& scale);

    /**
    * Dirichlet deviate
    * @param vectX deviate
    * @param vectA shape parameters
    * @param arraySize size of vector
    */
    void rdirichlet(double *vectX,double *const vectA,const int& arraySize);

    /**
    * Multinomial deviate
    */
    void rmultinomial(const int& n,double *const p,const int& ncat,int *ix);

    /**
    * Binomial deviate
    */
    int bnldev(const double& pp,const int& n);

    /// Access to 53-bit random numbers (capacity of IEEE double precision)
    double rand53();  // real number in [0,1)

    /// Access to nonuniform random number distributions
    double randNorm( const double& mean = 0.0, const double& variance = 0.0 );

    /// Re-seeding functions with same behavior as initializers
    void seed( const uint32 oneSeed );
    void seed( uint32 *const bigSeed, const uint32 seedLength = N );
    void seed();

    /// Saving and loading generator state
    void save( uint32* saveArray ) const;  // to array of size SAVE
    void load( uint32 *const loadArray );  // from such array
    friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
    friend std::istream& operator>>( std::istream& is, MTRand& mtrand );

  protected:
    void initialize( const uint32 oneSeed );
    void reload();
    uint32 hiBit( const uint32& u ) const
      {
        return u & 0x80000000UL;
      }
    uint32 loBit( const uint32& u ) const
      {
        return u & 0x00000001UL;
      }
    uint32 loBits( const uint32& u ) const
      {
        return u & 0x7fffffffUL;
      }
    uint32 mixBits( const uint32& u, const uint32& v ) const
      {
        return hiBit(u) | loBits(v);
      }
    uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const
      {
        return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL);
      }
    static uint32 hash( time_t t, clock_t c );

  };

inline double MTRand::runiform(const double& a,const double& b)
{
  return (b - a) * randDblExc() + a;
}

inline int MTRand::runif_int (const int& size)
{
  return randInt(size-1);
}

inline int MTRand::rnunif_int(double *const p,const int& size)
{
  double u = runiform(0,1);
  double sum = 0;
  for(int i=0;i<size;i++)
    {
      sum += p[i];
      if(u < sum)
        return i;
    }
}

inline double MTRand::rexp(const double& lambda)
{
  return -(1.0/lambda) * (log(runiform(0,1)));
}

inline double MTRand::gasdev()
{
  double phi = runiform(0,2 * M_PI);
  double r2 = rexp(0.5);

  return sqrt(r2)*cos(phi);
}

inline double MTRand::rnorm(const double& mu,const double& sigma2)
{
  return sqrt (sigma2) * gasdev () + mu;
}

inline double MTRand::rstgam(const double& a,const double& scale)
{
  /*  int acpt;
    double c1,c2,c3,c4,c5,u1,u2,w;
   
    c1=alpha1-1.0;
    c2=(alpha1-(1.0/(6.0*alpha1)))/c1;
    c3=2.0/c1;
    c4=c3+2.0;
    c5=1.0/sqrt(alpha1);
   
    do
    {
      do
      {
        u1=randDblExc();
        u2=randDblExc();
   
        if (alpha1>2.5)
          u1=u2+c5*(1.0-(1.86*u1));
      }
      while(u1>=1.0 || u1<=0);
   
      w=(c2*u2)/u1;
      if((c3*u1+w+(1.0/w))<=c4)
        acpt=1;
      else if ((c3*logl(u1)-logl(w)+w)>=1.0)  //repeat outer do loop
        acpt=0;
      else
        acpt=1;
    }
    while (acpt!=1);
   
    return c1*w*scale;*/

  /* Constants : */
  const static double sqrt32 = 5.656854;
  const static double exp_m1 = 0.36787944117144232159;/* exp(-1) = 1/e */

  /* Coefficients q[k] - for q0 = sum(q[k]*a^(-k))
  * Coefficients a[k] - for q = q0+(t*t/2)*sum(a[k]*v^k)
  * Coefficients e[k] - for exp(q)-1 = sum(e[k]*q^k)
  */
  const static double q1 = 0.04166669;
  const static double q2 = 0.02083148;
  const static double q3 = 0.00801191;
  const static double q4 = 0.00144121;
  const static double q5 = -7.388e-5;
  const static double q6 = 2.4511e-4;
  const static double q7 = 2.424e-4;

  const static double a1 = 0.3333333;
  const static double a2 = -0.250003;
  const static double a3 = 0.2000062;
  const static double a4 = -0.1662921;
  const static double a5 = 0.1423657;
  const static double a6 = -0.1367177;
  const static double a7 = 0.1233795;

  /* State variables [FIXME for threading!] :*/
  static double aa = 0.;
  static double aaa = 0.;
  static double s, s2, d;    /* no. 1 (step 1) */
  static double q0, b, si, c;/* no. 2 (step 4) */

  double e, p, q, r, t, u, v, w, x, ret_val;

  if (a < 1.)
    { /* GS algorithm for parameters a < 1 */
      e = 1.0 + exp_m1 * a;
      repeat {
        p = e * randExc();
        if (p >= 1.0)
        {
          x = -log((e - p) / a);
            if (rexp(1) >= (1.0 - a) * log(x))
              break;
          }
        else
          {
            x = exp(log(p) / a);
            if (rexp(1) >= x)
              break;
          }
      }
      return scale * x;
    }

  /* --- a >= 1 : GD algorithm --- */

  /* Step 1: Recalculations of s2, s, d if a has changed */
  if (a != aa)
    {
      aa = a;
      s2 = a - 0.5;
      s = sqrt(s2);
      d = sqrt32 - s * 12.0;
    }
  /* Step 2: t = standard normal deviate,
  x = (s,1/2) -normal deviate. */

  /* immediate acceptance (i) */
  t = rnorm(0,1);
  x = s + 0.5 * t;
  ret_val = x * x;
  if (t >= 0.0)
    return scale * ret_val;

  /* Step 3: u = 0,1 - uniform sample. squeeze acceptance (s) */
  u = randExc();
  if (d * u <= t * t * t)
    return scale * ret_val;

  /* Step 4: recalculations of q0, b, si, c if necessary */

  if (a != aaa)
    {
      aaa = a;
      r = 1.0 / a;
      q0 = ((((((q7 * r + q6) * r + q5) * r + q4) * r + q3) * r
             + q2) * r + q1) * r;

      /* Approximation depending on size of parameter a */
      /* The constants in the expressions for b, si and c */
      /* were established by numerical experiments */

      if (a <= 3.686)
        {
          b = 0.463 + s + 0.178 * s2;
          si = 1.235;
          c = 0.195 / s - 0.079 + 0.16 * s;
        }
      else if (a <= 13.022)
        {
          b = 1.654 + 0.0076 * s2;
          si = 1.68 / s + 0.275;
          c = 0.062 / s + 0.024;
        }
      else
        {
          b = 1.77;
          si = 0.75;
          c = 0.1515 / s;
        }
    }
  /* Step 5: no quotient test if x not positive */

  if (x > 0.0)
    {
      /* Step 6: calculation of v and quotient q */
      v = t / (s + s);
      if (fabs(v) <= 0.25)
        q = q0 + 0.5 * t * t * ((((((a7 * v + a6) * v + a5) * v + a4) * v
                                  + a3) * v + a2) * v + a1) * v;
      else
        q = q0 - s * t + 0.25 * t * t + (s2 + s2) * log(1.0 + v);


      /* Step 7: quotient acceptance (q) */
      if (log(1.0 - u) <= q)
        return scale * ret_val;
    }

  repeat {
    /* Step 8: e = standard exponential deviate
    	*	u =  0,1 -uniform deviate
    *	t = (b,si)-double exponential (laplace) sample */
    e = rexp(1);
    u = randExc();
    u = u + u - 1.0;
    if (u < 0.0)
    t = b - si * e;
    else
      t = b + si * e;
      /* Step	 9:  rejection if t < tau(1) = -0.71874483771719 */
      if (t >= -0.71874483771719)
        {
          /* Step 10:	 calculation of v and quotient q */
          v = t / (s + s);
            if (fabs(v) <= 0.25)
              q = q0 + 0.5 * t * t *
                  ((((((a7 * v + a6) * v + a5) * v + a4) * v + a3) * v
                    + a2) * v + a1) * v;
            else
              q = q0 - s * t + 0.25 * t * t + (s2 + s2) * log(1.0 + v);
            /* Step 11:	 hat acceptance (h) */
            /* (if q not positive go to step 8) */
            if (q > 0.0)
              {
                w = expm1(q);
                /*  ^^^^^ original code had approximation with rel.err < 2e-7 */
                /* if t is rejected sample again at step 8 */
                if (c * fabs(u) <= w * exp(e - 0.5 * t * t))
                  break;
              }
          }
  } /* repeat .. until  `t' is accepted */
  x = s + 0.5 * t;
  return scale * x * x;
}

inline void MTRand::rdirichlet(double *vectX,double *const vectA,const int& arraySize)
{
  int i;
  double sum = 0;
  double DumRan;

  for(i=0;i<arraySize;i++)
    {
      if(vectA[i] == 0.0)
        vectX[i] = 0.0;
      else if(vectA[i]>1.0)
        vectX[i]=rstgam(vectA[i],1);
      else if (vectA[i]<1.0)
        {
          DumRan=randDblExc();

          vectX[i]=rstgam(vectA[i]+1.0,1)*pow((double) DumRan,1.0/vectA[i]);
        }
      else
        {
          DumRan=randDblExc();

          vectX[i]=(-log((double) DumRan));
        }

      sum += vectX[i];
    }

  for(i=0;i<arraySize;i++)
    vectX[i]=vectX[i]/sum;
}

inline void MTRand::rmultinomial(const int& n,double *const p,const int& ncat,int *ix)
{
  static double prob,sum;
  static int i,icat,ntot;
  ntot = n;
  sum = 1;
  for(i=0; i<ncat; i++)
    ix[i] = 0;
  for(icat=0; icat<ncat-1; icat++)
    {
      prob = *(p+icat)/sum;
      *(ix+icat) = bnldev(prob,ntot);
      ntot -= *(ix+icat);
      if(ntot <= 0)
        return;
      sum -= *(p+icat);
    }
  *(ix+ncat-1) = ntot;
  return;
}

inline int MTRand::bnldev(const double& pp,const int& n)
{
  int j;
  static int nold=(-1);
  double am, em, g, angle, p, bnl, sq, t, y;
  static double pold=(-1.0), pc, plog, pclog, en, oldg;

  p=(pp <= 0.5 ? pp : 1.0-pp);
  am=n*p;
  if (n < 25)
    {
      bnl=0.0;
      for (j=1;j<=n;j++)
        if (runiform(0,1) < p)
          ++bnl;
    }
  else if (am < 1.0)
    {
      g=exp(-am);
      t=1.0;
      for (j=0;j<=n;j++)
        {
          t *= runiform(0,1);
          if (t < g)
            break;
        }
      bnl=(j <= n ? j : n);
    }
  else
    {
      if (n != nold)
        {
          en = n;
          oldg=gsl_sf_lngamma(en+1.0);
          nold=n;
        }
      if (p != pold)
        {
          pc=1.0-p;
          plog=log(p);
          pclog=log(pc);
          pold=p;
        }
      sq=sqrt(2.0*am*pc);
      do
        {
          do
            {
              angle=M_PI*runiform(0,1);
              y=tan(angle);
              em=sq*y+am;
            }
          while (em < 0.0 || em >= (en+1.0));
          em=floor(em);
          t=1.2*sq*(1.0+y*y)*exp(oldg-gsl_sf_lngamma(em+1.0)
                                 -gsl_sf_lngamma(en-em+1.0)+em*plog+(en-em)*pclog);
        }
      while (runiform(0,1) > t);
      bnl=em;
    }
  if (p!=pp)
    bnl=n-bnl;
  return ((int) bnl);
}

inline MTRand::MTRand( const uint32& oneSeed )
{
  seed(oneSeed);
}

inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength )
{
  seed(bigSeed,seedLength);
}

inline MTRand::MTRand()
{
  seed();
}

inline double MTRand::rand()
{
  return double(randInt()) * (1.0/4294967295.0);
}

inline double MTRand::rand( const double& n )
{
  return rand() * n;
}

inline double MTRand::randExc()
{
  return double(randInt()) * (1.0/4294967296.0);
}

inline double MTRand::randExc( const double& n )
{
  return randExc() * n;
}

inline double MTRand::randDblExc()
{
  return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0);
}

inline double MTRand::randDblExc( const double& n )
{
  return randDblExc() * n;
}

inline double MTRand::rand53()
{
  uint32 a = randInt() >> 5, b = randInt() >> 6;
  return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0);  // by Isaku Wada
}

inline double MTRand::randNorm( const double& mean, const double& variance )
{
  // Return a real number from a normal (Gaussian) distribution with given
  // mean and variance by Box-Muller method
  double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance;
  double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
  return mean + r * cos(phi);
}

inline MTRand::uint32 MTRand::randInt()
{
  // Pull a 32-bit integer from the generator state
  // Every other access function simply transforms the numbers extracted here

  if( left == 0 )
    reload();
  --left;

  register uint32 s1;
  s1 = *pNext++;
  s1 ^= (s1 >> 11);
  s1 ^= (s1 <<  7) & 0x9d2c5680UL;
  s1 ^= (s1 << 15) & 0xefc60000UL;
  return ( s1 ^ (s1 >> 18) );
}

inline MTRand::uint32 MTRand::randInt( const uint32& n )
{
  // Find which bits are used in n
  // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
  uint32 used = n;
  used |= used >> 1;
  used |= used >> 2;
  used |= used >> 4;
  used |= used >> 8;
  used |= used >> 16;

  // Draw numbers until one is found in [0,n]
  uint32 i;
  do
    i = randInt() & used;  // toss unused bits to shorten search
  while( i > n );
  return i;
}


inline void MTRand::seed( const uint32 oneSeed )
{
  // Seed the generator with a simple uint32
  initialize(oneSeed);
  reload();
}


inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength )
{
  // Seed the generator with an array of uint32's
  // There are 2^19937-1 possible initial states.  This function allows
  // all of those to be accessed by providing at least 19937 bits (with a
  // default seed length of N = 624 uint32's).  Any bits above the lower 32
  // in each element are discarded.
  // Just call seed() if you want to get array from /dev/urandom
  initialize(19650218UL);
  register int i = 1;
  register uint32 j = 0;
  register int k = ( N > seedLength ? N : seedLength );
  for( ; k; --k )
    {
      state[i] =
        state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL );
      state[i] += ( bigSeed[j] & 0xffffffffUL ) + j;
      state[i] &= 0xffffffffUL;
      ++i;
      ++j;
      if( i >= N )
        {
          state[0] = state[N-1];
          i = 1;
        }
      if( j >= seedLength )
        j = 0;
    }
  for( k = N - 1; k; --k )
    {
      state[i] =
        state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL );
      state[i] -= i;
      state[i] &= 0xffffffffUL;
      ++i;
      if( i >= N )
        {
          state[0] = state[N-1];
          i = 1;
        }
    }
  state[0] = 0x80000000UL;  // MSB is 1, assuring non-zero initial array
  reload();
}


inline void MTRand::seed()
{
  // Seed the generator with an array from /dev/urandom if available
  // Otherwise use a hash of time() and clock() values

  // First try getting an array from /dev/urandom
  FILE* urandom = fopen( "/dev/urandom", "rb" );
  if( urandom )
    {
      uint32 bigSeed[N];
      register uint32 *s = bigSeed;
      register int i = N;
      register bool success = true;
      while( success && i-- )
        success = fread( s++, sizeof(uint32), 1, urandom );
      fclose(urandom);
      if( success )
        {
          seed( bigSeed, N );
          return;
        }
    }

  // Was not successful, so use time() and clock() instead
  seed( hash( time(NULL), clock() ) );
}


inline void MTRand::initialize( const uint32 seed )
{
  // Initialize generator state with seed
  // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
  // In previous versions, most significant bits (MSBs) of the seed affect
  // only MSBs of the state array.  Modified 9 Jan 2002 by Makoto Matsumoto.
  register uint32 *s = state;
  register uint32 *r = state;
  register int i = 1;
  *s++ = seed & 0xffffffffUL;
  for( ; i < N; ++i )
    {
      *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL;
      r++;
    }
}


inline void MTRand::reload()
{
  // Generate N new values in state
  // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
  register uint32 *p = state;
  register int i;
  for( i = N - M; i--; ++p )
    *p = twist( p[M], p[0], p[1] );
  for( i = M; --i; ++p )
    *p = twist( p[M-N], p[0], p[1] );
  *p = twist( p[M-N], p[0], state[0] );

  left = N, pNext = state;
}


inline MTRand::uint32 MTRand::hash( time_t t, clock_t c )
{
  // Get a uint32 from t and c
  // Better than uint32(x) in case x is floating point in [0,1]
  // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)

  static uint32 differ = 0;  // guarantee time-based seeds will change

  uint32 h1 = 0;
  unsigned char *p = (unsigned char *) &t;
  for( size_t i = 0; i < sizeof(t); ++i )
    {
      h1 *= UCHAR_MAX + 2U;
      h1 += p[i];
    }
  uint32 h2 = 0;
  p = (unsigned char *) &c;
  for( size_t j = 0; j < sizeof(c); ++j )
    {
      h2 *= UCHAR_MAX + 2U;
      h2 += p[j];
    }
  return ( h1 + differ++ ) ^ h2;
}


inline void MTRand::save( uint32* saveArray ) const
  {
    register uint32 *sa = saveArray;
    register const uint32 *s = state;
    register int i = N;
    for( ; i--; *sa++ = *s++ )
    {}
    *sa = left;
  }


inline void MTRand::load( uint32 *const loadArray )
{
  register uint32 *s = state;
  register uint32 *la = loadArray;
  register int i = N;
  for( ; i--; *s++ = *la++ )
  {}
  left = *la;
  pNext = &state[N-left];
}


inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
{
  register const MTRand::uint32 *s = mtrand.state;
  register int i = mtrand.N;
  for( ; i--; os << *s++ << "\t" )
  {}
  return os << mtrand.left;
}


inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
{
  register MTRand::uint32 *s = mtrand.state;
  register int i = mtrand.N;
  for( ; i--; is >> *s++ )
  {}
  is >> mtrand.left;
  mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
  return is;
}

#endif  
  
// MERSENNETWISTER_H

// Change log:
//
// v0.1 - First release on 15 May 2000
//      - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
//      - Translated from C to C++
//      - Made completely ANSI compliant
//      - Designed convenient interface for initialization, seeding, and
//        obtaining numbers in default or user-defined ranges
//      - Added automatic seeding from /dev/urandom or time() and clock()
//      - Provided functions for saving and loading generator state
//
// v0.2 - Fixed bug which reloaded generator one step too late
//
// v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
//
// v0.4 - Removed trailing newline in saved generator format to be consistent
//        with output format of built-in types
//
// v0.5 - Improved portability by replacing static const int's with enum's and
//        clarifying return values in seed(); suggested by Eric Heimburg
//      - Removed MAXINT constant; use 0xffffffffUL instead
//
// v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
//      - Changed integer [0,n] generator to give better uniformity
//
// v0.7 - Fixed operator precedence ambiguity in reload()
//      - Added access for real numbers in (0,1) and (0,n)
//
// v0.8 - Included time.h header to properly support time_t and clock_t
//
// v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
//      - Allowed for seeding with arrays of any length
//      - Added access for real numbers in [0,1) with 53-bit resolution
//      - Added access for real numbers from normal (Gaussian) distributions
//      - Increased overall speed by optimizing twist()
//      - Doubled speed of integer [0,n] generation
//      - Fixed out-of-range number generation on 64-bit machines
//      - Improved portability by substituting literal constants for long enum's
//      - Changed license from GNU LGPL to BSD
