Index: /trunk/FACT++/src/datalogger.cc
===================================================================
--- /trunk/FACT++/src/datalogger.cc	(revision 12166)
+++ /trunk/FACT++/src/datalogger.cc	(revision 12167)
@@ -10,29 +10,49 @@
   The possible states and transitions of the machine are:
   \dot
-  digraph datalogger {
-          node [shape=record, fontname=Helvetica, fontsize=10];
-      e [label="Error" color="red"];
-   r [label="Ready"]
-   d [label="NightlyOpen"]
-   w [label="WaitingRun"]
-      l [label="Logging"]
-   b [label="BadNightlyconfig" color="red"]
-   c [label="BadRunConfig" color="red"]
+  // FIXME FIXME: Error states missing...
+  digraph datalogger
+  { 
+     node [shape=record, fontname=Helvetica, fontsize=10];
   
-  e -> r
-  r -> e
-  r -> d
-  r -> b
-  d -> w
-  d -> r
-  w -> r
-  l -> r
-  l -> w
-  b -> d
-  w -> c
-  w -> l
-  b -> r
-  c -> r
-  c -> l
+     srt  [label="Start" style="rounded"]
+     rdy  [label="Ready"]
+     nop  [label="NightlyOpen"]
+     wait [label="WaitingRun"]
+     log  [label="Logging"]
+
+     //e    [label="Error" color="red"];
+     //c    [label="BadFolder" color="red"]
+     
+     
+     cmd_start  [label="START"              shape="none" height="0"]
+     cmd_stop   [label="STOP"               shape="none" height="0"]
+     cmd_stopr  [label="STOP_RUN_LOGGING"   shape="none" height="0"]
+     cmd_startr [label="START_RUN_LOGGING"  shape="none" height="0"]
+     
+     { rank=same; cmd_startr cmd_stopr }
+     { rank=same; cmd_start  cmd_stop  }
+     
+  
+     srt  -> rdy  
+       
+     rdy -> cmd_start   [ arrowhead="open" dir="both" arrowtail="tee" weight=10 ]
+     cmd_start -> nop   
+
+     nop  -> cmd_stop   [ arrowhead="none" dir="both" arrowtail="inv"  ]
+     wait -> cmd_stop   [ arrowhead="none" dir="both" arrowtail="inv"  ]
+     log  -> cmd_stop   [ arrowhead="none" dir="both" arrowtail="inv"  ]
+     cmd_stop -> rdy    
+
+     wait -> cmd_stopr  [ arrowhead="none" dir="both" arrowtail="inv"  ]
+     log  -> cmd_stopr  [ arrowhead="none" dir="both" arrowtail="inv"  ]
+     cmd_stopr -> nop   
+
+     nop -> cmd_startr  [ arrowhead="none" dir="both" arrowtail="inv" weight=10 ]
+     rdy -> cmd_startr  [ arrowhead="none" dir="both" arrowtail="inv" ]
+     cmd_startr -> wait [ weight=10 ]
+
+
+     wait -> log
+     log  -> wait
   }
   \enddot
@@ -181,11 +201,10 @@
     enum
     {
-        kSM_NightlyOpen = 20, ///< Nightly file openned and writing
-        kSM_WaitingRun = 30, ///< waiting for the run number to open the run file
-        kSM_Logging = 40, ///< both files openned and writing
-        kSM_BadNightlyConfig = 0x101, ///< the folder specified for Nightly logging does not exist or has bad permissions
-        kSM_BadRunConfig = 0x102, ///<  the folder specified for the run logging does not exist or has wrong permissions or no run number
-        kSM_RunWriteError = 0x103, ///< Denotes that an error occured while writing a run file (text or fits).
-        kSM_DailyWriteError = 0x103,///< Denots that an error occured while writing a daily file (text or fits).
+        kSM_NightlyOpen     = 20,    ///< Nightly file openned and writing
+        kSM_WaitingRun      = 30,    ///< waiting for the run number to open the run file
+        kSM_Logging         = 40,    ///< both files openned and writing
+        kSM_BadFolder       = 0x101, ///< the folder specified for Nightly logging does not exist or has bad permissions
+        kSM_RunWriteError   = 0x103, ///< Denotes that an error occured while writing a run file (text or fits).
+        kSM_DailyWriteError = 0x103, ///< Denots that an error occured while writing a daily file (text or fits).
     } localstates_t;
     
@@ -203,8 +222,6 @@
     /// ofstream for the Nightly report file
     ofstream fNightlyReportFile;
-    /// base path of the Nightlyfile
-    string fNightlyFilePath;
-    ///base path of the run file
-    string fRunFilePath;
+    /// base path of files
+    string fFilePath;
     ///run numbers
     list<RunNumberType> fRunNumber;
@@ -246,11 +263,6 @@
     void ReportPlease(DimInfo* I, SubscriptionType& sub);  
 
-    int ConfigureFileName(string &target, const string &type, const EventImp &evt);
     ///Configuration of the nightly file path
-    int ConfigureNightlyFileName(const Event& evt); 
-    ///Configuration fo the file name
-    int ConfigureRunFileName(const Event& evt); 
-    ///DEPREC - configuration of the run number
-    int ConfigureRunNumber(const Event& evt); 
+    int ConfigureFilePath(const Event& evt);
     ///print the current state of the dataLogger
     int PrintStatePlease(const Event& evt);
@@ -260,7 +272,7 @@
     int StartPlease(); 
     ///from waiting to logging transition
-    int StartRunPlease(); 
-    /// from logging to waiting transition
-    int StopRunPlease(); 
+    //int StartRunPlease();
+    // from logging to waiting transition
+    int StopRunLogging();
     ///stop and reset transition
     int GoToReadyPlease(); 
@@ -336,11 +348,7 @@
     void AppendYearMonthDaytoPath(string& path);
     ///Form the files path
-    string CompileFileNameWithPath(const string &path, const string &service, const string & extension, const Time &time=Time());
+    string CompileFileNameWithPath(const string &path, const string &service, const string & extension, uint32_t run=0/*, const Time &time=Time()*/);
     ///Form the file names only
-    string CompileFileName(const string& service, const string& extension, const Time& time=Time());
-    ///Form the files path
-    string CompileFileNameWithPath(const string &path, const int32_t run, const string &service, const string & extension, const Time &time=Time());
-    ///Form the file names only
-    string CompileFileName(const int32_t run, const string& service, const string& extension);//, const Time& time=Time());
+    string CompileFileName(const string& service, const string& extension, uint32_t run=0, const Time& time=Time()) const;
     ///Check whether service is in black and/or white list
     bool ShouldSubscribe(const string& server, const string& service);
@@ -633,18 +641,17 @@
 //
 //string DataLogger::CompileFileName(const string &path, const string &service, const string & extension, const Time &time)
-string DataLogger::CompileFileName(const string& service, const string& extension, const Time& time)
+string DataLogger::CompileFileName(const string& service, const string& extension, uint32_t run, const Time& time) const
 {
     ostringstream str;
-    //calculate time suitable for naming path.
-    const Time ftime(time-boost::posix_time::time_duration(12,0,0));
-
-    //output base of file name
-    str << Time::fmt("%Y_%m_%d") << ftime;
-
-    //output service name
+
+    const Time ftime(time-boost::posix_time::hours(12));
+    str << ftime.NightAsInt();
+
+    if (run>0)
+        str << '_' << setfill('0') << setw(3) << run;
+
     if (!service.empty())
-        str  << "_" << service;
-
-    //output appropriate extension
+        str << '.' << service;
+
     if (!extension.empty())
         str << "." << extension;
@@ -653,12 +660,15 @@
 }
 
-string DataLogger::CompileFileNameWithPath(const string& path, const string& service, const string& extension, const Time& time)
+string DataLogger::CompileFileNameWithPath(const string& path, const string& service, const string& extension, uint32_t run/*, const Time& time*/)
 {
     ostringstream str;
+
+    const Time time;
+
     //calculate time suitable for naming files.
-    const Time ftime(time-boost::posix_time::time_duration(12,0,0));
+    const Time ftime = time-boost::posix_time::hours(12);
 
     //output it
-    str << path << Time::fmt("/%Y/%m/%d") << ftime;
+    str << path << ftime.GetAsStr("/%Y/%m/%d");
 
     //check if target directory exist
@@ -666,5 +676,5 @@
         CreateDirectory(str.str());
 
-    str << '/' << CompileFileName(service, extension, time);
+    str << '/' << CompileFileName(service, extension, run, time);
 
     return str.str();
@@ -672,50 +682,5 @@
 
 }
-// --------------------------------------------------------------------------
-//
-//! Compiles a file name
-//! @param run the run number
-//! @param service the service name, if any
-//! @param extension the extension to add, if any
-//
-string DataLogger::CompileFileName(const int32_t run, const string& service, const string& extension)
-{
-       ostringstream str;
-       //output base of file name
-       str << setfill('0') << setw(8) << run;
-
-       //output service name
-       if (!service.empty())
-           str  << "_" << service;
-
-       //output appropriate extension
-       if (!extension.empty())
-           str << "." << extension;
-       return str.str();
-}
-// --------------------------------------------------------------------------
-//
-//! Compiles a file name withh path
-//! @param path the base path where to put the file
-//! @param time the time at which the file is created
-//! @param run the run number
-//! @param service the service name, if any
-//! @param extension the extension to add, if any
-//
-string DataLogger::CompileFileNameWithPath(const string& path, const int32_t run, const string& service, const string& extension, const Time& time)
-{
-    ostringstream str;
-    //calculate suitable time for naming files and output it
-    str << path << Time::fmt("/%Y/%m/%d") << (time-boost::posix_time::time_duration(12,0,0));
-
-    //check if target directory exist
-    if (!DoesPathExist(str.str()))
-        CreateDirectory(str.str());
-
-    str << '/' << CompileFileName(run, service, extension);//, time);
-
-    return str.str();
-
-}
+
 // --------------------------------------------------------------------------
 //
@@ -772,6 +737,5 @@
     shouldBackLog = true;
     //initialize member data
-    fNightlyFilePath = ".";
-    fRunFilePath = ".";
+    fFilePath = ".";
 
     //Give a name to this machine's specific states
@@ -779,11 +743,10 @@
     AddStateName(kSM_WaitingRun,       "WaitForRun",       "The summary files for the night are open and we wait for a run to be started.");
     AddStateName(kSM_Logging,          "Logging",          "The summary files for the night and the files for a single run are open.");
-    AddStateName(kSM_BadNightlyConfig, "ErrNightlyFolder", "The folder for the nighly summary files is invalid.");
-    AddStateName(kSM_BadRunConfig,     "ErrRunFolder",     "The folder for the run files is invalid.");
+    AddStateName(kSM_BadFolder,        "ErrInvalidFolder", "The folder for the files is not invalid.");
     AddStateName(kSM_DailyWriteError,  "ErrDailyWrite",    "An error occured while writing to a daily (and run) file.");
     AddStateName(kSM_RunWriteError,    "ErrRunWrite",      "An error occured while writing to a run file.");
 
     // Add the possible transitions for this machine
-    AddEvent(kSM_NightlyOpen, "START", kSM_Ready, kSM_BadNightlyConfig)
+    AddEvent(kSM_NightlyOpen, "START", kSM_Ready, kSM_BadFolder)
         (bind(&DataLogger::StartPlease, this))
         ("Start the nightly logging. Nightly file location must be specified already");
@@ -792,5 +755,5 @@
         (bind(&DataLogger::GoToReadyPlease, this))
         ("Stop all data logging, close all files.");
-
+/*
     AddEvent(kSM_Logging, "START_RUN", kSM_WaitingRun, kSM_BadRunConfig)
         (bind(&DataLogger::StartRunPlease, this))
@@ -798,21 +761,22 @@
 
     AddEvent(kSM_WaitingRun, "STOP_RUN", kSM_Logging)
-        (bind(&DataLogger::StopRunPlease, this))
+        (bind(&DataLogger::StopRunLogging, this))
         ("Wait for a run to be started, open run-files as soon as a run number arrives.");
-
-    AddEvent(kSM_Ready, "RESET", kSM_Error, kSM_BadNightlyConfig, kSM_BadRunConfig, kSM_DailyWriteError, kSM_RunWriteError)
+*/
+    AddEvent(kSM_Ready, "RESET", kSM_Error, kSM_BadFolder, kSM_DailyWriteError, kSM_RunWriteError)
         (bind(&DataLogger::GoToReadyPlease, this))
         ("Transition to exit error states. Closes the any open file.");
 
-    AddEvent(kSM_WaitingRun, "WAIT_FOR_RUN_NUMBER", kSM_Logging, kSM_NightlyOpen, kSM_Ready)
+    AddEvent(kSM_WaitingRun, "START_RUN_LOGGING", /*kSM_Logging,*/ kSM_NightlyOpen, kSM_Ready)
         (bind(&DataLogger::NightlyToWaitRunPlease, this))
         ("Go to waiting for run number state. In this state with any received run-number a new file is opened.");
 
-    AddEvent(kSM_NightlyOpen, "BACK_TO_NIGHTLY_OPEN", kSM_WaitingRun)
-    (bind(&DataLogger::BackToNightlyOpenPlease, this))
-    ("Go from the wait for run to nightly open state.");
-
+    AddEvent(kSM_NightlyOpen, "STOP_RUN_LOGGING", kSM_WaitingRun, kSM_Logging)
+        (bind(&DataLogger::BackToNightlyOpenPlease, this))
+        ("Go from the wait for run to nightly open state.");
+
+    /*
     // Add the possible configurations for this machine
-    AddEvent("SET_NIGHTLY_FOLDER", "C", kSM_Ready, kSM_BadNightlyConfig)
+    AddEvent("SET_FOLDER", "C", kSM_Ready, kSM_BadNightlyConfig)
         (bind(&DataLogger::ConfigureNightlyFileName, this, placeholders::_1))
         ("Configure the base folder for the nightly files."
@@ -823,11 +787,7 @@
         ("Configure the base folder for the run files."
          "|Path[string]:Absolute or relative path name where the run files should be stored.");
-
-    AddEvent("SET_RUN_NUMBER", "X", kSM_Ready, kSM_NightlyOpen, kSM_WaitingRun, kSM_BadRunConfig, kSM_Logging)
-        (bind(&DataLogger::ConfigureRunNumber, this, placeholders::_1))
-        ("Configure the run number. Cannot be done in logging state");
-
+     */
      // Provide a print command
-     AddEvent("PRINT")
+     AddEvent("PRINT_INFO")
             (bind(&DataLogger::PrintStatePlease, this, placeholders::_1))
             ("Print information about the internal status of the data logger.");
@@ -1053,5 +1013,5 @@
 #ifdef RUN_LOGS
     // open log file
-    run.logName = CompileFileName(fRunFilePath, run.runNumber, "", "log");
+    run.logName = CompileFileName(fFilePath, "", "log", run.runNumber);
     if (!OpenStream(run.logFile, run.logName))
         return -1;
@@ -1059,5 +1019,5 @@
 
     // open report file
-    run.reportName = CompileFileNameWithPath(fRunFilePath, run.runNumber, "", "rep");
+    run.reportName = CompileFileNameWithPath(fFilePath, "", "rep", run.runNumber);
     if (!OpenStream(run.reportFile, run.reportName))
         return -1;
@@ -1069,5 +1029,5 @@
     fFilesStats.FileOpened(run.reportName);
     //TODO this notification scheme might be messed up now.... fix it !
-    const string baseFileName = CompileFileNameWithPath(fRunFilePath, run.runNumber, "", "");
+    const string baseFileName = CompileFileNameWithPath(fFilePath, "", "", run.runNumber);
     NotifyOpenedFile(baseFileName, 3, fOpenedRunFiles);
     run.openedFits.clear();
@@ -1093,5 +1053,5 @@
         {
             Error("Newly provided run number has already been used (or is still in use). Going to error state");
-            SetCurrentState(kSM_BadRunConfig);
+            SetCurrentState(kSM_BadFolder);
             return;
         }
@@ -1133,6 +1093,6 @@
 #endif
         }
-        StopRunPlease();
-        SetCurrentState(kSM_BadRunConfig);
+        StopRunLogging();
+        SetCurrentState(kSM_BadFolder);
     }
 
@@ -1181,11 +1141,21 @@
     }
 
-    //Check whether we should close and reopen daily text files or not
-    //This should work in any case base of the following:
-    // - fDailyFileDayChangedAlready is initialized to true. So if the dataLogger is started around noon, no file will be closed
-    // - fDailyFileDayChangedAlready is set to false if (time != 12), so the file will be closed and reopened only if the logger runs since before noon (which is the required behavior)
-    //This only applies to text files. Fits are closed and reopened based on the last and current service received time.
-    //this was not applicable to text files, because as they gather several services, we have no guarantee that the received time will be greater than the previous one,
-    //which could lead to several close/reopen instead of only one.
+    //
+    // Check whether we should close and reopen daily text files or not
+    //
+    // This should work in any case base of the following:
+    //  - fDailyFileDayChangedAlready is initialized to true. So if the
+    //    dataLogger is started around noon, no file will be closed
+    //  - fDailyFileDayChangedAlready is set to false if (time != 12), so
+    //    the file will be closed and reopened only if the logger runs since
+    //    before noon (which is the required behavior)
+    //
+    // This only applies to text files. Fits are closed and reopened based on
+    // the last and current service received time.
+    // This was not applicable to text files, because as they gather several
+    // services, we have no guarantee that the received time will be greater
+    // than the previous one, which could lead to several close/reopen instead
+    // of only one.
+    //
     if (Time().h() == 12 && !fDailyFileDayChangedAlready)
     {
@@ -1200,18 +1170,18 @@
         Info("Closed: "+fFullNightlyReportFileName);
 
-        fFullNightlyLogFileName = CompileFileNameWithPath(fNightlyFilePath, "", "log");
+        fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
         if (!OpenTextFilePlease(fNightlyLogFile, fFullNightlyLogFileName))
         {
             GoToReadyPlease();
-            SetCurrentState(kSM_BadNightlyConfig);
+            SetCurrentState(kSM_BadFolder);
             return;
         }
         fNightlyLogFile << endl;
 
-        fFullNightlyReportFileName = CompileFileNameWithPath(fNightlyFilePath, "", "rep");
+        fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
         if (!OpenTextFilePlease(fNightlyReportFile, fFullNightlyReportFileName))
         {
             GoToReadyPlease();
-            SetCurrentState(kSM_BadNightlyConfig);
+            SetCurrentState(kSM_BadFolder);
             return;
         }
@@ -1407,6 +1377,5 @@
 
     //print the path configuration
-    Message("Nightly path: " + boost::filesystem::system_complete(boost::filesystem::path(fNightlyFilePath)).directory_string());
-    Message("Run path:     " + boost::filesystem::system_complete(boost::filesystem::path(fRunFilePath)).directory_string());
+    Message("File path:    " + boost::filesystem::system_complete(boost::filesystem::path(fFilePath)).directory_string());
 
     //print active run numbers
@@ -1619,40 +1588,4 @@
 // --------------------------------------------------------------------------
 //
-//!    Configure a given file name
-//! @param target
-//!        where to put the result
-//! @param type
-//!         what to append to the created path. currently only run or nightly
-//! @param evt
-//!         the event transporting the path
-//! @returns
-//!        currently only the current state.
-//
-int DataLogger::ConfigureFileName(string &target, const string &type, const EventImp &evt)
-{
-    if (!evt.GetText())
-    {
-        Error("Empty "+type+" folder given. Please specify a valid path.");
-        return GetCurrentState();
-    }
-
-    const string givenPath = evt.GetText();
-    if (!DoesPathExist(givenPath))
-    {
-        Error("Provided "+type+" path '"+givenPath+"' is not a valid folder. Ignored");
-        return GetCurrentState();
-    }
-
-    Message("New "+type+" folder: "+givenPath);
-
-    target = givenPath;
-
-    fFilesStats.SetCurrentFolder(givenPath);
-
-    return GetCurrentState();
-}
-
-// --------------------------------------------------------------------------
-//
 //!    Sets the path to use for the Nightly log file.
 //! @param evt
@@ -1660,34 +1593,30 @@
 //! @returns
 //!        currently only the current state.
-//
-int DataLogger::ConfigureNightlyFileName(const Event& evt)
-{
-    return ConfigureFileName(fNightlyFilePath, "nightly", evt);
-}
-
-// --------------------------------------------------------------------------
-//
-//! Sets the path to use for the run log file.
-//! @param evt
-//!        the event transporting the path
-//! @returns
-//!     currently only the current state
-int DataLogger::ConfigureRunFileName(const Event& evt)
-{
-    return ConfigureFileName(fRunFilePath, "run", evt);
-}
-
-// --------------------------------------------------------------------------
-//
-//! Sets the run number.
-//! @param evt
-//!        the event transporting the run number
-//! @returns
-//!     currently only the current state
-int DataLogger::ConfigureRunNumber(const Event& evt)
-{
-    AddNewRunNumber(evt.GetXtra(), evt.GetTime());
+/*
+int DataLogger::ConfigureFilePath(const Event& evt)
+{
+    if (!evt.GetText())
+    {
+        Error("Empty folder given. Please specify a valid path.");
+        return GetCurrentState();
+    }
+
+    const string givenPath = evt.GetText();
+    if (!DoesPathExist(givenPath))
+    {
+        Error("Provided path '"+givenPath+"' is not a valid folder... ignored.");
+        return GetCurrentState();
+    }
+
+    Message("New folder: "+givenPath);
+
+    fFilePath = givenPath;
+
+    fFilesStats.SetCurrentFolder(givenPath);
+
     return GetCurrentState();
 }
+*/
+
 // --------------------------------------------------------------------------
 //
@@ -1733,5 +1662,5 @@
 //! and tries to open it.
 //! @returns 
-//!        kSM_NightlyOpen if success, kSM_BadNightlyConfig if failure
+//!        kSM_NightlyOpen if success, kSM_BadFolder if failure
 int DataLogger::StartPlease()
 {
@@ -1740,17 +1669,17 @@
         Debug("Starting...");    
     }
-    fFullNightlyLogFileName = CompileFileNameWithPath(fNightlyFilePath, "", "log");
+    fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
     bool nightlyLogOpen = fNightlyLogFile.is_open();
     if (!OpenTextFilePlease(fNightlyLogFile, fFullNightlyLogFileName))
-        return kSM_BadNightlyConfig;
+        return kSM_BadFolder;
     if (!nightlyLogOpen)
         fNightlyLogFile << endl;
 
-    fFullNightlyReportFileName = CompileFileNameWithPath(fNightlyFilePath, "", "rep");
+    fFullNightlyReportFileName = CompileFileNameWithPath(fFilePath, "", "rep");
     if (!OpenTextFilePlease(fNightlyReportFile, fFullNightlyReportFileName))
     {
         fNightlyLogFile.close();
         Info("Closed: "+fFullNightlyReportFileName);
-        return kSM_BadNightlyConfig;
+        return kSM_BadFolder;
     }
 
@@ -1758,5 +1687,5 @@
     fFilesStats.FileOpened(fFullNightlyReportFileName);
     //notify that a new file has been opened.
-    const string baseFileName = CompileFileNameWithPath(fNightlyFilePath, "", "");
+    const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
     NotifyOpenedFile(baseFileName, 3, fOpenedNightlyFiles);
 
@@ -1807,5 +1736,5 @@
     if (!sub.nightlyFile.IsOpen())
     {
-        const string partialName = CompileFileNameWithPath(fNightlyFilePath, serviceName, "fits");
+        const string partialName = CompileFileNameWithPath(fFilePath, serviceName, "fits");
 
         const string fileNameOnly = partialName.substr(partialName.find_last_of('/')+1, partialName.size());
@@ -1827,5 +1756,5 @@
 
         //notify the opening
-        const string baseFileName = CompileFileNameWithPath(fNightlyFilePath, "", "");
+        const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
         NotifyOpenedFile(baseFileName, 7, fOpenedNightlyFiles);
         if (fNumSubAndFitsIsOn)
@@ -1835,16 +1764,10 @@
     if (!sub.runFile.IsOpen() && (GetCurrentState() == kSM_WaitingRun || GetCurrentState() == kSM_Logging) && sub.runNumber > 0)
     {//buffer for the run file have already been allocated when doing the Nightly file
-        string fileNameOnly;
-        string partialName;
-        if (hasGrouping)
-        {
-            partialName = CompileFileNameWithPath(fRunFilePath, sub.runNumber, "", "fits");
-        }
-        else
-        {
-            partialName = CompileFileNameWithPath(fRunFilePath, sub.runNumber, serviceName, "fits");
-        }
-
-        fileNameOnly = partialName.substr(partialName.find_last_of('/')+1, partialName.size());
+
+        const string partialName =
+            CompileFileNameWithPath(fFilePath, hasGrouping ? "" : serviceName, "fits", sub.runNumber);
+
+        const string fileNameOnly =
+            partialName.substr(partialName.find_last_of('/')+1, partialName.size());
 
         //get the size of the file we're about to open
@@ -1873,5 +1796,5 @@
             }
 
-        const string baseFileName = CompileFileNameWithPath(fRunFilePath, sub.runNumber, "", "");
+        const string baseFileName = CompileFileNameWithPath(fFilePath, "", "", sub.runNumber);
         NotifyOpenedFile(baseFileName, 7, fOpenedRunFiles);
 
@@ -1982,4 +1905,5 @@
 }
 
+/*
 // --------------------------------------------------------------------------
 //
@@ -2005,5 +1929,5 @@
     return kSM_Logging;
 }
-
+*/
 #ifdef HAVE_FITS
 // --------------------------------------------------------------------------
@@ -2053,9 +1977,5 @@
         return;
     }
-    string groupName;
-    if (runNumber != 0)
-        groupName = CompileFileNameWithPath(fRunFilePath, runNumber, "", "fits");
-    else
-        groupName = CompileFileNameWithPath(fNightlyFilePath, "", "fits");
+    const string groupName = CompileFileNameWithPath(fFilePath, "", "fits", runNumber);
 
     Info("Creating FITS group in: "+groupName);
@@ -2150,5 +2070,5 @@
 //! @returns
 //!        kSM_WaitingRun if success, kSM_FatalError otherwise
-int DataLogger::StopRunPlease()
+int DataLogger::StopRunLogging()
 {
 
@@ -2209,7 +2129,8 @@
    }
    if (GetCurrentState() == kSM_Logging || GetCurrentState() == kSM_WaitingRun)
-       StopRunPlease();
+       StopRunLogging();
+
    //it may be that dim tries to write a dimInfo while we're closing files. Prevent that
-   const string baseFileName = CompileFileNameWithPath(fNightlyFilePath, "", "");
+   const string baseFileName = CompileFileNameWithPath(fFilePath, "", "");
 
     if (fNightlyReportFile.is_open())
@@ -2245,11 +2166,11 @@
 //! If current state is kSM_Ready, then tries to go to nightlyOpen state first.
 //!    @returns
-//!        kSM_WaitingRun or kSM_badNightlyConfig
+//!        kSM_WaitingRun or kSM_BadFolder
 int DataLogger::NightlyToWaitRunPlease()
 {
     int cState = GetCurrentState();
 
-    if (cState == kSM_Logging)
-        cState = kSM_NightlyOpen;
+//    if (cState == kSM_Logging)
+//        cState = kSM_NightlyOpen;
 
     if (cState == kSM_Ready)
@@ -2273,4 +2194,7 @@
 int DataLogger::BackToNightlyOpenPlease()
 {
+    if (GetCurrentState()==kSM_Logging)
+        StopRunLogging();
+
     if (fDebugIsOn)
     {
@@ -2326,7 +2250,6 @@
              return 2;
 
-         fRunFilePath     = folder;
-         fNightlyFilePath = folder;
-         fFullNightlyLogFileName = CompileFileNameWithPath(fNightlyFilePath, "", "log");
+         fFilePath = folder;
+         fFullNightlyLogFileName = CompileFileNameWithPath(fFilePath, "", "log");
          if (!OpenTextFilePlease(fNightlyLogFile, fFullNightlyLogFileName))
              return 3;
