Index: /trunk/MagicSoft/Mars/Changelog
===================================================================
--- /trunk/MagicSoft/Mars/Changelog	(revision 2385)
+++ /trunk/MagicSoft/Mars/Changelog	(revision 2386)
@@ -1,3 +1,54 @@
                                                  -*-*- END OF LINE -*-*-
+  2003/10/15: Thomas Bretz
+
+   * Makefile.conf.general:
+     - added libThread to support mona
+     
+   * manalysis/MCerPhotAnal2.cc:
+     - changed comments
+     - accelerated the code a bit by using pointer arithmetic
+     
+   * mbase/BaseLinkDef.h, mbase/Makefile:
+     - added MReadSocket
+
+   * mbase/MReadSocket.[h,cc]:
+     - added MReadSocket
+     
+   * mbase/MEvtLoop.cc:
+     - fixed some crashes in ProcessGuiEvents
+     
+   * mbase/MFilter.cc:
+     - changed header
+     
+   * mbase/MTime.h:
+     - added operator double() 
+
+   * mimage/MHillas.cc:
+     - changed the comments about corrxy
+     
+   * mmain/MStatusDisplay.cc:
+     - added many comments
+     - added kFileClose stuff
+     - added AddRawTab
+     - added thread handling in UpdateTab
+     - fixed deletion in case the pointer is on heap
+     - added date/time to ps-output
+     
+   * mraw/MRawEvtHeader.cc:
+     - added some comments about the total number of bytes read
+     
+   * mraw/MRawRunHeader.[h,cc]:
+     - added some comments about the total number of bytes read
+     - fixed treating files with 0xc0c1 as Magic-Number
+     - added GetNumTotalBytes
+
+   * mraw/Makefile, mraw/RawLinkDef.h:
+     - added MRawSocketRead
+
+   * mraw/MRawSocketRead.[h,cc]:
+     - added
+
+
+
   2003/10/05: Abelardo Moralejo
 
@@ -6,5 +57,6 @@
        version of the macro, sorry!)
 
-  
+
+
   2003/10/02: Thomas Bretz
 
Index: /trunk/MagicSoft/Mars/Makefile.conf.general
===================================================================
--- /trunk/MagicSoft/Mars/Makefile.conf.general	(revision 2385)
+++ /trunk/MagicSoft/Mars/Makefile.conf.general	(revision 2386)
@@ -4,6 +4,6 @@
 
 ROOTVER    =  `root-config --version`
-ROOTLIBS   =  `root-config --libs` -lMinuit -lHistPainter
-ROOTGLIBS  =  `root-config --glibs` -lMinuit -lHistPainter
+ROOTLIBS   =  `root-config --libs` -lMinuit -lHistPainter -lThread
+ROOTGLIBS  =  `root-config --glibs` -lMinuit -lHistPainter -lThread
 ROOTCFLAGS =  `root-config --cflags`
 
Index: /trunk/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc
===================================================================
--- /trunk/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc	(revision 2386)
@@ -24,16 +24,16 @@
 
 //////////////////////////////////////////////////////////////////////////////
-//                                                                          //
-//   MCerPhotAnal2                                                           //
-//                                                                          //
-//   This is a task which calculates the number of photons from the FADC    //
-//   time slices. At the moment it integrates simply the FADC values.       //
-//                                                                          //
-//  Input Containers:                                                       //
-//   MRawEvtData, MPedesdtalCam                                             //
-//                                                                          //
-//  Output Containers:                                                      //
-//   MCerPhotEvt                                                            //
-//                                                                          //
+//
+//   MCerPhotAnal2
+//
+//   This is a task which calculates the number of photons from the FADC
+//   time slices. At the moment it integrates simply the FADC values.
+//
+//  Input Containers:
+//   MRawEvtData, MPedestalCam
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
 //////////////////////////////////////////////////////////////////////////////
 
@@ -134,8 +134,9 @@
     while (pixel.Next())
     {
-        Byte_t max = pixel.GetNumMaxHiGainSample();
-	Byte_t num = fRawEvt->GetNumHiGainSamples();
-
-        Byte_t *ptr = pixel.GetHiGainSamples();
+        Byte_t *ptr   = pixel.GetHiGainSamples();
+        Byte_t *max   = ptr+pixel.GetIdxMaxHiGainSample();
+	Byte_t *end   = ptr+fRawEvt->GetNumHiGainSamples();
+        Byte_t *first = max-fBefore;
+        Byte_t *last  = max+fAfter;
 
         ULong_t sumb  = 0;   // sum background
@@ -147,24 +148,23 @@
         Int_t nb  = 0;
         Int_t nsb = 0;
-        for (int i=0; i<num; i++)
+
+        if (*max==255)
+            sat++;
+
+        while (ptr<end)
         {
-            if (ptr[i]==255)
-                sat++;
-
-            //if (sat>1)
-            //    continue;
-
-            if (i<max-fBefore || i>max+fAfter)
-            {
-                sumb += ptr[i];
-                sqb  += ptr[i]*ptr[i];
+            if (ptr<first || ptr>last)
+            {
+                sumb += *ptr;
+                sqb  += *ptr* *ptr;
                 nb++;
             }
             else
             {
-                sumsb += ptr[i];
-                sqsb  += ptr[i]*ptr[i];
+                sumsb += *ptr;
+                sqsb  += *ptr* *ptr;
                 nsb++;
             }
+            ptr++;
         }
 
@@ -172,8 +172,16 @@
         {
             // Area: x9
-            max = pixel.GetNumMaxLoGainSample();
-            num = fRawEvt->GetNumLoGainSamples();
-
             ptr = pixel.GetLoGainSamples();
+            max = ptr+pixel.GetIdxMaxLoGainSample();
+
+            if (*max>250)
+            {
+                fSkip++;
+                return kCONTINUE;
+            }
+
+            end   = ptr+fRawEvt->GetNumLoGainSamples();
+            first = max-fBefore;
+            last  = max+fAfter;
 
             sumsb = 0;   // sum signal+background
@@ -184,14 +192,10 @@
             //nb = 0;
             nsb = 0;
-            for (int i=0; i<num; i++)
-            {
-                if (ptr[i]>250)
-                {
-                    fSkip++;
-                    return kCONTINUE;
-                }
-                if (i<max-fBefore || i>max+fAfter)
+            while (ptr<end)
+            {
+                if (ptr<first || ptr>last)
                 {
                     /*
+                     // Background already calced from hi-gains!
                     sumb += ptr[i];
                     sqb  += ptr[i]*ptr[i];
@@ -200,8 +204,9 @@
                 else
                 {
-                    sumsb += ptr[i];
-                    sqsb  += ptr[i]*ptr[i];
+                    sumsb += *ptr;
+                    sqsb  += *ptr* *ptr;
                     nsb++;
                 }
+                ptr++;
             }
         }
Index: /trunk/MagicSoft/Mars/mbase/BaseLinkDef.h
===================================================================
--- /trunk/MagicSoft/Mars/mbase/BaseLinkDef.h	(revision 2385)
+++ /trunk/MagicSoft/Mars/mbase/BaseLinkDef.h	(revision 2386)
@@ -14,4 +14,5 @@
 
 #pragma link C++ class MLog+;
+#pragma link C++ class MReadSocket+;
 
 #pragma link C++ class MIter+;
Index: /trunk/MagicSoft/Mars/mbase/MEvtLoop.cc
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MEvtLoop.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mbase/MEvtLoop.cc	(revision 2386)
@@ -168,5 +168,6 @@
 {
     fProgress = bar;
-    fProgress->SetBit(kMustCleanup);
+    if (fProgress)
+        fProgress->SetBit(kMustCleanup);
 }
 
@@ -187,10 +188,8 @@
     MParContainer::SetDisplay(d);
     if (!d)
-    {
         fProgress=NULL;
-        return;
-    }
-
-    d->SetBit(kMustCleanup);
+    else
+        d->SetBit(kMustCleanup);
+
     if (fParList)
         fParList->SetDisplay(d);
@@ -269,5 +268,5 @@
 Bool_t MEvtLoop::ProcessGuiEvents(Int_t num, Int_t entries)
 {
-    if (!fProgress || gROOT->IsBatch())
+    if (gROOT->IsBatch())
         return kTRUE;
 
@@ -286,6 +285,33 @@
             fDisplay->ClearStatus();
             break;
+        //
+        // If the display is not on the heap (means: not created
+        // with the new operator) the object is deleted somewhere
+        // else in the code. It is the responsibility of the
+        // application which instantiated the object to make
+        // sure that the correct action is taken. This can be
+        // done by calling MStatusDisplay::CheckStatus()
+        //
+        // Because we are synchronous we can safely delete it here!
+        //
+        // Close means: Close the display but leave analysis running
+        // Exit means: Close the display and stop analysis
+        //
+        case MStatusDisplay::kFileClose:
+        case MStatusDisplay::kFileExit:
+            rc = fDisplay->CheckStatus() == MStatusDisplay::kFileClose;
+
+            if (fDisplay->IsOnHeap())
+                delete fDisplay;
+
+            //
+            // This makes the display really disappear physically on
+            // the screen in case of MStatusDisplay::kFileClose
+            //
+            gSystem->ProcessEvents();
+
+            return rc;
         default:
-            *fLog << warn << "MEvtloop: fDisplay->ChecStatus() has returned unknown status #" << fDisplay->CheckStatus() << "... cleared." << endl;
+            *fLog << warn << "MEvtloop: fDisplay->CheckStatus() has returned unknown status #" << fDisplay->CheckStatus() << "... cleared." << endl;
             fDisplay->ClearStatus();
             break;
@@ -293,8 +319,8 @@
 
     //
-    // Check System time (don't loose too much time by updates)
-    //
-
-    // FIXME: Not thread safe
+    // Check System time (don't loose too much time by updating the GUI)
+    //
+
+    // FIXME: Not thread safe (if you have more than one eventloop running)
     static Int_t start = num;
     static TTime t1 = gSystem->Now();
@@ -335,5 +361,6 @@
     // Set new progress bar position
     //
-    fProgress->SetPosition(num);
+    if (fProgress)
+        fProgress->SetPosition(num);
 
     //
@@ -346,5 +373,6 @@
         gSystem->ProcessEvents();
     else
-        gClient->ProcessEventsFor(fProgress);
+        if (fProgress)
+            gClient->ProcessEventsFor(fProgress);
 #endif
 
Index: /trunk/MagicSoft/Mars/mbase/MFilter.cc
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MFilter.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mbase/MFilter.cc	(revision 2386)
@@ -16,7 +16,7 @@
 !
 !
-!   Author(s): Thomas Bretz  07/2001 <mailto:tbretz@uni-sw.gwdg.de>
+!   Author(s): Thomas Bretz, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
 !
-!   Copyright: MAGIC Software Development, 2000-2001
+!   Copyright: MAGIC Software Development, 2000-2003
 !
 !
Index: /trunk/MagicSoft/Mars/mbase/MReadSocket.cc
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MReadSocket.cc	(revision 2386)
+++ /trunk/MagicSoft/Mars/mbase/MReadSocket.cc	(revision 2386)
@@ -0,0 +1,184 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MReadSocket
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReadSocket.h"
+
+/*
+ #ifdef _REENTRANT
+ #include <pthread.h>
+ #endif
+*/
+
+#include <unistd.h>          // usleep
+
+#include <TMath.h>           // TMath::Min
+#include <TTime.h>           // TTime
+#include <TDatime.h>         // TDatime
+#include <TSystem.h>         // gSystem
+#include <TSocket.h>         // TSocket
+#include <TServerSocket.h>   // TServerSocket
+
+ClassImp(MReadSocket);
+
+using namespace std;
+
+MReadSocket::MReadSocket(int port, int mtu) : istream(this), fMtu(mtu), fTimeout(2500), fServSock(NULL), fRxSocket(NULL)
+{
+    fBuffer = new char[mtu];
+
+    setg(fBuffer, fBuffer, fBuffer+1);
+
+    cout << "Starting server socket on port 7000..." << endl;
+
+    while (1)
+    {
+        fServSock=new TServerSocket(port, kTRUE);
+        if (fServSock->IsValid())
+            break;
+
+        cout << "ServerSocket not valid: ";
+        switch (fServSock->GetErrorCode())
+        {
+        case 0: cout << "No error." << endl; break;
+        case -1: cout << "low level socket() call failed." << endl; break;
+        case -2: cout << "low level bind() call failed." << endl; break;
+        case -3: cout << "low level listen() call failed." << endl; break;
+        default: cout << "Unknown." << endl; break;
+        }
+
+        delete fServSock;
+        fServSock=NULL;
+        break;
+    }
+    if (!fServSock)
+    {
+        cout << "MReadSocket: TServerSocket - Connection timed out." << endl;
+        setstate(ios::failbit);
+        return;
+    }
+
+    fServSock->SetOption(kNoBlock, 1);
+
+    while (1)
+    {
+        const TTime timeout = gSystem->Now() + TTime(5000);
+
+        TDatime now;
+        cout << now.AsString() << ": Waiting for conntection on port 7000..." << endl;
+        fRxSocket = NULL;
+        while ((Long_t)fRxSocket<=0 && gSystem->Now()<timeout)
+        {
+            fRxSocket = fServSock->Accept();
+            if (fRxSocket==0)
+                cout << "Error: TServerSock::Accept" << endl;
+            usleep(1);
+        }
+
+        if ((Long_t)fRxSocket<=0)
+            continue;
+
+        if (fRxSocket->IsValid())
+            break;
+
+        cout << "TSocket: Connection not valid..." << endl;
+        delete fRxSocket;
+    }
+
+    if ((Long_t)fRxSocket<=0)
+    {
+        cout << "MReadSocket: TServerSocket::Accept - Connection timed out." << endl;
+        fRxSocket=NULL;
+        setstate(ios::failbit);
+        return;
+    }
+
+    cout << "Connection established..." << endl;
+
+    fRxSocket->SetOption(kNoBlock, 1);
+
+    underflow();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor, destroying the gui mutex.
+//
+MReadSocket::~MReadSocket()
+{
+    if (fRxSocket)
+        delete fRxSocket;
+    if (fServSock)
+        delete fServSock;
+
+    delete fBuffer;
+
+    cout << "Connection on Port 7000 closed." << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// This is called to flush the buffer of the streaming devices
+//
+int MReadSocket::sync()
+{
+    cout << "sync" << endl;
+    return 0;
+}
+
+int MReadSocket::underflow()
+{
+    //
+    // This simple trick should do its job, because the
+    // TCP/IP stream is buffered already
+    //
+    const TTime timeout = fTimeout+gSystem->Now();
+
+    Int_t l, len=-1;
+    while (len<0 && gSystem->Now()<timeout)
+    {
+        fRxSocket->GetOption(kBytesToRead, l);
+        if (l==0)
+        {
+            usleep(1);
+            continue;
+        }
+        len = fRxSocket->RecvRaw(fBuffer, TMath::Min(fMtu, l));
+    }
+
+    if (len<0)
+    {
+        cout << "MReadSocket: TSocket::RecvRaw - Connection timed out." << endl;
+        setstate(ios::failbit);
+    }
+
+    setg(fBuffer, fBuffer, fBuffer+len);
+    return 0;
+}
+
Index: /trunk/MagicSoft/Mars/mbase/MReadSocket.h
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MReadSocket.h	(revision 2386)
+++ /trunk/MagicSoft/Mars/mbase/MReadSocket.h	(revision 2386)
@@ -0,0 +1,42 @@
+#ifndef MARS_MReadSocket
+#define MARS_MReadSocket
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+#ifndef ROOT_TTime
+#include <TTime.h>
+#endif
+
+#include <iostream>  // base classes for MReadSocket
+
+class TSocket;
+class TServerSocket;
+
+class MReadSocket : public std::streambuf, public std::istream
+{
+private:
+    char *fBuffer; //!
+
+    int   fMtu;
+    TTime fTimeout;
+
+    TServerSocket  *fServSock;
+    TSocket        *fRxSocket;
+
+    int underflow();
+    int sync();
+
+public:
+    MReadSocket(int port, int mtu=1500);
+    MReadSocket(MReadSocket const& log) : istream((std::streambuf*)&log)
+    {
+    }
+    ~MReadSocket();
+
+    void SetTimeout(UInt_t millisec) { fTimeout = millisec; }
+
+    ClassDef(MReadSocket, 0) // This is what we call 'The logging system'
+};
+
+#endif
Index: /trunk/MagicSoft/Mars/mbase/MTime.h
===================================================================
--- /trunk/MagicSoft/Mars/mbase/MTime.h	(revision 2385)
+++ /trunk/MagicSoft/Mars/mbase/MTime.h	(revision 2386)
@@ -108,4 +108,9 @@
     }
 
+    operator double() const //[s]
+    {
+        return fNanoSec/1e9+(fHour*24*60*60+fMin*60+fSec);
+    }
+
     ClassDef(MTime, 1)	//A generalized MARS time stamp
 };
Index: /trunk/MagicSoft/Mars/mbase/Makefile
===================================================================
--- /trunk/MagicSoft/Mars/mbase/Makefile	(revision 2385)
+++ /trunk/MagicSoft/Mars/mbase/Makefile	(revision 2386)
@@ -44,4 +44,5 @@
            MEvtLoop.cc \
            MIter.cc \
+           MReadSocket.cc \
            MDirIter.cc \
            MGList.cc \
Index: /trunk/MagicSoft/Mars/mimage/MHillas.cc
===================================================================
--- /trunk/MagicSoft/Mars/mimage/MHillas.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mimage/MHillas.cc	(revision 2386)
@@ -277,10 +277,10 @@
 
     //
-    // If corrxy=0 (which should never happen, because fSize>0) we
-    // cannot calculate Length and Width. The calculation failed
-    // and returns kFALSE
-    // In reallity it is almost impossible to have a distribution
-    // of cerenkov photons in the used pixels which is exactly symmetric
+    // If corrxy=0 (which should happen not very often, because fSize>0)
+    // we cannot calculate Length and Width.
+    // In reallity it is almost impossible to have a distribution of
+    // cerenkov photons in the used pixels which is exactly symmetric
     // along one of the axis.
+    // It seems to be less than 0.1% of all events.
     //
     if (corrxy==0)
Index: /trunk/MagicSoft/Mars/mmain/MStatusDisplay.cc
===================================================================
--- /trunk/MagicSoft/Mars/mmain/MStatusDisplay.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mmain/MStatusDisplay.cc	(revision 2386)
@@ -75,4 +75,5 @@
 #include <TObjArray.h>            // TObjArray
 #include <TPostScript.h>          // TPostScript
+#include <TInterpreter.h>         // gInterpreter
 
 #include <TGTab.h>                // TGTab
@@ -186,4 +187,5 @@
     //filemenu->AddEntry("Set printer &name",    kFilePrinterName);
     filemenu->AddSeparator();
+    filemenu->AddEntry("C&lose", kFileClose);
     filemenu->AddEntry("E&xit", kFileExit);
     filemenu->Associate(this);
@@ -507,8 +509,17 @@
 : TGMainFrame(gClient ? gClient->GetRoot() : NULL, 1, 1), fTimer(this, t, kTRUE), fStatus(kLoopNone), fLog(&gLog), fLogIdx(-1), fLogTimer(this, 250, kTRUE), fLogBox(NULL), fIsLocked(0)
 {
+    //
+    // This is a possibility for the user to check whether this
+    // object has already been deleted. It will be removed
+    // from the list in the destructor.
+    //
     gROOT->GetListOfSpecials()->Add(this);
 
     fFont = gVirtualX->LoadQueryFont("7x13bold");
 
+    //
+    // In case we are in batch mode use a list of canvases
+    // instead of the Root Embedded Canvases in the TGTab
+    //
     fBatch = new TList;
     fBatch->SetOwner();
@@ -566,11 +577,33 @@
 MStatusDisplay::~MStatusDisplay()
 {
+    //
+    // Delete object from global object table so it cannot
+    // be deleted by chance a second time
+    //
+    gInterpreter->DeleteGlobal(this);
+
+    //
+    // This is a possibility for the user to check whether this
+    // object has already been deleted. It has been added
+    // to the list in the constructor.
+    //
     gROOT->GetListOfSpecials()->Remove(this);
 
     SetLogStream(NULL);
 
+    //
+    // Delete the list of objects corresponding to this object
+    //
     delete fList;
+
+    //
+    // Delete the list list of canvases used in batch mode
+    // instead of the Root Embedded Canvases in the TGTab
+    //
     delete fBatch;
 
+    //
+    // Delete the font used for the logging window
+    //
     if (fFont)
         gVirtualX->DeleteFont(fFont);
@@ -671,4 +704,41 @@
 }
 
+/*
+class MCanvas : public TRootEmbeddedCanvas
+{
+public:
+    MCanvas(const char* name, const TGWindow* p, UInt_t w, UInt_t h, UInt_t o) :
+              TRootEmbeddedCanvas(name, p, w, h, o) {}
+              void Layout()
+              {
+                  cout << "EmbLayout: " << GetCanvas()->GetName() << endl;
+
+                  // Create layout for canvas. Depending on the size of the container
+                  // we need to add the scrollbars.
+                  TRootEmbeddedCanvas::Layout();
+              }
+};
+*/
+
+TGCompositeFrame *MStatusDisplay::AddRawTab(const char *name)
+{
+    // Add new tab
+    TGCompositeFrame *f = fTab->AddTab(name);
+
+    // layout and map new tab
+    Layout();
+    MapSubwindows();
+    Layout();
+
+    // display new tab in the main frame
+    gClient->ProcessEventsFor(fTab);
+
+    *fLog << inf << "Adding Raw Tab '" << name << "' (" << f->GetWidth() << "x";
+    *fLog << f->GetHeight() << ")" << endl;
+
+    // return pointer to new canvas
+    return f;
+}
+
 // --------------------------------------------------------------------------
 //
@@ -688,5 +758,5 @@
     TGCompositeFrame *f = fTab->AddTab(name);
 
-    // create root emb 0edded canvas and add it to the tab
+    // create root embedded canvas and add it to the tab
     TRootEmbeddedCanvas *ec = new TRootEmbeddedCanvas(name, f, f->GetWidth(), f->GetHeight(), 0);
     f->AddFrame(ec, fLayCanvas);
@@ -723,4 +793,5 @@
 }
 
+
 // --------------------------------------------------------------------------
 //
@@ -737,8 +808,19 @@
         return;
 
-    // Code taken from TCanvas::Update() and TCanvas::Paint
-    c->FeedbackMode(kFALSE);  // Goto double buffer mode
-    c->Paint();               // Repaint all pad's
-    c->Flush();               // Copy all pad pixmaps to the screen
+    // Code taken from TCanvas::Update() and TCanvas::Paint()
+    // replaces PaintModified() by Paint()
+    if (gThreadXAR)
+    {
+        void *arr[2] = { NULL, c };
+        if (((*gThreadXAR)("CUPD", 2, arr, NULL)))
+            return;
+    }
+
+    if (!c->IsBatch())
+        c->FeedbackMode(kFALSE);  // Goto double buffer mode
+
+    c->Paint();                   // Repaint all pads
+    c->Flush();                   // Copy all pad pixmaps to the screen
+
     //c->SetCursor(kCross);
 
@@ -871,7 +953,8 @@
     {
     case kLoopStop:
+    case kFileClose:
     case kFileExit:
-        if (id==kFileExit)
-            delete this;
+        if (id==kFileExit || id==kFileClose)
+            CloseWindow();
         fStatus = (Status_t)id;
         return kTRUE;
@@ -1029,8 +1112,11 @@
         return ProcessMessageCommandMenu(mp1); // mp2=userdata
     case kCM_TAB:
-        for (int i=1; i<fTab->GetNumberOfTabs(); i++)
-            fTab->GetTabContainer(i)->UnmapWindow();
+        /*
+         for (int i=0; i<fTab->GetNumberOfTabs(); i++)
+         fTab->GetTabContainer(i)->UnmapWindow();
+         */
         UpdateTab(fTab->GetTabContainer(mp1));
-        fTab->GetTabContainer(mp1)->MapWindow();
+        //fTab->GetTabContainer(mp1)->MapWindow();
+
         /*
         if (mp1>0)
@@ -1187,5 +1273,13 @@
     // and the destructor are calling DestroyWindow which seems to be
     // in conflict with the TRootEmbeddedCanvas.
-    delete this;
+
+    // FIXME: Make sure that the Status Display is deleted from every
+    //        where (eg Eventloop) first!
+
+    gLog << dbg << "MStatusDisplay is on heap: " << (int)IsOnHeap() << endl;
+
+    if (fIsLocked<=0 && IsOnHeap())
+        delete this;
+    fStatus = kFileExit;
 }
 
@@ -1201,4 +1295,5 @@
 
     flag ? SetBit(kNoContextMenu) : ResetBit(kNoContextMenu);
+
     for (int i=1; i<fTab->GetNumberOfTabs(); i++)
     {
@@ -1563,4 +1658,6 @@
     TVirtualPS *psave  = gVirtualPS;
 
+    TDatime d;
+
     TPostScript ps(name, 112);
     ps.SetBit(TPad::kPrintingPS);
@@ -1608,6 +1705,10 @@
         ps.NewPage();
 
-        Float_t psw = 26; // A4 - width
-        Float_t psh = 20; // A4 - height
+        //
+        // 26 is used here to scale the canvas into a height of 26,
+        // such that the page title can be set above the canvas...
+        //
+        Float_t psw = 26; //29.7; // A4 - width
+        Float_t psh = 21.0; // A4 - height
 
         const Float_t cw = c->GetWw();
@@ -1655,5 +1756,5 @@
         ps.TextNDC(0, 1.02, TString("  ")+n->GetName());
         ps.SetTextAlign(21); // cent top
-        ps.TextNDC(0.5, 1.02, "MARS - Magic Analysis and Reconstruction Software");
+        ps.TextNDC(0.5, 1.02, TString("MARS - Magic Analysis and Reconstruction Software - ")+d.AsString());
         ps.SetTextAlign(31); // right top
         ps.TextNDC(1, 1.02, Form("Page No.%i (%i)  ", page++, i));
Index: /trunk/MagicSoft/Mars/mona.cc
===================================================================
--- /trunk/MagicSoft/Mars/mona.cc	(revision 2386)
+++ /trunk/MagicSoft/Mars/mona.cc	(revision 2386)
@@ -0,0 +1,161 @@
+#include <TROOT.h>
+#include <TApplication.h>
+
+#include <TThread.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MLogManip.h"
+
+#include "MRawSocketRead.h"
+#include "MGeomApply.h"
+#include "MCerPhotAnal2.h"
+#include "MFillH.h"
+#include "MFRealTimePeriod.h"
+#include "MOnlineDump2.h"
+#include "MHTriggerLvl0.h"
+
+#include "MStatusDisplay.h"
+
+#include "MImgCleanStd.h"
+#include "MHillasCalc.h"
+#include "MHillasSrcCalc.h"
+
+void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    gLog << "==================================================" << endl;
+    gLog << "                    MONA V" << MARSVER << "                      " << endl;
+    gLog << "              Magic Online Analysis               " << endl;
+    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
+    gLog << "               Using ROOT v" << ROOTVER             << endl;
+    gLog << "==================================================" << endl;
+    gLog << endl;
+}
+
+Bool_t Loop(MStatusDisplay *display)
+{
+    //
+    // create the tasks which should be executed and add them to the list
+    // in the case you don't need parameter containers, all of them can
+    // be created by MRawFileRead::PreProcess
+    //
+    MRawSocketRead reader;
+
+    //
+    // create a (empty) list of parameters which can be used by the tasks
+    // and an (empty) list of tasks which should be executed
+    //
+    MParList plist;
+
+    MTaskList tasks;
+    plist.AddToList(&tasks);
+    tasks.AddToList(&reader);
+
+    //MParList &plist = *(MParList*)ptr;
+    //MTaskList &tasks = *(MTaskList*)plist.FindObject("MTaskList");
+
+    MGeomApply geomapl;
+    MCerPhotAnal2 ncalc;
+    tasks.AddToList(&geomapl);
+    tasks.AddToList(&ncalc);
+
+    MFillH fill1("MHCamEvent", "MCerPhotEvt");
+    MFillH fill2("MHEvent",    "MCerPhotEvt");
+
+    MHTriggerLvl0 trigmap(128, "Above 128");
+    MFillH fill3(&trigmap, "MRawEvtData");
+
+    MFRealTimePeriod filter;
+    fill2.SetFilter(&filter);
+
+    fill1.SetName("MFillCamEvent");
+    fill2.SetName("MFillEvent");
+    fill3.SetName("MFillTriggerLvl0");
+
+    tasks.AddToList(&fill2);
+    tasks.AddToList(&filter);
+    tasks.AddToList(&fill1);
+    tasks.AddToList(&fill3);
+
+    MOnlineDump2 dump;
+    dump.SetFilter(&filter);
+    tasks.AddToList(&dump);
+
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+    MFillH hfill3("MHHillas", "MHillas");
+    MFillH hfill6("MHHillasSrc","MHillasSrc");
+    tasks.AddToList(&clean);
+    tasks.AddToList(&hcalc);
+    tasks.AddToList(&scalc);
+    tasks.AddToList(&hfill3);
+    tasks.AddToList(&hfill6);
+
+    MEvtLoop magic;
+    //plist.AddToList(&magic);
+    magic.SetParList(&plist);
+
+    magic.SetDisplay(display);
+
+    if (!magic.Eventloop())
+    {
+        gLog << err << "Mona Eventloop error..." << endl;
+        return kFALSE;
+    }
+
+    tasks.PrintStatistics();
+    return kTRUE;
+}
+
+void *thread(void *ptr)
+{
+    // TThread::SetCancelAsynchronous();
+    // TThread::SetCancelOn();
+    MStatusDisplay *display=(MStatusDisplay*)ptr;
+//    display->Lock();
+
+    //
+    // If a loop is stopped reinitialize a new loop until the
+    // user requested to exit the program.
+    //
+    while (display->CheckStatus()!=MStatusDisplay::kFileExit)
+        Loop(display);
+
+    gLog << dbg << "Exit System Loop... " << flush;
+    gSystem->ExitLoop();
+    gLog << "done." << endl;
+
+    return 0;
+}
+
+int main(int argc, char **argv)
+{
+    TROOT simple("mona", "Magic ONline Analysis");
+    TApplication app("MonaApp", &argc, argv);
+
+    StartUpMessage();
+
+    //
+    // Starting MStatusDisplay in the thread results in hangs
+    // if the thread is terminated (by return)
+    //
+    MStatusDisplay d;
+    d.Resize(740, 600);
+
+    gLog << dbg << "Starting Thread..." << endl;
+    TThread t(thread, &d);
+    t.Run();
+
+    gLog << dbg << "Starting System loop..." << endl;
+    app.Run(kTRUE);
+    gLog << dbg << "System loop stopped." << endl;
+
+    return 0;
+}
Index: /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 2386)
@@ -237,8 +237,8 @@
 int MRawEvtHeader::ReadEvt(istream &fin)
 {
-    fin.read((char*)&fDAQEvtNumber, 4);
+    fin.read((char*)&fDAQEvtNumber, 4);  // Total=4
 
     UInt_t fAbsTime[2];
-    fin.read((char*)fAbsTime,       8);
+    fin.read((char*)fAbsTime,       8);  // Total=12
 
     //
@@ -246,9 +246,9 @@
     //
     const Double_t mhz = 9.375;                          // [1e6 ticks/s]
-    const Double_t t   = (Double_t)fAbsTime[0]/mhz*1e-3; // [ns]
-    const UShort_t ns  = (UShort_t)fmod(t, 1e9);
-    const Byte_t s     = (Byte_t)fmod(t/1e9, 60);
-    const Byte_t m     = (Byte_t)fmod(t/60e9, 60);
-    const Byte_t h     = (Byte_t)(t/3600e9);
+    const Double_t t   = (Double_t)fAbsTime[0]/mhz;      // [ns]
+    const UShort_t ns  = (UShort_t)fmod(t*1e-3, 1e9);
+    const Byte_t s     = (Byte_t)fmod(t/1e12, 60);
+    const Byte_t m     = (Byte_t)fmod(t/60e12, 60);
+    const Byte_t h     = (Byte_t)(t/3600e12);
 
     fTime->SetTime(h, m, s, ns);
@@ -257,9 +257,9 @@
     Byte_t dummy[4];
 
-    fin.read((char*)&fNumTrigLvl1,  4);
-    fin.read((char*)&fNumTrigLvl2,  4);
-    fin.read((char*)fTrigPattern,   8);
-    fin.read((char*)&fTrigType,     2);
-    fin.read((char*)dummy,          2); // was fAllLoGainOn
+    fin.read((char*)&fNumTrigLvl1,  4);  // Total=16
+    fin.read((char*)&fNumTrigLvl2,  4);  // Total=20
+    fin.read((char*)fTrigPattern,   8);  // Total=28
+    fin.read((char*)&fTrigType,     2);  // Total=30
+    fin.read((char*)dummy,          2);  // Total=32, was fAllLoGainOn
     fin.read((char*)fPixLoGainOn->GetArray(), fPixLoGainOn->GetSize());
 
Index: /trunk/MagicSoft/Mars/mraw/MRawRunHeader.cc
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawRunHeader.cc	(revision 2385)
+++ /trunk/MagicSoft/Mars/mraw/MRawRunHeader.cc	(revision 2386)
@@ -94,5 +94,7 @@
     // read one RUN HEADER from the input stream
     //
-    fin.read((char*)&fMagicNumber, 2);
+    fMagicNumber = 0;
+
+    fin.read((char*)&fMagicNumber, 2);          // Total=2
 
     //
@@ -101,32 +103,32 @@
     if (fMagicNumber != kMagicNumber && fMagicNumber != kMagicNumber+1)
     {
-        *fLog << err << "Error: Wrong Magic Number: Not a Magic File!" << endl;
+        *fLog << err << "Error: Wrong Magic Number (0x" << hex << fMagicNumber << "): Not a Magic File!" << endl;
         return;
     }
 
-    if (fMagicNumber == kMagicNumber && fMagicNumber != kMagicNumber+1)
+    if (fMagicNumber == kMagicNumber+1)
         *fLog << warn << "WARNING - This file maybe broken (0xc0c1) - DAQ didn't close it correctly!" << endl;
 
     Byte_t dummy[16];
 
-    fin.read((char*)&fFormatVersion,    2);
-    fin.read((char*)&fSoftVersion,      2);
-    fin.read((char*)&fRunType,          2);
-    fin.read((char*)&fRunNumber,        4);
-    fin.read((char*)&fProjectName,     22);
-    fin.read((char*)&fSourceName,      12);
+    fin.read((char*)&fFormatVersion,    2);     // Total=4
+    fin.read((char*)&fSoftVersion,      2);     // Total=6
+    fin.read((char*)&fRunType,          2);     // Total=8
+    fin.read((char*)&fRunNumber,        4);     // Total=12
+    fin.read((char*)&fProjectName,     22);     // Total=34
+    fin.read((char*)&fSourceName,      12);     // Total=46
     fin.read((char*)dummy,              4); // was RA  (moved to tracking system)
     fin.read((char*)dummy,              4); // was DEC (moved to tracking system)
-    fin.read((char*)&fSourceEpochChar,  2);
-    fin.read((char*)&fSourceEpochDate,  2);
-    fin.read((char*)&fMJD,              4);
-    fin.read((char*)&fDateYear,         2);
-    fin.read((char*)&fDateMonth,        2);
-    fin.read((char*)&fDateDay,          2);
-    fin.read((char*)&fNumCrates,        2);
-    fin.read((char*)&fNumPixInCrate,    2);
-    fin.read((char*)&fNumSamplesLoGain, 2);
-    fin.read((char*)&fNumSamplesHiGain, 2);
-    fin.read((char*)&fNumEvents,        4);
+    fin.read((char*)&fSourceEpochChar,  2);     // Total=56
+    fin.read((char*)&fSourceEpochDate,  2);     // Total=58
+    fin.read((char*)&fMJD,              4);     // Total=62
+    fin.read((char*)&fDateYear,         2);     // Total=64
+    fin.read((char*)&fDateMonth,        2);     // Total=66
+    fin.read((char*)&fDateDay,          2);     // Total=68
+    fin.read((char*)&fNumCrates,        2);     // Total=70
+    fin.read((char*)&fNumPixInCrate,    2);     // Total=72
+    fin.read((char*)&fNumSamplesLoGain, 2);     // Total=74
+    fin.read((char*)&fNumSamplesHiGain, 2);     // Total=76
+    fin.read((char*)&fNumEvents,        4);     // Total=80
 
 
@@ -148,5 +150,12 @@
 {
     *fLog << all << endl;
-    *fLog << "MagicNumber:  0x" << hex << fMagicNumber << " - " << (fMagicNumber==kMagicNumber?"OK":"Wrong!") << endl;
+    *fLog << "MagicNumber:  0x" << hex << fMagicNumber << " - ";
+    switch (fMagicNumber)
+    {
+    case kMagicNumber:   *fLog << "OK";               break;
+    case kMagicNumber+1: *fLog << "File not closed!"; break;
+    default:             *fLog << "Wrong!";           break;
+    }
+    *fLog << endl;
     *fLog << "Version:      " << dec << "Format=" << fFormatVersion << "  ";
     *fLog << "Software=" << fSoftVersion << endl;
@@ -213,2 +222,13 @@
     return fPixAssignment->GetSize();
 }
+
+// --------------------------------------------------------------------------
+//
+// Returns absolute size in bytes of the run header as read from a raw file.
+// This must be done _after_ the header is read, because the header doesn't
+// have a fixed size (used in MRawSocketRead)
+//
+Int_t MRawRunHeader::GetNumTotalBytes() const
+{
+    return 80+fNumCrates*fNumPixInCrate*2+16;
+}
Index: /trunk/MagicSoft/Mars/mraw/MRawRunHeader.h
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawRunHeader.h	(revision 2385)
+++ /trunk/MagicSoft/Mars/mraw/MRawRunHeader.h	(revision 2386)
@@ -104,4 +104,5 @@
 
     UShort_t GetNumPixel() const;
+    Int_t GetNumTotalBytes() const;
 
     void Print(Option_t *t=NULL) const;
Index: /trunk/MagicSoft/Mars/mraw/MRawSocketRead.cc
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawSocketRead.cc	(revision 2386)
+++ /trunk/MagicSoft/Mars/mraw/MRawSocketRead.cc	(revision 2386)
@@ -0,0 +1,290 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that copyright notice and this permission notice appear
+! * in supporting documentation. It is provided "as is" without express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MRawSocketRead                                                            //
+//                                                                          //
+//  This tasks reads the raw binary file like specified in the TDAS???      //
+//  and writes the data in the corresponding containers which are           //
+//  either retrieved from the parameter list or created and added.          //
+//                                                                          //
+//  Input Containers:                                                       //
+//   -/-                                                                    //
+//                                                                          //
+//  Output Containers:                                                      //
+//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawCrateArray, MRawEvtTime //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawSocketRead.h"
+
+#include <TMutex.h>
+
+#include "MReadSocket.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MTime.h"
+#include "MRawRunHeader.h"
+#include "MRawEvtHeader.h"
+#include "MRawEvtData.h"
+#include "MRawCrateData.h"
+#include "MRawCrateArray.h"
+
+ClassImp(MRawSocketRead);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It tries to open the given file.
+//
+MRawSocketRead::MRawSocketRead(const char *name, const char *title)
+    : fIn(NULL)
+{
+    fName  = name  ? name  : "MRawSocketRead";
+    fTitle = title ? title : "Task to read DAQ binary data from tcp/ip socket";
+
+    fIn = new MReadSocket(7000);
+    fMutex = new TMutex;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawSocketRead::~MRawSocketRead()
+{
+    delete fMutex;
+    delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess of this task checks for the following containers in the
+// list:
+//   MRawRunHeader <output>   if not found it is created
+//   MRawEvtHeader <output>   if not found it is created
+//   MRawEvtData <output>     if not found it is created
+//   MRawCrateArray <output>  if not found it is created
+//   MRawEvtTime <output>     if not found it is created (MTime)
+//
+// If all containers are found or created the run header is read from the
+// binary file and printed.  If the Magic-Number (file identification)
+// doesn't match we stop the eventloop.
+//
+// Now the EvtHeader and EvtData containers are initialized.
+//
+Int_t MRawSocketRead::PreProcess(MParList *pList)
+{
+    //
+    //  check if all necessary containers exist in the Parameter list.
+    //  if not create one and add them to the list
+    //
+    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
+    if (!fRawRunHeader)
+        return kFALSE;
+
+    fRawEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
+    if (!fRawEvtHeader)
+        return kFALSE;
+
+    fRawEvtData = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
+    if (!fRawEvtData)
+        return kFALSE;
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindCreateObj("MRawCrateArray");
+    if (!fRawCrateArray)
+        return kFALSE;
+
+    fRawEvtTime = (MTime*)pList->FindCreateObj("MTime", "MRawEvtTime");
+    if (!fRawEvtTime)
+        return kTRUE;
+
+    fParList = pList;
+    fRunNumber = (UInt_t)-1;
+    fEvtNumber = (UInt_t)-1;
+
+    /*
+    MEvtLoop *loop=(MEvtLoop*)pList->FindObject("Evtloop");
+    if (loop)
+        loop->SetProgressBar((TGProgressBar*)NULL);
+     */
+    return kTRUE;
+}
+
+Int_t MRawSocketRead::Do()
+{
+    /*
+    sprintf(report_str, " %8.8d %8.8d %6.6d",
+    run_header->RunNumber, run.event_number,
+    time.tv_sec - run.time_start_secs);
+    if (send(sd, report_str, strlen(report_str), flags) == -1) {
+    return -1;
+    }
+
+    sprintf(report_str, " %6.1f %6.1f %6.6d %7.4f %8.8d %6.6d ",
+    trigrate_hz, storerate_hz, storerate_kbps, gammarate_hz,
+    diskspace_kb, remtime_sec);
+    if (send(sd, report_str, strlen(report_str), flags) == -1) {
+    return -1;
+    }
+    */
+    char dummy[126];
+    fIn->read(dummy, 4);   // \nEVT
+
+    if (!(dummy[0]=='\n' && dummy[1]=='E' && dummy[2]=='V' &&dummy[3]=='T'))
+    {
+        *fLog << warn << "EVT tag not found. Stream out of sync. Please try to restart..." << endl;
+        // FIXME: Synchronization missing...
+        return kFALSE;
+    }
+
+    char size[6] = {0,0,0,0,0,0};
+    fIn->read(size, 5);
+    fIn->read(dummy, 126); //00000[CC-DATA]\n
+
+    /*
+    int numevt;
+    sscanf(dummy,  "%*s %*d %*d %*d %*d %*d %*d %*d "
+           "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
+           "%d %*d %*f %*f %*d %*f %*d %*d", &numevt);
+    */
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    fLog->SetNullOutput();
+    fRawRunHeader->ReadEvt(*fIn);
+    fLog->SetNullOutput(kFALSE);
+
+    if (fRawRunHeader->GetMagicNumber()!=kMagicNumber && fRawRunHeader->GetMagicNumber()!=kMagicNumber+1)
+    {
+        *fLog << err << "Error: Wrong Magic Number (0x" << hex << fRawRunHeader->GetMagicNumber() << "): Not a Magic File!" << endl;
+        return kFALSE;
+    }
+
+    if (fRunNumber!=fRawRunHeader->GetRunNumber())
+    {
+        fRawRunHeader->Print();
+
+        MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
+        if (!tlist)
+        {
+            *fLog << err << dbginf << "ERROR - Task List not found in Parameter List." << endl;
+            return kFALSE;
+        }
+
+        if (!tlist->ReInit())
+            return kFALSE;
+
+        fRunNumber = fRawRunHeader->GetRunNumber();
+    }
+
+    if (atoi(size)==fRawRunHeader->GetNumTotalBytes())
+        return kCONTINUE;
+
+    //
+    // Give the run header information to the 'sub-classes'
+    //
+    fRawEvtHeader->Init(fRawRunHeader, fRawEvtTime);
+    fRawEvtData  ->Init(fRawRunHeader);
+
+    //
+    //  Read in the next EVENT HEADER (see specification),
+    // if there is no next event anymore stop eventloop
+    //
+    if (!fRawEvtHeader->ReadEvt(*fIn))
+        return kFALSE;
+
+    //
+    //  Get number of crates from the run header
+    //
+    const UShort_t nc = fRawRunHeader->GetNumCrates();
+
+    //
+    // Delete arrays which stores the pixel information (time slices)
+    //
+    fRawEvtData->ResetPixels();
+
+    //
+    // clear the TClonesArray which stores the Crate Information
+    // and create a new array of the correct size
+    //
+    fRawCrateArray->SetSize(nc);
+
+    //
+    // read the CRATE DATA (see specification) from file
+    //
+    for (int i=0; i<nc; i++)
+    {
+        fRawCrateArray->GetEntry(i)->ReadEvt(*fIn);
+        if (!*fIn)
+            return kFALSE;
+
+        fRawEvtData->ReadEvt(*fIn);
+        if (!*fIn)
+            return kFALSE;
+    }
+
+    if (fEvtNumber==fRawEvtHeader->GetDAQEvtNumber())
+        return kCONTINUE;
+
+    fEvtNumber=fRawEvtHeader->GetDAQEvtNumber();
+
+    //*fLog << dbg << "Evt " << fRawEvtHeader->GetDAQEvtNumber() << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// The Process reads one event from the binary file:
+//  - The event header is read
+//  - the run header is read
+//  - all crate information is read
+//  - the raw data information of one event is read
+//
+Int_t MRawSocketRead::Process()
+{
+    Lock();
+    Int_t rc = Do();
+    UnLock();
+    return rc;
+}
+
+Int_t MRawSocketRead::Lock()
+{
+    return fMutex->Lock();
+}
+
+Int_t MRawSocketRead::UnLock()
+{
+    return fMutex->UnLock();
+}
Index: /trunk/MagicSoft/Mars/mraw/MRawSocketRead.h
===================================================================
--- /trunk/MagicSoft/Mars/mraw/MRawSocketRead.h	(revision 2386)
+++ /trunk/MagicSoft/Mars/mraw/MRawSocketRead.h	(revision 2386)
@@ -0,0 +1,53 @@
+#ifndef MARS_MRawSocketRead
+#define MARS_MRawSocketRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+// gcc 3.2
+//class ifstream;
+#include <iosfwd>
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawEvtData;
+class MRawCrateArray;
+class MReadSocket;
+class TMutex;
+
+class MRawSocketRead : public MTask
+{
+private:
+    MRawRunHeader  *fRawRunHeader;  // run header information container to fill from file
+    MRawEvtHeader  *fRawEvtHeader;  // event header information container to fill from file
+    MRawEvtData    *fRawEvtData;    // raw evt header infomation container to fill from file
+    MRawCrateArray *fRawCrateArray; // crate information array container to fill from file
+    MTime          *fRawEvtTime;    // raw evt time information container to fill from file
+
+    TMutex *fMutex;
+
+    MReadSocket    *fIn;            //! buffered input stream (file to read from)
+    MParList       *fParList;       //!
+
+    UInt_t          fRunNumber;     //!
+    UInt_t          fEvtNumber;     //!
+
+    Int_t Do();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MRawSocketRead(const char *name=NULL, const char *title=NULL);
+    ~MRawSocketRead();
+
+    Int_t Lock();
+    Int_t UnLock();
+
+    ClassDef(MRawSocketRead, 0)	//Task to read DAQ binary data from tcp/ip socket
+};
+
+#endif
Index: /trunk/MagicSoft/Mars/mraw/Makefile
===================================================================
--- /trunk/MagicSoft/Mars/mraw/Makefile	(revision 2385)
+++ /trunk/MagicSoft/Mars/mraw/Makefile	(revision 2386)
@@ -34,6 +34,7 @@
 	   MRawCrateArray.cc \
 	   MRawCrateData.cc \
+           MRawFileWrite.cc \
            MRawFileRead.cc \
-           MRawFileWrite.cc
+           MRawSocketRead.cc
 
 SRCS    = $(SRCFILES)
Index: /trunk/MagicSoft/Mars/mraw/RawLinkDef.h
===================================================================
--- /trunk/MagicSoft/Mars/mraw/RawLinkDef.h	(revision 2385)
+++ /trunk/MagicSoft/Mars/mraw/RawLinkDef.h	(revision 2386)
@@ -14,4 +14,5 @@
 #pragma link C++ class MRawCrateData+;
 
+#pragma link C++ class MRawSocketRead+;
 #pragma link C++ class MRawFileRead+;
 #pragma link C++ class MRawFileWrite+;
