//--------------------------------------------------------------------------------
// Programme d'exemple multi-threads et test de la classe RandomGenerator de SOPHYA
//   R. Ansari - C. Magneville  ,   Novembre 2007
//   SOPHYA (C) UPS+LAL IN2P3/CNRS   (C) DAPNIA/SPP  CEA  - 2007   
// Exemples de commandes pour test (dans l'ordre ci-dessous :
// csh> tmtrnd OCG 1000000 XXX
// csh> tmtrnd STG 1000000 1024
// csh> tmtrnd RDG 1000000 rg1.ppf
// csh> tmtrnd MTG 3000000 4 
//--------------------------------------------------------------------------------

#include "sopnamsp.h"
#include "zthread.h"
#include "resusage.h"
#include "ctimer.h"
#include "timing.h"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <iostream>

#include "tvector.h"
#include "fioarr.h"
#include "matharr.h"
#include "tarrinit.h"

#include "srandgen.h"
#include "randr48.h"


// Choix du nom de la classe thread-safe a tester 
#define TC_RandomGenerator ThSDR48RandGen

//---------------------------------------------------------------------------------
// Definition d'une classe heritant de ZThread, pour remplir un vecteur avec 
// des aleatoires
class MTRnd : public ZThread {
public:
  MTRnd(TVector<r_8>& v, bool fgg=true);
  virtual void run(); 
protected:
  string nom_;
  TVector<r_8> vv_;
  bool fgg_; // true -> gaussien, false rand01() 
};

static int mtrandId = 0;  // Pour donner un identificateur a chaque thread

MTRnd::MTRnd(Vector& v, bool fgg)
  : vv_(v,true), fgg_(fgg)  // Partage de reference du vecteur 
{
  char buff[32];
  sprintf(buff, "MTRnd-Id=%d", mtrandId);
  mtrandId++;
  nom_ = buff;
  cout << " Thread MTRnd(" << nom_ << " ) Created ... " << endl;
}


// Le travail fait dans chaque thread (appele par start())
void MTRnd::run()
{
  Timer tm(nom_.c_str());
  cout << "MTRnd::run() - Nom= " << nom_ << " vv.Size()= " << vv_.Size() << endl;
  TC_RandomGenerator rgen;
  if (fgg_) 
    for(sa_size_t k=0; k<vv_.Size(); k++) vv_(k) = rgen.Gaussian();
  else
    for(sa_size_t k=0; k<vv_.Size(); k++) vv_(k) = rgen.Flat01();
}
// ----- Fin de la definition de la classe MTRnd ----
//---------------------------------------------------------------------------------

//----------------- Les fonction de test -----------------
//------- f0_tmtrnd()
int f0_tmtrnd(sa_size_t VSZ, bool fgg=true)
{
  cout << "[1] f0_tmtrnd/starting, VSZ= " << VSZ << endl;
  TVector<r_8> DATA(VSZ);
  {
    Timer tm("f0_tmtrnd-Gaussian/drand01");
    if (fgg) 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = GaussianRand(1.,0.);
    else 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = drand01();
    cout << "[2] f0_tmtrnd/ End of random generation using Gaussian()/drand01() " << endl;
  }
  POutPersist po("data0.ppf");
  po << DATA;
  cout << "[3] f0_tmtrnd/  DATA saved to file data0.ppf " << endl;
  return 0; 
}
//------- f1_tmtrnd()
int f1_tmtrnd(sa_size_t VSZ, size_t seqsz, bool fgg=true)
{
  cout << "[1] f1_tmtrnd/starting, VSZ= " << VSZ << " SeqSz=" << seqsz << endl;
  TVector<r_8> DATA(VSZ);
  TC_RandomGenerator rg(seqsz, (seqsz==0)?false:true);  
  unsigned short seed[3];
//  rg.GetSeed(seed,2);  // pour imprimer l'etat du generateur
  {
    Timer tm("f0_tmtrnd-Gaussian/drand01");
    if (fgg) 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = rg.Gaussian();
    else 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = rg.Flat01();
    cout << "[2] f1_tmtrnd/ End of random generation using RandomGen class " << endl;
  }
  POutPersist po("data1.ppf");
  po << DATA;
  cout << "[3] f1_tmtrnd/  DATA saved to file data1.ppf " << endl;
  POutPersist porg("rg1.ppf");
  porg << rg;
//  rg.GetSeed(seed);  // pour imprimer l'etat du generateur
  cout << "[4] f1_tmtrnd/  RandGen saved to file rg1.ppf " << endl;
  return 0; 
}
//------- f2_tmtrnd()
int f2_tmtrnd(sa_size_t VSZ, string & inppf, bool fgg=true)
{
  cout << "[1] f2_tmtrnd/starting, VSZ= " << VSZ << " InPPFName=" << inppf << endl;
  TVector<r_8> DATA(VSZ);
  TC_RandomGenerator rg;
  PInPersist pirg(inppf);
  pirg >> rg;
  cout << "[1.b] f2_tmtrnd/ RandGen read from InPPF OK " << endl;
  unsigned short seed[3];
//  rg.GetSeed(seed,2);  // pour imprimer l'etat du generateur
  {
    Timer tm("f0_tmtrnd-Gaussian/drand01");
    if (fgg) 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = rg.Gaussian();
    else 
      for(sa_size_t k=0; k<VSZ; k++)  DATA(k) = rg.Flat01();
    cout << "[2] f1_tmtrnd/ End of random generation using RandomGen class " << endl;
  }
  POutPersist po("data2.ppf");
  po << DATA;
  cout << "[3] f1_tmtrnd/  DATA saved to file data2.ppf " << endl;
  POutPersist porg("rg2.ppf");
  porg << rg;
//  rg.GetSeed(seed,2);  // pour imprimer l'etat du generateur
  cout << "[4] f1_tmtrnd/  RandGen saved to file rg2.ppf " << endl;
  return 0; 
}

//------- f3_tmtrnd()
int f3_tmtrnd(sa_size_t VSZ, int NTH, bool fgg=true) 
{
  cout << "[1] f3_tmtrnd/starting, VSZ= " << VSZ << " NTH= " << NTH << endl;
  ResourceUsage res(ResourceUsage::RU_All);
  vector<MTRnd *> vth;
  TVector<r_8> DATA(VSZ);
  sa_size_t csz = VSZ / NTH;
  sa_size_t first, last;
  cout << "[2] f3_tmtrnd/creating threads " << endl;
  for(int kt=0; kt<NTH; kt++) {
    first = kt*csz;
    last = (kt == NTH-1) ? VSZ-1 : first+csz-1;
    TVector<r_8> sv = DATA(Range(first, last));
    vth.push_back(new MTRnd(sv, fgg) );
  }
  cout << "[3] f3_tmtrnd/starting threads " << endl;
  for(int kt=0; kt<NTH; kt++)  vth[kt]->start();
  
  cout << "[4] f3_tmtrnd/waiting for all  threads to finish " << endl;
  sleep(2);
  for(int kt=0; kt<NTH; kt++)  vth[kt]->join();
  
  cout << "[5] f3_tmtrnd/deleting thread objects " << endl;
  for(int kt=0; kt<NTH; kt++)  delete vth[kt];
  
  cout << "[6] f3_tmtrnd/saving DATA to file data3.ppf " << endl;
  POutPersist po("data3.ppf");
  po << DATA;
  cout << res;
  return 0;
}
//----------------- FIN des fonctions de test -----------------

//-------------------------------------------------------------
//---------------------- MAIN MAIN MAIN -----------------------
//-------------------------------------------------------------

int main(int narg, char *arg[])

{
  InitTim();
  SophyaInit();

  int rc = 0;
  if (narg < 4) {
    cout << " tmtrnd/Error args - Usage: tmtrnd SEL arg1 arg2 ... " << endl;
    cout << "    ==> SEL=OCG/OCF : tmtrnd OCG/OCF VecSize XXX  (-> f0_tmtrnd())" << endl;
    cout << "        OCG/OCF Random gen. with (old) c-functions G/F-> Gaussian/Flat " << endl;
    cout << "    ==> SEL=STG/STF : tmtrnd STG/STF VecSize SeqSize  (-> f2_tmtrnd())" << endl;
    cout << "        STG/STF RandGen(SeqSize) SeqSz=0 -> NO-ThSafe G/F-> Gaussian/Flat " << endl;
    cout << "    ==> SEL=RDG/RDF : tmtrnd RDG/RDF VecSize InPPFName  (-> f2_tmtrnd())" << endl;
    cout << "        RDG/RDF Read RandGen object from file InPPFName G/F-> Gaussian/Flat " << endl;
    cout << "    ==> SEL=MTG/MTF : tmtrnd MTG/MTF VecSize NThread (-> f3_tmtrnd()) " << endl;
    cout << "        MTG/MTF Multithread generation, MTG-> Gaussian, MTF-> Flat " << endl;
    return 1;
  }
  string sel = arg[1];

  try {
    bool fgg = (sel[2]=='G')?true:false;
    if ((sel == "OCG")||(sel == "OCF")) {
      sa_size_t VSZ = atoi(arg[2]);
      rc = f0_tmtrnd(VSZ, fgg);
    }
    if ((sel == "STG")||(sel == "STF")) {
      sa_size_t VSZ = atoi(arg[2]);
      size_t seqsz = atoi(arg[3]);
      rc = f1_tmtrnd(VSZ, seqsz, fgg);
    }
    if ((sel == "RDG")||(sel == "RDF")) {
      sa_size_t VSZ = atoi(arg[2]);
      string inppf = arg[3];
      rc = f2_tmtrnd(VSZ, inppf, fgg);
    }
    if ((sel == "MTG")||(sel == "MTF")) {
      sa_size_t VSZ = atoi(arg[2]);
      int NTH = atoi(arg[3]);
      rc = f3_tmtrnd(VSZ, NTH, fgg);
    }

  }
  catch (PThrowable exc) {
    cerr << "zthr: catched Exception " << exc.Msg() << endl;
    rc = 77;
  }  
  catch (...) {
    cerr << " catched unknown (...) exception (tmtrnd.cc) " << endl; 
    rc = 78; 
  } 
  cout << "----------- tmtrnd/END ------- " << endl;
  PrtTim("---END tmtrnd---");
  return(rc);
  
}
