]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliGRPPreprocessor.cxx
Increased size of collection in Merge and protected SaveHistograms
[u/mrichter/AliRoot.git] / STEER / AliGRPPreprocessor.cxx
index f3ad733c7d0a6d6c20d042cabc04e193d7b8b275..11d0006786a80e10fa06489b0d93c564452a609f 100644 (file)
 
 #include "AliTriggerConfiguration.h"
 #include "AliTriggerRunScalers.h"
+#include "AliTriggerInput.h"
 
 #include "AliCDBMetaData.h"
-#include "AliLog.h"
 #include "AliESDVertex.h"
 #include "AliLHCReader.h"
 #include "AliLHCData.h"
 #include "AliDCSArray.h"
+#include "AliDAQ.h"
+#include "AliLTUConfig.h"
 
+class AliLog;
 class AliDCSValue;
 class AliShuttleInterface;
 
@@ -64,6 +67,7 @@ class AliShuttleInterface;
 #include <AliCDBId.h>
 #include <AliTriggerConfiguration.h>
 #include <AliCTPTimeParams.h>
+#include <AliLHCClockPhase.h>
 
 const Double_t kFitFraction = -1.;                 // Fraction of DCS sensor fits required
 
@@ -74,7 +78,7 @@ ClassImp(AliGRPPreprocessor)
   const Int_t AliGRPPreprocessor::fgknDAQLbPar = 6; // num parameters in the logbook used to fill the GRP object
   const Int_t AliGRPPreprocessor::fgknDCSDP = 48;   // number of dcs dps
   const Int_t AliGRPPreprocessor::fgknDCSDPHallProbes = 40;   // number of dcs dps
-  const Int_t AliGRPPreprocessor::fgknLHCDP = 4;   // number of dcs dps from LHC data
+  const Int_t AliGRPPreprocessor::fgknLHCDP = 6;   // number of dcs dps from LHC data
   const Int_t AliGRPPreprocessor::fgkDCSDPHallTopShift = 4;   // shift from the top to get tp the Hall Probes names in the list of DCS DPs
   const Int_t AliGRPPreprocessor::fgkDCSDPNonWorking = 5; // number of non working DCS DPs
   const char* AliGRPPreprocessor::fgkDCSDataPoints[AliGRPPreprocessor::fgknDCSDP] = {
@@ -179,7 +183,9 @@ ClassImp(AliGRPPreprocessor)
          "LHC_Beam_Energy",
          "LHC_MachineMode",
          "LHC_BeamMode",
-          "LHC_Beams_Particle_Type"
+          "LHC_Beams_Particle_Type",
+         "BPTX_Phase_Shift_B1",
+         "BPTX_Phase_Shift_B2"
   };
 
   const char* kppError[] = {
@@ -193,7 +199,9 @@ ClassImp(AliGRPPreprocessor)
                    "(CTP timing ERROR)",
                   "(SPD Mean Vertex ERROR)",
                   "(DCS FXS Error for LHC Data)",
-                  "(LHC Data Error)"
+                  "(LHC Data Error)",
+                  "(LHC Clock Phase Error (from LHC Data))",
+                  "(LTU Configuration Error)"
   };
 
 //_______________________________________________________________
@@ -514,6 +522,93 @@ UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
                error |= 32;
        }
 
+        //===========================//
+       // LTU Configuration         //
+        //===========================//
+
+       Log("*************** Processing LTU Configuration");
+       
+       if (partition.IsNull() && !detector.IsNull()){ // standalone partition
+               Log("STANDALONE partition for current run, not retrieving LTU configuration");
+               /*
+               Log("STANDALONE partition for current run, using LTU configuration dummy value");
+               AliCDBEntry *cdbEntry = GetFromOCDB("CTP","DummyLTUConfig");
+               if (!cdbEntry) {
+                       Log(Form("No dummy LTU Config entry found, going into error..."));
+                       error |= 2048;
+               }
+               else{
+                       TObjArray *ltuConfig = (TObjArray*)cdbEntry->GetObject();
+                       if (!ltuConfig){
+                               Log(Form("dummy LTU Config not found in OCDB entry, going into error..."));
+                               error |= 2048;
+                       }
+                       else {
+                               AliCDBMetaData metadata;
+                               metadata.SetResponsible("Roman Lietava");
+                               metadata.SetComment("LTU Config from dummy entry in OCDB");
+                               if (!Store("CTP","LTUConfig", ltuConfig, &metadata, 0, 0)) {
+                                       Log("Unable to store the dummy LTU Config object to OCDB!");
+                                       error |= 2048;
+                               }
+                       }
+               }
+               */
+       }
+
+       else if (!partition.IsNull() && detector.IsNull()){ // global partition
+       
+               Log("GLOBAL partition for current run, getting LTU Config from DAQ Logbook (logbook_detectors table)");
+               UInt_t  detectorMask = (UInt_t)(((TString)GetRunParameter("detectorMask")).Atoi());
+               Printf ("detectormask = %d",detectorMask);
+               TObjArray * ltuarray = new TObjArray();
+               ltuarray->SetOwner(1);
+               Bool_t isLTUok = kTRUE;
+               for(Int_t i = 0; i<AliDAQ::kNDetectors-2; i++){
+                       if ((detectorMask >> i) & 0x1) {
+                               TString det = AliDAQ::OfflineModuleName(i);
+                               TString detCTPName = AliTriggerInput::fgkCTPDetectorName[i];
+                               if (detCTPName == "CTP") {
+                                       detCTPName="TRG"; // converting according to what is found in DAQ logbook_detectors                                     
+                                       Printf("Processing CTP (CTP Detector name %s) --> SKIPPING, CTP does not have any LTU!!!!!!",detCTPName.Data());
+                                       continue;
+                               }                               
+                               Printf("Processing detector %s (CTP Detector name %s)",det.Data(),detCTPName.Data());
+                               TString* ltu = GetLTUConfig(detCTPName.Data());
+                               if (!ltu){
+                                       Log(Form("No LTU Configuration from DAQ logbook for detector %s (BUT it was expected)! The corresponding CDB entry will not be filled!",detCTPName.Data()));
+                                       error |= 2048;
+                                       isLTUok = kFALSE;
+                                       break;
+                               }
+                               else{
+                                       Float_t ltuFineDelay1 = ltu[0].Atof();
+                                       Float_t ltuFineDelay2 = ltu[1].Atof();
+                                       Float_t ltuBCDelayAdd = ltu[2].Atof();
+                                       const char* name = AliDAQ::DetectorName(i);
+                                       AliLTUConfig* ltuConfig = new AliLTUConfig((UChar_t)AliDAQ::DetectorID(name),ltuFineDelay1,ltuFineDelay2,ltuBCDelayAdd);
+                                       ltuarray->AddAtAndExpand(ltuConfig,i);
+                               }                               
+                       }
+               }
+               if (isLTUok){
+                       AliCDBMetaData metadata;
+                       metadata.SetBeamPeriod(0);
+                       metadata.SetResponsible("Roman Lietava");
+                       metadata.SetComment("LTU Configuration for current run");
+                       if (!Store("CTP","LTUConfig", ltuarray, &metadata, 0, 0)) {
+                               Log("Unable to store the LTU Config object to OCDB!");
+                               error |= 2048;
+                       }               
+               }
+               if (ltuarray) delete ltuarray;
+       }
+
+       else {
+               Log(Form("Incorrect field in DAQ logbook for partition = %s and detector = %s, going into error without trigger timing parameters...",partition.Data(),detector.Data()));
+               error |= 32;
+       }
+
 
        //=================//
        // LHC Data        //
@@ -529,10 +624,15 @@ UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
                } else  if (iLHCData == 1) {
                        Log(Form("LHC Data, problems with DCS FXS!"));
                        error |= 256;
+               } else  if (iLHCData == 2) {
+                       Log(Form("LHC Data, problems with DAQ_time_start/DAQ_time_end!"));
+                       error |= 512;
                } else if (iLHCData ==3){
-                       Log(Form("Problems in storing LHC Data - but not going into Error"));
+                       Log(Form("Problems in storing LHC Phase - going into Error"));
+                       error |= 1024;
                } else if (iLHCData ==4){
-                       Log(Form("Problems with LHC Data to be put in /GRP/GRP/LHCData - but not going into Error"));
+                       Log(Form("Problems with LHC Phase - going into Error"));
+                       error |= 1024;
                } else{
                        Log(Form("LHC Data problems"));
                        error |= 512;
@@ -573,7 +673,7 @@ UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
                Log("GRP Preprocessor Success");
                return 0;
        } else {
-               Log( Form("GRP Preprocessor FAILS!!! %s%s%s%s%s%s%s%s%s%s",
+               Log( Form("GRP Preprocessor FAILS!!! %s%s%s%s%s%s%s%s%s%s%s%s",
                          kppError[(error&1)?1:0],
                          kppError[(error&2)?2:0],
                          kppError[(error&4)?3:0],
@@ -583,7 +683,9 @@ UInt_t AliGRPPreprocessor::Process(TMap* valueMap)
                          kppError[(error&64)?7:0],
                          kppError[(error&128)?8:0],
                          kppError[(error&256)?9:0],
-                         kppError[(error&512)?10:0]
+                         kppError[(error&512)?10:0],
+                         kppError[(error&1024)?11:0],
+                         kppError[(error&2048)?12:0]
                          ));
                return error;
        }
@@ -618,244 +720,303 @@ UInt_t AliGRPPreprocessor::ProcessLHCData(AliGRPObject *grpobj)
        if (fileName.Length()>0){
                AliInfo("Got The LHC Data file");
                AliLHCReader lhcReader;
-               TMap* lhcMap = (TMap*)lhcReader.ReadLHCDP(fileName.Data());
-               if (lhcMap) {
-                       Log(Form("LHCData map entries = %d",lhcMap->GetEntries()));
-                       
-                       // Processing data to be put in AliGRPObject
-                       // Energy
-                       TObjArray* energyArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[0]);
-                       if (energyArray){                       
-                               Float_t energy = ProcessEnergy(energyArray,timeStart,timeEnd);
-                               if (energy != -1) {
-                                       grpobj->SetBeamEnergy(energy);
-                                       grpobj->SetBeamEnergyIsSqrtSHalfGeV(kTRUE);
-                               }
+
+               // Processing data to be put in AliGRPObject
+
+               // Energy
+               Log("*************Energy ");
+               TObjArray* energyArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[0]);
+               if (energyArray){                       
+                       Float_t energy = ProcessEnergy(energyArray,timeStart);
+                       if (energy != -1.) {
+                               grpobj->SetBeamEnergy(energy);
+                               grpobj->SetBeamEnergyIsSqrtSHalfGeV(kTRUE);
                        }
-                       else {
-                               AliError("Energy not found in LHC Data file!!!");
-                       }       
-                       Double_t timeBeamMode = 0;
-                       Double_t timeMachineMode = 0;
-                       Double_t timeBeam = 0;
-                       Bool_t flagBeamMode = kFALSE;  //flag set true if at least one BeamMode measurement is found within DAQ_time_start and DAQ_time_end
-                       Bool_t flagMachineMode = kFALSE;  //flag set true if at least one MachineMode measurement is found within DAQ_time_start and DAQ_time_end
-                       Bool_t flagBeam = kFALSE;  //flag set true if at least one Beam Type measurement is found within DAQ_time_start and DAQ_time_end
-
-                       // BeamMode
-                       TObjArray* beamModeArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[2]);
-                       Int_t nBeamMode = -1;
-                       if (beamModeArray){     
-                               nBeamMode = beamModeArray->GetEntries();        
-                               if (nBeamMode==0){
-                                       AliInfo("Found zero entries for  the Beam Mode, leaving it empty");
-                               }
-                               else{
-                                       if (nBeamMode==1){
-                                               AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(0);
-                                               if (beamMode->GetTimeStamp()>=timeStart && beamMode->GetTimeStamp()<=timeEnd){
-                                                       TObjString* beamModeString = beamMode->GetStringArray(0);
-                                                       AliInfo(Form("LHC State (corresponding to BeamMode) = %s",(beamModeString->String()).Data()));
-                                                       grpobj->SetLHCState(beamModeString->String());
+                       delete energyArray;
+               }
+               else {
+                       AliError("Energy not found in LHC Data file!!!");
+               }       
+
+               Double_t timeBeamModeEnd = timeEnd;        // max validity for Beam Mode 
+               Double_t timeMachineModeEnd = timeEnd;     // max validity for Machine Mode
+               Double_t timeBeamEnd = timeEnd;            // max validity for Beam Type
+               Double_t timeBeamModeStart = -1;    // min validity for Beam Mode
+               Double_t timeMachineModeStart = -1; // min validity for Machine Mode
+               Double_t timeBeamStart = -1;        // min validity for Beam Type
+               Int_t indexBeamMode = -1;                  // index of measurement used to set Beam Mode
+               Int_t indexMachineMode = -1;               // index of measurement used to set Beam Mode
+               Int_t indexBeam = -1;                      // index of measurement used to set Beam Mode
+               Bool_t foundBeamModeStart = kFALSE;        // flag to be set in case an entry for the Beam Mode is found before (or at) SOR
+               Bool_t foundMachineModeStart = kFALSE;     // flag to be set in case an entry for the Beam Mode is found before (or at) SOR
+               Bool_t foundBeamStart = kFALSE;            // flag to be set in case an entry for the Beam Mode is found before (or at) SOR
+               Bool_t flagBeamMode = kFALSE;  //flag set true if a changed occurred in BeamMode
+               Bool_t flagMachineMode = kFALSE;  //flag set true if a changed occurred in MachineMode
+               Bool_t flagBeam = kFALSE;  //flag set true if a changed occurred in BeamType
+               
+               // BeamMode
+               Log("*************BeamMode (LHCState) ");
+               TObjArray* beamModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[2]);
+               Int_t nBeamMode = -1;
+               if (beamModeArray){     
+                       nBeamMode = beamModeArray->GetEntries();        
+                       if (nBeamMode==0){
+                               AliInfo("Found zero entries for the Beam Mode, leaving it empty");
+                       }
+                       else{
+                               for (Int_t iBeamMode = 0; iBeamMode<nBeamMode; iBeamMode++){
+                                       AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(iBeamMode);
+                                       if (beamMode){
+                                               if (beamMode->GetTimeStamp()<=timeStart && beamMode->GetTimeStamp()>=timeBeamModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
+                                                       timeBeamModeStart = beamMode->GetTimeStamp();
+                                                       indexBeamMode = iBeamMode;
+                                                       foundBeamModeStart = kTRUE;
                                                }
-                                               else{
-                                                       AliInfo("No Beam Mode found within DAQ_time_start and DAQ_time_end, leaving it empty");
+                                               else {
+                                                       break;
+
                                                }
                                        }
-                                       else {
-                                               for (Int_t iBeamMode = 0; iBeamMode<nBeamMode; iBeamMode++){
-                                                       AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(iBeamMode);
-                                                       if (beamMode->GetTimeStamp()>=timeStart && beamMode->GetTimeStamp()<=timeEnd){
-                                                               AliDCSArray* beamMode1 = (AliDCSArray*)beamModeArray->At(iBeamMode+1);
-                                                               if (beamMode1->GetTimeStamp()>=timeStart && beamMode1->GetTimeStamp()<=timeEnd){
-                                                                       timeBeamMode = beamMode1->GetTimeStamp();
-                                                                       AliWarning(Form("The beam mode changed at timestamp %f! Setting it to the first value found and keeping track of the time of the change to set MaxTimeLHCValidity afterward",timeBeamMode));
+                               }
+                               if (!foundBeamModeStart){
+                                       AliInfo("No value for the Beam Mode found before start of run, the Beam Mode will remain empty");
+                               }
+                               else {
+                                       AliDCSArray* beamMode = (AliDCSArray*)beamModeArray->At(indexBeamMode);
+                                       TObjString* beamModeString = beamMode->GetStringArray(0);
+                                       AliInfo(Form("LHC State (corresponding to BeamMode) = %s (set at %f)",(beamModeString->String()).Data(),beamMode->GetTimeStamp()));
+                                       grpobj->SetLHCState(beamModeString->String());
+                                       if (indexBeamMode < nBeamMode-1){
+                                               AliDCSArray* beamMode1 = (AliDCSArray*)beamModeArray->At(indexBeamMode+1);
+                                               if (beamMode1){
+                                                       if (beamMode1->GetTimeStamp()<=timeStart){
+                                                               AliError("you did not choose the correct value! there is still something before (or at) SOR, but later than this!");
+                                                       }
+                                                       else if (beamMode1->GetTimeStamp()>timeStart && beamMode1->GetTimeStamp()<=timeEnd){
+                                                               timeBeamModeEnd = beamMode1->GetTimeStamp();
+                                                               TObjString* beamModeString1 = beamMode1->GetStringArray(0);
+                                                               TString bmString0 = beamModeString->String();
+                                                               TString bmString1 = beamModeString1->String();
+                                                               if (bmString0.CompareTo(bmString1.Data(),TString::kIgnoreCase) == -1){
+                                                                       AliWarning(Form("The beam mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",bmString0.Data(), bmString1.Data(), timeBeamModeEnd, bmString0.Data()));
+                                                                       flagBeamMode = kTRUE;
                                                                }
-                                                               TObjString* beamModeString = beamMode->GetStringArray(0);
-                                                               AliInfo(Form("LHC State (corresponding to BeamMode) = %s",(beamModeString->String()).Data()));
-                                                               grpobj->SetLHCState(beamModeString->String());
-                                                               flagBeamMode = kTRUE;
-                                                               break;
                                                        }
                                                }
-                                               if (!flagBeamMode){
-                                                       AliError("Found values for BeamMode, but none within DAQ_time_start and DAQ_time_end, leaving it empty");
+                                               else {
+                                                       AliInfo("Invalid pointer for the first entry for Beam Mode after the first valid one, not considering anything after what has already been found");
                                                }
                                        }
                                }
                        }
-                       else{
-                               AliError("Beam mode array not found in LHC Data file!!!");
+                       delete beamModeArray;
+               }
+               else{
+                       AliError("Beam mode array not found in LHC Data file!!!");
+               }
+               
+               // MachineMode
+               Log("*************MachineMode ");
+               TObjArray* machineModeArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[1]);
+               Int_t nMachineMode = -1;
+               if (machineModeArray){
+                       nMachineMode = machineModeArray->GetEntries();
+                       if (nMachineMode==0){
+                               AliInfo("No Machine Mode found, leaving it empty");
                        }
-
-                       // MachineMode
-                       TObjArray* machineModeArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[1]);
-                       Int_t nMachineMode = -1;
-                       if (machineModeArray){
-                               nMachineMode = machineModeArray->GetEntries();
-                               if (nMachineMode==0){
-                                       AliInfo("No Machine Mode found, leaving it empty");
-                               }
-                               else{
-                                       if (nMachineMode ==1) {
-                                               AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(0);
-                                               if (machineMode->GetTimeStamp()>=timeStart && machineMode->GetTimeStamp()<=timeEnd){
-                                                       TObjString* machineModeString = machineMode->GetStringArray(0);
-                                                       AliInfo(Form("Machine Mode = %s",(machineModeString->String()).Data()));
-                                                       grpobj->SetMachineMode(machineModeString->String());
+                       else{
+                               for (Int_t iMachineMode = 0; iMachineMode<nMachineMode; iMachineMode++){
+                                       AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(iMachineMode);
+                                       if (machineMode){
+                                               if (machineMode->GetTimeStamp()<=timeStart && machineMode->GetTimeStamp()>=timeMachineModeStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
+                                                       timeMachineModeStart = machineMode->GetTimeStamp();
+                                                       indexMachineMode = iMachineMode;
+                                                       foundMachineModeStart = kTRUE;
                                                }
                                                else{
-                                                       AliInfo("No Machine Mode found within DAQ_time_start and DAQ_time_end, leaving it empty");
+                                                       break;
                                                }
                                        }
-                                       else {
-                                               for (Int_t iMachineMode = 0; iMachineMode<nMachineMode; iMachineMode++){
-                                                       AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(iMachineMode);
-                                                       if (machineMode->GetTimeStamp()>=timeStart && machineMode->GetTimeStamp()<=timeEnd){
-                                                               AliDCSArray* machineMode1 = (AliDCSArray*)machineModeArray->At(iMachineMode+1);
-                                                               if (machineMode1->GetTimeStamp()>=timeStart && machineMode1->GetTimeStamp()<=timeEnd){
-                                                                       timeMachineMode = machineMode1->GetTimeStamp();
-                                                                       AliWarning(Form("The machine mode changed at timestamp %f! Setting it to the first value found and keeping track of the time of the change to set MaxTimeLHCValidity afterwards",timeMachineMode));
+                               }
+                               if (!foundMachineModeStart){
+                                       AliInfo("No value for the Machine Mode found before start of run, the Machine Mode will remain empty");
+                               }
+                               else {
+                                       AliDCSArray* machineMode = (AliDCSArray*)machineModeArray->At(indexMachineMode);
+                                       TObjString* machineModeString = machineMode->GetStringArray(0);
+                                       AliInfo(Form("MachineMode = %s (set at %f)",(machineModeString->String()).Data(),machineMode->GetTimeStamp()));
+                                       grpobj->SetMachineMode(machineModeString->String());
+                                       if (indexMachineMode < nMachineMode-1){
+                                               AliDCSArray* machineMode1 = (AliDCSArray*)machineModeArray->At(indexMachineMode+1);
+                                               if (machineMode1){
+                                                       if (machineMode1->GetTimeStamp()>timeStart && machineMode1->GetTimeStamp()<=timeEnd){
+                                                               timeMachineModeEnd = machineMode1->GetTimeStamp();
+                                                               TObjString* machineModeString1 = machineMode1->GetStringArray(0);
+                                                               TString mmString0 = machineModeString->String();
+                                                               TString mmString1 = machineModeString1->String();
+                                                               if (mmString0.CompareTo(mmString1.Data(),TString::kIgnoreCase) == -1){
+                                                                       AliWarning(Form("The machine mode changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",mmString0.Data(),mmString1.Data(),timeMachineModeEnd,mmString0.Data()));
+                                                                       flagMachineMode = kTRUE;
                                                                }
-                                                               TObjString* machineModeString = machineMode->GetStringArray(0);
-                                                               AliInfo(Form("Machine mode = %s",(machineModeString->String()).Data()));
-                                                               grpobj->SetMachineMode(machineModeString->String());
-                                                               flagMachineMode = kTRUE;
-                                                               break;
                                                        }
                                                }
-                                               if (!flagMachineMode){
-                                                       AliError("Found values for MachineMode, but none within DAQ_time_start and DAQ_time_end, setting MachineMode to UNKNOWN");
-                                                       grpobj->SetMachineMode("UNKONWN");
+                                               else {
+                                                       AliInfo("Invalid pointer for the first entry for Machine Mode after the first valid one, not considering anything after what has already been found");
                                                }
                                        }
                                }
                        }
-                       else {
-                               AliError("Machine mode array not found in LHC Data file!!!");
-                       }       
-
-                       // BeamType1 and BeamType2 - both put in the same string
-                       TObjArray* beamArray = (TObjArray*)lhcMap->GetValue(fgkLHCDataPoints[3]);
-                       if (beamArray){                 
-                               Int_t nBeam = beamArray->GetEntries();
-                               if (nBeam==0){
-                                       AliInfo("No Beam Type found, leaving it empty");
-                               }
-                               else{
-                                       if (nBeam == 1){
-                                               AliDCSArray* beam = (AliDCSArray*)beamArray->At(0);
-                                               if (beam->GetTimeStamp()>=timeStart && beam->GetTimeStamp()<=timeEnd){
-                                                       TObjString* beamString = beam->GetStringArray(0);
-                                                       TString beamType = beamString->String();
-                                                       AliInfo(Form("Beam Type = %s",beamType.Data()));        
-                                                       if (beamType.CompareTo("PROTON",TString::kIgnoreCase)){
-                                                               grpobj->SetBeamType("p-p");
-                                                       }
-                                                       else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase)){
-                                                               grpobj->SetBeamType("Pb-Pb");
-                                                       }
-                                                       else{
-                                                               AliError("Beam Type not known, leaving it empty");
-                                                       }
+                       delete machineModeArray;
+               }
+               else{
+                       AliError("Machine mode array not found in LHC Data file!!!");
+               }
+               
+               // BeamType1 and BeamType2 - both put in the same string
+               Log("*************BeamType ");
+               TObjArray* beamArray = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[3]);
+               if (beamArray){                 
+                       Int_t nBeam = beamArray->GetEntries();
+                       if (nBeam==0){
+                               AliInfo("No Beam Type found, leaving it empty");
+                       }
+                       else{
+                               for (Int_t iBeam = 0; iBeam<nBeam; iBeam++){
+                                       AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
+                                       if (beam){
+                                               if (beam->GetTimeStamp()<=timeStart && beam->GetTimeStamp()>=timeBeamStart){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
+                                                       timeBeamStart = beam->GetTimeStamp();
+                                                       indexBeam = iBeam;
+                                                       foundBeamStart = kTRUE;
                                                }
-                                               else {
-                                                       AliInfo("No Beam Type found within DAQ_time_start and DAQ_time_end, leaving it empty");
+                                               else{
+                                                       break;
                                                }
                                        }
+                               }
+                               if (!foundBeamStart){
+                                       AliInfo("No value for the Beam Type found before start of run, the Machine Mode will remain empty");
+                               }
+                               else {
+                                       AliDCSArray* beam = (AliDCSArray*)beamArray->At(indexBeam);
+                                       TObjString* beamString = beam->GetStringArray(0);
+                                       TString beamType = beamString->String();
+                                       AliInfo(Form("Beam Type = %s",beamType.Data()));        
+                                       if (beamType.CompareTo("PROTON",TString::kIgnoreCase) == 0){
+                                               AliInfo("Setting beam type to p-p");
+                                               grpobj->SetBeamType("p-p");
+                                       }
+                                       else { // if there is no PROTON beam, we suppose it is Pb, and we put A-A
+                                               AliInfo("Setting beam type to A-A");
+                                               grpobj->SetBeamType("A-A");
+                                       }
+                                       /*
+                                         else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase) == 0){
+                                               AliInfo("Setting beam type to Pb-Pb");
+                                               grpobj->SetBeamType("Pb-Pb");
+                                       }
                                        else{
-                                               for (Int_t iBeam=0; iBeam<nBeam; iBeam++){
-                                                       AliDCSArray* beam = (AliDCSArray*)beamArray->At(iBeam);
-                                                       if (beam->GetTimeStamp()>=timeStart && beam->GetTimeStamp()<=timeEnd){
-                                                               AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(iBeam+1);
-                                                               if (beam1->GetTimeStamp()>=timeStart && beam1->GetTimeStamp()<=timeEnd){
-                                                                       timeBeam = beam1->GetTimeStamp();
-                                                                       AliWarning(Form("The Beam Type changed at timestamp %f! Setting it to the first value found and keeping track of the time of the change to set MaxTimeLHCValidity afterwards",timeBeam));
-                                                               }
-                                                               TObjString* beamString = beam->GetStringArray(0);
-                                                               TString beamType = beamString->String();
-                                                               AliInfo(Form("Beam Type = %s",beamType.Data()));        
-                                                               if (beamType.CompareTo("PROTON",TString::kIgnoreCase)){
-                                                                       grpobj->SetBeamType("p-p");
-                                                               }
-                                                               else if (beamType.CompareTo("LEAD82",TString::kIgnoreCase)){
-                                                                       grpobj->SetBeamType("Pb-Pb");
-                                                               }
-                                                               else{
-                                                                       AliError("Beam Type not known, leaving it empty");
+                                               AliError("Beam Type not known, leaving it empty");
+                                       }
+                                       */
+                                       if (indexBeam < nBeam-1){
+                                               AliDCSArray* beam1 = (AliDCSArray*)beamArray->At(indexBeam+1);
+                                               if (beam1){
+                                                       if (beam1->GetTimeStamp()>timeStart && beam1->GetTimeStamp()<=timeEnd){
+                                                               timeBeamEnd = beam1->GetTimeStamp();
+                                                               TObjString* beamString1 = beam1->GetStringArray(0);
+                                                               TString beamType1 = beamString1->String();
+                                                               if (beamType.CompareTo(beamType1.Data(),TString::kIgnoreCase) == -1){
+                                                                       AliWarning(Form("The Beam Type changed from %s to %s during the run at timestamp %f! Setting it to %s and keeping track of the time of the change to set MaxTimeLHCValidity afterward",beamType.Data(),(beamString1->String()).Data(),timeBeamEnd,beamType.Data()));
+                                                                       flagBeam = kTRUE;
                                                                }
-                                                               flagBeam = kTRUE;
-                                                               break;
                                                        }
                                                }
-                                               if (!flagBeam){
-                                                       AliError("Found values for Beam Type, but none within DAQ_time_start and DAQ_time_end, leaving it empty");
+                                               else {
+                                                       AliInfo("Invalid pointer for the first entry for Beam Type after the first valid one, not considering anything after what has already been found");
                                                }
                                        }
                                }
                        }
-                       else{
-                               AliError("BeamType array not found in LHC data file!!!");
-                       }                       
-                       
-                       // Setting minTimeLHCValidity
-                       if (timeBeamMode!=0 || timeMachineMode!=0 || timeBeam !=0){
-                               Double_t minTimeLHCValidity;
-                               if (timeBeamMode == 0 && timeMachineMode == 0 && timeBeam != 0){ // timeBeam only != 0
-                                       minTimeLHCValidity = timeBeam;
-                               }
-                               else if (timeBeamMode == 0 && timeMachineMode != 0 && timeBeam == 0){ // timeMachineMode only != 0
-                                       minTimeLHCValidity = timeMachineMode;
-                               }
-                               else if (timeBeamMode != 0 && timeMachineMode == 0 && timeBeam == 0){ // timeBeamMode only != 0
-                                       minTimeLHCValidity = timeBeamMode;
-                               }
-                               else if (timeBeamMode == 0 && timeMachineMode != 0 && timeBeam != 0){ // timeBeam and timeMachineMode only != 0
-                                       minTimeLHCValidity= TMath::Min(timeBeam,timeMachineMode);
-                               }
-                               else if (timeBeamMode != 0 && timeMachineMode == 0 && timeBeam != 0){ // timeBeam and timeBeamMode only != 0
-                                       minTimeLHCValidity= TMath::Min(timeBeam,timeBeamMode);
-                               }
-                               else if (timeBeamMode != 0 && timeMachineMode != 0 && timeBeam == 0){ // timeMachineMode and timeBeamMode only != 0
-                                       minTimeLHCValidity= TMath::Min(timeMachineMode,timeBeamMode);
-                               }
-                               else {
-                                       Double_t arrayTimes[3] = {timeBeamMode,timeMachineMode,timeBeam};
-                                       minTimeLHCValidity= TMath::MinElement(3,arrayTimes);
-                               }
-                               AliWarning(Form("Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
-                               grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
-                       }
-                       
-                       // Processing data to go to AliLHCData object
-                       AliLHCData* dt = new AliLHCData(lhcMap,timeStart,timeEnd);
-                       
-                       // storing AliLHCData in OCDB
-                       if (dt){                        
-                               AliCDBMetaData md;
-                               md.SetResponsible("Ruben Shahoyan");
-                               md.SetComment("LHC data from the GRP preprocessor.");
-                               
-                               Bool_t result = kTRUE;
-                               result = Store("GRP", "LHCData", dt, &md); 
-                               delete dt;
-                               if (result) return 0;
-                               else return 3;
-                       }
-                       else return 4;
-                       delete lhcMap; 
+                       delete beamArray;
                }
-               else {
-                       AliError("Cannot read correctly LHCData file");
-                       return 2;
+               else{
+                       AliError("Beam Type array not found in LHC Data file!!!");
+               }               
+               
+               // Setting minTimeLHCValidity
+               if (timeBeamModeEnd!=0 || timeMachineModeEnd!=0 || timeBeamEnd !=0){
+                       Double_t minTimeLHCValidity;
+                       if (flagBeamMode == kFALSE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam only true
+                               minTimeLHCValidity = timeBeamEnd;
+                       }
+                       else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode only true
+                               minTimeLHCValidity = timeMachineModeEnd;
+                       }
+                       else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kFALSE){ // flagBeamMode only true
+                               minTimeLHCValidity = timeBeamModeEnd;
+                       }
+                       else if (flagBeamMode == kFALSE && flagMachineMode == kTRUE && flagBeam == kTRUE){ // flagBeam and flagMachineMode only true
+                               minTimeLHCValidity= TMath::Min(timeBeamEnd,timeMachineModeEnd);
+                       }
+                       else if (flagBeamMode == kTRUE && flagMachineMode == kFALSE && flagBeam == kTRUE){ // flagBeam and flagBeamMode only true
+                               minTimeLHCValidity= TMath::Min(timeBeamEnd,timeBeamModeEnd);
+                       }
+                       else if (flagBeamMode == kTRUE && flagMachineMode == kTRUE && flagBeam == kFALSE){ // flagMachineMode and flagBeamMode only true
+                               minTimeLHCValidity= TMath::Min(timeMachineModeEnd,timeBeamModeEnd);
+                       }
+                       else {
+                               Double_t arrayTimes[3] = {timeBeamModeEnd,timeMachineModeEnd,timeBeamEnd};// flagMachineMode and flagBeamMode and flagBeam 
+                               minTimeLHCValidity= TMath::MinElement(3,arrayTimes);
+                       }
+                       AliWarning(Form("Setting MaxTimeLHCValidity to %f",minTimeLHCValidity));
+                       grpobj->SetMaxTimeLHCValidity(minTimeLHCValidity);
+               }
+               
+               // Processing data to go to AliLHCData object
+               AliLHCData* dt = new AliLHCData(fileName.Data(),timeStart,timeEnd);
+               // storing AliLHCData in OCDB
+               if (dt){
+                 AliInfo(Form("Filled %d records to AliLHCData object",dt->GetData().GetEntriesFast()));
+                 AliCDBMetaData md;
+                 md.SetResponsible("Ruben Shahoyan");
+                 md.SetComment("LHC data from the GRP preprocessor.");
+                 Bool_t result = kTRUE;
+                 result = Store("GRP", "LHCData", dt, &md); 
+                 delete dt;
+                 if (!result){
+                       Log(Form("Problems in storing LHC Data - but not going into Error"));
+                 }
+               }
+
+               // processing LHC Phase
+
+               TObjArray *beam1phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[4]);
+               TObjArray *beam2phase = lhcReader.ReadSingleLHCDP(fileName.Data(),fgkLHCDataPoints[5]);
+               if (beam1phase == 0x0 || beam2phase == 0x0){
+                       Log(Form("Problems in retrieving LHC Clock data from LHC file"));
+                       return 4;
+               }                       
+               AliLHCClockPhase *phaseObj = ProcessLHCClockPhase(beam1phase,beam2phase,timeEnd);
+               if (phaseObj){
+                       AliInfo(Form("LHC Phase found"));
+                       AliCDBMetaData mdPhase;
+                       mdPhase.SetResponsible("Cvetan Cheshkov");
+                       mdPhase.SetComment("LHC Clock Phase");
+                       Bool_t result = kTRUE;
+                       result = Store("Calib", "LHCClockPhase", phaseObj, &mdPhase); 
+                       delete phaseObj;
+                       if (!result) return 3;
                }
+               else return 4;
        }
-  
+       
        else {
                AliError("No LHCData file found in DCS FXS");
                return 1;
        }
 
+       return 0;
 }
 
 //_______________________________________________________________
@@ -2277,7 +2438,7 @@ Int_t AliGRPPreprocessor::ReceivePromptRecoParameters(UInt_t run, const char* db
        
        // main logbook
        TString sqlQuery;
-       sqlQuery.Form("SELECT DAQ_time_start, run_type, detectorMask, L3_magnetCurrent, Dipole_magnetCurrent FROM logbook WHERE run = %d", run);
+       sqlQuery.Form("SELECT DAQ_time_start, run_type, detectorMask, L3_magnetCurrent, Dipole_magnetCurrent,beamType FROM logbook WHERE run = %d", run);
        TSQLResult* result = server->Query(sqlQuery);
        if (!result)
                {
@@ -2305,12 +2466,16 @@ Int_t AliGRPPreprocessor::ReceivePromptRecoParameters(UInt_t run, const char* db
        TString detectorMaskString(row->GetField(2));
        TString l3CurrentString(row->GetField(3));
        TString dipoleCurrentString(row->GetField(4));
+       TString beamTypeString(row->GetField(5));
        time_t timeStart = (time_t)(timeStartString.Atoi());
        UInt_t detectorMask = (UInt_t)(detectorMaskString.Atoi());
        Float_t l3Current = (Float_t)(TMath::Abs(l3CurrentString.Atof()));
        Float_t dipoleCurrent = (Float_t)(TMath::Abs(dipoleCurrentString.Atof()));
        Char_t l3Polarity = (l3CurrentString.Atof() < 0) ? 1 : 0;
        Char_t dipolePolarity = (dipoleCurrentString.Atof() < 0) ? 1 : 0;
+       if (beamTypeString.CompareTo("Pb-Pb",TString::kIgnoreCase) == 0){
+               beamTypeString="A-A";
+       }
        
        AliGRPObject * grpObj = new AliGRPObject();
        grpObj->SetTimeStart(timeStart); 
@@ -2321,6 +2486,7 @@ Int_t AliGRPPreprocessor::ReceivePromptRecoParameters(UInt_t run, const char* db
        grpObj->SetL3Polarity(l3Polarity);
        grpObj->SetDipolePolarity(dipolePolarity);
        grpObj->SetPolarityConventionLHC();  // after the dipole cables swap we comply with LHC convention
+       grpObj->SetBeamType(beamTypeString);
 
        delete row;
        row = 0;
@@ -2482,7 +2648,7 @@ Int_t AliGRPPreprocessor::ReceivePromptRecoParameters(UInt_t run, const char* db
        return lastRun;
 }
 //-----------------------------------------------------------------
-Double_t AliGRPPreprocessor::CalculateMean(TObjArray* array){
+Double_t AliGRPPreprocessor::CalculateMean(TObjArray* const array){
 
        //
        // Calculating mean over TObjArray from LHC Data
@@ -2715,7 +2881,7 @@ Double_t AliGRPPreprocessor::CalculateMean(TObjArray* array){
        return (parameters[0]);
 }
 //------------------------------------------------------------------------------------------------------
-Float_t AliGRPPreprocessor::ProcessEnergy(TObjArray* array, Double_t timeStart, Double_t timeEnd){
+Float_t AliGRPPreprocessor::ProcessEnergy(TObjArray* const array, Double_t timeStart){
 
        //
        // Method to processo LHC Energy information
@@ -2724,26 +2890,119 @@ Float_t AliGRPPreprocessor::ProcessEnergy(TObjArray* array, Double_t timeStart,
 
        Int_t nCounts = array->GetEntries();
        Float_t energy = -1;
-       Bool_t inRange = kFALSE;
+       Double_t timeEnergy = -1;
+       Int_t indexEnergy = -1;
+       Bool_t foundEnergy = kFALSE;
+
        AliDebug(2,Form("Energy measurements = %d\n",nCounts));
        if (nCounts ==0){
                AliWarning("No Energy values found! Beam Energy remaining invalid!");
        }
        else{
-               for(Int_t i = 0; i < nCounts; i++) {
+               for (Int_t i = 0; i < nCounts; i++){
                        AliDCSArray *dcs = (AliDCSArray*)array->At(i);
-                       if((dcs->GetTimeStamp() >= timeStart) &&(dcs->GetTimeStamp() <= timeEnd)) {
-                               energy = (Float_t)(TMath::Nint(((Double_t)(dcs->GetInt(0)))*120/1000)); // sqrt(s)/2 energy in GeV
-                               AliInfo(Form("Energy value found = %d, converting --> sqrt(s)/2 = %f (GeV)", dcs->GetInt(0),energy));
-                               inRange = kTRUE;
-                               break;
+                       if (dcs){
+                               if (dcs->GetTimeStamp()<=timeStart && dcs->GetTimeStamp()>=timeEnergy){// taking always the very last entry: of two measurements have the same timestamp, the last one is taken
+                                       timeEnergy = dcs->GetTimeStamp();
+                                       indexEnergy = i;
+                                       foundEnergy = kTRUE;
+                               }
+                               else{
+                                       break;
+                               }
                        }
                }
-               if (inRange == kFALSE){
-                               AliInfo("No Energy value found between DAQ_time_start and DAQ_time_end - energy will remain invalid!");
+               if (!foundEnergy){
+                       AliInfo("No value for the Energy found before start of run, the Energy will remain invalid");
+               }
+               else {
+                       AliDCSArray* dcs = (AliDCSArray*)array->At(indexEnergy);
+                       energy = (Float_t)(TMath::Nint(((Double_t)(dcs->GetInt(0)))*120/1000)); // sqrt(s)/2 energy in GeV
+                       AliInfo(Form("Energy value found = %d (at %f), converting --> sqrt(s)/2 = %f (GeV)", dcs->GetInt(0),dcs->GetTimeStamp(),energy));
                }
-       
        }
 
        return energy;
 }
+//------------------------------------------------------------------------------------------------------
+AliLHCClockPhase* AliGRPPreprocessor::ProcessLHCClockPhase(TObjArray *beam1phase,TObjArray *beam2phase, Double_t timeEnd)
+{
+  //
+  // Method to process LHC-Clock Phase data
+  // Only the values between DAQ_time_start and DAQ_time_end are kept
+  //
+  AliLHCClockPhase *phaseObj = new AliLHCClockPhase;
+
+  Bool_t foundBeam1Phase = kFALSE, foundBeam2Phase = kFALSE;
+  const Float_t threshold = 0.050; // we store the measurement only in case they differ with more 50ps from the previous one 
+
+  TString timeCreatedStr = GetRunParameter("time_created");
+  Double_t timeCreated = timeCreatedStr.Atof();
+
+  Int_t nCounts = beam1phase->GetEntries();
+  AliDebug(2,Form("Beam1 phase measurements = %d\n",nCounts));
+  if (nCounts ==0){
+    AliWarning("No beam1 LHC clock phase values found!");
+    delete phaseObj;
+    return NULL;
+  }
+  else{
+    Double_t prevPhase = 0;
+    for (Int_t i = 0; i < nCounts; i++){
+      AliDCSArray *dcs = (AliDCSArray*)beam1phase->At(i);
+      if (dcs){
+             //if (dcs->GetTimeStamp()>=timeStart && dcs->GetTimeStamp()<=timeEnd) {
+             if (dcs->GetTimeStamp()>=timeCreated && dcs->GetTimeStamp()<=timeEnd) {
+         if ((i == 0) || (i == (nCounts-1)) ||
+             !foundBeam1Phase ||
+             (TMath::Abs(dcs->GetDouble(0)-prevPhase) > threshold)) {
+           prevPhase = dcs->GetDouble(0);
+           foundBeam1Phase = kTRUE;
+           AliInfo(Form("B1 Clk Phase = %f at TS = %f",
+                        (Float_t)dcs->GetDouble(0),dcs->GetTimeStamp()));  
+           phaseObj->AddPhaseB1DP((UInt_t)dcs->GetTimeStamp(),(Float_t)dcs->GetDouble(0));
+         }
+       }
+      }
+    }
+    if (!foundBeam1Phase){
+      AliError("No beam1 LHC clock phase values found within the run!");
+      delete phaseObj;
+      return NULL;
+    }
+  }
+
+  nCounts = beam2phase->GetEntries();
+  AliDebug(2,Form("Beam2 phase measurements = %d\n",nCounts));
+  if (nCounts ==0){
+    AliWarning("No beam2 LHC clock phase values found!");
+    delete phaseObj;
+    return NULL;
+  }
+  else{
+    Double_t prevPhase = 0;
+    for (Int_t i = 0; i < nCounts; i++){
+      AliDCSArray *dcs = (AliDCSArray*)beam2phase->At(i);
+      if (dcs){
+       if (dcs->GetTimeStamp()>=timeCreated && dcs->GetTimeStamp()<=timeEnd) {
+         if ((i == 0) || (i == (nCounts-1)) ||
+             !foundBeam2Phase ||
+             (TMath::Abs(dcs->GetDouble(0)-prevPhase) > threshold)) {
+           prevPhase = dcs->GetDouble(0);
+           foundBeam2Phase = kTRUE;
+           AliInfo(Form("B2 Clk Phase = %f at TS = %f",
+                        (Float_t)dcs->GetDouble(0),dcs->GetTimeStamp()));  
+           phaseObj->AddPhaseB2DP((UInt_t)dcs->GetTimeStamp(),(Float_t)dcs->GetDouble(0));
+         }
+       }
+      }
+    }
+    if (!foundBeam2Phase){
+      AliError("No beam2 LHC clock phase values found within the run!");
+      delete phaseObj;
+      return NULL;
+    }
+  }
+
+  return phaseObj;
+}