#include <iomanip.h>
#include <fstream.h>
#include <iostream.h>

#include <TROOT.h>
#include <TSystem.h>
#include <TApplication.h>

#include "MCosy.h"
#include "MLogManip.h"
#include "base/timer.h"

#define clog(txt) \
    { \
    const Bool_t is = lout.IsOutputDeviceEnabled(MLog::eStdout); \
    lout << edev(MLog::eStdout) << txt << endl; \
    if (is) \
    lout.EnableOutputDevice(MLog::eStdout); \
    }

TROOT root("Cosy", "Magic Control System");

int main(int argc, char **argv)
{
    gLog << "==================================================" << endl;
    gLog << "                    Cosy V0.1                     " << endl;
    gLog << "       Magic Drive Control System Softwware       " << endl;
    gLog << "            Compiled on <" << __DATE__ << ">"       << endl;
    gLog << "               Using ROOT v" << ROOTVER             << endl;
    gLog << "==================================================" << endl;
    gLog << endl;

    Timer time;
    time.Now();

    //
    // this must move to MGCosy !!!! (or MApplication)
    //
    MLog *l = new MLog("log/cosy.log", kTRUE);
    MLog &lout = *l;
    lout.EnableOutputDevice(MLog::eStdout);

    clog("Starting Cosy at " << time.GetTimeStr() << " ...");

    //
    // start the main window
    //
    clog("- Initialising Root environment.");

    TApplication* app = new TApplication("App", &argc, argv);

    //
    // Create the Network. Device: /dev/dpm_00, Rate: 500kbps
    //
    clog("- Constructing MCosy.");

    //
    // check for the right usage of the program
    //
    int mode = 0;
    if (argc==2 && (argv[1][0]=='-' || argv[1][1]=='m'))
        switch (argv[1][2])
        {
        case '0':      // standard
            mode = 0;
            break;
        case '1':      // SE mode
            mode = 1;
            break;
        case '2':      // GUI demo mode
            mode = 2;
            break;
        }

    MCosy *cosy = new MCosy(mode, "/dev/dpm_00", 500, lout);

    clog("- Starting MCosy.");
    cosy->Start();

    clog("- Starting mainloop.");
    app->Run(kTRUE);

    clog("- Stopping cosy.");
    cosy->Stop();
    clog("- cosy stopped."); 

    delete cosy;

    clog("- Terminating Program.");

    delete l;

    cout << "The End." << endl;

}
