#include <iostream.h>

#include <TSystem.h>

#include "TFile.h"
#include "TTree.h"
#include "TBranch.h"

#include "MParList.h"
#include "MTaskList.h"
#include "MEvtLoop.h"

#include "MRawRunHeader.h"
#include "MRawEvtHeader.h"
#include "MRawEvtData.h"
#include "MRawCrateArray.h"
#include "MTime.h"
#include "MInputStreamID.h"

/////////////////////////////////////////////////////////////////////////////
//
// This is an easy implementation of the Merging process (as compilable prog)
//
// at the moment it reads a binary file ("rawtest.bin") which was written
// in the DAQ raw format.
//
// The data are stored in root container objects (classes derived from
// TObject like MRawRunHeader)
//
// This containers are written to a root file ("rawtest.root")
//
/////////////////////////////////////////////////////////////////////////////

int main(const int argc, const char **argv)
{
    cout << "==================================================" << endl ;
    cout << "                   MERPP v0.1" << endl;
    cout << "      MARS Merging and Preprocessing Program" << endl ;
    cout << "            Compiled on <" << __DATE__ << ">" << endl ;
    cout << "==================================================" << endl ;
    cout << endl;

    //
    // check for the right usage of the program
    //

    //
    //     initialize ROOT  (this is obligatory here)
    //
    TROOT simple("Merpp","Mars - Merging and Preprocessing Program");

    MRawRunHeader  *runheader = new MRawRunHeader();
    MRawEvtHeader  *evtheader = new MRawEvtHeader();
    MTime          *evttime   = new MTime();
    MRawEvtData    *evtdata   = new MRawEvtData();
    MRawCrateArray *evtcrate  = new MRawCrateArray();

    //
    //  open the file
    //
    TFile input("delme.root", "READ");

    //
    // open the Run Header and read in
    //

    TTree *runtree = (TTree*) input.Get("RunHeaders") ;
    
    cout << " Entries in Tree RunHeaders: " << dec << runtree->GetEntries() << endl ;

    runtree->GetBranch("MRawRunHeader")->SetAddress(&runheader);
    runtree->GetEvent(0);

    runheader->Print();


    //
    // open the DataTree and read in 
    //
    TTree *evttree = (TTree*) input.Get("Data") ;

    //
    //   connnect the branches in that tree
    //
    evttree->GetBranch("MRawEvtHeader")->SetAddress(&evtheader);
    evttree->GetBranch("MTime")->SetAddress(&evttime);
    evttree->GetBranch("MRawEvtData")->SetAddress(&evtdata);
    evttree->GetBranch("MRawCrateArray")->SetAddress(&evtcrate);

    Int_t iEnt = (Int_t)evttree->GetEntries();
    cout << " Entries in Tree Data: " << dec << iEnt << endl;

    for (Int_t i = 0; i<iEnt; i++)
    {
        cout << "Entry: " << i << endl;

        // readin event with the selected branches
        evttree->GetEvent(i);

        evtheader->Print();
        evttime->Print();
        evtcrate->Print();
        evtdata->Print();
    } 
    
    //   end of small readin program 

    return 0;
}


