From c75dca55d67be66e1ca91a76a2ac3c08d24f4a04 Mon Sep 17 00:00:00 2001
From: Christos Anastopoulos <christos.anastopoulos@cern.ch>
Date: Thu, 28 May 2020 13:25:37 +0000
Subject: [PATCH] egammaOQFlagsBuilder clean up 1st try

---
 .../egammaAlgs/src/egammaForwardBuilder.cxx   |  47 +-
 .../egammaAlgs/src/egammaForwardBuilder.h     |   9 +-
 .../egammaAlgs/src/topoEgammaBuilder.cxx      | 513 ++++++------
 .../egamma/egammaAlgs/src/topoEgammaBuilder.h |  58 +-
 .../egammaInterfaces/IegammaBackShape.h       |  20 +-
 .../egammaInterfaces/IegammaOQFlagsBuilder.h  |  50 ++
 .../egammaInterfaces/egammaInterfacesDict.h   |   1 +
 .../egammaInterfaces/selection.xml            |   1 +
 .../egammaRec/python/topoEgammaGetter.py      |  87 +-
 .../egammaTools/python/EMPIDBuilderBase.py    |  71 +-
 .../python/egammaToolsFactories.py            | 174 ++--
 .../egamma/egammaTools/src/EMPIDBuilder.cxx   |  36 +-
 .../egamma/egammaTools/src/egammaBaseTool.cxx |   7 +-
 .../egamma/egammaTools/src/egammaBaseTool.h   |  37 +-
 .../egammaTools/src/egammaOQFlagsBuilder.cxx  | 787 ++++++++++--------
 .../egammaTools/src/egammaOQFlagsBuilder.h    | 129 +--
 16 files changed, 1104 insertions(+), 923 deletions(-)
 create mode 100644 Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaOQFlagsBuilder.h

diff --git a/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.cxx b/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.cxx
index 09f74c0214a7..22999a96e127 100644
--- a/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.cxx
+++ b/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.cxx
@@ -8,6 +8,7 @@
 #include "xAODCaloEvent/CaloClusterContainer.h"
 #include "xAODCaloEvent/CaloClusterAuxContainer.h"
 #include "xAODCaloEvent/CaloCluster.h"
+#include "CaloDetDescr/CaloDetDescrManager.h"
 
 #include "xAODEgamma/ElectronContainer.h"
 #include "xAODEgamma/ElectronAuxContainer.h"
@@ -17,18 +18,10 @@
 #include "PATCore/AcceptData.h"
 
 #include <algorithm> 
-#include <math.h>
+#include <cmath>
 
-
-//  END OF HEADER FILES INCLUDE
-
-/////////////////////////////////////////////////////////////////
-
-//  CONSTRUCTOR:
-    
 egammaForwardBuilder::egammaForwardBuilder(const std::string& name, ISvcLocator* pSvcLocator): 
-  AthReentrantAlgorithm(name, pSvcLocator),
-  m_timingProfile("ChronoStatSvc", name)
+  AthReentrantAlgorithm(name, pSvcLocator)
 { 
 } 
 
@@ -36,20 +29,11 @@ egammaForwardBuilder::egammaForwardBuilder(const std::string& name, ISvcLocator*
 // ================================================================
 egammaForwardBuilder::~egammaForwardBuilder()
 { 
-  //
-  // destructor
-  //
 }
 
 // =================================================================
 StatusCode egammaForwardBuilder::initialize()
 {
-  //
-  // initialize method
-  //
-
-  ATH_MSG_DEBUG(" Initializing egammaForwardBuilder ");
-  
   // the data handle keys
   ATH_CHECK(m_topoClusterKey.initialize());
   ATH_CHECK(m_electronOutputKey.initialize());
@@ -61,7 +45,6 @@ StatusCode egammaForwardBuilder::initialize()
   if (!m_objectQualityTool.empty()) {
     ATH_CHECK(m_objectQualityTool.retrieve());
   } else {
-    ATH_MSG_DEBUG("egammaOQFlagsBuilder is disabled");
     m_objectQualityTool.disable();
   }
 
@@ -78,31 +61,25 @@ StatusCode egammaForwardBuilder::initialize()
     ATH_MSG_ERROR("The number of selectors does not match the number of given fwd-electron selector names");
     return StatusCode::FAILURE;
   }
-  
-  if (m_doChrono) ATH_CHECK( m_timingProfile.retrieve() );
 
   ATH_MSG_DEBUG("Initialization completed successfully");
 
   return StatusCode::SUCCESS;
 }
 
-// ====================================================================
 StatusCode egammaForwardBuilder::finalize()
 {
   return StatusCode::SUCCESS;
 }
 
-// ======================================================================
 StatusCode egammaForwardBuilder::execute(const EventContext& ctx) const
 {
-  ATH_MSG_DEBUG("Executing egammaForwardBuilder ");
 
   // create an egamma container and register it
   SG::WriteHandle<xAOD::ElectronContainer> xaodFrwd(m_electronOutputKey, ctx);
   ATH_CHECK(xaodFrwd.record(std::make_unique<xAOD::ElectronContainer>(),
 			    std::make_unique<xAOD::ElectronAuxContainer>()));
 
-  ATH_MSG_DEBUG( "Recorded Electrons with key: " << m_electronOutputKey.key() );
 
   //cluster
   SG::WriteHandle<xAOD::CaloClusterContainer> outClusterContainer(m_outClusterContainerKey, ctx);
@@ -121,7 +98,6 @@ StatusCode egammaForwardBuilder::execute(const EventContext& ctx) const
     return StatusCode::FAILURE;
   }
 
-
   //loop over cluster container
   xAOD::CaloClusterContainer::const_iterator  clus_begin = cluster->begin();
   xAOD::CaloClusterContainer::const_iterator  clus_end   = cluster->end();
@@ -171,7 +147,6 @@ StatusCode egammaForwardBuilder::execute(const EventContext& ctx) const
     }
   }
   
-
   // Now finalize the cluster: based on code in CaloClusterStoreHelper::finalizeClusters
   // Note: I don't specifically set the IProxyDict, since I also don't set it when I create
   //    data handles, either. 
@@ -180,8 +155,6 @@ StatusCode egammaForwardBuilder::execute(const EventContext& ctx) const
     cl->setLink(outClusterContainerCellLink.ptr(), sg);
   }
 
-  ATH_MSG_VERBOSE("egammaForward execute completed successfully");
-  
   return StatusCode::SUCCESS;
 }  
   
@@ -194,19 +167,11 @@ StatusCode egammaForwardBuilder::ExecObjectQualityTool(const EventContext& ctx,
   // protection in case tool is not available
   // return success as algorithm may be able to run without it 
   // in degraded mode
-
   if (m_objectQualityTool.name().empty()) return StatusCode::SUCCESS;
 
-  // setup chrono for this tool
-  std::string chronoName=this->name()+"_"+m_objectQualityTool->name() ;
-  if (m_doChrono) m_timingProfile->chronoStart(chronoName);
+  const CaloDetDescrManager* calodetdescrmgr = nullptr;
+  ATH_CHECK(detStore()->retrieve(calodetdescrmgr, "CaloMgr"));
 
   // execute the tool
-  StatusCode sc = m_objectQualityTool->execute(ctx, eg);
-  if ( sc.isFailure() ) {
-    ATH_MSG_DEBUG("failure returned by object quality tool"); 
-  }
-  if (m_doChrono) m_timingProfile->chronoStop(chronoName);
-
-  return sc;
+  return m_objectQualityTool->execute(ctx, *calodetdescrmgr,*eg);
 }
diff --git a/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.h b/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.h
index 4a2c58e51e73..dd83d9dfa974 100644
--- a/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.h
+++ b/Reconstruction/egamma/egammaAlgs/src/egammaForwardBuilder.h
@@ -24,7 +24,6 @@
 //
 #include "AthenaBaseComps/AthReentrantAlgorithm.h"
 #include "GaudiKernel/ToolHandle.h"
-#include "GaudiKernel/IChronoStatSvc.h"
 #include "GaudiKernel/ServiceHandle.h"
 #include "GaudiKernel/EventContext.h"
 
@@ -39,6 +38,7 @@
 #include "xAODEgamma/Egamma.h"
 #include "xAODEgamma/ElectronContainer.h"
 
+#include "egammaInterfaces/IegammaOQFlagsBuilder.h" 
 #include "egammaInterfaces/IegammaBaseTool.h"
 #include "egammaInterfaces/IEMFourMomBuilder.h"
 #include "EgammaAnalysisInterfaces/IAsgForwardElectronIsEMSelector.h"
@@ -69,7 +69,7 @@ class egammaForwardBuilder : public AthReentrantAlgorithm
   StatusCode ExecObjectQualityTool(const EventContext &ctx, xAOD::Egamma *eg) const; 
 
   /** @brief Tool to perform object quality*/
-  ToolHandle<IegammaBaseTool> m_objectQualityTool {this,
+  ToolHandle<IegammaOQFlagsBuilder> m_objectQualityTool {this,
       "ObjectQualityTool", "",
       "Name of the object quality tool (empty tool name ignored)"};
 
@@ -102,11 +102,6 @@ class egammaForwardBuilder : public AthReentrantAlgorithm
   /** @brief eta cut */
   Gaudi::Property<double> m_etacut {this, "EtaCut", 2.5, "eta cut"};
 
-  /** @brief do chrono service  */
-  Gaudi::Property<bool> m_doChrono {this, "doChrono", false, "do Chrono Service"}; 
-
-  // to measure speed of the algorithm
-  ServiceHandle<IChronoStatSvc> m_timingProfile;
  protected:
   /** Handle to the selectors */
   ToolHandleArray<IAsgForwardElectronIsEMSelector> m_forwardElectronIsEMSelectors {this,
diff --git a/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.cxx b/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.cxx
index 1a0e3818e05d..ffcf15bbd734 100644
--- a/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.cxx
+++ b/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.cxx
@@ -3,191 +3,190 @@
  */
 
 #include "topoEgammaBuilder.h"
-#include "smallChrono.h"
 
 #include "AthenaKernel/errorcheck.h"
+#include "GaudiKernel/EventContext.h"
 #include "GaudiKernel/IToolSvc.h"
 #include "GaudiKernel/ServiceHandle.h"
-#include "GaudiKernel/EventContext.h"
 #include "StoreGate/ReadHandle.h"
 #include "StoreGate/WriteHandle.h"
 
 #include "CaloDetDescr/CaloDetDescrManager.h"
 #include "xAODCaloEvent/CaloClusterContainer.h"
 
-#include "xAODTracking/TrackParticleContainer.h"
-#include "xAODTracking/VertexContainer.h"
-#include "xAODEgamma/ElectronContainer.h"
-#include "xAODEgamma/PhotonContainer.h"
-#include "xAODEgamma/EgammaContainer.h"
-#include "xAODEgamma/ElectronAuxContainer.h"
-#include "xAODEgamma/PhotonAuxContainer.h"
 #include "egammaRecEvent/egammaRecContainer.h"
+#include "xAODEgamma/EgammaContainer.h"
 #include "xAODEgamma/Electron.h"
+#include "xAODEgamma/ElectronAuxContainer.h"
+#include "xAODEgamma/ElectronContainer.h"
 #include "xAODEgamma/Photon.h"
-
+#include "xAODEgamma/PhotonAuxContainer.h"
+#include "xAODEgamma/PhotonContainer.h"
+#include "xAODTracking/TrackParticleContainer.h"
+#include "xAODTracking/VertexContainer.h"
 
 // INCLUDE GAUDI HEADER FILES:
-#include <algorithm> 
+#include <algorithm>
 #include <cmath>
 
+topoEgammaBuilder::topoEgammaBuilder(const std::string& name,
+                                     ISvcLocator* pSvcLocator)
+  : AthReentrantAlgorithm(name, pSvcLocator)
+{}
 
-topoEgammaBuilder::topoEgammaBuilder(const std::string& name, 
-                                     ISvcLocator* pSvcLocator): 
-  AthReentrantAlgorithm(name, pSvcLocator),
-  m_timingProfile("ChronoStatSvc", name)
-{
-}
-
-StatusCode topoEgammaBuilder::initialize()
+StatusCode
+topoEgammaBuilder::initialize()
 {
-
-  ATH_MSG_DEBUG("Initializing topoEgammaBuilder");
-
   // the data handle keys
   ATH_CHECK(m_electronSuperClusterRecContainerKey.initialize(m_doElectrons));
   ATH_CHECK(m_photonSuperClusterRecContainerKey.initialize(m_doPhotons));
   ATH_CHECK(m_electronOutputKey.initialize());
   ATH_CHECK(m_photonOutputKey.initialize());
   // retrieve tools
-  ATH_MSG_DEBUG("Retrieving " << m_egammaTools.size() << " tools for egamma objects");
-  ATH_CHECK( m_clusterTool.retrieve() );
-  ATH_CHECK( m_ShowerTool.retrieve() );
-  ATH_CHECK( m_egammaTools.retrieve() );
-
-  if ( m_doElectrons ){
-    ATH_MSG_DEBUG("Retrieving " << m_electronTools.size() << " tools for electrons");
-    ATH_CHECK( m_electronTools.retrieve() );
+  ATH_CHECK(m_clusterTool.retrieve());
+  ATH_CHECK(m_ShowerTool.retrieve());
+  ATH_CHECK(m_egammaTools.retrieve());
+
+  if (m_doElectrons) {
+    ATH_CHECK(m_electronTools.retrieve());
   }
-  if ( m_doPhotons ){
-    ATH_MSG_DEBUG("Retrieving " << m_photonTools.size() << " tools for photons");
-    ATH_CHECK( m_photonTools.retrieve() );
+  if (m_doPhotons) {
+    ATH_CHECK(m_photonTools.retrieve());
+  }
+  m_doOQ = !m_egammaOQTool.empty();
+  if (m_doOQ) {
+    ATH_CHECK(m_egammaOQTool.retrieve());
+  }else{
+    m_egammaOQTool.disable();
   }
 
-  if ( m_doElectrons && m_doPhotons ){
-    ATH_MSG_DEBUG("Retrieving ambiguity tool");
-    if (not m_ambiguityTool.isSet()) {
-      ATH_MSG_DEBUG("Ambiguity tool IS NOT set. Not using it");
-    }
-    else { 
-      ATH_CHECK( m_ambiguityTool.retrieve() );
-    }
+  //do we actually do ambiguity 
+  m_doAmbiguity = !m_ambiguityTool.empty();
+  if (m_doElectrons && m_doPhotons && m_doAmbiguity) {
+    ATH_CHECK(m_ambiguityTool.retrieve());
+  }else{
+    m_ambiguityTool.disable();
   }
- 
-  // retrieve timing profile
-  if (m_doChrono) CHECK( m_timingProfile.retrieve() );
 
-  ATH_MSG_DEBUG("Initialization completed successfully");
   return StatusCode::SUCCESS;
 }
 
-StatusCode topoEgammaBuilder::finalize(){
+StatusCode
+topoEgammaBuilder::finalize()
+{
   return StatusCode::SUCCESS;
 }
 
-StatusCode topoEgammaBuilder::execute(const EventContext& ctx) const{
+StatusCode
+topoEgammaBuilder::execute(const EventContext& ctx) const
+{
 
   // Chrono name for each Tool
   const EgammaRecContainer* inputElRecs = nullptr;
   const EgammaRecContainer* inputPhRecs = nullptr;
   xAOD::ElectronContainer* electrons = nullptr;
   xAOD::PhotonContainer* photons = nullptr;
-  /* 
-   * From here one if a Read/Write handle is retrieved the above will be != nullptr
-   * for electron or photons or both 
+  /*
+   * From here one if a Read/Write handle is retrieved the above will be !=
+   * nullptr for electron or photons or both
    */
- if (m_doElectrons){
+  if (m_doElectrons) {
     SG::ReadHandle<EgammaRecContainer> electronSuperRecs(m_electronSuperClusterRecContainerKey, ctx);
-    inputElRecs=electronSuperRecs.ptr();
+    inputElRecs = electronSuperRecs.ptr();
   }
-  if (m_doPhotons){
+  if (m_doPhotons) {
     SG::ReadHandle<EgammaRecContainer> photonSuperRecs(m_photonSuperClusterRecContainerKey, ctx);
-    inputPhRecs=photonSuperRecs.ptr();
+    inputPhRecs = photonSuperRecs.ptr();
   }
-  
+
   SG::WriteHandle<xAOD::ElectronContainer> electronContainer(m_electronOutputKey, ctx);
+  
   ATH_CHECK(electronContainer.record(std::make_unique<xAOD::ElectronContainer>(),
-                                       std::make_unique<xAOD::ElectronAuxContainer>()));
+                                     std::make_unique<xAOD::ElectronAuxContainer>()));
 
-  SG::WriteHandle<xAOD::PhotonContainer> photonContainer(m_photonOutputKey, ctx);
+  SG::WriteHandle<xAOD::PhotonContainer> photonContainer(m_photonOutputKey,ctx);
+  
   ATH_CHECK(photonContainer.record(std::make_unique<xAOD::PhotonContainer>(),
                                    std::make_unique<xAOD::PhotonAuxContainer>()));
-  electrons=electronContainer.ptr();
-  photons=photonContainer.ptr();
+  
+  electrons = electronContainer.ptr();
+  photons = photonContainer.ptr();
 
   /*
    * Now fill the electrons and photons
-   */  
-  if (m_doElectrons){
-    for (const egammaRec* electronRec : *inputElRecs) { 
-      //in case for some reasons we reach here with no trackparticles
-      if(electronRec->getNumberOfTrackParticles()==0){
+   */
+  if (m_doElectrons) {
+    for (const egammaRec* electronRec : *inputElRecs) {
+      // in case for some reasons we reach here with no trackparticles
+      if (electronRec->getNumberOfTrackParticles() == 0) {
         continue;
       }
       unsigned int author = xAOD::EgammaParameters::AuthorElectron;
-      xAOD::AmbiguityTool::AmbiguityType type= xAOD::AmbiguityTool::electron;
-      if(m_doPhotons){
+      xAOD::AmbiguityTool::AmbiguityType type = xAOD::AmbiguityTool::electron;
+      if (m_doPhotons) {
         // get the hottest cell
-        const xAOD::CaloCluster *const elClus = electronRec->caloCluster();
+        const xAOD::CaloCluster* const elClus = electronRec->caloCluster();
         const double elEta0 = elClus->eta0();
         const double elPhi0 = elClus->phi0();
         for (const egammaRec* photonRec : *inputPhRecs) {
-          const xAOD::CaloCluster *const phClus = photonRec->caloCluster();
-          //See if they have the same hottest cell
+          const xAOD::CaloCluster* const phClus = photonRec->caloCluster();
+          // See if they have the same hottest cell
           if (elEta0 == phClus->eta0() && elPhi0 == phClus->phi0()) {
-            if (m_ambiguityTool.isSet()) {  // should be the default
-              author = m_ambiguityTool->ambiguityResolve(elClus,
-                                                        photonRec->vertex(),
-                                                        electronRec->trackParticle(),
-                                                        type);
-            }
-            else {  // in case the ambiguity tool is not set ambiguity is not resolved
+            if (m_doAmbiguity) { // should be the default
+              author =
+                m_ambiguityTool->ambiguityResolve(elClus,
+                                                  photonRec->vertex(),
+                                                  electronRec->trackParticle(),
+                                                  type);
+            } else { // in case the ambiguity tool is not set ambiguity is not
+                     // resolved
               author = xAOD::EgammaParameters::AuthorAmbiguous;
             }
             break;
           }
         }
       }
-      //Create Electron xAOD objects
-      if (author == xAOD::EgammaParameters::AuthorElectron || 
-          author == xAOD::EgammaParameters::AuthorAmbiguous){
-        if ( !getElectron(electronRec, electrons, author,type) ){
+      // Create Electron xAOD objects
+      if (author == xAOD::EgammaParameters::AuthorElectron ||
+          author == xAOD::EgammaParameters::AuthorAmbiguous) {
+        if (!getElectron(electronRec, electrons, author, type)) {
           return StatusCode::FAILURE;
         }
       }
     }
   }
 
-  if (m_doPhotons){
+  if (m_doPhotons) {
     for (const egammaRec* photonRec : *inputPhRecs) {
       unsigned int author = xAOD::EgammaParameters::AuthorPhoton;
-      xAOD::AmbiguityTool::AmbiguityType type= xAOD::AmbiguityTool::photon;
-      if (m_doElectrons){
+      xAOD::AmbiguityTool::AmbiguityType type = xAOD::AmbiguityTool::photon;
+      if (m_doElectrons) {
         // get the hottest cell
-        const xAOD::CaloCluster *const phClus = photonRec->caloCluster();
+        const xAOD::CaloCluster* const phClus = photonRec->caloCluster();
         const double phEta0 = phClus->eta0();
         const double phPhi0 = phClus->phi0();
         for (const egammaRec* electronRec : *inputElRecs) {
-          const xAOD::CaloCluster *const elClus = electronRec->caloCluster();
-          //See if they have the same hottest cell
+          const xAOD::CaloCluster* const elClus = electronRec->caloCluster();
+          // See if they have the same hottest cell
           if (phEta0 == elClus->eta0() && phPhi0 == elClus->phi0()) {
-            if (m_ambiguityTool.isSet()) {  // should be the default
-              author = m_ambiguityTool->ambiguityResolve(elClus,
-                                                        photonRec->vertex(),
-                                                        electronRec->trackParticle(),
-                                                        type);
-            }
-            else {  // in case the ambiguity tool is not set ambiguity is not resolved
+            if (m_doAmbiguity) { // should be the default
+              author =
+                m_ambiguityTool->ambiguityResolve(elClus,
+                                                  photonRec->vertex(),
+                                                  electronRec->trackParticle(),
+                                                  type);
+            } else { // in case the ambiguity tool is not set ambiguity is not
+                     // resolved
               author = xAOD::EgammaParameters::AuthorAmbiguous;
             }
             break;
           }
         }
       }
-      //Create Photon xAOD objects
-      if (author == xAOD::EgammaParameters::AuthorPhoton || 
-          author == xAOD::EgammaParameters::AuthorAmbiguous){
-        if ( !getPhoton(photonRec, photons, author,type) ){
+      // Create Photon xAOD objects
+      if (author == xAOD::EgammaParameters::AuthorPhoton ||
+          author == xAOD::EgammaParameters::AuthorAmbiguous) {
+        if (!getPhoton(photonRec, photons, author, type)) {
           return StatusCode::FAILURE;
         }
       }
@@ -195,109 +194,123 @@ StatusCode topoEgammaBuilder::execute(const EventContext& ctx) const{
   }
 
   const CaloDetDescrManager* calodetdescrmgr = nullptr;
-  ATH_CHECK( detStore()->retrieve(calodetdescrmgr,"CaloMgr") );
+  ATH_CHECK(detStore()->retrieve(calodetdescrmgr, "CaloMgr"));
 
- 
-  /* 
-   * Shower Shapes
-   */
-  if(m_doElectrons){
-    for (xAOD::Electron* electron : *electronContainer){
-      ATH_CHECK(m_ShowerTool->execute(ctx,*calodetdescrmgr,electron));
+  // Shower Shapes
+  if (m_doElectrons) {
+    for (xAOD::Electron* electron : *electronContainer) {
+      ATH_CHECK(m_ShowerTool->execute(ctx, *calodetdescrmgr, electron));
     }
   }
-  if(m_doPhotons){
-    for (xAOD::Photon* photon : *photonContainer){
-      ATH_CHECK(m_ShowerTool->execute(ctx,*calodetdescrmgr,photon));
+  if (m_doPhotons) {
+    for (xAOD::Photon* photon : *photonContainer) {
+      ATH_CHECK(m_ShowerTool->execute(ctx, *calodetdescrmgr, photon));
     }
   }
-  /*
-   * Calibration
-   */
-  if ( m_clusterTool->contExecute(ctx, *calodetdescrmgr,electrons , photons).isFailure() ){
-    ATH_MSG_ERROR("Problem executing the " << m_clusterTool<<" tool");
+
+  // Object Quality
+  if (m_doOQ) {
+    if (m_doElectrons) {
+      for (xAOD::Electron* electron : *electronContainer) {
+        ATH_CHECK(m_egammaOQTool->execute(ctx, *calodetdescrmgr, *electron));
+      }
+    }
+    if (m_doPhotons) {
+      for (xAOD::Photon* photon : *photonContainer) {
+        ATH_CHECK(m_egammaOQTool->execute(ctx, *calodetdescrmgr, *photon));
+      }
+    }
+  }
+
+  // Calibration
+  if (m_clusterTool->contExecute(ctx, *calodetdescrmgr, electrons, photons)
+        .isFailure()) {
+    ATH_MSG_ERROR("Problem executing the " << m_clusterTool << " tool");
     return StatusCode::FAILURE;
   }
-  /*
-   * Tools for ToolHandleArrays
-   */
-  /* First common photon/electron tools*/
-  for (auto& tool : m_egammaTools){
-    ATH_CHECK( CallTool(ctx, tool, electrons,photons) );
+
+  // Tools for ToolHandleArrays
+  // First common photon/electron tools*/
+  for (auto& tool : m_egammaTools) {
+    ATH_CHECK(CallTool(ctx, tool, electrons, photons));
   }
-  /* Tools for only electrons*/
-  if(m_doElectrons){
-    /* egammaBaseTools*/
-    for (auto& tool : m_electronTools){
-      ATH_CHECK( CallTool(ctx, tool, electrons, nullptr) );
+  // Tools for only electrons
+  if (m_doElectrons) {
+    for (auto& tool : m_electronTools) {
+      ATH_CHECK(CallTool(ctx, tool, electrons, nullptr));
     }
   }
-  /* Tools for only photons*/
-  if(m_doPhotons){
-    /* egammaBaseTools*/
-    for (auto& tool : m_photonTools){
-      ATH_CHECK( CallTool(ctx, tool, nullptr, photons) );
+  // Tools for only photons
+  if (m_doPhotons) {
+    for (auto& tool : m_photonTools) {
+      ATH_CHECK(CallTool(ctx, tool, nullptr, photons));
     }
   }
-  //Do the ambiguity Links
-  if (m_doElectrons && m_doPhotons){
-    ATH_CHECK(doAmbiguityLinks (electrons,photons));
+  // Do the ambiguity Links
+  if (m_doElectrons && m_doPhotons) {
+    ATH_CHECK(doAmbiguityLinks(electrons, photons));
   }
 
   return StatusCode::SUCCESS;
 }
 
+StatusCode
+topoEgammaBuilder::doAmbiguityLinks(
+  xAOD::ElectronContainer* electronContainer,
+  xAOD::PhotonContainer* photonContainer) const
+{
 
-StatusCode topoEgammaBuilder::doAmbiguityLinks(xAOD::ElectronContainer *electronContainer, 
-                                               xAOD::PhotonContainer *photonContainer) const {
-
-  ///Needs the same logic as the ambiguity after building the objects (make sure they are all valid)
-  static const SG::AuxElement::Accessor < std::vector< 
-  ElementLink< xAOD::CaloClusterContainer > > > caloClusterLinks("constituentClusterLinks");
-  static const SG::AuxElement::Accessor<ElementLink<xAOD::EgammaContainer> > ELink ("ambiguityLink");
-  ElementLink<xAOD::EgammaContainer> dummylink;
-  for (auto && photonIndex : *photonContainer) {    
+  /// Needs the same logic as the ambiguity after building the objects (make
+  /// sure they are all valid)
+  static const SG::AuxElement::Accessor<
+    std::vector<ElementLink<xAOD::CaloClusterContainer>>>
+    caloClusterLinks("constituentClusterLinks");
 
-    xAOD::Photon* photon = photonIndex; 
-    ELink(*photon)=dummylink;
+  static const SG::AuxElement::Accessor<ElementLink<xAOD::EgammaContainer>>
+    ELink("ambiguityLink");
 
-    if(photon->author()!= xAOD::EgammaParameters::AuthorAmbiguous){
+  ElementLink<xAOD::EgammaContainer> dummylink;
+  for (xAOD::Photon* photon : *photonContainer) {
+    ELink(*photon) = dummylink;
+    if (photon->author() != xAOD::EgammaParameters::AuthorAmbiguous) {
       continue;
-    }      
+    }
 
-    for (size_t electronIndex=0; electronIndex < electronContainer->size() ; ++electronIndex) {
+    for (size_t electronIndex = 0; electronIndex < electronContainer->size();
+         ++electronIndex) {
 
-      xAOD::Electron* electron = electronContainer->at(electronIndex); 
-      if(electron->author()!= xAOD::EgammaParameters::AuthorAmbiguous){
+      xAOD::Electron* electron = electronContainer->at(electronIndex);
+      if (electron->author() != xAOD::EgammaParameters::AuthorAmbiguous) {
         continue;
       }
 
-      if(caloClusterLinks(*(electron->caloCluster())).at(0) ==
-         caloClusterLinks(*(photon->caloCluster())).at(0)){
-        ElementLink<xAOD::EgammaContainer> link (*electronContainer,electronIndex);
-        ELink(*photon)=link;
+      if (caloClusterLinks(*(electron->caloCluster())).at(0) ==
+          caloClusterLinks(*(photon->caloCluster())).at(0)) {
+        ElementLink<xAOD::EgammaContainer> link(*electronContainer,
+                                                electronIndex);
+        ELink(*photon) = link;
         break;
       }
     }
   }
-  for (auto && electronIndex : *electronContainer) {    
 
-    xAOD::Electron* electron = electronIndex; 
-    ELink(*electron)=dummylink;
-    if(electron->author()!= xAOD::EgammaParameters::AuthorAmbiguous){
+  for (xAOD::Electron* electron : *electronContainer) {
+    ELink(*electron) = dummylink;
+    if (electron->author() != xAOD::EgammaParameters::AuthorAmbiguous) {
       continue;
-    }      
-    for (size_t photonIndex=0; photonIndex < photonContainer->size() ; ++photonIndex) {
+    }
+    for (size_t photonIndex = 0; photonIndex < photonContainer->size();
+         ++photonIndex) {
 
-      xAOD::Photon* photon = photonContainer->at(photonIndex); 
-      if(photon->author()!= xAOD::EgammaParameters::AuthorAmbiguous){
+      xAOD::Photon* photon = photonContainer->at(photonIndex);
+      if (photon->author() != xAOD::EgammaParameters::AuthorAmbiguous) {
         continue;
       }
 
-      if(caloClusterLinks(*(electron->caloCluster())).at(0) ==
-         caloClusterLinks(*(photon->caloCluster())).at(0)){
-        ElementLink<xAOD::EgammaContainer> link (*photonContainer,photonIndex);
-        ELink(*electron)=link;
+      if (caloClusterLinks(*(electron->caloCluster())).at(0) ==
+          caloClusterLinks(*(photon->caloCluster())).at(0)) {
+        ElementLink<xAOD::EgammaContainer> link(*photonContainer, photonIndex);
+        ELink(*electron) = link;
         break;
       }
     }
@@ -305,125 +318,145 @@ StatusCode topoEgammaBuilder::doAmbiguityLinks(xAOD::ElectronContainer *electron
   return StatusCode::SUCCESS;
 }
 
-StatusCode topoEgammaBuilder::CallTool(const EventContext& ctx, 
-                                       const ToolHandle<IegammaBaseTool>& tool, 
-                                       xAOD::ElectronContainer *electronContainer /* = 0*/, 
-                                       xAOD::PhotonContainer *photonContainer /* = 0*/) const{
-
-
-  smallChrono timer(*m_timingProfile,this->name()+"_"+tool->name(), m_doChrono);  
+StatusCode
+topoEgammaBuilder::CallTool(
+  const EventContext& ctx,
+  const ToolHandle<IegammaBaseTool>& tool,
+  xAOD::ElectronContainer* electronContainer /* = 0*/,
+  xAOD::PhotonContainer* photonContainer /* = 0*/) const
+{
 
-  if (electronContainer){    
-    for (xAOD::Electron* electron : *electronContainer){
-      if (tool->execute(ctx, electron).isFailure() ){
+  if (electronContainer) {
+    for (xAOD::Electron* electron : *electronContainer) {
+      if (tool->execute(ctx, electron).isFailure()) {
         ATH_MSG_ERROR("Problem executing tool on electrons: " << tool);
         return StatusCode::FAILURE;
       }
     }
   }
-  if (photonContainer){
-    for (xAOD::Photon* photon : *photonContainer){
-      if (tool->execute(ctx, photon).isFailure() ){
+  if (photonContainer) {
+    for (xAOD::Photon* photon : *photonContainer) {
+      if (tool->execute(ctx, photon).isFailure()) {
         ATH_MSG_ERROR("Problem executing tool on photons: " << tool);
         return StatusCode::FAILURE;
       }
     }
-  }  
+  }
   return StatusCode::SUCCESS;
 }
 
-bool topoEgammaBuilder::getElectron(const egammaRec* egRec, 
-                                    xAOD::ElectronContainer *electronContainer,
-                                    const unsigned int author,
-                                    const uint8_t type) const{  
+bool
+topoEgammaBuilder::getElectron(const egammaRec* egRec,
+                               xAOD::ElectronContainer* electronContainer,
+                               const unsigned int author,
+                               const uint8_t type) const
+{
 
-  if (!egRec || !electronContainer) return false;
+  if (!egRec || !electronContainer){
+    return false;
+  }
 
-  xAOD::Electron *electron = new xAOD::Electron();
-  electronContainer->push_back( electron );
-  electron->setAuthor( author );
+  xAOD::Electron* electron = new xAOD::Electron();
+  electronContainer->push_back(electron);
+  electron->setAuthor(author);
 
   static const SG::AuxElement::Accessor<uint8_t> acc("ambiguityType");
   acc(*electron) = type;
 
-  std::vector< ElementLink< xAOD::CaloClusterContainer > > clusterLinks;
-  for (size_t i = 0 ; i < egRec->getNumberOfClusters(); ++i){
-    clusterLinks.push_back( egRec->caloClusterElementLink(i) );
+  std::vector<ElementLink<xAOD::CaloClusterContainer>> clusterLinks;
+  for (size_t i = 0; i < egRec->getNumberOfClusters(); ++i) {
+    clusterLinks.push_back(egRec->caloClusterElementLink(i));
   }
-  electron->setCaloClusterLinks( clusterLinks );
+  electron->setCaloClusterLinks(clusterLinks);
 
-  std::vector< ElementLink< xAOD::TrackParticleContainer > > trackLinks;
-  for (size_t i = 0 ; i < egRec->getNumberOfTrackParticles(); ++i){
-    trackLinks.push_back( egRec->trackParticleElementLink(i) );
+  std::vector<ElementLink<xAOD::TrackParticleContainer>> trackLinks;
+  for (size_t i = 0; i < egRec->getNumberOfTrackParticles(); ++i) {
+    trackLinks.push_back(egRec->trackParticleElementLink(i));
   }
-  electron->setTrackParticleLinks( trackLinks );
+  electron->setTrackParticleLinks(trackLinks);
 
   electron->setCharge(electron->trackParticle()->charge());
-  //Set DeltaEta, DeltaPhi , DeltaPhiRescaled
-  std::array<double,4> deltaEta = egRec->deltaEta();
-  std::array<double,4> deltaPhi = egRec->deltaPhi();
-  std::array<double,4> deltaPhiRescaled = egRec->deltaPhiRescaled();
-
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[0]),xAOD::EgammaParameters::deltaEta0);
-  electron->setTrackCaloMatchValue(static_cast<float> (deltaPhi[0]),xAOD::EgammaParameters::deltaPhi0 );
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[0]), xAOD::EgammaParameters::deltaPhiRescaled0);
-
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[1]), xAOD::EgammaParameters::deltaEta1);
-  electron->setTrackCaloMatchValue(static_cast<float> (deltaPhi[1]),xAOD::EgammaParameters::deltaPhi1 );
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[1]), xAOD::EgammaParameters::deltaPhiRescaled1);
-
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[2]), xAOD::EgammaParameters::deltaEta2);
-  electron->setTrackCaloMatchValue(static_cast<float> (deltaPhi[2]),xAOD::EgammaParameters::deltaPhi2 );
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[2]), xAOD::EgammaParameters::deltaPhiRescaled2);
-
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[3]), xAOD::EgammaParameters::deltaEta3);
-  electron->setTrackCaloMatchValue(static_cast<float> (deltaPhi[3]),xAOD::EgammaParameters::deltaPhi3 );
-  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[3]), xAOD::EgammaParameters::deltaPhiRescaled3);
-
-  float deltaPhiLast = static_cast<float>(egRec->deltaPhiLast ());
-  electron->setTrackCaloMatchValue(deltaPhiLast,xAOD::EgammaParameters::deltaPhiFromLastMeasurement );
-
+  // Set DeltaEta, DeltaPhi , DeltaPhiRescaled
+  std::array<double, 4> deltaEta = egRec->deltaEta();
+  std::array<double, 4> deltaPhi = egRec->deltaPhi();
+  std::array<double, 4> deltaPhiRescaled = egRec->deltaPhiRescaled();
+
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[0]),
+                                   xAOD::EgammaParameters::deltaEta0);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhi[0]),
+                                   xAOD::EgammaParameters::deltaPhi0);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[0]),
+                                   xAOD::EgammaParameters::deltaPhiRescaled0);
+
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[1]),
+                                   xAOD::EgammaParameters::deltaEta1);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhi[1]),
+                                   xAOD::EgammaParameters::deltaPhi1);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[1]),
+                                   xAOD::EgammaParameters::deltaPhiRescaled1);
+
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[2]),
+                                   xAOD::EgammaParameters::deltaEta2);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhi[2]),
+                                   xAOD::EgammaParameters::deltaPhi2);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[2]),
+                                   xAOD::EgammaParameters::deltaPhiRescaled2);
+
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaEta[3]),
+                                   xAOD::EgammaParameters::deltaEta3);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhi[3]),
+                                   xAOD::EgammaParameters::deltaPhi3);
+  electron->setTrackCaloMatchValue(static_cast<float>(deltaPhiRescaled[3]),
+                                   xAOD::EgammaParameters::deltaPhiRescaled3);
+
+  float deltaPhiLast = static_cast<float>(egRec->deltaPhiLast());
+  electron->setTrackCaloMatchValue(
+    deltaPhiLast, xAOD::EgammaParameters::deltaPhiFromLastMeasurement);
 
   return true;
 }
 
-bool topoEgammaBuilder::getPhoton(const egammaRec* egRec,
-                                  xAOD::PhotonContainer *photonContainer,
-                                  const unsigned int author,
-                                  const uint8_t type) const{
-  if (!egRec || !photonContainer) return false;
+bool
+topoEgammaBuilder::getPhoton(const egammaRec* egRec,
+                             xAOD::PhotonContainer* photonContainer,
+                             const unsigned int author,
+                             const uint8_t type) const
+{
+  if (!egRec || !photonContainer){
+    return false;
+  }
 
-  xAOD::Photon *photon = new xAOD::Photon();
-  photonContainer->push_back( photon );
-  photon->setAuthor( author );
+  xAOD::Photon* photon = new xAOD::Photon();
+  photonContainer->push_back(photon);
+  photon->setAuthor(author);
   static const SG::AuxElement::Accessor<uint8_t> acc("ambiguityType");
-  acc(*photon)=type;
+  acc(*photon) = type;
 
   // Transfer the links to the clusters
-  std::vector< ElementLink< xAOD::CaloClusterContainer > > clusterLinks;
-  for (size_t i = 0 ; i < egRec->getNumberOfClusters(); ++i){
-    clusterLinks.push_back( egRec->caloClusterElementLink(i) );
+  std::vector<ElementLink<xAOD::CaloClusterContainer>> clusterLinks;
+  for (size_t i = 0; i < egRec->getNumberOfClusters(); ++i) {
+    clusterLinks.push_back(egRec->caloClusterElementLink(i));
   }
-  photon->setCaloClusterLinks( clusterLinks );
+  photon->setCaloClusterLinks(clusterLinks);
 
-  // Transfer the links to the vertices  
-  std::vector< ElementLink< xAOD::VertexContainer > > vertexLinks;
-  for (size_t i = 0 ; i < egRec->getNumberOfVertices(); ++i){
-    vertexLinks.push_back( egRec->vertexElementLink(i) );
+  // Transfer the links to the vertices
+  std::vector<ElementLink<xAOD::VertexContainer>> vertexLinks;
+  for (size_t i = 0; i < egRec->getNumberOfVertices(); ++i) {
+    vertexLinks.push_back(egRec->vertexElementLink(i));
   }
-  photon->setVertexLinks( vertexLinks );
+  photon->setVertexLinks(vertexLinks);
 
   // Transfer deltaEta/Phi info
   float deltaEta = egRec->deltaEtaVtx();
   float deltaPhi = egRec->deltaPhiVtx();
-  if (!photon->setVertexCaloMatchValue( deltaEta,
-                                        xAOD::EgammaParameters::convMatchDeltaEta1) ){
+  if (!photon->setVertexCaloMatchValue(
+        deltaEta, xAOD::EgammaParameters::convMatchDeltaEta1)) {
     ATH_MSG_WARNING("Could not transfer deltaEta to photon");
     return false;
   }
 
-  if (!photon->setVertexCaloMatchValue( deltaPhi,
-                                        xAOD::EgammaParameters::convMatchDeltaPhi1) ){
+  if (!photon->setVertexCaloMatchValue(
+        deltaPhi, xAOD::EgammaParameters::convMatchDeltaPhi1)) {
     ATH_MSG_WARNING("Could not transfer deltaPhi to photon");
     return false;
   }
diff --git a/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.h b/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.h
index 1f27c77ef35c..d3208e296c61 100644
--- a/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.h
+++ b/Reconstruction/egamma/egammaAlgs/src/topoEgammaBuilder.h
@@ -33,6 +33,7 @@
 #include "EgammaAnalysisInterfaces/IEGammaAmbiguityTool.h"
 #include "egammaInterfaces/IEMClusterTool.h" 
 #include "egammaInterfaces/IEMShowerBuilder.h" 
+#include "egammaInterfaces/IegammaOQFlagsBuilder.h" 
 #include "egammaInterfaces/IegammaBaseTool.h" 
 class egammaRec;
 
@@ -51,6 +52,30 @@ public:
     StatusCode execute(const EventContext& ctx) const override final;
 
 private:
+    /** Given an egammaRec object, a pointer to the electron container and the author, 
+     * create and dress an electron, pushing it back to the container and 
+     * calling the relevant tools **/
+
+    bool getElectron(const egammaRec* egRec, xAOD::ElectronContainer *electronContainer,
+            const unsigned int author, const uint8_t type) const;
+
+    /** Given an egammaRec object, a pointer to the photon container and the author, 
+     * create and dress a photon, pushing it back to the container and 
+     * calling the relevant tools **/
+    bool getPhoton(const egammaRec* egRec, xAOD::PhotonContainer *photonContainer,
+            const unsigned int author, uint8_t type) const;
+
+
+    /** @brief Do the final ambiguity **/  
+    StatusCode doAmbiguityLinks(xAOD::ElectronContainer *electronContainer, 
+            xAOD::PhotonContainer *photonContainer) const ;
+
+    /** @brief Call a tool using contExecute and electrons, photon containers if given **/
+    StatusCode CallTool(const EventContext& ctx,
+            const ToolHandle<IegammaBaseTool>& tool, 
+            xAOD::ElectronContainer *electronContainer = nullptr, 
+            xAOD::PhotonContainer *photonContainer = nullptr) const;
+
 
     /** @brief Vector of tools for dressing electrons and photons **/
     ToolHandleArray<IegammaBaseTool> m_egammaTools {this,
@@ -76,33 +101,15 @@ private:
 
     /** @brief Tool to resolve electron/photon ambiguity */
     ToolHandle<IEGammaAmbiguityTool> m_ambiguityTool {this, 
-        "AmbiguityTool", "egammaTools/EGammaAmbiguityTool", 
+        "AmbiguityTool", "ElectronPhotonSelectorTools/EGammaAmbiguityTool", 
         "Tool that does electron/photon ambiguity resolution"};
 
+    /** @brief Tool to resolve electron/photon ambiguity */
+    ToolHandle<IegammaOQFlagsBuilder> m_egammaOQTool {this, 
+      "ObjectQualityTool", {}, 
+      "Tool that adds electron/photon Object Quality info"};
 
-    /** Given an egammaRec object, a pointer to the electron container and the author, 
-     * create and dress an electron, pushing it back to the container and 
-     * calling the relevant tools **/
-
-    bool getElectron(const egammaRec* egRec, xAOD::ElectronContainer *electronContainer,
-            const unsigned int author, const uint8_t type) const;
-
-    /** Given an egammaRec object, a pointer to the photon container and the author, 
-     * create and dress a photon, pushing it back to the container and 
-     * calling the relevant tools **/
-    bool getPhoton(const egammaRec* egRec, xAOD::PhotonContainer *photonContainer,
-            const unsigned int author, uint8_t type) const;
-
-
-    /** @brief Do the final ambiguity **/  
-    StatusCode doAmbiguityLinks(xAOD::ElectronContainer *electronContainer, 
-            xAOD::PhotonContainer *photonContainer) const ;
 
-    /** @brief Call a tool using contExecute and electrons, photon containers if given **/
-    StatusCode CallTool(const EventContext& ctx,
-            const ToolHandle<IegammaBaseTool>& tool, 
-            xAOD::ElectronContainer *electronContainer = nullptr, 
-            xAOD::PhotonContainer *photonContainer = nullptr) const;
 
     /** @brief Name of the electron output collection*/
     SG::WriteHandleKey<xAOD::ElectronContainer> m_electronOutputKey {this,
@@ -128,11 +135,10 @@ private:
     //
     // Other properties.
     //
-    // others:
-    ServiceHandle<IChronoStatSvc> m_timingProfile;
-    Gaudi::Property<bool> m_doChrono {this, "doChrono", false, "do Chrono Service"};
     Gaudi::Property<bool> m_doPhotons {this, "doPhotons", true, "Run the Photon reconstruction"};
     Gaudi::Property<bool> m_doElectrons {this, "doElectrons", true, "Run the Electron reconstruction"};
+    bool m_doAmbiguity;
+    bool m_doOQ;
 };
 
 #endif
diff --git a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaBackShape.h b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaBackShape.h
index e7a9981683f4..031ded974d3a 100755
--- a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaBackShape.h
+++ b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaBackShape.h
@@ -2,22 +2,18 @@
   Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-///////////////////////////////////////////////////////////////////
-// IegammaBackShape.h, (c) ATLAS Detector software 2009
-///////////////////////////////////////////////////////////////////
 
 #ifndef EGAMMAINTERFACES_IEGAMMABACKSHAPE_H
 #define EGAMMAINTERFACES_IEGAMMABACKSHAPE_H
 
-/// @class IegammaBackShape
-/// @brief Interface for the Reconstruction/egamma/egammaCaloTools/egammaBackrShape
-///
-/// @author Frederic Derue derue@lpnhe.in2p3.fr
-/// @author Christos Anastopoulos
-///
-/// $Revision:$
-/// $Date: 2014-02-11 17:40:48 +0100 (Tue, 11 Feb 2014) $
-///
+/*
+ * @name   IegammaBackShape.h, (c) ATLAS Detector software 2009
+ * @class IegammaBackShape
+ * @brief Interface for the Reconstruction/egamma/egammaCaloTools/egammaBackShape
+ *
+ * @author Frederic Derue derue@lpnhe.in2p3.fr
+ * @author Christos Anastopoulos
+ */
 
 // Gaudi
 #include "GaudiKernel/IAlgTool.h"
diff --git a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaOQFlagsBuilder.h b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaOQFlagsBuilder.h
new file mode 100644
index 000000000000..e3e6dd3c8bd2
--- /dev/null
+++ b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/IegammaOQFlagsBuilder.h
@@ -0,0 +1,50 @@
+/*
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+*/
+
+#ifndef EGAMMAINTERFACES_IEGAMMABACKSHAPE_H
+#define EGAMMAINTERFACES_IEGAMMABACKSHAPE_H
+
+/*
+ * @name   IegammaOQFlagsBuilder.h, (c) ATLAS Detector software 2009
+ * @class IegammaOQFlagsBuilder
+ * @brief Interface for the
+ * Reconstruction/egamma/egammaTools/egammaOQFlagsBuilder
+ *
+ * @author Christos Anastopoulos
+ */
+
+// Gaudi
+#include "GaudiKernel/IAlgTool.h"
+
+#include "GaudiKernel/EventContext.h"
+// Forward declarations
+#include "xAODEgamma/EgammaFwd.h"
+class CaloDetDescrManager;
+static const InterfaceID IID_IegammaOQFlagsBuilder("IegammaOQFlagsBuilder",
+                                                   1,
+                                                   0);
+
+class IegammaOQFlagsBuilder : virtual public IAlgTool
+{
+
+public:
+  /** @brief Virtual destructor */
+  virtual ~IegammaOQFlagsBuilder(){};
+
+  /** @brief AlgTool interface methods */
+  static const InterfaceID& interfaceID();
+
+  /** @brief AlgTool method.*/
+  virtual StatusCode execute(const EventContext& ctx,
+                             const CaloDetDescrManager& cmgr,
+                             xAOD::Egamma& egamma) const = 0;
+};
+
+inline const InterfaceID&
+IegammaOQFlagsBuilder::interfaceID()
+{
+  return IID_IegammaOQFlagsBuilder;
+}
+
+#endif // EGAMMAINTERFACES_IEGAMMABACKSHAPE_H
diff --git a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/egammaInterfacesDict.h b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/egammaInterfacesDict.h
index 0bc7fb62cf60..8a46b57f925e 100644
--- a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/egammaInterfacesDict.h
+++ b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/egammaInterfacesDict.h
@@ -33,4 +33,5 @@
 #include "egammaInterfaces/IegammaSwTool.h"
 #include "egammaInterfaces/IegammaTrkRefitterTool.h"
 #include "egammaInterfaces/IegammaMVASvc.h"
+#include "egammaInterfaces/IegammaOQFlagsBuilder.h"
 #endif // EGAMMAINTERFACES_EGAMMAINTERFACESDICT_H
diff --git a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/selection.xml b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/selection.xml
index 93e1b04344fb..1969394b3f99 100644
--- a/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/selection.xml
+++ b/Reconstruction/egamma/egammaInterfaces/egammaInterfaces/selection.xml
@@ -17,5 +17,6 @@
   <class name="IegammaSwTool" />
   <class name="IegammaTrkRefitterTool" />
   <class name="IegammaMVASvc" />
+  <class name="IegammaOQFlagsBuilder" />
 </lcgdict>
 
diff --git a/Reconstruction/egamma/egammaRec/python/topoEgammaGetter.py b/Reconstruction/egamma/egammaRec/python/topoEgammaGetter.py
index 0578b26cff77..587be57d9383 100644
--- a/Reconstruction/egamma/egammaRec/python/topoEgammaGetter.py
+++ b/Reconstruction/egamma/egammaRec/python/topoEgammaGetter.py
@@ -1,50 +1,45 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from __future__ import print_function
+from egammaTools.egammaToolsFactories import \
+    EMClusterTool, EMFourMomBuilder, EMShowerBuilder, egammaOQFlagsBuilder, \
+    ElectronPIDBuilder, PhotonPIDBuilder
 
 # specifies standard (supercluster) egamma.
 from AthenaCommon.Logging import logging
-from AthenaCommon.SystemOfUnits import *
-from AthenaCommon.Constants import *
-
 from AthenaCommon.DetFlags import DetFlags
 from RecExConfig.Configured import Configured
-#
-from egammaRec import egammaKeys
-from egammaAlgs import egammaAlgsConf
-from egammaRec.Factories import AlgFactory, FcnWrapper
+from egammaRec.Factories import FcnWrapper
 from egammaRec import egammaRecFlags as egRecFlags
 egammaRecFlags = egRecFlags.jobproperties.egammaRecFlags
 
-#Some handy flags
 
-def doConversions() :
-  return DetFlags.detdescr.ID_on() and egammaRecFlags.doConversions()
-################
+def doConversions():
+    return DetFlags.detdescr.ID_on() and egammaRecFlags.doConversions()
+
+# The tools used to add properties
 
-# Import the tool factories
-from egammaTools.egammaToolsFactories import \
-    EMClusterTool, EMFourMomBuilder, EMShowerBuilder, egammaOQFlagsBuilder, \
-    ElectronPIDBuilder, PhotonPIDBuilder
 
-#The tools used to add properties 
 def egammaDecorationTools():
-  "Return a list with the tools that decorate both electrons and photons"
-  return [ EMFourMomBuilder(), egammaOQFlagsBuilder()]
+    "Return a list with the tools that decorate both electrons and photons"
+    return [EMFourMomBuilder()]
+
 
 def electronDecorationTools():
-  "Return a list with the tools that decorate only electrons"
-  return [ ElectronPIDBuilder() ]
+    "Return a list with the tools that decorate only electrons"
+    return [ElectronPIDBuilder()]
+
 
 def photonDecorationTools():
-  "Return a list with the tools that decorate only photons"
-  return [ PhotonPIDBuilder() ]
+    "Return a list with the tools that decorate only photons"
+    return [PhotonPIDBuilder()]
 #
 
-class topoEgammaGetter ( Configured ) :
+
+class topoEgammaGetter (Configured):
 
     def configure(self):
-        mlog = logging.getLogger ('topoEgammaGetter.py::configure:')
+        mlog = logging.getLogger('topoEgammaGetter.py::configure:')
         mlog.info('entering')
 
         # # the egammaTopoClusterCopier
@@ -58,52 +53,51 @@ class topoEgammaGetter ( Configured ) :
         #     return False
         # print self._egammaTopoClusterCopierHandle
 
-
         # the egammaRecBuilder
         from egammaAlgs.egammaRecBuilder import egammaRecBuilder
         try:
-            self._egammaRecBuilder = egammaRecBuilder(doTrackMatching = DetFlags.detdescr.ID_on(),
-                                                      doConversions = doConversions())
+            self._egammaRecBuilder = egammaRecBuilder(doTrackMatching=DetFlags.detdescr.ID_on(),
+                                                      doConversions=doConversions())
         except Exception:
             mlog.error("could not get handle to egammaRecBuilder")
             import traceback
             traceback.print_exc()
             return False
-        print (self._egammaRecBuilder)
+        print(self._egammaRecBuilder)
 
         # the supercluster builders
         from egammaAlgs.egammaSuperClusterBuilder import \
             electronSuperClusterBuilder, photonSuperClusterBuilder
         try:
-          self._electronSuperClusterBuilder = electronSuperClusterBuilder(
-            doTrackMatching = DetFlags.detdescr.ID_on())
-          self._photonSuperClusterBuilder = photonSuperClusterBuilder(
-            doConversions = doConversions())
+            self._electronSuperClusterBuilder = electronSuperClusterBuilder(
+                doTrackMatching=DetFlags.detdescr.ID_on())
+            self._photonSuperClusterBuilder = photonSuperClusterBuilder(
+                doConversions=doConversions())
         except Exception:
             mlog.error("could not get handle to supcluster builders")
             import traceback
             traceback.print_exc()
             return False
-        print (self._electronSuperClusterBuilder)
-        print (self._photonSuperClusterBuilder)
-
+        print(self._electronSuperClusterBuilder)
+        print(self._photonSuperClusterBuilder)
         # the topoEgammaBuilder (the part that puts everything together
         from egammaAlgs.topoEgammaBuilder import topoEgammaBuilder
         try:
-            self._topoEgammaBuilder = topoEgammaBuilder(                                   
-			       EMClusterTool=EMClusterTool,
-                   EMShowerTool=EMShowerBuilder,
-			       # Decoration tools
-                   egammaTools = FcnWrapper(egammaDecorationTools),
-                   ElectronTools = FcnWrapper(electronDecorationTools),
-                   PhotonTools = FcnWrapper(photonDecorationTools)
-                   )
+            self._topoEgammaBuilder = topoEgammaBuilder(
+                EMClusterTool=EMClusterTool,
+                EMShowerTool=EMShowerBuilder,
+                ObjectQualityTool=egammaOQFlagsBuilder,
+                # Decoration tools
+                egammaTools=FcnWrapper(egammaDecorationTools),
+                ElectronTools=FcnWrapper(electronDecorationTools),
+                PhotonTools=FcnWrapper(photonDecorationTools)
+            )
         except Exception:
             mlog.error("could not get handle to topoEgammaBuilder")
             import traceback
             traceback.print_exc()
             return False
-        print (self._topoEgammaBuilder)
+        print(self._topoEgammaBuilder)
 
         # the egammaLargeClusterMaker (Which chooses the cells to store in the AOD)
         from egammaAlgs.egammaLargeClusterMakerAlg import egammaLargeClusterMakerAlg
@@ -114,7 +108,6 @@ class topoEgammaGetter ( Configured ) :
             import traceback
             traceback.print_exc()
             return False
-        print (self._egammaLargeClusterMaker)
+        print(self._egammaLargeClusterMaker)
 
         return True
-
diff --git a/Reconstruction/egamma/egammaTools/python/EMPIDBuilderBase.py b/Reconstruction/egamma/egammaTools/python/EMPIDBuilderBase.py
index 131beba797bb..b8fdfcccf3b1 100755
--- a/Reconstruction/egamma/egammaTools/python/EMPIDBuilderBase.py
+++ b/Reconstruction/egamma/egammaTools/python/EMPIDBuilderBase.py
@@ -1,81 +1,94 @@
 # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
 
 # default configuration of the EMPIDBuilder
+from ROOT import LikeEnum
+from ROOT import egammaPID
 from AthenaCommon.Logging import logging
-from AthenaCommon.DetFlags import DetFlags
-
 import traceback
 
 from ElectronPhotonSelectorTools.ElectronIsEMSelectorMapping import electronPIDmenu
 from ElectronPhotonSelectorTools.PhotonIsEMSelectorMapping import photonPIDmenu
 
-#import base class
+# import base class
 from egammaTools.egammaToolsConf import EMPIDBuilder
 
 import cppyy
 cppyy.loadDictionary('ElectronPhotonSelectorToolsDict')
-from ROOT import egammaPID
-from ROOT import LikeEnum
 
-class EMPIDBuilderElectronBase ( EMPIDBuilder ) :
+
+class EMPIDBuilderElectronBase (EMPIDBuilder):
     __slots__ = ()
 
     def __init__(self, name="EMPIDBuilderElectronBase"):
-        EMPIDBuilder.__init__(self,name)
+        EMPIDBuilder.__init__(self, name)
         mlog = logging.getLogger(name+'::__init__')
         mlog.debug("entering")
 
        # Electron Selectors
         try:
-            # Cut based 
+            # Cut based
             from ElectronPhotonSelectorTools.ConfiguredAsgElectronIsEMSelectors import ConfiguredAsgElectronIsEMSelector
-            LooseElectronSelector = ConfiguredAsgElectronIsEMSelector("LooseElectronSelector", egammaPID.ElectronIDLoosePP)
-            MediumElectronSelector = ConfiguredAsgElectronIsEMSelector("MediumElectronSelector", egammaPID.ElectronIDMediumPP)
-            TightElectronSelector = ConfiguredAsgElectronIsEMSelector("TightElectronSelector", egammaPID.ElectronIDTightPP)
+            LooseElectronSelector = ConfiguredAsgElectronIsEMSelector(
+                "LooseElectronSelector", egammaPID.ElectronIDLoosePP)
+            MediumElectronSelector = ConfiguredAsgElectronIsEMSelector(
+                "MediumElectronSelector", egammaPID.ElectronIDMediumPP)
+            TightElectronSelector = ConfiguredAsgElectronIsEMSelector(
+                "TightElectronSelector", egammaPID.ElectronIDTightPP)
 
             # Likelihood
             from ElectronPhotonSelectorTools.ConfiguredAsgElectronLikelihoodTools import ConfiguredAsgElectronLikelihoodTool
-            LooseLHSelector = ConfiguredAsgElectronLikelihoodTool("LooseLHSelector", LikeEnum.Loose)
-            LooseLHSelector.primaryVertexContainer="PrimaryVertices" 
-            MediumLHSelector = ConfiguredAsgElectronLikelihoodTool("MediumLHSelector", LikeEnum.Medium)
-            MediumLHSelector.primaryVertexContainer="PrimaryVertices"
-            TightLHSelector = ConfiguredAsgElectronLikelihoodTool("TightLHSelector", LikeEnum.Tight)
-            TightLHSelector.primaryVertexContainer="PrimaryVertices"
+            LooseLHSelector = ConfiguredAsgElectronLikelihoodTool(
+                "LooseLHSelector", LikeEnum.Loose)
+            LooseLHSelector.primaryVertexContainer = "PrimaryVertices"
+            MediumLHSelector = ConfiguredAsgElectronLikelihoodTool(
+                "MediumLHSelector", LikeEnum.Medium)
+            MediumLHSelector.primaryVertexContainer = "PrimaryVertices"
+            TightLHSelector = ConfiguredAsgElectronLikelihoodTool(
+                "TightLHSelector", LikeEnum.Tight)
+            TightLHSelector.primaryVertexContainer = "PrimaryVertices"
 
             # Multi Lepton
             from ElectronPhotonSelectorTools.ElectronPhotonSelectorToolsConf import AsgElectronMultiLeptonSelector
-            MultiLeptonSelector=AsgElectronMultiLeptonSelector("MultiLeptonSelector")
+            MultiLeptonSelector = AsgElectronMultiLeptonSelector(
+                "MultiLeptonSelector")
 
         except:
             mlog.error("could not get configure tools")
             traceback.print_exc()
             return False
 
-        self.electronIsEMselectors = [LooseElectronSelector, MediumElectronSelector, TightElectronSelector]
+        self.electronIsEMselectors = [
+            LooseElectronSelector, MediumElectronSelector, TightElectronSelector]
         self.electronIsEMselectorResultNames = ["Loose", "Medium", "Tight"]
-        self.electronLHselectors = [LooseLHSelector, MediumLHSelector, TightLHSelector]
-        self.electronLHselectorResultNames= ["LHLoose","LHMedium","LHTight"]
-        self.genericIsEMselectors =[MultiLeptonSelector]
-        self.genericIsEMselectorResultNames=["MultiLepton"]
+        self.electronLHselectors = [
+            LooseLHSelector, MediumLHSelector, TightLHSelector]
+        self.electronLHselectorResultNames = ["LHLoose", "LHMedium", "LHTight"]
+        self.genericIsEMselectors = [MultiLeptonSelector]
+        self.genericIsEMselectorResultNames = ["MultiLepton"]
+        self.LuminosityTool = None
+
 
-class EMPIDBuilderPhotonBase ( EMPIDBuilder ) :
+class EMPIDBuilderPhotonBase (EMPIDBuilder):
     __slots__ = ()
 
     def __init__(self, name="EMPIDBuilderPhotonBase"):
-        EMPIDBuilder.__init__(self,name)
+        EMPIDBuilder.__init__(self, name)
         mlog = logging.getLogger(name+'::__init__')
         mlog.debug("entering")
 
         # photon Selectors
         try:
             from ElectronPhotonSelectorTools.ConfiguredAsgPhotonIsEMSelectors import ConfiguredAsgPhotonIsEMSelector
-            LoosePhotonSelector = ConfiguredAsgPhotonIsEMSelector("LoosePhotonSelector", egammaPID.PhotonIDLoose)
-            TightPhotonSelector = ConfiguredAsgPhotonIsEMSelector("TightPhotonSelector", egammaPID.PhotonIDTight)
+            LoosePhotonSelector = ConfiguredAsgPhotonIsEMSelector(
+                "LoosePhotonSelector", egammaPID.PhotonIDLoose)
+            TightPhotonSelector = ConfiguredAsgPhotonIsEMSelector(
+                "TightPhotonSelector", egammaPID.PhotonIDTight)
 
         except:
             mlog.error("could not get configure tools")
             traceback.print_exc()
             return False
 
-        self.photonIsEMselectors= [LoosePhotonSelector,TightPhotonSelector]
-        self.photonIsEMselectorResultNames = ["Loose","Tight"]
+        self.photonIsEMselectors = [LoosePhotonSelector, TightPhotonSelector]
+        self.photonIsEMselectorResultNames = ["Loose", "Tight"]
+        self.LuminosityTool = None
diff --git a/Reconstruction/egamma/egammaTools/python/egammaToolsFactories.py b/Reconstruction/egamma/egammaTools/python/egammaToolsFactories.py
index c0397adeeef9..426d0715c0ad 100644
--- a/Reconstruction/egamma/egammaTools/python/egammaToolsFactories.py
+++ b/Reconstruction/egamma/egammaTools/python/egammaToolsFactories.py
@@ -1,106 +1,134 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 __doc__ = "ToolFactories to instantiate all egammaTools with default configuration"
 __author__ = "Bruno Lenzi"
 
+from ROOT import egammaPID
+import cppyy
+from ElectronPhotonSelectorTools.ConfiguredAsgForwardElectronIsEMSelectors import ConfiguredAsgForwardElectronIsEMSelector
+from .EMPIDBuilderBase import EMPIDBuilderPhotonBase
+from .EMPIDBuilderBase import EMPIDBuilderElectronBase
+from ElectronPhotonSelectorTools import ElectronPhotonSelectorToolsConf
+from egammaTrackTools.egammaTrackToolsFactories import EMExtrapolationTools
+from egammaMVACalib.egammaMVACalibFactories import egammaMVASvc
+
+
 from egammaTools import egammaToolsConf
-from egammaRec.Factories import FcnWrapper, ToolFactory
+from egammaRec.Factories import  ToolFactory
 from egammaRec import egammaKeys
-from egammaRec.egammaRecFlags import jobproperties # to set jobproperties.egammaRecFlags
-from RecExConfig.RecFlags import rec
+# to set jobproperties.egammaRecFlags
+from egammaRec.egammaRecFlags import jobproperties
 
 import six
 
+
 def configureClusterCorrections(swTool):
-  "Add attributes ClusterCorrectionToolsXX to egammaSwTool object"
-  from CaloClusterCorrection.CaloSwCorrections import  make_CaloSwCorrections, rfac, etaoff_b1, etaoff_e1, \
-      etaoff_b2,etaoff_e2,phioff_b2,phioff_e2,update,time,listBadChannel
-  from CaloRec.CaloRecMakers import _process_tools
-
-  clusterTypes = dict(
-    Ele35='ele35', Ele55='ele55', Ele37='ele37',
-    Gam35='gam35_unconv', Gam55='gam55_unconv',Gam37='gam37_unconv',
-    Econv35='gam35_conv', Econv55='gam55_conv', Econv37='gam37_conv'
-  )
-  for attrName, clName in six.iteritems (clusterTypes):
-    x = 'ClusterCorrectionTools' + attrName
-    if not hasattr(swTool, x) or getattr(swTool, x):
-      continue
-    y = make_CaloSwCorrections(clName, suffix='EG',
-      version = jobproperties.egammaRecFlags.clusterCorrectionVersion(),
-      cells_name=egammaKeys.caloCellKey() )
-    setattr(swTool, x, _process_tools (swTool, y) )
-
-  #Super cluster position only corrections
-  if jobproperties.egammaRecFlags.doSuperclusters():
-    for attrName, clName in six.iteritems (clusterTypes):
-      n = 'ClusterCorrectionToolsSuperCluster' + attrName
-      if not hasattr(swTool, n) or getattr(swTool, n):
-        continue
-  
-      setattr(swTool, n ,_process_tools(swTool, 
-                                        make_CaloSwCorrections(clName, suffix ='EGSuperCluster',
-                                                               corrlist=[[rfac,'v5'],[etaoff_b1,'v5'],[etaoff_e1,'v5'],
-                                                                         [etaoff_b2,'v5'],[etaoff_e2,'v5'], [phioff_b2, 'v5data'], 
-                                                                         [phioff_e2,  'v5data'], [update], [time], [listBadChannel]],
-                                                               cells_name=egammaKeys.caloCellKey() )))
-    #End of super cluster position only corrections
-#-------------------------
+    "Add attributes ClusterCorrectionToolsXX to egammaSwTool object"
+    from CaloClusterCorrection.CaloSwCorrections import make_CaloSwCorrections, rfac, etaoff_b1, etaoff_e1, \
+        etaoff_b2, etaoff_e2, phioff_b2, phioff_e2, update, time, listBadChannel
+    from CaloRec.CaloRecMakers import _process_tools
+
+    clusterTypes = dict(
+        Ele35='ele35', Ele55='ele55', Ele37='ele37',
+        Gam35='gam35_unconv', Gam55='gam55_unconv', Gam37='gam37_unconv',
+        Econv35='gam35_conv', Econv55='gam55_conv', Econv37='gam37_conv'
+    )
+    for attrName, clName in six.iteritems(clusterTypes):
+        x = 'ClusterCorrectionTools' + attrName
+        if not hasattr(swTool, x) or getattr(swTool, x):
+            continue
+        y = make_CaloSwCorrections(clName, suffix='EG',
+                                   version=jobproperties.egammaRecFlags.clusterCorrectionVersion(),
+                                   cells_name=egammaKeys.caloCellKey())
+        setattr(swTool, x, _process_tools(swTool, y))
+
+    # Super cluster position only corrections
+    if jobproperties.egammaRecFlags.doSuperclusters():
+        for attrName, clName in six.iteritems(clusterTypes):
+            n = 'ClusterCorrectionToolsSuperCluster' + attrName
+            if not hasattr(swTool, n) or getattr(swTool, n):
+                continue
+
+            setattr(swTool, n, _process_tools(swTool,
+                                              make_CaloSwCorrections(
+                                                  clName,
+                                                  suffix='EGSuperCluster',
+                                                  corrlist=[
+                                                      [rfac, 'v5'],
+                                                      [etaoff_b1, 'v5'],
+                                                      [etaoff_e1, 'v5'],
+                                                      [etaoff_b2, 'v5'],
+                                                      [etaoff_e2, 'v5'],
+                                                      [phioff_b2, 'v5data'],
+                                                      [phioff_e2, 'v5data'],
+                                                      [update],
+                                                      [time],
+                                                      [listBadChannel]],
+                                                  cells_name=egammaKeys.caloCellKey())))
+        # End of super cluster position only corrections
+
 
 egammaSwTool = ToolFactory(egammaToolsConf.egammaSwTool,
                            postInit=[configureClusterCorrections])
 
-from egammaMVACalib.egammaMVACalibFactories import egammaMVASvc
-
-EMClusterTool = ToolFactory(egammaToolsConf.EMClusterTool,
-                            OutputClusterContainerName = egammaKeys.outputClusterKey(),
-                            OutputTopoSeededClusterContainerName = egammaKeys.outputTopoSeededClusterKey(),
-                            ClusterCorrectionTool = egammaSwTool,
-                            doSuperCluster = jobproperties.egammaRecFlags.doSuperclusters(),
-                            MVACalibSvc = egammaMVASvc
-                            )
-
 
-from egammaTrackTools.egammaTrackToolsFactories import EMExtrapolationTools
+EMClusterTool = ToolFactory(
+    egammaToolsConf.EMClusterTool,
+    OutputClusterContainerName=egammaKeys.outputClusterKey(),
+    OutputTopoSeededClusterContainerName=egammaKeys.outputTopoSeededClusterKey(),
+    ClusterCorrectionTool=egammaSwTool,
+    doSuperCluster=jobproperties.egammaRecFlags.doSuperclusters(),
+    MVACalibSvc=egammaMVASvc
+)
 
 
-EMConversionBuilder = ToolFactory( egammaToolsConf.EMConversionBuilder,
-                                   ConversionContainerName = egammaKeys.outputConversionKey(),
-                                   ExtrapolationTool = EMExtrapolationTools)   
+EMConversionBuilder = ToolFactory(
+    egammaToolsConf.EMConversionBuilder,
+    ConversionContainerName=egammaKeys.outputConversionKey(),
+    ExtrapolationTool=EMExtrapolationTools)
 
-from ElectronPhotonSelectorTools import ElectronPhotonSelectorToolsConf
-EGammaAmbiguityTool = ToolFactory( ElectronPhotonSelectorToolsConf.EGammaAmbiguityTool )
+EGammaAmbiguityTool = ToolFactory(
+    ElectronPhotonSelectorToolsConf.EGammaAmbiguityTool)
 
-EMFourMomBuilder = ToolFactory( egammaToolsConf.EMFourMomBuilder)
+EMFourMomBuilder = ToolFactory(egammaToolsConf.EMFourMomBuilder)
 
-egammaLargeClusterMakerTool = ToolFactory( egammaToolsConf.egammaLargeClusterMaker,
-                                           name = "egammaLCMakerTool",
-                                           InputClusterCollection = egammaKeys.ClusterKey(),
-                                           CellsName = egammaKeys.caloCellKey()
-                                           )
+egammaLargeClusterMakerTool = ToolFactory(
+    egammaToolsConf.egammaLargeClusterMaker,
+    name="egammaLCMakerTool",
+    InputClusterCollection=egammaKeys.ClusterKey(),
+    CellsName=egammaKeys.caloCellKey()
+)
 
 # Electron Selectors
-from .EMPIDBuilderBase import EMPIDBuilderElectronBase
-ElectronPIDBuilder = ToolFactory( EMPIDBuilderElectronBase, name = "ElectronPIDBuilder")
+ElectronPIDBuilder = ToolFactory(
+    EMPIDBuilderElectronBase,
+    name="ElectronPIDBuilder")
 
 # Photon Selectors
-from .EMPIDBuilderBase import EMPIDBuilderPhotonBase
-PhotonPIDBuilder = ToolFactory( EMPIDBuilderPhotonBase, name = "PhotonPIDBuilder")
+PhotonPIDBuilder = ToolFactory(
+    EMPIDBuilderPhotonBase,
+    name="PhotonPIDBuilder")
 
 # ForwardElectron Selectors
-from ElectronPhotonSelectorTools.ConfiguredAsgForwardElectronIsEMSelectors import ConfiguredAsgForwardElectronIsEMSelector
 
-import cppyy
 cppyy.loadDictionary('ElectronPhotonSelectorToolsDict')
-from ROOT import egammaPID
-
-LooseForwardElectronSelector = ToolFactory( ConfiguredAsgForwardElectronIsEMSelector, name="LooseForwardElectronSelector", quality = egammaPID.ForwardElectronIDLoose )
-MediumForwardElectronSelector = ToolFactory( ConfiguredAsgForwardElectronIsEMSelector, name="MediumForwardElectronSelector", quality = egammaPID.ForwardElectronIDMedium )
-TightForwardElectronSelector = ToolFactory( ConfiguredAsgForwardElectronIsEMSelector, name="TightForwardElectronSelector", quality = egammaPID.ForwardElectronIDTight )
 
-#-------------------------
+LooseForwardElectronSelector = ToolFactory(
+    ConfiguredAsgForwardElectronIsEMSelector,
+    name="LooseForwardElectronSelector",
+    quality=egammaPID.ForwardElectronIDLoose)
+MediumForwardElectronSelector = ToolFactory(
+    ConfiguredAsgForwardElectronIsEMSelector,
+    name="MediumForwardElectronSelector",
+    quality=egammaPID.ForwardElectronIDMedium)
+TightForwardElectronSelector = ToolFactory(
+    ConfiguredAsgForwardElectronIsEMSelector,
+    name="TightForwardElectronSelector",
+    quality=egammaPID.ForwardElectronIDTight)
+
+# -------------------------
 
 # Import the factories that are not defined here
 from .EMShowerBuilder import EMShowerBuilder
 from .egammaOQFlagsBuilder import egammaOQFlagsBuilder
-from .EMTrackMatchBuilder import EMTrackMatchBuilder
+from .EMTrackMatchBuilder import EMTrackMatchBuilder
\ No newline at end of file
diff --git a/Reconstruction/egamma/egammaTools/src/EMPIDBuilder.cxx b/Reconstruction/egamma/egammaTools/src/EMPIDBuilder.cxx
index 1a1b2022a73a..47293e26ebba 100644
--- a/Reconstruction/egamma/egammaTools/src/EMPIDBuilder.cxx
+++ b/Reconstruction/egamma/egammaTools/src/EMPIDBuilder.cxx
@@ -15,30 +15,17 @@ EMPIDBuilder::EMPIDBuilder(const std::string& type,
         const IInterface* parent)
 : egammaBaseTool(type, name, parent)
 {
-    //
-    // constructor
-    //
-
     // declare interface
     declareInterface<IegammaBaseTool>(this);
 
 }
 
-// ===============================================================
 EMPIDBuilder::~EMPIDBuilder()
 { 
-    //
-    // destructor
-    //
 }
 
-// ==================================================================
 StatusCode EMPIDBuilder::initialize()
 {
-    //
-    // initialize method
-    //
-
     ATH_MSG_DEBUG(" Initializing EMPIDBuilder");
 
     ATH_CHECK(m_electronIsEMselectors.retrieve());
@@ -70,31 +57,25 @@ StatusCode EMPIDBuilder::initialize()
     }
 
     if (m_UselumiBlockMuTool) {
-        // retrieve the lumi tool
-        if (m_lumiBlockMuTool.retrieve().isFailure()) {
+       std::cout << "enabling lumiBlockMuTool" <<std::endl; 
+       if (m_lumiBlockMuTool.retrieve().isFailure()) {
             ATH_MSG_FATAL("Unable to retrieve Luminosity Tool");
             return StatusCode::FAILURE;
         } else {
             ATH_MSG_DEBUG("Successfully retrieved Luminosity Tool");
         }
     } else {
+       std::cout << "disabling lumiBlockMuTool" <<std::endl; 
         m_lumiBlockMuTool.disable();
     }
     return StatusCode::SUCCESS;
 }
 
-// ====================================================================
 StatusCode EMPIDBuilder::finalize()
 {
-    //
-    // finalize method
-    //
-
     return StatusCode::SUCCESS;
 }
 
-
-// =====================================================================
 StatusCode EMPIDBuilder::execute(const EventContext& ctx, xAOD::Egamma* eg) const
 {   
 
@@ -155,11 +136,13 @@ StatusCode EMPIDBuilder::execute(const EventContext& ctx, xAOD::Egamma* eg) cons
         //save the bool result
         eg->setPassSelection(static_cast<bool>(accept), m_electronLHselectorResultNames[i]);
         //save the isem
-        eg->setSelectionisEM(static_cast<unsigned int> (accept.getCutResultInverted()), "isEM"+m_electronLHselectorResultNames[i]); 
+        eg->setSelectionisEM(static_cast<unsigned int>(accept.getCutResultInverted()),
+                             "isEM" + m_electronLHselectorResultNames[i]);
 
         //save the LHValue only once
         if(i==0){
-            eg->setLikelihoodValue(static_cast<float>(m_electronLHselectors[i]->calculate(ctx,eg,avg_mu)), m_LHValueName);
+          eg->setLikelihoodValue(
+            static_cast<float>(m_electronLHselectors[i]->calculate(ctx, eg, avg_mu)),m_LHValueName);
         }  
     }
 
@@ -169,12 +152,11 @@ StatusCode EMPIDBuilder::execute(const EventContext& ctx, xAOD::Egamma* eg) cons
         //save the bool result
         eg->setPassSelection(static_cast<bool>(accept), m_genericIsEMselectorResultNames[i]);
         //save the isem
-        eg->setSelectionisEM(static_cast<unsigned int> (accept.getCutResultInverted()), "isEM"+m_genericIsEMselectorResultNames[i]);
+        eg->setSelectionisEM(static_cast<unsigned int>(accept.getCutResultInverted()),
+                             "isEM" + m_genericIsEMselectorResultNames[i]);
     }
 
 
     return StatusCode::SUCCESS;
 }
 
-
-
diff --git a/Reconstruction/egamma/egammaTools/src/egammaBaseTool.cxx b/Reconstruction/egamma/egammaTools/src/egammaBaseTool.cxx
index 24ada195be44..addb54a1a8e0 100644
--- a/Reconstruction/egamma/egammaTools/src/egammaBaseTool.cxx
+++ b/Reconstruction/egamma/egammaTools/src/egammaBaseTool.cxx
@@ -1,12 +1,10 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "egammaBaseTool.h"
 
-// INCLUDE Header Files:
 
-// ====================================================================================
 egammaBaseTool::egammaBaseTool(const std::string& type,
 			       const std::string& name,
 			       const IInterface* parent):
@@ -15,16 +13,13 @@ egammaBaseTool::egammaBaseTool(const std::string& type,
   declareInterface<IegammaBaseTool>(this);
 }
 
-// ====================================================================================
 egammaBaseTool::~egammaBaseTool() { 
 }
 
-// ====================================================================================
 StatusCode egammaBaseTool::initialize() {  
   return StatusCode::SUCCESS;
 }
 
-// =========================================================================================
 StatusCode egammaBaseTool::finalize(){
   return StatusCode::SUCCESS;
 }
diff --git a/Reconstruction/egamma/egammaTools/src/egammaBaseTool.h b/Reconstruction/egamma/egammaTools/src/egammaBaseTool.h
index 6de053386d38..7108ec799269 100644
--- a/Reconstruction/egamma/egammaTools/src/egammaBaseTool.h
+++ b/Reconstruction/egamma/egammaTools/src/egammaBaseTool.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef EGAMMATOOLS_EGAMMABASETOOL_H
@@ -8,32 +8,37 @@
 /**
   @class  egammaBaseTool
           Base Tool for all egamma tool that require 
-          an egamma object as its input.  Hence the specific versions
+          an egamma object as its input. Hence the specific versions
           will have access to all the framework services in addition
           of being passed an 'egamma' object.  The derived 
-          tool must implement an execute(egamma*) method.
+          tools must implement 
+          execute(const EventContext& ctx, xAOD::Egamma* eg).
+          Used typically for constucting ToolHandleArrays of 
+          egammaTools
   @author F. Derue, A. Kaczmarska
 */
 
 // INCLUDE HEADER FILES:
 #include "AthenaBaseComps/AthAlgTool.h"
 #include "egammaInterfaces/IegammaBaseTool.h"
- 
-class egammaBaseTool : public AthAlgTool, virtual public IegammaBaseTool{
 
- public:
+class egammaBaseTool
+  : public AthAlgTool
+  , virtual public IegammaBaseTool
+{
+
+public:
   /** @brief Default constructor*/
-  egammaBaseTool(const std::string& name, const std::string& description, 
-		 const IInterface* parent);
-  /** @brief destructor*/
-  virtual ~egammaBaseTool();
+   egammaBaseTool(const std::string& name,
+                  const std::string& description,
+                  const IInterface* parent);
+   /** @brief destructor*/
+   virtual ~egammaBaseTool();
 
-  /** @brief initialize method*/
-  StatusCode initialize() override;
-  /** @brief finalize method*/
-  StatusCode finalize() override;
-  
- 
+   /** @brief initialize method*/
+   StatusCode initialize() override;
+   /** @brief finalize method*/
+   StatusCode finalize() override;
 };
 
 #endif // EGAMMATOOLS_EGAMMABASETOOL_H
diff --git a/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.cxx b/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.cxx
index fbb8be357cf3..449164fb2356 100644
--- a/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.cxx
+++ b/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.cxx
@@ -4,127 +4,124 @@
 
 // INCLUDE HEADER FILES:
 #include "egammaOQFlagsBuilder.h"
+#include "xAODCaloEvent/CaloCluster.h"
 #include "xAODEgamma/Egamma.h"
 #include "xAODEgamma/EgammaxAODHelpers.h"
-#include "xAODCaloEvent/CaloCluster.h"
-#include <algorithm> 
-#include <math.h> 
+#include <algorithm>
+#include <cmath>
+#include <vector>
 
-#include "StoreGate/StoreGateSvc.h"
+#include "CLHEP/Units/SystemOfUnits.h"
 #include "CaloConditions/CaloAffectedRegionInfoVec.h"
-#include "Identifier/HWIdentifier.h"
-#include "CaloIdentifier/LArEM_ID.h"
 #include "CaloIdentifier/CaloCell_ID.h"
-#include "CLHEP/Units/SystemOfUnits.h"
+#include "CaloIdentifier/LArEM_ID.h"
 #include "FourMomUtils/P4Helpers.h"
+#include "Identifier/HWIdentifier.h"
 #include "StoreGate/ReadHandle.h"
-//  END OF HEADER FILES INCLUDE
+#include "StoreGate/StoreGateSvc.h"
 
 using CLHEP::GeV;
 
-
-// ===========================================================================
-egammaOQFlagsBuilder::egammaOQFlagsBuilder(const std::string& type,
-					   const std::string& name,
-					   const IInterface* parent)
-  : egammaBaseTool(type, name, parent),
-    m_emHelper(nullptr)
+namespace {
+bool
+isbadtilecell(CaloCellList& ccl,
+              const CaloDetDescrManager& cmgr,
+              const float clusterEta,
+              const float clusterPhi,
+              const double sizeEta,
+              const double sizePhi,
+              const CaloSampling::CaloSample sample)
 {
-  //
-  // constructor
-  //
 
-  // declare interface
-  declareInterface<IegammaBaseTool>(this);
+  bool isbadtilecell = false;
+  ccl.select(cmgr,clusterEta, clusterPhi, sizeEta, sizePhi, sample);
+  CaloCellList::list_iterator cclIter = ccl.begin();
+  CaloCellList::list_iterator cclIterEnd = ccl.end();
+  for (; cclIter != cclIterEnd; cclIter++) {
+    const CaloCell* cell = (*cclIter);
+    if (cell->badcell()) { // check of bad tile cell
+      isbadtilecell = true;
+      break;
+    }
+  }
+  return isbadtilecell;
+}
+}
 
+egammaOQFlagsBuilder::egammaOQFlagsBuilder(const std::string& type,
+                                           const std::string& name,
+                                           const IInterface* parent)
+  : AthAlgTool(type, name, parent)
+  , m_emHelper(nullptr)
+{
+  declareInterface<IegammaOQFlagsBuilder>(this);
   m_calocellId = nullptr;
 }
 
-// ===============================================================
-egammaOQFlagsBuilder::~egammaOQFlagsBuilder()
-{ 
-  //
-  // destructor
-  //
-}
+egammaOQFlagsBuilder::~egammaOQFlagsBuilder() {}
 
-// ==================================================================
-StatusCode egammaOQFlagsBuilder::initialize()
+StatusCode
+egammaOQFlagsBuilder::initialize()
 {
-  //
-  // initialize method
-  //
-
-  ATH_MSG_DEBUG(" Initializing egammaOQFlagsBuilder");
- 
   ATH_CHECK(m_cellsKey.initialize());
   ATH_CHECK(m_bcContKey.initialize());
   ATH_CHECK(m_affKey.initialize());
 
-   //Get CaloAffectedTool
+  // Get CaloAffectedTool
   StatusCode sc = m_affectedTool.retrieve();
-  if (sc.isFailure()){
-    msg(MSG::ERROR) << "Could not retrieve CaloAffectedTool " << m_affectedTool << endmsg;
+  if (sc.isFailure()) {
+    ATH_MSG_ERROR( "Could not retrieve CaloAffectedTool " << m_affectedTool);
     return StatusCode::FAILURE;
-  } else {
-    //if (msgLvl(MSG::DEBUG)) msg(MSG::DEBUG) << "CaloAffectedTool" << m_affectedTool << " retrieved" << endmsg;
   }
 
-
-  sc=detStore()->retrieve(m_calocellId, "CaloCell_ID"); 
-  if(sc.isFailure()){
-    msg(MSG::WARNING) <<  "Cannot retrieve online_id" << endmsg;
+  sc = detStore()->retrieve(m_calocellId, "CaloCell_ID");
+  if (sc.isFailure()) {
+    ATH_MSG_WARNING("Cannot retrieve online_id");
     return StatusCode::FAILURE;
-  } else {
-    //if (msgLvl(MSG::DEBUG)) msg(MSG::DEBUG) << "CaloCell_ID" << m_calocellId << " retrieved" << endmsg;
   }
-  
-  sc=detStore()->retrieve(m_emHelper); 
-  if(sc.isFailure()){
-    msg(MSG::WARNING) <<   "Cannot retrieve online_id" << endmsg;
+
+  sc = detStore()->retrieve(m_emHelper);
+  if (sc.isFailure()) {
+    ATH_MSG_WARNING("Cannot retrieve online_id");
     return StatusCode::FAILURE;
-  } else {
-    //if (msgLvl(MSG::DEBUG)) msg(MSG::DEBUG) << "CaloCell_ID  retrieved" << endmsg;
   }
 
-
   return StatusCode::SUCCESS;
 }
 
-// ====================================================================
-StatusCode egammaOQFlagsBuilder::finalize()
+StatusCode
+egammaOQFlagsBuilder::finalize()
 {
-  //
-  // finalize method
-  //
-
   return StatusCode::SUCCESS;
 }
 
-
-
-// ===============================================================
-bool egammaOQFlagsBuilder::findCentralCell(const xAOD::CaloCluster* cluster,
-                                           Identifier& cellCentrId) const {
+bool
+egammaOQFlagsBuilder::findCentralCell(const xAOD::CaloCluster* cluster,
+                                      Identifier& cellCentrId) const
+{
 
   bool thereIsACentrCell = false;
 
-  //LOOP OVER CLUSTER TO FIND THE CENTRAL CELL IN S2
-  xAOD::CaloCluster::const_cell_iterator  cellIter    = cluster->cell_begin();
-  xAOD::CaloCluster::const_cell_iterator  cellIterEnd = cluster->cell_end();
+  // LOOP OVER CLUSTER TO FIND THE CENTRAL CELL IN S2
+  xAOD::CaloCluster::const_cell_iterator cellIter = cluster->cell_begin();
+  xAOD::CaloCluster::const_cell_iterator cellIterEnd = cluster->cell_end();
   float clusEta = cluster->eta();
   float clusPhi = cluster->phi();
   float energymax = -999999.;
 
-  for( ;cellIter!=cellIterEnd;cellIter++) {
+  for (; cellIter != cellIterEnd; cellIter++) {
     const CaloCell* cell = (*cellIter);
-    if (!cell) continue;
+    if (!cell)
+      continue;
     float eta = cell->eta();
     float phi = cell->phi();
     float energy = cell->energy();
-    CaloSampling::CaloSample layer = cell->caloDDE()->getSampling() ;
-    if(fabs(eta - clusEta)<0.025 && fabs(P4Helpers::deltaPhi(phi, clusPhi))<0.025 && (layer==CaloSampling::EMB2 || layer==CaloSampling::EME2) && (energy>energymax)) { 
-      energymax=energy;
+    CaloSampling::CaloSample layer = cell->caloDDE()->getSampling();
+    if (fabs(eta - clusEta) < 0.025 &&
+        fabs(P4Helpers::deltaPhi(phi, clusPhi)) < 0.025 &&
+        (layer == CaloSampling::EMB2 || layer == CaloSampling::EME2) &&
+        (energy > energymax)) {
+      energymax = energy;
       cellCentrId = cellIter->ID();
       thereIsACentrCell = true;
     }
@@ -132,334 +129,436 @@ bool egammaOQFlagsBuilder::findCentralCell(const xAOD::CaloCluster* cluster,
   return thereIsACentrCell;
 }
 
-// ===============================================================
-bool egammaOQFlagsBuilder::isCore(const Identifier Id, const std::vector<IdentifierHash>& neighbourList) const {
+bool
+egammaOQFlagsBuilder::isCore(
+  const Identifier Id,
+  const std::vector<IdentifierHash>& neighbourList) const
+{
   const IdentifierHash hashId = m_calocellId->calo_cell_hash(Id);
-  std::vector<IdentifierHash>::const_iterator it=std::find(neighbourList.begin(),neighbourList.end(),hashId);
-  return (it!=neighbourList.end());
+  std::vector<IdentifierHash>::const_iterator it =
+    std::find(neighbourList.begin(), neighbourList.end(), hashId);
+  return (it != neighbourList.end());
 }
 
-
-// ===============================================================
-std::vector<IdentifierHash> egammaOQFlagsBuilder::findNeighbours(const Identifier cellCentrId) const{
+std::vector<IdentifierHash>
+egammaOQFlagsBuilder::findNeighbours(const Identifier cellCentrId) const
+{
   std::vector<IdentifierHash> neighbourList;
   const IdentifierHash hashId = m_calocellId->calo_cell_hash(cellCentrId);
-  m_emHelper->get_neighbours(hashId, LArNeighbours::all2D, neighbourList); 
-  return  neighbourList;
+  m_emHelper->get_neighbours(hashId, LArNeighbours::all2D, neighbourList);
+  return neighbourList;
 }
 
-// =====================================================================
-StatusCode egammaOQFlagsBuilder::execute(const EventContext& ctx, xAOD::Egamma* eg) const
-{ 
+StatusCode
+egammaOQFlagsBuilder::execute(const EventContext& ctx,
+                              const CaloDetDescrManager& cmgr,
+                              xAOD::Egamma& eg) const
+{
   // Protection against bad pointers
-  if (eg==nullptr) return StatusCode::SUCCESS;
-  const xAOD::CaloCluster* cluster = eg->caloCluster(); 
-  if (!cluster) return StatusCode::SUCCESS; 
-  if (cluster->size()==0) return StatusCode::SUCCESS; 
-
+  const xAOD::CaloCluster* cluster = eg.caloCluster();
+  if (!cluster) {
+    return StatusCode::SUCCESS;
+  }
+  if (cluster->size() == 0) {
+    return StatusCode::SUCCESS;
+  }
   //
   const float clusterEta = cluster->eta();
   const float clusterPhi = cluster->phi();
   //
-  //In case we have the sizes set during the cluster construction.
-  int etaSize=cluster->getClusterEtaSize();
-  int phiSize=cluster->getClusterPhiSize();
-  //If no proper size could be found automatically, deduce by hand
-  //for the known std cases
-  if (etaSize==0 && phiSize==0) {
-    bool isBarrel = xAOD::EgammaHelpers::isBarrel(cluster);  
-    if (xAOD::EgammaHelpers::isElectron(eg)){
-      etaSize= (isBarrel ? 3 : 5);
-      phiSize= (isBarrel ? 7 : 5);
-    }
-    else if (xAOD::EgammaHelpers::isConvertedPhoton(eg)){
-      etaSize= (isBarrel ? 3 : 5);
-      phiSize= (isBarrel ? 7 : 5);
-    }
-    else{//unconverted photons
-      etaSize= (isBarrel ? 3 : 5);
-      phiSize= (isBarrel ? 7 : 5);
+  // In case we have the sizes set during the cluster construction.
+  int etaSize = cluster->getClusterEtaSize();
+  int phiSize = cluster->getClusterPhiSize();
+  // If no proper size could be found automatically, deduce by hand
+  // for the known std cases
+  if (etaSize == 0 && phiSize == 0) {
+    bool isBarrel = xAOD::EgammaHelpers::isBarrel(cluster);
+    if (xAOD::EgammaHelpers::isElectron(&eg)) {
+      etaSize = (isBarrel ? 3 : 5);
+      phiSize = (isBarrel ? 7 : 5);
+    } else if (xAOD::EgammaHelpers::isConvertedPhoton(&eg)) {
+      etaSize = (isBarrel ? 3 : 5);
+      phiSize = (isBarrel ? 7 : 5);
+    } else { // unconverted photons
+      etaSize = (isBarrel ? 3 : 5);
+      phiSize = (isBarrel ? 7 : 5);
     }
   }
-  
+
   unsigned int iflag = 0;
-  
-  //Find the central cell in the middle layer 
+
+  // Find the central cell in the middle layer
   Identifier cellCentrId;
-  bool foundCentralCell = egammaOQFlagsBuilder::findCentralCell(cluster,cellCentrId);
-  
-  //=================== Set timing bit ===================================================//
-  const double absEnergyGeV = fabs(cluster->e()*(1./GeV));
-  if(absEnergyGeV != 0 &&  fabs(cluster->time()) > m_TCut + m_TCutVsE/absEnergyGeV) {
-    iflag |= ( 0x1 << xAOD::EgammaParameters::OutTime);
+  bool foundCentralCell =
+    egammaOQFlagsBuilder::findCentralCell(cluster, cellCentrId);
+
+  // Set timing bit
+  const double absEnergyGeV = fabs(cluster->e() * (1. / GeV));
+  if (absEnergyGeV != 0 &&
+      fabs(cluster->time()) > m_TCut + m_TCutVsE / absEnergyGeV) {
+    iflag |= (0x1 << xAOD::EgammaParameters::OutTime);
   }
-  //======================================================================================//
 
-  //Declare totE and badE for LarQ cleaning
-  double totE=0;
-  double badE=0;
-  double energyCellMax=0;
+  // Declare totE and badE for LarQ cleaning
+  double totE = 0;
+  double badE = 0;
+  double energyCellMax = 0;
 
   if (foundCentralCell) {
-    //Find the list of neighbours cells, to define the 3x3 cluster core
+    // Find the list of neighbours cells, to define the 3x3 cluster core
     std::vector<IdentifierHash> neighbourList = findNeighbours(cellCentrId);
 
-    //Get Bad-channel info for this event
-    SG::ReadCondHandle<LArBadChannelCont> larBadChanHdl{m_bcContKey,ctx};
-    const LArBadChannelCont* larBadChanCont=*larBadChanHdl;
-    
-    //Loop over all the Lar cluster cells
-    xAOD::CaloCluster::const_cell_iterator cellIter    = cluster->cell_begin();
+    // Get Bad-channel info for this event
+    SG::ReadCondHandle<LArBadChannelCont> larBadChanHdl{ m_bcContKey, ctx };
+    const LArBadChannelCont* larBadChanCont = *larBadChanHdl;
+
+    // Loop over all the Lar cluster cells
+    xAOD::CaloCluster::const_cell_iterator cellIter = cluster->cell_begin();
     xAOD::CaloCluster::const_cell_iterator cellIterEnd = cluster->cell_end();
-    for( ;cellIter!=cellIterEnd;cellIter++) {
+    for (; cellIter != cellIterEnd; cellIter++) {
       const CaloCell* cell = (*cellIter);
-      if(!cell) {
-	continue;
+      if (!cell) {
+        continue;
       }
-      //Check we are not tile
+      // Check we are not tile
       if (cell->caloDDE()->is_tile()) {
-	continue;
+        continue;
       }
-      //Find cell parameters and properties
+      // Find cell parameters and properties
       float eta = cell->eta();
       // float phi = cell->phi(); // no longer used
       float qual = cell->quality();
-      CaloSampling::CaloSample layer = cell->caloDDE()->getSampling()  ;
-
-      //Calculate badE et totE    
-      if( (cell->provenance()  & 0x2000) &&!(cell->provenance()  & 0x0800 )) {
-	totE += cell->e();
-	if(cell->e() > energyCellMax ) energyCellMax = cell->e();
-	if(cell->quality() > m_QCellCut ) badE += cell->e(); 
-      }       
-      bool isACoreCell =  false;
-      isACoreCell = isCore(cell->ID(),neighbourList);
-      
+      CaloSampling::CaloSample layer = cell->caloDDE()->getSampling();
+
+      // Calculate badE et totE
+      if ((cell->provenance() & 0x2000) && !(cell->provenance() & 0x0800)) {
+        totE += cell->e();
+        if (cell->e() > energyCellMax)
+          energyCellMax = cell->e();
+        if (cell->quality() > m_QCellCut)
+          badE += cell->e();
+      }
+      bool isACoreCell = false;
+      isACoreCell = isCore(cell->ID(), neighbourList);
+
       bool isStripCoreCell = false;
-      if ( (layer==CaloSampling::EMB1 || layer==CaloSampling::EME1) && fabs(eta-clusterEta)<0.025/2.) {
-	isStripCoreCell = true;
+      if ((layer == CaloSampling::EMB1 || layer == CaloSampling::EME1) &&
+          fabs(eta - clusterEta) < 0.025 / 2.) {
+        isStripCoreCell = true;
       }
-      
-      //=======================   Set HEC bit ============================================//
-      if (layer>=CaloSampling::HEC0 && layer<=CaloSampling::HEC3 && qual>m_QCellHECCut) {
-	iflag |= ( 0x1 << xAOD::EgammaParameters::HECHighQ);
+
+      // Set HEC bit
+      if (layer >= CaloSampling::HEC0 && layer <= CaloSampling::HEC3 &&
+          qual > m_QCellHECCut) {
+        iflag |= (0x1 << xAOD::EgammaParameters::HECHighQ);
       }
-      //==================================================================================//
 
-      //======================== Set LAr bits ============================================================//
-      //
-      const LArBadChannel bc = larBadChanCont-> offlineStatus(cell->ID());
+      // Set LAr bits
+      const LArBadChannel bc = larBadChanCont->offlineStatus(cell->ID());
       //
-      if(isACoreCell) {
-	if((cell->provenance() & 0x0A00) == 0x0A00) { 
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::MissingFEBCellCore);
-	}
-	if((cell->provenance() & 0x0A00) == 0x0800) {
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::MaskedCellCore); 
-	}
-	if(bc.sporadicBurstNoise() && qual<m_QCellSporCut) {
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::SporadicNoiseLowQCore);
-	}
-	if(bc.deadCalib() || bc.lowNoiseHG() || bc.lowNoiseMG() ||
-	   bc.lowNoiseLG() || bc.distorted() || bc.unstable() || 
-	   bc.unstableNoiseHG() || bc.unstableNoiseMG() || 
-	   bc.unstableNoiseLG() || bc.peculiarCalibrationLine() 
-	   || bc.almostDead() ||  bc.shortProblem()) { 
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::AffectedCellCore);
-	}
-	if (qual>=4000) {
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::HighQCore);
-	}
-      }else{
-	if((cell->provenance() & 0x0A00) == 0x0A00) { 
-	  if( layer==CaloSampling::PreSamplerB || layer==CaloSampling::PreSamplerE) {
-	    iflag |= ( 0x1 << xAOD::EgammaParameters::MissingFEBCellEdgePS);
-	  }
-	  if( layer==CaloSampling::EMB1 || layer==CaloSampling::EME1) {
-	    iflag |= ( 0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS1);
-	    if (isStripCoreCell)  iflag |= ( 0x1 << xAOD::EgammaParameters::BadS1Core);
-	  }
-	  if( layer==CaloSampling::EMB2 || layer==CaloSampling::EME2) iflag |= ( 0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS2);
-	  if( layer==CaloSampling::EMB3 || layer==CaloSampling::EME3) iflag |= ( 0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS3); 
-	}
-	if((cell->provenance() & 0x0A00)  == 0x0800) {
-	  if( layer==CaloSampling::PreSamplerB || layer==CaloSampling::PreSamplerE){
-	    iflag |= ( 0x1 << xAOD::EgammaParameters::MaskedCellEdgePS);
-	  }
-	  if( layer==CaloSampling::EMB1 || layer==CaloSampling::EME1) {
-	    iflag |= ( 0x1 << xAOD::EgammaParameters::MaskedCellEdgeS1);
-	    if (isStripCoreCell)  iflag |= ( 0x1 << xAOD::EgammaParameters::BadS1Core);
-	  }
-	  if( layer==CaloSampling::EMB2 || layer==CaloSampling::EME2) iflag |= ( 0x1 << xAOD::EgammaParameters::MaskedCellEdgeS2);
-	  if( layer==CaloSampling::EMB3 || layer==CaloSampling::EME3) iflag |= ( 0x1 << xAOD::EgammaParameters::MaskedCellEdgeS3); 
-	}
-	if(bc.sporadicBurstNoise() && qual<m_QCellSporCut) {
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::SporadicNoiseLowQEdge);
-	}
-	if(bc.deadCalib() || bc.lowNoiseHG() || bc.lowNoiseMG() ||
-	   bc.lowNoiseLG() || bc.distorted() || bc.unstable() ||
-	   bc.unstableNoiseHG() || bc.unstableNoiseMG() || 
-	   bc.unstableNoiseLG() || bc.peculiarCalibrationLine() 
-	   || bc.almostDead() ||  bc.shortProblem()) { 
-	  if( layer==CaloSampling::PreSamplerB || layer==CaloSampling::PreSamplerE) {
-	    iflag |= ( 0x1 << xAOD::EgammaParameters::AffectedCellEdgePS);
-	  }
-	  if( layer==CaloSampling::EMB1 || layer==CaloSampling::EME1) iflag |= ( 0x1 << xAOD::EgammaParameters::AffectedCellEdgeS1);
-	  if( layer==CaloSampling::EMB2 || layer==CaloSampling::EME2) iflag |= ( 0x1 << xAOD::EgammaParameters::AffectedCellEdgeS2);
-	  if( layer==CaloSampling::EMB3 || layer==CaloSampling::EME3) iflag |= ( 0x1 << xAOD::EgammaParameters::AffectedCellEdgeS3);
-	}
-	if (qual>=4000) {
-	  iflag |= ( 0x1 << xAOD::EgammaParameters::HighQEdge);
-	}
+      if (isACoreCell) {
+        if ((cell->provenance() & 0x0A00) == 0x0A00) {
+          iflag |= (0x1 << xAOD::EgammaParameters::MissingFEBCellCore);
+        }
+        if ((cell->provenance() & 0x0A00) == 0x0800) {
+          iflag |= (0x1 << xAOD::EgammaParameters::MaskedCellCore);
+        }
+        if (bc.sporadicBurstNoise() && qual < m_QCellSporCut) {
+          iflag |= (0x1 << xAOD::EgammaParameters::SporadicNoiseLowQCore);
+        }
+        if (bc.deadCalib() || bc.lowNoiseHG() || bc.lowNoiseMG() ||
+            bc.lowNoiseLG() || bc.distorted() || bc.unstable() ||
+            bc.unstableNoiseHG() || bc.unstableNoiseMG() ||
+            bc.unstableNoiseLG() || bc.peculiarCalibrationLine() ||
+            bc.almostDead() || bc.shortProblem()) {
+          iflag |= (0x1 << xAOD::EgammaParameters::AffectedCellCore);
+        }
+        if (qual >= 4000) {
+          iflag |= (0x1 << xAOD::EgammaParameters::HighQCore);
+        }
+      } else {
+        if ((cell->provenance() & 0x0A00) == 0x0A00) {
+          if (layer == CaloSampling::PreSamplerB ||
+              layer == CaloSampling::PreSamplerE) {
+            iflag |= (0x1 << xAOD::EgammaParameters::MissingFEBCellEdgePS);
+          }
+          if (layer == CaloSampling::EMB1 || layer == CaloSampling::EME1) {
+            iflag |= (0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS1);
+            if (isStripCoreCell)
+              iflag |= (0x1 << xAOD::EgammaParameters::BadS1Core);
+          }
+          if (layer == CaloSampling::EMB2 || layer == CaloSampling::EME2)
+            iflag |= (0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS2);
+          if (layer == CaloSampling::EMB3 || layer == CaloSampling::EME3)
+            iflag |= (0x1 << xAOD::EgammaParameters::MissingFEBCellEdgeS3);
+        }
+        if ((cell->provenance() & 0x0A00) == 0x0800) {
+          if (layer == CaloSampling::PreSamplerB ||
+              layer == CaloSampling::PreSamplerE) {
+            iflag |= (0x1 << xAOD::EgammaParameters::MaskedCellEdgePS);
+          }
+          if (layer == CaloSampling::EMB1 || layer == CaloSampling::EME1) {
+            iflag |= (0x1 << xAOD::EgammaParameters::MaskedCellEdgeS1);
+            if (isStripCoreCell)
+              iflag |= (0x1 << xAOD::EgammaParameters::BadS1Core);
+          }
+          if (layer == CaloSampling::EMB2 || layer == CaloSampling::EME2)
+            iflag |= (0x1 << xAOD::EgammaParameters::MaskedCellEdgeS2);
+          if (layer == CaloSampling::EMB3 || layer == CaloSampling::EME3)
+            iflag |= (0x1 << xAOD::EgammaParameters::MaskedCellEdgeS3);
+        }
+        if (bc.sporadicBurstNoise() && qual < m_QCellSporCut) {
+          iflag |= (0x1 << xAOD::EgammaParameters::SporadicNoiseLowQEdge);
+        }
+        if (bc.deadCalib() || bc.lowNoiseHG() || bc.lowNoiseMG() ||
+            bc.lowNoiseLG() || bc.distorted() || bc.unstable() ||
+            bc.unstableNoiseHG() || bc.unstableNoiseMG() ||
+            bc.unstableNoiseLG() || bc.peculiarCalibrationLine() ||
+            bc.almostDead() || bc.shortProblem()) {
+          if (layer == CaloSampling::PreSamplerB ||
+              layer == CaloSampling::PreSamplerE) {
+            iflag |= (0x1 << xAOD::EgammaParameters::AffectedCellEdgePS);
+          }
+          if (layer == CaloSampling::EMB1 || layer == CaloSampling::EME1)
+            iflag |= (0x1 << xAOD::EgammaParameters::AffectedCellEdgeS1);
+          if (layer == CaloSampling::EMB2 || layer == CaloSampling::EME2)
+            iflag |= (0x1 << xAOD::EgammaParameters::AffectedCellEdgeS2);
+          if (layer == CaloSampling::EMB3 || layer == CaloSampling::EME3)
+            iflag |= (0x1 << xAOD::EgammaParameters::AffectedCellEdgeS3);
+        }
+        if (qual >= 4000) {
+          iflag |= (0x1 << xAOD::EgammaParameters::HighQEdge);
+        }
       }
-    }// end loop over LAr cells
-    //====================================================================================================================//
-    //==== Set LArQCleaning bit ===============//
-    double egammaLArQCleaning=0;
-    if(totE !=0) egammaLArQCleaning=badE/totE;
-    if(egammaLArQCleaning>m_LArQCut){
+    } // end loop over LAr cells
+    
+    //Set LArQCleaning bit
+    double egammaLArQCleaning = 0;
+    if (totE != 0)
+      egammaLArQCleaning = badE / totE;
+    if (egammaLArQCleaning > m_LArQCut) {
       iflag |= (0x1 << xAOD::EgammaParameters::LArQCleaning);
     }
-    //=========================================//
-    //==== Set HighRcell bit ===============//
-    double ratioCell=0;
-    if(totE !=0) ratioCell=energyCellMax/totE;
-    if(ratioCell>m_RcellCut){
+    //Set HighRcell bit//
+    double ratioCell = 0;
+    if (totE != 0)
+      ratioCell = energyCellMax / totE;
+    if (ratioCell > m_RcellCut) {
       iflag |= (0x1 << xAOD::EgammaParameters::HighRcell);
     }
-    //=========================================//
-  } //close if found central cell
-  
-  //========================= Check the HV components ===================================================//
-  float deta=0;
-  float dphi=0;
-  CaloSampling::CaloSample layer;
+  } // close if found central cell
+
+  //Check the HV components
+  float deta = 0;
+  float dphi = 0;
+
+  // Get affected info for this event
+  SG::ReadCondHandle<CaloAffectedRegionInfoVec> affHdl{ m_affKey, ctx };
+  const CaloAffectedRegionInfoVec* affCont = *affHdl;
+  if (!affCont) {
+    ATH_MSG_WARNING("Do not have affected regions info, is this expected ?");
+  }
 
   //--------------> PRE SAMPLER
-  deta=0.5*0.025*etaSize;
-  dphi=0.5*0.025*phiSize;
-  layer=CaloSampling::PreSamplerE;
-
-  //Get affected info for this event
-  SG::ReadCondHandle<CaloAffectedRegionInfoVec> affHdl{m_affKey,ctx};
-  const CaloAffectedRegionInfoVec* affCont=*affHdl;
-  if(!affCont) {
-     ATH_MSG_WARNING("Do not have affected regions info, is this expected ?");
+  deta = 0.5 * 0.025 * etaSize;
+  dphi = 0.5 * 0.025 * phiSize;
+
+  bool isNonNominalHVPS = (m_affectedTool->isAffected(cluster,
+                                                      affCont,
+                                                      deta,
+                                                      dphi,
+                                                      CaloSampling::PreSamplerE,
+                                                      CaloSampling::PreSamplerE,
+                                                      1) ||
+                           m_affectedTool->isAffected(cluster,
+                                                      affCont,
+                                                      deta,
+                                                      dphi,
+                                                      CaloSampling::PreSamplerB,
+                                                      CaloSampling::PreSamplerB,
+                                                      1));
+  if (isNonNominalHVPS){
+    iflag |= (0x1 << xAOD::EgammaParameters::NonNominalHVPS);
   }
-    
-  bool checkNNHV_PSE   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_PSE = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::PreSamplerB;
 
-  bool checkNNHV_PSB   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_PSB = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  if(checkNNHV_PSE || checkNNHV_PSB)      iflag |= ( 0x1 << xAOD::EgammaParameters::NonNominalHVPS); 
-  if(checkDEADHV_PSE || checkDEADHV_PSB)  iflag |= ( 0x1 << xAOD::EgammaParameters::DeadHVPS);
+  bool isDeadHVPS = (m_affectedTool->isAffected(cluster,
+                                                affCont,
+                                                deta,
+                                                dphi,
+                                                CaloSampling::PreSamplerE,
+                                                CaloSampling::PreSamplerE,
+                                                2) ||
+                     m_affectedTool->isAffected(cluster,
+                                                affCont,
+                                                deta,
+                                                dphi,
+                                                CaloSampling::PreSamplerB,
+                                                CaloSampling::PreSamplerB,
+                                                2));
+  if (isDeadHVPS){
+    iflag |= (0x1 << xAOD::EgammaParameters::DeadHVPS);
+  }
 
   //---------------> SAMPLING 2 : CLUSTER CORE
-  layer=CaloSampling::EMB2;
-  //   deta=0.;
-  //   dphi=0.;
-  deta=0.5*0.025*3.;
-  dphi=0.5*0.025*3.;
-  bool checkDEADHV_CORE_B = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EME2;
-  bool checkDEADHV_CORE_E = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  if(checkDEADHV_CORE_B || checkDEADHV_CORE_E)  iflag |= ( 0x1 << xAOD::EgammaParameters::DeadHVS1S2S3Core); 
-
+  deta = 0.5 * 0.025 * 3.;
+  dphi = 0.5 * 0.025 * 3.;
+  bool isDeadHVS2Core = (m_affectedTool->isAffected(cluster,
+                                                    affCont,
+                                                    deta,
+                                                    dphi,
+                                                    CaloSampling::EMB2,
+                                                    CaloSampling::EMB2,
+                                                    2) ||
+                         m_affectedTool->isAffected(cluster,
+                                                    affCont,
+                                                    deta,
+                                                    dphi,
+                                                    CaloSampling::EME2,
+                                                    CaloSampling::EME2,
+                                                    2));
+
+  if (isDeadHVS2Core) {
+    iflag |= (0x1 << xAOD::EgammaParameters::DeadHVS1S2S3Core);
+  }
   //----------------> SAMPLINGS 1,2,3 : CLUSTER EDGE
-  deta=0.5*0.025*etaSize;
-  dphi=0.5*0.025*phiSize;
-  layer=CaloSampling::EMB1;
-
-  bool checkNNHV_EMB1   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EMB1 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EMB2;
-
-  bool checkNNHV_EMB2   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EMB2 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EMB3;
-
-  bool checkNNHV_EMB3   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EMB3 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EME1;
-
-  bool checkNNHV_EME1   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EME1 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EME2;
-
-  bool checkNNHV_EME2   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EME2 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  layer=CaloSampling::EME3;
-
-  bool checkNNHV_EME3   = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,1) ; //nnHVPS
-  bool checkDEADHV_EME3 = m_affectedTool->isAffected(cluster, affCont, deta , dphi ,layer,layer,2) ; //deadHVPS
-  if(checkNNHV_EMB1 || checkNNHV_EME1 || checkNNHV_EMB2 || checkNNHV_EME2 ||checkNNHV_EMB3 || checkNNHV_EME3) 
-    iflag |= ( 0x1 << xAOD::EgammaParameters::NonNominalHVS1S2S3); 
-  if(checkDEADHV_EMB1 || checkDEADHV_EME1 || checkDEADHV_EMB2 || checkDEADHV_EME2 ||checkDEADHV_EMB3 || checkDEADHV_EME3)  
-    iflag |= ( 0x1 << xAOD::EgammaParameters::DeadHVS1S2S3Edge);
-  //========================================================================================================================//
-
-  //====================  Check the tile component  ==================================//
-  //Get CaloCellContainer
+  deta = 0.5 * 0.025 * etaSize;
+  dphi = 0.5 * 0.025 * phiSize;
+
+  bool isNonNominalHVS1S2S3 = (m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EMB1,
+                                                          CaloSampling::EMB1,
+                                                          1) ||
+                               m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EMB2,
+                                                          CaloSampling::EMB2,
+                                                          1) ||
+                               m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EMB3,
+                                                          CaloSampling::EMB3,
+                                                          1) ||
+                               m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EME1,
+                                                          CaloSampling::EME1,
+                                                          1) ||
+                               m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EME2,
+                                                          CaloSampling::EME2,
+                                                          1) ||
+                               m_affectedTool->isAffected(cluster,
+                                                          affCont,
+                                                          deta,
+                                                          dphi,
+                                                          CaloSampling::EME3,
+                                                          CaloSampling::EME3,
+                                                          1));
+  if (isNonNominalHVS1S2S3) {
+    iflag |= (0x1 << xAOD::EgammaParameters::NonNominalHVS1S2S3);
+  }
+
+  bool isDeadHVS1S2S3Edge = (m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EMB1,
+                                                        CaloSampling::EMB1,
+                                                        2) ||
+                             m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EMB2,
+                                                        CaloSampling::EMB2,
+                                                        2) ||
+                             m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EMB3,
+                                                        CaloSampling::EMB3,
+                                                        2) ||
+                             m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EME1,
+                                                        CaloSampling::EME1,
+                                                        2) ||
+                             m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EME2,
+                                                        CaloSampling::EME2,
+                                                        2) ||
+                             m_affectedTool->isAffected(cluster,
+                                                        affCont,
+                                                        deta,
+                                                        dphi,
+                                                        CaloSampling::EME3,
+                                                        CaloSampling::EME3,
+                                                        2));
+
+  if (isDeadHVS1S2S3Edge) {
+    iflag |= (0x1 << xAOD::EgammaParameters::DeadHVS1S2S3Edge);
+  }
+
+  // Check the tile component
+  // Get CaloCellContainer
   SG::ReadHandle<CaloCellContainer> cellcoll(m_cellsKey, ctx);
   // check is only used for serial running; remove when MT scheduler used
-  if(!cellcoll.isValid()) {
-    ATH_MSG_ERROR("Failed to retrieve cell container: "<< m_cellsKey.key());
+  if (!cellcoll.isValid()) {
+    ATH_MSG_ERROR("Failed to retrieve cell container: " << m_cellsKey.key());
     return StatusCode::FAILURE;
   }
-  CaloCell_ID::SUBCALO HADCal = static_cast<CaloCell_ID::SUBCALO>(CaloCell_ID::TILE);
-  CaloCellList ccl(cellcoll.cptr(),HADCal);
+  CaloCell_ID::SUBCALO HADCal =
+    static_cast<CaloCell_ID::SUBCALO>(CaloCell_ID::TILE);
+  CaloCellList ccl(cellcoll.cptr(), HADCal);
   double size = 0.12;
-  //------------------------ TileBar0 --------------------------------//
-  bool isbadtilebar0cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileBar0);
-  //------------------------ TileExt0 --------------------------------//
-  bool isbadtileext0cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileExt0);
-  //----------------------------------------------------------------//
-
-  if( isbadtilebar0cell || isbadtileext0cell ){
-    iflag |= (0x1 << xAOD::EgammaParameters::DeadCellTileS0);    
+  // TileBar0  or TileExt0
+  bool isDeadCellTileS0 =
+    (isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileBar0) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileExt0));
+
+  if (isDeadCellTileS0) {
+    iflag |= (0x1 << xAOD::EgammaParameters::DeadCellTileS0);
   }
-  //---------------------- TileBar1 ----------------------------------//
-  bool isbadtilebar1cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileBar1);
-    //---------------------- TileExt1 ----------------------------------//
-  bool isbadtileext1cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileExt1);
-    //---------------------- TileGap1 ----------------------------------//
-  bool isbadtilegap1cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileGap1);
-  //---------------------- TileBar2 ----------------------------------//
-  bool isbadtilebar2cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileBar2);
-    //---------------------- TileExt2 ---------------------------------//
-  bool isbadtileext2cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileExt2);
-    //---------------------- TileGap2 ----------------------------------//
-  bool isbadtilegap2cell=isbadtilecell(ccl,clusterEta,clusterPhi,size,size,CaloSampling::TileGap2);
-  //---------------------------------------------------------------//
-  if( isbadtilebar1cell || isbadtilebar2cell ||
-      isbadtileext1cell || isbadtileext2cell ||
-      isbadtilegap1cell || isbadtilegap2cell ){
-    iflag |= (0x1 << xAOD::EgammaParameters::DeadCellTileS1S2);    
+  // TileBar1 TileExt1 TileGap1 TileBar2 TileExt2 TileGap2
+  bool isDeadCellTileS1S2 =
+    (isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileBar1) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileExt1) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileGap1) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileBar2) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileExt2) ||
+     isbadtilecell(
+       ccl, cmgr, clusterEta, clusterPhi, size, size, CaloSampling::TileGap2));
+  if (isDeadCellTileS1S2) {
+    iflag |= (0x1 << xAOD::EgammaParameters::DeadCellTileS1S2);
   }
 
-  //=================================================================================//
-  eg->setOQ(iflag);
+  eg.setOQ(iflag);
   ATH_MSG_DEBUG("Executing egammaOQFlagsBuilder::execute");
   return StatusCode::SUCCESS;
 }
 
-bool egammaOQFlagsBuilder::isbadtilecell ( CaloCellList& ccl, const float clusterEta, 
-					   const float clusterPhi, 
-					   const double sizeEta, const double sizePhi ,
-					   const CaloSampling::CaloSample sample) const {
-
-  bool isbadtilecell = false;
-  ccl.select(clusterEta,clusterPhi,sizeEta,sizePhi,sample);
-  CaloCellList::list_iterator cclIter     = ccl.begin();
-  CaloCellList::list_iterator cclIterEnd  = ccl.end();
-  for( ;cclIter!=cclIterEnd;cclIter++) {
-    const CaloCell* cell = (*cclIter);
-    if(cell->badcell()){//check of bad tile cell
-      isbadtilecell = true;
-      break;
-      }
-  }
-  return isbadtilecell;
-}
diff --git a/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.h b/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.h
index 0bed898ff832..201c9b8b5938 100644
--- a/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.h
+++ b/Reconstruction/egamma/egammaTools/src/egammaOQFlagsBuilder.h
@@ -6,15 +6,22 @@
 #define EGAMMATOOLS_EGAMMAOQFLAGSBUILDER_H
 /**
   @class egammaOQFlagsBuilder
-  egamma Object Quality flags data object builder : 
-    - This tool checks if any cell of the cluster associated to the egamma object is affected by a detector problem: non nominal or dead high voltage, readout problems, missing FEBs, high quality factor, timing, etc.... If this is the case, then a bit corresponding to a specific problem is filled ( see egammaEvent/egammaEvent/egammaPIDdefs.h for bits definition).
-Most of the informations are given separately for each layer of the EM calorimeter. They are also separately stored for the core (3x3 central cells in the middle layer of the EM calorimeter) and the edge (all the other cells) of the cluster.
+  egamma Object Quality flags data object builder :
+    - This tool checks if any cell of the cluster associated to the egamma
+object is affected by a detector problem: non nominal or dead high voltage,
+readout problems, missing FEBs, high quality factor, timing, etc.... If this is
+the case, then a bit corresponding to a specific problem is filled ( see
+egammaEvent/egammaEvent/egammaPIDdefs.h for bits definition). Most of the
+informations are given separately for each layer of the EM calorimeter. They are
+also separately stored for the core (3x3 central cells in the middle layer of
+the EM calorimeter) and the edge (all the other cells) of the cluster.
   @author Frederic Derue derue@lpnhe.in2p3.fr
   @author Francesco Polci polci@lpsc.in2p3.fr
   @author Quentin Buat quentin.buat@lpsc.in2p3.fr
 */
 
 // INCLUDE HEADER FILES: 
+#include "egammaInterfaces/IegammaOQFlagsBuilder.h"
 #include "egammaBaseTool.h"
 #include "GaudiKernel/ToolHandle.h"
 #include "GaudiKernel/EventContext.h"
@@ -37,65 +44,77 @@ class HWIdentifier;
 class LArEM_ID;
 class CaloCell_ID;
 
-class egammaOQFlagsBuilder : public egammaBaseTool
+class egammaOQFlagsBuilder
+  : public AthAlgTool
+  , virtual public IegammaOQFlagsBuilder
 {
  public:
 
   /** @brief Default constructor*/
-  egammaOQFlagsBuilder(const std::string& type,
-		       const std::string& name,
-		       const IInterface* parent);
-   
-  /** @brief Destructor*/
-  ~egammaOQFlagsBuilder();
-  /** @brief initialize method*/
-  StatusCode initialize();
-  /** @brief standard execute method */
-  virtual StatusCode execute(const EventContext& ctx, xAOD::Egamma*) const;
-  /** @brief finalize method*/
-  StatusCode finalize();
+   egammaOQFlagsBuilder(const std::string& type,
+                        const std::string& name,
+                        const IInterface* parent);
+
+   /** @brief Destructor*/
+   ~egammaOQFlagsBuilder();
+   /** @brief initialize method*/
+   StatusCode initialize();
+   /** @brief standard execute method */
+   virtual StatusCode execute(const EventContext& ctx,
+                              const CaloDetDescrManager& cmgr,
+                              xAOD::Egamma& egamma) const;
+   /** @brief finalize method*/
+   StatusCode finalize();
 
  private:
-  /** Handle to bad-channel CDO */
-  SG::ReadCondHandleKey<LArBadChannelCont> m_bcContKey{this,
-      "LArBadChannelKey", "LArBadChannel", "Key of the LArBadChannelCont CDO"};
-  
-  SG::ReadCondHandleKey<CaloAffectedRegionInfoVec> m_affKey{this,
-      "LArAffectedRegionKey", "LArAffectedRegionInfo", "SG key for affected regions cond object"};
-
-  ToolHandle<ICaloAffectedTool> m_affectedTool {this,
-      "affectedTool", "CaloAffectedTool", "CaloAffectedTool"};
-
-  const LArEM_ID* m_emHelper;
-  const CaloCell_ID* m_calocellId;
-
-  SG::ReadHandleKey<CaloCellContainer> m_cellsKey {this,
-      "CellsName", "AllCalo","Names of container which contain cells"};
-
-  // IToolSvc* m_toolSvc;
-  bool isCore(const Identifier Id, const std::vector<IdentifierHash>& neighbourList) const;
-  std::vector<IdentifierHash> findNeighbours( const Identifier cellCentrId) const; 
-  bool isbadtilecell (CaloCellList& ccl, float clusterEta, float clusterPhi, 
-		      double sizeEta, double sizePhi, CaloSampling::CaloSample sample) const ;   
-
-  bool findCentralCell(const xAOD::CaloCluster* cluster, Identifier& cellCentrId) const;
-
-  Gaudi::Property<double> m_QCellCut {this, "QCellCut", 4000.};
-  Gaudi::Property<double> m_QCellHECCut {this, "QCellHECCut", 60000.};
-  Gaudi::Property<double> m_QCellSporCut {this, "QCellSporCut", 4000.};
-  Gaudi::Property<double> m_LArQCut {this, "LArQCut", 0.8};
-  Gaudi::Property<double> m_TCut {this, "TCut", 10.0};
-  Gaudi::Property<double> m_TCutVsE {this, "TCutVsE", 2.0};
-  Gaudi::Property<double> m_RcellCut {this, "RcellCut", 0.8};
+   /** Handle to bad-channel CDO */
+   SG::ReadCondHandleKey<LArBadChannelCont> m_bcContKey{
+     this,
+     "LArBadChannelKey",
+     "LArBadChannel",
+     "Key of the LArBadChannelCont CDO"
+   };
+
+   SG::ReadCondHandleKey<CaloAffectedRegionInfoVec> m_affKey{
+     this,
+     "LArAffectedRegionKey",
+     "LArAffectedRegionInfo",
+     "SG key for affected regions cond object"
+   };
+
+   ToolHandle<ICaloAffectedTool> m_affectedTool{ this,
+                                                 "affectedTool",
+                                                 "CaloAffectedTool",
+                                                 "CaloAffectedTool" };
+
+   const LArEM_ID* m_emHelper;
+   const CaloCell_ID* m_calocellId;
+
+   SG::ReadHandleKey<CaloCellContainer> m_cellsKey{
+     this,
+     "CellsName",
+     "AllCalo",
+     "Names of container which contain cells"
+   };
+
+   // IToolSvc* m_toolSvc;
+   bool isCore(const Identifier Id,
+               const std::vector<IdentifierHash>& neighbourList) const;
+
+   std::vector<IdentifierHash> findNeighbours(
+     const Identifier cellCentrId) const;
+   
+   bool findCentralCell(const xAOD::CaloCluster* cluster,
+                        Identifier& cellCentrId) const;
+
+   Gaudi::Property<double> m_QCellCut{ this, "QCellCut", 4000. };
+   Gaudi::Property<double> m_QCellHECCut{ this, "QCellHECCut", 60000. };
+   Gaudi::Property<double> m_QCellSporCut{ this, "QCellSporCut", 4000. };
+   Gaudi::Property<double> m_LArQCut{ this, "LArQCut", 0.8 };
+   Gaudi::Property<double> m_TCut{ this, "TCut", 10.0 };
+   Gaudi::Property<double> m_TCutVsE{ this, "TCutVsE", 2.0 };
+   Gaudi::Property<double> m_RcellCut{ this, "RcellCut", 0.8 };
 };
 
 #endif
 
-
-
-
-
-
-
-
-
-- 
GitLab