/* ======================================================================== *\
!
! *
! * 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>
!   Author(s): Harald Kornmayer 1/2001
!
!   Copyright: MAGIC Software Development, 2000-2001
!
!
\* ======================================================================== */

#include "MMcTimeGenerate.h"

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

#include "MParList.h"
#include "MTime.h"

ClassImp(MMcTimeGenerate);

// --------------------------------------------------------------------------
//
MMcTimeGenerate::MMcTimeGenerate(const char *name, const char *title)
{
    fName  = name  ? name  : "MMcTimeGenerate";
    fTitle = title ? title : "Task to generate a random event time";

    const Double_t lambda = 100; // [Hz]

    fFunc = new TF1("Poisson", "[0] * exp(-[0]*x)", 0, 1);
    fFunc->SetParameter(0, lambda);

    fDeadTime = 0.1/lambda;
}

MMcTimeGenerate::~MMcTimeGenerate()
{
    delete fFunc;
}


// --------------------------------------------------------------------------
//
//  The PreProcess connects the raw data with this task. It checks if the 
//  input containers exist, if not a kFalse flag is returned. It also checks
//  if the output contaniers exist, if not they are created.
//  This task can read either Montecarlo files with multiple trigger
//  options, either Montecarlo files with a single trigger option.
//
Bool_t MMcTimeGenerate::PreProcess (MParList *pList)
{
    // connect the raw data with this task

    fTime = (MTime*)pList->FindCreateObj("MTime");
    if (!fTime)
        return kFALSE;

    return kTRUE;
}

// --------------------------------------------------------------------------
//
//
Bool_t MMcTimeGenerate::Process()
{
    Double_t dt;

    do dt = fFunc->GetRandom();
    while (dt < fDeadTime);

    const UInt_t t = fTime->GetTimeLo();

    fTime->SetTime(t+dt*10000, 0); // [0.1ms]

    return kTRUE;
}
