Index: /trunk/FACT++/src/EventBuilderWrapper.h
===================================================================
--- /trunk/FACT++/src/EventBuilderWrapper.h	(revision 11375)
+++ /trunk/FACT++/src/EventBuilderWrapper.h	(revision 11376)
@@ -33,8 +33,9 @@
 
 protected:
+    MessageImp &fLog;
     string fFileName;
 
 public:
-    DataFileImp(uint32_t id) : fRunId(id) { }
+    DataFileImp(uint32_t id, MessageImp &imp) : fRunId(id), fLog(imp) { }
     virtual ~DataFileImp() { }
 
@@ -94,5 +95,5 @@
 {
 public:
-    DataFileNone(uint32_t id) : DataFileImp(id) { }
+    DataFileNone(uint32_t id, MessageImp &imp) : DataFileImp(id, imp) { }
 
     bool OpenFile(RUN_HEAD* h)
@@ -123,5 +124,5 @@
 {
 public:
-    DataFileDebug(uint32_t id) : DataFileNone(id) { }
+    DataFileDebug(uint32_t id, MessageImp &imp) : DataFileNone(id, imp) { }
 
     bool Write(EVENT *e)
@@ -197,6 +198,6 @@
 
 public:
-    DataFileRaw(uint32_t id) : DataFileImp(id), fPosTail(0) { }
-    ~DataFileRaw() { Close(); }
+    DataFileRaw(uint32_t id, MessageImp &imp) : DataFileImp(id, imp), fPosTail(0) { }
+    ~DataFileRaw() { if (fOut.is_open()) Close(); }
 
     void WriteBlockHeader(uint32_t type, uint32_t ver, uint32_t cnt, uint32_t len)
@@ -223,7 +224,12 @@
     };
 
-    virtual bool OpenFile(RUN_HEAD *h)
+    bool OpenFile(RUN_HEAD *h)
     {
         const string name = FormFileName(h->RunType, "bin");
+        if (access(name.c_str(), F_OK)==0)
+        {
+            fLog.Error("File '"+name+"' already exists.");
+            return false;
+        }
 
         fFileName = name;
@@ -233,7 +239,7 @@
         if (!fOut)
         {
-            //ostringstream str;
-            //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
-            //Error(str);
+            ostringstream str;
+            str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
+            fLog.Error(str);
 
             return false;
@@ -268,7 +274,7 @@
         if (!fOut)
         {
-            //ostringstream str;
-            //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
-            //Error(str);
+            ostringstream str;
+            str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
+            fLog.Error(str);
 
             return false;
@@ -277,5 +283,5 @@
         return true;
     }
-    virtual bool Write(EVENT *evt)
+    bool Write(EVENT *evt)
     {
         const int sh = sizeof(EVENT)-2 + NPIX*evt->Roi*2;
@@ -285,5 +291,5 @@
         return true;
     }
-    virtual bool Close(RUN_TAIL *tail= 0)
+    bool Close(RUN_TAIL *tail= 0)
     {
         WriteBlockHeader(kEndOfFile, 0, 0, 0);
@@ -299,7 +305,7 @@
         if (!fOut)
         {
-            //ostringstream str;
-            //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
-            //Error(str);
+            ostringstream str;
+            str << " Writing footer: " << strerror(errno) << " (errno=" << errno << ")";
+            fLog.Error(str);
 
             return false;
@@ -310,7 +316,7 @@
         if (!fOut)
         {
-            //ostringstream str;
-            //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
-            //Error(str);
+            ostringstream str;
+            str << "Closing file: " << strerror(errno) << " (errno=" << errno << ")";
+            fLog.Error(str);
 
             return false;
@@ -321,5 +327,5 @@
 };
 
-#ifdef HAS_FITS
+#ifdef HAVE_FITS
 class DataFileFits : public DataFileImp
 {
@@ -329,6 +335,9 @@
     uint64_t fNumRows;                ///the number of rows that have been written already to the FITS file.
 
+    Converter *fConv;
+
 public:
-    DataFileFits(uint32_t runid) : DataFileImp(runid), fFile(0)
+    DataFileFits(uint32_t runid, MessageImp &imp) :
+        DataFileImp(runid, imp), fFile(0), fNumRows(0), fConv(0)
     {
     }
@@ -340,5 +349,5 @@
     //! related to the RUN_TAIL will NOT be written to the file.
     //
-    ~DataFileFits() { Close(); }
+    ~DataFileFits() { Close(); delete fConv; }
 
     // --------------------------------------------------------------------------
@@ -380,6 +389,6 @@
         {
             ostringstream str;
-            str << "Could not add header key ";
-            //TODO pipe the error message somewhere
+            str << "Could not add header key " << name;
+            fLog.Error(str);
         }
     }
@@ -404,6 +413,24 @@
         //Form filename, based on runid and run-type
         const string fileName = FormFileName(h->RunType, "fits");
+        if (access(fileName.c_str(), F_OK)==0)
+        {
+            fLog.Error("File '"+fileName+"' already exists.");
+            return false;
+        }
 
         fFileName = fileName;
+
+        /*
+         out <<
+         "SIMPLE  =                    T / file does conform to FITS standard             "
+         "BITPIX  =                    8 / number of bits per data pixel                  "
+         "NAXIS   =                    0 / number of data axes                            "
+         "EXTEND  =                    T / FITS dataset may contain extensions            "
+         "COMMENT   FITS (Flexible Image Transport System) format is defined in 'Astronomy"
+         "COMMENT   and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H "
+         "END                                                                             ";
+         for (int i=0; i<29; i++)
+         out << "                                                                                "
+         */
 
         //create the FITS object
@@ -415,32 +442,28 @@
         {
             ostringstream str;
-            str << "Could not open FITS file " << fileName << " reason: " << e.message();
-            //TODO display the message somewhere
-
+            str << "Could not open FITS file " << fileName << ": " << e.message();
+            fLog.Error(str);
             return false;
         }
-
-        //create columns according to header
-        ostringstream arrayTypes;
-
-        // uint32_t EventNum ;       // EventNumber as from FTM
-        // uint16_t TriggerType ;    // Trigger Type from FTM
-        // uint32_t SoftTrig ;       // SoftTrigger Info (TBD)
-        // uint32_t PCTime ;         // when did event start to arrive at PC
-        // uint32_t BoardTime[NBOARDS];//
-        // int16_t  StartPix[NPIX];  // First Channel per Pixel (Pixels sorted according Software ID)  ; -1 if not filled
-        // int16_t  StartTM[NTMARK]; // First Channel for TimeMark (sorted Hardware ID) ; -1 if not filled
-        // uint16_t Adc_Data[];      // final length defined by malloc ....
 
         vector<string> colNames;
         vector<string> dataTypes;
-        AddColumnEntry(colNames, dataTypes, 1,              'V', "EventNum");
-        AddColumnEntry(colNames, dataTypes, 1,              'U', "TriggerType");
-        AddColumnEntry(colNames, dataTypes, 1,              'V', "SoftTrig");
-        AddColumnEntry(colNames, dataTypes, 1,              'V', "PCTime");
-        AddColumnEntry(colNames, dataTypes, NBOARDS,        'V', "BoardTime");
-        AddColumnEntry(colNames, dataTypes, NPIX,           'I', "StartPix");
-        AddColumnEntry(colNames, dataTypes, NTMARK,         'I', "StartTM");
-        AddColumnEntry(colNames, dataTypes, NPIX*h->Nroi,   'U', "Data");
+        AddColumnEntry(colNames, dataTypes, 1,            'J', "EventNum");
+        AddColumnEntry(colNames, dataTypes, 1,            'I', "TriggerType");
+        AddColumnEntry(colNames, dataTypes, 1,            'J', "SoftTrig");
+        AddColumnEntry(colNames, dataTypes, 1,            'J', "PCTime");
+        AddColumnEntry(colNames, dataTypes, NBOARDS,      'J', "BoardTime");
+        AddColumnEntry(colNames, dataTypes, NPIX,         'I', "StartPix");
+        AddColumnEntry(colNames, dataTypes, NTMARK,       'I', "StartTM");
+        AddColumnEntry(colNames, dataTypes, NPIX*h->Nroi, 'I', "Data");
+
+        ostringstream fmt;
+        fmt << "I:1;S:1;I:1;I:1";
+        fmt << ";I:" << NBOARDS;
+        fmt << ";S:" << NPIX;
+        fmt << ";S:" << NTMARK;
+        fmt << ";S:" << NPIX*h->Nroi;
+
+        fConv = new Converter(fmt.str());
 
         //actually create the table
@@ -448,19 +471,16 @@
         {
             fTable = fFile->addTable("Events", 0, colNames, dataTypes);
-            if (fTable->rows() != 0)
-            {
-                ostringstream str;
-                str << "Error: table created on the fly looks non-empty.";
-                //TODO giev the error text to some error handler
-                //FIXME I guess that this error checking is useless. remove it for performances.
-            }
         }
         catch (const CCfits::FitsException &e)
         {
             ostringstream str;
-            str << "Could not create FITS table " << "Events" << " in file " << fileName << " reason: " << e.message();
-            //TODO give the error text to some error handler
-
-            Close();
+            str << "Could not create FITS table 'Events' in file " << fileName << " reason: " << e.message();
+            fLog.Error(str);
+            return false;
+        }
+
+        if (fTable->rows() != 0)
+        {
+            fLog.Error("FITS table created on the fly looks non-empty.");
             return false;
         }
@@ -468,5 +488,4 @@
         //write header data
         //first the "standard" keys
-        string stringValue;
         WriteKey("EXTREL",   1.0f,   "Release Number");
         WriteKey("TELESCOP", "FACT", "Telescope that acquired this data");
@@ -474,4 +493,5 @@
         WriteKey("CREATOR",  "FACT++ Event Builder", "Program that wrote this file");
 
+        string stringValue;
         stringValue = Time().GetAsStr();
         stringValue[10]= 'T';
@@ -488,5 +508,5 @@
         WriteKey("NTM",      h->NTm,      "Number of Time marks");
         WriteKey("NROI",     h->Nroi,     "Number of slices per pixels");
-
+/*
         //now the boards related keywords
         for (int i=0; i<h->NBoard; i++)
@@ -505,20 +525,20 @@
             WriteKey("STATUS",  i, hh.PLLLCK,
                      "");
-/*
-            WriteKey("TRIGCRC", i, hh.trigger_crc,
-                     "Trigger CRC");
-
-            WriteKey("TRIGTYP", i, hh.trigger_type,
-                     "Trigger type");
-
-            WriteKey("TRIGID",  i, hh.trigger_id,
-                     "Trigger ID");
-
-            WriteKey("EVTCNTR", i, hh.fad_evt_counter,
-                     "FAD Event Counter");
-
-            WriteKey("REFCLK",  i, hh.REFCLK_frequency,
-                     "Reference Clock Frequency");
-*/
+
+//            WriteKey("TRIGCRC", i, hh.trigger_crc,
+//                     "Trigger CRC");
+
+//            WriteKey("TRIGTYP", i, hh.trigger_type,
+//                     "Trigger type");
+
+//            WriteKey("TRIGID",  i, hh.trigger_id,
+//                     "Trigger ID");
+
+//            WriteKey("EVTCNTR", i, hh.fad_evt_counter,
+//                     "FAD Event Counter");
+
+//            WriteKey("REFCLK",  i, hh.REFCLK_frequency,
+//                     "Reference Clock Frequency");
+
             WriteKey("BOARDID", i, hh.board_id,
                      "Board ID");
@@ -536,19 +556,19 @@
             WriteKey("TIME",    i, hh.time,      "Time");
             WriteKey("RUNNB",   i, hh.runnumber, "Run number");
-/*
-            for (int j=0;j<NTemp;j++)
-            {
-                str.str(""); str2.str("");
-                str << "DRS_T" << i << j;
-                str2 << "DRS temperature #" << i << " " << j;
-                WriteKey(str.str(), h->FADhead[i].drs_temperature[j], str2.str());
-            }
-*/
+
+//            for (int j=0;j<NTemp;j++)
+//            {
+//                str.str(""); str2.str("");
+//                str << "DRS_T" << i << j;
+//                str2 << "DRS temperature #" << i << " " << j;
+//                WriteKey(str.str(), h->FADhead[i].drs_temperature[j], str2.str());
+//            }
             for (int j=0;j<NDAC;j++)
                 WriteKey("DAC", i*NDAC+j, hh.dac[j], "DAC");
-
-            //Last but not least, add header keys that will be updated when closing the file
-            WriteFooter(NULL);
-        }
+        }
+*/
+
+        //Last but not least, add header keys that will be updated when closing the file
+        //WriteFooter(NULL);
 
         return true;
@@ -556,15 +576,17 @@
 
 
-    int WriteColumns(size_t &start, size_t size, void *e)
+    int WriteColumns(size_t &start, size_t size, const void *e)
     {
         int status = 0;
-        fits_write_tblbytes(fFile->fitsPointer(), fNumRows, start, size, reinterpret_cast<unsigned char*>(e), &status);
+        fits_write_tblbytes(fFile->fitsPointer(), fNumRows, start, size,
+                            (unsigned char*)e, &status);
         if (status)
         {
             char text[30];//max length of cfitsio error strings (from doc)
             fits_get_errstatus(status, text);
-            //ostringstream str;
-            //str << "Writing FITS row " << i << " in " << groupName << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
-            //Error(str);
+
+            ostringstream str;
+            str << "Writing FITS row " << fNumRows << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
+            fLog.Error(str);
         }
 
@@ -587,16 +609,20 @@
         if (fits_insert_rows(fTable->fitsPointer(), fNumRows, 1, &status))
         {
-            //ostringstream str;
-            //str << "Inserting row into " << fFileName << " failed (fits_insert_rows, rc=" << status << ")";
-            //fMess->Error(str);
-            //TODO pipe this error message to the appropriate error stream
+            char text[30];//max length of cfitsio error strings (from doc)
+            fits_get_errstatus(status, text);
+
+            ostringstream str;
+            str << "Inserting row " << fNumRows << " into " << fFileName << ": " << text << " (fits_insert_rows, rc=" << status << ")";
+            fLog.Error(str);
+
+            return false;
         }
         fNumRows++;
 
-        const int sh = sizeof(EVENT)+NPIX*e->Roi*2;
+        const vector<char> data = fConv->ToFits(((char*)e)+2, sizeof(EVENT)+NPIX*e->Roi*2-2);
 
         // column size pointer
         size_t col = 1;
-        if (!WriteColumns(col, sh, e))
+        if (!WriteColumns(col, data.size(), data.data()))
             return true;
 
@@ -673,5 +699,5 @@
             return false;
 
-        WriteFooter(rt);
+        //WriteFooter(rt);
 
         delete fFile;
@@ -759,6 +785,5 @@
 
 
-    int fRunNumber;
-
+    uint32_t fRunNumber;
 
     void InitRunNumber()
@@ -768,5 +793,5 @@
         fRunNumber = 1000;
 
-        while (--fRunNumber>=0)
+        while (--fRunNumber>0)
         {
             ostringstream name;
@@ -813,5 +838,5 @@
             ConnectSlot(i, tcp::endpoint());
 
-        // InitRunNumber();
+        InitRunNumber();
     }
     virtual ~EventBuilderWrapper()
@@ -827,4 +852,10 @@
             delete *it;
     }
+
+    uint32_t IncreaseRunNumber()
+    {
+        return fRunNumber++;
+    }
+
 
     bool IsThreadRunning()
@@ -1076,8 +1107,8 @@
         switch (fFileFormat)
         {
-        case kNone:  file = new DataFileNone(runid);  break;
-        case kDebug: file = new DataFileDebug(runid); break;
-        case kFits:  file = new DataFileFits(runid);  break;
-	case kRaw:   file = new DataFileRaw(runid);   break;
+        case kNone:  file = new DataFileNone(runid, fMsg);  break;
+        case kDebug: file = new DataFileDebug(runid, fMsg); break;
+        case kFits:  file = new DataFileFits(runid, fMsg);  break;
+	case kRaw:   file = new DataFileRaw(runid, fMsg);   break;
         }
 
