#include "MLoopEvt.h"

#include <iostream.h>

#include <TStopwatch.h>

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

ClassImp(MLoopEvt)

MLoopEvt::MLoopEvt() : fTasks(NULL), fParlist(NULL)
{
}

MLoopEvt::~MLoopEvt()
{
}

void MLoopEvt::SetTaskList(MTaskList *t)
{
    fTasks = t;
}

void MLoopEvt::SetParList(MParList *p)
{
    fParlist = p;

    //
    // check if the task list is already known
    //
    if (fTasks)
    {
        cout << "MLoopEvt::SetParList - Warning: Task List already set, using this one" << endl;
        return;
    }

    //
    // get the task list from the parameter list
    //
    fTasks = (MTaskList*)fParlist->FindObject("MTaskList");

    if (!fTasks)
        cout << "MLoopEvt::SetParList - Warning: MTaskList not found." << endl;
}

void MLoopEvt::Eventloop(Int_t maxcnt)
{
    //
    // check if the parameter list is known
    //
    if (!fParlist)
    {
        cout << "MLoopEvt::Eventloop - Error: ParList not set." << endl;
        return;
    }

    //
    // check if the task list could be retrieved from the parameter list
    //
    if (!fTasks)
    {
        cout << "MLoopEvt::Eventloop - Error: TaskList not set." << endl;
        return;
    }

    //
    //  execute the preprocess of all tasks
    //  connect the different tasks with the right containers in
    //  the parameter list

    if (!fTasks->PreProcess(fParlist))
    {
        cout << "Error detected while PreProcessing" << endl;
        return;
    }

    //
    //   loop over all events and process all tasks for
    //   each event
    //
    cout << endl << "Eventloop running (";

    if (maxcnt<0)
        cout << "all";
    else
        cout << dec << maxcnt;

    cout << " events)..." << flush;

    Int_t dummy = maxcnt<0 ? 0 : maxcnt;

    TStopwatch clock;
    clock.Start();

    if (maxcnt<0)
        while (fTasks->Process() && ++dummy);
    else
        while (fTasks->Process() && dummy--);

    clock.Stop();

    cout << "Ready!" << endl << endl;

    clock.Print();

    cout << dec << endl
        << "Time: " << clock.CpuTime() << "s"
        << " for " << (maxcnt<0?dummy:maxcnt) << " Events"
        << " --> " << (maxcnt<0?dummy:maxcnt)/clock.CpuTime() << " Events/s"
        << endl << endl;

    //
    //  execute the post process of all tasks
    //
    fTasks->PostProcess();
}

