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

#include "Common/include/Debug.h"
#include "Common/include/Environment.h"
#include "Common/include/ToString.h"
#include "Common/include/ErrorMorpheo.h"
#include <sys/types.h>
#include <unistd.h>

namespace morpheo {

  static bool log_initialized;
  FILE * log_stream;
  
#undef  FUNCTION
#define FUNCTION "log"
  FILE * log (FILE * stream)
  {
    // if log stream is initialized, take this, else return the default stream.
    return (log_initialized and (log_stream!=NULL))?log_stream:stream;
  };
  
#undef  FUNCTION
#define FUNCTION "log_init"
  void log_init (bool        have_file,
                 std::string directory,
                 std::string file)
  {
    if (not log_initialized)
      {
        log_initialized = true;
        
        if (have_file)
          {
            // if the file is not define, take pid.
            std::string filename = directory+"/Morpheo_"+((file!="")?file:toString<pid_t>(getpid()))+".log";
            
            log_stream = fopen (filename.c_str(), "w");
            
            if (log_stream==NULL)
              {
                fprintf(stderr,_("%s Error create log file \"%s\", take the standard output.\n"),MSG_ERROR,filename.c_str());
                log_stream = stdout;
              }
            else
              {
                fprintf(stdout,_("%s Create log file \"%s\".\n"),MSG_INFORMATION,filename.c_str());
              }
          }
        else
          {
            log_stream = NULL;
          }
      }
  }
  
}; // end namespace morpheo
