#include "TString.h"
#include "TChain.h"
#include "TFile.h"
#include "TH1F.h"
#include "TMatrix.h"

#include "MParList.h"
#include "MTaskList.h"
#include "MReadTree.h"
#include "MHMatrix.h"
#include "MFillH.h"
#include "MEvtLoop.h"

//--------------------------------------------------------------------------------------
// MAIN INPUT/OUTPUT

#include "IOMkn421.h"
//--------------------------------------------------------------------------------------

void Convert2Matrix()
{
    //------------------------------------------------------
    // ON + OFF data to be filled into matrix

    MReadTree readOn("Events", fileOptOn);
    MReadTree readOff("Events", fileOptOff);

    const Int_t nent=readOn.GetEntries();

    //------------------------------------------------------

    // process On data
    MParList plistOn;
    MTaskList tlistOn;
    plistOn.AddToList(&tlistOn);

    readOn.DisableAutoScheme();

    TString sdist  = Form("MHillasSrc.fDist*%f",mm2deg);
  
    MHMatrix matOn("Matrix");
    matOn.AddColumn("MHillas.fSize");  // 0
    matOn.AddColumn(sdist.Data());     // 1
    matOn.AddColumn("MHillas.fWidth"); // 2
    matOn.AddColumn("MHillas.fLength");// 3
    matOn.AddColumn("MHillasSrc.fAlpha");
    plistOn.AddToList(&matOn);
    MFillH fillOn("Matrix");

    tlistOn.AddToList(&readOn);
    tlistOn.AddToList(&fillOn);

    MEvtLoop evtloopOn;
    evtloopOn.SetParList(&plistOn);

    if (!evtloopOn.Eventloop(0.5*nent))
        return;

    tlistOn.PrintStatistics();

    TFile fileOn2(fileMatOn.Data(),"recreate","");
    matOn.Write();
    fileOn2.Close();


    // process Off data

    MParList plistOff;
    MTaskList tlistOff;
    plistOff.AddToList(&tlistOff);

    readOff.DisableAutoScheme();

    MHMatrix matOff("Matrix");
    matOff.AddColumns(matOn.GetColumns());
    plistOff.AddToList(&matOff);
    MFillH fillOff("Matrix");

    tlistOff.AddToList(&readOff);
    tlistOff.AddToList(&fillOff);

    MEvtLoop evtloopOff;
    evtloopOff.SetParList(&plistOff);

    if (!evtloopOff.Eventloop())
        return;

    tlistOff.PrintStatistics();

    TFile fileOff2(fileMatOff.Data(),"recreate","");
    matOff.Write();
    fileOff2.Close();
}