#ifndef Morpheo_Filename_h
#define Morpheo_Filename_h

/*
 * $Id: Filename.h 100 2009-01-08 13:06:27Z rosiere $
 *
 * [ Description ]
 * 
 */

#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 str = 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 ;
        
        str+= "_"+                     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)
      {
        str+="_"+toString<pid_t>(getpid());
      }
    
    str+=filename_suffix;

    if (not overwrite)
      {
        int  it = 0;
        bool find;
        do
          {
            find = false;
            
            std::ifstream inputStream;
            std::string name = str+((it!=0)?("_"+toString<int>(it)):"");

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

        str+= str+((it!=0)?("_"+toString<int>(it)):"");
      }

    str+="."+extension;

    return str;
  }
  
}; // end namespace morpheo              

#endif
