#include "sopnamsp.h"
#include "piacmd.h"

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

#include "basexecut.h"

#include "pdlmgr.h"
#include "ctimer.h"
#include "strutilxx.h"

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

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

#include "tvector.h"


/* --Methode-- */
PIABaseExecutor::PIABaseExecutor(PIACmd* piac, NamedObjMgr* omg, PIStdImgApp* app)
{
mpiac = piac;
mObjMgr = omg; 
mImgApp = app;
dynlink = NULL;
dynlink2 = NULL;
RegisterCommands();
}

PIABaseExecutor::~PIABaseExecutor()
{
  if (dynlink) delete dynlink;
  if (dynlink2) delete dynlink2;
}



/* --Methode-- */
int PIABaseExecutor::Execute(string& kw, vector<string>& tokens, string& toks)
{
Services2NObjMgr* srvo = mObjMgr->GetServiceObj();
// >>>>> Chargement de modules
if (kw == "loadmodule") {
  if (tokens.size() < 2) { cout << "Usage: loadmodule fnameso modulename" << endl;  return(0); }
  mpiac->LoadModule(tokens[0], tokens[1]);
  }
  
// >>>>>>>>>>> Link dynamique de fonctions C++
else if (kw == "link" ) {
  if (tokens.size() < 2) { cout << "Usage: link fnameso f1 [f2 f3]" << endl;  return(0); }
  string sph = "";
  for(int gg=0; gg<5; gg++)   tokens.push_back(sph);
  int rc = LinkUserFuncs(tokens[0], tokens[1], tokens[2], tokens[3]);
  if (rc == 0)  cout << "PIABaseExecutor: Link from " << tokens[0] << " OK " << endl;
}
else if (kw == "linkff2" ) {
  if (tokens.size() < 2) { cout << "Usage: linkff2 fnameso f1 [f2 f3]" << endl;  return(0); }
  string sph = "";
  for(int gg=0; gg<5; gg++)   tokens.push_back(sph);
  int rc = LinkUserFuncs2(tokens[0], tokens[1], tokens[2], tokens[3]);
  if (rc == 0)  cout << "PIABaseExecutor: Link2 from " << tokens[0] << " OK " << endl;
}
else if (kw == "call" ) {
  if (tokens.size() < 1) { cout << "Usage: call userf [arg1 arg2 ...]" << endl;  return(0); }
  UsFmap::iterator it;
  UsFmap::iterator it1 = usfmap.find(tokens[0]);
  UsFmap::iterator it2 = usfmap2.find(tokens[0]);
  if ((it1 == usfmap.end()) && (it2 == usfmap2.end()) ) {
    cerr << "PIABaseExecutor: No User Function " << tokens[0] << endl;
    return(0);
  }
  if (it1 == usfmap.end())  it = it2;
  else it = it1;
  cout << "PIABaseExecutor: Call " << tokens[0] << "( ... )" << endl;
// on est oblige de faire un cast  etant donne qu'on 
// utilise donc des DlFunction  (Reza 20/08/98)  voir commentaire ds .h (pb g++)
  DlUserProcFunction fuf = (DlUserProcFunction)(*it).second;
/*DEL----- Plus besoin en multi-thread ? / Reza 06/01/2004 
//   On redirige la sortie sur le terminal 
  bool red = mImgApp->HasRedirectedStdOutErr();
  mImgApp->RedirectStdOutErr(false);
                                    --------DEL  */
  try {
    tokens.erase(tokens.begin());
    fuf(tokens);
    return(0);
  }
  catch ( PThrowable & exc ) {
    cerr << "\n PIABaseExecutor: Call / Catched Exception :" 
	 << (string)typeid(exc).name() << " Msg= " 
	 << exc.Msg() << endl;
    return(-77);
  }
  catch ( ... ) {
    cerr << "\n PIABaseExecutor: Call / Catched Exception ... " 
	 << endl;
    return(-79);
  }
/*DEL----- Plus besoin en multi-thread ? / Reza 06/01/2004 
  mImgApp->RedirectStdOutErr(red);
                                    --------DEL    */
}

else if (kw == "openppf" ) {
  if (tokens.size()<1) { 
    cout<<"Usage: openppf [-s] file [objname1 objname2 ...]"<<endl; 
    return(0); 
  }
  else if (tokens.size()==1)   // read all objects at nametags
    mObjMgr->ReadAll(tokens[0],true);  
  else { 
    if (tokens[0] == "-s")  // Read all objects sequentially
      mObjMgr->ReadAll(tokens[1],false);  
    else mObjMgr->ReadObj(tokens);   // read specified objects
  }
}
else if ((kw == "saveobjs") || (kw == "saveppf"))  {
  if (tokens.size() < 2) { cout << "Usage: saveobjs patt filename " << endl; return(0); }
  mObjMgr->SaveObjects(tokens[0], tokens[1]);  
}
else if (kw == "savelist")  {
  if (tokens.size() < 2) {
    cout << "Usage: savelist objname1 [objname2 ...] filename "<<endl;
    return(0);
  }
  mObjMgr->SaveListObjects(tokens);  
}
else if (kw == "saveall" ) {
  if (tokens.size() < 1) { cout << "Usage: saveall file " << endl; return(0); }
  mObjMgr->SaveAll(tokens[0]);  
}
else if (kw == "print" ) {
  if (tokens.size() < 1) { cout << "Usage: print nameobj [prtlev]" << endl; return(0); }
  int lev = 0;
  if (tokens.size()>1) lev = atoi(tokens[1].c_str());
  mObjMgr->PrintObj(tokens[0], lev);  
}
else if ( (kw == "rename" ) || (kw == "mv") )  {
  if (tokens.size() < 2) { cout << "Usage: rename/mv nameobj namenew" << endl; return(0); }
  mObjMgr->RenameObj(tokens[0], tokens[1]);  
}
else if ( (kw == "del" ) || (kw == "rm") ) {
  if (tokens.size() < 1) { cout << "Usage: del nameobj [nameobj2 ...]" << endl; return(0); }
  if (tokens.size()>0)
    for(uint_4 i=0;i<tokens.size();i++)  mObjMgr->DelObj(tokens[i]);  
}
else if (kw == "delobjs" ) {
  if (tokens.size() < 1) { cout << "Usage: delobjs nomobjpattern (*,?) " << endl; return(0); }
  mObjMgr->DelObjects(tokens[0]);  
}
else if ( (kw == "listobjs") || (kw == "ls") )    { 
  if  (tokens.size() < 1)  tokens.push_back("*");
  if  (tokens.size() < 2)  mObjMgr->ListObjs(tokens[0]);
  else {
    vector<string> olv;
    mObjMgr->GetObjList(tokens[0], olv);
    mpiac->SetVar(tokens[1], olv);
  }
}

// Gestion des repertoires
else if (kw == "mkdir" ) {
  if (tokens.size() < 1) { cout << "Usage: mkdir dirname [true]" << endl; return(0); }
  bool crd = mObjMgr->CreateDir(tokens[0]);  
  if ( crd && (tokens.size() > 1) && (tokens[1] == "true") )
    mObjMgr->SetKeepOldDirAtt(tokens[0], true);
  }
else if (kw == "rmdir" ) {
  if (tokens.size() < 1) { cout << "Usage: rmdir dirname " << endl; return(0); }
  mObjMgr->DeleteDir(tokens[0]);  
  }
else if (kw == "setdiratt" ) {
  if (tokens.size() < 2) { cout << "Usage: setdiratt dirname true/false" << endl; return(0); }
  if (tokens[1] == "true") mObjMgr->SetKeepOldDirAtt(tokens[0], true);
  else mObjMgr->SetKeepOldDirAtt(tokens[0], false);
}
else if (kw == "cd")   { 
  if  (tokens.size() < 1)  tokens.push_back("home");
  mObjMgr->SetCurrentDir(tokens[0]);
  }
else if (kw == "pwd") { 
  string dirn;
  mObjMgr->GetCurrentDir(dirn);
  cout << "CurrentDirectory: " << dirn << endl;
  }  
else if (kw == "listdirs")   { 
  if  (tokens.size() < 1)  tokens.push_back("*");
  mObjMgr->ListDirs(tokens[0]);
  }

// >>>>>>>>>>> Creation d'histos 1D-2D
else if (kw == "newh1d") {
  if (tokens.size() < 4) { cout << "Usage: newh1d name xmin xmax nbin" << endl; return(0); }
  int_4 nbx = 100;
  r_8 xmin = 0., xmax = 1.;
  nbx = atoi(tokens[3].c_str());
  xmin = atof(tokens[1].c_str());   xmax = atof(tokens[2].c_str());
  Histo* h = new Histo(xmin, xmax, nbx);
  mObjMgr->AddObj(h, tokens[0]);
  }
else if (kw == "newh2d") {
  if (tokens.size() < 7) { 
    cout << "Usage: newh2d name xmin xmax nbinx ymin ymax nbiny" << endl; 
    return(0); 
    }
  int_4 nbx = 50, nby = 50;
  r_8 xmin = 0., xmax = 1.;
  r_8 ymin = 0., ymax = 1.;
  nbx = atoi(tokens[3].c_str());
  nby = atoi(tokens[6].c_str());
  xmin = atof(tokens[1].c_str());   xmax = atof(tokens[2].c_str());
  ymin = atof(tokens[4].c_str());   ymax = atof(tokens[5].c_str());
  Histo2D* h = new Histo2D(xmin, xmax, nbx, ymin, ymax, nby);
  mObjMgr->AddObj(h, tokens[0]);
  }
else if (kw == "newprof" || kw == "newprofe") {
  if (tokens.size() < 4)
    { cout << "Usage: newprof[e] name xmin xmax nbin [ymin ymax]" << endl; return(0); }
  int_4 nbx = 100;
  r_8 xmin = 0., xmax = 1., ymin = 1., ymax = -1.;
  if(tokens.size() > 5)
    {ymin = atof(tokens[4].c_str());   ymax = atof(tokens[5].c_str());}
  nbx = atoi(tokens[3].c_str());
  xmin = atof(tokens[1].c_str());   xmax = atof(tokens[2].c_str());
  HProf* h = new HProf(xmin, xmax, nbx, ymin, ymax);
  if(kw == "newprofe") h->SetErrOpt(false);
  mObjMgr->AddObj(h, tokens[0]);
  }

// Creation de NTuple
else if (kw == "newnt") {
  if(tokens.size() < 2)
    {cout<<"Usage: newnt name v1 v2 ... vn / newnt name nvar"<<endl; return(0);}
  vector<string> varname;
  int nvar = 0;
  const char *c = tokens[1].c_str();
  if(isdigit(c[0])) {
    nvar = atoi(tokens[1].c_str());
    if(nvar<=0 || nvar>=10000)
      {cout<<"newnt name nvar : nvar must be an positive integer<10000"<<endl;
       return(0);}
    for(int i=0;i<nvar;i++) {
      char str[16]; sprintf(str,"%d",i);
      string dum = "v"; dum += str;
      varname.push_back(dum.c_str());
    }
  } else if( islower(c[0]) || isupper(c[0]) ) {
    for(int i=1;i<(int)tokens.size();i++) {
      varname.push_back(tokens[i].c_str());
      nvar++;
    }
  } else {
    cout<<"newnt name v1 v2 ... vn : name vi must begin by a letter"<<endl
        <<"newnt name nvar : nvar must be an positive integer"<<endl;
    return(0);
  }
  char **noms = new char*[nvar];
  for(int i=0;i<nvar;i++) noms[i] = (char *)varname[i].c_str();
  NTuple* nt = new NTuple(nvar,noms);
  delete [] noms;
  mObjMgr->AddObj(nt,tokens[0]);
  }

// Creation de DataTable
else if (kw == "newdt") {
  if(tokens.size() < 2)
    {cout<<"Usage: newdt name v1:t1 v2:t2 ... vn:tn / newdt name nvar"<<endl; return(0);}
  DataTable* dt = new DataTable();
  const char *c = tokens[1].c_str();
  if(isdigit(c[0])) {
    int n = atoi(tokens[1].c_str());
    if(n<=0 || n>=10000) {
      cout<<"newdt name nvar : nvar="<<n<<" must be an positive integer<10000"<<endl;
      delete dt; return(0);
    }
    for(int i=0;i<n;i++) {
      char str[16]; sprintf(str,"v%d",i);
      dt->AddDoubleColumn(str);
    }
  } else {
    for(int i=1;i<tokens.size();i++) {
      string vname = tokens[i];
      uint_4 p = tokens[i].find(':');
      if(p<tokens[i].size()) vname = vname.substr(0,p);
      if(vname.size()<1) {
        cout<<"Zero size name for variable: tokens["<<i<<"]="<<tokens[i]<<endl;
        delete dt; return(0);
      }
      if     (tokens[i].find(":r4")<tokens[i].size()) dt->AddFloatColumn(vname);
      else if(tokens[i].find(":r8")<tokens[i].size()) dt->AddDoubleColumn(vname);
      else if(tokens[i].find(":i4")<tokens[i].size()) dt->AddIntegerColumn(vname);
      else if(tokens[i].find(":i8")<tokens[i].size()) dt->AddLongColumn(vname);
      else if(tokens[i].find(":s") <tokens[i].size()) dt->AddStringColumn(vname);
      else                                            dt->AddDoubleColumn(vname);
    }
  }
  mObjMgr->AddObj(dt,tokens[0]);
}

// Creation de GeneralFitData
else if (kw == "newgfd") {
  if (tokens.size() < 3)
    { cout << "Usage: newgfd nvar nalloc [errx(0/1)]" << endl; return(0); }
  int nvar, nalloc, errx=0;
  if (tokens.size() > 3)
    { errx = atoi(tokens[3].c_str()); if(errx>0) errx=1; else errx = 0;}
  nvar = atoi(tokens[1].c_str()); nalloc = atoi(tokens[2].c_str());
  if(nvar>0 && nalloc>0) {
    GeneralFitData* gfd = new GeneralFitData(nvar,nalloc,errx);
    mObjMgr->AddObj(gfd, tokens[0]);
    }
  }

// Creation/remplissage de vecteur et de matrice
else if (kw == "newvec") {
  if (tokens.size() < 2) { 
    cout << "Usage: newvec name size [f(i) dopt] " << endl; return(0); 
    }
  int n = atoi(tokens[1].c_str());
  double xmin, xmax;
  xmin = 0.;  xmax = n;
  if (tokens.size() < 3)  { 
    Vector* v = new Vector(n);
    mObjMgr->AddObj(v, tokens[0]);
    }
  else {
    if (tokens.size() < 4)  tokens.push_back("");
    mObjMgr->GetServiceObj()->PlotFunc(tokens[2], tokens[0], xmin, xmax, n, tokens[3]); 
    }
  }
else if (kw == "newmtx") {
  if (tokens.size() < 3) { 
    cout << "Usage: newmtx name sizeX(Col) sizeY(Lines) [f(i,j) dopt] " << endl; return(0); 
    }
  int nx = atoi(tokens[1].c_str());
  int ny = atoi(tokens[2].c_str());
  double xmin, xmax, ymin, ymax;
  xmin = 0.;  xmax = nx;
  ymin = 0.;  ymax = ny;
  if (tokens.size() < 4)  {
    Matrix* mtx = new Matrix(ny,nx);
    mObjMgr->AddObj(mtx, tokens[0]);
    }
  else {
    if (tokens.size() < 5)  tokens.push_back("next");
    mObjMgr->GetServiceObj()->PlotFunc2D(tokens[3], tokens[0], xmin, xmax, ymin, ymax, 
                                         nx, ny, tokens[4]);
    }
  }
// ----- Vecteur/NTuple <> Lignes/variables interpreteur
// Creation de vecteur depuis le contenu de la ligne
else if (kw == "line2vec") {  
  if (tokens.size() < 2) { 
    cout << "Usage: line2vec vecname v0 v1 v2 ... " << endl; return(0); 
    }
  int vsz = tokens.size()-1;
  Vector* v = new Vector(vsz);
  for(int kkv=0; kkv<vsz; kkv++)  (*v)(kkv) = atof(tokens[kkv+1].c_str());
  mObjMgr->AddObj(v, tokens[0]);
  }
// Remplissage de NTuple depuis la ligne
else if (kw == "line2nt") {
  if (tokens.size() < 2) { 
    cout << "Usage: line2nt ntname col0 col1 ..." << endl; return(0); 
  }
  AnyDataObj* obj;
  obj = mObjMgr->GetObj(tokens[0]);
  if(obj == NULL) {
    cerr << "line2nt Error , No such object " << tokens[0] << endl; 
    return(0);
  }
  NTuple* nt = dynamic_cast<NTuple *>(obj);
  if(nt == NULL) {
    cerr << "line2nt Error " << tokens[0] << " not an NTuple ! " << endl;
    return(0);
  }
  if (nt->NbColumns() < 1) {
    cerr << "line2nt Error: NbColumns  < 1" << endl;
    return(0);
  }
  r_4* xnt = new r_4[ nt->NbColumns() ];
  int kkx; 
  for(kkx=0; kkx<nt->NbColumns(); kkx++) { 
    if (kkx < tokens.size()-1)  xnt[kkx] = atof(tokens[kkx+1].c_str());
    else xnt[kkx] = 0.;
  }
  nt->Fill(xnt);
  delete[] xnt;
}  
// Contenu du vecteur vers variable interpreteur
#define MAXNWORDSO2V 32768
else if (kw == "vec2var") {  
  if (tokens.size() < 2) { 
    cout << "Usage: vec2var vecname varname [loop_param start:end:step] " << endl; return(0); 
    }
  AnyDataObj* obj;
  obj = mObjMgr->GetObj(tokens[0]);
  if(obj == NULL) {
    cerr << "vec2var Error , No such object " << tokens[0] << endl; 
    return(0);
  }
  Vector* v = dynamic_cast<Vector *>(obj);
  if(v == NULL) {
    cerr << "vec2var Error " << tokens[0] << " not a Vector ! " << endl;
    return(0);
  }
  int_8 kks = 0;
  int_8 kke = v->NElts();
  int_8 kkp = 1;
  if (tokens.size() > 2) Services2NObjMgr::DecodeLoopParameters(tokens[2], kks, kke, kkp);
  if (kks < 0)  kks = 0;
  if (kke > (int_8)v->NElts()) kke = v->NElts();
  if (kkp < 1) kkp = 1;
  int nelt = (kke-kks-1)/kkp;
  if (nelt > MAXNWORDSO2V) {
    nelt = MAXNWORDSO2V;
    cout << "vec2var Warning:  Only " << nelt 
	 << " elements  will be converted to string" << endl;
    kke = kks+nelt*kkp;
  }
  string v2str;
  char buff[64];
  for(int kkv=kks; kkv<kke; kkv+=kkp) {
    sprintf(buff, "%lg ", (*v)(kkv));
    v2str += buff;
  }
  
  mpiac->SetVar(tokens[1], v2str);
}
// Une ligne du NTuple/NTupleInterface -> variable interpreteur
else if ((kw == "ntline2var") || (kw == "ntcol2var")) {  
  if (tokens.size() < 3) {
    cout << "Usage: ntline/col2var objname line_number varname" << endl; 
    return(0); 
  }
  NObjMgrAdapter* oa = mObjMgr->GetObjAdapter(tokens[0]);
  if(oa == NULL) {
    cerr << "ntline/col2var Error , No such object " << tokens[0] << endl; 
    return(0);
  }
  bool adel = false;
  NTupleInterface* nti = oa->GetNTupleInterface(adel);
  if(nti == NULL) {
    cerr << "ntline/col2var Error: objet" << tokens[0] << " has no NTupleInterface" << endl; 
    return(0);
  }

  if (nti->NbColumns() < 1 || nti->NbLines() < 1) {
    cerr << "ntline/col2var Error: NbColumns or NbLines < 1" << endl;
    return(0);
  }
  string v2str;
  char buff[64];
  if (kw == "ntline2var") {
    int numline = atoi(tokens[1].c_str());
    if ( (numline >= nti->NbLines()) || (numline < 0) )  {
      cerr << "ntline2var Error: numline" << tokens[1] << " out of bounds" << endl; 
      return(0);
    }
    r_8* dline = nti->GetLineD(numline);
    for(int kkv=0; kkv<nti->NbColumns(); kkv++) {
      sprintf(buff, "%lg ", dline[kkv]);
      v2str += buff;
    }
  }
  else {
    int numcol = atoi(tokens[1].c_str());
    if ( (numcol >= nti->NbColumns()) || (numcol < 0) )  {
      cerr << "ntcol2var Error: numcol" << tokens[1] << " out of bounds" << endl; 
      return(0);
    }
    int_8 kks = 0;
    int_8 kke = nti->NbLines();
    int_8 kkp = 1;
    if (tokens.size() > 3) Services2NObjMgr::DecodeLoopParameters(tokens[3], kks, kke, kkp);
    if (kks < 0)  kks = 0;
    if (kke > (int_8)nti->NbLines()) kke = nti->NbLines();
    if (kkp < 1) kkp = 1;
    int nelt = (kke-kks-1)/kkp;
    if (nelt > MAXNWORDSO2V) {
      nelt = MAXNWORDSO2V;
      cout << "ntcol2var Warning: Only " << nelt
	   << " lines " << " will be converted to string" << endl;
      kke = kks+nelt*kkp;
    }
    r_8* dline;
    for(int kkl=kks; kkl<kke; kkl+=kkp) {
      dline = nti->GetLineD(kkl);
      sprintf(buff, "%lg ", dline[numcol]);
      v2str += buff;
    }
  }
  mpiac->SetVar(tokens[2], v2str);
  if (adel) delete nti;
}
// Operation sur objets a travers l'adaptateur NObjMgrAdapter::PerformOperation()
else if (kw == "objaoper") {
  if (tokens.size() < 2) {
    cout << "Usage: objaoper objname operation [args ...]" << endl; 
    return(0); 
  }
  NObjMgrAdapter* oa = mObjMgr->GetObjAdapter(tokens[0]);
  if(oa == NULL) {
    cerr << "objaoper Error , No such object " << tokens[0] << endl; 
    return(0);
  }
  tokens.erase(tokens.begin());
  return oa->PerformOperation(tokens);
}

// -------------------------------------------------------
// Copie d'objets
else if ( (kw == "copy") || (kw == "cp") ) {
  if(tokens.size()<2) { 
    cout<<"Usage: copy name_from  name_to"<<endl;return(0); 
  }
  mObjMgr->CopyObj(tokens[0],tokens[1]);
}


// >>>>>>>>>>>  Trace de fonctions 
else if ( (kw == "func") ) {
  if(tokens.size()<3) {cout<<"Usage: func f(x) xmin xmax [npt opt]"<<endl; return(0);}
  int np = 100;
  double xmin=0., xmax=1.;
  string opt = "", nom = "";
  xmin = atof(tokens[1].c_str()); xmax = atof(tokens[2].c_str());
  if (tokens.size() > 3)  np = atoi(tokens[3].c_str());
  if (tokens.size() > 4)  opt = tokens[4];
  mObjMgr->GetServiceObj()->PlotFunc(tokens[0], nom, xmin, xmax, np, opt); 
  }
else if ( (kw == "funcff") ) {
  if (tokens.size()<4) {cout<<"Usage: funcff C-filename f(x)-name xmin xmax [npt opt]"<<endl; return(0);}
  int np = 100;
  double xmin=0., xmax=1.;
  string opt = "", nom = "";
  xmin = atof(tokens[2].c_str());  xmax = atof(tokens[3].c_str());
  if(tokens.size()>4)  np = atoi(tokens[4].c_str());
  if(tokens.size()>5)  opt = tokens[5];
  mObjMgr->GetServiceObj()->PlotFuncFrCFile(tokens[0], tokens[1], nom, xmin, xmax, np, opt); 
  }
else if ( (kw == "func2d") ) {
  if (tokens.size() < 7) {
    cout << "Usage: func2d f(x,y) xmin xmax nptx ymin ymax npty [opt]" << endl;
    return(0);
    }
  int npx, npy;
  double xmin, xmax;
  double ymin, ymax;
  npx = npy = 50;
  xmin = 0.;  xmax = 1.;
  ymin = 0.;  ymax = 1.;
  npx = atoi(tokens[3].c_str());
  npy = atoi(tokens[6].c_str());
  xmin = atof(tokens[1].c_str());   xmax = atof(tokens[2].c_str());
  ymin = atof(tokens[4].c_str());   ymax = atof(tokens[5].c_str());
  string opt = "";
  if (tokens.size() > 7)  opt = tokens[7];
  string nom = "";
  mObjMgr->GetServiceObj()->PlotFunc2D(tokens[0], nom, xmin, xmax, ymin, ymax, npx, npy, opt);
  }
else if ( (kw == "func2dff") ) {
  if (tokens.size() < 8) {
    cout << "Usage: func2d C-filename F(x,y)-name xmax nptx ymin ymax npty [opt]" << endl;
    return(0);
    }
  int npx, npy;
  double xmin, xmax;
  double ymin, ymax;
  npx = npy = 50;
  xmin = 0.;  xmax = 1.;
  ymin = 0.;  ymax = 1.;
  npx = atoi(tokens[4].c_str());
  npy = atoi(tokens[7].c_str());
  xmin = atof(tokens[2].c_str());   xmax = atof(tokens[3].c_str());
  ymin = atof(tokens[5].c_str());   ymax = atof(tokens[6].c_str());
  string opt = "";
  if (tokens.size() > 8)  opt = tokens[8];
  string nom = "";
  mObjMgr->GetServiceObj()->PlotFunc2DFrCFile(tokens[0], tokens[1], nom, xmin, xmax, ymin, ymax, npx, npy, opt);
  }

// >>>>>>>>>>>  Trace d'expressions de N_Tuple, StarList, etc ...
else if (kw == "plot2d" ) {
  if (tokens.size() < 3) {
    cout << "Usage: plot2d nameobj expx expy [expcut opt loop_par]" << endl;
    return(0); 
    }
  string errx = ""; string erry = ""; 
  if (tokens.size() < 4) tokens.push_back("1");
  while (tokens.size() < 6) tokens.push_back("");
  srvo->DisplayPoints2D(tokens[0],tokens[1],tokens[2],errx,erry,tokens[3],tokens[4],tokens[5]);
  }

else if (kw == "plot2de" ) {  // Plot2D avec les erreurs 
  if (tokens.size() < 5) {
    cout << "Usage: plot2de nameobj expx expy experrx experry [expcut opt loop_par]" << endl;
    return(0); 
    }
  if (tokens.size() < 6) tokens.push_back("1");
  while (tokens.size() < 8) tokens.push_back("");
  srvo->DisplayPoints2D(tokens[0],tokens[1],tokens[2],tokens[3],tokens[4],
                        tokens[5],tokens[6],tokens[7]);
  }

else if ((kw == "plot2dw")||(kw == "plot2dc")) {   // Plot2d avec poids
  if (tokens.size() < 4) { 
    cout << "Usage: plot2dw/c nomobj expx expy expwt/expcolidx [expcut opt loop_par]" << endl;
    return(0); 
    }
  if (tokens.size() < 5) tokens.push_back("1");
  while (tokens.size() < 7) tokens.push_back("");
  bool fgcolidx = false;
  if (kw == "plot2dc") fgcolidx = true;
  srvo->DisplayPoints2DW(tokens[0],tokens[1],tokens[2],tokens[3], tokens[4], 
			 fgcolidx, tokens[5], tokens[6]);
  }
else if (kw == "plot3d" ) {  
  if (tokens.size() < 4) { 
    cout << "Usage: plot3d nomobj expx expy expz [expcut opt loop_par]" << endl;
    return(0); 
    }
  if (tokens.size() < 5) tokens.push_back("1");
  while (tokens.size() < 7) tokens.push_back("");
  srvo->DisplayPoints3D(tokens[0],tokens[1],tokens[2],tokens[3], tokens[4], tokens[5], tokens[6]);
  }
else if (kw == "plot3dw" ) {  
  if (tokens.size() < 5) { 
    cout << "Usage: plot3dw nomobj expx expy expz expwt [expcut opt loop_par]" << endl;
    return(0); 
    }
  if (tokens.size() < 6) tokens.push_back("1");
  while (tokens.size() < 8) tokens.push_back("");
  srvo->DisplayPoints3DW(tokens[0],tokens[1],tokens[2],tokens[3], tokens[4], tokens[5], 
			 tokens[6], tokens[7]);
}

else if (kw == "projh1d" ) {
  if (tokens.size() < 3) { 
    cout << "Usage: projh1d nomh1 nomobj expx [expwt expcut opt loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 4) tokens.push_back("1.");
  if (tokens.size() < 5) tokens.push_back("1");
  while (tokens.size() < 7) tokens.push_back("");
  srvo->ProjectH1(tokens[1], tokens[2], tokens[3], tokens[4], tokens[0], tokens[5], tokens[6] );
  }


// Projection dans histogrammes
else if (kw == "projh2d" ) {
  if (tokens.size() < 4) { 
    cout << "Usage: projh2d nomh2 nomobj expx expy [expwt expcut opt loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 5) tokens.push_back("1.");
  if (tokens.size() < 6) tokens.push_back("1");
  while (tokens.size() < 8) tokens.push_back("");
  srvo->ProjectH2(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[0],
                  tokens[6], tokens[7] );
  }

else if (kw == "projprof" ) {
  if (tokens.size() < 4) { 
    cout << "Usage: projprof nomprof nomobj expx expy [expwt expcut opt loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 5) tokens.push_back("1.");
  if (tokens.size() < 6) tokens.push_back("1");
  while (tokens.size() < 8) tokens.push_back("");
  srvo->ProjectHProf(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[0],
                     tokens[6], tokens[7] );
  }

// Projection dans vector/matrix
else if (kw == "fillvec" ) {
  if (tokens.size() < 4) { 
    cout << "Usage: fillvec nomvec nomobj expx expv [expcut opt loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 5) tokens.push_back("1");
  while (tokens.size() < 7) tokens.push_back("");
  srvo->FillVect(tokens[1], tokens[2], tokens[3], tokens[4], tokens[0], tokens[5], tokens[6] );
  }

else if (kw == "fillmtx" ) {
  if (tokens.size() < 5) { 
    cout << "Usage: fillmtx nommtx nomobj expx expy expv [expcut opt loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 6) tokens.push_back("1");
  while (tokens.size() < 8) tokens.push_back("");
  srvo->FillMatx(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[0],
                    tokens[6], tokens[7] );
  }

// Remplissage NTuple,Vecteurs, ... , boucle de NTuple
else if (kw == "ntfrascii" ) {
  if(tokens.size() < 2) { 
    cout<<"Usage: ntfrascii nt_name file_name [def_init_val]"<<endl;
    return(0);
    }
  double def_val = 0.;
  if(tokens.size()>=3) def_val = atof(tokens[2].c_str());
  srvo->NtFromASCIIFile(tokens[0],tokens[1],def_val);
  }

/* Lecture matrice/vecteur depuis fichier ASCII  */
else if ((kw == "mtxfrascii") || (kw == "vecfrascii") ) {
  if(tokens.size() < 2) { 
    cout<<"Usage: mtxfrascii/vecfrascii mtx/vec_name file_name [CommLine Separator]"<<endl;
    return(0);
    }
  TMatrix<r_8> mtx;
  TVector<r_8> vec;
  FILE* fip = fopen(tokens[1].c_str(), "r");
  if (fip == NULL) {
    cout << "vec/mtxfrascii: can not open file " << tokens[1] << endl;
    return(0);
  }
  fclose(fip);
  ifstream is(tokens[1].c_str());
  sa_size_t nr, nc;
  char clm = '#';
  string sep = " \t";
  if (tokens.size()>2) clm = tokens[2][0];
  if (tokens.size()>3) sep = tokens[3];
  if (kw == "mtxfrascii") {
    mtx.ReadASCII(is, nr, nc, clm, sep.c_str());
    mObjMgr->AddObj(mtx, tokens[0]);    
    cout << "mtxfrascii: TMatrix<r_8> " << tokens[0] << " read from file " 
	 << tokens[1] << endl;
  }
  else {
    vec.ReadASCII(is, nr, nc, clm, sep.c_str());
    mObjMgr->AddObj(vec, tokens[0]);    
    cout << "vecfrascii: TVector<r_8> " << tokens[0] << " read from file " 
	 << tokens[1] << endl;
  }
}
else if (kw == "arrtoascii")  {
  if(tokens.size() < 2) { 
    cout<<"Usage: arrtoascii array_name file_name "<<endl;
    return(0);
  }
  
  AnyDataObj* obj;
  obj = mObjMgr->GetObj(tokens[0]);
  if(obj == NULL) {
    cerr << "arrtoascii Error , No such object " << tokens[0] << endl; 
    return(0);
  }
  BaseArray* ba = dynamic_cast<BaseArray *>(obj);
  if(ba == NULL) {
    cerr << "arrtoascii Error " << tokens[0] << " not a BaseArray ! " << endl;
    return(0);
  }
  ofstream os(tokens[1].c_str());  
  ba->WriteASCII(os);
  cout << "arrtoascii: Array " << tokens[0] << " written to file " << tokens[1] << endl;
}
  

else if (kw == "fillnt" ) {
  if (tokens.size() < 5) { 
    cout << "Usage: fillnt nameobj expx expy expz expt [expcut ntname loop_par]" << endl;
    return(0);
    }
  while (tokens.size() < 8) tokens.push_back("");
  srvo->FillNT(tokens[0],tokens[1],tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], tokens[7] );
  }

else if (kw == "ntloop" ) {
  if (tokens.size() < 3) { 
    cout << "Usage: ntloop nameobj fname funcname [ntname loop_par ]" << endl;
    return(0);
    }
  while (tokens.size() < 5) tokens.push_back("");
  srvo->FillNTFrCFile(tokens[0],tokens[1], tokens[2], tokens[3], tokens[4]);
  }

else if (kw == "ntexpcfile" ) {
  if (tokens.size() < 3) { 
    cout << "Usage: ntexpcfile nameobj fname funcname" << endl;
    return(0);
    }
  srvo->PrepareNTExpressionCFile(tokens[0],tokens[1], tokens[2]);
  }

else if (kw == "expmeansig" ) {
  if (tokens.size() < 2) { 
    cout << "Usage: expmeansig nameobj expx [expcut loop_par]" << endl;
    return(0);
    }
  while (tokens.size() < 4) tokens.push_back("");
  string dummy = "";
  cout << " expmeansig: computing mean/sigma + min/max for " << tokens[0] 
       << "." << tokens[1] << endl;
  srvo->ExpressionToVector(tokens[0],tokens[1],tokens[2],dummy,dummy,tokens[3]);
  }

else if (kw == "exptovec" ) {
  if (tokens.size() < 3) { 
    cout << "Usage: exptovec nomvec nameobj expx [expcut opt loop_par]" << endl;
    return(0);
    }
  while (tokens.size() < 6) tokens.push_back("");
  srvo->ExpressionToVector(tokens[1],tokens[2],tokens[3],tokens[0],tokens[4],tokens[5]);
  }

else if (kw == "fillgd1" ) {
  if (tokens.size() < 5) {
    cout << "Usage: fillgd1 nomgfd nomobj expx expy experry [expcut loop_par] " << endl;
    return(0);
    }
  if (tokens.size() < 6) tokens.push_back("1");
  if (tokens.size() < 7) tokens.push_back("");
  string expy = "";
  srvo->FillGFD(tokens[1],tokens[2], expy, tokens[3], tokens[4], tokens[5], tokens[0]);
  }

else if (kw == "fillgd2" ) {
  if (tokens.size() < 6) {
    cout << "Usage: fillgd2 nomgfd nomobj expx expy expz experrz [expcut loop_par]" << endl;
    return(0);
    }
  if (tokens.size() < 7) tokens.push_back("1");
  if (tokens.size() < 8) tokens.push_back("");
  srvo->FillGFD(tokens[1],tokens[2],tokens[3], tokens[4], tokens[5], tokens[6], tokens[0], tokens[7]);
  }

else if (kw == "gdfrvec" ) {
  if(tokens.size()<3) {
    cout<<"Usage: gdfrvec namegfd X Y\n"
        <<"       gdfrvec namegfd X Y"
        <<"       gdfrvec namegfd X Y ! EY\n"
        <<"       gdfrvec namegfd X Y Z\n"
        <<"       gdfrvec namegfd X Y Z EZ"<<endl;
    return(0);
  }
  while(tokens.size()<5) tokens.push_back("!");
  srvo->FillGFDfrVec(tokens[0],tokens[1],tokens[2],tokens[3],tokens[4]);
  }

// >>>>>>>>>>>  Calcul d'expression arithmetique
else if ( (kw == "eval") ) {
  if(tokens.size()<2)
    {cout<<"Usage: eval resultvarname arithmetic expression...."<<endl; return(0);}
  string expval = "";
  for(unsigned int i=1;i<tokens.size();i++) expval+=tokens[i];
  string resultvarname = "";
  if(isalpha(tokens[0][0])) resultvarname=tokens[0];
  mObjMgr->GetServiceObj()->ExpVal(expval,resultvarname); 
  }

else  { 
  cerr << "PIABaseExecutor::Do() Erreur - Commande " << kw << " inconuue ! " << endl;    
  return(-1);
  }

return(0);
}

/* --Methode-- */
bool PIABaseExecutor::IsThreadable(string const & keyw)
{
  if ( (keyw == "fillvec") || (keyw == "fillmtx") || 
       (keyw == "fillnt") || (keyw == "ntloop") )  return true;
  else if (keyw.substr(0,4) == "func")  return true;
  else {
    string skw = keyw.substr(0,5);
    if ( (skw == "plot2") || (skw == "plot3") || (skw == "projh") )  return true; 
  } 
  return false;	
}


/* --Methode-- */
void PIABaseExecutor::RegisterCommands()
{
string kw, usage, grp, gdesc;
//--------- Commandes du groupe modules externes

grp = "External Modules";
gdesc = "Dynmamic shared library load (DLL) and external (add-on) module management";
mpiac->AddHelpGroup(grp, gdesc);

kw = "loadmodule";
usage = "To load and initialize modules \n  Usage: loadmodule fnameso modulename";
usage += "\n  Related commands: link";  
mpiac->RegisterCommand(kw, usage, this, grp);
kw = "link";
usage = "Dynamic linking of compiled user functions \n  Usage: link fnameso f1 [f2 f3]";
usage += "\n  fnameso: Shared-object file name, f1,f2,f3 : User function names ";
usage += "\n  Related commands: call loadmodule linkff2";  
mpiac->RegisterCommand(kw, usage, this, grp);
kw = "linkff2";
usage = "Dynamic linking of compiled user functions (Set 2)\n  Usage: linkff2 fnameso f1 [f2 f3]";
usage += "\n  fnameso: Shared-object file name, f1,f2,f3 : User function names ";
usage += "\n  Related commands: call link loadmodule";  
mpiac->RegisterCommand(kw, usage, this, grp);
kw = "call";
usage = "Dynamically linked user function call \n Usage: call userf [arg1 arg2 ...]";
usage += "\n  User function : f(vector<string>& args)";
usage += "\n  Related commands: link";  
mpiac->RegisterCommand(kw, usage, this, grp);

kw = "openppf";
usage = "Reads all or some objects from a PPF file";
usage += "\n  Usage: (1) openppf filename ";
usage += "\n     Or  (2) openppf -s filename (2)";
usage += "\n     Or  (3) openppf filename objname1 [ objname2 ...]";
usage += "\n  The first form reads all objects at NameTags,";
usage += "\n    or all objects if the file has no NameTags.";     
usage += "\n  The third reads only the objects with the specified nametags";
usage += "\n  Related commands: saveppf saveall savelist";  
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "saveppf";
usage = "Saves objects with names matching a pattern into a\n";
usage += "  PPF file (pattern: x?y*) - Alias saveppf\n";
usage += "Usage: saveppf nameobjpattern filename";
usage += "\n  Related commands: saveobjs savelist saveall openppf";  
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "saveobjs";
usage = "Saves objects with names matching a pattern into a\n";
usage += "  PPF file (pattern: x?y*) - Alias saveppf\n";
usage += "Usage: saveobjs nameobjpattern filename";
usage += "\n  Related commands: saveppf savelist saveall openppf ";  
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "saveall";
usage = "Saves all objects into a PPF file \n Usage: saveall filename";
usage += "\n  Related commands: saveobj savelist openppf";  
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "savelist";
usage = "Saves a list of objects into a PPF file";
usage = "\n Usage: savelist objname1 [objname2 ...] filename";
usage += "\n  Related commands: saveobj openppf";  
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "ntfrascii";
usage = "Fills an existing NTuple or DataTable from ASCII table file";
usage += "\n Usage: ntfrascii nt_name file_name [def_init_val]";
usage += "\n  Related commands: ntloop fillnt ";
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "mtxfrascii";
usage = "Reads a matrix from an ASCII file (TMatrix<r_8>)";
usage += "\n Usage: mtxfrascii mtx_name file_name [CommChar Separator]";
usage += "\n  Related commands: arrtoascii vecfrascii ntfrascii ";
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "vecfrascii";
usage = "Reads a vector from an ASCII file (TVector<r_8>)";
usage += "\n Usage: vecfrascii vec_name file_name";
usage += "\n  Related commands: arrtoascii mtxfrascii ntfrascii [CommChar Separator]";
mpiac->RegisterCommand(kw, usage, this, "FileIO");
kw = "arrtoascii";
usage = "Writes an array (TArray<T>) to an ASCII file ";
usage += "\n Usage: arrtoascii array_name file_name";
usage += "\n  Related commands:  mtxfrascii vecfrascii ntfrascii ";
mpiac->RegisterCommand(kw, usage, this, "FileIO");

kw = "print";
usage = "Prints an object \n Usage: print nameobj [prtlev]";
usage += "\n prtlev = 0,1,2...  default: prtlev=0";
mpiac->RegisterCommand(kw, usage, this, "FileIO");

//------- Commandes gestion de repertoires et d'objets
kw = "mkdir";
usage = "Create a directory";
usage += "\n Usage: mkdir dirname [true]";
usage += "\n if second argument==true, the directory's KeepOld attribute is set to true";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "rmdir";
usage = "Removes an empty directory";
usage += "\n Usage: remove dirname";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "setdiratt";
usage = "Sets directory attributes";
usage += "\n Usage: setdiratt dirname KeepOldFlag(=true/false)";
usage += "\n   KeepOldFlag=true Object with the same name is moved to old";
usage += "\n   when adding objects";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "cd";
usage = "Change current directory";
usage += "\n Usage: cd [dirname]";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "pwd";
usage = "Prints current directory";
usage += "\n Usage: pwd";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "listdirs";
usage = "Prints the list of directories";
usage += "\n Usage: listdirs [patt=*] \n patt : * , ? ";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "listobjs";
usage = "Prints the list of objects (Alias: ls)";
usage += "\n Usage: listobjs [patt=*]  ";
usage += "\n    Or  listobjs patt VarName ";
usage += "\n   Obj. name pattern patt in the form abc?x* or /*/x?y ... ";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "ls";
usage = " Alias for listobjs ";
usage += "\n Usage: ls [patt=*] [VarName]";
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "rename";
usage = "Rename an object (Alias: mv) \n Usage: rename nameobj namenew";
usage += "\n  Related commands: mv del delobjs";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "mv";
usage = "Rename an object (Alias: rename) \n Usage: mv nameobj namenew";
usage += "\n  Related commands: rename del delobjs";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "copy";
usage = "Copy objects (Alias cp) \n";
usage +="  Usage: copy name_from name_to";
usage += "\n  Related commands: cp new...";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "cp";
usage = "Copy objects (Alias copy) \n";
usage +="  Usage: cp name_from name_to";
usage += "\n  Related commands: copy new...";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "del";
usage = "Deletes an object (Alias: rm) \n Usage: del nameobj [nameobj2 ...]";
usage += "\n  Related commands: rm delobjs rename";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "rm";
usage = "Deletes an object (Alias: del) \n Usage: rm nameobj [nameobj2 ...]";
usage += "\n  Related commands: del delobjs rename";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");
kw = "delobjs";
usage = "Delete a set of objects with names matching a pattern (x?y*)";
usage += "\n Usage: delobjs nameobjpattern \n";
usage += "\n  Related commands: del rename";  
mpiac->RegisterCommand(kw, usage, this, "Object Management");

//------- Commandes creation/manipulation d'objets 
kw = "newh1d";
usage = "Creates a 1D histogramm \n Usage: newh1d name xmin xmax nbin";
usage += "\n  Related commands: newh2d  newprof[e] newdt newnt  newgfd ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newh2d";
usage = "Creates a 2D histogramm \n Usage: newh2d name xmin xmax nbinx ymin ymax nbiny";
usage += "\n  Related commands: newh1d  newprof[e] newdt newnt  newgfd ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newprof";
usage = "Creates a profile histogramm \n Usage: newprof name xmin xmax nbin [ymin ymax]";
usage += "\n  Errors represent the data spread in the X bin ";  
usage += "\n  Related commands: newh1d  newh2d newprofe newdt newnt newgfd ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newprofe";
usage = "Creates a profile histogramm \n Usage: newprofe name xmin xmax nbin [ymin ymax]";
usage += "\n  Errors represent the error on the data mean in the X bin ";  
usage += "\n  Related commands: newh1d  newh2d newprof newdt newnt newgfd ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newnt";
usage = "Creates a ntuple \n Usage: newnt name v1 v2 v3 .. vn";
usage += "\n        newnt name nvar";  
usage += "\n  Related commands: newdt newh1d  newh2d newprof[e] newgfd ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newdt";
usage = "Creates a datatable \n Usage: newdt name v1:t1 v2:t2 v3:t3 .. vn:tn";
usage += "\n        newdt name nvar";  
usage += "\n    vi : variable name";  
usage += "\n    ti : variable type";  
usage += "\n         r8,r4 for 8 and 4 bytes float";  
usage += "\n         i8,i4 for 8 and 4 bytes signed integer";  
usage += "\n         s for string";  
usage += "\n  Related commands: newnt newh1d  newh2d newprof[e] newgfd";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newgfd";
usage = "Creates GeneralFit Data object \n Usage: newgfd nvar nalloc [errx(0/1)]";
usage += "\n  Related commands: newh1d  newh2d  newprof[e] newdt newnt ";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newvec";
usage = "Creates (and optionaly fills) a vector \n Usage: newvec name size [f(i) [dopt] ] ";
usage += "\n  Related commands: newmtx line2vec";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "newmtx";
usage = "Creates (and optionaly fills) a matrix \n";
usage +="  Usage: newmtx name sizeX(Col) sizeY(Lines) [f(i,j) [dopt] ] ";
usage += "\n  Related commands: newvec";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "line2vec";
usage = "Creates a vector from the line \n";
usage += "  Usage: line2vec vecname v0 v1 v2 ... \n";
usage += "  Related commands: newvec line2nt";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "line2nt";
usage = "Fills (append) an NTuple from the line content \n";
usage += "  Usage: line2nt ntname col0 col1 ... \n";
usage += "  Related commands: newnt line2vec ntline2var ntcol2var";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "vec2var";
usage = "Vector content to an interpreter variable varname = 'v0 v1 v2 ...' \n";
usage += "  Usage: line2vec vecname varname [LoopParam start:end[:step] ]\n";
usage += "  Related commands: line2vec ntline2var";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "ntline2var";
usage = "Object NTupleInterface line to an interpreter variable \n";
usage += "  Usage: ntline2var objname line_number varname \n";
usage += "  Related commands: vec2var ntcol2var";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "ntcol2var";
usage = "Object NTupleInterface column to an interpreter variable \n";
usage += "  Usage: ntline2var objname column_number varname [LoopParam start:end[:step] ] \n";
usage += "  Related commands: vec2var ntline2var";  
mpiac->RegisterCommand(kw, usage, this, "Objects");
kw = "objaoper";
usage = "Perform an operation through the object adapter NObjMgrAdapter::PerformOperation()\n";
usage += "  Usage: objaoper objname operation [arg1 ...] \n";
usage += "  Examples of defined operations : \n";
usage += "  Matrices: row indx_row , col indx_col \n";  
usage += "  Arrays: slicexy indx_Z , slicexz indx_Y, sliceyz indxX \n";  
mpiac->RegisterCommand(kw, usage, this, "Objects");

//------- Commandes trace de fonctions
kw = "func";
usage = "Displays a function y=f(x) (Fills a vector with function values)";
usage += "\n Usage: func f(x) xmin xmax [npt graphic_attributes]";
usage += "\n  Related commands: funcff func2d func2dff ";  
mpiac->RegisterCommand(kw, usage, this, "Func Plot");
kw = "funcff";
usage = "Displays a function y=f(x) from a C-file (Fills a vector with function values)";
usage += "\n Usage: funcff C-FileName FunctionName xmin xmax [npt graphic_attributes]";
usage += "\n  Related commands: func func2d func2dff ";  
mpiac->RegisterCommand(kw, usage, this, "Func Plot");
kw = "func2d";
usage = "Displays a function z=f(x,y) (Fills a matrix with function values)";
usage += "\n Usage: func2d f(x,y) xmin xmax nptx ymin ymax npty [graphic_attributes]";
usage += "\n  Related commands: func";  
mpiac->RegisterCommand(kw, usage, this, "Func Plot");
kw = "func2dff";
usage = "Displays a function z=f(x,y) from a C-file (Fills a matrix with function values)";
usage += "\n Usage: func2dff C-FileName FunctionName xmin xmax nptx ymin ymax npty [graphic_attributes]";
usage += "\n  Related commands: func funcff func2d ";  
mpiac->RegisterCommand(kw, usage, this, "Func Plot");

//------ Commandes trace d'expression
grp = "Expr. Plotting";
gdesc = "Compute and plot various (c-syntax) expressions of objects \n";
gdesc += "Objects are seen as list of structures (n-tuples)\n";
gdesc += "See ObjectExpressions help item for a list of structure\n";
gdesc += "fields for the different classes managed by piapp";
mpiac->AddHelpGroup(grp, gdesc);

kw = "ObjectExpressions";
usage = "Any mathematical expression (math.h) with object variables can be used";
usage += "\n  ------ Object Variable names (double) -------- ";
usage += "\n  (_nl is the table line number or the sequential index)";
usage += "\n- NTuple: ntuple variable names,_nl";
usage += "\n- Histo1D/HProf: i,x,val,err,nb,_nl";
usage += "\n- Histo2D: i,j,x,y,val,err,_nl";
usage += "\n- HistoErr: i,x,val,err2,nb,_nl";
usage += "\n- Histo2DErr: i,j,x,y,val,err2,nb,_nl";
usage += "\n- Vector/Matrix/Image: n,r,c,val,real,imag,mod,phas,_nl";
usage += "\n- TArray: n,x,y,z,t,u,val,real,imag,mod,phas,_nl";
usage += "\n- GeneralFitData: x0,ex0 x1,ex1 ...  xn,exn   y,ey   ok  ,_nl";
usage += "\n- SphereThetaPhi/SphereHEALPix/SphereECP/LocalMap: ";
usage += "\n-         i,k,val,real,imag,mod,phas,teta,phi,_nl";
usage += "\n- FITS Binary/ASCII table: fits column names,_nl";
usage += "\n  ------ Other parameters -------- ";
usage += "\nLoop parameters can be specified as I1[:I2[:DI]] for(int i=I1; i<I2; i+=DI)"; 
usage += "\nThe default Cut() expression in true (=1) for all"; 
usage += "\n\n Related commands: plot2d plot2de plot2dw plot3d plot3dw"; 
usage += "\n         projh1d projh2d  projprof fillvec fillmtx "; 
usage += "\n         fillnt fillgd1 fillgd2 ntloop exptovec ... ";
mpiac->RegisterHelp(kw, usage, grp);


kw = "plot2d";
usage = "Plots (2D) Y=g(Object) vs. X=f(Object) --- Object Variable names (double) :";
usage += "\n Usage: plot2d nameobj f_X() g_Y() [f_Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2de plot2dw plot3d plot3dw ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "plot2de";
usage = "Plots (2D) Y=g(Object) vs. X=f(Object) with error bars eX/Y=f_ErrX/Y(Object) ";
usage += "\n Usage: plot2de nameobj f_X() g_Y() f_ErrX() f_ErrY() [f_Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2d plot2dw plot3d ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "plot2dw";
usage = "Plots (2D) Y=g(Object) vs. X=f(Object) with Weight W=h(Object) ";
usage += "\n Usage: plot2dw nameobj f_X() g_Y() h_Wt() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2d plot2dc plot3d ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "plot2dc";
usage = "Plots (2D) Y=g(Object) vs. X=f(Object) with Color ColIndex=h(Object) ";
usage += "\n Usage: plot2dc nameobj f_X() g_Y() h_Col() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2d plot2dw plot3d ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "plot3d";
usage = "Plots (3D) Z=h(Object) vs. Y=g(Object) vs. X=f(Object)";
usage += "\n Usage: plot3d nameobj f_X() g_Y() h_Z() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2d plot2de plot3dw ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "plot3dw";
usage = "Plots (3D) Z=h(Object) vs. Y=g(Object) vs. X=f(Object) with Weight W=k(Object)  ";
usage += "\n Usage: plot3d nameobj f_X() g_Y() h_Z() k_Wt() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: plot2d plot2dw plot3d ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "projh1d";
usage = "Projects X=f(Object) with weight WT=h(Object) into a 1D histogram ";
usage += "\n Usage: projh1d nameh1d nameobj f_X() [h_WT()=1. Cut() graphic_attributes loop_param]";
usage += "\n   Histo1D nameh1d is created if necessary ";
usage += "\n  Related commands: projh2d projprof ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "projh2d";
usage = "Projects (X=f(Object),Y=g(Object)) with weight WT=h(Object) into a 2D histogram ";
usage += "\n Usage: projh2d nameh2d nameobj f_X() g_Y() [h_WT()=1. Cut() graphic_attributes loop_param]";
usage += "\n   Histo2D nameh2d is created if necessary ";
usage += "\n  Related commands: projh1d projprof ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "projprof";
usage = "Projects (X=f(Object),Y=g(Object)) with weight WT=h(Object) into a profile histogram ";
usage += "\n Usage: projprof nameprof nameobj f_X() g_Y() [h_WT()=1. Cut() graphic_attributes loop_param]";
usage += "\n   HProf nameprof is created if necessary ";
usage += "\n  Related commands: projh1d projh2d ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "fillvec";
usage = "Fills a Vector V((int)(f_X(Object)+0.5)) =  h_V(Object) ";
usage += "\n Usage: fillvec namevec nameobj f_X() h_V() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: fillmtx fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "fillmtx";
usage = "Fills a Matrix M(Line=g_Y(Object)+0.5, Col=f_X(Object)+0.5)) =  h_V(Object) ";
usage += "\n Usage: fillmtx namevec nameobj f_X() g_Y() h_V() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: fillvec fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "fillnt";
usage = "Creates and Fills an NTuple(x,y,z,t) with (X=f(Object),Y=g(...),Z=h(...),T=k(...))";
usage += "\n Usage: fillnt nameobj f_X() g_Y() h_Z() k_T() [Cut() nameNt loop_param]";
usage += "\n  Related commands: ntloop plot2d projh1d projh2d projprof ";
usage += "\n  Related commands: fillvec fillmtx ntloop exptovec fillgd1 fillgd2 ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "ntloop";
usage = "Loops over an Object NTupleInterface calling a function from a C-file \n";
usage += "and optionaly fills an NTuple(x,y,z,t) with (X=f(Object),Y=g(...),Z=h(...),T=k(...))";
usage += "\n Usage: ntloop nameobj CFileName FuncName [NtupleName loop_param]";
usage += "\n  Related commands: fillvec fillmtx fillnt fillgd1 fillgd2 exptovec ObjectExpressions ..."; 
usage += "\n  Related commands: ntexpcfile fillnt";
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "ntexpcfile";
usage = "Creates a C-File with declarations suitable to be used for ntloop";
usage += "\n Usage: ntexpcfile nameobj CFileName FuncName ";
usage += "\n  Related commands: ntloop";
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "expmeansig";
usage = "Computes Mean/Sigma (+Min/Max) for an expression X=f(Object)";
usage += "\n Usage: expmeansig nameobj f_X() [Cut() loop_param]";
usage += "\n  Related commands: exptovec ntloop fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "exptovec";
usage = "Creates and Fills a Vector with X=f(Object)";
usage += "\n Usage: exptovec namevec nameobj f_X() [Cut() graphic_attributes loop_param]";
usage += "\n  Related commands: ntloop fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");

kw = "fillgd1";
usage = "Creates and Fills a GeneralFitData with (X=f(Object), Y=g(...), ErrY=h(...))";
usage += "\n Usage: fillgd1 namegfd nameobj f_X() g_Y() h_ErrY() [Cut() loop_param]";
usage += "\n  Related commands: ntloop fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "fillgd2";
usage = "Creates and Fills a GeneralFitData with (X=f(Object), Y=g(...), Z=h(...)) ErrZ=k(...)";
usage += "\n Usage: fillgd1 namegfd nameobj f_X() g_Y() h_Z() k_ErrZ() [Cut() loop_param]";
usage += "\n  Related commands: ntloop fillnt ObjectExpressions ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");
kw = "gdfrvec";
usage = "Fills a GeneralFitData with vectors X,Y,Z,EZ";
usage += "\n Usage: gdfrvec namegfd X Y";
usage += "\n Usage: gdfrvec namegfd X Y ! EY";
usage += "\n Usage: gdfrvec namegfd X Y Z";
usage += "\n Usage: gdfrvec namegfd X Y Z EZ";
usage += "\n  Related commands: fillgd1 fillgd2 ..."; 
mpiac->RegisterCommand(kw, usage, this, "Expr. Plotting");


kw = "eval";
usage = "Compute arithmetic expression\n";
usage += "\n Usage: eval resultvarname arithmetic expression....";
usage += "\n  resultvarname: store result in variable resultvarname";
usage += "\n    - If first character is not alphabetic, just print result";
usage += "\n  arithmetic expression:";
usage += "\n      ex: x + sqrt(y)+z +3.14    (x,y,z are variables)";
usage += "\n      ex: $x + sqrt($y)+$z +3.14 (x,y,z are variables)";
usage += "\n      ex: 360 * M_PI / 180.";
mpiac->RegisterCommand(kw, usage, this, "Expr. Arithmetic");

}

/* --Methode-- */
int PIABaseExecutor::LinkUserFuncs(string& fnameso, string& func1, string& func2, string& func3)
//                          string& func4, string& func5)
{
string cmd;

if (dynlink) delete dynlink;    dynlink = NULL;
usfmap.clear();

dynlink = new PDynLinkMgr(fnameso, true);
if (dynlink == NULL) { 
  string sn = fnameso; 
  cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur ouverture SO " << sn << endl; 
  return(2); 
  }

int nok=0;
// on utilise donc des DlFunction  (Reza 20/08/98)  voir commentaire ds .h (pb g++)
// DlUserProcFunction f = NULL;
DlFunction f = NULL;
if ((func1.length() < 1) || (func1 == "-") || (func1 == ".") )  goto fin;
// f = (DlUserProcFunction)  dlsym(dlhandle, func1.c_str());
f = dynlink->GetFunction(func1);
if (f) { nok++;  usfmap[func1] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur linking " << func1 << endl;

if ((func2.length() < 1) || (func2 == "-") || (func2 == ".") )  goto fin;
// f = (DlUserProcFunction)  dlsym(dlhandle, func2.c_str());
f = dynlink->GetFunction(func2);
if (f) { nok++;  usfmap[func2] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur linking " << func2 << endl;

if ((func3.length() < 1) || (func3 == "-") || (func3 == ".") )  goto fin;
// f = (DlUserProcFunction)  dlsym(dlhandle, func3.c_str());
f = dynlink->GetFunction(func3);
if (f) { nok++;  usfmap[func3] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur linking " << func3 << endl;

/*  Pb compile g++ 2.7.2 
if ((func4.length() < 1) || (func4 == "-") || (func4 == ".") )  goto fin;
// f = (DlUserProcFunction)  dlsym(dlhandle, func4.c_str());
f = dynlink->GetFunction(func4);
if (f) { nok++;  usfmap[func4] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur linking " << func4 << endl;

if ((func5.length() < 1) || (func5 == "-") || (func5 == ".") )  goto fin;
// f = (DlUserProcFunction)  dlsym(dlhandle, func5.c_str());
f = dynlink->GetFunction(func5);
if (f) { nok++;  usfmap[func5] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs_Erreur: Erreur linking " << func5 << endl;
*/
fin:
if (nok < 1) { if (dynlink) delete dynlink;    dynlink = NULL;  return(3); }
else return(0);
}

/* --Methode-- */
int PIABaseExecutor::LinkUserFuncs2(string& fnameso, string& func1, string& func2, string& func3)
{
string cmd;

if (dynlink2) delete dynlink2;    dynlink2 = NULL;
usfmap2.clear();

dynlink2 = new PDynLinkMgr(fnameso, true);
if (dynlink2 == NULL) { 
  string sn = fnameso; 
  cerr << "PIABaseExecutor/LinkUserFuncs2_Erreur: Erreur ouverture SO " << sn << endl; 
  return(2); 
  }

int nok=0;
// on utilise donc des DlFunction  (Reza 20/08/98)  voir commentaire ds .h (pb g++)
// DlUserProcFunction f = NULL;
DlFunction f = NULL;
if ((func1.length() < 1) || (func1 == "-") || (func1 == ".") )  goto fin;
f = dynlink2->GetFunction(func1);
if (f) { nok++;  usfmap2[func1] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs2_Erreur: Erreur linking " << func1 << endl;

if ((func2.length() < 1) || (func2 == "-") || (func2 == ".") )  goto fin;
f = dynlink2->GetFunction(func2);
if (f) { nok++;  usfmap2[func2] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs2_Erreur: Erreur linking " << func2 << endl;

if ((func3.length() < 1) || (func3 == "-") || (func3 == ".") )  goto fin;
f = dynlink2->GetFunction(func3);
if (f) { nok++;  usfmap2[func3] = f; }
else cerr << "PIABaseExecutor/LinkUserFuncs2_Erreur: Erreur linking " << func3 << endl;

fin:
if (nok < 1) { if (dynlink2) delete dynlink2;    dynlink2 = NULL;  return(3); }
else return(0);
}

