/* ======================================================================== *\
!
! *
! * 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  12/2000 (tbretz@uni-sw.gwdg.de)
!
!   Copyright: MAGIC Software Development, 2000-2001
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
//  MRawEvtData
//
//  Storage container to store the raw FADC values.
//
//  MArrayS fHiGainPixId
//  ---------------------
//  Array of Pixel Numbers for their high voltage channel in the order the
//  FADC values are stored in fHiGainFadcSamples
//
//  MArrayB fHiGainFadcSaples
//  -------------------------
//  FADC samples (hi gain) of all pixels
//
//  MArrayS fLoGainPixId
//  --------------------
//  see fHiGainPixId
//
//  MArrayB fLoGainFadcSamples
//  --------------------------
//  see fHiGainFadcSaples
//
/////////////////////////////////////////////////////////////////////////////

#include "MRawEvtData.h"

#include <iomanip.h>

#include <fstream.h>

#include <TH1.h>
#include <TGraph.h>
#include <TArrayC.h>

#include "MLog.h"
#include "MArrayS.h"
#include "MArrayB.h"
#include "MRawRunHeader.h"

ClassImp(MRawEvtData);

// --------------------------------------------------------------------------
//
// Default constructor. It initializes all arrays with zero size.
//
MRawEvtData::MRawEvtData(const char *name, const char *title)
{
    fName  = name  ? name  : "MRawEvtData";
    fTitle = title ? title : "Raw Event Data Information";

    InitArrays();
}

// --------------------------------------------------------------------------
//
// Destructor. Deletes all the arrays.
//
MRawEvtData::~MRawEvtData()
{
    DeleteArrays();
}

// --------------------------------------------------------------------------
//
// reset all arrays
//
void MRawEvtData::Clear(Option_t *)
{
    /*
     FIXME:
     Is Reset (set all entries to zero) what you want to do
     or Set(0) (delete the array)
     */
    fHiGainPixId->Reset();
    fLoGainPixId->Reset();
    fHiGainFadcSamples->Reset();
    fLoGainFadcSamples->Reset();
}

// --------------------------------------------------------------------------
//
// return the number of hi gain samples per pixel
//
Byte_t MRawEvtData::GetNumHiGainSamples() const
{
    return fHiGainPixId->GetSize() ? fHiGainFadcSamples->GetSize()/fHiGainPixId->GetSize() : 0;
}

// --------------------------------------------------------------------------
//
// return the number of lo gain samples per pixel
//
Byte_t MRawEvtData::GetNumLoGainSamples() const
{
    return fLoGainPixId->GetSize() ? fLoGainFadcSamples->GetSize()/fLoGainPixId->GetSize() : 0;
}

// --------------------------------------------------------------------------
//
// return the number of stored pixel
//
UShort_t MRawEvtData::GetNumPixels() const
{
    return fHiGainPixId->GetSize();
}


// --------------------------------------------------------------------------
//
//  Print out the onformation to *fLog.
//  Options:
//     "hex"      Prints the time slices hexadecimal (default)
//     "dec"      Prints the time slices decimal
//
void MRawEvtData::Print(Option_t *opt) const
{
    //
    // print fadc inforation to screen
    // Possible Options:
    // - DEC: Print values decimal instead of hexadecimal (default)
    //
    const Byte_t nHiSamp = GetNumHiGainSamples();
    const Byte_t nLoSamp = GetNumLoGainSamples();

    const UShort_t nHiPix = fHiGainPixId->GetSize();;
    const UShort_t nLoPix = fLoGainPixId->GetSize();;

    fLog->unsetf(ios::showbase);

    *fLog << dec;
    *fLog << "HiGain: " << nHiPix << " Pixels with " << (Int_t)nHiSamp << " Samples" << endl;
    *fLog << "LoGain: " << nLoPix << " Pixels with " << (Int_t)nLoSamp << " Samples";;

    TString str(opt);
    Int_t manip = str.Contains("dec", TString::kIgnoreCase);

    Int_t l=0;
    for (int i=0; i<nHiPix; i++)
    {
        *fLog << endl;
        *fLog << " " << setfill(' ') << setw(3) << dec << i << ": ";
        *fLog << (manip?dec:hex) << flush;

        if (!manip)
            *fLog << setfill('0');

        for (int j=0; j<nHiSamp; j++)
        {
            *fLog << setw(manip?3:2);
            *fLog << ((UShort_t)(*fHiGainFadcSamples)[j+i*nHiSamp]&0xff);
            if (manip)
                *fLog << ' ';
            *fLog << flush;
        }

        if (!(l<nLoPix && (*fLoGainPixId)[l]==(*fHiGainPixId)[i]))
            continue;

        if (manip)
            *fLog << "/ ";

        for (int j=0; j<nLoSamp; j++)
        {
            *fLog << setw(manip?3:2);
            *fLog << ((UShort_t)(*fLoGainFadcSamples)[j+i*nLoSamp]&0xff);
            if (manip)
                *fLog << ' ';
            *fLog << flush;
        }
        l++;
    }
    *fLog << endl;
}

// --------------------------------------------------------------------------
//
// Draw a pixel. A Histogram or Graph is created and it's draw function is
// called.
//  Options:
//     "GRAPH"      A graph is drawn
//     "HIST"       A histogram is drawn
//     number       The pixel with the given number is drawn
//
void MRawEvtData::Draw(Option_t *opt)
{
    if (GetNumPixels()==0)
    {
        *fLog << "Sorry, no pixel to draw!" << endl;
        return;
    }

    TString str(opt);

    UInt_t num = 0;

    if (str.BeginsWith("GRAPH", TString::kIgnoreCase))
    {
        if (str.Length()>5)
            sscanf(&str[5], "%d", &num);

        if (num>=GetNumPixels())
            num= GetNumPixels();

        *fLog << "Drawing Graph: Pixel #" << num << " of " << (int)GetNumPixels() << endl;

        const Int_t n = GetNumHiGainSamples();

        Float_t *x = new Float_t[n];
        Float_t *y = new Float_t[n];

        for (int i=0; i<n; i++)
        {
            x[i] = i;
            y[i] = (*fHiGainFadcSamples)[i + num*GetNumHiGainSamples()];
        }

        TGraph *graph = new TGraph(n, x, y);
        graph->SetMaximum(256);
        graph->SetMinimum(0);

        graph->SetBit(kCanDelete);
        graph->Draw("AC*");

        TH1F *hist = graph->GetHistogram();

        hist->SetXTitle("Time/FADC Slices");
        hist->SetYTitle("Signal/FADC Units");

        return;
    }

    if (str.BeginsWith("HIST", TString::kIgnoreCase))
    {
        *fLog << "Length: " << str.Length() << endl;

        if (str.Length()>4)
            sscanf(&str[4], "%d", &num);

        if (num>=GetNumPixels())
            num= GetNumPixels();

        *fLog << "Drawing Histogram of Pixel " << num << endl;

        const Int_t n = GetNumHiGainSamples();

        char *name = new char[16];

        sprintf(name, "Pixel No.%d", (*fHiGainPixId)[num]);

        TH1F *hist = new TH1F(name, "Hi Gain Samples FADC", n, 0, n);
        hist->SetXTitle("Time/FADC Slices");
        hist->SetYTitle("Signal/FADC Units");

        for (int i=0; i<n; i++)
            hist->Fill(0.5+i, (*fHiGainFadcSamples)[i + num*GetNumHiGainSamples()]);

        hist->SetBit(kCanDelete);
        hist->Draw();

        return;
    }

    *fLog << "MRawEvtData::Draw: Warning: You must specify either 'GRAPH' or 'HIST'" << endl;
}

// --------------------------------------------------------------------------
//
// Deletes all arrays describing the pixel Id and Samples in pixels.
// The flag is for future usage.
//
void MRawEvtData::DeletePixels(Bool_t flag)
{
    const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();

    if (fArraySize == npix && flag)
    {
        fPosInArray = 0;
        return;
    }

    DeleteArrays();
    InitArrays(flag);
}

// --------------------------------------------------------------------------
//
//  Deletes all the arrays
//
void MRawEvtData::DeleteArrays()
{
    delete fHiGainPixId;
    delete fLoGainPixId;
    delete fHiGainFadcSamples;
    delete fLoGainFadcSamples;
}

// --------------------------------------------------------------------------
//
//  Deletes all the arrays
//  The flag is for future usage.
//
void MRawEvtData::InitArrays(Bool_t flag)
{
    if (flag)
    {
        const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();

        fHiGainPixId       = new MArrayS(npix);
        fLoGainPixId       = new MArrayS(npix);
        fHiGainFadcSamples = new MArrayB(npix*fRunHeader->GetNumSamplesHiGain());
        fLoGainFadcSamples = new MArrayB(npix*fRunHeader->GetNumSamplesLoGain());

        fArraySize  = npix;
    }
    else
    {
        fHiGainPixId       = new MArrayS(0);
        fLoGainPixId       = new MArrayS(0);
        fHiGainFadcSamples = new MArrayB(0);
        fLoGainFadcSamples = new MArrayB(0);

        fArraySize = 0;
    }

    fPosInArray = 0;
}

// --------------------------------------------------------------------------
//
//  This is to fill the data of one pixel to the MRawEvtHeader Class.
//  The parameters are the pixelnumber and the FADC_SLICES values of ADCs
//  Add to lo gains if lflag = 1
//
void MRawEvtData::AddPixel(UShort_t nOfPixel, TArrayC *data, Bool_t lflag)
{
    MArrayS *arrpix = lflag ? fLoGainPixId       : fHiGainPixId;
    MArrayB *arrsam = lflag ? fLoGainFadcSamples : fHiGainFadcSamples;

    //
    // check whether we got the right number of new samples
    // if there are no samples already stored: this is the new number of samples
    //
    const Byte_t ns    = data->GetSize();
    const Byte_t nSamp = lflag ? GetNumLoGainSamples() : GetNumHiGainSamples();
    if (nSamp && ns!=nSamp)
    {
        *fLog << "RawEvtData::AddPixel: Error, number of samples in ";
        *fLog << "TArrayC doesn't match actual number" << endl;
        return;
    }

    //
    // enhance pixel array by one
    //
    arrpix->Set(arrpix->GetSize()+1);

    //
    // add the number of the new pixel to the array as last entry
    //
    arrpix->AddAt(nOfPixel, arrpix->GetSize()-1);

    //
    // enhance the array by the number of new samples
    //
    arrsam->Set(arrsam->GetSize()+ns);

    //
    // add the new slices as last entries to array
    //
    arrsam->AddAt((Byte_t*)data->GetArray(), arrsam->GetSize()-ns, ns);
}

// --------------------------------------------------------------------------
//
// Fills members with information from a magic binary file.
//   WARNING: you have to use Init() before you can do this
//
void MRawEvtData::ReadEvt(istream &fin)
{
    const UShort_t nlo = fRunHeader->GetNumSamplesLoGain();
    const UShort_t nhi = fRunHeader->GetNumSamplesHiGain();

    const UShort_t npic = fRunHeader->GetNumPixInCrate();

    const UShort_t npos = npic*fPosInArray;

    Byte_t *higainsam = fHiGainFadcSamples->GetArray()+nhi*npos;
    Byte_t *logainsam = fLoGainFadcSamples->GetArray()+nlo*npos;

    // UShort_t *hipixid = (UShort_t*)fHiGainPixId->GetArray()+npos;
    // UShort_t *lopixid = (UShort_t*)fLoGainPixId->GetArray()+npos;

    for (int i=0; i<npic; i++)
    {
        //
        // get the spiral pixel number from the run header
        //
        const UShort_t npix = fRunHeader->GetPixAssignment(i);

        const UShort_t ipos = npos+i;
        //
        //  This is to fill the data of one pixel to the MRawEvtHeader Class.
        //  The parameters are the pixelnumber and the FADC_SLICES values of ADCs
        //  Add to lo gains if lflag = 1
        //
        fHiGainPixId->AddAt(npix, ipos);
        fin.read(higainsam, nhi);
        higainsam += nhi;

        // FIXME: Not implemented in the raw files yet
        //if (IsLoGainOn(i, j))
        //{
        fLoGainPixId->AddAt(npix, ipos);
        fin.read(logainsam, nlo);
        logainsam += nlo;
        //}
    }
}

