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

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

#include "sopnamsp.h"
#include "strutil.h"
#include "datatypes.h"

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

#include "dvlist.h"

#include "tvector.h"
#include "pitvmaad.h"
#include "piyfxdrw.h"

#include "pisurfdr.h"
#include "pipodrw.h"

#include "pintuple.h"
#include "pintup3d.h"
#include "pigfd1.h"
#include "pigfd2.h"

#include "zthread.h"


//++
// Class	NamedObjMgr
// Lib		PI
// include	nobjmgr.h
//
//	Cette classe fournit les services nécéssaires à la gestion des objets
//	(l'ensemble des objets PPersist de PEIDA++) au sein du programme
//	d'analyse interactive *piapp* . Elle constitue en outre l'interface
//	entre les fonctions utilisateur et l'application graphique.
//--
//++
// Links	Voir aussi
// PIStdImgApp
// Services2NObjMgr
// PIACmd
//--


// ..................................................................
// ......  Gestion des objets nommes, variables globales ............
struct nobj_diritem {
  int id;                 // Directory Id
  int nobj;               // Number of objects in directory
  bool lock;              // True -> directory locked, No Add, del or rename
  bool keepold;           // True -> When duplicate object name, old object moved to /old
};

typedef map<string, nobj_diritem, less<string> > NObjDirList;

struct nobj_item {
  AnyDataObj* obj;             // Object pointer
  NObjMgrAdapter* obja;        // Object adapter pointer
  int oid;                     // object Id
  int dirid;                   // Directory Id
  list<int> wrsid;             // List of Window Resource Id (Drawer, PIBaseWdg, ...) 
                               // (for PIStdImgApp)
  bool operator==(nobj_item const& b) const
    { return (this->obj ==  b.obj); }
};

typedef map<string, nobj_item, less<string> > NObjList;

static NObjDirList* myDirs = NULL;
static NObjList* myObjs = NULL;
static int fgOInit = 0;
static int myNObj = 0;
static int myDirId = 0;
static string* currDir;

static PIStdImgApp* myImgApp=NULL;
static Services2NObjMgr* servnobjm=NULL;

static DVList* myVars = NULL;  // Pour stocker les variables

static string* TmpDir = NULL;  // Repertoire pour les compilations / link dynamique

// Pour gestion multithread 
static ZMutex* myMutex = NULL;
static bool myMtxLocked = false;   // if myMutex has been locked
static bool obmWvis = false;  // true -> ObjMgrWindow() is active/visible
static bool obmWUpdReq = false; // true -> ObjMgrWindow Update requested
// ..................................................................
// .... Classe NObjMgrSync ....
class NObjMgrSync {
public:
  explicit NObjMgrSync(int sigbr) 
  {
    myMtxLocked = true;
    myMutex->lock();
    _sigbr = sigbr;
  }
  ~NObjMgrSync()
  {
    if (_sigbr == 1) myMutex->signal(); 
    else  if (_sigbr == 2) myMutex->broadcast(); 
    myMutex->unlock();
    myMtxLocked = false;
    if (obmWUpdReq) {
      NamedObjMgr _momg;
      _momg.UpdateObjMgrWindow(-1);
      obmWUpdReq = false;
    }
  }
  inline int NOp() { return _sigbr; } 

  int _sigbr;
};
//.............................

//++
// Titre	Constructeurs
//--
//++
// NamedObjMgr()
//	Constructeur. Les différents instantiation de la classe "NamedObjMgr" 
//	dans une même application créent des objets qui travaillent sur la même
//	liste d'objets. Les objets de cette classe ne possedent en effet pas
//	de variables membres. 
//--

/* --Methode-- */
NamedObjMgr::NamedObjMgr(bool fgimgapp)
{
_fgimgapp = fgimgapp;
if (fgOInit == 0) { 
  myNObj = 0;
  myDirId = 0;
  myDirs = new NObjDirList;
  myObjs = new NObjList;  
  myVars = new DVList;
  myMutex = new ZMutex;
  currDir = new string("home");
  string dirn = "home";
  CreateDir_P(dirn);
  SetKeepOldDirAtt(dirn, false);
  dirn = "tmp";
  CreateDir_P(dirn);
  SetKeepOldDirAtt(dirn, false);
  dirn = "autoc";
  CreateDir_P(dirn);
  SetKeepOldDirAtt(dirn, false);
  dirn = "old";
  CreateDir_P(dirn);
  SetKeepOldDirAtt(dirn, false);
  dirn = "home";
  SetCurrentDir(dirn);
  myDirId = 50;
  char* varenv;
  TmpDir = new string("");
  if ( (varenv=getenv("TMPDIR")) != NULL )  (*TmpDir) = varenv; 
  int l = (*TmpDir).length();
  if ( (l>0) && ((*TmpDir)[l-1] != '/') )  (*TmpDir) += '/';
  servnobjm = new Services2NObjMgr(*TmpDir);
  }
fgOInit++;
}

  
/* --Methode-- */
NamedObjMgr::~NamedObjMgr()
{
fgOInit--;
if (fgOInit == 0)  {
  string patt = "/*/*";
  DelObjects(patt, true);
  delete myObjs;
  delete myDirs;
  delete myVars;
  delete myMutex;
}
}

//++
// Titre	Méthodes
//--
//++
// void SetImgApp(PIStdImgApp* app)
//	Spécifie l'objet "PIStdImgApp" associé.
// PIStdImgApp* GetImgApp()
//	Accès à l'objet "PIStdImgApp" associé.
//--

/* --Methode-- */
void NamedObjMgr::SetImgApp(PIStdImgApp* app)
{
myImgApp = app;
servnobjm->SetImgApp(app);

NObjDirList::iterator it;
string cn;
for(it= myDirs->begin(); it != myDirs->end(); it++) {
  cn = '/' + (*it).first;
  (myImgApp->ObjMgrW())->AddDirectory(cn.c_str(), (*it).second.id);
  }
}


static bool verbeux = false;  // true -> plus de message (creation/suppression d'objets)
void NamedObjMgr::SetVerbose(bool fg)
{
verbeux = fg;
}

/* --Methode-- */
PIStdImgApp* NamedObjMgr::GetImgApp()
{
return(myImgApp);
}

/* --Methode-- */
Services2NObjMgr* NamedObjMgr::GetServiceObj()
{
return(servnobjm);
}

/* --Methode-- */
string const& NamedObjMgr::GetTmpDir()
{
return *TmpDir;
}

/* --Methode-- */
void NamedObjMgr::SetTmpDir(string const& tmpdir)
{
if(tmpdir.length()<1) return;
*TmpDir = tmpdir;
int l = (*TmpDir).length();
if ( (l>0) && ((*TmpDir)[l-1] != '/') )  (*TmpDir) += '/';
servnobjm->SetTmpDir(*TmpDir);
}

/* --Methode-- */
bool NamedObjMgr::SetVar(string const & key, string const & val)
{
  if ((key.length() < 1) || (! isalpha(key[0])) )   {
    cout << "NamedObjMgr::SetVar( " << key << " ...) Bad VarName " << endl;
    return(false);
  }
  NObjMgrSync zs(0); zs.NOp(); 
  bool fg = myVars->HasKey(key);
  myVars->SetS(key, val);
  //  cout << " DEBUG::SetVar " << *myVars << endl;
  return(fg);
}

/* --Methode-- */
bool NamedObjMgr::HasVar(string const & key)
{
  if ((key.length() < 1) || (! isalpha(key[0])) )   {
    cout << "NamedObjMgr::HasVar( " << key << ") Bad VarName " << endl;
    return(false);
  }
  NObjMgrSync zs(0); zs.NOp(); 
  return(myVars->HasKey(key));
}

/* --Methode-- */
bool NamedObjMgr::DeleteVar(string const & key)
{
  if ((key.length() < 1) || (! isalpha(key[0])) )   {
    cout << "NamedObjMgr::DeleteVar( " << key << ") Bad VarName " << endl;
    return(false);
  }
  NObjMgrSync zs(0); zs.NOp(); 
  return(myVars->DeleteKey(key));
}

/* --Methode-- */
string NamedObjMgr::GetVar(string const & key)
{
  if ((key.length() < 1) || (! isalpha(key[0])) )   {
    cout << "NamedObjMgr::GetVar( " << key << ") Bad VarName " << endl;
    return("");
  }
  NObjMgrSync zs(0); zs.NOp(); 
  //  cout << " DEBUG::GetVar " << *myVars << endl;
  return(myVars->GetS(key));
}

/* --Methode-- */
DVList& NamedObjMgr::GetVarList()
{
  //  cout << " DEBUG::GetVarList " << *myVars << endl;
  NObjMgrSync zs(0); zs.NOp(); 
  return(*myVars);
}

/* --Methode-- */
bool NamedObjMgr::CreateDir(string & dirname)
{
  NObjMgrSync zs(0); zs.NOp(); 
  return CreateDir_P(dirname);
}

/* --Methode-- */
bool NamedObjMgr::CreateDir_P(string & dirname)
{
if ( !CheckDirName(dirname) ) {
  cout << "NamedObjMgr::CreateDir( " << dirname << ") Error - Invalid name !" << endl;
  return(false); 
  }
NObjDirList::iterator it = myDirs->find(dirname);
if (it != myDirs->end()) {
  cout << "NamedObjMgr::CreateDir( " << dirname << ") Error - Existing directory !" << endl;
  return(false);
  }
myDirId++;
nobj_diritem di;
di.id = myDirId;
di.nobj = 0;
di.lock = false;
di.keepold = false;
(*myDirs)[dirname] = di;
if (myImgApp)  { 
  string str = '/' + dirname;
  if ( !_fgimgapp )  myImgApp->LockMutex();
  (myImgApp->ObjMgrW())->AddDirectory(str.c_str(), myDirId);
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
}
if (verbeux) cout << "NamedObjMgr::CreateDir() " << dirname << " Created " << endl;
return(true);
}

/* --Methode-- */
bool NamedObjMgr::DeleteDir(string & dirname)
{
if ( !CheckDirName(dirname) ) {
  cout << "NamedObjMgr::DeleteDir( " << dirname << ") Error - Invalid name !" << endl;
  return(false); 
  }
NObjMgrSync zs(0); zs.NOp(); 
NObjDirList::iterator it = myDirs->find(dirname);
if (it == myDirs->end()) {
  cout << "NamedObjMgr::DeleteDir( " << dirname << ") Error - No such directory !" << endl;
  return(false);
  }
if ((*it).second.nobj > 0) {
  cout << "NamedObjMgr::DeleteDir() " << dirname << " not empty ! " << endl;
  return(false);
  }
if ((*it).second.lock ) {
  cout << "NamedObjMgr::DeleteDir() " << dirname << " locked ! " << endl;
  return(false);
  }
if ((*it).second.id < 50) {
  cout << "NamedObjMgr::DeleteDir() " << dirname << " cannot be deleted ! " << endl;
  return(false);
  }

if (myImgApp) {
  if ( !_fgimgapp )  myImgApp->LockMutex();
  if ((myImgApp->ObjMgrW())->GetCurDirId() == (*it).second.id) {
    (myImgApp->ObjMgrW())->SetCurDir(*currDir);
    obmWUpdReq = true;
  }
  (myImgApp->ObjMgrW())->DelDirectory((*it).second.id);
  
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
}
myDirs->erase(it);
if (verbeux) cout << "NamedObjMgr::DeleteDir() " << dirname << " deleted " << endl;  
return(true);
}

/* --Methode-- */
void NamedObjMgr::LockDir(string & dirname)
{
NObjMgrSync zs(0); zs.NOp(); 
if ( !CheckDirName(dirname) ) return;
NObjDirList::iterator it = myDirs->find(dirname);
if (it == myDirs->end()) return;
(*it).second.lock = true;
if (verbeux) cout << "NamedObjMgr::LockDir() " << dirname << " Locked " << endl;
return;
}

/* --Methode-- */
void NamedObjMgr::UnlockDir(string & dirname)
{
NObjMgrSync zs(0); zs.NOp(); 
if ( !CheckDirName(dirname) ) return;
NObjDirList::iterator it = myDirs->find(dirname);
if (it == myDirs->end()) return;
(*it).second.lock = true;
if (verbeux) cout << "NamedObjMgr::UnlockDir() " << dirname << " Unlocked " << endl;
return;
}

/* --Methode-- */
void NamedObjMgr::SetKeepOldDirAtt(string & dirname, bool keepold)
{
NObjMgrSync zs(0); zs.NOp(); 
if ( !CheckDirName(dirname) ) return;
NObjDirList::iterator it = myDirs->find(dirname);
if (it == myDirs->end()) return;
(*it).second.keepold = keepold;
if (!verbeux) return;
cout << "NamedObjMgr::SetKeepOldDirAtt() " << dirname << "  ->  ";
if ( keepold ) cout << " True " << endl;
else cout << " False " << endl;
return;
}


/* --Methode-- */
bool NamedObjMgr::SetCurrentDir(string & dirname)
{
NObjMgrSync zs(0); zs.NOp(); 
if ( !CheckDirName(dirname) ) {
  cout << "NamedObjMgr::SetCurrentDir( " << dirname << ") Error - Invalid name !" << endl;
  return(false); 
  }
NObjDirList::iterator it = myDirs->find(dirname);
if (it == myDirs->end()) {
  cout << "NamedObjMgr::SetCurrentDir( " << dirname << ") Error - No such directory !" << endl;
  return(false);
  }
*currDir = dirname;
if (verbeux) cout << "NamedObjMgr::SetCurrentDir() -> " << dirname << endl;
return(true);
}

/* --Methode-- */
void NamedObjMgr::GetCurrentDir(string & dirname)
{
NObjMgrSync zs(0); zs.NOp(); 
dirname = *currDir;
}

/* --Methode-- */
void NamedObjMgr::ListDirs(string & patt)
{
NObjMgrSync zs(0); zs.NOp(); 
NObjDirList::iterator it;
string cn;
cout << "NamedObjMgr::ListDirs( " << patt << " ) " << endl;
int k = 0;
for(it= myDirs->begin(); it != myDirs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) == 0) continue;
  k++;
  cout << k << "- " << (*it).first;
  if ( (*it).second.lock )  cout << "  Locked " ;
  if ( (*it).second.keepold )   cout << "  KeepOld " ;
  cout << "  (Id= " << (*it).second.id << " NbObj= " << (*it).second.nobj << ")" << endl;
   
  }
}

/* --Methode-- */
void NamedObjMgr::GetDirList(string & patt, vector<string>& lstd)
{
NObjMgrSync zs(0); zs.NOp(); 
NObjDirList::iterator it;
string cn;
for(it= myDirs->begin(); it != myDirs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) == 0) continue;
  lstd.push_back(cn);
  }
}

/* --Methode-- */
void NamedObjMgr::CleanDir(string & dirname)
{
NObjMgrSync zs(0); zs.NOp(); 
CleanDir_P(dirname);
}

/* --Methode-- */
void NamedObjMgr::CleanDir_P(string & dirname)
{
if ( !CheckDirName(dirname) ) {
  cout << "NamedObjMgr::CleanDir( " << dirname << ") Error - Invalid name !" << endl;
 // return(false);  $CHECK$ illegal return value in void function
  }
NObjDirList::iterator itr = myDirs->find(dirname);
if (itr == myDirs->end()) {
  cout << "NamedObjMgr::CleanDir( " << dirname << ") Error - No such directory !" << endl;
 // return(false);  $CHECK$ illegal return value in void function
  }

int did = (*itr).second.id;
NObjList::iterator it;  
list<int>::iterator iwr;
bool nodisp = true;
list<string> odel;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  if ((*it).second.dirid != did) continue;
  nodisp = true;
  if (myImgApp) 
    for(iwr=(*it).second.wrsid.begin(); iwr != (*it).second.wrsid.end(); iwr++) 
      if (myImgApp->CheckWRsId(*iwr)) { nodisp = false; break; }
  if (nodisp) odel.push_back((*it).first);
  }
list<string>::iterator ii;
for(ii=odel.begin(); ii != odel.end(); ii++)  DelObj_P(*ii,true);

if (obmWvis) UpdateObjMgrWindow_P(did);  // On met a jour la fenetre de gestion des objets
}



//++
// Titre	Gestion de la liste des objets
//--
//++
// void AddObj(AnyDataObj* obj, string& nom)
//	Ajoute l'objet "obj" à la liste, identifié par "nom".
//	Si un objet de même nom existe, l'ancien objet est renommé en concaténant 
//	un numéro à son nom.
// void DelObj(string const& nom, bool fgd=true)
//	Supprime l'objet "nom" de la liste. L'objet est détruit si "fgd==true"	("delete obj")
// void DelObjects(string const& patt, bool fgd=true)
//	Supprime l'ensemble des objets dont le nom correspond au patron "patt".
//	Le patron peut contenir les caractères "*" et "?" . Les objets sont détruits si "fgd==true"
// AnyDataObj*  GetObj(string const& nom) 
//	Retourne l'objet identifié par "nom" dans la liste. Retourne "NULL" si "nom" n'est 
//	pas dans la liste.
// void  RenameObj(string const& nom, string& nomnew)
//	Change le nom d'un objet dans la liste.
// void  CopyObj(string const& nom, string& nomcp)
//	Copy l'objet "nom" de la liste dans l'objet "nomcp" de la liste.
//--

/* --Methode-- */
bool NamedObjMgr::AddObj(AnyDataObj* obj, string & nom, bool crd)
{
  NObjMgrSync zs(0); zs.NOp(); 
  return AddObj_P(obj, nom, crd);
}

/* --Methode-- */
bool NamedObjMgr::AddObj_P(AnyDataObj* obj, string & nom, bool crd)
{

if (obj == NULL)  return(false);
// On verifie si l'objet est deja dans la liste 
NObjList::iterator it;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  if ((*it).second.obj == obj) {
    cout << "NamedObjMgr::AddObj() Object already present with name " << (*it).first << endl;
    return(false);
    }
  }
string nobj;
string nrep;
char buff[32];
int did = ParseObjectName(nom, nrep, nobj);
if (did == 0) {
  if (!crd) {
    cout << "NamedObjMgr::AddObj() No " << nrep << " Directory " << endl;
    return(false);
    }
  else { CreateDir_P(nrep);  did =  myDirId; }
  }

// Si c'est le repertoire /autoc, on nettoie
if (nrep == "autoc")  {
  CleanDir_P(nrep);
  }

myNObj++;
if ( !CheckName(nobj) ) {
  sprintf(buff,"O%d", myNObj);
  cout << "NamedObjMgr::AddObj() Name changed: " << nom << " -> " << buff << endl;
  nobj = buff;
}

nom = '/' + nrep + '/' + nobj;  
NObjDirList::iterator itr = myDirs->find(nrep);
if ((*itr).second.lock) {
  cout << "NamedObjMgr::AddObj() " << nrep << " Locked Directory " << endl;
  return(false);
  }
it = myObjs->find(nom);
if (it != myObjs->end()) { // l'objet existe deja
  if (nrep == "autoc") {  // Dans /autoc , on garde les objets affiches, donc del. par Clean
    sprintf(buff, "%d", (*it).second.oid); 
    string nomnew = "/autoc/" + nobj + buff;
    RenameObj_P(nom, nomnew);
    }                              
  else if ( (*itr).second.keepold ) { // On met l'ancien objet dans /old
    string on,od;
//    ParseObjectName((*it).first, od, on); 
    sprintf(buff, "%d", (*it).second.oid);
    string nomnew = "/old/" + nobj + buff;
    RenameObj_P(nom, nomnew);
    }
  else {  // Sinon, on remplace l'objet
    cout << "NamedObjMgr::AddObj() - Replacing " << nom << endl;
    DelObj_P(nom);
    }
  }

nobj_item no;
no.obj = obj;
no.obja = servnobjm->GetAdapter(obj);  // L'adaptateur
no.oid =  myNObj;
no.dirid = did;
(*myObjs)[nom] = no;

(*itr).second.nobj++;

if (obmWvis && (myImgApp != NULL)) {
  if ( !_fgimgapp )  myImgApp->LockMutex();
  if ( (myImgApp->ObjMgrW())->Visible() ) {
    string oln = nobj + "  (T= " + no.obja->GetDataObjType() + ")" ; 
    (myImgApp->ObjMgrW())->AddObjList(did, oln.c_str(), no.oid);
  }
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
}
if (verbeux) cout << "NamedObjMgr::AddObj()  Object " << nom << " ( "  
     << typeid(*obj).name() << " ) added (Total= " << myObjs->size() << ")" << endl;  
return(true);
}

bool NamedObjMgr::AddObj(AnyDataObj& obj, string & nom, bool crd)
{
NObjMgrSync zs(0); zs.NOp(); 
NObjMgrAdapter* adap = GetServiceObj()->GetAdapter(&obj);
if (adap == NULL) {
  cout << "NamedObjMgr::AddObj() No Adapter !   " << nom << endl;
  return(false);
}
AnyDataObj * cloneobj = adap->CloneDataObj(true);
delete adap;
if (cloneobj == NULL) {
  cout << "NamedObjMgr::AddObj() Pb cloning object ! " << nom << endl;
  return(false);
}
return ( AddObj_P(cloneobj , nom, crd) );
}

/* --Methode-- */
bool NamedObjMgr::RenameObj(string & nom, string& nomnew)
{
  NObjMgrSync zs(0); zs.NOp(); 
  return RenameObj_P(nom, nomnew);
}

/* --Methode-- */
bool NamedObjMgr::RenameObj_P(string & nom, string& nomnew)
{
string n1,r1,n2,r2;
int dids = ParseObjectName(nom, r1, n1);
NObjDirList::iterator itr1 = myDirs->find(r1);
int did = ParseObjectName(nomnew, r2, n2);
NObjDirList::iterator itr2 = myDirs->find(r2);

if (did == 0) {
  cout << "NamedObjMgr::RenameObj() Error - No " << r2 << " directory !" << endl;
  return(false);
}
nom = '/' + r1 + '/' + n1;
nomnew = '/' + r2 + '/' + n2;
NObjList::iterator it1 = myObjs->find(nom);
if (it1 == myObjs->end()) {
  cout << "NamedObjMgr::RenameObj() Error -  No " << nom << " object !" << endl;
  return(false);
}

if ( !CheckName(n2) ) {
  cout << "NamedObjMgr::RenameObj() Error -  bad new object name" << n2 << endl;
  return(false);
}
NObjList::iterator it2 = myObjs->find(nomnew);
if (it2 != myObjs->end()) {
  cout << "NamedObjMgr::RenameObj() Error -  Object " << nomnew << " exist !" << endl;
  return(false);
}
    
if ( (*itr1).second.lock || (*itr2).second.lock ) {
  cout << "NamedObjMgr::RenameObj() Error - Source or destination directory locked !" 
       << endl;
  return(false);  
  }


nobj_item no = (*it1).second;
no.dirid = did;
myObjs->erase(it1);
NObjDirList::iterator itr = myDirs->find(r1);
(*itr).second.nobj--;
(*myObjs)[nomnew] = no;
itr = myDirs->find(r2);
(*itr).second.nobj++;

if (obmWvis && (myImgApp != NULL)) {
  if ( !_fgimgapp )  myImgApp->LockMutex();
  if ( (myImgApp->ObjMgrW())->Visible() ) {
    (myImgApp->ObjMgrW())->DelObjList(dids, no.oid);
    string oln = n2 + "  (T= " + no.obja->GetDataObjType() + ")" ; 
    (myImgApp->ObjMgrW())->AddObjList(did, oln.c_str(), no.oid);
  }
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
}
if (verbeux) 
  cout << "NamedObjMgr::RenameObj() - Object " << nom << " renamed to " << nomnew << endl;
return(true);
}

/* --Methode-- */
bool NamedObjMgr::CopyObj(string & nom, string& nomcp)
{
NObjMgrSync zs(0); zs.NOp(); 
if(nomcp.length()<=0)
  {cout<<"NamedObjMgr::CopyObj() Error, copied obj name "<<nomcp<<" not valid"<<endl;
  return(false);}
NObjMgrAdapter* obnom = GetObjAdapter_P(nom);
if(obnom==NULL)
  {cout<<"NamedObjMgr::CopyObj() Error -  No "<<nom<<" object !"<<endl;
  return(false);}
AnyDataObj* obnomcp = obnom->CloneDataObj();
if(obnomcp==NULL) return(false);
if(! AddObj_P(obnomcp,nomcp,false) ) {delete obnomcp; return(false);}
return true;
}

/* --Methode-- */
bool NamedObjMgr::DelObj(string & nom, bool fgd)
{
  NObjMgrSync zs(0); zs.NOp(); 
  return DelObj_P(nom, fgd);
}

/* --Methode-- */
bool NamedObjMgr::DelObj_P(string & nom, bool fgd)
{
string n1,r1;
int did = ParseObjectName(nom, r1, n1);
nom = '/' + r1 + '/' + n1;
NObjList::iterator it = myObjs->find(nom);
if (it == myObjs->end()) return(false); 
NObjDirList::iterator itr = myDirs->find(r1);
if ( (*itr).second.lock  ) {
  cout << "NamedObjMgr::DelObj() Error - Locked directory " << r1 << endl;
  return(false);
  }
list<int>::iterator ii;
if (myImgApp) {
//DBG  cerr << " *DBG* NamedObjMgr::DelObj Sz= " << (*it).second.wrsid.size() << endl; 
// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
  bool fglock = (_fgimgapp) ? false : true;
  if (fglock) myImgApp->LockMutex();
  for(ii=(*it).second.wrsid.begin(); ii != (*it).second.wrsid.end(); ii++) 
      myImgApp->DelWRsId((*ii));
  if (fglock) myImgApp->UnlockMutex(true);
}
delete (*it).second.obja;  // destruction de l'adaptateur 
if (fgd) delete (*it).second.obj;

if (obmWvis && (myImgApp != NULL)) {
  if ( !_fgimgapp )  myImgApp->LockMutex();
  if ( (myImgApp->ObjMgrW())->Visible() ) {
    int olid = (*it).second.oid;
    (myImgApp->ObjMgrW())->DelObjList(did, olid);
  }
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
}
myObjs->erase(it);
(*itr).second.nobj--;


if (!verbeux) return(true);  
if (fgd) cout << "NamedObjMgr::DelObj()  Object " << nom << " deleted (Total= " << myObjs->size() << ")" << endl;
else  cout << "NamedObjMgr::DelObj()  Object " << nom << " removed (Total= " << myObjs->size() << ")" << endl;
return(true);  
}

/* --Methode-- */
bool NamedObjMgr::DelObj_Id(int oid)
{
NObjMgrSync zs(0); zs.NOp(); 
NObjList::iterator it;
string nom;
bool of = false;
for(it = myObjs->begin(); it != myObjs->end(); it++) 
  if ( (*it).second.oid == oid ) { 
    of = true;  nom = (*it).first;
    break;
  }
if (of) return(DelObj_P(nom, true));
else return(false);
}

/* --Methode-- */
void NamedObjMgr::DelObjects(string & patt, bool fgd)
{
NObjMgrSync zs(0); zs.NOp(); 
string n1,r1;
ParseObjectName(patt, r1, n1);
patt = '/' + r1 + '/' + n1;
NObjList::iterator it;  
list<string> odel;
string cn;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) != 0)  odel.push_back(cn);
  }
list<string>::iterator ii;
for(ii=odel.begin(); ii != odel.end(); ii++)  DelObj_P(*ii, fgd);
}

/* --Methode-- */
AnyDataObj* NamedObjMgr::GetObj(string & nom)
{
NObjMgrSync zs(0); zs.NOp(); 
return GetObj_P(nom);
}

/* --Methode-- */
AnyDataObj* NamedObjMgr::GetObj_P(string & nom)
{
string n1,r1;
ParseObjectName(nom, r1, n1);
nom = '/' + r1 + '/' + n1;
NObjList::iterator it = myObjs->find(nom);
if (it == myObjs->end()) return(NULL); 
return((*it).second.obj);
}

/* --Methode-- */
NObjMgrAdapter* NamedObjMgr::GetObjAdapter(string & nom)
{
NObjMgrSync zs(0); zs.NOp(); 
return GetObjAdapter_P(nom);
}

/* --Methode-- */
NObjMgrAdapter* NamedObjMgr::GetObjAdapter_P(string & nom)
{
string n1,r1;
ParseObjectName(nom, r1, n1);
nom = '/' + r1 + '/' + n1;
NObjList::iterator it = myObjs->find(nom);
if (it == myObjs->end()) return(NULL); 
return((*it).second.obja);
}

/* --Methode-- */
void NamedObjMgr::ListObjs(string & patt)
{
NObjMgrSync zs(0); zs.NOp(); 
int k;
AnyDataObj* obj=NULL;
string ctyp;
char strg[256];

string n1,r1;
ParseObjectName(patt, r1, n1);
patt = '/' + r1 + '/' + n1;
 cout << "NamedObjMgr::ListObjs( " << patt << " ) TotNObjs= " << myObjs->size() << "\n" ;
NObjList::iterator it;  k = 0;
string cn;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) == 0)  continue;
  obj = (*it).second.obj;
  ctyp = typeid(*obj).name();
  sprintf(strg, "%2d/ %16s : %s", k, typeid(*obj).name(), ((*it).first).c_str()); 
  ctyp = strg;
  cout << ctyp << "\n" ;
  k++;
}
cout << endl;
return;
}

/* --Methode-- */
void NamedObjMgr::GetObjList(string & patt, vector<string> &lst)
{
NObjMgrSync zs(0); zs.NOp(); 
string n1,r1;
if (patt.length() < 1)  return;
bool fgr = (patt[0] == '/') ? true : false;
ParseObjectName(patt, r1, n1);
patt = '/' + r1 + '/' + n1;
NObjList::iterator it;
string cn;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) == 0)  continue;
  if (fgr) lst.push_back(cn);
  else {
    ParseObjectName(cn, r1, n1);
    lst.push_back(n1);
    }
  }
}

//++
// Titre	Entrées-Sorties (I/O) sur les objets
//--
//++
// void  ReadObj(PInPersist& s, int num=-1)
//	Lit l'objet à partir avec le tag numéro "num" dans le flot "PInPersist s"
//	et l'ajoute à la liste. Si "num" est négatif, tous les objets présents
//	sur le flot "s" sont créés et ajoutés à la liste.
// void  ReadObj(string const & nomppf, string nobj="")
//	Lit le premier objet à partir du fichier PPF "nomppf". L'objet est ajouté
//	à la liste avec le nom "nobj". Si "nobj" est une chaîne vide, un nom est 
//	composé à partir du nom de fichier. 
//--

/* --Methode-- */
void NamedObjMgr::ReadObj(string const & flnm, string & nobj)
{
PPersist* ppobj=NULL;
bool ok = true;
try {
  PInPersist pis(flnm);
  ppobj = pis.ReadObject();
  }
catch (IOExc iox) {
  cerr << "NamedObjMgr::ReadObj()/Error Exception - Msg= " << iox.Msg() << endl;
  ok = false;
  }
if (!ok)  return;
if (nobj.length()<1)  nobj = servnobjm->FileName2Name(flnm);
AddObj(ppobj->DataObj(), nobj, true);
cout << "NamedObjMgr::ReadObj(...) object " << nobj << " read from file " << endl;
return;
}
/* --Methode-- */ 
void NamedObjMgr::ReadObj(vector<string> & flnm_objname)
// flnm_objname[0] = nom du fichier .ppf
// flnm_objname[1...] = nom des tags des objects a lire
{
if(flnm_objname.size()<2) return;
int nread=0;
try {
  PInPersist pis(flnm_objname[0]);
  for(int i=1;i<flnm_objname.size();i++) {
    bool ok = pis.GotoNameTag(flnm_objname[i]);
    if(!ok) {
      cout<<"NamedObjMgr::ReadObj(...) Unknown object: "<<flnm_objname[i]<<endl;
      continue;
    }
    PPersist *ppobj = pis.ReadObject();;
    if(ppobj==NULL) {
      cout<<"NamedObjMgr::ReadObj(...) impossible to read "<<flnm_objname[i]<<endl;
      continue;
    }
    AddObj(ppobj->DataObj(),flnm_objname[i],true);
    nread++;
    cout<<"NamedObjMgr::ReadObj(...) object "<<flnm_objname[i]<<" read from file "<<endl;
  }
} catch (IOExc iox) {
  cerr<<"NamedObjMgr::ReadObj()/Error Exception - Msg= "<<iox.Msg()<<endl;
}
cout<<nread<<" objects have been read"<<endl;
return;
}

/* --Methode-- */
void NamedObjMgr::ReadObj(PInPersist& s, int num)
{
NObjMgrSync zs(0); zs.NOp();
ReadObj_P(s, num); 
}

/* --Methode-- */
void NamedObjMgr::ReadObj_P(PInPersist& s, int num)
{
int_4 i; // $CHECK$ int -> int_4 a cause de TagKey
int n0, n1;
bool ok = true;
PPersist* obj=NULL;
string nom;

int nread = 0;
int nbtags = 0;
nbtags = s.NbNameTags();
if ( (nbtags < 1) || (num >= nbtags) ) {
  if (num >= 0) { 
    cerr << "NamedObjMgr::ReadObj(PInPersist, " << num << "  Error! NbTags =" 
         << nbtags << endl;
    return;
  }

try {
  obj = s.ReadObject();
  }
catch (IOExc iox) {
  cerr << "NamedObjMgr::ReadObj()/Error Exception - Msg= " << iox.Msg() << endl;
  ok = false;
  }

  if (!ok)  return;
  nom = "";
  AddObj_P(obj->DataObj(), nom, false);
  nread++;
}
 
if (num < 0) { n0 = 0; n1 = nbtags; } 
else { n0 = num; n1 = num+1; }
for(i=n0; i<n1; i++) {
  s.GotoNameTagNum(i);
  nom = s.GetTagName(i);
  try {
    obj = s.ReadObject();
  }
  catch (IOExc iox) {
    cerr << "NamedObjMgr::ReadObj()/Error Exception - Msg= " << iox.Msg() << endl;
    ok = false;
    }
  if (ok)  { AddObj_P(obj->DataObj(), nom, true);  nread++; }
}

cout << "NamedObjMgr::ReadObj(...) " << nread << " Objects read " << endl;
return;
}
/* --Methode-- */
void NamedObjMgr::ReadAll(string const & flnm, bool atnametags)
  // Lit tous les objets d'un fichier PPF
  // si atnametags == true -> objets avec nametags seulement
  //    sinon, tous les objets sequentiellement
{
try {
  PInPersist pis(flnm);
  if (atnametags && (pis.NbNameTags() >= 1))  { 
    if (pis.NbNameTags() < pis.NbTopLevelObjects()) { 
      cout << "NamedObjMgr::ReadAll()/Warning File " << flnm << " NbNameTags="
	   << pis.NbNameTags() << " < NbTopLevelObjects= " 
	   << pis.NbTopLevelObjects() << endl;
      cout << " ... Reading " << pis.NbNameTags() << " objects at NameTags " ;
    }
    ReadObj(pis, -1);
    return;
  }

  // On lit tous les objets sequentiellement ...
  string nomr = servnobjm->FileName2Name(flnm);  
  string nom = nomr;
  string nums;
  int kn = 1;
  bool fgrdok = true;
  while (fgrdok) {
    try {
      PPersist* obj = pis.ReadObject();
      if (!obj) continue;
      AddObj(obj->DataObj(), nom, false);
      kn++;  nom = nomr + MuTyV(kn).Convert(nums);
    }
    catch (IOExc& iox) {
      fgrdok = false;  
    }
  }
  cout<<"NamedObjMgr::ReadAll(" << flnm << " ,seq) "<< kn-1 << " objects read from File" << endl;
}
catch (IOExc& iox) {
  cerr << "NamedObjMgr::ReadAll()/Error Exception - Msg= " << iox.Msg() << endl;
}
return;
}


/* --Methode-- */
void NamedObjMgr::SaveObj(string & nom, POutPersist& s, bool keeppath)
{
  NObjMgrSync zs(0); zs.NOp(); 
  SaveObj_P(nom, s, keeppath);
}

static int key_for_write = 5000;
/* --Methode-- */
void NamedObjMgr::SaveObj_P(string & nom, POutPersist& s, bool keeppath)
{
if (nom.length() < 1) return;
string nob,rep;
ParseObjectName(nom, rep, nob);
nom = '/' + rep + '/' + nob;
NObjMgrAdapter* obja=NULL;
string nomf = (keeppath) ? nom : nob;
obja = GetObjAdapter_P(nom);
if (obja == NULL)  return;
printf("NamedObjMgr::SaveObj(%s, )  (Type=%s) \n",  
       nom.c_str(), typeid(*(obja->GetDataObj())).name());
obja->SavePPF(s, nomf);
return; 
}

/* --Methode-- */
void NamedObjMgr::SaveObjects(string & patt, string const& flnm)
{
NObjMgrSync zs(0); zs.NOp(); 
string n1,r1;
if (patt.length() < 1)  return;
bool keeppath = (patt[0] == '/') ? true : false;
ParseObjectName(patt, r1, n1);
patt = '/' + r1 + '/' + n1;

bool ok = true;
POutPersist* pout=NULL;
try {
 pout = new POutPersist(flnm);
}
catch (IOExc iox) {
    cerr << "NamedObjMgr::SaveObjects()/Error Exception - Msg= " << iox.Msg() << endl;
    ok = false;
}
if (!ok)  return;
NObjList::iterator it;
string cn; 
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  cn = (*it).first;
  if (csh_parse(cn.c_str(), patt.c_str()) == 0)  continue;
  SaveObj_P(cn, (*pout), keeppath);
  }
delete pout;
return;
}

/* --Methode-- */
void NamedObjMgr::SaveListObjects(vector<string> &liste)
// Les n-1 premiers elements (liste[0 -> n-2]) contiennent
// les noms des objects a mettre  dans le fichier ppf
// dont le nom est le dernier argument (liste[n-1])
{
 NObjMgrSync zs(0); zs.NOp(); 

 if(liste.size()<2) {
   cerr<<"NamedObjMgr::SaveListObjects()/Error not enough argument"<<endl;
   return;
 }

 // open ppf file
 string ppfname = liste[liste.size()-1];
 POutPersist* pout=NULL;
 try {
   pout = new POutPersist(ppfname);
 } catch(IOExc iox) {
   cerr<<"NamedObjMgr::SaveObjects()/Error Exception - Msg= "<<iox.Msg()<<endl;
   return;
 }
 
 // put objects in ppf file
 for(int i=0;i<liste.size()-1;i++) {
   bool keeppath = (liste[i][0] == '/') ? true : false;
   SaveObj_P(liste[i], (*pout), keeppath);
 }

 // close ppf file
 delete pout;

 return;
}

/* --Methode-- */
void NamedObjMgr::SaveAll(string const& flnm)
{
NObjMgrSync zs(0); zs.NOp(); 
bool ok = true;

POutPersist* pout=NULL;
try {
 pout = new POutPersist(flnm);
}
catch (IOExc iox) {
    cerr << "NamedObjMgr::SaveAll()/Error Exception - Msg= " << iox.Msg() << endl;
    ok = false;
}
if (!ok)  return;
NObjList::iterator it;
string no; 
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  no = (*it).first;
  SaveObj_P(no, (*pout), true);
  }
delete pout;
return;
}



/* --Methode-- */
void NamedObjMgr::PrintObj(string& nom, int lev)
{
NObjMgrSync zs(0); zs.NOp(); 
NObjMgrAdapter* obja=NULL;
obja = GetObjAdapter_P(nom);
if (obja == NULL)  return;
AnyDataObj* ob = obja->GetDataObj();
if (ob == NULL) {
  cerr << "NamedObjMgr::PrintObj() / Error - NULL object ! in " << nom << endl;
  return;
  }
string ctyp = typeid(*ob).name();
cout << "NamedObjMgr::PrintObj(" << nom << ") Type: " << ctyp << endl;
obja->Print(cout, lev);

return;
}

/* --Methode-- */
void NamedObjMgr::DisplayObj(string& nom, string dopt) 
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

NObjMgrAdapter* obja=NULL;
obja = GetObjAdapter_P(nom);
if (obja == NULL) {
  cout << "NamedObjMgr::DisplayObj() Error , No object with name " << nom << endl; 
  return;
}
if (obja->GetDataObj() == NULL) {
  cerr << "NamedObjMgr::DisplayObj() / Error - NULL object ! in " << nom << endl;
  return;
  }
if (!myImgApp)  return;
 
PIDrawer * dr = NULL;
P2DArrayAdapter* arr = NULL;
dr = obja->GetDrawer(dopt);
if (!dr) arr = obja->Get2DArray(dopt);

if (!dr && !arr) { 
  string ctyp = typeid(*(obja->GetDataObj())).name();
  cout << "NamedObjMgr::DisplayObj() Error , No display for " << ctyp << endl; 
  return;
  }

int wrsid = 0;

string n1,r1;
ParseObjectName(nom, r1, n1);

// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
bool fglock = (_fgimgapp) ? false : true;

if (dr) { 
  PIDrawer3D * dr3 = dynamic_cast<PIDrawer3D *>(dr);
  if(dr3)  wrsid = myImgApp->Disp3DDrawer(dr3, n1, dopt, "", 0, fglock);
  else wrsid = myImgApp->DispScDrawer( dr, n1, dopt, "", 0, fglock); 
  }
else if (arr) wrsid = myImgApp->DispImage(arr, n1, dopt, false, 0, fglock);

AddWRsId_P(nom, wrsid);
return;
}

/* --Methode-- */
void NamedObjMgr::DisplayImage(string& nom, string dopt, bool fgimagnav)
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

NObjMgrAdapter* obja=NULL;
obja = GetObjAdapter_P(nom);
if (obja == NULL) {
  cout << "NamedObjMgr::DisplayImage() Error , No such object " << nom << endl; 
  return;
}
if (obja->GetDataObj() == NULL) {
  cerr << "NamedObjMgr::DisplayImage() / Error - NULL object ! in " << nom << endl;
  return;
  }
if (!myImgApp)  return;
 
P2DArrayAdapter* arr = obja->Get2DArray(dopt);

if (!arr) { 
  string ctyp = typeid(*(obja->GetDataObj())).name();
  cout << "NamedObjMgr::DisplayImage() Error , Not supported for " << ctyp << endl; 
  return;
  }

string n1,r1;
ParseObjectName(nom, r1, n1);

// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
bool fglock = (_fgimgapp) ? false : true;

int wrsid = 0;
wrsid = myImgApp->DispImage(arr, n1, dopt, fgimagnav, 0, fglock);

AddWRsId_P(nom, wrsid);
return;
}
/* --Methode-- */
void NamedObjMgr::DisplaySurf3D(string& nom, string dopt)
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

NObjMgrAdapter* obja=NULL;
obja = GetObjAdapter_P(nom);
if (obja == NULL) {
  cout << "NamedObjMgr::DisplaySurf3D() Error , No such object " << nom << endl; 
  return;
}
if (obja->GetDataObj() == NULL) {
  cerr << "NamedObjMgr::DisplaySurf3D() / Error - NULL object ! in " << nom << endl;
  return;
  }
if (!myImgApp)  return;
 
P2DArrayAdapter* arr = obja->Get2DArray(dopt);

if (!arr) { 
  string ctyp = typeid(*(obja->GetDataObj())).name();
  cout << "NamedObjMgr::DisplaySurf3D() Error , Not supported " << ctyp << endl; 
  return;
  }

if ((arr->XSize() > 250) || (arr->YSize() > 250)) {
  cout << "NamedObjMgr::DisplaySurf3D() Error , 2D-Array(" <<  arr->XSize() 
       << "x" << arr->YSize() << ") too big (max=250x250)" << endl; 
  delete arr;
  return;
  }

string n1,r1;
ParseObjectName(nom, r1, n1);

// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
bool fglock = (_fgimgapp) ? false : true;

int wrsid = 0;
PISurfaceDrawer* sdr = new PISurfaceDrawer(arr, true, true, true);
wrsid = myImgApp->Disp3DDrawer(sdr, n1, dopt, "", 0, fglock);
AddWRsId_P(nom, wrsid);
return; 
}

/* --Methode-- */
void NamedObjMgr::DisplayNT(string& nom, string& nmx, string& nmy, string& nmz,
                            string& erx, string& ery, string& erz, string& wt, 
                            string& label, string& colornm, bool coloridx, string dopt, bool fg3d)
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

AnyDataObj* obj=GetObj_P(nom);
if (obj == NULL) {
  cout << "NamedObjMgr::DisplayNT() Error , No such object " << nom << endl; 
  return;
}
if (!myImgApp)  return; 

NTupleInterface * nt = dynamic_cast<NTupleInterface *>(obj);
if (nt == NULL) {
// if (typeid(*obj) != typeid(NTupleInterface)) { 
  string ctyp = typeid(*obj).name();
  cout << "NamedObjMgr::DisplayNT() Error , Object not an NTuple " << ctyp << endl; 
  return;
  }

int wrsid = 0;
dopt = "defline " + dopt;

string n1,r1;
ParseObjectName(nom, r1, n1);

// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
bool fglock = (_fgimgapp) ? false : true;

if ( fg3d && (nmz.length()>0) )  { // Display 3D
  PINTuple3D* pin = new PINTuple3D(nt, false);
  pin->SelectXYZ(nmx.c_str(), nmy.c_str(), nmz.c_str());
  pin->SelectWt(wt.c_str());
  pin->SelectLabel(label.c_str());
  pin->SelectErrBar(erx.c_str(), ery.c_str(), erz.c_str());
  string titre = nmz + "%" + nmy + "%" + nmz;
  wrsid = myImgApp->Disp3DDrawer(pin, n1, dopt, titre, 0, fglock);  
}
else {
  PINTuple* pin = new PINTuple(nt, false);
  pin->SelectXY(nmx.c_str(), nmy.c_str());
  pin->SelectWt(wt.c_str());
  pin->SelectLabel(label.c_str());
  pin->SelectErrBar(erx.c_str(), ery.c_str());
  if (colornm.length() > 0) {   // Juin 2007 : gestion de nom de colonne pour la couleur
    if (coloridx) pin->SelectColorByIndex(colornm.c_str());
    else pin->SelectColorByName(colornm.c_str());
  }
  string titre = nmy + "%" + nmx;
  wrsid = myImgApp->DispScDrawer( (PIDrawer*)pin, n1, dopt, titre, 0, fglock);
  }

AddWRsId_P(nom, wrsid);
return;
}

/* --Methode-- cmv 13/10/98 : Obsolete mais ne pas virer SVP */
void NamedObjMgr::DisplayGFD(string& nom, string& numvarx, string& numvary, string& err, string dopt)
//	Pour le display 2D ou 3D d'un ``GeneralFitData''.
//|  nom = nom de l'objet GeneralFitData a representer.
//|  numvarx = numero (nombre entier) de la 1ere variable d'abscisse.
//|  numvary = numero (nombre entier) de la 2sd variable d'abscisse (3D).
//|            Pour le display 2D, numvary="" string vide.
//|  err = qu'elles erreurs faut il representer ?
//|      - 2D : x y xy   (display y=f(x))
//|      - 3D : x y z xy xz yz xzy   (display z=f(x,y))
//|      Ceci n'est suivi que si on a PI_NotDefLineAtt, sinon toutes
//|      les barres d'erreurs sont representees.
//|  opt = options generales pour le display.
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

AnyDataObj* obj=GetObj_P(nom);
if(obj == NULL)
  {cout << "NamedObjMgr::DisplayGFD() Error , No such object " << nom << endl; 
   return;}
if(!myImgApp) return; 
if(typeid(*obj) != typeid(GeneralFitData))
  {string ctyp = typeid(*obj).name();
   cout<<"NamedObjMgr::DisplayGFD() Error , Object not a GeneralFitData "<<ctyp<<endl; 
   return;}

// Decodage des erreurs a representer
bool errx=false, erry=false, errz=false;
if(err.length()>0) {
  for(int i=0;i<(int_4)err.length();i++)
    if     (err[i]=='x' || err[i]=='X') errx = true;
    else if(err[i]=='y' || err[i]=='Y') erry = true;
    else if(err[i]=='z' || err[i]=='Z') errz = true;
}
// Decodage des numeros de variables en abscisse
 int numvx=-1, numvy=-1;
 if(numvarx.length()>0) numvx = atoi(numvarx.c_str());
 if(numvary.length()>0) numvy = atoi(numvary.c_str());
 
 string n1,r1;
 ParseObjectName(nom, r1, n1);
 // Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
 bool fglock = (_fgimgapp) ? false : true;

 int wrsid = 0;
 if(numvy>=0) {              // display 3D
  PIGenFitDat3D* pigfd = new PIGenFitDat3D(((GeneralFitData*)obj),false);
  pigfd->SelectXY(numvx,numvy);
  pigfd->SelectErrBar(errx,erry,errz);
  wrsid = myImgApp->Disp3DDrawer(pigfd,n1,dopt,"",0,fglock);  
} else {                   // display 2D
  PIGenFitDat* pigfd = new PIGenFitDat(((GeneralFitData*)obj),false);
  pigfd->SelectX(numvx);
  pigfd->SelectErrBar(errx,erry);
  wrsid = myImgApp->DispScDrawer((PIDrawer*)pigfd,n1,dopt,"",0,fglock);
}

AddWRsId_P(nom, wrsid);

return;
}

/* --Methode-- */ 
void NamedObjMgr::DisplayVector(string & nomvx, string& nomvy, string dopt)
//	Pour l'affichage 2-D de points avec coordonnees definies par deux vecteurs
//   nomvx et nomvy
{
// Pas de display si option dopt = nodisp 
if ( (dopt == "nodisp") || (dopt == "nodisplay") ) return;

NObjMgrSync zs(0); zs.NOp(); 

if(!myImgApp) return; 

AnyDataObj* obj;
obj = GetObj_P(nomvx);
if(obj == NULL) {
  cout << "NamedObjMgr::DisplayVector() Error , No such object " << nomvx << endl; 
  return;
}
//Vector * vx = dynamic_cast<Vector *>(obj);
BaseArray* bax = dynamic_cast<BaseArray *>(obj);
if (bax == NULL) {
  cout << "NamedObjMgr::DisplayVector() Error " << nomvx << " not a BaseArray ! " << endl;
  return;  
}

obj = GetObj_P(nomvy);
if(obj == NULL) {
  cout << "NamedObjMgr::DisplayVector() Error , No such object " << nomvy << endl; 
  return;
}
BaseArray* bay = dynamic_cast<BaseArray *>(obj);
if (bay == NULL) {
  cout << "NamedObjMgr::DisplayVector() Error " << nomvy << " not a BaseArray ! " << endl;
  return;  
}

Vector vx = *bax;
Vector vy = *bay;
Vector * cvx, * cvy;

if (vx.Size() != vy.Size()) {
  cout << "NamedObjMgr::DisplayVector() Warning / Vx.Size() != Vy.Size() " << endl;
  if (vx.Size() < vy.Size()) {
    cvx = new Vector(vx);
    cvy = new Vector(vy.SubVector(Range(0, 0, vx.Size()-1)));
  }
  else {
    cvx = new Vector(vx.SubVector(Range(0, 0, vy.Size()-1)));
    cvy = new Vector(vy);
  }
}
else {
  cvx = new Vector(vx);
  cvy = new Vector(vy);
}

POVectorAdapter * avx = new POVectorAdapter(cvx, true);
POVectorAdapter * avy = new POVectorAdapter(cvy, true);
PIYfXDrawer * vxydrw = new PIYfXDrawer(avx, avy, true);

string nx,rx;
ParseObjectName(nomvx, rx, nx);
string ny,ry;
ParseObjectName(nomvy, ry, ny);

// Si appel venant de PIStdImgApp, il ne faut pas locker le Mutex global de la boucle d'evts
bool fglock = (_fgimgapp) ? false : true;

string title = ny + " (Y) vs. " + nx + " (X)";
// display 2D
myImgApp->DispScDrawer(vxydrw, title, dopt, "", 0, fglock);

return;

}

/* --Methode-- 
void NamedObjMgr::DisplayImage(string& nom, string dopt)
{
  cout << "NamedObjMgr::DisplayImage() a faire ! " << endl;
}
*/




/* --Methode-- 
void NamedObjMgr::SetGraphicAttributes(string gratt)
{
bool fg = false;
servnobjm->DecodeDispOption(gratt, fg);
Services2NObjMgr::SetDefaultStatsOption(Services2NObjMgr::GetStatsOption(gratt));
}

void NamedObjMgr::SetGraphicWinZone(int nzx, int nzy, bool fcr)
{
if (!myImgApp)  return; 
if (fcr)  myImgApp->CreateGraphWin(nzx, nzy);
else myImgApp->SetZone(nzx, nzy);
}
*/

/* --Methode-- */
int NamedObjMgr::NameToOId(string & nom)
{
NObjMgrSync zs(0); zs.NOp(); 
return NameToOId_P(nom);
}

/* --Methode-- */
int NamedObjMgr::NameToOId_P(string & nom)
{
string n1,r1;
ParseObjectName(nom, r1, n1);
nom = '/' + r1 + '/' + n1;
NObjList::iterator it = myObjs->find(nom);
if (it == myObjs->end()) return(-1); 
else return((*it).second.oid);
}


/* --Methode-- */
void NamedObjMgr::AddWRsId(string & nom, int wrsid)
{
NObjMgrSync zs(0); zs.NOp(); 
AddWRsId_P(nom, wrsid);
}

/* --Methode-- */
void NamedObjMgr::AddWRsId_P(string & nom, int wrsid)
{
if(wrsid != 0) {
  NObjList::iterator it = myObjs->find(nom);
  if (it == myObjs->end()) return; 
  (*it).second.wrsid.push_back(wrsid);
  }
return;
}

/* --Methode-- */
void NamedObjMgr::UpdateObjMgrWindow(int did)
{
if (!myImgApp)  return;
NObjMgrSync zs(0); zs.NOp();
UpdateObjMgrWindow_P(did);
}

/* --Methode-- */
void NamedObjMgr::SetObjMgrWindowVisibility(bool fgvis)
{
obmWvis = fgvis;
}

/* --Methode-- */
void NamedObjMgr::UpdateObjMgrWindow_P(int did)
{
obmWUpdReq = false;
obmWvis = false;
if (!myImgApp)  return;
if ( !_fgimgapp )  myImgApp->LockMutex();
// On ne fait rien si la fenetre non visible ou autre repertoire courant ds fenetre
if ( !(myImgApp->ObjMgrW())->Visible() || 
     ( (did >= 0) && (myImgApp->ObjMgrW())->GetCurDirId() != did) ) {
  if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
  return;
  }

// on change le repertoire courant de la fenetre si did<0
if (did < 0) {
  string cdir = *currDir;
  cdir = '/' + cdir;
  (myImgApp->ObjMgrW())->SetCurDir(cdir);
  did = (myImgApp->ObjMgrW())->GetCurDirId();
}

(myImgApp->ObjMgrW())->ClearObjList();

NObjList::iterator it;  
string cn;
int loid = 0;
for(it = myObjs->begin(); it != myObjs->end(); it++) {
  if ((*it).second.dirid != did) continue;
  cn = (*it).first.substr(1);
  //  cn = cn.substr(cn.find('/')+1) + "  (T= " + typeid(*((*it).second.obj)).name() + ")" ;
  cn = cn.substr(cn.find('/')+1) + "  (T= " + (*it).second.obja->GetDataObjType() + ")" ;
  loid = (*it).second.oid;
  (myImgApp->ObjMgrW())->AddObj(cn.c_str(), loid);
  }
(myImgApp->ObjMgrW())->SelObjByOid(loid);

(myImgApp->ObjMgrW())->SetSensitive();
if ( !_fgimgapp )  myImgApp->UnlockMutex(true);
obmWvis = true;
return;
}


/* Nouvelle-Fonction */
void NamedObjMgr::RemoveSpacesFromName(string & nom)
{
// on supprime les blancs de debut et de fin 
size_t p = nom.find_first_not_of(" ");
if(p>nom.length()) { nom = ""; return; }
nom = nom.substr(p);
p = nom.find(' ');
if(p>nom.length()) p=nom.length();
nom = nom.substr(0, p);
}

/* Nouvelle-Fonction */
bool NamedObjMgr::CheckDirName(string & nom)
{
RemoveSpacesFromName(nom);
if (nom.length() < 1)  return(false); 
if (nom[0] == '/') nom = nom.substr(1) ;
size_t p = nom.find('/');
if (p < nom.length()) nom = nom.substr(0,p);
if ((nom.length() < 1) || (! isalpha(nom[0]) ) )  return(false); 
return(true);
}

/* Nouvelle-Fonction */
int NamedObjMgr::ParseObjectName(string & nom, string & nomrep, string & nomobj)
{
RemoveSpacesFromName(nom);
// Si le nom ne commence pas par un slash, c'est le repertoire courant 
if (nom[0] != '/') { nomrep = *currDir;  nomobj = nom; }
else {
  string xx = nom.substr(1);
  size_t p = xx.find('/');
  if (p < xx.length())  { 
    nomrep = xx.substr(0,p); 
    nomobj = xx.substr(p+1);
    }
  else {
    nomrep = xx;
    nomobj = "";
    }
  }
int rc = 0;
NObjDirList::iterator it = myDirs->find(nomrep);
if (it != myDirs->end())  rc = (*it).second.id;
return(rc);
}

/* Nouvelle-Fonction */
bool NamedObjMgr::CheckName(string const & nom)
{
if (nom.length() < 1) return false;
if (! isalpha(nom[0]) ) return false;
for(int k=0; k<nom.length(); k++)
  if ((!isalnum(nom[k])) && (nom[k] != '_')) return false;
return true;
}
