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

#include <typeinfo>
#include <iostream>
#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 "piyfxdrw.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;
}
  
/* --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) ; 
  dopt = "thinline " + dopt;
  int rsid = mImgapp->DispScDrawer(dr, titre, dopt);
  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;
  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, dopt);
  if (nom.length() > 0)  { 
    mOmg->AddObj(mtx, nom);
    mOmg->AddWRsId(nom, rsid);
    }
  }

return;
}

/* --Methode-- */
void Services2NObjMgr::ExpVal(string expval,string resultvarname)
{
 // Fill C-file to be executed
 FILE *fip;
 string func = "eval_pia_dl_func";
 string fname = TmpDir + func; fname += ".c";
 string  cmd = "rm -f " + fname; system(cmd.c_str());
 if((fip=fopen(fname.c_str(), "w"))==NULL) { 
   cout << "Services2NObjMgr/EvalExp_Error: fopen("<<fname<<")"<<endl; 
   return; 
 }
 fprintf(fip,"#include <math.h>\n");
 fprintf(fip,"double %s(double ___dummy_variable___) \n{\n",func.c_str());
 // Add all variables already declared
 DVList& varlist = mOmg->GetVarList();
 DVList::ValList::const_iterator it;
 for(it = varlist.Begin(); it != varlist.End(); it++) {
#ifdef SANS_EVOLPLANCK
   MuTyV mtv = (*it).second;
   double value = (double)(mtv);
#else
   double value = (double)((*it).second.elval);
#endif
   string name_var = (*it).first;
   fprintf(fip,"double %s = %.17f;\n",name_var.c_str(),value);
 }
 fprintf(fip,"return %s;\n}\n",expval.c_str());
 fclose(fip);

 // Dynamically link function
 DlFunctionOfX f = (DlFunctionOfX) LinkFunctionFromFile(fname,func);
 if(!f) {
   cout<<"Services2NObjMgr/EvalExp_Error: linking DlFunctionOfX"<<endl;
   cout<<"...expval = "<<expval<<endl;
   return;
 }

 // Evaluate function and close dynamic link
 double result;
 try {
   result = f(0.);
   CloseDLL();
 } catch ( ... ) {
   cout<<"Services2NObjMgr/EvalExp_Error: Arithmetic exception"<<endl;
   CloseDLL();
   return;
 }

 // Eventually store the result into variable or just print it
 if(resultvarname.size()>0) {
   if(mOmg->HasVar(resultvarname)) mOmg->DeleteVar(resultvarname);
   char str[512];
   if(result==0.) sprintf(str,"%f",result);
   else {
     double lr = log10(fabs(result));
     if(lr>-17. && lr<17.) sprintf(str,"%17f",result);
     else                   sprintf(str,"%.17e",result);
   }
   mOmg->SetVar(resultvarname,(string)str);
 } else cout<<result<<" = "<<expval<<endl;

}

/* --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->SelectXY(ntn[0], ntn[1]);
if ( haserr ) pin->SelectErrBar(ntn[2], ntn[3]);

dopt = "defline " + dopt;
string titre =  nom + ":" + expy + "%" + expx;
mImgapp->DispScDrawer( (PIDrawer*)pin, titre, dopt);
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]);
dopt = "defline " + dopt;

// 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, dopt);

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->SelectXY(ntn[0], ntn[1]);
pin->SelectWt(ntn[2]);

string titre =  nom + ":" + expwt + "_" + expy + "%" + expx ;
mImgapp->DispScDrawer( (PIDrawer*)pin, titre, dopt);
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 = int(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 = int(xn[0]+0.5);
    jl = int(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_8 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 > (int_8)objnt->NbLines()) k2 = objnt->NbLines();
if (dk <= 0) dk = 1;

try  {
  double* xn;
  int_8 kstart = k1, kend = k2;
  for(k=kstart; k<kend; k+=dk)    {
    xn = objnt->GetLineD(k);
    if (f((int_8_exprf)k, xn, xnt, xnt+1, xnt+2, xnt+3, (int_8_exprf)kstart,(int_8_exprf) kend) != 0) {
      if (nt) { 
         for(int 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_exprf;\n", fip);
fputs("int_8_exprf BitCmp64(double v,int_8_exprf flg)\n", fip);
fputs("{return ((int_8_exprf)((v<0.) ? v-0.1 : v+0.1))&flg;}\n", fip);
fputs("/* ------ Some random number generators --------- */ \n", fip);
fputs("#if defined(__ppc__) && defined(__MACH__) \n",fip);
fputs("#include <limits.h> \n", fip);
fputs("#define drand48() ((double)(random())/LONG_MAX) \n",fip);
fputs("#endif \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", fip);
fputs("/* _nl line number or sequential index : _nstart <= _nl < _nend */ \n\n", fip);
fprintf(fip,"int %s(int_8_exprf _nl, double* _xnti_, double* _rx_, double* _ry_, double* _rz_, \n", 
        funcname.c_str());
fprintf(fip,"       double* _rt_, int_8_exprf _nstart, int_8_exprf _nend) \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_8 k;
for(k=0; k<10; k++) xnt[k] = 0.;
int_8 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 > (int_8)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((int_8_exprf)k,xn, xnt, xnt+1, xnt+2, xnt+3) != 0) {
      if (nt) { 
         for(int 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_exprf;\n", fip);
fputs("int_8_exprf BitCmp64(double v,int_8_exprf flg)\n", fip);
fputs("{return ((int_8_exprf)((v<0.) ? v-0.1 : v+0.1))&flg;}\n", fip);
fputs("/* ------ Some random number generators --------- */ \n", fip);
fputs("#if defined(__ppc__) && defined(__MACH__) \n",fip);
fputs("#include <limits.h> \n", fip);
fputs("#define drand48() ((double)(random())/LONG_MAX) \n",fip);
fputs("#endif \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(int_8_exprf _nl, 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_8& i1, int_8& i2, int_8& 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 = atol(loop.c_str()); return; }
i1 = atol(loop.substr(0, p).c_str());
string aa = loop.substr(p+1);
p = aa.find(':');
if (p < aa.length() ) { 
  i2 = atol(aa.substr(0,p).c_str());
  di = atol(aa.substr(p+1).c_str());
  }
else i2 = atol(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));
}




// 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
