From bf08cba9f4935b821e637c23d15b982965872ffb Mon Sep 17 00:00:00 2001
From: Markus Frank <Markus.Frank@cern.ch>
Date: Thu, 23 May 2024 10:12:16 +0200
Subject: [PATCH] The battle agains coverity

---
 DDCond/src/ConditionsContent.cpp           |  2 +-
 DDCond/src/plugins/ConditionsPlugins.cpp   |  2 +-
 DDCond/src/plugins/ConditionsXmlLoader.cpp |  2 +-
 DDCore/include/DD4hep/GeoHandler.h         | 24 ++----
 DDCore/src/GeoHandler.cpp                  | 47 ++++++------
 DDCore/src/plugins/CodeGenerator.cpp       |  2 +-
 DDCore/src/plugins/DetectorChecksum.cpp    |  8 +-
 DDCore/src/plugins/VisProcessor.cpp        |  3 +-
 DDDigi/include/DDDigi/DigiData.h           | 43 +++++------
 DDDigi/io/DigiIO.cpp                       |  6 +-
 DDDigi/src/DigiContainerProcessor.cpp      | 78 ++++++++++----------
 DDDigi/src/DigiData.cpp                    |  2 +-
 DDDigi/src/DigiKernel.cpp                  |  2 +-
 DDDigi/src/DigiStoreDump.cpp               | 86 +++++++++++-----------
 DDDigi/src/noise/FalphaNoise.cpp           |  7 +-
 DDEve/include/DDEve/Display.h              | 14 ++--
 DDEve/src/Display.cpp                      |  8 +-
 DDG4/hepmc/HepMC3EventReader.cpp           |  2 +-
 DDG4/hepmc/HepMC3FileReader.cpp            |  2 +-
 DDG4/include/DDG4/Geant4InputAction.h      |  2 +-
 DDG4/lcio/LCIOFileReader.cpp               | 15 ++--
 DDG4/plugins/Geant4EscapeCounter.cpp       |  4 +-
 DDG4/plugins/Geant4EventReaderHepMC.cpp    | 28 ++++---
 DDG4/plugins/Geant4ROOTDump.cpp            |  2 +-
 DDG4/src/Geant4AssemblyVolume.cpp          |  2 +-
 DDG4/src/Geant4Converter.cpp               | 63 +++++++++++++++-
 DDG4/src/Geant4Helpers.cpp                 |  2 +-
 DDG4/src/Geant4SensDetAction.cpp           |  2 +-
 DDG4/src/Geant4ShapeConverter.cpp          |  3 +-
 DDG4/src/Geant4VolumeManager.cpp           |  5 +-
 DDParsers/src/Evaluator/Evaluator.cpp      |  6 +-
 DDRec/src/CellIDPositionConverter.cpp      | 10 +--
 DDRec/src/MaterialScan.cpp                 |  9 ++-
 DDTest/src/test_EventReaders.cc            |  2 +-
 GaudiPluginService/interface/DD4hep.h      |  2 +-
 35 files changed, 283 insertions(+), 214 deletions(-)

diff --git a/DDCond/src/ConditionsContent.cpp b/DDCond/src/ConditionsContent.cpp
index b7fbabae9..1540539f7 100644
--- a/DDCond/src/ConditionsContent.cpp
+++ b/DDCond/src/ConditionsContent.cpp
@@ -146,7 +146,7 @@ ConditionsContent::addDependency(DetElement de,
                                  Condition::itemkey_type item,
                                  std::shared_ptr<ConditionUpdateCall> callback)
 {
-  ConditionDependency* dep = new ConditionDependency(de, item, callback);
+  ConditionDependency* dep = new ConditionDependency(de, item, std::move(callback));
   return addDependency(dep);
 }
 
diff --git a/DDCond/src/plugins/ConditionsPlugins.cpp b/DDCond/src/plugins/ConditionsPlugins.cpp
index a675c0856..cad179458 100644
--- a/DDCond/src/plugins/ConditionsPlugins.cpp
+++ b/DDCond/src/plugins/ConditionsPlugins.cpp
@@ -436,7 +436,7 @@ static void* create_printer(Detector& description, int argc,char** argv)  {
   }
   PRINTER* p = (flags) ? new PRINTER(slice, prefix, flags) : new PRINTER(slice, prefix);
   p->printLevel = print_level;
-  if ( !name.empty() ) p->name = name;
+  if ( !name.empty() ) p->name = std::move(name);
   return (void*)dynamic_cast<WRAPPER*>(createProcessorWrapper(p));
 }
 
diff --git a/DDCond/src/plugins/ConditionsXmlLoader.cpp b/DDCond/src/plugins/ConditionsXmlLoader.cpp
index 71ae953e7..73af85faf 100644
--- a/DDCond/src/plugins/ConditionsXmlLoader.cpp
+++ b/DDCond/src/plugins/ConditionsXmlLoader.cpp
@@ -175,6 +175,6 @@ std::size_t ConditionsXmlLoader::load_range(key_type key,
     }
     keep.emplace_back(condition);
   }
-  m_buffer = keep;
+  m_buffer = std::move(keep);
   return conditions.size()-len;
 }
diff --git a/DDCore/include/DD4hep/GeoHandler.h b/DDCore/include/DD4hep/GeoHandler.h
index 3674b4ea3..6abb8fd91 100644
--- a/DDCore/include/DD4hep/GeoHandler.h
+++ b/DDCore/include/DD4hep/GeoHandler.h
@@ -51,17 +51,6 @@ namespace dd4hep {
      */
     class GeoHandlerTypes {
     public:
-#if 0
-      typedef std::set<const TGeoVolume*> ConstVolumeSet;
-      typedef std::map<SensitiveDetector, ConstVolumeSet> SensitiveVolumes;
-      typedef std::map<Region,   ConstVolumeSet>          RegionVolumes;
-      typedef std::map<LimitSet, ConstVolumeSet>          LimitVolumes;
-      typedef std::map<int, std::set<const TGeoNode*> >   Data;
-      typedef std::set<SensitiveDetector>                 SensitiveDetectorSet;
-      typedef std::set<Region>                            RegionSet;
-      typedef std::set<LimitSet>                          LimitSetSet;
-      typedef std::set<TNamed*>                           ObjectSet;
-#endif
       /// Data container to store information obtained during the geometry scan
       /**
        *  \author  M.Frank
@@ -97,13 +86,13 @@ namespace dd4hep {
     class GeoHandler: public GeoHandlerTypes {
 
     protected:
-      bool  m_propagateRegions;
-      std::map<int, std::set<const TGeoNode*> >* m_data;
-
+      bool  m_propagateRegions { false };
+      std::map<int, std::set<const TGeoNode*> >*    m_data      { nullptr };
+      std::map<const TGeoNode*, std::vector<TGeoNode*> >* m_daughters { nullptr };
       /// Internal helper to collect geometry information from traversal
       GeoHandler& i_collect(const TGeoNode* parent,
-			    const TGeoNode* node,
-			    int level, Region rg, LimitSet ls);
+                            const TGeoNode* node,
+                            int level, Region rg, LimitSet ls);
 
     private:
       /// Never call Copy constructor
@@ -118,7 +107,8 @@ namespace dd4hep {
       /// Default constructor
       GeoHandler();
       /// Initializing constructor
-      GeoHandler(std::map<int, std::set<const TGeoNode*> >* ptr);
+      GeoHandler(std::map<int, std::set<const TGeoNode*> >* ptr,
+                 std::map<const TGeoNode*, std::vector<TGeoNode*> >* daus = nullptr);
       /// Default destructor
       virtual ~GeoHandler();
       /// Propagate regions. Returns the previous value
diff --git a/DDCore/src/GeoHandler.cpp b/DDCore/src/GeoHandler.cpp
index 04941b671..38a10f5f6 100644
--- a/DDCore/src/GeoHandler.cpp
+++ b/DDCore/src/GeoHandler.cpp
@@ -50,13 +50,15 @@ namespace {
 }
 
 /// Default constructor
-detail::GeoHandler::GeoHandler() : m_propagateRegions(false)  {
+detail::GeoHandler::GeoHandler()  {
   m_data = new std::map<int, std::set<const TGeoNode*> >();
 }
 
 /// Initializing constructor
-detail::GeoHandler::GeoHandler(std::map<int, std::set<const TGeoNode*> >* ptr)
-  : m_propagateRegions(false), m_data(ptr) {
+detail::GeoHandler::GeoHandler(std::map<int, std::set<const TGeoNode*> >* ptr,
+                               std::map<const TGeoNode*, std::vector<TGeoNode*> >* daus)
+  : m_data(ptr), m_daughters(daus)
+{
 }
 
 /// Default destructor
@@ -91,15 +93,15 @@ detail::GeoHandler& detail::GeoHandler::collect(DetElement element, GeometryInfo
   TGeoNode* par_node = par.isValid() ? par.placement().ptr() : nullptr;
   m_data->clear();
   i_collect(par_node, element.placement().ptr(), 0, Region(), LimitSet());
-  for (auto i = m_data->rbegin(); i != m_data->rend(); ++i) {
+  for ( auto i = m_data->rbegin(); i != m_data->rend(); ++i ) {
     const auto& mapped = (*i).second;
-    for (const TGeoNode* n : mapped )  {
+    for ( const TGeoNode* n : mapped )  {
       TGeoVolume* v = n->GetVolume();
-      if (v) {
+      if ( v ) {
         Material mat(v->GetMedium());
         Volume   vol(v);
         // Note : assemblies and the world do not have a real volume nor a material
-        if (info.volumeSet.find(vol) == info.volumeSet.end()) {
+        if ( info.volumeSet.find(vol) == info.volumeSet.end() ) {
           info.volumeSet.emplace(vol);
           info.volumes.emplace_back(vol);
         }
@@ -128,35 +130,38 @@ detail::GeoHandler& detail::GeoHandler::i_collect(const TGeoNode* /* parent */,
                                                   const TGeoNode*    current,
                                                   int level, Region rg, LimitSet ls)
 {
-  TGeoVolume* volume = current->GetVolume();
-  TObjArray*  nodes = volume->GetNodes();
-  int         num_children = nodes ? nodes->GetEntriesFast() : 0;
-  Volume      vol(volume);
-  Region      region = vol.region();
-  LimitSet    limits = vol.limitSet();
+  TGeoVolume* vol    = current->GetVolume();
+  TObjArray*  nodes  = vol->GetNodes();
+  Volume      volume = vol;
+  Region      region = volume.region();
+  LimitSet    limits = volume.limitSet();
 
   if ( m_propagateRegions )  {
     if ( !region.isValid() && rg.isValid() )   {
       region = rg;
-      vol.setRegion(region);
+      volume.setRegion(region);
     }
     if ( !limits.isValid() && ls.isValid() )  {
       limits = ls;
-      vol.setLimitSet(limits);
+      volume.setLimitSet(limits);
     }
   }
+  /// Collect the hierarchy of placements
   (*m_data)[level].emplace(current);
-  if (num_children > 0) {
-    for (int i = 0; i < num_children; ++i) {
-      TGeoNode* node = (TGeoNode*) nodes->At(i);
-      i_collect(current, node, level + 1, region, limits);
-    }
+  int num = nodes ? nodes->GetEntriesFast() : 0;
+  for (int i = 0; i < num; ++i)
+    i_collect(current, (TGeoNode*)nodes->At(i), level + 1, region, limits);
+  /// Now collect all the daughters of this volume, so that we can reconnect them in the correct order
+  if ( m_daughters && m_daughters->find(current) == m_daughters->end() )  {
+    auto [idau,success] = m_daughters->emplace(current, std::vector<TGeoNode*>());
+    for (int i = 0; i < num; ++i)
+      idau->second.push_back((TGeoNode*)nodes->At(i));
   }
   return *this;
 }
 
 /// Initializing constructor
-detail::GeoScan::GeoScan(DetElement e) {
+detail::GeoScan::GeoScan(DetElement e)  {
   m_data = GeoHandler().collect(e).release();
 }
 
diff --git a/DDCore/src/plugins/CodeGenerator.cpp b/DDCore/src/plugins/CodeGenerator.cpp
index bc120a404..d9044132b 100644
--- a/DDCore/src/plugins/CodeGenerator.cpp
+++ b/DDCore/src/plugins/CodeGenerator.cpp
@@ -302,7 +302,7 @@ namespace {
         log << "\t structure[" << pointer(de) << "] = de; " << newline
             << "}"   << newline;
       }
-      for(auto d : de.children() )  {
+      for(const auto& d : de.children() )  {
         handleStructure(log, de, d.second);
       }
       if ( !parent.isValid() )   {
diff --git a/DDCore/src/plugins/DetectorChecksum.cpp b/DDCore/src/plugins/DetectorChecksum.cpp
index 6c2578d9b..2d11a919e 100644
--- a/DDCore/src/plugins/DetectorChecksum.cpp
+++ b/DDCore/src/plugins/DetectorChecksum.cpp
@@ -138,13 +138,17 @@ DetectorChecksum::~DetectorChecksum() {
 template <typename T> std::string DetectorChecksum::refName(T handle)  const  {
   std::string nam = handle->GetName();
   std::size_t idx = nam.find("_0x");
-  return idx == std::string::npos ? nam : nam.substr(0, idx);
+  if ( idx == std::string::npos ) return nam;
+  return nam.substr(0, idx);
 }
+
 template <> std::string DetectorChecksum::refName(Segmentation handle)  const  {
   std::string nam = handle->name();
   std::size_t idx = nam.find("_0x");
-  return idx == std::string::npos ? nam : nam.substr(0, idx);
+  if ( idx == std::string::npos ) return nam;
+  return nam.substr(0, idx);
 }
+
 template <typename T> std::string DetectorChecksum::attr_name(T handle)  const  {
   std::string n = " name=\"" + refName(handle)+"\"";
   return n;
diff --git a/DDCore/src/plugins/VisProcessor.cpp b/DDCore/src/plugins/VisProcessor.cpp
index f16a6a360..ecbc7029d 100644
--- a/DDCore/src/plugins/VisProcessor.cpp
+++ b/DDCore/src/plugins/VisProcessor.cpp
@@ -228,8 +228,7 @@ static void* create_object(Detector& description, int argc, char** argv)   {
         printout(ERROR,"VisMaterialProcessor","++ Invalid DetElement path: %s",path.c_str());
       }
       else if ( ::strncmp(argv[i],"-name",4) == 0 )   {
-        std::string name = argv[++i];
-        proc->name = name;
+        proc->name = argv[++i];
         continue;
       }
       else if ( ::strncmp(argv[i],"-show",4) == 0 )   {
diff --git a/DDDigi/include/DDDigi/DigiData.h b/DDDigi/include/DDDigi/DigiData.h
index f0d529f7e..c0ddfb7d0 100644
--- a/DDDigi/include/DDDigi/DigiData.h
+++ b/DDDigi/include/DDDigi/DigiData.h
@@ -74,6 +74,7 @@ namespace dd4hep {
         mask_type    mask;
         itemkey_type item;
       } values;
+
     public:
       /// Default constructor
       Key();
@@ -884,13 +885,13 @@ namespace dd4hep {
     public: 
       template <typename T> using map_type_t = std::map<std::string, std::vector<T> >;
       struct header_data  {
-	map_type_t<std::string> stringParams;
-	map_type_t<float>       floatParams;
-	map_type_t<int>         intParams;
-	std::int32_t            run_number    {  -1 };
-	std::int32_t            event_number  {  -1 };
-	std::int64_t            time_stamp    {   0 };
-	double                  event_weight  { 0e0 };
+        map_type_t<std::string> stringParams;
+        map_type_t<float>       floatParams;
+        map_type_t<int>         intParams;
+        std::int32_t            run_number    {  -1 };
+        std::int32_t            event_number  {  -1 };
+        std::int64_t            time_stamp    {   0 };
+        double                  event_weight  { 0e0 };
       };
       std::shared_ptr<header_data> data;
     public: 
@@ -912,35 +913,35 @@ namespace dd4hep {
       std::size_t size()  const;
       /// Access the event number
       std::int32_t getEventNumber() const   {
-	return data->event_number;
+        return data->event_number;
       }
       /// Access the run number
       std::int32_t getRunNumber() const   {
-	return data->run_number;
+        return data->run_number;
       }
       /// Access the time stamp
       std::uint64_t getTimeStamp() const   {
-	return data->time_stamp;
+        return data->time_stamp;
       }
       /// Access the event weight
       float getWeight() const   {
-	return data->event_weight;
+        return data->event_weight;
       }
       /// Set the event number
       void setEventNumber(std::int32_t value)   {
-	data->event_number = value;
+        data->event_number = value;
       }
       /// Set the run number
       void setRunNumber(std::int32_t value)   {
-	data->run_number = value;
+        data->run_number = value;
       }
       /// Set the time stamp
       void setTimeStamp(std::uint64_t value)   {
-	data->time_stamp = value;
+        data->time_stamp = value;
       }
       /// Set the event weight
       void setWeight(float value)   {
-	data->event_weight = value;
+        data->event_weight = value;
       }
     };
 
@@ -1053,24 +1054,24 @@ namespace dd4hep {
     template<typename DATA> inline DATA& DataSegment::get(Key key)     {
       if ( DATA* ptr = std::any_cast<DATA>(this->get_item(key, true)) )
         return *ptr;
-      throw std::runtime_error(this->invalid_cast(key, typeid(DATA)));
+      throw std::runtime_error(this->invalid_cast(std::move(key), typeid(DATA)));
     }
     /// Access data as reference by key. If not existing, an exception is thrown
     template<typename DATA> inline const DATA& DataSegment::get(Key key)  const   {
       if ( const DATA* ptr = std::any_cast<DATA>(this->get_item(key, true)) )
         return *ptr;
-      throw std::runtime_error(this->invalid_cast(key, typeid(DATA)));
+      throw std::runtime_error(this->invalid_cast(std::move(key), typeid(DATA)));
     }
 
     /// Access data as pointers by key. If not existing, nullptr is returned
     template<typename DATA> inline DATA* DataSegment::pointer(Key key)     {
-      if ( DATA* ptr = std::any_cast<DATA>(this->get_item(key, false)) )
+      if ( DATA* ptr = std::any_cast<DATA>(this->get_item(std::move(key), false)) )
         return ptr;
       return nullptr;
     }
     /// Access data as pointers by key. If not existing, nullptr is returned
     template<typename DATA> inline const DATA* DataSegment::pointer(Key key)  const   {
-      if ( const DATA* ptr = std::any_cast<DATA>(this->get_item(key, false)) )
+      if ( const DATA* ptr = std::any_cast<DATA>(this->get_item(std::move(key), false)) )
         return ptr;
       return nullptr;
     }
@@ -1080,14 +1081,14 @@ namespace dd4hep {
       key.set_segment(this->id);
       value.key.set_segment(this->id);
       std::any item = std::make_any<DATA>(std::move(value));
-      return this->emplace_any(key, std::move(item));
+      return this->emplace_any(std::move(key), std::move(item));
     }
 
     /// Helper to place data to data segment
     template <typename KEY, typename DATA> 
     bool put_data(DataSegment& segment, KEY key, DATA&& value)    {
       std::any item = std::make_any<DATA>(std::move(value));
-      return segment.emplace_any(key, std::move(item));
+      return segment.emplace_any(std::move(key), std::move(item));
     }
 
     ///  User event data for DDDigi
diff --git a/DDDigi/io/DigiIO.cpp b/DDDigi/io/DigiIO.cpp
index 56bd3a0e4..1d8ccf374 100644
--- a/DDDigi/io/DigiIO.cpp
+++ b/DDDigi/io/DigiIO.cpp
@@ -498,18 +498,16 @@ namespace dd4hep {
       Key history_key;
       EnergyDeposit dep { };
       const auto* h = depo.second.get();
-      Position pos = h->position;
-      pos *= 1./dd4hep::mm;
 
       dep.flag = h->flag;
       dep.deposit = h->energyDeposit;
-      dep.position = pos;
+      dep.position = (h->position / dd4hep::mm);
 
       history_key.set_mask(key.mask());
       history_key.set_item(out.size());
       history_key.set_segment(key.segment());
       dep.history.hits.emplace_back(history_key, dep.deposit);
-      add_particle_history(h, history_key, dep.history);
+      add_particle_history(h, std::move(history_key), dep.history);
       out.emplace(depo.first, std::move(dep));
     }
 
diff --git a/DDDigi/src/DigiContainerProcessor.cpp b/DDDigi/src/DigiContainerProcessor.cpp
index d41894678..dd8ba5e22 100644
--- a/DDDigi/src/DigiContainerProcessor.cpp
+++ b/DDDigi/src/DigiContainerProcessor.cpp
@@ -32,30 +32,30 @@ namespace dd4hep {
 
     template <typename T> T* DigiContainerProcessor::work_t::get_input(bool exc)   {
       if ( input.data->has_value() )  {
-	T* object = std::any_cast<T>(input.data);
-	if ( object )   {
-	  return object;
-	}
+        T* object = std::any_cast<T>(input.data);
+        if ( object )   {
+          return object;
+        }
       }
       if ( exc )   {
-	dd4hep::except("DigiContainerProcessor",
-		       "+++ Cannot access input %s. Invalid data handle of type: %s",
-		       Key::key_name(input.key).c_str(), input_type_name().c_str());
+        dd4hep::except("DigiContainerProcessor",
+                       "+++ Cannot access input %s. Invalid data handle of type: %s",
+                       Key::key_name(input.key).c_str(), input_type_name().c_str());
       }
       return nullptr;
     }
 
     template <typename T> const T* DigiContainerProcessor::work_t::get_input(bool exc)  const  {
       if ( input.data->has_value() )  {
-	const T* object = std::any_cast<T>(input.data);
-	if ( object )   {
-	  return object;
-	}
+        const T* object = std::any_cast<T>(input.data);
+        if ( object )   {
+          return object;
+        }
       }
       if ( exc )   {
-	dd4hep::except("DigiContainerProcessor",
-		       "+++ Cannot access input %s. Invalid data handle of type: %s",
-		       Key::key_name(input.key).c_str(), input_type_name().c_str());
+        dd4hep::except("DigiContainerProcessor",
+                       "+++ Cannot access input %s. Invalid data handle of type: %s",
+                       Key::key_name(input.key).c_str(), input_type_name().c_str());
       }
       return nullptr;
     }
@@ -116,8 +116,8 @@ void DigiContainerProcessor::adopt_monitor(DigiDepositMonitor* monitor)    {
 
 /// Main functional callback if specific work is known
 void DigiContainerProcessor::execute(context_t&         /* context   */,
-				     work_t&            /* work      */,
-				     const predicate_t& /* predicate */)  const   {
+                                     work_t&            /* work      */,
+                                     const predicate_t& /* predicate */)  const   {
 }
 
 /// Main functional callback adapter
@@ -165,9 +165,9 @@ void DigiContainerSequence::execute(context_t& context, work_t& work, const pred
 
 /// Worker adaptor for caller DigiContainerSequence
 template <> void DigiParallelWorker<DigiContainerProcessor,
-				    DigiContainerSequence::work_t,
-				    std::size_t,
-				    DigiContainerSequence&>::execute(void* data) const  {
+                                    DigiContainerSequence::work_t,
+                                    std::size_t,
+                                    DigiContainerSequence&>::execute(void* data) const  {
   calldata_t* arg  = reinterpret_cast<calldata_t*>(data);
   action->execute(arg->environ.context, *arg, predicate.m_worker_predicate);
 }
@@ -212,18 +212,18 @@ void DigiContainerSequenceAction::set_predicate(const predicate_t& predicate)
 
 /// Adopt new parallel worker
 void DigiContainerSequenceAction::adopt_processor(DigiContainerProcessor* action,
-						  const std::string& container)
+                                                  const std::string& container)
 {
   Key key(container.c_str(), 0x0);
   auto it = m_registered_processors.find(key);
   if ( it != m_registered_processors.end() )   {
     if ( action != it->second )   {
       except("+++ The action %s was already registered to mask:%04X container:%s!",
-	     action->c_name(), m_input_mask, container.c_str());
+             action->c_name(), m_input_mask, container.c_str());
     }
     else   {
       warning("+++ The action %s was already registered to mask:%04X container:%s!",
-	      action->c_name(), m_input_mask, container.c_str());
+              action->c_name(), m_input_mask, container.c_str());
     }
     return;
   }
@@ -235,7 +235,7 @@ void DigiContainerSequenceAction::adopt_processor(DigiContainerProcessor* action
 
 /// Adopt new parallel worker acting on multiple containers
 void DigiContainerSequenceAction::adopt_processor(DigiContainerProcessor* action,
-						  const std::vector<std::string>& containers)
+                                                  const std::vector<std::string>& containers)
 {
   info("+++ Adding bulk processor: %s for %ld container", action->c_name(), containers.size());
   for( const auto& cont : containers )   {
@@ -276,8 +276,8 @@ void DigiContainerSequenceAction::execute(context_t& context)  const   {
     Key key(i.first);
     if ( key.mask() == m_input_mask )   {
       if ( worker_t* w = need_registered_worker(key, false) )  {
-	event_workers.emplace_back(w);
-	arg.input_items[w->options] = { &input, key, &i.second };
+        event_workers.emplace_back(w);
+        arg.input_items[w->options] = { &input, std::move(key), &i.second };
       }
     }
   }
@@ -288,9 +288,9 @@ void DigiContainerSequenceAction::execute(context_t& context)  const   {
 
 /// Worker adaptor for caller DigiContainerSequenceAction
 template <> void DigiParallelWorker<DigiContainerProcessor,
-				    DigiContainerSequenceAction::work_t,
-				    std::size_t,
-				    DigiContainerSequenceAction&>::execute(void* data) const  {
+                                    DigiContainerSequenceAction::work_t,
+                                    std::size_t,
+                                    DigiContainerSequenceAction&>::execute(void* data) const  {
   auto* args = reinterpret_cast<calldata_t*>(data);
   auto& item = args->input_items[this->options];
   DigiContainerProcessor::work_t work { args->environ, item };
@@ -402,7 +402,7 @@ void DigiMultiContainerProcessor::execute(context_t& context)  const  {
     if ( use )   {
       use = m_work_items.empty() || m_work_items.find(key) != m_work_items.end();
       if ( use )   {
-	items.push_back({ &input, i.first, &i.second});
+        items.push_back({ &input, i.first, &i.second});
       }
     }
   }
@@ -417,9 +417,9 @@ void DigiMultiContainerProcessor::execute(context_t& context)  const  {
 
 /// Worker adaptor for caller DigiMultiContainerProcessor
 template <> void DigiParallelWorker<DigiContainerProcessor,
-				    DigiMultiContainerProcessor::work_t,
-				    std::size_t,
-				    DigiMultiContainerProcessor&>::execute(void* data) const  {
+                                    DigiMultiContainerProcessor::work_t,
+                                    std::size_t,
+                                    DigiMultiContainerProcessor&>::execute(void* data) const  {
   calldata_t* arg   = reinterpret_cast<calldata_t*>(data);
   const auto& par   = arg->parent;
   const auto& keys  = par.worker_keys(this->options);
@@ -431,21 +431,21 @@ template <> void DigiParallelWorker<DigiContainerProcessor,
     if ( masks.empty() || std::find(masks.begin(), masks.end(), key.mask()) != masks.end() )  {
       tag = "mask accepted";
       if ( keys.empty() )  {
-	DigiContainerProcessor::work_t  work { arg->environ, item };
-	action->execute(work.environ.context, work, predicate.m_worker_predicate);
-	continue;
+        DigiContainerProcessor::work_t  work { arg->environ, item };
+        action->execute(work.environ.context, work, predicate.m_worker_predicate);
+        continue;
       }
       else if ( std::find(keys.begin(), keys.end(), key) != keys.end() )    {
-	DigiContainerProcessor::work_t work { arg->environ, item };
-	action->execute(work.environ.context, work, predicate.m_worker_predicate);
-	continue;
+        DigiContainerProcessor::work_t work { arg->environ, item };
+        action->execute(work.environ.context, work, predicate.m_worker_predicate);
+        continue;
       }
       tag = "no keys matching";
     }
     if ( tag )  {}
 #if 0
     par.info("%s+++ Ignore container: %016lX  --> %04X %08X %s [%s]",
-	     arg->context.event->id(), key.value(), key.mask(), key.item(), Key::key_name(key).c_str(), tag);
+             arg->context.event->id(), key.value(), key.mask(), key.item(), Key::key_name(key).c_str(), tag);
 #endif
   }
 }
diff --git a/DDDigi/src/DigiData.cpp b/DDDigi/src/DigiData.cpp
index 20f3afab6..3f971ac94 100644
--- a/DDDigi/src/DigiData.cpp
+++ b/DDDigi/src/DigiData.cpp
@@ -494,7 +494,7 @@ std::any* DataSegment::get_item(Key key, bool exc)   {
   it = this->data.find(key);
   if (it != this->data.end()) return &it->second;
 
-  if ( exc ) throw std::runtime_error(invalid_request(key));
+  if ( exc ) throw std::runtime_error(invalid_request(std::move(key)));
   return nullptr;
 }
 
diff --git a/DDDigi/src/DigiKernel.cpp b/DDDigi/src/DigiKernel.cpp
index 92ea50c06..bab1ed049 100644
--- a/DDDigi/src/DigiKernel.cpp
+++ b/DDDigi/src/DigiKernel.cpp
@@ -382,7 +382,7 @@ void DigiKernel::submit (DigiContext& context, ParallelCall*const algorithms[],
       std::exception_ptr eptr = std::current_exception();
       internals->stop = true;
       error("%s+++ C++ exception. STOP event loop. [%s]", tag, e.what());
-      std::rethrow_exception(eptr);
+      std::rethrow_exception(std::move(eptr));
     }
     return;
   }
diff --git a/DDDigi/src/DigiStoreDump.cpp b/DDDigi/src/DigiStoreDump.cpp
index 5f7893e1a..aaca0e0cb 100644
--- a/DDDigi/src/DigiStoreDump.cpp
+++ b/DDDigi/src/DigiStoreDump.cpp
@@ -54,23 +54,23 @@ void DigiStoreDump::initialize()   {
 
 template <typename T> std::string DigiStoreDump::data_header(Key key, const std::string& tag, const T& container)  const  {
   return this->format("%04X %04X %08X %-32s: %6ld %-12s [%s]", 
-		      key.segment(), key.mask(), key.item(),
-		      ('"'+Key::key_name(key)+'"').c_str(), container.size(), tag.c_str(),
-		      digiTypeName(typeid(T)).c_str());
+                      key.segment(), key.mask(), key.item(),
+                      ('"'+Key::key_name(key)+'"').c_str(), container.size(), tag.c_str(),
+                      digiTypeName(typeid(T)).c_str());
 }
 
 template <> std::string DigiStoreDump::data_header(Key key, const std::string& tag, const std::type_info& info)  const  {
   std::string typ = digiTypeName(info);
   if ( tag.empty() )   {
     return this->format("%04X %04X %08X %-32s: %6s %s",
-			key.segment(), key.mask(), key.item(),
-			('"'+Key::key_name(key)+'"').c_str(), "",
-			typ.c_str());
+                        key.segment(), key.mask(), key.item(),
+                        ('"'+Key::key_name(key)+'"').c_str(), "",
+                        typ.c_str());
   }
   return this->format("%04X %04X %08X %-32s: %-12s %s",
-		      key.segment(), key.mask(), key.item(),
-		      ('"'+Key::key_name(key)+'"').c_str(), tag.c_str(),
-		      typ.c_str());
+                      key.segment(), key.mask(), key.item(),
+                      ('"'+Key::key_name(key)+'"').c_str(), tag.c_str(),
+                      typ.c_str());
 }
 
 template <> std::string DigiStoreDump::data_header(Key key, const std::string& tag, const std::any& data)  const  {
@@ -95,11 +95,11 @@ DigiStoreDump::dump_history(DigiContext& context,
   str << Key::key_name(key) << "[" << seq_no << "]:";
   std::string line =
     format("|----  %-18s Segment:%04X Mask:%04X Item:%04X %016lX",
-	   str.str().c_str(), particle_key.segment(), particle_key.mask(), particle_key.item(),
-	   long(&data.second));
+           str.str().c_str(), particle_key.segment(), particle_key.mask(), particle_key.item(),
+           long(&data.second));
   records.emplace_back(line);
   line = format("|        PDG:%6d Charge:%-2d Mass:%7.2f v:%7.5g %7.5g %7.5g  p:%12g %12g %12g      %016lX",
-		par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z(), long(&par));
+                par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z(), long(&par));
   records.emplace_back(line);
   return records;
 }
@@ -131,10 +131,10 @@ DigiStoreDump::dump_history(DigiContext& context,
     str.str("");
     str << "|        Hit-history[" << i << "]:";
     line = format("%-30s Segment:%04X Mask:%04X Cell:%08X  Weight:%.8g",
-		  str.str().c_str(), k.segment(), k.mask(), k.item(), entry.weight);
+                  str.str().c_str(), k.segment(), k.mask(), k.item(), entry.weight);
     records.emplace_back(line);
     line = format("|              pos: %7.3f %7.3f %7.3f   p: %7.3f %7.3f %7.3f deposit: %7.3f",
-		  pos.X(), pos.Y(), pos.Z(), mom.X(), mom.Y(), mom.Z(), dep.deposit);
+                  pos.X(), pos.Y(), pos.Z(), mom.X(), mom.Y(), mom.Z(), dep.deposit);
     records.emplace_back(line);
   }
   for( std::size_t i=0; i<item.history.particles.size(); ++i )   {
@@ -146,10 +146,10 @@ DigiStoreDump::dump_history(DigiContext& context,
     str.str("");
     str << "|        Part-history[" << i << "]:";
     line = format("%-30s Segment:%04X Mask:%04X Key: %08X  %.8g",
-		  str.str().c_str(), key.segment(), key.mask(), key.item(), ent.weight);
+                  str.str().c_str(), key.segment(), key.mask(), key.item(), ent.weight);
     records.emplace_back(line);
     line = format("|              PDG:%6d Charge:%-2d Mass:%7.3f v:%7.3f %7.3f %7.3f   p:%7.3f %7.3f %7.3f",
-		  par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z());
+                  par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z());
     records.emplace_back(line);
   }
   return records;
@@ -157,9 +157,9 @@ DigiStoreDump::dump_history(DigiContext& context,
 
 template <> std::vector<std::string> 
 DigiStoreDump::dump_history(DigiContext& context,
-			    Key container_key,
-			    const std::pair<const CellID, History>& data,
-			    std::size_t seq_no)  const
+                            Key container_key,
+                            const std::pair<const CellID, History>& data,
+                            std::size_t seq_no)  const
 {
   std::string line;
   std::stringstream str;
@@ -170,8 +170,8 @@ DigiStoreDump::dump_history(DigiContext& context,
 
   str << Key::key_name(container_key) << "[" << seq_no << "]:";
   line = format("+----- %-30s Container: Segment:%04X Mask:%04X Item:%08X Cell:%016lX Hist: Hits:%ld Parts:%ld",
-		str.str().c_str(), container_key.segment(), container_key.mask(), container_key.item(),
-		cell, history.hits.size(), history.particles.size());
+                str.str().c_str(), container_key.segment(), container_key.mask(), container_key.item(),
+                cell, history.hits.size(), history.particles.size());
   records.emplace_back(line);
   for( std::size_t i=0; i<history.hits.size(); ++i )   {
     const auto& entry = history.hits[i];
@@ -182,10 +182,10 @@ DigiStoreDump::dump_history(DigiContext& context,
     str.str("");
     str << "|        Hit-history[" << i << "]:";
     line = format("%-30s Segment:%04X Mask:%04X Cell:%08X  Weight:%.8g",
-		  str.str().c_str(), k.segment(), k.mask(), k.item(), entry.weight);
+                  str.str().c_str(), k.segment(), k.mask(), k.item(), entry.weight);
     records.emplace_back(line);
     line = format("|              pos: %7.3f %7.3f %7.3f   p: %7.3f %7.3f %7.3f deposit: %7.3f",
-		  pos.X(), pos.Y(), pos.Z(), mom.X(), mom.Y(), mom.Z(), dep.deposit);
+                  pos.X(), pos.Y(), pos.Z(), mom.X(), mom.Y(), mom.Z(), dep.deposit);
     records.emplace_back(line);
   }
   for( std::size_t i=0; i<history.particles.size(); ++i )   {
@@ -197,10 +197,10 @@ DigiStoreDump::dump_history(DigiContext& context,
     str.str("");
     str << "|        Part-history[" << i << "]:";
     line = format("%-30s Segment:%04X Mask:%04X Key: %08X  %.8g",
-		  str.str().c_str(), key.segment(), key.mask(), key.item(), ent.weight);
+                  str.str().c_str(), key.segment(), key.mask(), key.item(), ent.weight);
     records.emplace_back(line);
     line = format("|              PDG:%6d Charge:%-2d Mass:%7.3f v:%7.3f %7.3f %7.3f   p:%7.3f %7.3f %7.3f",
-		  par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z());
+                  par.pdgID, int(par.charge), par.mass, vtx.X(), vtx.Y(), vtx.Z(), mom.X(), mom.Y(), mom.Z());
     records.emplace_back(line);
   }
   return records;
@@ -250,9 +250,9 @@ DigiStoreDump::dump_particle_history(DigiContext& context, Key container_key, co
 
 /// Dump hit container
 void DigiStoreDump::dump_history(DigiContext& context,
-				 const std::string& tag,
-				 const DigiEvent& event,
-				 const DataSegment& segment)  const
+                                 const std::string& tag,
+                                 const DigiEvent& event,
+                                 const DataSegment& segment)  const
 {
   std::vector<std::string> records;
   std::lock_guard<std::mutex> lock(segment.lock);
@@ -269,22 +269,22 @@ void DigiStoreDump::dump_history(DigiContext& context,
     if ( use )   {
       std::vector<std::string> rec;
       if ( const auto* mapping = std::any_cast<DepositMapping>(&data) )   {
-	rec = dump_deposit_history(context, key, *mapping);
+        rec = dump_deposit_history(context, std::move(key), *mapping);
       }
       else if ( const auto* vector = std::any_cast<DepositVector>(&data) )   {
-	rec = dump_deposit_history(context, key, *vector);
+        rec = dump_deposit_history(context, std::move(key), *vector);
       }
       else if ( const auto* parts = std::any_cast<ParticleMapping>(&data) )   {
-	rec = dump_particle_history(context, key, *parts);
+        rec = dump_particle_history(context, std::move(key), *parts);
       }
       else if ( const auto* adcs = std::any_cast<DetectorResponse>(&data) )   {
-	rec = { format("|----  %s", data_header(key, "ADC values", *adcs).c_str()) };
+        rec = { format("|----  %s", data_header(std::move(key), "ADC values", *adcs).c_str()) };
       }
       else if ( const auto* hist = std::any_cast<DetectorHistory>(&data) )   {
-	rec = { format("|----  %s", data_header(key, "histories", *hist).c_str()) };
+        rec = { format("|----  %s", data_header(std::move(key), "histories", *hist).c_str()) };
       }
       else   {
-	rec = { format("|----  %s", data_header(key, "", data).c_str()) };
+        rec = { format("|----  %s", data_header(std::move(key), "", data).c_str()) };
       }
       records.insert(records.end(), rec.begin(), rec.end());
     }
@@ -296,8 +296,8 @@ void DigiStoreDump::dump_history(DigiContext& context,
 
 /// Dump hit container
 void DigiStoreDump::dump_headers(const std::string& tag,
-				 const DigiEvent&   event,
-				 const DataSegment& segment)  const
+                                 const DigiEvent&   event,
+                                 const DataSegment& segment)  const
 {
   int first = 1;
   std::string str;
@@ -309,19 +309,19 @@ void DigiStoreDump::dump_headers(const std::string& tag,
     Key key {entry.first};
     const std::any& data = entry.second;
     if ( const auto* mapping = std::any_cast<DepositMapping>(&data) )
-      str = "| " + data_header(key, "deposits", *mapping);
+      str = "| " + data_header(std::move(key), "deposits", *mapping);
     else if ( const auto* vector = std::any_cast<DepositVector>(&data) )
-      str = "| " + data_header(key, "deposits", *vector);
+      str = "| " + data_header(std::move(key), "deposits", *vector);
     else if ( const auto* parts = std::any_cast<ParticleMapping>(&data) )
-      str = "| " + data_header(key, "particles", *parts);
+      str = "| " + data_header(std::move(key), "particles", *parts);
     else if ( const auto* adcs = std::any_cast<DetectorResponse>(&data) )
-      str = "| " + data_header(key, "ADC values", *adcs);
+      str = "| " + data_header(std::move(key), "ADC values", *adcs);
     else if ( const auto* hist = std::any_cast<DetectorHistory>(&data) )
-      str = "| " + data_header(key, "histories", *hist);
+      str = "| " + data_header(std::move(key), "histories", *hist);
     else if ( data.type() == typeid(void) )
-      str = "| " + data_header(key, "void data", data);
+      str = "| " + data_header(std::move(key), "void data", data);
     else
-      str = "| " + data_header(key, "", data);
+      str = "| " + data_header(std::move(key), "", data);
     if ( first )   {
       first = false;
     }
diff --git a/DDDigi/src/noise/FalphaNoise.cpp b/DDDigi/src/noise/FalphaNoise.cpp
index 01c564e56..6c4701c17 100644
--- a/DDDigi/src/noise/FalphaNoise.cpp
+++ b/DDDigi/src/noise/FalphaNoise.cpp
@@ -382,12 +382,12 @@ void FalphaNoise::normalize(size_t shots)    {
 /// Internal usage to normalize using user defined random engine
 void FalphaNoise::normalizeVariance(const random_engine_wrapper& generator, size_t shots)  {
   double mean = 0e0, mean2 = 0e0, var;
-  auto tmp = m_multipliers;
-  double val = 1e0;
+  auto tmp    = m_multipliers;
+  double val  = 1e0;
   /// We have to correct for the case of white noise: alpha=0
   for ( size_t i=0; i<m_poles; ++i)   {
     val *= (double(i) - 0.5) / double(i+1);
-    m_multipliers[i] = val;
+    tmp[i] = val;
   }
   for ( size_t i=0; i < shots; i++)  {
     var = (*this)(generator);
@@ -397,7 +397,6 @@ void FalphaNoise::normalizeVariance(const random_engine_wrapper& generator, size
   mean  /= double(shots);
   var = std::sqrt(mean2/double(shots) - mean*mean);
   m_variance *= m_variance/var;
-  m_multipliers = tmp;
   m_distribution = std::normal_distribution<double>(0.0, m_variance);
 }
 
diff --git a/DDEve/include/DDEve/Display.h b/DDEve/include/DDEve/Display.h
index 29b2a350b..2aafe4408 100644
--- a/DDEve/include/DDEve/Display.h
+++ b/DDEve/include/DDEve/Display.h
@@ -128,17 +128,17 @@ namespace dd4hep {
     /// Access to geometry hub
     Detector& detectorDescription() const;
     /// Access to the EVE manager
-    TEveManager& manager() const                         { return *m_eve;             }
+    TEveManager& manager() const                           { return *m_eve;             }
     /// Access View configurations
-    const ViewConfigurations& viewConfigurations() const { return m_viewConfigs;      }
+    const ViewConfigurations& viewConfigurations() const   { return m_viewConfigs;      }
     /// Set Vis level in geo manager (either from XML or BEFORE XML file was loaded)
-    void setVisLevel(int new_level)                      { m_visLevel = new_level;    }
+    void setVisLevel(int new_level)                        { m_visLevel = new_level;    }
     /// Set Eve Geometry load level in manager (either from XML or BEFORE XML file was loaded)
-    void setLoadLevel(int new_level)                     { m_loadLevel = new_level;   }
-    /// Set Event Handler Plugin name
-    void setEventHandlerName(std::string eventHandlerName) {m_eventHandlerName = eventHandlerName;}
+    void setLoadLevel(int new_level)                       { m_loadLevel = new_level;   }
     /// Get Event Handler Plugin name
-    std::string getEventHandlerName() {return m_eventHandlerName;}
+    std::string getEventHandlerName()                      { return m_eventHandlerName; }
+    /// Set Event Handler Plugin name
+    void setEventHandlerName(const std::string& nam)       { m_eventHandlerName = nam;  }
 
     /// Access to X-client
     TGClient& client() const;
diff --git a/DDEve/src/Display.cpp b/DDEve/src/Display.cpp
index 25b266366..587032b38 100644
--- a/DDEve/src/Display.cpp
+++ b/DDEve/src/Display.cpp
@@ -231,14 +231,14 @@ Display::CalodataContext& Display::GetCaloHistogram(const std::string& nam)   {
       else   {
         CalodataContext c = GetCaloHistogram(use);
         ctx = c;
-        ctx.config.use = use;
-        ctx.config.hits = hits;
+        ctx.config.use  = std::move(use);
+        ctx.config.hits = std::move(hits);
         ctx.config.name = nam;
       }
-      i = m_calodata.emplace(nam,ctx).first;
+      i = m_calodata.emplace(nam, ctx).first;
       return (*i).second;      
     }
-    throw std::runtime_error("Cannot access calodata configuration "+nam);
+    throw std::runtime_error("Cannot access calodata configuration " + nam);
   }
   return (*i).second;
 }
diff --git a/DDG4/hepmc/HepMC3EventReader.cpp b/DDG4/hepmc/HepMC3EventReader.cpp
index 38508786b..61385d21a 100644
--- a/DDG4/hepmc/HepMC3EventReader.cpp
+++ b/DDG4/hepmc/HepMC3EventReader.cpp
@@ -67,7 +67,7 @@ HEPMC3EventReader::readParticles(int event_number, Vertices& vertices, Particles
   for(int i=0; i<NHEP; ++i ) {
     auto p = genEvent.particles().at(i);
     mcparts[p] = i;
-    mcpcoll[i] = p;
+    mcpcoll[i] = std::move(p);
   }
 
   //treat event attributes, flow[12]
diff --git a/DDG4/hepmc/HepMC3FileReader.cpp b/DDG4/hepmc/HepMC3FileReader.cpp
index 15c93cce2..63cda707b 100644
--- a/DDG4/hepmc/HepMC3FileReader.cpp
+++ b/DDG4/hepmc/HepMC3FileReader.cpp
@@ -139,7 +139,7 @@ HEPMC3FileReader::HEPMC3FileReader(const std::string& nam)
   // so we can open the file again from the start
   m_reader = HepMC3::deduce_reader(nam);
   // and set the run info object now
-  m_reader->set_run_info(runInfo);
+  m_reader->set_run_info(std::move(runInfo));
 #endif
   m_directAccess = false;
 }
diff --git a/DDG4/include/DDG4/Geant4InputAction.h b/DDG4/include/DDG4/Geant4InputAction.h
index 5b7202882..cc7571140 100644
--- a/DDG4/include/DDG4/Geant4InputAction.h
+++ b/DDG4/include/DDG4/Geant4InputAction.h
@@ -97,7 +97,7 @@ namespace dd4hep  {
           dd4hep::Parsers::parse( parameter, parameters.at( parameterName ) );
           parameters.erase( parameterName );
         } else {
-          parameter = defaultValue;
+          parameter = std::move(defaultValue);
         }
       }
 
diff --git a/DDG4/lcio/LCIOFileReader.cpp b/DDG4/lcio/LCIOFileReader.cpp
index 311395063..417c87954 100644
--- a/DDG4/lcio/LCIOFileReader.cpp
+++ b/DDG4/lcio/LCIOFileReader.cpp
@@ -44,23 +44,26 @@ namespace dd4hep  {
 
     /// get the parameters from the input LCIO Event and store them in the EventParameters extension
     template <class T=EVENT::LCParameters> void EventParameters::ingestParameters(T const& source) {
-      EVENT::StringVec intKeys; source.getIntKeys(intKeys);
-      EVENT::StringVec floatKeys; source.getFloatKeys(floatKeys);
-      EVENT::StringVec stringKeys; source.getStringKeys(stringKeys);
+      EVENT::StringVec intKeys;
+      EVENT::StringVec floatKeys;
+      EVENT::StringVec stringKeys;
+      source.getIntKeys(intKeys);
+      source.getFloatKeys(floatKeys);
+      source.getStringKeys(stringKeys);
       for(auto const& key: intKeys) {
         EVENT::IntVec intVec;
         source.getIntVals(key,intVec);
-        m_intValues[key] = intVec;
+        m_intValues[key] = std::move(intVec);
       }
       for(auto const& key: floatKeys) {
         EVENT::FloatVec floatVec;
         source.getFloatVals(key,floatVec);
-        m_fltValues[key] = floatVec;
+        m_fltValues[key] = std::move(floatVec);
       }
       for(auto const& key: stringKeys) {
         EVENT::StringVec stringVec;
         source.getStringVals(key,stringVec);
-        m_strValues[key] = stringVec;
+        m_strValues[key] = std::move(stringVec);
       }
     }
 
diff --git a/DDG4/plugins/Geant4EscapeCounter.cpp b/DDG4/plugins/Geant4EscapeCounter.cpp
index 283c5c7a0..c8bde03b9 100644
--- a/DDG4/plugins/Geant4EscapeCounter.cpp
+++ b/DDG4/plugins/Geant4EscapeCounter.cpp
@@ -37,6 +37,7 @@ namespace dd4hep {
       size_t m_collectionID;
       /// Detector name set
       std::vector<std::string> m_detectorNames;
+
     public:
       /// Standard constructor
       Geant4EscapeCounter(Geant4Context* ctxt, const std::string& name, DetElement det, Detector& description);
@@ -101,7 +102,6 @@ bool Geant4EscapeCounter::process(const G4Step* step, G4TouchableHistory* /* his
   Geant4TouchableHandler handler(step);
   std::string hdlr_path  = handler.path();
   Position prePos     = h.prePos();
-  Position postPos    = h.postPos();
   Geant4HitCollection* coll = collection(m_collectionID);
   SimpleTracker::Hit*  hit = new SimpleTracker::Hit();
   hit->g4ID          = th.id();
@@ -110,7 +110,7 @@ bool Geant4EscapeCounter::process(const G4Step* step, G4TouchableHistory* /* his
   hit->energyDeposit = th.energy();
   hit->position      = prePos;
   hit->momentum      = h.trkMom();
-  hit->length        = (postPos-prePos).R();
+  hit->length        = (h.postPos()-prePos).R();
   hit->truth.trackID = th.id();
   hit->truth.deposit = h.deposit();
   hit->truth.pdgID   = th.pdgID();
diff --git a/DDG4/plugins/Geant4EventReaderHepMC.cpp b/DDG4/plugins/Geant4EventReaderHepMC.cpp
index 9cedb5e5b..3f652ec0a 100644
--- a/DDG4/plugins/Geant4EventReaderHepMC.cpp
+++ b/DDG4/plugins/Geant4EventReaderHepMC.cpp
@@ -513,9 +513,10 @@ int HepMC::read_vertex(EventStream &info, std::istream& is, std::istringstream &
   v->x *= info.pos_unit;
   v->y *= info.pos_unit;
   v->z *= info.pos_unit;
-  weights.resize(weights_size);
   for (int i1 = 0; i1 < weights_size; ++i1) {
-    input >> weights[i1];
+    float value = 0e0;
+    input >> value;
+    weights.emplace_back(value);
     if( !input ) {
       delete v;
       return 0;
@@ -591,21 +592,28 @@ int HepMC::read_event_header(EventStream &info, std::istringstream & input, Even
   input.clear();
   if( input.fail() ) return 0;
 
-  header.random.resize(random_states_size);
-  for(int i = 0; i < random_states_size; ++i )
-    input >> header.random[i];
+  
+  for(int i = 0; i < random_states_size; ++i )  {
+    long val = 0e0;
+    input >> val;
+    header.random.emplace_back(val);
+    if( input.fail() ) return 0;
+  }
 
   size_t weights_size = 0;
   input >> weights_size;
   if( input.fail() ) return 0;
 
-  std::vector<float> wgt(weights_size);
-  for(size_t ii = 0; ii < weights_size; ++ii )
-    input >> wgt[ii];
-  if( input.fail() ) return 0;
+  std::vector<float> wgt;
+  for(size_t ii = 0; ii < weights_size; ++ii )  {
+    float val = 0e0;
+    input >> val;
+    wgt.emplace_back(val);
+    if( input.fail() ) return 0;
+  }
 
   // weight names will be added later if they exist
-  if( weights_size > 0 ) header.weights = wgt;
+  if( weights_size > 0 ) header.weights = std::move(wgt);
   return 1;
 }
 
diff --git a/DDG4/plugins/Geant4ROOTDump.cpp b/DDG4/plugins/Geant4ROOTDump.cpp
index eb12b5fb5..d6ca49050 100644
--- a/DDG4/plugins/Geant4ROOTDump.cpp
+++ b/DDG4/plugins/Geant4ROOTDump.cpp
@@ -118,7 +118,7 @@ static long dump_root(dd4hep::Detector&, int argc, char** argv) {
       for (Int_t i=0;i<nbranches;i++)  {
         TBranch* branch = (TBranch*)branches->UncheckedAt(i);
         std::pair<TClass*,void*> data = load(branch,ievt);
-        if ( data.first ) event[branch->GetName()] = data;
+        if ( data.first ) event[branch->GetName()] = std::move(data);
       }
       // Now dump the stuff
       for(ENTRIES::const_iterator i=event.begin(); i!=event.end(); ++i)  {
diff --git a/DDG4/src/Geant4AssemblyVolume.cpp b/DDG4/src/Geant4AssemblyVolume.cpp
index 342fdb761..331c6aeb0 100644
--- a/DDG4/src/Geant4AssemblyVolume.cpp
+++ b/DDG4/src/Geant4AssemblyVolume.cpp
@@ -159,7 +159,7 @@ void Geant4AssemblyVolume::imprint(const Geant4Converter& cnv,
     }
     else if ( triplet.GetAssembly() )  {
       // Place volumes in this assembly with composed transformation
-      imprint(cnv, parent, new_chain, avol, pMotherLV, Tfinal, i*100+copyNumBase, surfCheck );
+      imprint(cnv, parent, std::move(new_chain), avol, pMotherLV, Tfinal, i*100+copyNumBase, surfCheck );
     }
     else   {
       G4Exception("Geant4AssemblyVolume::imprint(..)", "GeomVol0003", FatalException,
diff --git a/DDG4/src/Geant4Converter.cpp b/DDG4/src/Geant4Converter.cpp
index 183858365..f62e8c25f 100644
--- a/DDG4/src/Geant4Converter.cpp
+++ b/DDG4/src/Geant4Converter.cpp
@@ -120,7 +120,7 @@ namespace {
   template <typename O, typename C, typename F> void handleRMap(const O* o, const C& c, F pmf) {
     for (typename C::const_reverse_iterator i = c.rbegin(); i != c.rend(); ++i)  {
       //cout << "Handle RMAP [ " << (*i).first << " ]" << std::endl;
-      handle(o, (*i).second, pmf);
+      handle(o, i->second, pmf);
     }
   }
   template <typename O, typename C, typename F> void handleRMap_(const O* o, const C& c, F pmf) {
@@ -1659,12 +1659,16 @@ void* Geant4Converter::printPlacement(const std::string& name, const TGeoNode* n
 
 /// Create geometry conversion
 Geant4Converter& Geant4Converter::create(DetElement top) {
+  typedef std::map<const TGeoNode*, std::vector<TGeoNode*> > _DAU;
+  _DAU daughters;
   Geant4GeometryInfo& geo = this->init();
   World wrld = top.world();
+
   m_data->clear();
+  m_daughters = &daughters;
   geo.manager = &wrld.detectorDescription().manager();
-  collect(top, geo);
-  checkOverlaps = false;
+  this->collect(top, geo);
+  this->checkOverlaps = false;
   // We do not have to handle defines etc.
   // All positions and the like are not really named.
   // Hence, start creating the G4 objects for materials, solids and log volumes.
@@ -1684,7 +1688,57 @@ Geant4Converter& Geant4Converter::create(DetElement top) {
   printout(outputLevel, "Geant4Converter", "++ Handled %ld volumes.", geo.volumes.size());
   handleRMap(this, *m_data,     &Geant4Converter::handleAssembly);
   // Now place all this stuff appropriately
-  handleRMap(this, *m_data,     &Geant4Converter::handlePlacement);
+  //handleRMap(this, *m_data,     &Geant4Converter::handlePlacement);
+  std::map<int, std::set<const TGeoNode*> >::const_reverse_iterator i = m_data->rbegin();
+  for ( ; i != m_data->rend(); ++i )  {
+    for ( const TGeoNode* node : i->second )  {
+#if 0
+      TGeoVolume* vm = node->GetMotherVolume();
+      if ( vm )   {
+        for(int iv=0; iv < vm->GetNdaughters(); ++iv)  {
+          TGeoNode* n = vm->GetNode(iv);
+          this->handlePlacement(n->GetName(), n);
+        }
+      }
+#endif
+      this->handlePlacement(node->GetName(), node);
+#if 0
+#if 0
+      auto idau = m_daughters->find(Volume(node->GetVolume()));
+      std::vector<std::pair<TGeoNode*, G4VPhysicalVolume*> > vol_daughters;
+      if ( idau != m_daughters->end() )  {
+        for( auto* d : idau->second )  {
+          void* dau = handlePlacement(d->GetName(), d);
+          vol_daughters.push_back({ d, (G4VPhysicalVolume*)dau });
+        }
+      }
+      G4VPhysicalVolume* pl = (G4VPhysicalVolume*)handlePlacement(node->GetName(), node);
+      if ( pl )  {
+        // Now run check:
+        G4LogicalVolume* lv = pl->GetLogicalVolume();
+        for(int ik=0; ik<node->GetNdaughters(); ++ik)   {
+          const auto& p = vol_daughters[ik];
+          printout(INFO, "Geant4Converter", "+++ %i TGEO Parent: %s daughter: %s",
+                   ik, node->GetName(), node->GetDaughter(ik)->GetName());
+          printout(INFO, "Geant4Converter", "+++ %i G4   Parent: %s daughter: %s",
+                   ik, pl->GetName().c_str(),   lv->GetDaughter(ik)->GetName().c_str());
+          if ( p.first != node->GetDaughter(ik) || p.second != lv->GetDaughter(ik) )  {
+            printout(INFO, "Geant4Converter", "+++  BAD Volume order: %s", p.first->GetName());          
+          }
+        }
+      }
+#else
+      auto id = m_daughters->find(node);
+      if ( id != m_daughters->end() )  {
+        for( auto* dau : id->second )  {
+          handlePlacement(dau->GetName(), dau);
+        }
+      }
+      handlePlacement(node->GetName(), node);
+#endif
+#endif
+    }
+  }
   /// Handle concrete surfaces
   handleArray(this, geo.manager->GetListOfSkinSurfaces(),   &Geant4Converter::handleSkinSurface);
   handleArray(this, geo.manager->GetListOfBorderSurfaces(), &Geant4Converter::handleBorderSurface);
@@ -1697,6 +1751,7 @@ Geant4Converter& Geant4Converter::create(DetElement top) {
     handleRMap(this, *m_data, &Geant4Converter::printPlacement);
   }
 
+  m_daughters = nullptr;
   geo.setWorld(top.placement().ptr());
   geo.valid = true;
   printout(INFO, "Geant4Converter", "+++  Successfully converted geometry to Geant4.");
diff --git a/DDG4/src/Geant4Helpers.cpp b/DDG4/src/Geant4Helpers.cpp
index 5e5f3fcd0..806c6b557 100644
--- a/DDG4/src/Geant4Helpers.cpp
+++ b/DDG4/src/Geant4Helpers.cpp
@@ -39,7 +39,7 @@ namespace  {
     MyTransform3D(const double* t)
       : G4Transform3D(1.0, 0.0, 0.0, t[0]*CM_2_MM, 0.0, 1.0, 0.0, t[1]*CM_2_MM, 0.0, 0.0, 1.0, t[2]*CM_2_MM)  {
     }
-    MyTransform3D(Transform3D&& copy) : Transform3D(copy) {}
+    MyTransform3D(Transform3D&& copy) : Transform3D(std::move(copy)) {}
   };
   /// Overload to access protected constructor
   class MyG4RotationMatrix : public G4RotationMatrix   {
diff --git a/DDG4/src/Geant4SensDetAction.cpp b/DDG4/src/Geant4SensDetAction.cpp
index cb6e8ec1c..67b954b3e 100644
--- a/DDG4/src/Geant4SensDetAction.cpp
+++ b/DDG4/src/Geant4SensDetAction.cpp
@@ -311,7 +311,7 @@ long long int Geant4Sensitive::cellID(const G4VTouchable* touchable, const G4Thr
       error("....... TGeo-local: (%f, %f, %f) TGeo-global: (%f, %f, %f)",
 	    loc.x(), loc.y(), loc.z(), glob.x(), glob.y(), glob.z());
       error("....... Touchable:  %s  SD: %s", vol->GetName().c_str(), sd ? sd->GetName().c_str() : "???");
-      std::rethrow_exception(eptr);
+      std::rethrow_exception(std::move(eptr));
     }
   }
   return volID;
diff --git a/DDG4/src/Geant4ShapeConverter.cpp b/DDG4/src/Geant4ShapeConverter.cpp
index 0023c3d7d..b4945786a 100644
--- a/DDG4/src/Geant4ShapeConverter.cpp
+++ b/DDG4/src/Geant4ShapeConverter.cpp
@@ -96,7 +96,8 @@ namespace dd4hep {
       G4ThreeVector   highNorm(hn[0], hn[1], hn[2]);
       return new G4CutTubs(sh->GetName(),
                            sh->GetRmin() * CM_2_MM, sh->GetRmax() * CM_2_MM, sh->GetDz() * CM_2_MM,
-                           sh->GetPhi1() * DEGREE_2_RAD, (sh->GetPhi2()-sh->GetPhi1()) * DEGREE_2_RAD, lowNorm, highNorm);
+                           sh->GetPhi1() * DEGREE_2_RAD, (sh->GetPhi2()-sh->GetPhi1()) * DEGREE_2_RAD,
+                           std::move(lowNorm), std::move(highNorm));
     }
 
     template <> G4VSolid* convertShape<TGeoEltu>(const TGeoShape* shape)  {
diff --git a/DDG4/src/Geant4VolumeManager.cpp b/DDG4/src/Geant4VolumeManager.cpp
index 34a402e81..a2e1d2cb1 100644
--- a/DDG4/src/Geant4VolumeManager.cpp
+++ b/DDG4/src/Geant4VolumeManager.cpp
@@ -64,10 +64,11 @@ namespace {
           PlacedVolume::VolIDs ids;
           m_entries.clear();
           chain.emplace_back(m_detDesc.world().placement().ptr());
-          scanPhysicalVolume(pv.ptr(), ids, sd, chain);
+          scanPhysicalVolume(pv.ptr(), std::move(ids), sd, chain);
           continue;
         }
-        printout(WARNING, "Geant4VolumeManager", "++ Detector element %s of type %s has no placement.", de.name(), de.type().c_str());
+        printout(WARNING, "Geant4VolumeManager",
+                 "++ Detector element %s of type %s has no placement.", de.name(), de.type().c_str());
       }
       /// Needed to compute the cellID of parameterized volumes
       for( const auto& pv : m_geo.g4Placements )   {
diff --git a/DDParsers/src/Evaluator/Evaluator.cpp b/DDParsers/src/Evaluator/Evaluator.cpp
index 070b2fe0c..979ceff4a 100644
--- a/DDParsers/src/Evaluator/Evaluator.cpp
+++ b/DDParsers/src/Evaluator/Evaluator.cpp
@@ -54,7 +54,7 @@ namespace  {
 
     explicit Item()              : what(UNKNOWN),   variable(0),expression(), function(0) {}
     explicit Item(double x)      : what(VARIABLE),  variable(x),expression(), function(0) {}
-    explicit Item(std::string x) : what(EXPRESSION),variable(0),expression(x),function(0) {}
+    explicit Item(std::string x) : what(EXPRESSION),variable(0),expression(std::move(x)),function(0) {}
     explicit Item(void  *x)      : what(FUNCTION),  variable(0),expression(), function(x) {}
   };
 
@@ -757,14 +757,14 @@ int Evaluator::Object::setEnviron(const char* name, const char* value)  {
   item.variable = 0;
   dic_type::iterator iter = imp->theDictionary.find(item_name);
   if (iter != imp->theDictionary.end()) {
-    iter->second = item;
+    iter->second = std::move(item);
     if (item_name == name) {
       return EVAL::WARNING_EXISTING_VARIABLE;
     }else{
       return EVAL::WARNING_EXISTING_FUNCTION;
     }
   }else{
-    imp->theDictionary[item_name] = item;
+    imp->theDictionary[item_name] = std::move(item);
     return EVAL::OK;
   }
 }
diff --git a/DDRec/src/CellIDPositionConverter.cpp b/DDRec/src/CellIDPositionConverter.cpp
index c3a4e3ad9..7c40655df 100644
--- a/DDRec/src/CellIDPositionConverter.cpp
+++ b/DDRec/src/CellIDPositionConverter.cpp
@@ -11,12 +11,12 @@
 //
 //==========================================================================
 
-#include "DDRec/CellIDPositionConverter.h"
+#include <DDRec/CellIDPositionConverter.h>
 
-#include "DD4hep/Detector.h"
-#include "DD4hep/detail/VolumeManagerInterna.h"
+#include <DD4hep/Detector.h>
+#include <DD4hep/detail/VolumeManagerInterna.h>
 
-#include "TGeoManager.h"
+#include <TGeoManager.h>
 
 namespace dd4hep {
   namespace rec {
@@ -221,7 +221,7 @@ namespace dd4hep {
 	// see if we have a child DetElement that contains the point ...
 
 	DetElement result ;
-	for( auto it : det.children() ){
+	for( const auto& it : det.children() ){
 	  // std::cout << " -   " << global << it.second.name()  << " " << containsPoint( it.second , global )
 	  // 	    << " nChild: " << it.second.children().size() << " isValid: " <<  it.second.isValid()
 	  // 	    << std::endl ;
diff --git a/DDRec/src/MaterialScan.cpp b/DDRec/src/MaterialScan.cpp
index f37f0d11d..0313935f8 100644
--- a/DDRec/src/MaterialScan.cpp
+++ b/DDRec/src/MaterialScan.cpp
@@ -237,8 +237,13 @@ void MaterialScan::print(const Vector3D& p0, const Vector3D& p1, double epsilon)
 	       p0[0]/dd4hep::cm, p0[1]/dd4hep::cm, p0[2]/dd4hep::cm);
     }
     else   {
-      ::printf(fmt, std::to_string(i+1).c_str(), mname.c_str(), next_mat->GetZ(), next_mat->GetA(),
-	       next_mat->GetDensity(), next_mat->GetRadLen()/dd4hep::cm, next_mat->GetIntLen()/dd4hep::cm,
+      double next_dens = next_mat ? next_mat->GetDensity() : 0e0;
+      double next_rad  = next_mat ? next_mat->GetRadLen() : 0e0;
+      double next_int  = next_mat ? next_mat->GetIntLen() : 0e0;
+      double next_Z    = next_mat ? next_mat->GetZ() : 0e0;
+      double next_A    = next_mat ? next_mat->GetA() : 0e0;
+      ::printf(fmt, std::to_string(i+1).c_str(), mname.c_str(), next_Z, next_A,
+	       next_dens, next_rad/dd4hep::cm, next_int/dd4hep::cm,
 	       length/dd4hep::cm, path_length/dd4hep::cm, sum_x0, sum_lambda,
 	       end[0]/dd4hep::cm, end[1]/dd4hep::cm, end[2]/dd4hep::cm);
     }
diff --git a/DDTest/src/test_EventReaders.cc b/DDTest/src/test_EventReaders.cc
index 7994193ae..d48985884 100644
--- a/DDTest/src/test_EventReaders.cc
+++ b/DDTest/src/test_EventReaders.cc
@@ -73,7 +73,7 @@ int main(int argc, char** argv ){
 
       //Reset Reader to check what happens if moving to far in the file
       if (not skipEOF) {
-        thisReader = dd4hep::PluginService::Create<dd4hep::sim::Geant4EventReader*>(readerType, inputFile);
+        thisReader = dd4hep::PluginService::Create<dd4hep::sim::Geant4EventReader*>(readerType, std::move(inputFile));
         sc = thisReader->moveToEvent(1000000);
         test( sc != dd4hep::sim::Geant4EventReader::EVENT_READER_OK , readerType + std::string("EventReader False") );
       }
diff --git a/GaudiPluginService/interface/DD4hep.h b/GaudiPluginService/interface/DD4hep.h
index 3688e4312..cd1f7948a 100644
--- a/GaudiPluginService/interface/DD4hep.h
+++ b/GaudiPluginService/interface/DD4hep.h
@@ -80,7 +80,7 @@ extern "C"  {
     using namespace Gaudi::PluginService::v2;
     Details::Registry::Properties props = {};
     std::string lib_name = "";
-    Details::Registry::instance().add( id, {lib_name, std::move( stub ), std::move( props )} );
+    Details::Registry::instance().add( id, {std::move(lib_name), std::move( stub ), std::move( props )} );
   }
 #elif GAUDI_PLUGIN_SERVICE_VERSION==1
   /// Add a new factory to the registry
-- 
GitLab