#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#include <typeinfo>
#include <iostream.h>
#include <string>
#include <list>
#include <map>

#include "strutil.h"

#include "nobjmgr.h"
#include "servnobjm.h"
#include "nomgadapter.h"
#include "pistdimgapp.h"

#include "fct1dfit.h"
#include "fct2dfit.h"

#ifdef SANS_EVOLPLANCK
#include "matrix.h"
#include "cvector.h"
#else
#include "tmatrix.h"
#include "tvector.h"
#include "pitvmaad.h"
#endif

#include "ntuple.h"
#include "cimage.h"

#include "histos.h"
#include "histos2.h"
#include "ntuple.h"
#include "hisprof.h"

#include "piscdrawwdg.h"
#include "pisurfdr.h"

#include "pintuple.h"
#include "pintup3d.h"

#include "pipodrw.h"



/* --Methode-- */
Services2NObjMgr::Services2NObjMgr(NamedObjMgr* omg, string& tmpdir)
{
SetTmpDir(tmpdir);
mImgapp = NULL;
mOmg = omg;
dynlink = NULL;
InitGrAttNames();
}
  
/* --Methode-- */
Services2NObjMgr::~Services2NObjMgr()
{
CloseDLL();
}

/* --Methode-- */
void Services2NObjMgr::RegisterClass(AnyDataObj* o, NObjMgrAdapter* oa)
{
ObjAdaptList::iterator it;
for(it = objadaplist.begin(); it != objadaplist.end(); it++) 
#ifdef SANS_EVOLPLANCK
    if (typeid(*o) == typeid(*((*it).obj)))  THROW(dupIdErr);
#else
    if (typeid(*o) == typeid(*((*it).obj)))  
     throw(DuplicateIdExc("Services2NObjMgr::RegisterClass() - Duplicate class"));
#endif
dataobj_adapter oba;
oba.obj = o;
oba.obja = oa;
objadaplist.push_back(oba);
}

/* --Methode-- */
NObjMgrAdapter* Services2NObjMgr::GetAdapter(AnyDataObj* o)
{
ObjAdaptList::iterator it;
for(it = objadaplist.begin(); it != objadaplist.end(); it++) 
  if (typeid(*o) == typeid(*((*it).obj)))  return((*it).obja->Clone(o));
return(new NObjMgrAdapter(o));
}

/* --Methode-- */
void Services2NObjMgr::SetTmpDir(string const & tmpdir)
{
TmpDir = tmpdir;
PDynLinkMgr::SetTmpDir(tmpdir);
return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFunc(string const & expfunc, string & nom, double xmin, double xmax, int np, string dopt)
{
FILE *fip;
string fname = TmpDir + "func1_pia_dl.c";
string  cmd;
int rc;

if (!mImgapp)  return; 

cmd = "rm -f " + fname;
rc = system(cmd.c_str());
// printf("PlotFunc_Do> %s  (Rc=%d)\n", cmd.c_str(), rc); 

if ((fip = fopen(fname.c_str(), "w")) == NULL)   { 
  string sn = fname; 
  cout << "Services2NObjMgr/PlotFunc_Error: fopen( " << sn << endl; 
  return; 
  }

// constitution du fichier a compiler
fputs("#include <math.h> \n", fip);
fputs("double func1_pia_dl_func(double x) \n{\n", fip);
fprintf(fip,"return(%s); \n}\n", expfunc.c_str());
fclose(fip);

string func = "func1_pia_dl_func";
DlFunctionOfX f = (DlFunctionOfX) LinkFunctionFromFile(fname, func);
if (!f) return; 
PlotFunc(f, nom, xmin, xmax, np, dopt);
CloseDLL();
return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFunc2D(string const & expfunc, string & nom, double xmin, double xmax, 
                                  double ymin, double ymax, int npx, int npy, string dopt)
{
FILE *fip;
string fname = TmpDir + "func2_pia_dl.c";
string cmd;
int rc;

if (!mImgapp)  return; 

cmd = "rm " + fname;
rc = system(cmd.c_str());
// printf("PlotFunc2D_Do> %s  (Rc=%d)\n", cmd.c_str(), rc); 

if ((fip = fopen(fname.c_str(), "w")) == NULL)   { 
  string sn = fname; 
  cout << "Services2NObjMgr/PlotFunc2D_Error:  fopen( " << sn << endl; 
  return; 
  }

// constitution du fichier a compiler
fputs("#include <math.h> \n", fip);
fputs("double func2_pia_dl_func(double x, double y) \n{\n", fip);
fprintf(fip,"return(%s); \n}\n", expfunc.c_str());
fclose(fip);

string func = "func2_pia_dl_func";
DlFunctionOfXY f = (DlFunctionOfXY) LinkFunctionFromFile(fname, func);
if (!f)  return;
PlotFunc2D(f, nom, xmin, xmax, ymin, ymax, npx, npy, dopt);
CloseDLL();
return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFuncFrCFile(string const & fname, string const & func, string & nom, 
                                       double xmin, double xmax, int np, string dopt)
{
DlFunctionOfX f = (DlFunctionOfX) LinkFunctionFromFile(fname, func);
if (!f) return; 
PlotFunc(f, nom, xmin, xmax, np, dopt);
CloseDLL();
return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFunc2DFrCFile(string const & fname, string const & func, string & nom, 
                                         double xmin, double xmax, double ymin, double ymax, int npx, int npy, string dopt)
{
DlFunctionOfXY f = (DlFunctionOfXY) LinkFunctionFromFile(fname, func);
if (!f)  return;
PlotFunc2D(f, nom, xmin, xmax, ymin, ymax, npx, npy, dopt);
CloseDLL();
return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFunc(DlFunctionOfX f, string & nom, double xmin, double xmax, int np, string dopt)
{
if (!mImgapp)  return; 

int k;
if (np < 1) np = 1;
if (xmax <= xmin) xmax = xmin+1.;
Vector* vpy = new Vector(np);

double xx;
double dx = (xmax-xmin)/np;

try {
  for(k=0; k<np; k++) { xx = xmin+dx*k; (*vpy)(k) = f(xx); }
} 
#ifdef SANS_EVOLPLANCK
CATCH(merr) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  string es = PeidaExc(merr);
  cerr << "Services2NObjMgr::PlotFunc()  Exception :" << merr << es;
  delete vpy;
  vpy = NULL;
  } ENDTRY;
#else
catch ( PException exc ) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  cerr << "Services2NObjMgr::PlotFunc()  Exception :"  << exc.Msg() << endl; 
  delete vpy;
  vpy = NULL;
}
#endif

if (vpy) {
  string titre;
  if (nom.length() < 1) {
     titre = "Function f(x)";
     nom = "/autoc/f_x";
    }
  else titre = nom;
  
  P1DArrayAdapter* vya = new POVectorAdapter(vpy, false);
  vya->DefineXCoordinate(xmin, (xmax-xmin)/np);
  PIYfXDrawer* dr = new   PIYfXDrawer(vya, NULL, true) ; 
  bool fgsr = true;
  dopt = "thinline," + dopt;
  int opt = DecodeDispOption(dopt, fgsr);
  int rsid = mImgapp->DispScDrawer(dr, titre, opt);
  if (fgsr) mImgapp->RestoreGraphicAtt(); 
  if (nom.length() > 0) { 
    mOmg->AddObj(vpy, nom);
    mOmg->AddWRsId(nom, rsid);
    }
  }

return;
}

/* --Methode-- */
void Services2NObjMgr::PlotFunc2D(DlFunctionOfXY f, string & nom, double xmin, double xmax, double ymin, double ymax, 
                             int npx, int npy, string dopt)
{
if (!mImgapp)  return; 

if (npx < 3) npx = 3;
if (npy < 3) npy = 3;
if (npx > 250) npx = 250;
if (npy > 250) npy = 250;
if (xmax <= xmin) xmax = xmin+1.;
if (ymax <= ymin) ymax = ymin+1.;

Matrix* mtx = new Matrix(npy, npx);

int i,j;
double xx, yy;
double dx = (xmax-xmin)/npx;
double dy = (ymax-ymin)/npy;
// printf(" -- DBG -- %d %d , %g %g , %g %g \n", npx, npy, xmin, xmax, ymin, ymax);
try {
  for(j=0; j<npy; j++) {
    yy = ymin+dy*j; 
    for(i=0; i<npx; i++) {
      xx = xmin+dx*i;
      (*mtx)(j, i) = f(xx, yy);
    }
  }
}
#ifdef SANS_EVOLPLANCK
CATCH(merr) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  string es = PeidaExc(merr);
  cerr << "Services2NObjMgr::PlotFunc2D()  Exception :" << merr << es;
  delete mtx;  mtx = NULL;
  } ENDTRY;
#else
catch ( PException exc ) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  cerr << "Services2NObjMgr::PlotFunc2D()  Exception :"  << exc.Msg() << endl; 
  delete mtx;  mtx = NULL;
}
#endif

if (mtx) {
  string titre;
  if (nom.length() < 1) {
     titre = "Function f(x,y)";
     nom = "/autoc/f2d_xy";
    }
  else titre = nom;
  bool fgsr = true;
  int opt = DecodeDispOption(dopt, fgsr);
  P2DArrayAdapter* arr = new POMatrixAdapter(mtx, false);
  arr->DefineXYCoordinates(xmin, ymin, dx, dy);
  PISurfaceDrawer* sdr = new PISurfaceDrawer(arr, true, true, true);
  int rsid = mImgapp->Disp3DDrawer(sdr, titre, opt);
  if (fgsr) mImgapp->RestoreGraphicAtt();
  if (nom.length() > 0)  { 
    mOmg->AddObj(mtx, nom);
    mOmg->AddWRsId(nom, rsid);
    }
  }

return;
}

/* --Methode-- */
void Services2NObjMgr::DisplayPoints2D(string& nom,  string& expx, string& expy,
                                       string& experrx, string& experry,
                                       string& expcut, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::DisplayPoints2D() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

// Creation NTuple 
char* ntn[4] = {"expx","expy","expex","expey",};
NTuple* nt = NULL;
bool haserr = false;

if ( (experrx.length() > 0 ) && (experry.length() > 0 ) ) {  haserr = true;   nt = new NTuple(4, ntn); }
else {  haserr = false;  experrx = experry = "0."; nt = new NTuple(2, ntn); }

ComputeExpressions(obja, expx, expy, experrx, experry, expcut, loop, nt, NULL, NULL);

if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::DisplayPoints2D() Warning  Zero points satisfy cut !" << endl; 
  delete nt;
  return;
  }

// nt->Show();
// nt->Print(0,10);
PINTuple* pin = new PINTuple(nt, true);
pin->SetStats(Services2NObjMgr::GetStatsOption(dopt));
pin->SelectXY(ntn[0], ntn[1]);
if ( haserr ) pin->SelectErrBar(ntn[2], ntn[3]);

bool fgsr = true;
dopt = "defline," + dopt;
int opt = DecodeDispOption(dopt, fgsr);
string titre =  nom + ":" + expy + "%" + expx;
mImgapp->DispScDrawer( (PIDrawer*)pin, titre, opt);
if (fgsr) mImgapp->RestoreGraphicAtt();
return;
}

/* --Methode-- */
void Services2NObjMgr::DisplayPoints3D(string& nom,  string& expx, string& expy, 
                                       string& expz, string& expcut, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::DisplayPoints3D() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

char* ntn[3] = {"expx","expy","expz"};
NTuple* nt = new NTuple(3,ntn);  // Creation NTuple

string expwt = "1.";
ComputeExpressions(obja, expx, expy, expz, expwt, expcut, loop, nt, NULL, NULL);

if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::DisplayPoints3D() Warning  Zero points satisfy cut !" << endl;
  delete nt;
  return;
  }
nt->Show();
nt->Print(0,10);
PINTuple3D* pin = new PINTuple3D(nt, true);
pin->SelectXYZ(ntn[0], ntn[1], ntn[2]);
bool fgsr = true;
dopt = "defline," + dopt;
int opt = DecodeDispOption(dopt, fgsr);

// Pour plot a partir de DispScDrawer
// string nomdisp = "_NT3D_";
// mImgapp->DispScDrawer( (PIDrawer*)pin, nomdisp, opt);
// Pour plot a partir de Disp3DDrawer
string titre =  nom + ":" + expy + "%" + expx;
mImgapp->Disp3DDrawer(pin, titre, opt);

if (fgsr) mImgapp->RestoreGraphicAtt();
return;
}

/* --Methode-- */
void Services2NObjMgr::DisplayPoints2DW(string& nom, string& expx, string& expy, 
                                        string& expwt, string& expcut, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::DisplayPoints2DW() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

char* ntn[3] = {"expx","expy","expw"};
NTuple* nt = new NTuple(3,ntn);  // Creation NTuple

string exp = "1.";
ComputeExpressions(obja, expx, expy, expwt, exp, expcut, loop, nt, NULL, NULL);

if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::DisplayPoints2DW() Warning  Zero points satisfy cut !" << endl;
  delete nt;
  return;
  }

PINTuple* pin = new PINTuple(nt, true);
pin->SetStats(Services2NObjMgr::GetStatsOption(dopt));
pin->SelectXY(ntn[0], ntn[1]);
pin->SelectWt(ntn[2]);

bool fgsr = true;
int opt = DecodeDispOption(dopt, fgsr);
string titre =  nom + ":" + expwt + "_" + expy + "%" + expx ;
mImgapp->DispScDrawer( (PIDrawer*)pin, titre, opt);
if (fgsr) mImgapp->RestoreGraphicAtt();
return;
}

/* --Methode-- */
void Services2NObjMgr::ProjectH1(string& nom, string& expx, string& expwt, 
                                 string& expcut, string& nomh1, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::ProjectH1() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

Histo* h1 = NULL;
NTuple* nt = NULL;
AnyDataObj* oh = NULL; 
if (nomh1.length() > 0) oh=mOmg->GetObj(nomh1);
else nomh1 = "/tmp/projh1d";
if ( (oh != NULL) && (typeid(*oh) == typeid(Histo)) )  h1 = (Histo*)oh;  // Pas de remise a zero ! h1->Zero();
else {
  char* ntn[2]= {"hxval", "hwt"};
  nt = new NTuple(2,ntn);  // Creation NTuple 
  }
string expz = "0.";   
ComputeExpressions(obja, expx, expwt, expz, expwt, expcut, loop, nt, h1, NULL);

if ((!h1) && (!nt)) return;
if (!h1) {
  if (nt->NEntry() < 1) {
    cout << "Services2NObjMgr::ProjectH1() Warning  Zero points satisfy cut !" << endl; 
    delete nt;
    return;
    }
  double xmin, xmax;
  nt->GetMinMax(0, xmin, xmax);
  h1 = new Histo(xmin, xmax, 100);
  int k;
  float* xn;
  for(k=0; k<nt->NEntry(); k++)    {
    xn = nt->GetVec(k);
    h1->Add(xn[0], xn[1]);    
    }
  delete nt;
  mOmg->AddObj(h1, nomh1);
  }

mOmg->DisplayObj(nomh1, dopt);
return;  
}

/* --Methode-- */
void Services2NObjMgr::ProjectH2(string& nom, string& expx, string& expy, string& expwt, 
                                 string& expcut, string& nomh2, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::ProjectH2() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

Histo2D* h2 = NULL;
NTuple* nt = NULL;
AnyDataObj* oh = NULL;
if (nomh2.length() > 0)  oh=mOmg->GetObj(nomh2);
else nomh2 = "/tmp/projh2d";
if ( (oh != NULL) && (typeid(*oh) == typeid(Histo2D)) )  h2 = (Histo2D*)oh;  // Pas de remise a zero ! h2->Zero();
else {
  char* ntn[3]= {"hxval", "hyval", "hwt"};
  nt = new NTuple(3,ntn);  // Creation NTuple 
  }
string expz = "0.";   
ComputeExpressions(obja, expx, expy, expwt, expwt, expcut, loop, nt, NULL, h2);

if ((!h2) && (!nt)) return;
if (!h2) {
  if (nt->NEntry() < 1) {
    cout << "Services2NObjMgr::ProjectH2() Warning  Zero points satisfy cut !" << endl; 
    delete nt;
    return;
    }
  double xmin, xmax, ymin, ymax;
  nt->GetMinMax(0, xmin, xmax);
  nt->GetMinMax(1, ymin, ymax);
  h2 = new Histo2D(xmin, xmax, 50, ymin, ymax, 50);
  int k;
  float* xn;
  for(k=0; k<nt->NEntry(); k++)    {
    xn = nt->GetVec(k);
    h2->Add(xn[0], xn[1], xn[2]);    
    }
  delete nt;
  mOmg->AddObj(h2, nomh2);
  }

mOmg->DisplayObj(nomh2, dopt);
return;  

}

/* --Methode-- cmv 13/10/98 */
void Services2NObjMgr::ProjectHProf(string& nom, string& expx, string& expy, string& expwt,
                                    string& expcut, string& nomprof, string dopt, string loop)
//	Pour remplir un ``GeneralFitData'' a partir de divers objets: 
//| nom = nom de l'objet a projeter dans un HProf.
//| expx = expression X de definition du bin.
//| expy = expression Y a additionner dans le bin.
//| expwt = expression W du poids a additionner.
//| expcut = expression du test de selection.
//| nomprof = nom du HProf engendre (optionnel). Si l'objet n'existe pas
//|           les limites Xmin,Xmax sont calculees automatiquement.
//|           sinon ce sont celles de l'objet preexistant.
//| opt = options generales pour le display.
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::ProjectHProf() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

HProf* hprof = NULL;
NTuple* nt = NULL;
AnyDataObj* oh = NULL;
if (nomprof.length() > 0)  oh=mOmg->GetObj(nomprof);
else nomprof = "/tmp/projprof";
if( (oh!=NULL) && (typeid(*oh) == typeid(HProf)) )  hprof = (HProf*)oh;
else {
  char* ntn[3]= {"hxval", "hyval", "hwt"};
  nt = new NTuple(3,ntn);  // Creation NTuple 
}
string expz = "0.";
ComputeExpressions(obja, expx, expy, expwt, expwt, expcut, loop, nt, NULL, NULL, hprof);

if((!hprof) && (!nt)) return;
if(!hprof) {
  if (nt->NEntry() < 1) {
    cout << "Services2NObjMgr::ProjectHProf() Warning  Zero points satisfy cut !" << endl;
    delete nt;
    return;
  }
  r_8 xmin, xmax;
  nt->GetMinMax(0, xmin, xmax);
  hprof = new HProf(xmin, xmax, 100);
  int k;
  float* xn;
  for(k=0; k<nt->NEntry(); k++)    {
    xn = nt->GetVec(k);
    hprof->Add(xn[0], xn[1], xn[2]);
    }
  delete nt;
  mOmg->AddObj(hprof, nomprof);
  }
hprof->UpdateHisto();

mOmg->DisplayObj(nomprof, dopt);
return;
}


/* --Methode-- */
void Services2NObjMgr::FillVect(string& nom, string& expx, string& expv, 
                                   string& expcut, string& nomvec, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::FillVect() Error , No such object: " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

Vector* v1 = NULL;
AnyDataObj* ov = NULL; 
ov=mOmg->GetObj(nomvec);
if (ov != NULL) v1 = dynamic_cast<Vector *>(ov);
if (v1 == NULL) {
  cout << "Services2NObjMgr::FillVect() Error , No such object or not a vector: " << nomvec << endl; 
  return;
  }

char* ntn[2]= {"vi", "vv"};
NTuple* nt = new NTuple(2,ntn);  // Creation NTuple 

string expz = "0.";   
ComputeExpressions(obja, expx, expv, expz, expz, expcut, loop, nt);

if (!nt) return;
if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::FillVect() Warning  Zero points satisfy cut !" << endl; 
  delete nt;
  return;
  }

  int i,k;
  double* xn;
  for(k=0; k<nt->NEntry(); k++)    {
    xn = nt->GetLineD(k);
    i = xn[0]+0.5;
    if ( (i < 0) || i >= v1->NElts() ) continue;
    (*v1)(i) = xn[1];
    }
  delete nt;
  

mOmg->DisplayObj(nomvec, dopt);
return;  
}

/* --Methode-- */
void Services2NObjMgr::FillMatx(string& nom, string& expx, string& expy, string& expv, 
                                string& expcut, string& nommtx, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::FillMatx() Error , No such objet " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

Matrix* mtx = NULL;
AnyDataObj* om = NULL; 
om=mOmg->GetObj(nommtx);
if (om != NULL) mtx = dynamic_cast<Matrix *>(om);
if (mtx == NULL) {
  cout << "Services2NObjMgr::FillMatx() Error , No such object or not a matrix " << nommtx << endl; 
  return;
  }

char* ntn[3]= {"mi", "mj", "mv"};
NTuple* nt = new NTuple(3,ntn);  // Creation NTuple 

string expz = "0.";   
ComputeExpressions(obja, expx, expy, expv, expz, expcut, loop, nt);

if (!nt) return;
if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::FillMatx() Warning  Zero points satisfy cut !" << endl; 
  delete nt;
  return;
  }

  int ic, jl, k;
  double* xn;
  for(k=0; k<nt->NEntry(); k++)    {
    xn = nt->GetLineD(k);
    ic = xn[0]+0.5;
    jl = xn[1]+0.5;
    if ( (ic < 0) || ic >= mtx->NCol() ) continue;
    if ( (jl < 0) || jl >= mtx->NRows() ) continue;
    (*mtx)(jl, ic) = xn[2];
    }
  delete nt;
  

mOmg->DisplayObj(nommtx, dopt);
return;  

}

/* --Methode-- */
void Services2NObjMgr::ExpressionToVector(string& nom, string& expx, string& expcut, 
                                          string& nomvec, string dopt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::ExpressionToVector() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

NTuple* nt = NULL;
if (nomvec.length() < 1) nomvec = "/tmp/expvec";

char* ntn[2]= {"vecval", "vecwt"};
nt = new NTuple(1,ntn);  // Creation NTuple
 
string expwt = "1.";
string expz = "0.";
string dumexpcut = expcut; if(dumexpcut.size()<=0) dumexpcut = "1.";
ComputeExpressions(obja,expx,expz,expz,expwt,dumexpcut,loop,nt,NULL,NULL);

if (!nt) return;
if (nt->NEntry() < 1) {
  cout << "Services2NObjMgr::ExpressionToVector() Warning  Zero points satisfy cut !" << endl; 
  delete nt;
  return;
  }
  
Vector* vec = new Vector(nt->NEntry());
int k;
float* xn;
for(k=0; k<nt->NEntry(); k++)    {
  xn = nt->GetVec(k);
  (*vec)(k) = xn[0];
  }
delete nt;
mOmg->AddObj(vec, nomvec); 
mOmg->DisplayObj(nomvec, dopt);
return;  
}

/* --Methode-- */
void Services2NObjMgr::NtFromASCIIFile(string& nom,string& filename,double def_val)
//	Pour remplir un ntuple "nom" existant a partir du fichier
//	ASCII table "filename". Si il y a plus de variables dans le
//	ntuple que dans le fichier "filename",
//	les sur-numeraires sont mises a "def_val" par defaut.
{
AnyDataObj* mobj = mOmg->GetObj(nom);
if(mobj == NULL)
  {cout<<"NtFromASCIIFile() Error, object "<<nom<<" not existing"<<endl;
   return;}
if(typeid(*mobj) != typeid(NTuple))
  {cout<<"NtFromASCIIFile() Error, object "<<nom<<" not an NTuple"<<endl;
   return;}
if (!mImgapp)  return; 

NTuple* nt = (NTuple*) mobj;
nt->FillFromASCIIFile(filename, def_val);
return;
}

/* --Methode-- */
void Services2NObjMgr::FillNT(string& nom, string& expx, string& expy, string& expz, 
                              string& expt, string& expcut, string& nomnt, string loop)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::FillNT() Error , No such object " << nom << endl; 
  return;
  }
if (!mImgapp)  return; 

bool fgnnt = false;
NTuple* nt = NULL;
AnyDataObj* oh = NULL;
if (nomnt.length() > 0)  oh=mOmg->GetObj(nomnt);
else nomnt = "/tmp/fillnt";
if ( (oh != NULL) && (typeid(*oh) == typeid(NTuple)) )  { 
  nt = (NTuple*)oh;
  if (nt->NVar() > 10) {
    cout << "Services2NObjMgr::FillNT() Warning , Max 10 var in NTuple -> new NTuple" << endl;
    nt = NULL;
    }
  }  
if (nt == NULL) {
  char* ntn[4]= {"x", "y","z","t"};
  nt = new NTuple(4,ntn);  // Creation NTuple 
  fgnnt = true;
  }

ComputeExpressions(obja, expx, expy, expz, expt, expcut, loop, nt, NULL, NULL);

if (fgnnt) mOmg->AddObj(nt, nomnt);
return;  

}

/* --Methode-- */
void Services2NObjMgr::FillNTFrCFile(string & nom, string const & fname, 
                                     string const & funcname, string & nomnt, string loop)
{
if (!mImgapp)  return; 

NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::FillNTFrCFile( " << nom << "...) No such object" <<endl;
  return;
  }
bool adel = true;
NTupleInterface* objnt = obja->GetNTupleInterface(adel);
if (objnt == NULL)  {
  cout << "Services2NObjMgr::FillNTFrCFile( " << nom << "...) Not an NTupleInterface !" <<endl;
  return;
  }

NTLoopExprFunc f = (NTLoopExprFunc)LinkFunctionFromFile(fname, funcname);
if (!f) { 
  cerr << "Services2NObjMgr::FillNTFrCFile Error Creation  NTLoopExprFunc" <<  endl; 
  if (adel) delete objnt;   // Delete de l'objet NTupleInterface si necessaire
  return;
  }

bool fgnnt = false;
NTuple* nt = NULL;
if (nomnt.length() > 0) {
  AnyDataObj* oh = NULL;
  oh=mOmg->GetObj(nomnt);
  if ( (oh != NULL) && (typeid(*oh) == typeid(NTuple)) )  { 
    nt = (NTuple*)oh;
    if (nt->NVar() > 10) {
      cout << "Services2NObjMgr::FillNTFrCFile() Warning , Max 10 var in NTuple -> new NTuple" << endl;
      nt = NULL;
      }
    }  
  if (nt == NULL) {
    char* ntn[4]= {"x", "y","z","t"};
    nt = new NTuple(4,ntn);  // Creation NTuple 
    fgnnt = true;
    }
  }

double xnt[10];
float  fxnt[10];

int i,k;
for(i=0; i<10; i++) fxnt[i] = xnt[i] = 0.;


// $CHECK$ A virer des que possible  - Pb blocage application quand trop d'impression
// redirige -    On redirige la sortie sur le terminal 
bool red = mImgapp->HasRedirectedStdOutErr();
mImgapp->RedirectStdOutErr(false);

int k1,k2,dk;
k1 = 0;  k2 = objnt->NbLines();  dk = 1;
DecodeLoopParameters(loop, k1, k2, dk);
if (k1 < 0) k1 = 0;
if (k2 < 0) k2 = objnt->NbLines();
if (k2 > objnt->NbLines()) k2 = objnt->NbLines();
if (dk <= 0) dk = 1;

try  {
  double* xn;
  int kmax = k2;
  for(k=k1; k<kmax; k+=dk)    {
    xn = objnt->GetLineD(k);
    if (f(xn, xnt, xnt+1, xnt+2, xnt+3, k, kmax) != 0) {
      if (nt) { 
         for(i=0; i<4; i++) fxnt[i] = xnt[i]; 
         nt->Fill(fxnt);
         }
      }
    }
 }
#ifdef SANS_EVOLPLANCK
CATCH(merr) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  string es = PeidaExc(merr);
  cerr << "Services2NObjMgr::FillNTFrCFile()  Exception :" << merr << es;
  } ENDTRY;
#else
catch ( PException exc ) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  cerr << "Services2NObjMgr::FillNTFrCFile()  Exception :" << exc.Msg() << endl; 
}
#endif

if (adel) delete objnt;   // Delete de l'objet NTupleInterface si necessaire
CloseDLL();

// $CHECK$ A virer des que possible  On redirige la sortie sur la fenetre PIConsole 
mImgapp->RedirectStdOutErr(red);

if (fgnnt) mOmg->AddObj(nt, nomnt);
return;
}

/* --Methode-- */
void Services2NObjMgr::PrepareNTExpressionCFile(string & nom, string const & fname, 
                                                string const & funcname)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::PrepareNTExpressionCFile( " << nom << "...) No such object" <<endl;
  return;
  }
bool adel = true;
NTupleInterface* objnt = obja->GetNTupleInterface(adel);
if (objnt == NULL)  {
  cout << "Services2NObjMgr::PrepareNTExpressionCFile( " << nom 
       << "...) No NTupleInterface !" <<endl;
  return;
  }
string  vardec = objnt->VarList_C("_xnti_");

FILE *fip;
if ((fip = fopen(fname.c_str(), "w")) == NULL)   { 
  cout << "Services2NObjMgr::PrepareNTExpressionCFile()_Error: fopen " << fname << endl; 
  if (adel) delete objnt;   // Delete de l'objet NTupleInterface si necessaire
  return; 
  }

// constitution du fichier des decalarations des variables de l'interface NTuple
fputs("#include <stdlib.h> \n", fip);
fputs("#include <stdio.h> \n", fip);
fputs("#include <math.h> \n\n", fip);

fputs("/* ------ Compare bits on double --------- */ \n", fip);
fputs("typedef long long int_8;\n", fip);
fputs("int_8 BitCmp64(double v,int_8 flg)\n", fip);
fputs("{return ((int_8)((v<0.) ? v-0.1 : v+0.1))&flg;}\n", fip);
fputs("/* ------ Some random number generators --------- */ \n", fip);
fputs("#define frand01() ( (float) drand48() ) \n", fip);
fputs("#define drand01() drand48()  \n", fip);
fputs("#define rand01()  drand48()  \n", fip);
fputs("#define frandpm1() ( 2. * frand01() - 1.) \n", fip);
fputs("#define drandpm1() ( 2. * drand01() - 1.) \n", fip);
fputs("#define randpm1() ( 2. * drand01() - 1.) \n", fip);
fputs("double NorRand(void) \n", fip);
fputs(" { \n double x,A,B; \n LAB10: \n A = drand01(); \n", fip);
fputs(" if ( A == 0. ) goto LAB10; \n B = drand01(); \n", fip);
fputs(" x = sqrt(-2.*log(A))*cos(2.*M_PI*B); \n", fip);
fputs(" return(x); \n } \n", fip);
fputs("#define GauRand() NorRand() \n", fip);
fputs("#define gaurand() NorRand() \n\n", fip);

fputs("/* NTupleInterface Variable declaration - Generated by piapp  \n", fip);
fputs("      -- Services2NObjMgr::PrepareNTExpressionCFile()  --     */ \n\n", fip);
fprintf(fip,"int %s(double* _xnti_, double* _rx_, double* _ry_, double* _rz_, \n", 
        funcname.c_str());
fprintf(fip,"       double* _rt_, int _n_, int _nmax_) \n");
fprintf(fip, "{ \n %s \n", vardec.c_str());
fputs("  if (!1) { /* Cut Expression failed */ \n", fip);
fputs("    *_rx_ = *_ry_ = *_rz_ = *_rt_ = 0.;  return(0);", fip);
fputs("  } \n  /* Cut expression satisfied */ \n", fip);
fputs("  *_rx_ = 1.; \n  *_ry_ = 1.; \n  *_rz_ = 1.; \n  *_rt_ = 1.; \n", fip);
fputs("  return(1); \n} \n", fip);

fclose(fip);

if (adel) delete objnt;   // Delete de l'objet NTupleInterface si necessaire
return;
}

/* --Methode-- cmv 13/10/98 */
void Services2NObjMgr::FillGFD(string& nom, string& expx, string& expy, string& expz,
                               string& experr, string& expcut, string& nomgfd, string loop)
//	Pour remplir un ``GeneralFitData'' a partir de divers objets:
//| nom = nom de l'objet a transcrire selon 1D: Z=f(X) ou 2D: Z=f(X,Y) .
//|       Vector,Matrix,Histo,HProf,Histo2D,Image<T>,StarList,NTuple,GeneralFitData
//| expx = expression X du GeneralFitData (1er abscisse)
//| expy = expression Y du GeneralFitData (2sd abscisse si non "", Z=f(X,Y))
//| expz = expression Z du GeneralFitData (valeur de l'ordonnee)
//| experr = expression de l'erreur sur l'ordonnee Z
//| expcut = expression du test de selection
//| nomgfd = nom du GeneralFitData engendre (optionnel)
{
NObjMgrAdapter* obja=NULL;
obja = mOmg->GetObjAdapter(nom);
if (obja == NULL) {
  cout << "Services2NObjMgr::FillGFD() Error , No such object "<<nom<<endl;
  return;
  }
if(!mImgapp)  return;

// 2D ou 3D?
int nvar = 2;
if(expy.length()<=0) {nvar = 1; expy = "0.";}

// Creation NTuple Buffer
char* ntn[4]= {"x","y","f","e"};
NTuple*nt = new NTuple(4,ntn);

// Remplissage NTuple buffer
ComputeExpressions(obja, expx, expy, expz, experr, expcut, loop, nt, NULL, NULL);
if(nt->NEntry() < 1)
  {cout<<"Services2NObjMgr::FillGFD() Warning  Zero points satisfy cut !"<<endl; 
   delete nt; return;}

//Remplissage de la structure GeneraFitData
if (nt->NEntry() <= 0) {
  cout<<"Services2NObjMgr::FillGFD() Warning - NData= " << nt->NEntry() << endl;
  delete nt;
  return;
  }

GeneralFitData* gfd = new GeneralFitData(nvar,nt->NEntry(),0);
int k;
float* xn;
for(k=0; k<nt->NEntry(); k++) {
  xn = nt->GetVec(k);
  gfd->AddData(xn,xn[2],xn[3]);
}

// Menage et table d'objets
delete nt;
mOmg->AddObj(gfd, nomgfd);
return;
}

/* --Methode-- cmv 12/07/00 */
void Services2NObjMgr::FillGFDfrVec(string nomgfd,string namx,string namy,string namz,string name)
//	Pour remplir un ``GeneralFitData'' a partir de vecteurs
//| gdfrvec nomgd X Y ! !
//| gdfrvec nomgd X Y ! EY
//| gdfrvec nomgd X Y Z !
//| gdfrvec nomgd X Y Z EZ
//| - nomgfd = nom du generaldata a remplir
//| - namx = nom du vecteur contenant les valeurs X
//| - namy = nom du vecteur contenant les valeurs Y
//| - namz = nom du vecteur contenant les valeurs Z (ou "!")
//| - name = nom du vecteur contenant les valeurs des erreurs EY ou EZ
{
// Decodage des noms des vecteurs pour le remplissage du generaldata
if(nomgfd=="!" || nomgfd.length()<1)
  {cout<<"FillGFDfrVec_Error: bad GenaralData name "<<nomgfd<<endl; return;}
if(namx=="!" || namx.length()<1)
  {cout<<"FillGFDfrVec_Error: bad X vector name "<<namx<<endl; return;}
if(namy=="!" || namy.length()<1)
  {cout<<"FillGFDfrVec_Error: bad Y vector name "<<namy<<endl; return;}
if(namz.length()<1) namz = "!";
if(name.length()<1) name = "!";
int nvar = 0;
if(namz=="!") nvar = 1; else nvar = 2;

// Identify data
NamedObjMgr omg;
AnyDataObj* mobj = NULL;
Vector* v;
int nel = 0;
r_8 *x=NULL, *y=NULL, *z=NULL,* ez=NULL;

if( (mobj=omg.GetObj(namx)) == NULL) {
  cout<<"FillGFDfrVec_Error: unknown X object "<<namx<<endl; return;
} else {
  v = (Vector*) mobj; x = v->Data(); nel=v->NElts();
}

if( (mobj=omg.GetObj(namy)) == NULL) {
  cout<<"FillGFDfrVec_Error: unknown Y object "<<namy<<endl; return;
} else {
  v = (Vector*) mobj; y = z = v->Data(); if(v->NElts()<nel) nel=v->NElts();
}

if( nvar==2 && (mobj=omg.GetObj(namz)) == NULL) {
  cout<<"FillGFDfrVec_Error: unknown Z object "<<namz<<endl; return;
} else {
  v = (Vector*) mobj; z = v->Data(); if(v->NElts()<nel) nel=v->NElts();
}

if(name!="!") {
  if( (mobj=omg.GetObj(name)) == NULL) {
    cout<<"FillGFDfrVec_Error: unknown EZ object "<<name<<endl; return;
  } else {
    v = (Vector*) mobj; ez = v->Data(); if(v->NElts()<nel) nel=v->NElts();
  }
}

if(nel<=0)
  {cout<<"FillGFDfrVec_Error: bad number of elements "<<nel<<endl; return;}

// Create GeneralData and fill it with vectors
GeneralFitData* gfd = new GeneralFitData(nvar,nel+5,0);
if(nvar==1) gfd->SetData1(nel,x,z,ez);     // On remplit Y=f(X)
else        gfd->SetData2(nel,x,y,z,ez);   // On remplit Z=f(X,y)

// Menage et table d'objets
if( omg.GetObj(nomgfd) != NULL ) omg.DelObj(nomgfd);
mOmg->AddObj(gfd,nomgfd);
return;
}

/* --Methode-- */
void Services2NObjMgr::ComputeExpressions(NObjMgrAdapter* obja, string& expx, 
                          string& expy, string& expz, string& expt, string& expcut, string& loop, 
                          NTuple* nt, Histo* h1, Histo2D* h2, HProf* hp)
{
if (obja == NULL) return;
bool adel = true;
NTupleInterface* objnt = obja->GetNTupleInterface(adel);
if (objnt == NULL)  return;
string  vardec = objnt->VarList_C("_zz6qi_");

PlotExprFunc f = LinkExprFunc(vardec, expx, expy, expz, expt, expcut);
if (!f) { 
  cerr << "Services2NObjMgr::::ComputeExpressions() Error Creation PlotExprFunc " <<  endl; 
  if (adel) delete objnt;  // Delete de l'objet NTupleInterface si necessaire
  return;
  }

double xnt[10];
float  fxnt[10];

int i,k;
for(i=0; i<10; i++) xnt[i] = 0.;
int k1,k2,dk;
k1 = 0;  k2 = objnt->NbLines();  dk = 1;
DecodeLoopParameters(loop, k1, k2, dk);
if (k1 < 0) k1 = 0;
if (k2 < 0) k2 = objnt->NbLines();
if (k2 > objnt->NbLines()) k2 = objnt->NbLines();
if (dk <= 0) dk = 1;

try  {
  double* xn;
  for(k=k1; k<k2; k += dk)    {
    xn = objnt->GetLineD(k);
    if (f(xn, xnt, xnt+1, xnt+2, xnt+3) != 0) {
      if (nt) { 
         for(i=0; i<4; i++) fxnt[i] = xnt[i]; 
         nt->Fill(fxnt);
         }
      if (h1) h1->Add(xnt[0], xnt[3]);
      if (h2) h2->Add(xnt[0], xnt[1], xnt[3]);
      if (hp) hp->Add(xnt[0], xnt[1], xnt[3]);
      }
    }
 }
#ifdef SANS_EVOLPLANCK
CATCH(merr) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  string es = PeidaExc(merr);
  cerr << "Services2NObjMgr::ComputeExpressions()  Exception :" << merr << es;
  } ENDTRY;
#else
catch ( PException exc ) {
  fflush(stdout); 
  cout << endl; 
  cerr << endl;
  cerr << "Services2NObjMgr::ComputeExpressions()  Exception :" << exc.Msg() << endl; 
}
#endif

if (adel) delete objnt;  // Delete de l'objet NTupleInterface si necessaire
// Fermeture du fichier .so 
CloseDLL();
return;
}


/* --Methode-- */
PlotExprFunc Services2NObjMgr::LinkExprFunc(string& vardec, string& expx, string& expy, 
                                            string& expz, string& expt, string& cut)
{
FILE *fip;
string fname = TmpDir + "expf_pia_dl.c";
string cmd;
int rc;

cmd = "rm -f " + fname;
rc = system(cmd.c_str());
//DBG printf("LinkExprFunc_Do> %s  (Rc=%d)\n", cmd.c_str(), rc); 

if ((fip = fopen(fname.c_str(), "w")) == NULL)   { 
  string sn = fname; 
  cout << "Services2NObjMgr/LinkExprFunc_Error: fopen( " << sn << endl; 
  return(NULL); 
  }

// constitution du fichier a compiler
fputs("#include <stdlib.h> \n", fip);
fputs("#include <math.h> \n", fip);

fputs("/* ------ Compare bits on double --------- */ \n", fip);
fputs("typedef long long int_8;\n", fip);
fputs("int_8 BitCmp64(double v,int_8 flg)\n", fip);
fputs("{return ((int_8)((v<0.) ? v-0.1 : v+0.1))&flg;}\n", fip);
fputs("/* ------ Some random number generators --------- */ \n", fip);
fputs("#define frand01() ( (float) drand48() ) \n", fip);
fputs("#define drand01() drand48()  \n", fip);
fputs("#define rand01()  drand48()  \n", fip);
fputs("#define frandpm1() ( 2. * frand01() - 1.) \n", fip);
fputs("#define drandpm1() ( 2. * drand01() - 1.) \n", fip);
fputs("#define randpm1() ( 2. * drand01() - 1.) \n", fip);
fputs("double NorRand(void) \n", fip);
fputs(" { \n double x,A,B; \n LAB10: \n A = drand01(); \n", fip);
fputs(" if ( A == 0. ) goto LAB10; \n B = drand01(); \n", fip);
fputs(" x = sqrt(-2.*log(A))*cos(2.*M_PI*B); \n", fip);
fputs(" return(x); \n } \n", fip);
fputs("#define GauRand() NorRand() \n", fip);
fputs("#define gaurand() NorRand() \n\n", fip);

fputs("int expf_pia_dl_func(double* _zz6qi_, double* _rx_6q_, double* _ry_6q_, double* _rz_6q_, double* _rt_6q_) \n{\n", fip);
fprintf(fip,"%s \n", vardec.c_str());
fprintf(fip, "if (!(%s)) { *_rx_6q_ = *_ry_6q_ = *_rz_6q_ = *_rt_6q_ = 0.;  return(0); } \n", cut.c_str());
fprintf(fip, "*_rx_6q_ = %s ; \n", expx.c_str());
fprintf(fip, "*_ry_6q_ = %s ; \n", expy.c_str());
fprintf(fip, "*_rz_6q_ = %s ; \n", expz.c_str());
fprintf(fip, "*_rt_6q_ = %s ; \n", expt.c_str());
fputs("return(1); \n} \n", fip);
fclose(fip);
string func = "expf_pia_dl_func";
return((PlotExprFunc)LinkFunctionFromFile(fname, func));
}


/* --Methode-- */
DlFunction Services2NObjMgr::LinkFunctionFromFile(string const & fname, string const & funcname)
{
//  Le link dynamique
CloseDLL();
dynlink = PDynLinkMgr::BuildFromCFile(fname);
if (dynlink == NULL) { 
  cerr << "Services2NObjMgr/LinkFunctionFromFile_Erreur: Erreur creation/Ouverture SO " << endl; 
  return(NULL); 
  }

DlFunction retfunc = dynlink->GetFunction(funcname);
if (retfunc == NULL) { 
  string sn = funcname; 
  cerr << "Services2NObjMgr/LinkExprFunc_Erreur: Erreur linking " << sn << endl; 
  CloseDLL();
  return(NULL); 
  }
else return(retfunc);
}

/* --Methode-- */
void Services2NObjMgr::CloseDLL()
{
if (dynlink) delete dynlink;   dynlink = NULL;
}

/* --Methode-- */
int Services2NObjMgr::ExecuteCommand(string line)
{
  if (mImgapp == NULL) return(99);
  return(mImgapp->CmdInterpreter()->Interpret(line));
}

// Fonction static
/* --Methode-- */
void Services2NObjMgr::DecodeLoopParameters(string& loop, int& i1, int& i2, int& di)
{
// Decode des paramatres de boucle for(int i=i1; i<i2; i+=di) specifies 
// sous forme i1[:i2[:di]]
// cout << "LoopParam() " << loop << " I1=" << i1 << " I2=" << i2 << " DI=" << di; 
size_t l = loop.length();
if (l < 1) return;
size_t p = loop.find(':');
if (p >= l) { i1 = atoi(loop.c_str()); return; }
i1 = atoi(loop.substr(0, p).c_str());
string aa = loop.substr(p+1);
p = aa.find(':');
if (p < aa.length() ) { 
  i2 = atoi(aa.substr(0,p).c_str());
  di = atoi(aa.substr(p+1).c_str());
  }
else i2 = atoi(aa.c_str());
// cout << "-> I1= " << i1 << " I2= " << i2 << " DI= " << di << endl; 
return;
}

/* --Methode-- */
string Services2NObjMgr::FileName2Name(string const & fn)
{

char fsep[2] = {FILESEP, '\0'};
char tsep[2] = {'.', '\0'};
size_t p = fn.find_last_of(fsep);
size_t l = fn.length();
if (p >= l)  p = 0;
else p++;
size_t q = fn.find_first_of(tsep,p);
if (q < p) q = l;
return(fn.substr(p,q-p));
}


// Variable pour stocker l'option de stat des drawers
static bool stats_option = true;
/* --Methode-- */
void Services2NObjMgr::SetDefaultStatsOption(bool opt)
{
  stats_option = opt;
}

typedef vector<string> GraTok;

/* --Methode-- */
bool Services2NObjMgr::GetStatsOption(string& gratt)
{
int ropt = Disp_Next;
for(int i=0; i<gratt.length(); i++) gratt[i] = tolower(gratt[i]);
// On separe en mots separes par des virgules 
gratt = ","+gratt;
size_t p = 0;
size_t q = 0;
size_t l = gratt.length();
string token;

GraTok grt;

while (q < l)  {
  p = gratt.find_first_not_of(" ,",q+1); // au debut d'un token
  if (p>=l) break;
  q = gratt.find_first_of(" ,",p); // la fin du token;
  token = gratt.substr(p,q-p);
  grt.push_back(token);
  }
int k;
bool fgsame = false;
int option = 0; 
for(k=0; k<grt.size(); k++) {
  if ( (grt[k] == "same") || (grt[k] == "s") )  option = 1;
  else if ( (grt[k] == "stat") || (grt[k] == "stats") ) option = 2;
  else if ( (grt[k] == "nostat") || (grt[k] == "nostats") ) option = 3;
}

if (option == 0)  return(stats_option);
else if ( (option == 1) || (option == 3) )  return(false);
else return(true);
}

/* --Methode-- */
int Services2NObjMgr::DecodeDispOption(string& gratt, bool& fgsrgr)
{
int ropt = Disp_Next;
if (!mImgapp)  return(ropt); 

for(int i=0; i<gratt.length(); i++) gratt[i] = tolower(gratt[i]);

if (fgsrgr) mImgapp->SaveGraphicAtt();

if ( (gratt == "def") || (gratt == "default") )  {  // Remise aux valeurs par defaut = non defini
  mImgapp->SetColAtt();
  mImgapp->SetLineAtt();
  mImgapp->SetFontName();
  mImgapp->SetFontAtt();
  mImgapp->SetMarkerAtt();
  mImgapp->SetColMapId();
  mImgapp->SetReverseColMapFlag();
  mImgapp->SetZoomAtt();
  mImgapp->SetAxesAtt();
  mImgapp->SetXYLimits();
  mImgapp->UseXYLimits();
  mImgapp->SetImageCenterPosition();
  mImgapp->UseImageCenter();
  mImgapp->SetXLogScale();
  mImgapp->SetYLogScale();
  mImgapp->SetAutoAddTitle();
  stats_option = true;
  return(ropt);
  }

// On separe en mots separes par des virgules 
gratt = ","+gratt;
size_t p = 0;
size_t q = 0;
size_t l = gratt.length();
string token;

GraTok grt;

while (q < l)  {
  p = gratt.find_first_not_of(" ,",q+1); // au debut d'un token
  if (p>=l) break;
  q = gratt.find_first_of(" ,",p); // la fin du token;
  token = gratt.substr(p,q-p);
  grt.push_back(token);
  }


static GrAttNames::iterator it;

int k; 
bool fgcont = true;
fgsrgr = false;

for(k=0; k<grt.size(); k++) {
//  cout << "--DBG--SetGraphicAttributes() " << grt[k] << endl;

 // Decodage option affichage (win, next, etc 
  fgcont = true;
  if ( (grt[k] == "win") || (grt[k] == "w") )  ropt =  Disp_Win;
  else if ( (grt[k] == "same") || (grt[k] == "s") )  ropt = Disp_Same;
  else if ( (grt[k] == "inset") || (grt[k] == "ins") )  ropt = Disp_Inset;
  else  if ( (grt[k] == "stack") || (grt[k] == "st") )  ropt = Disp_Stack;
  else fgcont = false;
  if (fgcont)   continue;

  // Utilisation limites X-Y
  if ( grt[k] == "xylimits" ) { mImgapp->UseXYLimits(true);  fgsrgr = true;  continue; }
  if ( grt[k] == "centerimg" ) { mImgapp->UseImageCenter(true);  fgsrgr = true;  continue; }
  // Echelle logarithmique d'axe
  if ( grt[k] == "logx" )  { mImgapp->SetXLogScale(true); fgsrgr = true;  continue; }
  if ( grt[k] == "linx" )  { mImgapp->SetXLogScale(false); fgsrgr = true;  continue; }
  if ( grt[k] == "logy" )  { mImgapp->SetYLogScale(true); fgsrgr = true;  continue; }
  if ( grt[k] == "liny" )  { mImgapp->SetYLogScale(false); fgsrgr = true;  continue; }
  // Ajout automatique de titre
  if ( ( grt[k] == "tit" ) || ( grt[k] == "title" ) )
    { mImgapp->SetAutoAddTitle(true); fgsrgr = true;  continue; }
  if ( ( grt[k] == "notit" ) || ( grt[k] == "notitle" ) )
    { mImgapp->SetAutoAddTitle(false); fgsrgr = true;  continue; }

  // Inversion d'indexage de ColorMap
  if (grt[k] == "revcmap") 
    { mImgapp->SetReverseColMapFlag(true); fgsrgr = true;  continue; }

  // Si c'est une couleur
  it = GrAcolors.find(grt[k]);
  if (it != GrAcolors.end())  { mImgapp->SetColAtt((PIColors)((*it).second.a1)); fgsrgr = true; continue; }
  // Si c'est un attribut de lignes
  it = GrAlines.find(grt[k]);
  if (it != GrAlines.end())  { mImgapp->SetLineAtt((PILineAtt)((*it).second.a1));  fgsrgr = true; continue; }
  // Si c'est un attribut de fontes
  it = GrAfonts.find(grt[k]);
  if (it != GrAfonts.end())  { mImgapp->SetFontAtt((PIFontSize)((*it).second.a2), (PIFontAtt)((*it).second.a1) ); 
                               fgsrgr = true;  continue; }
  // Si c'est un nom de fontes
  it = GrAfontNames.find(grt[k]);
  if (it != GrAfontNames.end()) { mImgapp->SetFontName((PIFontName)((*it).second.a1));
                                 fgsrgr = true;  continue; }
  // Si c'est un attribut de markers
  it = GrAmarkers.find(grt[k]);
  if (it != GrAmarkers.end())  { mImgapp->SetMarkerAtt((*it).second.a2, (PIMarker)((*it).second.a1) ); 
                                 fgsrgr = true;  continue; }
  // Si c'est un colormap
  it = GrAcmap.find(grt[k]);
  if (it != GrAcmap.end())  { mImgapp->SetColMapId( (CMapId)((*it).second.a1) ); fgsrgr = true; continue; }  
  // Si c'est un facteur de zoom
  it = GrAzoom.find(grt[k]);
  if (it != GrAzoom.end())  { mImgapp->SetZoomAtt( (*it).second.a1 );  fgsrgr = true; continue; }  
  // Si c'est un attribut d'axe
  it = GrAaxes.find(grt[k]);
  if (it != GrAaxes.end())  { mImgapp->SetAxesAtt( (*it).second.a1 );  fgsrgr = true; continue; }  
  
  }  

return(ropt);
}


// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Initialisation des chaines de caracteres designant les attributs graphiques 

/* --Methode-- */
void Services2NObjMgr::InitGrAttNames()
{
gratt_item gi;
// Les couleurs
gi.a2 = 0;
gi.a1 = PI_NotDefColor;
GrAcolors["defcol"] = gi;
gi.a1 = PI_Black;
GrAcolors["black"] = gi;
gi.a1 = PI_White;
GrAcolors["white"] = gi;
gi.a1 = PI_Grey;
GrAcolors["grey"] = gi;
gi.a1 = PI_Red;
GrAcolors["red"] = gi;
gi.a1 = PI_Blue;
GrAcolors["blue"] = gi;
gi.a1 = PI_Green;
GrAcolors["green"] = gi;
gi.a1 = PI_Yellow;
GrAcolors["yellow"] = gi;
gi.a1 = PI_Magenta;
GrAcolors["magenta"] = gi;

gi.a1 = PI_Cyan;
GrAcolors["cyan"] = gi;
gi.a1 = PI_Turquoise;
GrAcolors["turquoise"] = gi;
gi.a1 = PI_NavyBlue;
GrAcolors["navyblue"] = gi;
gi.a1 = PI_Orange;
GrAcolors["orange"] = gi;
gi.a1 = PI_SiennaRed;
GrAcolors["siennared"] = gi;
gi.a1 = PI_Purple;
GrAcolors["purple"] = gi;
gi.a1 = PI_LimeGreen;
GrAcolors["limegreen"] = gi;
gi.a1 = PI_Gold;
GrAcolors["gold"] = gi;
gi.a1 = PI_Violet;
GrAcolors["violet"] = gi;
gi.a1 = PI_VioletRed;
GrAcolors["violetred"] = gi;
gi.a1 = PI_BlueViolet;
GrAcolors["blueviolet"] = gi;
gi.a1 = PI_DarkViolet;
GrAcolors["darkviolet"] = gi;

// Les attributs de lignes
gi.a2 = 0;
gi.a1 = PI_NotDefLineAtt;
GrAlines["defline"] = gi;
gi.a1 = PI_NormalLine;
GrAlines["normalline"] = gi;
gi.a1 = PI_ThinLine;
GrAlines["thinline"] = gi;
gi.a1 = PI_ThickLine;
GrAlines["thickline"] = gi;
gi.a1 = PI_DashedLine;
GrAlines["dashedline"] = gi;
gi.a1 = PI_ThinDashedLine;
GrAlines["thindashedline"] = gi;
gi.a1 = PI_ThickDashedLine;
GrAlines["thickdashedline"] = gi;
gi.a1 = PI_DottedLine;
GrAlines["dottedline"] = gi;
gi.a1 = PI_ThinDottedLine;
GrAlines["thindottedline"] = gi;
gi.a1 = PI_ThickDottedLine;
GrAlines["thickdottedline"] = gi;

// Noms de fontes
gi.a2 = 0;
gi.a1 = PI_DefaultFont;
GrAfontNames["deffont"] = gi;
gi.a1 = PI_CourierFont;
GrAfontNames["courierfont"] = gi;
gi.a1 = PI_HelveticaFont;
GrAfontNames["helveticafont"] = gi;
gi.a1 = PI_TimesFont;
GrAfontNames["timesfont"] = gi;
gi.a1 = PI_SymbolFont;
GrAfontNames["symbolfont"] = gi;

// Attributs de fontes 
gi.a2 = PI_NotDefFontSize;
gi.a1 = PI_NotDefFontAtt;
GrAfontNames["deffontatt"] = gi;
gi.a2 = PI_NormalSizeFont;
gi.a1 = PI_RomanFont;
GrAfonts["normalfont"] = gi;
gi.a1 = PI_BoldFont;
GrAfonts["boldfont"] = gi;
gi.a1 = PI_ItalicFont;
GrAfonts["italicfont"] = gi;
gi.a1 = PI_BoldItalicFont;
GrAfonts["bolditalicfont"] = gi;
gi.a2 = PI_SmallSizeFont;
gi.a1 = PI_RomanFont;
GrAfonts["smallfont"] = gi;
gi.a1 = PI_BoldFont;
GrAfonts["smallboldfont"] = gi;
gi.a1 = PI_ItalicFont;
GrAfonts["smallitalicfont"] = gi;
gi.a1 = PI_BoldItalicFont;
GrAfonts["smallbolditalicfont"] = gi;
gi.a2 = PI_BigSizeFont;
gi.a1 = PI_RomanFont;
GrAfonts["bigfont"] = gi;
gi.a1 = PI_BoldFont;
GrAfonts["bigboldfont"] = gi;
gi.a1 = PI_ItalicFont;
GrAfonts["bigitalicfont"] = gi;
gi.a1 = PI_BoldItalicFont;
GrAfonts["bigbolditalicfont"] = gi;
gi.a2 = PI_HugeSizeFont;
gi.a1 = PI_RomanFont;
GrAfonts["hugefont"] = gi;
gi.a1 = PI_BoldFont;
GrAfonts["hugeboldfont"] = gi;
gi.a1 = PI_ItalicFont;
GrAfonts["hugeitalicfont"] = gi;
gi.a1 = PI_BoldItalicFont;
GrAfonts["hugebolditalicfont"] = gi;


// Les markers 
const char* mrkn[11] = { "dotmarker", "plusmarker", "crossmarker", 
                         "circlemarker", "fcirclemarker", "boxmarker", "fboxmarker", 
                         "trianglemarker", "ftrianglemarker", "starmarker", "fstarmarker"};
PIMarker mrk[11] = { PI_DotMarker, PI_PlusMarker, PI_CrossMarker, 
                     PI_CircleMarker, PI_FCircleMarker, PI_BoxMarker, PI_FBoxMarker, 
                     PI_TriangleMarker, PI_FTriangleMarker, PI_StarMarker, PI_FStarMarker};

gi.a2 = 0;
gi.a1 = PI_NotDefMarker;
GrAmarkers["defmarker"] = gi;
 
for(int j=0; j<11; j++) {
  string smrk;
  char buff[16];
  for(int m=1; m<10; m+=2) {
    sprintf(buff,"%d",m);
    smrk = (string)mrkn[j] + (string)buff;
    gi.a1 = mrk[j];  gi.a2 = m;
    GrAmarkers[smrk] = gi;
    }
  }

// Les tables de couleurs 
gi.a2 = 0;
gi.a1 = CMAP_OTHER;
GrAcmap["defcmap"] = gi;
for(int kcc=0; kcc<PIColorMap::NumberStandardColorMaps(); kcc++) {
  gi.a1 = PIColorMap::GetStandardColorMapId(kcc);
  string colname = PIColorMap::GetStandardColorMapName(kcc);
  for(int jll=0; jll<colname.length(); jll++)
    colname[jll] = tolower(colname[jll]);
  GrAcmap[colname] = gi;
}


// La valeur de zoom
gi.a2 = 0;
gi.a1 = 0;
GrAzoom["defzoom"] = gi;
gi.a1 = 1;
GrAzoom["zoomx1"] = gi;
gi.a1 = 2;
GrAzoom["zoomx2"] = gi;
gi.a1 = 3;
GrAzoom["zoomx3"] = gi;
gi.a1 = 4;
GrAzoom["zoomx4"] = gi;
gi.a1 = 5;
GrAzoom["zoomx5"] = gi;
gi.a1 = -2;
GrAzoom["zoom/2"] = gi;
gi.a1 = -3;
GrAzoom["zoom/3"] = gi;
gi.a1 = -4;
GrAzoom["zoom/4"] = gi;
gi.a1 = -5;
GrAzoom["zoom/5"] = gi;

// Attributs d'axes
gi.a2 = 0;
gi.a1 = (int)(kBoxAxes | kExtTicks | kLabels);
GrAaxes["stdaxes"] = gi;
GrAaxes["defaxes"] = gi;
GrAaxes["boxaxes"] = gi;
gi.a1 = (int)kAxesDflt;
GrAaxes["simpleaxes"] = gi;
gi.a1 = (int)(kBoxAxes | kExtTicks | kLabels | kGridOn);
GrAaxes["boxaxesgrid"] = gi;

gi.a1 = (int)(kBoxAxes | kTicks | kLabels | kMinTicks | kMajTicks);
GrAaxes["fineaxes"] = gi;
 gi.a1 = (int)(kBoxAxes | kTicks | kLabels | kMinTicks | kMajTicks | kGridOn);
GrAaxes["grid"] = gi;
GrAaxes["fineaxesgrid"] = gi;
                
}


// SANS_EVOLPLANCK     Attention !
#ifdef SANS_EVOLPLANCK
#include "pclassids.h"

/* --Methode-- */
char* Services2NObjMgr::PClassIdToClassName(int cid)
{
switch (cid) {
  case ClassId_Poly1 : 
    return("Poly1");
  case ClassId_Poly2 : 
    return("Poly2");
  case ClassId_Matrix : 
    return("Matrix");
  case ClassId_Vector : 
    return("Vector");

  case ClassId_DVList : 
    return("DVList");

  case ClassId_Histo1D : 
    return("Histo1D");
  case ClassId_Histo2D : 
    return("Histo2D");
  case ClassId_HProf : 
    return("HProf");
  case ClassId_NTuple : 
    return("NTuple");
  case ClassId_XNTuple : 
    return("XNTuple");
  case ClassId_GeneralFitData : 
    return("GeneralFitData");

  case ClassId_Image : 
    return("RzImage");
  case ClassId_Image + kuint_1 : 
    return("ImageU1");
  case ClassId_Image + kint_1 : 
    return("ImageI1");
  case ClassId_Image + kuint_2 : 
    return("ImageU2");
  case ClassId_Image + kint_2 : 
    return("ImageI2");
  case ClassId_Image + kuint_4 : 
    return("ImageU4");
  case ClassId_Image + kint_4 : 
    return("ImageI4");
  case ClassId_Image + kr_4 : 
    return("ImageR4");
  case ClassId_Image + kr_8 : 
    return("ImageR8");
  case ClassId_ZFidu : 
    return("ZFidu");

  case ClassId_StarList : 
    return("StarList");
  case ClassId_Transfo : 
    return("Transfo");
  case ClassId_PSF : 
    return("PSF");


// - Ajout objet PPF
  default:
    return("AnyDataObj");
  }
}  

#else
char* Services2NObjMgr::PClassIdToClassName(int cid)
{
    return("AnyDataObj");
}
#endif
