/* ======================================================================== *\
!
! *
! * 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, 04/2005 <mailto:tbretz@astro.uni-wuerzburg.de>
!   Author(s): Daniela Dorner, 04/2005 <mailto:dorner@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
// fillsignal.C
// ============
//
// This macro is used to read the calibration-/callisto-output files
// signal00000.root.
//
// From this file the Mean PedRms for the inner and outer camera is extracted.
//
// Usage:
//   .x fillsignal.C("/data/MAGIC/Period014/signal00000.root", kTRUE)
//
// The second argument is the 'dummy-mode'. If it is kTRUE dummy-mode is
// switched on and nothing will be written into the database. This is usefull
// for tests.
//
// The macro can also be run without ACLiC but this is a lot slower...
//
// Remark: Running it from the commandline looks like this:
//   root -q -l -b fillsignal.C+\(\"filename\"\,kFALSE\) 2>&1 | tee fillsignal.log
//
// Make sure, that database and password are corretly set in a resource
// file called sql.rc and the resource file is found.
//
// Returns 0 in case of failure and 1 in case of success.
//
/////////////////////////////////////////////////////////////////////////////
#include <iostream>

#include <TEnv.h>
#include <TRegexp.h>

#include <TFile.h>
#include <TSQLResult.h>

#include "MSQLServer.h"

#include "MStatusArray.h"
#include "MHCamera.h"

using namespace std;

int Process(MSQLServer &serv, TString fname, Bool_t dummy)
{
    TFile file(fname, "READ");
    if (!file.IsOpen())
    {
        cout << "ERROR - Could not find file " << fname << endl;
        return 0;
    }

    MStatusArray *arr = (MStatusArray*)file.Get("MStatusDisplay");
    if (!arr)
    {
        cout << "ERROR - Reading of MStatusDisplay failed." << endl;
        return 0;
    }

    MHCamera *cam = (MHCamera*)arr->FindObjectInCanvas("PedRMS;avg", "MHCamera", "PedRMS");
    if (!cam)
    {
        cout << "WARNING - Reading of PedRMS;avg failed." << endl;
        return 0;
    }

    MHCamera *pul = (MHCamera*)arr->FindObjectInCanvas("PulsePos;avg", "MHCamera", "PulsePos");
    if (!pul)
    {
        cout << "WARNING - Reading of PulsePos;avg failed." << endl;
        return 0;
    }

    TArrayI inner(1);
    inner[0] = 0;

    TArrayI outer(1);
    outer[0] = 1;

    Int_t s0[] = { 1, 2, 3, 4, 5, 6 };

    Stat_t meanrmsi = cam->GetMeanSectors(TArrayI(6, s0), inner);
    Stat_t meanrmso = cam->GetMeanSectors(TArrayI(6, s0), outer);

    if (meanrmsi<0 || meanrmso<0)
    {
        cout << "WARNING - MeanPedRMS inner or outer < 0 " << endl;
        cout << "MeanPedRMS inner " << meanrmsi << endl;
        cout << "MeanPedRMS outer " << meanrmso << endl;
        return 0;
    }

    meanrmsi = TMath::Nint(meanrmsi*100)/100.;
    meanrmso = TMath::Nint(meanrmso*100)/100.;

    cam = (MHCamera*)arr->FindObjectInCanvas("Interp'd;avg", "MHCamera", "Interp'd");
    if (!cam)
    {
        cout << "WARNING - Reading of Interp'd;avg failed." << endl;
        return 0;
    }

    Stat_t meansigi = cam->GetMeanSectors(TArrayI(6, s0), inner);
    Stat_t meansigo = cam->GetMeanSectors(TArrayI(6, s0), outer);

    if (meansigi<0 || meansigo<0)
    {
        cout << "WARNING - MeanInterp'd inner or outer < 0 " << endl;
        cout << "MeanInterp'd inner " << meansigi << endl;
        cout << "MeanInterp'd outer " << meansigo << endl;
        return 0;
    }

    meansigi = TMath::Nint(meansigi*100)/100.;
    meansigo = TMath::Nint(meansigo*100)/100.;

    Stat_t meanpul = pul->GetMean();
    Stat_t rmspul  = pul->GetRMS();

    if (meanpul<0 || rmspul<0)
    {
        cout << "WARNING - PulsePos'd mean or rms < 0 " << endl;
        cout << "PulsePos'd mean " << meanpul << endl;
        cout << "PulsePos'd rms  " << rmspul << endl;
        return 0;
    }

    meanpul = TMath::Nint(meanpul*100)/100.;
    rmspul  = TMath::Nint(rmspul*100)/100.;

    TString sequence = fname(TRegexp("signal[0-9]+[.]root$"));
    if (sequence.IsNull())
    {
        cout << "WARNING - Sequ# empty" << endl;
        cout << "Sequ# " << sequence << endl;
        return 0;
    }

    Int_t seq = atoi(sequence.Data()+6);
    TString meanrmsinner=Form("%6.2f", meanrmsi);
    TString meanrmsouter=Form("%6.2f", meanrmso);
    TString meansiginner=Form("%6.2f", meansigi);
    TString meansigouter=Form("%6.2f", meansigo);
    TString meanpulpos  =Form("%6.2f", meanpul);
    TString rmspulpos   =Form("%6.2f", rmspul);

    cout << "Sequence #" << seq << endl;
    cout << "  Mean Ped RMS inner [phe] " << meanrmsinner << endl;
    cout << "  Mean Ped RMS outer [phe] " << meanrmsouter << endl;
    cout << "  Mean Signal  inner [phe] " << meansiginner << endl;
    cout << "  Mean Signal  outer [phe] " << meansigouter << endl;
    cout << "  Mean PulsePos            " << meanpulpos   << endl;
    cout << "  Rms  PulsePos            " << rmspulpos    << endl;

    TString query = Form("UPDATE Calibration SET "
                         " fMeanPedRmsInner=%s, fMeanPedRmsOuter=%s, "
                         " fMeanSignalInner=%s, fMeanSignalOuter=%s, "
                         " fPulsePosMean=%s,    fPulsePosRms=%s      "
                         " WHERE fSequenceFirst='%d' ",
                         meanrmsinner.Data(), meanrmsouter.Data(),
                         meansiginner.Data(), meansigouter.Data(),
                         meanpulpos.Data(),   rmspulpos.Data(),
                         seq);

    if (dummy)
        return 0;

    TSQLResult *res = serv.Query(query);
    if (!res)
    {
        cout << "ERROR - Query failed: " << query << endl;
        return 0;
    }

    return 1;
}

int fillsignal(TString fname, Bool_t dummy=kTRUE)
{
    TEnv env("sql.rc");

    MSQLServer serv(env);
    if (!serv.IsConnected())
    {
        cout << "ERROR - Connection to database failed." << endl;
        return 0;
    }

    cout << "fillsignal" << endl;
    cout << "----------" << endl;
    cout << endl;
    cout << "Connected to " << serv.GetName() << endl;
    cout << "File: " << fname << endl;
    cout << endl;

    return Process(serv, fname, dummy);
}
