/*
 * $Id: Environment.cpp 97 2008-12-19 15:34:00Z rosiere $
 *
 * [ Description ]
 * 
 */

#include "Common/include/Environment.h"
#include "Common/include/ErrorMorpheo.h"
#include "Common/include/Debug.h"
#include "Common/include/Message.h"
#include <sys/stat.h>

namespace morpheo {

static bool environment_initialized;
std::string MORPHEO_HOME;
std::string MORPHEO_TOPLEVEL;

#undef  FUNCTION
#define FUNCTION "environment"
void environment (void)
{
  if (not environment_initialized)
    {
      {
        char * toplevel = getenv("MORPHEO_TOPLEVEL");
        
        if (toplevel == NULL)
          throw ERRORMORPHEO(FUNCTION,_("Error morpheo environment is not positioned.\n"));

        MORPHEO_TOPLEVEL = toplevel;
      }

      {
        char * home = getenv("MORPHEO_HOME");
        
        if (home == NULL)
          throw ERRORMORPHEO(FUNCTION,_("Error morpheo environment is not positioned.\n"));

        MORPHEO_HOME = home;
      }

      environment_initialized = true;
    }
}

static bool directory_initialized;
std::string MORPHEO_STATISTICS;
std::string MORPHEO_VHDL;
std::string MORPHEO_POSITION;
std::string MORPHEO_LOG;

#undef  FUNCTION
#define FUNCTION "exist_directory"
void exist_directory (std::string dir)
{
//   struct stat *buf;
//   int res = stat(dir.c_str(), buf);
//   if ((res != 0) or not S_ISDIR(buf->st_mode))
//     throw ERRORMORPHEO(FUNCTION,toString(_("Error in opening directory \"%s\".\n"),dir.c_str()));


  char * pwd = getenv("PWD");
  if (chdir(dir.c_str())!=0)
    throw ERRORMORPHEO(FUNCTION,toString(_("Error in opening directory \"%s\".\n"),dir.c_str()));
  chdir(pwd);
}

#undef  FUNCTION
#define FUNCTION "directory_init"
void directory_init (std::string morpheo_statistics,
                     std::string morpheo_vhdl      ,
                     std::string morpheo_position  ,
                     std::string morpheo_log       )
{
  if (not directory_initialized)
    {
      exist_directory(morpheo_statistics);
      exist_directory(morpheo_vhdl      );
      exist_directory(morpheo_position  );
      exist_directory(morpheo_log       );

      MORPHEO_STATISTICS = morpheo_statistics;
      MORPHEO_VHDL       = morpheo_vhdl      ;
      MORPHEO_POSITION   = morpheo_position  ;
      MORPHEO_LOG        = morpheo_log       ;

      directory_initialized = true;
    }
//   else
//     {
//       msg_printf(WARNING,_("Multi instance of Morpheo : directory, keep actual directory."));
//     }
}

#undef  FUNCTION
#define FUNCTION "directory"
void directory (void)
{
  // with default value
  directory_init();
};

}; //end namespace morpheo
