diff --git a/Calorimeter/CaloExample/CaloRecEx/share/CaloRecOutputItemList_jobOptions.py b/Calorimeter/CaloExample/CaloRecEx/share/CaloRecOutputItemList_jobOptions.py
index fbb3ed952c6773eaf770ef2d71c6ad7f50caebc7..bece6e4a22a2d669bb8cdba34190239c94e7ffd1 100644
--- a/Calorimeter/CaloExample/CaloRecEx/share/CaloRecOutputItemList_jobOptions.py
+++ b/Calorimeter/CaloExample/CaloRecEx/share/CaloRecOutputItemList_jobOptions.py
@@ -195,13 +195,17 @@ for theKey in CaloClusterKeys: #Fixme .. Apply this only to TopoClusters?
      AuxListItem="xAOD::CaloClusterAuxContainer#"+theKey+"Aux"
      for moment in AODMoments:
          AuxListItem+="."+moment
-         pass
+     # for tau clusters
+     if theKey == "CaloCalTopoClusters":
+         AuxListItem += ".CellLink"
      if len(AODMoments)==0: AuxListItem+="." 
      CaloClusterItemList+=[AuxListItem]
 
 # write the link only for egClusterColl
 #CaloClusterItemList+=["CaloClusterCellLinkContainer#egClusterCollection_links"]
 
+# for tau clusters (CaloCalTopoClusters within 0.2 of the tau axis)
+CaloClusterItemList += ["CaloClusterCellLinkContainer#CaloCalTopoClusters_links"]
 
 CaloAODList+=CaloClusterItemList
 
@@ -216,4 +220,3 @@ CaloAODList+=["TileMuContainer#TileMuObj"]
 
 # LAr noisy Feb/PA summary
 CaloAODList +=  ["LArNoisyROSummary#LArNoisyROSummary"]
-
diff --git a/Control/AthenaConfiguration/share/confTool.py b/Control/AthenaConfiguration/share/confTool.py
index d71a22292d007d810f27d632efbedcd8d86b3a6a..4b0db76067a44d8bfebeebc7423073d0b4a26bdf 100755
--- a/Control/AthenaConfiguration/share/confTool.py
+++ b/Control/AthenaConfiguration/share/confTool.py
@@ -281,6 +281,9 @@ def _compareComponent(compRef, compChk, prefix, args, component):
         allProps.sort()
 
         for prop in allProps:
+            if args.ignoreIrrelevant and prop in args.ignoreList:
+                continue
+
             if prop not in compRef.keys():
                 print(
                     "%s%s = %s: \033[94m exists only in 2nd file \033[0m \033[91m<< !!!\033[0m"
@@ -298,9 +301,7 @@ def _compareComponent(compRef, compChk, prefix, args, component):
             refVal = compRef[prop]
             chkVal = compChk[prop]
 
-            if args.ignoreIrrelevant and any(
-                element in args.ignoreList for element in [chkVal, prop]
-            ):
+            if args.ignoreIrrelevant and chkVal in args.ignoreList:
                 continue
 
             refVal, chkVal = _parseNumericalValues(refVal, chkVal)
diff --git a/Control/AthenaMonitoring/python/AthMonitorCfgHelper.py b/Control/AthenaMonitoring/python/AthMonitorCfgHelper.py
index 955aeb00492a2f92cdcc694debe122cd4c11bae1..2f65e43046edf6f1a5d2fada67ae334601ab0ced 100644
--- a/Control/AthenaMonitoring/python/AthMonitorCfgHelper.py
+++ b/Control/AthenaMonitoring/python/AthMonitorCfgHelper.py
@@ -135,8 +135,8 @@ class AthMonitorCfgHelper(object):
         pathToSet = self.inputFlags.DQ.FileKey+('/%s' % topPath if topPath else '')
         array.broadcast('HistPath',pathToSet)
         array.broadcast('UseCache',True)
-        # in the future, autodetect if we are online or not
-        array.broadcast('convention','OFFLINE')
+        convention = 'ONLINE' if self.inputFlags.Common.isOnline else 'OFFLINE'
+        array.broadcast('convention', convention)
         array.broadcast('defaultDuration',defaultDuration)
         alg.GMTools += array.toolList()
         return array
diff --git a/Control/AthenaMonitoring/src/DQEventFlagFilterTool.cxx b/Control/AthenaMonitoring/src/DQEventFlagFilterTool.cxx
index 1a0efb7640700c276d36acf7684a1c5b558366a6..3ca699460e7a9b33696db1f6a13ecbfe456c36a4 100644
--- a/Control/AthenaMonitoring/src/DQEventFlagFilterTool.cxx
+++ b/Control/AthenaMonitoring/src/DQEventFlagFilterTool.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "DQEventFlagFilterTool.h"
@@ -18,6 +18,7 @@ StatusCode DQEventFlagFilterTool::initialize()
   ATH_MSG_VERBOSE("ATLAS Ready initialize");
   // don't register callback if we always return true anyway
   ATH_CHECK( m_EventInfoKey.initialize(!m_alwaysReturnTrue) );
+  ATH_CHECK( m_TileStatusKey.initialize(!m_alwaysReturnTrue) );
   return StatusCode::SUCCESS;
 }
 
diff --git a/Control/AthenaMonitoring/src/DQEventFlagFilterTool.h b/Control/AthenaMonitoring/src/DQEventFlagFilterTool.h
index 2fac590257ceeaa3a010e651226d3a2a30b115d3..deeed055ca97b23438f9cf75d92e238ee6bb1e85 100644
--- a/Control/AthenaMonitoring/src/DQEventFlagFilterTool.h
+++ b/Control/AthenaMonitoring/src/DQEventFlagFilterTool.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef DQEVENTFLAGFILTERTOOL_H
@@ -32,6 +32,7 @@ class DQEventFlagFilterTool :  public AthAlgTool, virtual public IDQFilterTool
   Gaudi::Property<bool> m_doSCT{this, "doSCT", true};
   Gaudi::Property<bool> m_doCore{this, "doCore", true};
   SG::ReadHandleKey<xAOD::EventInfo> m_EventInfoKey{this, "EventInfoKey", "EventInfo"};
+  SG::ReadDecorHandleKey<xAOD::EventInfo> m_TileStatusKey{this, "TileStatusKey", "EventInfo.TileStatus"};
 };
 
 #endif //DQEVENTFLAGFILTERTOOL_H
diff --git a/DataQuality/DataQualityTools/DataQualityTools/DQTBackgroundMon.h b/DataQuality/DataQualityTools/DataQualityTools/DQTBackgroundMon.h
index 4f1118dfa66441118348878f1712b424b8ca306b..a3e179ccf584633d2223aee8099dbcc6882c0d36 100644
--- a/DataQuality/DataQualityTools/DataQualityTools/DQTBackgroundMon.h
+++ b/DataQuality/DataQualityTools/DataQualityTools/DQTBackgroundMon.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 /**
@@ -44,6 +44,11 @@ private:
     RHK<Trk::SegmentCollection> m_SegmentCollectionKey {this, "MuonSegmentsKey", "MuonSegments", ""};
     RHK<BeamBackgroundData> m_BeamBackgroundDataKey {this, "BeamBackgroundDataKey", "BeamBackgroundData", ""};
     RHK<xAOD::VertexContainer> m_VertexContainerKey {this, "PrimaryVerticesKey", "PrimaryVertices", ""};
+    SG::ReadDecorHandleKey<xAOD::EventInfo> m_eventInfoDecorKey{this,"eventInfoDecorKey",
+                                                               "EventInfo.backgroundWord",
+                                                               "Key to enforce scheduling"};
+    // we dp not need a decorhandle key for the MBTS background because we already depend on MBTSCollisionTime
+
 
     // For parsing the int returned by TrigDecTool's getBGCode()
     GP<int> m_filledBG {this, "FilledBGIndex", 1};
diff --git a/DataQuality/DataQualityTools/DataQualityTools/DQTDataFlowMonAlg.h b/DataQuality/DataQualityTools/DataQualityTools/DQTDataFlowMonAlg.h
index 06cef9ce52386aa505f9a709be91f2b8d6745290..50901fd5951ee69b7153630a8b3c612c0596be5d 100644
--- a/DataQuality/DataQualityTools/DataQualityTools/DQTDataFlowMonAlg.h
+++ b/DataQuality/DataQualityTools/DataQualityTools/DQTDataFlowMonAlg.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 // ********************************************************************
@@ -25,8 +25,13 @@ class DQTDataFlowMonAlg: public AthMonitorAlgorithm
 
   virtual ~DQTDataFlowMonAlg() {};
 
+  virtual StatusCode initialize() override;
+
   virtual StatusCode fillHistograms( const EventContext& ctx ) const override;
 
+ private:
+    SG::ReadDecorHandleKey<xAOD::EventInfo> m_TileStatusKey{this, "TileStatusKey", "EventInfo.TileStatus"};
+
 };
 
 #endif
diff --git a/DataQuality/DataQualityTools/src/DQTBackgroundMon.cxx b/DataQuality/DataQualityTools/src/DQTBackgroundMon.cxx
index 3d0489a1dad4d97cdbeffdd3ff7fb01a961e404c..1c17221900d3af52a028a8e8236480941aab48f6 100644
--- a/DataQuality/DataQualityTools/src/DQTBackgroundMon.cxx
+++ b/DataQuality/DataQualityTools/src/DQTBackgroundMon.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "DataQualityTools/DQTBackgroundMon.h"
@@ -18,6 +18,7 @@ StatusCode DQTBackgroundMon::initialize() {
     ATH_CHECK( m_LUCID_RawDataContainerKey.initialize() );
     ATH_CHECK( m_BeamBackgroundDataKey.initialize() );
     ATH_CHECK( m_VertexContainerKey.initialize() );
+    ATH_CHECK( m_eventInfoDecorKey.initialize() );
 
     return AthMonitorAlgorithm::initialize();
 }
diff --git a/DataQuality/DataQualityTools/src/DQTDataFlowMonAlg.cxx b/DataQuality/DataQualityTools/src/DQTDataFlowMonAlg.cxx
index a73005be38dedf3d38a189c5c84b15cf8fc8d5c6..566b793d704f1166eb583cb9ed35f624b49b0d17 100644
--- a/DataQuality/DataQualityTools/src/DQTDataFlowMonAlg.cxx
+++ b/DataQuality/DataQualityTools/src/DQTDataFlowMonAlg.cxx
@@ -21,6 +21,13 @@ DQTDataFlowMonAlg::DQTDataFlowMonAlg( const std::string& name,
 {
 }
 
+StatusCode
+DQTDataFlowMonAlg::initialize()
+{
+  ATH_CHECK(AthMonitorAlgorithm::initialize());
+  ATH_CHECK(m_TileStatusKey.initialize());
+  return StatusCode::SUCCESS;
+}
 
 StatusCode 
 DQTDataFlowMonAlg::fillHistograms( const EventContext& ctx ) const
diff --git a/DataQuality/DataQualityUtils/python/messaging_listen.py b/DataQuality/DataQualityUtils/python/messaging_listen.py
index 6b1080ef9052fca73a53058b4814f28e09dc6369..214098897db23c7ebeccdc44f3666fb910bab7b7 100644
--- a/DataQuality/DataQualityUtils/python/messaging_listen.py
+++ b/DataQuality/DataQualityUtils/python/messaging_listen.py
@@ -18,12 +18,13 @@ class ATLASDQMListener(object):
         self.selector = selector
 
     def __enter__(self):
-        if stomp.__version__ >= (4,1,11):
-            return self.__enter41__()
+        if stomp.__version__ >= (6,1,0):
+            return self.__enter61__()
         else:
-            return self.__enter31__()
+            logging.critical("Unable to find stomp.py >= 6.1.0, can't proceed")
+            raise ValueError("Version of stomp.py is too old")
 
-    def __enter31__(self):
+    def __enter61__(self):
         serverlist=[_[4] for _ in socket.getaddrinfo(MSGSERVER, MSGPORT,
                                                      socket.AF_INET, 
                                                      socket.SOCK_STREAM)]
@@ -33,62 +34,16 @@ class ATLASDQMListener(object):
         if hasattr(self.listener, 'conn'):
             self.listener.conn=[]
         for svr in serverlist:
-            #print 'set up', svr
-            cfg = stompconfig.config()
+            auth = stompconfig.config()
+            cfg = {}
             cfg['heartbeats'] = (0,0)
             cfg['reconnect_attempts_max'] = 3
             cfg['version'] = 1.1
             conn=stomp.Connection([svr], **cfg)
-            #print('set up Connection')
             conn.set_listener('somename',self.listener)
             if hasattr(self.listener, 'conn'):
                 self.listener.conn.append(conn)
-            #print('Set up listener')
-            conn.start()
-
-            #print('started connection')
-
-            conn.connect(wait=True)
-            #print('connected')
-            hdr = {}
-            if self.selector is not None: hdr['selector'] = self.selector
-            if hasattr(self.listener, 'ack_mode'):
-                ack_mode=self.listener.ack_mode
-            else:
-                ack_mode='auto'
-            conn.subscribe(destination=self.dest, ack=ack_mode, headers = hdr, id=len(self.conns))
-            #print('subscribed')
-            self.conns.append(conn)
-        return self
-
-    def __enter41__(self):
-        serverlist=[_[4] for _ in socket.getaddrinfo(MSGSERVER, MSGPORT,
-                                                     socket.AF_INET, 
-                                                     socket.SOCK_STREAM)]
-        
-        from . import stompconfig
-        self.conns = []
-        if hasattr(self.listener, 'conn'):
-            self.listener.conn=[]
-        for svr in serverlist:
-            #print 'set up', svr
-            cfg = stompconfig.config()
-            #cfg['heart-beat'] = (5000,5000)
-            cfg['reconnect_attempts_max'] = 3
-            cfg['version'] = 1.1
-            cfg['login'] = cfg['user']
-            conn=stomp.Connection([svr], heartbeats=(180000,180000))
-            #print('set up Connection')
-            conn.set_listener('somename',self.listener)
-            if hasattr(self.listener, 'conn'):
-                self.listener.conn.append(conn)
-            #print('Set up listener')
-            conn.start()
-
-            #print('started connection')
-
-            conn.connect(wait=True, **cfg)
-            #print('connected')
+            conn.connect(wait=True, **auth)
             hdr = {}
             if self.selector is not None: hdr['selector'] = self.selector
             if hasattr(self.listener, 'ack_mode'):
@@ -96,7 +51,6 @@ class ATLASDQMListener(object):
             else:
                 ack_mode='auto'
             conn.subscribe(destination=self.dest, ack=ack_mode, headers = hdr, id=len(self.conns))
-            #print('subscribed')
             self.conns.append(conn)
         return self
 
diff --git a/DataQuality/DataQualityUtils/python/panic.py b/DataQuality/DataQualityUtils/python/panic.py
index b0efb85a371b79651c3c7844a25989382c5aa03f..7df3dfa65ca81057b1b5a833f9531131ba708ad4 100644
--- a/DataQuality/DataQualityUtils/python/panic.py
+++ b/DataQuality/DataQualityUtils/python/panic.py
@@ -10,11 +10,10 @@ def panic(msg):
     import traceback
     import time
 
-    conn=stomp.Connection([('atlas-mb.cern.ch', 61013)], **stompconfig.config())
-    conn.start()
+    conn=stomp.Connection([('atlas-mb.cern.ch', 61013)])
     print('panic: started connection')
     
-    conn.connect(wait=True)
+    conn.connect(wait=True, **stompconfig.config())
     print('panic: connected')
 
     header={'MsgClass':'DQ', 
@@ -32,7 +31,6 @@ def panic(msg):
                      'time': time.time(),
                      'usrtime': time.strftime('%Y-%m-%d %H:%H:%M %Z', time.localtime()),
                      })
-    #print(msg)
     conn.send(body, **header)
     print('panic: sent message')
     print(header)
diff --git a/DataQuality/DataQualityUtils/python/stompconfig.py b/DataQuality/DataQualityUtils/python/stompconfig.py
index 71b3f9a9cc3f7d91b84754b6166d741e330390fc..c8f389fbd9934ae6a75a783dcd5d74e52440c62b 100644
--- a/DataQuality/DataQualityUtils/python/stompconfig.py
+++ b/DataQuality/DataQualityUtils/python/stompconfig.py
@@ -3,6 +3,6 @@
 
 def config():
     with open('/afs/cern.ch/user/a/atlasdqm/atlas/mqinfo') as f:
-        return {'user': 'atlasdqm',
+        return {'username': 'atlasdqm',
                 'passcode': f.read().strip()}
     raise RuntimeError('Unable to read STOMP connection info')
diff --git a/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_tf.py b/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_tf.py
index e2dc385808a67f5e70f5656c0ed1c7d060ad8998..b0e756d36dabdee0a841f92c17af276c2669a172 100755
--- a/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_tf.py
+++ b/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_tf.py
@@ -87,9 +87,8 @@ def publish_success_to_mq(run, ptag, stream, incr, ami, procpass, hcfg, isprod):
   import stomp, json, ssl
   from DataQualityUtils import stompconfig
   dest='/topic/atlas.dqm.progress'
-  conn=stomp.Connection([('atlas-mb.cern.ch', 61013)], **stompconfig.config())
-  conn.start()
-  conn.connect(wait=True)
+  conn=stomp.Connection([('atlas-mb.cern.ch', 61013)])
+  conn.connect(wait=True, **stompconfig.config())
 
   body = {
     'run': run,
@@ -107,7 +106,7 @@ def publish_success_to_mq(run, ptag, stream, incr, ami, procpass, hcfg, isprod):
     'persistent': 'true',
     'destination': dest,
     }
-  conn.send(message=json.dumps(body), destination=dest,headers=headers,ack='auto')
+  conn.send(body=json.dumps(body), destination=dest,headers=headers,ack='auto')
   conn.disconnect()
 
 #########################################################################
diff --git a/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_trf.py b/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_trf.py
index b10788862cac2a058b985e8d3cc54f5cb1f1ddb7..fb15b787a84c531247c89f3c708e9c8e692bf337 100755
--- a/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_trf.py
+++ b/DataQuality/DataQualityUtils/scripts/DQM_Tier0Wrapper_trf.py
@@ -83,12 +83,8 @@ def publish_success_to_mq(run, ptag, stream, incr, ami, procpass, hcfg, isprod):
   import stomp, json, ssl
   from DataQualityUtils import stompconfig
   dest='/topic/atlas.dqm.progress'
-  #conn=stomp.Connection([('atlas-mb.cern.ch', 61023)], use_ssl=True,
-  #                      ssl_cert_file=os.environ['X509_USER_PROXY'],
-  #                      ssl_version=ssl.PROTOCOL_TLSv1)
-  conn=stomp.Connection([('atlas-mb.cern.ch', 61013)], **stompconfig.config())
-  conn.start()
-  conn.connect(wait=True)
+  conn=stomp.Connection([('atlas-mb.cern.ch', 61013)])
+  conn.connect(wait=True, **stompconfig.config())
 
   body = {
     'run': run,
@@ -106,7 +102,7 @@ def publish_success_to_mq(run, ptag, stream, incr, ami, procpass, hcfg, isprod):
     'persistent': 'true',
     'destination': dest,
     }
-  conn.send(message=json.dumps(body), destination=dest,headers=headers,ack='auto')
+  conn.send(body=json.dumps(body), destination=dest,headers=headers,ack='auto')
   conn.disconnect()
 
 #########################################################################
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/CMakeLists.txt b/DetectorDescription/GeoModel/AtlasGeoModel/CMakeLists.txt
index 2f77ee8ad5a65e2e001cdeb40deb4853bf2c911b..3f0edb1092b102378b1d2590f633c5dfcb46967d 100644
--- a/DetectorDescription/GeoModel/AtlasGeoModel/CMakeLists.txt
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/CMakeLists.txt
@@ -1,14 +1,11 @@
-################################################################################
-# Package: AtlasGeoModel
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( AtlasGeoModel )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
-atlas_install_joboptions( share/*.py )
-atlas_install_scripts( test/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
+atlas_install_scripts( test/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 
 if( NOT GENERATIONBASE )
   atlas_add_test( EVNT_InputGeo_test
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/Agdd2Geo.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/Agdd2Geo.py
index 581c3601798025025ccc83fdfcc8c6022f7363d8..b30e1815a559f231df1b4340e72dcd5365c7b3fe 100644
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/Agdd2Geo.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/Agdd2Geo.py
@@ -1,20 +1,20 @@
-# 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 AthenaCommon.DetFlags import DetFlags
 from AtlasGeoModel.MuonGMJobProperties import MuonGeometryFlags
 
 if ( DetFlags.detdescr.Muon_on() ):
     from AthenaCommon import CfgGetter
-    from AthenaCommon.AppMgr import ToolSvc,ServiceMgr,theApp
+    from AthenaCommon.AppMgr import ServiceMgr,theApp
 
     from AGDD2GeoSvc.AGDD2GeoSvcConf import AGDDtoGeoSvc
     AGDD2Geo = AGDDtoGeoSvc()
 
-    if not "MuonAGDDTool/MuonSpectrometer" in AGDD2Geo.Builders.__str__():
+    if "MuonAGDDTool/MuonSpectrometer" not in AGDD2Geo.Builders.__str__():
         AGDD2Geo.Builders += [CfgGetter.getPrivateTool("MuonSpectrometer", checkType=True)]
 
     if (MuonGeometryFlags.hasSTGC() and MuonGeometryFlags.hasMM()):
-        if not "NSWAGDDTool/NewSmallWheel" in AGDD2Geo.Builders.__str__():
+        if "NSWAGDDTool/NewSmallWheel" not in AGDD2Geo.Builders.__str__():
             AGDD2Geo.Builders += [CfgGetter.getPrivateTool("NewSmallWheel", checkType=True)]
 
     theApp.CreateSvc += ["AGDDtoGeoSvc"]
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/AtlasGeoDBInterface.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/AtlasGeoDBInterface.py
index be5826fefe83c6ced9114b17507511d3bf6c1e48..52a73c8ecb14fc1523c865ee19fd20010a40fa64 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/AtlasGeoDBInterface.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/AtlasGeoDBInterface.py
@@ -1,4 +1,4 @@
-# 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 AthenaCommon import Logging
 
@@ -126,10 +126,10 @@ class AtlasGeoDBInterface:
 
         # Check if the geometry tag was found in the DB
         if self.dbGeoTagId=="":
-            Logging.log.error("The geometry tag "+self.dbGeoTag+" could not be found in the database.")
+            Logging.log.error("The geometry tag %s could not be found in the database.", self.dbGeoTag)
             Logging.log.error("Its name might be misspelled and/or the script might access a local DB that is not up to date.")
             import sys
-            sys.exit();
+            sys.exit()
 
         # Get node ids for the geometry tag
         tagIdList=[int(self.dbGeoTagId)]    # start with the geometry tag Id
@@ -137,7 +137,7 @@ class AtlasGeoDBInterface:
         # Loop while child tags are found
         while not bStopLoop :
 
-            query0 = self.dbSchema.newQuery();
+            query0 = self.dbSchema.newQuery()
 
             query0.addToOutputList('C.NODE_NAME',"nodename")
             query0.addToOutputList('A.TAG_NAME',"tagname")
@@ -177,7 +177,7 @@ class AtlasGeoDBInterface:
         upLeafName=leafName.upper()
 
         # check if table is defined in the current geometry
-        if not leafName in self.TagAndNodeVersionDict:
+        if leafName not in self.TagAndNodeVersionDict:
             dbId=[]
             dbContent={}
             paramName=[]
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInit.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInit.py
index 8b1d7599900f606c0ffe6c6e4ada56fb09461a06..1c3f95c46ac4fa8dd3f3a7c786fa79ecf0dc153f 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInit.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInit.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 ## @file: AtlasGeoModel/python/GeoModelInit.py
 ## @brief: Encapsulate GeoModel configuration
@@ -13,24 +13,24 @@ def _setupGeoModel():
             import DetDescrCnvSvc.DetStoreConfig
             svcMgr.DetDescrCnvSvc.IdDictFromRDB = True
     except ImportError:
-        import DetDescrCnvSvc.DetStoreConfig
+        import DetDescrCnvSvc.DetStoreConfig  # noqa: F401
         svcMgr.DetDescrCnvSvc.IdDictFromRDB = True
 
     # Conditions DB setup and TagInfo
-    from IOVDbSvc.CondDB import conddb
-    import EventInfoMgt.EventInfoMgtInit
+    from IOVDbSvc.CondDB import conddb    # noqa: F401
+    import EventInfoMgt.EventInfoMgtInit  # noqa: F401
  
     if ( jobproperties.Global.DataSource() == "geant3" ):
-        from AtlasGeoModel import GeoModelInitDC1
- 
+        from AtlasGeoModel import GeoModelInitDC1  # noqa: F401
+
     elif ( jobproperties.Global.DetGeo() == "ctbh8" ):
-        from AtlasGeoModel import GeoModelInitCTB
+        from AtlasGeoModel import GeoModelInitCTB  # noqa: F401
  
     elif ( jobproperties.Global.DetGeo() == "ctbh6" ):
-        from AtlasGeoModel import GeoModelInitH6
+        from AtlasGeoModel import GeoModelInitH6   # noqa: F401
  
     else:
-        from AtlasGeoModel import GeoModelInitStandard
+        from AtlasGeoModel import GeoModelInitStandard  # noqa: F401
 
     pass
 
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitCTB.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitCTB.py
index ea3c08786ab2e786f1d85fe69193fa5639ae139b..306df1243fa752fdbdad7f81500e3f862bb426be 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitCTB.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitCTB.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.AppMgr import ServiceMgr
 from AthenaCommon.AppMgr import theApp
@@ -7,7 +7,6 @@ from GeoModelSvc.GeoModelSvcConf import GeoModelSvc
 ServiceMgr += GeoModelSvc()
 theApp.CreateSvc += [ "GeoModelSvc"]
 
-from AtlasGeoModel import InDetGMCTB
-from AtlasGeoModel import TileGMCTB
-from AtlasGeoModel import LArGM
-
+from AtlasGeoModel import InDetGMCTB  # noqa: F401
+from AtlasGeoModel import TileGMCTB   # noqa: F401
+from AtlasGeoModel import LArGM       # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitDC1.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitDC1.py
index e8cc398862643c1469d75ee8c75c11809ae435ba..f3fcc9ccb178bbb6b1b28e0a5e2f10023ee68cc1 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitDC1.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitDC1.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.AppMgr import ServiceMgr
 from AthenaCommon.AppMgr import theApp
@@ -7,5 +7,5 @@ from GeoModelSvc.GeoModelSvcConf import GeoModelSvc
 ServiceMgr += GeoModelSvc()
 theApp.CreateSvc += [ "GeoModelSvc"]
 
-from AtlasGeoModel import InDetGM
-from AtlasGeoModel import MuonGM
+from AtlasGeoModel import InDetGM  # noqa: F401
+from AtlasGeoModel import MuonGM   # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitH6.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitH6.py
index 48d019513292d16cc1785cfcb1f03faa647c3e36..c9bda3fd87c6e9389c2963fba23f6e39c116624f 100644
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitH6.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitH6.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.AppMgr import ServiceMgr
 from AthenaCommon.AppMgr import theApp
@@ -35,4 +35,4 @@ elif (SimFlags.SimLayout.get_Value()=="tb_LArH6_2004"):
 
 
 # as long as not created anywhere else in GeoModel :
-from CaloDetMgrDetDescrCnv import CaloDetMgrDDCnv
+from CaloDetMgrDetDescrCnv import CaloDetMgrDDCnv  # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitStandard.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitStandard.py
index 9bd604af9af019aa7499f197c34ab93c0ff29e1a..e9e9279bb1be82df3a89a75eae57d1a3632ce018 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitStandard.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/GeoModelInitStandard.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.AppMgr import ServiceMgr
 from AthenaCommon.AppMgr import theApp
@@ -8,10 +8,9 @@ ServiceMgr += GeoModelSvc()
 theApp.CreateSvc += [ "GeoModelSvc"]
 
 # Load the detectors. These job option fragments look at DetFlags 
-from AtlasGeoModel import InDetGM
-from AtlasGeoModel import LArGM
-from AtlasGeoModel import TileGM
-from AtlasGeoModel import MuonGM
-from AtlasGeoModel import ForDetGM
-from AtlasGeoModel import MiscGM
-
+from AtlasGeoModel import InDetGM   # noqa: F401
+from AtlasGeoModel import LArGM     # noqa: F401
+from AtlasGeoModel import TileGM    # noqa: F401
+from AtlasGeoModel import MuonGM    # noqa: F401
+from AtlasGeoModel import ForDetGM  # noqa: F401
+from AtlasGeoModel import MiscGM    # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGM.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGM.py
index 7f1952dc4e11e0edcc3de97254c66875f66db672..a2d8e46b004ba6b3bd2ab14a408c83373e057063 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGM.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGM.py
@@ -1,22 +1,18 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #
 # InDet GeoModel initialization
 #
-from AthenaCommon.GlobalFlags import globalflags
 from AthenaCommon.JobProperties import jobproperties
 from AthenaCommon.DetFlags      import DetFlags
 from AthenaCommon.AppMgr        import ServiceMgr as svcMgr
 
 from AtlasGeoModel.CommonGMJobProperties import CommonGeometryFlags
 from AtlasGeoModel.InDetGMJobProperties import InDetGeometryFlags
-if InDetGeometryFlags.isSLHC():
-    #SLHC specific code
-    from AthenaCommon.AppMgr import ToolSvc
 
 # Treat CTB separately
 if ( jobproperties.Global.DetGeo() == "ctbh8" or jobproperties.Global.DetGeo() == "ctbh6" ):
-    from AtlasGeoModel import InDetGMCTB
+    from AtlasGeoModel import InDetGMCTB  # noqa: F401
 
 elif ( DetFlags.detdescr.ID_on() ):
     from GeoModelSvc.GeoModelSvcConf import GeoModelSvc
@@ -31,7 +27,6 @@ elif ( DetFlags.detdescr.ID_on() ):
         GeoModelSvc.DetectorTools += [ CfgGetter.getPrivateTool("PixelDetectorTool", checkType=True) ]
 
         if (DetFlags.detdescr.BCM_on() ) :
-            from AthenaCommon.AppMgr import ToolSvc
             from BCM_GeoModel.BCM_GeoModelConf import InDetDD__BCM_Builder
             bcmTool = InDetDD__BCM_Builder()
             GeoModelSvc.DetectorTools['PixelDetectorTool'].BCM_Tool = bcmTool
@@ -51,7 +46,6 @@ elif ( DetFlags.detdescr.ID_on() ):
             else:
                 from SCT_SLHC_GeoModel.SCT_SLHC_GeoModelConf import SCT_SLHC_DetectorTool
                 sctSLHCTool = SCT_SLHC_DetectorTool()
-                sctSLHCTool.ServiceBuilderTool = InDetServMatBuilderToolSLHC
             GeoModelSvc.DetectorTools += [ sctSLHCTool ]
         else:
             # Current atlas specific code
@@ -71,10 +65,8 @@ elif ( DetFlags.detdescr.ID_on() ):
         #SLHC specific code
         servMatTool = InDetServMatTool()
         GeoModelSvc.DetectorTools += [ servMatTool ]
-        servMatTool.ServiceBuilderTool = InDetServMatBuilderToolSLHC
     else:
         GeoModelSvc.DetectorTools += [ InDetServMatTool() ]
 
     # Make alignable
-    from InDetCondFolders import InDetAlignFolders
-
+    from InDetCondFolders import InDetAlignFolders  # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGMJobProperties.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGMJobProperties.py
index 43c5b63cf2118e038e1f08bd1cddcc2173b00438..5744bd0b379a968bbe104feab957b8979e7a7ead 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGMJobProperties.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/InDetGMJobProperties.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #
 # InDet GeoModel initialization
@@ -70,21 +70,21 @@ class InDetGMFlags(CommonGMFlags, object):
         self.__dict__["IBL"] = False
         self.__dict__["SLHC"] = False
         if _layout in ['IBL'] : self.__dict__["IBL"] = True
-        if self.__dict__["IBL"] == False: self.__dict__["IBLlayout"]="noIBL"
+        if self.__dict__["IBL"] is False: self.__dict__["IBLlayout"]="noIBL"
         if _layout not in ['SLHC'] and ( CommonGeometryFlags.Run() in ["RUN2", "RUN3"] ) : self.__dict__["IBL"] = True
         if _layout in ['SLHC'] : self.__dict__["SLHC"] = True
 
 
     def dump(self):
 
-        Logging.log.info("Geometry tag InDetGMFlags : "+self.__dict__["geomTag"]+" ------------------------------------")
-        Logging.log.info("VersionName = "+self.__dict__["VersionName"])
-        Logging.log.info("Layout      = "+self.__dict__["Layout"])
-        Logging.log.info("DBM         = "+self.__dict__["DBM"])
+        Logging.log.info("Geometry tag InDetGMFlags : %s", self.__dict__["geomTag"]+" ------------------------------------")
+        Logging.log.info("VersionName = %s", self.__dict__["VersionName"])
+        Logging.log.info("Layout      = %s", self.__dict__["Layout"])
+        Logging.log.info("DBM         = %s", self.__dict__["DBM"])
 
-        Logging.log.info("SLHC flag : "+self.__dict__["SLHC"])
-        Logging.log.info("IBL flag   : "+self.__dict__["IBL"])
-        Logging.log.info("IBL layout : "+ self.__dict__["IBLlayout"])
+        Logging.log.info("SLHC flag : %s", self.__dict__["SLHC"])
+        Logging.log.info("IBL flag   : %s", self.__dict__["IBL"])
+        Logging.log.info("IBL layout : %s", self.__dict__["IBLlayout"])
 
 
 # -------------------------------------------------------------------------------------
@@ -169,14 +169,14 @@ class InDetGeometryFlags_JobProperties(JobPropertyContainer):
 
     def dump(self):
 
-        Logging.log.info("VersionName = "+self.GeoVersionName())
-        Logging.log.info("Layout      = "+self.GeoLayout())
-        Logging.log.info("DBM         = "+self.isDBM())
+        Logging.log.info("VersionName = %s", self.GeoVersionName())
+        Logging.log.info("Layout      = %s", self.GeoLayout())
+        Logging.log.info("DBM         = %s", self.isDBM())
 
-        Logging.log.info("SLHC flag : "+self.isSLHC())
-        Logging.log.info("IBL flag   : "+self.isIBL())
-        Logging.log.info("IBL layout : "+self.IBLLayout())
-        Logging.log.info("Dynamic alignment : "+self.useDynamicAlignFolders())
+        Logging.log.info("SLHC flag : %s", self.isSLHC())
+        Logging.log.info("IBL flag   : %s", self.isIBL())
+        Logging.log.info("IBL layout : %s", self.IBLLayout())
+        Logging.log.info("Dynamic alignment : %s", self.useDynamicAlignFolders())
 
 
 jobproperties.add_Container(InDetGeometryFlags_JobProperties)
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/LArGM.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/LArGM.py
index e1356826b363ce1e877125e069fa560872022143..b184c5fd6b2137d5545d67fae06a6f39ddcd4bba 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/LArGM.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/LArGM.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #
 # LAr GeoModel initialization
@@ -13,10 +13,10 @@ if ( DetFlags.detdescr.LAr_on() ):
     GeoModelSvc.DetectorTools += [ LArDetectorToolNV() ]
 
     # as long as not created anywhere else in GeoModel :
-    from CaloDetMgrDetDescrCnv import CaloDetMgrDDCnv
+    from CaloDetMgrDetDescrCnv import CaloDetMgrDDCnv  # noqa: F401
 
     # apply possible alignments
     if ( jobproperties.Global.DetGeo() == "atlas" or
          jobproperties.Global.DetGeo() == "commis" ):
-        from LArConditionsCommon import LArAlignable
+        from LArConditionsCommon import LArAlignable  # noqa: F401
         GeoModelSvc.DetectorTools[ "LArDetectorToolNV" ].ApplyAlignments = True
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/MuonGMJobProperties.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/MuonGMJobProperties.py
index 48aff257792f7794a6408147ad1f6ecdd7faf698..9e73288340537a78dda7d00775eec80072b4e7aa 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/MuonGMJobProperties.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/MuonGMJobProperties.py
@@ -1,9 +1,7 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
-
-from __future__ import print_function
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.JobProperties import JobProperty, JobPropertyContainer, jobproperties
-from AtlasGeoModel.CommonGMJobProperties import CommonGMFlags, CommonGeometryFlags
+from AtlasGeoModel.CommonGMJobProperties import CommonGMFlags
 
 # -------------------------------------------------------------------------------------
 #  Muon geometry flags initialization
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/SetGeometryVersion.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/SetGeometryVersion.py
index 3e282c80f5369850e71c70f8abebc29d48aa1294..f4d98482af204b752735cc4116bb77b9e03c4408 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/SetGeometryVersion.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/SetGeometryVersion.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 from AthenaCommon.JobProperties import jobproperties
 from AthenaCommon.DetFlags    import DetFlags
@@ -56,5 +56,5 @@ relversion = rel_metadata['release'].split('.')
 if len(relversion) < 3:
     relversion = rel_metadata['base release'].split('.')
 
-Logging.log.info("SetGeometryVersion.py obtained major release version %s" % relversion[0])
+Logging.log.info("SetGeometryVersion.py obtained major release version %s", relversion[0])
 GeoModelSvc.SupportedGeometry = int(relversion[0])
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/python/SetupRecoGeometry.py b/DetectorDescription/GeoModel/AtlasGeoModel/python/SetupRecoGeometry.py
index 4c5de86c63cd1cbcad5f8bc796839c90f881fb2e..da80c36147565d7baeb45359cd5c7fee8dd60dfa 100644
--- a/DetectorDescription/GeoModel/AtlasGeoModel/python/SetupRecoGeometry.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/python/SetupRecoGeometry.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #
 # Configure GeoModel tools to build minimal geometry fo reconstruction
@@ -19,4 +19,4 @@ if ( DetFlags.detdescr.Tile_on() ):
 # Build Muon dead materials using AGDD2Geo
 #
 
-from AtlasGeoModel import Agdd2Geo
+from AtlasGeoModel import Agdd2Geo  # noqa: F401
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelBuildAll.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelBuildAll.py
deleted file mode 100755
index 750b4dcb3fa77a8a9ed7df5f24e2f7ea14ac498a..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelBuildAll.py
+++ /dev/null
@@ -1,6 +0,0 @@
-
-print "AtlasGeoModel/GeoModelBuildAll.py is OBSOLETE"
-
-from AtlasGeoModel import SetGeometryVersion
-from AtlasGeoModel import GeoModelInit
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelCommon.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelCommon.py
deleted file mode 100755
index c99b7cd38200b17a663ae0b240d2c5eeb63704cd..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelCommon.py
+++ /dev/null
@@ -1,6 +0,0 @@
-
-print "AtlasGeoModel/GeoModelCommon.py is OBSOLETE"
-
-from AtlasGeoModel import SetGeometryVersion
-from AtlasGeoModel import GeoModelInit
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInit.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInit.py
deleted file mode 100755
index af3f02e4cf8ae32bc0f69952cfa9192833f12008..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInit.py
+++ /dev/null
@@ -1,4 +0,0 @@
-
-printfunc ("AtlasGeoModel/GeoModelInit.py is OBSOLETE")
-
-from AtlasGeoModel import GeoModelInit
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitCTB.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitCTB.py
deleted file mode 100755
index 116fc9ce10fb1916788fe31fd16e9e12f57eb52e..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitCTB.py
+++ /dev/null
@@ -1,4 +0,0 @@
-print "AtlasGeoModel/GeoModelInitCTB.py is OBSOLETE"
-
-from AtlasGeoModel import GeoModelInitCTB
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitDC1.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitDC1.py
deleted file mode 100755
index 34c62664445f22ba450bc0a726cdbedf5d004909..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitDC1.py
+++ /dev/null
@@ -1,4 +0,0 @@
-print "AtlasGeoModel/GeoModelInitDC1.py is OBSOLETE"
-
-from AtlasGeoModel import GeoModelInitDC1
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitH6.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitH6.py
deleted file mode 100644
index ca5fca556792656d082225a269945ba19dc92fed..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitH6.py
+++ /dev/null
@@ -1,4 +0,0 @@
-print "AtlasGeoModel/GeoModelInitH6.py is OBSOLETE"
-
-from AtlasGeoModel import GeoModelInitH6
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitStandard.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitStandard.py
deleted file mode 100755
index 3d15de2aeb3dbf2577faa2ef1caa081146449514..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/GeoModelInitStandard.py
+++ /dev/null
@@ -1,5 +0,0 @@
-
-print "AtlasGeoModel/GeoModelInitStandard.py is OBSOLETE"
-
-from AtlasGeoModel import GeoModelInitStandard
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModel.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModel.py
deleted file mode 100755
index 3cd0c8974460a5adc2ab822b12802cd7c9d82fa8..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModel.py
+++ /dev/null
@@ -1,5 +0,0 @@
-
-print "AtlasGeoModel/InDetGeoModel.py is OBSOLETE"
-
-from AtlasGeoModel import InDetGM
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelCTB.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelCTB.py
deleted file mode 100755
index 173c59dac7731b64f829c4d9625c21a8702a370e..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelCTB.py
+++ /dev/null
@@ -1,7 +0,0 @@
-
-print "AtlasGeoModel/InDetGeoModelCTB.py is OBSOLETE"
-
-from AtlasGeoModel import InDetGMCTB
-
-
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelDC2.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelDC2.py
deleted file mode 100755
index 5f043fb4571f6a480da86303019b8167e1e25a5f..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/InDetGeoModelDC2.py
+++ /dev/null
@@ -1,5 +0,0 @@
-
-print "AtlasGeoModel/InDetGeoModelDC2.py is OBSOLETE"
-
-from AtlasGeoModel import InDetGM
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/LArGeoModel.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/LArGeoModel.py
deleted file mode 100755
index 29a4b4563512bb277e99bd5934e44ae733f632ea..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/LArGeoModel.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from AtlasGeoModel import LArGM
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/MiscGeoModel.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/MiscGeoModel.py
deleted file mode 100755
index a57eb05c77ea3b06a2e4b19792abf68b60bdd26f..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/MiscGeoModel.py
+++ /dev/null
@@ -1,4 +0,0 @@
-
-print "AtlasGeoModel/MiscGeoModel.py is OBSOLETE"
-
-from AtlasGeoModel import MiscGM
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModel.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModel.py
deleted file mode 100755
index f0b394a49478b3ade8e4a35e44c5e461f800c477..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModel.py
+++ /dev/null
@@ -1,4 +0,0 @@
-
-print "AtlasGeoModel/MuonGeoModel.py is OBSOLETE"
-
-from AtlasGeoModel import MuonGM
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModelCTB.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModelCTB.py
deleted file mode 100755
index 0f5d97372a46b0417dd1e5a86d3b3034fc9aef38..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/MuonGeoModelCTB.py
+++ /dev/null
@@ -1,2 +0,0 @@
-print " MuonGeoModelCTB is not supported "
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersion.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersion.py
deleted file mode 100755
index c5ef0cad550eea54128f1d1def907b3ca87aaf54..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersion.py
+++ /dev/null
@@ -1,5 +0,0 @@
-
-printfunc ("AtlasGeoModel/SetGeometryVersion.py is OBSOLETE")
-
-from AtlasGeoModel import SetGeometryVersion
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersionNew.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersionNew.py
deleted file mode 100755
index 1e0eb7f3044d3823a0650f60a1b7cd2753348a21..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/SetGeometryVersionNew.py
+++ /dev/null
@@ -1,6 +0,0 @@
-
-print "AtlasGeoModel/SetGeometryVersionNew.py is OBSOLETE"
-
-from AtlasGeoModel import SetGeometryVersion
-      
-   
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModel.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModel.py
deleted file mode 100755
index bbbe0de6cab50ef018bbf583b74b6519f1b4d84a..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModel.py
+++ /dev/null
@@ -1,4 +0,0 @@
-
-print "AtlasGeoModel/TileGeoModel.py is OBSOLETE"
-
-from AtlasGeoModel import TileGM   
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModelCTB.py b/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModelCTB.py
deleted file mode 100755
index 33a6e3df95fb16e363cb6e415c0d69a62fb0cafd..0000000000000000000000000000000000000000
--- a/DetectorDescription/GeoModel/AtlasGeoModel/share/TileGeoModelCTB.py
+++ /dev/null
@@ -1,6 +0,0 @@
-
-print "AtlasGeoModel/TileGeoModelCTB.py is OBSOLETE"
-
-from AtlasGeoModel import TileGMCTB
-
-
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_AOD_test.py b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_AOD_test.py
index baeaf75e8615a2b731599e224364f0e5afaa3c00..6c0cace9af8a3394e4b19f3916cde38223a9356e 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_AOD_test.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_AOD_test.py
@@ -1,10 +1,9 @@
 #!/usr/bin/env python
 """Run a test on Atlas Geometry configuration using a HITS file as input
 
-Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 """
 if __name__ == "__main__":
-    import os
     from AthenaCommon.Logging import log
     from AthenaCommon.Constants import DEBUG
     from AthenaCommon.Configurable import Configurable
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_EVNT_test.py b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_EVNT_test.py
index 96e2f53e8cd2a36f646b1c3952a641a7c7fe0284..431daabf194eb26d363e92a4ab061ed1e27d0c1a 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_EVNT_test.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_EVNT_test.py
@@ -1,10 +1,9 @@
 #!/usr/bin/env python
 """Run a test on Atlas Geometry configuration using a EVNT file as input
 
-Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 """
 if __name__ == "__main__":
-    import os
     from AthenaCommon.Logging import log
     from AthenaCommon.Constants import DEBUG
     from AthenaCommon.Configurable import Configurable
diff --git a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_HITS_test.py b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_HITS_test.py
index e6d7ec29305405e6e7fa64e8ed789e7c31065969..b1f721b81d458e9a7fb1ce1dbeb5579806db6349 100755
--- a/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_HITS_test.py
+++ b/DetectorDescription/GeoModel/AtlasGeoModel/test/AtlasGeometryConfig_HITS_test.py
@@ -1,10 +1,9 @@
 #!/usr/bin/env python
 """Run a test on Atlas Geometry configuration using a HITS file as input
 
-Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 """
 if __name__ == "__main__":
-    import os
     from AthenaCommon.Logging import log
     from AthenaCommon.Constants import DEBUG
     from AthenaCommon.Configurable import Configurable
diff --git a/Event/EventBookkeeperTools/CMakeLists.txt b/Event/EventBookkeeperTools/CMakeLists.txt
index 97705ec7682333e4a78c895435cd83a6627f0033..3878dd2fec896cc6d1a75c893ebd572cbadbcada 100644
--- a/Event/EventBookkeeperTools/CMakeLists.txt
+++ b/Event/EventBookkeeperTools/CMakeLists.txt
@@ -43,7 +43,7 @@ atlas_add_executable( dump-cbk
                       LINK_LIBRARIES ${xaod_access_lib} AsgTools )  
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
 # Tests
diff --git a/Event/EventBookkeeperTools/python/BookkeepingInfoWriter.py b/Event/EventBookkeeperTools/python/BookkeepingInfoWriter.py
index 06b6ff2d5755b3258445ee7be4868545e5ba3a6e..3b45b72840be921f98ed964cec2be74bf1d315e8 100644
--- a/Event/EventBookkeeperTools/python/BookkeepingInfoWriter.py
+++ b/Event/EventBookkeeperTools/python/BookkeepingInfoWriter.py
@@ -93,11 +93,11 @@ class BookkeepingWriterBase( PyAthena.Alg ):
 
             if alg:
                 dic[name]["Alg"]=alg
-                self.msg.debug("Succesfully added algorithm '%s'"%name)
+                self.msg.debug("Succesfully added algorithm '%s'", name)
 
 
             else:
-                self.msg.warning("BookkeepingWriterBase cannot get algorithm '%s'. This alg will not be bookkept."%name)
+                self.msg.warning("BookkeepingWriterBase cannot get algorithm '%s'. This alg will not be bookkept.", name)
                 dic.pop(name)
         return
 
@@ -119,7 +119,7 @@ class SkimDecisionsWriter(BookkeepingWriterBase):
         return
 
     def initialize(self):
-        self.msg.info("SkimDecisionsContainer name: '%s'"%self.SkimDecisionsContainerName)
+        self.msg.info("SkimDecisionsContainer name: '%s'", self.SkimDecisionsContainerName)
         self.sg = PyAthena.py_svc("StoreGateSvc")
         return BookkeepingWriterBase.initialize(self)
 
@@ -129,12 +129,12 @@ class SkimDecisionsWriter(BookkeepingWriterBase):
             sd.setName(prefix+"_"+key)
             try:
                 sd.setIsAccepted(dic[key]["Alg"].filterPassed())
-            except:
-                self.msg.error("problem with filterPassed() for alg %s..."%key)
+            except Exception:
+                self.msg.error("problem with filterPassed() for alg %s...", key)
 
             sdc.push_back(sd)
             ROOT.SetOwnership (sd, False)
-            self.msg.debug("Skim %s: %i (%s)"%(key,sd.isAccepted(),prefix))
+            self.msg.debug("Skim %s: %i (%s)", key, sd.isAccepted(), prefix)
         return
 
     def execute(self):
diff --git a/Event/EventBookkeeperTools/python/CutFlowHelpers.py b/Event/EventBookkeeperTools/python/CutFlowHelpers.py
index 6e246a6e802f1437a678894dfd233cbb95504d25..351ed7a8ee1b749cb36a1fe0215c6a5d52238430 100644
--- a/Event/EventBookkeeperTools/python/CutFlowHelpers.py
+++ b/Event/EventBookkeeperTools/python/CutFlowHelpers.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Creation: Karsten Koeneke
 def GetCurrentStreamName( msg ):
@@ -6,7 +6,7 @@ def GetCurrentStreamName( msg ):
     # First, try to get the info from the RecFlags
     try:
         from RecExConfig.RecFlags import rec
-        msg.debug("Got the stream name from the RecFlags: %s" % rec.mergingStreamName())
+        msg.debug("Got the stream name from the RecFlags: %s", rec.mergingStreamName())
         streamName = rec.mergingStreamName()
         if streamName == "":
             streamName = "unknownStream"
@@ -39,7 +39,7 @@ def CreateCutFlowSvc( svcName="CutFlowSvc", seq=None, addMetaDataToAllOutputFile
 
     # Determine current input stream name
     inputStreamName = GetCurrentStreamName( msg=msg )
-    msg.debug("CreateCutFlowSvc: Have inputStreamName = %s" % (inputStreamName) )
+    msg.debug("CreateCutFlowSvc: Have inputStreamName = %s", inputStreamName)
 
     # Create the CutFlowSvc instance
     import AthenaCommon.CfgMgr as CfgMgr
@@ -81,11 +81,11 @@ def CreateCutFlowSvc( svcName="CutFlowSvc", seq=None, addMetaDataToAllOutputFile
                     if alg.getName() == "xAODMaker::EventInfoCnvAlg": break
                     pass
                 pass
-            msg.debug("Adding EventCounterAlg with name AllExecutedEvents to sequence with name %s at position %i" % (seq.getName(),index))
+            msg.debug("Adding EventCounterAlg with name AllExecutedEvents to sequence with name %s at position %i", seq.getName(), index)
             seq.insert( index, CfgMgr.EventCounterAlg("AllExecutedEvents") )
             pass
         else :
-            msg.info("Could NOT add EventCounterAlg with name AllExecutedEvents to locked sequence with name %s" % seq.getName())
+            msg.info("Could NOT add EventCounterAlg with name AllExecutedEvents to locked sequence with name %s", seq.getName())
             pass
         pass
 
diff --git a/Event/EventBookkeeperTools/python/PyFilterTester.py b/Event/EventBookkeeperTools/python/PyFilterTester.py
index 3257a3a64bc37c3112ff7042e218a417ea70c0da..ad4f070ef6dc73ce7c1aa289b32a29686d7176b7 100644
--- a/Event/EventBookkeeperTools/python/PyFilterTester.py
+++ b/Event/EventBookkeeperTools/python/PyFilterTester.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 ##=============================================================================
 ## Name:        PyFilterTester
@@ -35,5 +35,5 @@ class PyFilterTester( AthFilterAlgorithm ):
         return StatusCode.Success
 
     def finalize(self):
-        self.msg.info( ' Number of processed events:  %r' % self.nProcessed )
+        self.msg.info( ' Number of processed events:  %r', self.nProcessed )
         return StatusCode.Success
diff --git a/Event/EventBookkeeperTools/python/TestLogicalFilterCombiner.py b/Event/EventBookkeeperTools/python/TestLogicalFilterCombiner.py
index 111bdc81fc3310d1c2f3e31098546b1cd196df00..fec3b11db7e0d141f505f00f350cb8b8b1994e21 100644
--- a/Event/EventBookkeeperTools/python/TestLogicalFilterCombiner.py
+++ b/Event/EventBookkeeperTools/python/TestLogicalFilterCombiner.py
@@ -88,7 +88,7 @@ class TestLogicalFilterCombiner( PyAthena.AthFilterAlgorithm ):
                         self.msg.error("Algorithm %s not found" , tokval)
                         return False
                     else:
-                        self.msg.debug("Found algorithm: %s -> %s" % (tokval, _alg))
+                        self.msg.debug("Found algorithm: %s -> %s", tokval, _alg)
            
 
                     exec('self.%s = _alg' % tokval)
@@ -123,7 +123,7 @@ class TestLogicalFilterCombiner( PyAthena.AthFilterAlgorithm ):
     def execute(self):
 
         for k,v in self.algdict.iteritems():
-            self.msg.debug("Alg %s : %s" % (k, v.filterPassed()))
+            self.msg.debug("Alg %s : %s", k, v.filterPassed())
             pass
 
         response = bool(eval(self.cmd))
diff --git a/Event/EventKernel/CMakeLists.txt b/Event/EventKernel/CMakeLists.txt
index 88b35e78eea6b9c4b60ca4195e89922b511ae2f1..9edbda24983f57fcc783f0ec04294ee6508bb7fe 100644
--- a/Event/EventKernel/CMakeLists.txt
+++ b/Event/EventKernel/CMakeLists.txt
@@ -26,4 +26,4 @@ atlas_add_dictionary( EventKernelDict
                       LINK_LIBRARIES EventKernel )
 
 # Install files from the package:
-atlas_install_python_modules( python/__init__.py python/ParticleDataType.py )
+atlas_install_python_modules( python/__init__.py python/ParticleDataType.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/Event/FourMomUtils/CMakeLists.txt b/Event/FourMomUtils/CMakeLists.txt
index c2daa8b5d117af7ddf7f7e9e4882a17bf6487e86..87b974f4fbbf505d83527346971fd671cee83071 100644
--- a/Event/FourMomUtils/CMakeLists.txt
+++ b/Event/FourMomUtils/CMakeLists.txt
@@ -39,4 +39,4 @@ atlas_add_dictionary( FourMomUtilsDict
    LINK_LIBRARIES FourMomUtils )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/Event/FourMomUtils/python/Bindings.py b/Event/FourMomUtils/python/Bindings.py
index b752c20616082b143e6787cf69348acfe767556f..44192fc88b905f65f2182083e64d0b9b3aadb07d 100644
--- a/Event/FourMomUtils/python/Bindings.py
+++ b/Event/FourMomUtils/python/Bindings.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # @file FourMomUtils/python/Bindings.py
 # @author Sebastien Binet <binet@cern.ch>
@@ -12,7 +12,7 @@ def _installBindings():
     import cppyy
     cppyy.load_library('liblibFourMomUtilsDict')
 
-    x = cppyy.gbl.xAOD.Helpers._importHelper()
+    x = cppyy.gbl.xAOD.Helpers._importHelper()  # noqa: F841
 
     return
 
diff --git a/Event/PyDumper/CMakeLists.txt b/Event/PyDumper/CMakeLists.txt
index b072c68b996bc4062db77b67592712a90a29cac9..5bd90b2b20ae560d1b7e81793b3e9b2b7bf19b3e 100644
--- a/Event/PyDumper/CMakeLists.txt
+++ b/Event/PyDumper/CMakeLists.txt
@@ -13,7 +13,7 @@ atlas_add_dictionary( PyDumperDictDict
    LINK_LIBRARIES AthContainers )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_scripts( bin/sg-dump.py )
 
 # Aliases:
diff --git a/Event/PyDumper/python/Dumpers.py b/Event/PyDumper/python/Dumpers.py
index 3d2a63c20c3b4503e2407a81da1db11c57c39212..4a83826b58ffc60e36decff6a8001b388f29f7c5 100644
--- a/Event/PyDumper/python/Dumpers.py
+++ b/Event/PyDumper/python/Dumpers.py
@@ -19,7 +19,6 @@ __author__ = "Scott Snyder, Sebastien Binet"
 
 ### imports
 from contextlib import contextmanager
-import math
 import sys
 from io import StringIO
 from functools import cmp_to_key
@@ -33,7 +32,8 @@ from PyUtils.fprint import fprint, fprintln, fwrite
 import ROOT
 import cppyy
 
-cmp = lambda x, y: (x > y) - (x < y)
+def cmp(x, y):
+    return (x > y) - (x < y)
 
 # not available due to a reflex bug.
 etcone10 = 0
@@ -3090,7 +3090,7 @@ def dump_ExtendedVxCandidate (c, f):
 
 
 def dump_V0Hypothesis (h, f):
-    if h == None:
+    if h is None:
         fprint (f, None)
         return
     fprint (f, 'V0Hypothesis', h.positiveTrackID(),
@@ -3668,7 +3668,7 @@ def dump_CaloTopoTowerContainer (t, f):
     dl(t.GetTowers())
     dl(t.GetCells())
     if t.GetCellToClusterMap():
-        fprintln (f, '  ', GetCellToClusterMap().size())
+        fprintln (f, '  ', t.GetCellToClusterMap().size())
     else:
         fprintln (f, '  (null)')
     return
@@ -3814,7 +3814,7 @@ def dump_TrigRNNOutput (p, f):
 
 
 def dump_InDetLowBetaCandidate (p, f):
-    if p == None:
+    if p is None:
         fprint (f, '(null)')
         return
     if hasattr (p, 'getTRTInverseBeta'):
@@ -4714,9 +4714,9 @@ atomic_accessors = {
 
 
 def format_obj (x, name=None):
-    if type(x) == type(1.5):
+    if isinstance(x, float):
         return format_float (x)
-    if type(x) == type(1):
+    if isinstance(x, int):
         return format_int (x)
     tname = typename(type(x))
     if tname.startswith ('ROOT.'):
@@ -4855,7 +4855,7 @@ def dump_xAODObjectNL(o, f):
 def dump_list (l, f, dumper, nmax = None):
     i = 0
     for x in l:
-        if nmax != None and i >= nmax: break
+        if nmax is not None and i >= nmax: break
         i += 1
         fprint (f, '  ')
         dumper (x, f)
diff --git a/Event/PyDumper/python/PyComps.py b/Event/PyDumper/python/PyComps.py
index e13eedff6eebb6826be99ff63c7a17ccc7189ef4..7621415ad250b7d68273d056c82cf0a1fc2aa29e 100644
--- a/Event/PyDumper/python/PyComps.py
+++ b/Event/PyDumper/python/PyComps.py
@@ -3,7 +3,6 @@
 # @file:    PyDumper/python/PyComps.py
 # @purpose: A set of PyAthena components to test reading/writing EDM classes
 # @author:  Sebastien Binet <binet@cern.ch>
-# $Id: PyComps.py,v 1.11 2008-12-17 10:19:03 binet Exp $
 
 __doc__     = 'A set of PyAthena components to test reading/writing EDM classes'
 __version__ = '$Revision: 1.11 $'
@@ -11,7 +10,7 @@ __author__  = 'Sebastien Binet <binet@cern.ch>'
 
 import os
 from fnmatch import fnmatch
-import AthenaCommon.SystemOfUnits as Units
+from io import IOBase
 import AthenaPython.PyAthena as PyAthena
 from AthenaPython.PyAthena import StatusCode
 
@@ -149,7 +148,7 @@ class PyReader (PyAthena.Alg):
             pass
         elif isinstance(self.ofile, str):
             self.ofile = open(self.ofile, 'w')
-        elif isinstance(self.ofile, file):
+        elif isinstance(self.ofile, IOBase):
             pass
         else:
             self.msg.error("don't know how to handle ofile value/type [%s/%s]!",
@@ -261,7 +260,7 @@ class PySgDumper (PyAthena.Alg):
             pass
         elif isinstance(self.ofile, str):
             self.ofile = open(self.ofile, 'w')
-        elif isinstance(self.ofile, file):
+        elif isinstance(self.ofile, IOBase):
             pass
         else:
             self.msg.error("don't know how to handle ofile value/type [%s/%s]!",
@@ -441,12 +440,8 @@ class DataProxyLoader(PyAthena.Alg):
         return StatusCode.Success
 
     def execute(self):
-        _debug= self.msg.debug
-        _info = self.msg.info
-        _warn = self.msg.warning
-        _fatal= self.msg.fatal
         _add_fail = self.failed_dumps.add
-        _info('==> processing event [%s]...', self._evt_nbr)
+        self.msg.info('==> processing event [%s]...', self._evt_nbr)
         self._evt_nbr += 1
         if self.items is None:
             # take all from storegate
@@ -466,13 +461,13 @@ class DataProxyLoader(PyAthena.Alg):
         for p in proxies:
             clid = p.clID()
             sgkey= p.name()
-            _debug('loading proxy [%s#%s]...', clid, sgkey)
+            self.msg.debug('loading proxy [%s#%s]...', clid, sgkey)
             try:
                 dobj = p.accessData()
                 if not dobj:
                     all_good = False
             except Exception as err:
-                _fatal('problem loading proxy [%s#%s]', clid, sgkey)
+                self.msg.fatal('problem loading proxy [%s#%s]', clid, sgkey)
                 _add_fail((sgkey, clid, str(err)))
                 all_good = False
                 
diff --git a/Event/PyDumper/python/SgDumpLib.py b/Event/PyDumper/python/SgDumpLib.py
index e1380d81380a2c8359da3777e2b0fea55d5c1142..85387d68d093d3219eae6db828172c02f80233c2 100644
--- a/Event/PyDumper/python/SgDumpLib.py
+++ b/Event/PyDumper/python/SgDumpLib.py
@@ -5,19 +5,13 @@
 # @author  Sebastien Binet <binet@cern.ch>
 # @date    August 2009
 
-from __future__ import with_statement, print_function
-import sys
 import os
 
-from future import standard_library
-standard_library.install_aliases()
-
 __doc__ = """\
 API for the sg-dump script (which dumps an ASCII representation of events in
 POOL or RAW files
 """
 __author__ = "Sebastien Binet <binet@cern.ch>"
-__version__= "$Revision$"
 
 __all__ = [
     'run_sg_dump',
@@ -226,7 +220,7 @@ def _gen_jobo(dct):
     return job
 
 def _run_jobo(job, msg, options):
-    import os,atexit,tempfile,shutil,glob
+    import os,atexit,tempfile,shutil
     # capture current directory's content
     keep_files = [os.path.abspath(item)
                   for item in os.listdir(os.getcwd())]
@@ -275,7 +269,7 @@ def _run_jobo(job, msg, options):
     if options.use_recex_links:
         sc,out = subprocess.getstatusoutput ('RecExCommon_links.sh')
         if sc != 0:
-            msg.error("could not run 'RecExCommon_links.sh':\n%s"%out)
+            msg.error("could not run 'RecExCommon_links.sh':\n%s", out)
             return sc, out
         msg.info ('installed RecExCommon links')
     
@@ -309,7 +303,7 @@ def _run_jobo(job, msg, options):
                             stderr=logfile,
                             env=env)
     pos = 0
-    import time, re
+    import re
     pat = re.compile (r'^Py:pyalg .*')
     evt_pat = re.compile (
         r'^Py:pyalg .*? ==> processing event \[(?P<evtnbr>\d*?)\].*'
diff --git a/Event/xAOD/xAODBase/CMakeLists.txt b/Event/xAOD/xAODBase/CMakeLists.txt
index 97c640fda79fad99ba7e6784d4c0f636712cfc9c..7ce6b21596a21f782d43554095a3d77c4929a5b8 100644
--- a/Event/xAOD/xAODBase/CMakeLists.txt
+++ b/Event/xAOD/xAODBase/CMakeLists.txt
@@ -36,7 +36,7 @@ atlas_add_dictionary( xAODBaseObjectTypeDict
    xAODBase/selection-ObjectType.xml )
 
 # Install files from the package.
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 
 # Test(s) in the package.
 atlas_add_test( ut_xAODObjectType_test
diff --git a/Event/xAOD/xAODEgamma/CMakeLists.txt b/Event/xAOD/xAODEgamma/CMakeLists.txt
index ab77b70d752e335d5fc2cf7585dfee648a7452c0..7f4d9c75bd1aa000201f217a20f4cb3abb93688b 100644
--- a/Event/xAOD/xAODEgamma/CMakeLists.txt
+++ b/Event/xAOD/xAODEgamma/CMakeLists.txt
@@ -33,4 +33,4 @@ atlas_add_dictionary( xAODEgammaParametersDict
    xAODEgamma/selectionParameters.xml )
 
 # Install files from the package.
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/Event/xAOD/xAODJetCnv/CMakeLists.txt b/Event/xAOD/xAODJetCnv/CMakeLists.txt
index f03c03e7cb032bc17be34cf68f77f1ea264a74a5..edb816cb9717c1a1de2e1d1974e86cf33df4cd3d 100644
--- a/Event/xAOD/xAODJetCnv/CMakeLists.txt
+++ b/Event/xAOD/xAODJetCnv/CMakeLists.txt
@@ -16,6 +16,6 @@ atlas_add_component( xAODJetCnv
                      LINK_LIBRARIES xAODJetCnvLib xAODJet GaudiKernel AthenaBaseComps AthenaKernel StoreGateLib SGtests JetEvent )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/Event/xAOD/xAODPrimitives/CMakeLists.txt b/Event/xAOD/xAODPrimitives/CMakeLists.txt
index 5563fec425bfb0df96e6ecfb081952966c0f2292..ac725ffe4497b23b57aaf0c5598394da3b95a09e 100644
--- a/Event/xAOD/xAODPrimitives/CMakeLists.txt
+++ b/Event/xAOD/xAODPrimitives/CMakeLists.txt
@@ -20,4 +20,4 @@ atlas_add_test( ut_xAOD_primitives_enums_test
    LINK_LIBRARIES xAODPrimitives )
 
 # Install files from the package.
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/ForwardDetectors/AFP/Run3AFPMonitoring/python/Run3AFPExampleMonitorAlgorithm.py b/ForwardDetectors/AFP/Run3AFPMonitoring/python/Run3AFPExampleMonitorAlgorithm.py
index 5a1c07c50c2c0806ab7934ed9b1d3e80b9750b24..3c7d444ffb6cd5e98ba40d80b95acd647c7892ae 100644
--- a/ForwardDetectors/AFP/Run3AFPMonitoring/python/Run3AFPExampleMonitorAlgorithm.py
+++ b/ForwardDetectors/AFP/Run3AFPMonitoring/python/Run3AFPExampleMonitorAlgorithm.py
@@ -12,6 +12,10 @@ def Run3AFPExampleMonitoringConfig(inputFlags):
     from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
     result = ComponentAccumulator()
 
+    # don't run in RAWtoESD
+    if inputFlags.DQ.Environment in ('tier0Raw',):
+        return result
+
     from LumiBlockComps.BunchCrossingCondAlgConfig import BunchCrossingCondAlgCfg
     result.merge(BunchCrossingCondAlgCfg(inputFlags))
     
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfig.py b/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfig.py
index a91384df66ac5edd0b2469f7b4ab7bf6a91afb0e..2b2b09cba25790105523aef717991252cd3183eb 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfig.py
+++ b/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfig.py
@@ -4,7 +4,7 @@ from __future__ import print_function
 
 from AthenaCommon import CfgMgr
 from Digitization.DigitizationFlags import digitizationFlags
-
+        
 # The earliest bunch crossing time for which interactions will be sent
 # to the Pixel Digitization code.
 def Pixel_FirstXing():
@@ -55,12 +55,24 @@ def SensorSimPlanarTool(name="SensorSimPlanarTool", **kwargs):
     from AthenaCommon.AppMgr import ToolSvc
     kwargs.setdefault("SiPropertiesTool", ToolSvc.PixelSiPropertiesTool)
     kwargs.setdefault("LorentzAngleTool", ToolSvc.PixelLorentzAngleTool)
-#    kwargs.setdefault("LorentzAngleTool", pixelLorentzAngleToolSetup.PixelLorentzAngleTool)
+    kwargs.setdefault("doRadDamage", digitizationFlags.doRadiationDamage.get_Value())
+    # TODO This is 2018 fluence setting. These parameters should be controlled by the conditions data.
+    kwargs.setdefault("fluence", 6.4)
+    kwargs.setdefault("fluenceB", 4.6)
+    kwargs.setdefault("fluence1", 2.1)
+    kwargs.setdefault("fluence2", 1.3)
+    kwargs.setdefault("voltage", 400)
+    kwargs.setdefault("voltageB", 400)
+    kwargs.setdefault("voltage1", 250)
+    kwargs.setdefault("voltage2", 250)
     return CfgMgr.SensorSimPlanarTool(name, **kwargs)
 
 def SensorSim3DTool(name="SensorSim3DTool", **kwargs):
     from AthenaCommon.AppMgr import ToolSvc
     kwargs.setdefault("SiPropertiesTool", ToolSvc.PixelSiPropertiesTool)
+    kwargs.setdefault("doRadDamage", digitizationFlags.doRadiationDamage.get_Value())
+    # TODO This is 2018 fluence setting. These parameters should be controlled by the conditions data.
+    kwargs.setdefault("fluence", 6)
     return CfgMgr.SensorSim3DTool(name, **kwargs)
 
 def SensorSimTool(name="SensorSimTool", **kwargs):
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfigNew.py b/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfigNew.py
index d01cd5f28bc865ef19459935f6185e5e71f95132..bb9daa4ff5bf9f4786a53e5400212902e73b7c31 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfigNew.py
+++ b/InnerDetector/InDetDigitization/PixelDigitization/python/PixelDigitizationConfigNew.py
@@ -83,6 +83,16 @@ def SensorSimPlanarToolCfg(flags, name="SensorSimPlanarTool", **kwargs):
     kwargs.setdefault("SiPropertiesTool", SiTool)
     kwargs.setdefault("LorentzAngleTool", LorentzTool)
     SensorSimPlanarTool = CompFactory.SensorSimPlanarTool
+    kwargs.setdefault("doRadDamage", flags.Digitization.DoRadiationDamage)
+    # TODO This is 2018 fluence setting. These parameters should be controlled by the conditions data.
+    kwargs.setdefault("fluence", 6.4)
+    kwargs.setdefault("fluenceB", 4.6)
+    kwargs.setdefault("fluence1", 2.1)
+    kwargs.setdefault("fluence2", 1.3)
+    kwargs.setdefault("voltage", 400)
+    kwargs.setdefault("voltageB", 400)
+    kwargs.setdefault("voltage1", 250)
+    kwargs.setdefault("voltage2", 250)
     acc.setPrivateTools(SensorSimPlanarTool(name, **kwargs))
     return acc
 
@@ -94,6 +104,9 @@ def SensorSim3DToolCfg(flags, name="SensorSim3DTool", **kwargs):
     acc.popToolsAndMerge(PixelLorentzAngleCfg(flags))
     kwargs.setdefault("SiPropertiesTool", SiTool)
     SensorSim3DTool = CompFactory.SensorSim3DTool
+    kwargs.setdefault("doRadDamage", flags.Digitization.DoRadiationDamage)
+    # TODO This is 2018 fluence setting. These parameters should be controlled by the conditions data.
+    kwargs.setdefault("fluence", 6)
     acc.setPrivateTools(SensorSim3DTool(name, **kwargs))
     return acc
 
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.cxx b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.cxx
index 7d783d4d5054e52dbe002662cd3e8570d88309ca..0ac99797f98f03f7b95d3bbf36ca9b9386264f2f 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.cxx
+++ b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.cxx
@@ -51,35 +51,35 @@ StatusCode SensorSim3DTool::initialize() {
 
   if (!m_doRadDamage) { m_fluence=0; }
 
-  if (m_fluence==1) {
+  if (static_cast<int>(m_fluence)==1) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_0_20V.root")); 
     m_fluence_layers.push_back(1e-10);
   }
-  else if (m_fluence==2) {
+  else if (static_cast<int>(m_fluence)==2) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_1e14_20V.root"));
     m_fluence_layers.push_back(1e14);
   }
-  else if (m_fluence==3) {
+  else if (static_cast<int>(m_fluence)==3) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_2e14_30V.root"));
     m_fluence_layers.push_back(2e14);
   }
-  else if (m_fluence==4) {
+  else if (static_cast<int>(m_fluence)==4) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_5e14_40V.root")); 
     m_fluence_layers.push_back(5e14);
   } 
-  else if (m_fluence==5) {
+  else if (static_cast<int>(m_fluence)==5) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_1e15_50V.root"));
     m_fluence_layers.push_back(1e15); 
   }
-  else if (m_fluence==6) {
+  else if (static_cast<int>(m_fluence)==6) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_5e15_160V.root"));
     m_fluence_layers.push_back(5e15);
   }
-  else if (m_fluence==7) {
+  else if (static_cast<int>(m_fluence)==7) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_6e15_190V_new.root"));       
     m_fluence_layers.push_back(6e15);
   }
-  else if (m_fluence==8) {
+  else if (static_cast<int>(m_fluence)==8) {
     mapsPath_list.push_back(PathResolverFindCalibFile("PixelDigitization/TCAD_IBL_3Dsensors_efields/phi_1e16_260V_new.root"));
     m_fluence_layers.push_back(1e16);
   }
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.h b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.h
index 34a3b8ab1206bd84088cc7b507818bef53af15e1..70b71af3106192d1d9f60b082c753beb6da71b9f 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.h
+++ b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSim3DTool.h
@@ -80,7 +80,7 @@ class SensorSim3DTool : public SensorSimTool {
     Gaudi::Property<bool> m_doChunkCorrection
     {this, "doChunkCorrection", false, "doChunkCorrection bool: should be flag"};
 
-    Gaudi::Property<int> m_fluence
+    Gaudi::Property<double> m_fluence
     {this, "fluence", 0, "this is the fluence benchmark, 0-6.  0 is unirradiated, 1 is start of Run 2, 5 is end of 2018 and 6 is projected end of 2018"};
 
     Gaudi::Property<double> m_trappingTimeElectrons
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.cxx b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.cxx
index 985ac58eebcbad5deace49ca5b680f9de8053551..df14c3d5aececbc9c238dc01ee0e660841e95da1 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.cxx
+++ b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.cxx
@@ -68,7 +68,7 @@ StatusCode SensorSimPlanarTool::initialize() {
   // For each layer one configuration
   TCADpath_list = {iblFiles, sensorFiles, sensorFiles, sensorFiles};           //IBL - 200um sensor depth, B layer - 20um, layer 1, layer 2
 
-  if (m_fluence==1) {
+  if (static_cast<int>(m_fluence)==1) {
     ATH_MSG_INFO("Use benchmark point 1!");
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_PL_80V_fl0em10.root") );  //IBL  PL - Barrel
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_PIX_250V_fl7e13.root") );    //B-Layer - Barrel                                                                                                  
@@ -85,7 +85,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(150);
     m_voltage_layers.push_back(150);
   }
-  else if (m_fluence==2) {
+  else if (static_cast<int>(m_fluence)==2) {
     ATH_MSG_INFO("Use benchmark point 2!");
 
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_PL_80V_fl1e14.root") );
@@ -103,7 +103,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(200);
     m_voltage_layers.push_back(150);
   }
-  else if (m_fluence==3) {
+  else if (static_cast<int>(m_fluence)==3) {
     ATH_MSG_INFO("Use benchmark point 3!");
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_PL_80V_fl2e14.root") );
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_PIX_350V_fl1_7e14.root") );                                                                                                            
@@ -120,7 +120,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(200);
     m_voltage_layers.push_back(150);
   }
-  else if (m_fluence==4) {
+  else if (static_cast<int>(m_fluence)==4) {
     ATH_MSG_INFO("Use benchmark point 4!");
 
     mapsPath_list.push_back(  PathResolverFindCalibFile("PixelDigitization/maps_IBL_PL_150V_fl2e14.root") );
@@ -138,7 +138,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(200);
     m_voltage_layers.push_back(150);
   }
-  else if (m_fluence==5) {
+  else if (static_cast<int>(m_fluence)==5) {
     ATH_MSG_INFO("Use benchmark point 5!");
 
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_PL_350V_fl5e14.root") );
@@ -156,7 +156,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(200);
     m_voltage_layers.push_back(150);
   }
-  else if (m_fluence==6) {
+  else if (static_cast<int>(m_fluence)==6) {
     ATH_MSG_INFO("Use benchmark point 6!");
 
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_400V_fl8_7e14.root") );
@@ -174,7 +174,7 @@ StatusCode SensorSimPlanarTool::initialize() {
     m_voltage_layers.push_back(250);
     m_voltage_layers.push_back(250);
   }
-  else if (m_fluence==7) {
+  else if (static_cast<int>(m_fluence)==7) {
     ATH_MSG_INFO("Use benchmark point 7!");
 
     mapsPath_list.push_back( PathResolverFindCalibFile("PixelDigitization/maps_IBL_endLHC.root") );
diff --git a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.h b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.h
index 2afbac5510d1990403d21d33e7bbff71b4fbadb3..3db9f5b5e22d13bca13f2be9bc14d169277d1857 100644
--- a/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.h
+++ b/InnerDetector/InDetDigitization/PixelDigitization/src/SensorSimPlanarTool.h
@@ -62,16 +62,16 @@ class SensorSimPlanarTool : public SensorSimTool {
     Gaudi::Property<double> m_trappingTimeHoles
     {this, "trappingTimeHoles", 0.0, "Characteristic time till hole is trapped [ns]"};
 
-    Gaudi::Property<int> m_fluence
+    Gaudi::Property<double> m_fluence
     {this, "fluence", 0, "this is the fluence benchmark, 0-6. 0 is unirradiated, 1 is start of Run 2, 5 is end of 2018 and 6 is projected end of 2018"};
 
-    Gaudi::Property<int> m_fluenceB
+    Gaudi::Property<double> m_fluenceB
     {this, "fluenceB", -1, "fluence detector has recieved in neqcm2 at the B layer."};
 
-    Gaudi::Property<int> m_fluence1
+    Gaudi::Property<double> m_fluence1
     {this, "fluence1", -1, "fluence detector has recieved in neqcm2 at the layer 1."};
 
-    Gaudi::Property<int> m_fluence2
+    Gaudi::Property<double> m_fluence2
     {this, "fluence2", -1, "fluence detector has recieved in neqcm2 at the layer 2."};
 
     Gaudi::Property<double> m_voltage
diff --git a/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfig.py b/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfig.py
index 5a008625ea9f6d68dc3c4130f90118a0f94fa115..e67c0a76a253c608b1802c5f17162b1e2a16bbbe 100644
--- a/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfig.py
+++ b/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfig.py
@@ -244,6 +244,11 @@ def InDetGlobalChi2Fitter(name='InDetGlobalChi2Fitter', **kwargs) :
     pix_cluster_on_track_args = stripArgs(kwargs,['SplitClusterMapExtension','ClusterSplitProbabilityName','RenounceInputHandles','nameSuffix'])
 
     from InDetRecExample import TrackingCommon as TrackingCommon
+
+    # PHF cut during fit iterations to save CPU time
+    kwargs=setDefaults(kwargs,
+                       MinPHFCut                 = TrackingCommon.getInDetNewTrackingCuts().minTRTPrecFrac()) 
+
     if 'RotCreatorTool' not in kwargs :
         kwargs=setDefaults(kwargs,
                            RotCreatorTool        = TrackingCommon.getInDetRotCreator(**pix_cluster_on_track_args))
@@ -288,6 +293,16 @@ def InDetGlobalChi2Fitter(name='InDetGlobalChi2Fitter', **kwargs) :
                            Momentum            = 1000.*Units.MeV)
     return InDetGlobalChi2FitterBase(name, **kwargs)
 
+def InDetGlobalChi2FitterBT(name='InDetGlobalChi2FitterBT', **kwargs):
+    '''
+    Global Chi2 Fitter for backtracking
+    '''
+    from InDetRecExample import TrackingCommon as TrackingCommon
+    kwargs=setDefaults(kwargs,
+                       MinPHFCut = 0.)
+    return InDetGlobalChi2Fitter(name, **kwargs)
+
+
 def InDetGlobalChi2FitterLowPt(name='InDetGlobalChi2FitterLowPt', **kwargs) :
     # @TODO TrackingGeometrySvc was not set but is set now
     #       RotCreatorTool and BroadRotCreatorTool not set
@@ -390,6 +405,13 @@ def InDetTrackFitter(name='InDetTrackFitter', **kwargs) :
         'GaussianSumFilter'       : GaussianSumFitter
     }[InDetFlags.trackFitterType()](name,**kwargs)
 
+def InDetTrackFitterBT(name='InDetTrackFitterBT', **kwargs) :
+    from InDetRecExample.InDetJobProperties import InDetFlags
+    if InDetFlags.trackFitterType() != 'GlobalChi2Fitter' :
+        return InDetTrackFitter(name,**kwargs)
+    else :
+        return InDetGlobalChi2FitterBT(name,**kwargs)
+
 def InDetTrackFitterLowPt(name='InDetTrackFitter', **kwargs) :
     from InDetRecExample.InDetJobProperties import InDetFlags
     if InDetFlags.trackFitterType() != 'GlobalChi2Fitter' :
diff --git a/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfigDb.py b/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfigDb.py
index c636839641bc3ce29b62098a1dac485d73101e53..4ebf510ac320be7263e8c62b7fbeb80918fcde77 100644
--- a/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfigDb.py
+++ b/InnerDetector/InDetExample/InDetRecExample/python/InDetRecExampleConfigDb.py
@@ -26,6 +26,7 @@ addTool('InDetRecExample.InDetRecExampleConfig.KalmanFitter','KalmanFitter')
 addTool('InDetRecExample.InDetRecExampleConfig.ReferenceKalmanFitter','ReferenceKalmanFitter')
 addTool('InDetRecExample.InDetRecExampleConfig.KalmanDNAFitter','KalmanDNAFitter')
 addTool('InDetRecExample.InDetRecExampleConfig.InDetTrackFitter','InDetTrackFitter')
+addTool('InDetRecExample.InDetRecExampleConfig.InDetTrackFitterBT','InDetTrackFitterBT')
 addTool('InDetRecExample.InDetRecExampleConfig.InDetTrackFitterLowPt','InDetTrackFitterLowPt')
 addTool('InDetRecExample.InDetRecExampleConfig.InDetTrackFitterTRT','InDetTrackFitterTRT')
 addTool('InDetRecExample.InDetRecExampleConfig.InDetTrackFitterDBM','InDetTrackFitterDBM')
diff --git a/InnerDetector/InDetExample/InDetRecExample/share/ConfiguredBackTracking.py b/InnerDetector/InDetExample/InDetRecExample/share/ConfiguredBackTracking.py
index a1c93a15d586d6b71e5689145a88c2fe4217476b..dd9ea324c1b0b5999da5c34f7af87f4754a5d9e5 100755
--- a/InnerDetector/InDetExample/InDetRecExample/share/ConfiguredBackTracking.py
+++ b/InnerDetector/InDetExample/InDetRecExample/share/ConfiguredBackTracking.py
@@ -164,7 +164,7 @@ class ConfiguredBackTracking:
          from TRT_SeededTrackFinder.TRT_SeededTrackFinderConf import InDet__TRT_SeededTrackFinder
          import InDetRecExample.TrackingCommon as TrackingCommon
          InDetTRT_SeededTrackFinder = InDet__TRT_SeededTrackFinder(name                  = 'InDetTRT_SeededTrackFinder',
-                                                                   RefitterTool          = CfgGetter.getPublicTool('InDetTrackFitter'),
+                                                                   RefitterTool          = CfgGetter.getPublicTool('InDetTrackFitterBT'),
                                                                    TrackTool             = InDetTRT_SeededTrackTool,
                                                                    PRDtoTrackMap         = prefix+'PRDtoTrackMap'+suffix \
                                                                                                if usePrdAssociationTool else "",
@@ -262,7 +262,7 @@ class ConfiguredBackTracking:
          #
          from TrkAmbiguityProcessor.TrkAmbiguityProcessorConf import Trk__SimpleAmbiguityProcessorTool
          InDetTRT_SeededAmbiguityProcessor = Trk__SimpleAmbiguityProcessorTool(name               = 'InDetTRT_SeededAmbiguityProcessor',
-                                                                               Fitter             = CfgGetter.getPublicTool('InDetTrackFitter'),
+                                                                               Fitter             = CfgGetter.getPublicTool('InDetTrackFitterBT'),
                                                                                AssociationTool    = TrackingCommon.getInDetPRDtoTrackMapToolGangedPixels(),
                                                                                TrackSummaryTool   = InDetTRT_SeededSummaryTool,
                                                                                SelectionTool      = InDetTRT_SeededAmbiTrackSelectionTool,
diff --git a/InnerDetector/InDetMonitoring/TRTMonitoringRun3/python/TRTMonitoringRun3ESD_Alg.py b/InnerDetector/InDetMonitoring/TRTMonitoringRun3/python/TRTMonitoringRun3ESD_Alg.py
index 0a9c0ae2892e8fb87c22f208a90c11e1101ddd76..eb82fe897f1b9fe36d120185bc395c1acb70c0ac 100644
--- a/InnerDetector/InDetMonitoring/TRTMonitoringRun3/python/TRTMonitoringRun3ESD_Alg.py
+++ b/InnerDetector/InDetMonitoring/TRTMonitoringRun3/python/TRTMonitoringRun3ESD_Alg.py
@@ -16,10 +16,6 @@ def TRTMonitoringRun3ESD_AlgConfig(inputFlags):
     from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
     result = ComponentAccumulator()
 
-    from TrkConfig.TrackCollectionReadConfig import TrackCollectionReadCfg
-    result.merge (TrackCollectionReadCfg (inputFlags, 'CombinedInDetTracks'))
-    result.merge (TrackCollectionReadCfg (inputFlags, 'Tracks'))
-
     from AthenaMonitoring import AthMonitorCfgHelper
     helper = AthMonitorCfgHelper(inputFlags, 'TRTMonitoringCfg')
 
@@ -221,6 +217,11 @@ if __name__ == '__main__':
     geoCfg = AtlasGeometryCfg(ConfigFlags)
     cfg.merge(geoCfg)
 
+    # Force special handling of converters
+    from TrkConfig.TrackCollectionReadConfig import TrackCollectionReadCfg
+    cfg.merge (TrackCollectionReadCfg (ConfigFlags, 'CombinedInDetTracks'))
+    cfg.merge (TrackCollectionReadCfg (ConfigFlags, 'Tracks'))
+
     TRTMonitoringRun3Acc = TRTMonitoringRun3ESD_AlgConfig(ConfigFlags)
     ServiceMgr.Dump = False
 
diff --git a/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/SiSPSeededTrackFinder/SiSPSeededTrackFinder.h b/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/SiSPSeededTrackFinder/SiSPSeededTrackFinder.h
index 1524a165a3df3db58d477328ac37813ef7e3fe01..a19cc99c6850e152f483047665507dde2021d94a 100644
--- a/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/SiSPSeededTrackFinder/SiSPSeededTrackFinder.h
+++ b/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/SiSPSeededTrackFinder/SiSPSeededTrackFinder.h
@@ -120,6 +120,8 @@ namespace InDet {
 
     SG::ReadCondHandleKey<InDet::BeamSpotData> m_beamSpotKey{this, "BeamSpotKey", "BeamSpotData", "SG key for beam spot"};
 
+    SG::ReadDecorHandleKey<xAOD::EventInfo> m_mbtsKey{this, "MBTSKey", "EventInfo.MBTSBackground"};
+
     SG::WriteHandleKey<TrackCollection> m_outputTracksKey{this, "TracksLocation", "SiSPSeededTracks"};
     //@}
 
diff --git a/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/src/SiSPSeededTrackFinder.cxx b/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/src/SiSPSeededTrackFinder.cxx
index d74fa67cbe42f49edefe32cb2f61d6fac751befb..c608055d1ec69bbe598261664aeb7cebda896c88 100644
--- a/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/src/SiSPSeededTrackFinder.cxx
+++ b/InnerDetector/InDetRecAlgs/SiSPSeededTrackFinder/src/SiSPSeededTrackFinder.cxx
@@ -28,6 +28,7 @@ InDet::SiSPSeededTrackFinder::SiSPSeededTrackFinder
 StatusCode InDet::SiSPSeededTrackFinder::initialize() 
 {
   ATH_CHECK(m_evtKey.initialize());
+  ATH_CHECK(m_mbtsKey.initialize(m_useMBTS));
   if (not m_SpacePointsPixelKey.empty()) {
     ATH_CHECK(m_SpacePointsPixelKey.initialize());
   }
diff --git a/LArCalorimeter/LArCellRec/python/LArCollisionTimeConfig.py b/LArCalorimeter/LArCellRec/python/LArCollisionTimeConfig.py
index 7f981afa82793cb861a8c08a4bc82bc64b3543f7..b78b5eb870c791433275d33ad34f058ecde859aa 100644
--- a/LArCalorimeter/LArCellRec/python/LArCollisionTimeConfig.py
+++ b/LArCalorimeter/LArCellRec/python/LArCollisionTimeConfig.py
@@ -1,16 +1,18 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # python fragment to configure LAr collision time algo
 
 from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
 from AthenaConfiguration.ComponentFactory import CompFactory
 
-def LArCollisionTimeCfg(configFlags):
+def LArCollisionTimeCfg(configFlags, cutIteration=False):
 
    result=ComponentAccumulator()
 
    LArCollisionTimeAlg=CompFactory.LArCollisionTimeAlg
-   result.addEventAlgo(LArCollisionTimeAlg("LArCollisionTimeAlg", isMC=configFlags.Input.isMC))
+   result.addEventAlgo(LArCollisionTimeAlg("LArCollisionTimeAlg", 
+                       isMC=configFlags.Input.isMC,
+                       cutIteration=cutIteration))
 
    return result   
 
diff --git a/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.cxx b/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.cxx
index 57941f2f7a60e9385b2fab962d93254214d4e5fd..d15e9b4625d89410ad463aa4a9205fcd9d789d3d 100644
--- a/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.cxx
+++ b/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "LArCollisionTimeAlg.h"
@@ -12,8 +12,6 @@ LArCollisionTimeAlg:: LArCollisionTimeAlg(const std::string& name, ISvcLocator*
     AthAlgorithm(name,pSvcLocator),
     m_calo_id(nullptr)
   {
-    declareProperty("cellContainerName", m_cellsContName="AllCalo" );
-    declareProperty("collisionTime", m_collTimeName="LArCollisionTime" );
   }
   
 //__________________________________________________________________________
diff --git a/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.h b/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.h
index b6210ae4539a1826165bab447d933426676ee4fd..518078efe522c39fac724da28b02e0b9b59856d3 100644
--- a/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.h
+++ b/LArCalorimeter/LArCellRec/src/LArCollisionTimeAlg.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 // TheLArCollisionsAlg.h
@@ -46,13 +46,13 @@ class LArCollisionTimeAlg : public AthAlgorithm {
   // Properties
   // --------------------------------------------------
   Gaudi::Property<bool>  m_isMC     { this, "isMC", false, "Are we working with simu?" };
-  Gaudi::Property<bool>  m_iterCut  { this, "cutIteration", true, "cut on OFC iteration, will not work for Online" };
+  Gaudi::Property<bool>  m_iterCut  { this, "cutIteration", false, "cut on OFC iteration, will not work for Online" };
   Gaudi::Property<float> m_timeCut  { this, "timeDiffCut", 5., "|A-C| time < timeDiffCut to pass the filter" };
   Gaudi::Property<int>   m_minCells { this, "nCells", 2, "min. number of cells per endcap to pass the filter" };
 
 
-  SG::ReadHandleKey<CaloCellContainer> m_cellsContName;
-  SG::WriteHandleKey<LArCollisionTime> m_collTimeName;
+  SG::ReadHandleKey<CaloCellContainer> m_cellsContName{this,"cellContainerName","AllCalo"};
+  SG::WriteHandleKey<LArCollisionTime> m_collTimeName{this,"collisionTime","LArCollisionTime"};
   SG::ReadCondHandleKey<CaloNoise> m_noiseCDOKey{this,"CaloNoiseKey","totalNoise","SG Key of CaloNoise data object"};
 
 };
diff --git a/LArCalorimeter/LArConfiguration/python/LArMonitoringConfig.py b/LArCalorimeter/LArConfiguration/python/LArMonitoringConfig.py
index d5c8d636413b540d922bf0bb613bea008839cbbf..29830d9744436b832bc09c725f92b455a2e0bb24 100644
--- a/LArCalorimeter/LArConfiguration/python/LArMonitoringConfig.py
+++ b/LArCalorimeter/LArConfiguration/python/LArMonitoringConfig.py
@@ -18,18 +18,18 @@ def LArMonitoringConfig(inputFlags):
     from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator
     acc = ComponentAccumulator()
     
-    if not inputFlags.Input.isMC:
-         acc.merge(LArAffectedRegionsConfig(inputFlags))
-         acc.merge(LArNoisyROMonConfig(inputFlags))
-         if 'online' not in inputFlags.DQ.Environment:
-            acc.merge(LArHVCorrMonConfig(inputFlags))
-
     # algos which can run in ESD but not AOD:
     if inputFlags.DQ.Environment != 'AOD':
         if inputFlags.DQ.DataType != 'cosmics':
             from LumiBlockComps.BunchCrossingCondAlgConfig import BunchCrossingCondAlgCfg
             acc.merge(BunchCrossingCondAlgCfg(inputFlags))
             acc.merge(LArCollisionTimeMonConfig(inputFlags))
+        if not inputFlags.Input.isMC:
+            acc.merge(LArNoisyROMonConfig(inputFlags))
+            acc.merge(LArAffectedRegionsConfig(inputFlags))
+            if 'online' not in inputFlags.DQ.Environment:
+                acc.merge(LArHVCorrMonConfig(inputFlags))
+
 
     # and others on RAW data only
     if inputFlags.DQ.Environment in ('online', 'tier0', 'tier0Raw'):
diff --git a/LArCalorimeter/LArMonitoring/python/LArCollisionTimeMonAlg.py b/LArCalorimeter/LArMonitoring/python/LArCollisionTimeMonAlg.py
index 432bee17c98166fb8f1a4639a1182a4856fe7806..88eb02c0a98622e1a3fe271f1a465a172828671f 100644
--- a/LArCalorimeter/LArMonitoring/python/LArCollisionTimeMonAlg.py
+++ b/LArCalorimeter/LArMonitoring/python/LArCollisionTimeMonAlg.py
@@ -269,8 +269,7 @@ if __name__=='__main__':
 
     # try collision time algo 
     from LArCellRec.LArCollisionTimeConfig import LArCollisionTimeCfg
-    cfg.merge(LArCollisionTimeCfg(ConfigFlags))
-    cfg.getEventAlgo("LArCollisionTimeAlg").cutIteration=False
+    cfg.merge(LArCollisionTimeCfg(ConfigFlags, cutIteration=False))
     # add cluster collision time algo
     # cluster config is still missing
     #from LArClusterRec.LArClusterSwConfig import LArClusterSwConfig
diff --git a/LArCalorimeter/LArMonitoring/python/LArReco_fromraw_Cfg.py b/LArCalorimeter/LArMonitoring/python/LArReco_fromraw_Cfg.py
index 8a2b376c7a69d11447568e50a4952428784b14cb..9e7110b92ca90cc5f2942940ac204605a4ea5ecb 100644
--- a/LArCalorimeter/LArMonitoring/python/LArReco_fromraw_Cfg.py
+++ b/LArCalorimeter/LArMonitoring/python/LArReco_fromraw_Cfg.py
@@ -38,8 +38,7 @@ if __name__=="__main__":
 
    #collision time algo 
    from LArCellRec.LArCollisionTimeConfig import LArCollisionTimeCfg
-   cfg.merge(LArCollisionTimeCfg(ConfigFlags))
-   cfg.getEventAlgo("LArCollisionTimeAlg").cutIteration=False
+   cfg.merge(LArCollisionTimeCfg(ConfigFlags, cutIteration=False))
 
    # and collision time monitoring algo
    from LArMonitoring.LArCollisionTimeMonAlg import LArCollisionTimeMonConfig
diff --git a/MuonSpectrometer/MuonDigitization/MM_Digitization/MM_Digitization/VMM_Shaper.h b/MuonSpectrometer/MuonDigitization/MM_Digitization/MM_Digitization/VMM_Shaper.h
index 3798409d2d776de38d5091d5b6214a68a2fc96f7..4def653f55ca39a53c6d4ff82f3b8fe8a1e38a9f 100644
--- a/MuonSpectrometer/MuonDigitization/MM_Digitization/MM_Digitization/VMM_Shaper.h
+++ b/MuonSpectrometer/MuonDigitization/MM_Digitization/MM_Digitization/VMM_Shaper.h
@@ -5,40 +5,40 @@
 #ifndef MM_DIGITIZATION_VMM_SHAPER_H
 #define MM_DIGITIZATION_VMM_SHAPER_H
 
-#include <TH1F.h>
 #include <vector>
 
 
 class VMM_Shaper{
  public:
-    VMM_Shaper(float peakTime);
+    VMM_Shaper(const float peakTime, const float lowerTimeWindow, const float upperTimeWindow);
     virtual ~VMM_Shaper()=default;
 
     void initialize();
 
-    void vmmPeakResponse(const std::vector<float> effectiveCharge, const std::vector<float> electronsTime, const double electronicsThreshold, double &amplitudeFirstPeak, double &timeFirstPeak) const;
-    void vmmThresholdResponse(const std::vector<float> effectiveCharge, const std::vector<float> electronsTime, const double electronicsThreshold, double &amplitudeAtFirstPeak, double &timeAtThreshold) const;
+    void vmmPeakResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold, double &amplitudeFirstPeak, double &timeFirstPeak) const;
+    void vmmThresholdResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold, double &amplitudeAtFirstPeak, double &timeAtThreshold) const;
 
-    bool hasChargeAboveThreshold(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double &electronicsThreshold) const;
+    bool hasChargeAboveThreshold(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const;
 
 
  private:
      double m_peakTime;
-     double m_timeStep;
-     double m_maxTime;
-
+     double m_lowerTimeWindow, m_upperTimeWindow;
+     
+     double m_timeStep, m_inverseTimeStep;
 
+     double m_preCalculationVMMShaper; 
      // shaper parameters
      double m_a, m_pole0, m_re_pole1, m_im_pole1, m_pole1_square, m_k1_abs, m_argK1;
      int m_nBins;
 
      double m_peakTimeChargeScaling;
 
-     void vmmResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, TH1F &response) const;
-     int findPeak(const TH1F &response, const double &electronicsThreshold) const;
-
+     double vmmResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, double time) const;
+     double findPeak(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const;
+     bool aboveThresholdSimple(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const;
 
 
 };
 
-#endif  // MM_DIGITIZATION_VMM_SHAPER_H
\ No newline at end of file
+#endif  // MM_DIGITIZATION_VMM_SHAPER_H
diff --git a/MuonSpectrometer/MuonDigitization/MM_Digitization/src/MM_ElectronicsResponseSimulation.cxx b/MuonSpectrometer/MuonDigitization/MM_Digitization/src/MM_ElectronicsResponseSimulation.cxx
index e227749c34319986071a7223a82eac2e9b7061b4..c47bbbbcf8a11a60da40c4620f42fa4774a8393f 100644
--- a/MuonSpectrometer/MuonDigitization/MM_Digitization/src/MM_ElectronicsResponseSimulation.cxx
+++ b/MuonSpectrometer/MuonDigitization/MM_Digitization/src/MM_ElectronicsResponseSimulation.cxx
@@ -29,7 +29,7 @@ MM_ElectronicsResponseSimulation::MM_ElectronicsResponseSimulation():
 /*******************************************************************************/
 void MM_ElectronicsResponseSimulation::initialize()
 {
-  m_vmmShaper = std::make_unique<VMM_Shaper>(m_peakTime);
+  m_vmmShaper = std::make_unique<VMM_Shaper>(m_peakTime, m_timeWindowLowerOffset, m_timeWindowUpperOffset);
   m_vmmShaper->initialize();
 }
 /*******************************************************************************/
diff --git a/MuonSpectrometer/MuonDigitization/MM_Digitization/src/VMM_Shaper.cxx b/MuonSpectrometer/MuonDigitization/MM_Digitization/src/VMM_Shaper.cxx
index d27d7e2dfdf57e4936701b73fa30fcbad721d76e..39d0763c2ab71b15c51ad1432226b15fc35274cc 100644
--- a/MuonSpectrometer/MuonDigitization/MM_Digitization/src/VMM_Shaper.cxx
+++ b/MuonSpectrometer/MuonDigitization/MM_Digitization/src/VMM_Shaper.cxx
@@ -4,6 +4,7 @@
 
 #include "MM_Digitization/VMM_Shaper.h"
 #include <cmath>
+#include <algorithm>
 
 namespace {
     // VMM shaper parameters provided by G. Iakovidis
@@ -16,10 +17,12 @@ namespace {
     static constexpr double mmIonFlowTime = 150.;  // ns
 }
 
-VMM_Shaper::VMM_Shaper(float peakTime):m_peakTime(peakTime),
-m_timeStep(0.1),
-m_maxTime(700.0)
+VMM_Shaper::VMM_Shaper(const float peakTime,const float lowerTimeWindow,const float upperTimeWindow):m_peakTime(peakTime),
+m_lowerTimeWindow(lowerTimeWindow),
+m_upperTimeWindow(upperTimeWindow),
+m_timeStep(0.1)
 {
+    m_inverseTimeStep = 1./m_timeStep;
     initialize();
 }
 
@@ -33,80 +36,138 @@ void VMM_Shaper::initialize() {
     m_k1_abs = std::sqrt(Re_K1*Re_K1 + Im_K1*Im_K1);
     m_argK1 = std::atan2(Im_K1, Re_K1);
 
-    m_nBins = m_maxTime/m_timeStep;
     // scale factor for charge taking into account the mm ion flow time of ~150ns
     // if the peaking time is lower then that, only a fration of the total charge is integrated
     m_peakTimeChargeScaling = (m_peakTime < mmIonFlowTime ? 1.0*m_peakTime/mmIonFlowTime : 1.0);
+    
+    // preCalculate factor to avoid recalculating for each electron
+    m_preCalculationVMMShaper = chargeScaleFactor*m_peakTimeChargeScaling*std::pow(m_a, 3)*m_pole0*m_pole1_square;
 }
 
-void VMM_Shaper::vmmResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, TH1F &response) const {
-    for (uint i_electron = 0; i_electron < effectiveCharge.size(); i_electron++) {
-        for (double ti = electronsTime[i_electron]; ti < m_maxTime; ti += m_timeStep) {
-            double t = (ti-electronsTime.at(i_electron))*(10^-9);
+double VMM_Shaper::vmmResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, double time) const{
+    double response = 0;
+    for (unsigned int i_electron = 0; i_electron < effectiveCharge.size(); i_electron++) {
+            if (time < electronsTime.at(i_electron)) continue;
+            double t = (time-electronsTime.at(i_electron))*(10^-9);
             // now follows the vmm shaper response function provided by G. Iakovidis
             // It is described in section 7.1.3 of https://cds.cern.ch/record/1955475
-            double st = effectiveCharge.at(i_electron)*chargeScaleFactor*m_peakTimeChargeScaling*std::pow(m_a, 3)*m_pole0*m_pole1_square*((K0*std::exp(-t*m_pole0))+(2.*m_k1_abs*std::exp(-t*m_re_pole1)*std::cos(-t*m_im_pole1+m_argK1)));
-            response.Fill(ti, st);
-        }
+            double st = effectiveCharge.at(i_electron)*m_preCalculationVMMShaper*((K0*std::exp(-t*m_pole0))+(2.*m_k1_abs*std::exp(-t*m_re_pole1)*std::cos(-t*m_im_pole1+m_argK1)));
+            response += st;
     }
+    return response;
 }
 
-void VMM_Shaper::vmmPeakResponse(const std::vector<float> effectiveCharge, const std::vector<float> electronsTime, const double electronicsThreshold, double &amplitudeFirstPeak, double &timeFirstPeak) const {
-    TH1F response("response", "response", m_nBins, 0, m_maxTime);
+void VMM_Shaper::vmmPeakResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold, double &amplitudeFirstPeak, double &timeFirstPeak) const{
+    double t_peak = findPeak(effectiveCharge, electronsTime, electronicsThreshold);
+    
+    if (t_peak == -9999 ) return;  // no peak found
 
-    vmmResponse(effectiveCharge, electronsTime, response);
-    int i_bin_peak = findPeak(response, electronicsThreshold);
+    amplitudeFirstPeak = vmmResponse(effectiveCharge, electronsTime, t_peak);
+    timeFirstPeak = t_peak;
+}
 
-    if (i_bin_peak == -1) return;  // no peak found
 
-    timeFirstPeak = response.GetXaxis()->GetBinCenter(i_bin_peak);
-    amplitudeFirstPeak = response.GetBinContent(i_bin_peak);
-}
+void VMM_Shaper::vmmThresholdResponse(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold, double &amplitudeAtFirstPeak, double &timeAtThreshold) const {
+    if (!aboveThresholdSimple(effectiveCharge, electronsTime, electronicsThreshold)) return;
 
+    if (effectiveCharge.size() == 0) return;  // protect min_element
+    double startTime = m_lowerTimeWindow;
+    double minElectronTime = *std::min_element(electronsTime.begin(), electronsTime.end());
+    if (startTime < minElectronTime) startTime = minElectronTime;  // if smallest strip times are higher then the lower time window, just start the loop from the smallest electron time
+
+    double tmpTimeAtThreshold = -9999;
+    for (double time = startTime; time < m_upperTimeWindow; time += m_timeStep) {
+        if (vmmResponse(effectiveCharge, electronsTime, time) >= electronicsThreshold) {
+            tmpTimeAtThreshold = time;
+            break;
+        }
+    }
 
-void VMM_Shaper::vmmThresholdResponse(const std::vector<float> effectiveCharge, const std::vector<float> electronsTime, const double electronicsThreshold, double &amplitudeAtFirstPeak, double &timeAtThreshold) const {
-    TH1F response("response", "response", m_nBins, 0, m_maxTime);
+    if (tmpTimeAtThreshold == -9999) return;
 
-    vmmResponse(effectiveCharge, electronsTime, response);
-    int i_bin_peak = findPeak(response, electronicsThreshold);
+    double t_peak = findPeak(effectiveCharge, electronsTime, electronicsThreshold);
+    if (t_peak == -9999) return;
 
-    int binAboveThreshold = response.FindFirstBinAbove(electronicsThreshold);
-    if (binAboveThreshold == -1) return;
-    timeAtThreshold = response.GetXaxis()->GetBinCenter(binAboveThreshold);
-    amplitudeAtFirstPeak = response.GetBinContent(i_bin_peak);
+    timeAtThreshold = tmpTimeAtThreshold;
+    amplitudeAtFirstPeak = vmmResponse(effectiveCharge, electronsTime, t_peak);
 }
 
 
-int VMM_Shaper::findPeak(const TH1F &response, const double &electronicsThreshold) const{
-    TH1F derivative("derivative", "derivative", m_nBins, 0, m_maxTime);
+double VMM_Shaper::findPeak(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const{
+    if(effectiveCharge.size()==0) return -9999; // protect min_element
+    double startTime = m_lowerTimeWindow;
+    double minElectronTime = *std::min_element(electronsTime.begin(), electronsTime.end());
+    if(startTime < minElectronTime) startTime = minElectronTime; // if smallest strip times are higher then the lower time window, just start the loop from the smallest electron time
+
+    double oldResponse = 0;
+    double oldDerivative = 0 , currentDerivative = 0;
+
+    for (double time = startTime; time < m_upperTimeWindow; time += m_timeStep) {
+
+        double response = vmmResponse(effectiveCharge, electronsTime, time);
+
+        oldDerivative = currentDerivative;
+        currentDerivative = (response-oldResponse) * m_inverseTimeStep;
+        //  check if sign of derivative has not changed ==> no peak;  or if response is below threshold
+        if (oldDerivative*currentDerivative >= 0 || oldResponse < electronicsThreshold) {oldResponse = response; continue;}
+
+        // from here one its assumed that a peak above threshold was found
+
+        //  check if the derivative is monoton falling within the given window of 5 bins
+        bool checkDerivative = true;
+        double tmp_checkOldDerivative = 0, tmp_checkCurrentDerivative = 0;
+        double tmp_checkOldResponse = 0;
 
-    // First the derivative gets calculated, then its zero crossing is searched for
-    // if in 4 bins around the 0 crossing the derivative is falling, it is accepted as peak
+        int searchWindow = 5;
 
-    for(int i_bin = 1; i_bin<m_nBins; i_bin++){
-        derivative.SetBinContent(i_bin, (response.GetBinContent(i_bin+1) - response.GetBinContent(i_bin)) / response.GetXaxis()->GetBinWidth(i_bin));
+        for (int i_timeOfPeak = -searchWindow; i_timeOfPeak <= searchWindow; i_timeOfPeak ++) {
+           double response = vmmResponse(effectiveCharge, electronsTime, time + i_timeOfPeak * m_timeStep);
+
+           tmp_checkOldDerivative = tmp_checkCurrentDerivative;
+           tmp_checkCurrentDerivative = (response - tmp_checkOldResponse) * m_inverseTimeStep;
+           tmp_checkOldResponse = response;
+
+           if (i_timeOfPeak >= -searchWindow + 2  // needs two iterations to fill the variables
+                && tmp_checkOldDerivative < tmp_checkCurrentDerivative) {  // derivative is not falling monothonic
+               checkDerivative = false;
+               break;
+           }
+        }
+        if (!checkDerivative) continue;
+        return time - m_timeStep;
     }
+    return -9999;  // no peak found
+}
+
+
+bool VMM_Shaper::hasChargeAboveThreshold(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const{
+    if (!aboveThresholdSimple(effectiveCharge, electronsTime, electronicsThreshold)) return false;
 
-    for (int i_bin = 1; i_bin < m_nBins; i_bin++) {
-        if (derivative.GetBinContent(i_bin) * derivative.GetBinContent(i_bin + 1) > 0.0) continue;  //  continue loop if no 0 crossing was there
-        if (response.GetBinContent(i_bin + 1) < electronicsThreshold) continue;  //  continue if peak is below threshold
-        bool derivativeCut = true;
-        for (int j_bin = i_bin-2; j_bin <= i_bin + 2; j_bin++) {
-            if (derivative.GetBinContent(j_bin) <= derivative.GetBinContent(j_bin+1)) {  // check that the derivative is falling for 4 bins around the 0 crossing
-                derivativeCut = false;
-            }
-            if (derivativeCut) {
-                return i_bin + 1;
-            }
+    if (effectiveCharge.size() == 0) return false;  // protect min_element
+    double startTime = m_lowerTimeWindow;
+    double minElectronTime = *std::min_element(electronsTime.begin(), electronsTime.end());
+    // since we are only checking if signal is above threshold, we can start searching close to the peak
+    minElectronTime += m_peakTime * 0.8;
+    if (startTime < minElectronTime) startTime = minElectronTime;  // if smallest strip times are higher then the lower time window, just start the loop from the smallest electron time
+
+    for (double time = startTime; time < m_upperTimeWindow; time += m_timeStep) {
+        if (vmmResponse(effectiveCharge, electronsTime, time) >= electronicsThreshold) {
+           return true;
         }
     }
-    return -1;
+    return false;
+
 }
 
 
-bool VMM_Shaper::hasChargeAboveThreshold(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double &electronicsThreshold) const {
-    TH1F response("response", "response", m_nBins, 0, m_maxTime);
-    vmmResponse(effectiveCharge, electronsTime, response);
-    int i_aboveThreshold = response.FindFirstBinAbove(electronicsThreshold);
-    return i_aboveThreshold > 0;
-}
\ No newline at end of file
+bool VMM_Shaper::aboveThresholdSimple(const std::vector<float> &effectiveCharge, const std::vector<float> &electronsTime, const double electronicsThreshold) const {
+    // check if total strip charge is above threshold, otherwise skip VMM
+    float chargeSum = 0;
+    for (unsigned int i_elec = 0; i_elec < effectiveCharge.size(); i_elec++) {
+        if (electronsTime.at(i_elec) >= m_lowerTimeWindow - m_peakTime && electronsTime.at(i_elec) <= m_upperTimeWindow) {
+            chargeSum += effectiveCharge.at(i_elec)*m_peakTimeChargeScaling;
+        }
+    }
+    if (chargeSum >= electronicsThreshold) return true;
+    return false;
+}
diff --git a/MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/TgcRawDataMonitoring/python/TgcRawDataMonitorAlgorithm.py b/MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/TgcRawDataMonitoring/python/TgcRawDataMonitorAlgorithm.py
index 617f0a5b3c988c6bc2004b8f1fe3cfdca1dfa576..6fbcd4d033bbd2acf26d28cfbd23e29a522337e3 100644
--- a/MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/TgcRawDataMonitoring/python/TgcRawDataMonitorAlgorithm.py
+++ b/MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/TgcRawDataMonitoring/python/TgcRawDataMonitorAlgorithm.py
@@ -37,9 +37,11 @@ def TgcRawDataMonitoringConfig(inputFlags):
     if not inputFlags.DQ.triggerDataAvailable:
         tgcRawDataMonAlg.MuonRoIContainerName = ''
 
-    if 'HLT_xAOD__MuonContainer_MuonEFInfo' in inputFlags.Input.Collections:
+    isBS = (inputFlags.Input.Format == 'BS')
+    # if input is raw data, objects won't be in input collections
+    if (isBS and inputFlags.DQ.triggerDataAvailable) or 'HLT_xAOD__MuonContainer_MuonEFInfo' in inputFlags.Input.Collections:
         tgcRawDataMonAlg.MuonEFContainerName='HLT_xAOD__MuonContainer_MuonEFInfo'
-    if 'TGC_MeasurementsAllBCs' in inputFlags.Input.Collections:
+    if isBS or 'TGC_MeasurementsAllBCs' in inputFlags.Input.Collections:
         tgcRawDataMonAlg.AnaTgcPrd=True
     
     mainDir = 'Muon/MuonRawDataMonitoring/TGC/'
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/CMakeLists.txt
index e8b2857f8bb11fecb6cca5421cdc75294f2cc4ca..aacb71eaac743229e5f8e4aca27fbb10c7398260 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/CMakeLists.txt
@@ -9,4 +9,4 @@ atlas_add_component( DerivationFrameworkCalo
                      LINK_LIBRARIES LINK_LIBRARIES AthenaBaseComps CaloClusterCorrectionLib CaloEvent CaloGeoHelpers CaloIdentifier CaloUtilsLib DerivationFrameworkInterfaces ExpressionEvaluationLib FourMomUtils GaudiKernel LArCablingLib StoreGateLib xAODBase xAODCaloEvent xAODEgamma xAODJet xAODMuon xAODTau )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/python/CaloCellDFGetter.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/python/CaloCellDFGetter.py
index 4f03e5e967c367712868318057f4483afbe84075..13e4b469736671e1283780005013c233ca74b0c8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/python/CaloCellDFGetter.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCalo/python/CaloCellDFGetter.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #==========================================================================================
 #This is basically based in the  Calorimeter/CaloRec/python/CaloCellAODGetter.py (used for ESD to AOD)
@@ -38,8 +38,6 @@
 # to write extra cell for e/gamma
 #==========================================================================================
 
-from AthenaCommon.Constants import *  
-from RecExConfig.Configured import Configured
 from AthenaCommon.AlgSequence import AlgSequence
 topSequence=AlgSequence()
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/CMakeLists.txt
index cd274a1e3c6524b2412345249a879dd59c8936f4..7f742b3ecd24355d228640d7e58561fe5a54d7f2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/CMakeLists.txt
@@ -9,6 +9,6 @@ atlas_add_component( DerivationFrameworkCore
                      LINK_LIBRARIES AsgAnalysisInterfaces AthAnalysisBaseCompsLib AthContainers AthLinks AthenaKernel DerivationFrameworkInterfaces GoodRunsListsLib PathResolver SGTools TrigDecisionToolLib TriggerMatchingToolLib xAODBase xAODEgamma xAODEventInfo xAODMuon )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 atlas_install_scripts( scripts/frozen_derivation_test.py )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ContentHandler.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ContentHandler.py
index 898d991d6c06d8c734c4634425d71f742c7a0b03..6af0970e7b11e84fa044fd2f097aeae612a63011 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ContentHandler.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ContentHandler.py
@@ -21,7 +21,7 @@ class ContentHandler:
 		if containerName in theDictionary.keys():
 			line = theDictionary[containerName]+"#"+containerName
 		else:
-			msg.warning('Collection with name %s not found in input file or in definitions from user. No action will be taken for this collection.' % containerName)
+			msg.warning('Collection with name %s not found in input file or in definitions from user. No action will be taken for this collection.', containerName)
 		return line
 		
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkMaster.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkMaster.py
index 90a0af470a936ad8e7baee65a2cc66da845dd320..2a364ea7a57b9a7a4b43f9113b5f80c716de47d2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkMaster.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkMaster.py
@@ -7,17 +7,11 @@
 # Contains all basic includes for running the derivation framework
 #-------------------------------------------------------------
 
-from __future__ import print_function
-
-from AthenaCommon.AppMgr import ToolSvc
 from AthenaCommon.AppMgr import theApp
 # Derivation names and locations of job options
-from DerivationFrameworkCore.DerivationFrameworkProdFlags import derivationFlags
-# Multiple stream manager
-from OutputStreamAthenaPool.MultipleStreamManager import MSMgr
+from DerivationFrameworkCore.DerivationFrameworkProdFlags import derivationFlags  # noqa: F401
 # Athena common properties
-from AthenaCommon.JobProperties import jobproperties
-from AthenaCommon import CfgMgr 
+from AthenaCommon import CfgMgr
 from AthenaCommon.AlgSequence import AlgSequence 
 from JetRec.JetRecFlags import jetFlags 
 from AthenaCommon.GlobalFlags  import globalflags
@@ -26,7 +20,7 @@ from AthenaCommon.AppMgr import ServiceMgr as svcMgr
 
 import os
 if "AthAnalysisBase" not in os.environ.get("CMTEXTRATAGS",""):
-  from AODFix.AODFix import *
+  from AODFix.AODFix import *  # noqa: F401, F403
 
 # Trap for ROOT6 errors
 theApp.CreateSvc += ["AthROOTErrorHandlerSvc"]
@@ -60,11 +54,12 @@ if inputFileSummary is not None:
 # Set up the metadata tool:
 if not globalflags.InputFormat=="bytestream":
     # Extra config: make sure if we are using EVNT that we don't try to check sim/digi/reco metadata 
-    from RecExConfig.ObjKeyStore import objKeyStore
+#    from RecExConfig.ObjKeyStore import objKeyStore
 #    ToolSvc += CfgMgr.xAODMaker__FileMetaDataCreatorTool( "FileMetaDataCreatorTool",
 #                                  isEVNT = objKeyStore.isInInput( "McEventCollection", "GEN_EVENT" ),
 #                                  OutputLevel = 2 )
 #    svcMgr.MetaDataSvc.MetaDataTools += [ ToolSvc.FileMetaDataCreatorTool ]
+     pass
 
 # Set up stream auditor
 if not hasattr(svcMgr, 'DecisionSvc'):
@@ -95,7 +90,7 @@ if globalflags.DataSource()=='geant4':
         # Make sure input file is not EVNT
         if not objKeyStore.isInInput( "McEventCollection", "GEN_EVENT" ):
             DerivationFrameworkSimBarcodeOffset = int(inputFileSummary['metadata']['/Simulation/Parameters']['SimBarcodeOffset'])
-    except:
+    except Exception:
         print ('Could not retrieve SimBarcodeOffset from /Simulation/Parameters, leaving at 200k')
 
 def buildFileName(derivationStream):
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkProdFlags.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkProdFlags.py
index 9ca72cb748a521400fdf4fcb27cd13a8b0e3fcd5..765154d5141db0e5140308b300302912a170892d 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkProdFlags.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/DerivationFrameworkProdFlags.py
@@ -1,4 +1,4 @@
-# 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 AthenaCommon.JobProperties import JobProperty, JobPropertyContainer
 from AthenaCommon.JobProperties import jobproperties
@@ -914,7 +914,7 @@ jobproperties.DerivationFrameworkProdFlags.add_JobProperty(WriteDAOD_STDM11Strea
 listAODtoDPD.append(WriteDAOD_STDM11Stream.StreamName)
 
 class WriteDAOD_STDM12Stream (JobProperty):
-    """Derivation for B\pm fragmentation, Photon + B\pm, J/psi and Upsilon fragmentation measurements"""
+    """Derivation for B+- fragmentation, Photon + B+-, J/psi and Upsilon fragmentation measurements"""
     statusOn = True
     allowedTypes = ['bool']
     StoredValue = False
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/LHE3WeightMetadata.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/LHE3WeightMetadata.py
index 8e3f0e174e5c02a550be6760adddc1373cb7508c..f5e8c07f0745811f576ee6d1a4fa9503303a1426 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/LHE3WeightMetadata.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/LHE3WeightMetadata.py
@@ -1,13 +1,11 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
 import operator
 import json 
 def addLHE3Weights(seq, pref = '', var_dict = {}):
   
   from AthenaCommon.AppMgr import ToolSvc
-  from ReweightUtils.ReweightUtilsConf import SumOfWeightsAlg
+  from ReweightUtils.ReweightUtilsConf import SumOfWeightsAlg, McEventWeight
 
   sumOfWeightsAlg = SumOfWeightsAlg(name = pref+"LHE3SumWeightsAlg")
 
@@ -24,7 +22,7 @@ def addLHE3Weights(seq, pref = '', var_dict = {}):
   seq += sumOfWeightsAlg
 
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 # skip this in datfrom AthenaCommon.GlobalFlags import globalflags
 from AthenaCommon.GlobalFlags import globalflags
@@ -33,8 +31,9 @@ if globalflags.DataSource() == 'geant4':
   mcweight_dict_orig = dict()
   mcweight_dict = dict()
   try:
+    from RecExConfig.InputFilePeeker import inputFileSummary
     mcweight_dict_orig = inputFileSummary['metadata']['/Generation/Parameters']['HepMCWeightNames']
-  except:
+  except Exception:
     print ('Could not retrieve HepMCWeightNames /Generation/Parameters metadata.')
   
   # Recent versions of MadGraph are writing the dictionary as a flat string
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/SlimmingHelper.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/SlimmingHelper.py
index a0dcba819a6a0b94812342885c931070aecccaec..0200eb94cca4b4350245088bade746db68df530c 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/SlimmingHelper.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/SlimmingHelper.py
@@ -34,17 +34,13 @@
 # may be unreadable.
 ####################################################################
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.CompulsoryContent import *
-from DerivationFrameworkCore.ContentHandler import *
+from DerivationFrameworkCore.CompulsoryContent import CompulsoryContent, CompulsoryTriggerNavigation
+from DerivationFrameworkCore.ContentHandler import ContentHandler
 from DerivationFrameworkCore.ContainersForExpansion import ContainersForExpansion
 from DerivationFrameworkCore.ContainersOnTheFly import ContainersOnTheFly
 from DerivationFrameworkCore.AllVariablesDisallowed import AllVariablesDisallowed
 from DerivationFrameworkCore.FullListOfSmartContainers import FullListOfSmartContainers
 from DerivationFrameworkCore.PreliminarySmartContainers import PreliminarySmartContainers
-from AthenaCommon.BeamFlags import jobproperties
-from AthenaCommon.GlobalFlags  import globalflags
 import PyUtils.Logging as L
 msg = L.logging.getLogger('DerivationFramework__SlimmingHelper')
 msg.setLevel(L.logging.INFO)
@@ -56,13 +52,13 @@ class lockable_list(list):
                 list.__init__(self,data)
                 self.__dict__["_locked"] = False
         def append(self,name):
-                if self._locked == True:
+                if self._locked is True:
                         msg.error("Attempting to Modify SlimmingHelper after AppendContentToStream has Been Called")
                         raise RuntimeError("Late Modification to SlimmingHelper do not modify after calling AppendContentToStream")
                 else:
                         return list.append(self, name)
         def __setattr__(self,name,value):
-                if self._locked==True:
+                if self._locked is True:
                         msg.error("Attempting to Modify SlimmingHelper after AppendContentToStream has Been Called")
                         raise RuntimeError("Late Modification to SlimmingHelper do not modify after calling AppendContentToStream")
                 else:
@@ -107,7 +103,7 @@ class SlimmingHelper:
 
         # This hack prevents any members from being modified after lock is set to true, this happens in AppendContentToStream
         def __setattr__(self,name,value):
-                if self._locked==True:
+                if self._locked is True:
                         msg.error("Attempting to Modify SlimmingHelper "+self.name+" After AppendContentToStream has Been Called")
                         raise RuntimeError("Late Modification to SlimmingHelper, do not modifiy after calling AppendContentToStream")
                 elif type(value)==list:
@@ -157,44 +153,44 @@ class SlimmingHelper:
                 # Trigger objects: add them by hand to the smart collection list (to keep the previous interface)
                 triggerContent = False
 
-                if (self.IncludeAdditionalTriggerContent == True):
+                if (self.IncludeAdditionalTriggerContent is True):
                         triggerContent = True
 
-                if (self.IncludeMuonTriggerContent == True):
+                if (self.IncludeMuonTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__MuonContainer_MuonEFInfo")
 
-                if (self.IncludeEGammaTriggerContent == True):
+                if (self.IncludeEGammaTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__PhotonContainer_egamma_Photons")
 
-                if (self.IncludeJetTriggerContent == True):
+                if (self.IncludeJetTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__JetContainer_a4tcemsubjesFS")
                         from DerivationFrameworkCore.JetTriggerFixContent import JetTriggerFixContent
                         for item in JetTriggerFixContent:
                                 Stream.AddItem(item)
 
-                if (self.IncludeEtMissTriggerContent == True):
+                if (self.IncludeEtMissTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__TrigMissingETContainer_TrigEFMissingET")
                         from DerivationFrameworkCore.EtMissTriggerFixContent import EtMissTriggerFixContent
                         for item in EtMissTriggerFixContent:
                                 Stream.AddItem(item)
 
-                if (self.IncludeTauTriggerContent == True):
+                if (self.IncludeTauTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__TauJetContainer_TrigTauRecMerged")
 
-                if (self.IncludeBJetTriggerContent == True):
+                if (self.IncludeBJetTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__BTaggingContainer_HLTBjetFex")
 
-                if (self.IncludeBPhysTriggerContent == True):
+                if (self.IncludeBPhysTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__TrigBphysContainer_EFBMuMuFex")
 
-                if (self.IncludeMinBiasTriggerContent == True):
+                if (self.IncludeMinBiasTriggerContent is True):
                         triggerContent = True
                         self.SmartCollections.append("HLT_xAOD__TrigVertexCountsContainer_vertexcounts")
 
@@ -270,13 +266,13 @@ class SlimmingHelper:
 
                 # Add trigger item (not covered by smart slimming so no expansion)
                 # Old, will be removed (kept just to not break some deriavtions)
-                if (self.IncludeJetTauEtMissTriggerContent == True):
+                if (self.IncludeJetTauEtMissTriggerContent is True):
                         from DerivationFrameworkCore.JetTauEtMissTriggerContent import JetTauEtMissTriggerContent
                         for item in JetTauEtMissTriggerContent:
                                 Stream.AddItem(item)
 
                 # non xAOD collections for MinBias
-                if (self.IncludeMinBiasTriggerContent == True):
+                if (self.IncludeMinBiasTriggerContent is True):
                         from DerivationFrameworkCore.MinBiasTrigger_nonxAOD_Content import MinBiasTrigger_nonxAOD_Content
                         for item in MinBiasTrigger_nonxAOD_Content:
                                 Stream.AddItem(item)
@@ -661,7 +657,7 @@ class SlimmingHelper:
                 elif collectionName=="PrimaryVertices":
                         from DerivationFrameworkInDet.PrimaryVerticesCPContent import PrimaryVerticesCPContent
                         items.extend(PrimaryVerticesCPContent)
-                elif self.IncludeAdditionalTriggerContent == True:
+                elif self.IncludeAdditionalTriggerContent is True:
                         from DerivationFrameworkCore.AdditionalTriggerContent import AdditionalTriggerContent
                         items.extend(AdditionalTriggerContent)
 
@@ -727,7 +723,6 @@ class SlimmingHelper:
                         return "WILDCARD"
                 # No xAOD containers
                 sep = item.split("#")
-                collection = sep[1]
                 if ("xAOD::" in item and sep[1] in self.NamesAndTypes.keys()):
                         return "XAOD"
                 return "OK"
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ThinningHelper.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ThinningHelper.py
index d03049845f304e0cf907be95172661536c8ad97f..e16bbb25a846e4ece3618acf5567ac8ff86e7294 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ThinningHelper.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/ThinningHelper.py
@@ -12,9 +12,6 @@
 # (3) passes the thinning service back to the job options on request 
 ####################################################################
 
-# Needed import(s):
-import AthenaCommon.CfgMgr as CfgMgr
-
 ## Class helping to set up (navigation) thinning in derivation jobs
 #
 # In order to hide the complexity of using navigation thinning from the users,
@@ -34,7 +31,6 @@ class ThinningHelper:
     # @param helperName The instance name of this helper object
     #
     def __init__( self, helperName ):
-        from AthenaCommon.AppMgr import ServiceMgr as svcMgr
         self.helperName = helperName
         self.TriggerChains = ""
         from AthenaCommon.Logging import logging
@@ -54,11 +50,7 @@ class ThinningHelper:
     def AppendToStream( self, augmentedStream, extraTriggerContent = [] ):
         # Access the stream object:
         stream = augmentedStream.GetEventStream()
-        # Get the name of the "format":
-        formatName = stream.name().strip( "StreamDAOD_" )
-        # The necessary import(s):
-        from AthenaCommon.AppMgr import ServiceMgr as svcMgr
-        
+
         if self.TriggerChains == "":
             # No trigger selection required.
             return
@@ -96,7 +88,7 @@ class ThinningHelper:
                 t.TrigNavigationThinningSvc = tSvc
                 break
         else:
-            log.error ("Can't find ThinningCacheTool for stream %s", stream)
+            self.log.error ("Can't find ThinningCacheTool for stream %s", stream)
 
         return
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/WeightMetadata.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/WeightMetadata.py
index 59c5886b901846dc19039fd96a1a35dc035225ac..50ddd043db49b748283ff1d9c5d8184e31e62c28 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/WeightMetadata.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkCore/python/WeightMetadata.py
@@ -1,6 +1,6 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from ReweightUtils.ReweightUtilsConf import * 
+from ReweightUtils.ReweightUtilsConf import McEventWeight, PDFWeight, SumOfWeightsAlg, WeightsAgregator
 
 
 def addWeights(seq, pdfMap = {'CT14nlo':20}, pref = ""):
@@ -89,7 +89,7 @@ def addWeightsHist(stream, seq, svcMgr, CfgMgr, ToolSvc, derivName, fileName, pd
       seq += CfgMgr.CP__PileupReweightingProvider(derivName+"_pdfProvWeight"+pdfName+"_"+str(i),Tool=provTools[i],ConfigOutputStream="METADATA/pdfWeight"+pdfName+"_"+str(i))
 
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 #addWeights(DerivationFrameworkJob, {'CT10nlo':52, 'MSTW2008nlo68cl': 40, 'NNPDF23_lo_as_0130_qed': 100, 'NNPDF30_nlo_as_0118': 100}, "")
 listPDF = {}
 #listPDF["CT14nlo"] = 56
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/CMakeLists.txt
index ed2f1499363a833facfa5bb5c950ab3c00e8c685..12941799f08b9a420c2d1317a0938fb458112f5a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/CMakeLists.txt
@@ -13,6 +13,6 @@ atlas_add_component( DerivationFrameworkEGamma
                      LINK_LIBRARIES ${ROOT_LIBRARIES} AsgTools AthContainers AthenaBaseComps CaloCalibHitRecLib DerivationFrameworkInterfaces EgammaAnalysisHelpersLib EgammaAnalysisInterfacesLib ExpressionEvaluationLib GaudiKernel MCTruthClassifierLib PATCoreLib xAODBase xAODCaloEvent xAODEgamma xAODMissingET xAODMuon xAODTracking xAODTruth )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM1ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM1ExtraContent.py
index c9f84c6756f3b96fcdd09ff6b134a686170f3e8e..c55bdc9568425508a92b29b1b3934b58aebebfc0 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM1ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM1ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 
 #Content included in addition to the Smart Slimming Content
@@ -40,8 +40,8 @@ ExtraMuonsTruth=[
     ]
 
 ExtraContentPhotons=[
-	]
-	
+    ]
+
 ExtraContentPrimaryVertices=["PrimaryVertices.x.y.sumPt2"]
 
 ExtraPhotonsTruth=[
@@ -51,18 +51,18 @@ ExtraPhotonsTruth=[
     ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 #ExtraContentHLTElectrons=[
 #        "HLT_xAOD__ElectronContainer_egamma_Electrons.e.pt.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks"
@@ -84,10 +84,10 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
-		      ]
+                      ]
 
 ExtraContainersElectrons=["Electrons",
                           "GSFTrackParticles",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM2ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM2ExtraContent.py
index e248b0a25cb25bd3e53edc2e5ba0b26f78482d46..1f077a8f6480de97c9bb751c6905d65547f0cbb2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM2ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM2ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #Content included in addition to the Smart Slimming Content
 
@@ -28,7 +28,7 @@ ExtraMuonsTruth=[
     ]
 
 ExtraContentPhotons=[
-	]
+        ]
 
 ExtraContentElectrons=[]
 
@@ -41,34 +41,34 @@ ExtraPhotonsTruth=[
     ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 #cells = ("Cells5x5","Cells3x5","Cells3x7","Cells7x11")
-#layers_gains =  (	"_Lr0", "_Lr1", "_Lr2", "_Lr3",
-#					"_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
-#					"_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
-#					"_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
+#layers_gains =  (      "_Lr0", "_Lr1", "_Lr2", "_Lr3",
+#                                       "_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
+#                                       "_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
+#                                       "_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
 #
 #for cell in cells:
-#	ExtraContentPhotons.append("Photons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentPhotons.append("Photons."+cell+layer)
+#       ExtraContentPhotons.append("Photons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentPhotons.append("Photons."+cell+layer)
 #
 #for cell in cells:
-#	ExtraContentElectrons.append("Electrons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentElectrons.append("Electrons."+cell+layer)
+#       ExtraContentElectrons.append("Electrons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentElectrons.append("Electrons."+cell+layer)
 from DerivationFrameworkCalo.DerivationFrameworkCaloFactories import GainDecorator, getGainDecorations
 GainDecoratorTool = GainDecorator()
 ExtraContentPhotons.extend( getGainDecorations(GainDecoratorTool) )
@@ -82,7 +82,7 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
                       ]
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM3ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM3ExtraContent.py
index 990c084d3c0fb1c978d9ae9dabd4c83d75d482e5..bd1d12d646c7fa69e278714aaef19807134d91fa 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM3ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM3ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #Content included in addition to the Smart Slimming Content
 
@@ -42,39 +42,39 @@ ExtraPhotonsTruth=[
 ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 ExtraContentHLTPhotons=[
-	"HLT_xAOD__PhotonContainer_egamma_Photons.e.pt.m.author.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex.calE.calEta.calPhi.calM.e_sampl.eta_sampl.etaCalo.phiCalo.ETACALOFRAME.PHICALOFRAME"
+        "HLT_xAOD__PhotonContainer_egamma_Photons.e.pt.m.author.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex.calE.calEta.calPhi.calM.e_sampl.eta_sampl.etaCalo.phiCalo.ETACALOFRAME.PHICALOFRAME"
 ]
 
 #cells = ("Cells5x5","Cells3x5","Cells3x7","Cells7x11")
-#layers_gains =  (	"_Lr0", "_Lr1", "_Lr2", "_Lr3",
-#					"_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
-#					"_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
-#					"_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
+#layers_gains =  (      "_Lr0", "_Lr1", "_Lr2", "_Lr3",
+#                                       "_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
+#                                       "_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
+#                                       "_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
 #
 #for cell in cells:
-#	ExtraContentPhotons.append("Photons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentPhotons.append("Photons."+cell+layer)
+#       ExtraContentPhotons.append("Photons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentPhotons.append("Photons."+cell+layer)
 #
 #for cell in cells:
-#	ExtraContentElectrons.append("Electrons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentElectrons.append("Electrons."+cell+layer)
+#       ExtraContentElectrons.append("Electrons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentElectrons.append("Electrons."+cell+layer)
 from DerivationFrameworkCalo.DerivationFrameworkCaloFactories import GainDecorator, getGainDecorations
 GainDecoratorTool = GainDecorator()
 ExtraContentPhotons.extend( getGainDecorations(GainDecoratorTool) )
@@ -87,8 +87,8 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles",
-		      "MuonTruthParticles"
+                      "egammaTruthParticles",
+                      "MuonTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
                       ]
@@ -105,39 +105,39 @@ ExtraContainersPhotons=["Photons",
 
 # for trigger studies
 ExtraContainersTrigger=[
-	"HLT_xAOD__ElectronContainer_egamma_Electrons",
-	"HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
-	"HLT_xAOD__PhotonContainer_egamma_Photons",
-	"HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
+        "HLT_xAOD__ElectronContainer_egamma_Electrons",
+        "HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
+        "HLT_xAOD__PhotonContainer_egamma_Photons",
+        "HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
         "HLT_xAOD__PhotonContainer_egamma_Iso_Photons",
         "HLT_xAOD__PhotonContainer_egamma_Iso_PhotonsAux.",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFex",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
-	"LVL1EmTauRoIs",
-	"LVL1EmTauRoIsAux.",
-	"HLT_TrigPassBitsCollection_passbits",
-	"HLT_TrigPassBitsCollection_passbitsAux.",
-	"HLT_TrigPassFlagsCollection_passflags",
-	"HLT_TrigPassFlagsCollection_passflagsAux.",
-	"HLT_TrigRoiDescriptorCollection_initialRoI",
-	"HLT_TrigRoiDescriptorCollection_initialRoIAux."
-	]
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFex",
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
+        "LVL1EmTauRoIs",
+        "LVL1EmTauRoIsAux.",
+        "HLT_TrigPassBitsCollection_passbits",
+        "HLT_TrigPassBitsCollection_passbitsAux.",
+        "HLT_TrigPassFlagsCollection_passflags",
+        "HLT_TrigPassFlagsCollection_passflagsAux.",
+        "HLT_TrigRoiDescriptorCollection_initialRoI",
+        "HLT_TrigRoiDescriptorCollection_initialRoIAux."
+        ]
 
 ExtraContainersTriggerDataOnly=[
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTF",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTFAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2ID",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2IDAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrig",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrigAux."
-	]
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTF",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTFAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2ID",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2IDAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrig",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrigAux."
+        ]
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM4ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM4ExtraContent.py
index 27a494b113c2beb84d53433e74742388f00609ab..2fbf7a3688ec5999ab9ef46f531dafd49ea6d9fe 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM4ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM4ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #Content included in addition to the Smart Slimming Content
 
@@ -48,22 +48,22 @@ ExtraPhotonsTruth=[
 ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 ExtraContentHLTPhotons=[
         "HLT_xAOD__PhotonContainer_egamma_Photons.e.pt.m.author.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex.calE.calEta.calPhi.calM.e_sampl.eta_sampl.etaCalo.phiCalo.ETACALOFRAME.PHICALOFRAME"
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex.calE.calEta.calPhi.calM.e_sampl.eta_sampl.etaCalo.phiCalo.ETACALOFRAME.PHICALOFRAME"
 ]
 
 from DerivationFrameworkCalo.DerivationFrameworkCaloFactories import GainDecorator, getGainDecorations
@@ -79,8 +79,8 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles",
-		      "MuonTruthParticles"
+                      "egammaTruthParticles",
+                      "MuonTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
                       ]
@@ -95,31 +95,31 @@ ExtraContainersPhotons=["Photons",
 
 # for trigger studies and for trigger matching
 ExtraContainersTrigger=[
-	"HLT_xAOD__MuonContainer_MuonEFInfo",
-	"HLT_xAOD__MuonContainer_MuonEFInfoAux.",
+        "HLT_xAOD__MuonContainer_MuonEFInfo",
+        "HLT_xAOD__MuonContainer_MuonEFInfoAux.",
         "HLT_xAOD__MuonContainer_MuonEFInfo_FullScan",
         "HLT_xAOD__MuonContainer_MuonEFInfo_FullScanAux.",
-	"HLT_xAOD__PhotonContainer_egamma_Photons",
-	"HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
+        "HLT_xAOD__PhotonContainer_egamma_Photons",
+        "HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
         "HLT_xAOD__PhotonContainer_egamma_Iso_Photons",
         "HLT_xAOD__PhotonContainer_egamma_Iso_PhotonsAux.",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
-	"LVL1EmTauRoIs",
-	"LVL1EmTauRoIsAux.",
-	"HLT_TrigPassBitsCollection_passbits",
-	"HLT_TrigPassBitsCollection_passbitsAux.",
-	"HLT_TrigPassFlagsCollection_passflags",
-	"HLT_TrigPassFlagsCollection_passflagsAux.",
-	"HLT_TrigRoiDescriptorCollection_initialRoI",
-	"HLT_TrigRoiDescriptorCollection_initialRoIAux."
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
+        "LVL1EmTauRoIs",
+        "LVL1EmTauRoIsAux.",
+        "HLT_TrigPassBitsCollection_passbits",
+        "HLT_TrigPassBitsCollection_passbitsAux.",
+        "HLT_TrigPassFlagsCollection_passflags",
+        "HLT_TrigPassFlagsCollection_passflagsAux.",
+        "HLT_TrigRoiDescriptorCollection_initialRoI",
+        "HLT_TrigRoiDescriptorCollection_initialRoIAux."
         ]
 
 ExtraContainersTriggerDataOnly=[
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux."
-	]
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux."
+        ]
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM5ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM5ExtraContent.py
index eca0e30a85720475ece329349965f899bc0f4bce..590f71a6a4467444c58ec0ebdeefd9e43a26bb4d 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM5ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM5ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #Content included in addition to the Smart Slimming Content
 
@@ -42,34 +42,34 @@ ExtraPhotonsTruth=[
 ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
 ]
 
 #cells = ("Cells5x5","Cells3x5","Cells3x7","Cells7x11")
-#layers_gains =  (	"_Lr0", "_Lr1", "_Lr2", "_Lr3",
-#					"_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
-#					"_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
-#					"_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
+#layers_gains =  (      "_Lr0", "_Lr1", "_Lr2", "_Lr3",
+#                                       "_Lr0_LwG", "_Lr1_LwG", "_Lr2_LwG", "_Lr3_LwG",
+#                                       "_Lr0_LwG", "_Lr1_MdG", "_Lr2_MdG", "_Lr3_MdG",
+#                                       "_Lr0_LwG", "_Lr1_HiG", "_Lr2_HiG", "_Lr3_HiG" )
 #
 #for cell in cells:
-#	ExtraContentPhotons.append("Photons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentPhotons.append("Photons."+cell+layer)
+#       ExtraContentPhotons.append("Photons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentPhotons.append("Photons."+cell+layer)
 #
 #for cell in cells:
-#	ExtraContentElectrons.append("Electrons."+cell)
-#	for layer in layers_gains:
-#		ExtraContentElectrons.append("Electrons."+cell+layer)
+#       ExtraContentElectrons.append("Electrons."+cell)
+#       for layer in layers_gains:
+#               ExtraContentElectrons.append("Electrons."+cell+layer)
 #
 from DerivationFrameworkCalo.DerivationFrameworkCaloFactories import GainDecorator, getGainDecorations
 GainDecoratorTool = GainDecorator()
@@ -83,7 +83,7 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
                       ]
@@ -95,32 +95,32 @@ ExtraContainersElectrons=["Electrons",
 
 # for trigger studies
 ExtraContainersTrigger=[
-	"HLT_xAOD__ElectronContainer_egamma_Electrons",
-	"HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
-	"HLT_xAOD__PhotonContainer_egamma_Photons",
-	"HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFex",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
-	"LVL1EmTauRoIs",
-	"LVL1EmTauRoIsAux.",
-	"HLT_TrigPassBitsCollection_passbits",
-	"HLT_TrigPassBitsCollection_passbitsAux.",
-	"HLT_TrigPassFlagsCollection_passflags",
-	"HLT_TrigPassFlagsCollection_passflagsAux.",
-	"HLT_TrigRoiDescriptorCollection_initialRoI",
-	"HLT_TrigRoiDescriptorCollection_initialRoIAux."
-	]
+        "HLT_xAOD__ElectronContainer_egamma_Electrons",
+        "HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
+        "HLT_xAOD__PhotonContainer_egamma_Photons",
+        "HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFex",
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
+        "LVL1EmTauRoIs",
+        "LVL1EmTauRoIsAux.",
+        "HLT_TrigPassBitsCollection_passbits",
+        "HLT_TrigPassBitsCollection_passbitsAux.",
+        "HLT_TrigPassFlagsCollection_passflags",
+        "HLT_TrigPassFlagsCollection_passflagsAux.",
+        "HLT_TrigRoiDescriptorCollection_initialRoI",
+        "HLT_TrigRoiDescriptorCollection_initialRoIAux."
+        ]
 
 ExtraContainersTriggerDataOnly=[
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux."
-	]
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux."
+        ]
 
 #should probably slim electron/fwdelectrons/cluster collections and keep only relevant subset of variables..
 # no ForwardElectrons, InDetTrackParticlesForward, ForwardElectronClusters, CaloCalTopoCluster
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM7ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM7ExtraContent.py
index 2088e310366dd84b952298f48ad02feeaf5be89d..183b85a3223f3dd9e396cf278b98f48f2dea4851 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM7ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM7ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 
 #Content included in addition to the Smart Slimming Content
@@ -40,8 +40,8 @@ ExtraMuonsTruth=[
     ]
 
 ExtraContentPhotons=[
-	]
-	
+        ]
+
 ExtraContentPrimaryVertices=["PrimaryVertices.x.y.sumPt2"]
 
 ExtraPhotonsTruth=[
@@ -51,18 +51,18 @@ ExtraPhotonsTruth=[
     ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 #ExtraContentHLTElectrons=[
 #        "HLT_xAOD__ElectronContainer_egamma_Electrons.e.pt.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks"
@@ -84,10 +84,10 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
-		      ]
+                      ]
 
 ExtraContainersElectrons=["Electrons",
                           "GSFTrackParticles",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM8ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM8ExtraContent.py
index b2b8645ca4251d4bd4e0ace83b67d891cf574728..12707ad40866bbdb990237bf5e908fe5d7ff8351 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM8ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM8ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 
 #Content included in addition to the Smart Slimming Content
@@ -31,8 +31,8 @@ ExtraMuonsTruth=[
     ]
 
 ExtraContentPhotons=[
-	]
-	
+        ]
+
 ExtraContentPrimaryVertices=["PrimaryVertices.x.y.sumPt2"]
 
 ExtraPhotonsTruth=[
@@ -42,18 +42,18 @@ ExtraPhotonsTruth=[
     ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 from DerivationFrameworkCalo.DerivationFrameworkCaloFactories import GainDecorator, getGainDecorations
 GainDecoratorTool = GainDecorator()
@@ -67,10 +67,10 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
-		      ]
+                      ]
 
 ExtraContainersElectrons=["Electrons",
                           "ForwardElectrons",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM9ExtraContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM9ExtraContent.py
index 35c6d8b288ff654a72a9b3ae088299afbadb3429..41a619906c29c5b3bf026f4db0e0957f362f5852 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM9ExtraContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGAM9ExtraContent.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 
 #Content included in addition to the Smart Slimming Content
@@ -32,8 +32,8 @@ ExtraMuonsTruth=[
 
 ExtraContentPhotons=[
     "Photons.DFCommonLoosePrime5",
-	]
-	
+        ]
+
 ExtraContentPrimaryVertices=["PrimaryVertices.x.y.sumPt2"]
 
 ExtraPhotonsTruth=[
@@ -43,18 +43,18 @@ ExtraPhotonsTruth=[
     ]
 
 ExtraContentGSFConversionVertices=[
-	"GSFConversionVertices.x",
-	"GSFConversionVertices.y",
-	"GSFConversionVertices.z",
-	"GSFConversionVertices.px",
-	"GSFConversionVertices.py",
-	"GSFConversionVertices.pz",
-	"GSFConversionVertices.pt1",
-	"GSFConversionVertices.pt2",
-	"GSFConversionVertices.etaAtCalo",
-	"GSFConversionVertices.phiAtCalo",
-	"GSFConversionVertices.trackParticleLinks"
-	]
+        "GSFConversionVertices.x",
+        "GSFConversionVertices.y",
+        "GSFConversionVertices.z",
+        "GSFConversionVertices.px",
+        "GSFConversionVertices.py",
+        "GSFConversionVertices.pz",
+        "GSFConversionVertices.pt1",
+        "GSFConversionVertices.pt2",
+        "GSFConversionVertices.etaAtCalo",
+        "GSFConversionVertices.phiAtCalo",
+        "GSFConversionVertices.trackParticleLinks"
+        ]
 
 #ExtraContentHLTElectrons=[
 #        "HLT_xAOD__ElectronContainer_egamma_Electrons.e.pt.Rhad.Rhad1.e277.Reta.Rphi.weta2.f1.fracs1.wtots1.weta1.DeltaE.Eratio.caloClusterLinks"
@@ -72,10 +72,10 @@ ExtraContainersTruth=["TruthEvents",
                       "TruthParticles",
                       "TruthVertices",
                       "AntiKt4TruthJets",
-		      "egammaTruthParticles"
+                      "egammaTruthParticles"
                       #,"BTagging_AntiKt4TruthWZ"
                       #,"AntiKt4TruthWZJets"
-		      ]
+                      ]
 
 ExtraContainersElectrons=["Electrons",
                           "GSFTrackParticles",
@@ -89,41 +89,41 @@ ExtraContainersPhotons=["Photons",
 
 # for trigger studies
 ExtraContainersTrigger=[
-	"HLT_xAOD__ElectronContainer_egamma_Electrons",
-	"HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
-	"HLT_xAOD__PhotonContainer_egamma_Photons",
-	"HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
+        "HLT_xAOD__ElectronContainer_egamma_Electrons",
+        "HLT_xAOD__ElectronContainer_egamma_ElectronsAux.",
+        "HLT_xAOD__PhotonContainer_egamma_Photons",
+        "HLT_xAOD__PhotonContainer_egamma_PhotonsAux.",
         "HLT_xAOD__PhotonContainer_egamma_Iso_Photons",
         "HLT_xAOD__PhotonContainer_egamma_Iso_PhotonsAux.",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFex",
-	"HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
-	"HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
-	"HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
-	"LVL1EmTauRoIs",
-	"LVL1EmTauRoIsAux.",
-	"HLT_TrigPassBitsCollection_passbits",
-	"HLT_TrigPassBitsCollection_passbitsAux.",
-	"HLT_TrigPassFlagsCollection_passflags",
-	"HLT_TrigPassFlagsCollection_passflagsAux.",
-	"HLT_TrigRoiDescriptorCollection_initialRoI",
-	"HLT_TrigRoiDescriptorCollection_initialRoIAux."
-	]
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFex",
+        "HLT_xAOD__TrigElectronContainer_L2ElectronFexAux.",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFex",
+        "HLT_xAOD__TrigPhotonContainer_L2PhotonFexAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFex",
+        "HLT_xAOD__CaloClusterContainer_TrigEFCaloCalibFexAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFID",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_EFIDAux.",
+        "LVL1EmTauRoIs",
+        "LVL1EmTauRoIsAux.",
+        "HLT_TrigPassBitsCollection_passbits",
+        "HLT_TrigPassBitsCollection_passbitsAux.",
+        "HLT_TrigPassFlagsCollection_passflags",
+        "HLT_TrigPassFlagsCollection_passflagsAux.",
+        "HLT_TrigRoiDescriptorCollection_initialRoI",
+        "HLT_TrigRoiDescriptorCollection_initialRoIAux."
+        ]
 
 ExtraContainersTriggerDataOnly=[
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
-	"HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
-	"HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTF",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTFAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2ID",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2IDAux.",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrig",
-	"HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrigAux."
-	]
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgamma",
+        "HLT_xAOD__TrigEMClusterContainer_TrigT2CaloEgammaAux.",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMaker",
+        "HLT_xAOD__CaloClusterContainer_TrigCaloClusterMakerAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTF",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_FTFAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2ID",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_L2IDAux.",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrig",
+        "HLT_xAOD__TrackParticleContainer_InDetTrigTrackingxAODCnv_Electron_IDTrigAux."
+        ]
 
 #should slim electron/fwdelectrons/cluster collections and keep only relevant subset of variables..
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGammaCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGammaCommon.py
index 1dbe056b965c47e9d8caee966c7f4951d507295d..711fa4faa8a6ba2be1e7d88f0bd24ed1b92676ba 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGammaCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkEGamma/python/EGammaCommon.py
@@ -1,13 +1,14 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
 #********************************************************************
 # EGammaCommon.py 
 # Schedules all tools needed for e-gamma object selection and writes
 # results into SG. These may then be accessed along the train   
 #********************************************************************
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob, DerivationFrameworkSimBarcodeOffset
+from AthenaCommon import CfgMgr
+from AthenaCommon.GlobalFlags import globalflags
+from AthenaCommon.AppMgr import ToolSvc, ServiceMgr as svcMgr
 
 #====================================================================
 # PHOTON ETA (=ETA2), ET (=E/COSH(ETA2))
@@ -178,7 +179,6 @@ ToolSvc += EGAMCOM_caloFillRect711
 #====================================================================
 # AUGMENTATION TOOLS
 #====================================================================
-from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__AsgSelectionToolWrapper
 from DerivationFrameworkEGamma.DerivationFrameworkEGammaConf import DerivationFramework__EGSelectionToolWrapper
 from DerivationFrameworkEGamma.DerivationFrameworkEGammaConf import DerivationFramework__EGElectronLikelihoodToolWrapper
 
@@ -188,7 +188,7 @@ ElectronPassLHVeryLoose = DerivationFramework__EGElectronLikelihoodToolWrapper(
                                                                           EGammaFudgeMCTool = "",
                                                                           CutType = "",
                                                                           StoreGateEntryName = "DFCommonElectronsLHVeryLoose",
-	                                                                  ContainerName = "Electrons",
+                                                                          ContainerName = "Electrons",
                                                                           StoreTResult = False)
 ToolSvc += ElectronPassLHVeryLoose
 print(ElectronPassLHVeryLoose)
@@ -247,7 +247,7 @@ ElectronPassECIDS = DerivationFramework__EGElectronLikelihoodToolWrapper( name =
                                                                           EGammaFudgeMCTool = "",
                                                                           CutType = "",
                                                                           StoreGateEntryName = "DFCommonElectronsECIDS",
-	                                                                  ContainerName = "Electrons",
+                                                                          ContainerName = "Electrons",
                                                                           StoreTResult = True)
 ToolSvc += ElectronPassECIDS
 print (ElectronPassECIDS)
@@ -455,7 +455,6 @@ if  rec.doTruth():
 # CREATE THE DERIVATION KERNEL ALGORITHM   
 #=======================================
 
-from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
 DerivationFrameworkJob += CfgMgr.DerivationFramework__CommonAugmentation("EGammaCommonKernel",
                                                                          AugmentationTools = EGAugmentationTools
                                                                          )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/CMakeLists.txt
index 3ce221e99d5e1ae37901f929145a3d81c0365a8a..370ec81968dc83e4fad2f59e62ca1e26dccbd337 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/CMakeLists.txt
@@ -13,7 +13,7 @@ atlas_add_component( DerivationFrameworkFlavourTag
                      LINK_LIBRARIES AthenaBaseComps FlavorTagDiscriminants GaudiKernel xAODJet xAODTracking xAODBTagging )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
 # add the test utility
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJetsCPContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJetsCPContent.py
index 5358ebd53c9dd9b698120d68229fa781769e659c..9573d77ff44aeb271fb983ce07780cf5f2a499d4 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJetsCPContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJetsCPContent.py
@@ -1,6 +1,4 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
-
-from JetFlavorGhostLabels import getJetFlavorGhostLabels
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 AntiKtVR30Rmax4Rmin02TrackJetsCPContent = [
 "AntiKtVR30Rmax4Rmin02TrackJets_BTagging201810",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903CPContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903CPContent.py
index b5c8827888089e59e67dd99a2eabb932cb8f2fff..2cc0ec5a87eafd6c1e6cbe9c634eae5ade90c28b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903CPContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903CPContent.py
@@ -1,6 +1,4 @@
-# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
-
-from JetFlavorGhostLabels import getJetFlavorGhostLabels
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903CPContent = [
 "AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/FlavourTagCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/FlavourTagCommon.py
index e2f829a670c24fe4727afc4003afb66f21d1e0fa..45df4a5f969505c3f1ca01e694e0719d4f83aa00 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/FlavourTagCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/FlavourTagCommon.py
@@ -1,7 +1,5 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
 #********************************************************************
 
 # FlavourTagCommon.py
@@ -16,10 +14,10 @@ import AthenaCommon.Constants as Lvl
 from AthenaCommon import Logging
 ftaglog = Logging.logging.getLogger('FlavourTagCommon')
 
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 from BTagging.BTaggingFlags import BTaggingFlags
 from AthenaCommon.GlobalFlags import globalflags
+from AthenaCommon import CfgMgr
 
 DoneJetCollections=set([])
 
@@ -57,8 +55,6 @@ def DontReduceInfo(Rel20=True):
     if globalflags.DataSource()=='data':
         augmentationTools = []
 
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
-
     global DerivationFrameworkJob
     DerivationFrameworkJob += CfgMgr.DerivationFramework__CommonAugmentation("MyDFTSOS_KERN",
                                                                              AugmentationTools = augmentationTools,
@@ -220,8 +216,8 @@ def FlavorTagInit(DoReduceInfo = False,
     #doRetag      =True  ## perform retagging
     #adjust configurations
 
-    if DoRetag==False:
-        DoReduceInfo=True
+    #if DoRetag is False:
+    #    DoReduceInfo=True
 
 
     #if the user has defined a list of desired taggers use that one, otherwise use only the active taggers
@@ -282,7 +278,7 @@ def applyBTagging_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJo
       supportedJets = ['AntiKt4EMTopo_BTagging201810', 'AntiKt4EMPFlow_BTagging201810']
     else:
       supportedJets = ['AntiKt4EMTopo', 'AntiKt4EMPFlow']
-    if not jetalg in supportedJets:
+    if jetalg not in supportedJets:
         ftaglog.warning('B-tagging requested for unsupported jet collection {}!'.format(jetalg))
         return
     else:
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/HbbCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/HbbCommon.py
index d00ab7adeea213569360ea9fc468f028d8c6b086..31abe1dd32c870f5c08ea7fd80575ad9f23ef7a8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/HbbCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/HbbCommon.py
@@ -1,8 +1,5 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-
 # import Common Algs
 from DerivationFrameworkJetEtMiss.JetCommon import DFJetAlgs
 
@@ -13,12 +10,13 @@ from DerivationFrameworkCore.DerivationFrameworkMaster import (
 from BTagging.BTaggingConfiguration import getConfiguration
 ConfInst=getConfiguration()
 
-from GaudiKernel.Configurable import WARNING, VERBOSE
+from AthenaCommon import CfgMgr
+from AthenaCommon import Logging
+from AthenaCommon.Constants import WARNING
 
-# Import star stuff (it was like that when I got here)
-from DerivationFrameworkJetEtMiss.JetCommon import *
-from DerivationFrameworkJetEtMiss.ExtendedJetCommon import *
+from DerivationFrameworkJetEtMiss.JetCommon import addTrimmedJets
 from JetRec.JetRecConf import JetAlgorithm
+from JetRec.JetRecFlags import jetFlags
 
 #===================================================================
 # ExKt/CoM Subjets
@@ -62,7 +60,6 @@ def buildExclusiveSubjets(ToolSvc, JetCollectionName, subjet_mode, nsubjet, doGh
     else:
         print (" building ExKtbbTagTool ", ExKtbbTagToolName)
 
-        from JetSubStructureMomentTools.JetSubStructureMomentToolsConf import SubjetFinderTool
         from JetSubStructureMomentTools.JetSubStructureMomentToolsConf import SubjetRecorderTool
 
         subjetrecorder = SubjetRecorderTool("subjetrecorder_%s%i%s_%s" % (subjet_mode, nsubjet, talabel, JetCollectionName))
@@ -215,7 +212,6 @@ def addExKtCoM(sequence, ToolSvc, JetCollectionExCoM, nSubjets, doTrackSubJet, d
 # AntiKt10LCTopoJets
 ##################################################################
 def addVRJets(sequence, largeRColls = None, do_ghost=False, logger=None, doFlipTagger=False, training='201810', *pos_opts, **opts):
-    from AthenaCommon import Logging
 
     if logger is None:
         logger = Logging.logging.getLogger('VRLogger')
@@ -289,8 +285,8 @@ def buildVRJets(sequence, do_ghost, logger = None, doFlipTagger=False, training=
     VRJetAlgName = "jfind_%s" % (VRJetRecToolName)
     VRJetBTagName = "BTagging_%s" % (VRJetName.replace('BTagging',''))
 
-    logger.info("VR Btag name: %s" % VRJetBTagName)
-    logger.info("VR jet name: %s" % VRJetRecToolName)
+    logger.info("VR Btag name: %s", VRJetBTagName)
+    logger.info("VR jet name: %s", VRJetRecToolName)
 
     from AthenaCommon.AppMgr import ToolSvc
 
@@ -329,20 +325,20 @@ def buildVRJets(sequence, do_ghost, logger = None, doFlipTagger=False, training=
         pseudoJetGetters.append(jtm["gtrackget"])
 
     if VRJetAlgName in DFJetAlgs:
-        logger.info("Algorithm %s already built before" % VRJetAlgName)
+        logger.info("Algorithm %s already built before", VRJetAlgName)
 
         if hasattr(sequence, VRJetAlgName):
-            logger.info("Sequence %s already has an instance of algorithm %s" % (sequence, VRJetAlgName))
+            logger.info("Sequence %s already has an instance of algorithm %s", sequence, VRJetAlgName)
         else:
-            logger.info("Add algorithm %s to sequence %s" % (VRJetAlgName, sequence))
+            logger.info("Add algorithm %s to sequence %s", VRJetAlgName, sequence)
             sequence += DFJetAlgs[VRJetAlgName]
     else:
-        logger.info("Create algorithm %s" % VRJetAlgName)
+        logger.info("Create algorithm %s", VRJetAlgName)
 
         if hasattr(jtm, VRJetRecToolName):
-            logger.info("JetRecTool %s is alredy in jtm.tools in sequence %s" % (VRJetRecToolName, sequence))
+            logger.info("JetRecTool %s is alredy in jtm.tools in sequence %s", VRJetRecToolName, sequence)
         else:
-            logger.info("Create JetRecTool %s" % VRJetRecToolName)
+            logger.info("Create JetRecTool %s", VRJetRecToolName)
             #can only run trackjetdrlabeler with truth labels, so MC only
 
             mods = [defaultTrackAssoc, defaultMuonAssoc, btag_vrjets]
@@ -372,9 +368,9 @@ def buildVRJets(sequence, do_ghost, logger = None, doFlipTagger=False, training=
     from DerivationFrameworkJetEtMiss.ExtendedJetCommon import nameJetsFromAlg
 
     if hasattr(jtm, pjgettername):
-        logger.info("Found %s in jtm in sequence %s" % (pjgettername, sequence))
+        logger.info("Found %s in jtm in sequence %s", pjgettername, sequence)
     else:
-        logger.info("Add %s to jtm in sequence %s" % (pjgettername, sequence))
+        logger.info("Add %s to jtm in sequence %s", pjgettername, sequence)
         
         inputContainerName = jetFlags.containerNamePrefix() + nameJetsFromAlg(VRJetName)
 
@@ -415,7 +411,7 @@ def getJetRecTool(collection, getParent=True):
   from JetRec.JetRecStandardToolManager import jtm
   try:
     jetRecTool = jtm[collection]
-  except KeyError as e:
+  except KeyError:
      raise KeyError("JetRecTool {0} not present in jtm".format(collection) )
   if getParent and hasattr(jetRecTool, "InputContainer") and jetRecTool.InputContainer:
     jetRecTool = getJetRecTool(jetRecTool.InputContainer, True)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/SoftBtagCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/SoftBtagCommon.py
index 851ac74ec106b9fef716027fb460cbf1196523db..ebc8c0ec89874299497d3d7f68e6a55806109e3e 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/SoftBtagCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkFlavourTag/python/SoftBtagCommon.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #********************************************************************
 
@@ -6,13 +6,9 @@
 
 #********************************************************************
 
-import AthenaCommon.Constants as Lvl
 from AthenaCommon import Logging
 ftaglog = Logging.logging.getLogger('SoftBtagCommon')
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from AthenaCommon.GlobalFlags import globalflags
-
 def applySoftBtagging(algname,sequence):
 
     from VrtSecInclusive.SoftBtagTrackSelector import SoftBtagTrackSelector
@@ -55,7 +51,7 @@ def applySoftBtagging(algname,sequence):
                                                   Extrapolator        = ToolSvc.AtlasExtrapolator,
                                                   IterationNumber     = 30
                                                   )
-    ToolSvc +=  InclusiveVxFitterTool;
+    ToolSvc +=  InclusiveVxFitterTool
 
     VrtSecInclusive_SoftB.VertexFitterTool=InclusiveVxFitterTool
     VrtSecInclusive_SoftB.Extrapolator = ToolSvc.AtlasExtrapolator
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/CMakeLists.txt
index 150d015311fe703bad405729fc0796aaf9fd462e..8b7686551e098b9c9ecd0342d5c7a671fc895d03 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/CMakeLists.txt
@@ -14,6 +14,6 @@ atlas_add_component( DerivationFrameworkHiggs
                      LINK_LIBRARIES ${CLHEP_LIBRARIES} AthenaBaseComps DerivationFrameworkInterfaces TrigDecisionToolLib xAODEgamma xAODEventInfo xAODJet xAODMuon xAODTracking )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxAugmentation.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxAugmentation.py
index 795444b0c592b9e9a71cef5d005ea6e6ba71d9aa..d6500646bca855697741a4f6b37f73ff31e180ac 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxAugmentation.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxAugmentation.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #################################################
 # Common code used for the HIGG4 augmentation  	#
@@ -66,14 +66,14 @@ def setup(HIGG4DxName, ToolSvc):
         augmentationTools.append(HIGG4DxTauPVRefittingTool)
 
     if DFisMC:
-   	# Tau truth matching 
+        # Tau truth matching
         from TauAnalysisTools.TauAnalysisToolsConf import TauAnalysisTools__TauTruthMatchingTool
         HIGG4DxTauTruthMatchingTool = TauAnalysisTools__TauTruthMatchingTool(name="HIGG4DxTauTruthMatchingTool",
                                                                              WriteTruthTaus = True)
         
         ToolSvc += HIGG4DxTauTruthMatchingTool
 
-   	# Tau truth matching wrapper 
+        # Tau truth matching wrapper
         from DerivationFrameworkTau.DerivationFrameworkTauConf import DerivationFramework__TauTruthMatchingWrapper
         HIGG4DxTauTruthMatchingWrapper = DerivationFramework__TauTruthMatchingWrapper( name = "HIGG4DxTauTruthMatchingWrapper",
                                                                                 TauTruthMatchingTool = HIGG4DxTauTruthMatchingTool)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxJets.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxJets.py
index 04d095c46fd8cebf6c3810d916f6bd9bd3c2e851..9c3800f900515168fe6577cbaf6cc8c8d1c334a1 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxJets.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxJets.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #################################################################
 # Common code used for the HIGG4 jet building and calibration   #
@@ -7,8 +7,8 @@
 # Nov 2015                                      		#
 #################################################################
 
-from DerivationFrameworkJetEtMiss.JetCommon import *
-from DerivationFrameworkJetEtMiss.ExtendedJetCommon import *
+from DerivationFrameworkJetEtMiss.JetCommon import OutputJets
+from DerivationFrameworkJetEtMiss.ExtendedJetCommon import addDefaultTrimmedJets
 
 def setup(HIGG4DxName, HIGG4DxSequence, HIGG4DxSlimmingHelper):
 
@@ -17,13 +17,13 @@ def setup(HIGG4DxName, HIGG4DxSequence, HIGG4DxSlimmingHelper):
         # add a small-R collection
 #        OutputJets[DAOD_StreamID+"Jets"] = ["AntiKt2PV0TrackJets"]
 
-    	# schedule reconstruction of AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets 
+        # schedule reconstruction of AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets
 #        addTrimmedJets("AntiKt", 1.0, "LCTopo", rclus=0.2, ptfrac=0.05, algseq=DerivationFrameworkJob)
 #        OutputJets[DAOD_StreamID+"Jets"].append("AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets")
 #        print "HELLO HERE", OutputJets[DAOD_StreamID+"Jets"]
     
     jet_collection = HIGG4DxName+"Jets"
-    if not jet_collection in OutputJets:
+    if jet_collection not in OutputJets:
         # AntiKt10*PtFrac5Rclus20 jets
         if HIGG4DxName in ['HIGG4D2', 'HIGG4D3']:
             addDefaultTrimmedJets(HIGG4DxSequence, jet_collection, False)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSkimming.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSkimming.py
index c2b41a1f0f3799705806d468400d3e492709beda..7ba2dc395c67bd2504f6ec0d2c9b07e433d6e8e0 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSkimming.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSkimming.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #################################################
 # Common code used for the HIGG4 skimming       #
@@ -42,7 +42,7 @@ def setup(HIGG4DxName, ToolSvc):
         tauReq1 = '(count( '+tauSubl+' && '+tauTrks+' && '+tauId+' ) >= 1)'
         tauReq2 = '(count( '+tauLead+' && '+tauTrks+' ) >= 1)'
         skim_expression = tauReq0 + '&&' + tauReq1 + '&&' + tauReq2
-	#skim_expression = tauReq0 + '&&' + tauReq2
+        #skim_expression = tauReq0 + '&&' + tauReq2
     elif HIGG4DxName == 'HIGG4D4':
         ditau = '(count(((TauJets.nTracks == 1) || (TauJets.nTracks == 3)) && (TauJets.pt > 45.0*GeV)) >= 2)'
         tau1 = '(count((TauJets.pt > 100.0*GeV)) >= 1)'
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSlimming.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSlimming.py
index 042fdeb9e95d2d754378067f8e176d152977b379..c8e1f53ed93bec7969bdb06121351f4f096a774d 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSlimming.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxSlimming.py
@@ -1,4 +1,4 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #################################################
 # Common code used for the HIGG4 slimming       #
@@ -7,8 +7,7 @@
 # Nov 2015                                      #
 #################################################
 
-from DerivationFrameworkMCTruth.MCTruthCommon import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
+from DerivationFrameworkJetEtMiss.JetCommon import addJetOutputs
 
 def setup(HIGG4DxName, HIGG4DxStream, HIGG4DxSlimmingHelper):
     from AthenaCommon.GlobalFlags import globalflags
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxThinning.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxThinning.py
index 40001dd624e45cf46040a53174d82806977e2ef4..73877bf343ac0eba1bdf27c71985b9ed6576346f 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxThinning.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkHiggs/python/HIGG4DxThinning.py
@@ -58,16 +58,16 @@ def setup(HIGG4DxName, streamName, ToolSvc):
         ToolSvc += HIGG4DxJetTrackThinningTool1
         thinningTools.append(HIGG4DxJetTrackThinningTool1)
 
-    if HIGG4DxName in ['HIGG4D2', 'HIGG4D3']:
-        from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__JetTrackParticleThinning
-        HIGG4DxJetTrackThinningTool2 = DerivationFramework__JetTrackParticleThinning( name          	    = HIGG4DxName+"JetTrackThinningTool2",
-                                                                                      StreamName              = streamName,
-                                                                                      JetKey                 = "AntiKt2PV0TrackJets",
-                                                                                      SelectionString        = "AntiKt2PV0TrackJets.pt > 6*GeV",
-                                                                                      InDetTrackParticlesKey = "InDetTrackParticles",
-                                                                                      ApplyAnd               = True)
-        #ToolSvc += HIGG4DxJetTrackThinningTool2
-        #thinningTools.append(HIGG4DxJetTrackThinningTool2)
+    #if HIGG4DxName in ['HIGG4D2', 'HIGG4D3']:
+    #    from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__JetTrackParticleThinning
+    #    HIGG4DxJetTrackThinningTool2 = DerivationFramework__JetTrackParticleThinning( name          	    = HIGG4DxName+"JetTrackThinningTool2",
+    #                                                                                  StreamName              = streamName,
+    #                                                                                  JetKey                 = "AntiKt2PV0TrackJets",
+    #                                                                                  SelectionString        = "AntiKt2PV0TrackJets.pt > 6*GeV",
+    #                                                                                  InDetTrackParticlesKey = "InDetTrackParticles",
+    #                                                                                  ApplyAnd               = True)
+    #    ToolSvc += HIGG4DxJetTrackThinningTool2
+    #    thinningTools.append(HIGG4DxJetTrackThinningTool2)
 
     # Tracks associated with Muons
     HIGG4DxMuonSelectionString = ""
@@ -120,9 +120,9 @@ def setup(HIGG4DxName, streamName, ToolSvc):
     # PreserveDescendants keeps all particles including those that come from Geant processes
 
     if DFisMC:
-    	#thin special containers
+        #thin special containers
         from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__GenericTruthThinning
-    	#thin taus
+        #thin taus
         HIGG4DxTruthTool_TAU = DerivationFramework__GenericTruthThinning(name                         = HIGG4DxName+"TruthTool_TAU",
                                                                          StreamName                   = streamName,
                                                                          ParticleSelectionString      = truth_cond_tau,
@@ -133,7 +133,7 @@ def setup(HIGG4DxName, streamName, ToolSvc):
         ToolSvc += HIGG4DxTruthTool_TAU
         thinningTools.append(HIGG4DxTruthTool_TAU)
 
-	#thin leptons and taus
+        #thin leptons and taus
         HIGG4DxTruthTool_COMB = DerivationFramework__GenericTruthThinning(name                         = HIGG4DxName+"TruthTool_COMB",
                                                                           StreamName                   = streamName,
                                                                           ParticleSelectionString      = truth_cond_comb,
@@ -145,7 +145,7 @@ def setup(HIGG4DxName, streamName, ToolSvc):
         ToolSvc += HIGG4DxTruthTool_COMB
         thinningTools.append(HIGG4DxTruthTool_COMB)
 
-    	#thin photons
+        #thin photons
         """HIGG4DxTruthTool_PHO = DerivationFramework__GenericTruthThinning(name                    = "HIGG4DxTruthTool_PHO",
                                                                      StreamName              = streamName,
                                                                      ParticlesKey            = "TruthPhotons",
@@ -154,9 +154,9 @@ def setup(HIGG4DxName, streamName, ToolSvc):
                                                                      ToolSvc += HIGG4DxTruthTool_PHO
                                                                      thinningTools.append(HIGG4DxTruthTool_PHO)"""
 
-    	#thinning the master truth collection
+        #thinning the master truth collection
         from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__MenuTruthThinning
-        HIGG4DxTruthTool_MENU = DerivationFramework__MenuTruthThinning(  name 			    = HIGG4DxName+"TruthTool_MENU",
+        HIGG4DxTruthTool_MENU = DerivationFramework__MenuTruthThinning(  name                       = HIGG4DxName+"TruthTool_MENU",
                                                                          StreamName                 = streamName,
                                                                          WritePartons               = False,
                                                                          WriteHadrons               = False,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/CMakeLists.txt
index 4f2b36a26847a20df976817f2c7ad3aadd4c2e47..f91659662caf7a921e9fdca66d574b5f0cb00926 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/CMakeLists.txt
@@ -13,5 +13,5 @@ atlas_add_component( DerivationFrameworkInDet
                      LINK_LIBRARIES ${ROOT_LIBRARIES} AthLinks AthenaBaseComps AthenaKernel AtlasDetDescr CommissionEvent DerivationFrameworkInterfaces ExpressionEvaluationLib FourMomUtils GaudiKernel InDetIdentifier InDetPrepRawData InDetRIO_OnTrack InDetReadoutGeometry InDetTrackSelectionToolLib LArRecEvent SCT_CablingLib SCT_ConditionsToolsLib StoreGateLib TRT_ConditionsServicesLib TRT_ElectronPidToolsLib TRT_ReadoutGeometry TrigDecisionToolLib TrkCompetingRIOsOnTrack TrkEventPrimitives TrkEventUtils TrkExInterfaces TrkParameters TrkPrepRawData TrkRIO_OnTrack TrkToolInterfaces TrkTrack TrkVertexFitterInterfaces xAODBase xAODCore xAODEgamma xAODEventInfo xAODJet xAODMuon xAODTau xAODTracking )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/python/InDetCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/python/InDetCommon.py
index 4e0edd43f80f9858a37f5169de08d77d82b68c79..1c7bb13b23cacf6e6343da62c72489701f6d6fad 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/python/InDetCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/python/InDetCommon.py
@@ -5,11 +5,13 @@
 # Schedules all tools needed for ID track object selection and writes
 # results into SG. These may then be accessed along the train   
 #********************************************************************
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 # Check file contains PrimaryVertices container (protect against non-collision data)
 # If running from RAW the eventdata_items are none or emtpy
 from RecExConfig.InputFilePeeker import inputFileSummary
+from AthenaCommon import CfgMgr
+from AthenaCommon.AppMgr import ToolSvc
 from AthenaCommon.BeamFlags import jobproperties
 from InDetRecExample.InDetJobProperties import InDetFlags
 
@@ -47,8 +49,7 @@ if have_PV_container :
 #=======================================
 # CREATE THE DERIVATION KERNEL ALGORITHM   
 #=======================================
-    
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
+
     DerivationFrameworkJob += CfgMgr.DerivationFramework__CommonAugmentation("InDetCommonKernel",
                                                                              AugmentationTools = [DFCommonTrackSelection,DFCommonZ0AtPV]
                                                                              )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/CMakeLists.txt
index a1044f0500ec8de4f91bf7bdcfd4b900d0b16330..f7b7f6f31067eda7f33fb11d51ff968eebc407fd 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/CMakeLists.txt
@@ -13,5 +13,5 @@ atlas_add_component( DerivationFrameworkJetEtMiss
                      LINK_LIBRARIES ${ROOT_LIBRARIES} AsgTools AthLinks AthenaBaseComps DerivationFrameworkInterfaces FTagAnalysisInterfacesLib GaudiKernel InDetTrackSelectionToolLib JetAnalysisInterfacesLib JetInterface PFlowUtilsLib ParticleJetToolsLib PathResolver StoreGateLib TrackVertexAssociationToolLib TrigAnalysisInterfaces xAODCaloEvent xAODCore xAODEventInfo xAODJet xAODPFlow xAODTracking xAODTrigger xAODTruth )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/ExtendedJetCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/ExtendedJetCommon.py
index 739e6b3bfa324ad820e6d6ab9fc5214100b03dc3..082f7414d39394a1a6ee8b05fb6729cf565f33f8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/ExtendedJetCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/ExtendedJetCommon.py
@@ -5,11 +5,11 @@
 # Schedules special jet tools
 #********************************************************************
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
-from JetRec.JetRecFlags import jetFlags
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob, DerivationFrameworkIsMonteCarlo
+from DerivationFrameworkJetEtMiss.JetCommon import addStandardJets, addSoftDropJets, addTrimmedJets
 from JetJvtEfficiency.JetJvtEfficiencyToolConfig import (getJvtEffTool, getJvtEffToolName)
 
+from AthenaCommon import CfgMgr
 from AthenaCommon import Logging
 extjetlog = Logging.logging.getLogger('ExtendedJetCommon')
 
@@ -44,6 +44,7 @@ def addTCCTrimmedJets(sequence,outputlist,dotruth=True,writeUngroomed=False):
                    algseq=sequence, outputGroup=outputlist, writeUngroomed=writeUngroomed)
 
 def addCSSKSoftDropJets(sequence, seq_name, logger=extjetlog):
+    from DerivationFrameworkFlavourTag.HbbCommon import addVRJets, buildVRJets
     vrJetName, vrGhostLabel = buildVRJets(
         sequence, do_ghost=True, logger=logger)
 
@@ -115,15 +116,17 @@ def addAntiKt4TruthDressedWZJets(sequence,outputlist):
         addStandardJets("AntiKt", 0.4, "TruthDressedWZ", ptmin=5000, mods="truth_ungroomed", algseq=sequence, outputGroup=outputlist)
 
 def addAntiKt10TruthJets(sequence,outputlist):
+    from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkHasTruth
     if DerivationFrameworkHasTruth:
         addStandardJets("AntiKt", 1.0, "Truth", ptmin=40000, mods="truth_ungroomed_larger", algseq=sequence, outputGroup=outputlist)
 
 def addAntiKt10TruthWZJets(sequence,outputlist):
+    from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkHasTruth
     if DerivationFrameworkHasTruth:
         addStandardJets("AntiKt", 1.0, "TruthWZ", ptmin=40000, mods="truth_ungroomed_larger", algseq=sequence, outputGroup=outputlist)
 
 def addAntiKt4EMPFlowJetsFE(sequence, outputlist):
-    addCHSPFlowObjectsFE()
+    addCHSPFlowObjectsFE()   # noqa: F821 (FIXME, does not exist)
     addStandardJets("AntiKt", 0.4, "EMPFlowFE", ptmin=10000, ptminFilter=15000, mods="pflow_ungroomed", algseq=sequence, outputGroup=outputlist)
 
 ##################################################################  
@@ -147,7 +150,7 @@ def replaceAODReducedJets(jetlist,sequence,outputlist):
     if "AntiKt10TruthWZJets" in jetlist:
         addAntiKt10TruthWZJets(sequence,outputlist)
     if "AntiKt2LCTopoJets" in jetlist:
-        addAntiKt2LCTopoJets(sequence,outputlist)
+        addAntiKt2LCTopoJets(sequence,outputlist)  # noqa: F821 (FIXME, does not exist)
     if "AntiKt10LCTopoJets" in jetlist:
         addAntiKt10LCTopoJets(sequence,outputlist)
 
@@ -187,7 +190,7 @@ def applyJetAugmentation(jetalg,algname,sequence,jetaugtool):
         jetaug = CfgMgr.DerivationFramework__CommonAugmentation(algname)
         sequence += jetaug
 
-    if not jetaugtool in jetaug.AugmentationTools:
+    if jetaugtool not in jetaug.AugmentationTools:
         jetaug.AugmentationTools.append(jetaugtool)
 
 def getJetAugmentationTool(jetalg, suffix=''):
@@ -253,7 +256,7 @@ def applyJetCalibration(jetalg,algname,sequence,largeRjetconfig = 'comb', suffix
         isdata=False
 
         #largeRconfig selects config file for AntiKt10LCTopoTrimmedPtFrac5SmallR20, default is JES_MC16recommendation_FatJet_JMS_comb_19Jan2018.config
-        if not largeRjetconfig in ['comb','calo','TA']:
+        if largeRjetconfig not in ['comb','calo','TA']:
             extjetlog.warning('*** Wrong value for fatjetconfig!  Only \'comb\' (default), \'calo\' or \'TA\' can be used. ***')
 
         #Warning: these are quite outdated ... leaving for validation purposes for now
@@ -280,6 +283,7 @@ def applyJetCalibration(jetalg,algname,sequence,largeRjetconfig = 'comb', suffix
         isMC = DerivationFrameworkIsMonteCarlo
         isAF2 = False
         if isMC:
+            from RecExConfig.InputFilePeeker import inputFileSummary
             isAF2 = 'ATLFASTII' in inputFileSummary['metadata']['/Simulation/Parameters']['SimulationFlavour'].upper()
         if isMC and isAF2:
             ## Warning: these are quite outdated ... leaving for validation purposes for now
@@ -312,7 +316,7 @@ def applyJetCalibration(jetalg,algname,sequence,largeRjetconfig = 'comb', suffix
 
 def applyJetCalibration_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     supportedJets = ['AntiKt4EMTopo','AntiKt4LCTopo','AntiKt4EMPFlow','AntiKt4EMTopo_BTagging201810','AntiKt4EMPFlow_BTagging201810']
-    if not jetalg in supportedJets:
+    if jetalg not in supportedJets:
         extjetlog.warning('*** Calibration requested for unsupported jet collection '+jetalg+'! ***')
         return
     else:
@@ -322,7 +326,7 @@ def applyJetCalibration_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrame
 
 def applyJetCalibration_CustomColl(jetalg='AntiKt10LCTopoTrimmedPtFrac5SmallR20',sequence=None):
     supportedJets = ['AntiKt10LCTopoTrimmedPtFrac5SmallR20','AntiKt2LCTopo']
-    if not jetalg in supportedJets:
+    if jetalg not in supportedJets:
         extjetlog.warning('*** Calibration requested for unsupported jet collection! ***')
         extjetlog.warning('Supported custom jets: '+supportedJets)
         return
@@ -335,7 +339,7 @@ def applyJetCalibration_CustomColl(jetalg='AntiKt10LCTopoTrimmedPtFrac5SmallR20'
 
 def updateJVT(jetalg,algname,sequence, suffix = '',customVxColl = 'PrimaryVertices'):
     jetaugtool = getJetAugmentationTool(jetalg, suffix)
-    if(jetaugtool==None or jetaugtool.JetCalibTool==''):
+    if(jetaugtool is None or jetaugtool.JetCalibTool==''):
         extjetlog.warning('*** JVT update called but corresponding augmentation tool does not exist! ***')
         extjetlog.warning('*** You must apply jet calibration before scheduling JVT! ***')
 
@@ -381,7 +385,7 @@ def updateJVT(jetalg,algname,sequence, suffix = '',customVxColl = 'PrimaryVertic
 
 def updateJVT_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     supportedJets = ['AntiKt4EMTopo','AntiKt4EMPFlow','AntiKt4EMTopo_BTagging201810','AntiKt4EMPFlow_BTagging201810']
-    if not jetalg in supportedJets:
+    if jetalg not in supportedJets:
         extjetlog.warning('*** JVT update requested for unsupported jet collection {}! ***'.format(jetalg))
         return
     else:
@@ -391,7 +395,7 @@ def updateJVT_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
 
 def addJetPtAssociation(jetalg, truthjetalg, sequence, algname):
     jetaugtool = getJetAugmentationTool(jetalg, '_PtAssoc')
-    if(jetaugtool==None):
+    if(jetaugtool is None):
         extjetlog.warning('*** addJetPtAssociation called but corresponding augmentation tool does not exist! ***')
 
     jetptassociationtoolname = 'DFJetPtAssociation_'+truthjetalg
@@ -413,10 +417,10 @@ def addJetTruthLabel(jetalg,algname,labelname,sequence):
     supportedTruthJets = ['AntiKt10Truth','AntiKt10TruthTrimmedPtFrac5SmallR20']
     supportedRecoJets = ['AntiKt10LCTopoTrimmedPtFrac5SmallR20','AntiKt10TrackCaloClusterTrimmedPtFrac5SmallR20','AntiKt10UFOCSSKTrimmedPtFrac5SmallR20','AntiKt10UFOCSSKSoftDropBeta100Zcut10','AntiKt10UFOCSSKBottomUpSoftDropBeta100Zcut5','AntiKt10UFOCSSKRecursiveSoftDropBeta100Zcut5Ninf','AntiKt10UFOCHSTrimmedPtFrac5SmallR20']
     supportedJets = supportedRecoJets + supportedTruthJets
-    if not jetalg in supportedJets:
+    if jetalg not in supportedJets:
         extjetlog.warning('*** JetTruthLabeling augmentation requested for unsupported jet collection {}! ***'.format(jetalg))
         return
-    elif not labelname in supportedLabelNames:
+    elif labelname not in supportedLabelNames:
         extjetlog.warning('*** JetTruthLabeling augmentation requested for unsupported label definition {}! ***'.format(labelname))
         return
     else:
@@ -426,7 +430,7 @@ def addJetTruthLabel(jetalg,algname,labelname,sequence):
 
         jetaugtool = getJetAugmentationTool(jetalg)
 
-        if(jetaugtool==None):
+        if(jetaugtool is None):
             extjetlog.warning('*** addJetTruthLabel called but corresponding augmentation tool does not exist! ***')
             return
 
@@ -451,7 +455,7 @@ def applyBTaggingAugmentation(jetalg,algname='default',sequence=DerivationFramew
       algname = 'JetCommonKernel_{0}'.format(jetalg)
     jetaugtool = getJetAugmentationTool(jetalg)
 
-    if(jetaugtool==None or jetaugtool.JetCalibTool=='' or jetaugtool.JetJvtTool==''):
+    if(jetaugtool is None or jetaugtool.JetCalibTool=='' or jetaugtool.JetJvtTool==''):
         extjetlog.warning('*** B-tagging called but corresponding augmentation tool does not exist! ***')
         extjetlog.warning('*** You must apply jet calibration and JVT! ***')
 
@@ -474,12 +478,12 @@ def applyBTaggingAugmentation(jetalg,algname='default',sequence=DerivationFramew
 #################################################################
 def addQGTaggerTool(jetalg, sequence, algname, truthjetalg=None ):
     jetaugtool = getJetAugmentationTool(jetalg,'_qgTag')
-    if(jetaugtool==None):
+    if(jetaugtool is None):
         extjetlog.warning('*** addQGTaggerTool called but corresponding augmentation tool does not exist! ***')
 
     from AthenaCommon.AppMgr import ToolSvc
 
-    if truthjetalg!=None:
+    if truthjetalg is not None:
         jetptassociationtoolname = 'DFJetPtAssociation_'+truthjetalg+'_'+jetalg
         if hasattr(ToolSvc,jetptassociationtoolname):
             jetaugtool.JetPtAssociationTool = getattr(ToolSvc,jetptassociationtoolname)
@@ -567,7 +571,6 @@ def getJetCleaningTool(cleaningLevel):
 def eventCleanLoose_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     from JetSelectorTools.JetSelectorToolsConf import ECUtils__EventCleaningTool as EventCleaningTool
     from JetSelectorTools.JetSelectorToolsConf import EventCleaningTestAlg
-    jetcleaningtoolname = "EventCleaningTool_Loose"
     prefix = "DFCommonJets_"
     ecToolLoose = EventCleaningTool('EventCleaningTool_Loose',CleaningLevel='LooseBad')
     ecToolLoose.JetCleanPrefix = prefix
@@ -583,7 +586,6 @@ def eventCleanLoose_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFramework
 def eventCleanTight_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     from JetSelectorTools.JetSelectorToolsConf import ECUtils__EventCleaningTool as EventCleaningTool
     from JetSelectorTools.JetSelectorToolsConf import EventCleaningTestAlg
-    jetcleaningtoolname = "EventCleaningTool_Tight"
     prefix = "DFCommonJets_"
     ecToolTight = EventCleaningTool('EventCleaningTool_Tight',CleaningLevel='TightBad')
     ecToolTight.JetCleanPrefix = prefix
@@ -601,7 +603,6 @@ def eventCleanTight_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFramework
 def eventCleanLooseLLP_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     from JetSelectorTools.JetSelectorToolsConf import ECUtils__EventCleaningTool as EventCleaningTool
     from JetSelectorTools.JetSelectorToolsConf import EventCleaningTestAlg
-    jetcleaningtoolname = "EventCleaningTool_LooseLLP"
     prefix = "DFCommonJets_"
     ecToolLooseLLP = EventCleaningTool('EventCleaningTool_LooseLLP',CleaningLevel='LooseBadLLP')
     ecToolLooseLLP.JetCleanPrefix = prefix
@@ -619,7 +620,6 @@ def eventCleanLooseLLP_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFramew
 def eventCleanVeryLooseLLP_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     from JetSelectorTools.JetSelectorToolsConf import ECUtils__EventCleaningTool as EventCleaningTool
     from JetSelectorTools.JetSelectorToolsConf import EventCleaningTestAlg
-    jetcleaningtoolname = "EventCleaningTool_VeryLooseLLP"
     prefix = "DFCommonJets_"
     #Do not save decorations, which are anyway not listed in AntiKt4EMTopoJetsCPContent.py
     ecToolVeryLooseLLP = EventCleaningTool('EventCleaningTool_VeryLooseLLP',CleaningLevel='VeryLooseBadLLP')
@@ -638,7 +638,6 @@ def eventCleanVeryLooseLLP_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFr
 def eventCleanSuperLooseLLP_xAODColl(jetalg='AntiKt4EMTopo',sequence=DerivationFrameworkJob):
     from JetSelectorTools.JetSelectorToolsConf import ECUtils__EventCleaningTool as EventCleaningTool
     from JetSelectorTools.JetSelectorToolsConf import EventCleaningTestAlg
-    jetcleaningtoolname = "EventCleaningTool_SuperLooseLLP"
     prefix = "DFCommonJets_"
     #Do not save decorations, which are anyway not listed in AntiKt4EMTopoJetsCPContent.py
     ecToolSuperLooseLLP = EventCleaningTool('EventCleaningTool_SuperLooseLLP',CleaningLevel='SuperLooseBadLLP')
@@ -744,13 +743,13 @@ def addOriginCorrectedClusters(slimhelper,writeLC=False,writeEM=False):
     slimhelper.ExtraVariables.append('CaloCalTopoClusters.calE.calEta.calPhi.calM')
 
     if writeLC:
-        if not slimhelper.AppendToDictionary.has_key("LCOriginTopoClusters"):
+        if "LCOriginTopoClusters" not in slimhelper.AppendToDictionary:
             slimhelper.AppendToDictionary["LCOriginTopoClusters"]='xAOD::CaloClusterContainer'
             slimhelper.AppendToDictionary["LCOriginTopoClustersAux"]='xAOD::ShallowAuxContainer'
             slimhelper.ExtraVariables.append('LCOriginTopoClusters.calEta.calPhi')
 
     if writeEM:
-        if not slimhelper.AppendToDictionary.has_key("EMOriginTopoClusters"):
+        if "EMOriginTopoClusters" not in slimhelper.AppendToDictionary:
             slimhelper.AppendToDictionary["EMOriginTopoClusters"]='xAOD::CaloClusterContainer'
             slimhelper.AppendToDictionary["EMOriginTopoClustersAux"]='xAOD::ShallowAuxContainer'
             slimhelper.ExtraVariables.append('EMOriginTopoClusters.calE.calEta.calPhi')
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/HiggsCustomMET.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/HiggsCustomMET.py
index c693ed07685548c8bac12194d9dc4304d91d78c3..279a827b7b3a595261db718c3c2c6d81f6c315cd 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/HiggsCustomMET.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/HiggsCustomMET.py
@@ -1,8 +1,6 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 # Set up custom MET reconstruction algorithms
 from METReconstruction.METRecoFlags import metFlags
 from METReconstruction.METRecoConfig import BuildConfig, RefConfig, METConfig, getMETRecoAlg
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetCommon.py
index cca3d4b75189fa213237e34e2e3e6bc14232c76e..1d104b57b25493eb1d59fde98db74b0062cbc360 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetCommon.py
@@ -6,11 +6,9 @@
 # results into SG. These may then be accessed along the train  
 #********************************************************************
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 from AthenaCommon.GlobalFlags  import globalflags
-
+from AthenaCommon import CfgMgr
 from AthenaCommon import Logging
 dfjetlog = Logging.logging.getLogger('JetCommon')
 
@@ -47,7 +45,7 @@ else:
         else:
             batmanaugtool = CfgMgr.DerivationFramework__BadBatmanAugmentationTool("BadBatmanAugmentationTool")
             ToolSvc += batmanaugtool
-        if not batmanaugtool in batmanaug.AugmentationTools:
+        if batmanaugtool not in batmanaug.AugmentationTools:
             batmanaug.AugmentationTools.append(batmanaugtool)
     else:
         if not objKeyStore.isInInput( "McEventCollection", "GEN_EVENT" ):
@@ -61,8 +59,6 @@ def defineEDAlg(R=0.4, inputtype="LCTopo"):
     from EventShapeTools.EventDensityConfig import configEventDensityTool, EventDensityAlg
     from AthenaCommon.AppMgr import ToolSvc
 
-    from JetRec.JetRecStandard import jtm
-
     t=configEventDensityTool("EDTool"+str(int(R*10))+inputtype,
                              inputlabel = inputtype,
                              radius = R)
@@ -85,7 +81,6 @@ def moveEDAlg(seq):
 def addGhostAssociation(DerivationFrameworkJob):
 
     from JetRec.JetRecStandard import jtm
-    from JetRec.JetRecConf import PseudoJetGetter
 
     flavorgetters1 = []
     for ptype in jetFlags.truthFlavorTags():
@@ -109,7 +104,6 @@ def reCreatePseudoJets(jetalg, rsize, inputtype, variableRMassScale=-1.0, variab
     from JetRec.JetRecUtils import buildJetContName
     constmodstr = "".join(constmods)
     inputname = inputtype+constmodstr
-    label = inputtype + constmodstr
     jetContName = buildJetContName(jetalg, rsize, inputname, variableRMassScale, variableRMinRadius)
 
     # Set default for the arguments to be passd to addJetFinder
@@ -232,7 +226,6 @@ def buildGenericGroomAlg(jetalg, rsize, inputtype, groomedName, jetToolBuilder,
     from JetRec.JetRecUtils import buildJetContName
     constmodstr = "".join(constmods)
     inputname = inputtype+constmodstr
-    label = inputtype + constmodstr
     ungroomedName = buildJetContName(jetalg, rsize, inputname, variableRMassScale, variableRMinRadius)
     ungroomedalgname = "jetalg"+ungroomedName[:-4] # Remove "Jets" from name
 
@@ -256,12 +249,13 @@ def buildGenericGroomAlg(jetalg, rsize, inputtype, groomedName, jetToolBuilder,
         # this returns a list of the needed tools to do so.
         jetalgTools = reCreatePseudoJets(jetalg, rsize, inputtype, variableRMassScale, variableRMinRadius, algseq, constmods=constmods)
 
-        if includePreTools and jetFlags.useTracks() and not "Truth" in inputtype:
+        if includePreTools and jetFlags.useTracks() and "Truth" not in inputtype:
             # enable track ghost association and JVF
+            from JetRec.JetRecStandard import jtm
             jetalgTools =  [jtm.tracksel, jtm.tvassoc] + jetalgTools 
 
         finderalg = JetAlgorithm(ungroomedalgname, Tools = jetalgTools )
-        DFJetAlgs[ungroomedalgname] = finderalg;
+        DFJetAlgs[ungroomedalgname] = finderalg
         dfjetlog.info( "Added jet finder "+ungroomedalgname+" to sequence "+algseq.name() )
         algseq += finderalg
 
@@ -275,7 +269,7 @@ def buildGenericGroomAlg(jetalg, rsize, inputtype, groomedName, jetToolBuilder,
     
     dfjetlog.info( "Added jet groomer "+algname+" to sequence "+algseq.name() )
     groomeralg = JetAlgorithm(algname, Tools = [fatjet_groom])
-    DFJetAlgs[algname] = groomeralg;
+    DFJetAlgs[algname] = groomeralg
     algseq += groomeralg
     return groomeralg
 
@@ -283,7 +277,6 @@ def buildGenericGroomAlg(jetalg, rsize, inputtype, groomedName, jetToolBuilder,
 def addTrimmedJets(jetalg, rsize, inputtype, rclus=0.3, ptfrac=0.05, mods="groomed",
                    includePreTools=False, algseq=None, outputGroup="Trimmed",
                    writeUngroomed=False, variableRMassScale=-1.0, variableRMinRadius=-1.0, constmods=[]):
-    from JetRec.JetRecUtils import buildJetContName
     from JetRec.JetRecUtils import buildJetAlgName
     inputname = inputtype + "".join(constmods)
     trimmedName = "{0}{1}TrimmedPtFrac{2}SmallR{3}Jets".format(buildJetAlgName(jetalg, rsize, variableRMassScale, variableRMinRadius),inputname,int(ptfrac*100),int(rclus*100))
@@ -437,7 +430,7 @@ def addStandardJets(jetalg, rsize, inputtype, ptmin=0., ptminFilter=0.,
         return DFJetAlgs[algname]
 
     from JetRec.JetRecStandard import jtm
-    if not jetname in jtm.tools:
+    if jetname not in jtm.tools:
         # no container exist. simply build a new one.
         # Set default for the arguments to be passd to addJetFinder
         defaultmods = {"EMTopo":"emtopo_ungroomed",
@@ -520,7 +513,7 @@ def addDistanceInTrain(sequence=DerivationFrameworkJob):
                 ToolSvc += BunchCrossingTool( "LHC" )
                 distanceintrainaugtool.BCTool = "Trig::LHCBunchCrossingTool/BunchCrossingTool"
             ToolSvc += distanceintrainaugtool
-        if not distanceintrainaugtool in distanceintrainaug.AugmentationTools:
+        if distanceintrainaugtool not in distanceintrainaug.AugmentationTools:
             distanceintrainaug.AugmentationTools.append(distanceintrainaugtool)
 
 ##################################################################
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMetCustomMET.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMetCustomMET.py
index e22122c4cc9b11ccd6fbf7519b0731f96712bfcd..77160cfe3ee42e8f5b2dd0c33d44865af12f23ac 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMetCustomMET.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMetCustomMET.py
@@ -1,8 +1,6 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 # Set up custom MET reconstruction algorithms
 from METReconstruction.METRecoFlags import metFlags
 from METReconstruction.METRecoConfig import BuildConfig, RefConfig, METConfig, getMETRecoAlg
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMomentFix.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMomentFix.py
index eb775e1f712168548404dd769e85d4f37479a6f5..caefab41b99807604d09b6f4c0fd487570bdb6e8 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMomentFix.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/JetMomentFix.py
@@ -5,13 +5,11 @@
 # Schedules jet moment corrections
 #********************************************************************
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 from JetRec.JetRecConf import JetAlgorithm
-from DerivationFrameworkJetEtMiss.DFJetMetFlags import *
+from JetRec.JetRecStandard import jtm
+from DerivationFrameworkJetEtMiss.DFJetMetFlags import dfjmFlags
 
 if dfjmFlags.doJetTrackMomentFix:
     print ("Scheduling jet track moment fix: ")
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METCommon.py
index dc7b3b4f924fa13f77594c0003a3615fa0a22255..f1225557349114474fa945d122817f8d8a8b62ab 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METCommon.py
@@ -5,9 +5,8 @@
 # Schedules default DF MET content building tools and writes the
 # results into SG. These may then be accessed along the train  
 #********************************************************************
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from AthenaCommon import CfgMgr
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 ##########################################################################################
 # MET
@@ -73,7 +72,7 @@ metalgs = {}
 def addMETTruthMap(jetcoll='AntiKt4EMTopo',configlist="CustomMET"):
     assocname = 'Truth_'+jetcoll
     customMETConfigs.setdefault(configlist,{})
-    if not assocname in customMETConfigs[configlist]:
+    if assocname not in customMETConfigs[configlist]:
         from METReconstruction.METAssocConfig import METAssocConfig,AssocConfig
         cfg_truthassoc = METAssocConfig(assocname,
                         [AssocConfig('Truth',jetcoll+'Jets')],
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METTriggerDerivationContent.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METTriggerDerivationContent.py
index 368277ad4a23c477c38e1a0ae77ec73dbd82329b..d4fb08f284d085b2047569907e2331188688d1c2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METTriggerDerivationContent.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/METTriggerDerivationContent.py
@@ -1,13 +1,11 @@
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
-from DerivationFrameworkJetEtMiss.ExtendedJetCommon import *
-from DerivationFrameworkJetEtMiss.METCommon import *
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+
+from AthenaCommon import CfgMgr
 
 from DerivationFrameworkCore.ThinningHelper import ThinningHelper
 from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning, DerivationFramework__MuonTrackParticleThinning, DerivationFramework__EgammaTrackParticleThinning, DerivationFramework__TauTrackParticleThinning
 from DerivationFrameworkCore.SlimmingHelper import SlimmingHelper
 from AthenaCommon.SystemOfUnits import GeV
-from AthenaCommon.AppMgr import ToolSvc
 from DerivationFrameworkJetEtMiss.PFlowCommon import applyPFOAugmentation
 
 class METTriggerDerivationContentManager(object):
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowCommon.py
index 2a0dff341119b21e95cbe8af473fd00e035ac592..0adbc619dc0773bb5baa836a89ed35b63ad7572a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowCommon.py
@@ -1,8 +1,7 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from AthenaCommon import CfgMgr
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 def applyPFOAugmentation(sequence=DerivationFrameworkJob):
 
@@ -26,7 +25,7 @@ def applyPFOAugmentation(sequence=DerivationFrameworkJob):
             pfoaugtool = CfgMgr.DerivationFramework__PFlowAugmentationTool("PFlowAugmentationTool",
                                                                            WeightPFOTool=weightpfotool)
             ToolSvc += pfoaugtool
-        if not pfoaugtool in pfaug.AugmentationTools:
+        if pfoaugtool not in pfaug.AugmentationTools:
             pfaug.AugmentationTools.append(pfoaugtool)        
 
 ##################################################################
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowJetCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowJetCommon.py
index d853948733e5f31944a236481f1688ae2985c77b..1e21d0fd4b5d2d39aa6c59e10a3d86af37816b17 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowJetCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/PFlowJetCommon.py
@@ -1,15 +1,13 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 #********************************************************************
 # PFlowJetCommon.py
 # Schedules special jet tools
 #********************************************************************
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
+from DerivationFrameworkJetEtMiss.JetCommon import addPFlowJets
 
-from JetRec.JetRecStandard import jtm
-from JetRec.JetRecConf import JetAlgorithm
 jetalg1 = addPFlowJets("EM", 0.4)
 jetalg2 = addPFlowJets("EMC", 0.4)
 DerivationFrameworkJob += jetalg1
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/SUSYCustomMET.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/SUSYCustomMET.py
index c3f99bfe905b5fb3ef003050710857c5ef28f758..b5e4faf21ef35dad13df995c5aa637edf7672add 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/SUSYCustomMET.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/SUSYCustomMET.py
@@ -1,8 +1,6 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 # Set up custom MET reconstruction algorithms
 from METReconstruction.METRecoFlags import metFlags
 from METReconstruction.METRecoConfig import BuildConfig, RefConfig, METConfig, getMETRecoAlg
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/TopCustomMET.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/TopCustomMET.py
index 3e833445ed9b1f49dfa78cfc0d3575f1f6044dbc..bfe028791df65269f39d14a8882dfcfd4de7b6c6 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/TopCustomMET.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/python/TopCustomMET.py
@@ -1,8 +1,6 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-from __future__ import print_function
-
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 # Set up custom MET reconstruction algorithms
 from METReconstruction.METRecoFlags import metFlags
 from METReconstruction.METRecoConfig import BuildConfig, RefConfig, METConfig, getMETRecoAlg
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/CMakeLists.txt
index 4d703be048a6917beb4a40bca3b01b13c439279d..c3e0c29fb35b887d0b978f89e82ab0f0aeb82c86 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/CMakeLists.txt
@@ -16,6 +16,6 @@ atlas_add_component( DerivationFrameworkMCTruth
                      LINK_LIBRARIES ${Boost_LIBRARIES} ${FASTJET_LIBRARIES} ${HEPPDT_LIBRARIES} ${ROOT_LIBRARIES} AthenaBaseComps AthenaKernel AtlasHepMCLib DerivationFrameworkInterfaces ExpressionEvaluationLib GaudiKernel GenInterfacesLib GeneratorObjects MCTruthClassifierLib StoreGateLib TauAnalysisToolsLib TruthUtils xAODBase xAODEgamma xAODEventInfo xAODEventShape xAODJet xAODMuon xAODTruth )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/HFHadronsCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/HFHadronsCommon.py
index 56af6be1820f0fdea8a69ef9378750b3f4e02ca0..e2287b4056f33dfebbc4b4c3790ff335980072ff 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/HFHadronsCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/HFHadronsCommon.py
@@ -3,7 +3,10 @@
 #############################################
 # Heavy flavour from tt tools
 #############################################
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from AthenaCommon import CfgMgr
+from AthenaCommon.AppMgr import ToolSvc
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
+
 DSIDList=[
   410000,
   410001,
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/MCTruthCommon.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/MCTruthCommon.py
index b120796b22269b6da7f4cb750aa75d895f93d763..8ba6d1969e81d24a8be3d417e8bce4d6ec7c8773 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/MCTruthCommon.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/MCTruthCommon.py
@@ -1,11 +1,12 @@
 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Add translator from EVGEN input to xAOD-like truth here
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 from RecExConfig.ObjKeyStore import objKeyStore
 from xAODTruthCnv.xAODTruthCnvConf import xAODMaker__xAODTruthCnvAlg
-from DerivationFrameworkMCTruth.TruthDerivationTools import *
+import DerivationFrameworkMCTruth.TruthDerivationTools as dfTruth
 
+from AthenaCommon import CfgMgr
 from AthenaCommon import Logging
 dfcommontruthlog = Logging.logging.getLogger('DFCommonTruth')
 
@@ -53,7 +54,6 @@ def addTruthJetsEVNT(kernel=None, decorationDressing=None):
         kernel = DerivationFrameworkJob
     # Add jet algorithms if they aren't there
     from JetRec.JetRecStandard import jtm
-    from JetRec.JetRecConf import JetAlgorithm
     truth_modifiers = [jtm.truthpartondr, jtm.partontruthlabel, jtm.jetdrlabeler, jtm.trackjetdrlabeler]
     if not objKeyStore.isInInput( "xAOD::JetContainer","AntiKt4TruthJets") and not hasattr(kernel,'jetalgAntiKt4Truth'):
         # Standard truth jets
@@ -77,7 +77,7 @@ def addTruthJetsEVNT(kernel=None, decorationDressing=None):
     if not objKeyStore.isInInput( "xAOD::JetContainer","AntiKt10TruthJets") and not hasattr(kernel,'jetalgAntiKt10Truth'):
         # AntiKt2 truth charged jets ghost association
         from JetRec.JetRecConf import PseudoJetGetter
-        if not 'gakt2truthchargedget' in jtm.tools:
+        if 'gakt2truthchargedget' not in jtm.tools:
             jtm += PseudoJetGetter("gakt2truthchargedget", # give a unique name
                                     InputContainer = "AntiKt2TruthChargedJets", # SG key
                                     Label = "GhostAntiKt2TruthChargedJets",   # this is the name you'll use to retrieve associated ghosts
@@ -104,9 +104,10 @@ def addTruthJetsEVNT(kernel=None, decorationDressing=None):
 
     if not objKeyStore.isInInput( "xAOD::JetContainer","AntiKt10TruthTrimmedPtFrac5SmallR20Jets") and not hasattr(kernel,'jetalgAntiKt10TruthTrimmedPtFrac5SmallR20'):
         #Large R jets
-        from DerivationFrameworkJetEtMiss.JetCommon import addTrimmedJets
+        #from DerivationFrameworkJetEtMiss.JetCommon import addTrimmedJets
         #addTrimmedJets('AntiKt', 1.0, 'Truth', rclus=0.2, ptfrac=0.05, mods="truth_groomed",
         #               algseq=kernel, outputGroup="Trimmed", writeUngroomed=False)
+        pass
 
 def addTruthJetsAOD(kernel=None, decorationDressing=None):
     # Ensure that we are adding it to something
@@ -122,9 +123,10 @@ def addTruthJetsAOD(kernel=None, decorationDressing=None):
     #    addAntiKt4TruthDressedWZJets(kernel,'TRUTH')
     if not objKeyStore.isInInput( "xAOD::JetContainer","AntiKt10TruthTrimmedPtFrac5SmallR20Jets"):
         #Large R jets
-        from DerivationFrameworkJetEtMiss.JetCommon import addTrimmedJets
+        #from DerivationFrameworkJetEtMiss.JetCommon import addTrimmedJets
         #addTrimmedJets('AntiKt', 1.0, 'Truth', rclus=0.2, ptfrac=0.05, mods="truth_groomed",
         #               algseq=kernel, outputGroup="Trimmed", writeUngroomed=False)
+        pass
     elif not objKeyStore.isInInput( "xAOD::JetContainer","AntiKt10TruthJets"):
         addAntiKt10TruthJets(kernel,"TRUTH")
 
@@ -143,7 +145,7 @@ def addTruthJets(kernel=None, decorationDressing=None):
             barCodeFromMetadata=0
         from JetRec.JetRecStandardToolManager import jtm
         from ParticleJetTools.ParticleJetToolsConf import CopyTruthJetParticles
-        if not 'truthpartdressedwz' in jtm.tools:
+        if 'truthpartdressedwz' not in jtm.tools:
             jtm += CopyTruthJetParticles("truthpartdressedwz", OutputName="JetInputTruthParticlesDressedWZ",
                                           MCTruthClassifier=jtm.JetMCTruthClassifier,
                                           #IncludePromptLeptons=False,#IncludePromptPhotons=False,
@@ -157,7 +159,7 @@ def addTruthJets(kernel=None, decorationDressing=None):
         kernel += JetAlgorithm("jetdressedwzalg")
         jetdressedwzalg = kernel.jetdressedwzalg
         jetdressedwzalg.Tools = [ jtm.jetdressedwzrun ]
-        if not 'truthdressedwzget' in jtm.tools:
+        if 'truthdressedwzget' not in jtm.tools:
             jtm += PseudoJetGetter("truthdressedwzget",
                                    Label = "TruthDressedWZ",
                                    InputContainer = jtm.truthpartdressedwz.OutputName,
@@ -175,10 +177,10 @@ def addTruthJets(kernel=None, decorationDressing=None):
         # make sure if we are using EVNT that we don't try to check sim metadata
         barCodeFromMetadata=2
         if objKeyStore.isInInput( "McEventCollection", "GEN_EVENT" ):
-            barCodeFromMetadata=0
+            barCodeFromMetadata=0   # noqa: F841 (kept for documentation purposes)
         from JetRec.JetRecStandardToolManager import jtm
         from ParticleJetTools.ParticleJetToolsConf import CopyTruthJetParticles
-        if not 'truthpartcharged' in jtm.tools:
+        if 'truthpartcharged' not in jtm.tools:
             jtm += CopyTruthJetParticles("truthpartcharged", OutputName="JetInputTruthParticlesCharged",
                                          MCTruthClassifier=jtm.JetMCTruthClassifier,
                                          #ChargedParticlesOnly=True,
@@ -191,7 +193,7 @@ def addTruthJets(kernel=None, decorationDressing=None):
         kernel += JetAlgorithm("jetchargedalg")
         jetchargedalg = kernel.jetchargedalg
         jetchargedalg.Tools = [ jtm.jetchargedrun ]
-        if not 'truthchargedget' in jtm.tools:
+        if 'truthchargedget' not in jtm.tools:
             jtm += PseudoJetGetter("truthchargedget",
                                    Label = "TruthCharged",
                                    InputContainer = jtm.truthpartcharged.OutputName,
@@ -216,7 +218,7 @@ def addTruthMET(kernel=None):
     # This should handle EVNT correctly without an explicit check
     from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
     if not objKeyStore.isInInput( "xAOD::MissingETContainer","MET_Truth") and not hasattr(DerivationFrameworkJob,"METReconstruction"):
-        import METReconstruction.METConfig_Truth
+        import METReconstruction.METConfig_Truth  # noqa: F401
         from METReconstruction.METRecoConfig import getMETRecoAlg
         metAlg = getMETRecoAlg('METReconstruction')
         kernel += metAlg
@@ -232,24 +234,24 @@ def schedulePreJetMCTruthAugmentations(kernel=None, decorationDressing=None):
     # These augmentations do *not* require truth jets at all
     # If requested, add a decoration to photons that were used in the dressing
     if decorationDressing is not None:
-        DFCommonTruthElectronDressingTool.decorationName = decorationDressing
-        DFCommonTruthMuonDressingTool.decorationName = decorationDressing
+        dfTruth.DFCommonTruthElectronDressingTool.decorationName = decorationDressing
+        dfTruth.DFCommonTruthMuonDressingTool.decorationName = decorationDressing
 
     # schedule the special truth building tools and add them to a common augmentation; note taus are handled separately below
-    augmentationToolsList = [ DFCommonTruthClassificationTool,
-                              DFCommonTruthMuonTool,DFCommonTruthElectronTool,
-                              DFCommonTruthPhotonToolSim,
-                              DFCommonTruthNeutrinoTool,
-                              DFCommonTruthBottomTool,
-                              DFCommonTruthTopTool,
-                              DFCommonTruthBosonTool,
-                              DFCommonTruthBSMTool,
-                              DFCommonTruthForwardProtonTool,
-                              DFCommonTruthElectronDressingTool, DFCommonTruthMuonDressingTool,
-                              DFCommonTruthElectronIsolationTool1, DFCommonTruthElectronIsolationTool2,
-                              DFCommonTruthMuonIsolationTool1, DFCommonTruthMuonIsolationTool2,
-                              DFCommonTruthPhotonIsolationTool1, DFCommonTruthPhotonIsolationTool2, DFCommonTruthPhotonIsolationTool3]
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
+    augmentationToolsList = [ dfTruth.DFCommonTruthClassificationTool,
+                              dfTruth.DFCommonTruthMuonTool,dfTruth.DFCommonTruthElectronTool,
+                              dfTruth.DFCommonTruthPhotonToolSim,
+                              dfTruth.DFCommonTruthNeutrinoTool,
+                              dfTruth.DFCommonTruthBottomTool,
+                              dfTruth.DFCommonTruthTopTool,
+                              dfTruth.DFCommonTruthBosonTool,
+                              dfTruth.DFCommonTruthBSMTool,
+                              dfTruth.DFCommonTruthForwardProtonTool,
+                              dfTruth.DFCommonTruthElectronDressingTool, dfTruth.DFCommonTruthMuonDressingTool,
+                              dfTruth.DFCommonTruthElectronIsolationTool1, dfTruth.DFCommonTruthElectronIsolationTool2,
+                              dfTruth.DFCommonTruthMuonIsolationTool1, dfTruth.DFCommonTruthMuonIsolationTool2,
+                              dfTruth.DFCommonTruthPhotonIsolationTool1, dfTruth.DFCommonTruthPhotonIsolationTool2, dfTruth.DFCommonTruthPhotonIsolationTool3]
+
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonPreJetKernel",
                                                              AugmentationTools = augmentationToolsList
                                                              )
@@ -272,7 +274,7 @@ def schedulePostJetMCTruthAugmentations(kernel=None, decorationDressing=None):
     # truth tau matching needs truth jets, truth electrons and truth muons
     from DerivationFrameworkTau.TauTruthCommon import scheduleTauTruthTools
     scheduleTauTruthTools(kernel)
-    augmentationToolsList = [ DFCommonTruthTauDressingTool ]
+    augmentationToolsList = [ dfTruth.DFCommonTruthTauDressingTool ]
 
     #Save the post-shower HT and MET filter values that will make combining filtered samples easier (adds to the EventInfo)
     #from DerivationFrameworkMCTruth.GenFilterToolSetup import DFCommonTruthGenFilter
@@ -293,8 +295,7 @@ def schedulePostJetMCTruthAugmentations(kernel=None, decorationDressing=None):
     if IsSUSYSignal():
         from DerivationFrameworkSUSY.DecorateSUSYProcess import DecorateSUSYProcess
         augmentationToolsList += DecorateSUSYProcess('MCTruthCommon')
-        
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
+
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonPostJetKernel",
                                                              AugmentationTools = augmentationToolsList
                                                              )
@@ -350,7 +351,7 @@ def addParentAndDownstreamParticles(kernel=None,
         # Already there!  Carry on...
         dfcommontruthlog.warning("Attempt to add a duplicate "+kernel_name+". Failing.")
         return
-    collection_name=collection_prefix+'WithDecay' if collection_prefix!=None else 'Truth'+prefix+'WithDecay'
+    collection_name=collection_prefix+'WithDecay' if collection_prefix is not None else 'Truth'+prefix+'WithDecay'
     # Set up a tool to keep the W/Z/H bosons and all downstream particles
     from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__TruthDecayCollectionMaker
     collection_maker = DerivationFramework__TruthDecayCollectionMaker( name='DFCommon'+prefix+'AndDecaysTool',
@@ -360,7 +361,6 @@ def addParentAndDownstreamParticles(kernel=None,
                                                                        RejectHadronChildren=rejectHadronChildren)
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += collection_maker
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation(kernel_name,
                                                              AugmentationTools = [collection_maker] )
 
@@ -431,7 +431,6 @@ def addHFAndDownstreamParticles(kernel=None, addB=True, addC=True, generations=-
                                                                               Generations=generations)
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonHFAndDecaysTool
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation(prefix+"MCTruthCommonHFAndDecaysKernel",
                                                              AugmentationTools = [DFCommonHFAndDecaysTool] )
 
@@ -451,7 +450,6 @@ def addPVCollection(kernel=None):
                                                                       NewCollectionName="TruthPrimaryVertices")
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonTruthPVCollTool
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonTruthPVCollKernel",
                                                              AugmentationTools = [DFCommonTruthPVCollTool] )
 
@@ -472,7 +470,6 @@ def addHardScatterCollection(kernel=None, generations=1):
                                                                          Generations=generations)
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonHSCollectionTool
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonHSCollectionKernel",
                                                              AugmentationTools = [DFCommonHSCollectionTool] )
 
@@ -493,7 +490,6 @@ def addTruthCollectionNavigationDecorations(kernel=None,TruthCollections=[], pre
                                                                                       InputCollections=TruthCollections)
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonTruthNavigationDecorator
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation(prefix+"MCTruthNavigationDecoratorKernel",
                                                              AugmentationTools = [DFCommonTruthNavigationDecorator] )
 
@@ -515,7 +511,6 @@ def addBSMAndDownstreamParticles(kernel=None, generations=-1):
                                                                          Generations=generations)
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonBSMAndDecaysTool
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonBSMAndDecaysKernel",
                                                              AugmentationTools = [DFCommonBSMAndDecaysTool] )
 
@@ -535,7 +530,6 @@ def addBornLeptonCollection(kernel=None):
                                                                          NewCollectionName="BornLeptons")
     from AthenaCommon.AppMgr import ToolSvc
     ToolSvc += DFCommonBornLeptonCollTool
-    from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
     kernel += CfgMgr.DerivationFramework__CommonAugmentation("MCTruthCommonBornLeptonsKernel",
                                                              AugmentationTools = [DFCommonBornLeptonCollTool] )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/TruthDerivationTools.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/TruthDerivationTools.py
index e1d8205d77b2b8b52d8fae04274c4370b3a6c621..c341e53339d2ec1936fb5948e89a70baa0e0728a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/TruthDerivationTools.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/python/TruthDerivationTools.py
@@ -2,10 +2,10 @@
 
 from AthenaCommon.AppMgr import ToolSvc
 
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkSimBarcodeOffset
 from MCTruthClassifier.MCTruthClassifierConf import MCTruthClassifier
 DFCommonTruthClassifier = MCTruthClassifier(name = "DFCommonTruthClassifier",
-                                    ParticleCaloExtensionTool = "") 
+                                            ParticleCaloExtensionTool = "")
 ToolSvc += DFCommonTruthClassifier
 
 #==============================================================================
@@ -75,7 +75,7 @@ DFCommonTruthBSMTool = DerivationFramework__TruthCollectionMaker(name
 ToolSvc += DFCommonTruthBSMTool
 
 # Set up a tool to keep forward protons for AFP
-# Note that we have inputFileSummary coming from derivation framework master
+from RecExConfig.InputFilePeeker import inputFileSummary
 if 'beam_energy' in inputFileSummary:
     beam_energy = inputFileSummary['beam_energy']
 elif '/TagInfo' in inputFileSummary and 'beam_energy' in inputFileSummary['/TagInfo']:
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/CMakeLists.txt
index 759f5c066d8594bd1172f21af9ab36764498638b..a472a8332264e3f836a6d91592830b1eca7df5a9 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/CMakeLists.txt
@@ -4,6 +4,6 @@
 atlas_subdir( DerivationFrameworkPhys )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_DataCompressionList.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_DataCompressionList.py
index d08346d71d90ed041d334846424cc196c45b229d..c61bcbf8155ecae54b75d7a2ecebd8f02cef646a 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_DataCompressionList.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_DataCompressionList.py
@@ -1,3 +1,5 @@
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+
 PHYS_DataCompressionList=[ 
 "SoftBVrtClusterTool_Loose_VerticesAux.", "SoftBVrtClusterTool_Medium_VerticesAux.", "SoftBVrtClusterTool_Tight_VerticesAux.", "AntiKt10LCTopoJetsAux.", "AntiKt10LCTopoTrimmedPtFrac5SmallR20JetsAux.", "AntiKt2PV0TrackJetsAux.", "AntiKt4EMPFlowJetsAux.", "AntiKt4EMTopoJetsAux.", "AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903Aux.", "AntiKt4EMPFlowJets_BTagging201810Aux.", "AntiKt4EMPFlowJets_BTagging201903Aux.", "AntiKt4EMTopoJets_BTagging201810Aux.", "xTrigDecisionAux.", "Kt4EMPFlowEventShapeAux.", "Kt4EMTopoOriginEventShapeAux.", "NeutralParticleFlowIsoCentralEventShapeAux.", "NeutralParticleFlowIsoForwardEventShapeAux.", "TopoClusterIsoCentralEventShapeAux.", "TopoClusterIsoForwardEventShapeAux.", "BTagging_AntiKt4EMPFlow_201810Aux.", "BTagging_AntiKt4EMPFlow_201903Aux.", "BTagging_AntiKt4EMTopo_201810Aux.", "BTagging_AntiKtVR30Rmax4Rmin02Track_201903Aux.", "CombinedMuonTrackParticlesAux.", "DiTauJetsAux.", "DiTauJetsLowPtAux.", "ElectronsAux.", "GSFConversionVerticesAux.", "GSFTrackParticlesAux.", "InDetForwardTrackParticlesAux.", "InDetTrackParticlesAux.", "MET_Core_AntiKt4EMPFlowAux.", "MET_Core_AntiKt4EMTopoAux.", "MET_TrackAux.", "MuonSpectrometerTrackParticlesAux.", "MuonsAux.", "PhotonsAux.", "PrimaryVerticesAux.", "TauJetsAux.", "TauTracksAux.", "TrigMatch_HLT_2e12_lhloose_nod0_mu10Aux.", "TrigMatch_HLT_2e17_lhvloose_nod0Aux.", "TrigMatch_HLT_2e17_lhvloose_nod0_L12EM15VHIAux.", "TrigMatch_HLT_2e24_lhvloose_nod0Aux.", "TrigMatch_HLT_2g20_tight_icalovloose_L12EM15VHIAux.", "TrigMatch_HLT_2g22_tightAux.", "TrigMatch_HLT_2g22_tight_L12EM15VHIAux.", "TrigMatch_HLT_2g22_tight_L1EM7_EMPTYAux.", "TrigMatch_HLT_2g22_tight_L1EM7_UNPAIRED_ISOAux.", "TrigMatch_HLT_2g22_tight_icalovlooseAux.", "TrigMatch_HLT_2g25_loose_g15_looseAux.", "TrigMatch_HLT_2g25_tight_L12EM20VHAux.", "TrigMatch_HLT_2g50_loose_L12EM20VHAux.", "TrigMatch_HLT_2mu14Aux.", "TrigMatch_HLT_2mu20_L12MU20_OVERLAYAux.", "TrigMatch_HLT_3g20_looseAux.", "TrigMatch_HLT_3mu3_mu3noL1_L13MU4Aux.", "TrigMatch_HLT_3mu4Aux.", "TrigMatch_HLT_3mu4_mu2noL1Aux.", "TrigMatch_HLT_3mu6Aux.", "TrigMatch_HLT_3mu6_msonlyAux.", "TrigMatch_HLT_3mu6_msonly_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_3mu6_msonly_L1MU6_EMPTYAux.", "TrigMatch_HLT_4mu4Aux.", "TrigMatch_HLT_e12_lhloose_nod0_2mu10Aux.", "TrigMatch_HLT_e140_lhloose_nod0Aux.", "TrigMatch_HLT_e140_lhloose_nod0_L1EM24VHIAux.", "TrigMatch_HLT_e140_lhvloose_nod0Aux.", "TrigMatch_HLT_e160_lhvloose_nod0Aux.", "TrigMatch_HLT_e17_lhloose_nod0_2e12_lhloose_nod0_L1EM15VH_3EM10VHAux.", "TrigMatch_HLT_e17_lhloose_nod0_mu14Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoEFAux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoEF_L1DR-EM15TAU12I-J25Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoEF_L1EM15VHI_2TAU12IM_4J12Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoMVA_L1DR-EM15TAU12I-J25Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoMVA_L1EM15VHI_2TAU12IM_4J12Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwo_L1DR-EM15TAU12I-J25Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwo_L1EM15VHI_2TAU12IM_4J12Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_mediumRNN_tracktwoMVAAux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_mediumRNN_tracktwoMVA_L1DR-EM15TAU12I-J25Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_mediumRNN_tracktwoMVA_L1EM15VHI_2TAU12IM_4J12Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_tau80_medium1_tracktwoAux.", "TrigMatch_HLT_e200_etcutAux.", "TrigMatch_HLT_e22_lhvloose_nod0_e12_lhvloose_nod0_e10_lhvloose_nod0_L1EM20VH_2EM10VH_3EM8VHAux.", "TrigMatch_HLT_e24_lhmedium_nod0_ivarloose_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_e24_lhmedium_nod0_ivarloose_tau35_medium1_tracktwoEFAux.", "TrigMatch_HLT_e24_lhmedium_nod0_ivarloose_tau35_medium1_tracktwoMVAAux.", "TrigMatch_HLT_e24_lhmedium_nod0_ivarloose_tau35_mediumRNN_tracktwoMVAAux.", "TrigMatch_HLT_e24_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e24_lhvloose_nod0_2e12_lhvloose_nod0_L1EM20VH_3EM10VHAux.", "TrigMatch_HLT_e26_lhloose_nod0Aux.", "TrigMatch_HLT_e26_lhmedium_nod0_mu8noL1Aux.", "TrigMatch_HLT_e26_lhtight_nod0Aux.", "TrigMatch_HLT_e26_lhtight_nod0_e15_etcut_L1EM7_ZeeAux.", "TrigMatch_HLT_e26_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e28_lhmedium_nod0_mu8noL1Aux.", "TrigMatch_HLT_e28_lhtight_nod0_L1EM22VHIAux.", "TrigMatch_HLT_e28_lhtight_nod0_e15_etcut_L1EM7_ZeeAux.", "TrigMatch_HLT_e28_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e28_lhtight_nod0_noringer_ivarlooseAux.", "TrigMatch_HLT_e300_etcutAux.", "TrigMatch_HLT_e60_lhmedium_nod0Aux.", "TrigMatch_HLT_e60_lhmedium_nod0_L1EM24VHIAux.", "TrigMatch_HLT_e7_lhmedium_nod0_mu24Aux.", "TrigMatch_HLT_e9_lhvloose_nod0_mu20_mu8noL1Aux.", "TrigMatch_HLT_e9_lhvloose_nod0_mu20_mu8noL1_L1EM7_MU20Aux.", "TrigMatch_HLT_g120_looseAux.", "TrigMatch_HLT_g140_looseAux.", "TrigMatch_HLT_g140_tightAux.", "TrigMatch_HLT_g200_etcutAux.", "TrigMatch_HLT_g200_looseAux.", "TrigMatch_HLT_g300_etcutAux.", "TrigMatch_HLT_g300_etcut_L1EM24VHIAux.", "TrigMatch_HLT_g35_loose_g25_looseAux.", "TrigMatch_HLT_g35_loose_g25_loose_L12EM20VHAux.", "TrigMatch_HLT_g35_medium_g25_medium_L12EM20VHAux.", "TrigMatch_HLT_g35_medium_g25_medium_L1EM7_EMPTYAux.", "TrigMatch_HLT_g35_medium_g25_medium_L1EM7_UNPAIRED_ISOAux.", "TrigMatch_HLT_id_cosmicid_L1MU11_EMPTYAux.", "TrigMatch_HLT_mu13_mu13_idperf_ZmumuAux.", "TrigMatch_HLT_mu14_ivarloose_L1MU11_tau35_medium1_tracktwoEF_L1MU11_TAU20IMAux.", "TrigMatch_HLT_mu14_ivarloose_L1MU11_tau35_medium1_tracktwoMVA_L1MU11_TAU20IMAux.", "TrigMatch_HLT_mu14_ivarloose_L1MU11_tau35_medium1_tracktwo_L1MU11_TAU20IMAux.", "TrigMatch_HLT_mu14_ivarloose_L1MU11_tau35_mediumRNN_tracktwoMVA_L1MU11_TAU20IMAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoEFAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoEF_L1DR-MU10TAU12I_TAU12I-J25Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoEF_L1MU10_TAU12IM_3J12Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoMVA_L1DR-MU10TAU12I_TAU12I-J25Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoMVA_L1MU10_TAU12IM_3J12Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwo_L1DR-MU10TAU12I_TAU12I-J25Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwo_L1MU10_TAU12IM_3J12Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_mediumRNN_tracktwoMVAAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_mediumRNN_tracktwoMVA_L1DR-MU10TAU12I_TAU12I-J25Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_mediumRNN_tracktwoMVA_L1MU10_TAU12IM_3J12Aux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwoEFAux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwoEF_L1MU10_TAU20IM_J25_2J20Aux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwoMVA_L1MU10_TAU20IM_J25_2J20Aux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwo_L1MU10_TAU20IM_J25_2J20Aux.", "TrigMatch_HLT_mu14_ivarloose_tau35_mediumRNN_tracktwoMVAAux.", "TrigMatch_HLT_mu14_ivarloose_tau35_mediumRNN_tracktwoMVA_L1MU10_TAU20IM_J25_2J20Aux.", "TrigMatch_HLT_mu20_2mu2noL1_JpsimumuFSAux.", "TrigMatch_HLT_mu20_2mu4_JpsimumuL2Aux.", "TrigMatch_HLT_mu20_2mu4noL1Aux.", "TrigMatch_HLT_mu20_ivarmedium_mu8noL1Aux.", "TrigMatch_HLT_mu20_msonly_iloosems_mu6noL1_msonly_nscan05_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_mu20_msonly_iloosems_mu6noL1_msonly_nscan05_L1MU6_EMPTYAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noCombAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noComb_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noComb_L1MU6_EMPTYAux.", "TrigMatch_HLT_mu20_msonly_mu6noL1_msonly_nscan05Aux.", "TrigMatch_HLT_mu22_mu8noL1Aux.", "TrigMatch_HLT_mu22_mu8noL1_TagandProbeAux.", "TrigMatch_HLT_mu24_ivarmediumAux.", "TrigMatch_HLT_mu24_mu8noL1Aux.", "TrigMatch_HLT_mu26_ivarmediumAux.", "TrigMatch_HLT_mu50Aux.", "TrigMatch_HLT_mu60Aux.", "TrigMatch_HLT_mu60_0eta105_msonlyAux.", "TrigMatch_HLT_mu6_2mu4Aux.", "TrigMatch_HLT_mu6_dRl1_mu20_msonly_iloosems_mu6noL1_dRl1_msonlyAux.", "TrigMatch_HLT_mu6_nomucomb_2mu4_nomucomb_L1MU6_3MU4Aux.", "TrigMatch_HLT_mu80_msonly_3layersECAux.", "TrigMatch_HLT_tau125_medium1_tracktwoAux.", "TrigMatch_HLT_tau160_medium1_tracktwoAux.", "TrigMatch_HLT_tau160_medium1_tracktwoEF_L1TAU100Aux.", "TrigMatch_HLT_tau160_medium1_tracktwoMVA_L1TAU100Aux.", "TrigMatch_HLT_tau160_medium1_tracktwo_L1TAU100Aux.", "TrigMatch_HLT_tau160_mediumRNN_tracktwoMVA_L1TAU100Aux.", "TrigMatch_HLT_tau35_loose1_tracktwo_tau25_loose1_tracktwoAux.", "TrigMatch_HLT_tau35_medium1_tracktwoEF_tau25_medium1_tracktwoEF_03dR30_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwoEF_tau25_medium1_tracktwoEF_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwoEF_tau25_medium1_tracktwoEF_L1TAU20IM_2TAU12IM_4J12_0ETA23Aux.", "TrigMatch_HLT_tau35_medium1_tracktwoMVA_tau25_medium1_tracktwoMVA_03dR30_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwoMVA_tau25_medium1_tracktwoMVA_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwoMVA_tau25_medium1_tracktwoMVA_L1TAU20IM_2TAU12IM_4J12_0ETA23Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_03dR30_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1TAU20IM_2TAU12IMAux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1TAU20IM_2TAU12IM_4J12Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1TAU20IM_2TAU12IM_4J12_0ETA23Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_tautsf_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_mediumRNN_tracktwoMVA_tau25_mediumRNN_tracktwoMVA_03dR30_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_mediumRNN_tracktwoMVA_tau25_mediumRNN_tracktwoMVA_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_mediumRNN_tracktwoMVA_tau25_mediumRNN_tracktwoMVA_L1TAU20IM_2TAU12IM_4J12_0ETA23Aux.", "TrigMatch_HLT_tau40_medium1_tracktwoEF_tau35_medium1_tracktwoEFAux.", "TrigMatch_HLT_tau40_medium1_tracktwoMVA_tau35_medium1_tracktwoMVAAux.", "TrigMatch_HLT_tau40_medium1_tracktwo_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_tau40_mediumRNN_tracktwoMVA_tau35_mediumRNN_tracktwoMVAAux.", "TrigMatch_HLT_tau60_medium1_tracktwo_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_tau80_medium1_tracktwoEF_L1TAU60_tau35_medium1_tracktwoEF_L1TAU12IM_L1TAU60_DR-TAU20ITAU12IAux.", "TrigMatch_HLT_tau80_medium1_tracktwoEF_L1TAU60_tau60_medium1_tracktwoEF_L1TAU40Aux.", "TrigMatch_HLT_tau80_medium1_tracktwoMVA_L1TAU60_tau35_medium1_tracktwoMVA_L1TAU12IM_L1TAU60_DR-TAU20ITAU12IAux.", "TrigMatch_HLT_tau80_medium1_tracktwoMVA_L1TAU60_tau60_medium1_tracktwoMVA_L1TAU40Aux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60Aux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau35_medium1_tracktwo_L1TAU12IM_L1TAU60_DR-TAU20ITAU12IAux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau50_medium1_tracktwo_L1TAU12Aux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau60_medium1_tracktwo_L1TAU40Aux.", "TrigMatch_HLT_tau80_mediumRNN_tracktwoMVA_L1TAU60_tau35_mediumRNN_tracktwoMVA_L1TAU12IM_L1TAU60_DR-TAU20ITAU12IAux.", "TrigMatch_HLT_tau80_mediumRNN_tracktwoMVA_L1TAU60_tau60_mediumRNN_tracktwoMVA_L1TAU40Aux.", "egammaClustersAux.", "METAssoc_AntiKt4EMPFlowAux.", "METAssoc_AntiKt4EMTopoAux.",
 ] 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_MCCompressionList.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_MCCompressionList.py
index fafd173090ff8da74e22bdaa833e26b3e7b3e48a..03ce7922fa175409fe83137a321f625cd69696ee 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_MCCompressionList.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkPhys/python/PHYS_MCCompressionList.py
@@ -1,3 +1,5 @@
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+
 PHYS_MCCompressionList=[ 
 "SoftBVrtClusterTool_Loose_VerticesAux.", "SoftBVrtClusterTool_Medium_VerticesAux.", "SoftBVrtClusterTool_Tight_VerticesAux.", "AntiKt10LCTopoJetsAux.", "AntiKt10LCTopoTrimmedPtFrac5SmallR20JetsAux.", "AntiKt10TruthTrimmedPtFrac5SmallR20JetsAux.", "AntiKt2PV0TrackJetsAux.", "AntiKt4EMPFlowJetsAux.", "AntiKt4EMTopoJetsAux.", "AntiKt4TruthDressedWZJetsAux.", "AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903Aux.", "AntiKt4EMPFlowJets_BTagging201810Aux.", "AntiKt4EMPFlowJets_BTagging201903Aux.", "AntiKt4EMTopoJets_BTagging201810Aux.", "xTrigDecisionAux.", "Kt4EMPFlowEventShapeAux.", "Kt4EMTopoOriginEventShapeAux.", "NeutralParticleFlowIsoCentralEventShapeAux.", "NeutralParticleFlowIsoForwardEventShapeAux.", "TopoClusterIsoCentralEventShapeAux.", "TopoClusterIsoForwardEventShapeAux.", "BTagging_AntiKt4EMPFlow_201810Aux.", "BTagging_AntiKt4EMPFlow_201903Aux.", "BTagging_AntiKt4EMTopo_201810Aux.", "BTagging_AntiKtVR30Rmax4Rmin02Track_201903Aux.", "BornLeptonsAux.", "CombinedMuonTrackParticlesAux.", "DiTauJetsAux.", "DiTauJetsLowPtAux.", "ElectronsAux.", "GSFConversionVerticesAux.", "GSFTrackParticlesAux.", "HardScatterParticlesAux.", "HardScatterVerticesAux.", "InDetForwardTrackParticlesAux.", "InDetTrackParticlesAux.", "MET_Core_AntiKt4EMPFlowAux.", "MET_Core_AntiKt4EMTopoAux.", "MET_TrackAux.", "MET_TruthAux.", "MuonSpectrometerTrackParticlesAux.", "MuonsAux.", "PhotonsAux.", "PrimaryVerticesAux.", "TauJetsAux.", "TauTracksAux.", "TrigMatch_HLT_2e12_lhloose_nod0_mu10Aux.", "TrigMatch_HLT_2e12_lhloose_nodeta_L12EM10VHAux.", "TrigMatch_HLT_2e12_lhloose_nodphires_L12EM10VHAux.", "TrigMatch_HLT_2e17_lhvloose_nod0Aux.", "TrigMatch_HLT_2e17_lhvloose_nod0_L12EM15VHIAux.", "TrigMatch_HLT_2e17_lhvloose_nod0_ringerAux.", "TrigMatch_HLT_2e17_lhvloose_nod0_ringer_L12EM15VHIAux.", "TrigMatch_HLT_2e24_lhvloose_nod0Aux.", "TrigMatch_HLT_2g20_loose_g15_looseAux.", "TrigMatch_HLT_2g20_tightAux.", "TrigMatch_HLT_2g20_tight_icalovloose_L12EM15VHIAux.", "TrigMatch_HLT_2g22_tightAux.", "TrigMatch_HLT_2g22_tight_L12EM15VHIAux.", "TrigMatch_HLT_2g22_tight_L1EM7_EMPTYAux.", "TrigMatch_HLT_2g22_tight_L1EM7_UNPAIRED_ISOAux.", "TrigMatch_HLT_2g22_tight_icalovlooseAux.", "TrigMatch_HLT_2g25_loose_g15_looseAux.", "TrigMatch_HLT_2g25_tight_L12EM20VHAux.", "TrigMatch_HLT_2g50_loose_L12EM20VHAux.", "TrigMatch_HLT_2mu10Aux.", "TrigMatch_HLT_2mu10_nomucombAux.", "TrigMatch_HLT_2mu14Aux.", "TrigMatch_HLT_2mu14_nomucombAux.", "TrigMatch_HLT_2mu20_L12MU20_OVERLAYAux.", "TrigMatch_HLT_2mu4_mu3_mu2noL1_L13MU4Aux.", "TrigMatch_HLT_2mu4_mu3_mu2noL1_calotag_0eta010_L13MU4Aux.", "TrigMatch_HLT_2mu6_10invm30_pt2_z10Aux.", "TrigMatch_HLT_3g20_looseAux.", "TrigMatch_HLT_3mu3_mu3noL1_L13MU4Aux.", "TrigMatch_HLT_3mu3_mu3noL1_calotag_0eta010_L13MU4Aux.", "TrigMatch_HLT_3mu4Aux.", "TrigMatch_HLT_3mu4_mu2noL1Aux.", "TrigMatch_HLT_3mu4_mu2noL1_calotag_0eta010Aux.", "TrigMatch_HLT_3mu4_nomucombAux.", "TrigMatch_HLT_3mu4_nomucomb_mu2noL1Aux.", "TrigMatch_HLT_3mu6Aux.", "TrigMatch_HLT_3mu6_msonlyAux.", "TrigMatch_HLT_3mu6_msonly_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_3mu6_msonly_L1MU6_EMPTYAux.", "TrigMatch_HLT_4mu4Aux.", "TrigMatch_HLT_4mu4_nomucombAux.", "TrigMatch_HLT_e120_lhloose_nod0Aux.", "TrigMatch_HLT_e12_lhloose_nod0_2mu10Aux.", "TrigMatch_HLT_e140_lhloose_nod0Aux.", "TrigMatch_HLT_e140_lhloose_nod0_L1EM24VHIAux.", "TrigMatch_HLT_e140_lhloose_nod0_ringerAux.", "TrigMatch_HLT_e140_lhvloose_nod0Aux.", "TrigMatch_HLT_e160_lhvloose_nod0Aux.", "TrigMatch_HLT_e17_lhloose_nod0_2e12_lhloose_nod0_L1EM15VH_3EM10VHAux.", "TrigMatch_HLT_e17_lhloose_nod0_2e9_lhloose_nod0Aux.", "TrigMatch_HLT_e17_lhloose_nod0_mu14Aux.", "TrigMatch_HLT_e17_lhmedium_iloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_nod0_iloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwo_L1DR-EM15TAU12I-J25Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_ivarloose_tau25_medium1_tracktwo_L1EM15VHI_2TAU12IM_4J12Aux.", "TrigMatch_HLT_e17_lhmedium_nod0_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_nod0_tau80_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_e17_lhmedium_tau80_medium1_tracktwoAux.", "TrigMatch_HLT_e200_etcutAux.", "TrigMatch_HLT_e22_lhvloose_nod0_e12_lhvloose_nod0_e10_lhvloose_nod0_L1EM20VH_2EM10VH_3EM8VHAux.", "TrigMatch_HLT_e24_lhmedium_nod0_L1EM20VHI_mu8noL1Aux.", "TrigMatch_HLT_e24_lhmedium_nod0_ivarloose_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_e24_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e24_lhvloose_nod0_2e12_lhvloose_nod0_L1EM20VH_3EM10VHAux.", "TrigMatch_HLT_e26_lhloose_nod0Aux.", "TrigMatch_HLT_e26_lhloose_nod0_ringerAux.", "TrigMatch_HLT_e26_lhmedium_nod0_mu8noL1Aux.", "TrigMatch_HLT_e26_lhtight_cutd0dphideta_ivarlooseAux.", "TrigMatch_HLT_e26_lhtight_nod0Aux.", "TrigMatch_HLT_e26_lhtight_nod0_e15_etcut_L1EM7_ZeeAux.", "TrigMatch_HLT_e26_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e26_lhtight_nod0_ringer_ivarlooseAux.", "TrigMatch_HLT_e28_lhmedium_nod0_mu8noL1Aux.", "TrigMatch_HLT_e28_lhtight_nod0_L1EM22VHIAux.", "TrigMatch_HLT_e28_lhtight_nod0_e15_etcut_L1EM7_ZeeAux.", "TrigMatch_HLT_e28_lhtight_nod0_ivarlooseAux.", "TrigMatch_HLT_e28_lhtight_nod0_noringer_ivarlooseAux.", "TrigMatch_HLT_e28_lhtight_nod0_ringer_ivarlooseAux.", "TrigMatch_HLT_e300_etcutAux.", "TrigMatch_HLT_e60_lhmedium_nod0Aux.", "TrigMatch_HLT_e60_lhmedium_nod0_L1EM24VHIAux.", "TrigMatch_HLT_e60_lhmedium_nod0_ringerAux.", "TrigMatch_HLT_e60_mediumAux.", "TrigMatch_HLT_e7_lhmedium_nod0_mu24Aux.", "TrigMatch_HLT_g120_looseAux.", "TrigMatch_HLT_g140_looseAux.", "TrigMatch_HLT_g140_tightAux.", "TrigMatch_HLT_g200_etcutAux.", "TrigMatch_HLT_g200_looseAux.", "TrigMatch_HLT_g300_etcutAux.", "TrigMatch_HLT_g300_etcut_L1EM24VHIAux.", "TrigMatch_HLT_g35_loose_g25_looseAux.", "TrigMatch_HLT_g35_loose_g25_loose_L12EM20VHAux.", "TrigMatch_HLT_g35_medium_g25_medium_L12EM20VHAux.", "TrigMatch_HLT_g35_medium_g25_medium_L1EM7_EMPTYAux.", "TrigMatch_HLT_g35_medium_g25_medium_L1EM7_UNPAIRED_ISOAux.", "TrigMatch_HLT_id_cosmicid_L1MU11_EMPTYAux.", "TrigMatch_HLT_mu11_2mu4noL1_nscan03_L1MU11_2MU6Aux.", "TrigMatch_HLT_mu11_L1MU10_2mu4noL1_nscan03_L1MU10_2MU6Aux.", "TrigMatch_HLT_mu11_nomucomb_2mu4noL1_nscan03_L1MU11_2MU6Aux.", "TrigMatch_HLT_mu13_mu13_idperf_ZmumuAux.", "TrigMatch_HLT_mu14_iloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_iloose_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_ivarloose_L1MU11_tau35_medium1_tracktwo_L1MU11_TAU20IMAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwo_L1DR-MU10TAU12I_TAU12I-J25Aux.", "TrigMatch_HLT_mu14_ivarloose_tau25_medium1_tracktwo_L1MU10_TAU12IM_3J12Aux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_ivarloose_tau35_medium1_tracktwo_L1MU10_TAU20IM_J25_2J20Aux.", "TrigMatch_HLT_mu14_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_mu14_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_mu20_2mu2noL1_JpsimumuFSAux.", "TrigMatch_HLT_mu20_2mu4_JpsimumuL2Aux.", "TrigMatch_HLT_mu20_2mu4noL1Aux.", "TrigMatch_HLT_mu20_ivarmedium_mu8noL1Aux.", "TrigMatch_HLT_mu20_msonly_iloosems_mu6noL1_msonly_nscan05_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_mu20_msonly_iloosems_mu6noL1_msonly_nscan05_L1MU6_EMPTYAux.", "TrigMatch_HLT_mu20_msonly_mu10noL1_msonly_nscan05_noCombAux.", "TrigMatch_HLT_mu20_msonly_mu10noL1_msonly_nscan05_noComb_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_mu20_msonly_mu10noL1_msonly_nscan05_noComb_L1MU6_EMPTYAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noCombAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noComb_L1MU4_UNPAIRED_ISOAux.", "TrigMatch_HLT_mu20_msonly_mu15noL1_msonly_nscan05_noComb_L1MU6_EMPTYAux.", "TrigMatch_HLT_mu20_msonly_mu6noL1_msonly_nscan05Aux.", "TrigMatch_HLT_mu20_mu8noL1Aux.", "TrigMatch_HLT_mu20_mu8noL1_calotag_0eta010Aux.", "TrigMatch_HLT_mu20_mu8noL1_e9_lhvloose_nod0Aux.", "TrigMatch_HLT_mu20_mu8noL1_e9_lhvloose_nod0_L1EM7_MU20Aux.", "TrigMatch_HLT_mu20_nomucomb_mu6noL1_nscan03Aux.", "TrigMatch_HLT_mu22_mu8noL1Aux.", "TrigMatch_HLT_mu22_mu8noL1_calotag_0eta010Aux.", "TrigMatch_HLT_mu24_ilooseAux.", "TrigMatch_HLT_mu24_imediumAux.", "TrigMatch_HLT_mu24_ivarlooseAux.", "TrigMatch_HLT_mu24_ivarmediumAux.", "TrigMatch_HLT_mu24_mu8noL1Aux.", "TrigMatch_HLT_mu26_ivarmediumAux.", "TrigMatch_HLT_mu40Aux.", "TrigMatch_HLT_mu50Aux.", "TrigMatch_HLT_mu60Aux.", "TrigMatch_HLT_mu60_0eta105_msonlyAux.", "TrigMatch_HLT_mu6_2mu4Aux.", "TrigMatch_HLT_mu6_dRl1_mu20_msonly_iloosems_mu6noL1_dRl1_msonlyAux.", "TrigMatch_HLT_mu6_iloose_mu6_11invm24_noosAux.", "TrigMatch_HLT_mu6_nomucomb_2mu4_nomucomb_L1MU6_3MU4Aux.", "TrigMatch_HLT_tau125_medium1_trackAux.", "TrigMatch_HLT_tau125_medium1_tracktwoAux.", "TrigMatch_HLT_tau160_medium1_tracktwoAux.", "TrigMatch_HLT_tau160_medium1_tracktwo_L1TAU100Aux.", "TrigMatch_HLT_tau35_loose1_tracktwo_tau25_loose1_tracktwoAux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwoAux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_03dR30Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_03dR30_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1TAU20IM_2TAU12IMAux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_L1TAU20IM_2TAU12IM_4J12Aux.", "TrigMatch_HLT_tau35_medium1_tracktwo_tau25_medium1_tracktwo_tautsf_L1DR-TAU20ITAU12I-J25Aux.", "TrigMatch_HLT_tau40_medium1_tracktwo_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_tau60_medium1_tracktwo_tau35_medium1_tracktwoAux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60Aux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau35_medium1_tracktwo_L1TAU12IM_L1TAU60_DR-TAU20ITAU12IAux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau50_medium1_tracktwo_L1TAU12Aux.", "TrigMatch_HLT_tau80_medium1_tracktwo_L1TAU60_tau60_medium1_tracktwo_L1TAU40Aux.", "TruthBSMAux.", "TruthBSMWithDecayParticlesAux.", "TruthBSMWithDecayVerticesAux.", "TruthBosonAux.", "TruthBosonsWithDecayParticlesAux.", "TruthBosonsWithDecayVerticesAux.", "TruthBottomAux.", "TruthCharmAux.", "TruthElectronsAux.", "TruthEventsAux.", "TruthForwardProtonsAux.", "TruthHFWithDecayParticlesAux.", "TruthHFWithDecayVerticesAux.", "TruthMuonsAux.", "TruthNeutrinosAux.", "TruthPhotonsAux.", "TruthPrimaryVerticesAux.", "TruthTausAux.", "TruthTopAux.", "egammaClustersAux.", "METAssoc_AntiKt4EMPFlowAux.", "METAssoc_AntiKt4EMTopoAux.",
 ] 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/CMakeLists.txt
index 7d6ef45df2edd8c1b78764105f4866b24bf68488..6130e7da2dc08b7a53a0ccee04b4282ba56dab8b 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/CMakeLists.txt
@@ -4,6 +4,6 @@
 atlas_subdir( DerivationFrameworkSM )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/python/STDMCommonTruthTools.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/python/STDMCommonTruthTools.py
index 5e297ab3634e447b797d4e674d2aa2bf03a8f7c0..3029bfb2429ec6fcdad3325f79b8d7a3ff27ffc1 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/python/STDMCommonTruthTools.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkSM/python/STDMCommonTruthTools.py
@@ -1,7 +1,8 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
+from AthenaCommon import CfgMgr
 from AthenaCommon.AppMgr import ToolSvc
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from DerivationFrameworkCore.DerivationFrameworkMaster import DerivationFrameworkJob
 
 #==============================================================================
 # Set up the MCTruthClassifier
@@ -124,5 +125,4 @@ STDMAugmentationTools.append(STDMMuonDressingTool2)
 #==============================================================================
 # CREATE THE COMMON AUGMENTATION KERNEL ALGORITHM
 #==============================================================================
-from DerivationFrameworkCore.DerivationFrameworkCoreConf import DerivationFramework__CommonAugmentation
 DerivationFrameworkJob += CfgMgr.DerivationFramework__CommonAugmentation("STDMAugmentationKernel", AugmentationTools = STDMAugmentationTools)
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/CMakeLists.txt b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/CMakeLists.txt
index 85da10191b61be3601524c0a49b650b4424f18d2..41f22685aef49cd0444c4f83f93469d1742589d2 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/CMakeLists.txt
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/CMakeLists.txt
@@ -9,5 +9,5 @@ atlas_add_component( DerivationFrameworkTop
                      LINK_LIBRARIES AthenaBaseComps DerivationFrameworkInterfaces ExpressionEvaluationLib GaudiKernel StoreGateLib xAODBTagging xAODEventInfo xAODJet xAODTracking xAODTruth )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonJets.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonJets.py
index dc48423a9685daf416bd6fa57f7a84c9ed57eb56..733bedfdba6c62fb70d25f75073acf54679ff532 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonJets.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonJets.py
@@ -9,12 +9,10 @@
 #   DerivationFrameworkTop.TOPQCommonJets.TOPQupdateJVT("JetCollection")
 #===================================================================================
 
-from __future__ import print_function
-
 #========
 # IMPORTS
 #========
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+from AthenaCommon import CfgMgr
 from AthenaCommon.GlobalFlags import globalflags
 from RecExConfig.ObjKeyStore import cfgKeyStore
 
@@ -99,6 +97,7 @@ def addStandardJetsForTop(algseq, outputGroup):
 #==================
 # PhysicsAnalysis/DerivationFramework/DerivationFrameworkJetEtMiss/trunk/python/ExtendedJetCommon.py
 def buildTOPQCA15jets(algseq):
+  from JetRec.JetRecStandard import jtm
   if not cfgKeyStore.isInInput("xAOD::JetContainer","CamKt15LCTopoJets"):
     from JetRec.JetRecConf import JetAlgorithm
     jtm.modifiersMap["lctopoCA15"] = list(jtm.modifiersMap["lctopo"])
@@ -123,7 +122,7 @@ def applyTOPQJetCalibration(jetcollection, algseq=None):
     applyJetCalibration_xAODColl, applyJetCalibration_CustomColl
 
   supportedJets = ['AntiKt4EMTopo', 'AntiKt10LCTopoTrimmedPtFrac5SmallR20']
-  if not jetcollection in supportedJets:
+  if jetcollection not in supportedJets:
     print ("TOPQCommonJets:",jetcollection, "is an unsupported collection for calibration!")
     return
   elif jetcollection == 'AntiKt4EMTopo':
@@ -140,7 +139,7 @@ def TOPQupdateJVT(jetcollection, algseq=None):
   from DerivationFrameworkJetEtMiss.ExtendedJetCommon import updateJVT_xAODColl
 
   supportedJets = ['AntiKt4EMTopo']
-  if not jetcollection in supportedJets:
+  if jetcollection not in supportedJets:
     print ("TOPQCommonJets:", jetcollection, "is an unsupported collection for JVT augmentation!")
     return
   else:
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSelection.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSelection.py
index 0cde41ad846e51aad891065594c3151bda5305ce..21e126a3c71a20209243daa141bdea6837fc098f 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSelection.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSelection.py
@@ -8,8 +8,6 @@
 #   skimmingTools_jet = DerivationFrameworkTop.TOPQCommonSelection.setup_jet('TOPQ1', ToolSvc)
 #====================================================================
 
-from __future__ import print_function
-
 #================================
 # SKIMMING SELECTIONS
 #================================
@@ -43,7 +41,7 @@ from __future__ import print_function
 #================================
 # IMPORTS
 #================================
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
+import DerivationFrameworkCore.DerivationFrameworkMaster  # noqa: F401
 
 #================
 # ELECTRONS
@@ -105,9 +103,9 @@ def setup_lep(TOPQname, ToolSvc):
   elif TOPQname == 'TOPQ2':
     TOPQ2_LEP10 = "( (count("+EL10+") >= 2) || (count("+MU10+") >= 2) || (count("+EL10+")>= 1 && count("+MU10+") >= 1) )" 
     TOPQ2_LEP15 = "( (count("+EL15+") >= 2) || (count("+MU15+") >= 2) || (count("+EL15+")>= 1 && count("+MU15+") >= 1) )"
-    TOPQ2_LEP17 = "( (count("+EL17+") >= 2) || (count("+MU17+") >= 2) || (count("+EL17+")>= 1 && count("+MU17+") >= 1) )"  
+    TOPQ2_LEP17 = "( (count("+EL17+") >= 2) || (count("+MU17+") >= 2) || (count("+EL17+")>= 1 && count("+MU17+") >= 1) )"  # noqa: F841 (FIXME, not used)
     TOPQ2_LEP20 = "( (count("+EL20+") >= 1) || (count("+MU20+") >= 1) )"
-    TOPQ2_LEP22 = "( (count("+EL22+") >= 1) || (count("+MU22+") >= 1) )"
+    TOPQ2_LEP22 = "( (count("+EL22+") >= 1) || (count("+MU22+") >= 1) )"  # noqa: F841 (FIXME, not used)
     TOPQ_Selection_lep = "( ("+TOPQ2_LEP15+") || (("+TOPQ2_LEP10+") && ("+TOPQ2_LEP20+")) )"
   elif TOPQname == 'TOPQ3':
     TOPQ_Selection_lep = "( (count("+MU13+") >= 1) || (count("+EL13+") >= 1) )"
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSlimming.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSlimming.py
index f8a6f7a2534d478fdf4a435640cd0013edb24bed..23d3000091e435ee911398b1e2f0bec465e2d695 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSlimming.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonSlimming.py
@@ -7,16 +7,14 @@
 #     DerivationFrameworkTop.TOPQCommonSlimming.setup('TOPQX', TOPQStream)
 #====================================================================
 
-from __future__ import print_function
-
 #================================
 # IMPORTS
 #================================
 from DerivationFrameworkCore.SlimmingHelper import SlimmingHelper
 from AthenaCommon.GlobalFlags import globalflags
-from DerivationFrameworkTop.TOPQCommonExtraContent import *
-from DerivationFrameworkJetEtMiss.METCommon import *
-from DerivationFrameworkJetEtMiss.JetCommon import *
+import DerivationFrameworkTop.TOPQCommonExtraContent as tec
+from DerivationFrameworkJetEtMiss.METCommon import addMETOutputs
+from DerivationFrameworkJetEtMiss.JetCommon import addJetOutputs
 
 import JetTagNonPromptLepton.JetTagNonPromptLeptonConfig as Config
 
@@ -34,7 +32,7 @@ def setup(TOPQname, stream):
   # SMART SLIMMING
   #================================
   TOPQSlimmingHelper.SmartCollections =  []
-  TOPQSlimmingHelper.SmartCollections += TOPQSmartSlimmingCollections
+  TOPQSlimmingHelper.SmartCollections += tec.TOPQSmartSlimmingCollections
 
   print ("TOPQSlimmingHelper.SmartCollections: " , TOPQSlimmingHelper.SmartCollections)
 
@@ -42,27 +40,27 @@ def setup(TOPQname, stream):
   # EXTRA VARIABLES FROM DerivationFrameworkTop.TOPQCommonExtraContent
   #=================================================================
   TOPQSlimmingHelper.ExtraVariables = []
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesAntiKt4EMTopoJets
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesAntiKt4EMPFlowJets
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesBTagging_AntiKt4EMPFlow
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesBTagging_AntiKt4EMTopo
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesPhotons
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesElectrons
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesMuons
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesTaus
-  TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesTrackJets
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesAntiKt4EMTopoJets
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesAntiKt4EMPFlowJets
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesBTagging_AntiKt4EMPFlow
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesBTagging_AntiKt4EMTopo
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesPhotons
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesElectrons
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesMuons
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesTaus
+  TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesTrackJets
   TOPQSlimmingHelper.ExtraVariables += Config.GetExtraPromptVariablesForDxAOD()
   #  TOPQSlimmingHelper.ExtraVariables += ["CaloCalTopoClusters.calE.calEta.calPhi.calM.rawM.rawE.rawEta.rawPhi.e_sampl.eta_sampl.etaCalo.phiCalo"]
   TOPQSlimmingHelper.ExtraVariables += ["CaloCalTopoClusters.calPt.calEta.calPhi.calM.calE.CENTER_MAG"]
 
   if DFisMC:
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesPhotonsTruth
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesElectronsTruth
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesMuonsTruth
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVariablesTausTruth
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVarsBTag_HLT_Container
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVarsJet_EF_Container
-    TOPQSlimmingHelper.ExtraVariables += TOPQExtraVarsJet_Split_Container
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesPhotonsTruth
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesElectronsTruth
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesMuonsTruth
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVariablesTausTruth
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVarsBTag_HLT_Container
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVarsJet_EF_Container
+    TOPQSlimmingHelper.ExtraVariables += tec.TOPQExtraVarsJet_Split_Container
 
   print ("TOPQSlimmingHelper.ExtraVariables: " , TOPQSlimmingHelper.ExtraVariables)
 
@@ -70,11 +68,11 @@ def setup(TOPQname, stream):
   # EXTRA COLLECTIONS - user added
   #================================
   TOPQSlimmingHelper.AllVariables = []
-  TOPQSlimmingHelper.AllVariables += TOPQExtraContainersStandard
-  TOPQSlimmingHelper.AllVariables += TOPQExtraContainersTrigger
+  TOPQSlimmingHelper.AllVariables += tec.TOPQExtraContainersStandard
+  TOPQSlimmingHelper.AllVariables += tec.TOPQExtraContainersTrigger
 
   if DFisMC:
-    TOPQSlimmingHelper.AllVariables += TOPQExtraContainersTruth
+    TOPQSlimmingHelper.AllVariables += tec.TOPQExtraContainersTruth
 
   print ("TOPQSlimmingHelper.AllVariables: " , TOPQSlimmingHelper.AllVariables)
 
@@ -82,10 +80,10 @@ def setup(TOPQname, stream):
   # CREATED ON-THE-FLY COLLECTIONS
   #================================
   TOPQSlimmingHelper.StaticContent = []
-  TOPQSlimmingHelper.StaticContent += TOPQStaticContent
+  TOPQSlimmingHelper.StaticContent += tec.TOPQStaticContent
 
   if DFisMC:
-    TOPQSlimmingHelper.StaticContent += TOPQStaticContentTruth
+    TOPQSlimmingHelper.StaticContent += tec.TOPQStaticContentTruth
 
   print ("TOPQSlimmingHelper.StaticContent: " , TOPQSlimmingHelper.StaticContent)
 
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonThinning.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonThinning.py
index 2b09791d3fe420340aae462e756ca0b655a5c9c7..7e26d7944225b1dae9943e75c767a4e99dcf5081 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonThinning.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonThinning.py
@@ -19,8 +19,6 @@
 #   * GenericTruthThinning (fine-grained thinning)
 #====================================================================
 
-from __future__ import print_function
-
 #============================
 # Define trigger chain output
 #============================
@@ -54,13 +52,13 @@ def setup(TOPQname, streamName, ToolSvc):
   # Track Particle Thinning !!! BUGGY (yes, that's a technical term)...CURRENTLY NOT USING !!!
   #========================
   # PhysicsAnalysis/DerivationFramework/DerivationFrameworkInDet/trunk/src/TrackParticleThinning.cxx
-  thinning_expression = "(InDetTrackParticles.pt > 0.5*GeV) && (InDetTrackParticles.numberOfPixelHits > 0) && (InDetTrackParticles.numberOfSCTHits > 5) && (abs(DFCommonInDetTrackZ0AtPV) < 1.5)"
-  from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning
-  TOPQTPThinningTool = DerivationFramework__TrackParticleThinning(  
-                         name                    = TOPQname + "TPThinningTool",
-                         StreamName              = streamName,
-                         SelectionString         = thinning_expression,
-                         InDetTrackParticlesKey  = "InDetTrackParticles")
+  #thinning_expression = "(InDetTrackParticles.pt > 0.5*GeV) && (InDetTrackParticles.numberOfPixelHits > 0) && (InDetTrackParticles.numberOfSCTHits > 5) && (abs(DFCommonInDetTrackZ0AtPV) < 1.5)"
+  #from DerivationFrameworkInDet.DerivationFrameworkInDetConf import DerivationFramework__TrackParticleThinning
+  #TOPQTPThinningTool = DerivationFramework__TrackParticleThinning(
+  #                       name                    = TOPQname + "TPThinningTool",
+  #                       StreamName              = streamName,
+  #                       SelectionString         = thinning_expression,
+  #                       InDetTrackParticlesKey  = "InDetTrackParticles")
 
   #ToolSvc += TOPQTPThinningTool
   #thinningTools.append(TOPQTPThinningTool)
@@ -259,7 +257,6 @@ def setup(TOPQname, streamName, ToolSvc):
 
   # we remove photons below 9GeV
   from DerivationFrameworkTools.DerivationFrameworkToolsConf import DerivationFramework__GenericObjectThinning
-  pTPhotonVariableToCutOn = ".pt"
   photonColl = "Photons"
   TOPQPhotonThinning = DerivationFramework__GenericObjectThinning(
     name = TOPQname + photonColl + "Thinning_lowpTphotons",
diff --git a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonTruthTools.py b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonTruthTools.py
index e3fe9f5189a56a80bb75fc52f8501efd0a0286b0..6df910529db278a08c1b916779b4f0089e305bcf 100644
--- a/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonTruthTools.py
+++ b/PhysicsAnalysis/DerivationFramework/DerivationFrameworkTop/python/TOPQCommonTruthTools.py
@@ -7,13 +7,14 @@
 #  TOPQXSequence += TOPQCommonTruthKernel
 #====================================================================
 
-from __future__ import print_function
-
 #================================
 # IMPORTS
 #================================
-from DerivationFrameworkCore.DerivationFrameworkMaster import *
-from DerivationFrameworkMCTruth.HFHadronsCommon import *
+from AthenaCommon import CfgMgr
+from AthenaCommon.AppMgr import ToolSvc
+
+from DerivationFrameworkMCTruth.HFHadronsCommon import DSIDList
+
 
 def setup(ToolSvc):
 
@@ -47,7 +48,6 @@ def setup(ToolSvc):
   #==============================================================================
   # PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/trunk/src/TruthCollectionMaker.cxx
   # PhysicsAnalysis/DerivationFramework/DerivationFrameworkMCTruth/trunk/src/TruthCollectionMakerTau.cxx
-  from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__TruthCollectionMaker
   from DerivationFrameworkMCTruth.DerivationFrameworkMCTruthConf import DerivationFramework__TruthCollectionMakerTau
 
   #==========
@@ -174,7 +174,7 @@ TOPQCommonTruthKernel = CfgMgr.DerivationFramework__CommonAugmentation("TOPQComm
 #==============================================================================
 # Add SumOfWeights metadata for LHE3 multiweights: TOPQDERIV-21
 #==============================================================================
-import DerivationFrameworkCore.LHE3WeightMetadata
+import DerivationFrameworkCore.LHE3WeightMetadata  # noqa: F401
 
 #     #==============================================================================
 #     # HIGGS TEMPLATE XSECTION augmentation
diff --git a/Reconstruction/HeavyIonRec/HIGlobal/CMakeLists.txt b/Reconstruction/HeavyIonRec/HIGlobal/CMakeLists.txt
index 340e93a3bb1589b0b63688b9af69261e51bdfedd..bf55458e480fe8edf6a68609c4e3fb10aebbfcfd 100644
--- a/Reconstruction/HeavyIonRec/HIGlobal/CMakeLists.txt
+++ b/Reconstruction/HeavyIonRec/HIGlobal/CMakeLists.txt
@@ -1,38 +1,21 @@
-################################################################################
-# Package: HIGlobal
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( HIGlobal )
 
-# Declare the package's dependencies:
-atlas_depends_on_subdirs( PUBLIC
-                          Calorimeter/CaloEvent
-                          Control/AthToolSupport/AsgTools
-                          Control/AthenaBaseComps
-                          Event/NavFourMom
-                          Event/xAOD/xAODHIEvent
-                          PhysicsAnalysis/HeavyIonPhys/HIEventUtils
-                          PRIVATE
-                          Control/Navigation
-                          GaudiKernel )
-
-# External dependencies:
-find_package( ROOT COMPONENTS Core Tree MathCore Hist RIO pthread )
-
 # Component(s) in the package:
 atlas_add_library( HIGlobalLib
                    HIGlobal/*.h
                    INTERFACE
                    PUBLIC_HEADERS HIGlobal
-                   LINK_LIBRARIES AsgTools AthenaBaseComps CaloEvent GaudiKernel HIEventUtilsLib NavFourMom xAODHIEvent )
+                   LINK_LIBRARIES AsgTools AthenaBaseComps CaloEvent GaudiKernel HIEventUtilsLib NavFourMom StoreGateLib xAODCaloEvent xAODHIEvent )
 
 atlas_add_component( HIGlobal
                      src/*.cxx
                      src/components/*.cxx
-                     LINK_LIBRARIES GaudiKernel Navigation HIGlobalLib )
+                     LINK_LIBRARIES CaloEvent GaudiKernel HIEventUtilsLib HIGlobalLib Navigation StoreGateLib xAODHIEvent )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/Reconstruction/HeavyIonRec/HIJetRec/CMakeLists.txt b/Reconstruction/HeavyIonRec/HIJetRec/CMakeLists.txt
index 0f6fbbb31b319bbab257654cd2f20e0a69c4d704..b380f54ca13fc625644a2a33ba265fa720d25e13 100644
--- a/Reconstruction/HeavyIonRec/HIJetRec/CMakeLists.txt
+++ b/Reconstruction/HeavyIonRec/HIJetRec/CMakeLists.txt
@@ -16,7 +16,7 @@ atlas_add_library( HIJetRecLib
 
 atlas_add_component( HIJetRec
                      Root/*.cxx src/*.h src/*.cxx src/components/*.cxx
-                     LINK_LIBRARIES AthenaBaseComps CaloEvent CaloInterfaceLib CaloRecLib CaloUtilsLib CxxUtils HIJetRecLib JetInterface JetRecLib NavFourMom Navigation PathResolver StoreGateLib xAODCore xAODEventInfo xAODTracking )
+                     LINK_LIBRARIES ${ROOT_LIBRARIES} AsgTools AthenaBaseComps CaloEvent CaloInterfaceLib CaloRecLib CaloUtilsLib CxxUtils FourMomUtils HIEventUtilsLib HIJetRecLib JetInterface JetRecLib NavFourMom Navigation PathResolver StoreGateLib xAODBase xAODCaloEvent xAODCore xAODEventInfo xAODHIEvent xAODJet xAODTracking )
 
 # Install files from the package:
 atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
diff --git a/Reconstruction/HeavyIonRec/HIMonitoring/CMakeLists.txt b/Reconstruction/HeavyIonRec/HIMonitoring/CMakeLists.txt
index 76958d5975b2fe9819d8dd9e2c9eb9eac14f2350..df9bd52fed372b7845b28dc1711a24e9c6818b7d 100644
--- a/Reconstruction/HeavyIonRec/HIMonitoring/CMakeLists.txt
+++ b/Reconstruction/HeavyIonRec/HIMonitoring/CMakeLists.txt
@@ -1,40 +1,22 @@
-################################################################################
-# Package: HIMonitoring
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( HIMonitoring )
 
-# Declare the package's dependencies:
-atlas_depends_on_subdirs( PUBLIC
-                          Control/AthenaMonitoring
-                          Event/xAOD/xAODEgamma
-                          Event/xAOD/xAODForward
-                          Event/xAOD/xAODHIEvent
-                          Event/xAOD/xAODMuon
-                          Event/xAOD/xAODTracking
-                          Event/xAOD/xAODTrigMinBias
-                          ForwardDetectors/ZDC/ZdcAnalysis
-			  GaudiKernel
-                          PhysicsAnalysis/ElectronPhotonID/ElectronPhotonSelectorTools
-                          PRIVATE
-                          Tools/LWHists )
-
 # External dependencies:
-find_package( ROOT COMPONENTS MathCore Core Tree Hist RIO pthread Graf Graf3d Gpad Html Postscript Gui GX11TTF GX11 )
+find_package( ROOT COMPONENTS Core )
 
 # Component(s) in the package:
 atlas_add_library( HIMonitoringLib
                    src/*.cxx
                    PUBLIC_HEADERS HIMonitoring
                    INCLUDE_DIRS ${ROOT_INCLUDE_DIRS}
-		   LINK_LIBRARIES ${ROOT_LIBRARIES} xAODEgamma xAODForward xAODHIEvent xAODMuon xAODTracking xAODTrigMinBias GaudiKernel AthenaMonitoringLib ZdcAnalysisLib ElectronPhotonSelectorToolsLib
-                   PRIVATE_LINK_LIBRARIES LWHists )
+                   LINK_LIBRARIES AthenaMonitoringLib xAODHIEvent xAODTrigMinBias
+                   PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} ElectronPhotonSelectorToolsLib LWHists PATCoreAcceptLib xAODEgamma xAODForward xAODMuon )
 
 atlas_add_component( HIMonitoring
                      src/components/*.cxx
-                     INCLUDE_DIRS ${ROOT_INCLUDE_DIRS}
-		     LINK_LIBRARIES ${ROOT_LIBRARIES} AthenaMonitoringLib xAODEgamma xAODForward xAODHIEvent xAODMuon xAODTracking xAODTrigMinBias GaudiKernel ElectronPhotonSelectorToolsLib LWHists ZdcAnalysisLib HIMonitoringLib )
+		             LINK_LIBRARIES HIMonitoringLib )
 
 # Install files from the package:
 atlas_install_joboptions( share/*.py )
diff --git a/Reconstruction/HeavyIonRec/HIRecExample/CMakeLists.txt b/Reconstruction/HeavyIonRec/HIRecExample/CMakeLists.txt
index ab24f98b37b6d54cc67af44cb63e52f56cb8f50c..1e258fa5a3e8fdb3bf1d7eb60031e8760d4794e5 100644
--- a/Reconstruction/HeavyIonRec/HIRecExample/CMakeLists.txt
+++ b/Reconstruction/HeavyIonRec/HIRecExample/CMakeLists.txt
@@ -1,11 +1,9 @@
-################################################################################
-# Package: HIRecExample
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( HIRecExample )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
diff --git a/Reconstruction/MuonIdentification/MuidInterfaces/MuidInterfaces/IMuonAlignmentUncertTool.h b/Reconstruction/MuonIdentification/MuidInterfaces/MuidInterfaces/IMuonAlignmentUncertTool.h
new file mode 100755
index 0000000000000000000000000000000000000000..32831774ec1eef6963b65fc771d464855437b0af
--- /dev/null
+++ b/Reconstruction/MuonIdentification/MuidInterfaces/MuidInterfaces/IMuonAlignmentUncertTool.h
@@ -0,0 +1,51 @@
+/*
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+*/
+
+///////////////////////////////////////////////////////////////////
+// IMuonAlignmentUncertTool
+//    Interface tool to assess the muon alignment and scattering
+//    uncertainties using calibration files
+//  (c) ATLAS Combined Muon software
+///////////////////////////////////////////////////////////////////
+
+#ifndef MUIDINTERFACES_IMUONALIGNMENTUNCERTTOOL_H
+#define MUIDINTERFACES_IMUONALIGNMENTUNCERTTOOL_H
+
+#include <GaudiKernel/IAlgTool.h>
+#include <TrkTrack/TrackStateOnSurface.h>
+#include <TrkTrack/Track.h>
+
+namespace Muon {
+  
+    /** Interface ID for ICombinedMuonTrackBuilder*/  
+    static const InterfaceID IID_IMuonAlignmentUncertTool("IMuonAlignmentUncertTool", 1, 0);
+  
+    /**@class IMuonAlignmentUncertTool
+        Base class for MuonAlignmentUncertTool AlgTool
+    */
+    class IMuonAlignmentUncertTool : virtual public IAlgTool {
+        public:
+            /**Virtual destructor*/
+            virtual ~IMuonAlignmentUncertTool()= default;
+            
+            /** AlgTool and IAlgTool interface methods */
+            static const InterfaceID&	interfaceID() { return IID_IMuonAlignmentUncertTool; }
+
+            /**IMuonAlignmentUncertTool interface: retrieve the associated uncertainties */
+            virtual float get_uncertainty (const Trk::Track* trk) const = 0;
+            
+            /// Helper method to retrieve the last measurement of the ID, 
+            /// the first and last scatterer in the calorimeter
+            /// and finally to retrieve the first measurement inside the MS
+            virtual void get_track_state_measures(const Trk::Track* track, const Trk::TrackStateOnSurface*& id_exit,
+                                                  const Trk::TrackStateOnSurface*& calo_entrance,
+                                                  const Trk::TrackStateOnSurface*& calo_exit,
+                                                  const Trk::TrackStateOnSurface*& ms_entrance) const  = 0;
+    };
+ 
+}	// end of namespace
+
+#endif
+
+
diff --git a/Reconstruction/MuonIdentification/MuidTrackBuilder/MuidTrackBuilder/CombinedMuonTrackBuilder.h b/Reconstruction/MuonIdentification/MuidTrackBuilder/MuidTrackBuilder/CombinedMuonTrackBuilder.h
index e6f6efdd65efdfcd2a546cad6c6f46ac109d4c3a..e783b3f0b53dc2f3af7aca6898661909786bb68a 100755
--- a/Reconstruction/MuonIdentification/MuidTrackBuilder/MuidTrackBuilder/CombinedMuonTrackBuilder.h
+++ b/Reconstruction/MuonIdentification/MuidTrackBuilder/MuidTrackBuilder/CombinedMuonTrackBuilder.h
@@ -16,6 +16,8 @@
 #define MUIDTRACKBUILDER_COMBINEDMUONTRACKBUILDER_H
 
 #include "MuidInterfaces/ICombinedMuonTrackBuilder.h"
+#include "MuidInterfaces/IMuonAlignmentUncertTool.h"
+
 #include "AthenaBaseComps/AthAlgTool.h"
 #include "GaudiKernel/ServiceHandle.h"
 #include "GaudiKernel/ToolHandle.h"
@@ -61,7 +63,7 @@ namespace Rec {
 class CombinedMuonTrackBuilder : public AthAlgTool, virtual public ICombinedMuonTrackBuilder {
   public:
     CombinedMuonTrackBuilder(const std::string& type, const std::string& name, const IInterface* parent);
-    ~CombinedMuonTrackBuilder() = default;
+    ~CombinedMuonTrackBuilder();
 
     StatusCode initialize();
     StatusCode finalize();
@@ -258,6 +260,12 @@ class CombinedMuonTrackBuilder : public AthAlgTool, virtual public ICombinedMuon
         "CaloMaterialProvider",
         "Trk::TrkMaterialProviderTool/TrkMaterialProviderTool",
     };
+    
+    /// ToolHandles to retrieve the uncertainties for theta and phi for 
+    /// the scattering uncertainties
+    ToolHandle<Muon::IMuonAlignmentUncertTool> m_alignUncertTool_theta;
+    ToolHandle<Muon::IMuonAlignmentUncertTool> m_alignUncertTool_phi;
+    
 
     ServiceHandle<Muon::IMuonIdHelperSvc> m_idHelperSvc{this, "MuonIdHelperSvc",
                                                         "Muon::MuonIdHelperSvc/MuonIdHelperSvc"};
@@ -294,23 +302,22 @@ class CombinedMuonTrackBuilder : public AthAlgTool, virtual public ICombinedMuon
     double   m_vertex3DSigmaRPhi;
     double   m_vertex3DSigmaZ;
     double   m_zECToroid;
-    double   m_IDMS_xySigma;
-    double   m_IDMS_rzSigma;
+
 
     // dummy (unused - kept for backwards compatibility)
     bool m_indetSlimming;
     bool m_inputSlimming;
 
     // constants
-    const Trk::Volume*         m_calorimeterVolume;
-    const Trk::Volume*         m_indetVolume;
+    std::unique_ptr<const Trk::Volume>         m_calorimeterVolume;
+    std::unique_ptr<const Trk::Volume>         m_indetVolume;
     const Trk::TrackingVolume* m_spectrometerEntrance;
 
     // vertex region and phi modularity for pseudo-measurement constraints
-    Trk::RecVertex*      m_beamAxis;
-    Trk::PerigeeSurface* m_perigeeSurface;
+    std::unique_ptr<Trk::RecVertex>      m_beamAxis;
+    std::unique_ptr<Trk::PerigeeSurface> m_perigeeSurface;
     double               m_sigmaPhiSector;
-    Trk::RecVertex*      m_vertex;
+    std::unique_ptr<Trk::RecVertex>      m_vertex;
 
     // counters
     mutable std::atomic_uint m_countAcceptedStandaloneFit;
@@ -322,7 +329,7 @@ class CombinedMuonTrackBuilder : public AthAlgTool, virtual public ICombinedMuon
     mutable std::atomic_uint m_countVertexRegion;
 
     // count warnings
-    MessageHelper* m_messageHelper;
+    std::unique_ptr<MessageHelper> m_messageHelper;
 
     bool m_updateWithCaloTG;
     bool m_useCaloTG;
diff --git a/Reconstruction/MuonIdentification/MuidTrackBuilder/src/CombinedMuonTrackBuilder.cxx b/Reconstruction/MuonIdentification/MuidTrackBuilder/src/CombinedMuonTrackBuilder.cxx
index 91df3e06db34b667e0601e6dd721725f3cbedf4f..b1f92b8658b4d270f37265db6211ecd7ef03eba9 100755
--- a/Reconstruction/MuonIdentification/MuidTrackBuilder/src/CombinedMuonTrackBuilder.cxx
+++ b/Reconstruction/MuonIdentification/MuidTrackBuilder/src/CombinedMuonTrackBuilder.cxx
@@ -48,10 +48,12 @@
 
 namespace Rec {
 
-
+CombinedMuonTrackBuilder::~CombinedMuonTrackBuilder(){}
 CombinedMuonTrackBuilder::CombinedMuonTrackBuilder(const std::string& type, const std::string& name,
-                                                   const IInterface* parent)
-    : AthAlgTool(type, name, parent),
+                                                   const IInterface* parent): 
+      AthAlgTool(type, name, parent),
+      m_alignUncertTool_theta("Muon::MuonAlignmentUncertTool/MuonAlignmentUncertToolTheta"),
+      m_alignUncertTool_phi("Muon::MuonAlignmentUncertTool/MuonAlignmentUncertToolPhi"),
       m_magFieldProperties(Trk::FullField),
       m_allowCleanerVeto(true),
       m_cleanCombined(true),
@@ -73,9 +75,7 @@ CombinedMuonTrackBuilder::CombinedMuonTrackBuilder(const std::string& type, cons
       m_vertex2DSigmaZ(100. * Gaudi::Units::meter),
       m_vertex3DSigmaRPhi(6. * Gaudi::Units::mm),
       m_vertex3DSigmaZ(60. * Gaudi::Units::mm),
-      m_zECToroid(10. * Gaudi::Units::meter),
-      m_IDMS_xySigma(1. * Gaudi::Units::mm),
-      m_IDMS_rzSigma(1. * Gaudi::Units::mm),
+      m_zECToroid(10. * Gaudi::Units::meter),     
       m_indetSlimming(false),
       m_inputSlimming(false),
       m_calorimeterVolume(nullptr),
@@ -100,9 +100,8 @@ CombinedMuonTrackBuilder::CombinedMuonTrackBuilder(const std::string& type, cons
       m_refineELossStandAloneTrackFit(true),
       m_addElossID(true),
       m_addIDMSerrors(true),
-      m_useRefitTrackError(true)
-{
-    m_messageHelper = new MessageHelper(*this);
+      m_useRefitTrackError(true) {
+    m_messageHelper = std::make_unique<MessageHelper>(*this);
 
     declareInterface<ICombinedMuonTrackBuilder>(this);
     declareProperty("AllowCleanerVeto", m_allowCleanerVeto);
@@ -126,8 +125,9 @@ CombinedMuonTrackBuilder::CombinedMuonTrackBuilder(const std::string& type, cons
     declareProperty("Vertex3DSigmaRPhi", m_vertex3DSigmaRPhi);
     declareProperty("Vertex3DSigmaZ", m_vertex3DSigmaZ);
     declareProperty("zECToroid", m_zECToroid);
-    declareProperty("IDMS_xySigma", m_IDMS_xySigma);
-    declareProperty("IDMS_rzSigma", m_IDMS_rzSigma);
+    declareProperty("AlignmentUncertToolTheta"  , m_alignUncertTool_theta);
+    declareProperty("AlignmentUncertToolPhi"    , m_alignUncertTool_phi);
+    
 
     // deprecated
     declareProperty("IndetSlimming", m_indetSlimming);
@@ -292,30 +292,33 @@ CombinedMuonTrackBuilder::initialize()
     ATH_MSG_DEBUG("Retrieved Svc " << m_trackingVolumesSvc);
 
     m_calorimeterVolume =
-        new Trk::Volume(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::MuonSpectrometerEntryLayer));
-    m_indetVolume = new Trk::Volume(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::CalorimeterEntryLayer));
+        std::make_unique<Trk::Volume>(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::MuonSpectrometerEntryLayer));
+    m_indetVolume = std::make_unique<Trk::Volume>(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::CalorimeterEntryLayer));
 
     // sigma of phi sector for pseudo-measurement constraint
     m_sigmaPhiSector = std::tan(0.125 * M_PI / std::sqrt(12.));
 
     // create beamAxis and vertexRegion for constrained (projective) track fits
     Amg::Vector3D origin(0., 0., 0.);
-    m_perigeeSurface = new Trk::PerigeeSurface(origin);
+    m_perigeeSurface = std::make_unique<Trk::PerigeeSurface>(origin);
 
     AmgSymMatrix(3) beamAxisCovariance;
     beamAxisCovariance.setZero();
     (beamAxisCovariance)(0, 0) = m_vertex2DSigmaRPhi * m_vertex2DSigmaRPhi;
     (beamAxisCovariance)(1, 1) = m_vertex2DSigmaRPhi * m_vertex2DSigmaRPhi;
     (beamAxisCovariance)(2, 2) = m_vertex2DSigmaZ * m_vertex2DSigmaZ;
-    m_beamAxis                 = new Trk::RecVertex(origin, beamAxisCovariance);
+    m_beamAxis                 = std::make_unique<Trk::RecVertex>(origin, beamAxisCovariance);
 
     AmgSymMatrix(3) vertexRegionCovariance;
     vertexRegionCovariance.setZero();
     (vertexRegionCovariance)(0, 0) = m_vertex3DSigmaRPhi * m_vertex3DSigmaRPhi;
     (vertexRegionCovariance)(1, 1) = m_vertex3DSigmaRPhi * m_vertex3DSigmaRPhi;
     (vertexRegionCovariance)(2, 2) = m_vertex3DSigmaZ * m_vertex3DSigmaZ;
-    m_vertex                       = new Trk::RecVertex(origin, vertexRegionCovariance);
-
+    m_vertex                       = std::make_unique<Trk::RecVertex>(origin, vertexRegionCovariance);
+    if (m_addIDMSerrors) {
+        ATH_CHECK(m_alignUncertTool_theta.retrieve());
+        ATH_CHECK(m_alignUncertTool_phi.retrieve());
+    }
 #ifndef NDEBUG
     ATH_MSG_DEBUG(" vertex region: ");
     m_vertex->dump(msg(MSG::DEBUG));
@@ -352,15 +355,7 @@ CombinedMuonTrackBuilder::finalize()
 
     // summarize WARNINGs
     m_messageHelper->printSummary();
-
-    delete m_beamAxis;
-    delete m_calorimeterVolume;
-    delete m_indetVolume;
-    delete m_messageHelper;
-    delete m_perigeeSurface;
-    delete m_vertex;
-
-    return AthAlgTool::finalize();
+    return StatusCode::SUCCESS;
 }
 
 
@@ -2750,9 +2745,7 @@ CombinedMuonTrackBuilder::optimizeErrors(Trk::Track* track) const
     return false;
 }
 
-Trk::Track*
-CombinedMuonTrackBuilder::addIDMSerrors(Trk::Track* track) const
-{
+Trk::Track* CombinedMuonTrackBuilder::addIDMSerrors(Trk::Track* track) const {
     //
     // take track and correct the two scattering planes in the Calorimeter
     // to take into account m_IDMS_rzSigma and m_IDMS_xySigma
@@ -2764,168 +2757,97 @@ CombinedMuonTrackBuilder::addIDMSerrors(Trk::Track* track) const
     }
 
     ATH_MSG_DEBUG(" CombinedMuonTrackBuilder addIDMSerrors to track ");
-    Amg::Vector3D positionMS(0, 0, 0);
-    Amg::Vector3D positionCaloFirst(0, 0, 0);
-    Amg::Vector3D positionCaloLast(0, 0, 0);
-
-    int    itsos          = 0;
-    int    itsosCaloFirst = -1;
-    int    itsosCaloLast  = -1;
-    double p              = -1.;
-
-    DataVector<const Trk::TrackStateOnSurface>::const_iterator t = track->trackStateOnSurfaces()->begin();
-    for (; t != track->trackStateOnSurfaces()->end(); ++t) {
-        itsos++;
-
-        if ((**t).trackParameters()) {
-            if (p == -1.) {
-                p = (**t).trackParameters()->momentum().mag() / Gaudi::Units::GeV;
-            }
-
-            if (m_indetVolume->inside((**t).trackParameters()->position())) {
-                continue;
-            }
-
-            if ((**t).trackParameters()->position().mag() < 1000) {
-                continue;
-            }
-
-            if (m_calorimeterVolume->inside((**t).trackParameters()->position())) {
-                // first scattering plane in Calorimeter
-                if ((**t).type(Trk::TrackStateOnSurface::Scatterer) && (**t).materialEffectsOnTrack()) {
-                    double X0 = (**t).materialEffectsOnTrack()->thicknessInX0();
-                    if (X0 < 10) {
-                        continue;
-                    }
-
-                    if (itsosCaloFirst != -1) {
-                        itsosCaloLast    = itsos;
-                        positionCaloLast = (**t).trackParameters()->position();
-                    }
-
-                    if (itsosCaloFirst == -1) {
-                        itsosCaloFirst    = itsos;
-                        positionCaloFirst = (**t).trackParameters()->position();
-                    }
-                }
-            }
-
-            if (!m_calorimeterVolume->inside((**t).trackParameters()->position())) {
-                if ((**t).measurementOnTrack()) {
-                    // inside muon system
-                    positionMS = (**t).trackParameters()->position();
-                    break;
-                }
-            }
-        }
-    }
-
-    // it can happen that no Calorimeter Scatterers are found.
-    ATH_MSG_DEBUG(" CombinedMuonTrackBuilder addIDMSerrors p muon GeV "
-                  << p << " First Calorimeter Scatterer radius " << positionCaloFirst.perp() << " z "
-                  << positionCaloFirst.z() << " Second Scatterer r " << positionCaloLast.perp() << " z "
-                  << positionCaloLast.z() << " First Muon hit r " << positionMS.perp() << " z " << positionMS.z());
-
-    if (itsosCaloFirst < 0 || itsosCaloLast < 0) {
+   
+    
+    /// Use pointer in the data vector to refer on the track
+    const Trk::TrackStateOnSurface* id_exit       = nullptr;
+    const Trk::TrackStateOnSurface* calo_entrance = nullptr;
+    const Trk::TrackStateOnSurface* calo_exit     = nullptr;
+    const Trk::TrackStateOnSurface* ms_entrance   = nullptr;
+   
+    m_alignUncertTool_theta->get_track_state_measures(track,
+                                                      id_exit,
+                                                      calo_entrance,
+                                                      calo_exit,
+                                                      ms_entrance);
+    /// it can happen that no Calorimeter Scatterers are found.
+    if (!calo_entrance || !calo_exit || !ms_entrance) {
         ATH_MSG_DEBUG(" addIDMSerrors keep original track ");
         return track;
     }
-
-    // If no Calorimeter no IDMS uncertainties have to be propagated
-    positionCaloFirst = positionCaloFirst - positionMS;
-    positionCaloLast  = positionCaloLast - positionMS;
-
-    double sigmaDeltaPhiIDMS2   = m_IDMS_xySigma / (positionCaloFirst.perp() + positionCaloLast.perp());
-    double sigmaDeltaThetaIDMS2 = m_IDMS_rzSigma / (positionCaloFirst.mag() + positionCaloLast.mag());
-
-    sigmaDeltaPhiIDMS2 *= sigmaDeltaPhiIDMS2;
-    sigmaDeltaThetaIDMS2 *= sigmaDeltaThetaIDMS2;
-
-    DataVector<const Trk::TrackStateOnSurface>* trackStateOnSurfaces = new DataVector<const Trk::TrackStateOnSurface>;
+   
+    std::unique_ptr<DataVector<const Trk::TrackStateOnSurface>> trackStateOnSurfaces = std::make_unique<DataVector<const Trk::TrackStateOnSurface>>();
     trackStateOnSurfaces->reserve(track->trackStateOnSurfaces()->size());
 
-    t     = track->trackStateOnSurfaces()->begin();
-    itsos = 0;
-    for (; t != track->trackStateOnSurfaces()->end(); ++t) {
-        itsos++;
-
-        if (itsos == itsosCaloFirst || itsos == itsosCaloLast) {
-            if ((**t).materialEffectsOnTrack()) {
-                double X0 = (**t).materialEffectsOnTrack()->thicknessInX0();
-
-                const Trk::MaterialEffectsOnTrack* meot =
-                    dynamic_cast<const Trk::MaterialEffectsOnTrack*>((**t).materialEffectsOnTrack());
-
-                if (meot) {
-                    const Trk::ScatteringAngles* scat = meot->scatteringAngles();
-
-                    if (scat) {
-                        double sigmaDeltaPhi =
-                            std::sqrt((scat->sigmaDeltaPhi()) * (scat->sigmaDeltaPhi()) + sigmaDeltaPhiIDMS2);
-
-                        double sigmaDeltaTheta =
-                            std::sqrt((scat->sigmaDeltaTheta()) * (scat->sigmaDeltaTheta()) + sigmaDeltaThetaIDMS2);
-
-                        const Trk::EnergyLoss* energyLossNew = new Trk::EnergyLoss(0., 0., 0., 0.);
-
-                        const Trk::ScatteringAngles* scatNew =
-                            new Trk::ScatteringAngles(0., 0., sigmaDeltaPhi, sigmaDeltaTheta);
-
-                        const Trk::Surface& surfNew = (**t).trackParameters()->associatedSurface();
+    for (const Trk::TrackStateOnSurface* trk_srf : *track->trackStateOnSurfaces()) {        
+        if (calo_entrance == trk_srf || calo_entrance == trk_srf) {
+            if (!trk_srf->materialEffectsOnTrack()) {
+                ATH_MSG_DEBUG("No material effect on track");
+                continue;
+            }          
+            const Trk::MaterialEffectsOnTrack* meot = dynamic_cast<const Trk::MaterialEffectsOnTrack*>(trk_srf->materialEffectsOnTrack());
+            if (!meot){
+                ATH_MSG_WARNING(" This should not happen: no MaterialEffectsOnTrack for scatterer ");
+                continue;
+            }
+            const Trk::ScatteringAngles* scat = meot->scatteringAngles();
+            if (!scat){
+                ATH_MSG_WARNING(" This should not happen: no Scattering Angles for scatterer ");
+                continue;
+            }
+                 
+            float sigmaDeltaPhi   = std::hypot( scat->sigmaDeltaPhi(), m_alignUncertTool_phi->get_uncertainty(track));
+            float sigmaDeltaTheta = std::hypot( scat->sigmaDeltaPhi(), m_alignUncertTool_theta->get_uncertainty(track));
+            float X0 = trk_srf->materialEffectsOnTrack()->thicknessInX0();
+            
+            // 
 
-                        std::bitset<Trk::MaterialEffectsBase::NumberOfMaterialEffectsTypes> meotPattern(0);
-                        meotPattern.set(Trk::MaterialEffectsBase::EnergyLossEffects);
-                        meotPattern.set(Trk::MaterialEffectsBase::ScatteringEffects);
 
-                        const Trk::MaterialEffectsOnTrack* meotNew =
-                            new Trk::MaterialEffectsOnTrack(X0, scatNew, energyLossNew, surfNew, meotPattern);
+            const Trk::EnergyLoss* energyLossNew = new Trk::EnergyLoss(0., 0., 0., 0.);
+            const Trk::ScatteringAngles* scatNew = new Trk::ScatteringAngles(0., 0., sigmaDeltaPhi, sigmaDeltaTheta);
 
-                        const Trk::TrackParameters* parsNew = ((**t).trackParameters())->clone();
+            const Trk::Surface& surfNew = trk_srf->trackParameters()->associatedSurface();
 
-                        std::bitset<Trk::TrackStateOnSurface::NumberOfTrackStateOnSurfaceTypes> typePatternScat(0);
-                        typePatternScat.set(Trk::TrackStateOnSurface::Scatterer);
+            std::bitset<Trk::MaterialEffectsBase::NumberOfMaterialEffectsTypes> meotPattern(0);
+            meotPattern.set(Trk::MaterialEffectsBase::EnergyLossEffects);
+            meotPattern.set(Trk::MaterialEffectsBase::ScatteringEffects);
 
-                        const Trk::TrackStateOnSurface* newTSOS =
-                            new Trk::TrackStateOnSurface(nullptr, parsNew, nullptr, meotNew, typePatternScat);
+            const Trk::MaterialEffectsOnTrack* meotNew = new Trk::MaterialEffectsOnTrack(X0, scatNew, energyLossNew, surfNew, meotPattern);
+            const Trk::TrackParameters* parsNew = trk_srf->trackParameters()->clone();
 
-                        trackStateOnSurfaces->push_back(newTSOS);
+            std::bitset<Trk::TrackStateOnSurface::NumberOfTrackStateOnSurfaceTypes> typePatternScat(0);
+            typePatternScat.set(Trk::TrackStateOnSurface::Scatterer);
 
-                        ATH_MSG_DEBUG(" old Calo scatterer had sigmaDeltaPhi mrad      "
-                                      << scat->sigmaDeltaPhi() * 1000 << " sigmaDeltaTheta mrad "
-                                      << scat->sigmaDeltaTheta() * 1000 << " X0 " << X0);
+            const Trk::TrackStateOnSurface* newTSOS = new Trk::TrackStateOnSurface(nullptr, parsNew, nullptr, meotNew, typePatternScat);
+            trackStateOnSurfaces->push_back(newTSOS);
 
-                        ATH_MSG_DEBUG(" new Calo scatterer made with sigmaDeltaPhi mrad "
-                                      << sigmaDeltaPhi * 1000 << " sigmaDeltaTheta mrad " << sigmaDeltaTheta * 1000);
+            ATH_MSG_DEBUG(" old Calo scatterer had sigmaDeltaPhi mrad      "
+                                  << scat->sigmaDeltaPhi() * 1000 << " sigmaDeltaTheta mrad "
+                                  << scat->sigmaDeltaTheta() * 1000 << " X0 " << X0);
 
-                    } else {
-                        ATH_MSG_WARNING(" This should not happen: no Scattering Angles for scatterer ");
-                    }
-                } else {
-                    ATH_MSG_WARNING(" This should not happen: no MaterialEffectsOnTrack for scatterer ");
-                }
-            }
+            ATH_MSG_DEBUG(" new Calo scatterer made with sigmaDeltaPhi mrad "
+                                      << sigmaDeltaPhi * 1000 << " sigmaDeltaTheta mrad " << sigmaDeltaTheta * 1000);                          
+            
         } else {
             // skip AEOTs
-            if ((**t).alignmentEffectsOnTrack()) {
+            if (trk_srf->alignmentEffectsOnTrack()) {
                 ATH_MSG_DEBUG(" addIDMSerrors alignmentEffectsOnTrack()  found on track ");
-            }
-            const Trk::TrackStateOnSurface* TSOS = (**t).clone();
-            trackStateOnSurfaces->push_back(TSOS);
+                continue;
+            }           
+            trackStateOnSurfaces->push_back(trk_srf->clone());
         }
     }
-
     ATH_MSG_DEBUG(" trackStateOnSurfaces on input track " << track->trackStateOnSurfaces()->size()
                                                           << " trackStateOnSurfaces found "
                                                           << trackStateOnSurfaces->size());
 
-    Trk::Track* newTrack = new Trk::Track(track->info(), trackStateOnSurfaces, nullptr);
+    Trk::Track* newTrack = new Trk::Track(track->info(), trackStateOnSurfaces.release(), nullptr);
     if (newTrack) countAEOTs(newTrack, " add IDMS errors ");
     return newTrack;
 }
 
 
-void
-CombinedMuonTrackBuilder::appendSelectedTSOS(DataVector<const Trk::TrackStateOnSurface>& trackStateOnSurfaces,
+void CombinedMuonTrackBuilder::appendSelectedTSOS(DataVector<const Trk::TrackStateOnSurface>& trackStateOnSurfaces,
                                              DataVector<const Trk::TrackStateOnSurface>::const_iterator begin,
                                              DataVector<const Trk::TrackStateOnSurface>::const_iterator end) const
 {
diff --git a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/CMakeLists.txt b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/CMakeLists.txt
index 78cbdc3dfc48e62ca3fc3c8dddd43996077756f9..609be509ba9eb29dc34430157b453367191577ca 100644
--- a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/CMakeLists.txt
+++ b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/CMakeLists.txt
@@ -14,5 +14,5 @@ atlas_add_component( MuonCombinedBaseTools
                      src/*.cxx
                      src/components/*.cxx
                      INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ${CLHEP_INCLUDE_DIRS} 
-                     LINK_LIBRARIES ${ROOT_LIBRARIES} ${CLHEP_LIBRARIES} AtlasHepMCLib CaloEvent AthLinks AthenaBaseComps Identifier EventPrimitives FourMomUtils xAODCaloEvent xAODEventInfo xAODMuon xAODTracking xAODTruth GaudiKernel MuonReadoutGeometry MuonIdHelpersLib MuonCompetingRIOsOnTrack MuonRIO_OnTrack MuonSegment MuonRecHelperToolsLib MuonRecToolInterfaces MuonSegmentMakerUtils MuonSelectorToolsLib ICaloTrkMuIdTools MuidInterfaces MuonCombinedEvent MuonCombinedToolInterfaces muonEvent MuidEvent ParticleTruth RecoToolInterfaces TrackToCaloLib TrkGeometry TrkSurfaces TrkCaloExtension TrkEventPrimitives TrkEventUtils TrkMaterialOnTrack TrkParameters TrkParametersIdentificationHelpers TrkSegment TrkTrack TrkTrackSummary TrkExInterfaces TrkToolInterfaces BeamSpotConditionsData MagFieldElements MagFieldConditions xAODMuonCnvLib MuonSegmentTaggerToolInterfaces )
+                     LINK_LIBRARIES ${ROOT_LIBRARIES} ${CLHEP_LIBRARIES} AtlasHepMCLib PathResolver CaloEvent AthLinks AthenaBaseComps Identifier EventPrimitives FourMomUtils xAODCaloEvent xAODEventInfo xAODMuon xAODTracking xAODTruth GaudiKernel MuonReadoutGeometry MuonIdHelpersLib MuonCompetingRIOsOnTrack MuonRIO_OnTrack MuonSegment MuonRecHelperToolsLib MuonRecToolInterfaces MuonSegmentMakerUtils MuonSelectorToolsLib ICaloTrkMuIdTools MuidInterfaces MuonCombinedEvent MuonCombinedToolInterfaces muonEvent MuidEvent ParticleTruth RecoToolInterfaces TrackToCaloLib TrkGeometry TrkSurfaces TrkCaloExtension TrkEventPrimitives TrkEventUtils TrkMaterialOnTrack TrkParameters TrkParametersIdentificationHelpers TrkSegment TrkTrack TrkTrackSummary TrkExInterfaces TrkDetDescrInterfaces TrkToolInterfaces BeamSpotConditionsData MagFieldElements MagFieldConditions xAODMuonCnvLib MuonSegmentTaggerToolInterfaces )
 
diff --git a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.cxx b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.cxx
new file mode 100755
index 0000000000000000000000000000000000000000..6842ce41ce06aa663e710e26ed4971d02a32f6bd
--- /dev/null
+++ b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.cxx
@@ -0,0 +1,254 @@
+/*
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+*/
+
+#include "MuonAlignmentUncertTool.h"
+#include <cmath>
+#include <iomanip>
+#include "AthenaKernel/Units.h"
+#include "GaudiKernel/ServiceHandle.h"
+#include "TrkDetDescrInterfaces/ITrackingVolumesSvc.h"
+#include "TrkMaterialOnTrack/EnergyLoss.h"
+#include "TrkMaterialOnTrack/MaterialEffectsOnTrack.h"
+#include "TrkMaterialOnTrack/ScatteringAngles.h"
+#include "TrkParameters/TrackParameters.h"
+#include "TrkTrack/TrackStateOnSurface.h"
+#include <TFile.h>
+#include <PathResolver/PathResolver.h>
+
+
+namespace {
+    constexpr float MeVtoGeV = 1.e-3;
+}
+
+namespace Muon {
+    MuonAlignmentUncertTool::MuonAlignmentUncertTool(const std::string& type, const std::string& name,
+                                                   const IInterface* parent): 
+            AthAlgTool(type, name, parent),  
+            m_histo(nullptr),
+            m_dim(-1),                          
+            m_x_reader(make_reader(nullptr)),
+            m_y_reader(make_reader(nullptr)),
+            m_z_reader(make_reader(nullptr)),
+            m_calorimeterVolume(nullptr),                       
+            m_indetVolume(nullptr) {  
+    }
+    StatusCode MuonAlignmentUncertTool::initialize(){
+        /// Open the TFile
+        std::unique_ptr<TFile> r_file( TFile::Open(PathResolverFindCalibFile(m_in_file).c_str(), "READ"));
+        if (!r_file || !r_file->IsOpen()){
+            ATH_MSG_FATAL("No such file or directory "<<m_in_file);
+            return StatusCode::FAILURE;
+        }        
+        /// Read the histogram from the file
+        TH1* histo_in_file =nullptr;
+        r_file->GetObject(m_histo_name.value().c_str(), histo_in_file);
+        m_histo = std::unique_ptr<TH1>(histo_in_file);
+        if (!m_histo) {
+            ATH_MSG_FATAL("File "<<m_in_file<<" does not contain the histogram "<<m_histo_name<<".");
+            return StatusCode::FAILURE;
+        }
+        m_histo->SetDirectory(nullptr);
+        /// Set the dimension and the readers to be used
+        m_dim = m_histo->GetDimension();
+        m_x_reader = make_reader(m_histo->GetXaxis());
+        m_y_reader = make_reader(m_histo->GetYaxis());
+        m_z_reader = make_reader(m_histo->GetZaxis());
+       
+        ATH_CHECK(m_trackingVolumesSvc.retrieve());
+        m_calorimeterVolume = std::make_unique<Trk::Volume>(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::MuonSpectrometerEntryLayer));
+        m_indetVolume = std::make_unique<Trk::Volume>(m_trackingVolumesSvc->volume(Trk::ITrackingVolumesSvc::CalorimeterEntryLayer));
+        return StatusCode::SUCCESS;    
+    }
+    float MuonAlignmentUncertTool::get_uncertainty(const Trk::Track* trk) const {
+        if (!trk){
+            ATH_MSG_ERROR("No track has been given. Return FLT_MAX");
+            return FLT_MAX;
+        }
+        const int bin_x = m_x_reader(trk);
+        /// The second and third arguments of the GetBin method 
+        /// are 0 as default
+        const int bin_y = m_dim > 1 ? m_y_reader(trk) : 0;
+        const int bin_z = m_dim > 2 ? m_z_reader(trk) : 0;
+        return m_histo->GetBinContent(bin_x,bin_y,bin_z);
+    }
+    std::function<int(const Trk::Track* trk)> MuonAlignmentUncertTool::make_reader(const TAxis* axis) const{
+        /// Dummy function just returning 0 if no axis is given
+        if(!axis){
+            return [](const Trk::Track* ){return 0;};
+        }
+        std::string axis_title = axis->GetTitle();
+        if (axis_title == "#eta" || axis_title=="eta"){
+            return [axis] (const Trk::Track* trk){               
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(perigee->eta());
+            };
+        } else if (axis_title == "|#eta|" || axis_title == "abseta"){
+            return [axis] (const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(std::abs(perigee->eta()));
+            };
+        } else if (axis_title == "#phi" || axis_title == "phi"){
+            return [axis] (const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(perigee->parameters()[2]);
+            };
+        } else if (axis_title == "|#phi|" || axis_title == "absphi"){
+            return [axis] (const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(std::abs(perigee->parameters()[2]));
+            };
+        } else if (axis_title == "#theta" || axis_title == "theta"){
+            return [axis](const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(perigee->parameters()[3]);
+            };
+        } else if (axis_title == "|#theta|" || axis_title == "abstheta"){
+            return [axis](const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(std::abs(perigee->parameters()[3]));
+            };
+        } else if (axis_title == "p_{T}" || axis_title == "pT") {
+            return [axis](const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(perigee->pT());
+            };
+        } else if (axis_title == "p_{T} [GeV]" || axis_title == "pTinGeV") {
+            return [axis](const Trk::Track* trk){
+                const Trk::Perigee* perigee = trk->perigeeParameters();
+                return axis->FindBin(perigee->pT()*MeVtoGeV);
+            };
+        } else if (axis_title == "#rho @ ID-exit"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* id_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, id_exit, dummy, dummy, dummy);
+                 return axis->FindBin( id_exit->trackParameters()->position().perp());
+            };
+        } else if (axis_title == "R @ ID-exit"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* id_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, id_exit, dummy, dummy, dummy);
+                 return axis->FindBin( id_exit->trackParameters()->position().mag());
+            };
+        } else if (axis_title == "z @ ID-exit"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* id_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, id_exit, dummy, dummy, dummy);
+                 return axis->FindBin( id_exit->trackParameters()->position()[2]);
+            };
+        } else if (axis_title == "#rho @ Calo-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, dummy, dummy);
+                 return axis->FindBin( calo_entrance->trackParameters()->position().perp());
+            };
+        } else if (axis_title == "R @ Calo-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, dummy, dummy);
+                 return axis->FindBin( calo_entrance->trackParameters()->position().mag());
+            };
+        } else if (axis_title == "z @ Calo-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, dummy, dummy);
+                 return axis->FindBin( calo_entrance->trackParameters()->position()[2]);
+            };
+        } else if (axis_title == "#rho @ Calo-centre"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* calo_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, calo_exit, dummy);
+                 const Amg::Vector3D calo_centre = 0.5 * (calo_entrance->trackParameters()->position() +
+                                                          calo_exit->trackParameters()->position());
+                 return axis->FindBin( calo_centre.perp());
+            };
+        } else if (axis_title == "R @ Calo-centre"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* calo_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, calo_exit, dummy);
+                 const Amg::Vector3D calo_centre = 0.5 * (calo_entrance->trackParameters()->position() +
+                                                          calo_exit->trackParameters()->position());
+                 return axis->FindBin(calo_centre.mag());
+            };
+        } else if (axis_title == "z @ Calo-centre"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* calo_entrance;
+                 const Trk::TrackStateOnSurface* calo_exit;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, calo_entrance, calo_exit, dummy);
+                 const Amg::Vector3D calo_centre = 0.5 * (calo_entrance->trackParameters()->position() +
+                                                          calo_exit->trackParameters()->position());
+                 return axis->FindBin(calo_centre[2]);
+            };
+        }  else if (axis_title == "#rho @ MS-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* ms_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, dummy, dummy, ms_entrance);
+                 return axis->FindBin( ms_entrance->trackParameters()->position().perp());
+            };
+        } else if (axis_title == "R @ MS-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* ms_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, dummy, dummy, ms_entrance);
+                 return axis->FindBin( ms_entrance->trackParameters()->position().mag());
+            };
+        } else if (axis_title == "z @ MS-entrance"){
+            return[axis,this](const Trk::Track* trk){
+                 const Trk::TrackStateOnSurface* ms_entrance;
+                 const Trk::TrackStateOnSurface* dummy;
+                 get_track_state_measures(trk, dummy, dummy, dummy, ms_entrance);
+                 return axis->FindBin( ms_entrance->trackParameters()->position()[2]);
+            };
+        }       
+        return make_reader(nullptr);    
+    }
+    
+    void MuonAlignmentUncertTool::get_track_state_measures(const Trk::Track* track, const Trk::TrackStateOnSurface*& id_exit,
+                                                    const Trk::TrackStateOnSurface*& calo_entrance,
+                                                    const Trk::TrackStateOnSurface*& calo_exit,
+                                                    const Trk::TrackStateOnSurface*& ms_entrance) const {
+        id_exit = calo_entrance = calo_exit = ms_entrance = nullptr;        
+        if (!track) {
+            ATH_MSG_DEBUG("No track has been given. Where is my track?!");
+            return;
+        }
+        for (const Trk::TrackStateOnSurface* trk_srf : *track->trackStateOnSurfaces()) {
+            if (!trk_srf->trackParameters()) { continue; }
+            if (m_indetVolume->inside(trk_srf->trackParameters()->position())) {
+                if (trk_srf->type(Trk::TrackStateOnSurface::Measurement)) id_exit = trk_srf;
+                continue;
+            }
+            /// Try to find the calorimeter entrance and leaving points
+            if (m_calorimeterVolume->inside(trk_srf->trackParameters()->position())) {
+                // first scattering plane in Calorimeter
+                if (trk_srf->type(Trk::TrackStateOnSurface::Scatterer) && trk_srf->materialEffectsOnTrack()) {
+                    if (trk_srf->materialEffectsOnTrack()->thicknessInX0() < 10) { continue; }
+                    if (!calo_entrance) {
+                        calo_entrance = trk_srf;
+                    } else {
+                        calo_exit = trk_srf;
+                    }
+                }
+            }
+            /// inside muon system
+            else if (trk_srf->measurementOnTrack()) {
+                ms_entrance = trk_srf;
+                break;
+            }
+        }
+    }
+            
+    
+}  // namespace Rec
diff --git a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.h b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.h
new file mode 100755
index 0000000000000000000000000000000000000000..fea5b199ed086727d43d6465c2ba13979894f7cb
--- /dev/null
+++ b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/MuonAlignmentUncertTool.h
@@ -0,0 +1,89 @@
+/*
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
+*/
+
+//////////////////////////////////////////////////////////////////////////////
+//   MuonAlignmentUncertTool
+//      Helper classes to read the scattering and alignment uncertainties
+//      of the muons from the histograms
+//  (c) ATLAS Combined Muon software
+//////////////////////////////////////////////////////////////////////////////
+
+#ifndef MUONCOMBINEDBASETOOLS_MUONALIGNMENTUNCERTTOOL_H
+#define MUONCOMBINEDBASETOOLS_MUONALIGNMENTUNCERTTOOL_H
+
+#include <MuidInterfaces/IMuonAlignmentUncertTool.h>
+#include <AthenaBaseComps/AthAlgTool.h>
+#include <GaudiKernel/ServiceHandle.h>
+#include "GaudiKernel/ToolHandle.h"
+
+#include <TrkDetDescrInterfaces/ITrackingVolumesSvc.h>
+#include <TrkTrack/TrackStateOnSurface.h>
+#include <TrkTrack/Track.h>
+#include <TrkGeometry/TrackingVolume.h>
+/// Memory for the smart pointers
+#include <memory>
+/// Numbers are read from histograms
+#include <TH1.h>
+#include <string>
+#include <map>
+#include <vector>
+#include <functional>
+
+namespace Muon {
+    class MuonAlignmentUncertTool : public AthAlgTool, virtual public IMuonAlignmentUncertTool {
+        public:
+            
+            MuonAlignmentUncertTool(const std::string& type, const std::string& name, const IInterface* parent);
+            ~MuonAlignmentUncertTool()=default;
+
+            StatusCode initialize() override;
+              
+            float get_uncertainty(const Trk::Track* trk) const override;
+            
+            /// Helper method to retrieve the last measurement of the ID, 
+            ///  the first and last scatterer in the calorimeter
+            /// and finally to retrieve the first measurement inside the MS
+           void get_track_state_measures(const Trk::Track* track, const Trk::TrackStateOnSurface*& id_exit,
+                                                    const Trk::TrackStateOnSurface*& calo_entrance,
+                                                    const Trk::TrackStateOnSurface*& calo_exit,
+                                                    const Trk::TrackStateOnSurface*& ms_entrance) const override;
+                                                    
+        private:
+            /// Helper function to assign the uncertainty from the Axis. 
+            /// Assignment is based on the title of the axis
+            std::function<int(const Trk::Track* trk)> make_reader(const TAxis* axis) const;
+           
+           
+           
+            /// Volume service to 
+            ///
+            ServiceHandle<Trk::ITrackingVolumesSvc>  m_trackingVolumesSvc{this,"TrackingVolumesSvc",
+                                                                               "TrackingVolumesSvc/TrackingVolumesSvc"};
+            
+           
+           Gaudi::Property<std::string> m_in_file{this, "InFile", 
+                                    "MuonCombinedBaseTools/AlignmentUncertainties/201029_initial/ID_MS_Uncertainties.root", 
+                                    "Location of the calibration file"};
+           Gaudi::Property<std::string> m_histo_name{this, "HistoName", "", "Name of the histogram in the file"};
+          
+            
+            /// Histogram to be cached
+            std::unique_ptr<TH1> m_histo;
+            unsigned int m_dim;
+            /// Standard functions used to read the histogram having as input
+            /// a Trk::Track. 
+            std::function<int(const Trk::Track* trk)> m_x_reader;
+            std::function<int(const Trk::Track* trk)> m_y_reader;
+            std::function<int(const Trk::Track* trk)> m_z_reader;
+            
+            
+            std::unique_ptr<const Trk::Volume>         m_calorimeterVolume;            
+            std::unique_ptr<const Trk::Volume>         m_indetVolume;          
+    
+    };
+
+
+}  // end of namespace Rec
+
+#endif  
diff --git a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/components/MuonCombinedBaseTools_entries.cxx b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/components/MuonCombinedBaseTools_entries.cxx
index fd5af147393aad3b94330436f20ae10e6424e8d8..1f7548ef23d2c377d4ba03285dac8f70232cf47f 100644
--- a/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/components/MuonCombinedBaseTools_entries.cxx
+++ b/Reconstruction/MuonIdentification/MuonCombinedBaseTools/src/components/MuonCombinedBaseTools_entries.cxx
@@ -8,10 +8,12 @@
 #include "../MuonSegmentTagTool.h"
 #include "../MuonCaloTagTool.h"
 #include "../TrackSegmentAssociationTool.h"
+#include "../MuonAlignmentUncertTool.h"
 
 using namespace MuonCombined;
 using namespace Muon;
 DECLARE_COMPONENT( MuonCandidateTool )
+DECLARE_COMPONENT( MuonAlignmentUncertTool )
 DECLARE_COMPONENT( MuonCombinedTool )
 DECLARE_COMPONENT( MuonCombinedDebuggerTool )
 DECLARE_COMPONENT( MuonCreatorTool )
diff --git a/Reconstruction/MuonIdentification/MuonCombinedConfig/python/MuonCombinedRecToolsConfig.py b/Reconstruction/MuonIdentification/MuonCombinedConfig/python/MuonCombinedRecToolsConfig.py
index 9e18e52a5dc1699e4b7df8cd5609283b56470780..1b39bc031dfd4fe728750020f2196b6f8bd25963 100644
--- a/Reconstruction/MuonIdentification/MuonCombinedConfig/python/MuonCombinedRecToolsConfig.py
+++ b/Reconstruction/MuonIdentification/MuonCombinedConfig/python/MuonCombinedRecToolsConfig.py
@@ -567,6 +567,20 @@ def MuidErrorOptimisationToolCfg(flags, name='MuidErrorOptimisationToolFit', **k
     kwargs.setdefault("TrackSummaryTool",  result.popPrivateTools() )
     return result
 
+def MuonAlignmentUncertToolThetaCfg(flags,name ="MuonAlignmentUncertToolTheta", **kwargs):
+    result = ComponentAccumulator()
+    kwargs.setdefault("HistoName", "ThetaScattering")
+    kwargs.setdefault("InFile", "MuonCombinedBaseTools/AlignmentUncertainties/201029_initial/ID_MS_Uncertainties.root")
+    tool = CompFactory.Muon.MuonAlignmentUncertTool(name,**kwargs)
+    result.addPublicTool(tool)
+    return result
+def MuonAlignmentUncertToolPhiCfg(flags,name ="MuonAlignmentUncertToolPhi", **kwargs):
+    result = ComponentAccumulator()
+    kwargs.setdefault("HistoName", "PhiScattering")
+    kwargs.setdefault("InFile", "MuonCombinedBaseTools/AlignmentUncertainties/201029_initial/ID_MS_Uncertainties.root")
+    tool =  CompFactory.Muon.MuonAlignmentUncertTool(name,**kwargs)
+    result.addPublicTool(tool)
+    return result
 def CombinedMuonTrackBuilderCfg(flags, name='CombinedMuonTrackBuilder', **kwargs ):
     from AthenaCommon.SystemOfUnits import meter
     from MuonConfig.MuonRIO_OnTrackCreatorConfig import CscClusterOnTrackCreatorCfg,MdtDriftCircleOnTrackCreatorCfg
@@ -581,7 +595,13 @@ def CombinedMuonTrackBuilderCfg(flags, name='CombinedMuonTrackBuilder', **kwargs
     acc = MuidTrackCleanerCfg(flags)
     kwargs.setdefault("Cleaner"                      , acc.popPrivateTools() )
     result.merge(acc)
-
+    acc = MuonAlignmentUncertToolPhiCfg(flags)
+    result.merge(acc)
+    kwargs.setdefault("AlignmentUncertToolPhi", result.getPublicTool('MuonAlignmentUncertToolPhi') )      
+    acc = MuonAlignmentUncertToolThetaCfg(flags)
+    result.merge(acc)
+    kwargs.setdefault("AlignmentUncertToolTheta", result.getPublicTool('MuonAlignmentUncertToolTheta') )
+      
     if flags.Detector.GeometryCSC and not flags.Muon.MuonTrigger:
         acc = CscClusterOnTrackCreatorCfg(flags)
         kwargs.setdefault("CscRotCreator"                 , acc.popPrivateTools() )
@@ -687,8 +707,7 @@ def CombinedMuonTrackBuilderCfg(flags, name='CombinedMuonTrackBuilder', **kwargs
     tool = CompFactory.Rec.CombinedMuonTrackBuilder(name,**kwargs)
     result.setPrivateTools(tool)
     return result
-
-
+   
 def CombinedMuonTrackBuilderFitCfg(flags, name='CombinedMuonTrackBuilderFit', **kwargs ):
     # In the old configuration we had duplication between CombinedMuonTrackBuilder and CombinedMuonTrackBuilderFit
     # Here we just call the Combined
@@ -699,7 +718,6 @@ def CombinedMuonTrackBuilderFitCfg(flags, name='CombinedMuonTrackBuilderFit', **
     acc = CombinedMuonTrackBuilderCfg(flags, name, **kwargs)
     tool = acc.popPrivateTools() #Need to reset this to be the primary tool
     result.merge(acc)
-
     result.setPrivateTools(tool)
     return result
 
diff --git a/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedFitTools.py b/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedFitTools.py
index 3f49316625f8f16a3f4c3332d15d5b457d081308..2f628b59fadbe87fba8dcccc4458f15b3e3aab2d 100644
--- a/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedFitTools.py
+++ b/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedFitTools.py
@@ -226,12 +226,25 @@ def MuonMaterialProviderTool( name = "MuonMaterialProviderTool"):
         materialProviderTool.UseCaloEnergyMeasurement = False
     return materialProviderTool
 
+def MuonAlignmentUncertToolTheta(name ="MuonAlignmentUncertToolTheta", **kwargs):
+    kwargs.setdefault("HistoName", "ThetaScattering")
+    kwargs.setdefault("InFile", "MuonCombinedBaseTools/AlignmentUncertainties/201029_initial/ID_MS_Uncertainties.root")
+    return CfgMgr.Muon__MuonAlignmentUncertTool(name,**kwargs)
+
+def MuonAlignmentUncertToolPhi(name ="MuonAlignmentUncertToolPhi", **kwargs):
+    kwargs.setdefault("HistoName", "PhiScattering")
+    kwargs.setdefault("InFile", "MuonCombinedBaseTools/AlignmentUncertainties/201029_initial/ID_MS_Uncertainties.root")
+    return CfgMgr.Muon__MuonAlignmentUncertTool(name,**kwargs)
+        
 def CombinedMuonTrackBuilderFit( name='CombinedMuonTrackBuilderFit', **kwargs ):
     from AthenaCommon.AppMgr import ToolSvc
     kwargs.setdefault("CaloEnergyParam"               , getPublicTool("MuidCaloEnergyToolParam") )
     kwargs.setdefault("CaloTSOS"                      , getPublicTool("MuidCaloTrackStateOnSurface") )
     kwargs.setdefault("MaterialAllocator"             , getPublicTool("MuidMaterialAllocator") )
     kwargs.setdefault("MdtRotCreator"                 , getPublicTool("MdtDriftCircleOnTrackCreator") )
+    kwargs.setdefault("AlignmentUncertToolPhi"        , getPublicTool("MuonAlignmentUncertToolPhi") )
+    kwargs.setdefault("AlignmentUncertToolTheta"      , getPublicTool("MuonAlignmentUncertToolTheta") )
+    
     kwargs.setdefault("CleanCombined"                 , True )
     kwargs.setdefault("CleanStandalone"               , True )
     kwargs.setdefault("BadFitChi2"                    , 2.5 )
diff --git a/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedRecExampleConfigDb.py b/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedRecExampleConfigDb.py
index 0a3cd804794cc3e402e9513341ee2070d65f86fe..3424802d13253e4950f6d2f47591809f033e68c7 100644
--- a/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedRecExampleConfigDb.py
+++ b/Reconstruction/MuonIdentification/MuonCombinedRecExample/python/MuonCombinedRecExampleConfigDb.py
@@ -102,6 +102,9 @@ addTool("MuonCombinedRecExample.MuonCaloTagTool.CaloMuonScoreTool","CaloMuonScor
 addService("MuonCombinedRecExample.MuonCaloTagTool.CaloMuonScoreONNXRuntimeSvc","CaloMuonScoreONNXRuntimeSvc")
 
 ####### muid tools
+addTool("MuonCombinedRecExample.MuonCombinedFitTools.MuonAlignmentUncertToolTheta","MuonAlignmentUncertToolTheta")
+addTool("MuonCombinedRecExample.MuonCombinedFitTools.MuonAlignmentUncertToolPhi"  ,"MuonAlignmentUncertToolPhi")
+
 addTool("MuonCombinedRecExample.MuonCombinedFitTools.MuonMatchQuality","MuonMatchQuality")
 addTool("MuonCombinedRecExample.MuonCombinedFitTools.MuidMuonRecovery","MuidMuonRecovery")
 addTool("MuonCombinedRecExample.MuonCombinedFitTools.MuonCombinedTrackFitter","MuonCombinedTrackFitter")
diff --git a/Reconstruction/RecBackground/RecBackgroundAlgs/RecBackgroundAlgs/BackgroundWordFiller.h b/Reconstruction/RecBackground/RecBackgroundAlgs/RecBackgroundAlgs/BackgroundWordFiller.h
index fa61a22807f7e278dbc8d078e195518796606cc7..7bd7d5da4062365d199ede30923cb2b4fa02afb8 100644
--- a/Reconstruction/RecBackground/RecBackgroundAlgs/RecBackgroundAlgs/BackgroundWordFiller.h
+++ b/Reconstruction/RecBackground/RecBackgroundAlgs/RecBackgroundAlgs/BackgroundWordFiller.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
 */
 
 /* Algorihtm to fill the background word that is stored in the EventInfo 
@@ -58,6 +58,11 @@ class BackgroundWordFiller : public AthAlgorithm
   /** ReadHandleKey for LArCollisionTime */
   SG::ReadHandleKey<LArCollisionTime> m_lArCollisionTimeKey{this,"LArCollisionTimeKey","LArCollisionTime","Key for LArCollisionTime"};
 
+  /** WriteDecorHandleKey: needed for scheduling downstream clients */
+  SG::WriteDecorHandleKey<xAOD::EventInfo> m_eventInfoDecorKey{this,"eventInfoDecorKey",
+                                                               "EventInfo.backgroundWord",
+                                                               "Decoration key for downstream clients"};
+
   Gaudi::Property<bool> m_isMC{this, "IsMC", false, "Sets whether we should expect MC objects"};
   
   int m_HaloNumSegment_Cut;
diff --git a/Reconstruction/RecBackground/RecBackgroundAlgs/src/BackgroundWordFiller.cxx b/Reconstruction/RecBackground/RecBackgroundAlgs/src/BackgroundWordFiller.cxx
index 52e545b4d2d3ac04fbdfc10f931e7f1242df323b..b3f5ec723f5fd354e6aec5db430fd7343cc5b82c 100644
--- a/Reconstruction/RecBackground/RecBackgroundAlgs/src/BackgroundWordFiller.cxx
+++ b/Reconstruction/RecBackground/RecBackgroundAlgs/src/BackgroundWordFiller.cxx
@@ -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
 */
 
 /* Algorihtm to fill the background word that is stored in the EventInfo 
@@ -139,6 +139,7 @@ StatusCode BackgroundWordFiller::initialize() {
   ATH_CHECK(m_rawInfoSummaryForTagKey.initialize(!m_isMC));
   ATH_CHECK(m_tileCellContainerKey.initialize());
   ATH_CHECK(m_lArCollisionTimeKey.initialize(!m_isMC));
+  ATH_CHECK(m_eventInfoDecorKey.initialize());
   
   return StatusCode::SUCCESS;  
 }
diff --git a/Reconstruction/RecExample/RecExCommon/share/RecExCommon_topOptions.py b/Reconstruction/RecExample/RecExCommon/share/RecExCommon_topOptions.py
index fb3a520a2af04978a42a22617ce2395427da5801..fb953b93aecd9944913a2f68433ddf62b4d7202f 100644
--- a/Reconstruction/RecExample/RecExCommon/share/RecExCommon_topOptions.py
+++ b/Reconstruction/RecExample/RecExCommon/share/RecExCommon_topOptions.py
@@ -1293,6 +1293,7 @@ if ( rec.doAOD() or rec.doWriteAOD()) and not rec.readAOD() :
                 alg = TauCellThinningAlg('TauCellThinningAlg',
                                          StreamName = 'StreamAOD',
                                          Cells = 'AllCalo',
+                                         CellLinks = 'CaloCalTopoClusters_links',
                                          Taus = "TauJets",
                                          UseSubtractedCluster = tauFlags.useSubtractedCluster())
                 topSequence += alg
diff --git a/Reconstruction/VKalVrt/VrtSecInclusive/src/Utilities.cxx b/Reconstruction/VKalVrt/VrtSecInclusive/src/Utilities.cxx
index b87d036b8decbf56c193870be8e9685f8f69dbb2..1d4b6c6f7772d8549dcc8052159b4af82b7995dc 100755
--- a/Reconstruction/VKalVrt/VrtSecInclusive/src/Utilities.cxx
+++ b/Reconstruction/VKalVrt/VrtSecInclusive/src/Utilities.cxx
@@ -21,7 +21,7 @@
 using namespace std;
 
 namespace Trk {
-  extern void dsinv(long int * , double *, long int , long int *);             
+  extern void dsinv(long int, double *, long int , long int *) noexcept;
 }
 
 namespace VKalVrtAthena {
@@ -54,7 +54,7 @@ namespace VKalVrtAthena {
     mmm[2][2] =             VrtErr1[5]+VrtErr2[5];
 
     long int jfail,NN=3;
-    Trk::dsinv( &NN, &mmm[0][0], NN, &jfail);
+    Trk::dsinv( NN, &mmm[0][0], NN, &jfail);
 
     if(jfail==0){
       Signif = distx*mmm[0][0]*distx
diff --git a/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.cxx b/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.cxx
index 4f7d23655bd723cde357bcf85087b86d12c77679..3f272c68cce72416ce0a5e5a6e854329fd034357 100755
--- a/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.cxx
+++ b/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.cxx
@@ -19,6 +19,7 @@ StatusCode MonitorElectronAlgorithm::initialize() {
     using namespace Monitored;
     ATH_CHECK( AthMonitorAlgorithm::initialize() );
     ATH_CHECK( m_ParticleContainerKey.initialize() );
+    ATH_CHECK( m_ElectronIsolationKey.initialize() );
     return StatusCode::SUCCESS;
 }
 
diff --git a/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.h b/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.h
index 356f5a99f3bae345ac6e94b8bee2b79bcb75f9a6..a54d5843a5b449f705018b6ebda0d13538170106 100755
--- a/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.h
+++ b/Reconstruction/egamma/egammaPerformance/src/MonitorElectronAlgorithm.h
@@ -30,6 +30,7 @@ public:
 private:
 
   SG::ReadHandleKey<xAOD::ElectronContainer> m_ParticleContainerKey {this, "ParticleContainerName", "Electrons", "Name of electron container" };
+  SG::ReadDecorHandleKey<xAOD::ElectronContainer> m_ElectronIsolationKey {this, "ElectronIsolationKey", "Electrons.ptcone20"};
   Gaudi::Property<std::string> m_ParticlePrefix {this,"ParticlePrefix","electron","Name of the particle prefix to be used to define hists"};
   Gaudi::Property<std::string> m_RecoName {this,"RecoName","LHTight","Name of particle flavor in egamma reco"};
   Gaudi::Property<std::string> m_WithTrigger {this,"WithTrigger","","Name extension when electrons are chosen from triggered events"};
diff --git a/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.cxx b/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.cxx
index 00341330b04954b0bb952be1f1711ec5adf52bb0..5753e41688a5fe30b8a36b1f86131daab369d1bc 100755
--- a/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.cxx
+++ b/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.cxx
@@ -19,6 +19,7 @@ StatusCode MonitorPhotonAlgorithm::initialize() {
     using namespace Monitored;
     ATH_CHECK(AthMonitorAlgorithm::initialize() );
     ATH_CHECK( m_ParticleContainerKey.initialize() );
+    ATH_CHECK( m_PhotonIsolationKey.initialize() );
     return StatusCode::SUCCESS;
 }
 
diff --git a/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.h b/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.h
index f8921a4151b6b6cdce3f46740bf921aedfef97b9..775f59469dfa20ed30b9c62d03220898b7832302 100755
--- a/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.h
+++ b/Reconstruction/egamma/egammaPerformance/src/MonitorPhotonAlgorithm.h
@@ -29,6 +29,7 @@ class MonitorPhotonAlgorithm : public AthMonitorAlgorithm {
 
   private:
     SG::ReadHandleKey<xAOD::PhotonContainer> m_ParticleContainerKey {this, "ParticleContainerName", "Photons", "Name of electron container" };
+    SG::ReadDecorHandleKey<xAOD::PhotonContainer> m_PhotonIsolationKey {this, "PhotonIsolationKey", "Photons.ptcone20"};
     Gaudi::Property<std::string> m_ParticlePrefix {this,"ParticlePrefix","photon","Name of the particle prefix to be used to define hists"};
     Gaudi::Property<std::string> m_RecoName {this,"RecoName","Tight","Name of particle flavor in egamma reco"};
     Gaudi::Property<std::string> m_WithTrigger {this,"WithTrigger","","Name extension when electrons are chosen from triggered events"};
diff --git a/Reconstruction/tauRec/src/TauCellThinningAlg.cxx b/Reconstruction/tauRec/src/TauCellThinningAlg.cxx
index 1faf4ef756ced6c604e06631377687b85a6e45f0..15dcd85b8e4bb5d4f09d9f668adc29653b14ddec 100644
--- a/Reconstruction/tauRec/src/TauCellThinningAlg.cxx
+++ b/Reconstruction/tauRec/src/TauCellThinningAlg.cxx
@@ -15,6 +15,7 @@
 StatusCode TauCellThinningAlg::initialize()
 {
   ATH_CHECK( m_cells.initialize(m_streamName) );
+  ATH_CHECK( m_cellLinks.initialize(m_streamName) );
   ATH_CHECK( m_taus.initialize() );
 
   return StatusCode::SUCCESS;
@@ -28,6 +29,9 @@ StatusCode TauCellThinningAlg::execute (const EventContext& ctx) const
 {
   SG::ThinningHandle<CaloCellContainer> cells (m_cells, ctx);
   cells.thinAll();
+  
+  SG::ThinningHandle<CaloClusterCellLinkContainer> cellLinkHandle (m_cellLinks, ctx);
+  cellLinkHandle.thinAll();
 
   SG::ReadHandle<xAOD::TauJetContainer> taus (m_taus, ctx);
   if (!taus.isValid()) {
@@ -45,7 +49,7 @@ StatusCode TauCellThinningAlg::execute (const EventContext& ctx) const
 
       const CaloClusterCellLink* cellLinks = cluster->getCellLinks();
       if (!cellLinks) {
-	ATH_MSG_WARNING( "Cluster without cell links found! Cells cannot be written in AOD." );
+	ATH_MSG_WARNING( "Cluster without cell links found! Cells cannot be written in xAOD." );
 	continue;
       }
       
@@ -56,7 +60,18 @@ StatusCode TauCellThinningAlg::execute (const EventContext& ctx) const
 			 << m_cells.key() << "; cluster skipped.");
 	continue;
       }
-      
+
+      // cluster cell link thinning
+      CaloClusterCellLinkContainer::const_iterator cellLinks_it = std::find(cellLinkHandle->begin(), cellLinkHandle->end(), cellLinks);
+      if(cellLinks_it != cellLinkHandle->end()) {
+	size_t link_index = std::distance(cellLinkHandle->begin(), cellLinks_it);
+	cellLinkHandle.keep(link_index);
+      }
+      else {
+	ATH_MSG_WARNING( "Could not find cluster cell link in " << m_cellLinks.key() << ", won't be saved in xAOD." );
+      }
+
+      // cell thinning
       CaloClusterCellLink::const_iterator it = cellLinks->begin();
       CaloClusterCellLink::const_iterator end = cellLinks->end();
       for (; it != end; ++it) {
diff --git a/Reconstruction/tauRec/tauRec/TauCellThinningAlg.h b/Reconstruction/tauRec/tauRec/TauCellThinningAlg.h
index 6af5a040330bc137f673170e9d1f90eee8563954..a202feee001d8b16f6a2e384728c81ed9cd34379 100644
--- a/Reconstruction/tauRec/tauRec/TauCellThinningAlg.h
+++ b/Reconstruction/tauRec/tauRec/TauCellThinningAlg.h
@@ -7,6 +7,7 @@
 
 #include "AthenaBaseComps/AthReentrantAlgorithm.h"
 #include "CaloEvent/CaloCellContainer.h"
+#include "CaloEvent/CaloClusterCellLinkContainer.h"
 #include "xAODTau/TauJetContainer.h"
 #include "StoreGate/ReadHandleKey.h"
 #include "StoreGate/ThinningHandleKey.h"
@@ -45,6 +46,10 @@ class TauCellThinningAlg : public AthReentrantAlgorithm
   SG::ThinningHandleKey<CaloCellContainer> m_cells
     { this, "Cells", "AllCalo", "Cell container to thin" };
 
+  // Cluster cell link container to thin
+  SG::ThinningHandleKey<CaloClusterCellLinkContainer> m_cellLinks
+    { this, "CellLinks", "CaloCalTopoClusters_links", "Cell container to thin" };
+
   // Tau container
   SG::ReadHandleKey<xAOD::TauJetContainer> m_taus
     { this, "Taus", "TauJets", "Container of taus for which cells should be saved" };
diff --git a/Reconstruction/tauRecTools/Root/TauPi0ScoreCalculator.cxx b/Reconstruction/tauRecTools/Root/TauPi0ScoreCalculator.cxx
index 1adadc66ea3637a3f1e7d51944c462132c4e110f..93832ed995735e4a3421dd4ba7450502140fc6e2 100644
--- a/Reconstruction/tauRecTools/Root/TauPi0ScoreCalculator.cxx
+++ b/Reconstruction/tauRecTools/Root/TauPi0ScoreCalculator.cxx
@@ -2,38 +2,20 @@
   Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-//-----------------------------------------------------------------------------
-// file:        TauPi0ScoreCalculator.cxx
-// package:     Reconstruction/tauRec
-// authors:     Benedict Winter, Will Davey
-// date:        2012-10-09
-//-----------------------------------------------------------------------------
-
 #include "tauRecTools/TauPi0ScoreCalculator.h"
 #include "tauRecTools/HelperFunctions.h"
 #include "xAODPFlow/PFO.h"
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
+
 
 TauPi0ScoreCalculator::TauPi0ScoreCalculator(const std::string& name) :
-  TauRecToolBase(name),
-  m_mvaBDT(nullptr)
-{
-    declareProperty("BDTWeightFile", m_weightfile);
+    TauRecToolBase(name) {
+  declareProperty("BDTWeightFile", m_weightfile = "");
 }
 
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
 
-TauPi0ScoreCalculator::~TauPi0ScoreCalculator() 
-{
-}
 
-StatusCode TauPi0ScoreCalculator::initialize() 
-{
+StatusCode TauPi0ScoreCalculator::initialize() {
   std::string weightFile = find_file(m_weightfile);
 
   m_mvaBDT = std::make_unique<tauRecTools::BDTHelper>();
@@ -42,124 +24,119 @@ StatusCode TauPi0ScoreCalculator::initialize()
   return StatusCode::SUCCESS;
 }
 
-StatusCode TauPi0ScoreCalculator::executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const
-{
-    //---------------------------------------------------------------------
-    // only run on 1-5 prong taus 
-    //---------------------------------------------------------------------
-    if (pTau.nTracks() == 0 || pTau.nTracks() >5 ) {
-        return StatusCode::SUCCESS;
-    }
-    ATH_MSG_DEBUG("ScoreCalculator: new tau. \tpt = " << pTau.pt() << "\teta = " << pTau.eta() << "\tphi = " << pTau.phi() << "\tnprongs = " << pTau.nTracks());
-
-    //---------------------------------------------------------------------
-    // retrieve neutral PFOs from tau, calculate BDT scores and store them in PFO
-    //---------------------------------------------------------------------
-    for( auto neutralPFO : neutralPFOContainer )
-    {
-      float BDTScore = calculateScore(neutralPFO);
-      neutralPFO->setBDTPi0Score(BDTScore);
-    }
-
-    ATH_MSG_DEBUG("End of TauPi0ScoreCalculator::execute");
 
+
+StatusCode TauPi0ScoreCalculator::executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const {
+  // Only run on 1-5 prong taus 
+  if (pTau.nTracks() == 0 || pTau.nTracks() > 5 ) {
     return StatusCode::SUCCESS;
+  }
+
+  // retrieve neutral PFOs from tau, calculate BDT scores and store them in PFO
+  for (xAOD::PFO* neutralPFO : neutralPFOContainer) {
+    float BDTScore = calculateScore(neutralPFO);
+    neutralPFO->setBDTPi0Score(BDTScore);
+  }
+
+  return StatusCode::SUCCESS;
 }
 
-float TauPi0ScoreCalculator::calculateScore(const xAOD::PFO* neutralPFO) const
-{
-    std::map<TString, float> availableVariables; // map of the variable name to its value
-    
-    float Abs_FIRST_ETA = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_FIRST_ETA, Abs_FIRST_ETA) == false) {
-        ATH_MSG_WARNING("Can't find FIRST_ETA. Set it to 0.");
-    }
-    Abs_FIRST_ETA = std::abs(Abs_FIRST_ETA);
-    availableVariables.insert(std::make_pair("Pi0Cluster_Abs_FIRST_ETA", Abs_FIRST_ETA));
-
-    float SECOND_R = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_R, SECOND_R) == false) {
-        ATH_MSG_WARNING("Can't find SECOND_R. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_SECOND_R", SECOND_R));
-
-    float Abs_DELTA_THETA = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_DELTA_THETA, Abs_DELTA_THETA) == false) {
-        ATH_MSG_WARNING("Can't find DELTA_THETA. Set it to 0.");
-    }
-    Abs_DELTA_THETA = std::abs(Abs_DELTA_THETA);
-    availableVariables.insert(std::make_pair("Pi0Cluster_Abs_DELTA_THETA", Abs_DELTA_THETA));
-
-    float CENTER_LAMBDA_helped = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_CENTER_LAMBDA, CENTER_LAMBDA_helped) == false) {
-        ATH_MSG_WARNING("Can't find CENTER_LAMBDA. Set it to 0.");
-    }
-    CENTER_LAMBDA_helped = fmin(CENTER_LAMBDA_helped, 1000.);
-    availableVariables.insert(std::make_pair("Pi0Cluster_CENTER_LAMBDA_helped", CENTER_LAMBDA_helped));
-    
-    float LONGITUDINAL = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_LONGITUDINAL, LONGITUDINAL) == false) {
-        ATH_MSG_WARNING("Can't find LONGITUDINAL. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_LONGITUDINAL", LONGITUDINAL));
-
-    float ENG_FRAC_EM = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_EM, ENG_FRAC_EM) == false) {
-        ATH_MSG_WARNING("Can't find ENG_FRAC_EM. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_ENG_FRAC_EM", ENG_FRAC_EM));
-
-    float ENG_FRAC_CORE = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_CORE, ENG_FRAC_CORE) == false) { 
-        ATH_MSG_WARNING("Can't find ENG_FRAC_CORE. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_ENG_FRAC_CORE", ENG_FRAC_CORE));
-
-    float log_SECOND_ENG_DENS = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_ENG_DENS, log_SECOND_ENG_DENS) == false) { 
-        ATH_MSG_WARNING("Can't find SECOND_ENG_DENS. Set it to 0.");
-    }
-    if(log_SECOND_ENG_DENS==0.) {
-        log_SECOND_ENG_DENS=-50.;
-    }
-    else {
-        log_SECOND_ENG_DENS = log(log_SECOND_ENG_DENS);
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_log_SECOND_ENG_DENS", log_SECOND_ENG_DENS));
-
-    float EcoreOverEEM1 = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_EM1CoreFrac, EcoreOverEEM1) == false) { 
-        ATH_MSG_WARNING("Can't find EM1CoreFrac. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_EcoreOverEEM1", EcoreOverEEM1));
-    
-    int NPosECells_EM1 = 0;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM1, NPosECells_EM1) == false) { 
-        ATH_MSG_WARNING("Can't find NPosECells_EM1. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_NPosECells_EM1", static_cast<float>(NPosECells_EM1)));
-
-    int NPosECells_EM2 = 0;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM2, NPosECells_EM2) == false) { 
-        ATH_MSG_WARNING("Can't find NPosECells_EM2. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_NPosECells_EM2", static_cast<float>(NPosECells_EM2)));
-    
-    float AbsFirstEtaWRTClusterPosition_EM1 = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM1, AbsFirstEtaWRTClusterPosition_EM1) == false) { 
-        ATH_MSG_WARNING("Can't find firstEtaWRTClusterPosition_EM1. Set it to 0.");
-    }
-    AbsFirstEtaWRTClusterPosition_EM1 = std::abs(AbsFirstEtaWRTClusterPosition_EM1);
-    availableVariables.insert(std::make_pair("Pi0Cluster_AbsFirstEtaWRTClusterPosition_EM1", AbsFirstEtaWRTClusterPosition_EM1));
-
-    float secondEtaWRTClusterPosition_EM2 = 0.;
-    if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM2, secondEtaWRTClusterPosition_EM2) == false) { 
-        ATH_MSG_WARNING("Can't find secondEtaWRTClusterPosition_EM2. Set it to 0.");
-    }
-    availableVariables.insert(std::make_pair("Pi0Cluster_secondEtaWRTClusterPosition_EM2", secondEtaWRTClusterPosition_EM2)); 
-
-    // Calculate BDT score, will be -999 when availableVariables lack variables
-    float score = m_mvaBDT->getGradBoostMVA(availableVariables);
-
-    return score;
+
+
+float TauPi0ScoreCalculator::calculateScore(const xAOD::PFO* neutralPFO) const {
+  
+  std::map<TString, float> availableVariables;
+  
+  float Abs_FIRST_ETA = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_FIRST_ETA, Abs_FIRST_ETA) == false) {
+    ATH_MSG_WARNING("Can't find FIRST_ETA. Set it to 0.");
+  }
+  Abs_FIRST_ETA = std::abs(Abs_FIRST_ETA);
+  availableVariables.insert(std::make_pair("Pi0Cluster_Abs_FIRST_ETA", Abs_FIRST_ETA));
+
+  float SECOND_R = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_R, SECOND_R) == false) {
+    ATH_MSG_WARNING("Can't find SECOND_R. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_SECOND_R", SECOND_R));
+
+  float Abs_DELTA_THETA = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_DELTA_THETA, Abs_DELTA_THETA) == false) {
+    ATH_MSG_WARNING("Can't find DELTA_THETA. Set it to 0.");
+  }
+  Abs_DELTA_THETA = std::abs(Abs_DELTA_THETA);
+  availableVariables.insert(std::make_pair("Pi0Cluster_Abs_DELTA_THETA", Abs_DELTA_THETA));
+
+  float CENTER_LAMBDA_helped = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_CENTER_LAMBDA, CENTER_LAMBDA_helped) == false) {
+    ATH_MSG_WARNING("Can't find CENTER_LAMBDA. Set it to 0.");
+  }
+  CENTER_LAMBDA_helped = fmin(CENTER_LAMBDA_helped, 1000.);
+  availableVariables.insert(std::make_pair("Pi0Cluster_CENTER_LAMBDA_helped", CENTER_LAMBDA_helped));
+  
+  float LONGITUDINAL = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_LONGITUDINAL, LONGITUDINAL) == false) {
+    ATH_MSG_WARNING("Can't find LONGITUDINAL. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_LONGITUDINAL", LONGITUDINAL));
+
+  float ENG_FRAC_EM = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_EM, ENG_FRAC_EM) == false) {
+    ATH_MSG_WARNING("Can't find ENG_FRAC_EM. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_ENG_FRAC_EM", ENG_FRAC_EM));
+
+  float ENG_FRAC_CORE = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_CORE, ENG_FRAC_CORE) == false) { 
+    ATH_MSG_WARNING("Can't find ENG_FRAC_CORE. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_ENG_FRAC_CORE", ENG_FRAC_CORE));
+
+  float log_SECOND_ENG_DENS = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_ENG_DENS, log_SECOND_ENG_DENS) == false) { 
+    ATH_MSG_WARNING("Can't find SECOND_ENG_DENS. Set it to 0.");
+  }
+  if(log_SECOND_ENG_DENS==0.) {
+    log_SECOND_ENG_DENS=-50.;
+  }
+  else {
+    log_SECOND_ENG_DENS = log(log_SECOND_ENG_DENS);
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_log_SECOND_ENG_DENS", log_SECOND_ENG_DENS));
+
+  float EcoreOverEEM1 = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_EM1CoreFrac, EcoreOverEEM1) == false) { 
+    ATH_MSG_WARNING("Can't find EM1CoreFrac. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_EcoreOverEEM1", EcoreOverEEM1));
+  
+  int NPosECells_EM1 = 0;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM1, NPosECells_EM1) == false) { 
+    ATH_MSG_WARNING("Can't find NPosECells_EM1. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_NPosECells_EM1", static_cast<float>(NPosECells_EM1)));
+
+  int NPosECells_EM2 = 0;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM2, NPosECells_EM2) == false) { 
+    ATH_MSG_WARNING("Can't find NPosECells_EM2. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_NPosECells_EM2", static_cast<float>(NPosECells_EM2)));
+  
+  float AbsFirstEtaWRTClusterPosition_EM1 = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM1, AbsFirstEtaWRTClusterPosition_EM1) == false) { 
+    ATH_MSG_WARNING("Can't find firstEtaWRTClusterPosition_EM1. Set it to 0.");
+  }
+  AbsFirstEtaWRTClusterPosition_EM1 = std::abs(AbsFirstEtaWRTClusterPosition_EM1);
+  availableVariables.insert(std::make_pair("Pi0Cluster_AbsFirstEtaWRTClusterPosition_EM1", AbsFirstEtaWRTClusterPosition_EM1));
+
+  float secondEtaWRTClusterPosition_EM2 = 0.;
+  if(neutralPFO->attribute(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM2, secondEtaWRTClusterPosition_EM2) == false) { 
+    ATH_MSG_WARNING("Can't find secondEtaWRTClusterPosition_EM2. Set it to 0.");
+  }
+  availableVariables.insert(std::make_pair("Pi0Cluster_secondEtaWRTClusterPosition_EM2", secondEtaWRTClusterPosition_EM2)); 
+
+  // Calculate BDT score, will be -999 when availableVariables lack variables
+  float score = m_mvaBDT->getGradBoostMVA(availableVariables);
+
+  return score;
 }
diff --git a/Reconstruction/tauRecTools/Root/TauPi0Selector.cxx b/Reconstruction/tauRecTools/Root/TauPi0Selector.cxx
index 6c80984f9de6337c9e235fa280909587a2196c83..592e021630fc7efbb033204a0cdcb6a724fa04c8 100644
--- a/Reconstruction/tauRecTools/Root/TauPi0Selector.cxx
+++ b/Reconstruction/tauRecTools/Root/TauPi0Selector.cxx
@@ -2,149 +2,120 @@
   Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-//-----------------------------------------------------------------------------
-// file:        TauPi0Selector.cxx
-// package:     Reconstruction/tauRec
-// authors:     Benedict Winter, Will Davey
-// date:        2012-10-09
-//-----------------------------------------------------------------------------
-
 #include "tauRecTools/TauPi0Selector.h"
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
 
-TauPi0Selector::TauPi0Selector(const std::string& name) :
-    TauRecToolBase(name)
-{
-    declareProperty("ClusterEtCut",             m_clusterEtCut);
-    declareProperty("ClusterBDTCut_1prong",     m_clusterBDTCut_1prong);
-    declareProperty("ClusterBDTCut_mprong",     m_clusterBDTCut_mprong);
+
+TauPi0Selector::TauPi0Selector(const std::string& name) : 
+    TauRecToolBase(name) {
+  declareProperty("ClusterEtCut", m_clusterEtCut);
+  declareProperty("ClusterBDTCut_1prong", m_clusterBDTCut_1prong);
+  declareProperty("ClusterBDTCut_mprong", m_clusterBDTCut_mprong);
 }
 
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
 
-TauPi0Selector::~TauPi0Selector() 
-{
-}
 
-StatusCode TauPi0Selector::executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const
-{
-    // decay mode enum
-    auto kDecayModeProto = xAOD::TauJetParameters::PanTau_DecayModeProto;
-    // Clear vector of cell-based pi0 PFO Links. Required when rerunning on xAOD level.
-    pTau.clearProtoPi0PFOLinks();
-
-    //---------------------------------------------------------------------
-    // only run on 1-5 prong taus 
-    //---------------------------------------------------------------------
-    if (pTau.nTracks() == 0 || pTau.nTracks() >5 ) {
-        // Set proto decay mode to "not set". Will be overwritten for taus with 1-5 tracks
-        pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_NotSet);
-        return StatusCode::SUCCESS;
+StatusCode TauPi0Selector::executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const {
+  // Clear vector of cell-based pi0 PFO Links. Required when rerunning on xAOD level.
+  pTau.clearProtoPi0PFOLinks();
+  
+  // Decay mode enum
+  auto kDecayModeProto = xAOD::TauJetParameters::PanTau_DecayModeProto;
+
+  // 0, >=5 prong taus will have Mode_NotSet 
+  if (pTau.nTracks() == 0 || pTau.nTracks() >5 ) {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_NotSet);
+      return StatusCode::SUCCESS;
+  }
+
+  // 1-5 prong taus have Mode_Other by default
+  // 1, 3 prong taus will be over-written
+  pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_Other);
+
+  // Apply selection to the pi0, and count the number
+  int nRecoPi0s=0;
+  for (xAOD::PFO* neutralPFO : neutralPFOContainer) {
+    // Set number of pi0s to 0 for all neutral PFOs. Required when rerunning on xAOD level
+    neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 0);
+
+    // Only consider PFOs within 0.2 cone of the tau axis
+    if (pTau.p4().DeltaR(neutralPFO->p4()) > 0.2) continue;
+    
+    int etaBin = getEtaBin( neutralPFO->cluster(0)->eta() );
+    
+    // Apply Et cut
+    if (neutralPFO->p4().Et() < m_clusterEtCut.at(etaBin)) continue;
+    
+    // Apply BDT score cut
+    double BDTScore = neutralPFO->bdtPi0Score();
+    if ((pTau.nTracks() == 1 && BDTScore < m_clusterBDTCut_1prong.at(etaBin)) || 
+        (pTau.nTracks() > 1 && BDTScore < m_clusterBDTCut_mprong.at(etaBin))) continue;
+
+    int nHitsInEM1 = 0;
+    if (!neutralPFO->attribute(xAOD::PFODetails::cellBased_NHitsInEM1, nHitsInEM1)) { 
+      ATH_MSG_WARNING("Couldn't retrieve nHitsInEM1. Will set it to 0.");
     }
 
-    // Set proto decay mode to "other". Will be overwritten for taus with 1 or 3 tracks
-    pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_Other);
-
-    //---------------------------------------------------------------------
-    // retrieve neutral PFOs from tau. Apply selection and create links to
-    // Pi0NeutralPFOs 
-    //---------------------------------------------------------------------
-    int nRecoPi0s=0;
-    for( auto neutralPFO : neutralPFOContainer )
-    {
-        // Set number of pi0s to 0 for all neutral PFOs. Required when rerunning on xAOD level
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 0);
-
-        // Get eta bin
-        int etaBin = getPi0Cluster_etaBin( neutralPFO->cluster(0)->eta() );
-
-        // Preselection
-        if(neutralPFO->p4().Et() < m_clusterEtCut.at(etaBin)) continue;
-        if(pTau.p4().DeltaR(neutralPFO->p4()) > 0.2) continue; // TODO: Replace by shrinking cone?
-
-        // BDT Selection
-        float BDTScore = neutralPFO->bdtPi0Score();
-        ATH_MSG_DEBUG("etaBin = " << etaBin 
-                   << ", m_clusterEtCut.at(etaBin) = " <<m_clusterEtCut.at(etaBin) 
-                   << ", m_clusterBDTCut_1prong.at(etaBin) = " << m_clusterBDTCut_1prong.at(etaBin) 
-                   << ", m_clusterBDTCut_mprong.at(etaBin) = " << m_clusterBDTCut_mprong.at(etaBin));
-        if( (pTau.nTracks()==1 && BDTScore < m_clusterBDTCut_1prong.at(etaBin)) 
-                || (pTau.nTracks()>1 && BDTScore < m_clusterBDTCut_mprong.at(etaBin)) ) continue;
-
-        // Set number of pi0s
-        int nHitsInEM1 = 0;
-        if(!neutralPFO->attribute(xAOD::PFODetails::cellBased_NHitsInEM1, nHitsInEM1)) 
-            ATH_MSG_WARNING("Couldn't retrieve nHitsInEM1. Will set it to 0.");
-        if(nHitsInEM1<3){ 
-            neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 1);
-            nRecoPi0s++;
-        }   
-        else{ 
-            neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 2);
-            nRecoPi0s+=2;
-        }
-
-        // Set element link to Pi0tagged PFO
-        pTau.addProtoPi0PFOLink(ElementLink< xAOD::PFOContainer > (neutralPFO, neutralPFOContainer));
+    // nHitsInEM1 < 3 --- one pi0; nHitsInEM1 >= 3 --- two pi0s
+    // FIXME: what about nHitsInEM1 == 0 ?
+    if (nHitsInEM1 < 3) { 
+      neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 1);
+      ++nRecoPi0s;
+    }   
+    else {
+      neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, 2);
+      nRecoPi0s += 2;
     }
 
-    // Set Proto Decay Mode
-    if(pTau.nTracks()==1){
-      if(nRecoPi0s==0)      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1p0n);
-      else if(nRecoPi0s==1) pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1p1n);
-      else                  pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1pXn);
+    pTau.addProtoPi0PFOLink(ElementLink< xAOD::PFOContainer > (neutralPFO, neutralPFOContainer));
+  }
+
+  // Set Proto Decay Mode based on the number charged tracks and pi0s
+  if (pTau.nTracks()==1) {
+    if (nRecoPi0s==0) {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1p0n);
     }
-    if(pTau.nTracks()==3){
-      if(nRecoPi0s==0)      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_3p0n);
-      else                  pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_3pXn);
+    else if (nRecoPi0s==1) {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1p1n);
     }
-    
-    return StatusCode::SUCCESS;
+    else {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_1pXn);
+    }
+  }
+  else if (pTau.nTracks()==3) {
+    if (nRecoPi0s==0) {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_3p0n);
+    }
+    else {
+      pTau.setPanTauDetail(kDecayModeProto, xAOD::TauJetParameters::DecayMode::Mode_3pXn);
+    }
+  }
+  
+  return StatusCode::SUCCESS;
 }
 
-int TauPi0Selector::getPi0Cluster_etaBin(double Pi0Cluster_eta) const {
-    int Pi0Cluster_etaBin = -1;
-    double Pi0Cluster_noCorr_ABSeta = std::abs(Pi0Cluster_eta);
 
-    if( Pi0Cluster_noCorr_ABSeta < 0.80 ) Pi0Cluster_etaBin = 0;
-    else if( Pi0Cluster_noCorr_ABSeta < 1.40 ) Pi0Cluster_etaBin = 1;
-    else if( Pi0Cluster_noCorr_ABSeta < 1.50 ) Pi0Cluster_etaBin = 2;
-    else if( Pi0Cluster_noCorr_ABSeta < 1.90 ) Pi0Cluster_etaBin = 3;
-    else Pi0Cluster_etaBin = 4;
-    return Pi0Cluster_etaBin;
-}
 
-TLorentzVector TauPi0Selector::getP4(const xAOD::TauJet& pTau) const
-{
-    TLorentzVector p4(0.,0.,0.,0.);
-    // Add charged PFOs 
-    for( auto chargedPFOLink : pTau.protoChargedPFOLinks() ){
-        if( not chargedPFOLink.isValid() ){
-            ATH_MSG_WARNING("Invalid protoChargedPFOLink");
-            continue;
-        }
-        p4+=(*chargedPFOLink)->p4();
-    }
-    // Add pi0 PFOs
-    for( auto pi0PFOLink : pTau.protoPi0PFOLinks() )
-    {
-        if( not pi0PFOLink.isValid() ){
-            ATH_MSG_WARNING("Invalid protoPi0PFOLink");
-            continue;
-        }
-        const xAOD::PFO* pi0PFO = (*pi0PFOLink);
-        // assign neutral pion mass
-        double mass = 134.9766;
-        double p  = std::sqrt(std::pow(pi0PFO->e(),2) - std::pow(mass,2));
-        double pt = p/std::cosh(pi0PFO->eta());
-        TLorentzVector pi0_corrP4;
-        pi0_corrP4.SetPtEtaPhiM(pt,pi0PFO->eta(),pi0PFO->phi(),mass);
-        p4+=pi0_corrP4;
-    }
-    return p4;
+int TauPi0Selector::getEtaBin(double eta) const {
+  int etaBin = -1;
+  
+  double absEta = std::abs(eta);
+
+  if (absEta < 0.80) {
+    etaBin = 0;
+  }
+  else if (absEta < 1.40) {
+    etaBin = 1;
+  }
+  else if (absEta < 1.50) {
+    etaBin = 2;
+  }
+  else if (absEta < 1.90) {
+    etaBin = 3;
+  }
+  else {
+    etaBin = 4;
+  }
+
+  return etaBin;
 }
diff --git a/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.cxx b/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.cxx
index 2dc44c96932cf4933f60dfc76eb1cd64c2843433..241dc39b8b00e66d38daab8109dd5a9c8517a783 100644
--- a/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.cxx
+++ b/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.cxx
@@ -3,35 +3,20 @@
 */
 
 #ifndef XAOD_ANALYSIS
-//-----------------------------------------------------------------------------
-// file:        TauPi0ClusterCreator.cxx
-// package:     Reconstruction/tauEvent
-// authors:     Benedict Winter, Will Davey, Stephanie Yuen
-// date:        2012-10-09
-//-----------------------------------------------------------------------------
+
+#include "TauPi0ClusterCreator.h"
+#include "tauRecTools/HelperFunctions.h"
 
 #include "CaloUtils/CaloClusterStoreHelper.h"
 #include "FourMomUtils/P4Helpers.h"
 #include "xAODJet/Jet.h"
 
-#include "TauPi0ClusterCreator.h"
-#include "tauRecTools/HelperFunctions.h"
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
 
 TauPi0ClusterCreator::TauPi0ClusterCreator(const std::string& name) :
     TauRecToolBase(name) {
 }
 
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
-
-TauPi0ClusterCreator::~TauPi0ClusterCreator() 
-{
-}
 
 
 StatusCode TauPi0ClusterCreator::initialize() {
@@ -39,454 +24,463 @@ StatusCode TauPi0ClusterCreator::initialize() {
   return StatusCode::SUCCESS;
 }
 
-//______________________________________________________________________________
-StatusCode TauPi0ClusterCreator::executePi0ClusterCreator(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer,
-							  xAOD::PFOContainer& hadronicClusterPFOContainer,
-							  const xAOD::CaloClusterContainer& pi0ClusterContainer) const
-{
-    // Any tau needs to have PFO vectors. Set empty vectors before nTrack cut
-    std::vector<ElementLink<xAOD::PFOContainer> > empty;
-    pTau.setProtoChargedPFOLinks(empty);
-    pTau.setProtoNeutralPFOLinks(empty);
-    pTau.setProtoPi0PFOLinks(empty);
-    pTau.setHadronicPFOLinks(empty);
-
-    // only run shower subtraction on 1-5 prong taus 
-    if (pTau.nTracks() == 0 || pTau.nTracks() >5) {
-        return StatusCode::SUCCESS;
+
+
+StatusCode TauPi0ClusterCreator::executePi0ClusterCreator(xAOD::TauJet& tau, xAOD::PFOContainer& neutralPFOContainer,
+							  xAOD::PFOContainer& hadronicPFOContainer,
+							  const xAOD::CaloClusterContainer& pi0ClusterContainer) const {
+  // Any tau needs to have PFO vectors. Set empty vectors before nTrack cut
+  std::vector<ElementLink<xAOD::PFOContainer>> empty;
+  tau.setProtoNeutralPFOLinks(empty);
+  tau.setHadronicPFOLinks(empty);
+
+  // only run shower subtraction on 1-5 prong taus 
+  if (tau.nTracks() == 0 || tau.nTracks() > 5) {
+    return StatusCode::SUCCESS;
+  }
+
+  // Retrieve Ecal1 shots and match them to clusters
+  std::vector<const xAOD::PFO*> shotPFOs;
+  
+  unsigned nShots = tau.nShotPFOs();
+  for (unsigned index=0; index<nShots; ++index) {
+    const xAOD::PFO* shotPFO = tau.shotPFO(index);
+    shotPFOs.push_back(shotPFO);
+  }
+  
+  // Map shot to the pi0 cluster 
+  std::map<unsigned, const xAOD::CaloCluster*> shotToClusterMap = getShotToClusterMap(shotPFOs, pi0ClusterContainer, tau);
+
+  // FIXME: These clusters are custom ones, so could be corrected using tau vertex directly
+  if (! tau.jetLink().isValid()) {
+    ATH_MSG_ERROR("Tau jet link is invalid.");
+    return StatusCode::FAILURE;
+  }
+  const xAOD::Jet *jetSeed = tau.jet();
+  const xAOD::Vertex* jetVertex = m_tauVertexCorrection->getJetVertex(*jetSeed);
+  const xAOD::Vertex* tauVertex = nullptr;
+  if (tau.vertexLink().isValid()) tauVertex = tau.vertex();
+  TLorentzVector tauAxis = m_tauVertexCorrection->getTauAxis(tau);
+
+  // Loop over clusters, and create neutral PFOs
+  for (const xAOD::CaloCluster* cluster: pi0ClusterContainer) {
+    TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
+    
+    // Clusters must have enough energy, and within 0.4 cone of the tau candidate
+    if (clusterP4.Pt() < m_clusterEtCut)   continue;
+    if (clusterP4.DeltaR(tauAxis) > 0.4) continue;
+
+    // Create the neutral PFOs
+    xAOD::PFO* neutralPFO = new xAOD::PFO();
+    neutralPFOContainer.push_back(neutralPFO);
+    
+    // Add the link to the tau candidate 
+    ElementLink<xAOD::PFOContainer> PFOElementLink;
+    PFOElementLink.toContainedElement(neutralPFOContainer, neutralPFO);
+    tau.addProtoNeutralPFOLink(PFOElementLink);
+
+    ATH_CHECK(configureNeutralPFO(*cluster, pi0ClusterContainer, tau, shotPFOs, shotToClusterMap, *neutralPFO));
+  }
+
+  // Loop over clusters, and create hadronic PFOs
+  std::vector<const xAOD::CaloCluster*> clusterList;
+  ATH_CHECK(tauRecTools::GetJetClusterList(jetSeed, clusterList, m_useSubtractedCluster));
+  for (const xAOD::CaloCluster* cluster: clusterList) {
+    TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
+       
+    // Clusters must have positive energy, and within 0.2 cone of the tau candidate 
+    if(clusterP4.E()<=0.) continue;
+    if(clusterP4.DeltaR(tauAxis) > 0.2) continue;
+
+    double clusterEnergyHad = 0.;
+    const CaloClusterCellLink* cellLinks = cluster->getCellLinks();
+    CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+	for (; cellLink != cellLinks->end(); ++cellLink) {
+	  const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
+       
+      int sampling = cell->caloDDE()->getSampling();
+      if (sampling < 8) continue;
+
+      double cellEnergy = cell->e() * cellLink.weight();
+      clusterEnergyHad += cellEnergy;
     }
-    ATH_MSG_DEBUG("ClusterCreator: new tau. \tpt = " << pTau.pt() << "\teta = " << pTau.eta() << "\tphi = " << pTau.phi() << "\tnprongs = " << pTau.nTracks());
-
-    // Retrieve Ecal1 shots and match them to clusters
-    std::vector<const xAOD::PFO*> shotVector;
-    unsigned nShots = pTau.nShotPFOs();
-    for(unsigned iShot=0;iShot<nShots;++iShot){
-        const xAOD::PFO* thisShot = pTau.shotPFO(iShot);
-        shotVector.push_back( thisShot );
+    
+    // Energy in Had Calorimeter must be positive
+    if(clusterEnergyHad <= 0.) continue;
+  
+    // Create the hadrnic PFO
+    xAOD::PFO* hadronicPFO = new xAOD::PFO();
+    hadronicPFOContainer.push_back(hadronicPFO);
+    
+    // Add element link from tau to hadronic PFO
+    ElementLink<xAOD::PFOContainer> PFOElementLink;
+    PFOElementLink.toContainedElement( hadronicPFOContainer, hadronicPFO );
+    tau.addHadronicPFOLink( PFOElementLink );
+    
+    ATH_CHECK(configureHadronicPFO(*cluster, clusterEnergyHad, *hadronicPFO));
+  }
+
+  return StatusCode::SUCCESS;
+}
+
+
+
+std::map<unsigned, const xAOD::CaloCluster*> TauPi0ClusterCreator::getShotToClusterMap(const std::vector<const xAOD::PFO*>& shotPFOs,
+										 const xAOD::CaloClusterContainer& pi0ClusterContainer,
+										 const xAOD::TauJet &tau) const {
+  std::map<unsigned, const xAOD::CaloCluster*> shotToClusterMap;
+  for (unsigned index = 0; index < shotPFOs.size(); ++index) {
+    const xAOD::PFO* shotPFO = shotPFOs.at(index);
+
+    int seedHashInt = -1;
+    if (!shotPFO->attribute(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHashInt)) {
+      ATH_MSG_WARNING("Couldn't find seed hash. Set it to -1, no cluster will be associated to shot.");
     }
-    std::map<unsigned, xAOD::CaloCluster*> clusterToShotMap = getClusterToShotMap(shotVector, pi0ClusterContainer, pTau);
- 
-    if (! pTau.jetLink().isValid()) {
+    const IdentifierHash seedHash = static_cast<const IdentifierHash>(seedHashInt);
+
+    const xAOD::Jet *jetSeed = tau.jet();
+    if (!jetSeed) {
       ATH_MSG_ERROR("Tau jet link is invalid.");
-      return StatusCode::FAILURE;
+      return shotToClusterMap;
     }
-    const xAOD::Jet *jetSeed = pTau.jet();
-    
     const xAOD::Vertex* jetVertex = m_tauVertexCorrection->getJetVertex(*jetSeed);
-    
+  
     const xAOD::Vertex* tauVertex = nullptr;
-    if (pTau.vertexLink().isValid()) tauVertex = pTau.vertex();
+    if (tau.vertexLink().isValid()) tauVertex = tau.vertex();
     
-    TLorentzVector tauAxis = m_tauVertexCorrection->getTauAxis(pTau);
+    TLorentzVector tauAxis = m_tauVertexCorrection->getTauAxis(tau);
 
-    for (const xAOD::CaloCluster* cluster: pi0ClusterContainer){
-        TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
+    float weightInCluster = -1.;
+    float weightInPreviousCluster = -1;
+    
+    for (const xAOD::CaloCluster* cluster : pi0ClusterContainer) {
+      // FIXME: cluster here is not corrected
+      TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
+      
+      weightInCluster = -1.;
+      if (clusterP4.Et() < m_clusterEtCut) continue;
+      if (clusterP4.DeltaR(tauAxis) > 0.4)  continue;
         
-        // selection
-        if (clusterP4.Pt() < m_clusterEtCut)   continue;
-        // Cluster container has clusters for all taus.
-        // Only run on clusters that belong to this tau
-        if (clusterP4.DeltaR(tauAxis) > 0.4) continue;
-
-        // Get shots in this cluster. Need to use (CaloCluster*) (*clusterItr) 
-        // (not a copy!) since the pointer will otherwise be different than in clusterToShotMap
-        std::vector<unsigned> shotsInCluster = getShotsMatchedToCluster( shotVector, clusterToShotMap, cluster);
-
-        // Calculate input variables for fake supression. 
-        // Do this before applying the vertex correction, 
-        // since the position of the cluster in the 
-        // calorimeter is required.
-        float EM1CoreFrac = getEM1CoreFrac(cluster);
-        int NHitsInEM1 = getNPhotons(shotVector, shotsInCluster);
-	std::vector<int> NPosECellsInLayer = getNPosECells(cluster);
-	std::vector<float> firstEtaWRTClusterPositionInLayer = get1stEtaMomWRTCluster(cluster);
-	std::vector<float> secondEtaWRTClusterPositionInLayer = get2ndEtaMomWRTCluster(cluster);
-
-        // Retrieve cluster moments that are used for fake supression and that are not stored in AOD
-        // for every cluster. Do this after applying the vertex correction, since the moments 
-        // (especcially DELTA_PHI and DELTA_THETA) must be calculated WRT the tau vertex
-        double CENTER_MAG = 0.0;
-        double FIRST_ETA = 0.0;
-        double SECOND_R = 0.0;
-        double SECOND_LAMBDA = 0.0;
-        double DELTA_PHI = 0.0;
-        double DELTA_THETA = 0.0;
-        double CENTER_LAMBDA = 0.0;
-        double LATERAL = 0.0;
-        double LONGITUDINAL = 0.0;
-        double ENG_FRAC_EM = 0.0;
-        double ENG_FRAC_MAX = 0.0;
-        double ENG_FRAC_CORE = 0.0;
-        double SECOND_ENG_DENS = 0.0;
-
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::CENTER_MAG, CENTER_MAG) ) ATH_MSG_WARNING("Couldn't retrieve CENTER_MAG moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::FIRST_ETA, FIRST_ETA) ) ATH_MSG_WARNING("Couldn't retrieve FIRST_ETA moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::SECOND_R, SECOND_R) ) ATH_MSG_WARNING("Couldn't retrieve SECOND_R moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::SECOND_LAMBDA, SECOND_LAMBDA) ) ATH_MSG_WARNING("Couldn't retrieve SECOND_LAMBDA moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::DELTA_PHI, DELTA_PHI) ) ATH_MSG_WARNING("Couldn't retrieve DELTA_PHI moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::DELTA_THETA, DELTA_THETA) ) ATH_MSG_WARNING("Couldn't retrieve DELTA_THETA moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::CENTER_LAMBDA, CENTER_LAMBDA) ) ATH_MSG_WARNING("Couldn't retrieve CENTER_LAMBDA moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::LATERAL, LATERAL) ) ATH_MSG_WARNING("Couldn't retrieve LATERAL moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::LONGITUDINAL, LONGITUDINAL) ) ATH_MSG_WARNING("Couldn't retrieve LONGITUDINAL moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::ENG_FRAC_EM, ENG_FRAC_EM) ) ATH_MSG_WARNING("Couldn't retrieve ENG_FRAC_EM moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::ENG_FRAC_MAX, ENG_FRAC_MAX) ) ATH_MSG_WARNING("Couldn't retrieve ENG_FRAC_MAX moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::ENG_FRAC_CORE, ENG_FRAC_CORE) ) ATH_MSG_WARNING("Couldn't retrieve ENG_FRAC_CORE moment. Set it to 0.");
-        if( !cluster->retrieveMoment(xAOD::CaloCluster::MomentType::SECOND_ENG_DENS, SECOND_ENG_DENS) ) ATH_MSG_WARNING("Couldn't retrieve SECOND_ENG_DENS moment. Set it to 0.");
-
-       	float E_EM1 = cluster->eSample(CaloSampling::EMB1) + cluster->eSample(CaloSampling::EME1);
-	      float E_EM2 = cluster->eSample(CaloSampling::EMB2) + cluster->eSample(CaloSampling::EME2);
+      const CaloClusterCellLink* cellLinks = cluster->getCellLinks();
+      CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+	  for (; cellLink != cellLinks->end(); ++cellLink) {
+        const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
         
-        // create neutral PFO. Set BDTScore to dummy value <-1. The BDT score is calculated within TauPi0Selector.cxx.
-        xAOD::PFO* neutralPFO = new xAOD::PFO();
-        neutralPFOContainer.push_back( neutralPFO );
-
-        // Create element link from tau to neutral PFO
-        ElementLink<xAOD::PFOContainer> PFOElementLink;
-        PFOElementLink.toContainedElement( neutralPFOContainer, neutralPFO );
-        pTau.addProtoNeutralPFOLink( PFOElementLink );
-
-        // Set PFO variables
-        ElementLink<xAOD::CaloClusterContainer> clusElementLink;
-        clusElementLink.toContainedElement( pi0ClusterContainer, cluster );
-        neutralPFO->setClusterLink( clusElementLink );
+        // Check if seed cell is in cluster.
+        if (cell->caloDDE()->calo_hash() != seedHash) continue;
         
-        neutralPFO->setP4( (float) cluster->pt(), (float) cluster->eta(), (float) cluster->phi(), (float) cluster->m());
-        neutralPFO->setBDTPi0Score( (float) -9999. );
-        neutralPFO->setCharge( 0. );
-        neutralPFO->setCenterMag( (float) CENTER_MAG);
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, -1);
-
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_FIRST_ETA,       (float) FIRST_ETA);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_R,        (float) SECOND_R);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_LAMBDA,   (float) SECOND_LAMBDA);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_DELTA_PHI,       (float) DELTA_PHI);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_DELTA_THETA,     (float) DELTA_THETA);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_CENTER_LAMBDA,   (float) CENTER_LAMBDA);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_LATERAL,         (float) LATERAL);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_LONGITUDINAL,    (float) LONGITUDINAL);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_EM,     (float) ENG_FRAC_EM);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_MAX,    (float) ENG_FRAC_MAX);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_ENG_FRAC_CORE,   (float) ENG_FRAC_CORE);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_SECOND_ENG_DENS, (float) SECOND_ENG_DENS);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_energy_EM1,      (float) E_EM1);
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_energy_EM2,      (float) E_EM2);
-
-
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_EM1CoreFrac, EM1CoreFrac);
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NHitsInEM1, NHitsInEM1);
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_PS,  NPosECellsInLayer.at(0));
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM1, NPosECellsInLayer.at(1));
-        neutralPFO->setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM2, NPosECellsInLayer.at(2));
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM1, firstEtaWRTClusterPositionInLayer.at(1));
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM2, firstEtaWRTClusterPositionInLayer.at(2));
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM1, secondEtaWRTClusterPositionInLayer.at(1));
-        neutralPFO->setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM2, secondEtaWRTClusterPositionInLayer.at(2));
-
-        // Store shot element links in neutral PFO
-        std::vector<ElementLink<xAOD::IParticleContainer> > shotlinks;
-        for(unsigned iShot = 0;iShot<shotsInCluster.size();++iShot){
-            ElementLink<xAOD::PFOContainer> shotPFOElementLink = pTau.shotPFOLinks().at(shotsInCluster.at(iShot));
-            ElementLink<xAOD::IParticleContainer> shotElementLink;
-            shotPFOElementLink.toPersistent();
-            shotElementLink.resetWithKeyAndIndex( shotPFOElementLink.persKey(), shotPFOElementLink.persIndex() ); 
-            if (!shotElementLink.isValid()) ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
-            shotlinks.push_back(shotElementLink);
+        weightInCluster = cellLink.weight();
+        // found cell, no need to loop over other cells
+        break;
+      }
+      
+      if (weightInCluster < 0) continue;
+        
+      // Check if cell was already found in a previous cluster
+      if (weightInPreviousCluster < 0) {
+        // Cell not found in a previous cluster. 
+        // Have to check whether cell is shared with other cluster
+        shotToClusterMap[index] = cluster;
+        weightInPreviousCluster = weightInCluster;
+      }
+      else {
+        // Cell has been found in a previous cluster
+        // assign shot to this cluster if it has larger weight for the cell
+        // otherwise the shots keeps assigned to the previous cluster
+        if (weightInCluster > weightInPreviousCluster) {
+            shotToClusterMap[index] = cluster;
         }
-        if(!neutralPFO->setAssociatedParticleLinks( xAOD::PFODetails::TauShot,shotlinks)) 
-            ATH_MSG_WARNING("Couldn't add shot links to neutral PFO!");
+        // FIXME: why break here ? Should loop all the cluster, and find the largest weight
+        break;
+      }
     }
+  }
+  
+  return shotToClusterMap;
+}
 
-    // Create hadronic PFOs, put them in output container and store links to tau
-    if(!setHadronicClusterPFOs(pTau, hadronicClusterPFOContainer)){
-        ATH_MSG_ERROR("Could not set hadronic PFOs");
-        return StatusCode::FAILURE;
-    }
 
-    return StatusCode::SUCCESS;
+
+std::vector<unsigned> TauPi0ClusterCreator::getShotsMatchedToCluster(const std::vector<const xAOD::PFO*>& shotPFOs,
+								                                     const std::map<unsigned, const xAOD::CaloCluster*>& shotToClusterMap, 
+								                                     const xAOD::CaloCluster& pi0Cluster) const {
+  std::vector<unsigned> shotsMatchedToCluster;
+  
+  // Loop over the shots, and select those matched to the cluster
+  for (unsigned index = 0; index < shotPFOs.size(); ++index) {
+    auto iterator = shotToClusterMap.find(index);
+    if (iterator == shotToClusterMap.end()) continue;
+    if (iterator->second != &pi0Cluster) continue;
+    
+    shotsMatchedToCluster.push_back(index);
+  }
+  
+  return shotsMatchedToCluster;
 }
 
-//______________________________________________________________________________
-// Functions used to calculate BDT variables other than those provided by the CaloClusterMomentsMaker
-float TauPi0ClusterCreator::getEM1CoreFrac(const xAOD::CaloCluster* pi0Candidate) const
-{
-    float coreEnergy=0.;
-    float sumEPosCellsEM1=0.;
-
-    const CaloClusterCellLink* theCellLink = pi0Candidate->getCellLinks();
-    CaloClusterCellLink::const_iterator cellInClusterItr  = theCellLink->begin();
-    CaloClusterCellLink::const_iterator cellInClusterItrE = theCellLink->end();
-    for(;cellInClusterItr!=cellInClusterItrE;++cellInClusterItr){
-        CaloCell* cellInCluster = (CaloCell*) *cellInClusterItr;
-        int sampling = cellInCluster->caloDDE()->getSampling();
-        if(sampling!=1 && sampling!=5) continue;
-        float cellE = cellInCluster->e() * cellInClusterItr.weight();
-        if(cellE<=0) continue;
-        sumEPosCellsEM1 += cellE;
-        float cellEtaWRTCluster = cellInCluster->eta()-pi0Candidate->eta();
-        float cellPhiWRTCluster = P4Helpers::deltaPhi(cellInCluster->phi(), pi0Candidate->phi());
-        if(std::abs(cellPhiWRTCluster) > 0.05 || std::abs(cellEtaWRTCluster) > 2 * 0.025/8.) continue;
-        coreEnergy+=cellE;
+
+
+int TauPi0ClusterCreator::getNPhotons(const std::vector<const xAOD::PFO*>& shotPFOs,
+				                      const std::vector<unsigned>& shotsInCluster) const {
+  int totalPhotons = 0;
+  
+  for (unsigned index = 0; index < shotsInCluster.size(); ++index) {
+    int nPhotons = 0;
+    const xAOD::PFO* shotPFO = shotPFOs.at(shotsInCluster.at(index));
+    if (! shotPFO->attribute(xAOD::PFODetails::PFOAttributes::tauShots_nPhotons, nPhotons)) { 
+      ATH_MSG_WARNING("Can't find NHitsInEM1. Set it to 0.");
     }
-    if(sumEPosCellsEM1<=0.) return 0.;
-    return coreEnergy/sumEPosCellsEM1;
+    totalPhotons += nPhotons;
+  }
+  
+  return totalPhotons;
 }
 
-//______________________________________________________________________________
-// Do cluster to shot matching. 
-// A cluster is matched to a shot if the seed cell of the shot is in the cluster
-std::map<unsigned, xAOD::CaloCluster*> TauPi0ClusterCreator::getClusterToShotMap(const std::vector<const xAOD::PFO*>& shotVector,
-										 const xAOD::CaloClusterContainer& pi0ClusterContainer,
-										 const xAOD::TauJet &pTau) const
-{
-    std::map<unsigned, xAOD::CaloCluster*> clusterToShotMap;
-    for(unsigned iShot = 0;iShot<shotVector.size();++iShot){
-        int seedHash_int = -1;
-        if( shotVector.at(iShot)->attribute(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHash_int) == false) {
-            std::cout << "WARNING: Couldn't find seed hash. Set it to -1, no cluster will be associated to shot." << std::endl;
-        }
-        const IdentifierHash seedHash = (const IdentifierHash) seedHash_int; 
-        xAOD::CaloClusterContainer::const_iterator clusterItr   (pi0ClusterContainer.begin()),
-                                                   clusterItrEnd(pi0ClusterContainer.end());
-        float weightInCluster=-1.;
-        float weightInPreviousCluster=-1;
-    
-        const xAOD::Jet *jetSeed = pTau.jet();
-        if (!jetSeed) {
-          ATH_MSG_ERROR("Tau jet link is invalid.");
-          return clusterToShotMap;
-        }
-        const xAOD::Vertex* jetVertex = m_tauVertexCorrection->getJetVertex(*jetSeed);
+
+
+std::vector<int> TauPi0ClusterCreator::getNPosECells(const xAOD::CaloCluster& cluster) const {
+  std::vector<int> nPosECells(3, 0);
+
+  const CaloClusterCellLink* cellLinks = cluster.getCellLinks();
+  CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+  for (; cellLink != cellLinks->end(); ++cellLink) {
+    const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
+    int sampling = cell->caloDDE()->getSampling();
     
-        const xAOD::Vertex* tauVertex = nullptr;
-        if (pTau.vertexLink().isValid()) tauVertex = pTau.vertex();
-      
-        TLorentzVector tauAxis = m_tauVertexCorrection->getTauAxis(pTau);
-
-        for (; clusterItr != clusterItrEnd; ++clusterItr){
-            xAOD::CaloCluster* cluster = (xAOD::CaloCluster*) (*clusterItr);
-            TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
-            
-            weightInCluster=-1.;
-            if (clusterP4.Et() < m_clusterEtCut) continue; // Not interested in clusters that fail the Et cut
-            // Cluster container has clusters for all taus.
-            // Only run on clusters that belong to this tau
-            if (clusterP4.DeltaR(tauAxis) > 0.4)  continue;
-            const CaloClusterCellLink* theCellLink = cluster->getCellLinks();
-            CaloClusterCellLink::const_iterator cellItr  = theCellLink->begin();
-            CaloClusterCellLink::const_iterator cellItrE = theCellLink->end();
-            for(;cellItr!=cellItrE; ++cellItr){
-                CaloCell* cellInCluster = (CaloCell*) *cellItr;
-                // Check if seed cell is in cluster.
-                if(cellInCluster->caloDDE()->calo_hash()!=seedHash) continue;
-                weightInCluster = cellItr.weight();
-                // found cell, no need to loop over other cells
-                break;
-            }
-            if(weightInCluster<0) continue;
-            // Check if cell was already found in a previous cluster
-            if(weightInPreviousCluster<0){
-                // Cell not found in a previous cluster. 
-                // Have to check whether cell is shared with other cluster
-                clusterToShotMap[iShot] = cluster;
-                weightInPreviousCluster = weightInCluster;
-            }
-            else{
-                // Cell has been found in a previous cluster
-                // assign shot to this cluster if it has larger weight for the cell
-                // otherwise the shots keeps assigned to the previous cluster
-                if(weightInCluster>weightInPreviousCluster){
-                    clusterToShotMap[iShot] = cluster;
-                }
-                // No need to loop over other clusters as cells can not be shared by more than two clusters
-                break;
-            }
-        }
+    // layer0: PS, layer1: EM1, layer2: EM2
+    int layer = sampling%4;  
+    if (layer < 3 && cell->e() > 0) {
+      ++nPosECells[layer];
     }
-    return clusterToShotMap;
-}
+  }
 
-//______________________________________________________________________________
-std::vector<unsigned> TauPi0ClusterCreator::getShotsMatchedToCluster(const std::vector<const xAOD::PFO*>& shotVector,
-								     const std::map<unsigned, xAOD::CaloCluster*>& clusterToShotMap, 
-								     const xAOD::CaloCluster* pi0Cluster) const
-{
-    std::vector<unsigned> shotsMatchedToCluster;
-    for(unsigned iShot = 0;iShot<shotVector.size();++iShot){
-        auto itr = clusterToShotMap.find(iShot);
-        if(itr==clusterToShotMap.end()) continue;
-        if(itr->second!=pi0Cluster) continue;
-        shotsMatchedToCluster.push_back(iShot);
-    }
-    return shotsMatchedToCluster;
+  return nPosECells;
 }
 
-//______________________________________________________________________________
-int TauPi0ClusterCreator::getNPhotons(const std::vector<const xAOD::PFO*>& shotVector,
-				      const std::vector<unsigned>& shotsInCluster ) const
-{
-    int nPhotons = 0;
-    for(unsigned iShot = 0;iShot<shotsInCluster.size();++iShot){
-        int curNPhotons=0;
-        if(shotVector.at(shotsInCluster.at(iShot))->attribute(xAOD::PFODetails::PFOAttributes::tauShots_nPhotons,curNPhotons) == false)
-            ATH_MSG_WARNING("Can't find NHitsInEM1. Set it to 0.");
-        nPhotons+=curNPhotons;
-    }
-    return nPhotons;
+
+
+float TauPi0ClusterCreator::getEM1CoreFrac(const xAOD::CaloCluster& cluster) const {
+  float coreEnergyEM1 = 0.;
+  float totalEnergyEM1 = 0.;
+  
+  const CaloClusterCellLink* cellLinks = cluster.getCellLinks();
+  CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+  for (; cellLink != cellLinks->end(); ++cellLink) {
+    const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
+    
+    // Only consider EM1
+    int sampling = cell->caloDDE()->getSampling();
+    if (sampling != 1 && sampling != 5) continue;
+    
+    // Only consider positive cells
+    // FIXME: is the weight needed ?
+    float cellEnergy = cell->e() * cellLink.weight();
+    if (cellEnergy <= 0) continue;
+    
+    totalEnergyEM1 += cellEnergy;
+
+    float deltaEta = cell->eta() - cluster.eta();
+    float deltaPhi = P4Helpers::deltaPhi(cell->phi(), cluster.phi());
+    
+    // Core region: [0.05, 0.05/8]
+    if(std::abs(deltaPhi) > 0.05 || std::abs(deltaEta) > 2 * 0.025/8.) continue;
+    
+    coreEnergyEM1 += cellEnergy;
+  }
+  
+  if (totalEnergyEM1 <= 0.) return 0.;
+  return coreEnergyEM1/totalEnergyEM1;
 }
 
-//______________________________________________________________________________
-std::vector<int> TauPi0ClusterCreator::getNPosECells(const xAOD::CaloCluster* pi0Candidate) const
-{
-    std::vector<int> nPosECellsInLayer(3,0); // 3 layers initialised with 0 +ve cells
-
-    const CaloClusterCellLink* theCellLink = pi0Candidate->getCellLinks();
-    CaloClusterCellLink::const_iterator cellInClusterItr  = theCellLink->begin();
-    CaloClusterCellLink::const_iterator cellInClusterItrE = theCellLink->end();
-
-    for(;cellInClusterItr!=cellInClusterItrE; ++cellInClusterItr){
-        const CaloCell* cellInCluster = static_cast<const CaloCell*>( *cellInClusterItr);
-        int sampling = cellInCluster->caloDDE()->getSampling();
-        // Get cell layer: PSB and PSE belong to layer 0,  
-        // EMB1 and EME1 to layer 1, EMB2 and EME2 to layer 2. 
-        int cellLayer = sampling%4;  
-        if(cellLayer < 3 && cellInCluster->e() > 0) nPosECellsInLayer[cellLayer]++;
+
+
+std::vector<float> TauPi0ClusterCreator::get1stEtaMomWRTCluster(const xAOD::CaloCluster& cluster) const {
+  std::vector<float> deltaEtaFirstMom (3, 0.);
+  std::vector<float> totalEnergy (3, 0.);
+
+  const CaloClusterCellLink* cellLinks = cluster.getCellLinks();
+  CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+  for (; cellLink != cellLinks->end(); ++cellLink) {
+    const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
+    
+    // Only consider PS, EM1, and EM2
+    int sampling = cell->caloDDE()->getSampling();
+    int layer = sampling%4;
+    if (layer >= 3) continue;
+
+    // Only consider positive cells
+    float cellEnergy = cell->e();
+    if (cellEnergy <= 0) continue;
+
+    float deltaEta = cell->eta() - cluster.eta();
+    deltaEtaFirstMom[layer] += deltaEta * cellEnergy;
+    totalEnergy[layer] += cellEnergy;
+  }
+
+  for (int layer=0; layer < 3; ++layer) {
+    if (totalEnergy[layer] != 0.) {
+      deltaEtaFirstMom[layer]/=std::abs(totalEnergy[layer]);
+    }
+    else {
+      deltaEtaFirstMom[layer]=0.;
     }
-    return nPosECellsInLayer;
+  }
+  
+  return deltaEtaFirstMom;
 }
 
-//______________________________________________________________________________
-std::vector<float> TauPi0ClusterCreator::get1stEtaMomWRTCluster(const xAOD::CaloCluster* pi0Candidate) const
-{
-    std::vector<float> firstEtaWRTClusterPositionInLayer (4, 0.);  //init with 0. for 0-3 layers
-    std::vector<float> sumEInLayer (4, 0.); //init with 0. for 0-3 layers
-
-    const CaloClusterCellLink* theCellLink = pi0Candidate->getCellLinks();
-    CaloClusterCellLink::const_iterator cellInClusterItr  = theCellLink->begin();
-    CaloClusterCellLink::const_iterator cellInClusterItrE = theCellLink->end();
-
-    for(;cellInClusterItr!=cellInClusterItrE;++cellInClusterItr){
-        CaloCell* cellInCluster = (CaloCell*) *cellInClusterItr;
-        int sampling = cellInCluster->caloDDE()->getSampling();
-        // Get cell layer: PSB and PSE belong to layer 0,  
-        // EMB1 and EME1 to layer 1, EMB2 and EME2 to layer 2. 
-        int cellLayer = sampling%4;
-        
-        float cellEtaWRTClusterPos=cellInCluster->eta()-pi0Candidate->eta();
-        float cellE=cellInCluster->e();
-        if(cellE<=0  || cellLayer>=3) continue;
-        firstEtaWRTClusterPositionInLayer[cellLayer]+=cellEtaWRTClusterPos*cellE;
-        sumEInLayer[cellLayer]+=cellE;
-    }
 
-    for(int iLayer=0;iLayer<4;++iLayer){
-        if(sumEInLayer[iLayer]!=0) 
-            firstEtaWRTClusterPositionInLayer[iLayer]/=std::abs(sumEInLayer[iLayer]);
-        else firstEtaWRTClusterPositionInLayer[iLayer]=0.;
+
+std::vector<float> TauPi0ClusterCreator::get2ndEtaMomWRTCluster(const xAOD::CaloCluster& cluster) const {
+  std::vector<float> deltaEtaSecondMom (3, 0.);
+  std::vector<float> totalEnergy (3, 0.);
+
+  const CaloClusterCellLink* cellLinks = cluster.getCellLinks();
+  CaloClusterCellLink::const_iterator cellLink = cellLinks->begin();
+  for (; cellLink != cellLinks->end(); ++cellLink) {
+    const CaloCell* cell = static_cast<const CaloCell*>(*cellLink);
+    
+    // Only consider PS, EM1, and EM2
+    int sampling = cell->caloDDE()->getSampling();
+    int layer = sampling%4;
+    if (layer >= 3) continue;
+
+    // Only consider positive cells
+    float cellEnergy=cell->e();
+    if (cellEnergy <= 0) continue;
+
+    float deltaEta = cell->eta() - cluster.eta();
+    deltaEtaSecondMom[layer] += deltaEta * deltaEta * cellEnergy;
+    totalEnergy[layer] += cellEnergy;
+  }
+
+  for (int layer=0; layer < 3; ++layer) {
+    if (totalEnergy[layer] != 0.) {
+      deltaEtaSecondMom[layer]/=std::abs(totalEnergy[layer]);
+    }
+    else {
+      deltaEtaSecondMom[layer]=0.;
     }
-    return firstEtaWRTClusterPositionInLayer;
+  }
+  
+  return deltaEtaSecondMom;
 }
 
-//______________________________________________________________________________
-std::vector<float> TauPi0ClusterCreator::get2ndEtaMomWRTCluster( const xAOD::CaloCluster* pi0Candidate) const
-{
-      std::vector<float> secondEtaWRTClusterPositionInLayer (4, 0.); //init with 0. for 0-3 layers
-      std::vector<float> sumEInLayer (4, 0.); //init with 0. for 0-3 layers
-
-      const CaloClusterCellLink* theCellLinks = pi0Candidate->getCellLinks();
-
-      for(const CaloCell* cellInCluster: *theCellLinks){
-            int sampling = cellInCluster->caloDDE()->getSampling();
-            // Get cell layer: PSB and PSE belong to layer 0,  
-            // EMB1 and EME1 to layer 1, EMB2 and EME2 to layer 2. 
-            int cellLayer = sampling%4;
-
-            float cellEtaWRTClusterPos=cellInCluster->eta()-pi0Candidate->eta();
-            float cellE=cellInCluster->e();
-            if(cellE<=0  || cellLayer>=3) continue;
-            secondEtaWRTClusterPositionInLayer[cellLayer]+=cellEtaWRTClusterPos*cellEtaWRTClusterPos*cellE;
-            sumEInLayer[cellLayer]+=cellE;
-      }
 
-      for(int iLayer=0;iLayer<4;++iLayer){
-            if(sumEInLayer[iLayer]!=0) 
-                secondEtaWRTClusterPositionInLayer[iLayer]/=std::abs(sumEInLayer[iLayer]);
-            else secondEtaWRTClusterPositionInLayer[iLayer]=0.;
-      }
-      return secondEtaWRTClusterPositionInLayer;
-}
 
-//______________________________________________________________________________
-bool TauPi0ClusterCreator::setHadronicClusterPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pHadronPFOContainer) const
-{
-    if (! pTau.jetLink().isValid()) {
-      ATH_MSG_ERROR("Tau jet link is invalid.");
-      return false;
+StatusCode TauPi0ClusterCreator::configureNeutralPFO(const xAOD::CaloCluster& cluster,
+                                                     const xAOD::CaloClusterContainer& pi0ClusterContainer,
+                                                     const xAOD::TauJet& tau,
+                                                     const std::vector<const xAOD::PFO*>& shotPFOs, 
+                                                     const std::map<unsigned, const xAOD::CaloCluster*>& shotToClusterMap,
+                                                     xAOD::PFO& neutralPFO) const {
+  // Set the property of the PFO
+  // -- Four momentum: not corrected yet
+  neutralPFO.setP4(cluster.pt(), cluster.eta(), cluster.phi(), cluster.m());
+  
+  // -- Default value
+  neutralPFO.setBDTPi0Score(-9999.);
+  neutralPFO.setCharge(0);
+  neutralPFO.setAttribute<int>(xAOD::PFODetails::PFOAttributes::nPi0Proto, -1);
+
+  // -- CENTER_MAG
+  double CENTER_MAG = 0.0;
+  if (!cluster.retrieveMoment(xAOD::CaloCluster::MomentType::CENTER_MAG, CENTER_MAG)) {
+    ATH_MSG_WARNING("Couldn't retrieve CENTER_MAG moment. Set it to 0.");
+  }
+  neutralPFO.setCenterMag( (float) CENTER_MAG);
+  
+  // -- Number of photons 
+  std::vector<unsigned> shotsInCluster = getShotsMatchedToCluster(shotPFOs, shotToClusterMap, cluster);
+  int NHitsInEM1 = getNPhotons(shotPFOs, shotsInCluster);
+  neutralPFO.setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NHitsInEM1, NHitsInEM1);
+  
+  // -- Energy at each layer
+  float eEM1 = cluster.eSample(CaloSampling::EMB1) + cluster.eSample(CaloSampling::EME1);
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_energy_EM1, eEM1);
+  
+  float eEM2 = cluster.eSample(CaloSampling::EMB2) + cluster.eSample(CaloSampling::EME2);
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_energy_EM2, eEM2);
+  
+  // -- Number of positive cells in each layer
+  std::vector<int> nPosECells = getNPosECells(cluster);
+  neutralPFO.setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_PS,  nPosECells.at(0));
+  neutralPFO.setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM1, nPosECells.at(1));
+  neutralPFO.setAttribute<int>(xAOD::PFODetails::PFOAttributes::cellBased_NPosECells_EM2, nPosECells.at(2));
+ 
+  // -- Core Fraction of the energy in EM1 
+  float EM1CoreFrac = getEM1CoreFrac(cluster);
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_EM1CoreFrac, EM1CoreFrac);
+
+  // -- First moment of deltaEta(cluster, cell) in EM1 and EM2 
+  std::vector<float> deltaEtaFirstMom = get1stEtaMomWRTCluster(cluster);
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM1, deltaEtaFirstMom.at(1));
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_firstEtaWRTClusterPosition_EM2, deltaEtaFirstMom.at(2));
+  
+  // -- Second moment of deltaEta(cluster, cell) in EM1 and EM2
+  std::vector<float> secondEtaWRTClusterPositionInLayer = get2ndEtaMomWRTCluster(cluster);
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM1, secondEtaWRTClusterPositionInLayer.at(1));
+  neutralPFO.setAttribute<float>(xAOD::PFODetails::PFOAttributes::cellBased_secondEtaWRTClusterPosition_EM2, secondEtaWRTClusterPositionInLayer.at(2));
+
+  // -- Retrieve cluster moments
+  using Moment = xAOD::CaloCluster::MomentType;
+  using Attribute = xAOD::PFODetails::PFOAttributes; 
+  const std::array< std::pair<Moment, Attribute>, 12> momentAttributePairs {{
+      {Moment::FIRST_ETA, Attribute::cellBased_FIRST_ETA},
+      {Moment::SECOND_R, Attribute::cellBased_SECOND_R}, 
+      {Moment::SECOND_LAMBDA, Attribute::cellBased_SECOND_LAMBDA},
+      {Moment::DELTA_PHI, Attribute::cellBased_DELTA_PHI},
+      {Moment::DELTA_THETA, Attribute::cellBased_DELTA_THETA},
+      {Moment::CENTER_LAMBDA, Attribute::cellBased_CENTER_LAMBDA},
+      {Moment::LATERAL, Attribute::cellBased_LATERAL},
+      {Moment::LONGITUDINAL, Attribute::cellBased_LONGITUDINAL},
+      {Moment::ENG_FRAC_EM, Attribute::cellBased_ENG_FRAC_EM},
+      {Moment::ENG_FRAC_MAX, Attribute::cellBased_ENG_FRAC_MAX},
+      {Moment::ENG_FRAC_CORE, Attribute::cellBased_ENG_FRAC_CORE},
+      {Moment::SECOND_ENG_DENS, Attribute::cellBased_SECOND_ENG_DENS}
+  }};
+  
+  for (const auto& [moment, attribute] : momentAttributePairs) {
+    double value = 0.0;
+    if (! cluster.retrieveMoment(moment, value)) {
+      ATH_MSG_WARNING("Cound not retrieve " << moment);
     }
-    const xAOD::Jet *jetSeed = pTau.jet();
-    
-    const xAOD::Vertex* jetVertex = m_tauVertexCorrection->getJetVertex(*jetSeed);
-    
-    const xAOD::Vertex* tauVertex = nullptr;
-    if (pTau.vertexLink().isValid()) tauVertex = pTau.vertex();
-    
-    TLorentzVector tauAxis = m_tauVertexCorrection->getTauAxis(pTau);
-    
-    std::vector<const xAOD::CaloCluster*> clusterList;
-    StatusCode sc = tauRecTools::GetJetClusterList(jetSeed, clusterList, m_useSubtractedCluster);
-    if (!sc) return false;
-
-    for (const xAOD::CaloCluster* cluster : clusterList){
-        // Procedure: 
-        // - Calculate cluster energy in Hcal. This is to treat -ve energy cells correctly
-        // - Then set 4momentum via setP4(E/cosh(eta), eta, phi, m). This forces the PFO to have the correct energy and mass
-        // - Ignore clusters outside 0.2 cone and those with overall negative energy or negative energy in Hcal
-
-        // Don't create PFOs for clusters with overall (Ecal+Hcal) negative energy (noise)
-        TLorentzVector clusterP4 = m_tauVertexCorrection->getVertexCorrectedP4(*cluster, tauVertex, jetVertex);
-        
-        if(clusterP4.E()<=0.) continue;
+    neutralPFO.setAttribute(attribute, static_cast<float>(value));
+  }
 
-        // Only need clusters in core cone. Others are not needed for subtraction
-        if(tauAxis.DeltaR(clusterP4) > 0.2) continue;
+  // -- Element link to the cluster 
+  ElementLink<xAOD::CaloClusterContainer> clusElementLink;
+  clusElementLink.toContainedElement(pi0ClusterContainer, &cluster);
+  neutralPFO.setClusterLink( clusElementLink );
+ 
+  // -- Element link to the shots
+  std::vector<ElementLink<xAOD::IParticleContainer>> shotlinks;
+  for (unsigned index = 0; index < shotsInCluster.size(); ++index) {
+    ElementLink<xAOD::PFOContainer> shotPFOElementLink = tau.shotPFOLinks().at(shotsInCluster.at(index));
+    ElementLink<xAOD::IParticleContainer> shotElementLink;
+    shotPFOElementLink.toPersistent();
+    shotElementLink.resetWithKeyAndIndex(shotPFOElementLink.persKey(), shotPFOElementLink.persIndex()); 
+    if (!shotElementLink.isValid()) {
+      ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
+    }
+    shotlinks.push_back(shotElementLink);
+  }
+  if(!neutralPFO.setAssociatedParticleLinks( xAOD::PFODetails::TauShot,shotlinks)) { 
+    ATH_MSG_WARNING("Couldn't add shot links to neutral PFO!");
+  }
 
-        // Loop over cells to calculate cluster energy in Hcal
-        double clusterE_Hcal=0.;
-	const CaloClusterCellLink* theCellLink = cluster->getCellLinks();
-	CaloClusterCellLink::const_iterator cellInClusterItr  = theCellLink->begin();
-	CaloClusterCellLink::const_iterator cellInClusterItrE = theCellLink->end();
+  return StatusCode::SUCCESS;
+}
 
-	for(; cellInClusterItr != cellInClusterItrE; ++cellInClusterItr){
-	   const CaloCell* cellInCluster = static_cast<const CaloCell*> (*cellInClusterItr);
 
-            //Get only HCAL cells
-            int sampling = cellInCluster->caloDDE()->getSampling();
-            if (sampling < 8) continue;
 
-            double cellE = cellInCluster->e()*cellInClusterItr.weight();
-            clusterE_Hcal+=cellE;
-        }
-        // Don't save PFOs for clusters with negative energy in Hcal 
-        if(clusterE_Hcal<=0.) continue;
-
-        // Create hadronic PFO
-        xAOD::PFO* hadronicPFO = new xAOD::PFO();
-        pHadronPFOContainer.push_back( hadronicPFO );
-
-        // Set 4mom. Eta and phi are taken from cluster
-        double cluster_Pt_Hcal = clusterE_Hcal/std::cosh(cluster->eta());
-        hadronicPFO->setP4( (float) cluster_Pt_Hcal, (float) cluster->eta(), (float) cluster->phi(), (float) 0.);
-
-        // TODO: May want to set element link to the cluster the PFO is originating from
-        // ElementLink<xAOD::CaloClusterContainer> clusElementLink;
-        // clusElementLink.toContainedElement( CLUSTERCONTAINER, cluster );
-        // hadronicPFO->setClusterLink( clusElementLink );
-
-        // Create element link from tau to hadronic PFO
-        ElementLink<xAOD::PFOContainer> PFOElementLink;
-        PFOElementLink.toContainedElement( pHadronPFOContainer, hadronicPFO );
-        pTau.addHadronicPFOLink( PFOElementLink );
-    }
-    return true;
+StatusCode TauPi0ClusterCreator::configureHadronicPFO(const xAOD::CaloCluster& cluster, 
+                                                      double clusterEnergyHad, 
+                                                      xAOD::PFO& hadronicPFO) const {
+  double clusterPtHad = clusterEnergyHad/std::cosh(cluster.eta());
+  hadronicPFO.setP4(clusterPtHad, cluster.eta(), cluster.phi(), 0.);
+
+  return StatusCode::SUCCESS;
 }
 
 #endif
diff --git a/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.h b/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.h
index 4ac1db7f16326dbf39eb13075398e3cfaef5d078..fcb8c415b532cb25f71b4ad9c741b6735de82fcc 100644
--- a/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.h
+++ b/Reconstruction/tauRecTools/src/TauPi0ClusterCreator.h
@@ -27,50 +27,64 @@
  */
 
 class TauPi0ClusterCreator : public TauRecToolBase {
+
 public:
-    TauPi0ClusterCreator(const std::string& name) ;
-    ASG_TOOL_CLASS2(TauPi0ClusterCreator, TauRecToolBase, ITauToolBase);
-    virtual ~TauPi0ClusterCreator();
-
-    virtual StatusCode initialize() override;
-    virtual StatusCode executePi0ClusterCreator(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer, 
-						xAOD::PFOContainer& hadronicClusterPFOContainer,
-						const xAOD::CaloClusterContainer& pi0CaloClusContainer) const override;
-    
+  
+  ASG_TOOL_CLASS2(TauPi0ClusterCreator, TauRecToolBase, ITauToolBase);
+  
+  TauPi0ClusterCreator(const std::string& name) ;
+  virtual ~TauPi0ClusterCreator() = default;
+
+  virtual StatusCode initialize() override;
+  virtual StatusCode executePi0ClusterCreator(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer, 
+  					xAOD::PFOContainer& hadronicClusterPFOContainer,
+  					const xAOD::CaloClusterContainer& pi0CaloClusContainer) const override;
+  
 private:
-    /** @brief fraction of cluster enegry in central EM1 cells */
-    float getEM1CoreFrac( const xAOD::CaloCluster* pi0Candidate) const;
-    
-    /** @brief number of cells from cluster with positive energy in PS, EM1 and EM2 */
-    std::vector<int> getNPosECells( const xAOD::CaloCluster* pi0Candidate) const;
-
-    std::map<unsigned, xAOD::CaloCluster*> getClusterToShotMap(
-        const std::vector<const xAOD::PFO*>& shotVector,
-        const xAOD::CaloClusterContainer& pi0ClusterContainer,
-        const xAOD::TauJet &pTau) const;
-
-    std::vector<unsigned> getShotsMatchedToCluster(
-        const std::vector<const xAOD::PFO*>& shotVector,
-        const std::map<unsigned, xAOD::CaloCluster*>& clusterToShotMap,
-        const xAOD::CaloCluster* pi0Cluster) const;
-
-    int getNPhotons( const std::vector<const xAOD::PFO*>& shotVector,
-                     const std::vector<unsigned>& shotsInCluster) const;
-
-    /** @brief first eta moment in PS, EM1 and EM2 w.r.t cluster eta: (eta_i - eta_cluster) */
-    std::vector<float> get1stEtaMomWRTCluster( const xAOD::CaloCluster* pi0Candidate) const;
-
-    /** @brief second eta moment in PS, EM1 and EM2 w.r.t cluster eta: (eta_i - eta_cluster)^2 */ 
-    std::vector<float> get2ndEtaMomWRTCluster(const xAOD::CaloCluster* pi0Candidate) const;
-
-    /** @brief get hadronic cluster PFOs*/
-    bool setHadronicClusterPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pHadronicClusterContainer) const;
-
-    Gaudi::Property<double> m_clusterEtCut {this, "ClusterEtCut", 0.5 * Gaudi::Units::GeV, "Et threshould for pi0 candidate clusters"};
-    Gaudi::Property<bool> m_useSubtractedCluster {this, "UseSubtractedCluster", true, "use shower subtracted clusters in calo calculations"};
-
-    ToolHandle<ITauVertexCorrection> m_tauVertexCorrection { this, 
-      "TauVertexCorrection", "TauVertexCorrection", "Tool to perform the vertex correction"};
+  
+  /** @brief Configure the neutral PFO*/
+  StatusCode configureNeutralPFO(const xAOD::CaloCluster& cluster,
+                                 const xAOD::CaloClusterContainer& pi0ClusterContainer,
+                                 const xAOD::TauJet& tau,
+                                 const std::vector<const xAOD::PFO*>& shotPFOs,
+                                 const std::map<unsigned, const xAOD::CaloCluster*>& shotsInCluster,
+                                 xAOD::PFO& neutralPFO) const;
+
+  /** @brief Configure the haronic PFO*/
+  StatusCode configureHadronicPFO(const xAOD::CaloCluster& cluster,
+                                  double clusterEnergyHad,
+                                  xAOD::PFO& hadronicPFO) const;
+
+  std::map<unsigned, const xAOD::CaloCluster*> getShotToClusterMap(
+      const std::vector<const xAOD::PFO*>& shotVector,
+      const xAOD::CaloClusterContainer& pi0ClusterContainer,
+      const xAOD::TauJet &pTau) const;
+
+  std::vector<unsigned> getShotsMatchedToCluster(
+      const std::vector<const xAOD::PFO*>& shotVector,
+      const std::map<unsigned, const xAOD::CaloCluster*>& clusterToShotMap,
+      const xAOD::CaloCluster& pi0Cluster) const;
+
+  int getNPhotons( const std::vector<const xAOD::PFO*>& shotVector,
+                   const std::vector<unsigned>& shotsInCluster) const;
+
+  /** @brief fraction of cluster enegry in central EM1 cells */
+  float getEM1CoreFrac(const xAOD::CaloCluster& cluster) const;
+  
+  /** @brief number of cells from cluster with positive energy in PS, EM1 and EM2 */
+  std::vector<int> getNPosECells(const xAOD::CaloCluster& cluster) const;
+
+  /** @brief first eta moment in PS, EM1 and EM2 w.r.t cluster eta */
+  std::vector<float> get1stEtaMomWRTCluster(const xAOD::CaloCluster& cluster) const;
+
+  /** @brief second eta moment in PS, EM1 and EM2 w.r.t cluster eta */ 
+  std::vector<float> get2ndEtaMomWRTCluster(const xAOD::CaloCluster& cluster) const;
+
+  Gaudi::Property<double> m_clusterEtCut {this, "ClusterEtCut", 0.5 * Gaudi::Units::GeV, "Et threshould for pi0 candidate clusters"};
+  Gaudi::Property<bool> m_useSubtractedCluster {this, "UseSubtractedCluster", true, "use shower subtracted clusters in calo calculations"};
+
+  ToolHandle<ITauVertexCorrection> m_tauVertexCorrection { this, 
+    "TauVertexCorrection", "TauVertexCorrection", "Tool to perform the vertex correction"};
 };
 
 #endif	/* TAUPI0CLUSTERCREATOR_H */
diff --git a/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.cxx b/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.cxx
index 45aeb323e2db670626a9ac6cf8ebded2293c96d9..9bd8f013719507e97ad7ee69db98af774cf1b064 100644
--- a/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.cxx
+++ b/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.cxx
@@ -2,323 +2,325 @@
   Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
-//-----------------------------------------------------------------------------
-// file:        TauPi0ClusterScaler.cxx
-// package:     Reconstruction/tauRec
-// authors:     Stephanie Yuen, Benedict Winter, Will Davey
-// date:        2014-08-04
-//-----------------------------------------------------------------------------
-
-#include <vector>
 
 #include "TauPi0ClusterScaler.h"
+
 #include "xAODTau/TauJet.h"
 #include "xAODPFlow/PFO.h"
-#include "tauRecTools/ITauToolBase.h"
-#include "FourMomUtils/xAODP4Helpers.h"
 #include "xAODCaloEvent/CaloVertexedTopoCluster.h"
+#include "FourMomUtils/xAODP4Helpers.h"
+
+#include <vector>
+
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
 
 TauPi0ClusterScaler::TauPi0ClusterScaler(const std::string& name) :
-    TauRecToolBase(name)
-{
+    TauRecToolBase(name) {
 }
 
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
 
-TauPi0ClusterScaler::~TauPi0ClusterScaler()
-{
+
+StatusCode TauPi0ClusterScaler::executePi0ClusterScaler(xAOD::TauJet& tau, 
+                                                        xAOD::PFOContainer& neutralPFOContainer, 
+                                                        xAOD::PFOContainer& chargedPFOContainer) const {
+  // Clear vector of cell-based charged PFO Links, which are required when running xAOD 
+  tau.clearProtoChargedPFOLinks();
+ 
+  // Only run on 1-5 prong taus 
+  if (tau.nTracks() == 0 or tau.nTracks() >5) { 
+    return StatusCode::SUCCESS;
+  }
+ 
+  ATH_MSG_DEBUG("Process a new tau candidate, addreess " << &tau
+                  << ", e: " << tau.pt()
+                  << ", eta: " << tau.eta()
+                  << ", pt: " << tau.pt());
+
+  // Correct neutral PFO kinematics to point at tau vertex, this is needed since the 
+  // charged shower subtraction is performed several times for each neutral PFO
+  correctNeutralPFOs(tau, neutralPFOContainer);
+  
+  // Create new proto charged PFOs
+  createChargedPFOs(tau, chargedPFOContainer);
+  
+  // Associate hadronic PFOs to charged PFOs using extrapolated positions in HCal
+  associateHadronicToChargedPFOs(tau, chargedPFOContainer);
+  
+  // Associate charged PFOs to neutral PFOs using extrapolated positions in ECal
+  associateChargedToNeutralPFOs(tau, neutralPFOContainer);
+  
+  // Estimate charged PFO EM energy and subtract from neutral PFOs
+  subtractChargedEnergyFromNeutralPFOs(neutralPFOContainer);
+
+  for (xAOD::PFO* pfo : neutralPFOContainer) {
+    ATH_MSG_DEBUG("Final Neutral PFO, address " << pfo
+                  << ", e: " << pfo->pt()
+                  << ", eta: " << pfo->eta()
+                  << ", pt: " << pfo->pt());
+  }
+
+  return StatusCode::SUCCESS;
 }
 
-//______________________________________________________________________________
-StatusCode TauPi0ClusterScaler::executePi0ClusterScaler(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer, xAOD::PFOContainer& chargedPFOContainer) const
-{
-    // Clear vector of cell-based charged PFO Links. 
-    // Required when rerunning on xAOD level.
-    pTau.clearProtoChargedPFOLinks();
 
-    // Only run on 1-5 prong taus 
-    if (pTau.nTracks() == 0 or pTau.nTracks() >5 ) 
-        return StatusCode::SUCCESS;
-    
-    ATH_MSG_DEBUG("new tau pt = " << pTau.pt() 
-                  << ", eta = " << pTau.eta() 
-                  << ", phi = " << pTau.phi() 
-                  << ", nprongs = " << pTau.nTracks());
-
-    // reset neutral PFO kinematics (incase re-run on AOD)
-    resetNeutralPFOs(pTau, neutralPFOContainer);
-    // create new proto charged PFOs, extrapolate tracks, add to tau 
-    createChargedPFOs(pTau, chargedPFOContainer);
-    // associate hadronic PFOs to charged PFOs using extrapolated positions in HCal
-    associateHadronicToChargedPFOs(pTau, chargedPFOContainer);
-    // associate charged PFOs to neutral PFOs using extrapolated positions in ECal
-    associateChargedToNeutralPFOs(pTau, neutralPFOContainer);
-    // estimate charged PFO EM energy and subtract from neutral PFOs
-    subtractChargedEnergyFromNeutralPFOs(neutralPFOContainer);
-
-    ATH_MSG_DEBUG("End of TauPi0ClusterScaler::execute");
 
-    return StatusCode::SUCCESS;
+void TauPi0ClusterScaler::clearAssociatedParticleLinks(xAOD::PFOContainer& pfoContainer, xAOD::PFODetails::PFOParticleType type) const {
+  std::vector<ElementLink<xAOD::IParticleContainer>> emptyLinks;
+  
+  for (xAOD::PFO* pfo : pfoContainer) {
+    pfo->setAssociatedParticleLinks(type, emptyLinks);
+  }
 }
 
-//______________________________________________________________________________
-void TauPi0ClusterScaler::resetNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const
-{
-    // Set neutral PFO kinematics to vertex corrected cluster
-    ATH_MSG_DEBUG("Resetting neutral PFO kinematics");
-    for( auto pfo : neutralPFOContainer )
-    {
-        const xAOD::CaloCluster* cl = pfo->cluster(0);
-
-        // apply cluster vertex correction 
-        if(pTau.vertexLink().isValid()){
-            auto clcorr = xAOD::CaloVertexedTopoCluster(*cl, pTau.vertex()->position());
-            pfo->setP4(clcorr.pt(), clcorr.eta(), clcorr.phi(), 0.0);
-        }
-        else{
-            pfo->setP4(cl->pt(), cl->eta(), cl->phi(), 0.0);
-        }
-
-        ATH_MSG_DEBUG("Neutral PFO, ptr: " <<  cl
-                        << ", e: " << pfo->e() 
-                        << ", pt: " << pfo->pt()
-                        << ", eta: " << pfo->eta()
-                        << ", eta(unorr): " << cl->eta());
+
+
+void TauPi0ClusterScaler::correctNeutralPFOs(xAOD::TauJet& tau, xAOD::PFOContainer& neutralPFOContainer) const {
+  // FIXME: Loop over existing neutral PFOs, this may include those not associated to the tau candidate
+  // What if two taus have different vertex ??? Seems rare.
+  for (xAOD::PFO* pfo : neutralPFOContainer ) {
+    const xAOD::CaloCluster* cluster = pfo->cluster(0);
+
+    // apply cluster vertex correction 
+    if(tau.vertexLink().isValid()) {
+      auto clusterAtTauVertx = xAOD::CaloVertexedTopoCluster(*cluster, tau.vertex()->position());
+      pfo->setP4(clusterAtTauVertx.pt(), clusterAtTauVertx.eta(), clusterAtTauVertx.phi(), 0.0);
+    }
+    else{
+      pfo->setP4(cluster->pt(), cluster->eta(), cluster->phi(), 0.0);
     }
+    
+    ATH_MSG_DEBUG("Original Neutral PFO" 
+                  << ", e: " << cluster->pt() 
+                  << ", eta: " << cluster->eta() 
+                  << ", pt: " << cluster->pt());
+
+    ATH_MSG_DEBUG("Corrected Neutral PFO" 
+                  << ", e: " << pfo->pt()
+                  << ", eta: " << pfo->eta()
+                  << ", pt: " << pfo->pt());
+  }
 }
 
-//______________________________________________________________________________
-void TauPi0ClusterScaler::createChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& cPFOContainer) const
-{
-    ATH_MSG_DEBUG("Creating charged PFOs");
-    for(auto tauTrackLink : pTau.tauTrackLinks(xAOD::TauJetParameters::classifiedCharged)){
-        if( not tauTrackLink.isValid() ){
-            ATH_MSG_WARNING("Invalid tauTrackLink");
-            continue;
-        }
-        const xAOD::TauTrack* tauTrack = (*tauTrackLink);
-        // create pfo
-        xAOD::PFO* chargedPFO = new xAOD::PFO();
-        cPFOContainer.push_back(chargedPFO);
-        // set properties
-        chargedPFO->setCharge(tauTrack->track()->charge());
-        chargedPFO->setP4(tauTrack->p4());
-        // link to track
-	if(not chargedPFO->setTrackLink((*tauTrackLink)->trackLinks().at(0)))
-	  ATH_MSG_WARNING("Could not add Track to PFO");
-	// now directly using tau track link from above
-        if(not chargedPFO->setAssociatedParticleLink(xAOD::PFODetails::CaloCluster,tauTrackLink))
-	  ATH_MSG_WARNING("Could not add TauTrack to PFO");
-
-	// link from tau
-        pTau.addProtoChargedPFOLink(ElementLink< xAOD::PFOContainer >
-                                    (chargedPFO, cPFOContainer));
+
+
+void TauPi0ClusterScaler::createChargedPFOs(xAOD::TauJet& tau, xAOD::PFOContainer& chargedPFOContainer) const {
+  for (auto tauTrackLink : tau.tauTrackLinks(xAOD::TauJetParameters::classifiedCharged)) {
+    if (not tauTrackLink.isValid()) {
+      ATH_MSG_WARNING("Invalid tauTrackLink");
+      continue;
+    }
+    const xAOD::TauTrack* tauTrack = (*tauTrackLink);
+    
+    // Create charged PFO
+    xAOD::PFO* chargedPFO = new xAOD::PFO();
+    chargedPFOContainer.push_back(chargedPFO);
+
+    // Set properties
+    chargedPFO->setCharge(tauTrack->track()->charge());
+    chargedPFO->setP4(tauTrack->p4());
+    
+    // Link to track
+    if (not chargedPFO->setTrackLink(tauTrack->trackLinks().at(0))) {
+      ATH_MSG_WARNING("Could not add Track to PFO");
+    }
+
+    // FIXME: Better to change xAOD::PFODetails::CaloCluster, it is confusing 
+    if (not chargedPFO->setAssociatedParticleLink(xAOD::PFODetails::CaloCluster, tauTrackLink)) {
+      ATH_MSG_WARNING("Could not add TauTrack to PFO");
     }
+
+    tau.addProtoChargedPFOLink(ElementLink<xAOD::PFOContainer>(chargedPFO, chargedPFOContainer));
+  }
+}
+
+
+
+float TauPi0ClusterScaler::getExtrapolatedPosition(const xAOD::PFO& chargedPFO, xAOD::TauJetParameters::TrackDetail detail) const {
+  float position = -10.0;
+  
+  // Obtain the associated TauTrack  
+  std::vector<const xAOD::IParticle*> tauTrackParticles;
+  // FIXME: The type here is confusing
+  chargedPFO.associatedParticles(xAOD::PFODetails::CaloCluster, tauTrackParticles);
+  if (tauTrackParticles.empty()) {
+    ATH_MSG_WARNING("ChargedPFO has no associated TauTrack, will set -10.0 to " << detail);
+    return -10.0;
+  }
+
+  const xAOD::TauTrack* tauTrack = dynamic_cast<const xAOD::TauTrack*>(tauTrackParticles.at(0));
+  if (not tauTrack) {
+    ATH_MSG_WARNING("Failed to retrieve TauTrack from ChargedPFO, will set -10.0 to " << detail);
+    return -10.0;
+  }
+  
+  if( not tauTrack->detail(detail, position)) {
+    ATH_MSG_WARNING("Failed to retrieve extrapolated chargedPFO position, will set -10.0 to " << detail);
+    return -10.0;
+  }
+  
+  return position; 
 }
 
-//______________________________________________________________________________
-void TauPi0ClusterScaler::associateHadronicToChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& chargedPFOContainer) const
-{
-    ATH_MSG_DEBUG("Associating hadronic PFOs to charged PFOs");
-
-    // Will: I'm ashamed of this link-map, but its necessary until the 
-    // PFO EDM is improved to allow sequential addition of particle links
-    std::map< xAOD::PFO*,std::vector< ElementLink< xAOD::IParticleContainer > > > linkMap;
-    ATH_MSG_DEBUG("nHadPFOs: " << pTau.nHadronicPFOs() );
-    for( auto hadPFOLink : pTau.hadronicPFOLinks() ){
-        if( not hadPFOLink.isValid() ){
-            ATH_MSG_WARNING("Invalid hadPFOLink");
-            continue;
-        }
-        ATH_MSG_DEBUG("hadPFO " << hadPFOLink.index() 
-                      << ", eta: " << (*hadPFOLink)->eta() 
-                      << ", phi: " << (*hadPFOLink)->phi() );
-        xAOD::PFO* chargedPFOMatch = nullptr;
-        // assign hadPFO to closest extrapolated chargedPFO track within dR<0.4
-        float dRmin = 0.4; 
-        for( auto chargedPFO : chargedPFOContainer ){
-            // get extrapolated positions from tau-track
-            std::vector<const xAOD::IParticle*> tauTrackPcleVec;
-            chargedPFO->associatedParticles(xAOD::PFODetails::CaloCluster, tauTrackPcleVec);
-            if( tauTrackPcleVec.empty() ){
-                ATH_MSG_WARNING("ChargedPFO has no associated TauTrack");
-                continue;
-            }
-
-	    auto tauTrack = dynamic_cast<const xAOD::TauTrack*>(tauTrackPcleVec.at(0));
-	    if( not tauTrack ){
-                ATH_MSG_WARNING("Failed to retrieve TauTrack from ChargedPFO");
-                continue;
-	    }
-	    float etaCalo = -10.0;
-	    float phiCalo = -10.0;
-	    if( not tauTrack->detail(xAOD::TauJetParameters::CaloSamplingEtaHad, etaCalo))
-	      ATH_MSG_WARNING("Failed to retrieve extrapolated chargedPFO eta");
-	    if( not tauTrack->detail(xAOD::TauJetParameters::CaloSamplingPhiHad, phiCalo))
-	      ATH_MSG_WARNING("Failed to retrieve extrapolated chargedPFO phi");
-            // calculate dR (false means use eta instead of rapidity)
-            float dR = xAOD::P4Helpers::deltaR((**hadPFOLink), etaCalo, phiCalo, false);
-            ATH_MSG_DEBUG("chargedPFO, pt: " << chargedPFO->pt()
-			  << ", type: " << tauTrack->flagSet()
-			  << ", eta: " << etaCalo
-			  << ", phi: " << phiCalo
-			  << ", dR: " << dR );
-            if (dR < dRmin){
-                dRmin = dR;
-                chargedPFOMatch = chargedPFO;
-            }
-        }
-        if( not chargedPFOMatch ){
-            ATH_MSG_DEBUG("Unassigned Hadronic PFO");
-            continue; 
-        }
-
-        // create link to had PFO (add to chargedPFO later)
-        ElementLink< xAOD::IParticleContainer > newHadLink;
-        newHadLink.toPersistent();
-        newHadLink.resetWithKeyAndIndex( hadPFOLink.persKey(), hadPFOLink.persIndex() );
-        if (not newHadLink.isValid()){
-            ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
-            continue;
-        }
-
-        // temporarily store in linkMap since we can't sequentially add to chargedPFOMatch
-        if( not linkMap.count(chargedPFOMatch) )
-            linkMap[chargedPFOMatch] = std::vector< ElementLink< xAOD::IParticleContainer > >();
-        linkMap[chargedPFOMatch].push_back(newHadLink);
+
+
+void TauPi0ClusterScaler::associateHadronicToChargedPFOs(xAOD::TauJet& tau, xAOD::PFOContainer& chargedPFOContainer) const {
+  std::map< xAOD::PFO*,std::vector< ElementLink< xAOD::IParticleContainer > > > linkMap;
+ 
+  // For each hadronic PFO, associate it to the cloest charged PFO. It assumes that one hadronic PFO comes from at 
+  // most one charged PFO.
+  for (auto hadPFOLink : tau.hadronicPFOLinks()) {
+    if (not hadPFOLink.isValid()) {
+      ATH_MSG_WARNING("Invalid hadPFOLink");
+      continue;
+    }
+    ATH_MSG_DEBUG("hadPFO " << hadPFOLink.index() << ", eta: " << (*hadPFOLink)->eta() << ", phi: " << (*hadPFOLink)->phi() );
+    
+    // Assign hadPFO to closest extrapolated chargedPFO track within dR < 0.4
+    xAOD::PFO* chargedPFOMatch = nullptr;
+    float dRmin = 0.4;
+    
+    // FIXME: This loops over the existing charged PFO container, and could contain PFO not associated to this tau.
+    // It could make the association depending on the order of the tau candidate, but the point is that 
+    // hadronic PFO in one tau candidate is unlikely to be associated to charged PFO in another tau candidate
+    for (xAOD::PFO* chargedPFO : chargedPFOContainer) {
+      
+      float etaCalo = getExtrapolatedPosition(*chargedPFO, xAOD::TauJetParameters::CaloSamplingEtaHad);
+      float phiCalo = getExtrapolatedPosition(*chargedPFO, xAOD::TauJetParameters::CaloSamplingPhiHad);
+    
+      float dR = xAOD::P4Helpers::deltaR((**hadPFOLink), etaCalo, phiCalo, false);
+      if (dR < dRmin){
+        dRmin = dR;
+        chargedPFOMatch = chargedPFO;
+      }
+    }
+    
+    if( not chargedPFOMatch ){
+      ATH_MSG_DEBUG("Unassigned Hadronic PFO");
+      continue; 
     }
 
-    // finally set hadronic PFO links (note: we use existing TauShot enum)
-    for( auto [k,v] : linkMap ){
-        if(not k->setAssociatedParticleLinks(xAOD::PFODetails::TauShot, v))
-            ATH_MSG_WARNING("Couldn't add hadronic PFO links to charged PFO!");
+    // create link to had PFO (add to chargedPFO later)
+    ElementLink< xAOD::IParticleContainer > newHadLink;
+    newHadLink.toPersistent();
+    newHadLink.resetWithKeyAndIndex( hadPFOLink.persKey(), hadPFOLink.persIndex() );
+    if (not newHadLink.isValid()){
+        ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
+        continue;
+    }
+    
+    if( not linkMap.count(chargedPFOMatch) ) {
+        linkMap[chargedPFOMatch] = std::vector< ElementLink< xAOD::IParticleContainer > >();
     }
+
+    linkMap[chargedPFOMatch].push_back(newHadLink);
+  }
+
+  // finally set hadronic PFO links (note: we use existing TauShot enum)
+  for (auto [k,v] : linkMap) {
+    if(not k->setAssociatedParticleLinks(xAOD::PFODetails::TauShot, v))
+      ATH_MSG_WARNING("Couldn't add hadronic PFO links to charged PFO!");
+  }
 }
 
-//______________________________________________________________________________
-void TauPi0ClusterScaler::associateChargedToNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& neutralPFOContainer) const
-{
-    ATH_MSG_DEBUG("Associating charged PFOs to neutral PFOs");
-    // Will: I'm ashamed of this link-map, but its necessary until the 
-    // PFO EDM is improved to allow sequential addition of particle links
-    std::map< xAOD::PFO*,std::vector< ElementLink< xAOD::IParticleContainer > > > linkMap;
-    ATH_MSG_DEBUG("nChargedPFOs: " << pTau.nProtoChargedPFOs() );
-    for( auto chargedPFOLink : pTau.protoChargedPFOLinks() ){
-        if( not chargedPFOLink.isValid() ){
-            ATH_MSG_WARNING("Invalid protoChargedPFOLink");
-            continue;
-        }
-        const xAOD::PFO* chargedPFO = (*chargedPFOLink);
-        
-        // get extrapolated positions from tau-track
-        std::vector<const xAOD::IParticle*> tauTrackPcleVec;
-        chargedPFO->associatedParticles(xAOD::PFODetails::CaloCluster, tauTrackPcleVec);
-        if( tauTrackPcleVec.empty() ){
-            ATH_MSG_WARNING("ChargedPFO has no associated TauTrack");
-            continue;
-        }
-        auto tauTrack = dynamic_cast<const xAOD::TauTrack*>(tauTrackPcleVec.at(0));
-        if( not tauTrack ){
-            ATH_MSG_WARNING("Failed to retrieve TauTrack from ChargedPFO");
-            continue;
-        } 
-        float etaCalo = -10.0;
-        float phiCalo = -10.0;
-        if( not tauTrack->detail(xAOD::TauJetParameters::CaloSamplingEtaEM, etaCalo))
-            ATH_MSG_WARNING("Failed to retrieve extrapolated chargedPFO eta");
-        if( not tauTrack->detail(xAOD::TauJetParameters::CaloSamplingPhiEM, phiCalo))
-            ATH_MSG_WARNING("Failed to retrieve extrapolated chargedPFO phi");
-        ATH_MSG_DEBUG("chargedPFO " << chargedPFOLink.index() 
-                      << ", eta: " << etaCalo 
-                      << ", phi: " << phiCalo );
+
+
+void TauPi0ClusterScaler::associateChargedToNeutralPFOs(xAOD::TauJet& tau, xAOD::PFOContainer& neutralPFOContainer) const {
+  std::map< xAOD::PFO*,std::vector< ElementLink< xAOD::IParticleContainer > > > linkMap;
+  for (auto chargedPFOLink : tau.protoChargedPFOLinks()) {
+    if (not chargedPFOLink.isValid()) {
+      ATH_MSG_WARNING("Invalid protoChargedPFOLink");
+      continue;
+    }
+    const xAOD::PFO* chargedPFO = (*chargedPFOLink);
+    
+    float etaCalo = getExtrapolatedPosition(*chargedPFO, xAOD::TauJetParameters::CaloSamplingEtaEM);
+    float phiCalo = getExtrapolatedPosition(*chargedPFO, xAOD::TauJetParameters::CaloSamplingPhiEM);
+    
+    // Assign extrapolated chargedPFO to closest neutralPFO within dR<0.04
+    xAOD::PFO* neutralPFOMatch = nullptr;
+    
+    // FIXME: This loops over the existing neutral PFO container, and could contain PFO not associated to this tau.
+    // It could make the association depending on the order of the tau candidate. but the point is that 
+    // charged PFO in one tau candidate is unlikely to be associated to the neutral PFO in another tau candidate
+    float dRmin = 0.04; 
+    for (xAOD::PFO* neutralPFO : neutralPFOContainer) {
+      // FIXME: cluster p4 is not corrected to the tau axis 
+      float dR = xAOD::P4Helpers::deltaR((*neutralPFO->cluster(0)), etaCalo, phiCalo, false);
+      if (dR < dRmin){
+        dRmin = dR;
+        neutralPFOMatch = neutralPFO;
+      }
+    }
+    
+    if (not neutralPFOMatch){
+      ATH_MSG_DEBUG("Unassigned Charged PFO");
+      continue; 
+    }
+
+    // create link to charged PFO 
+    ElementLink<xAOD::IParticleContainer> newChargedLink;
+    newChargedLink.toPersistent();
+    newChargedLink.resetWithKeyAndIndex(chargedPFOLink.persKey(), chargedPFOLink.persIndex());
+    if (not newChargedLink.isValid()){
+      ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
+      continue;
+    }
         
-        // assign extrapolated chargedPFO to closest neutralPFO within dR<0.04
-        xAOD::PFO* neutralPFOMatch = nullptr;
-        float dRmin = 0.04; 
-        for( auto neutralPFO : neutralPFOContainer ){
-            // calculate dR (false means use eta instead of rapidity)
-            float dR = xAOD::P4Helpers::deltaR((*neutralPFO->cluster(0)), etaCalo, phiCalo, false);
-            ATH_MSG_DEBUG("neutralPFO, eta: " << neutralPFO->cluster(0)->eta()
-                            << ", phi: " << neutralPFO->cluster(0)->phi()
-                            << ", dR: " << dR );
-            if (dR < dRmin){
-                dRmin = dR;
-                neutralPFOMatch = neutralPFO;
-            }
-        }
-        if( not neutralPFOMatch ){
-            ATH_MSG_DEBUG("Unassigned Charged PFO");
-            continue; 
-        }
-        else ATH_MSG_DEBUG("Assigned Charged PFO");
-
-        // create link to charged PFO 
-        ElementLink< xAOD::IParticleContainer > newChargedLink;
-        newChargedLink.toPersistent();
-        newChargedLink.resetWithKeyAndIndex( chargedPFOLink.persKey(), chargedPFOLink.persIndex() );
-        if (not newChargedLink.isValid()){
-            ATH_MSG_WARNING("Created an invalid element link to xAOD::PFO");
-            continue;
-        }
-
-        // temporarily store in linkMap since we can't sequentially add to neutralPFOMatch
-        if( not linkMap.count(neutralPFOMatch) )
-            linkMap[neutralPFOMatch] = std::vector< ElementLink< xAOD::IParticleContainer > >();
-        linkMap[neutralPFOMatch].push_back(newChargedLink);
+    if( not linkMap.count(neutralPFOMatch) ) {
+      linkMap[neutralPFOMatch] = std::vector< ElementLink< xAOD::IParticleContainer > >();
     }
 
-    // finally set charged PFO links
-    for( auto [k,v] : linkMap ){
-        if(not k->setAssociatedParticleLinks(xAOD::PFODetails::Track,v))
-            ATH_MSG_WARNING("Couldn't add charged PFO links to neutral PFO!");
+    linkMap[neutralPFOMatch].push_back(newChargedLink);
+  }
+    
+  // Finally set charged PFO links,
+  for (auto [k,v] : linkMap) {
+    if(not k->setAssociatedParticleLinks(xAOD::PFODetails::Track,v)) {
+      ATH_MSG_WARNING("Couldn't add charged PFO links to neutral PFO!");
     }
+  }
 }
 
-//______________________________________________________________________________
-void TauPi0ClusterScaler::subtractChargedEnergyFromNeutralPFOs(xAOD::PFOContainer& neutralPFOContainer) const
-{
-    ATH_MSG_DEBUG("Subtracting charged energy from neutral PFOs");
-    for( auto neutralPFO : neutralPFOContainer )
-    {
-        // get associated charged PFOs
-        std::vector<const xAOD::IParticle*> chargedPFOs;
-        neutralPFO->associatedParticles(xAOD::PFODetails::Track, chargedPFOs);
-        if( chargedPFOs.empty() ){
-            ATH_MSG_DEBUG("No associated charged to subtract"); 
-            continue;
-        }
-        ATH_MSG_DEBUG("Associated charged PFOs: " << chargedPFOs.size() );
-
-        // estimate charged EM energy and subtract
-        float neutralEnergy = neutralPFO->e();
-        for( auto chargedPcle : chargedPFOs )
-        {
-            // since PFO stores element links as IParticle, need to cast back
-            const xAOD::PFO* chargedPFO = dynamic_cast<const xAOD::PFO*>(chargedPcle);
-            if( not chargedPFO ){
-                ATH_MSG_WARNING("Failed to downcast IParticle ptr: " << chargedPcle << ", to ChargedPFO! " );
-                continue;
-            }
-            float chargedEMEnergy = chargedPFO->e();
-            std::vector<const xAOD::IParticle*> hadPFOs;
-            chargedPFO->associatedParticles(xAOD::PFODetails::TauShot, hadPFOs);
-            for( auto hadPFO : hadPFOs )
-                chargedEMEnergy -= hadPFO->e();
-            
-            if( chargedEMEnergy < 0.0 ) chargedEMEnergy = 0.0;
-            neutralEnergy -= chargedEMEnergy;
-            ATH_MSG_DEBUG("Subtracting charged energy: " << chargedEMEnergy );
-        } 
-        float neutralPt = neutralEnergy / std::cosh(neutralPFO->eta());
-        if(neutralPt <= 100.) neutralPt = 100.0;
-        
-        ATH_MSG_DEBUG("Neutral PFO pt, orig: " << neutralPFO->pt() << "  new: " << neutralPt); 
-        neutralPFO->setP4(neutralPt , neutralPFO->eta(), neutralPFO->phi(), neutralPFO->m());
+
+
+void TauPi0ClusterScaler::subtractChargedEnergyFromNeutralPFOs(xAOD::PFOContainer& neutralPFOContainer) const {
+  // FIXME: It loops all the exsiting PFOs, will make the PFO kinematic depend on the current 
+  // tau candidate. The kinematics written to the xAOD is the one for the last tau candidate.
+  
+  for (xAOD::PFO* neutralPFO : neutralPFOContainer) {
+    // Get associated charged PFOs
+    std::vector<const xAOD::IParticle*> chargedPFOs;
+    neutralPFO->associatedParticles(xAOD::PFODetails::Track, chargedPFOs);
+    if (chargedPFOs.empty()) {
+      ATH_MSG_DEBUG("No associated charged to subtract"); 
+      continue;
     }
+    ATH_MSG_DEBUG("Associated charged PFOs: " << chargedPFOs.size() );
+
+    // estimate charged EM energy and subtract
+    float neutralEnergy = neutralPFO->e();
+    for (const xAOD::IParticle* chargedParticle : chargedPFOs) {
+      const xAOD::PFO* chargedPFO = dynamic_cast<const xAOD::PFO*>(chargedParticle);
+      if( not chargedPFO ){
+          ATH_MSG_WARNING("Failed to downcast IParticle ptr: " << chargedParticle << ", to ChargedPFO! " );
+          continue;
+      }
+      float chargedEMEnergy = chargedPFO->e();
+      
+      std::vector<const xAOD::IParticle*> hadPFOs;
+      chargedPFO->associatedParticles(xAOD::PFODetails::TauShot, hadPFOs);
+      for (auto hadPFO : hadPFOs) {
+          chargedEMEnergy -= hadPFO->e();
+      }
+
+      if( chargedEMEnergy < 0.0 ) chargedEMEnergy = 0.0;
+      neutralEnergy -= chargedEMEnergy;
+      ATH_MSG_DEBUG("Subtracting charged energy: " << chargedEMEnergy );
+    } 
+    float neutralPt = neutralEnergy / std::cosh(neutralPFO->eta());
+    if (neutralPt <= 100.) neutralPt = 100.0;
+    
+    ATH_MSG_DEBUG("Neutral PFO pt, original: " << neutralPFO->pt() << "  subtracted: " << neutralPt); 
+    neutralPFO->setP4(neutralPt , neutralPFO->eta(), neutralPFO->phi(), neutralPFO->m());
+  }
 }
diff --git a/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.h b/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.h
index bb05d81d099398cdb304e1982152bafd45383e1c..90e9083ea8336bf9a178c12ce69eafe60ab8fd6b 100644
--- a/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.h
+++ b/Reconstruction/tauRecTools/src/TauPi0ClusterScaler.h
@@ -19,51 +19,39 @@
  * @author Will Davey <will.davey@cern.ch> 
  */
 
-//namespace Trk {
-//    class IParticleCaloExtensionTool;
-//}
 class TauPi0ClusterScaler : virtual public TauRecToolBase {
-public:
-    TauPi0ClusterScaler(const std::string& name);
-    ASG_TOOL_CLASS2(TauPi0ClusterScaler, TauRecToolBase, ITauToolBase)
-    virtual ~TauPi0ClusterScaler();
-
-    virtual StatusCode executePi0ClusterScaler(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer, xAOD::PFOContainer& pChargedPFOContainer) const override; 
-
-private:
-
-    /** @brief tool handles */
-    //ToolHandle<Trk::IParticleCaloExtensionTool> m_caloExtensionTool;
 
-    /** @brief reset neutral PFO kinematics (for AOD running) */
-    void resetNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const;
-
-    /** @brief create charged PFOs */
-    void createChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pChargedPFOContainer) const;
-
-    /** @brief extrapolate charged PFO tracks to EM and HAD layers */
-    //void extrapolateChargedPFOs(xAOD::TauJet& pTau);
-    
-    /** @brief associate hadronic PFOs to charged PFOs */
-    void associateHadronicToChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pChargedPFOContainer) const;
-    
-    /** @brief associate charged PFOs to neutral PFOs */
-    void associateChargedToNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const;
-    
-    /** @brief associate charged PFOs to neutral PFOs */
-    void subtractChargedEnergyFromNeutralPFOs(xAOD::PFOContainer& pNeutralPFOContainer) const;
+public:
+  
+  ASG_TOOL_CLASS2(TauPi0ClusterScaler, TauRecToolBase, ITauToolBase)
 
-    /** @brief sets of EM/Had samplings for track extrapolation */
-    //std::set<CaloSampling::CaloSample> m_EMSamplings;
-    //std::set<CaloSampling::CaloSample> m_HadSamplings;
+  TauPi0ClusterScaler(const std::string& name);
+  virtual ~TauPi0ClusterScaler() = default;
 
-    /** dodgy re-purposed PFOAttributes enums */
-    //xAOD::PFODetails::PFOAttributes ETAECAL; 
-    //xAOD::PFODetails::PFOAttributes PHIECAL;
-    //xAOD::PFODetails::PFOAttributes ETAHCAL;
-    //xAOD::PFODetails::PFOAttributes PHIHCAL;
+  virtual StatusCode executePi0ClusterScaler(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer, xAOD::PFOContainer& pChargedPFOContainer) const override; 
 
+private:
+  
+  /** @brief Clear accosicated partcle links for the pfo container */
+  void clearAssociatedParticleLinks(xAOD::PFOContainer& pfoContainer, xAOD::PFODetails::PFOParticleType type) const;
+
+  /** @brief Get extrapolated position to the CAL */
+  float getExtrapolatedPosition(const xAOD::PFO& chargedPFO, xAOD::TauJetParameters::TrackDetail detail) const; 
+
+  /** @brief Correct neutral PFO kinematics to point at the current tau vertex */
+  void correctNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const;
+
+  /** @brief create charged PFOs */
+  void createChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pChargedPFOContainer) const;
+
+  /** @brief associate hadronic PFOs to charged PFOs */
+  void associateHadronicToChargedPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pChargedPFOContainer) const;
+  
+  /** @brief associate charged PFOs to neutral PFOs */
+  void associateChargedToNeutralPFOs(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const;
+  
+  /** @brief associate charged PFOs to neutral PFOs */
+  void subtractChargedEnergyFromNeutralPFOs(xAOD::PFOContainer& pNeutralPFOContainer) const;
 };
 
 #endif  /* TAUPI0CLUSTERSCALER_H */
-
diff --git a/Reconstruction/tauRecTools/src/TauPi0CreateROI.cxx b/Reconstruction/tauRecTools/src/TauPi0CreateROI.cxx
index 586d7b68d0d155b12ec07c856b90803de7b40f8d..e2cf019bdbd38632ba65797eef143136047b62d8 100644
--- a/Reconstruction/tauRecTools/src/TauPi0CreateROI.cxx
+++ b/Reconstruction/tauRecTools/src/TauPi0CreateROI.cxx
@@ -3,33 +3,20 @@
 */
 
 #ifndef XAOD_ANALYSIS
-//-----------------------------------------------------------------------------
-// file:        TauPi0CreateROI.cxx
-// package:     Reconstruction/tauEvent
-// authors:     Will Davey, Benedict Winter, Stephanie Yuen
-// date:        2012-10-09
-//-----------------------------------------------------------------------------
 
-#include "CaloUtils/CaloCellList.h"
 #include "TauPi0CreateROI.h"
 
+#include "CaloUtils/CaloCellList.h"
+
 #include <boost/scoped_ptr.hpp>
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
+
 
 TauPi0CreateROI::TauPi0CreateROI(const std::string& name) :
-     TauRecToolBase(name)
-{
+     TauRecToolBase(name) {
 }
    
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
 
-TauPi0CreateROI::~TauPi0CreateROI() {
-}
 
 StatusCode TauPi0CreateROI::initialize() {
     
@@ -38,58 +25,45 @@ StatusCode TauPi0CreateROI::initialize() {
     return StatusCode::SUCCESS;
 }
 
-//______________________________________________________________________________
-StatusCode TauPi0CreateROI::executePi0CreateROI(xAOD::TauJet& pTau, CaloCellContainer& pPi0CellContainer, boost::dynamic_bitset<>& addedCellsMap) const {
 
-    //---------------------------------------------------------------------
-    // only run on 1-5 prong taus 
-    //---------------------------------------------------------------------
-    if (pTau.nTracks() == 0 || pTau.nTracks() >5 ) {
-        return StatusCode::SUCCESS;
-    }
-    ATH_MSG_DEBUG("new tau. \tpt = " << pTau.pt() << "\teta = " << pTau.eta() << "\tphi = " << pTau.phi() << "\tnprongs = " << pTau.nTracks());
-
-    //---------------------------------------------------------------------
-    // retrieve cells around tau 
-    //---------------------------------------------------------------------
-    // get all calo cell container
-    SG::ReadHandle<CaloCellContainer> caloCellInHandle( m_caloCellInputContainer );
-    if (!caloCellInHandle.isValid()) {
-      ATH_MSG_ERROR ("Could not retrieve HiveDataObj with key " << caloCellInHandle.key());
-      return StatusCode::FAILURE;
-    }
-    const CaloCellContainer *pCellContainer = NULL;
-    pCellContainer = caloCellInHandle.cptr();
-    
-    // get only EM cells within dR<0.4
-    std::vector<CaloCell_ID::SUBCALO> emSubCaloBlocks;
-    emSubCaloBlocks.push_back(CaloCell_ID::LAREM);
-    boost::scoped_ptr<CaloCellList> pCells(new CaloCellList(pCellContainer,emSubCaloBlocks)); 
-    pCells->select(pTau.eta(), pTau.phi(), 0.4); // TODO: change hardcoded 0.4 to tau cone variable, (or func. from TauJet)?
-
-    //---------------------------------------------------------------------
-    // Put Ecal cells in output container
-    //---------------------------------------------------------------------
-
-    CaloCellList::list_iterator cellItr(pCells->begin()), cellItrE(pCells->end());
-    for(; cellItr != cellItrE; ++cellItr) {
-        const CaloCell* cell = (*cellItr);
-
-        // only keep cells that are in Ecal (PS, EM1, EM2 and EM3, both barrel and endcap).
-        int samp = cell->caloDDE()->getSampling();
-        if(samp>7) continue;
-
-        // Store cell in output container
-        const IdentifierHash cellHash = cell->caloDDE()->calo_hash();
-
-	if(!addedCellsMap.test(cellHash)) {
-            CaloCell* copyCell = cell->clone();
-            pPi0CellContainer.push_back(copyCell);
-	    addedCellsMap.set(cellHash);
-        }
-    }
 
+StatusCode TauPi0CreateROI::executePi0CreateROI(xAOD::TauJet& tau, CaloCellContainer& pi0CellContainer, boost::dynamic_bitset<>& addedCellsMap) const {
+  // only run on 1-5 prong taus 
+  if (tau.nTracks() == 0 || tau.nTracks() >5 ) {
     return StatusCode::SUCCESS;
+  }
+
+  SG::ReadHandle<CaloCellContainer> caloCellInHandle( m_caloCellInputContainer );
+  if (!caloCellInHandle.isValid()) {
+    ATH_MSG_ERROR ("Could not retrieve HiveDataObj with key " << caloCellInHandle.key());
+    return StatusCode::FAILURE;
+  }
+  const CaloCellContainer *cellContainer = caloCellInHandle.cptr();;
+  
+  // get only EM cells within dR < 0.4
+  // TODO: change hardcoded 0.4 to meaningful variable
+  std::vector<CaloCell_ID::SUBCALO> emSubCaloBlocks;
+  emSubCaloBlocks.push_back(CaloCell_ID::LAREM);
+  boost::scoped_ptr<CaloCellList> cellList(new CaloCellList(cellContainer,emSubCaloBlocks)); 
+  // FIXME: tau p4 is corrected to point at tau vertex, but the cells are not
+  cellList->select(tau.eta(), tau.phi(), 0.4);
+
+  for (const CaloCell* cell : *cellList) {
+    // only keep cells that are in Ecal (PS, EM1, EM2 and EM3, both barrel and endcap).
+    int sampling = cell->caloDDE()->getSampling();
+    if (sampling > 7) continue;
+
+    // Store cell in output container
+    const IdentifierHash cellHash = cell->caloDDE()->calo_hash();
+
+    if (!addedCellsMap.test(cellHash)) {
+      CaloCell* newCell = cell->clone();
+      pi0CellContainer.push_back(newCell);
+      addedCellsMap.set(cellHash);
+    }
+  }
+
+  return StatusCode::SUCCESS;
 }
 
 #endif
diff --git a/Reconstruction/tauRecTools/src/TauPi0CreateROI.h b/Reconstruction/tauRecTools/src/TauPi0CreateROI.h
index ee9e0ea640ae615e95a55282a14045012bd9fdf4..e3c6b54f1aaf3d86fc351139228d26e521742865 100644
--- a/Reconstruction/tauRecTools/src/TauPi0CreateROI.h
+++ b/Reconstruction/tauRecTools/src/TauPi0CreateROI.h
@@ -18,7 +18,7 @@
 #include "xAODTau/TauJet.h"
 
 /**
- * @brief Create ROIs for the Pi0 finder.
+ * @brief Find the cells used to create pi0 cluster
  * 
  * @author Will Davey <will.davey@cern.ch> 
  * @author Benedict Winter <benedict.tobias.winter@cern.ch> 
@@ -26,17 +26,21 @@
  */
 
 class TauPi0CreateROI : public TauRecToolBase {
+
 public:
-    TauPi0CreateROI(const std::string& name);
-    ASG_TOOL_CLASS2(TauPi0CreateROI, TauRecToolBase, ITauToolBase);
-    virtual ~TauPi0CreateROI();
 
-    virtual StatusCode initialize() override;
-    virtual StatusCode executePi0CreateROI(xAOD::TauJet& pTau, CaloCellContainer& Pi0CellContainer, boost::dynamic_bitset<>& map) const override;
+  ASG_TOOL_CLASS2(TauPi0CreateROI, TauRecToolBase, ITauToolBase);
+  
+  TauPi0CreateROI(const std::string& name);
+  virtual ~TauPi0CreateROI() = default;
+
+  virtual StatusCode initialize() override;
+  virtual StatusCode executePi0CreateROI(xAOD::TauJet& pTau, CaloCellContainer& Pi0CellContainer, boost::dynamic_bitset<>& map) const override;
 
 private:
-    SG::ReadHandleKey<CaloCellContainer> m_caloCellInputContainer{this,"Key_caloCellInputContainer", "AllCalo", "input vertex container key"};
+    
+  SG::ReadHandleKey<CaloCellContainer> m_caloCellInputContainer{this,"Key_caloCellInputContainer", "AllCalo", "input vertex container key"};
+
 };
 
 #endif	/* TAUPI0CREATEROI_H */
-
diff --git a/Reconstruction/tauRecTools/src/TauShotFinder.cxx b/Reconstruction/tauRecTools/src/TauShotFinder.cxx
index 1ebb673a60f559186064b3904bd4600e691c6f5b..04c9964045d9a5f5f3154ff07d0d98a51f4f0567 100644
--- a/Reconstruction/tauRecTools/src/TauShotFinder.cxx
+++ b/Reconstruction/tauRecTools/src/TauShotFinder.cxx
@@ -3,346 +3,401 @@
 */
 
 #ifndef XAOD_ANALYSIS
-//-----------------------------------------------------------------------------
-// file:        TauShotFinder.cxx
-// package:     Reconstruction/tauRec
-// authors:     Will Davey, Benedict Winter, Stephanie Yuen
-// date:        2013-05-22
-//-----------------------------------------------------------------------------
 
-#include <boost/scoped_ptr.hpp>
+#include "TauShotFinder.h"
+#include "TauShotVariableHelpers.h"
 
 #include "xAODCaloEvent/CaloClusterContainer.h"
 #include "xAODCaloEvent/CaloClusterKineHelper.h"
 #include "CaloUtils/CaloClusterStoreHelper.h"
 #include "CaloUtils/CaloCellList.h"
-#include "TauShotFinder.h"
-#include "TauShotVariableHelpers.h"
 #include "xAODPFlow/PFOContainer.h"
 #include "xAODPFlow/PFOAuxContainer.h"
 #include "xAODPFlow/PFO.h"
 
-//-------------------------------------------------------------------------
-// Constructor
-//-------------------------------------------------------------------------
+#include <boost/scoped_ptr.hpp>
+
+
 
 TauShotFinder::TauShotFinder(const std::string& name) :
     TauRecToolBase(name) {
 }
 
-//-------------------------------------------------------------------------
-// Destructor
-//-------------------------------------------------------------------------
 
-TauShotFinder::~TauShotFinder() {
-}
 
-//______________________________________________________________________________
 StatusCode TauShotFinder::initialize() {
-    
-    // retrieve tools
-    ATH_MSG_DEBUG( "Retrieving tools" );
-    CHECK( m_caloWeightTool.retrieve() );
+  
+  ATH_CHECK(m_caloWeightTool.retrieve());
+  ATH_CHECK(m_caloCellInputContainer.initialize());
+  ATH_CHECK(detStore()->retrieve (m_calo_id, "CaloCell_ID"));
 
-    ATH_CHECK( m_caloCellInputContainer.initialize() );
+  return StatusCode::SUCCESS;
+}
 
-    // initialize calo cell geo
-    ATH_CHECK( detStore()->retrieve (m_calo_id, "CaloCell_ID") );
 
-    return StatusCode::SUCCESS;
-}
 
-//______________________________________________________________________________
-StatusCode TauShotFinder::executeShotFinder(xAOD::TauJet& pTau, xAOD::CaloClusterContainer& tauShotClusterContainer,
-					    xAOD::PFOContainer& tauShotPFOContainer) const {
+StatusCode TauShotFinder::executeShotFinder(xAOD::TauJet& tau, xAOD::CaloClusterContainer& shotClusterContainer,
+					    xAOD::PFOContainer& shotPFOContainer) const {
 
-    ATH_MSG_DEBUG("execute");
-    // Any tau needs to have shot PFO vectors. Set empty vectors before nTrack cut
-    std::vector<ElementLink<xAOD::PFOContainer> > empty;
-    pTau.setShotPFOLinks(empty);
+  // Any tau needs to have shot PFO vectors. Set empty vectors before nTrack cut
+  std::vector<ElementLink<xAOD::PFOContainer>> empty;
+  tau.setShotPFOLinks(empty);
+  
+  // Only run on 1-5 prong taus 
+  if (tau.nTracks() == 0 || tau.nTracks() >5 ) {
+     return StatusCode::SUCCESS;
+  }
+    
+  SG::ReadHandle<CaloCellContainer> caloCellInHandle( m_caloCellInputContainer );
+  if (!caloCellInHandle.isValid()) {
+    ATH_MSG_ERROR ("Could not retrieve HiveDataObj with key " << caloCellInHandle.key());
+    return StatusCode::FAILURE;
+  }
+  const CaloCellContainer *cellContainer = caloCellInHandle.cptr();;
+    
+  // Select seed cells:
+  // -- dR < 0.4, EM1, pt > 100
+  // -- largest pt among the neighbours in eta direction 
+  // -- no other seed cell as neighbour in eta direction 
+  std::vector<const CaloCell*> seedCells = selectSeedCells(tau, *cellContainer);
+  ATH_MSG_DEBUG("seedCells.size() = " << seedCells.size());
     
-    //---------------------------------------------------------------------
-    // only run shower subtraction on 1-5 prong taus 
-    //---------------------------------------------------------------------
-    if (pTau.nTracks() == 0 || pTau.nTracks() >5 ) {
-       return StatusCode::SUCCESS;
+  // Construt shot by merging neighbour cells in phi direction 
+  while (seedCells.size()) {
+    // Find the neighbour in phi direction, and choose the one with highest pt
+    const CaloCell* cell = seedCells.front(); 
+    const CaloCell* phiNeigCell = getPhiNeighbour(*cell, seedCells);
+    
+    // Construct shot PFO candidate
+    xAOD::PFO* shot = new xAOD::PFO();
+    shotPFOContainer.push_back(shot);
+
+    // -- Construct the shot cluster 
+    xAOD::CaloCluster* shotCluster = createShotCluster(cell, phiNeigCell, *cellContainer);
+    shotClusterContainer.push_back(shotCluster);
+   
+    ElementLink<xAOD::CaloClusterContainer> clusElementLink;
+    clusElementLink.toContainedElement( shotClusterContainer, shotCluster );
+    shot->setClusterLink( clusElementLink );
+   
+    // -- Calculate the four momentum
+    // TODO: simplify the calculation 
+    if (phiNeigCell) {
+      // interpolate position
+      double dPhi = TVector2::Phi_mpi_pi( phiNeigCell->phi() - cell->phi());
+      double ratio = phiNeigCell->pt()*m_caloWeightTool->wtCell(phiNeigCell)/(cell->pt()*m_caloWeightTool->wtCell(cell) + phiNeigCell->pt()*m_caloWeightTool->wtCell(phiNeigCell));
+      float phi = cell->phi()+dPhi*ratio;
+      float pt = cell->pt()*m_caloWeightTool->wtCell(cell)+phiNeigCell->pt()*m_caloWeightTool->wtCell(phiNeigCell);
+
+      shot->setP4( (float) pt, (float) cell->eta(), (float) phi, (float) cell->m());
     }
-    //---------------------------------------------------------------------
-    // retrieve cells around tau 
-    //---------------------------------------------------------------------
-    // get all calo cell container
-    SG::ReadHandle<CaloCellContainer> caloCellInHandle( m_caloCellInputContainer );
-    if (!caloCellInHandle.isValid()) {
-      ATH_MSG_ERROR ("Could not retrieve HiveDataObj with key " << caloCellInHandle.key());
-      return StatusCode::FAILURE;
+    else {
+      shot->setP4( (float) cell->pt()*m_caloWeightTool->wtCell(cell), (float) cell->eta(), (float) cell->phi(), (float) cell->m()); 
     }
-    const CaloCellContainer *pCellContainer = caloCellInHandle.cptr();;
+
+    // -- Set the Attribute 
+    shot->setBDTPi0Score(-9999.);
+    shot->setCharge(0);
+    shot->setCenterMag(0.0);
     
-    // get only EM cells within dR<0.4
-    std::vector<CaloCell_ID::SUBCALO> emSubCaloBlocks;
-    emSubCaloBlocks.push_back(CaloCell_ID::LAREM);
-    boost::scoped_ptr<CaloCellList> pCells(new CaloCellList(pCellContainer,emSubCaloBlocks)); 
-    pCells->select(pTau.eta(), pTau.phi(), 0.4); 
-
-    // Dump cells into a std::vector since CaloCellList wont allow sorting
-    // Also apply very basic preselection
-    std::vector<const CaloCell*> cells;
-    CaloCellList::list_iterator cellItr = pCells->begin();
-    for(; cellItr!=pCells->end();++cellItr){
-        // require cells above 100 MeV
-        if( (*cellItr)->pt()*m_caloWeightTool->wtCell(*cellItr) < 100. ) continue;
-        // require cells in EM1 
-        int samp = (*cellItr)->caloDDE()->getSampling();
-        if( !( samp == CaloCell_ID::EMB1 || samp == CaloCell_ID::EME1 ) ) continue;
-        cells.push_back(*cellItr);
-    }
-    // sort cells in descending pt    
-    std::sort(cells.begin(),cells.end(),ptSort(*this));
+    shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_nCellsInEta, m_nCellsInEta);
     
-    //---------------------------------------------------------------------
-    // shot seeding 
-    //---------------------------------------------------------------------
-    // get seed cells
-    std::vector<const CaloCell*> seedCells; 
-    std::set<IdentifierHash> seedCellHashes;
-    cellItr = cells.begin();
-    for(; cellItr != cells.end(); ++cellItr) {
-        const CaloCell* cell = (*cellItr);
-        const IdentifierHash cellHash = cell->caloDDE()->calo_hash();
-
-        // apply seed selection on nearest neighbours
-        std::vector<IdentifierHash> nextEta, prevEta;
-        m_calo_id->get_neighbours(cellHash,LArNeighbours::nextInEta,nextEta);
-        m_calo_id->get_neighbours(cellHash,LArNeighbours::prevInEta,prevEta);
-        std::vector<IdentifierHash> neighbours = nextEta;
-        neighbours.insert(neighbours.end(),prevEta.begin(),prevEta.end()); 
-        bool status = true;
-        std::vector<IdentifierHash>::iterator hashItr = neighbours.begin();
-        for(;hashItr!=neighbours.end();++hashItr){
-            // must not be next to seed cell (TODO: maybe this requirement can be removed)
-            if( seedCellHashes.find(*hashItr) != seedCellHashes.end() ){
-                status = false;
-                break;
-            }
-            // must be maximum
-            const CaloCell* neigCell = pCellContainer->findCell(*hashItr);
-            if( !neigCell ) continue;
-            if( neigCell->pt()*m_caloWeightTool->wtCell(neigCell) >= cell->pt()*m_caloWeightTool->wtCell(cell) ){
-                status = false;
-                break;
-            }
-        }
-        if( !status ) continue;        
-        seedCells.push_back(cell); 
-        seedCellHashes.insert(cellHash);
-    } // preselected cells
-    ATH_MSG_DEBUG("seedCells.size() = " << seedCells.size());
+    const IdentifierHash seedHash = cell->caloDDE()->calo_hash();
+    shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHash);
+
+    std::vector<std::vector<const CaloCell*>> cellBlock = TauShotVariableHelpers::getCellBlock(*shot, m_calo_id);
+
+    float pt1 = TauShotVariableHelpers::ptWindow(cellBlock, 1, m_caloWeightTool);
+    shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt1, pt1);
     
-    // merge across phi and construct shots
-    while( seedCells.size() ){
-        
-        const CaloCell* cell = seedCells.front(); 
-        const IdentifierHash seedHash = cell->caloDDE()->calo_hash();
-
-        // look for match across phi in current seeds
-        const CaloCell* nextPhi = NULL;
-        const CaloCell* prevPhi = NULL;
-        for( cellItr = seedCells.begin(); cellItr!=seedCells.end(); ++cellItr){
-            if( (*cellItr) == cell ) continue;
-            IdentifierHash shotCellHash = (*cellItr)->caloDDE()->calo_hash();
-            if( this->isPhiNeighbour(seedHash,shotCellHash,true) )       nextPhi = (*cellItr);
-            else if( this->isPhiNeighbour(seedHash,shotCellHash,false) ) prevPhi = (*cellItr);
-        }
-       
-        const CaloCell* mergePhi = NULL;
-        if( nextPhi && prevPhi ){
-            // take higest-pt if merged up and down
-            if( nextPhi->pt()*m_caloWeightTool->wtCell(nextPhi) > prevPhi->pt()*m_caloWeightTool->wtCell(prevPhi) ) mergePhi = nextPhi;
-            else                                mergePhi = prevPhi;
-        }
-        else if (nextPhi) mergePhi = nextPhi;
-        else if (prevPhi) mergePhi = prevPhi;
-
-        // get neighbours in 5x1 window
-        std::vector<const CaloCell*> windowNeighbours = this->getNeighbours(pCellContainer,cell,2);
-        if( mergePhi ){
-            std::vector<const CaloCell*> mergeCells = this->getNeighbours(pCellContainer,mergePhi,2);
-            windowNeighbours.push_back(mergePhi);
-            windowNeighbours.insert(windowNeighbours.end(),mergeCells.begin(),mergeCells.end());
-        }
-
-        
-        // create seed cluster
-        xAOD::CaloCluster* shotCluster = CaloClusterStoreHelper::makeCluster(pCellContainer);
-        shotCluster->getOwnCellLinks()->reserve(windowNeighbours.size()+1);
-        shotCluster->addCell(pCellContainer->findIndex(seedHash), 1.);
-        cellItr = windowNeighbours.begin();
-        for( ; cellItr!=windowNeighbours.end(); ++cellItr)
-            shotCluster->addCell(pCellContainer->findIndex((*cellItr)->caloDDE()->calo_hash()),1.0);
-        CaloClusterKineHelper::calculateKine(shotCluster,true,true);
-        tauShotClusterContainer.push_back(shotCluster);
-        
-        // create shot PFO and store it in output container
-        xAOD::PFO* shot = new xAOD::PFO();
-        tauShotPFOContainer.push_back( shot );
-
-        // Create element link from tau to shot
-        ElementLink<xAOD::PFOContainer> PFOElementLink;
-        PFOElementLink.toContainedElement( tauShotPFOContainer, shot );
-        pTau.addShotPFOLink( PFOElementLink );
-       
-        if( mergePhi ){
-            // interpolate position
-            double dPhi = TVector2::Phi_mpi_pi( mergePhi->phi() - cell->phi());
-            double ratio = mergePhi->pt()*m_caloWeightTool->wtCell(mergePhi)/(cell->pt()*m_caloWeightTool->wtCell(cell) + mergePhi->pt()*m_caloWeightTool->wtCell(mergePhi));
-            float phi = cell->phi()+dPhi*ratio;
-            float pt = cell->pt()*m_caloWeightTool->wtCell(cell)+mergePhi->pt()*m_caloWeightTool->wtCell(mergePhi);
-
-            shot->setP4( (float) pt, (float) cell->eta(), (float) phi, (float) cell->m());
-        }
-        else shot->setP4( (float) cell->pt()*m_caloWeightTool->wtCell(cell), (float) cell->eta(), (float) cell->phi(), (float) cell->m());
-        
-        shot->setBDTPi0Score( (float) -9999. );
-        shot->setCharge( 0. );
-        double center_mag = 0.0;
-        shot->setCenterMag( (float) center_mag);
-        
-        ElementLink<xAOD::CaloClusterContainer> clusElementLink;
-        clusElementLink.toContainedElement( tauShotClusterContainer, shotCluster );
-        shot->setClusterLink( clusElementLink );
-        shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_nCellsInEta, m_nCellsInEta);
-        shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHash);
-
-        // Get cell block for variable calculations
-        std::vector<std::vector<const CaloCell*> > cellBlock = TauShotVariableHelpers::getCellBlock(shot, m_calo_id);
-
-        // Some DEBUG statements
-        if (msgLvl(MSG::DEBUG)) { 
-          if(cell->pt()*m_caloWeightTool->wtCell(cell)>300){
-            ATH_MSG_DEBUG("New shot. \t block size phi = " << cellBlock.size() << " \t block size eta = " << cellBlock.at(0).size() << "\t shot->pt() = " << shot->pt());
-            for(unsigned iCellPhi = 0; iCellPhi<cellBlock.size();++iCellPhi){
-              for(unsigned iCellEta = 0; iCellEta<cellBlock.at(iCellPhi).size();++iCellEta){
-                const CaloCell* cell = cellBlock.at(iCellPhi).at(iCellEta);
-                if( cell==NULL ) ATH_MSG_DEBUG("Cell" << iCellPhi << iCellEta << ": \t NULL" );
-                else            ATH_MSG_DEBUG("Cell"<<iCellPhi<<iCellEta<<":\tPt = "<< cell->pt()*m_caloWeightTool->wtCell(cell)<<"\teta = "<<cell->eta()<<"\tphi = "<<cell->phi());
-              }
-            }
-          }
-        }
-        // Get eta bin
-        int etaBin = getEtaBin(cell->eta());
-
-        // set variables used for photon counting
-        float pt1=TauShotVariableHelpers::ptWindow(cellBlock,1,m_caloWeightTool);
-        float pt3=TauShotVariableHelpers::ptWindow(cellBlock,3,m_caloWeightTool);
-        float pt5=TauShotVariableHelpers::ptWindow(cellBlock,5,m_caloWeightTool);
-
-        // Calculate number of photons in shot
-        int nPhotons = getNPhotons(etaBin, pt1);
-
-        // Set variables in shot PFO
-        shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt1, pt1);
-        shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt3, pt3);
-        shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt5, pt5);
-        shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_nPhotons, nPhotons);
-
-        // remove shot(s) from list
-	std::vector<const CaloCell*>::iterator cellItrNonConst;
-        cellItrNonConst = std::find(seedCells.begin(),seedCells.end(),cell);
-        seedCells.erase(cellItrNonConst);
-        if( mergePhi ){
-            cellItrNonConst = std::find(seedCells.begin(),seedCells.end(),mergePhi);
-            seedCells.erase(cellItrNonConst);
-        }
-    } // seed cells
+    float pt3 = TauShotVariableHelpers::ptWindow(cellBlock, 3, m_caloWeightTool);
+    shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt3, pt3);
     
+    float pt5 = TauShotVariableHelpers::ptWindow(cellBlock, 5, m_caloWeightTool);
+    shot->setAttribute<float>(xAOD::PFODetails::PFOAttributes::tauShots_pt5, pt5);
     
-    return StatusCode::SUCCESS;
+    int nPhotons = getNPhotons(cell->eta(), pt1);
+    shot->setAttribute<int>(xAOD::PFODetails::PFOAttributes::tauShots_nPhotons, nPhotons);
+
+    // Add Element link to the shot PFO container
+    ElementLink<xAOD::PFOContainer> PFOElementLink;
+    PFOElementLink.toContainedElement(shotPFOContainer, shot);
+    tau.addShotPFOLink(PFOElementLink);
+    
+    // Remove used cells from list
+    std::vector<const CaloCell*>::iterator cellItrNonConst;
+    auto cellIndex = std::find(seedCells.begin(), seedCells.end(), cell);
+    seedCells.erase(cellIndex);
+    if (phiNeigCell) {
+      cellIndex = std::find(seedCells.begin(), seedCells.end(), phiNeigCell);
+      seedCells.erase(cellIndex);
+    }
+  } // Loop over seed cells
+  
+  return StatusCode::SUCCESS;
 }
 
-//______________________________________________________________________________
-std::vector<const CaloCell*> TauShotFinder::getNeighbours(const CaloCellContainer* pCellContainer, 
-							  const CaloCell* cell, 
-							  int maxDepth) const
-{
-    std::vector<const CaloCell*> cells;
-    this->addNeighbours(pCellContainer,cell,cells,0,maxDepth,true);  //next
-    this->addNeighbours(pCellContainer,cell,cells,0,maxDepth,false); //prev
-    return cells; 
+
+
+int TauShotFinder::getEtaBin(float eta) const {
+  float absEta=std::abs(eta);
+  
+  if (absEta < 0.80) {
+    return 0; // Central Barrel
+  }
+  if (absEta<1.39) {
+    return 1; // Outer Barrel
+  }
+  if (absEta<1.51) {
+    return 2; // Crack region
+  }
+  if (absEta<1.80) {
+    return 3; // Endcap, fine granularity
+  }
+  return 4; // ndcap, coarse granularity
 }
 
-//______________________________________________________________________________
-void TauShotFinder::addNeighbours(const CaloCellContainer* pCellContainer,
-                                  const CaloCell* cell, 
-                                  std::vector<const CaloCell*>& cells,
-                                  int depth,
-                                  int maxDepth,
-                                  bool next) const
-{
-    depth++; 
-    if( depth > maxDepth ) return;
 
+
+int TauShotFinder::getNPhotons(float eta, float energy) const {
+  int etaBin = getEtaBin(eta);
+  
+  // No photons in crack region
+  if(etaBin==2) return 0;
+
+  const std::vector<float>& minPtCut = m_minPtCut.value();
+  const std::vector<float>& doubleShotCut = m_doubleShotCut.value();
+  ATH_MSG_DEBUG("etaBin = " << etaBin  << ", energy = " << energy);
+  ATH_MSG_DEBUG("MinPtCut: " << minPtCut.at(etaBin) << "DoubleShotCut: " << doubleShotCut.at(etaBin));
+
+  if (energy < minPtCut.at(etaBin)) return 0;
+  if (energy > doubleShotCut.at(etaBin)) return 2;
+  return 1;
+}
+
+
+
+std::vector<const CaloCell*> TauShotFinder::selectCells(const xAOD::TauJet& tau,
+                                                        const CaloCellContainer& cellContainer) const {
+  // Get only cells within dR < 0.4
+  // -- TODO: change the hardcoded 0.4
+  std::vector<CaloCell_ID::SUBCALO> emSubCaloBlocks;
+  emSubCaloBlocks.push_back(CaloCell_ID::LAREM);
+  boost::scoped_ptr<CaloCellList> cellList(new CaloCellList(&cellContainer,emSubCaloBlocks)); 
+  // -- FIXME: tau p4 is corrected to point at tau vertex, but the cells are not 
+  cellList->select(tau.eta(), tau.phi(), 0.4); 
+
+  std::vector<const CaloCell*> cells;
+  for (const CaloCell* cell : *cellList) {
+    // Require cells above 100 MeV
+    // FIXME: cells are not corrected to point at tau vertex
+    if (cell->pt() * m_caloWeightTool->wtCell(cell) < 100.) continue;
+    
+    // Require cells in EM1 
+    int sampling = cell->caloDDE()->getSampling();
+    if( !( sampling == CaloCell_ID::EMB1 || sampling == CaloCell_ID::EME1 ) ) continue;
+    
+    cells.push_back(cell);
+  }
+
+  return cells;
+} 
+
+
+
+std::vector<const CaloCell*> TauShotFinder::selectSeedCells(const xAOD::TauJet& tau,
+                                                            const CaloCellContainer& cellContainer) const {
+
+  // Apply pre-selection of the cells
+  std::vector<const CaloCell*> cells = selectCells(tau, cellContainer);
+  std::sort(cells.begin(),cells.end(),ptSort(*this));
+
+  std::vector<const CaloCell*> seedCells;  
+  std::set<IdentifierHash> seedCellHashes;
+
+  // Loop the pt sorted cells, and select the seed cells
+  for (const CaloCell* cell: cells) {
     const IdentifierHash cellHash = cell->caloDDE()->calo_hash();
-    std::vector<IdentifierHash> neigHashes;
-    if( next )
-        m_calo_id->get_neighbours(cellHash,LArNeighbours::nextInEta,neigHashes);
-    else
-        m_calo_id->get_neighbours(cellHash,LArNeighbours::prevInEta,neigHashes);
+
+    std::vector<IdentifierHash> nextEtaHashes;
+    m_calo_id->get_neighbours(cellHash, LArNeighbours::nextInEta, nextEtaHashes);
+    std::vector<IdentifierHash> prevEtaHashes;
+    m_calo_id->get_neighbours(cellHash, LArNeighbours::prevInEta, prevEtaHashes);
+   
+    std::vector<IdentifierHash> neighHashes = nextEtaHashes; 
+    neighHashes.insert(neighHashes.end(),prevEtaHashes.begin(),prevEtaHashes.end()); 
+   
+    // Check whether it is a seed cell
+    bool status = true;
+    for (const IdentifierHash& neighHash : neighHashes) {
+      // Seed cells must not have seed cells as neighbours
+      // TODO: maybe this requirement can be removed
+      if (seedCellHashes.find(neighHash) != seedCellHashes.end()) {
+        status = false;
+        break;
+      }
+      
+      // Pt of seed cells must be larger than neighbours'
+      const CaloCell* neighCell = cellContainer.findCell(neighHash);
+      if (!neighCell) continue;
+      if (neighCell->pt() * m_caloWeightTool->wtCell(neighCell) >= cell->pt() * m_caloWeightTool->wtCell(cell)) {
+        status = false;
+        break;
+      }
+    } // End of the loop of neighbour cells
     
-    std::vector<IdentifierHash>::iterator hashItr = neigHashes.begin();
-    for( ; hashItr!=neigHashes.end(); ++hashItr ){
-        const CaloCell* newCell = pCellContainer->findCell(*hashItr);
-        if(!newCell)continue;
-        cells.push_back(newCell);
-        this->addNeighbours(pCellContainer,newCell,cells,depth,maxDepth,next);
-        // no EM1 cell should have more than one neighbor. Just add this neigbor for now
-        // FIXME: Check whether it happens that a cell has > 1 neighbors
-        break; 
-    } 
+    if (!status) continue; 
+    
+    seedCells.push_back(cell); 
+    seedCellHashes.insert(cellHash);
+  } // End of the loop of cells
+
+  return seedCells; 
+} 
+
+
+
+bool TauShotFinder::isPhiNeighbour(IdentifierHash cell1Hash, IdentifierHash cell2Hash) const {
+  std::vector<IdentifierHash> neigHashes;
+ 
+  // Next cell in phi direction 
+  m_calo_id->get_neighbours(cell1Hash,LArNeighbours::nextInPhi,neigHashes);
+  if (neigHashes.size() > 1) {
+    ATH_MSG_WARNING(cell1Hash << " has " << neigHashes.size()  <<  " neighbours in the next phi direction !"); 
+  }
+  if (std::find(neigHashes.begin(), neigHashes.end(), cell2Hash) != neigHashes.end()) {
+    return true;
+  }
+  
+  // Previous cell in phi direction
+  m_calo_id->get_neighbours(cell1Hash,LArNeighbours::prevInPhi,neigHashes);
+  if (neigHashes.size() > 1) {
+    ATH_MSG_WARNING(cell1Hash << " has " << neigHashes.size()  <<  " neighbours in the previous phi direction !"); 
+  }
+  if (std::find(neigHashes.begin(), neigHashes.end(), cell2Hash) != neigHashes.end()) {
+    return true;
+  }
+
+  return false;
 }
 
-//______________________________________________________________________________
-bool TauShotFinder::isPhiNeighbour(IdentifierHash cell1Hash, IdentifierHash cell2Hash, bool next) const{
-    std::vector<IdentifierHash> neigHashes;
-    if( next ) m_calo_id->get_neighbours(cell1Hash,LArNeighbours::nextInPhi,neigHashes);
-    else       m_calo_id->get_neighbours(cell1Hash,LArNeighbours::prevInPhi,neigHashes);
-    std::vector<IdentifierHash>::iterator itr = neigHashes.begin();
-    for( ; itr!=neigHashes.end(); ++itr ){
-        if(cell2Hash == (*itr)) return true;
-    } 
-    return false;
+
+
+const CaloCell* TauShotFinder::getPhiNeighbour(const CaloCell& seedCell, 
+                                               const std::vector<const CaloCell*>& seedCells) const {
+
+  const IdentifierHash seedHash = seedCell.caloDDE()->calo_hash();
+ 
+  // Obtain the neighbour cells in the phi direction 
+  std::vector<const CaloCell*> neighCells;
+  for (const CaloCell* neighCell : seedCells) {
+    if (neighCell == &seedCell) continue;
+    
+    IdentifierHash neighHash = neighCell->caloDDE()->calo_hash();
+    if (this->isPhiNeighbour(seedHash, neighHash)) {
+      neighCells.push_back(neighCell);
+    }
+  }
+  std::sort(neighCells.begin(),neighCells.end(),ptSort(*this)); 
+
+  // Select the one with largest pt
+  const CaloCell* phiNeigCell = nullptr;
+  if (neighCells.size() >= 1) {
+    phiNeigCell = neighCells[0];
+  } 
+
+  return phiNeigCell;
 }
 
-//______________________________________________________________________________
-float TauShotFinder::getEtaBin(float seedEta) const {
-    float absSeedEta=std::abs(seedEta);
-    if(absSeedEta < 0.80)      return 0; // Central Barrel
-    else if(absSeedEta<1.39) return 1; // Outer Barrel
-    else if(absSeedEta<1.51) return 2; // crack
-    else if(absSeedEta<1.80) return 3; // endcap, fine granularity
-    else return 4;                           // endcap, coarse granularity
+
+
+std::vector<const CaloCell*> TauShotFinder::getEtaNeighbours(const CaloCell& cell,
+                                                             const CaloCellContainer& cellContainer, 
+							                                 int maxDepth) const {
+    std::vector<const CaloCell*> cells;
+    
+    // Add neighbours in next eta direction
+    this->addEtaNeighbours(cell, cellContainer, cells, 0, maxDepth, true);
+    // Add neighbours in previous eta direction
+    this->addEtaNeighbours(cell, cellContainer, cells, 0, maxDepth, false);
+
+    return cells; 
 }
 
-//______________________________________________________________________________
-float TauShotFinder::getNPhotons(int etaBin, float seedEnergy) const {
-    // no photon counting in crack region, e.g. [1.39, 1.51]
-    if(etaBin==2) return 0;
 
-    const std::vector<float>& minPtCut = m_minPtCut.value();
-    const std::vector<float>& autoDoubleShotCut = m_autoDoubleShotCut.value();
-    ATH_MSG_DEBUG("etaBin = " << etaBin  << ", seedEnergy = " << seedEnergy);
-    ATH_MSG_DEBUG("MinPtCut: " << minPtCut.at(etaBin) << "DoubleShotCut: " << autoDoubleShotCut.at(etaBin));
 
-    if( seedEnergy < minPtCut.at(etaBin) ) return 0;
-    if( seedEnergy > autoDoubleShotCut.at(etaBin) ) return 2;
-    return 1;
+void TauShotFinder::addEtaNeighbours(const CaloCell& cell,
+                                     const CaloCellContainer& cellContainer,
+                                     std::vector<const CaloCell*>& cells,
+                                     int depth,
+                                     int maxDepth,
+                                     bool next) const {
+  ++depth; 
+  
+  if (depth > maxDepth) return;
+
+  const IdentifierHash cellHash = cell.caloDDE()->calo_hash();
+  
+  std::vector<IdentifierHash> neigHashes;
+  if (next) {
+    m_calo_id->get_neighbours(cellHash,LArNeighbours::nextInEta,neigHashes);
+  }
+  else {
+    m_calo_id->get_neighbours(cellHash,LArNeighbours::prevInEta,neigHashes);
+  }
+
+  for (const IdentifierHash& hash : neigHashes) {
+    const CaloCell* newCell = cellContainer.findCell(hash);
+    
+    if (!newCell) continue;
+    
+    cells.push_back(newCell);
+    this->addEtaNeighbours(*newCell, cellContainer, cells, depth, maxDepth, next);
+  
+    if (neigHashes.size() > 1) {
+      ATH_MSG_WARNING(cellHash << " has " << neigHashes.size()  <<  " neighbours in the eta direction !"); 
+      break; 
+    }
+  } 
 }
 
-//______________________________________________________________________________
-// some really slick c++ way of doing sort (since we need to use the member m_caloWeightTool)
+
+
+xAOD::CaloCluster* TauShotFinder::createShotCluster(const CaloCell* cell, 
+                                                    const CaloCell* phiNeigCell, 
+                                                    const CaloCellContainer& cellContainer) const {
+    
+  xAOD::CaloCluster* shotCluster = CaloClusterStoreHelper::makeCluster(&cellContainer);
+  
+  int maxDepth = (m_nCellsInEta - 1) / 2;
+
+  std::vector<const CaloCell*> windowNeighbours = this->getEtaNeighbours(*cell, cellContainer, maxDepth);
+  if (phiNeigCell) {
+    std::vector<const CaloCell*> mergeCells = this->getEtaNeighbours(*phiNeigCell, cellContainer, maxDepth);
+    windowNeighbours.push_back(phiNeigCell);
+    windowNeighbours.insert(windowNeighbours.end(), mergeCells.begin(), mergeCells.end());
+  }
+
+  shotCluster->getOwnCellLinks()->reserve(windowNeighbours.size()+1);
+  const IdentifierHash seedHash = cell->caloDDE()->calo_hash();
+  shotCluster->addCell(cellContainer.findIndex(seedHash), 1.);
+  
+  for (const CaloCell* cell : windowNeighbours) {
+    shotCluster->addCell(cellContainer.findIndex(cell->caloDDE()->calo_hash()), 1.0);
+  }
+
+  CaloClusterKineHelper::calculateKine(shotCluster,true,true);
+
+  return shotCluster;
+} 
+
+
+
 TauShotFinder::ptSort::ptSort( const TauShotFinder& info ) : m_info(info) { } 
-bool TauShotFinder::ptSort::operator()( const CaloCell* c1, const CaloCell* c2 ){
-     return  c1->pt()*m_info.m_caloWeightTool->wtCell(c1) > c2->pt()*m_info.m_caloWeightTool->wtCell(c2);  
+bool TauShotFinder::ptSort::operator()( const CaloCell* cell1, const CaloCell* cell2 ){
+  double pt1 = cell1->pt()*m_info.m_caloWeightTool->wtCell(cell1);
+  double pt2 = cell2->pt()*m_info.m_caloWeightTool->wtCell(cell2);
+  return pt1 > pt2;  
 }
 
 #endif
diff --git a/Reconstruction/tauRecTools/src/TauShotFinder.h b/Reconstruction/tauRecTools/src/TauShotFinder.h
index 6273fc619692164dbf2885e079f0f6b2b258ac24..fde52480403aa80dc4e9941b7eb382d32cb59b3d 100644
--- a/Reconstruction/tauRecTools/src/TauShotFinder.h
+++ b/Reconstruction/tauRecTools/src/TauShotFinder.h
@@ -5,69 +5,104 @@
 #ifndef TAUREC_TAUSHOTFINDER_H
 #define	TAUREC_TAUSHOTFINDER_H
 
-#include "GaudiKernel/ToolHandle.h"
 #include "tauRecTools/TauRecToolBase.h"
+
 #include "xAODPFlow/PFOAuxContainer.h"
 #include "xAODCaloEvent/CaloClusterAuxContainer.h"
 #include "CaloInterface/IHadronicCalibrationTool.h"
 
-class CaloDetDescrManager;
+#include "GaudiKernel/ToolHandle.h"
+
+/**
+ * @brief Construct the shot candidates
+ *        1. select seed cells used to construct the shot candidates 
+ *        2. create the shot PFOs by merging the neighbour seed cells in phi direction
+ *        3. the cluster of the shot PFO contains cells in a window of 2 x NCellsInEta
+ *
+ * @author Will Davey <will.davey@cern.ch> 
+ * @author Benedict Winter <benedict.tobias.winter@cern.ch>
+ * @author Stephanie Yuen <stephanie.yuen@cern.ch> 
+ */
+
 class CaloCell_ID;
 
 class TauShotFinder : public TauRecToolBase {
+
 public:
-    TauShotFinder(const std::string& name);
-    ASG_TOOL_CLASS2(TauShotFinder, TauRecToolBase, ITauToolBase);
-    virtual ~TauShotFinder();
+  
+  ASG_TOOL_CLASS2(TauShotFinder, TauRecToolBase, ITauToolBase);
+
+  TauShotFinder(const std::string& name);
+  virtual ~TauShotFinder() = default;
 
-    virtual StatusCode initialize() override;
-    virtual StatusCode executeShotFinder(xAOD::TauJet& pTau, xAOD::CaloClusterContainer& tauShotCaloClusContainer, xAOD::PFOContainer& tauShotPFOContainer) const override;
+  virtual StatusCode initialize() override;
+  virtual StatusCode executeShotFinder(xAOD::TauJet& pTau, xAOD::CaloClusterContainer& tauShotCaloClusContainer, xAOD::PFOContainer& tauShotPFOContainer) const override;
 
 private:
 
-    /** @brief tool handles */
-    ToolHandle<IHadronicCalibrationTool> m_caloWeightTool {this, "CaloWeightTool", "H1WeightToolCSC12Generic"};
-    
-    /** @brief new shot PFO container and name */
-    /** @brief calo cell navigation */
-    const CaloCell_ID* m_calo_id = NULL;
-
-    /** @brief Thanks C++ for ruining my day */
-    struct ptSort
-    { 
-         ptSort( const TauShotFinder& info );
-         const TauShotFinder& m_info;
-         bool operator()( const CaloCell* c1, const CaloCell* c2 );
-    };
-
-    /** @brief get neighbour cells */
-    std::vector<const CaloCell*> getNeighbours(const CaloCellContainer*,const CaloCell*,int /*maxDepth*/) const;
-
-    void addNeighbours(const CaloCellContainer*,
-                       const CaloCell* cell,
-                       std::vector<const CaloCell*>& cells,
-                       int depth,
-                       int maxDepth,
-                       bool next) const;
-
-    bool isPhiNeighbour(IdentifierHash cell1Hash, IdentifierHash cell2Hash, bool next) const;
-
-    /** @brief get eta bin */
-    float getEtaBin(float /*seedEta*/) const;
+  struct ptSort
+  { 
+    ptSort( const TauShotFinder& info );
+    const TauShotFinder& m_info;
+    bool operator()( const CaloCell* c1, const CaloCell* c2 );
+  };
+
+  /** @brief Apply preselection of the cells 
+   *         Cells within dR < 0.4, in EM1, and pt > 100 MeV are selected
+   */
+  std::vector<const CaloCell*> selectCells(const xAOD::TauJet& tau, const CaloCellContainer& cellContainer) const;
+
+  /** @brief Select the seed cells used to construct the shot 
+   *         Cells must sastisfy:
+   *         1. pre-selction: dR < 0.4, in EM1, and pt > 100 MeV
+   *         2. have largest pt among the neighbours in the eta direction 
+   *         3. no other seed cells as neighbors in the eta direction
+   */
+  std::vector<const CaloCell*> selectSeedCells(const xAOD::TauJet& tau, const CaloCellContainer& cellContainer) const;
+
+  /** @brief Check whether two cells are neighbours in the phi direction */
+  bool isPhiNeighbour(IdentifierHash cell1Hash, IdentifierHash cell2Hash) const;
+
+  /** @brief Get the hottest neighbour cell in the phi direction */ 
+  const CaloCell* getPhiNeighbour(const CaloCell& seedCell, const std::vector<const CaloCell*>& seedCells) const;
+  
+  /** @brief Get neighbour cells in the eta direction */
+  std::vector<const CaloCell*> getEtaNeighbours(const CaloCell& cell, const CaloCellContainer& cellContainer, int maxDepth) const;
+
+  /** @brief Get neighbour cells in the eta direction */
+  void addEtaNeighbours(const CaloCell& cell,
+                        const CaloCellContainer& cellContainer,
+                        std::vector<const CaloCell*>& cells,
+                        int depth,
+                        int maxDepth,
+                        bool next) const;
+
+  /** @brief Create the shot cluster 
+   *         Shot cluster contains 5x1 cells from the seed cell and hottestneighbour
+   *         cell in the phi direction
+   */
+  xAOD::CaloCluster* createShotCluster(const CaloCell* cell,
+                                       const CaloCell* phiNeighCell,
+                                       const CaloCellContainer& cellContainer) const;
+
+  /** @brief Get eta bin */
+  int getEtaBin(float eta) const;
+
+  /** @brief Get NPhotons in shot */
+  int getNPhotons(float eta, float energy) const;
+
+  Gaudi::Property<int> m_nCellsInEta {this, "NCellsInEta"};
+  Gaudi::Property<std::vector<float>> m_minPtCut {this, "MinPtCut"};
+  Gaudi::Property<std::vector<float>> m_doubleShotCut {this, "AutoDoubleShotCut"};
+
+  SG::ReadHandleKey<CaloCellContainer> m_caloCellInputContainer{this,"Key_caloCellInputContainer", "AllCalo", "input vertex container key"};
+  SG::WriteHandleKey<xAOD::PFOContainer> m_tauPFOOutputContainer{this,"Key_tauPFOOutputContainer", "TauShotParticleFlowObjects", "tau pfo out key"};
   
-    /** @brief get NPhotons in shot */
-    float getNPhotons(int /*etaBin*/, 
-                      float /*seedEnergy*/) const;
-
-    // number of cells in eta
-    Gaudi::Property<int> m_nCellsInEta {this, "NCellsInEta"};
-    Gaudi::Property<std::vector<float>> m_minPtCut {this, "MinPtCut"};
-    Gaudi::Property<std::vector<float>> m_autoDoubleShotCut {this, "AutoDoubleShotCut"};
+  ToolHandle<IHadronicCalibrationTool> m_caloWeightTool {this, "CaloWeightTool", "H1WeightToolCSC12Generic"};
   
-    SG::ReadHandleKey<CaloCellContainer> m_caloCellInputContainer{this,"Key_caloCellInputContainer", "AllCalo", "input vertex container key"};
-    SG::WriteHandleKey<xAOD::PFOContainer> m_tauPFOOutputContainer{this,"Key_tauPFOOutputContainer", "TauShotParticleFlowObjects", "tau pfo out key"};
-    
+  /// calo cell navigation
+  const CaloCell_ID* m_calo_id = nullptr;
+
 };
 
 #endif	/* TAUSHOTFINDER_H */
-
diff --git a/Reconstruction/tauRecTools/src/TauShotVariableHelpers.cxx b/Reconstruction/tauRecTools/src/TauShotVariableHelpers.cxx
index 3b2ef8c1dc49c3eacaa6f04b1d7e45d8362d5d03..d2e1021f2efa20e3a2b0eab39d609772e29e2146 100644
--- a/Reconstruction/tauRecTools/src/TauShotVariableHelpers.cxx
+++ b/Reconstruction/tauRecTools/src/TauShotVariableHelpers.cxx
@@ -3,6 +3,9 @@
 */
 
 #ifndef XAOD_ANALYSIS
+
+#include "TauShotVariableHelpers.h"
+
 /**
  * @brief implementation of photon shot variable calculation 
  * 
@@ -11,350 +14,174 @@
  * @author Stephanie Yuen <stephanie.yuen@cern.ch> 
  */
 
-#include "TauShotVariableHelpers.h"
+namespace TauShotVariableHelpers {
 
-using xAOD::PFO;
-using std::vector;
+ANA_MSG_SOURCE(msgTauShotVariableHelpers, "TauShotVariableHelpers")
 
-namespace TauShotVariableHelpers {
-    std::vector<std::vector<const CaloCell*> > getCellBlock(xAOD::PFO* shot, const CaloCell_ID* calo_id){
-        std::vector<std::vector<const CaloCell*> > cellVector;
-        std::vector<const CaloCell*> oneEtaLayer;
-        int nCellsInEta = 0;
-        if( shot->attribute(xAOD::PFODetails::PFOAttributes::tauShots_nCellsInEta, nCellsInEta) == false) {
-            std::cout << "WARNING: Couldn't find nCellsInEta. Return empty cell block." << std::endl;
-            return cellVector;
-        }
-        int seedHash = 0;
-        if( shot->attribute(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHash) == false) {
-            std::cout << "WARNING: Couldn't find seed hash. Return empty cell block." << std::endl;
-            return cellVector;
-        }
-        for(int iCell=0;iCell<nCellsInEta;++iCell) oneEtaLayer.push_back(NULL);
-        // have two layers in phi
-        cellVector.push_back(oneEtaLayer);
-        cellVector.push_back(oneEtaLayer);
-        // get cluster from shot
-        const xAOD::CaloCluster* cluster = shot->cluster(0);
-        const CaloClusterCellLink* theCellLink = cluster->getCellLinks();
-        CaloClusterCellLink::const_iterator cellItr  = theCellLink->begin();
-        CaloClusterCellLink::const_iterator cellItrE = theCellLink->end();
 
-        // get seed cell from shot cluster
-        const CaloCell* seedCell=NULL;
-        for(;cellItr!=cellItrE;++cellItr){
-            if((*cellItr)->caloDDE()->calo_hash()!=(unsigned) seedHash) continue;
-            seedCell = *cellItr;
-            break;
-        }
-        if(seedCell==NULL){
-          std::cout << "WARNING: Couldn't find seed cell in shot cluster. Return empty cell block." << std::endl;
-          return cellVector;
-        }
-        
-        // get merged cell in phi. Keep NULL if shot is not merged across phi
-        const CaloCell* mergedCell = NULL;
-        std::vector<IdentifierHash> nextInPhi;
-        std::vector<IdentifierHash> prevInPhi;
-        calo_id->get_neighbours(seedCell->caloDDE()->calo_hash(),LArNeighbours::nextInPhi,nextInPhi);
-        calo_id->get_neighbours(seedCell->caloDDE()->calo_hash(),LArNeighbours::prevInPhi,prevInPhi);
-        for(cellItr=theCellLink->begin();cellItr!=cellItrE;++cellItr){
-            std::vector<IdentifierHash>::iterator itr = nextInPhi.begin();
-            for( ; itr!=nextInPhi.end(); ++itr ){
-                if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                mergedCell = (*cellItr);
-                break;
-            }
-            if(mergedCell!=NULL) break;
-            itr = prevInPhi.begin();
-            for( ; itr!=prevInPhi.end(); ++itr ){
-                if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                mergedCell = (*cellItr);
-                break;
-            }
-            if(mergedCell!=NULL) break;
-        }
-        // store cells in the eta layer, which contains the seed cell
-        int nCellsFromSeed = 1;
-        const CaloCell* lastCell = seedCell;
-        cellVector.at(0).at(nCellsInEta/2) = seedCell; // store seed cell
-        std::vector<IdentifierHash> next;
-        while(lastCell!=NULL && nCellsFromSeed<nCellsInEta/2+1){
-            calo_id->get_neighbours(lastCell->caloDDE()->calo_hash(),LArNeighbours::nextInEta,next);
-            lastCell = NULL;
-            for(cellItr=theCellLink->begin();cellItr!=cellItrE;++cellItr){
-                std::vector<IdentifierHash>::iterator itr = next.begin();
-                for( ; itr!=next.end(); ++itr ){
-                    if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                    cellVector.at(0).at(nCellsInEta/2+nCellsFromSeed) = (*cellItr);
-                    lastCell = (*cellItr);
-                }
-            }
-            nCellsFromSeed++;
-        }
-        nCellsFromSeed = 1;
-        lastCell = seedCell;
-        while(lastCell!=NULL && nCellsFromSeed<nCellsInEta/2+1){
-            calo_id->get_neighbours(lastCell->caloDDE()->calo_hash(),LArNeighbours::prevInEta,next);
-            lastCell = NULL;
-            for(cellItr=theCellLink->begin();cellItr!=cellItrE;++cellItr){
-                std::vector<IdentifierHash>::iterator itr = next.begin();
-                for( ; itr!=next.end(); ++itr ){
-                    if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                    cellVector.at(0).at(nCellsInEta/2-nCellsFromSeed) = (*cellItr);
-                    lastCell = (*cellItr);
-                }
-            }
-            nCellsFromSeed++;
-        }
-        // store cells in the eta layer, which contains the merged cell
-        int nCellsFromMerged = 1;
-        lastCell = mergedCell; // is NULL if shot is not merged
-        cellVector.at(1).at(nCellsInEta/2) = mergedCell; // store merged cell
-        while(lastCell!=NULL && nCellsFromMerged<nCellsInEta/2+1){
-            calo_id->get_neighbours(lastCell->caloDDE()->calo_hash(),LArNeighbours::nextInEta,next);
-            lastCell = NULL;
-            for(cellItr=theCellLink->begin();cellItr!=cellItrE;++cellItr){
-                std::vector<IdentifierHash>::iterator itr = next.begin();
-                for( ; itr!=next.end(); ++itr ){
-                    if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                    cellVector.at(1).at(nCellsInEta/2+nCellsFromMerged) = (*cellItr);
-                    lastCell = (*cellItr);
-                }
-            }
-            nCellsFromMerged++;
-        }
-        nCellsFromMerged = 1;
-        lastCell = mergedCell;
-        while(lastCell!=NULL && nCellsFromMerged<nCellsInEta/2+1){
-            calo_id->get_neighbours(lastCell->caloDDE()->calo_hash(),LArNeighbours::prevInEta,next);
-            lastCell = NULL;
-            for(cellItr=theCellLink->begin();cellItr!=cellItrE;++cellItr){
-                std::vector<IdentifierHash>::iterator itr = next.begin();
-                for( ; itr!=next.end(); ++itr ){
-                    if((*cellItr)->caloDDE()->calo_hash() != (*itr)) continue;
-                    cellVector.at(1).at(nCellsInEta/2-nCellsFromMerged) = (*cellItr);
-                    lastCell = (*cellItr);
-                }
-            }
-            nCellsFromMerged++;
-        }
-        return cellVector;
-    
-    }
+const CaloCell* getNeighbour(const CaloCell* cell, 
+                             const CaloClusterCellLink& links, 
+                             const CaloCell_ID* calo_id, 
+                             const LArNeighbours::neighbourOption& option) {
+  const CaloCell* neigCell = nullptr;
 
+  std::vector<IdentifierHash> neighHashes;
+  calo_id->get_neighbours(cell->caloDDE()->calo_hash(), option, neighHashes);
+  
+  // Loop all the cells, and find the required neighbour cell
+  for (const auto& cell : links) {
+    const IdentifierHash& cellHash = cell->caloDDE()->calo_hash();
 
-    float mean_eta(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        float sumEta=0.;
-        float sumWeight=0.;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            vector<const CaloCell*>::iterator itrEta = itrPhi->begin();
-            for( ; itrEta!=itrPhi->end(); ++itrEta ){
-                if((*itrEta) == NULL) continue;
-                sumWeight += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta);
-                sumEta    += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta) * (*itrEta)->eta();
-            }
-        }
-        if(sumWeight<=0.) return -99999.;
-        return sumEta/sumWeight;
+    // Check whether the cell is a neighbour cell 
+    for (const IdentifierHash& neighHash : neighHashes) {
+      if (cellHash == neighHash) {
+        neigCell = cell;
+        return neigCell;
+      }
     }
+  }
 
-    float mean_pt(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        float sumPt=0.;
-        int nCells = 0;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            vector<const CaloCell*>::iterator itrEta = itrPhi->begin();
-            for( ; itrEta!=itrPhi->end(); ++itrEta ){
-                if((*itrEta) == NULL) continue;
-                sumPt  += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta);
-                nCells ++;
-            }
-        }
-        if(nCells==0) return -99999.;
-        return sumPt/nCells;
-    }
+  return neigCell;
+}
 
-    float ptWindow(vector<vector<const CaloCell*> > shotCells, int windowSize, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        // window size should be odd and noti be larger than eta window of shotCells
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        if( windowSize%2!=1 )        return 0.;
-        if( windowSize > nCells_eta) return 0.;
-        float ptWindow  = 0.;
-        for(int iCell = 0; iCell != nCells_eta; ++iCell ){
-	  if(std::abs(iCell-seedIndex)>windowSize/2) continue;
-            if(shotCells.at(0).at(iCell) != NULL) ptWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell) != NULL) ptWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-        }
-        return ptWindow;
-    }
 
-    float ws5(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        float sumWeight=0.;
-        float sumDev2=0.;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            for(unsigned iCell = 0; iCell != itrPhi->size(); ++iCell ){
-                if(itrPhi->at(iCell) == NULL) continue;
-                sumWeight += itrPhi->at(iCell)->pt()*caloWeightTool->wtCell(itrPhi->at(iCell));
-                sumDev2   += itrPhi->at(iCell)->pt()*caloWeightTool->wtCell(itrPhi->at(iCell)) * pow(iCell-seedIndex,2);
-            }
-        }
-        if(sumWeight<=0. || sumDev2 <0.) return -99999.;
-        return sqrt( sumDev2 / sumWeight );
+std::vector<std::vector<const CaloCell*> > getCellBlock(const xAOD::PFO& shot, const CaloCell_ID* calo_id) {
+  using namespace TauShotVariableHelpers::msgTauShotVariableHelpers; 
+
+  std::vector<std::vector<const CaloCell*>> cellBlock;
+
+  int etaSize = 0;
+  if (shot.attribute(xAOD::PFODetails::PFOAttributes::tauShots_nCellsInEta, etaSize) == false) {
+    ANA_MSG_WARNING("Couldn't find nCellsInEta. Return empty cell block.");
+    return cellBlock;
+  }
+  
+  int seedHash = 0;
+  if (shot.attribute(xAOD::PFODetails::PFOAttributes::tauShots_seedHash, seedHash) == false) {
+    ANA_MSG_WARNING("Couldn't find seed hash. Return empty cell block.");
+    return cellBlock;
+  }
+  
+  // Initialize the cell block
+  std::vector<const CaloCell*> etaLayer;
+  for (int etaIndex = 0; etaIndex < etaSize; ++ etaIndex) {
+    etaLayer.push_back(nullptr);
+  }
+  int phiSize = 2;
+  for (int phiIndex = 0; phiIndex < phiSize; ++phiIndex) {
+    cellBlock.push_back(etaLayer);
+  }
+
+  // Get seed cell from shot cluster
+  const xAOD::CaloCluster* cluster = shot.cluster(0);
+  const CaloClusterCellLink* cellLinks = cluster->getCellLinks();
+
+  const CaloCell* seedCell = nullptr;
+  for (const auto& cell : *cellLinks) {
+     if (cell->caloDDE()->calo_hash() != (unsigned) seedHash) continue;
+     seedCell = cell;
+     break;
+  }
+  if (seedCell==nullptr) {
+    ANA_MSG_WARNING("Couldn't find seed cell in shot cluster. Return empty cell block.");
+    return cellBlock;
+  }
+  int mediumEtaIndex = etaSize/2;
+  cellBlock.at(0).at(mediumEtaIndex) = seedCell;
+
+  // Obtain the neighbour cells in the eta direction
+  // -- Next in eta
+  const CaloCell* lastCell = seedCell;
+  int maxDepth = etaSize - mediumEtaIndex - 1;
+  for (int depth = 1; depth < maxDepth + 1; ++depth) {
+    lastCell = getNeighbour(lastCell, *cellLinks, calo_id, LArNeighbours::nextInEta);
+    if (lastCell != nullptr) {
+      cellBlock.at(0).at(mediumEtaIndex + depth) = lastCell;
     }
-
-    float sdevEta_WRTmean(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        float mean = mean_eta(shotCells, caloWeightTool); 
-        float sumWeight=0.;
-        float sumDev2=0.;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            vector<const CaloCell*>::iterator itrEta = itrPhi->begin();
-            for( ; itrEta!=itrPhi->end(); ++itrEta ){
-                if((*itrEta) == NULL) continue;
-                sumWeight += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta);
-                sumDev2   += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta) * pow((*itrEta)->eta() - mean,2);
-            }
-        }
-        if(sumWeight<=0. || sumDev2 <0.) return -99999.;
-        return sqrt( sumDev2 / sumWeight );
+    else {
+      break;
     }
-
-    float sdevEta_WRTmode(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        float mode = shotCells.at(0).at(seedIndex)->eta();
-        float sumWeight=0.;
-        float sumDev2=0.;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            vector<const CaloCell*>::iterator itrEta = itrPhi->begin();
-            for( ; itrEta!=itrPhi->end(); ++itrEta ){
-                if((*itrEta) == NULL) continue;
-                sumWeight += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta);
-                sumDev2   += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta) * pow((*itrEta)->eta() - mode,2);
-            }
-        }
-        if(sumWeight<=0. || sumDev2 <0.) return -99999.;
-        return sqrt( sumDev2 / sumWeight );
+  }
+
+  // -- Previous in eta
+  lastCell = seedCell;
+  for (int depth = 1; depth < maxDepth + 1; ++depth) {
+    lastCell = getNeighbour(lastCell, *cellLinks, calo_id, LArNeighbours::prevInEta);
+    if (lastCell != nullptr) {
+      cellBlock.at(0).at(mediumEtaIndex - depth) = lastCell;
     }
-
-    float sdevPt(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        float mean = mean_pt(shotCells, caloWeightTool);
-        float sumWeight=0.;
-        float sumDev2=0.;
-        vector<vector<const CaloCell*> >::iterator itrPhi = shotCells.begin();
-        for( ; itrPhi!=shotCells.end(); ++itrPhi ){
-            vector<const CaloCell*>::iterator itrEta = itrPhi->begin();
-            for( ; itrEta!=itrPhi->end(); ++itrEta ){
-                if((*itrEta) == NULL) continue;
-                sumWeight += (*itrEta)->pt()*caloWeightTool->wtCell(*itrEta);
-                sumDev2   += pow((*itrEta)->pt()*caloWeightTool->wtCell(*itrEta) - mean,2);
-            }
-        }
-        if(sumWeight<=0. || sumDev2 <0.) return -99999.;
-        return sqrt(sumDev2)/sumWeight;
+    else {
+      break;
     }
-
-    float deltaPt12_min(vector<vector<const CaloCell*> > shotCells, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        bool haveLeft  = false;
-        bool haveRight = false;
-        float deltaPt_left  = 0.;
-        float deltaPt_right = 0.;
-        if(shotCells.at(0).at(seedIndex-1)!=NULL && shotCells.at(0).at(seedIndex-2)!=NULL){
-            haveLeft  = true;
-            deltaPt_left =  shotCells.at(0).at(seedIndex-1)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(seedIndex-1))
-                           -shotCells.at(0).at(seedIndex-2)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(seedIndex-2));
-            if(shotCells.at(1).at(seedIndex-1)!=NULL && shotCells.at(1).at(seedIndex-2)!=NULL){
-                deltaPt_left += shotCells.at(1).at(seedIndex-1)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(seedIndex-1))
-                               -shotCells.at(1).at(seedIndex-2)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(seedIndex-2));
-            }
-        }
-        if(shotCells.at(0).at(seedIndex+1)!=NULL && shotCells.at(0).at(seedIndex+2)!=NULL){
-            haveRight = true;
-            deltaPt_right =  shotCells.at(0).at(seedIndex+1)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(seedIndex+1))
-                            -shotCells.at(0).at(seedIndex+2)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(seedIndex+2));
-            if(shotCells.at(1).at(seedIndex+1)!=NULL && shotCells.at(1).at(seedIndex+2)!=NULL){
-                deltaPt_right += shotCells.at(1).at(seedIndex+1)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(seedIndex+1))
-                                -shotCells.at(1).at(seedIndex+2)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(seedIndex+1));
-            }
-        }
-        if(haveLeft && haveRight) return fmin(deltaPt_left,deltaPt_right);
-        if(haveLeft)              return deltaPt_left;
-        if(haveRight)             return deltaPt_right;
-        else                      return -1.;
+  }
+
+  // Merged cell
+  const CaloCell* mergedCell = getNeighbour(seedCell, *cellLinks, calo_id, LArNeighbours::nextInPhi);
+  if (mergedCell == nullptr) {
+    mergedCell = getNeighbour(seedCell, *cellLinks, calo_id, LArNeighbours::prevInPhi);
+  }
+
+  if (mergedCell != nullptr) {
+    cellBlock.at(1).at(mediumEtaIndex) = mergedCell;
+  
+    // Obtain the neighbour cells in the eta direction
+    // -- Next in eta
+    lastCell = mergedCell;
+    for (int depth = 1; depth < maxDepth + 1; ++depth) {
+      lastCell = getNeighbour(lastCell, *cellLinks, calo_id, LArNeighbours::nextInEta);
+      if (lastCell != nullptr) {
+        cellBlock.at(1).at(mediumEtaIndex + depth) = lastCell;
+      }
+      else {
+        break;
+      }
     }
+  
+    // -- Previous in eta
+    lastCell = mergedCell;
+    for (int depth = 1; depth < maxDepth + 1; ++depth) {
+      lastCell = getNeighbour(lastCell, *cellLinks, calo_id, LArNeighbours::prevInEta);
+      if (lastCell != nullptr) {
+        cellBlock.at(1).at(mediumEtaIndex - depth) = lastCell;
+      }
+      else {
+        break;
+      }
+    }
+  } // End of mergedCell != nullptr
 
+  return cellBlock;
+}
 
-    float Fside(vector<vector<const CaloCell*> > shotCells, int largerWindow, int smallerWindow, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        // window sizes should be odd and windows should be not larger than eta window of shotCells
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        if( largerWindow%2!=1 || smallerWindow%2!=1) return 0.;
-        if( largerWindow <= smallerWindow)           return 0.;
-        if( largerWindow > nCells_eta)   return 0.;
-        float pt_largerWindow  = 0.;
-        float pt_smallerWindow = 0.;
-        for(int iCell = 0; iCell != nCells_eta; ++iCell ){
-	    if(std::abs(iCell-seedIndex)>largerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-            if(std::abs(iCell-seedIndex)>smallerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-        }
-        if(pt_smallerWindow==0.) return -99999.;
-        return (pt_largerWindow-pt_smallerWindow)/pt_smallerWindow;
-    }
 
-    float fracSide(vector<vector<const CaloCell*> > shotCells, int largerWindow, int smallerWindow, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        // window sizes should be odd and windows should be not larger than eta window of shotCells
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        if( largerWindow%2!=1 || smallerWindow%2!=1) return 0.;
-        if( largerWindow <= smallerWindow)           return 0.;
-        if( largerWindow > nCells_eta)   return 0.;
-        float pt_largerWindow  = 0.;
-        float pt_smallerWindow = 0.;
-        for(int iCell = 0; iCell != nCells_eta; ++iCell ){
-            if(std::abs(iCell-seedIndex)>largerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-            if(std::abs(iCell-seedIndex)>smallerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-        }
-        if(pt_largerWindow==0.) return -99999.;
-        return (pt_largerWindow-pt_smallerWindow)/pt_largerWindow;
-    }
 
-    float ptWindowFrac(vector<vector<const CaloCell*> > shotCells, int largerWindow, int smallerWindow, const ToolHandle<IHadronicCalibrationTool>& caloWeightTool){
-        // window sizes should be odd and windows should be not larger than eta window of shotCells
-        int nCells_eta = shotCells.at(0).size();
-        int seedIndex = nCells_eta/2;
-        if( largerWindow%2!=1 || smallerWindow%2!=1) return 0.;
-        if( largerWindow <= smallerWindow)           return 0.;
-        if( largerWindow > nCells_eta)   return 0.;
-        float pt_largerWindow  = 0.;
-        float pt_smallerWindow = 0.;
-        for(int iCell = 0; iCell != nCells_eta; ++iCell ){
-            if(std::abs(iCell-seedIndex)>largerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_largerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-            if(std::abs(iCell-seedIndex)>smallerWindow/2) continue;
-            if(shotCells.at(0).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(0).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(0).at(iCell));
-            if(shotCells.at(1).at(iCell)!=NULL) pt_smallerWindow+=shotCells.at(1).at(iCell)->pt()*caloWeightTool->wtCell(shotCells.at(1).at(iCell));
-        }
-        if(pt_largerWindow==0.) return -99999.;
-        return pt_smallerWindow/pt_largerWindow;
+float ptWindow(const std::vector<std::vector<const CaloCell*>>& shotCells, 
+               int windowSize, 
+               const ToolHandle<IHadronicCalibrationTool>& caloWeightTool) {
+  // window size should be odd and smaller than eta window of shotCells
+  if (windowSize%2 != 1) return 0.;
+  
+  int etaSize = shotCells.at(0).size();
+  if (windowSize > etaSize) return 0.;
+  
+  int seedIndex = etaSize/2;
+  int phiSize = shotCells.size();
+
+  float ptWindow  = 0.;
+  for (int etaIndex = 0; etaIndex != etaSize; ++etaIndex) {
+    if (std::abs(etaIndex-seedIndex) > windowSize/2) continue;
+    
+    for (int phiIndex = 0; phiIndex != phiSize; ++phiIndex) {
+      const CaloCell* cell = shotCells.at(phiIndex).at(etaIndex);
+      if (cell != nullptr) {
+        ptWindow += cell->pt() * caloWeightTool->wtCell(cell);
+      }     
     }
+  }
+
+  return ptWindow;
 }
 
+} // End of namespace TauShotVariableHelpers 
+
 #endif
diff --git a/Reconstruction/tauRecTools/src/TauShotVariableHelpers.h b/Reconstruction/tauRecTools/src/TauShotVariableHelpers.h
index fdc21ce85d0941f815d48d1e9de3e75c2aaa44ca..8e5f867fa6d222cb949b53ba8e38097c32a39aab 100644
--- a/Reconstruction/tauRecTools/src/TauShotVariableHelpers.h
+++ b/Reconstruction/tauRecTools/src/TauShotVariableHelpers.h
@@ -14,65 +14,33 @@
 #define TAUSHOTVARIABLEHELPERS_H
 
 #include "xAODPFlow/PFO.h"
-#include "GaudiKernel/ToolHandle.h"
 #include "CaloInterface/IHadronicCalibrationTool.h"
+#include "CaloIdentifier/LArNeighbours.h"
 
-namespace TauShotVariableHelpers {
-
-    /** @brief get cell block with (currently) 5x2 cells in correct order for variable calculations */
-    std::vector<std::vector<const CaloCell*> > getCellBlock(xAOD::PFO* shot,
-                                                            const CaloCell_ID* calo_id);
-
-    /** @brief mean eta, used by other functions */
-    float mean_eta(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                   const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
-
-    /** @brief mean pt, used by other functions */ 
-    float mean_pt(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                  const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
-
-    /** @brief pt in windows */
-    float ptWindow(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                   int /*windowSize*/, 
-                   const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
-
-    /** @brief ws5 variable (egamma) */
-    float ws5(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-	      const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
-
-    /** @brief standard deviation in eta WRT mean */
-    float sdevEta_WRTmean(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                          const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+#include "AsgMessaging/MessageCheck.h"
+#include "GaudiKernel/ToolHandle.h"
 
-    /** @brief standard deviation in eta WRT mode */
-    float sdevEta_WRTmode(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                          const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+class CaloCell_ID;
 
-    /** @brief normalized standard deviation in pt */
-    float sdevPt(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-		 const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+namespace TauShotVariableHelpers {
+  
+  ANA_MSG_HEADER(msgHelperFunction)
 
-    /** @brief pT diff b/w lead and sub-lead cell */
-    float deltaPt12_min(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                        const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+  /** @brief Obtain the required neighbour cell */
+  const CaloCell* getNeighbour(const CaloCell* cell,
+                               const CaloClusterCellLink& links,
+                               const CaloCell_ID* calo_id,
+                               const LArNeighbours::neighbourOption& option);
 
-    /** @brief Fside variable (egamma) */
-    float Fside(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                int /*largerWindow*/, 
-                int /*smallerWindow*/, 
-                const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+  /** @brief Get cell block with (currently) 2 x 5 cells in correct order for variable calculations */
+  std::vector<std::vector<const CaloCell*>> getCellBlock(const xAOD::PFO& shot,
+                                                         const CaloCell_ID* calo_id);
 
-    /** @brief similar than Fside but in unit of eta instead of number of cells */
-    float fracSide(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                   int /*largerWindow*/, 
-                   int /*smallerWindow*/, 
-                   ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
+  /** @brief pt in a window of (currently) 2 x windowSize cells */
+  float ptWindow(const std::vector<std::vector<const CaloCell*>>& shotCells, 
+                 int windowSize, 
+                 const ToolHandle<IHadronicCalibrationTool>& caloWeightTool);
 
-    /** @brief pt window fraction */
-    float ptWindowFrac(std::vector<std::vector<const CaloCell*> > /*shotCells*/, 
-                       int /*largerWindow*/, 
-                       int /*smallerWindow*/, 
-                       const ToolHandle<IHadronicCalibrationTool>& /*caloWeightTool*/);
 }
 
 #endif // TAUSHOTVARIABLEHELPERS_H
diff --git a/Reconstruction/tauRecTools/tauRecTools/TauPi0ScoreCalculator.h b/Reconstruction/tauRecTools/tauRecTools/TauPi0ScoreCalculator.h
index ba8b377e9a6fba52417b92dfe37cc0160df8533f..b57c013c456aedaa1b7a7e4a78db2ecd12817317 100644
--- a/Reconstruction/tauRecTools/tauRecTools/TauPi0ScoreCalculator.h
+++ b/Reconstruction/tauRecTools/tauRecTools/TauPi0ScoreCalculator.h
@@ -5,12 +5,13 @@
 #ifndef TAUREC_TAUPI0SCORECALCULATOR_H
 #define	TAUREC_TAUPI0SCORECALCULATOR_H
 
-#include <string>
-#include <map>
 #include "tauRecTools/TauRecToolBase.h"
-#include "xAODPFlow/PFO.h"
 #include "tauRecTools/BDTHelper.h"
 
+#include "xAODPFlow/PFO.h"
+
+#include <string>
+
 /**
  * @brief Selectes pi0Candidates (Pi0 Finder).
  * 
@@ -21,20 +22,24 @@
  */
 
 class TauPi0ScoreCalculator : public TauRecToolBase {
+
 public:
-    TauPi0ScoreCalculator(const std::string& name);
-    ASG_TOOL_CLASS2(TauPi0ScoreCalculator, TauRecToolBase, ITauToolBase)
-    virtual ~TauPi0ScoreCalculator();
 
-    virtual StatusCode initialize() override;
-    virtual StatusCode executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const override;
+  ASG_TOOL_CLASS2(TauPi0ScoreCalculator, TauRecToolBase, ITauToolBase)
+  
+  TauPi0ScoreCalculator(const std::string& name);
+  virtual ~TauPi0ScoreCalculator() = default;
+
+  virtual StatusCode initialize() override;
+  virtual StatusCode executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const override;
 
 private:
-    /** @brief function used to calculate BDT score */
-    float calculateScore(const xAOD::PFO* neutralPFO) const;
+  
+  /** @brief Calculate pi0 BDT score */
+  float calculateScore(const xAOD::PFO* neutralPFO) const;
 
-    std::string m_weightfile;    
-    std::unique_ptr<tauRecTools::BDTHelper> m_mvaBDT;
+  std::string m_weightfile = "";
+  std::unique_ptr<tauRecTools::BDTHelper> m_mvaBDT = nullptr;
 };
 
 #endif	/* TAUPI0SCORECALCULATOR_H */
diff --git a/Reconstruction/tauRecTools/tauRecTools/TauPi0Selector.h b/Reconstruction/tauRecTools/tauRecTools/TauPi0Selector.h
index 16506a71f5ff79b3a3ddd5793e51e152b648b367..79c12f6eccf0a62fcd2ed313a1e23b449c622b29 100644
--- a/Reconstruction/tauRecTools/tauRecTools/TauPi0Selector.h
+++ b/Reconstruction/tauRecTools/tauRecTools/TauPi0Selector.h
@@ -5,11 +5,12 @@
 #ifndef TAUREC_TAUPI0SELECTOR_H
 #define	TAUREC_TAUPI0SELECTOR_H
 
-#include <string>
 #include "tauRecTools/TauRecToolBase.h"
 
+#include <string>
+
 /**
- * @brief Selects pi0s
+ * @brief Apply Et and BDT score cut to pi0s
  * 
  * @author Will Davey <will.davey@cern.ch> 
  * @author Benedict Winter <benedict.tobias.winter@cern.ch> 
@@ -17,21 +18,23 @@
  */
 
 class TauPi0Selector : public TauRecToolBase {
+
 public:
-    TauPi0Selector(const std::string& name);
-    ASG_TOOL_CLASS2(TauPi0Selector, TauRecToolBase, ITauToolBase)
-    virtual ~TauPi0Selector();
-    virtual StatusCode executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const override;
+  
+  ASG_TOOL_CLASS2(TauPi0Selector, TauRecToolBase, ITauToolBase)
+  
+  TauPi0Selector(const std::string& name);
+  virtual ~TauPi0Selector() = default;
+  
+  virtual StatusCode executePi0nPFO(xAOD::TauJet& pTau, xAOD::PFOContainer& pNeutralPFOContainer) const override;
 
 private:
+  /** @brief Get eta bin of Pi0Cluster */
+  int getEtaBin(double eta) const;
 
-    std::vector<float> m_clusterEtCut;
-    std::vector<float> m_clusterBDTCut_1prong;
-    std::vector<float> m_clusterBDTCut_mprong;
-    /** @brief function used to get eta bin of Pi0Cluster */
-    int getPi0Cluster_etaBin(double Pi0Cluster_eta) const;
-    /** @brief function used to calculate the visible tau 4 momentum */
-    TLorentzVector getP4(const xAOD::TauJet& tauJet) const;
+  std::vector<double> m_clusterEtCut;
+  std::vector<double> m_clusterBDTCut_1prong;
+  std::vector<double> m_clusterBDTCut_mprong;
 };
 
 #endif	/* TAUPI0SELECTOR_H */
diff --git a/Simulation/Digitization/python/DigiAlgConfig.py b/Simulation/Digitization/python/DigiAlgConfig.py
index f40254bc5529268fb7534cff9f162e4e1b90bd0b..73cd7cb4c84f179d48b76743037897e11f817b52 100644
--- a/Simulation/Digitization/python/DigiAlgConfig.py
+++ b/Simulation/Digitization/python/DigiAlgConfig.py
@@ -118,8 +118,6 @@ def getStandardInDetPileUpTools():
             PileUpToolsList += [ "PixelLightDigitizationTool" ]
         elif 'doSmearedPixelDigi' in digitizationFlags.experimentalDigi():
             PileUpToolsList += [ "PixelSmearedDigitizationTool" ]
-        elif digitizationFlags.doRadiationDamage():
-            PileUpToolsList += [ "PixelRadDamDigitizationTool" ]
         else:
             PileUpToolsList += [ "PixelDigitizationTool" ]
     if DetFlags.digitize.SCT_on():
diff --git a/Simulation/Digitization/python/DigitizationConfigFlags.py b/Simulation/Digitization/python/DigitizationConfigFlags.py
index feab44fe3826edfb64785e40c34bcd0c740163b5..8c37d85be85293a14a35850404d760ccd7737010 100644
--- a/Simulation/Digitization/python/DigitizationConfigFlags.py
+++ b/Simulation/Digitization/python/DigitizationConfigFlags.py
@@ -95,6 +95,9 @@ def createDigitizationCfgFlags():
     # Override the HIT file Run Number with one from a data run
     flags.addFlag("Digitization.DataRunNumber", -1)
     
+    # Run radiation damage simulation
+    flags.addFlag("Digitization.DoRadiationDamage", False)
+    
     # for PileUp digitization
     # Beam Halo input collections
     flags.addFlag("Digitization.PU.BeamHaloInputCols", [])
diff --git a/Simulation/FastSimulation/FastChainPileup/test/test_ttFC_reco_newTracking_PseudoT_fullSim_fullDigi.sh b/Simulation/FastSimulation/FastChainPileup/test/test_ttFC_reco_newTracking_PseudoT_fullSim_fullDigi.sh
index be1247ee60ce3ececb9fa0d026436f0800900c10..42d635c0e31b8cce89ccc6e9346824e73c7bfe8f 100755
--- a/Simulation/FastSimulation/FastChainPileup/test/test_ttFC_reco_newTracking_PseudoT_fullSim_fullDigi.sh
+++ b/Simulation/FastSimulation/FastChainPileup/test/test_ttFC_reco_newTracking_PseudoT_fullSim_fullDigi.sh
@@ -54,7 +54,7 @@ FastChain_tf.py --maxEvents 500 \
     --conditionsTag OFLCOND-RUN12-SDR-31  \
     --inputRDOFile RDO_pileup_fullsim_fulldigi.pool.root \
     --outputAODFile AOD_newTracking_pseudoTracking_fullSim_fullDigi.pool.root \
-    --preExec "RAWtoESD:from InDetRecExample.InDetJobProperties import InDetFlags;InDetFlags.doPseudoTracking.set_Value_and_Lock(True);InDetFlags.doNewTracking.set_Value_and_Lock(True);rec.doTrigger.set_Value_and_Lock(False);recAlgs.doTrigger.set_Value_and_Lock(False);InDetFlags.doTrackSegmentsTRT.set_Value_and_Lock(True);" \
+    --preExec "RAWtoESD:from InDetRecExample.InDetJobProperties import InDetFlags;InDetFlags.doPseudoTracking.set_Value_and_Lock(True);InDetFlags.doNewTracking.set_Value_and_Lock(True);rec.doTrigger.set_Value_and_Lock(False);recAlgs.doTrigger.set_Value_and_Lock(False);" \
     --outputNTUP_PHYSVALFile 'physval-newTracking_PseudoT_fullSim_fullDigi.root' \
     --validationFlags 'doInDet' \
     --valid 'True' \
diff --git a/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfig.py b/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfig.py
index 185d371fab45174201296a17a1b542f6fc281a15..33788a8cb7cef0949642a78a061d507f1b48fd09 100644
--- a/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfig.py
+++ b/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfig.py
@@ -68,7 +68,9 @@ def getGenParticleFilters():
         from AthenaCommon.BeamFlags import jobproperties
         if jobproperties.Beam.beamType() != "cosmics":
             genParticleFilterList += ['ISF_ParticlePositionFilterDynamic']
-            if (not simFlags.CavernBG.statusOn or simFlags.CavernBG.get_Value() == 'Signal') and\
+            from AthenaCommon.DetFlags import DetFlags
+            if not (DetFlags.geometry.AFP_on() or DetFlags.geometry.ALFA_on() or DetFlags.geometry.FwdRegion_on()) and\
+               (not simFlags.CavernBG.statusOn or simFlags.CavernBG.get_Value() == 'Signal') and\
                not (simFlags.SimulateCavern.statusOn and simFlags.SimulateCavern.get_Value()):
                 genParticleFilterList += ['ISF_EtaPhiFilter']
     genParticleFilterList += ['ISF_GenParticleInteractingFilter']
diff --git a/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfigNew.py b/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfigNew.py
index d791a274b2a67b59407023f2961f7fef038db655..8904278b810a94f59bd3f512790392ea95ad54e4 100644
--- a/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfigNew.py
+++ b/Simulation/ISF/ISF_Core/ISF_Services/python/ISF_ServicesConfigNew.py
@@ -39,8 +39,11 @@ def GenParticleFiltersToolCfg(ConfigFlags):
         if ConfigFlags.Beam.Type != "cosmics":
             acc = ParticlePositionFilterDynamicCfg(ConfigFlags)
             genParticleFilterList += [result.popToolsAndMerge(acc)]
-            if ((ConfigFlags.Sim.CavernBG in (False, "Signal")) and
-                (not ConfigFlags.Detector.SimulateCavern)):
+            if not (ConfigFlags.Detector.SimulateAFP or
+               ConfigFlags.Detector.SimulateALFA or
+               ConfigFlags.Detector.SimulateFwdRegion) and \
+               ((ConfigFlags.Sim.CavernBG in (False, "Signal")) and
+               (not ConfigFlags.Detector.SimulateCavern)):
                 acc = EtaPhiFilterCfg(ConfigFlags)
                 genParticleFilterList += [result.popToolsAndMerge(acc)]
     acc = GenParticleInteractingFilterCfg(ConfigFlags)
diff --git a/Simulation/ISF/ISF_Fatras/ISF_FatrasRecoTools/CMakeLists.txt b/Simulation/ISF/ISF_Fatras/ISF_FatrasRecoTools/CMakeLists.txt
index baad18866a2febca7e74d90ed235b02063bc3db5..683b6dab65c03776d7998559752a65f180f88db4 100644
--- a/Simulation/ISF/ISF_Fatras/ISF_FatrasRecoTools/CMakeLists.txt
+++ b/Simulation/ISF/ISF_Fatras/ISF_FatrasRecoTools/CMakeLists.txt
@@ -1,50 +1,10 @@
-################################################################################
-# Package: ISF_FatrasRecoTools
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( ISF_FatrasRecoTools )
 
-# Declare the package's dependencies:
-atlas_depends_on_subdirs( PUBLIC
-                          Control/AthenaBaseComps
-                          DetectorDescription/GeoPrimitives
-                          DetectorDescription/Identifier
-                          Simulation/ISF/ISF_Fatras/ISF_FatrasEvent
-                          Tracking/TrkEvent/TrkEventPrimitives
-                          Tracking/TrkEvent/TrkParameters
-                          Tracking/TrkEvent/TrkSpacePoint
-                          Tracking/TrkEvent/TrkTrackSummary
-                          Tracking/TrkTools/TrkToolInterfaces
-                          Tracking/TrkTruthTracks/TrkTruthTrackInterfaces
-                          PRIVATE
-                          DetectorDescription/AtlasDetDescr
-                          Event/EventPrimitives
-                          Generators/AtlasHepMC
-                          GaudiKernel
-                          InnerDetector/InDetDetDescr/InDetIdentifier
-                          InnerDetector/InDetRecEvent/InDetPrepRawData
-                          InnerDetector/InDetRecEvent/SiSpacePoint
-                          Simulation/ISF/ISF_Fatras/ISF_FatrasDetDescrModel
-                          Tracking/TrkDetDescr/TrkDetElementBase
-                          Tracking/TrkEvent/TrkCompetingRIOsOnTrack
-                          Tracking/TrkEvent/TrkEventUtils
-                          Tracking/TrkEvent/TrkPrepRawData
-                          Tracking/TrkEvent/TrkRIO_OnTrack
-                          Tracking/TrkEvent/TrkTrack
-                          Tracking/TrkEvent/TrkTruthData )
-
-# External dependencies:
-find_package( Eigen )
-find_package( ROOT COMPONENTS Core Tree MathCore Hist RIO pthread )
-
 # Component(s) in the package:
 atlas_add_component( ISF_FatrasRecoTools
                      src/*.cxx
                      src/components/*.cxx
-                     INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ${EIGEN_INCLUDE_DIRS}
-                     LINK_LIBRARIES ${ROOT_LIBRARIES} ${EIGEN_LIBRARIES} AtlasHepMCLib AthenaBaseComps GeoPrimitives Identifier ISF_FatrasEvent TrkEventPrimitives TrkParameters TrkSpacePoint TrkTrackSummary TrkToolInterfaces AtlasDetDescr EventPrimitives GaudiKernel InDetIdentifier InDetPrepRawData SiSpacePoint ISF_FatrasDetDescrModel TrkDetElementBase TrkCompetingRIOsOnTrack TrkEventUtils TrkPrepRawData TrkRIO_OnTrack TrkTrack TrkTruthData TrkTruthTrackInterfaces )
-
-# Install files from the package:
-atlas_install_headers( ISF_FatrasRecoTools )
-
+                     LINK_LIBRARIES AtlasHepMCLib AthenaBaseComps GeoPrimitives Identifier ISF_FatrasEvent TrkEventPrimitives TrkParameters TrkSpacePoint TrkTrackSummary TrkToolInterfaces AtlasDetDescr EventPrimitives GaudiKernel InDetIdentifier InDetPrepRawData SiSpacePoint ISF_FatrasDetDescrModel TrkDetElementBase TrkCompetingRIOsOnTrack TrkEventUtils TrkPrepRawData TrkRIO_OnTrack TrkTrack TrkTruthData TrkTruthTrackInterfaces )
diff --git a/Simulation/ISF/ISF_Fatras/ISF_FatrasToolsMS/CMakeLists.txt b/Simulation/ISF/ISF_Fatras/ISF_FatrasToolsMS/CMakeLists.txt
index 350a0e1084a7876bf98593a804a30a962e215a62..23d4aec01e2fedaac2deba6272399d26fa568035 100644
--- a/Simulation/ISF/ISF_Fatras/ISF_FatrasToolsMS/CMakeLists.txt
+++ b/Simulation/ISF/ISF_Fatras/ISF_FatrasToolsMS/CMakeLists.txt
@@ -1,6 +1,4 @@
-################################################################################
-# Package: ISF_FatrasToolsMS
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( ISF_FatrasToolsMS )
@@ -8,28 +6,9 @@ atlas_subdir( ISF_FatrasToolsMS )
 # External dependencies:
 find_package( CLHEP )
 
-# Declare the package's dependencies:
-atlas_depends_on_subdirs( PUBLIC
-                          GaudiKernel
-                          PRIVATE
-                          Control/AthenaBaseComps
-                          Control/AthenaKernel
-                          DetectorDescription/Identifier
-                          MuonSpectrometer/MuonDetDescr/MuonReadoutGeometry
-                          MuonSpectrometer/MuonIdHelpers
-                          MuonSpectrometer/MuonReconstruction/MuonRecTools/MuonTGRecTools
-                          MuonSpectrometer/MuonSimEvent
-                          Simulation/ISF/ISF_Core/ISF_Event
-                          Simulation/ISF/ISF_Core/ISF_Interfaces
-                          Simulation/ISF/ISF_Fatras/ISF_FatrasInterfaces
-                          Tracking/TrkEvent/TrkParameters
-                          Tracking/TrkEvent/TrkTrack
-                          Tracking/TrkExtrapolation/TrkExInterfaces )
-
 # Component(s) in the package:
 atlas_add_component( ISF_FatrasToolsMS
                      src/*.cxx
                      src/components/*.cxx
                      INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS}
-                     LINK_LIBRARIES ${CLHEP_LIBRARIES} AthenaBaseComps AthenaKernel Identifier GaudiKernel MuonSimEvent ISF_FatrasInterfaces TrkParameters TrkExInterfaces MuonReadoutGeometry MuonIdHelpersLib ISF_Event ISF_InterfacesLib TrkTrack MuonTGRecToolsLib )
-
+                     LINK_LIBRARIES ${CLHEP_LIBRARIES} AthenaBaseComps AthenaKernel GaudiKernel MuonSimEvent ISF_FatrasInterfaces TrkParameters TrkExInterfaces MuonReadoutGeometry MuonIdHelpersLib ISF_Event ISF_InterfacesLib TrkTrack MuonTGRecToolsLib )
diff --git a/TileCalorimeter/TileMonitoring/python/TileMonitoringCfgHelper.py b/TileCalorimeter/TileMonitoring/python/TileMonitoringCfgHelper.py
index 4ba90944b8ee28c571f61d91671070b3e2c7268a..ff8e8a79a017d4e090c2fa11535f399604ddb671 100644
--- a/TileCalorimeter/TileMonitoring/python/TileMonitoringCfgHelper.py
+++ b/TileCalorimeter/TileMonitoring/python/TileMonitoringCfgHelper.py
@@ -191,10 +191,10 @@ def getLabels(labels, partition = ''):
 
 
 def getCellNameTMDB(partition, channel):
-        return _cellNameTMDB_LB[channel] if partition.startswith('L') else _cellNameTMDB_EB[channel]
+    return _cellNameTMDB_LB[channel] if partition.startswith('L') else _cellNameTMDB_EB[channel]
 
 def getCellChannelTMDB_Labels(partition):
-        return _cellNameTMDB_LB if partition.startswith('L') else _cellNameTMDB_EB
+    return _cellNameTMDB_LB if partition.startswith('L') else _cellNameTMDB_EB
 
 
 def addValueVsModuleAndChannelMaps(group, name, title, path, subDirectory = False, type = 'TH2D', value = '', trigger = '', run = ''):
@@ -313,7 +313,7 @@ def addTile2DHistogramsArray(helper, algorithm, name = '', xvalue = '', yvalue =
     dimensions = _getDimensions(triggers = triggers, perPartition = perPartition, perSample = perSample,
                                 perGain = perGain, allPartitions = allPartitions)
 
-    array = helper.addArray(dimensions, algorithm, name)
+    array = helper.addArray(dimensions, algorithm, name, topPath = path)
     for postfix, tool in array.Tools.items():
 
         kwargs = _parsePostfix(postfix, triggers = triggers, perPartition = perPartition,
@@ -326,10 +326,10 @@ def addTile2DHistogramsArray(helper, algorithm, name = '', xvalue = '', yvalue =
         fullName = xvalue + ',' + yvalue + (',' + value if 'Profile' in type else '') + ';'
         fullName += getTileHistogramName(name = name,separator = separator, **kwargs)
 
-        fullPath = getTileHistogramPath(path = path, subDirectory = subDirectory, **kwargs)
+        subPath = getTileHistogramPath(path = '', subDirectory = subDirectory, **kwargs)
         fullTitle = getTileHistogramTitle(title = title, run = run, **kwargs)
 
-        tool.defineHistogram( fullName, path = fullPath, type = type, title = fullTitle,
+        tool.defineHistogram( fullName, path = subPath, type = type, title = fullTitle,
                               xlabels = nxlabels, ylabels = nylabels,
                               xbins = xbins, xmin = xmin, xmax = xmax,
                               ybins = ybins, ymin = ymin, ymax = ymax, weight = weight)
@@ -535,7 +535,7 @@ def addTile1DHistogramsArray(helper, algorithm, name = '', xvalue = '', value =
     dimensions = _getDimensions(triggers = triggers, perPartition = perPartition, perSample = perSample,
                                 perGain = perGain, allPartitions = allPartitions)
 
-    array = helper.addArray(dimensions, algorithm, name)
+    array = helper.addArray(dimensions, algorithm, name, topPath = path)
     for postfix, tool in array.Tools.items():
 
         kwargs = _parsePostfix(postfix, triggers = triggers, perPartition = perPartition,
@@ -547,10 +547,10 @@ def addTile1DHistogramsArray(helper, algorithm, name = '', xvalue = '', value =
         fullName = xvalue + (',' + value if 'Profile' in type else '') + ';'
         fullName += getTileHistogramName(name = name,separator = separator, **kwargs)
 
-        fullPath = getTileHistogramPath(path = path, subDirectory = subDirectory, **kwargs)
+        subPath = getTileHistogramPath(path = '', subDirectory = subDirectory, **kwargs)
         fullTitle = getTileHistogramTitle(title = title, run = run, **kwargs)
 
-        tool.defineHistogram( fullName, path = fullPath, type = type, title = fullTitle,
+        tool.defineHistogram( fullName, path = subPath, type = type, title = fullTitle,
                               xlabels = nxlabels, xbins = xbins, xmin = xmin, xmax = xmax, opt = opt)
 
     return array
@@ -590,7 +590,7 @@ def addTileModuleArray(helper, algorithm, name, title, path,
 def addTileTMDB_2DHistogramsArray(helper, algorithm, name = '', value = '',
                                   title = '', path = '', type = 'TH2D', run = ''):
 
-    array = helper.addArray([int(Tile.MAX_ROS - 1)], algorithm, name)
+    array = helper.addArray([int(Tile.MAX_ROS - 1)], algorithm, name, topPath = path)
     for postfix, tool in array.Tools.items():
         ros = int(postfix.split('_').pop()) + 1
 
@@ -604,7 +604,7 @@ def addTileTMDB_2DHistogramsArray(helper, algorithm, name = '', value = '',
 
         fullTitle = getTileHistogramTitle(title, run = run, partition = partition)
 
-        tool.defineHistogram( fullName, path = path, type = type, title = fullTitle,
+        tool.defineHistogram( fullName, path = '', type = type, title = fullTitle,
                                 xlabels = nxlabels, ylabels = nylabels,
                                 xbins = Tile.MAX_DRAWER, xmin = -0.5, xmax = Tile.MAX_DRAWER - 0.5,
                                 ybins = ybins, ymin = -0.5, ymax = ybins - 0.5)
@@ -619,7 +619,7 @@ def addTileTMDB_1DHistogramsArray(helper, algorithm, name = '', xvalue = '', val
         baseName = "{}_{}".format(name, partition)
         nChannels = len(_cellNameTMDB_LB) if partition.startswith('L') else len(_cellNameTMDB_EB)
         dimensions = [int(Tile.MAX_DRAWER), nChannels] if perModule else [nChannels]
-        array = helper.addArray(dimensions, algorithm,  baseName, topPath = 'Tile')
+        array = helper.addArray(dimensions, algorithm,  baseName, topPath = path)
         for postfix, tool in array.Tools.items():
             elements = postfix.split('_')
             channel = int(elements.pop())
@@ -631,7 +631,6 @@ def addTileTMDB_1DHistogramsArray(helper, algorithm, name = '', xvalue = '', val
 
             moduleOrPartition = 'Module ' + partition + module if perModule else 'Partition ' + partition
             fullTitle = 'Run {} {} TMDB {}: {}'.format(run, moduleOrPartition, cell, title)
-            fullPath = path.replace('Tile/', '') if  path.startswith('Tile/') else path
 
-            tool.defineHistogram(fullName, path = fullPath, type = type, title = fullTitle,
+            tool.defineHistogram(fullName, path = '', type = type, title = fullTitle,
                                  xbins = xbins, xmin = xmin, xmax = xmax)
diff --git a/TileCalorimeter/TileMonitoring/share/TileMonState.py b/TileCalorimeter/TileMonitoring/share/TileMonState.py
index 9965bed55f665c5ff73fdf01a76b3774746a779c..2f5b0b3752d0f28fa10c5774fda652ae72293083 100644
--- a/TileCalorimeter/TileMonitoring/share/TileMonState.py
+++ b/TileCalorimeter/TileMonitoring/share/TileMonState.py
@@ -53,7 +53,9 @@ ByteStreamEmonInputSvc = svcMgr.ByteStreamInputSvc
 # ############################################################
 
 if 'Partition' not in dir():
-    Partition="ATLAS"
+    import os
+    Partition = os.getenv("TDAQ_PARTITION","ATLAS")
+
 ByteStreamEmonInputSvc.Partition = Partition
 
 
@@ -127,7 +129,7 @@ else:
 # #########################################
 #ByteStreamEmonInputSvc.Key = "ReadoutApplication"
 if 'Key' not in dir():
-    Key="dcm"
+    Key = {'ATLAS' : 'dcm', 'TileMon' : 'CompleteEvent', 'Tile' : 'ReadoutApplication'}.get(Partition, 'dcm')
 ByteStreamEmonInputSvc.Key = Key
 
 # ############################################################
@@ -139,6 +141,8 @@ ByteStreamEmonInputSvc.Key = Key
 #    KeyValue=[""]
 #ByteStreamEmonInputSvc.KeyValue = KeyValue
 
+if Partition == 'Tile':
+    KeyValue = ['TileREB-ROS']
 if 'KeyValue' in dir():
     ByteStreamEmonInputSvc.KeyValue = KeyValue
 
diff --git a/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.cxx b/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.cxx
index 8adc8a3ae49707c7cfabb603a5fd70ffcff593d6..c0e9aed5f3df2ab13c27bfa4a1cbfd83479bd610 100644
--- a/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.cxx
+++ b/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #include "TileDQFragMonitorAlgorithm.h"
@@ -29,6 +29,7 @@ StatusCode TileDQFragMonitorAlgorithm::initialize() {
   ATH_CHECK( m_DCSStateKey.initialize(m_checkDCS) );
   ATH_CHECK( m_digitsContainerKey.initialize(SG::AllowEmpty) );
   ATH_CHECK( m_rawChannelContainerKey.initialize(SG::AllowEmpty) );
+  ATH_CHECK( m_eventInfoTileStatusKey.initialize() );
 
   using Tile = TileCalibUtils;
 
diff --git a/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.h b/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.h
index 7e63e2b09de7efbf45deb6662b1721d25444b483..9ca6101b0f03721be7deb718b58c2e6f22d99900 100644
--- a/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.h
+++ b/TileCalorimeter/TileMonitoring/src/TileDQFragMonitorAlgorithm.h
@@ -87,6 +87,10 @@ class TileDQFragMonitorAlgorithm : public AthMonitorAlgorithm {
     SG::ReadHandleKey<TileDigitsContainer> m_digitsContainerKey{this,
         "TileDigitsContainer", "TileDigitsCnt", "Input Tile digits container key"};
 
+    SG::ReadDecorHandleKey<xAOD::EventInfo> m_eventInfoTileStatusKey{this, "EventInfoTileStatus",
+                                                                    "EventInfo.TileStatus",
+                                                                    "Aid to MT scheduling, do not change"};
+
     std::vector<std::vector<int>> m_errorsGroups;
     std::vector<std::vector<int>> m_errorsVsLBGroups;
 
diff --git a/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.cxx b/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.cxx
index d1f91f678879ccae120afd032ad206ddca8fcd69..f23e151387d52111bf27da04e2b3c47b36551485 100644
--- a/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.cxx
+++ b/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 // Tile includes
@@ -36,6 +36,7 @@ StatusCode MBTSTimeDiffEventInfoAlg::initialize() {
   ATH_CHECK( m_mbtsContainerKey.initialize() );
   ATH_CHECK( m_eventInfoKey.initialize() );
   ATH_CHECK( m_mbtsCollisionTimeKey.initialize() );
+  ATH_CHECK( m_eventInfoDecorKey.initialize() );
 
   return StatusCode::SUCCESS;
 }
diff --git a/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.h b/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.h
index 218a33cf3ce1a7ab1688eb41419936601ced99b8..257a21ca8210c01d1b3cd7035c1498bad877eda3 100644
--- a/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.h
+++ b/TileCalorimeter/TileRecAlgs/src/MBTSTimeDiffEventInfoAlg.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef TILERECALGS_MBTSTIMEDIFFEVENTINFOALG_
@@ -42,6 +42,7 @@ class MBTSTimeDiffEventInfoAlg: public AthReentrantAlgorithm {
     SG::ReadHandleKey<TileCellContainer> m_mbtsContainerKey{this,"MBTSContainer","MBTSContainer","Input MBTS container key"};
     SG::ReadHandleKey<xAOD::EventInfo> m_eventInfoKey{this, "EventInfo", "EventInfo", "Input Event info key"};
     SG::WriteHandleKey<MBTSCollisionTime> m_mbtsCollisionTimeKey{this,"MBTSCollisionTime","MBTSCollisionTime","Output MBTS collision time key"};
+    SG::WriteDecorHandleKey<xAOD::EventInfo> m_eventInfoDecorKey{this, "EventInfoDecorKey", "EventInfo.MBTSBackground", "EventInfo decoration key"};
 
     const TileTBID* m_tileTBID{nullptr};
 
diff --git a/TileCalorimeter/TileRecUtils/TileRecUtils/TileCellBuilder.h b/TileCalorimeter/TileRecUtils/TileRecUtils/TileCellBuilder.h
index d4a35d2ffb675ef2edf21e9e447e26fb709c51d1..17eb77928e56b6cbd0338b0e9fb4b78f5a728253 100644
--- a/TileCalorimeter/TileRecUtils/TileRecUtils/TileCellBuilder.h
+++ b/TileCalorimeter/TileRecUtils/TileRecUtils/TileCellBuilder.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 #ifndef TILERECUTILS_TILECELLBUILDER_H
@@ -159,6 +159,10 @@ private:
                                                              "E4prContainer",
                                                              "Output Tile E4 prime container key"};
 
+    SG::WriteDecorHandleKey<xAOD::EventInfo> m_EventInfoTileStatusKey{this, "EventInfoTileStatus",
+                                                                      "EventInfo.TileStatus",
+                                                                      "Dummy decoration key to aid scheduling"};
+
 
     std::string m_dspRawChannelContainer;
 
diff --git a/TileCalorimeter/TileRecUtils/src/TileCellBuilder.cxx b/TileCalorimeter/TileRecUtils/src/TileCellBuilder.cxx
index 4fdedbfd1439664247430940938d49f4d84682c7..008b9eefa399239aa5e394ec25dfb762733899a9 100644
--- a/TileCalorimeter/TileRecUtils/src/TileCellBuilder.cxx
+++ b/TileCalorimeter/TileRecUtils/src/TileCellBuilder.cxx
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
+  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 */
 
 // Tile includes
@@ -175,6 +175,7 @@ StatusCode TileCellBuilder::initialize() {
 
   ATH_CHECK( m_eventInfoKey.initialize() );
   ATH_CHECK( m_DQstatusKey.initialize() );
+  ATH_CHECK( m_EventInfoTileStatusKey.initialize() );
 
   ATH_CHECK( detStore()->retrieve(m_tileMgr) );
   ATH_CHECK( detStore()->retrieve(m_tileID) );
diff --git a/Tracking/TrkConfig/CMakeLists.txt b/Tracking/TrkConfig/CMakeLists.txt
index a25ad88624a51e3815472a02b14521642a1f0d7c..66041e2e20d87486866bc3563ff90d68485b3fc3 100644
--- a/Tracking/TrkConfig/CMakeLists.txt
+++ b/Tracking/TrkConfig/CMakeLists.txt
@@ -1,12 +1,10 @@
-################################################################################
-# Package: TrkConfig
-################################################################################
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 # Declare the package name:
 atlas_subdir( TrkConfig )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py)
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_data( share/*.ref )
 
 
diff --git a/Tracking/TrkDetDescr/TrkDetDescrExample/CMakeLists.txt b/Tracking/TrkDetDescr/TrkDetDescrExample/CMakeLists.txt
index 8c2cc24b80f918b9d22a40666732b00bda8c4068..3741d3facc8a7efa5769a8f989f514cd041d8c40 100644
--- a/Tracking/TrkDetDescr/TrkDetDescrExample/CMakeLists.txt
+++ b/Tracking/TrkDetDescr/TrkDetDescrExample/CMakeLists.txt
@@ -4,6 +4,5 @@
 atlas_subdir( TrkDetDescrExample )
 
 # Install files from the package:
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
-
diff --git a/Tracking/TrkDetDescr/TrkDetDescrExample/python/LayerMaterialUtils.py b/Tracking/TrkDetDescr/TrkDetDescrExample/python/LayerMaterialUtils.py
index 2342143606e6ffc4dee35d98e4e4a8eb6b2c1e63..0037e564784fade892401d1665482ac14347fd8b 100644
--- a/Tracking/TrkDetDescr/TrkDetDescrExample/python/LayerMaterialUtils.py
+++ b/Tracking/TrkDetDescr/TrkDetDescrExample/python/LayerMaterialUtils.py
@@ -1,8 +1,7 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
-from __future__ import print_function
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
 import math
-from ROOT import *
+from ROOT import TCanvas, TH2F, TH3F, TProfile, gDirectory, gROOT, kCanDelete, kMustCleanup, kRed, kWhite
 
 def drawCylinderLayer(g4CylTree,cylLayer,tgCylTree,saveLocation) :
     
@@ -33,21 +32,15 @@ def drawCylinderLayer(g4CylTree,cylLayer,tgCylTree,saveLocation) :
         
         # create the x0 histogram
         clmap_x0         = TH2F('clmap_x0_'+clname,clname,binsz,-halfz,halfz,binsphi,-math.pi,math.pi)
-        # the steps
-        stepZ   = 2.*halfz/numbinsz
-        stepPhi = 2*math.pi/numbinsphi
         x0max = 0.
         # loop over bins and fill it
-        for ibin in xrange(evt.cylMatBinsTotal) :
+        for ibin in range(evt.cylMatBinsTotal) :
             # first get the ibin phi
             ibinz   = ibin/numbinsphi
             ibinphi = ibin - ibinz*numbinsphi      
             x0 = evt.cylMatX0[ibin]
             if x0 > x0max : x0max = x0           
             clmap_x0.SetBinContent(ibinz+1,ibinphi+1,x0)
-            # z / phi value for the profile plots
-            izval   = -halfz+(ibinz+0.5)*stepZ
-            iphival = -math.pi+(ibinphi+0.5)*stepPhi
         pass
     
     # and draw it
@@ -57,8 +50,8 @@ def drawCylinderLayer(g4CylTree,cylLayer,tgCylTree,saveLocation) :
     # ---------------------------------------------------------
     # draw profiles first to get a good estimate for the maximum
     canvasX0map.cd(5)
-    x0profZG4 = TProfile(clname+'x0profZG4',clname+'x0profZG4',numbinsz,-halfz+position,halfz+position)
-    x0profZTG = TProfile(clname+'x0profZTG',clname+'x0profZTG',numbinsz,-halfz+position,halfz+position)
+    x0profZG4 = TProfile(clname+'x0profZG4',clname+'x0profZG4',numbinsz,-halfz+position,halfz+position)  # noqa: F841
+    x0profZTG = TProfile(clname+'x0profZTG',clname+'x0profZTG',numbinsz,-halfz+position,halfz+position)  # noqa: F841
     g4CylTree.Draw('PathInX0:DensedHitZ>>'+clname+'x0profZG4','','prof')
     tgCylTree.Draw('PathInX0:DensedHitZ>>'+clname+'x0profZTG','','prof')
     x0profG4z = gDirectory.Get(clname+'x0profZG4')
@@ -77,8 +70,8 @@ def drawCylinderLayer(g4CylTree,cylLayer,tgCylTree,saveLocation) :
     x0profTGz.SetMarkerSize(0.8)
     x0profTGz.Draw('pe,same')
     canvasX0map.cd(6)
-    x0profPhiG4 = TProfile(clname+'x0profPhiG4',clname+'x0profPhiG4',numbinsphi,-math.pi,math.pi)
-    x0profPhiTG = TProfile(clname+'x0profPhiTG',clname+'x0profPhiTG',numbinsphi,-math.pi,math.pi)
+    x0profPhiG4 = TProfile(clname+'x0profPhiG4',clname+'x0profPhiG4',numbinsphi,-math.pi,math.pi)  # noqa: F841
+    x0profPhiTG = TProfile(clname+'x0profPhiTG',clname+'x0profPhiTG',numbinsphi,-math.pi,math.pi)  # noqa: F841
     g4CylTree.Draw('PathInX0:DensedHitPhi>>'+clname+'x0profPhiG4','','prof')
     tgCylTree.Draw('PathInX0:DensedHitPhi>>'+clname+'x0profPhiTG','','prof')
     x0profG4phi = gDirectory.Get(clname+'x0profPhiG4')
@@ -217,7 +210,7 @@ def drawDiscLayer(g4DiscTree,discLayer,tgDiscTree,saveLocation) :
         stepPhi = 2*math.pi/binsPhi
         x0max = 0.
         # loop over bins and fill it
-        for ibin in xrange(evt.discMatBinsTotal) :
+        for ibin in range(evt.discMatBinsTotal) :
             ibinphi = ibin/binsR
             ibinr = ibin - ibinphi*binsR
             #ibinz   = ibin/binsphi
@@ -236,8 +229,8 @@ def drawDiscLayer(g4DiscTree,discLayer,tgDiscTree,saveLocation) :
     # draw profiles tog et good estimate for x0max first
     x0maxProf = x0max
     canvasX0map.cd(5)
-    x0profRG4 = TProfile(dlname+'x0profRG4',dlname+'x0profRG4',numbinsr,innerR,outerR)
-    x0profRTG = TProfile(dlname+'x0profRTG',dlname+'x0profRTG',numbinsr,innerR,outerR)
+    x0profRG4 = TProfile(dlname+'x0profRG4',dlname+'x0profRG4',numbinsr,innerR,outerR)  # noqa: F841
+    x0profRTG = TProfile(dlname+'x0profRTG',dlname+'x0profRTG',numbinsr,innerR,outerR)  # noqa: F841
     g4DiscTree.Draw('PathInX0:DensedHitR>>'+dlname+'x0profRG4','','prof')
     tgDiscTree.Draw('PathInX0:DensedHitR>>'+dlname+'x0profRTG','','prof')
     x0profG4r = gDirectory.Get(dlname+'x0profRG4')
@@ -256,8 +249,8 @@ def drawDiscLayer(g4DiscTree,discLayer,tgDiscTree,saveLocation) :
     x0profTGr.SetMarkerSize(0.8)
     x0profTGr.Draw('pe,same')
     canvasX0map.cd(6)
-    x0profPhiG4 = TProfile(dlname+'x0profPhiG4',dlname+'x0profPhiG4',numbinsphi,-math.pi,math.pi)
-    x0profPhiTG = TProfile(dlname+'x0profPhiTG',dlname+'x0profPhiTG',numbinsphi,-math.pi,math.pi)
+    x0profPhiG4 = TProfile(dlname+'x0profPhiG4',dlname+'x0profPhiG4',numbinsphi,-math.pi,math.pi)  # noqa: F841
+    x0profPhiTG = TProfile(dlname+'x0profPhiTG',dlname+'x0profPhiTG',numbinsphi,-math.pi,math.pi)  # noqa: F841
     g4DiscTree.Draw('PathInX0:DensedHitPhi>>'+dlname+'x0profPhiG4','','prof')
     tgDiscTree.Draw('PathInX0:DensedHitPhi>>'+dlname+'x0profPhiTG','','prof')
     x0profG4phi = gDirectory.Get(dlname+'x0profPhiG4')
diff --git a/Tracking/TrkDetDescr/TrkDetDescrExample/python/TrackingVolumeUtils.py b/Tracking/TrkDetDescr/TrkDetDescrExample/python/TrackingVolumeUtils.py
index cceb29667f78cf9d78795206018f407db2c01e20..43a4005e813ff89e12f4f2a1a767f7a97811bfcb 100644
--- a/Tracking/TrkDetDescr/TrkDetDescrExample/python/TrackingVolumeUtils.py
+++ b/Tracking/TrkDetDescr/TrkDetDescrExample/python/TrackingVolumeUtils.py
@@ -1,8 +1,6 @@
-# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
-from __future__ import print_function
+# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
 
-import math
-from ROOT import *
+from ROOT import TCanvas, gDirectory, kRed
 
 def drawTrackingVolume(g4Tree,tgTree,saveLocation) :
     
diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GXFTrajectory.h b/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GXFTrajectory.h
index cc6439560e592f22bc99bd25e21ff934847d1b2a..ecf39131e4d4d6b90aa82044bb652730a333c817 100644
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GXFTrajectory.h
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GXFTrajectory.h
@@ -66,11 +66,15 @@ namespace Trk {
     int numberOfPerigeeParameters();
     int numberOfFitParameters();
     int numberOfSiliconHits();
+    int numberOfTRTPrecHits();
+    int numberOfTRTTubeHits();
     int numberOfTRTHits();
     int numberOfHits();
     int numberOfPseudoMeasurements();
     int numberOfOutliers();
 
+    void updateTRTHitCount(int index, float oldError);
+
     const std::vector<std::unique_ptr<GXFTrackState>> & trackStates() const;
     std::vector<std::unique_ptr<GXFTrackState>> & trackStates();
     std::vector < std::pair < double, double >>&scatteringAngles();
@@ -121,6 +125,8 @@ namespace Trk {
     int m_noutl;
     int m_nsihits;
     int m_ntrthits;
+    int m_ntrtprechits;
+    int m_ntrttubehits;
     int m_npseudo;
     int m_nmeasoutl;
     std::unique_ptr<const TrackParameters> m_refpar;
diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GlobalChi2Fitter.h b/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GlobalChi2Fitter.h
index 86c15ba531082ce137e43a41f21bafb96e00c86c..23ef2bc5d3c0aeb8173485e0f856a574369aaf8c 100755
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GlobalChi2Fitter.h
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/TrkGlobalChi2Fitter/GlobalChi2Fitter.h
@@ -924,6 +924,7 @@ namespace Trk {
     Gaudi::Property<double> m_p {this, "Momentum", 0.0};
     Gaudi::Property<double> m_chi2cut {this, "TrackChi2PerNDFCut", 1.e15};
     Gaudi::Property<double> m_scalefactor {this, "TRTTubeHitCut", 2.5};
+    Gaudi::Property<double> m_minphfcut {this, "MinPHFCut", 0.};
 
     Gaudi::Property<int> m_maxoutliers {this, "MaxOutliers", 10};
     Gaudi::Property<int> m_maxit {this, "MaxIterations", 30};
diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GXFTrajectory.cxx b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GXFTrajectory.cxx
index dbbc23c960ba20f02eda39d69ef86ce1f5604d1f..589c60c2aafa71dcd35af231f0e93ba04b0b1426 100644
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GXFTrajectory.cxx
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GXFTrajectory.cxx
@@ -26,6 +26,8 @@ namespace Trk {
     m_nupstreambrems = 0;
     m_nsihits = 0;
     m_ntrthits = 0;
+    m_ntrtprechits = 0;
+    m_ntrttubehits = 0;
     m_npseudo = 0;
     m_nhits = 0;
     m_noutl = 0;
@@ -55,6 +57,8 @@ namespace Trk {
     m_nupstreambrems = rhs.m_nupstreambrems;
     m_nsihits = rhs.m_nsihits;
     m_ntrthits = rhs.m_ntrthits;
+    m_ntrtprechits = rhs.m_ntrtprechits;
+    m_ntrttubehits = rhs.m_ntrttubehits;
     m_npseudo = rhs.m_npseudo;
     m_nhits = rhs.m_nhits;
     m_noutl = rhs.m_noutl;
@@ -104,6 +108,8 @@ namespace Trk {
       m_nupstreambrems = rhs.m_nupstreambrems;
       m_nsihits = rhs.m_nsihits;
       m_ntrthits = rhs.m_ntrthits;
+      m_ntrtprechits = rhs.m_ntrtprechits;
+      m_ntrttubehits = rhs.m_ntrttubehits;
       m_nhits = rhs.m_nhits;
       m_npseudo = rhs.m_npseudo;
       m_noutl = rhs.m_noutl;
@@ -199,6 +205,8 @@ namespace Trk {
     
     if (state->measurementType() == TrackState::TRT) {
       m_ntrthits++;
+      if (errors[0]<1) m_ntrtprechits++;
+      if (errors[0]>1) m_ntrttubehits++;
     }
     
     if (state->measurementType() == TrackState::Pseudo) {
@@ -383,6 +391,22 @@ namespace Trk {
     }
   }
 
+  void GXFTrajectory::updateTRTHitCount(int index, float oldError) {
+    double error = (m_states[index]->measurementErrors())[0];
+    if (m_states[index]->getStateType(TrackStateOnSurface::Outlier)) {
+      if (oldError<1) { m_ntrtprechits--; }
+      else {m_ntrttubehits--; }
+    }
+    if (error>1 && oldError<1) { // was precison, became tube
+      m_ntrttubehits++;
+      m_ntrtprechits--;
+    }
+    else if (error<1 && oldError>1) { // was tube, became precision
+      m_ntrttubehits--;
+      m_ntrtprechits++;
+    }
+  }
+
   void GXFTrajectory::setPrefit(int isprefit) {
     m_prefit = isprefit;
   }
@@ -425,6 +449,14 @@ namespace Trk {
     return m_ntrthits;
   }
 
+  int GXFTrajectory::numberOfTRTPrecHits() {
+    return m_ntrtprechits;
+  }
+
+  int GXFTrajectory::numberOfTRTTubeHits() {
+    return m_ntrttubehits;
+  }
+
   int GXFTrajectory::numberOfPseudoMeasurements() {
     return m_npseudo;
   }
diff --git a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
index c168976cfe8877b02c387e863eaf94f65417c2a3..756be534e5796ad1fa230d889b49c466907233ca 100644
--- a/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
+++ b/Tracking/TrkFitter/TrkGlobalChi2Fitter/src/GlobalChi2Fitter.cxx
@@ -5209,6 +5209,20 @@ namespace Trk {
             }
           }
         }
+
+	// PHF cut at iteration 3 (to save CPU time)
+	int ntrtprechits = trajectory.numberOfTRTPrecHits();
+	int ntrttubehits = trajectory.numberOfTRTTubeHits();
+	float phf = 1.;
+	if (ntrtprechits+ntrttubehits) {
+	  phf = float(ntrtprechits)/float(ntrtprechits+ntrttubehits);
+	}
+	if (phf<m_minphfcut && it>=3) {
+	  if ((ntrtprechits+ntrttubehits)>=15) {
+	    return nullptr;
+	  }
+	}
+	ATH_MSG_DEBUG("Iter = " << it << " | nTRTStates = " << ntrthits << " | nTRTPrecHits = " << ntrtprechits << " | nTRTTubeHits = " << ntrttubehits << " | nOutliers = " << trajectory.numberOfOutliers());
         
         if (!trajectory.converged()) {
           cache.m_fittercode = updateFitParameters(trajectory, b, lu);
@@ -6272,6 +6286,8 @@ namespace Trk {
 
             double *errors = state->measurementErrors();
             double olderror = errors[0];
+
+	    trajectory.updateTRTHitCount(stateno, olderror);
             
             for (int i = 0; i < nfitpars; i++) {
               if (weightderiv(measno, i) == 0) {
@@ -6332,6 +6348,8 @@ namespace Trk {
                 errors[0] = newerror;
                 state->setMeasurement(std::move(newrot));
 
+		trajectory.updateTRTHitCount(stateno, olderror);
+
                 for (int i = 0; i < nfitpars; i++) {
                   if (weightderiv(measno, i) == 0) {
                     continue;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/Derivt.h b/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/Derivt.h
index abcac6ebe07fd0c5ae1d1854377056eb835985a2..31845901c604ebf6fdfc2e818ab0f8f63c6cca60 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/Derivt.h
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/Derivt.h
@@ -46,7 +46,7 @@ namespace Trk {
    {
       public:
         VKMassConstraint(int,double, VKVertex*); 
-        VKMassConstraint(int,double, const std::vector<int>&, VKVertex*); 
+        VKMassConstraint(int,double, std::vector<int>, VKVertex*); 
         ~VKMassConstraint(); 
         friend std::ostream& operator<<( std::ostream& out, const VKMassConstraint& );
         virtual VKConstraintBase* clone() const override;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/TrkVKalVrtCoreBase.h b/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/TrkVKalVrtCoreBase.h
index 830bd02a7c89634560cd620237a5713ed1ff79c5..5d3bf121ea6777a60d67351f9c1630bdb837fd1f 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/TrkVKalVrtCoreBase.h
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/TrkVKalVrtCore/TrkVKalVrtCoreBase.h
@@ -44,7 +44,7 @@ namespace Trk {
    class TWRK       // collection of temporary arrays for 
    {   
     public:
-      TWRK() = default;
+      TWRK() { }; //bypass initialization
      ~TWRK() = default;//default destructor allows compiler to optimize out method in this case.
 
      public:
@@ -170,11 +170,11 @@ namespace Trk {
        std::vector<std::unique_ptr<VKConstraintBase> > ConstraintList;
 
 
-       void setRefV(double []);
-       void setCnstV(double []);
-       void setRefIterV(double []);
-       void setIniV(double []);
-       void setFitV(double []);
+       void setRefV(double []) noexcept;
+       void setCnstV(double []) noexcept;
+       void setRefIterV(double []) noexcept;
+       void setIniV(double []) noexcept;
+       void setFitV(double []) noexcept;
 
 
        VKVertex * nextCascadeVrt;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFit.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFit.cxx
index d498d6c3bdd5ee8e151d1a58c471a99a279aca49..aafd833e0bad4484659cb981efb1abf714f0f042 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFit.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFit.cxx
@@ -192,7 +192,7 @@ int fitVertex(VKVertex * vk)
        if(vrtForCFT.wmfit[ic]>0){    // new mass constraint
            index.clear();
            for(tk=0; tk<NTRK; tk++){ if( vrtForCFT.indtrkmc[ic][tk] )index.push_back(tk); }
-           vk->ConstraintList.emplace_back(std::make_unique<VKMassConstraint>( NTRK, vrtForCFT.wmfit[ic], index, vk));
+           vk->ConstraintList.emplace_back(std::make_unique<VKMassConstraint>( NTRK, vrtForCFT.wmfit[ic], std::move(index), vk));
         }
       }
     }
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascade.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascade.cxx
index 398977cbf6effea18aaada3d0826aa3fe59138ae..14642e3d753e860e9f00c878815a8a71a8438971 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascade.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascade.cxx
@@ -43,7 +43,7 @@ extern double cfVrtDstSig( VKVertex * , bool );
 extern void robtest(VKVertex * , long int );
 
 extern int fixPseudoTrackPt(long int NPar, double * fullMtx, double * LSide, CascadeEvent&);
-extern void getNewCov(double *OldCov, double* Der, double* Cov, long int DIM);
+extern void getNewCov(double *OldCov, double* Der, double* Cov, long int DIM) noexcept;
 
 //--------------------------------------------------------------------
 //
@@ -433,12 +433,12 @@ int fitVertexCascade( VKVertex * vk, int Pointing)
        IERR = vkMSolve(fullMatrix, fullLSide, fullNPar);
        if(IERR){ delete[] fullMatrix; delete[] fullLSide; delete[] tmpLSide; delete[] iniCovMatrix;return IERR;}
      }else{                                               //Last step. Solution+full error matrix
-       cascadeEvent_.fullCovMatrix = std::make_unique< double[] >(fullNPar*fullNPar);     //Create fresh matrix
+       cascadeEvent_.fullCovMatrix.reset( new double[fullNPar*fullNPar] );     //Create fresh matrix
        IERR = vkMSolve(fullMatrix, fullLSide, fullNPar, cascadeEvent_.fullCovMatrix.get());
        if(IERR){ delete[] fullMatrix; delete[] fullLSide; delete[] tmpLSide; delete[] iniCovMatrix;
                  cascadeEvent_.fullCovMatrix.reset(); return IERR;}
 //std::cout<<"fulcov="; for(int tt=0; tt<fullNPar; tt++)std::cout<<cascadeEvent_.fullCovMatrix[tt*fullNPar+tt]<<", "; std::cout<<'\n';
-       auto  newCov = std::make_unique<double[]>(fullNPar*fullNPar);  //Check via error transfer from left side (measured values). Gives exactly the same errors - correct!!! 
+       std::unique_ptr<double[]> newCov(new double[fullNPar*fullNPar]); //Check via error transfer from left side (measured values). Gives exactly the same errors - correct!!! 
        getNewCov(iniCovMatrix, cascadeEvent_.fullCovMatrix.get(), newCov.get(), fullNPar);
        cascadeEvent_.fullCovMatrix=std::move(newCov); //Unique_ptr will handle deletion automatically
      }
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascadeScale.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascadeScale.cxx
index 7745424f0b273bf84dc352873395a27b279ba594..eab8178064bf67ec5a724230d2aea02f31720986 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascadeScale.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CFitCascadeScale.cxx
@@ -223,7 +223,7 @@ std::cout<<"================================================="<<sum_dstToVrt<<'\
 //  if(sum_dstToVrt>limDstToVrt*(cascadeEvent_.cascadeNV-1) )return -2;        //Pointing is not resolved
 
   long int fullNPar = getCascadeNPar(cascadeEvent_);
-  cascadeEvent_.fullCovMatrix = std::make_unique< double[] >(fullNPar*fullNPar);
+  cascadeEvent_.fullCovMatrix.reset( new double[fullNPar*fullNPar] );
   for(int im=0; im<fullNPar*fullNPar; im++)cascadeEvent_.fullCovMatrix[im]=0.;
   for(int im=0; im<fullNPar; im++)cascadeEvent_.fullCovMatrix[im*fullNPar + im]=1.;
   int NStart=0;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeDefinition.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeDefinition.cxx
index 530160e29efa042db35e62e1bde2372f5223d8ef..348991dbb33a8008e0bf22cc8cd27f179d471790 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeDefinition.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeDefinition.cxx
@@ -263,7 +263,7 @@ int setCascadeMassConstraint(CascadeEvent & cascadeEvent_, long int IV, std::vec
        tmpIndex.push_back(pseudoInVrt[it]+nRealTrk);
     }
 
-    vk->ConstraintList.emplace_back(new VKMassConstraint( NTRK, Mass, tmpIndex, vk));
+    vk->ConstraintList.emplace_back(new VKMassConstraint( NTRK, Mass, std::move(tmpIndex), vk));
     return 0; 
 }
 
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeUtils.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeUtils.cxx
index 953db14246d5e6c1cbfcbf0c8e0b211e4d0bbab9..48edfcf8c94f1c0a9ffef0c3871874e1a99fe1db 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeUtils.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/CascadeUtils.cxx
@@ -22,9 +22,10 @@ int fixPseudoTrackPt(long int NPar, double * fullMtx, double * LSide, CascadeEve
 {
 
    int iv,it,ivnext;
-   auto DerivC = std::make_unique<double[]>(NPar);
-   auto DerivP = std::make_unique<double[]>(NPar);
-   auto DerivT = std::make_unique<double[]>(NPar);
+   //Deliberately not make_unique to bypass inititalization
+   std::unique_ptr<double[]> DerivC( new double[NPar] );
+   std::unique_ptr<double[]> DerivP( new double[NPar] );
+   std::unique_ptr<double[]> DerivT( new double[NPar] );
 //
    std::vector<double> vMagFld; double vBx,vBy,vBz;
    for( iv=0; iv<cascadeEvent_.cascadeNV; iv++){
@@ -265,7 +266,7 @@ void copyFullMtx(double *Input, long int IPar, long int IDIM,
 //--------------------------------------------------------------------
 //  Make the convolution Cov=D*OldCov*Dt
 //
-void getNewCov(double *OldCov, double* Der, double* Cov, long int DIM)
+void getNewCov(double *OldCov, double* Der, double* Cov, long int DIM) noexcept
 {
    int i,j,it,jt;
    for( i=0; i<DIM; i++){
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/FullMtx.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/FullMtx.cxx
index cc063af2435e1d8b03570e3b831a7127ab3b8554..b2fda0b2e4f43f6fdd14eab1051c319b4e1af170 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/FullMtx.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/FullMtx.cxx
@@ -1,7 +1,7 @@
-/*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
-*/
-
+/*
+  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+*/
+
 #include "TrkVKalVrtCore/CommonPars.h"
 #include "TrkVKalVrtCore/TrkVKalVrtCoreBase.h"
 #include "TrkVKalVrtCore/Derivt.h"
@@ -90,19 +90,20 @@ int FullMCNSTfill(VKVertex * vk, double * ader, double * LSide)
 //    int NPar=3*NTrkM+3;
 
     for (i=0; i<NPar; i++) { for (j=0; j<NPar; j++) ader[i+j*NPar]=0.; }
-    std::vector<std::vector< Vect3DF> > tf0t;  // derivative collectors
-    std::vector< Vect3DF >              th0t;  // derivative collectors
+    std::vector<std::vector< const Vect3DF*> > tf0t;  // derivative collectors
+    std::vector< const Vect3DF* >              th0t;  // derivative collectors
     std::vector< double >               taa;   // derivative collectors
-    std::vector< Vect3DF > tmpVec;
+    std::vector< const Vect3DF* > tmpVec;
     for(ii=0; ii<(int)vk->ConstraintList.size();ii++){
        for(ic=0; ic<(int)vk->ConstraintList[ii]->NCDim; ic++){
          taa.push_back(  vk->ConstraintList[ii]->aa[ic] );
-         th0t.push_back( vk->ConstraintList[ii]->h0t[ic] );
+         th0t.push_back( &(vk->ConstraintList[ii]->h0t[ic]) );
          tmpVec.clear();
+         tmpVec.reserve(vk->ConstraintList[ii]->f0t.size());
          for(it=0; it<(int)vk->ConstraintList[ii]->f0t.size(); it++){
-	    tmpVec.push_back( vk->ConstraintList[ii]->f0t[it][ic] );
+	    tmpVec.push_back( &(vk->ConstraintList[ii]->f0t[it][ic]) );
          }
-	 tf0t.push_back( tmpVec );
+	 tf0t.push_back( std::move(tmpVec) );
        }
     }
 //-----------------------------------------------------------------------------
@@ -179,19 +180,19 @@ int FullMCNSTfill(VKVertex * vk, double * ader, double * LSide)
 //
     int NTrP=NTRK*3 + 3; // track part of matrix
     for(ic=0; ic<totNC; ic++){
-       ader[(0)      + (NTrP+ic)*NPar] = -2.*th0t[ic].X;
-       ader[(1)      + (NTrP+ic)*NPar] = -2.*th0t[ic].Y;
-       ader[(2)      + (NTrP+ic)*NPar] = -2.*th0t[ic].Z;
-       ader[(0)*NPar + (NTrP+ic)     ] = -2.*th0t[ic].X;
-       ader[(1)*NPar + (NTrP+ic)     ] = -2.*th0t[ic].Y;
-       ader[(2)*NPar + (NTrP+ic)     ] = -2.*th0t[ic].Z;
+       ader[(0)      + (NTrP+ic)*NPar] = -2.*th0t[ic]->X;
+       ader[(1)      + (NTrP+ic)*NPar] = -2.*th0t[ic]->Y;
+       ader[(2)      + (NTrP+ic)*NPar] = -2.*th0t[ic]->Z;
+       ader[(0)*NPar + (NTrP+ic)     ] = -2.*th0t[ic]->X;
+       ader[(1)*NPar + (NTrP+ic)     ] = -2.*th0t[ic]->Y;
+       ader[(2)*NPar + (NTrP+ic)     ] = -2.*th0t[ic]->Z;
        for (it=0; it<NTRK; ++it) {
-         ader[(it*3+3+0)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it].X;
-         ader[(it*3+3+1)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it].Y;
-         ader[(it*3+3+2)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it].Z;
-         ader[(it*3+3+0)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it].X;
-         ader[(it*3+3+1)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it].Y;
-         ader[(it*3+3+2)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it].Z;
+         ader[(it*3+3+0)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it]->X;
+         ader[(it*3+3+1)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it]->Y;
+         ader[(it*3+3+2)      + (NTrP+ic)*NPar] = - 2.*tf0t[ic][it]->Z;
+         ader[(it*3+3+0)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it]->X;
+         ader[(it*3+3+1)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it]->Y;
+         ader[(it*3+3+2)*NPar + (NTrP+ic)]      = - 2.*tf0t[ic][it]->Z;
        }
     }
 //
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/Matrix.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/Matrix.cxx
index 591265542343028793e8534b59dc0bb4c84a02c4..5dd945127905721a953b0428e047f86d80ac47c1 100644
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/Matrix.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/Matrix.cxx
@@ -42,7 +42,7 @@ double cfSmallEigenvalue(double *cov,long int n )
 
 int cfInv5(double *cov, double *wgt )
 {
-    extern void dsinv(long int *, double *, long int, long int *);
+    extern void dsinv(long int , double *, long int, long int *) noexcept;
     double dest[25];
     long int  i, j, k, N;
 /* -----------------------------------------*/
@@ -63,7 +63,7 @@ int cfInv5(double *cov, double *wgt )
 	for (j = 0; j < N; ++j) dest[i*N+j] -= X[i]*X[j]/cov[14];
     }
     long int jerr;
-    dsinv(&N, dest, N, &jerr);
+    dsinv(N, dest, N, &jerr);
     if(jerr) return jerr;
 
     double L[4]={0.,0.,0.,0.};
@@ -82,7 +82,7 @@ int cfInv5(double *cov, double *wgt )
 
 int cfdinv(double *cov, double *wgt, long int NI )
 {
-    extern void dsinv(long int *, double *, long int, long int *);
+    extern void dsinv(long int , double *, long int, long int *) noexcept;
 
     double dest[100]              /* was [10][10] */;
     long int  i, j, k, n, ib;
@@ -129,7 +129,7 @@ int cfdinv(double *cov, double *wgt, long int NI )
 /* -- INVERT */
 /* ccc      CALL DINV(N,DEST,N,TMP,JERR) */
     long int jerr;
-    dsinv(&n, dest, n, &jerr);
+    dsinv(n, dest, n, &jerr);
     //if (eig[0]<=eig[n-1]*1.e-12 && NI>0)std::cout<<" in dsinv="<<jerr<<'\n'; 
     if(jerr)return jerr;
 /* -- PACK MATRIX */
@@ -145,7 +145,7 @@ int cfdinv(double *cov, double *wgt, long int NI )
 } 
 
 
-void  dsinv(long int *n, double *a, long int DIM, long int *ifail)
+void  dsinv(long int n, double *a, long int DIM, long int *ifail) noexcept
 {
     long int a_dim1, a_offset, i__1, i__2, i__3;
     long int i__, j, k, l;
@@ -161,17 +161,17 @@ void  dsinv(long int *n, double *a, long int DIM, long int *ifail)
     /* Function Body */
     jp1 = 0;
     *ifail = 0;
-    i__1 = *n;
+    i__1 = n;
     for (j = 1; j <= i__1; ++j) {
 	if (a[j + j * a_dim1] <= 0.) {
 	    goto L150;
 	}
 	a[j + j * a_dim1] = 1. / a[j + j * a_dim1];
-	if (j == *n) {
+	if (j == n) {
 	    goto L199;
 	}
 	jp1 = j + 1;
-	i__2 = *n;
+	i__2 = n;
 	for (l = jp1; l <= i__2; ++l) {
 	    a[j + l * a_dim1] = a[j + j * a_dim1] * a[l + j * a_dim1];
 	    s1 = -a[l + (j + 1) * a_dim1];
@@ -187,15 +187,15 @@ L150:
     return;
 L199:
 
-    if (*n == 1) {
+    if (n == 1) {
 	goto L399;
     }
     a[(a_dim1 << 1) + 1] = -a[(a_dim1 << 1) + 1];
     a[a_dim1 + 2] = a[(a_dim1 << 1) + 1] * a[(a_dim1 << 1) + 2];
-    if (*n == 2) {
+    if (n == 2) {
 	goto L320;
     }
-    i__1 = *n;
+    i__1 = n;
     for (j = 3; j <= i__1; ++j) {
 	jm2 = j - 2;
 	i__2 = jm2;
@@ -216,9 +216,9 @@ L320:
     j = 1;
 L323:
     s33 = a[j + j * a_dim1];
-    if (j == *n)	goto L325;
+    if (j == n)	goto L325;
     jp1 = j + 1;
-    i__1 = *n;
+    i__1 = n;
     for (i__ = jp1; i__ <= i__1; ++i__) {
 	s33 = a[j + i__ * a_dim1] * a[i__ + j * a_dim1] + s33;
     }
@@ -229,21 +229,21 @@ L325:
     i__1 = jm1;
     for (k = 1; k <= i__1; ++k) {
 	s32 = 0.;
-	i__2 = *n;
+	i__2 = n;
 	for (i__ = j; i__ <= i__2; ++i__) {
 	    s32 = a[k + i__ * a_dim1] * a[i__ + j * a_dim1] + s32;
 	}
 	a[k + j * a_dim1] = s32;
 	a[j + k * a_dim1] = s32;
     }
-    if (j < *n)	goto L323;
+    if (j < n)	goto L323;
 L399:
     return;
 } 
 
 
 
-void scaleg(double *g, double *scale, long int N, long int mfirst)
+void scaleg(double *g, double *scale, long int N, long int mfirst) noexcept
 {
 
    long int g_dim1, g_offset, i__, j;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/TrkVKalVrtCoreBase.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/TrkVKalVrtCoreBase.cxx
index aae85b40a3e5d25dd6daa36d48ea8588c89b1ec8..26e64fad0abd3ce76602231920962faf9487521f 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/TrkVKalVrtCoreBase.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/TrkVKalVrtCoreBase.cxx
@@ -119,11 +119,11 @@ namespace Trk {
   {  
 //       for( int i=0; i<(int)includedVrt.size(); i++) includedVrt[i]=0;  // these vertice are not owned, then must not be deleted.
   }
-  void VKVertex::setRefV(double v[3]){ refV[0]=v[0]; refV[1]=v[1]; refV[2]=v[2];}
-  void VKVertex::setRefIterV(double v[]){ refIterV[0]=v[0]; refIterV[1]=v[1]; refIterV[2]=v[2];}
-  void VKVertex::setIniV(double v[3]){ iniV[0]=v[0]; iniV[1]=v[1]; iniV[2]=v[2];}
-  void VKVertex::setFitV(double v[3]){ fitV[0]=v[0]; fitV[1]=v[1]; fitV[2]=v[2];}
-  void VKVertex::setCnstV(double v[3]){ cnstV[0]=v[0]; cnstV[1]=v[1]; cnstV[2]=v[2];}
+  void VKVertex::setRefV(double v[3]) noexcept { std::copy(v, v+3, refV);}
+  void VKVertex::setRefIterV(double v[]) noexcept { std::copy(v, v+3, refIterV); }
+  void VKVertex::setIniV(double v[3]) noexcept { std::copy(v, v+3, iniV); }
+  void VKVertex::setFitV(double v[3]) noexcept { std::copy(v, v+3, fitV); }
+  void VKVertex::setCnstV(double v[3]) noexcept { std::copy(v, v+3, cnstV);}
 
 
   VKVertex::VKVertex(const VKVertex & src):        //copy constructor
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFit.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFit.cxx
index 18d510b9e67873055865772aa5bb67a3bbdebdbf..33db41f19070b487508bf7ec4015d0879c96e1f3 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFit.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFit.cxx
@@ -61,7 +61,7 @@ namespace Trk {
     int ic, jj, it, jt, ii, kt;
     int j, k, l;
 
-    extern void dsinv(long int *, double *, long int , long int *);
+    extern void dsinv(long int , double *, long int , long int *) noexcept;
     //extern void digx(double *, double *, double *, long int , long int );
     extern void vkGetEigVal(double ci[], double d[], int n);
     extern int cfdinv(double *, double *, long int);
@@ -552,7 +552,7 @@ namespace Trk {
 	  }
 //----------------------------------------------------------------------------------
 	long int NParam = NTRK*3 + 3;
-	dsinv(&NParam, vk->ader, vkalNTrkM*3+3, &IERR);
+	dsinv(NParam, vk->ader, vkalNTrkM*3+3, &IERR);
 	if ( IERR != 0) {
         std::cout << " Bad problem in CFIT inversion ierr="<<IERR<<", "<<eigv[2]<<'\n'; return IERR;
 	} 
@@ -666,7 +666,7 @@ namespace Trk {
 
   extern double finter(double , double , double , double , double , double );
   extern double cfchi2(double *, double *, VKTrack *);
-  extern double getCnstValues2( VKVertex * vk );
+  extern double getCnstValues2( VKVertex * vk ) noexcept;
   extern void applyConstraints( VKVertex * vk );
 
   double setLimitedFitVrt(VKVertex * vk, double alf, double bet, double dCoefNorm, double newVrt[3])
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitC.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitC.cxx
index 675f6e8df8d1044199cb2395603b6f52ee7144ac..6b59ab0dedd7f7a25d45af3b560c44367688b94c 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitC.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitC.cxx
@@ -13,8 +13,8 @@ namespace Trk {
 
 
     //extern void digx(double *, double *, double *, long int , long int );
-    extern void dsinv(long int *, double *, long int , long int *);
-    extern void scaleg(double *, double *, long int  ,long int );
+    extern void dsinv(long int, double *, long int , long int *) noexcept;
+    extern void scaleg(double *, double *, long int  ,long int ) noexcept;
 
 
 int vtcfitc( VKVertex * vk )
@@ -36,59 +36,62 @@ int vtcfitc( VKVertex * vk )
 //
 // Extruction of derivatives
 //
-    std::vector<std::vector< Vect3DF> > tf0t;  // derivative collectors
-    std::vector< Vect3DF >              th0t;  // derivative collectors
+    std::vector<std::vector< const Vect3DF*> > tf0t;  // derivative collectors
+    std::vector< const Vect3DF* >       th0t;  // derivative collectors
     std::vector< double >               taa;   // derivative collectors
-    std::vector< Vect3DF > tmpVec;
+    th0t.reserve(vk->ConstraintList.size() * vk->ConstraintList[0]->NCDim);
+    tf0t.reserve(vk->ConstraintList.size());
+	
     for(ii=0; ii<(int)vk->ConstraintList.size();ii++){
        totNC += vk->ConstraintList[ii]->NCDim;
        for(ic=0; ic<(int)vk->ConstraintList[ii]->NCDim; ic++){
          taa.push_back(  vk->ConstraintList[ii]->aa[ic] );
-         th0t.push_back( vk->ConstraintList[ii]->h0t[ic] );
-         tmpVec.clear();
+         th0t.push_back( &(vk->ConstraintList[ii]->h0t[ic]) );
+         std::vector< const Vect3DF* > tmpVec;
+         tmpVec.reserve(vk->ConstraintList[ii]->f0t.size());
          for(it=0; it<(int)vk->ConstraintList[ii]->f0t.size(); it++){
-	    tmpVec.push_back( vk->ConstraintList[ii]->f0t[it][ic] );
+	    tmpVec.push_back( &(vk->ConstraintList[ii]->f0t[it][ic]) );
          }
-	 tf0t.push_back( tmpVec );
+	 tf0t.push_back( std::move(tmpVec) );
        }
     }
     if(totNC==0)return 0;
-    tmpVec.clear();
 //
     std::vector< std::vector<double> > denom;
-    std::vector<double> tmpDV(totNC,0.);
-    for(ic=0; ic<totNC; ic++) denom.push_back( tmpDV );
+    denom.reserve(totNC);
+    for(int ic=0; ic<totNC; ic++) denom.emplace_back( totNC, 0 );
 //
 //  Start of calc
 //
-    std::vector< Vect3DF > al0(totNC);
+    //This is deliberately written without make_unqiue to bypass auto intialization!!
+    std::unique_ptr< Vect3DF[] > al0( new Vect3DF[ totNC ]);
     for(ic=0;ic<totNC; ic++){ al0[ic].X=0.; al0[ic].Y=0.; al0[ic].Z=0.;}
     std::vector<double> anum(totNC,0.);
     for (ic=0; ic<totNC; ++ic) {
 	for (it = 0; it<NTRK; ++it) {
 
 /*   summation of  WBCI * F0T  into vector  AL0 */
-	    al0[ic].X +=  vk->tmpArr[it]->wbci[0] * tf0t[ic][it].X 
-		        + vk->tmpArr[it]->wbci[3] * tf0t[ic][it].Y 
-		        + vk->tmpArr[it]->wbci[6] * tf0t[ic][it].Z;
-	    al0[ic].Y +=  vk->tmpArr[it]->wbci[1] * tf0t[ic][it].X
-		        + vk->tmpArr[it]->wbci[4] * tf0t[ic][it].Y 
-		        + vk->tmpArr[it]->wbci[7] * tf0t[ic][it].Z;
-	    al0[ic].Z +=  vk->tmpArr[it]->wbci[2] * tf0t[ic][it].X 
-		        + vk->tmpArr[it]->wbci[5] * tf0t[ic][it].Y 
-		        + vk->tmpArr[it]->wbci[8] * tf0t[ic][it].Z;
+	    al0[ic].X +=  vk->tmpArr[it]->wbci[0] * tf0t[ic][it]->X
+		        + vk->tmpArr[it]->wbci[3] * tf0t[ic][it]->Y
+		        + vk->tmpArr[it]->wbci[6] * tf0t[ic][it]->Z;
+	    al0[ic].Y +=  vk->tmpArr[it]->wbci[1] * tf0t[ic][it]->X
+		        + vk->tmpArr[it]->wbci[4] * tf0t[ic][it]->Y
+		        + vk->tmpArr[it]->wbci[7] * tf0t[ic][it]->Z;
+	    al0[ic].Z +=  vk->tmpArr[it]->wbci[2] * tf0t[ic][it]->X
+		        + vk->tmpArr[it]->wbci[5] * tf0t[ic][it]->Y
+		        + vk->tmpArr[it]->wbci[8] * tf0t[ic][it]->Z;
 
-	    anum[ic] +=  vk->tmpArr[it]->parf0[0] * tf0t[ic][it].X
-	               + vk->tmpArr[it]->parf0[1] * tf0t[ic][it].Y 
-		       + vk->tmpArr[it]->parf0[2] * tf0t[ic][it].Z;
+	    anum[ic] +=  vk->tmpArr[it]->parf0[0] * tf0t[ic][it]->X
+	               + vk->tmpArr[it]->parf0[1] * tf0t[ic][it]->Y
+		       + vk->tmpArr[it]->parf0[2] * tf0t[ic][it]->Z;
 
 	}
-	al0[ic].X -=  th0t[ic].X;
-	al0[ic].Y -=  th0t[ic].Y;
-	al0[ic].Z -=  th0t[ic].Z;
-	anum[ic] = 2.*anum[ic] + dxyz[0] * 2. * th0t[ic].X 
-	                       + dxyz[1] * 2. * th0t[ic].Y
-		               + dxyz[2] * 2. * th0t[ic].Z
+	al0[ic].X -=  th0t[ic]->X;
+	al0[ic].Y -=  th0t[ic]->Y;
+	al0[ic].Z -=  th0t[ic]->Z;
+	anum[ic] = 2.*anum[ic] + dxyz[0] * 2. * th0t[ic]->X 
+	                       + dxyz[1] * 2. * th0t[ic]->Y
+		               + dxyz[2] * 2. * th0t[ic]->Z
 		               + taa[ic];
     }
 
@@ -100,7 +103,6 @@ int vtcfitc( VKVertex * vk )
 
 
 /*  calculation (AL0)t * VCOV * AL0 and (F0T)t * WCI * F0T */
-    TWRK * t_trk;
     for (ic=0; ic<totNC; ++ic) {
 	for (jc=0; jc<totNC; ++jc) {
 	    denom[ic][jc] =     al0[ic].X * vk->fitVcov[0] * al0[jc].X 
@@ -123,25 +125,25 @@ int vtcfitc( VKVertex * vk )
 			      + al0[jc].Z * vk->fitVcov[5] * al0[ic].Z;
 
 	    for (it=0; it<NTRK; ++it) {
-                t_trk=vk->tmpArr[it].get();
-		denom[ic][jc] +=          tf0t[ic][it].X * t_trk->wci[0] * tf0t[jc][it].X 
-					+ tf0t[ic][it].Y * t_trk->wci[1] * tf0t[jc][it].X 
-					+ tf0t[ic][it].Z * t_trk->wci[3] * tf0t[jc][it].X 
-					+ tf0t[ic][it].X * t_trk->wci[1] * tf0t[jc][it].Y 
-					+ tf0t[ic][it].Y * t_trk->wci[2] * tf0t[jc][it].Y 
-					+ tf0t[ic][it].Z * t_trk->wci[4] * tf0t[jc][it].Y 
-					+ tf0t[ic][it].X * t_trk->wci[3] * tf0t[jc][it].Z 
-					+ tf0t[ic][it].Y * t_trk->wci[4] * tf0t[jc][it].Z 
-					+ tf0t[ic][it].Z * t_trk->wci[5] * tf0t[jc][it].Z 
-					+ tf0t[jc][it].X * t_trk->wci[0] * tf0t[ic][it].X 
-					+ tf0t[jc][it].Y * t_trk->wci[1] * tf0t[ic][it].X 
-					+ tf0t[jc][it].Z * t_trk->wci[3] * tf0t[ic][it].X 
-					+ tf0t[jc][it].X * t_trk->wci[1] * tf0t[ic][it].Y 
-					+ tf0t[jc][it].Y * t_trk->wci[2] * tf0t[ic][it].Y 
-					+ tf0t[jc][it].Z * t_trk->wci[4] * tf0t[ic][it].Y 
-					+ tf0t[jc][it].X * t_trk->wci[3] * tf0t[ic][it].Z 
-					+ tf0t[jc][it].Y * t_trk->wci[4] * tf0t[ic][it].Z 
-					+ tf0t[jc][it].Z * t_trk->wci[5] * tf0t[ic][it].Z;
+                TWRK * t_trk=vk->tmpArr[it].get();
+		denom[ic][jc] +=          tf0t[ic][it]->X * t_trk->wci[0] * tf0t[jc][it]->X 
+					+ tf0t[ic][it]->Y * t_trk->wci[1] * tf0t[jc][it]->X 
+					+ tf0t[ic][it]->Z * t_trk->wci[3] * tf0t[jc][it]->X 
+					+ tf0t[ic][it]->X * t_trk->wci[1] * tf0t[jc][it]->Y 
+					+ tf0t[ic][it]->Y * t_trk->wci[2] * tf0t[jc][it]->Y 
+					+ tf0t[ic][it]->Z * t_trk->wci[4] * tf0t[jc][it]->Y 
+					+ tf0t[ic][it]->X * t_trk->wci[3] * tf0t[jc][it]->Z 
+					+ tf0t[ic][it]->Y * t_trk->wci[4] * tf0t[jc][it]->Z 
+					+ tf0t[ic][it]->Z * t_trk->wci[5] * tf0t[jc][it]->Z 
+					+ tf0t[jc][it]->X * t_trk->wci[0] * tf0t[ic][it]->X 
+					+ tf0t[jc][it]->Y * t_trk->wci[1] * tf0t[ic][it]->X 
+					+ tf0t[jc][it]->Z * t_trk->wci[3] * tf0t[ic][it]->X 
+					+ tf0t[jc][it]->X * t_trk->wci[1] * tf0t[ic][it]->Y 
+					+ tf0t[jc][it]->Y * t_trk->wci[2] * tf0t[ic][it]->Y 
+					+ tf0t[jc][it]->Z * t_trk->wci[4] * tf0t[ic][it]->Y 
+					+ tf0t[jc][it]->X * t_trk->wci[3] * tf0t[ic][it]->Z 
+					+ tf0t[jc][it]->Y * t_trk->wci[4] * tf0t[ic][it]->Z 
+					+ tf0t[jc][it]->Z * t_trk->wci[5] * tf0t[ic][it]->Z;
 	    }
 	}
     }
@@ -149,7 +151,8 @@ int vtcfitc( VKVertex * vk )
 /*    Solving of system DENOM(i,j)*COEF(j)=ANUM(i) */
 /*            for lagrange couplings               */
 /*-------------------------------------------------*/
-    auto coef = std::make_unique<double[]>(totNC);
+    //This is deliberately written without make_unqiue to bypass auto intialization!!
+    auto coef = std::unique_ptr<double[]>(new double[totNC]);
     if (totNC == 1) {
 	if (denom[0][0] != 0.) {
 	    coef[0] = anum[0] / denom[0][0];
@@ -157,10 +160,12 @@ int vtcfitc( VKVertex * vk )
 	    coef[0] = 1.e3;
 	}
     } else {
-        auto adenom = std::make_unique<double[]>(totNC*totNC);
+    	//This is deliberately written without make_unqiue to bypass auto intialization!!
+    	std::unique_ptr<double[]> adenom( new double[totNC*totNC] );
 //        auto work   = std::make_unique<double[]>(totNC*totNC);
 //        auto eigv   = std::make_unique<double[]>(totNC*totNC);
-        auto scale  = std::make_unique<double[]>(totNC);
+        std::unique_ptr<double[]> scale( new double[totNC] );
+
 	for (ic=0; ic<totNC; ic++) {
 	    for (jc=0; jc<totNC; jc++) {
 		adenom[ic*totNC + jc] = denom[ic][jc];
@@ -173,7 +178,7 @@ int vtcfitc( VKVertex * vk )
 	//    for (ic=0; ic<totNC; ++ic) { adenom[ic*totNC + ic] += sdet;}
 	//}
 /* -- INVERT */
-	dsinv(&totNC, adenom.get(), totNC, &IERR);
+	dsinv(totNC, adenom.get(), totNC, &IERR);
 	if (IERR) {
 	  return IERR;
 	}
@@ -192,7 +197,9 @@ int vtcfitc( VKVertex * vk )
     dxyz[0] = 0.;
     dxyz[1] = 0.;
     dxyz[2] = 0.;
-    tmpVec.resize(totNC);
+
+    //This is deliberately written without make_unqiue to bypass auto intialization!!
+    auto tmpVec = std::unique_ptr<Vect3DF[]>(new  Vect3DF[totNC]);
     for (ic=0; ic<totNC; ++ic) {
 	tmpVec[ic].X =     vk->fitVcov[0] * al0[ic].X 
 	                 + vk->fitVcov[1] * al0[ic].Y 
@@ -216,18 +223,18 @@ int vtcfitc( VKVertex * vk )
 
 /*  new momenta */
     for (it=0; it<NTRK; ++it) {
-        t_trk=vk->tmpArr[it].get();
+       TWRK * t_trk=vk->tmpArr[it].get();
 	tmp[0] = 0.;
 	tmp[1] = 0.;
 	tmp[2] = 0.;
 	for (ic=0; ic<totNC; ++ic) {
-	    tmp[0] += coef[ic] * ( tf0t[ic][it].X + t_trk->wb[0]*tmpVec[ic].X 
+	    tmp[0] += coef[ic] * ( tf0t[ic][it]->X + t_trk->wb[0]*tmpVec[ic].X 
 	    		 			  + t_trk->wb[1]*tmpVec[ic].Y 
 						  + t_trk->wb[2]*tmpVec[ic].Z);
-	    tmp[1] += coef[ic] * ( tf0t[ic][it].Y + t_trk->wb[3]*tmpVec[ic].X 
+	    tmp[1] += coef[ic] * ( tf0t[ic][it]->Y + t_trk->wb[3]*tmpVec[ic].X 
 	    					  + t_trk->wb[4]*tmpVec[ic].Y 
 						  + t_trk->wb[5]*tmpVec[ic].Z);
-	    tmp[2] += coef[ic] * ( tf0t[ic][it].Z + t_trk->wb[6]*tmpVec[ic].X 
+	    tmp[2] += coef[ic] * ( tf0t[ic][it]->Z + t_trk->wb[6]*tmpVec[ic].X 
 	    					  + t_trk->wb[7]*tmpVec[ic].Y
 						  + t_trk->wb[8]*tmpVec[ic].Z);
 	}
@@ -248,7 +255,7 @@ int vtcfitc( VKVertex * vk )
 //
 //  Get sum of squared aa[ic]  for all constraints. It's needed for postfit. 
 //
-double getCnstValues2( VKVertex * vk )
+double getCnstValues2( VKVertex * vk ) noexcept
 {
     if (vk->ConstraintList.empty()) return 0.;
     double sumSQ=0.;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitE.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitE.cxx
index 51fee04032e2ed1064b598509a1d1218f1bdb136..2b37e83ec60422854f602f207b8370beb9b39254 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitE.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/VtCFitE.cxx
@@ -1,7 +1,7 @@
-/*
-  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
-*/
-
+/*
+  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
+*/
+
 #include "TrkVKalVrtCore/CommonPars.h"
 #include "TrkVKalVrtCore/Derivt.h"
 #include "TrkVKalVrtCore/TrkVKalVrtCoreBase.h"
@@ -24,7 +24,7 @@ namespace Trk {
 
 int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 {
-    extern void scaleg(double *, double *, long int  ,long int );
+    extern void scaleg(double *, double *, long int  ,long int ) noexcept;
 
     int i,j,ic1,ic2;
 
@@ -32,7 +32,7 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
     double  cnt = 1e8;
 
 
-    extern void dsinv(long int *, double  *, long int , long int *);
+    extern void dsinv(long int, double  *, long int , long int *) noexcept;
     extern void FullMTXfill( VKVertex* , double *);
     extern void vkSVDCmp(double**, int, int, double*, double**);
 
@@ -40,64 +40,64 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
     long int NTRK = vk->TrackList.size();
     long int IERR=0;
     long int NVar = (NTRK + 1) * 3;
-    if(vk->passNearVertex && vk->ConstraintList.empty()) {
+    if(vk->passNearVertex && vk->ConstraintList.empty()) {
                                  /*  Fit is with "pass near" constraint and then */
                                  /*     matrix is already present                */
     } else if ( !vk->ConstraintList.empty()  && useWeightScheme ) {
 /*  Full matrix inversion i */
 //
         FullMTXfill( vk, ader);
-	if ( vk->passNearVertex ) {
-          double drdpy[2][3];
-          double dpipj[3][3];
-	  for (it = 1; it <= NTRK; ++it) {
-	    drdpy[0][0] = vk->tmpArr[it-1]->drdp[0][0] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][0] * vk->FVC.ywgt[1];
-            drdpy[1][0] = vk->tmpArr[it-1]->drdp[0][0] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][0] * vk->FVC.ywgt[2];
-	    drdpy[0][1] = vk->tmpArr[it-1]->drdp[0][1] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][1] * vk->FVC.ywgt[1];
-	    drdpy[1][1] = vk->tmpArr[it-1]->drdp[0][1] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][1] * vk->FVC.ywgt[2];
-	    drdpy[0][2] = vk->tmpArr[it-1]->drdp[0][2] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][2] * vk->FVC.ywgt[1];
-	    drdpy[1][2] = vk->tmpArr[it-1]->drdp[0][2] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][2] * vk->FVC.ywgt[2];
-	    for (jt = 1; jt <= NTRK; ++jt) {   /* Matrix */
-		    for (int k = 0; k < 3; ++k) {
-			for (int l = 0; l < 3; ++l) {
-			    dpipj[k][l] = 0.;
-			    for (int j = 0; j < 2; ++j) {
-				dpipj[k][l] +=  vk->tmpArr[jt-1]->drdp[j][k] * drdpy[j][l];
-			    }
-			}
-		    }
-		    for (int k = 1; k <= 3; ++k) {
-			for (int l = 1; l <= 3; ++l) {
-			    ader_ref(it * 3 + k, jt * 3 + l) +=  dpipj[l-1][k-1];
-			}
-		    }
-	    }
-	  }
-	}
+	if ( vk->passNearVertex ) {
+          double drdpy[2][3];
+          double dpipj[3][3];
+	  for (it = 1; it <= NTRK; ++it) {
+	    drdpy[0][0] = vk->tmpArr[it-1]->drdp[0][0] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][0] * vk->FVC.ywgt[1];
+            drdpy[1][0] = vk->tmpArr[it-1]->drdp[0][0] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][0] * vk->FVC.ywgt[2];
+	    drdpy[0][1] = vk->tmpArr[it-1]->drdp[0][1] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][1] * vk->FVC.ywgt[1];
+	    drdpy[1][1] = vk->tmpArr[it-1]->drdp[0][1] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][1] * vk->FVC.ywgt[2];
+	    drdpy[0][2] = vk->tmpArr[it-1]->drdp[0][2] * vk->FVC.ywgt[0] + vk->tmpArr[it-1]->drdp[1][2] * vk->FVC.ywgt[1];
+	    drdpy[1][2] = vk->tmpArr[it-1]->drdp[0][2] * vk->FVC.ywgt[1] + vk->tmpArr[it-1]->drdp[1][2] * vk->FVC.ywgt[2];
+	    for (jt = 1; jt <= NTRK; ++jt) {   /* Matrix */
+		    for (int k = 0; k < 3; ++k) {
+			for (int l = 0; l < 3; ++l) {
+			    dpipj[k][l] = 0.;
+			    for (int j = 0; j < 2; ++j) {
+				dpipj[k][l] +=  vk->tmpArr[jt-1]->drdp[j][k] * drdpy[j][l];
+			    }
+			}
+		    }
+		    for (int k = 1; k <= 3; ++k) {
+			for (int l = 1; l <= 3; ++l) {
+			    ader_ref(it * 3 + k, jt * 3 + l) +=  dpipj[l-1][k-1];
+			}
+		    }
+	    }
+	  }
+	}
         Vect3DF th0t,tf0t;
         for(ic1=0; ic1<(int)vk->ConstraintList.size();ic1++){
           for(ic2=0; ic2<vk->ConstraintList[ic1]->NCDim; ic2++){
             th0t = vk->ConstraintList[ic1]->h0t[ic2];
-            ader_ref(1, 1) += cnt * th0t.X * th0t.X;
-            ader_ref(2, 1) += cnt * th0t.Y * th0t.X;
-            ader_ref(3, 1) += cnt * th0t.Z * th0t.X;
-            ader_ref(1, 2) += cnt * th0t.X * th0t.Y;
-            ader_ref(2, 2) += cnt * th0t.Y * th0t.Y;
-            ader_ref(3, 2) += cnt * th0t.Z * th0t.Y;
-            ader_ref(1, 3) += cnt * th0t.X * th0t.Z;
-            ader_ref(2, 3) += cnt * th0t.Y * th0t.Z;
-            ader_ref(3, 3) += cnt * th0t.Z * th0t.Z;
-	    for (it = 1; it <= NTRK; ++it) {
-                tf0t = vk->ConstraintList[ic1]->f0t[it-1][ic2];
-		ader_ref(1, it * 3 + 1) += cnt * th0t.X * tf0t.X;
-		ader_ref(2, it * 3 + 1) += cnt * th0t.Y * tf0t.X;
-		ader_ref(3, it * 3 + 1) += cnt * th0t.Z * tf0t.X;
-		ader_ref(1, it * 3 + 2) += cnt * th0t.X * tf0t.Y;
-		ader_ref(2, it * 3 + 2) += cnt * th0t.Y * tf0t.Y;
-		ader_ref(3, it * 3 + 2) += cnt * th0t.Z * tf0t.Y;
-		ader_ref(1, it * 3 + 3) += cnt * th0t.X * tf0t.Z;
-		ader_ref(2, it * 3 + 3) += cnt * th0t.Y * tf0t.Z;
-		ader_ref(3, it * 3 + 3) += cnt * th0t.Z * tf0t.Z;
+            ader_ref(1, 1) += cnt * th0t.X * th0t.X;
+            ader_ref(2, 1) += cnt * th0t.Y * th0t.X;
+            ader_ref(3, 1) += cnt * th0t.Z * th0t.X;
+            ader_ref(1, 2) += cnt * th0t.X * th0t.Y;
+            ader_ref(2, 2) += cnt * th0t.Y * th0t.Y;
+            ader_ref(3, 2) += cnt * th0t.Z * th0t.Y;
+            ader_ref(1, 3) += cnt * th0t.X * th0t.Z;
+            ader_ref(2, 3) += cnt * th0t.Y * th0t.Z;
+            ader_ref(3, 3) += cnt * th0t.Z * th0t.Z;
+	    for (it = 1; it <= NTRK; ++it) {
+                tf0t = vk->ConstraintList[ic1]->f0t[it-1][ic2];
+		ader_ref(1, it * 3 + 1) += cnt * th0t.X * tf0t.X;
+		ader_ref(2, it * 3 + 1) += cnt * th0t.Y * tf0t.X;
+		ader_ref(3, it * 3 + 1) += cnt * th0t.Z * tf0t.X;
+		ader_ref(1, it * 3 + 2) += cnt * th0t.X * tf0t.Y;
+		ader_ref(2, it * 3 + 2) += cnt * th0t.Y * tf0t.Y;
+		ader_ref(3, it * 3 + 2) += cnt * th0t.Z * tf0t.Y;
+		ader_ref(1, it * 3 + 3) += cnt * th0t.X * tf0t.Z;
+		ader_ref(2, it * 3 + 3) += cnt * th0t.Y * tf0t.Z;
+		ader_ref(3, it * 3 + 3) += cnt * th0t.Z * tf0t.Z;
 	    }
 	  }
 	}
@@ -105,27 +105,27 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 
         for(ic1=0; ic1<(int)vk->ConstraintList.size();ic1++){
           for(ic2=0; ic2<vk->ConstraintList[ic1]->NCDim; ic2++){
-	    for (it = 1; it <= NTRK; ++it) {
-	      for (jt = it; jt <= NTRK; ++jt) {
-                Vect3DF tf0ti = vk->ConstraintList[ic1]->f0t[it-1][ic2];
-                Vect3DF tf0tj = vk->ConstraintList[ic1]->f0t[jt-1][ic2];
-	        ader_ref(it*3 + 1, jt*3 + 1) += cnt * tf0ti.X * tf0tj.X;
-	        ader_ref(it*3 + 2, jt*3 + 1) += cnt * tf0ti.Y * tf0tj.X;
-	        ader_ref(it*3 + 3, jt*3 + 1) += cnt * tf0ti.Z * tf0tj.X;
-	        ader_ref(it*3 + 1, jt*3 + 2) += cnt * tf0ti.X * tf0tj.Y;
-	        ader_ref(it*3 + 2, jt*3 + 2) += cnt * tf0ti.Y * tf0tj.Y;
-	        ader_ref(it*3 + 3, jt*3 + 2) += cnt * tf0ti.Z * tf0tj.Y;
-	        ader_ref(it*3 + 1, jt*3 + 3) += cnt * tf0ti.X * tf0tj.Z;
-	        ader_ref(it*3 + 2, jt*3 + 3) += cnt * tf0ti.Y * tf0tj.Z;
-	        ader_ref(it*3 + 3, jt*3 + 3) += cnt * tf0ti.Z * tf0tj.Z;
+	    for (it = 1; it <= NTRK; ++it) {
+	      for (jt = it; jt <= NTRK; ++jt) {
+                Vect3DF tf0ti = vk->ConstraintList[ic1]->f0t[it-1][ic2];
+                Vect3DF tf0tj = vk->ConstraintList[ic1]->f0t[jt-1][ic2];
+	        ader_ref(it*3 + 1, jt*3 + 1) += cnt * tf0ti.X * tf0tj.X;
+	        ader_ref(it*3 + 2, jt*3 + 1) += cnt * tf0ti.Y * tf0tj.X;
+	        ader_ref(it*3 + 3, jt*3 + 1) += cnt * tf0ti.Z * tf0tj.X;
+	        ader_ref(it*3 + 1, jt*3 + 2) += cnt * tf0ti.X * tf0tj.Y;
+	        ader_ref(it*3 + 2, jt*3 + 2) += cnt * tf0ti.Y * tf0tj.Y;
+	        ader_ref(it*3 + 3, jt*3 + 2) += cnt * tf0ti.Z * tf0tj.Y;
+	        ader_ref(it*3 + 1, jt*3 + 3) += cnt * tf0ti.X * tf0tj.Z;
+	        ader_ref(it*3 + 2, jt*3 + 3) += cnt * tf0ti.Y * tf0tj.Z;
+	        ader_ref(it*3 + 3, jt*3 + 3) += cnt * tf0ti.Z * tf0tj.Z;
 	      }
 	    }	    
 	  }
 	}
 /* symmetrisation */
-	for (i=1; i<=NVar-1; ++i) {
-	    for (j = i+1; j<=NVar; ++j) {
-		ader_ref(j,i) = ader_ref(i,j);
+	for (i=1; i<=NVar-1; ++i) {
+	    for (j = i+1; j<=NVar; ++j) {
+		ader_ref(j,i) = ader_ref(i,j);
 	    }
 	}
 //-------------------------------------------------------------------------
@@ -147,8 +147,8 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 /* weight matrix ready.Invert */
         double * Scale=new double[NVar]; scaleg(ader, Scale, NVar, vkalNTrkM*3+3);              // Balance matrix
         double **ta = new double*[NVar+1]; for(i=0; i<NVar+1; i++) ta[i] = new double[NVar+1];  // Make a copy 
- 	for (i=1; i<=NVar; ++i) for (j = i; j<=NVar; ++j) ta[i][j] = ta[j][i] = ader_ref(i,j);  // for failure treatment
-	dsinv(&NVar, ader, vkalNTrkM*3+3, &IERR);
+ 	for (i=1; i<=NVar; ++i) for (j = i; j<=NVar; ++j) ta[i][j] = ta[j][i] = ader_ref(i,j);  // for failure treatment
+	dsinv(NVar, ader, vkalNTrkM*3+3, &IERR);
 	if ( IERR != 0) {
           double **tv = new double*[NVar+1]; for(i=0; i<NVar+1; i++) tv[i] = new double[NVar+1];
           double **tr = new double*[NVar+1]; for(i=0; i<NVar+1; i++) tr[i] = new double[NVar+1];
@@ -161,12 +161,12 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
           for(i=1; i<=NVar; i++){ for(j=1; j<=NVar; j++){
             tr[i][j]=0.; for(int k=1; k<=NVar; k++)  if(tw[k]!=0.) tr[i][j] += ta[i][k]*tv[j][k]/tw[k];
           }} 
-	  for (i=1; i<=NVar; ++i) for (j=1; j<=NVar; ++j) ader_ref(i,j)=tr[i][j];
+	  for (i=1; i<=NVar; ++i) for (j=1; j<=NVar; ++j) ader_ref(i,j)=tr[i][j];
           for(i=0; i<NVar+1; i++) {delete[] tv[i];delete[] tr[i];} 
 	  delete[] tv; delete[] tr; delete[] tw;	
 	  IERR=0; //return IERR;
         }
- 	for (i=1; i<=NVar; ++i) for (j = 1; j<=NVar; ++j) ader_ref(i,j)*=Scale[i-1]*Scale[j-1];
+ 	for (i=1; i<=NVar; ++i) for (j = 1; j<=NVar; ++j) ader_ref(i,j)*=Scale[i-1]*Scale[j-1];
         delete[] Scale; //Restore scale
         for(i=0; i<NVar+1; i++) delete[] ta[i];
         delete[] ta;                 //Clean memory
@@ -174,60 +174,60 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
     } else {
 /* ---------------------------------------- */
 /* Simple and fast without constraints */
-	for (i=1; i<=NVar; i++) {
-	    for (j=1; j<=NVar; j++) {
-		ader_ref(i,j)=0.;
-	    }
-	}
-        double vcov[6]={vk->fitVcov[0],vk->fitVcov[1],vk->fitVcov[2],vk->fitVcov[3],vk->fitVcov[4],vk->fitVcov[5]};
-	ader_ref(1,1) = vcov[0];
-	ader_ref(1,2) = vcov[1];
-	ader_ref(2,2) = vcov[2];
-	ader_ref(1,3) = vcov[3];
-	ader_ref(2,3) = vcov[4];
-	ader_ref(3,3) = vcov[5];
-	ader_ref(2,1) = ader_ref(1,2);
-	ader_ref(3,1) = ader_ref(1,3);
-	ader_ref(3,2) = ader_ref(2,3);
+	for (i=1; i<=NVar; i++) {
+	    for (j=1; j<=NVar; j++) {
+		ader_ref(i,j)=0.;
+	    }
+	}
+        double vcov[6]={vk->fitVcov[0],vk->fitVcov[1],vk->fitVcov[2],vk->fitVcov[3],vk->fitVcov[4],vk->fitVcov[5]};
+	ader_ref(1,1) = vcov[0];
+	ader_ref(1,2) = vcov[1];
+	ader_ref(2,2) = vcov[2];
+	ader_ref(1,3) = vcov[3];
+	ader_ref(2,3) = vcov[4];
+	ader_ref(3,3) = vcov[5];
+	ader_ref(2,1) = ader_ref(1,2);
+	ader_ref(3,1) = ader_ref(1,3);
+	ader_ref(3,2) = ader_ref(2,3);
 
-	for (it=1; it<=NTRK; it++) {
+	for (it=1; it<=NTRK; it++) {
             t_trk=vk->tmpArr[it-1].get();
-	    ader_ref(1, it*3 + 1) = -vcov[0] * t_trk->wbci[0] 
-	                           - vcov[1] * t_trk->wbci[1] 
-				   - vcov[3] * t_trk->wbci[2];
-	    ader_ref(2, it*3 + 1) = -vcov[1] * t_trk->wbci[0] 
-	                           - vcov[2] * t_trk->wbci[1] 
-				   - vcov[4] * t_trk->wbci[2];
-	    ader_ref(3, it*3 + 1) = -vcov[3] * t_trk->wbci[0] 
-	                           - vcov[4] * t_trk->wbci[1] 
-				   - vcov[5] * t_trk->wbci[2];
-	    ader_ref(1, it*3 + 2) = -vcov[0] * t_trk->wbci[3] 
-	                           - vcov[1] * t_trk->wbci[4] 
-		                   - vcov[3] * t_trk->wbci[5];
-	    ader_ref(2, it*3 + 2) = -vcov[1] * t_trk->wbci[3] 
-	                           - vcov[2] * t_trk->wbci[4] 
-				   - vcov[4] * t_trk->wbci[5];
-	    ader_ref(3, it*3 + 2) = -vcov[3] * t_trk->wbci[3] 
-	                           - vcov[4] * t_trk->wbci[4] 
-				   - vcov[5] * t_trk->wbci[5];
-	    ader_ref(1, it*3 + 3) = -vcov[0] * t_trk->wbci[6] 
-	                           - vcov[1] * t_trk->wbci[7] 
-				   - vcov[3] * t_trk->wbci[8];
-	    ader_ref(2, it*3 + 3) = -vcov[1] * t_trk->wbci[6] 
-	                           - vcov[2] * t_trk->wbci[7] 
-				   - vcov[4] * t_trk->wbci[8];
-	    ader_ref(3, it*3 + 3) = -vcov[3] * t_trk->wbci[6]  
+	    ader_ref(1, it*3 + 1) = -vcov[0] * t_trk->wbci[0] 
+	                           - vcov[1] * t_trk->wbci[1] 
+				   - vcov[3] * t_trk->wbci[2];
+	    ader_ref(2, it*3 + 1) = -vcov[1] * t_trk->wbci[0] 
+	                           - vcov[2] * t_trk->wbci[1] 
+				   - vcov[4] * t_trk->wbci[2];
+	    ader_ref(3, it*3 + 1) = -vcov[3] * t_trk->wbci[0] 
+	                           - vcov[4] * t_trk->wbci[1] 
+				   - vcov[5] * t_trk->wbci[2];
+	    ader_ref(1, it*3 + 2) = -vcov[0] * t_trk->wbci[3] 
+	                           - vcov[1] * t_trk->wbci[4] 
+		                   - vcov[3] * t_trk->wbci[5];
+	    ader_ref(2, it*3 + 2) = -vcov[1] * t_trk->wbci[3] 
+	                           - vcov[2] * t_trk->wbci[4] 
+				   - vcov[4] * t_trk->wbci[5];
+	    ader_ref(3, it*3 + 2) = -vcov[3] * t_trk->wbci[3] 
+	                           - vcov[4] * t_trk->wbci[4] 
+				   - vcov[5] * t_trk->wbci[5];
+	    ader_ref(1, it*3 + 3) = -vcov[0] * t_trk->wbci[6] 
+	                           - vcov[1] * t_trk->wbci[7] 
+				   - vcov[3] * t_trk->wbci[8];
+	    ader_ref(2, it*3 + 3) = -vcov[1] * t_trk->wbci[6] 
+	                           - vcov[2] * t_trk->wbci[7] 
+				   - vcov[4] * t_trk->wbci[8];
+	    ader_ref(3, it*3 + 3) = -vcov[3] * t_trk->wbci[6]  
 		                   			- vcov[4] * t_trk->wbci[7] 
 				   			- vcov[5] * t_trk->wbci[8];
-	    ader_ref(it*3 + 1, 1) = ader_ref(1, it*3 + 1);
-	    ader_ref(it*3 + 1, 2) = ader_ref(2, it*3 + 1);
-	    ader_ref(it*3 + 1, 3) = ader_ref(3, it*3 + 1);
-	    ader_ref(it*3 + 2, 1) = ader_ref(1, it*3 + 2);
-	    ader_ref(it*3 + 2, 2) = ader_ref(2, it*3 + 2);
-	    ader_ref(it*3 + 2, 3) = ader_ref(3, it*3 + 2);
-	    ader_ref(it*3 + 3, 1) = ader_ref(1, it*3 + 3);
-	    ader_ref(it*3 + 3, 2) = ader_ref(2, it*3 + 3);
-	    ader_ref(it*3 + 3, 3) = ader_ref(3, it*3 + 3);
+	    ader_ref(it*3 + 1, 1) = ader_ref(1, it*3 + 1);
+	    ader_ref(it*3 + 1, 2) = ader_ref(2, it*3 + 1);
+	    ader_ref(it*3 + 1, 3) = ader_ref(3, it*3 + 1);
+	    ader_ref(it*3 + 2, 1) = ader_ref(1, it*3 + 2);
+	    ader_ref(it*3 + 2, 2) = ader_ref(2, it*3 + 2);
+	    ader_ref(it*3 + 2, 3) = ader_ref(3, it*3 + 2);
+	    ader_ref(it*3 + 3, 1) = ader_ref(1, it*3 + 3);
+	    ader_ref(it*3 + 3, 2) = ader_ref(2, it*3 + 3);
+	    ader_ref(it*3 + 3, 3) = ader_ref(3, it*3 + 3);
 	}
 
 
@@ -298,7 +298,7 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 // R*Cov matrix
           for(ic=0; ic<totNC; ic++){
 	    for(j=0; j<NVar; j++){ RC[ic][j]=0;
-	      for(i=0; i<NVar; i++) RC[ic][j] += R[ic][i]*ader_ref(i+1,j+1);
+	      for(i=0; i<NVar; i++) RC[ic][j] += R[ic][i]*ader_ref(i+1,j+1);
             }
           }
 // R*Cov*Rt matrix        -  Lagrange multiplyers errors
@@ -307,7 +307,7 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 	      for(i=0; i<NVar; i++) RCRt[ic*totNC + jc] += RC[ic][i]*R[jc][i];
 	    }
           }
-	  dsinv(&totNC, RCRt, totNC, &IERR);
+	  dsinv(totNC, RCRt, totNC, &IERR);
 	  if ( IERR != 0) return IERR;
 // Correction matrix
 	 for(i=0; i<NVar; i++){
@@ -317,7 +317,7 @@ int getFullVrtCov(VKVertex * vk, double *ader, double *dcv, double verr[6][6])
 	         COR += RC[ic][i]*RC[jc][j]*RCRt[ic*totNC +jc];
 	       }
 	     }
-	     ader_ref(i+1, j+1) -= COR;
+	     ader_ref(i+1, j+1) -= COR;
 	   }
 	 }
 // Delete temporary matrices
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/cfMassErr.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/cfMassErr.cxx
index 6232b780b3effb6a458a17ce0ca3453ab6cf8e57..94f12938be7a1f20c3fa9203aa16c22fca901b43 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/cfMassErr.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/cfMassErr.cxx
@@ -14,7 +14,8 @@ namespace Trk {
 void cfmasserr(VKVertex * vk, int *list, double BMAG, double *MASS, double *sigM)
 {
   int NTRK=vk->TrackList.size();
-  auto deriv = std::make_unique< double[] >(3*NTRK+3);
+  //Deliberately not using make_unique
+  std::unique_ptr < double[] > deriv(new double[3*NTRK+3]);
   double ptot[4]={0.};
   std::vector< std::array<double,6> > pmom(NTRK);
   double dm2dpx, dm2dpy, dm2dpz, ee, pt, px, py, pz, cth;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/stCnst.cxx b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/stCnst.cxx
index 361b74d698d64c23e89f72ae8fc93f8d0dec836e..e32c0fcf7806c3fd0ddedbbe2b4f1f179a7c0fad 100755
--- a/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/stCnst.cxx
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtCore/src/stCnst.cxx
@@ -81,11 +81,10 @@ void applyConstraints(VKVertex * vk)
   {
     for(int i=0; i<NTrk; i++) m_usedParticles[i]=i;
   }
-  VKMassConstraint::VKMassConstraint(int NTRK, double mass, const std::vector<int> &listTrk, VKVertex *vk) :
+  VKMassConstraint::VKMassConstraint(int NTRK, double mass, std::vector<int> listTrk, VKVertex *vk) :
     VKConstraintBase(1,NTRK, VKContraintType::Mass, vk),
-    m_usedParticles(0), m_targetMass(mass)
+    m_usedParticles(std::move(listTrk)), m_targetMass(mass)
   {
-    for(int i=0; i<(int)listTrk.size(); i++) m_usedParticles.push_back(listTrk[i]);
     m_originVertex = vk;
   }
   VKMassConstraint::~VKMassConstraint()= default;
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtFitter/CMakeLists.txt b/Tracking/TrkVertexFitter/TrkVKalVrtFitter/CMakeLists.txt
index ee0c6669817642ef795d4f64f707c6df3248fa55..64f679e0c4127681bfebddd239ed0f5009e7b0ed 100644
--- a/Tracking/TrkVertexFitter/TrkVKalVrtFitter/CMakeLists.txt
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtFitter/CMakeLists.txt
@@ -24,7 +24,7 @@ atlas_add_component( TrkVKalVrtFitter
    LINK_LIBRARIES TrkVKalVrtFitterLib )
 
 # Install files from the package.
-atlas_install_python_modules( python/*.py )
+atlas_install_python_modules( python/*.py POST_BUILD_CMD ${ATLAS_FLAKE8} )
 atlas_install_joboptions( share/*.py )
 
 # Test(s) in the package.
diff --git a/Tracking/TrkVertexFitter/TrkVKalVrtFitter/python/VKalVrtFitter.py b/Tracking/TrkVertexFitter/TrkVKalVrtFitter/python/VKalVrtFitter.py
index f1379cd0ff0d272eb695e86a43f223b64fde2d50..d10f37211c5061efe97dd948d54927151c50ea2b 100644
--- a/Tracking/TrkVertexFitter/TrkVKalVrtFitter/python/VKalVrtFitter.py
+++ b/Tracking/TrkVertexFitter/TrkVKalVrtFitter/python/VKalVrtFitter.py
@@ -1,24 +1,21 @@
 # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
 
-from GaudiKernel.GaudiHandles import *
-from AthenaCommon.Configurable import *
+from AthenaCommon.Configurable import ConfigurableAlgTool
 from AthenaCommon.Logging import logging
-from AthenaCommon.AppMgr import ToolSvc
-#
+
 from TrkVKalVrtFitterConf import Trk__TrkVKalVrtFitter
-#
+
 class InDetVKalVrtFitter( ConfigurableAlgTool ) :
 
     def __init__(self, name="InDetVKalVrtFitter"):        
 
-        from __main__ import ToolSvc
         mlog = logging.getLogger( 'InDetVKalVrtFitter::__init__ ' )
         mlog.info("entering")
 
         Trk__TrkVKalVrtFitter.__init__( self,name="Trk__TrkVKalVrtFitter",
-	                     Extrapolator="Trk::Extrapolator/InDetExtrapolator",
-			     MagFieldSvc="Trk::MagneticFieldTool/InDetMagField" )
-	   
+                             Extrapolator="Trk::Extrapolator/InDetExtrapolator",
+                             MagFieldSvc="Trk::MagneticFieldTool/InDetMagField" )
+
 
 class VKalFitterForAnalysis( ConfigurableAlgTool ) :
 
@@ -28,9 +25,9 @@ class VKalFitterForAnalysis( ConfigurableAlgTool ) :
         mlog.info("entering")
 
         Trk__TrkVKalVrtFitter.__init__( self,name="Trk__TrkVKalVrtFitter",
-	                     Extrapolator="DefaultVKalPropagator",   # Internal VKal propagator
-			     MagFieldSvc="DefaultMagneticField"    # Internal VKal field
-			     )
+                             Extrapolator="DefaultVKalPropagator",   # Internal VKal propagator
+                             MagFieldSvc="DefaultMagneticField"    # Internal VKal field
+                             )
 
 class VKalFitterForAnalysisWithField( ConfigurableAlgTool ) :
 
@@ -40,7 +37,7 @@ class VKalFitterForAnalysisWithField( ConfigurableAlgTool ) :
         mlog.info("entering")
 
         Trk__TrkVKalVrtFitter.__init__( self,name="Trk__TrkVKalVrtFitter",
-	                     Extrapolator="DefaultVKalPropagator",      # internal VKal propagatorcd 
-			     MagFieldSvc="DefaultMagneticField",  
-			     MagFieldAtlasService="MagFieldAthenaSvc" # ATLAS mag field 
-			     )
+                             Extrapolator="DefaultVKalPropagator",      # internal VKal propagatorcd
+                             MagFieldSvc="DefaultMagneticField",
+                             MagFieldAtlasService="MagFieldAthenaSvc" # ATLAS mag field
+                             )
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.cxx
index f111c28f6ce0296a05d4d2b5c7e76711713b5a44..12ce977dda87240bde2a2353352a270d141073fc 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.cxx
@@ -37,7 +37,7 @@ void TrigL2MuonSA::AlphaBetaEstimate::setMCFlag(BooleanProperty use_mcLUT,
 StatusCode TrigL2MuonSA::AlphaBetaEstimate::setAlphaBeta(const LVL1::RecMuonRoI*   p_roi,
 							 TrigL2MuonSA::TgcFitResult& tgcFitResult,
 							 TrigL2MuonSA::TrackPattern& trackPattern,
-                                                         const TrigL2MuonSA::MuonRoad& /*muonRoad*/)
+                                                         const TrigL2MuonSA::MuonRoad& /*muonRoad*/) const
 {
   const int MAX_STATION = 6;
   const double PHI_RANGE = 12./(M_PI/8.);
@@ -270,7 +270,7 @@ StatusCode TrigL2MuonSA::AlphaBetaEstimate::setAlphaBeta(const LVL1::RecMuonRoI*
 
 double TrigL2MuonSA::AlphaBetaEstimate::computeRadius(double InnerSlope, double InnerR, double InnerZ,
 						       double MiddleSlope, double MiddleR, double MiddleZ,
-						       double sign)
+						       double sign) const
 {
   double cr1 = 0.080/400;
   double cr2 = cr1;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.h
index 35ddd6ddff8c8adf7e728cd748d7e5817e5281e4..d36f725969bb874828ffc038a70a0282d70052d9 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/AlphaBetaEstimate.h
@@ -35,13 +35,13 @@ class AlphaBetaEstimate: public AthAlgTool
   StatusCode setAlphaBeta(const LVL1::RecMuonRoI*       p_roi,
 			  TrigL2MuonSA::TgcFitResult&   tgcFitResult,
 			  TrigL2MuonSA::TrackPattern&   trackPattern,
-			  const TrigL2MuonSA::MuonRoad& muonRoad);
+			  const TrigL2MuonSA::MuonRoad& muonRoad) const;
 
  private:
 
   double computeRadius(double InnerSlope, double InnerR, double InnerZ,
 		       double MiddleSlope, double MiddleR, double MiddleZ,
-		       double sign);
+		       double sign) const;
 
   double computeRadius3Points(double InnerZ, double InnerR, double EEZ, double EER,double MiddleZ, double MiddleR ) const ;
   double calcDistance(double x1,double y1,double x2,double y2,double x3,double y3) const;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.cxx
index 69a49b9b2abc5d63494913678a88b4e32d189081..b4f636f45579e65a9774965782d634fc68f0b4d2 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.cxx
@@ -233,7 +233,7 @@ StatusCode TrigL2MuonSA::CscDataPreparator::prepareData(const TrigRoiDescriptor*
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-double TrigL2MuonSA::CscDataPreparator::calc_residual(double aw,double bw,double x,double y)
+double TrigL2MuonSA::CscDataPreparator::calc_residual(double aw,double bw,double x,double y) const
 {
   const double ZERO_LIMIT = 1e-4;
   if( fabs(aw) < ZERO_LIMIT ) return y-bw;
@@ -245,7 +245,8 @@ double TrigL2MuonSA::CscDataPreparator::calc_residual(double aw,double bw,double
 }
 
 
-double TrigL2MuonSA::CscDataPreparator::calc_residual_phi( double aw, double bw, double phiw, double hitphi, double hitz){
+double TrigL2MuonSA::CscDataPreparator::calc_residual_phi( double aw, double bw, double phiw, double hitphi, double hitz) const 
+{
 
   double roadr = hitz*aw + bw;
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.h
index bee5ac5d8abdb7a87db55947e3c7628c1ac190a0..23f8bafc3a6fc3d92c252d4a8088c77c387cf36d 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscDataPreparator.h
@@ -51,9 +51,9 @@ namespace TrigL2MuonSA {
     double calc_residual(double aw,
 			 double bw,
 			 double x,
-			 double y);
+			 double y) const;
 
-    double calc_residual_phi(double aw, double bw, double phiw, double hitphi, double hitz);
+    double calc_residual_phi(double aw, double bw, double phiw, double hitphi, double hitz) const;
 
   private:
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.cxx
index aea9e4a5b874234da3488a9e24bfd661e760545f..fc56caeecd3d1bcf280e99501ca565a44d90cd73 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.cxx
@@ -122,7 +122,7 @@ StatusCode CscRegDict :: initialize(){
 }
 
 
-int CscRegDict :: get_hash(int stationname, int stationeta, int stationphi){
+int CscRegDict :: get_hash(int stationname, int stationeta, int stationphi) const{
 
   int sname, seta, sphi;
   if (stationname == 50 || stationname == 51)  sname = stationname-50;
@@ -171,7 +171,7 @@ ReturnCode CscRegDict :: initializeHashDictionary(){
 
 
 
-Amg::Vector3D CscRegDict::nomalVector(int module){
+Amg::Vector3D CscRegDict::nomalVector(int module) const{
     
   double phi=m_reg_dict[module].phiCen;
   double theta=m_reg_dict[module].idealAtanNormal;
@@ -204,7 +204,7 @@ double CscRegDict :: posCorrectionZ(int module, int charge/*0 or 1*/){
 
 
 
-double UtilTools :: calc_phi(double x, double y){
+double UtilTools :: calc_phi(double x, double y) const{
   
   double /*abs_x=fabs(x),*/ abs_y=fabs(y);
   double abs_sine=abs_y/sqrt(x*x+y*y);
@@ -226,8 +226,8 @@ double UtilTools :: calc_phi(double x, double y){
 }
 
 
-double UtilTools :: calc_dphi(double phi1, double phi2){
-  
+double UtilTools :: calc_dphi(double phi1, double phi2) const
+{  
   double dphi=phi1-phi2;
   
   if (dphi > M_PI) {
@@ -236,13 +236,12 @@ double UtilTools :: calc_dphi(double phi1, double phi2){
     dphi += 2*M_PI;
   }
   
-  return dphi;
-  
+  return dphi; 
 }
 
 
-double UtilTools :: average_phi(double phi1, double phi2){
-  
+double UtilTools :: average_phi(double phi1, double phi2) const
+{  
   double phi = 0.;
   
   if (phi1*phi2<0. && fabs(phi1)>M_PI/2.){
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.h
index dc002d9862b2011eb9ff5cede561c62a3804cfc4..601a5456ce23c6ea1e424b6bcbe081b76acb095b 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscRegUtils.h
@@ -27,16 +27,16 @@ class UtilTools{
 public:
   UtilTools(){}
 
-  double calc_theta(double eta){ return 2*atan(exp((-1)*eta)); }
-  double calc_theta(double x, double y, double z){ return acos(z/sqrt(x*x+y*y+z*z)); } // for position not for direction theta in [0,pi]
-  double calc_eta(double x, double y, double z){return (-1)*log(tan(calc_theta(x,y,z)/2.));}
-  double calc_phi( double x, double y);
-  double calc_dphi(double phi1, double phi2);
-  double calc_sumsq(double x, double y){ return sqrt(x*x+y*y); }
-  double calc_sumsq(double x, double y, double z){ return sqrt(x*x+y*y+z*z);}
-  double cotan(double theta){ return tan(M_PI-theta); }
-  double relative_error(double measured, double reference){return (measured-reference)/reference; }
-  double average_phi(double phi1, double phi2);
+  double calc_theta(double eta) const{ return 2*atan(exp((-1)*eta)); }
+  double calc_theta(double x, double y, double z) const{ return acos(z/sqrt(x*x+y*y+z*z)); } // for position not for direction theta in [0,pi]
+  double calc_eta(double x, double y, double z) const {return (-1)*log(tan(calc_theta(x,y,z)/2.));}
+  double calc_phi( double x, double y) const;
+  double calc_dphi(double phi1, double phi2) const;
+  double calc_sumsq(double x, double y) const { return sqrt(x*x+y*y); }
+  double calc_sumsq(double x, double y, double z) const { return sqrt(x*x+y*y+z*z);}
+  double cotan(double theta) const { return tan(M_PI-theta); }
+  double relative_error(double measured, double reference) const {return (measured-reference)/reference; }
+  double average_phi(double phi1, double phi2) const;
 
 };
 
@@ -66,18 +66,18 @@ class CscRegDict: public AthAlgTool{
   virtual StatusCode initialize() override;
 
   double phiCen(int module){ return m_reg_dict[module].phiCen; }
-  double phiMod(int module){ return m_reg_dict[module].phiMod; }
+  double phiMod(int module) const { return m_reg_dict[module].phiMod; }
 
-  int get_hash(int stationname, int stationeta, int stationphi); //return a module context hashId.
-  Amg::Vector3D nomalVector(int module);
-  double displacement(int module);
+  int get_hash(int stationname, int stationeta, int stationphi) const; //return a module context hashId.
+  Amg::Vector3D nomalVector(int module) const;
+  double displacement(int module) const;
   double posCorrectionR(int module, int charge);
   double posCorrectionZ(int module, int charge);
-  double idealAtanNormal(int module){ return m_reg_dict[module].idealAtanNormal; }
-  double actualAtanNormal(int module){ return m_reg_dict[module].actualAtanNormal; }
-  int stationName(int hash);
-  int stationEta(int hash);
-  int stationPhi(int hash);
+  double idealAtanNormal(int module) const { return m_reg_dict[module].idealAtanNormal; }
+  double actualAtanNormal(int module) const { return m_reg_dict[module].actualAtanNormal; }
+  int stationName(int hash) const;
+  int stationEta(int hash) const; 
+  int stationPhi(int hash) const;
 
  private:
   Gaudi::Property< bool >  m_isMC { this, "MCFlag", true, "" };
@@ -96,16 +96,19 @@ class CscRegDict: public AthAlgTool{
 };
 
 
-inline double CscRegDict::displacement(int module){
+inline double CscRegDict::displacement(int module) const
+{
   return (0<=module && module <32) ? m_reg_dict[module].Displacement : 0.;
 }
 
-inline int CscRegDict::stationName(int hash){
+inline int CscRegDict::stationName(int hash) const
+{
    if(hash<0 || hash>31) return 999;
    else return (hash<16) ? 50 : 51;
 }
 
-inline int CscRegDict::stationEta(int hash){
+inline int CscRegDict::stationEta(int hash) const
+{
    if(hash<0 || hash>31) return 999;
    else{
      int secteta=(hash - hash%8)/8;// secteta: 0(Small Cside),1(Small Aside), 2(Large Cside), 3(Large Aside)
@@ -113,7 +116,8 @@ inline int CscRegDict::stationEta(int hash){
    }
 }
 
-inline int CscRegDict::stationPhi(int hash){
+inline int CscRegDict::stationPhi(int hash) const
+{
    if(hash<0 || hash>31) return 999;
    else return hash%8+1;
 }
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.cxx
index 9a42898f10b768076d2093bb233938b8dd333793..78bdb86380372a099cb2090d5718112ab9e48265 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.cxx
@@ -35,7 +35,7 @@ StatusCode CscSegmentMaker::initialize(){
 ReturnCode CscSegmentMaker::FindSuperPointCsc( const TrigL2MuonSA::CscHits &cscHits,
                                                 std::vector<TrigL2MuonSA::TrackPattern> &v_trackPatterns,
                                                 const TrigL2MuonSA::TgcFitResult &tgcFitResult,
-                                                const TrigL2MuonSA::MuonRoad &muroad)
+                                                const TrigL2MuonSA::MuonRoad &muroad) const
 {
   ATH_MSG_DEBUG( "FindSuperPointCsc" );
   SG::ReadCondHandle<MuonGM::MuonDetectorManager> muDetMgrHandle{m_muDetMgrKey};
@@ -143,7 +143,7 @@ ReturnCode CscSegmentMaker::FindSuperPointCsc( const TrigL2MuonSA::CscHits &cscH
 
 ReturnCode  CscSegmentMaker::make_segment(int mod_hash, TrigL2MuonSA::CscHits clusters[8],
                                             CscSegment &cscsegment,
-                                            CscSegment &cscsegment_noip, const MuonGM::MuonDetectorManager* muDetMgr)
+                                            CscSegment &cscsegment_noip, const MuonGM::MuonDetectorManager* muDetMgr) const
 {
   ATH_MSG_DEBUG("################################## make_segment #####################################");
   
@@ -261,7 +261,7 @@ ReturnCode  CscSegmentMaker::make_segment(int mod_hash, TrigL2MuonSA::CscHits cl
   ReturnCode CscSegmentMaker::make_2dsegment(int measphi, const localCscHit &ip_loc, const std::vector<localCscHit> hits_loc[4],
                                              local2dSegment &seg2d,
                                              local2dSegment &seg2d_ipremoved,
-                                             int &nhit)
+                                             int &nhit) const
 {
   
   int nohit=0;
@@ -326,7 +326,7 @@ ReturnCode  CscSegmentMaker::make_segment(int mod_hash, TrigL2MuonSA::CscHits cl
 ReturnCode CscSegmentMaker::make_2dseg4hit(int measphi, const localCscHit &ip_loc,
                                              std::vector<localCscHit>  hits_loc[4], //removing hits used in fit with 4 hits
                                              std::vector<local2dSegment> &seg2d_4hitCollection,
-                                             int &nhit)
+                                             int &nhit) const
 {
   
   std::vector<localCscHit> hit_fit;
@@ -393,7 +393,7 @@ ReturnCode CscSegmentMaker::make_2dseg4hit(int measphi, const localCscHit &ip_lo
 ReturnCode CscSegmentMaker::make_2dseg3hit(int measphi, const localCscHit &ip_loc,
                                              const std::vector<localCscHit> hits_loc[4],
                                              std::vector<local2dSegment> &seg2d_3hitCollection,
-                                             int &nhit)
+                                             int &nhit) const
 {
   
   int empty_lyr=-1;
@@ -451,7 +451,7 @@ ReturnCode CscSegmentMaker::make_2dseg3hit(int measphi, const localCscHit &ip_lo
 }
 
 
-ReturnCode CscSegmentMaker::fit_clusters(int measphi, const std::vector<localCscHit> &hits_fit, local2dSegment &seg2d){
+ReturnCode CscSegmentMaker::fit_clusters(int measphi, const std::vector<localCscHit> &hits_fit, local2dSegment &seg2d) const{
   
   
   double S=0.;
@@ -534,7 +534,7 @@ ReturnCode CscSegmentMaker::fit_clusters(int measphi, const std::vector<localCsc
 ReturnCode CscSegmentMaker::make_4dsegment(const local2dSegment &seg2d_eta,
                                              const local2dSegment &seg2d_phi,
                                              Amg::Vector3D &seg_pos,
-                                             Amg::Vector3D &seg_dir)
+                                             Amg::Vector3D &seg_dir) const
 {
   
   int nhit_e=seg2d_eta.nhit;
@@ -578,7 +578,12 @@ ReturnCode CscSegmentMaker::make_4dsegment(const local2dSegment &seg2d_eta,
 
 
 
-ReturnCode CscSegmentMaker::getModuleSP(int mod_hashes[2], const TrigL2MuonSA::TgcFitResult &tgcFitResult, int phibin, const MuonRoad &muroad, const int hash_clusters[32]){
+ReturnCode CscSegmentMaker::getModuleSP(int mod_hashes[2], 
+                                        const TrigL2MuonSA::TgcFitResult &tgcFitResult, 
+                                        int phibin, 
+                                        const MuonRoad &muroad, 
+                                        const int hash_clusters[32]) const
+{
   ATH_MSG_DEBUG("getModuleSP()");
   
   
@@ -623,7 +628,7 @@ ReturnCode CscSegmentMaker::getModuleSP(int mod_hashes[2], const TrigL2MuonSA::T
 }
 
 
-CscSegment CscSegmentMaker::segmentAtFirstLayer(int mod_hash, TrigL2MuonSA::CscSegment *mu_seg){
+CscSegment CscSegmentMaker::segmentAtFirstLayer(int mod_hash, TrigL2MuonSA::CscSegment *mu_seg) const{
   
   
   double alpha = m_cscregdict->displacement(mod_hash);
@@ -645,9 +650,8 @@ CscSegment CscSegmentMaker::segmentAtFirstLayer(int mod_hash, TrigL2MuonSA::CscS
 
 
 
-ReturnCode CscSegmentMaker::display_hits(const std::vector<localCscHit> localHits[4]){
-  
-  
+ReturnCode CscSegmentMaker::display_hits(const std::vector<localCscHit> localHits[4]) const
+{  
   for(unsigned int ilyr=0; ilyr<4; ++ilyr){
     for (unsigned int ihit=0; ihit<localHits[ilyr].size(); ++ihit) {
       const localCscHit &locHit = localHits[ilyr][ihit];
@@ -656,8 +660,7 @@ ReturnCode CscSegmentMaker::display_hits(const std::vector<localCscHit> localHit
                     << " err=" << locHit.error << " res=" << locHit.residual);
     }
   }
-  
-  
+   
   return ReturnCode::SUCCESS;
 }
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.h
index 6fb3b3bba95cd9099f5a469ff515170c3905c7e8..619533b5778dd148f8f0c8028dc1325f4cd1e4c3 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/CscSegmentMaker.h
@@ -63,27 +63,29 @@ namespace TrigL2MuonSA{
     virtual StatusCode initialize() override;
 
 
-    ReturnCode	FindSuperPointCsc( const TrigL2MuonSA::CscHits &cscHits, std::vector<TrigL2MuonSA::TrackPattern> &v_trackPatterns, const TrigL2MuonSA::TgcFitResult &tgcFitResult, const TrigL2MuonSA::MuonRoad &muroad);
+    ReturnCode	FindSuperPointCsc( const TrigL2MuonSA::CscHits &cscHits, 
+                                   std::vector<TrigL2MuonSA::TrackPattern> &v_trackPatterns, 
+                                   const TrigL2MuonSA::TgcFitResult &tgcFitResult, 
+                                   const TrigL2MuonSA::MuonRoad &muroad) const;
 
 
-    ReturnCode make_segment(int mod_hash, TrigL2MuonSA::CscHits clusters[8], CscSegment &cscsegment, CscSegment &cscsegment_noip, const MuonGM::MuonDetectorManager* muDetMgr);
+    ReturnCode make_segment(int mod_hash, TrigL2MuonSA::CscHits clusters[8], CscSegment &cscsegment, CscSegment &cscsegment_noip, const MuonGM::MuonDetectorManager* muDetMgr) const;
 
-    ReturnCode make_2dsegment(int measphi, const localCscHit &ip_loc,const std::vector<localCscHit> hits_loc[4], local2dSegment &seg2d_eta,local2dSegment &local2d_noip, int &nhite);
+    ReturnCode make_2dsegment(int measphi, const localCscHit &ip_loc,const std::vector<localCscHit> hits_loc[4], local2dSegment &seg2d_eta,local2dSegment &local2d_noip, int &nhite) const;
 
-    ReturnCode make_2dseg4hit(int measphi, const localCscHit &ip_loc,std::vector<localCscHit> hits_loc[4], std::vector<local2dSegment> &seg2d_4hitCollection, int &nhite);
+    ReturnCode make_2dseg4hit(int measphi, const localCscHit &ip_loc,std::vector<localCscHit> hits_loc[4], std::vector<local2dSegment> &seg2d_4hitCollection, int &nhite) const;
 
-    ReturnCode make_2dseg3hit(int measphi, const localCscHit &ip_loc, const std::vector<localCscHit> hits_loc[4], std::vector<local2dSegment> &seg2d_4hitCollection, int &nhit);
-
-    ReturnCode fit_clusters(int measphi, const std::vector<localCscHit> &hits_fit, local2dSegment &seg2d);
+    ReturnCode make_2dseg3hit(int measphi, const localCscHit &ip_loc, const std::vector<localCscHit> hits_loc[4], std::vector<local2dSegment> &seg2d_4hitCollection, int &nhit) const;
+    ReturnCode fit_clusters(int measphi, const std::vector<localCscHit> &hits_fit, local2dSegment &seg2d) const;
 
     ReturnCode make_4dsegment(const local2dSegment &seg2d_eta, const local2dSegment &seg2d_phi,
-			      Amg::Vector3D &seg_pos, Amg::Vector3D &seg_dir);
+			      Amg::Vector3D &seg_pos, Amg::Vector3D &seg_dir) const;
 
-    ReturnCode getModuleSP(int mod_hash[2], const TrigL2MuonSA::TgcFitResult &tgcFitResult, int phibin, const TrigL2MuonSA::MuonRoad &muroad, const int exist_clusters[32]);
+    ReturnCode getModuleSP(int mod_hash[2], const TrigL2MuonSA::TgcFitResult &tgcFitResult, int phibin, const TrigL2MuonSA::MuonRoad &muroad, const int exist_clusters[32]) const;
 
-    ReturnCode display_hits(const std::vector<localCscHit> localHits[4]);
+    ReturnCode display_hits(const std::vector<localCscHit> localHits[4]) const;
 
-    CscSegment segmentAtFirstLayer(int mod_hash, TrigL2MuonSA::CscSegment *mu_seg);
+    CscSegment segmentAtFirstLayer(int mod_hash, TrigL2MuonSA::CscSegment *mu_seg) const;
 
   private:
     UtilTools m_util;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.cxx
index d7789555e3f7f486b3a044ed53ef0e554fca64dd..f35203989a2987f350f79388c395e651c60d7805 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.cxx
@@ -26,7 +26,7 @@ StatusCode TrigL2MuonSA::FtfRoadDefiner::initialize()
 // --------------------------------------------------------------------------------
 
 StatusCode TrigL2MuonSA::FtfRoadDefiner::defineRoad(const xAOD::TrackParticle* idtrack,
-						    TrigL2MuonSA::MuonRoad&    muonRoad)
+						    TrigL2MuonSA::MuonRoad&    muonRoad) const
 {
   ATH_MSG_DEBUG("FtfRoadDefiner::defineRoad");
 
@@ -145,7 +145,8 @@ StatusCode TrigL2MuonSA::FtfRoadDefiner::defineRoad(const xAOD::TrackParticle* i
 // --------------------------------------------------------------------------------
 
 // extrapolate a FTF track to MS in order to define FTF Road
-std::unique_ptr<const Trk::TrackParameters> TrigL2MuonSA::FtfRoadDefiner::extTrack( const xAOD::TrackParticle* trk, const double R, const double halflength, int& extFlag ) {
+std::unique_ptr<const Trk::TrackParameters> TrigL2MuonSA::FtfRoadDefiner::extTrack( const xAOD::TrackParticle* trk, const double R, const double halflength, int& extFlag ) const 
+{
 
   const bool boundaryCheck = true;
   bool bCylinder = false;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.h
index a814605967a3392065ba2d3e2b8734793d617001..42de958f7605dd18c526faa29f5bc8cc4f8c9783 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/FtfRoadDefiner.h
@@ -30,8 +30,8 @@ namespace TrigL2MuonSA {
 
   public:
     StatusCode defineRoad( const xAOD::TrackParticle* idtrack,
-			   TrigL2MuonSA::MuonRoad&    muonRoad);
-    std::unique_ptr<const Trk::TrackParameters> extTrack( const xAOD::TrackParticle* trk, const double R, const double halflength,  int& extFlag );
+			   TrigL2MuonSA::MuonRoad&    muonRoad) const;
+    std::unique_ptr<const Trk::TrackParameters> extTrack( const xAOD::TrackParticle* trk, const double R, const double halflength,  int& extFlag ) const;
 
   protected:
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.cxx
index 4222d085c8317803d648187e3d687e565db79e6f..fc17297940ede325c619d1214bcb8dd2e849d04c 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.cxx
@@ -505,22 +505,22 @@ bool TrigL2MuonSA::MdtDataPreparator::decodeMdtCsm(const MdtCsm* csm,
        continue;
      }
      
-     m_mdtReadout = muDetMgr->getMdtRElement_fromIdFields(StationName, StationEta, StationPhi,MultiLayer);
-     if (!m_mdtReadout) {
+     const MuonGM::MdtReadoutElement* mdtReadout = muDetMgr->getMdtRElement_fromIdFields(StationName, StationEta, StationPhi,MultiLayer);
+     if (!mdtReadout) {
        ++amt;
        continue;
      }
      
-     m_muonStation = m_mdtReadout->parentMuonStation();
+     const MuonGM::MuonStation* muonStation = mdtReadout->parentMuonStation();
      
-     int TubeLayers = m_mdtReadout->getNLayers();
+     int TubeLayers = mdtReadout->getNLayers();
      int TubeLayer = Layer;
      if(TubeLayer > TubeLayers) TubeLayer -= TubeLayers;
      if(MultiLayer==2)
-       Layer = Layer + m_mdtReadout->getNLayers();
+       Layer = Layer + mdtReadout->getNLayers();
      
-     double OrtoRadialPos = m_mdtReadout->getStationS();
-     std::string chamberType = m_mdtReadout->getStationType();
+     double OrtoRadialPos = mdtReadout->getStationS();
+     std::string chamberType = mdtReadout->getStationType();
      char st = chamberType[1];
      
      int chamber = 0;
@@ -554,18 +554,18 @@ bool TrigL2MuonSA::MdtDataPreparator::decodeMdtCsm(const MdtCsm* csm,
          }
        }
      }
-     R = m_mdtReadout->center(TubeLayer, Tube).perp();
-     Z = m_mdtReadout->center(TubeLayer, Tube).z();
+     R = mdtReadout->center(TubeLayer, Tube).perp();
+     Z = mdtReadout->center(TubeLayer, Tube).z();
      
-     Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*m_muonStation->getNominalAmdbLRSToGlobal());
-     if(m_muonStation->endcap()==0){
+     Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*muonStation->getNominalAmdbLRSToGlobal());
+     if(muonStation->endcap()==0){
        cXmid = (trans*Amg::Vector3D(0.,0.,0.)).z();
-       double halfRadialThicknessOfMultilayer = m_muonStation->RsizeMdtStation()/2.;
+       double halfRadialThicknessOfMultilayer = muonStation->RsizeMdtStation()/2.;
        cYmid = ((trans*Amg::Vector3D(0.,0.,0.)).perp()+halfRadialThicknessOfMultilayer);
      }
      else{
        cXmid = (trans*Amg::Vector3D(0.,0.,0.)).perp();
-       double halfZThicknessOfMultilayer = m_muonStation->ZsizeMdtStation()/2.;
+       double halfZThicknessOfMultilayer = muonStation->ZsizeMdtStation()/2.;
        cYmid = (trans*Amg::Vector3D(0.,0.,0.)).z();
        if(cYmid>0) cYmid += halfZThicknessOfMultilayer;
        else cYmid -= halfZThicknessOfMultilayer;
@@ -586,11 +586,11 @@ bool TrigL2MuonSA::MdtDataPreparator::decodeMdtCsm(const MdtCsm* csm,
        }
      }
      
-     if(m_muonStation->endcap()==1)
+     if(muonStation->endcap()==1)
        R = sqrt(R*R+R*R*tan(dphi)*tan(dphi));
      
      Amg::Vector3D OrigOfMdtInAmdbFrame = 
-       Amg::Hep3VectorToEigen( m_muonStation->getBlineFixedPointInAmdbLRS() );
+       Amg::Hep3VectorToEigen( muonStation->getBlineFixedPointInAmdbLRS() );
      double Rmin =(trans*OrigOfMdtInAmdbFrame).perp();
 
      float cInCo = 1./cos(std::abs(atan(OrtoRadialPos/Rmin)));
@@ -676,9 +676,10 @@ uint32_t TrigL2MuonSA::MdtDataPreparator::get_system_id (unsigned short int Subs
 
 void TrigL2MuonSA::MdtDataPreparator::getMdtIdHashesBarrel(const TrigL2MuonSA::MdtRegion& mdtRegion,
 							   std::vector<IdentifierHash>& mdtIdHashes_normal,
-							   std::vector<IdentifierHash>& mdtIdHashes_overlap)
+							   std::vector<IdentifierHash>& mdtIdHashes_overlap) const
 {
    std::vector<IdentifierHash> idList;
+   float etaMinChamber[11],etaMaxChamber[11],phiMinChamber[11],phiMaxChamber[11];
 
    //combine regions of sector and type
    for(int j_station=0; j_station<6; j_station++) {
@@ -746,9 +747,10 @@ void TrigL2MuonSA::MdtDataPreparator::getMdtIdHashesBarrel(const TrigL2MuonSA::M
 
 void TrigL2MuonSA::MdtDataPreparator::getMdtIdHashesEndcap(const TrigL2MuonSA::MdtRegion& mdtRegion,
 							   std::vector<IdentifierHash>& mdtIdHashes_normal,
-							   std::vector<IdentifierHash>& mdtIdHashes_overlap)
+							   std::vector<IdentifierHash>& mdtIdHashes_overlap) const
 {
    std::vector<IdentifierHash> idList;
+   float etaMinChamber[11],etaMaxChamber[11],phiMinChamber[11],phiMaxChamber[11];
 
    //combine regions of sector and type
    for(int j_station=0; j_station<6; j_station++) {
@@ -819,7 +821,7 @@ StatusCode TrigL2MuonSA::MdtDataPreparator::collectMdtHitsFromPrepData(const std
 								       std::vector<uint32_t>& v_robIds,
 								       TrigL2MuonSA::MdtHits& mdtHits,
 								       const TrigL2MuonSA::MuonRoad& muonRoad,
-                       const MuonGM::MuonDetectorManager* muDetMgr)
+                                                                       const MuonGM::MuonDetectorManager* muDetMgr)
 {
   if(m_doDecoding) {
     if(m_decodeBS) {
@@ -876,14 +878,14 @@ StatusCode TrigL2MuonSA::MdtDataPreparator::collectMdtHitsFromPrepData(const std
     mdtHits.reserve( mdtHits.size() + mdtCol->size() );
     for( const Muon::MdtPrepData* mdt : *mdtCol ) {
 
-      m_mdtReadout = mdt->detectorElement();
-      if (!m_mdtReadout) continue;
+      const MuonGM::MdtReadoutElement* mdtReadout = mdt->detectorElement();
+      if (!mdtReadout) continue;
 
-      m_muonStation = m_mdtReadout->parentMuonStation();
+      const MuonGM::MuonStation* muonStation = mdtReadout->parentMuonStation();
 
-      int StationPhi = m_mdtReadout->getStationPhi();
-      int StationEta = m_mdtReadout->getStationEta();
-      int MultiLayer = m_mdtReadout->getMultilayer();
+      int StationPhi = mdtReadout->getStationPhi();
+      int StationEta = mdtReadout->getStationEta();
+      int MultiLayer = mdtReadout->getMultilayer();
       double cXmid;
       double cYmid;
       double cAmid = 0;
@@ -893,14 +895,14 @@ StatusCode TrigL2MuonSA::MdtDataPreparator::collectMdtHitsFromPrepData(const std
       int adc       = mdt->adc();
       int drift     = mdt->tdc();
 
-      int TubeLayers = m_mdtReadout->getNLayers();
+      int TubeLayers = mdtReadout->getNLayers();
       int TubeLayer = m_idHelperSvc->mdtIdHelper().tubeLayer(id);
       if(TubeLayer > TubeLayers) TubeLayer -= TubeLayers;
       int Layer = (MultiLayer-1)*TubeLayers + TubeLayer;
       int Tube = m_idHelperSvc->mdtIdHelper().tube(id);
 
-      double OrtoRadialPos = m_mdtReadout->getStationS();
-      std::string chamberType = m_mdtReadout->getStationType();
+      double OrtoRadialPos = mdtReadout->getStationS();
+      std::string chamberType = mdtReadout->getStationType();
       char st = chamberType[1];
 
       int chamber = 0;
@@ -930,18 +932,18 @@ StatusCode TrigL2MuonSA::MdtDataPreparator::collectMdtHitsFromPrepData(const std
           }
         }
       }
-      R = m_mdtReadout->center(TubeLayer, Tube).perp();
-      Z = m_mdtReadout->center(TubeLayer, Tube).z();
+      R = mdtReadout->center(TubeLayer, Tube).perp();
+      Z = mdtReadout->center(TubeLayer, Tube).z();
 
-      Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*m_muonStation->getNominalAmdbLRSToGlobal());
-      if(m_muonStation->endcap()==0){
+      Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*muonStation->getNominalAmdbLRSToGlobal());
+      if(muonStation->endcap()==0){
 	cXmid = (trans*Amg::Vector3D(0.,0.,0.)).z();
-	double halfRadialThicknessOfMultilayer = m_muonStation->RsizeMdtStation()/2.;
+	double halfRadialThicknessOfMultilayer = muonStation->RsizeMdtStation()/2.;
 	cYmid = ((trans*Amg::Vector3D(0.,0.,0.)).perp()+halfRadialThicknessOfMultilayer);
       }
       else{
 	cXmid = (trans*Amg::Vector3D(0.,0.,0.)).perp();
-	double halfZThicknessOfMultilayer = m_muonStation->ZsizeMdtStation()/2.;
+	double halfZThicknessOfMultilayer = muonStation->ZsizeMdtStation()/2.;
 	cYmid = (trans*Amg::Vector3D(0.,0.,0.)).z();
 	if(cYmid>0) cYmid += halfZThicknessOfMultilayer;
 	else cYmid -= halfZThicknessOfMultilayer;
@@ -963,11 +965,11 @@ StatusCode TrigL2MuonSA::MdtDataPreparator::collectMdtHitsFromPrepData(const std
 	}
       }
 
-      if(m_muonStation->endcap()==1)
+      if(muonStation->endcap()==1)
 	R = sqrt(R*R+R*R*tan(dphi)*tan(dphi));
 
       Amg::Vector3D OrigOfMdtInAmdbFrame =
-	Amg::Hep3VectorToEigen( m_muonStation->getBlineFixedPointInAmdbLRS() );
+	Amg::Hep3VectorToEigen( muonStation->getBlineFixedPointInAmdbLRS() );
       double Rmin =(trans*OrigOfMdtInAmdbFrame).perp();
 
       float cInCo = 1./cos(std::abs(atan(OrtoRadialPos/Rmin)));
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.h
index 4edb0f5ab823e737130849e60804e986d51b835b..b1fef4d2acf89c7d2e7d046bfcf5b567401da78d 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtDataPreparator.h
@@ -77,9 +77,6 @@ namespace TrigL2MuonSA {
     void setMdtDataCollection(bool use_mdtcsm){m_use_mdtcsm = use_mdtcsm;};
     void setRoIBasedDataAccess(bool use_RoIBasedDataAccess){m_use_RoIBasedDataAccess = use_RoIBasedDataAccess;};
 
-  public:
-    float etaMinChamber[11],etaMaxChamber[11],phiMinChamber[11],phiMaxChamber[11];
-
   private:
 
     StatusCode getMdtHits(const LVL1::RecMuonRoI* p_roi,
@@ -91,11 +88,11 @@ namespace TrigL2MuonSA {
 
     void getMdtIdHashesBarrel(const TrigL2MuonSA::MdtRegion& mdtRegion,
 			std::vector<IdentifierHash>& mdtIdHashes_normal,
-			std::vector<IdentifierHash>& mdtIdHashes_overlap);
+			std::vector<IdentifierHash>& mdtIdHashes_overlap) const;
 
     void getMdtIdHashesEndcap(const TrigL2MuonSA::MdtRegion& mdtRegion,
 			std::vector<IdentifierHash>& mdtIdHashes_normal,
-			std::vector<IdentifierHash>& mdtIdHashes_overlap);
+			std::vector<IdentifierHash>& mdtIdHashes_overlap) const;
 
     StatusCode getMdtCsm(const MdtCsmContainer* pMdtCsmContainer,
 			 const std::vector<const OFFLINE_FRAGMENTS_NAMESPACE::ROBFragment*>& v_robFragments,
@@ -121,8 +118,6 @@ namespace TrigL2MuonSA {
 
 
     // Geometry Services
-    const MuonGM::MdtReadoutElement* m_mdtReadout {nullptr};
-    const MuonGM::MuonStation* m_muonStation {nullptr};
     ServiceHandle<Muon::IMuonIdHelperSvc> m_idHelperSvc {this, "MuonIdHelperSvc", "Muon::MuonIdHelperSvc/MuonIdHelperSvc"};
     IdentifierHash m_hash_id;
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.cxx
index 33e4d6a109747d59d5cdb8b48b70f765534ce538..5222e52a1b527615375ef54feb42394fc423a097 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.cxx
@@ -38,7 +38,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::initialize()
 StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI* p_roi,
 							 const TrigL2MuonSA::RpcFitResult& rpcFitResult,
 							 TrigL2MuonSA::MuonRoad& muonRoad,
-							 TrigL2MuonSA::MdtRegion& mdtRegion)
+							 TrigL2MuonSA::MdtRegion& mdtRegion) const
 {
   constexpr double ZERO_LIMIT = 1e-5;
   mdtRegion.Clear();
@@ -101,16 +101,17 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 	    ty1 = m_idHelperSvc->mdtIdHelper().stationNameIndex(name)+1;
 	  else if(ty2 == -1)
 	    ty2 = m_idHelperSvc->mdtIdHelper().stationNameIndex(name)+1;
-	  m_mdtReadout = muDetMgr->getMdtReadoutElement(id);
-	  m_muonStation = m_mdtReadout->parentMuonStation();
+          
+          const MuonGM::MdtReadoutElement* mdtReadout = muDetMgr->getMdtReadoutElement(id);
+          const MuonGM::MuonStation* muonStation = mdtReadout->parentMuonStation();
 	  
-	  Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*m_muonStation->getNominalAmdbLRSToGlobal());
+	  Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*muonStation->getNominalAmdbLRSToGlobal());
 	  
 	  Amg::Vector3D OrigOfMdtInAmdbFrame = 
-	    Amg::Hep3VectorToEigen( m_muonStation->getBlineFixedPointInAmdbLRS() );
+	    Amg::Hep3VectorToEigen( muonStation->getBlineFixedPointInAmdbLRS() );
 	  
 	  tmp_rMin = (trans*OrigOfMdtInAmdbFrame).perp();
-	  tmp_rMax = tmp_rMin+m_muonStation->Rsize();
+	  tmp_rMax = tmp_rMin+muonStation->Rsize();
 	  
 	  if(rMin==0 || tmp_rMin < rMin)rMin = tmp_rMin;
 	  if(rMax==0 || tmp_rMax > rMax)rMax = tmp_rMax;
@@ -118,7 +119,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 	    tmp_zMin = (trans*OrigOfMdtInAmdbFrame).z();
 	    if(tmp_zMin < 0) sign = -1;
 	    else if(tmp_zMin > 0) sign = 1;
-	    tmp_zMax = tmp_zMin + sign*m_muonStation->Zsize();
+	    tmp_zMax = tmp_zMin + sign*muonStation->Zsize();
 	    if(zMin==0 || tmp_zMin < zMin)zMin = tmp_zMin;
 	    if(zMax==0 || tmp_zMax > zMax)zMax = tmp_zMax;
 	  }
@@ -200,7 +201,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI* p_roi,
 							 const TrigL2MuonSA::TgcFitResult& tgcFitResult,
 							 TrigL2MuonSA::MuonRoad& muonRoad,
-							 TrigL2MuonSA::MdtRegion& mdtRegion)
+							 TrigL2MuonSA::MdtRegion& mdtRegion) const
 {
   mdtRegion.Clear();
   
@@ -267,19 +268,21 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 	    ty1 = m_idHelperSvc->mdtIdHelper().stationNameIndex(name)+1;
 	  else if(ty2 == -1)
 		ty2 = m_idHelperSvc->mdtIdHelper().stationNameIndex(name)+1;
-	  m_mdtReadout = muDetMgr->getMdtReadoutElement(id);
-	  m_muonStation = m_mdtReadout->parentMuonStation();
+          
+          const MuonGM::MdtReadoutElement* mdtReadout = muDetMgr->getMdtReadoutElement(id);
+          const MuonGM::MuonStation* muonStation = mdtReadout->parentMuonStation();
+    
 	  float scale = 10.;
 	  
-	  Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*m_muonStation->getNominalAmdbLRSToGlobal());
+	  Amg::Transform3D trans = Amg::CLHEPTransformToEigen(*muonStation->getNominalAmdbLRSToGlobal());
 	  
 	  Amg::Vector3D OrigOfMdtInAmdbFrame = 
-	    Amg::Hep3VectorToEigen( m_muonStation->getBlineFixedPointInAmdbLRS() );
+	    Amg::Hep3VectorToEigen( muonStation->getBlineFixedPointInAmdbLRS() );
 	  
 	  tmp_zMin = (trans*OrigOfMdtInAmdbFrame).z();
 	  if(tmp_zMin < 0) sign = -1;
 	  else if(tmp_zMin > 0) sign = 1;
-	  tmp_zMax = tmp_zMin + sign*m_muonStation->Zsize();
+	  tmp_zMax = tmp_zMin + sign*muonStation->Zsize();
 	  
 	  if(sta_zMin==0 || tmp_zMin<sta_zMin) sta_zMin = tmp_zMin;
 	  if(sta_zMin==0 || tmp_zMax<sta_zMin) sta_zMin = tmp_zMax;
@@ -288,14 +291,14 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 	  
 	  if (chamber_this==barrel_inner){//barrel inner
 	    tmp_rMin = (trans*OrigOfMdtInAmdbFrame).perp()/scale;
-	    tmp_rMax = tmp_rMin+m_muonStation->Rsize()/scale;
+	    tmp_rMax = tmp_rMin+muonStation->Rsize()/scale;
 	    if(rMin==0 || tmp_rMin < rMin)rMin = tmp_rMin;
 	    if(rMax==0 || tmp_rMax > rMax)rMax = tmp_rMax;
 	  }
 
 	  if (chamber_this==bee){//BEE
 	    tmp_rMin = (trans*OrigOfMdtInAmdbFrame).perp()/scale;
-	    tmp_rMax = tmp_rMin+m_muonStation->Rsize()/scale;
+	    tmp_rMax = tmp_rMin+muonStation->Rsize()/scale;
 	    if(rMin==0 || tmp_rMin < rMin)rMin = tmp_rMin;
 	    if(rMax==0 || tmp_rMax > rMax)rMax = tmp_rMax;
 	  }
@@ -379,7 +382,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::getMdtRegions(const LVL1::RecMuonRoI*
 // --------------------------------------------------------------------------------
 
 void TrigL2MuonSA::MdtRegionDefiner::find_station_sector(std::string name, int phi, bool& endcap, 
-    int& chamber, int& sector)
+    int& chamber, int& sector) const
 {   
   if(name[0]=='E' || name[0]=='F' || (name[0]=='B' && name[1]=='E'))
     endcap = true;
@@ -419,7 +422,7 @@ void TrigL2MuonSA::MdtRegionDefiner::find_station_sector(std::string name, int p
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-void TrigL2MuonSA::MdtRegionDefiner::find_phi_min_max(float phiMiddle, float& phiMin, float& phiMax)
+void TrigL2MuonSA::MdtRegionDefiner::find_phi_min_max(float phiMiddle, float& phiMin, float& phiMax) const
 {   
    phiMin = phiMiddle - 0.1;
    phiMax = phiMiddle + 0.1;
@@ -431,7 +434,7 @@ void TrigL2MuonSA::MdtRegionDefiner::find_phi_min_max(float phiMiddle, float& ph
 // --------------------------------------------------------------------------------
 
 void TrigL2MuonSA::MdtRegionDefiner::find_eta_min_max(float zMin, float rMin, float zMax, float rMax,
-						      float& etaMin, float& etaMax)
+						      float& etaMin, float& etaMax) const
 {   
    // const bool doEmulateMuFast = true;
    const bool doEmulateMuFast = false;
@@ -477,7 +480,7 @@ void TrigL2MuonSA::MdtRegionDefiner::find_eta_min_max(float zMin, float rMin, fl
 // --------------------------------------------------------------------------------
 
 void TrigL2MuonSA::MdtRegionDefiner::find_barrel_road_dim(float max_road, float aw, float bw,
-							  float rMin,float rMax,float *zMin,float *zMax)
+							  float rMin,float rMax,float *zMin,float *zMax) const
 {
   float ia,iaq,dz,z,points[4];
   int i;
@@ -513,7 +516,7 @@ void TrigL2MuonSA::MdtRegionDefiner::find_barrel_road_dim(float max_road, float
 // --------------------------------------------------------------------------------
 
 void TrigL2MuonSA::MdtRegionDefiner::find_endcap_road_dim(float road,float aw, float bw, float zMin,
-							  float zMax,float *rMin,float *rMax)
+							  float zMax,float *rMin,float *rMax) const
 {
    float r,points[4];
    int i;
@@ -590,7 +593,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::prepareTgcPoints(const TrigL2MuonSA::
 StatusCode TrigL2MuonSA::MdtRegionDefiner::computePhi(const LVL1::RecMuonRoI* p_roi,
 						      const TrigL2MuonSA::RpcFitResult& rpcFitResult,
 						      const TrigL2MuonSA::MdtRegion& mdtRegion,
-						      TrigL2MuonSA::MuonRoad& muonRoad)
+						      TrigL2MuonSA::MuonRoad& muonRoad) const
 {
   int barrel_inner = xAOD::L2MuonParameters::Chamber::BarrelInner;
   int barrel_middle = xAOD::L2MuonParameters::Chamber::BarrelMiddle;
@@ -661,7 +664,7 @@ StatusCode TrigL2MuonSA::MdtRegionDefiner::computePhi(const LVL1::RecMuonRoI* p_
 StatusCode TrigL2MuonSA::MdtRegionDefiner::computePhi(const LVL1::RecMuonRoI* p_roi,
 						      const TrigL2MuonSA::TgcFitResult& tgcFitResult,
 						      const TrigL2MuonSA::MdtRegion& mdtRegion,
-						      TrigL2MuonSA::MuonRoad& muonRoad)
+						      TrigL2MuonSA::MuonRoad& muonRoad) const
 {
   int endcap_inner = xAOD::L2MuonParameters::Chamber::EndcapInner;
   int endcap_middle = xAOD::L2MuonParameters::Chamber::EndcapMiddle;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.h
index 4e5e8ac0f4da63bfbba9f811e9fbe76f86721226..8d7cd555ea90da0946ad280a192d3aba90a568c6 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MdtRegionDefiner.h
@@ -50,43 +50,40 @@ namespace TrigL2MuonSA {
     StatusCode getMdtRegions(const LVL1::RecMuonRoI*           p_roi,
 			     const TrigL2MuonSA::RpcFitResult& rpcFitResult,
 			     TrigL2MuonSA::MuonRoad&           muonRoad,
-			     TrigL2MuonSA::MdtRegion&          mdtRegion);
+			     TrigL2MuonSA::MdtRegion&          mdtRegion) const;
     
     StatusCode getMdtRegions(const LVL1::RecMuonRoI*           p_roi,
 			     const TrigL2MuonSA::TgcFitResult& tgcFitResult,
 			     TrigL2MuonSA::MuonRoad&           muonRoad,
-			     TrigL2MuonSA::MdtRegion&          mdtRegion);
+			     TrigL2MuonSA::MdtRegion&          mdtRegion) const;
     
   private:
     StatusCode prepareTgcPoints(const TrigL2MuonSA::TgcHits& tgcHits);
     void find_barrel_road_dim(float max_road, float aw, float bw,
-			      float rMmin,float rMax,float *zMin,float *zMax);
+			      float rMmin,float rMax,float *zMin,float *zMax) const;
     void find_endcap_road_dim(float road,float aw, float bw, float zMin,
-			      float zMax,float *rMin,float *rMax);
+			      float zMax,float *rMin,float *rMax) const;
     void find_eta_min_max(float zMin, float rMin,
 			  float zMax, float rMax,
-			  float& etaMin, float& etaMax);
-    void find_phi_min_max(float phiMiddle, float& phiMin, float& phiMax);
+			  float& etaMin, float& etaMax) const;
+    void find_phi_min_max(float phiMiddle, float& phiMin, float& phiMax) const;
         
-    void find_station_sector(std::string name, int phi, bool& endcap, int& chamber, int& sector);
+    void find_station_sector(std::string name, int phi, bool& endcap, int& chamber, int& sector) const;
 
     StatusCode computePhi(const LVL1::RecMuonRoI*           p_roi,
 			  const TrigL2MuonSA::RpcFitResult& rpcFitResult,
 			  const TrigL2MuonSA::MdtRegion&    mdtRegion,
-			  TrigL2MuonSA::MuonRoad&           muonRoad);
+			  TrigL2MuonSA::MuonRoad&           muonRoad) const;
       
     StatusCode computePhi(const LVL1::RecMuonRoI*           p_roi,
 			  const TrigL2MuonSA::TgcFitResult& tgcFitResult,
 			  const TrigL2MuonSA::MdtRegion&    mdtRegion,
-			  TrigL2MuonSA::MuonRoad&           muonRoad);
+			  TrigL2MuonSA::MuonRoad&           muonRoad) const;
 
   private:
     ServiceHandle<Muon::IMuonIdHelperSvc> m_idHelperSvc {this, "MuonIdHelperSvc", "Muon::MuonIdHelperSvc/MuonIdHelperSvc"};
     SG::ReadCondHandleKey<MuonGM::MuonDetectorManager> m_muDetMgrKey {this, "DetectorManagerKey", "MuonDetectorManager", "Key of input MuonDetectorManager condition data"}; 
 
-    const MuonGM::MdtReadoutElement* m_mdtReadout {nullptr};
-    const MuonGM::MuonStation* m_muonStation {nullptr};
-    
     bool m_use_rpc {true};
 
     TrigL2MuonSA::TgcFit::PointArray m_tgcStripMidPoints;  // List of TGC strip middle station points.
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.cxx
index 743f13929934ad5767b6dc7972d4e50c5eb613a8..9350fa9f89247ba34c5f2c9679c6bf549ef41c5c 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.cxx
@@ -32,7 +32,7 @@ StatusCode TrigL2MuonSA::MuFastPatternFinder::initialize()
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-void TrigL2MuonSA::MuFastPatternFinder::doMdtCalibration(TrigL2MuonSA::MdtHitData& mdtHit, double track_phi, double phi0, bool isEndcap)
+void TrigL2MuonSA::MuFastPatternFinder::doMdtCalibration(TrigL2MuonSA::MdtHitData& mdtHit, double track_phi, double phi0, bool isEndcap) const
 {
    int StationName  = mdtHit.name;
    int StationEta   = mdtHit.StationEta;
@@ -108,7 +108,7 @@ StatusCode TrigL2MuonSA::MuFastPatternFinder::findPatterns(const TrigL2MuonSA::M
 							   TrigL2MuonSA::MdtHits&                   mdtHits,
 							   TrigL2MuonSA::StgcHits&                  stgcHits,
 							   TrigL2MuonSA::MmHits&                    mmHits,
-							   std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns)
+							   std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns) const
 {
   ATH_CHECK( findPatterns(muonRoad, mdtHits, v_trackPatterns) );
   ATH_CHECK( m_nswPatternFinder->findPatterns(muonRoad, stgcHits, mmHits, v_trackPatterns.back()) );
@@ -128,7 +128,7 @@ StatusCode TrigL2MuonSA::MuFastPatternFinder::findPatterns(const TrigL2MuonSA::M
 
 StatusCode TrigL2MuonSA::MuFastPatternFinder::findPatterns(const TrigL2MuonSA::MuonRoad&            muonRoad,
 							   TrigL2MuonSA::MdtHits&                   mdtHits,
-							   std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns)
+							   std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns) const
 {
 
    // find only 1 track pattern
@@ -309,7 +309,7 @@ StatusCode TrigL2MuonSA::MuFastPatternFinder::findPatterns(const TrigL2MuonSA::M
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-double TrigL2MuonSA::MuFastPatternFinder::calc_residual(double aw,double bw,double x,double y)
+double TrigL2MuonSA::MuFastPatternFinder::calc_residual(double aw,double bw,double x,double y) const
 {
    const double ZERO_LIMIT = 1e-4;
    if( fabs(aw) < ZERO_LIMIT ) return y-bw;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.h
index 01f3e4f64210caa5825d003da7b092b2e61521ec..3c4dc37107011cc15e16edd66543b3d2eec3cde5 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastPatternFinder.h
@@ -47,20 +47,20 @@ class MuFastPatternFinder: public AthAlgTool
     
    private:
 
-      double calc_residual(double aw,double bw,double x,double y);
-      void  doMdtCalibration(TrigL2MuonSA::MdtHitData& mdtHit, double track_phi, double phi0, bool isEndcap);
+      double calc_residual(double aw,double bw,double x,double y) const;
+      void  doMdtCalibration(TrigL2MuonSA::MdtHitData& mdtHit, double track_phi, double phi0, bool isEndcap) const;
 
    public:
 
       StatusCode findPatterns(const TrigL2MuonSA::MuonRoad& muonRoad,
 			      TrigL2MuonSA::MdtHits&        mdtHits,
-			      std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns);
+			      std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns) const;
 
       StatusCode findPatterns(const TrigL2MuonSA::MuonRoad& muonRoad,
 			      TrigL2MuonSA::MdtHits&        mdtHits,
 			      TrigL2MuonSA::StgcHits&       stgcHits,
 			      TrigL2MuonSA::MmHits&         mmHits,
-			      std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns);
+			      std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns) const;
    private:
       ToolHandle<NswPatternFinder>  m_nswPatternFinder {this, "NswPatternFinder", "TrigL2MuonSA::NswPatternFinder"};
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.cxx
index c1af2468ba6b12cb0c5c19d70d6cb1f59bb74199..918ef9da7781b4c13753101980180e9351ff727d 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.cxx
@@ -29,7 +29,7 @@ TrigL2MuonSA::MuFastTrackExtrapolator::MuFastTrackExtrapolator(const std::string
 // --------------------------------------------------------------------------------
 
 StatusCode TrigL2MuonSA::MuFastTrackExtrapolator::extrapolateTrack(std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns,
-                                                                   double winPt)
+                                                                   double winPt) const
 {
   ATH_MSG_DEBUG("in extrapolateTrack");
   
@@ -110,7 +110,8 @@ void TrigL2MuonSA::MuFastTrackExtrapolator::setMuFastRes(std::vector<double>& ve
 // Copied from TrigmuComb/muCombUtil.cxx
 double TrigL2MuonSA::MuFastTrackExtrapolator::getMuFastRes(std::vector<double> vec,
                                                            const double pt, const int add,
-                                                           const double eta, const double phi) {
+                                                           const double eta, const double phi) const
+{
   
   if (pt == 0) return 1.0e30;
   
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.h
index 7e54a8d3006f097313815733b6e870464d9eca39..84d3779d4a6a7600cb747d56df29b34b4c2dfce3 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/MuFastTrackExtrapolator.h
@@ -25,11 +25,11 @@ namespace TrigL2MuonSA {
     void setExtrapolatorTool(ToolHandle<ITrigMuonBackExtrapolator>* backExtrapolator) {m_backExtrapolatorTool = backExtrapolator;};
 
     StatusCode extrapolateTrack(std::vector<TrigL2MuonSA::TrackPattern>& v_trackPatterns,
-				double winPt);
+				double winPt) const;
     
     void setMuFastRes(std::vector<double>& vec, double p1,double p2, double p3,double p4,double p5,double p6);
 
-    double getMuFastRes(std::vector<double> vec, const double pt, const int add, const double eta, const double phi);
+    double getMuFastRes(std::vector<double> vec, const double pt, const int add, const double eta, const double phi) const;
 
   private:
     ToolHandle<ITrigMuonBackExtrapolator>* m_backExtrapolatorTool {nullptr};
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.cxx
index fcd5fbbe3ed3301b2c00309f4b02043db029f757..19f159de614692a7b952ceceb9bb6d55c4d808bd 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.cxx
@@ -17,7 +17,7 @@ TrigL2MuonSA::NswStationFitter::NswStationFitter(const std::string& type,
 }
 
 StatusCode TrigL2MuonSA::NswStationFitter::superPointFitter(const LVL1::RecMuonRoI* p_roi,
-                                                            TrigL2MuonSA::TrackPattern& trackPattern)
+                                                            TrigL2MuonSA::TrackPattern& trackPattern) const
 {
 
   ATH_MSG_DEBUG("NswStationFitter::findSuperPoints() was called.");
@@ -34,7 +34,7 @@ StatusCode TrigL2MuonSA::NswStationFitter::superPointFitter(const LVL1::RecMuonR
 }
 
 StatusCode TrigL2MuonSA::NswStationFitter::selectStgcHits(const LVL1::RecMuonRoI* p_roi,
-                                                          TrigL2MuonSA::StgcHits& stgcHits)
+                                                          TrigL2MuonSA::StgcHits& stgcHits) const
 {
 
   TrigL2MuonSA::StgcHits selectedStgcHits;
@@ -80,7 +80,7 @@ StatusCode TrigL2MuonSA::NswStationFitter::selectStgcHits(const LVL1::RecMuonRoI
 }
 
 StatusCode TrigL2MuonSA::NswStationFitter::selectMmHits(const LVL1::RecMuonRoI* p_roi,
-                                                        TrigL2MuonSA::MmHits& mmHits)
+                                                        TrigL2MuonSA::MmHits& mmHits) const
 {
 
   TrigL2MuonSA::MmHits selectedMmHits;
@@ -127,7 +127,7 @@ StatusCode TrigL2MuonSA::NswStationFitter::selectMmHits(const LVL1::RecMuonRoI*
 
 }
 
-StatusCode TrigL2MuonSA::NswStationFitter::calcWeightedSumHit(TrigL2MuonSA::TrackPattern& trackPattern)
+StatusCode TrigL2MuonSA::NswStationFitter::calcWeightedSumHit(TrigL2MuonSA::TrackPattern& trackPattern) const
 {
 
   TrigL2MuonSA::StgcHits stgcHits = trackPattern.stgcSegment;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.h
index 13cace4562e86c5336f3d7be13ffcd37f7e79ba4..b04aaa86cc8e543ceac802aa336dc58baa321dd2 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/NswStationFitter.h
@@ -28,15 +28,15 @@ namespace TrigL2MuonSA {
 		     const IInterface*  parent);
 
     StatusCode superPointFitter(const LVL1::RecMuonRoI* p_roi,
-				TrigL2MuonSA::TrackPattern& trackPattern);
+				TrigL2MuonSA::TrackPattern& trackPattern) const;
 
     StatusCode selectStgcHits(const LVL1::RecMuonRoI* p_roi,
-			      TrigL2MuonSA::StgcHits& stgcHits);
+			      TrigL2MuonSA::StgcHits& stgcHits) const;
 
     StatusCode selectMmHits(const LVL1::RecMuonRoI* p_roi,
-			    TrigL2MuonSA::MmHits& mmHits);
+			    TrigL2MuonSA::MmHits& mmHits) const;
 
-    StatusCode calcWeightedSumHit(TrigL2MuonSA::TrackPattern& trackPattern);
+    StatusCode calcWeightedSumHit(TrigL2MuonSA::TrackPattern& trackPattern) const;
 
   private :
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.cxx
index 70bd86d3672f77dd929cd91a6c02eb63283d7c6f..c37eae8c7f1f10ddfbc20bee6daef677d8b610fc 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.cxx
@@ -43,7 +43,7 @@ void TrigL2MuonSA::PtFromAlphaBeta::setMCFlag(BooleanProperty use_mcLUT,
 // --------------------------------------------------------------------------------
 
 StatusCode TrigL2MuonSA::PtFromAlphaBeta::setPt(TrigL2MuonSA::TrackPattern& trackPattern,
-                                                TrigL2MuonSA::TgcFitResult& tgcFitResult)
+                                                TrigL2MuonSA::TgcFitResult& tgcFitResult) const
 {
 
   if (trackPattern.etaBin < -1) 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.h
index 2d3afb4aec86d91dd960983d90f6f3923ce95b46..70d72ea182afb4da3d4f30e104b3252c319be7a6 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromAlphaBeta.h
@@ -32,7 +32,7 @@ class PtFromAlphaBeta: public AthAlgTool
  public:
     
     StatusCode setPt(TrigL2MuonSA::TrackPattern& trackPattern,
-                     TrigL2MuonSA::TgcFitResult& tgcFitResult);
+                     TrigL2MuonSA::TgcFitResult& tgcFitResult) const;
     
     double     compute_radius(double InnerSlope, double InnerR, double InnerZ,
 			      double MiddleSlope, double MiddleR, double MiddleZ,
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.cxx
index b8a22b7c24dc38941ad670e693c7bf243661e47f..8b0778496fed5f0fcf6a680ba0cddbb82ae9df7c 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.cxx
@@ -32,7 +32,7 @@ void TrigL2MuonSA::PtFromRadius::setMCFlag(BooleanProperty use_mcLUT,
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-StatusCode TrigL2MuonSA::PtFromRadius::setPt(TrigL2MuonSA::TrackPattern& trackPattern)
+StatusCode TrigL2MuonSA::PtFromRadius::setPt(TrigL2MuonSA::TrackPattern& trackPattern) const
 {
   const double ZERO_LIMIT = 1e-5;
 
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.h
index 0d51efd779795a43bf4bbb329abebdc54608f2b2..f3d9e9a6ab9ac864c20c5f454d8f98cba886b4fb 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/PtFromRadius.h
@@ -29,7 +29,7 @@ class PtFromRadius: public AthAlgTool
  public:
   
   // For Barrel
-  StatusCode setPt(TrigL2MuonSA::TrackPattern& trackPattern);
+  StatusCode setPt(TrigL2MuonSA::TrackPattern& trackPattern) const;
   
  private:
   BooleanProperty  m_use_mcLUT{0};
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RecMuonRoIUtils.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RecMuonRoIUtils.h
index 091cedda2bd8c7db61789e79efcc8d88e861dbf0..5c031b02f77d37b4893a81284104de208b49d408 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RecMuonRoIUtils.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RecMuonRoIUtils.h
@@ -16,13 +16,13 @@ class RecMuonRoIUtils
       ~RecMuonRoIUtils() {};
 
    public:
-      bool isBarrel(const LVL1::RecMuonRoI* p_roi){
+      bool isBarrel(const LVL1::RecMuonRoI* p_roi) const {
         return (p_roi->sysID()==0) ? true : false; 
       };
-      bool isLowPt(const LVL1::RecMuonRoI* p_roi){
+      bool isLowPt(const LVL1::RecMuonRoI* p_roi) const {
         return (p_roi->getThresholdNumber() <4) ? true : false;
       };
-      bool isHighPt(const LVL1::RecMuonRoI* p_roi){
+      bool isHighPt(const LVL1::RecMuonRoI* p_roi) const {
         return (p_roi->getThresholdNumber()>=4) ? true : false;
       };
 };
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.cxx
index 16cc5e662b05b8b763a8eb7b5492e62af1c7ac12..45e271dd9a883bdbf7776a6d4adb180bf24cbfcd 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.cxx
@@ -40,7 +40,7 @@ StatusCode TrigL2MuonSA::RpcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
                                                     double                       roiEtaMinLow,
                                                     double                       roiEtaMaxLow,
                                                     double                       roiEtaMinHigh,
-                                                    double                       roiEtaMaxHigh)
+                                                    double                       roiEtaMaxHigh) const
 {
 
   const double ZERO_LIMIT = 1e-5;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.h
index 2d048de141ae9740fe5612126d82d20019d28797..3c21dc00fc7f794ca6581ea2dce04c623299ca73 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/RpcRoadDefiner.h
@@ -47,7 +47,7 @@ class RpcRoadDefiner: public AthAlgTool
 			double                       roiEtaMinLow,
 			double                       roiEtaMaxLow,
 			double                       roiEtaMinHigh,
-			double                       roiEtaMaxHigh);
+			double                       roiEtaMaxHigh) const;
 
   void setMdtGeometry(const ServiceHandle<IRegSelSvc>& regionSelector){ m_regionSelector = regionSelector; };
   void setRoadWidthForFailure(double rWidth_RPC_Failed){ m_rWidth_RPC_Failed = rWidth_RPC_Failed; };
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.cxx
index 6b5088969bba6e70aa9c12254899a7e9d79959b7..7ea260af65bbcca69a55e45781c695aae2d20998 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.cxx
@@ -36,7 +36,7 @@ void TrigL2MuonSA::SagittaRadiusEstimate::setMCFlag(BooleanProperty use_mcLUT,
 
 StatusCode TrigL2MuonSA::SagittaRadiusEstimate::setSagittaRadius(const LVL1::RecMuonRoI*     p_roi,
 								 TrigL2MuonSA::RpcFitResult& rpcFitResult,
-								 TrigL2MuonSA::TrackPattern& trackPattern)
+								 TrigL2MuonSA::TrackPattern& trackPattern) const
 {
   const int MAX_STATION = 4;
   const float ZERO_LIMIT = 1e-5;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.h
index f0d837cafe548de37046d7922d87fefef4739690..e7cd91234d6eea3dd00d47421a53d721eb68f1a2 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/SagittaRadiusEstimate.h
@@ -36,7 +36,7 @@ namespace TrigL2MuonSA {
   
   StatusCode setSagittaRadius(const LVL1::RecMuonRoI*     p_roi,
 			      TrigL2MuonSA::RpcFitResult& rpcFitResult,
-			      TrigL2MuonSA::TrackPattern& trackPattern);
+			      TrigL2MuonSA::TrackPattern& trackPattern) const;
   
  private:
   
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.cxx
index f71644cdb8c2f81a1b8c14bc72d26d941e08dc69..8b97200d32aaa467f68344aff28648b2e7f26a38 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.cxx
@@ -48,7 +48,7 @@ double TrigL2MuonSA::TgcFit::LinStats::eval(double fX) const
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-void TrigL2MuonSA::TgcFit::SimpleStatistics(TrigL2MuonSA::TgcFit::PointArray& points, TrigL2MuonSA::TgcFit::SimpleStats& stats)
+void TrigL2MuonSA::TgcFit::SimpleStatistics(TrigL2MuonSA::TgcFit::PointArray& points, TrigL2MuonSA::TgcFit::SimpleStats& stats) const
 {
   double *y = new double[points.size()];
   double *w = new double[points.size()];
@@ -104,7 +104,7 @@ void TrigL2MuonSA::TgcFit::SimpleStatistics(TrigL2MuonSA::TgcFit::PointArray& po
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-void TrigL2MuonSA::TgcFit::linReg(TrigL2MuonSA::TgcFit::PointArray& points, TrigL2MuonSA::TgcFit::LinStats& stats)
+void TrigL2MuonSA::TgcFit::linReg(TrigL2MuonSA::TgcFit::PointArray& points, TrigL2MuonSA::TgcFit::LinStats& stats) const
 {
   double *x = new double[points.size()];
   double *y = new double[points.size()];
@@ -179,7 +179,7 @@ void TrigL2MuonSA::TgcFit::linReg(TrigL2MuonSA::TgcFit::PointArray& points, Trig
 
 TrigL2MuonSA::TgcFit::Status TrigL2MuonSA::TgcFit::runTgcMiddle(TrigL2MuonSA::TgcFit::PointArray& stripPoints,
     TrigL2MuonSA::TgcFit::PointArray& wirePoints,
-    TrigL2MuonSA::TgcFitResult& tgcFitResult)
+    TrigL2MuonSA::TgcFitResult& tgcFitResult) const
 {
   ATH_MSG_DEBUG("TrigL2MuonSA::TgcFit::runTgcMiddle stripPoints=" << stripPoints.size()
       << " wirePoints=" << wirePoints.size());
@@ -304,7 +304,7 @@ TrigL2MuonSA::TgcFit::Status TrigL2MuonSA::TgcFit::runTgcMiddle(TrigL2MuonSA::Tg
 
 TrigL2MuonSA::TgcFit::Status TrigL2MuonSA::TgcFit::runTgcInner(TrigL2MuonSA::TgcFit::PointArray& stripPoints,
     TrigL2MuonSA::TgcFit::PointArray& wirePoints,
-    TrigL2MuonSA::TgcFitResult& tgcFitResult)
+    TrigL2MuonSA::TgcFitResult& tgcFitResult) const
 {
   Status status = FIT_NONE;
   SimpleStats stripStats;
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.h
index c418c0524773765ac829ff24ea59bc0f6982cd67..d69ad5bea68d3a03ba9dd7189860bc3453dd647b 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcFit.h
@@ -176,18 +176,18 @@ class TgcFit: public AthAlgTool
    * @param points The input list of data points.
    * @param stats The statistics struct to fill with fit results.
    */
-  void linReg(PointArray& points, LinStats& stats);
+  void linReg(PointArray& points, LinStats& stats) const;
   /*
    *  Calculate simple statistics for the Y values of a set of points.
    * @param points The input list of data points.
    * @param stats The statistics struct to fill with fit results.
    */
-  void SimpleStatistics(PointArray& points, SimpleStats& stats);
+  void SimpleStatistics(PointArray& points, SimpleStats& stats) const;
   /*
    *  Fit data to TGC. Calculate outliers and fit lines to strip and wire points.
    */
-  Status runTgcMiddle(PointArray& stripPoints, PointArray& wirePoints, TgcFitResult& fitResult);
-  Status runTgcInner(PointArray& stripPoints, PointArray& wirePoints, TgcFitResult& fitResult);
+  Status runTgcMiddle(PointArray& stripPoints, PointArray& wirePoints, TgcFitResult& fitResult) const;
+  Status runTgcInner(PointArray& stripPoints, PointArray& wirePoints, TgcFitResult& fitResult) const;
   
  protected:
   PointArray m_superPoints;           /**< List of wire (eta) super-points. */
@@ -196,7 +196,7 @@ class TgcFit: public AthAlgTool
   unsigned m_MIN_WIRE_POINTS { 4 };   /**< Minimum number of wire points for linear fit. */
   unsigned m_MIN_STRIP_POINTS { 3 };  /**< Minimum number of strip points for linear fit. */
   
-  void printDebug(const std::string& str){ ATH_MSG_DEBUG(str); };
+  void printDebug(const std::string& str) const { ATH_MSG_DEBUG(str); };
 };
  
 }
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.cxx b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.cxx
index 462859b0adc50bc55368baec8b99c5b630ba1fff..7511369023e3682798d62c7c3fd66c73747dc78e 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.cxx
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.cxx
@@ -47,7 +47,7 @@ StatusCode TrigL2MuonSA::TgcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
                                                     const bool                   insideOut,
                                                     const TrigL2MuonSA::TgcHits& tgcHits,
                                                     TrigL2MuonSA::MuonRoad&      muonRoad,
-                                                    TrigL2MuonSA::TgcFitResult&  tgcFitResult)
+                                                    TrigL2MuonSA::TgcFitResult&  tgcFitResult) const
 {
   const int N_STATION = 10;
   const int N_LAYER = 8;
@@ -73,12 +73,17 @@ StatusCode TrigL2MuonSA::TgcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
   int barrel_inner = xAOD::L2MuonParameters::Chamber::BarrelInner;
   int csc = xAOD::L2MuonParameters::Chamber::CSC;
   int bee = xAOD::L2MuonParameters::Chamber::BEE;
- 
+  
+  TrigL2MuonSA::TgcFit::PointArray tgcStripMidPoints;  // List of TGC strip middle station points.
+  TrigL2MuonSA::TgcFit::PointArray tgcWireMidPoints;   // List of TGC wire middle station points.
+  TrigL2MuonSA::TgcFit::PointArray tgcStripInnPoints;  // List of TGC strip inner station points.
+  TrigL2MuonSA::TgcFit::PointArray tgcWireInnPoints;   // List of TGC wire inner station points.
+
   if (tgcHits.size()>0) {
     // TGC data is properly read
  
     // Split digits to Strip/Wire points.
-    if( ! prepareTgcPoints(tgcHits) ) {
+    if( ! prepareTgcPoints(tgcHits, tgcStripInnPoints, tgcWireInnPoints, tgcStripMidPoints, tgcWireMidPoints) ) {
       ATH_MSG_ERROR("Preparation of Tgc points failed");
       return StatusCode::FAILURE;
     }
@@ -86,7 +91,7 @@ StatusCode TrigL2MuonSA::TgcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
 
     // Fit lines to TGC middle station
     isMiddleFailure = false;
-    TgcFit::Status status = m_tgcFit->runTgcMiddle(m_tgcStripMidPoints, m_tgcWireMidPoints, tgcFitResult);
+    TgcFit::Status status = m_tgcFit->runTgcMiddle(tgcStripMidPoints, tgcWireMidPoints, tgcFitResult);
     if (status == TgcFit::FIT_NONE) {
       ATH_MSG_WARNING("Fit to TGC middle station points failed");
       isMiddleFailure = true;
@@ -96,7 +101,7 @@ StatusCode TrigL2MuonSA::TgcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
     }
     
     // Fit lines to TGC inner station
-    status = m_tgcFit->runTgcInner(m_tgcStripInnPoints, m_tgcWireInnPoints, tgcFitResult);
+    status = m_tgcFit->runTgcInner(tgcStripInnPoints, tgcWireInnPoints, tgcFitResult);
     if (status == TgcFit::FIT_NONE) {
       ATH_MSG_DEBUG("Fit to TGC inner station points failed");
     } 
@@ -402,19 +407,18 @@ StatusCode TrigL2MuonSA::TgcRoadDefiner::defineRoad(const LVL1::RecMuonRoI*
 // --------------------------------------------------------------------------------
 // --------------------------------------------------------------------------------
 
-bool TrigL2MuonSA::TgcRoadDefiner::prepareTgcPoints(const TrigL2MuonSA::TgcHits& tgcHits)
+bool TrigL2MuonSA::TgcRoadDefiner::prepareTgcPoints(const TrigL2MuonSA::TgcHits& tgcHits,
+                                                    TrigL2MuonSA::TgcFit::PointArray& tgcStripInnPoints,
+                                                    TrigL2MuonSA::TgcFit::PointArray& tgcWireInnPoints,
+                                                    TrigL2MuonSA::TgcFit::PointArray& tgcStripMidPoints,
+                                                    TrigL2MuonSA::TgcFit::PointArray& tgcWireMidPoints) const
 {
    const double PHI_BOUNDARY = 0.2;
 
-   ATH_MSG_DEBUG(", m_tgcStripMidPoints.size()=" << m_tgcStripMidPoints.size() <<
-		 ", m_tgcStripInnPoints.size()=" << m_tgcStripInnPoints.size() <<
-		 ", m_tgcWireMidPoints.size()=" << m_tgcWireMidPoints.size() <<
-		 ", m_tgcWireInnPoints.size()=" << m_tgcWireInnPoints.size());
-   
-   m_tgcStripMidPoints.clear();
-   m_tgcStripInnPoints.clear();
-   m_tgcWireMidPoints.clear();
-   m_tgcWireInnPoints.clear();
+   tgcStripMidPoints.clear();
+   tgcStripInnPoints.clear();
+   tgcWireMidPoints.clear();
+   tgcWireInnPoints.clear();
 
    // loop over TGC digits.
    unsigned int iHit;
@@ -433,15 +437,20 @@ bool TrigL2MuonSA::TgcRoadDefiner::prepareTgcPoints(const TrigL2MuonSA::TgcHits&
          w *= hit.r * hit.r;
          double phi = hit.phi;
          if( phi < 0 && ( (M_PI+phi)<PHI_BOUNDARY) ) phi += M_PI*2;
-         if      ( hit.sta < 3 ) { m_tgcStripMidPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, phi, w)); }
-         else if ( hit.sta ==3 ) { m_tgcStripInnPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, phi, w)); }
+         if      ( hit.sta < 3 ) { tgcStripMidPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, phi, w)); }
+         else if ( hit.sta ==3 ) { tgcStripInnPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, phi, w)); }
       }
       else
       {
-         if      ( hit.sta < 3 ) { m_tgcWireMidPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, hit.r, w)); }
-         else if ( hit.sta ==3 ) { m_tgcWireInnPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, hit.r, w)); }
+         if      ( hit.sta < 3 ) { tgcWireMidPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, hit.r, w)); }
+         else if ( hit.sta ==3 ) { tgcWireInnPoints.push_back(TgcFit::Point(iHit + 1, hit.sta, hit.z, hit.r, w)); }
       }
    }
-
+   
+   ATH_MSG_DEBUG(", tgcStripMidPoints.size()=" << tgcStripMidPoints.size() <<
+		 ", tgcStripInnPoints.size()=" << tgcStripInnPoints.size() <<
+		 ", tgcWireMidPoints.size()=" << tgcWireMidPoints.size() <<
+		 ", tgcWireInnPoints.size()=" << tgcWireInnPoints.size());
+   
    return true;
 }
diff --git a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.h b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.h
index 0ee78135ca39ca997e13dcd93396c6c19cf6223a..6987ce71bf4d95a295d67d7bc64ba246b93f8d46 100644
--- a/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.h
+++ b/Trigger/TrigAlgorithms/TrigL2MuonSA/src/TgcRoadDefiner.h
@@ -40,15 +40,19 @@ class TgcRoadDefiner: public AthAlgTool
                         const bool                   insideOut,
                         const TrigL2MuonSA::TgcHits& tgcHits,
                         TrigL2MuonSA::MuonRoad&      muonRoad,
-                        TrigL2MuonSA::TgcFitResult&  tgcFitResult);
+                        TrigL2MuonSA::TgcFitResult&  tgcFitResult) const;
 
   void setMdtGeometry(const ServiceHandle<IRegSelSvc>& regionSelector) { m_regionSelector = regionSelector; };
   void setPtLUT(const TrigL2MuonSA::PtEndcapLUTSvc* ptEndcapLUTSvc) { m_ptEndcapLUT = ptEndcapLUTSvc->ptEndcapLUT(); };
   void setRoadWidthForFailure(double rWidth_TGC_Failed) { m_rWidth_TGC_Failed = rWidth_TGC_Failed; };
   void setExtrapolatorTool(ToolHandle<ITrigMuonBackExtrapolator>* backExtrapolator) { m_backExtrapolatorTool = backExtrapolator; };
 
-  bool prepareTgcPoints(const TrigL2MuonSA::TgcHits& tgcHits);
-  
+  bool prepareTgcPoints(const TrigL2MuonSA::TgcHits& tgcHits,
+                        TrigL2MuonSA::TgcFit::PointArray& tgcStripInnPoints,
+                        TrigL2MuonSA::TgcFit::PointArray& tgcWireInnPoints,
+                        TrigL2MuonSA::TgcFit::PointArray& tgcStripMidPoints,
+                        TrigL2MuonSA::TgcFit::PointArray& tgcWireMidPoints) const;
+
  private:
   // setted in MuFastSteering::hltInitialize, setExtrapolatorTool
   ToolHandle<ITrigMuonBackExtrapolator>* m_backExtrapolatorTool {nullptr};
@@ -57,11 +61,6 @@ class TgcRoadDefiner: public AthAlgTool
 
   ToolHandle<TgcFit>                     m_tgcFit {"TrigL2MuonSA::TgcFit"};
 
-  TrigL2MuonSA::TgcFit::PointArray m_tgcStripMidPoints;  // List of TGC strip middle station points.
-  TrigL2MuonSA::TgcFit::PointArray m_tgcWireMidPoints;   // List of TGC wire middle station points.
-  TrigL2MuonSA::TgcFit::PointArray m_tgcStripInnPoints;  // List of TGC strip inner station points.
-  TrigL2MuonSA::TgcFit::PointArray m_tgcWireInnPoints;   // List of TGC wire inner station points.
-
   double m_rWidth_TGC_Failed {0};
   
   ServiceHandle<IRegSelSvc> m_regionSelector;
diff --git a/Trigger/TrigHypothesis/TrigHypoCommonTools/TrigHypoCommonTools/L1InfoHypoTool.h b/Trigger/TrigHypothesis/TrigHypoCommonTools/TrigHypoCommonTools/L1InfoHypoTool.h
index 0a57b49eb7fa8843de80cea0a3a23cba71cc08e0..0f2a20c5afd874865d871e80330678ec1be9b7f9 100644
--- a/Trigger/TrigHypothesis/TrigHypoCommonTools/TrigHypoCommonTools/L1InfoHypoTool.h
+++ b/Trigger/TrigHypothesis/TrigHypoCommonTools/TrigHypoCommonTools/L1InfoHypoTool.h
@@ -8,7 +8,7 @@
 #include "Gaudi/Property.h"
 #include "GaudiKernel/ToolHandle.h"
 #include "AthenaBaseComps/AthAlgTool.h"
-#include "L1Decoder/CTPUnpackingTool.h"
+#include "L1Decoder/ICTPUnpackingTool.h"
 
 #include "IL1InfoHypoTool.h"
 
@@ -26,7 +26,7 @@ public:
 private:
     HLT::Identifier m_decisionId;
     Gaudi::Property <std::vector<std::string>> m_l1ItemNames {this, "L1ItemNames"};
-    ToolHandle <CTPUnpackingTool> m_ctpUnpackingTool {this, "CTPUnpackingTool", "CTPUnpackingTool"};
+    ToolHandle <ICTPUnpackingTool> m_ctpUnpackingTool {this, "CTPUnpackingTool", "CTPUnpackingTool"};
 };
 
 #endif //TRIGHYPOCOMMONTOOLS_L1INFOHYPOTOOL_H
\ No newline at end of file
diff --git a/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.cxx b/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.cxx
index 15c87be8ae846ac67e9188736d97eab98dd14706..0ae9e41f7144166007f6d8b215784eedffd51321 100755
--- a/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.cxx
+++ b/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.cxx
@@ -724,12 +724,20 @@ void HLTJetMonTool::bookJetHists() {
   nvar = basicKineVar(varlist,bookvars);
   levels.clear(); levels.push_back("HLT"); /*levels.push_back("L1");*/
   for(JetSigIter k= m_basicHLTTrig.begin(); k != m_basicHLTTrig.end(); ++k ) {
-    const std::string theDir = HLTdir + "/" + (*k).first;
+    std::string theDir = HLTdir + "/" + (*k).first;
     m_monGroups[(*k).first] = theDir;
     ATH_MSG_DEBUG("Booking histograms for " << theDir);
     addMonGroup (new MonGroup(this, theDir, run));
     setCurrentMonGroup(theDir);
     bookBasicHists(levels,bookvars);
+    //Add MonGroup for plots based only on jets passing the chain criteria,
+    //to be stored in expert folder chain/PassingJets
+    theDir = HLTdir + "/" + (*k).first + "/PassingJets";
+    m_monGroups[(*k).first + "_PJ"] = theDir;
+    ATH_MSG_DEBUG("Booking histograms for " << theDir);
+    addMonGroup (new MonGroup(this, theDir, run));
+    setCurrentMonGroup(theDir);
+    bookBasicHists(levels,bookvars);
   }
  
   /* 
@@ -1855,10 +1863,75 @@ void HLTJetMonTool::fillBasicHLTforChain( const std::string& theChain, double th
       }// loop over features container
 
     } else { // TrigComposite mode
+
+      // First: retrieve all jets in the underlying jet container
+      // so that we can compare with the Legacy code above
+
+      std::string jetcollname = GetJetCollectionName(theChain); //need to retrieve underlying jet container name - hard-coded function!
+      const xAOD::JetContainer *jcont = 0;
+      StatusCode sc = StatusCode::SUCCESS;
+      sc = evtStore()->retrieve(jcont, jetcollname);
+      if(sc.isFailure() || !jcont) {
+        ATH_MSG_INFO ("Could not retrieve JetCollection with key \"" << jetcollname << "\" from TDS"  );
+      }
+      else {
+        ATH_MSG_DEBUG("FOUND JetCollection with key \"" << jetcollname << "\" from TDS"  );
+	for (const xAOD::Jet* j : *jcont) {
+
+          double e = (j->e())/Gaudi::Units::GeV;
+          double et = 0., epsilon = 1.e-3;
+
+          if(j->p4().Et() > epsilon) et = (j->p4().Et())/Gaudi::Units::GeV;
+
+          ATH_MSG_DEBUG("jet et = "<<et);
+
+          if(et < epsilon) et = 0;
+          bool hlt_thr_pass = ( et > thrHLT );
+          if(hlt_thr_pass) {
+            double eta     = j->eta();
+            double phi     = j->phi();
+            double m       = j->m()/Gaudi::Units::GeV;
+            float  emfrac  =1;
+            float  hecfrac =1;
+            if ((m_isPP || m_isCosmic || m_isMC) &&
+              j->getAttribute<float>(xAOD::JetAttribute::EMFrac, emfrac))
+            {
+              hecfrac = j->getAttribute<float>(xAOD::JetAttribute::HECFrac); 
+            }
+
+            v_thisjet.SetPtEtaPhiE(j->pt()/Gaudi::Units::GeV,j->eta(), j->phi(),j->e()/Gaudi::Units::GeV);
+            m_v_HLTjet.push_back(v_thisjet);
+            m_n_index++;
+
+            if((h  = hist("HLTJet_Et")))            h->Fill(et,      m_lumi_weight);
+            if((h  = hist("HLTJet_HighEt")))        h->Fill(et,      m_lumi_weight);
+            if((h  = hist("HLTJet_eta")))           h->Fill(eta,     m_lumi_weight);
+            if((h  = hist("HLTJet_phi")))           h->Fill(phi,     m_lumi_weight);
+            if((h  = hist("HLTJet_m")))             h->Fill(m,       m_lumi_weight);
+            if((h  = hist("HLTJet_emfrac")))        h->Fill(emfrac,  m_lumi_weight);
+            if((h  = hist("HLTJet_hecfrac")))       h->Fill(hecfrac, m_lumi_weight);
+
+            if (count==0){
+              if((h  = hist("HLTJet_Leading_Et")))            h->Fill(et,      m_lumi_weight);
+            }
+
+            if((h2 = hist2("HLTJet_phi_vs_eta")))   h2->Fill(eta,phi,m_lumi_weight);  
+            if((h2 = hist2("HLTJet_E_vs_eta")))     h2->Fill(eta,e,m_lumi_weight); 
+            if((h2 = hist2("HLTJet_E_vs_phi")))     h2->Fill(phi,e,m_lumi_weight); 
+
+          }// if hlt threshold
+          count++;
+        }// loop over jet container
+      if((h  = hist("HLTJet_n")))            h->Fill(count,      m_lumi_weight);
+      } //else found jetcontainer
+      m_v_HLTindex.push_back(m_n_index);
+
       // Note: Only getting jets which pass theChain here
+      // Thus, setting path for plots to a subfolder "/PassingJets" of the chain
+      setCurrentMonGroup(m_monGroups[Form("%s_PJ",theChain.c_str())]);
+      count=0;
       const std::vector< TrigCompositeUtils::LinkInfo<xAOD::JetContainer> > fc = 
         getTDT()->features<xAOD::JetContainer>( chain );
-
       std::list<const xAOD::Jet*> jetList; //structure needed to sort jets by ET
       for(const auto& jetLinkInfo : fc) {
         if (!jetLinkInfo.isValid()) {
@@ -1869,7 +1942,7 @@ void HLTJetMonTool::fillBasicHLTforChain( const std::string& theChain, double th
         const xAOD::Jet *trigjet = dynamic_cast<const xAOD::Jet*>(*j);
         jetList.push_back( trigjet );
       }
-      auto sort = [] (const xAOD::Jet * j1, const xAOD::Jet * j2) {return j1->p4().Et() > j2->p4().Et(); } ;
+      auto sort = [] (const xAOD::Jet * j1, const xAOD::Jet * j2) {return j1->p4().Et() > j2->p4().Et(); } ; //can choose different way of sorting!
       jetList.sort( sort );
       for(const xAOD::Jet* j : jetList) {
         // ATH_MSG_INFO("Loop Over Features");
@@ -1893,10 +1966,6 @@ void HLTJetMonTool::fillBasicHLTforChain( const std::string& theChain, double th
           {
             hecfrac = j->getAttribute<float>(xAOD::JetAttribute::HECFrac); 
           }
-
-          v_thisjet.SetPtEtaPhiE(j->pt()/Gaudi::Units::GeV,j->eta(), j->phi(),j->e()/Gaudi::Units::GeV);
-          m_v_HLTjet.push_back(v_thisjet);
-          m_n_index++;
            
           if((h  = hist("HLTJet_Et")))            h->Fill(et,      m_lumi_weight);
           if((h  = hist("HLTJet_HighEt")))        h->Fill(et,      m_lumi_weight);
@@ -3302,3 +3371,17 @@ int HLTJetMonTool::basicKineVar(const std::string& hist, std::vector<std::string
   return retval;
 }
 // ------------------------------------------------------------------------------------
+std::string HLTJetMonTool::GetJetCollectionName(const std::string& theChain) {
+  std::string jetcoll = "HLT_AntiKt4EMTopoJets_subjesIS"; //default small-R EMTopo jets
+  if (theChain.find("a10t") != std::string::npos) jetcoll = "HLT_AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets_jes";
+  else if(theChain.find("a10r") != std::string::npos) jetcoll = "HLT_AntiKt10JetRCJets_subjesIS";
+  else if(theChain.find("a10") != std::string::npos) jetcoll = "HLT_AntiKt10LCTopoJets_subjes"; //default large-R jets
+  else if(theChain.find("ftf") != std::string::npos) { //EMPFlow jets
+    if (theChain.find("subjesgsc") != std::string::npos) jetcoll = "HLT_AntiKt4EMPFlowJets_subjesgscIS_ftf";
+    else if (theChain.find("pf_nojcalib") != std::string::npos) jetcoll = "HLT_AntiKt4EMPFlowJets_nojcalib_ftf";
+    else if (theChain.find("csskpf_nojcalib") != std::string::npos) jetcoll = "HLT_AntiKt4EMPFlowCSSKJets_nojcalib_ftf";
+    else jetcoll = "HLT_AntiKt4EMPFlowJets_subjesIS_ftf"; //default small-R EMPFlow
+  }
+  return jetcoll;
+}
+// ------------------------------------------------------------------------------------
diff --git a/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.h b/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.h
index 8ed6e84559a7d9ad192a3d97dee4f1ff2fe14e81..bb1212fb33343d2c976c5960fffcffdf37af608b 100755
--- a/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.h
+++ b/Trigger/TrigMonitoring/TrigJetMonitoring/src/HLTJetMonTool.h
@@ -205,6 +205,7 @@ class HLTJetMonTool : public IHLTMonTool {
     void setHistProperties(TH1* h);
     void set2DHistProperties(TH2* h);
     int basicKineVar(const std::string& hist, std::vector<std::string>& kinevars);
+    std::string GetJetCollectionName(const std::string& theChain);
     void clearVectors();
     
     // offline jet cuts
diff --git a/Trigger/TrigMonitoring/TrigTauMonitoring/src/HLTTauMonTool.cxx b/Trigger/TrigMonitoring/TrigTauMonitoring/src/HLTTauMonTool.cxx
index f6553da429ead9e19844fae4e1a01fd277d02c12..63a93ca8d991ea05a4fd49a05492e860bb166d44 100644
--- a/Trigger/TrigMonitoring/TrigTauMonitoring/src/HLTTauMonTool.cxx
+++ b/Trigger/TrigMonitoring/TrigTauMonitoring/src/HLTTauMonTool.cxx
@@ -3727,7 +3727,7 @@ bool HLTTauMonTool::HLTTauMatching(const std::string & trigItem, const TLorentzV
     } else { // TrigComposite
 
       const std::vector< TrigCompositeUtils::LinkInfo<xAOD::TauJetContainer> > features = 
-        getTDT()->features<xAOD::TauJetContainer>( trig_item_EF, TrigDefs::includeFailedDecisions, "TrigTauRecMerged" );
+        getTDT()->features<xAOD::TauJetContainer>( trig_item_EF, TrigDefs::includeFailedDecisions, ".*TrigTauRecMerged_.*" );
 
       for(const auto& tauJetLinkInfo : features){
         if (!tauJetLinkInfo.isValid()) {
diff --git a/Trigger/TrigSteer/L1Decoder/CMakeLists.txt b/Trigger/TrigSteer/L1Decoder/CMakeLists.txt
index 6c516ca73e62d1f7767873b4ac9caeb795de490d..a31a47f532740242523d857800c70e1c554b2628 100644
--- a/Trigger/TrigSteer/L1Decoder/CMakeLists.txt
+++ b/Trigger/TrigSteer/L1Decoder/CMakeLists.txt
@@ -9,13 +9,12 @@ find_package( CLHEP )
 
 # Component(s) in the package:
 atlas_add_library( L1DecoderLib
-                   L1DecoderRoot/*.cxx
                    PUBLIC_HEADERS L1Decoder
                    INTERFACE 
                    LINK_LIBRARIES TrigConfInterfaces)
                    
 atlas_add_component( L1Decoder
-                     src/*.cxx src/components/*.cxx L1DecoderRoot/*.cxx
+                     src/*.cxx src/components/*.cxx
                      INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${CLHEP_INCLUDE_DIRS}
                      LINK_LIBRARIES ${CLHEP_LIBRARIES} AthViews AthenaBaseComps AthenaKernel AthenaMonitoringKernelLib GaudiKernel L1DecoderLib StoreGateLib TrigCompositeUtilsLib TrigConfData TrigConfHLTData TrigConfL1Data TrigCostMonitorMTLib TrigSteeringEvent TrigT1Interfaces TrigT1Result TrigTimeAlgsLib xAODEventInfo xAODTrigger TrigConfxAODLib  )
 
diff --git a/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingTool.h b/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingTool.h
index 53d1f72df5dcfac9e8f00b6e72cc412bb4530f0d..d8b306166ab472b51de2b20d14f04a88ab1584af 100644
--- a/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingTool.h
+++ b/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingTool.h
@@ -29,7 +29,7 @@ public:
 
   virtual StatusCode start() override;
 
-  StatusCode passBeforePrescaleSelection(const ROIB::RoIBResult* roib, const std::vector<std::string>& l1ItemNames, bool& pass) const;
+  virtual StatusCode passBeforePrescaleSelection(const ROIB::RoIBResult* roib, const std::vector<std::string>& l1ItemNames, bool& pass) const;
 
 private:
   // Menu objects (that act here as configuration) need to be available in detector store.
diff --git a/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingToolBase.h b/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingToolBase.h
index e524808911cffec636e19e5326d9d3eece2d259f..dff6163befe1c15a68b6131c3e4a89938504519b 100644
--- a/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingToolBase.h
+++ b/Trigger/TrigSteer/L1Decoder/L1Decoder/CTPUnpackingToolBase.h
@@ -29,12 +29,12 @@ public:
                        const IInterface* parent);
 
   virtual StatusCode decode(const ROIB::RoIBResult& /*roib*/,
-                            HLT::IDVec& /*enabledChains*/) const override
-  { return StatusCode::SUCCESS; }
+                            HLT::IDVec& /*enabledChains*/) const override;
 
   virtual StatusCode initialize() override;
 
-  virtual StatusCode passBeforePrescaleSelection(const ROIB::RoIBResult* roib, const std::vector<std::string>& l1ItemNames, bool& pass) const override;
+  virtual StatusCode passBeforePrescaleSelection(const ROIB::RoIBResult* /*roib*/,
+                            const std::vector<std::string>& /*l1ItemNames*/, bool& /*pass*/) const override;
 
 protected:
 
diff --git a/Trigger/TrigSteer/L1Decoder/L1DecoderRoot/CTPUnpackingTool.cxx b/Trigger/TrigSteer/L1Decoder/src/CTPUnpackingTool.cxx
similarity index 100%
rename from Trigger/TrigSteer/L1Decoder/L1DecoderRoot/CTPUnpackingTool.cxx
rename to Trigger/TrigSteer/L1Decoder/src/CTPUnpackingTool.cxx
diff --git a/Trigger/TrigSteer/L1Decoder/L1DecoderRoot/CTPUnpackingToolBase.cxx b/Trigger/TrigSteer/L1Decoder/src/CTPUnpackingToolBase.cxx
similarity index 71%
rename from Trigger/TrigSteer/L1Decoder/L1DecoderRoot/CTPUnpackingToolBase.cxx
rename to Trigger/TrigSteer/L1Decoder/src/CTPUnpackingToolBase.cxx
index 2a228fe7bf5f556560498823b76394b837d4e057..a9976d88c3d6465ce02dc15879afb833df4e75ae 100644
--- a/Trigger/TrigSteer/L1Decoder/L1DecoderRoot/CTPUnpackingToolBase.cxx
+++ b/Trigger/TrigSteer/L1Decoder/src/CTPUnpackingToolBase.cxx
@@ -25,5 +25,11 @@ StatusCode CTPUnpackingToolBase::initialize()
 }
 
 StatusCode CTPUnpackingToolBase::passBeforePrescaleSelection(const ROIB::RoIBResult* /*roib*/, const std::vector<std::string>& /*l1ItemNames*/, bool& /*pass*/) const {
-  return StatusCode::SUCCESS;
+  ATH_MSG_ERROR("Base class should not call this function");
+  return StatusCode::FAILURE;
+}
+
+StatusCode CTPUnpackingToolBase::decode(const ROIB::RoIBResult& /*roib*/, HLT::IDVec& /*enabledChains*/) const {
+  ATH_MSG_ERROR("Base class should not call this function");
+  return StatusCode::FAILURE;
 }
diff --git a/Trigger/TrigValidation/TrigAnalysisTest/share/ref_RDOtoRDOTrig_v1Dev_build.ref b/Trigger/TrigValidation/TrigAnalysisTest/share/ref_RDOtoRDOTrig_v1Dev_build.ref
index d68c23ad0ad69f8b054456b08ff39525f621192f..919cfc6341500652c7a1528cfd136e97a40ed999 100644
--- a/Trigger/TrigValidation/TrigAnalysisTest/share/ref_RDOtoRDOTrig_v1Dev_build.ref
+++ b/Trigger/TrigValidation/TrigAnalysisTest/share/ref_RDOtoRDOTrig_v1Dev_build.ref
@@ -590,8 +590,8 @@ TrigSignatureMoniMT                                 INFO HLT_mu0_muoncalib_L1MU4
 TrigSignatureMoniMT                                 INFO -- #782182242 Events          0          0          0          0          0          0          0          0          -          -          -          -          -          -          -          -          0
 TrigSignatureMoniMT                                 INFO -- #782182242 Features                              0          0          0          0          0          0          -          -          -          -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu10_L1MU10 #209090273
-TrigSignatureMoniMT                                 INFO -- #209090273 Events          10         10         0          0          0          0          0          10         10         10         8          -          -          -          -          -          8
-TrigSignatureMoniMT                                 INFO -- #209090273 Features                              0          0          0          0          0          12         12         13         10         -          -          -          -          -
+TrigSignatureMoniMT                                 INFO -- #209090273 Events          10         10         0          0          0          0          0          10         10         10         9          -          -          -          -          -          9
+TrigSignatureMoniMT                                 INFO -- #209090273 Features                              0          0          0          0          0          12         12         13         11         -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu10_ivarmedium_mu10_10invm70_L12MU10 #2386882549
 TrigSignatureMoniMT                                 INFO -- #2386882549 Events         3          3          0          0          0          0          0          2          2          2          2          2          -          -          -          -          2
 TrigSignatureMoniMT                                 INFO -- #2386882549 Features                             0          0          0          0          0          4          4          4          4          2          -          -          -          -
@@ -674,8 +674,8 @@ TrigSignatureMoniMT                                 INFO HLT_mu35_ivarmedium_L1M
 TrigSignatureMoniMT                                 INFO -- #597064890 Events          8          8          0          0          0          0          0          8          5          4          2          1          -          -          -          -          1
 TrigSignatureMoniMT                                 INFO -- #597064890 Features                              0          0          0          0          0          10         6          4          2          1          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu4_l2io_L1MU4 #1048276860
-TrigSignatureMoniMT                                 INFO -- #1048276860 Events         12         12         0          0          0          0          0          12         12         11         10         -          -          -          -          -          10
-TrigSignatureMoniMT                                 INFO -- #1048276860 Features                             0          0          0          0          0          15         50         15         14         -          -          -          -          -
+TrigSignatureMoniMT                                 INFO -- #1048276860 Events         12         12         0          0          0          0          0          12         12         11         11         -          -          -          -          -          11
+TrigSignatureMoniMT                                 INFO -- #1048276860 Features                             0          0          0          0          0          15         50         15         15         -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu50_L1MU20 #3657158931
 TrigSignatureMoniMT                                 INFO -- #3657158931 Events         8          8          0          0          0          0          0          8          5          2          1          -          -          -          -          -          1
 TrigSignatureMoniMT                                 INFO -- #3657158931 Features                             0          0          0          0          0          10         6          2          1          -          -          -          -          -
@@ -689,17 +689,17 @@ TrigSignatureMoniMT                                 INFO HLT_mu60_L1MU20 #287183
 TrigSignatureMoniMT                                 INFO -- #2871837722 Events         8          8          0          0          0          0          0          8          5          1          1          -          -          -          -          -          1
 TrigSignatureMoniMT                                 INFO -- #2871837722 Features                             0          0          0          0          0          10         6          1          1          -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_L1MU6 #2560542253
-TrigSignatureMoniMT                                 INFO -- #2560542253 Events         10         10         0          0          0          0          0          10         10         10         9          -          -          -          -          -          9
-TrigSignatureMoniMT                                 INFO -- #2560542253 Features                             0          0          0          0          0          13         12         13         12         -          -          -          -          -
+TrigSignatureMoniMT                                 INFO -- #2560542253 Events         10         10         0          0          0          0          0          10         10         10         10         -          -          -          -          -          10
+TrigSignatureMoniMT                                 INFO -- #2560542253 Features                             0          0          0          0          0          13         12         13         13         -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_idperf_L1MU6 #934918532
 TrigSignatureMoniMT                                 INFO -- #934918532 Events          10         10         0          0          0          0          0          10         10         10         10         -          -          -          -          -          10
 TrigSignatureMoniMT                                 INFO -- #934918532 Features                              0          0          0          0          0          13         13         13         13         -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_ivarmedium_L1MU6 #1012713062
-TrigSignatureMoniMT                                 INFO -- #1012713062 Events         10         10         0          0          0          0          0          10         10         10         9          6          -          -          -          -          6
-TrigSignatureMoniMT                                 INFO -- #1012713062 Features                             0          0          0          0          0          13         12         13         12         6          -          -          -          -
+TrigSignatureMoniMT                                 INFO -- #1012713062 Events         10         10         0          0          0          0          0          10         10         10         10         6          -          -          -          -          6
+TrigSignatureMoniMT                                 INFO -- #1012713062 Features                             0          0          0          0          0          13         12         13         13         6          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_j45_nojcalib_L1J20 #2114129685
-TrigSignatureMoniMT                                 INFO -- #2114129685 Events         19         19         0          0          0          0          0          9          9          9          8          0          0          -          -          -          0
-TrigSignatureMoniMT                                 INFO -- #2114129685 Features                             0          0          0          0          0          11         10         11         10         0          0          -          -          -
+TrigSignatureMoniMT                                 INFO -- #2114129685 Events         19         19         0          0          0          0          0          9          9          9          9          0          0          -          -          -          0
+TrigSignatureMoniMT                                 INFO -- #2114129685 Features                             0          0          0          0          0          11         10         11         11         0          0          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_msonly_L1MU6 #3895421032
 TrigSignatureMoniMT                                 INFO -- #3895421032 Events         10         10         0          0          0          0          0          10         0          10         -          -          -          -          -          -          10
 TrigSignatureMoniMT                                 INFO -- #3895421032 Features                             0          0          0          0          0          13         0          13         -          -          -          -          -          -
@@ -707,11 +707,11 @@ TrigSignatureMoniMT                                 INFO HLT_mu6_mu4_L12MU4 #171
 TrigSignatureMoniMT                                 INFO -- #1713982776 Events         4          4          0          0          0          0          0          3          3          2          2          -          -          -          -          -          2
 TrigSignatureMoniMT                                 INFO -- #1713982776 Features                             0          0          0          0          0          6          6          4          4          -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu6_mu6noL1_L1MU6 #451489897
-TrigSignatureMoniMT                                 INFO -- #451489897 Events          10         10         0          0          0          0          0          10         10         10         9          0          0          0          4          3          3
-TrigSignatureMoniMT                                 INFO -- #451489897 Features                              0          0          0          0          0          13         12         13         12         0          0          0          6          5
+TrigSignatureMoniMT                                 INFO -- #451489897 Events          10         10         0          0          0          0          0          10         10         10         10         0          0          0          6          4          4
+TrigSignatureMoniMT                                 INFO -- #451489897 Features                              0          0          0          0          0          13         12         13         13         0          0          0          8          6
 TrigSignatureMoniMT                                 INFO HLT_mu6_xe30_mht_L1XE10 #3192713675
-TrigSignatureMoniMT                                 INFO -- #3192713675 Events         19         19         0          0          0          0          0          9          9          9          8          0          8          -          -          -          8
-TrigSignatureMoniMT                                 INFO -- #3192713675 Features                             0          0          0          0          0          12         11         12         11         0          10         -          -          -
+TrigSignatureMoniMT                                 INFO -- #3192713675 Events         19         19         0          0          0          0          0          9          9          9          9          0          9          -          -          -          9
+TrigSignatureMoniMT                                 INFO -- #3192713675 Features                             0          0          0          0          0          12         11         12         12         0          11         -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu80_L1MU20 #387900377
 TrigSignatureMoniMT                                 INFO -- #387900377 Events          8          8          0          0          0          0          0          8          5          1          0          -          -          -          -          -          0
 TrigSignatureMoniMT                                 INFO -- #387900377 Features                              0          0          0          0          0          10         6          1          0          -          -          -          -          -
@@ -719,8 +719,8 @@ TrigSignatureMoniMT                                 INFO HLT_mu80_msonly_3layers
 TrigSignatureMoniMT                                 INFO -- #761101109 Events          8          8          0          0          0          0          0          8          0          1          -          -          -          -          -          -          1
 TrigSignatureMoniMT                                 INFO -- #761101109 Features                              0          0          0          0          0          10         0          1          -          -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_mu8_L1MU6 #1467711434
-TrigSignatureMoniMT                                 INFO -- #1467711434 Events         10         10         0          0          0          0          0          10         10         10         9          -          -          -          -          -          9
-TrigSignatureMoniMT                                 INFO -- #1467711434 Features                             0          0          0          0          0          13         12         13         12         -          -          -          -          -
+TrigSignatureMoniMT                                 INFO -- #1467711434 Events         10         10         0          0          0          0          0          10         10         10         10         -          -          -          -          -          10
+TrigSignatureMoniMT                                 INFO -- #1467711434 Features                             0          0          0          0          0          13         12         13         13         -          -          -          -          -
 TrigSignatureMoniMT                                 INFO HLT_noalg_L1All #2979253164
 TrigSignatureMoniMT                                 INFO -- #2979253164 Events         20         20         -          -          -          -          -          -          -          -          -          -          -          -          -          -          20
 TrigSignatureMoniMT                                 INFO -- #2979253164 Features                             -          -          -          -          -          -          -          -          -          -          -          -          -          -
diff --git a/Trigger/TrigValidation/TrigAnalysisTest/test/test_trigAna_HITtoAOD_trigRel21_mc16a_build.py b/Trigger/TrigValidation/TrigAnalysisTest/test/test_trigAna_HITtoAOD_trigRel21_mc16a_build.py
index fff2952e1bbb703620a1fb11e744dc3e1f25bb6a..70405a41232dc99470841167ee3278cb3ed10954 100755
--- a/Trigger/TrigValidation/TrigAnalysisTest/test/test_trigAna_HITtoAOD_trigRel21_mc16a_build.py
+++ b/Trigger/TrigValidation/TrigAnalysisTest/test/test_trigAna_HITtoAOD_trigRel21_mc16a_build.py
@@ -59,7 +59,7 @@ rdo2rdotrig.args = '--inputRDOFile=RDO.pool.root --outputRDO_TRIGFile=RDO_TRIG.p
 rdo2rdotrig.args += ' --asetup="RDOtoRDOTrigger:Athena,21.0-mc16a,slc6,latest"'
 rdo2rdotrig.args += ' --triggerConfig="MCRECO:MC_pp_v6_tight_mc_prescale"'
 rdo2rdotrig.args += ' --imf="all:True"'
-rdo2rdotrig.args += ' --preExec="all:from TriggerJobOpts.TriggerFlags import TriggerFlags; TriggerFlags.run2Config=\"2016\""'
+rdo2rdotrig.args += ' --preExec="all:from TriggerJobOpts.TriggerFlags import TriggerFlags; TriggerFlags.run2Config=\'2016\'"'
 
 # Clear AthFile cache from r21 because it is incompatible with py3 r22 (ATR-21489)
 rm_cache = ExecStep.ExecStep('ClearAthFileCache')
diff --git a/Trigger/TriggerCommon/TriggerJobOpts/share/runHLT_standalone.py b/Trigger/TriggerCommon/TriggerJobOpts/share/runHLT_standalone.py
index 56aa312dcf6e410aa7612bda0e0c2ce53375bd89..5b5c3d7e80507ef0cba506185cb61d2378e9df51 100644
--- a/Trigger/TriggerCommon/TriggerJobOpts/share/runHLT_standalone.py
+++ b/Trigger/TriggerCommon/TriggerJobOpts/share/runHLT_standalone.py
@@ -61,7 +61,6 @@ class opt:
     doMonitorSlice    = True
     doBeamspotSlice   = True
     doCosmicSlice     = True
-    doEnhancedBiasSlice = True
     doUnconventionalTrackingSlice   = True
     reverseViews      = False
     filterViews       = False