/* ======================================================================== *\
!
! *
! * 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, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
!         
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */
//////////////////////////////////////////////////////////////////////////////
//
//  MCalibColorSet
//
//  Sets the color for events depending on the color which was used for
//  the run. This is a workaround for runs which were taken before the
//  digital module could deliver the color 'per event'
// 
//  Input Containers:
//   MRawRunHeader
//
//  Output Containers:
//   MRawEvtHeader
//
//////////////////////////////////////////////////////////////////////////////
#include "MCalibColorSet.h"

#include "TRegexp.h"

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

#include "MParList.h"

#include "MRawEvtHeader.h"
#include "MRawRunHeader.h"

ClassImp(MCalibColorSet);


using namespace std;

const Int_t MCalibColorSet::gkIFAEBoxInaugurationRun = 20113;
const Int_t MCalibColorSet::gkMCRunLimit             = 1000;
const UInt_t MCalibColorSet::gkFirstRunWithFinalBits = 45626;
// --------------------------------------------------------------------------
//
//  Default constructor. MGeomCamMagic is the default geometry.
//
MCalibColorSet::MCalibColorSet(const char *name, const char *title)
    : fHeader(0)
{
  fName  = name  ? name  : "MCalibColorSet";
  fTitle = title ? title : "Task to set workaround missing colors calibration events";

  Clear();
}

void MCalibColorSet::Clear(const Option_t *o)
{
  
  fPattern = 0;
  fIsValid = kFALSE;
  
}


// -----------------------------------------------------------------------------------
//
// The following container are searched for and execution aborted if not in MParList:
//  - MRawEvtHeader
//
Int_t MCalibColorSet::PreProcess(MParList *pList)
{

  fHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
  if (!fHeader)
    {
      *fLog << err << "MRawEvtHeader not found... abort." << endl;
      return kFALSE;
    }

  return kTRUE;
}

// --------------------------------------------------------------------------
//
// Search for the following input containers and abort if not existing:
// - MRawRunHeader
//
// If Runnumber < gkIFAEBoxInaugurationRun, set colour pattern: 0
//
// If Runnumber > gkIFAEBoxInaugurationRun, search for colour in 
// the project name: Set colour pattern according to the following 
// convention: 
//    Green: assume slot 1  ( 5 Leds Green)
//    Blue:  assume slot 14 ( 5 Leds Blue )
//    UV:    assume slot 12 ( 5 Leds UV   )
//    CT1:   take  'slot 17'
//
Bool_t MCalibColorSet::ReInit(MParList *pList)
{

  Clear();

  MRawRunHeader *header = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
  if (!header)
    {
      *fLog << err << "MRawRunHeader not found... abort." << endl;
      return kFALSE;
    }
  
  if (header->GetRunNumber() > gkFirstRunWithFinalBits)
    return kTRUE;

  //
  // Consider the case that a pedestal run is interleaved in the calibration run sequence ... prepare
  // to skip this run.
  //
  if (header->GetRunType() == MRawRunHeader::kRTPedestal)
    {
      *fLog << warn << "New run is a pedestal run... need intensity calibration to treat this case!" << endl;
      fPattern = 0;
      fIsValid = kTRUE;      
      return kTRUE;
    }

  enum { kNONE, kGREEN, kBLUE, kUV, kCT1 };
  
  enum ColorCode_t 
    {
      k01LedGreen  = BIT(15),
      k1LedGreen   = BIT(14),
      k2LedGreen   = BIT(1 ),
      k3LedGreen   = k1LedGreen | k2LedGreen,
      k5LedGreen   = BIT(0 ),
      k6LedGreen   = k5LedGreen | k1LedGreen,
      k7LedGreen   = k5LedGreen | k2LedGreen,
      k8LedGreen   = k5LedGreen | k3LedGreen,
      k1LedUV      = BIT(3 ),
      k2LedUV      = BIT(4 ),
      k3LedUV      = k1LedUV | k2LedUV,
      k5LedUV1     = BIT(11),
      k5LedUV2     = BIT(12),
      k6LedUV      = k5LedUV1 | k1LedUV,
      k7LedUV      = k5LedUV1 | k2LedUV,
      k8LedUV      = k5LedUV1 | k3LedUV,
      k10LedUV     = k5LedUV1 | k5LedUV2,
      k11LedUV     = k10LedUV | k1LedUV,
      k12LedUV     = k10LedUV | k2LedUV,
      k13LedUV     = k10LedUV | k1LedUV,
      k01LedBlue   = BIT(8 ),
      k1LedBlue    = BIT(10),
      k2LedBlue    = BIT(7 ),
      k3LedBlue    = k1LedBlue | k2LedBlue,
      k5LedBlue1   = BIT(13),
      k5LedBlue2   = BIT(2 ),      
      k5LedBlue3   = BIT(5 ),
      k5LedBlue4   = BIT(6 ),
      k6LedBlue    = k5LedBlue1 | k1LedBlue,
      k7LedBlue    = k5LedBlue1 | k2LedBlue,
      k8LedBlue    = k5LedBlue1 | k3LedBlue,
      k10LedBlue   = k5LedBlue1 | k5LedBlue2,
      k15LedBlue   = k10LedBlue | k5LedBlue3,
      k20LedBlue   = k15LedBlue | k5LedBlue4,
      k21LedBlue   = k20LedBlue | k1LedBlue,
      k22LedBlue   = k20LedBlue | k2LedBlue,
      k23LedBlue   = k22LedBlue | k1LedBlue,
      kCT1Pulser   = BIT(16)
    };

  const Int_t num = header->GetRunNumber();

  if (num<gkMCRunLimit)
    {
      *fLog << inf << "Assumed MC run ... using GREEN pulser." << endl;
      fPattern |= k1LedGreen;
      fIsValid  = kTRUE;
      return kTRUE;
    }

  if (num<gkIFAEBoxInaugurationRun)
    {
      *fLog << inf << "Run taken before inauguration of IFAE-box... using CT1 pulser." << endl;
      fPattern |= kCT1Pulser;
      fIsValid  = kTRUE;
      return kTRUE;
    }
  
  Int_t color = kNONE;

  switch (num)
    {
    case 22246:
    case 22253:
    case 25792:
    case 26402:
    case 35415:
    case 44768:
    case 44976:
    case 45249:
    case 45253:
    case 45262:
    case 45274:
    case 45275:
    case 45276:
    case 45365:
    case 45366:
    case 45367:
    case 45368:
    case 45369:
    case 45370:
    case 45371:
    case 45382:
    case 45401:
    case 45419:
    case 45432:
    case 45471:
    case 45485:
    case 45489:
      //    case 31756:
      color = kBLUE;
      break;
      
    case 30090:
    case 31745:
    case 31746:
    case 31747:
    case 31748:
    case 20660:
    case 20661:
    case 26408:
    case 26409:
    case 26412:
    case 26568:
    case 26924:
    case 45227:
    case 45241:
    case 45250:
    case 45254:
    case 45263:
    case 45372:
    case 45373:
      color = kGREEN;
      break;
      
    case 45216:
    case 45218:
    case 45226:
    case 45240:
    case 45251:
    case 45278:
    case 45336:
    case 45341:
    case 45358:
    case 45374:
    case 45375:
    case 45376:
    case 45377:
    case 45381:
    case 45400:
    case 45418:
    case 45431:
    case 45470:
    case 45484:
    case 45490:
      color = kUV;
      break;
      
    case 27474:
      *fLog << err << "Sorry, run 27474 was taken with CLOSED LIDS. It should not be used! " << endl;
      return kFALSE;
      break;
      
    case 45219:
      *fLog << err << "Sorry, run 45219 was taken with a combination of colours used to flat-field ";
      *fLog << err << "the camera. It cannot be used for the standard calibration " << endl;
      return kFALSE;
      break;
    }
  
  if (color!=kNONE)
    {
      *fLog << inf << "Color determined from the run-number... ";
      switch (color)
        {
        case kGREEN: *fLog << "Green."; fPattern |= k5LedGreen; break;
        case kBLUE:  *fLog << "Blue.";  fPattern |= k5LedBlue1; break;
        case kUV:    *fLog << "UV.";    fPattern |= k10LedUV; break;
        }
      *fLog << endl;
      fIsValid  = kTRUE;
      return kTRUE;
    }
  else
    {

      TString proj = header->GetProjectName();
      proj.ToLower();

      // Possible green combinations
      TRegexp gre0("0.1led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre0))
        { fPattern |= k01LedGreen; color = kGREEN;    }
      TRegexp gre1("1led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre1))
        { fPattern |= k1LedGreen; color = kGREEN;    }
      TRegexp gre2("2led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre2))
        { fPattern |= k2LedGreen; color = kGREEN;    }
      TRegexp gre3("3led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre3))
        { fPattern |= k3LedGreen; color = kGREEN;    }
      TRegexp gre5("5led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre5))
        { fPattern |= k5LedGreen; color = kGREEN;    }
      TRegexp gre6("6led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre6))
        { fPattern |= k6LedGreen; color = kGREEN;    }
      TRegexp gre7("7led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre7))
        { fPattern |= k7LedGreen; color = kGREEN;    }
      TRegexp gre8("8led[sS]?[gG][rR][eE][eE]");
      if (proj.Contains(gre8))
        { fPattern |= k8LedGreen; color = kGREEN;    }

      // Possible blue combinations
      TRegexp blu0("0.1led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu0))
        { fPattern |= k01LedBlue; color = kBLUE;    }
      TRegexp blu1("1led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu1))
        { fPattern |= k1LedBlue; color = kBLUE;    }
      TRegexp blu2("2led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu2))
        { fPattern |= k2LedBlue; color = kBLUE;    }
      TRegexp blu3("3led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu3))
        { fPattern |= k3LedBlue; color = kBLUE;    }
      TRegexp blu5("5led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu5))
        { fPattern |= k5LedBlue1; color = kBLUE;    }
      TRegexp blu6("6led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu6))
        { fPattern |= k6LedBlue; color = kBLUE;    }
      TRegexp blu7("7led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu7))
        { fPattern |= k7LedBlue; color = kBLUE;    }
      TRegexp blu8("8led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu8))
        { fPattern |= k8LedBlue; color = kBLUE;    }
      TRegexp blu10("10led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu10))
        { fPattern |= k10LedBlue; color = kBLUE;    }
      TRegexp blu15("15led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu15))
        { fPattern |= k15LedBlue; color = kBLUE;    }
      TRegexp blu20("20led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu20))
        { fPattern |= k20LedBlue; color = kBLUE;    }
      TRegexp blu21("21led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu21))
        { fPattern |= k21LedBlue; color = kBLUE;    }
      TRegexp blu22("22led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu22))
        { fPattern |= k22LedBlue; color = kBLUE;    }
      TRegexp blu23("23led[sS]?[bB][lL][uU][eE]");
      if (proj.Contains(blu23))
        { fPattern |= k23LedBlue; color = kBLUE;    }

      // Possible UV combinations
      TRegexp uv1("1led[sS]?[U][vV]");
      if (proj.Contains(uv1))
        { fPattern |= k1LedUV; color = kUV;    }
      TRegexp uv2("2led[sS]?[U][vV]");
      if (proj.Contains(uv2))
        { fPattern |= k2LedUV; color = kUV;    }
      TRegexp uv3("3led[sS]?[U][vV]");
      if (proj.Contains(uv3))
        { fPattern |= k3LedUV; color = kUV;    }
      TRegexp uv5("5led[sS]?[U][vV]");
      if (proj.Contains(uv5))
        { fPattern |= k5LedUV1; color = kUV;    }
      TRegexp uv6("6led[sS]?[U][vV]");
      if (proj.Contains(uv6))
        { fPattern |= k6LedUV; color = kUV;    }
      TRegexp uv7("7led[sS]?[U][vV]");
      if (proj.Contains(uv7))
        { fPattern |= k7LedUV; color = kUV;    }
      TRegexp uv8("8led[sS]?[U][vV]");
      if (proj.Contains(uv8))
        { fPattern |= k8LedUV; color = kUV;    }
      TRegexp uv10("10led[sS]?[U][vV]");
      if (proj.Contains(uv10))
        { fPattern |= k10LedUV; color = kUV;    }
      TRegexp uv11("11led[sS]?[U][vV]");
      if (proj.Contains(uv11))
        { fPattern |= k11LedUV; color = kUV;    }
      TRegexp uv12("12led[sS]?[U][vV]");
      if (proj.Contains(uv12))
        { fPattern |= k12LedUV; color = kUV;    }
      TRegexp uv13("13led[sS]?[U][vV]");
      if (proj.Contains(uv13))
        { fPattern |= k13LedUV; color = kUV;    }

      // Possible slot combinations
      TRegexp slot("slot");
      if (proj.Contains(slot))
        {
          proj.ReplaceAll("slot","");
          UInt_t nr = 0;
          TRegexp slotnr("^[0-9]");
          
          if (proj.Contains(slotnr))
            { fPattern = 0; proj.Replace(2,99,""); 
            proj.ReplaceAll("u","");
            proj.ReplaceAll("v","");
            proj.ReplaceAll("g","");
            nr = atoi(proj.Data())-1; 
            fPattern |= BIT(nr);
            color = nr < 2 ? kGREEN : 
              ( nr < 3 ) ? kBLUE : 
              ( nr < 5 ) ? kUV : 
              ( nr < 11 ) ? kBLUE : 
              ( nr < 13 ) ? kUV : 
              ( nr < 14 ) ? kBLUE : 
              ( nr < 16 ) ? kGREEN : 
              kCT1;    
            }
        }
      
      if (color != kNONE)
        *fLog << inf << "Color and Intensity determined from project-name (" << proj << ")... ";          
      else
        {
          if (proj.Contains("gree",TString::kIgnoreCase))
            { fPattern |= k5LedGreen; color = kGREEN; }
          if (proj.Contains("blue",TString::kIgnoreCase))
            { fPattern |=k5LedBlue1; color = kBLUE;}
          if (proj.Contains("uv",TString::kIgnoreCase))
            { fPattern |=k5LedUV1  ; color = kUV;  }
          if (proj.Contains("ct1",TString::kIgnoreCase))
            { fPattern |=kCT1Pulser; color = kCT1; }
          if (color != kNONE)
            *fLog << inf << "Color determined from project-name (" << proj << ")... ";
          else if (proj.Contains("cl",TString::kIgnoreCase))
            {
              *fLog << warn << "This run has been taken with the continuous light source." << endl;
              *fLog << warn 
                    << "It cannot be used for calibration. Try to run a pedestal extraction on it." << endl;
              fPattern = 0;
              fIsValid = kTRUE;
              return kTRUE;
            }
        }
    }
  
  if (color==kNONE)
    {
      *fLog << err << "Sorry, calibration run " << num << " was taken before the events could be" << endl;
      *fLog << "flagged with a color by the digital modul and no color" << endl;
      *fLog << "could be determined... abort." << endl;
      return kFALSE;
    }
  
  switch (color)
    {
    case kGREEN: *fLog << "Green.";  break;
    case kBLUE:  *fLog << "Blue.";   break;
    case kUV:    *fLog << "UV.";     break;
    case kCT1:   *fLog << "CT1.";    break;
    }
  *fLog << endl;
  
  fIsValid = kTRUE;
  
  return kTRUE;
}

// --------------------------------------------------------------------------
//
// Sets the pattern to MRawEvtHeader from outside, if fIsValid is set.
//
Int_t MCalibColorSet::Process()
{

  if (fIsValid)
    {
      if (fPattern == 0)
        return kCONTINUE;

      fHeader->SetCalibrationPattern(fPattern);
    }
  
  return kTRUE;
}
