#include "MEvtLoop.h"

#include <iostream.h>

#include <TStopwatch.h>

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

ClassImp(MEvtLoop)

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

MEvtLoop::~MEvtLoop()
{
}

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

void MEvtLoop::Eventloop(Int_t maxcnt, const char *ftasks)
{
    //
    // check if the needed parameter list is set.
    //
    if (!fParlist)
    {
        cout << "MEvtLoop::Eventloop - Error: Parlist not initialized." << endl;
        return;
    }

    //
    //  check for the existance of the specified task list
    //  the default name is "MTaskList"
    //
    MTaskList *tasks = (MTaskList*)fParlist->FindObject(ftasks);
    if (!tasks)
    {
        cout << "MEvtLoop::Eventloop - Error: Cannot find tasklist '" << ftasks << "' in parameter list." << endl;
        return;
    }

    //
    //  execute the preprocess of all tasks
    //  connect the different tasks with the right containers in
    //  the parameter list
    //
    if (!tasks->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;

    //
    // start a stopwatch
    //
    TStopwatch clock;
    clock.Start();

    //
    // This is the MAIN EVENTLOOP which processes the data
    // if maxcnt<0 the number of processed events is counted
    // else only maxcnt events are processed
    //
    if (maxcnt<0)
        while (tasks->Process() && ++dummy);
    else
        while (tasks->Process() && dummy--);

    //
    // stop stop-watch, print results
    //
    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
    //
    tasks->PostProcess();
}

