Index: trunk/FACT++/src/Fits.cc
===================================================================
--- trunk/FACT++/src/Fits.cc	(revision 10488)
+++ trunk/FACT++/src/Fits.cc	(revision 10489)
@@ -79,6 +79,10 @@
 //! @param file a pointer to an existing FITS file. If NULL, file will be opened and managed internally
 //
-void Fits::Open(const std::string& fileName, const std::string& tableName, FITS* file)
+void Fits::Open(const std::string& fileName, const std::string& tableName, FITS* file, int* fitsCounter, std::ostream& out)
 {		
+	if (fMess)
+		delete fMess;
+	fMess = new MessageImp(out);
+	
 	fFileName = fileName;
 	if (file == NULL)
@@ -88,11 +92,15 @@
 			fFile = new FITS(fileName, RWmode::Write);
 		}
-		catch (FITS::CantOpen)
-		{
-			std::ostringstream err;
-			err << "Could not open " << fileName << ".Skipping it.";
-			throw runtime_error(err.str());	
+		catch (CCfits::FitsError e)
+		{			
+			std::stringstream str;
+			str << "Could not open FITS file " << fileName << " reason: " << e.message();
+			fMess->Error(str);
+			fFile = NULL;
+			return;
 		}	
 		fOwner = true;
+		fNumOpenFitsFiles = fitsCounter;
+		(*fNumOpenFitsFiles)++;
 	}
 	else
@@ -133,5 +141,6 @@
 	try
 	{
-		fTable = fFile->addTable(tableName, 0, allNames, allDataTypes, allUnits);
+		std::string factTableName = "FACT-" + tableName;
+		fTable = fFile->addTable(factTableName, 0, allNames, allDataTypes, allUnits);
 		fCopyBuffer = new unsigned char[fTotalNumBytes]; 
 		fNumRows = fTable->rows();
@@ -153,10 +162,11 @@
 	catch(CCfits::FitsError e)
 	{
-		std::ostringstream err;
-		err << "Error when adding table " << tableName << " : " << e.message();
-		throw runtime_error(err.str());
+		std::stringstream str;
+		str << "Could not open or create FITS table " << tableName << " in  file " << fileName << " reason: " << e.message();
+		fMess->Error(str);
+		fTable = NULL;
 	}
 			
-	fEndMjD = * static_cast<double*>(fStandardPointers[0]);
+	fRefMjD = * static_cast<double*>(fStandardPointers[0]);
 	if (!updating)
 		WriteHeaderKeys();
@@ -168,4 +178,6 @@
 void Fits::WriteHeaderKeys()
 {
+	if (!fTable)
+		return;
 	std::string name;
 	std::string comment;
@@ -174,46 +186,63 @@
 	double doubleValue;
 	std::string stringValue;
+	try
+	{	
+		name = "EXTREL";
+		comment = "Release Number";
+		floatValue = 1.0f;
+		fTable->addKey(name, floatValue, comment);
+				
+		name = "BASETYPE";
+		comment = "Base type of the data structure";
+		stringValue = "??????";
+		fTable->addKey(name, stringValue, comment);
+				
+		name = "TELESCOP";
+		comment = "Telescope that acquired this data";
+		stringValue = "FACT";
+		fTable->addKey(name, stringValue, comment);
+				
+		name = "ORIGIN";
+		comment = "Institution that wrote the file";
+		stringValue = "ISDC";
+		fTable->addKey(name, stringValue, comment);
+				
+		name = "CREATOR";
+		comment = "Program that wrote this file";
+		stringValue = "FACT++_DataLogger";
+		fTable->addKey(name, stringValue, comment);
+				
+		name = "DATE";
+		stringValue = Time().GetAsStr();
+		stringValue[10] = 'T';
+		comment = "File creation date";
+		fTable->addKey(name, stringValue, comment);
+		
+		name = "TIMESYS";
+		stringValue = "TT";
+		comment = "Time frame system";
+		fTable->addKey(name, stringValue, comment);
+		
+		name = "TIMEUNIT";
+		stringValue = "d";
+		comment = "Time unit";
+		fTable->addKey(name, stringValue, comment);
+		
+		name = "TIMEREF";
+		stringValue = "UTC";
+		comment = "Time reference frame";
+		fTable->addKey(name, stringValue, comment);
 			
-	name = "EXTREL";
-	comment = "Release Number";
-	floatValue = 1.0f;
-	fTable->addKey(name, floatValue, comment);
-			
-	name = "BASETYPE";
-	comment = "Base class that wrote this file";
-	stringValue = "CCFits_table";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "TELESCOP";
-	comment = "Telescope that acquired this data";
-	stringValue = "FACT";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "ORIGIN";
-	comment = "Institution that wrote the file";
-	stringValue = "ISDC";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "CREATOR";
-	comment = "Program that wrote this file";
-	stringValue = "FACT++_DataLogger";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "DATE";
-	stringValue = Time().GetAsStr();
-	stringValue[10] = 'T';
-	comment = "File creation date";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "TIMEREF";
-	stringValue = "UTC";
-	comment = "Time reference system";
-	fTable->addKey(name, stringValue, comment);
-			
-	name = "TSTART";
-	doubleValue = fEndMjD;
-	comment = "Time of the first received data";
-	fTable->addKey(name, doubleValue, comment);
-			
+		name = "MJDREF";
+		doubleValue = fRefMjD;
+		comment = "Modified Julian Date of origin";
+		fTable->addKey(name, doubleValue, comment);
+	}
+	catch (CCfits::FitsError e)
+	{
+		std::stringstream str;
+		str << "Could not add header keys in file " << fFileName << " reason: " << e.message();
+		fMess->Error(str);
+	}			
 	//More ?
 }
@@ -233,11 +262,18 @@
 	catch(CCfits::FitsError e)
 	{
-		std::ostringstream err;
-		err << "Error when inserting a row: " << e.message();
-		throw runtime_error(err.str());
+		std::stringstream str;
+		str << "Could not insert row in file " << fFileName << " reason: " << e.message();
+		fMess->Error(str);
 	}
 	fNumRows++;
 			
 	//the first standard variable is the current MjD
+	if (fEndMjD == 0)
+	{
+		std::string name = "TSTART";
+		double doubleValue = *static_cast<double*>(fStandardPointers[0]) - fRefMjD;
+		std::string comment = "Time of the first received data";
+		fTable->addKey(name, doubleValue, comment);	
+	}
 	fEndMjD = * static_cast<double*>(fStandardPointers[0]);
 			
@@ -259,8 +295,24 @@
 	//TODO check the status after the write operation
    	fits_write_tblbytes(fFile->fitsPointer(), fNumRows, 1, fTotalNumBytes, fCopyBuffer, &status);
-
+	if (status)
+	{
+		char text[30];//max length of cfitsio error strings (from doc)
+		fits_get_errstatus(status, text);
+		std::stringstream str;
+		str << "Error while writing FITS row in " << fFileName << ". Message: " << text << " [" << status << "]";
+		fMess->Error(str);	
+	}
 	//This forces the writting of each row to the disk. Otherwise all rows are written when the file is closed.
 	///TODO check whether this consumes too much resources or not. If it does, flush every N write operations instead
-	fFile->flush();
+	try
+	{
+		fFile->flush();
+	}
+	catch (CCfits::FitsError e)
+	{
+		std::stringstream str;
+		str << "Error while flushing bytes to disk. File: " << fFileName << " reason: " << e.message();
+		fMess->Error(str);	
+	}
 }
 // --------------------------------------------------------------------------
@@ -274,7 +326,6 @@
 //			if (fTable != NULL)
 //				delete fTable;
-
 	std::string name = "TEND";
-	double doubleValue = fEndMjD;
+	double doubleValue = fEndMjD - fRefMjD;
 	std::string comment = "Time of the last received data";
 	fTable->addKey(name, doubleValue, comment);
@@ -286,4 +337,9 @@
 		delete [] fCopyBuffer;
 	fCopyBuffer = NULL;
+	if (fOwner && fNumOpenFitsFiles != NULL)
+		(*fNumOpenFitsFiles)--;
+	if (fMess)
+		delete fMess;
+	fMess = NULL;
 }
 
Index: trunk/FACT++/src/Fits.h
===================================================================
--- trunk/FACT++/src/Fits.h	(revision 10488)
+++ trunk/FACT++/src/Fits.h	(revision 10489)
@@ -6,5 +6,5 @@
 
 #include "Description.h"
-
+#include "MessageImp.h"
 using namespace CCfits;
 
@@ -46,7 +46,16 @@
 		///to keep track of the time of the latest written entry (to update the header when closing the file)
 		double fEndMjD;
+		///to keep track of the reference MjD
+		double fRefMjD;
 		///Write the FITS header keys
 		void WriteHeaderKeys();
-		
+public:
+		///Name of the openned file. For querying stats
+		std::string fFileName;
+private:
+		///Keep track of number of opened fits
+		int* fNumOpenFitsFiles;
+		///were to log the errors
+		MessageImp* fMess;		
 	public:
 		
@@ -60,5 +69,8 @@
 					 fTotalNumBytes(0),
 					 fEndMjD(0.0),
-					 fFileName("")
+					 fRefMjD(0.0),
+					 fFileName(""),
+					 fNumOpenFitsFiles(NULL),
+					 fMess(NULL)
 		 {}
 		
@@ -78,5 +90,5 @@
 
 		///Opens a FITS file
-		void Open(const std::string& fileName, const std::string& tableName, FITS* file);
+		void Open(const std::string& fileName, const std::string& tableName, FITS* file, int* fitsCounter, std::ostream& out);
 
 		///Write one line of data. Use the given converter.
@@ -88,6 +100,4 @@
 		///Get the size currently written on the disk
 		int GetWrittenSize();
-		///Name of the openned file. For querying stats
-		std::string fFileName;
 
 };//Fits
Index: trunk/FACT++/src/dataLogger.cc
===================================================================
--- trunk/FACT++/src/dataLogger.cc	(revision 10488)
+++ trunk/FACT++/src/dataLogger.cc	(revision 10489)
@@ -85,5 +85,15 @@
 	int numOpenFits;
 };
-
+//For debugging DIM's services
+class MyService
+{
+public:
+	MyService(){};
+	MyService(std::string, std::string, void*, int){};
+	MyService(std::string, const char*){};
+	void updateService(){};
+	void updateService(void*, int){};
+	void setQuality(int){};
+};
 class DataLogger : public StateMachineDim, DimInfoHandler
 {
@@ -136,12 +146,4 @@
 	static const char* fTransWait;
 	static const char* fRunNumberInfo; ///< This is the name of the dimInfo received to specify the run number. It must be updated once the final name will be defined
-	///Inherited from state machine impl
-	//int Execute();
-	
-	///Inherited from state machine impl
-	//int Transition(const Event& evt);
-	
-	///Inherited from state machine impl
-	//int Configure(const Event& evt);
 	
 	//overloading of DIM's infoHandler function
@@ -293,10 +295,11 @@
 	long long fBaseSizeRun;
 	///Service for opened files
-	DimService* fOpenedDailyFiles;
-	DimService* fOpenedRunFiles;
-	DimService* fNumSubAndFits;
+	DimDescribedService* fOpenedDailyFiles;
+	DimDescribedService* fOpenedRunFiles;
+	DimDescribedService* fNumSubAndFits;
 	NumSubAndFitsType fNumSubAndFitsData;
 //	char* fDimBuffer;
 	inline void NotifyOpenedFile(std::string name, int type, DimService* service);
+	inline void NotifyOpenedFile(std::string , int , MyService* ){}
 	
 }; //DataLogger
@@ -334,7 +337,8 @@
 //        DimDescribedService srvc((GetName()+"/STATS").c_str(), "x:2;l:1", &statVar, dataSize,//static_cast<void*>(data), dataSize,
 //                                        "Add description here");
-		DimService srvc ("DATA_LOGGER/STATS", "x:2;l:1", &statVar, dataSize);
+		DimDescribedService srvc ("DATA_LOGGER/STATS", "X:2;L:1", &statVar, dataSize, "Add description here");
 		double deltaT = 1;
 		fPreviousSize = 0;
+		bool statWarning = false;
 		//loop-wait for broadcast
 		while (fContinueMonitoring)
@@ -384,7 +388,17 @@
 
 			if (!statvfs(fDailyFileName.c_str(), &vfs))
+			{
 				statVar.freeSpace = vfs.f_bsize*vfs.f_bavail;
+				statWarning = false;
+			}
 			else
+			{
+				std::stringstream str;
+				str << "Unable to retrieve stats for " << fDailyFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+				if (!statWarning)
+					Error(str);
+				statWarning = true;
 				statVar.freeSpace = -1;
+			}
 			
 			//sum up all the file sizes. past and present
@@ -416,6 +430,6 @@
 {	
 		//initialize member data
-		fDailyFileName = "/home/lyard/log";//".";
-		fRunFileName = "/home/lyard/log";//".";
+		fDailyFileName = ".";//"/home/lyard/log";//
+		fRunFileName = ".";//"/home/lyard/log";
 		fRunNumber = 12345;
 #ifdef HAS_FITS
@@ -433,22 +447,22 @@
         /*Add the possible transitions for this machine*/
                 AddTransition(kSM_DailyOpen, fTransStart, kSM_Ready, kSM_BadDailyConfig)
-                    (boost::bind(&DataLogger::StartPlease, this));
-//                    ("start the daily logging. daily file location must be specified already");
+                    (boost::bind(&DataLogger::StartPlease, this))
+                    ("start the daily logging. daily file location must be specified already");
 
 		AddTransition(kSM_Ready, fTransStop, kSM_DailyOpen, kSM_WaitingRun, kSM_Logging)
-                    (boost::bind(&DataLogger::GoToReadyPlease, this));
-//                   ("stop the data logging");
+                    (boost::bind(&DataLogger::GoToReadyPlease, this))
+                   ("stop the data logging");
 
                 AddTransition(kSM_Logging, fTransStartRun, kSM_WaitingRun, kSM_BadRunConfig)
-                    (boost::bind(&DataLogger::StartRunPlease, this));
-//                    ("start the run logging. run file location must be specified already.");
+                    (boost::bind(&DataLogger::StartRunPlease, this))
+                    ("start the run logging. run file location must be specified already.");
 
                 AddTransition(kSM_WaitingRun, fTransStopRun, kSM_Logging)
-                    (boost::bind(&DataLogger::StopRunPlease, this));
-//                    ("");
+                    (boost::bind(&DataLogger::StopRunPlease, this))
+                    ("");
 
                 AddTransition(kSM_Ready, fTransReset, kSM_Error, kSM_BadDailyConfig, kSM_BadRunConfig, kSM_Error)
-                    (boost::bind(&DataLogger::GoToReadyPlease, this));
-//                    ("transition to exit error states. dunno if required or not, would close the daily file if already openned.");
+                    (boost::bind(&DataLogger::GoToReadyPlease, this))
+                    ("transition to exit error states. dunno if required or not, would close the daily file if already openned.");
 
                 AddTransition(kSM_WaitingRun, fTransWait, kSM_DailyOpen)
@@ -458,10 +472,10 @@
         
                 AddConfiguration(fConfigDay, "C", kSM_Ready, kSM_BadDailyConfig)
-                    (boost::bind(&DataLogger::ConfigureDailyFileName, this, _1));;
-//                    ("configure the daily file location. cannot be done before the file is actually opened");
+                    (boost::bind(&DataLogger::ConfigureDailyFileName, this, _1))
+                    ("configure the daily file location. cannot be done before the file is actually opened");
 
                 AddConfiguration(fConfigRun, "C", kSM_Ready, kSM_BadDailyConfig, kSM_DailyOpen, kSM_WaitingRun, kSM_BadRunConfig)
-                    (boost::bind(&DataLogger::ConfigureRunFileName, this, _1));
-//                    ("configure the run file location. cannot be done before the file is actually opened, and not in a dailly related error.");
+                    (boost::bind(&DataLogger::ConfigureRunFileName, this, _1))
+                    ("configure the run file location. cannot be done before the file is actually opened, and not in a dailly related error.");
 
 		//Provide a logging command
@@ -481,13 +495,9 @@
 		fBaseSizeDaily = 0;
 		fBaseSizeRun = 0;
-		//start the open files service
-//		fDimBuffer = new char[256];
-//		memset(fDimBuffer, 0, sizeof(int));
-//		fDimBuffer[sizeof(int)] = '\0';
 
 		//gives the entire buffer size. Otherwise, dim overwrites memory at bizarre locations if smaller size is given at creation time.
 //        fOpenedFiles = 	new DimDescribedService((GetName()+"/FILENAME").c_str(), "i:1;C", static_cast<void*>(fDimBuffer), 256, "Add description here");
-		fOpenedDailyFiles = new DimService((GetName() + "/FILENAME_DAILY").c_str(), const_cast<char*>(""));//"i:1;C", static_cast<void*>(fDimBuffer), 256);
-		fOpenedRunFiles = new DimService((GetName() + "/FILENAME_RUN").c_str(), const_cast<char*>(""));
+		fOpenedDailyFiles = new DimDescribedService((GetName() + "/FILENAME_DAILY").c_str(), const_cast<char*>(""), "Add description here");//"i:1;C", static_cast<void*>(fDimBuffer), 256);
+		fOpenedRunFiles = new DimDescribedService((GetName() + "/FILENAME_RUN").c_str(), const_cast<char*>(""), "Add description here");
 		fOpenedDailyFiles->setQuality(0);
 		fOpenedRunFiles->setQuality(0);
@@ -496,5 +506,5 @@
 		fNumSubAndFitsData.numSubscriptions = 0;
 		fNumSubAndFitsData.numOpenFits = 0;
-		fNumSubAndFits = new DimService((GetName() + "/NUM_SUBS").c_str(), "i:2", &fNumSubAndFitsData, sizeof(NumSubAndFitsType));
+		fNumSubAndFits = new DimDescribedService((GetName() + "/NUM_SUBS").c_str(), "I:2", &fNumSubAndFitsData, sizeof(NumSubAndFitsType), "Add description here");
 
 }
@@ -527,5 +537,5 @@
 		}
 			
-	}
+	} 
 	for (std::vector<std::string>::const_iterator it = toBeDeleted.begin(); it != toBeDeleted.end(); it++)
 		fServiceSubscriptions.erase(*it);
@@ -620,125 +630,5 @@
 #endif
 }
-/*
-// --------------------------------------------------------------------------
-//
-//! Execute
-//! Shouldn't be run as we use callbacks instead
-//
-int DataLogger::Execute()
-{
-	//due to the callback mecanism, this function should never be called
-	return kSM_FatalError;
-	
-	switch (GetCurrentState())
-	{
-	case kSM_Error:
-	case kSM_Ready:
-	case kSM_DailyOpen:
-	case kSM_WaitingRun:
-	case kSM_Logging:
-	case kSM_BadDailyConfig:
-	case kSM_BadRunConfig:
-		return GetCurrentState();
-	}
-	//this line below should never be hit. It here mainly to remove warnings at compilation
-	return kSM_FatalError;
-}
-// --------------------------------------------------------------------------
-//
-//! Shouldn't be run as we use callbacks instead
-//
- int DataLogger::Transition(const Event& evt)
-{
-	//due to the callback mecanism, this function should never be called
-	return kSM_FatalError;
-	
-	switch (evt.GetTargetState())
-	{
-		case kSM_Ready:
-		//here we must figure out whether the STOP or RESET command was sent
-		//close opened files and go back to ready state
-			switch (GetCurrentState())
-			{
-				case kSM_BadDailyConfig:
-				case kSM_BadRunConfig:
-				case kSM_Error:
-					return GoToReadyPlease();
-					
-				case kSM_Logging:
-				case kSM_WaitingRun:
-				case kSM_DailyOpen:
-					return GoToReadyPlease();
-			}
-		break;
-		
-		case kSM_DailyOpen:
-			//Attempt to open the daily file
-			switch (GetCurrentState())
-			{
-				case kSM_Ready:
-				case kSM_BadDailyConfig:
-					return StartPlease();	
-			}
-		break;
-		
-		case kSM_WaitingRun:
-			//either close the run file, or just go to the waitingrun state (if coming from daily open
-			switch (GetCurrentState())
-			{
-				case kSM_DailyOpen:
-					return kSM_WaitingRun;
-				
-				case kSM_Logging:
-					return StopRunPlease();	
-			}
-		break;
-		
-		case kSM_Logging:
-			//Attempt to open run file
-			switch (GetCurrentState())
-			{
-				case kSM_WaitingRun:
-				case kSM_BadRunConfig:
-					return StartRunPlease();
-			}	
-		break;
-	}
-	//Getting here means that an invalid transition has been asked. 
-	//TODO Log an error message
-	//and return the fatal error state
-	return kSM_FatalError;
-}
-// --------------------------------------------------------------------------
-//
-//! Shouldn't be run as we use callbacks instead
-//
- int DataLogger::Configure(const Event& evt)
-{
-	//due to the callback mecanism, this function should never be called
-	return kSM_FatalError;
-
-	switch (evt.GetTargetState())
-	{
-		case kSM_Ready:
-		case kSM_BadDailyConfig:
-			return ConfigureDailyFileName(evt);
-		break;
-		
-		case kSM_WaitingRun:
-		case kSM_BadRunConfig:
-			return ConfigureRunFileName(evt);	
-		break;
-		
-		case kSM_Logging:
-		case kSM_DailyOpen:
-				return 0;
-		break;
-
-	}	
-
-	return kSM_FatalError;
-}
-*/
+
 // --------------------------------------------------------------------------
 //
@@ -827,5 +717,7 @@
 		if (!sub.fConv)
 		{
-			Error("Couldn't properly parse the format... service ignored.");
+			std::stringstream str;
+			str << "Couldn't properly parse the format... service " << sub.dimInfo->getName() << " ignored.";
+			Error(str);
 			return;	
 		}
@@ -854,36 +746,76 @@
         {
         	Out() << kRed << e.what() << endl;
-            Error("Couldn't properly parse the data... ignored.");
+        	std::stringstream str;
+        	str << "Could not properly parse the data for service " << sub.dimInfo->getName();
+        	str << " reason: " << e.what() << ". Entry ignored";
+            Error(str);
             return;
         }
 
 		if (text.empty())
+		{
+			std::stringstream str;
+			str << "Service " << sub.dimInfo->getName() << " sent an empty string";
+			Info(str);
         	return;
-
+		}
         //replace bizarre characters by white space
         replace(text.begin(), text.end(), '\n', '\\');
         replace_if(text.begin(), text.end(), std::ptr_fun<int, int>(&std::iscntrl), ' ');
-	
-		if (fDailyReportFile.is_open())
-			fDailyReportFile << header.str();
-		if (fRunReportFile.is_open())
-			fRunReportFile << header.str();
-
-        if (fDailyReportFile.is_open())
-			fDailyReportFile << text << std::endl;
-		if (fRunReportFile.is_open())
-			fRunReportFile << text << std::endl;
+        
+        //write entry to daily report
+		try
+		{
+			if (fDailyReportFile.is_open())
+				fDailyReportFile << header.str() << text << std::endl;
+		}
+		catch (std::exception e)
+		{
+			std::stringstream str;
+			str << "Error while writing to daily report file: " << e.what();
+			Error(str);	
+		}
+		//write entry to run-report
+		try
+		{
+			if (fRunReportFile.is_open())
+				fRunReportFile << header.str() << text << std::endl;
+		}
+		catch (std::exception e)
+		{
+			std::stringstream str;
+			str << "Error while writing to run report file: " << e.what();
+			Error(str);
+		}
 	}
 	else
-	{
+	{//write entry to both daily and run logs
 		std::string n = I->getName();
 		std::stringstream msg;
 		msg << n.substr(0, n.find_first_of('/')) << ": " << I->getString();
-		MessageImp dailyMess(fDailyLogFile);
-		dailyMess.Write(cTime, msg.str().c_str(), fQuality);
+		try
+		{
+			MessageImp dailyMess(fDailyLogFile);
+			dailyMess.Write(cTime, msg.str().c_str(), fQuality);
+		}
+		catch (std::exception e)
+		{
+			std::stringstream str;
+			str << "Error while writing to daily log file: " << e.what();
+			Error(str);	
+		}
 		if (fRunLogFile.is_open())
 		{
-			MessageImp runMess(fRunLogFile);
-			runMess.Write(cTime, msg.str().c_str(), fQuality);
+			try 
+			{
+				MessageImp runMess(fRunLogFile);
+				runMess.Write(cTime, msg.str().c_str(), fQuality);
+			}
+			catch (std::exception e)
+			{
+				std::stringstream str;
+				str << "Error while writing to run log file: " << e.what();
+				Error(str);	
+			}
 		}
 	}
@@ -910,4 +842,5 @@
 //
 //TODO isn't that function not used any longer ? If so I guess that we should get rid of it...
+//Otherwise re-write it properly with the MessageImp class
 int DataLogger::LogMessagePlease(const Event& evt)
 {
@@ -969,9 +902,11 @@
 int DataLogger::ConfigureDailyFileName(const Event& evt)
 {
-std::cout << "Configure Daily File Name" << std::endl;
 	if (evt.GetText() != NULL)
+	{
 		fDailyFileName = std::string(evt.GetText());	
+		Message("New daily folder specified: " + fDailyFileName);
+	}
 	else
-		Error("Empty daily folder");
+		Error("Empty daily folder given. Please specify a valid path.");
 
 	return GetCurrentState();
@@ -986,9 +921,11 @@
 int DataLogger::ConfigureRunFileName(const Event& evt)
 {
-std::cout << "Configure Run File Name" << std::endl;
 	if (evt.GetText() != NULL)
+	{
 		fRunFileName = std::string(evt.GetText());
+		Message("New Run folder specified: " + fRunFileName);
+	}
 	else
-		Error("Empty daily folder");
+		Error("Empty daily folder given. Please specify a valid path");
 
 	return GetCurrentState();
@@ -1001,8 +938,8 @@
 //! @returns
 //! 	currently only the current state
+//TODO remove this function as the run numbers will be distributed through a dedicated service
 int DataLogger::ConfigureRunNumber(const Event& evt)
 {
 	fRunNumber = evt.GetInt();
-
 	return GetCurrentState();
 }
@@ -1016,10 +953,6 @@
 inline void DataLogger::NotifyOpenedFile(std::string name, int type, DimService* service)
 {
-//std::cout << "name: " << name << " size: " << name.size() << std::endl;
-//	reinterpret_cast<int*>(fDimBuffer)[0] = type;
-//	strcpy(&fDimBuffer[sizeof(int)], name.c_str());
 	service->setQuality(type);
 	service->updateService(const_cast<char*>(name.c_str()));
-//	fOpenedFiles->updateService(static_cast<void*>(fDimBuffer), name.size() + 1 + sizeof(int));
 }
 // --------------------------------------------------------------------------
@@ -1033,13 +966,25 @@
 {
 	//TODO concatenate the dailyFileName and the formatted date and extension to obtain the full file name
-	Time time;//(Time::utc);
+	Time time;
 	std::stringstream sTime;
 	sTime << time.Y() << "_" << time.M() << "_" << time.D();
+
 	fFullDailyLogFileName = fDailyFileName + '/' + sTime.str() + ".log"; 
-	
-	fDailyLogFile.open(fFullDailyLogFileName.c_str(), std::ios_base::out | std::ios_base::app); //maybe should be "app" instead of "ate" ??
+	fDailyLogFile.open(fFullDailyLogFileName.c_str(), std::ios_base::out | std::ios_base::app); 
+	if (errno != 0)
+	{
+		std::stringstream str;
+		str << "Unable to open daily Log " << fFullDailyLogFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+		Error(str);	
+	}
 	fFullDailyReportFileName = fDailyFileName + '/' + sTime.str() + ".rep";
 	fDailyReportFile.open(fFullDailyReportFileName.c_str(), std::ios_base::out | std::ios_base::app);
-	
+	if (errno != 0)
+	{
+		std::stringstream str;
+		str << "Unable to open daily Report " << fFullDailyReportFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+		Error(str);	
+	}
+
 	if (!fDailyLogFile.is_open() || !fDailyReportFile.is_open())
 	{	
@@ -1062,4 +1007,10 @@
 		char currentPath[FILENAME_MAX];
 		getcwd(currentPath, sizeof(currentPath));
+		if (errno != 0)
+		{
+			std::stringstream str;
+			str << "Unable retrieve current path" << ". Reason: " << strerror(errno) << " [" << errno << "]";
+			Error(str);	
+		}
 		actualTargetDir = currentPath;
 	}
@@ -1068,5 +1019,5 @@
 		actualTargetDir = fDailyFileName;	
 	}
-std::cout << actualTargetDir << '/' << sTime.str() << std::endl;
+
 	NotifyOpenedFile(actualTargetDir + '/' + sTime.str(), 3, fOpenedDailyFiles);
 	
@@ -1108,5 +1059,5 @@
 			fFileSizesMap[partialName] = 0;
 		}
-		sub.dailyFile.Open(partialName, serviceName, NULL, &fNumSubAndFitsData.numOpenFits);
+		sub.dailyFile.Open(partialName, serviceName, NULL, &fNumSubAndFitsData.numOpenFits, Out());
 		//notify the opening
 		std::string actualTargetDir;
@@ -1153,7 +1104,8 @@
 			catch (CCfits::FitsError e)
 			{
-				std::ostringstream err;
-				err << "Could not open run file " << partialName;
-				throw runtime_error(err.str());	
+				std::stringstream str;
+				str << "Could not open FITS Run file " << partialName << " reason: " << e.message();
+				Error(str);
+				fRunFitsFile = NULL;
 			}
 #endif
@@ -1172,7 +1124,7 @@
 #ifdef ONE_RUN_FITS_ONLY
 		}
-		sub.runFile.Open(partialName, serviceName, fRunFitsFile, &fNumSubAndFitsData.numOpenFits);
+		sub.runFile.Open(partialName, serviceName, fRunFitsFile, &fNumSubAndFitsData.numOpenFits, Out());
 #else
-		sub.runFile.Open(partialName, serviceName, NULL, &fNumSubAndFitsData.numOpenFits);
+		sub.runFile.Open(partialName, serviceName, NULL, &fNumSubAndFitsData.numOpenFits, Out());
 #endif //one_run_fits_only
 	   fNumSubAndFits->updateService();
@@ -1281,7 +1233,18 @@
 	fFullRunLogFileName = fRunFileName + '/' + sRun.str() + ".log";
 	fRunLogFile.open(fFullRunLogFileName.c_str(), std::ios_base::out | std::ios_base::app); //maybe should be app instead of ate
-
+	if (errno != 0)
+	{
+		std::stringstream str;
+		str << "Unable to open run Log " << fFullRunLogFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+		Error(str);	
+	}
 	fFullRunReportFileName = fRunFileName + '/' + sRun.str() + ".rep";
 	fRunReportFile.open(fFullRunReportFileName.c_str(), std::ios_base::out | std::ios_base::app);
+	if (errno != 0)
+	{
+		std::stringstream str;
+		str << "Unable to open run report " << fFullRunReportFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+		Error(str);	
+	}
 	
 	if (!fRunLogFile.is_open() || !fRunReportFile.is_open())
@@ -1296,5 +1259,12 @@
 	{
 		stat(fFullRunLogFileName.c_str(), &st);
-		fBaseSizeRun += st.st_size;
+		if (errno != 0)
+		{
+			std::stringstream str;
+			str << "Unable to stat " << fFullRunLogFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+			Error(str);	
+		}
+		else
+			fBaseSizeRun += st.st_size;
 		fFileSizesMap[fFullRunLogFileName] = 0;
 	}
@@ -1302,5 +1272,12 @@
 	{
 		stat(fFullRunReportFileName.c_str(), &st);
-		fBaseSizeRun += st.st_size;
+		if (errno != 0)
+		{
+			std::stringstream str;
+			str << "Unable to stat " << fFullRunReportFileName << ". Reason: " << strerror(errno) << " [" << errno << "]";
+			Error(str);	
+		}
+		else
+			fBaseSizeRun += st.st_size;
 		fFileSizesMap[fFullRunReportFileName] = 0;
 	}
@@ -1310,4 +1287,10 @@
 		char currentPath[FILENAME_MAX];
 		getcwd(currentPath, sizeof(currentPath));
+		if (errno != 0)
+		{
+			std::stringstream str;
+			str << "Unable to retrieve the current path" << ". Reason: " << strerror(errno) << " [" << errno << "]";
+			Error(str);	
+		}		
 		actualTargetDir = currentPath;
 	}
@@ -1345,7 +1328,5 @@
 		delete fRunFitsFile;
 		fRunFitsFile = NULL;	
-std::cout << "FNumSub2: " << fNumSubAndFitsData.numOpenFits << std::endl;
 		(fNumSubAndFitsData.numOpenFits)--;
-std::cout << "FNumSub3: " << fNumSubAndFitsData.numOpenFits << std::endl;
 	}
 #endif
@@ -1433,10 +1414,10 @@
 }
 
-void RunThread(DataLogger *logger)
-{
-    // This is necessary so that the StateMachien Thread can signal the
-    // Readline thread to exit
-    logger->Run(true);
-    Readline::Stop();
+void RunThread(DataLogger* logger)
+{
+	// This is necessary so that the StateMachine Thread can signal the 
+	// Readline thread to exit
+	logger->Run(true);
+	Readline::Stop();	
 }
 
@@ -1454,16 +1435,22 @@
 
     DataLogger logger(wout);
+    
+//    if (conf.Has("black-list"))
+//    	logger.setBlackList(conf.Get<std::string>("black-list"));
+//    else if (conf.Has("white-list"))
+//    	logger.setWhiteList(conf.Get<std::string>("white-list"));
+
     shell.SetReceiver(logger);
 
-    boost::thread t(boost::bind(RunThread, &logger));
-
-    shell.Run();    // Run the shell
-
-    logger.Stop();  // Signal Loop-thread to stop
-
-    // Wait until the StateMachine has finished its thread
-    // before returning and destroying the dim objects which might
-    // still be in use.
-    t.join();
+	boost::thread t(boost::bind(RunThread, &logger));
+	
+	shell.Run(); // Run the shell
+	
+	logger.Stop();
+	
+	//Wait until the StateMachine has finished its thread
+	//before returning and destroyinng the dim objects which might 
+	//still be in use.
+	t.join();
 
     return 0;
@@ -1505,18 +1492,4 @@
         "help message about the usuage can be brought to the screen."
         << endl;
-
-    /*
-     cout << "bla bla bla" << endl << endl;
-     cout << endl;
-     cout << "Environment:" << endl;
-     cout << "environment" << endl;
-     cout << endl;
-     cout << "Examples:" << endl;
-     cout << "test exam" << endl;
-     cout << endl;
-     cout << "Files:" << endl;
-     cout << "files" << endl;
-     cout << endl;
-     */
 }
 
@@ -1564,4 +1537,6 @@
         ("log,l",     var<string>(n), "Write log-file")
         ("console,c", var<int>(),     "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
+        ("black-list,b", var<string>(""), "Black-list of services")
+        ("white-list,w", var<string>(""), "White-list of services")
         ;
 
