/*
 * $Id: Message.cpp 120 2009-05-26 19:01:47Z rosiere $
 *
 * [ Description ]
 * 
 */

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

namespace morpheo {

  static bool log_initialized;
  bool   log_with_pid;
  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,
                 bool        with_pid ,
                 std::string directory,
                 std::string file)
  {
    if (not log_initialized)
      {
        log_initialized = true;
        log_with_pid    = with_pid;

        if (have_file)
          {
            // if the file is not define, take pid.
            std::string filename = morpheo::filename(directory,
                                                     "Morpheo",
                                                     "",
                                                     "log",
                                                     (file==""),
                                                     with_pid,
                                                     true);
            
            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
