/*
 * $Id: Filename.cpp 122 2009-06-03 08:15:51Z rosiere $
 *
 * [ Description ]
 * 
 */

#include "Common/include/Filename.h"
#include "Common/include/ToString.h"
#include <fstream>
#include <sstream>
#include <sys/time.h>
#include <unistd.h>

namespace morpheo {

  std::string filename (std::string directory,
                        std::string filename_prefix,
                        std::string filename_suffix,
                        std::string extension,
                        bool        with_date,
                        bool        with_pid,
                        bool        overwrite
                        )
  {
    std::string _return = directory+"/"+filename_prefix;

    if (with_date)
      {
        time_t current_time;
        time (&current_time);
        
        struct tm * _localtime = localtime (&current_time);
        
        int year = 1900+_localtime->tm_year;
        int mon  =    1+_localtime->tm_mon ;
        int mday =      _localtime->tm_mday;
        int hour =      _localtime->tm_hour;
        int min  =      _localtime->tm_min ;
        int sec  =      _localtime->tm_sec ;
        
        _return+= "_"+                     toString<int>(year) 
                 +((mon <10)?"0":"") + toString<int>(mon ) 
                 +((mday<10)?"0":"") + toString<int>(mday) 
             +"_"+((hour<10)?"0":"") + toString<int>(hour) 
                 +((min <10)?"0":"") + toString<int>(min ) 
                 +((sec <10)?"0":"") + toString<int>(sec );  
      }

    if (with_pid)
      {
        _return+="_"+toString<pid_t>(getpid());
      }
    
    _return+=filename_suffix;

    if (not overwrite)
      {
        int          it = 0;
        std::string _it = "";
        bool find;
        do
          {
            find = false;

            _it = ((it!=0)?("_"+toString<int>(it)):"");
            
            std::ifstream inputStream;
            std::string testname = _return+_it+"."+extension;

            inputStream.open(testname.c_str(),std::ios_base::in);
            
            if (inputStream)
              {
                find = true;
                it ++;
              }            
            inputStream.close();
          }
        while (find);

        _return+= _it;
      }

    _return+="."+extension;

    return _return;
  }
  
}; // end namespace morpheo              
