#include "MEvtLoop.h"

#include <iostream.h>

#include <TStopwatch.h>

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

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

MEvtLoop::~MEvtLoop()
{
}

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

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

void MEvtLoop::Eventloop(Int_t maxcnt)
{
    if (!fTasks || !fParlist)
    {
        cout << "Error: either tasklist or parlist not initialized" << 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 << 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 << 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();
}

