/***************************************************************************
**
**  This file is part of QGpCoreMath.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file 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 Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2002-10-13
**  Copyright: 2002-2019
**    Marc Wathelet
**    Marc Wathelet (ULg, Liège, Belgium)
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#ifndef RANDOM_H
#define RANDOM_H

#include <math.h>
#include <QGpCoreTools.h>

#include "GaussDistribution.h"

namespace QGpCoreMath {

#define RANDOM_NTAB 32
#define RANDOM_STATE_SIZE (RANDOM_NTAB+3)*sizeof(qint64)

class QGPCOREMATH_EXPORT Random
{
  TRANSLATIONS("Random")
public:
  Random(int seed=0);
  Random(const QByteArray& s);

  double uniform() {return ran2();}
  inline int uniform(int min, int max);
  inline double uniform(double min, double max);
  double normal(double mean, double stddev);
  double normal(GaussDistribution & gd) {return normal(gd.mean(),gd.stddev());}
  double ran2();

  QByteArray state() const;

  void testPeriod();
  void testDistribution(double max, qint64 nReset);
private:
  //int _nCalls;
  qint64 _idum;
  qint64 _idum2;
  qint64 _iy;
  qint64 _iv[RANDOM_NTAB];
};

inline double Random::uniform(double min, double max)
{
  return min+(max-min)*ran2();
}

inline int Random::uniform(int min, int max)
{
  return min+qRound((max-min)*ran2());
}

} // namespace QGpCoreMath

#endif // RANDOM_H
