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

/////////////////////////////////////////////////////////////////////////////
//
// MRawEvtHeader 
//    
// One Event is a sample of FADC measurements of different Pixels 
// (Photomultipliers) from the Camera of MAGIC. So all data (FADC) of the 
// interesting pixels are the modules of an event. To describe pixels the 
// class MRawPixel is used and the class MRawCrate to describe Crates.
// To define a single events some other data members are needed 
// (Time of the events, tirgger pattern of event..)
// 
// To describe one event on the level of FADC values the Class MRawEvtHeader is
// created. It has the following data members: 
//
// UInt_t    fDAQEvtNumber
// -----------------------
// This it the number of the Event in one 
// data run. The first event in this run get
// the number zero. The next one is one bigger.
//
// Assuming that one run takes 1 hour and a
// triggerrate of 1kHz the number must be able
// to reach 3.6e6 Events. To reach this number
// you need at least 22 bits. This is the reason
// why we use an integer (of root type UInt_t)
// with a range to 4.2e9. 
//
// MTime   fRawEvtTime
// -------------------
// Time of the event. 
// The start point of the time determination can be
// the millenium. From that start point the time is
// measured in 200ns-count. One day for example
// contains 432.e9 counts. An array of two unsigned Int is able to 
// contain 1.8e19 200ns-counts. This corresponds to 41.e6
// days. This should be more than the livetime of MAGIC.
// Private member of MTime.h
//
// UInt_t  fNumTrigLvl1
// --------------------
//
// Number of first level trigger
// This member counts the number of First Level Trigger
// between the last and this event. May be that due to 
// dead time of the DAQ this number is different from 1.
// If the DAQ is fast enough, this value should be 1. 
// This may be usefull in GammaRayBursts and if we 
// apply a data reduction in the DAQ-chain, which selects
// only good events. 
//
// UInt_t  fNumTrigLvl2
// ------------------ -
//
// Number of second level trigger
// This member counts the number of Second Level Trigger
// between the last and this event. 
//
// UInt_t  fTrigPattern[2]
// -----------------------
// Trigger Pattern used for this event
// Each event triggers for a particular configuration and each  
// configuration shoul have an ID (which is not fixed yet).
//
// UShort_t fAllLowGainOn
// ----------------------
// Type of Trigger. 
// This is a Byte (8 bit) to indicated if any of the pixels 
// have a non-negligible low gain (1) or not (0) 
//
/////////////////////////////////////////////////////////////////////////////
#include "MRawEvtHeader.h"

#include <iomanip>
#include <fstream>

#include "MLog.h"
#include "MLogManip.h"

#include "MTime.h"
#include "MArrayB.h"
#include "MRawRunHeader.h"

ClassImp(MRawEvtHeader);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor. Create the array to store the data.
//
MRawEvtHeader::MRawEvtHeader(const char *name, const char *title)
{
    fName  = name  ? name  : "MRawEvtHeader";
    fTitle = title ? title : "Raw Event Header Information";

    //
    //   set all member to zero, init the pointer to ClonesArray,
    //
    fPixLoGainOn = new MArrayB;

    Clear();
}

// --------------------------------------------------------------------------
//
// Destructor. Deletes the array to store pixlogainon
//
MRawEvtHeader::~MRawEvtHeader()
{
    delete fPixLoGainOn;
}

// --------------------------------------------------------------------------
//
// you have to init the conatainer before you can read from
// a raw binary file
//
void MRawEvtHeader::Init(MRawRunHeader *rh, MTime *t)
{
    //
    // this is the number of entries in the array like specification
    //
    UInt_t fN = (rh->GetNumCrates() * rh->GetNumPixInCrate() + 7) / 8;

    //
    // initialize the array
    //
    fPixLoGainOn->Set(fN);

    //
    // this is the conatiner where we have to store the time of the event we
    // read from the input stream
    //
    fTime = t;
}

// --------------------------------------------------------------------------
//
//   Implementation of the Clear function
//
//   Resets all members to zero, clear the list of Pixels
//
void MRawEvtHeader::Clear(Option_t *)
{
    fDAQEvtNumber   = 0;
    fNumTrigLvl1    = 0;
    fNumTrigLvl2    = 0;
    fTrigPattern[0] = 0;
    fTrigPattern[1] = 0;
    fTrigType       = 0;
    fNumLoGainOn    = 0;
}

// --------------------------------------------------------------------------
//
//  This member function prints all Data of one Event to *fLog.
//
void MRawEvtHeader::Print(Option_t *o) const
{
    *fLog << all;
    *fLog << "DAQEvtNr: " << dec << fDAQEvtNumber << "  (";
    *fLog << "Trigger: ";
    *fLog << "NumLvl1=" << fNumTrigLvl1 << " ";
    *fLog << "NumLvl2=" << fNumTrigLvl2 << " ";
    *fLog << "Pattern=" << hex << setfill('0');
    *fLog << setw(2) << fTrigPattern[0];
    *fLog << setw(2) << fTrigPattern[1] << " " << dec;

    *fLog << "Type=";
    switch (fTrigType)
    {
    case 0:
        *fLog << "Trigger";
        break;
    case 1:
        *fLog << "Pedestal";
        break;
    case 2:
        *fLog << "Calibration";
        break;
    }
    *fLog << ")" << endl;
    *fLog << "Number of Lo Gains On: " << fNumLoGainOn << endl;

    TString str(o);
    str.ToLower();

    if (str.Contains("nogains"))
        return;

    for (unsigned int i=0; i<fPixLoGainOn->GetSize(); i++)
    {
        for (int j=0; j<8; j++)
        {
            const UInt_t on = (*fPixLoGainOn)[i]&(1<<j) ? 1 : 0;
            *fLog << on;
        }
    }
    if (fPixLoGainOn->GetSize())
        *fLog << endl;
}

// --------------------------------------------------------------------------
//
// used to set the header information (eg. from MC)
//
void MRawEvtHeader::FillHeader(UInt_t uiN, Float_t ulTP)
{
    fDAQEvtNumber = uiN;
    fTrigPattern[0] = (UInt_t)(ulTP/4294967296.0) ;
    fTrigPattern[1] = (UInt_t)(ulTP-fTrigPattern[0]*4294967296.0);
}

Bool_t MRawEvtHeader::DecodeTime(UInt_t abstime[2]) const
{
    // BADC|1032 --> DCBA|3210 (Byte swap - exchange MSB and LSB)
    *fLog << hex << all << endl << abstime[0] << " " << abstime[1] << endl;

    abstime[0] = (abstime[0]<<16) | (abstime[0]>>16);
//  abstime[1] = (abstime[1]<<16) | (abstime[1]>>16);
//    *fLog << hex << abstime[0] << " " << abstime[1] << endl;
//    *fLog << dec;

    abstime[0] = abstime[0]<<8&0xff00 | abstime[0]>>8&0x00ff | abstime[0]&0xffff0000;
    abstime[1] = abstime[1]<<8&0xff00 | abstime[1]>>8&0x00ff | abstime[1]&0xffff0000;

    for (int i=4*8-1; i>=0; i--)
        *fLog << (int)(abstime[0]&BIT(i)?1:0);
    *fLog << " ";
    for (int i=4*8-1; i>=0; i--)
        *fLog << (int)(abstime[1]&BIT(i)?1:0);
    *fLog << endl;

/*    *fLog << hex << abstime[0] << " " << abstime[1] << endl;
*/

    // Strange thing!
    Char_t t = abstime[0]>>8 &0xf;
    abstime[0] &= 0xfffff0ff;

//    *fLog << abstime[0]<< " " << (int)t << endl;


    for (int i=0; i<4; i++)
    {
        abstime[0] |= (t&BIT(i) ? 1 : 0)<<(11-i);
        //*fLog << ((t&BIT(i) ? 1 : 0)<<(11-i)) << " ";
    }

    //*fLog << endl << abstime[0]<< endl;

    // Decode
    const Byte_t h = (abstime[0]>>18 & 0x3)*10 + (abstime[0]>>14 & 0xf);
    const Byte_t m = (abstime[0]>>11 & 0x7)*10 + (abstime[0]>> 7 & 0xf);
    const Byte_t s = (abstime[0]>> 4 & 0x7)*10 + (abstime[0]>> 0 & 0xf);
    const Int_t ms =
        ((abstime[0]>>12)&0xf)*1000 +
        ((abstime[0]>> 8)&0xf)* 100 +
        ((abstime[0]>> 4)&0xf)*  10 +
        ((abstime[0]>> 0)&0xf)*   1;

    // hms   =3210 -->  h=2:4 m=3:4 s=3:4
    // subsec=DCBA --> subsec?
    *fLog << all << dec << setfill('0') << setw(2) << (int)h << ":" << setw(2) << (int)m << ":" << setw(2) << (int)s;
    *fLog << " " << hex;
    *fLog << (int)(abstime[0]>>12 & 0xf) << ".";
    *fLog << (int)(abstime[0]>> 8 & 0xf) << ".";
    *fLog << (int)(abstime[0]>> 4 & 0xf) << ".";
    *fLog << (int)(abstime[0]>> 0 & 0xf);
    *fLog << endl;

    // Update the time stamp with the current event time.
    // Make sure, that the time stamp was initialized correctly
    // with the start-date/time of the run (after reading the run header)
    //
    // Here the nanosec precision is ignored... (FIXME!)

    static int i=0;
    i++;
    fTime->Print();
    fTime->UpdMagicTime(h, m, s, 0/*ms*/);
    fTime->Print();
    return i<5;
    //return fTime->UpdMagicTime(h, m, s, ms);
}

// --------------------------------------------------------------------------
//
// read the EVENT HEADER information from the input stream
// return FALSE if there is now header anymore, else TRUE
//
// Updates the time stamp with the current event time.
// Make sure, that the time stamp was initialized correctly
// with the start-date/time of the run (after reading the run header)
//
// Remark: This 'feature' disallows single runs of more than 11h!
//
int MRawEvtHeader::ReadEvt(istream &fin)
{
    fin.read((char*)&fDAQEvtNumber, 4);  // Total=4

    *fLog << "N: " << fDAQEvtNumber << endl;

    UInt_t abstime[2];                   // BADC|1032
    fin.read((char*)abstime,        8);  // Total=12
    if (!DecodeTime(abstime))
    {
        *fLog << err << "ERROR - Event time in event header invalid... abort." << endl;
        return kFALSE;
    }

    Byte_t dummy[4];
    fin.read((char*)&fNumTrigLvl1,  4);  // Total=16
    fin.read((char*)&fNumTrigLvl2,  4);  // Total=20
    fin.read((char*)fTrigPattern,   8);  // Total=28
    fin.read((char*)&fTrigType,     2);  // Total=30
    fin.read((char*)dummy,          2);  // Total=32, was fAllLoGainOn
    fin.read((char*)fPixLoGainOn->GetArray(), fPixLoGainOn->GetSize());

    *fLog << "T: " << fTrigType << endl;

    fNumLoGainOn = 0;
    for (unsigned int i=0; i<fPixLoGainOn->GetSize(); i++)
        for (int j=0; j<8; j++)
            if ((*fPixLoGainOn)[i] & (1<<j))
                fNumLoGainOn++;

    fin.read((char*)&dummy, 4);

    return !fin.eof();
}
