From e3e1f6da3963be98c23e23eb488c838362b48ec7 Mon Sep 17 00:00:00 2001
From: Christos Anastopoulos <christos.anastopoulos@cern.ch>
Date: Mon, 28 Aug 2017 23:02:31 +0200
Subject: [PATCH] Fix coverity warnings : CID 114007 , CID 113131,  CID
 114002:, CID 113068 , CID 114006,CID 19797,CID 115173,CID 115450,CID
 114671,CID 112968

Former-commit-id: f7ecf2700fd2b446da714f02670c06005b026f4e
---
 .../ElectronChargeEfficiencyCorrectionTool.h  |   2 +-
 ...ElectronChargeEfficiencyCorrectionTool.cxx |  54 +++----
 .../Root/AsgElectronChargeIDSelectorTool.cxx  |   6 +-
 .../Root/TElectronLikelihoodTool.cxx          |  23 +--
 .../MVAUtils/util/convertXmlToRootTree.cxx    |  13 +-
 .../egammaMVACalib/egammaMVACalib.h           |   2 -
 .../src/egammaTruthAssociationAlg.cxx         |   9 +-
 .../src/EMBremCollectionBuilder.cxx           | 135 ++++++++++--------
 .../egammaTools/src/FourMomCombiner.cxx       |   2 +-
 .../src/egammaSuperClusterBuilder.cxx         |  27 ++--
 .../src/CaloCluster_OnTrackBuilder.cxx        |   6 +-
 11 files changed, 143 insertions(+), 136 deletions(-)

diff --git a/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h b/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h
index edd860c578f..a2f6c5edd2a 100644
--- a/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h
+++ b/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h
@@ -152,7 +152,7 @@ namespace CP {
     CP::SystematicSet m_mySysConf;
     CP::SystematicSet m_affectingSys;
 
- /// Currently applied systematics
+    /// Currently applied systematics
    CP::SystematicSet* m_appliedSystematics;
  
     /// Decorator
diff --git a/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/Root/ElectronChargeEfficiencyCorrectionTool.cxx b/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/Root/ElectronChargeEfficiencyCorrectionTool.cxx
index ffe1d0f85a1..15e1f1164ac 100644
--- a/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/Root/ElectronChargeEfficiencyCorrectionTool.cxx
+++ b/PhysicsAnalysis/ElectronPhotonID/ElectronEfficiencyCorrection/Root/ElectronChargeEfficiencyCorrectionTool.cxx
@@ -10,7 +10,6 @@
    @date   September 2015
 */
 // Include this class's header
-// #include "ElectronChargeEfficiencyCorrectionTool/ElectronChargeEfficiencyCorrectionTool.h"
 #include "ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h"
 // xAOD includes
 #include "PathResolver/PathResolver.h"
@@ -51,6 +50,7 @@ CP::ElectronChargeEfficiencyCorrectionTool::ElectronChargeEfficiencyCorrectionTo
   m_filtered_sys_sets(),
   m_mySysConf(),
   m_affectingSys(),
+  m_appliedSystematics(0),
   m_sf_decoration_name("chargeIDEffiSF"),
   m_sfDec(0)
 {
@@ -129,14 +129,14 @@ StatusCode CP::ElectronChargeEfficiencyCorrectionTool::initialize()
   m_SF_SS.clear();
   m_SF_OS.clear();
   TList* keyListfolder = rootFile->GetListOfKeys();
-std::vector<std::string> names;
+  std::vector<std::string> names;
 
   for ( int j=0; j<keyListfolder->GetEntries(); j++ ){
-names.push_back(( keyListfolder->At(j)->GetName() ));
-}
-std::sort(names.begin(), names.end());
+    names.push_back(( keyListfolder->At(j)->GetName() ));
+  }
+  std::sort(names.begin(), names.end());
 
- for ( unsigned int j=0; j<names.size(); j++ ){
+  for ( unsigned int j=0; j<names.size(); j++ ){
 
     std::string name = names.at(j);
     ATH_MSG_DEBUG("Got ROOT object with name: " << name);
@@ -197,11 +197,11 @@ std::sort(names.begin(), names.end());
           std::string runlow = histid;
           runlow.erase(histid.find(Form("RunNumber") ),9);
           runlow.erase(runlow.find("_"),runlow.size() );
-//          m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runlow.c_str())) );
+	  //          m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runlow.c_str())) );
           std::string runhigh = histid;
           runhigh.erase(histid.find(Form("RunNumber") ),9);
           runhigh.erase(0,runhigh.find("_")+1);
-//          m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runhigh.c_str())) );
+	  //          m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runhigh.c_str())) );
         }
         ATH_MSG_VERBOSE("Using histid (OS hid): " << histid);
         m_SF_OS[histid].push_back( (TH2D*)rootFile->Get( names.at(j).c_str() ));
@@ -242,11 +242,11 @@ std::sort(names.begin(), names.end());
           std::string runlow = histid;
           runlow.erase(histid.find(Form("RunNumber") ),9);
           runlow.erase(runlow.find("_"),runlow.size() );
-  //        m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runlow.c_str())) );
+	  //        m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runlow.c_str())) );
           std::string runhigh = histid;
           runhigh.erase(histid.find(Form("RunNumber") ),9);
           runhigh.erase(0,runhigh.find("_")+1);
-    //      m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runhigh.c_str())) );
+	  //      m_RunNumbers.push_back( static_cast<unsigned int>(atoi(runhigh.c_str())) );
         }
         ATH_MSG_VERBOSE("Using histid (OS hid): " << histid);
         m_SF_OS[histid].push_back( (TH2D*)rootFile->Get( names.at(j).c_str() ));
@@ -269,7 +269,7 @@ std::sort(names.begin(), names.end());
   if ( m_SF_OS.size() <1 || m_SF_SS.size() <1 || m_SF_SS.size()!=m_SF_OS.size() ) {
     ATH_MSG_ERROR("OS/SS SF vectors not filled or of different size. -- Problem with files. -- Report to <hn-atlas-EGammaWG@cern.ch>");
     return CP::CorrectionCode::Error;
-}
+  }
 
 
   std::sort(m_RunNumbers.begin(),m_RunNumbers.end());
@@ -359,7 +359,7 @@ CP::ElectronChargeEfficiencyCorrectionTool::getEfficiencyScaleFactor(const xAOD:
   const double ele_pt  = ele.pt()*m_gevmev;
   const double ele_eta = std::abs( ele.caloCluster()->etaBE(2)   );
 
-   // getting the truth charge
+  // getting the truth charge
   int truth_ele_charge = 9999;
   CP::CorrectionCode charge_result = this->getEleTruthCharge( ele, truth_ele_charge); //// ## Giulia: second function to change
   if ( charge_result != CP::CorrectionCode::Ok ) {
@@ -402,9 +402,9 @@ CP::ElectronChargeEfficiencyCorrectionTool::getEfficiencyScaleFactor(const xAOD:
     }
     ATH_MSG_DEBUG("Number of RunNumbers: " << m_RunNumbers.size() );
     for ( std::size_t r=0; r<m_RunNumbers.size(); r++ ){
-ATH_MSG_DEBUG(  m_RunNumbers.at(r) );
-	}
-ATH_MSG_VERBOSE("DONE");
+      ATH_MSG_DEBUG(  m_RunNumbers.at(r) );
+    }
+    ATH_MSG_VERBOSE("DONE");
 
     for ( std::size_t r=0; r<m_RunNumbers.size()-1; r++ ){
       ATH_MSG_VERBOSE(m_RunNumbers.size()-1 << "  " << m_RunNumbers.at(r) << "  " << m_RunNumbers.at(r+1) << "  " << runnumber);
@@ -416,14 +416,14 @@ ATH_MSG_VERBOSE("DONE");
     }
 
     if (runnumber<m_RunNumbers.at(0) || (runnumber>m_RunNumbers.at(m_RunNumbers.size()-1) )) {
-    ATH_MSG_DEBUG("RunNumber not in valid RunNumber Range ");
-    sf = -9999.0;
-    return CP::CorrectionCode::OutOfValidityRange;
-      }
+      ATH_MSG_DEBUG("RunNumber not in valid RunNumber Range ");
+      sf = -9999.0;
+      return CP::CorrectionCode::OutOfValidityRange;
+    }
 
   }
 
-   // Determine WHICH histograms to use here
+  // Determine WHICH histograms to use here
   const std::vector<TH2D*>& SShistograms = m_SF_SS.at(cutRunNumber.c_str());
   const std::vector<TH2D*>& OShistograms = m_SF_OS.at(cutRunNumber.c_str());
 
@@ -449,14 +449,14 @@ ATH_MSG_VERBOSE("DONE");
     }
   }
 
-   ATH_MSG_DEBUG("eta: " << ele_eta << "  pt: "<< ele_pt );
-   ATH_MSG_DEBUG("SF Rates---- . SF: " << sf );
+  ATH_MSG_DEBUG("eta: " << ele_eta << "  pt: "<< ele_pt );
+  ATH_MSG_DEBUG("SF Rates---- . SF: " << sf );
 
 
   // Systematics ------------------------------------------------------------------------------------------------------
   double val_stat;
 
-   /// STAT
+  /// STAT
   if (isOS) {
     retVal = this->getChargeFlipRate( ele_eta, ele_pt,OShistograms.at(1), val_stat);
     if ( retVal != 0 ) {
@@ -475,7 +475,7 @@ ATH_MSG_VERBOSE("DONE");
 
   std::vector<float> systs;
   double val_sys{0.0};
-   /// STAT
+  /// STAT
   for (unsigned int s=2;s<OShistograms.size();s++){
     if (isOS) {
       retVal = this->getChargeFlipRate( ele_eta, ele_pt,OShistograms.at(s), val_sys);
@@ -495,7 +495,7 @@ ATH_MSG_VERBOSE("DONE");
     systs.push_back(static_cast<float>(val_sys));
   }
 
-    ATH_MSG_DEBUG(" ... nominal SF: "   << sf);
+  ATH_MSG_DEBUG(" ... nominal SF: "   << sf);
 
 
   if ( m_mySysConf.size()==0 ) {
@@ -622,7 +622,7 @@ CP::CorrectionCode CP::ElectronChargeEfficiencyCorrectionTool::getEleTruthCharge
 CP::CorrectionCode CP::ElectronChargeEfficiencyCorrectionTool::isGoodEle( const xAOD::Electron& ele, bool& goodele) const
 {
 
-   // good ele => (firstEgMotherPdgId) == 11 ## valid for both iso and conversion ele
+  // good ele => (firstEgMotherPdgId) == 11 ## valid for both iso and conversion ele
 
   goodele = false;
   int firstEgPdgId = -9999;
@@ -702,7 +702,7 @@ CP::SystematicSet CP::ElectronChargeEfficiencyCorrectionTool::affectingSystemati
     result.insert (SystematicVariation (Form("EL_CHARGEID_SYS%s",m_systematics.at(i).c_str()), 1));
     result.insert (SystematicVariation (Form("EL_CHARGEID_SYS%s",m_systematics.at(i).c_str()), -1));
   }
-   return result;
+  return result;
 }
 
 
diff --git a/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/AsgElectronChargeIDSelectorTool.cxx b/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/AsgElectronChargeIDSelectorTool.cxx
index dbeab65de7c..d78e948d37d 100644
--- a/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/AsgElectronChargeIDSelectorTool.cxx
+++ b/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/AsgElectronChargeIDSelectorTool.cxx
@@ -42,15 +42,15 @@
 // Standard constructor
 //=============================================================================
 AsgElectronChargeIDSelectorTool::AsgElectronChargeIDSelectorTool(std::string myname) :
-  AsgTool(myname) //,m_cutOnBDT(0)//,m_configFile("")//,m_rootTool(0)
+  AsgTool(myname) ,
+  m_cutPosition_bdt(0),
+  m_resultPosition_bdt(0)
 {
   // Declare the needed properties
   declareProperty("WorkingPoint",m_WorkingPoint="","The Working Point");
-  //declareProperty("ConfigFile",m_configFile="","The config file to use");
   declareProperty("usePVContainer", m_usePVCont=true, "Whether to use the PV container");
   declareProperty("nPVdefault", m_nPVdefault = 0, "The default number of PVs if not counted");
   declareProperty("primaryVertexContainer", m_primVtxContName="PrimaryVertices", "The primary vertex container name" );
-
   declareProperty("TrainingFile",  m_trainingFile="", "The input ROOT file name holding training" );
   declareProperty("CutOnBDT",m_cutOnBDT=0,"Cut on BDT discriminant");
   m_pid_name=myname.data();
diff --git a/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/TElectronLikelihoodTool.cxx b/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/TElectronLikelihoodTool.cxx
index 04eb9b4050f..b0d212978cf 100644
--- a/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/TElectronLikelihoodTool.cxx
+++ b/PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools/Root/TElectronLikelihoodTool.cxx
@@ -271,11 +271,11 @@ int Root::TElectronLikelihoodTool::LoadVarHistograms(std::string vstr,unsigned i
 	    continue;
 	  
 	  char pdfdir[500];
-	  sprintf(pdfdir,"%s/%s",vstr.c_str(),sig_bkg.c_str());
+	  snprintf(pdfdir,500,"%s/%s",vstr.c_str(),sig_bkg.c_str());
 	  char pdf[500];
-	  sprintf(pdf,"%s_%s_smoothed_hist_from_KDE_%s",vstr.c_str(),sig_bkg.c_str(),binname);
+	  snprintf(pdf,500,"%s_%s_smoothed_hist_from_KDE_%s",vstr.c_str(),sig_bkg.c_str(),binname);
 	  char pdf_newname[500];
-	  sprintf(pdf_newname,"%s_%s_%s_LHtool_copy_%s",Root::TSelectorToolBase::getName(),vstr.c_str(),sig_bkg.c_str(),binname);
+	  snprintf(pdf_newname,500,"%s_%s_%s_LHtool_copy_%s",Root::TSelectorToolBase::getName(),vstr.c_str(),sig_bkg.c_str(),binname);
 
 	  if (!m_pdfFile->GetListOfKeys()->Contains(vstr.c_str())){
             ATH_MSG_INFO("Warning: skipping variable " << vstr << " because the folder does not exist.");
@@ -299,8 +299,8 @@ int Root::TElectronLikelihoodTool::LoadVarHistograms(std::string vstr,unsigned i
           if (et == 0 && !((TDirectory*)m_pdfFile->Get(pdfdir))->GetListOfKeys()->Contains(pdf)) {
             //std::cout << "Info: using 7 GeV bin in place of 4 GeV bin." << std::endl;
             getBinName( binname, et_tmp+1, eta_tmp, ip, m_ipBinning );
-            sprintf(pdf,"%s_%s_smoothed_hist_from_KDE_%s",vstr.c_str(),sig_bkg.c_str(),binname);
-            sprintf(pdf_newname,"%s_%s_%s_LHtool_copy4GeV_%s",Root::TSelectorToolBase::getName(),vstr.c_str(),sig_bkg.c_str(),binname);
+            snprintf(pdf,500,"%s_%s_smoothed_hist_from_KDE_%s",vstr.c_str(),sig_bkg.c_str(),binname);
+            snprintf(pdf_newname,500,"%s_%s_%s_LHtool_copy4GeV_%s",Root::TSelectorToolBase::getName(),vstr.c_str(),sig_bkg.c_str(),binname);
           }
           if (((TDirectory*)m_pdfFile->Get(pdfdir))->GetListOfKeys()->Contains(pdf)) {
             TH1F* hist = (TH1F*)(((TDirectory*)m_pdfFile->Get(pdfdir))->Get(pdf));
@@ -870,8 +870,7 @@ unsigned int Root::TElectronLikelihoodTool::getLikelihoodEtDiscBin(double eT) co
     for(unsigned int eTBin = 0; eTBin < nEtBins; ++eTBin){
       if(eT < eTBins[eTBin])
         return eTBin;
-    }
-    
+    }   
     return nEtBins-1; // Return the last bin if > the last bin.
   }
 }
@@ -883,10 +882,12 @@ unsigned int Root::TElectronLikelihoodTool::getLikelihoodEtDiscBin(double eT) co
 void Root::TElectronLikelihoodTool::getBinName(char* buffer, int etbin,int etabin, int ipbin, std::string iptype) const{
   double eta_bounds[9] = {0.0,0.6,0.8,1.15,1.37,1.52,1.81,2.01,2.37};
   int et_bounds[fnEtBinsHist] = {4,7,10,15,20,30,40,100};
-  if (!iptype.empty())
-    sprintf(buffer, "%s%det%02deta%0.2f", iptype.c_str(), int(fIpBounds[ipbin]), et_bounds[etbin], eta_bounds[etabin]);
-  else 
-    sprintf(buffer, "et%deta%0.2f", et_bounds[etbin], eta_bounds[etabin]);
+  if (!iptype.empty()){
+    snprintf(buffer, 200,"%s%det%02deta%0.2f", iptype.c_str(), int(fIpBounds[ipbin]), et_bounds[etbin], eta_bounds[etabin]);
+  }
+  else{ 
+    snprintf(buffer, 200,"et%deta%0.2f", et_bounds[etbin], eta_bounds[etabin]);
+  }
   return;
 }
 
diff --git a/Reconstruction/MVAUtils/util/convertXmlToRootTree.cxx b/Reconstruction/MVAUtils/util/convertXmlToRootTree.cxx
index cdff52c44c7..24f186b8f2b 100644
--- a/Reconstruction/MVAUtils/util/convertXmlToRootTree.cxx
+++ b/Reconstruction/MVAUtils/util/convertXmlToRootTree.cxx
@@ -192,13 +192,6 @@ int main(int argc, char** argv){
   MVAUtils::BDT* bdt = new MVAUtils::BDT( method_bdt, isRegression || isGrad, useYesNoLeaf);
   bdt->SetPointers(m_vars);
 
-  // {
-  //   auto tree_itr = method_bdt->GetForest().begin();
-  //   const vector<float*>* p_vars(&m_vars);
-  //   TMVA::Event event( p_vars, m_vars.size() );
-  //   cout << "Verbose: " << (*tree_itr)->CheckEvent( &event, 0 ) << " " << bdt->GetTreeResponse(m_vars, bdt->m_forest[0]) << endl;
-  // }
-
 
   cout << endl << "Testing MVA produced from TMVA::Reader " << endl;
 
@@ -228,8 +221,14 @@ int main(int argc, char** argv){
 
 
   cout << endl << "Reading BDT from root file and testing " << outFileName << endl;
+
   f = TFile::Open(outFileName, "READ");
   TTree* bdt_tree = dynamic_cast<TTree*> (f->Get("BDT"));
+  if(!bdt_tree){
+    cerr <<"Could not Retrieve BDT TTree from file , should not happen" <<endl;
+    return 0;
+  }
+  
   bdt = new MVAUtils::BDT(bdt_tree);
   bdt->SetPointers(m_vars);
   cout << bdt->GetResponse() << endl;
diff --git a/Reconstruction/egamma/egammaMVACalib/egammaMVACalib/egammaMVACalib.h b/Reconstruction/egamma/egammaMVACalib/egammaMVACalib/egammaMVACalib.h
index 553dcb8af91..c86d94371f8 100644
--- a/Reconstruction/egamma/egammaMVACalib/egammaMVACalib/egammaMVACalib.h
+++ b/Reconstruction/egamma/egammaMVACalib/egammaMVACalib/egammaMVACalib.h
@@ -425,8 +425,6 @@ class egammaMVACalib : public asg::AsgMessaging
     // the tree or chain
     TTree *m_tree, *m_input_tree;
 
-    // use internal TTree
-    bool m_useInternalTree;
 
     // Pattern of xml file names
     TPRegexp *m_fileNamePattern;
diff --git a/Reconstruction/egamma/egammaRec/src/egammaTruthAssociationAlg.cxx b/Reconstruction/egamma/egammaRec/src/egammaTruthAssociationAlg.cxx
index 9dc23d31b0b..42903d9e8cc 100644
--- a/Reconstruction/egamma/egammaRec/src/egammaTruthAssociationAlg.cxx
+++ b/Reconstruction/egamma/egammaRec/src/egammaTruthAssociationAlg.cxx
@@ -229,15 +229,22 @@ template<class T> bool egammaTruthAssociationAlg::decorateWithRecoLink(T* part,
 
 // ==========================================================================
 xAOD::TruthParticle* egammaTruthAssociationAlg::getEgammaTruthParticle(const xAOD::TruthParticle *truth) const{
+
   if (!truth) return 0;
+
   // Find the original truth particle for electrons from conversions
   for (unsigned int i = 0; i < 100 && truth && truth->barcode() > 200e3; ++i){
     if (truth->prodVtx() && truth->prodVtx()->nIncomingParticles()){
       truth = truth->prodVtx()->incomingParticle(0);
     }
-    else
+    else{
       break;
+    }
   }
+
+  //In case truth became null in the above loop
+  if (!truth) return 0;
+  
   for (const auto& egammaTruth : *m_egammaTruthContainer)
     if (truth->barcode() == egammaTruth->barcode()) {
       return egammaTruth;
diff --git a/Reconstruction/egamma/egammaTools/src/EMBremCollectionBuilder.cxx b/Reconstruction/egamma/egammaTools/src/EMBremCollectionBuilder.cxx
index 36f1b45d77e..e6931de576f 100644
--- a/Reconstruction/egamma/egammaTools/src/EMBremCollectionBuilder.cxx
+++ b/Reconstruction/egamma/egammaTools/src/EMBremCollectionBuilder.cxx
@@ -361,7 +361,8 @@ StatusCode EMBremCollectionBuilder::refitTrack(const xAOD::TrackParticle* tmpTrk
     nSiliconHits_trk += dummy;
   }
   ATH_MSG_DEBUG("Number of Silicon hits "<<nSiliconHits_trk);    
-  //Get the original track that the track particle points to. Clone it in order to assume ownership
+
+  //Get the original track that the track particle points to. 
   const Trk::Track* tmpTrk(0);
   if ( tmpTrkPart->trackLink().isValid() ){
     tmpTrk =  tmpTrkPart->track();
@@ -370,8 +371,9 @@ StatusCode EMBremCollectionBuilder::refitTrack(const xAOD::TrackParticle* tmpTrk
     ATH_MSG_ERROR ("TrackParticle has not Track --  are you running on AOD?");
     return StatusCode::FAILURE;
   }
+
+  //Setup the Trk::Track Refit 
   std::unique_ptr<Trk::Track> trk_refit; 
-  //
   if( nSiliconHits_trk >= m_MinNoSiHits ) {
     StatusCode status = m_trkRefitTool->refitTrackParticle(tmpTrkPart);
     if (status == StatusCode::SUCCESS){
@@ -393,82 +395,89 @@ StatusCode EMBremCollectionBuilder::refitTrack(const xAOD::TrackParticle* tmpTrk
     m_FailedSiliconRequirFit++;
     trk_refit.reset(new Trk::Track(*tmpTrk));
   }
-  //
-  //Refit Trk::Track created
-  //
+  //Refit Trk::Track has been created
+
   //Get the vertex (may be pileup) that this track particle points to
   const xAOD::Vertex* trkVtx(0);
   if (tmpTrkPart->vertexLink().isValid()){ 
     trkVtx = tmpTrkPart->vertex();
   }
-  //
-  // Use the the refitted track and the original vertex to construct a new track particle
+
+  // Use the the Refitted Trk::Track and the original vertex to construct a new TrackParticle
   xAOD::TrackParticle* aParticle = m_particleCreatorTool->createParticle( *trk_refit, m_finalTrkPartContainer, trkVtx, xAOD::electron );
-  //
-  //finalize things
-  if(aParticle!=0) { //store in container
-    //Additional info using the full  Trk::Track
-    //Save extrapolated perigee to calo (eta,phi) for later usage in supercluster algorithm.
-    static const SG::AuxElement::Accessor<float> pgExtrapEta ("perigeeExtrapEta");
-    static const SG::AuxElement::Accessor<float> pgExtrapPhi ("perigeeExtrapPhi");  
-    float perigeeExtrapEta(-999.), perigeeExtrapPhi(-999.);
-    auto tsos = trk_refit->trackStateOnSurfaces()->begin();
-    for (;tsos != trk_refit->trackStateOnSurfaces()->end(); ++tsos) {
-
-      if ((*tsos)->type(Trk::TrackStateOnSurface::Perigee) && (*tsos)->trackParameters()!=0) {
-      
-	float extrapEta(-999.), extrapPhi(-999.);
-	const Trk::TrackParameters *perigeeTrackParams(0);
-	perigeeTrackParams = (*tsos)->trackParameters();
+
+
+  //If no TrackParticle , then ERROR
+  if (!aParticle){
+    ATH_MSG_ERROR("Could not create TrackParticle, this should never happen !");
+    return StatusCode::FAILURE;
+  }
+
+  //Set Vertex Link
+  aParticle->setVertexLink(tmpTrkPart->vertexLink());         
+
+   
+  //Additional info, e/gamma  using the full  Trk::Track
+
+  //Save extrapolated perigee to calo (eta,phi) for later usage in supercluster algorithm.
+  static const SG::AuxElement::Accessor<float> pgExtrapEta ("perigeeExtrapEta");
+  static const SG::AuxElement::Accessor<float> pgExtrapPhi ("perigeeExtrapPhi");  
+  float perigeeExtrapEta(-999.), perigeeExtrapPhi(-999.);
+
+  auto tsos = trk_refit->trackStateOnSurfaces()->begin();
+  for (;tsos != trk_refit->trackStateOnSurfaces()->end(); ++tsos) {
+    if ((*tsos)->type(Trk::TrackStateOnSurface::Perigee) && (*tsos)->trackParameters()!=0) {
+      float extrapEta(-999.), extrapPhi(-999.);
+      const Trk::TrackParameters *perigeeTrackParams(0);
+      perigeeTrackParams = (*tsos)->trackParameters();
       
-	const Trk::PerigeeSurface pSurface (perigeeTrackParams->position());
-	std::unique_ptr<const Trk::TrackParameters> pTrkPar(pSurface.createTrackParameters( perigeeTrackParams->position(), perigeeTrackParams->momentum().unit()*1.e9, +1, 0));
-	//Do the straight-line extrapolation.	  
-	bool hitEM2 = m_extrapolationTool->getEtaPhiAtCalo(pTrkPar.get(), &extrapEta, &extrapPhi);
-	if (hitEM2) {
-	  perigeeExtrapEta = extrapEta;
-	  perigeeExtrapPhi = extrapPhi;
-	} else {
-	  ATH_MSG_WARNING("Extrapolation to EM2 failed!");
-	}
-	break;
-      }
-    }
-    pgExtrapEta(*aParticle) = perigeeExtrapEta;    
-    pgExtrapPhi(*aParticle) = perigeeExtrapPhi;
-    //
-    //Add qoverP for the last measurement
-    static const SG::AuxElement::Accessor<float > QoverPLM  ("QoverPLM");
-    float QoverPLast(0);
-    auto rtsos = trk_refit->trackStateOnSurfaces()->rbegin();
-    for (;rtsos != trk_refit->trackStateOnSurfaces()->rend(); ++rtsos){
-      if ((*rtsos)->type(Trk::TrackStateOnSurface::Measurement) 
-	  && (*rtsos)->trackParameters()!=0 
-	  &&(*rtsos)->measurementOnTrack()!=0 
-	  && !dynamic_cast<const Trk::PseudoMeasurementOnTrack*>((*rtsos)->measurementOnTrack())) {
-	QoverPLast  = (*rtsos)->trackParameters()->parameters()[Trk::qOverP];
-	break;
+      const Trk::PerigeeSurface pSurface (perigeeTrackParams->position());
+      std::unique_ptr<const Trk::TrackParameters> pTrkPar(pSurface.createTrackParameters( perigeeTrackParams->position(), perigeeTrackParams->momentum().unit()*1.e9, +1, 0));
+      //Do the straight-line extrapolation.	  
+      bool hitEM2 = m_extrapolationTool->getEtaPhiAtCalo(pTrkPar.get(), &extrapEta, &extrapPhi);
+      if (hitEM2) {
+	perigeeExtrapEta = extrapEta;
+	perigeeExtrapPhi = extrapPhi;
+      } else {
+	ATH_MSG_WARNING("Extrapolation to EM2 failed!");
       }
+      break;
     }
-    QoverPLM(*aParticle) = QoverPLast;
-    //
-    //Now  Slim the track for writing to disk   
-    Trk::Track* slimmed = m_slimTool->slim(*trk_refit);
-    if(!slimmed){
-      ATH_MSG_ERROR ("TrackSlimming failed, this should never happen !");
-      return StatusCode::FAILURE;
+  }
+  pgExtrapEta(*aParticle) = perigeeExtrapEta;    
+  pgExtrapPhi(*aParticle) = perigeeExtrapPhi;
+  
+  //Add qoverP for the last measurement
+  static const SG::AuxElement::Accessor<float > QoverPLM  ("QoverPLM");
+  float QoverPLast(0);
+  auto rtsos = trk_refit->trackStateOnSurfaces()->rbegin();
+  for (;rtsos != trk_refit->trackStateOnSurfaces()->rend(); ++rtsos){
+    if ((*rtsos)->type(Trk::TrackStateOnSurface::Measurement) 
+	&& (*rtsos)->trackParameters()!=0 
+	&&(*rtsos)->measurementOnTrack()!=0 
+	&& !dynamic_cast<const Trk::PseudoMeasurementOnTrack*>((*rtsos)->measurementOnTrack())) {
+      QoverPLast  = (*rtsos)->trackParameters()->parameters()[Trk::qOverP];
+      break;
     }
+  }
+  QoverPLM(*aParticle) = QoverPLast;
+
+  //Now  Slim the TrK::Track for writing to disk   
+  Trk::Track* slimmed = m_slimTool->slim(*trk_refit);
+    
+  if(!slimmed){
+    ATH_MSG_WARNING ("TrackSlimming failed");
+    ElementLink<TrackCollection> dummy;
+    aParticle->setTrackLink(dummy);     
+  }else{
     m_finalTracks->push_back(slimmed);
-    //
     ElementLink<TrackCollection> trackLink( slimmed, *m_finalTracks);
     aParticle->setTrackLink( trackLink );     
-    aParticle->setVertexLink(tmpTrkPart->vertexLink());         
-    return StatusCode::SUCCESS;
-  }else {
-    ATH_MSG_WARNING("Could not create TrackParticle, this should never happen !");
-    return StatusCode::FAILURE;
   }
+
+  return StatusCode::SUCCESS;
 }
+
 // =================================================================
 bool EMBremCollectionBuilder::Select(const xAOD::CaloCluster*   cluster,
                                      bool                       trkTRT,
diff --git a/Reconstruction/egamma/egammaTools/src/FourMomCombiner.cxx b/Reconstruction/egamma/egammaTools/src/FourMomCombiner.cxx
index 78682fdfd93..ce05c529cef 100644
--- a/Reconstruction/egamma/egammaTools/src/FourMomCombiner.cxx
+++ b/Reconstruction/egamma/egammaTools/src/FourMomCombiner.cxx
@@ -153,7 +153,7 @@ StatusCode FourMomCombiner::TrackClusterExecute(xAOD::Egamma *eg,
   
   int charge(0);
   if (isElectron(eg)) {
-    xAOD::Electron* el = dynamic_cast<xAOD::Electron*> (eg);
+    xAOD::Electron* el =static_cast<xAOD::Electron*> (eg);
     charge = el->trackParticle(index)->charge();
   }
   
diff --git a/Reconstruction/egamma/egammaTools/src/egammaSuperClusterBuilder.cxx b/Reconstruction/egamma/egammaTools/src/egammaSuperClusterBuilder.cxx
index 6086d2ccb01..8789531a3b3 100644
--- a/Reconstruction/egamma/egammaTools/src/egammaSuperClusterBuilder.cxx
+++ b/Reconstruction/egamma/egammaTools/src/egammaSuperClusterBuilder.cxx
@@ -233,7 +233,7 @@ xAOD::CaloCluster* egammaSuperClusterBuilder::CreateNewCluster(const std::vector
     return nullptr;
   }
 
-  xAOD::CaloCluster* newCluster = CaloClusterStoreHelper::makeCluster(clusters.at(0)->getCellLinks()->getCellContainer());
+  std::unique_ptr<xAOD::CaloCluster> newCluster(CaloClusterStoreHelper::makeCluster(clusters.at(0)->getCellLinks()->getCellContainer()));
   if (!newCluster) {
     ATH_MSG_ERROR("CaloClusterStoreHelper::makeCluster failed.");
     return nullptr;
@@ -246,9 +246,8 @@ xAOD::CaloCluster* egammaSuperClusterBuilder::CreateNewCluster(const std::vector
   //
   //Start with the seed 
   //Add the EM cells of the seed cluster
-  if (AddEMCellsToCluster(newCluster,clusters[0]).isFailure()) {
+  if (AddEMCellsToCluster(newCluster.get(),clusters[0]).isFailure()) {
     ATH_MSG_DEBUG("There was problem adding the cells to cluster");
-    delete newCluster;
     return nullptr;
   }  
   //Set the element Link to the relevant constitent
@@ -259,7 +258,7 @@ xAOD::CaloCluster* egammaSuperClusterBuilder::CreateNewCluster(const std::vector
   }
   
   // calculate the seed cluster kinematics.
-  CaloClusterKineHelper::calculateKine(newCluster, true, true);
+  CaloClusterKineHelper::calculateKine(newCluster.get(), true, true);
   //
   //Set the eta0/phi0 based on the eta/phi of the seed 
   newCluster->setEta0(newCluster->eta());
@@ -272,9 +271,8 @@ xAOD::CaloCluster* egammaSuperClusterBuilder::CreateNewCluster(const std::vector
   // Now continue with the remaining clusters
   for (size_t i = 1; i < acSize; i++) {
     //Add te EM cells of the accumulated to the cluster
-    if (AddEMCellsToCluster(newCluster,clusters[i]).isFailure()) {
+    if (AddEMCellsToCluster(newCluster.get(),clusters[i]).isFailure()) {
       ATH_MSG_WARNING("There was problem adding the topocluster cells to the the cluster");
-      delete newCluster;
       return nullptr;
     }
     //
@@ -288,43 +286,40 @@ xAOD::CaloCluster* egammaSuperClusterBuilder::CreateNewCluster(const std::vector
   //
   //Set the link from the super cluster to the constituents (accumulated) clusters used. 
   static const SG::AuxElement::Accessor < std::vector< ElementLink< xAOD::CaloClusterContainer > > > caloClusterLinks("constituentClusterLinks");
-  caloClusterLinks(*newCluster) = constituentLinks;
+  caloClusterLinks(*newCluster.get()) = constituentLinks;
   //
   ///Calculate the kinematics of the new cluster, after all cells are added
-  CaloClusterKineHelper::calculateKine(newCluster, true, true);
+  CaloClusterKineHelper::calculateKine(newCluster.get(), true, true);
   //
   //Check to see if cluster doesn't have EMB2 OR EME2. If not, kill it.
   if (!newCluster->hasSampling(CaloSampling::EMB2) && !newCluster->hasSampling(CaloSampling::EME2)) {
     ATH_MSG_WARNING("Supercluster doesn't have energy in layer 2. Skipping...");
-    delete newCluster;
     return nullptr;     
   }
   //
   //If adding all EM cells I am somehow below the seed threshold then remove 
   //this one
   if(newCluster->et()<m_EtThresholdCut ){
-    delete newCluster;
     return nullptr;
   }
 
   // Apply SW-style summation of TileGap3 cells (if necessary).
-  if (AddTileGap3CellsinWindow(newCluster).isFailure()) {
+  if (AddTileGap3CellsinWindow(newCluster.get()).isFailure()) {
     ATH_MSG_ERROR("Problem with the input cluster when running AddTileGap3CellsinWindow?");
     return nullptr;
   }
-  CaloClusterKineHelper::calculateKine(newCluster, true, true);
+  CaloClusterKineHelper::calculateKine(newCluster.get(), true, true);
 
   // Apply correction  calibration
-  if (CalibrateCluster(newCluster, egType).isFailure()) {
+  if (CalibrateCluster(newCluster.get(), egType).isFailure()) {
     ATH_MSG_WARNING("There was problem calibrating the object");
-    delete newCluster;
     return nullptr;
   }
   // return the new cluster
-  return newCluster;  
+  return newCluster.release();  
 }
 
-StatusCode egammaSuperClusterBuilder::AddEMCellsToCluster(xAOD::CaloCluster       *newCluster,
+StatusCode egammaSuperClusterBuilder::AddEMCellsToCluster(xAOD::CaloCluster *newCluster,
 							  const xAOD::CaloCluster *ref) const {
   if (!newCluster || !ref) {
     ATH_MSG_ERROR("Invalid input in AddEMCellsToCluster");
diff --git a/Reconstruction/egamma/egammaTrackTools/src/CaloCluster_OnTrackBuilder.cxx b/Reconstruction/egamma/egammaTrackTools/src/CaloCluster_OnTrackBuilder.cxx
index 1dfc4917e72..6aed06d1ed5 100755
--- a/Reconstruction/egamma/egammaTrackTools/src/CaloCluster_OnTrackBuilder.cxx
+++ b/Reconstruction/egamma/egammaTrackTools/src/CaloCluster_OnTrackBuilder.cxx
@@ -106,14 +106,12 @@ StatusCode CaloCluster_OnTrackBuilder::finalize(){ return StatusCode::SUCCESS; }
   if(!surface) return 0;
   
   const Trk::LocalParameters*  lp =getClusterLocalParameters( cluster, surface, charge );
-
   if (!lp){
     delete surface;
     return 0;
   }
      
-  const  Amg::MatrixX *em  =getClusterErrorMatrix( cluster, surface, charge );
-  
+  const  Amg::MatrixX *em  =getClusterErrorMatrix( cluster, surface, charge );  
   if (!em){
     delete surface;
     delete lp;
@@ -123,10 +121,10 @@ StatusCode CaloCluster_OnTrackBuilder::finalize(){ return StatusCode::SUCCESS; }
   Trk::CaloCluster_OnTrack* ccot = new  Trk::CaloCluster_OnTrack( *lp, *em, *surface );
   delete surface;
   delete lp;
+  delete em;
 
   if(ccot) {
     ATH_MSG_DEBUG("Successful build of Trk::CaloCluster_OnTrack");
-    //std::cout << *ccot << std::endl;
   }
   
   return ccot;
-- 
GitLab