/* ======================================================================== *\
!
! *
! * 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, 1/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
//  MJCalibrateSignal
//
// This class is reading the output written by callisto. It calibrates
// signal and time.
//
// The signal and time extractors are read from the callisto-output. In
// pricipal you could overwrite these default using the resource file,
// but this is NOT recommended!
//
/////////////////////////////////////////////////////////////////////////////
#include "MJCalibrateSignal.h"

#include <TEnv.h>
#include <TFile.h>

#include "MLog.h"
#include "MLogManip.h"

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

#include "MStatusDisplay.h"

#include "MGeomCam.h"
#include "MHCamEvent.h"
#include "MPedestalCam.h"
#include "MBadPixelsCam.h"

#include "MCalibrationQECam.h"
#include "MCalibrationBlindCam.h"
#include "MCalibrationChargeCam.h"
#include "MCalibrationRelTimeCam.h"
#include "MCalibrationChargePINDiode.h"
#include "MCalibrationHiLoCam.h"
#include "MCalibrationPatternDecode.h"

#include "MCalibrationChargeCalc.h"
#include "MCalibrationRelTimeCalc.h"

#include "MCalibrationIntensityChargeCam.h"
#include "MCalibrationIntensityBlindCam.h"
#include "MCalibrationIntensityRelTimeCam.h"
#include "MCalibrationIntensityQECam.h"
#include "MBadPixelsIntensityCam.h"

#include "MHCalibrationChargeCam.h"
#include "MHCalibrationChargeBlindCam.h"
#include "MHCalibrationChargePINDiode.h"
#include "MHCalibrationRelTimeCam.h"
#include "MHCamera.h"

#include "MCalibCalcFromPast.h"

#include "MReadReports.h"
#include "MReadMarsFile.h"
#include "MRawFileRead.h"
#include "MContinue.h"
#include "MTriggerPatternDecode.h"
#include "MFTriggerPattern.h"
#include "MGeomApply.h"
#include "MMcPedestalCopy.h"
#include "MPointingPosCalc.h"
#include "MPointingPosInterpolate.h"
#include "MPedCalcFromLoGain.h"
#include "MExtractor.h"
#include "MExtractTimeAndCharge.h"
#include "MExtractPINDiode.h"
#include "MExtractBlindPixel.h"
#include "MFCosmics.h"
#include "MTaskEnv.h"
#include "MCalibrateData.h"
#include "MCalibrateRelTimes.h"
#include "MBadPixelsMerge.h"
#include "MBadPixelsCalc.h"
#include "MBadPixelsTreat.h"
#include "MFillH.h"
#include "MWriteRootFile.h"

ClassImp(MJCalibrateSignal);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor. 
//
// Sets fRuns to 0, fExtractor to NULL, 
//
MJCalibrateSignal::MJCalibrateSignal(const char *name, const char *title)
  : fDataFlag(0), fIsInterlaced(kTRUE), fIsRelTimesUpdate(kFALSE), fIsHiLoCalibration(kFALSE)
{
    fName  = name  ? name  : "MJCalibrateSignal";
    fTitle = title ? title : "Tool to calibrate data";

    SetRootData();
}

Bool_t MJCalibrateSignal::WriteResult(TObjArray &cont)
{
    if (fPathOut.IsNull())
    {
        *fLog << inf << "No output path specified via SetPathOut - no output written." << endl;
        return kTRUE;
    }

    const TString oname = Form("%s/signal%08d.root", (const char*)fPathOut, fSequence.GetSequence());

    *fLog << inf << "Writing to file: " << oname << endl;

    TFile file(oname, "RECREATE");

    *fLog << inf << " - MStatusDisplay..." << flush;
    if (fDisplay && fDisplay->Write()<=0)
    {
        *fLog << err << "Unable to write MStatusDisplay to " << oname << endl;
        return kFALSE;
    }
    *fLog << inf << "ok." << endl;

    return fIsInterlaced ? WriteContainer(cont) : kTRUE;
}

Bool_t MJCalibrateSignal::ReadCalibration(TObjArray &l, MBadPixelsCam &cam, MExtractor* &ext1, MExtractor* &ext2, TString &geom) const
{
    const TString fname = Form("%s/calib%08d.root", fPathIn.Data(), fSequence.GetSequence());

    *fLog << inf << "Reading from file: " << fname << endl;

    TFile file(fname, "READ");
    if (!file.IsOpen())
    {
        *fLog << err << dbginf << "ERROR - Could not open file " << fname << endl;
        return kFALSE;
    }

    TObject *o = file.Get("ExtractSignal");
    if (o && !o->InheritsFrom(MExtractor::Class()))
    {
        *fLog << err << dbginf << "ERROR - ExtractSignal read from " << fname << " doesn't inherit from MExtractor!" << endl;
        return kFALSE;
    }
    ext1 = o ? (MExtractor*)o->Clone() : NULL;

    o = file.Get("ExtractTime");
    if (o && !o->InheritsFrom(MExtractor::Class()))
    {
        *fLog << err << dbginf << "ERROR - ExtractTime read from " << fname << " doesn't inherit from MExtractor!" << endl;
        return kFALSE;
    }
    ext2 = o ? (MExtractor*)o->Clone() : NULL;
    if (!ext1 && !ext2)
    {
        *fLog << err << dbginf << "ERROR - Neither ExtractSignal nor ExrtractTime found in " << fname << "!" << endl;
        return kFALSE;
    }

    o = file.Get("MGeomCam");
    if (o && !o->InheritsFrom(MGeomCam::Class()))
    {
        *fLog << err << dbginf << "ERROR - MGeomCam read from " << fname << " doesn't inherit from MGeomCam!" << endl;
        return kFALSE;
    }
    geom = o ? o->ClassName() : "";

    TObjArray cont(l);
    cont.Add(&cam);
    return ReadContainer(cont);
}

// --------------------------------------------------------------------------
//
// MJCalibration allows to setup several option by a resource file:
//   MJCalibrateSignal.RawData: yes,no
//
// For more details see the class description and the corresponding Getters
//
Bool_t MJCalibrateSignal::CheckEnvLocal()
{

    SetInterlaced(GetEnv("Interlaced", fIsInterlaced));
    SetRelTimesUpdate(GetEnv("RelTimesUpdate", fIsRelTimesUpdate));
    SetHiLoCalibration(GetEnv("HiLoCalibration", fIsHiLoCalibration));

    SetRootData();

    if (HasEnv("RawData"))
    {
      fDataFlag = 0;
      SetRawData();
    }

    if (HasEnv("MC"))
    {
      fDataFlag = 0;
      SetMC();
    }

    return kTRUE;
}

Bool_t MJCalibrateSignal::ProcessFile(MPedestalCam &pedcamab, MPedestalCam &pedcambias, 
				      MPedestalCam &pedcamextr)
{
    if (!fSequence.IsValid())
    {
        *fLog << err << "ERROR - Sequence invalid!" << endl;
        return kFALSE;
    }

    //if (!CheckEnv())
    //    return kFALSE;

    CheckEnv();

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

    *fLog << inf;
    fLog->Separator(GetDescriptor());
    *fLog << "Calculate calibrated data from runs ";
    *fLog << fSequence.GetName() << endl;
    *fLog << endl;

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

    MDirIter iter;
    const Int_t n0 = fSequence.SetupDatRuns(iter, fPathData, "D", IsRawData());
    const Int_t n1 = fSequence.GetNumDatRuns();
    if (n0==0)
    {
        *fLog << err << "ERROR - No input files of sequence found!" << endl;
        return kFALSE;
    }
    if (n0!=n1)
    {
        *fLog << err << "ERROR - Number of files found (" << n0 << ") doesn't match number of files in sequence (" << n1 << ")" << endl;
        return kFALSE;
    }

    // Read File
    MCalibrationIntensityChargeCam      ichcam;
    MCalibrationIntensityQECam          iqecam;
    MCalibrationIntensityBlindCam       iblcam;
    MCalibrationIntensityRelTimeCam     itmcam;
    MBadPixelsIntensityCam              ibdcam;

    TObjArray interlacedcont;
    interlacedcont.Add(&ichcam);
    interlacedcont.Add(&iqecam);
    interlacedcont.Add(&iblcam);
    interlacedcont.Add(&itmcam);
    interlacedcont.Add(&ibdcam);

    MHCalibrationChargeCam      hchacam;
    MHCalibrationChargeBlindCam hbndcam;
    MHCalibrationChargePINDiode hpndiod;
    MHCalibrationRelTimeCam     hrelcam;

    interlacedcont.Add(&hchacam);
    interlacedcont.Add(&hbndcam);
    interlacedcont.Add(&hpndiod);
    if (fIsRelTimesUpdate)
      interlacedcont.Add(&hrelcam);

    MCalibrationChargeCam      calcam;
    MCalibrationQECam          qecam;
    MCalibrationBlindCam       bndcam;
    MCalibrationChargePINDiode pind;
    MCalibrationRelTimeCam     tmcam;
    MCalibrationHiLoCam        hilcam;

    if (fIsHiLoCalibration)
      interlacedcont.Add(&hilcam);      

    MBadPixelsCam              badpix;

    MExtractor *extractor1=0;
    MExtractor *extractor2=0;
    MExtractor *extractor3=0;
    TString geom;

    TObjArray calibcont;
    calibcont.Add(&calcam);
    calibcont.Add(&qecam);
    calibcont.Add(&bndcam);
    calibcont.Add(&pind);
    calibcont.Add(&tmcam);

    if (!ReadCalibration(calibcont, badpix, extractor1, extractor2, geom))
        return kFALSE;

    *fLog << all;
    if (extractor1)
    {
        *fLog << underline << "Signal Extractor found in calibration file" << endl;
        extractor1->Print();
        *fLog << endl;
	extractor3 = (MExtractor*)extractor1->Clone();
    }
    else
        *fLog << inf << "No Signal Extractor: ExtractSignal in file." << endl;

    if (extractor2)
    {
        *fLog << underline << "Time Extractor found in calibration file" << endl;
        extractor2->Print();
        *fLog << endl;
    }
    else
        *fLog << inf << "No Time Extractor: ExtractTime in file." << endl;

    if (!geom.IsNull())
        *fLog << inf << "Camera geometry found in file: " << geom << endl;
    else
        *fLog << inf << "No Camera geometry found using default <MGeomCamMagic>" << endl;

    // This is necessary for the case in which it is not in the files
    MBadPixelsCam badcam;

    // Setup Parlist
    MParList plist;
    plist.AddToList(this); // take care of fDisplay!
    plist.AddToList(&badcam);
    plist.AddToList(&calibcont);
    plist.AddToList(&hilcam);

    if (fIsInterlaced)
      plist.AddToList(&interlacedcont);

    // Setup Tasklist
    MTaskList tlist;
    plist.AddToList(&tlist);

    /*
    TString name = iter.Next();
    Byte_t filetype = MRawFileRead::IsFileValid(name);
    if (!filetype)
        filetype = MReadMarsFile::IsFileValid(name)+1;
    if (filetype<1||filetype>3)
    {
        gLog << err << "ERROR - FileType #" << (int)filetype << " of first file " << name << " unknown..." << endl;
        return kFALSE;
    } */

    MReadReports readreal;
    readreal.AddTree("Events", "MTime.", kTRUE);
    readreal.AddTree("Trigger");
    readreal.AddTree("Camera");
    readreal.AddTree("Drive");
    readreal.AddTree("CC");
    readreal.AddTree("Currents");

    //MReadMarsFile read("Events");
    //read.DisableAutoScheme();
    MRawFileRead rawread(NULL);
    if (IsRawData())
        rawread.AddFiles(iter);
    else
        readreal.AddFiles(iter);

    MPointingPosInterpolate pextr;
    pextr.AddFiles(&iter);
    
    MGeomApply             apply; // Only necessary to create geometry
    if (!geom.IsNull())
        apply.SetGeometry(geom);
    MBadPixelsMerge        merge(&badpix);

    // Make sure that pedcamab has the correct name
    pedcamab.SetName("MPedestalFundamental");
    pedcamextr.SetName("MPedestalFromExtractorRndm");
    pedcambias.SetName("MPedestalFromExtractor");
    plist.AddToList(&pedcamextr);
    plist.AddToList(&pedcambias);
    plist.AddToList(&pedcamab);

    // Check for interleaved events
    MCalibrationPatternDecode caldec;
    MTriggerPatternDecode     decode;

    MFTriggerPattern ftp;
    ftp.RequireCalibration();
    //    ftp.DenyCalibration();
    //    ftp.DenyPedestal();
    //    ftp.DenyPinDiode();
    //    ftp.SetInverted();
    MContinue conttp(&ftp, "ContTrigPattern");
    // --> tlist2

    // Do signal and pedestal calculation
    MPedCalcFromLoGain     pedlo1("MPedCalcFundamental");
    pedlo1.SetPedestalUpdate(kTRUE);
    pedlo1.SetNamePedestalCamOut("MPedestalFundamental");

    MPedCalcFromLoGain     pedlo2("MPedCalcWithExtractorRndm");
    pedlo2.SetPedestalUpdate(kTRUE);
    pedlo2.SetRandomCalculation(kTRUE);
    pedlo2.SetNamePedestalCamIn("MPedestalFundamental");
    pedlo2.SetNamePedestalCamOut("MPedestalFromExtractorRndm");

    MPedCalcFromLoGain     pedlo3("MPedCalcWithExtractor");
    pedlo3.SetPedestalUpdate(kTRUE);
    pedlo3.SetRandomCalculation(kFALSE);
    pedlo3.SetNamePedestalCamIn("MPedestalFundamental");
    pedlo3.SetNamePedestalCamOut("MPedestalFromExtractor");

    if (extractor1)
    {
        extractor1->SetPedestals(&pedcamab);

        if (extractor1->InheritsFrom("MExtractTimeAndCharge"))
        {
            pedlo2.SetExtractor((MExtractTimeAndCharge*)extractor1);
            pedlo3.SetExtractor((MExtractTimeAndCharge*)extractor1);
            const Int_t win = ((MExtractTimeAndCharge*)extractor1)->GetWindowSizeHiGain();
            pedlo1.SetExtractWindow(15, win);
            pedlo2.SetExtractWindow(15, win/*obsolete*/);
            pedlo3.SetExtractWindow(15, win/*obsolete*/);
        }
        else
        {
            // FIXME: How to get the fixed value 15 automatically?
            const Int_t f = (Int_t)(15.5+extractor1->GetHiGainFirst());
            const Int_t n = (Int_t)(15.5+extractor1->GetNumHiGainSamples());
            pedlo1.SetExtractWindow(f, n);
            pedlo2.SetExtractWindow(f, n);
            pedlo3.SetExtractWindow(f, n);
        }
    }
    if (extractor2)
      extractor2->SetPedestals(&pedcamab);

    if (extractor3)
      extractor3->SetPedestals(&pedcamab);

    MFCosmics fcosmics;
    fcosmics.SetNamePedestalCam("MPedestalFundamental");
    MContinue contcos(&fcosmics, "ContTrigEvts");
    contcos.SetInverted();

    MMcPedestalCopy pcopy;
    MTaskEnv taskenv1("ExtractSignal");
    MTaskEnv taskenv2("ExtractTime");
    MTaskEnv taskenv3("ExtractInterlaced");
    taskenv1.SetDefault(extractor1);
    taskenv2.SetDefault(extractor2);
    taskenv3.SetDefault(extractor3);

    MCalibrateData         calib;
    // 
    // This is new calibration to eff. photo-electrons, hard-coded as decided 
    // at the Wuerzburg software meeting 26.01.05
    //
    calib.SetSignalType(MCalibrateData::kPhe);

    if (IsMC()) // MC file
    {
        calib.SetCalibrationMode(MCalibrateData::kFfactor);
        calib.SetPedestalFlag(MCalibrateData::kRun);
        // FIXME: What to do for MC files???
        calib.AddPedestal("MPedestalCam", "MPedPhotFundamental");
        calib.AddPedestal("MPedestalCam", "MPedPhotFromExtractor");
        calib.AddPedestal("MPedestalCam", "MPedPhotFromExtractorRndm");
    }
    else
    {
        calib.AddPedestal("Fundamental");
        calib.AddPedestal("FromExtractor");
        calib.AddPedestal("FromExtractorRndm");
        calib.SetPedestalFlag(MCalibrateData::kEvent);
    }

    MExtractPINDiode        pinext;
    MExtractBlindPixel      bldext;

    MFTriggerPattern        fcalib("CalibFilter");
    MCalibrationChargeCalc  chcalc;
    MCalibrationRelTimeCalc recalc;
    MCalibCalcFromPast      pacalc;

    fcalib.DenyCalibration();
    fcalib.SetInverted();

    pinext.SetPedestals(&pedcamab);
    bldext.SetPedestals(&pedcamab);
    chcalc.SetPedestals(&pedcamextr);

    pacalc.SetChargeCalc(&chcalc);
    if (fIsRelTimesUpdate)
      pacalc.SetRelTimeCalc(&recalc);
    pacalc.SetCalibrate(&calib);

    //
    // Intensity Calibration histogramming
    //
    MFillH filpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode",   "FillPINDiode");
    MFillH filbnd("MHCalibrationChargeBlindCam", "MExtractedSignalBlindPixel", "FillBlindCam");
    MFillH filcam("MHCalibrationChargeCam",      "MExtractedSignalCam",        "FillChargeCam");
    MFillH filtme("MHCalibrationRelTimeCam",     "MArrivalTimeCam",            "FillRelTime");
    MFillH filhil("MHCalibrationHiLoCam",        "MExtractedSignalCam",        "FillHiLoRatio");

    filpin.SetBit(MFillH::kDoNotDisplay);
    filbnd.SetBit(MFillH::kDoNotDisplay);
    filcam.SetBit(MFillH::kDoNotDisplay);
    filtme.SetBit(MFillH::kDoNotDisplay);
    filhil.SetBit(MFillH::kDoNotDisplay);

    MCalibrateRelTimes     caltm;
    MBadPixelsCalc         bpcal;
    MBadPixelsTreat        treat;

    bpcal.SetNamePedPhotCam("MPedPhotFromExtractor");
    treat.AddNamePedPhotCam("MPedPhotFundamental");
    treat.AddNamePedPhotCam("MPedPhotFromExtractor");
    treat.AddNamePedPhotCam("MPedPhotFromExtractorRndm");
    if (!extractor2 && !extractor1->InheritsFrom("MExtractTimeAndCharge"))
        treat.SetProcessTimes(kFALSE);


    MHCamEvent evt0(0, "PedFLG",      "Pedestal from Lo Gain;;P [fadc/sl]");
    MHCamEvent evt1(2, "PedRmsFLG",   "Pedestal RMS from Lo Gain;;\\sigma_{p} [fadc/sl]");
    MHCamEvent evt2(0, "Extra'd",     "Extracted Signal;;S [fadc/sl]");
    //    MHCamEvent evt3(4, "PedPhot",     "Calibrated Pedestal;;P [phe]");
    MHCamEvent evt4(5, "PedRMS",      "Calibrated Pedestal RMS;;\\sigma_{p} [phe]");
    MHCamEvent evt5(3, "Interp'd",    "Interpolated Signal;;S [phe]");
    MHCamEvent evt6(2, "Unsuitable",  "Fraction of unsuitable events per Pixel;;[1]");
    MHCamEvent evt7(0, "Times",       "Arrival Time;;T [slice]");
    MHCamEvent evt8(0, "Conv",        "Calibration Conv. Factors;;[phe/fadc sl]");

    evt0.EnableVariance();
    evt1.EnableVariance();
    evt2.EnableVariance();
    // evt3.EnableVariance();
    evt4.EnableVariance();
    evt5.EnableVariance();
    evt7.EnableVariance();
    //    evt8.EnableVariance();

    MFillH fill0(&evt0, "MPedestalFundamental",   "FillPedFLG");
    MFillH fill1(&evt1, "MPedestalFromExtractor", "FillPedRmsFLG");
    MFillH fill2(&evt2, "MExtractedSignalCam",    "FillExtracted");
    // MFillH fill3(&evt3, "MPedPhotFundamental",    "FillPedPhot");
    MFillH fill4(&evt4, "MPedPhotFromExtractor",  "FillPedRMS");
    MFillH fill5(&evt5, "MCerPhotEvt",            "FillInterpolated");
    MFillH fill6(&evt6, "MBadPixelsCam",          "FillUnsuitable");
    MFillH fill7(&evt7, "MArrivalTime",           "FillTimes");
    MFillH fill8(&evt8, "MCalibrateData",         "FillConv");

    // The second rule is for the case reading raw-files!
    MWriteRootFile write(2, Form("%s{s/_D_/_Y_}{s/.raw$/.root}", fPathOut.Data()), fOverwrite);
    // Run Header
    write.AddContainer("MRawRunHeader",             "RunHeaders");
    write.AddContainer("MBadPixelsCam",             "RunHeaders");
    write.AddContainer("MGeomCam",                  "RunHeaders");
    // Monte Carlo Headers
    write.AddContainer("MMcTrigHeader",             "RunHeaders", kFALSE);
    write.AddContainer("MMcConfigRunHeader",        "RunHeaders", kFALSE);
    write.AddContainer("MMcCorsikaRunHeader",       "RunHeaders", kFALSE);
    // Monte Carlo
    write.AddContainer("MMcEvt",                    "Events",     kFALSE);
    write.AddContainer("MMcTrig",                   "Events",     kFALSE);
    // Data
    write.AddContainer("MCerPhotEvt",               "Events");
    write.AddContainer("MPedPhotFundamental",       "Events");
    write.AddContainer("MPedPhotFromExtractor",     "Events");
    write.AddContainer("MPedPhotFromExtractorRndm", "Events");
    write.AddContainer("MTime",                     "Events",     kFALSE);
    write.AddContainer("MRawEvtHeader",             "Events");
    write.AddContainer("MArrivalTime",              "Events",     kFALSE);
    // Slow-Control: Current
    write.AddContainer("MTimeCurrents",             "Currents",   kFALSE);
    write.AddContainer("MCameraDC",                 "Currents",   kFALSE);
    write.AddContainer("MReportCurrents",           "Currents",   kFALSE);
    // Slow-Control: Camera
    write.AddContainer("MReportCamera",             "Camera",     kFALSE);
    write.AddContainer("MTimeCamera",               "Camera",     kFALSE);
    write.AddContainer("MCameraAUX",                "Camera",     kFALSE);
    write.AddContainer("MCameraCalibration",        "Camera",     kFALSE);
    write.AddContainer("MCameraCooling",            "Camera",     kFALSE);
    write.AddContainer("MCameraHV",                 "Camera",     kFALSE);
    write.AddContainer("MCameraLV",                 "Camera",     kFALSE);
    write.AddContainer("MCameraLids",               "Camera",     kFALSE);
    // Slow-Control: Trigger
    write.AddContainer("MReportTrigger",            "Trigger",    kFALSE);
    write.AddContainer("MTimeTrigger",              "Trigger",    kFALSE);
    // Slow-Control: Drive
    write.AddContainer("MPointingPos",              "Events",     kFALSE);
    write.AddContainer("MReportDrive",              "Drive",      kFALSE);
    write.AddContainer("MTimeDrive",                "Drive",      kFALSE);
    // Slow-Control: Central Control
    write.AddContainer("MReportCC",                 "CC",         kFALSE);
    write.AddContainer("MTimeCC",                   "CC",         kFALSE);

    // Now setup tasklist for events
    MTaskList tlist2;

    tlist2.AddToList(&caldec);
    tlist2.AddToList(&decode);
    tlist2.AddToList(&apply);
    tlist2.AddToList(&merge);
    if (IsMC())
        tlist2.AddToList(&pcopy);
    else
    {
        tlist2.AddToList(&pedlo1);
        tlist2.AddToList(&pedlo2);
        tlist2.AddToList(&pedlo3);
    }
    if (fIsInterlaced)
      {
	pinext.SetFilter(&fcalib);
	bldext.SetFilter(&fcalib);
	taskenv3.SetFilter(&fcalib);
	pacalc.SetFilter(&fcalib);
	filcam.SetFilter(&fcalib);
	filtme.SetFilter(&fcalib);
	filbnd.SetFilter(&fcalib);
	filpin.SetFilter(&fcalib);
	chcalc.SetFilter(&fcalib);
	recalc.SetFilter(&fcalib);

        tlist2.AddToList(&fcalib);
        tlist2.AddToList(&pinext);
        tlist2.AddToList(&bldext);
	tlist2.AddToList(&taskenv3);
        tlist2.AddToList(&pacalc);
        tlist2.AddToList(&filcam);
	if (fIsRelTimesUpdate)
	  tlist2.AddToList(&filtme);
        tlist2.AddToList(&filbnd);
        tlist2.AddToList(&filpin);
        tlist2.AddToList(&chcalc);
	if (fIsRelTimesUpdate)
	  tlist2.AddToList(&recalc);
      }

    tlist2.AddToList(&conttp);
    if (extractor1)
      tlist2.AddToList(&taskenv1);
    if (extractor2)
      tlist2.AddToList(&taskenv2);
    tlist2.AddToList(&fill0);
    tlist2.AddToList(&fill1);
    tlist2.AddToList(&contcos);
    if (fIsHiLoCalibration)
      tlist2.AddToList(&filhil);
    tlist2.AddToList(&fill2);
    tlist2.AddToList(&calib);
    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
        tlist2.AddToList(&caltm);

    tlist2.AddToList(&bpcal);
    tlist2.AddToList(&treat);
    tlist2.AddToList(&fill6);
    //    tlist2.AddToList(&fill3);
    tlist2.AddToList(&fill4);
    tlist2.AddToList(&fill5);
    if (extractor2 || extractor1->InheritsFrom("MExtractTimeAndCharge"))
      tlist2.AddToList(&fill7);

    //    if (fIsInterlaced)
    tlist2.AddToList(&fill8);

    // Setup List for Drive-tree
    MPointingPosCalc pcalc;

    // Now setup main tasklist
    tlist.AddToList(IsRawData() ? (MTask*)&rawread : (MTask*)&readreal);
    if (IsRootData())
      tlist2.AddToList(&pextr);
    tlist.AddToList(&tlist2, IsRootData() ? "Events" : "All");

    if (IsMC())
      tlist.AddToList(&pcalc, "Drive");

    tlist.AddToList(&write);

    // Create and setup the eventloop
    MEvtLoop evtloop(fName);
    evtloop.SetParList(&plist);
    evtloop.SetDisplay(fDisplay);
    evtloop.SetLogStream(fLog);
    if (!SetupEnv(evtloop))
        return kFALSE;

    // Execute first analysis
    if (!evtloop.Eventloop(fMaxEvents))
    {
        *fLog << err << GetDescriptor() << ": Failed." << endl;
        return kFALSE;
    }

    tlist.PrintStatistics();

    DisplayResult(plist);

    if (!WriteResult(interlacedcont))
        return kFALSE;

    if (extractor1)
      delete extractor1;
    if (extractor2)
      delete extractor2;
    if (extractor3)
      delete extractor3;
 
    *fLog << all << GetDescriptor() << ": Done." << endl;
    *fLog << endl << endl;

    return kTRUE;
}


void MJCalibrateSignal::DisplayResult(MParList &plist)
{

    if (!fDisplay)
        return;

    if (!fIsHiLoCalibration)
      return;

    //
    // Get container from list
    //
    MGeomCam        &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
    MCalibrationHiLoCam *cam = (MCalibrationHiLoCam*)plist.FindObject("MCalibrationHiLoCam");

    // Create histograms to display
    MHCamera disp1 (geomcam, "HiLoConv", "Ratio Amplification HiGain vs. LoGain (Charges)");
    MHCamera disp2 (geomcam, "HiLoDiff", "Arrival Time Diff. HiGain vs. LoGain (Times)");

    disp1.SetCamContent(*cam,  0);
    disp1.SetCamError(  *cam,  1);
    disp2.SetCamContent(*cam,  5);
    disp2.SetCamError(  *cam,  6);

    disp1.SetYTitle("R [1]");
    disp2.SetYTitle("\\Delta T [FADC sl.]");


    TCanvas &c1 = fDisplay->AddTab("HiLoConv");
    c1.Divide(2,3);
    
    disp1.CamDraw(c1, 1, 2, 1);
    disp2.CamDraw(c1, 2, 2, 1);
}

