#undef  QUALITY_CHECKS

#include "scltypes.h"
#include "sclfuncs.h"

#if defined QUALITY_CHECKS
#include "libscl.h"
#endif

using namespace std;
using namespace scl;

int main()
{

  static INT_32BIT ix = 15;
  REAL    x = 0.0;

#if defined QUALITY_CHECKS
  
  // Chi square test

  ix = 421005;
  ix = 522329230;

  INTEGER ntrials = 1000000000;
  INTEGER nbins = 100;
  realmat bins(nbins,1,0.0);

  REAL sum = 0.0;
  REAL sumsqr = 0.0;
  REAL true_mean = 0.5;
  REAL true_var = REAL(1)/REAL(12);

  for (INTEGER t=1; t<=ntrials; ++t) {
    x = ran(ix);
    //if (x <= 0.0) cout << "Hit lower, " << ix << fmt('e',26,16,x) << '\n';
    //if (x >= 1.0) cout << "Hit upper, " << ix << fmt('e',26,16,x) << '\n';
    sum += x;
    sumsqr += pow(x-true_mean,2);
    for (INTEGER i=1; i<=100; ++i) {
      if (x <= REAL(i)/REAL(nbins)) { bins[i] += 1.0; break; }
    }
  }

  REAL mean = sum/REAL(ntrials);
  REAL var = sumsqr/REAL(ntrials);

  cout << '\n';
  cout << "Mean is " << mean << ". "
       << "Variance is " << var << ". "
       << "Sample size is " << ntrials << ". ";
  cout << '\n';
  cout << "The mean should be " << true_mean << " and the variance " 
       << true_var << ". ";
  cout << '\n';

  REAL expected = REAL(ntrials)/REAL(nbins);
  REAL chisq = 0.0;
  for (INTEGER i=1; i<=nbins; ++i) {
    chisq += pow(bins[i] - expected,2);
  }
  chisq /= expected;
  INTEGER df = nbins - 1;
  cout << '\n';
  cout << "Chi square is " << chisq 
       << " on " << df << " degrees freedom." 
       << " The z statistic is " 
       << (chisq - REAL(df))/sqrt(2.0*REAL(df)) << '\n';
  cout << "Remember that this test is one sided. " 
       << "Reject for large positive values only. " << '\n';
  cout << '\n';
  for (INTEGER i=1; i<=nbins; ++i) {
    bins[i] -= expected;
    bins[i] /= sqrt(expected);
  }
  cout << bins;
  cout << '\n';

#else

  ix = 15;

  INTEGER i;

  for (i=0; i < 50; i++) {
    x=ran(&ix);
    cout << x << "\n";
  }

  cout << endl;

  ix = 15;
  for (i=0; i < 50; i++) {
    x=ran(ix);
    cout << x << "\n";
  }

  ix = 1;
  for (i=0; i < 1000; i++) {
    x=ran(ix);
  }
  cout << '\n';
  cout << "The value should be 522329230 " << ix << '\n';

#endif

  exit(0);
}
