Extrapolator.cxx 254 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/

///////////////////////////////////////////////////////////////////
// Extrapolator.cxx, (c) ATLAS Detector software
///////////////////////////////////////////////////////////////////

#include "GaudiKernel/MsgStream.h"
// Trk inlcude
#include "TrkExTools/Extrapolator.h"
#include "TrkExInterfaces/IPropagator.h"
#include "TrkExInterfaces/IMultipleScatteringUpdator.h"
#include "TrkExInterfaces/IEnergyLossUpdator.h"
#include "TrkExUtils/IntersectionSolution.h"
#include "TrkSurfaces/SurfaceBounds.h"
#include "TrkSurfaces/DiscBounds.h"
#include "TrkSurfaces/PerigeeSurface.h"
#include "TrkSurfaces/StraightLineSurface.h"
#include "TrkSurfaces/CylinderSurface.h"
#include "TrkTrack/Track.h"
#include "TrkGeometry/DetachedTrackingVolume.h"
#include "TrkGeometry/AlignableTrackingVolume.h"
#include "TrkGeometry/Layer.h"
#include "TrkGeometry/CompoundLayer.h"
#include "TrkGeometry/CylinderLayer.h"
#include "TrkGeometry/SubtractedCylinderLayer.h"
#include "TrkGeometry/TrackingGeometry.h"
#include "TrkVolumes/BoundarySurface.h"
#include "TrkVolumes/BoundarySurfaceFace.h"
#include "TrkVolumes/Volume.h"
#include "TrkParticleBase/TrackParticleBase.h"
#include "TrkEventUtils/TrkParametersComparisonFunction.h"
#include "TrkDetDescrUtils/SharedObject.h"
#include "TrkDetDescrUtils/GeometrySignature.h"
#include "TrkMaterialOnTrack/EnergyLoss.h"
#include "TrkMaterialOnTrack/ScatteringAngles.h"
//#include "TrkParameters/CurvilinearParameters.h"
#include "TrkParameters/TrackParameters.h"
#include "TrkExUtils/ExtrapolationCache.h"
// for the comparison with a pointer
#include <stdint.h>

// Amg
#include "EventPrimitives/EventPrimitives.h"
#include "GeoPrimitives/GeoPrimitives.h"

// Trk
#include "TrkSurfaces/PlaneSurface.h"

51
52
#include <memory>

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// screen output measures
// "[+] Text describing layer      - with " << layerRZoutput()
// "[+] Text describing position   -   at " << positionOutput()
// "[+] Text describing single parameter  - par = "

// reference surface for Blind extrapolation
//Trk::PlaneSurface Trk::Extrapolator::s_referenceSurface(new Amg::Transform3D(Trk::s_idTransform), 0.,0.);
double Trk::Extrapolator::s_distIncreaseTolerance = 100. * Gaudi::Units::millimeter;
// constructor
Trk::Extrapolator::Extrapolator(const std::string& t, const std::string& n, const IInterface* p) :
  AthAlgTool(t,n,p),
  m_propagators(),
  m_stepPropagator("Trk::STEP_Propagator/AtlasSTEP_Propagator"), 
  m_navigator("Trk::Navigator/AtlasNavigator"), 
  m_updators(),
  m_msupdators(),
  m_elossupdators(),
  m_subPropagators(Trk::NumberOfSignatures),
  m_subUpdators(Trk::NumberOfSignatures),
  m_propNames(),
  m_updatNames(),
  m_meotpIndex(0),
  m_configurationLevel(10),
  m_searchLevel(10),
  m_includeMaterialEffects(true),
  m_requireMaterialDestinationHit(false),
  m_stopWithNavigationBreak(false),
  m_stopWithUpdateZero(false),
  m_subSurfaceLevel(true),
  m_skipInitialLayerUpdate(false),
  m_referenceMaterial(false),
  m_extendedLayerSearch(true), 
  m_initialLayerAttempts(3),
  m_successiveLayerAttempts(1),
  m_tolerance(0.002),  
  m_activeOverlap(false),
  m_useMuonMatApprox(false),
  m_useDenseVolumeDescription(true),
  m_checkForCompundLayers(false),
  m_destinationSurface(0),
  m_boundaryVolume(0),
  m_recall(false),
  m_recallSurface(0),
  m_recallLayer(0),
  m_recallTrackingVolume(0),
  m_parametersOnDetElements(0),
  m_lastValidParameters(0),
  m_currentStatic(0),
  m_currentDense(0),
  m_highestVolume(0),
  m_resolveActive(false),
  m_resolveMultilayers(true),
  m_muonEntrance(0),
  m_returnPassiveLayers(false),
  m_robustSampling(true),
  m_methodSequence(0),
  m_maxMethodSequence(2000),
  m_printHelpOutputAtInitialize(false),
  m_printRzOutput(true),
  m_extrapolateCalls(0),
  m_extrapolateBlindlyCalls(0),
  m_extrapolateDirectlyCalls(0),
  m_extrapolateStepwiseCalls(0),
  m_startThroughAssociation(0),        
  m_startThroughRecall(0),         
  m_startThroughGlobalSearch(0),       
  m_destinationThroughAssociation(0),  
  m_destinationThroughRecall(0),       
  m_destinationThroughGlobalSearch(0), 
  m_layerSwitched(0),
  m_navigationStatistics(false),
  m_navigationBreakDetails(false),
  m_navigationBreakLoop(0),
  m_navigationBreakOscillation(0),
  m_navigationBreakNoVolume(0),
  m_navigationBreakDistIncrease(0),
  m_navigationBreakVolumeSignature(0),
  m_overlapSurfaceHit(0),
  m_materialEffectsOnTrackValidation(false),
  m_meotSearchCallsFw(0),
  m_meotSearchCallsBw(0),
  m_meotSearchSuccessfulFw(0),  
  m_meotSearchSuccessfulBw(0),
  m_lastMaterialLayer(0),
  m_cacheLastMatLayer(false),
  m_matstates(0),
  m_jacs(0),
  m_extrapolationCache(0),
  m_cacheEloss(0),
  m_dumpCache(false),
  m_fastField(false)
{
      declareInterface<IExtrapolator>(this);
      
      // extrapolation steering
      declareProperty("StopWithNavigationBreak",        m_stopWithNavigationBreak);
      declareProperty("StopWithUpdateKill",             m_stopWithUpdateZero);      
      declareProperty("SkipInitialPostUpdate",          m_skipInitialLayerUpdate);
      declareProperty("MaximalMethodSequence",          m_maxMethodSequence);       
      // propagation steering
      declareProperty("Propagators",                    m_propagators);
      declareProperty("SubPropagators",                 m_propNames);
      declareProperty("STEP_Propagator",                m_stepPropagator);
      // material effects handling
      declareProperty("ApplyMaterialEffects",           m_includeMaterialEffects);      
      declareProperty("RequireMaterialDestinationHit",  m_requireMaterialDestinationHit);
      declareProperty("MaterialEffectsUpdators",        m_updators);  
      declareProperty("MultipleScatteringUpdators",     m_msupdators);  
      declareProperty("EnergyLossUpdators",             m_elossupdators);  
      declareProperty("SubMEUpdators",                  m_updatNames);  
      declareProperty("CacheLastMaterialLayer",         m_cacheLastMatLayer);
      // general behavior navigation      
      declareProperty("SearchLevelClosestParameters",   m_searchLevel);
      declareProperty("Navigator",                      m_navigator);
      // muon system specifics            

      declareProperty("UseMuonMatApproximation",        m_useMuonMatApprox);
      declareProperty("UseDenseVolumeDescription",      m_useDenseVolumeDescription);
      declareProperty("CheckForCompoundLayers",         m_checkForCompundLayers);
      declareProperty("ResolveMuonStation",             m_resolveActive);
      declareProperty("ResolveMultilayers",             m_resolveMultilayers);
      declareProperty("ConsiderMuonStationOverlaps",    m_activeOverlap);  
      declareProperty("RobustSampling",            m_robustSampling);  
      // material & navigation related steering
      declareProperty("MaterialEffectsOnTrackProviderIndex" , m_meotpIndex);  
      declareProperty("MaterialEffectsOnTrackValidation"    , m_materialEffectsOnTrackValidation);
      declareProperty("ReferenceMaterial"                   , m_referenceMaterial);
      declareProperty("ExtendedLayerSearch"                 , m_extendedLayerSearch);
      declareProperty("InitialLayerAttempts"                , m_initialLayerAttempts);
      declareProperty("SuccessiveLayerAttempts"             , m_successiveLayerAttempts);
      // debug and validation
      declareProperty("HelpOutput",                     m_printHelpOutputAtInitialize);
      declareProperty("positionOutput",                 m_printRzOutput);
      declareProperty("NavigationStatisticsOutput",     m_navigationStatistics);
      declareProperty("DetailedNavigationOutput",       m_navigationBreakDetails);
      declareProperty("Tolerance",                      m_tolerance);
      //Magnetic field properties
      declareProperty("DumpCache",			m_dumpCache);  
      declareProperty("MagneticFieldProperties",	m_fastField);  
}

// destructor
Trk::Extrapolator::~Extrapolator()
{}

// Athena standard methods
// initialize
StatusCode Trk::Extrapolator::initialize()
{   

    s_referenceSurface=new Trk::PlaneSurface(new Amg::Transform3D(Trk::s_idTransform), 0.,0.);
    s_referenceSurface->setOwner(Trk::TGOwn);

    m_fieldProperties = m_fastField ? Trk::MagneticFieldProperties(Trk::FastField) : Trk::MagneticFieldProperties(Trk::FullField);
    if(m_propagators.size() == 0) m_propagators.push_back("Trk::RungeKuttaPropagator/DefaultPropagator");
    if(m_updators.size() == 0) m_updators.push_back("Trk::MaterialEffectsUpdator/DefaultMaterialEffectsUpdator");
    if(m_msupdators.size() == 0) m_msupdators.push_back("Trk::MultipleScatteringUpdator/AtlasMultipleScatteringUpdator");
    if(m_elossupdators.size() == 0) m_elossupdators.push_back("Trk::EnergyLossUpdator/AtlasEnergyLossUpdator");
    
    if (m_propagators.size()) {
      if ( m_propagators.retrieve().isFailure() ) {
        ATH_MSG_FATAL( "Failed to retrieve tool " << m_propagators );
        return StatusCode::FAILURE;
      } else 
        ATH_MSG_INFO( "Retrieved tools " << m_propagators );      
    }

     
     // from the number of retrieved propagators set the configurationLevel
     unsigned int validprop = m_propagators.size();
     
     if (!validprop){
        ATH_MSG_WARNING( "None of the defined propagators could be retrieved!" );
        ATH_MSG_WARNING( "  Extrapolators jumps back in unconfigured mode, only strategy pattern methods can be used." ); 
      } else {
        m_configurationLevel = validprop - 1;
        ATH_MSG_VERBOSE( "Configuration level automatically set to " << m_configurationLevel );        
      }
    
    // Get the Navigation AlgTools
    if ( m_navigator.retrieve().isFailure() ) {
      ATH_MSG_FATAL( "Failed to retrieve tool " << m_navigator );
      return StatusCode::FAILURE;
    } else {
      ATH_MSG_INFO( "Retrieved tool " << m_navigator );
    }
    // Get the Material Updator
    if (m_includeMaterialEffects && m_updators.size()){
      if ( m_updators.retrieve().isFailure() ) {
        ATH_MSG_FATAL( "None of the defined material updatros could be retrieved!" );
        ATH_MSG_FATAL( "No multiple scattering and energy loss material update will be done."        );
        return StatusCode::FAILURE;
      } else 
        ATH_MSG_INFO( "Retrieved tools: " << m_updators );
    }

    // from the number of retrieved propagators set the configurationLevel
    unsigned int validmeuts = m_updators.size();
   
    // -----------------------------------------------------------
    // Sanity check 1
    
    if (!m_propNames.size() && m_propagators.size()){
       ATH_MSG_DEBUG( "Inconsistent setup of Extrapolator, no sub-propagators configured, doing it for you. " );
       m_propNames.push_back(m_propagators[0]->name().substr( 8, m_propagators[0]->name().size()-8 ));
    }
    
    if (!m_updatNames.size() && m_updators.size()){
       ATH_MSG_DEBUG( "Inconsistent setup of Extrapolator, no sub-materialupdators configured, doing it for you. " );
       m_updatNames.push_back(m_updators[0]->name().substr( 8, m_updators[0]->name().size()-8 ));
    }

    // -----------------------------------------------------------
    // Sanity check 2
    // fill the number of propagator names and updator names up with first one
    while ( int(m_propNames.size()) < int(Trk::NumberOfSignatures)) 
         m_propNames.push_back(m_propNames[0]); 
    while  (int(m_updatNames.size()) < int(Trk::NumberOfSignatures)) 
         m_updatNames.push_back(m_updatNames[0]); 
    if (validprop && validmeuts){
      // Per definition: if configured not found, take the lowest one
      for (unsigned int isign=0; int(isign) < int(Trk::NumberOfSignatures); ++isign){
                unsigned int index = 0;
           
          for (unsigned int iProp = 0; iProp < m_propagators.size(); iProp++) {
                 std::string pname = m_propagators[iProp]->name().substr( 8, m_propagators[iProp]->name().size()-8 );
            if ( m_propNames[isign] == pname ) index = iProp; 
              }
             ATH_MSG_DEBUG( " subPropagator:" << isign << " pointing to propagator: "<< m_propagators[index]->name() );
             m_subPropagators[isign] =  ( index < validprop ) ? &(*m_propagators[index]) : &(*m_propagators[Trk::Global]);     

          index = 0; 
          for (unsigned int iUp = 0; iUp < m_updators.size(); iUp++) {
          std::string uname = m_updators[iUp]->name().substr( 8, m_updators[iUp]->name().size()-8 );
          if ( m_updatNames[isign] == uname ) index = iUp; 
             }
            ATH_MSG_DEBUG( " subMEUpdator:" << isign << " pointing to updator: "<< m_updators[index]->name() );
            m_subUpdators[isign] =  ( index < validmeuts ) ? &(*m_updators[index]) : &(*m_updators[Trk::Global]);     
     }
   } else {
      ATH_MSG_FATAL( "Configuration Problem of Extrapolator: "                        
          << "  -- At least one IPropagator and IMaterialUpdator instance have to be given.! " );
   
   }

    m_maxNavigSurf = 1000;
    m_navigSurfs.reserve(m_maxNavigSurf); 
    m_maxNavigVol = 50;
    m_navigVols.reserve(m_maxNavigVol); 
    m_navigVolsInt.reserve(m_maxNavigVol); 

       
    ATH_MSG_INFO("initialize() successful" );    
    return StatusCode::SUCCESS;
}

// finalize
StatusCode Trk::Extrapolator::finalize()
{
    
  if (m_navigationStatistics || msgLvl(MSG::DEBUG)){
    ATH_MSG_INFO(   " Perfomance Statistics  : "                                                          );
    ATH_MSG_INFO(   " [P] Methode Statistics ------- -----------------------------------------------------------"  );
    ATH_MSG_INFO(   "     -> Number of extrapolate() calls                : " << m_extrapolateCalls               );
    ATH_MSG_INFO(   "     -> Number of extrapolateBlindly() calls         : " << m_extrapolateBlindlyCalls        );
    ATH_MSG_INFO(   "     -> Number of extrapolateDirectly() calls        : " << m_extrapolateDirectlyCalls       );
    ATH_MSG_INFO(   "     -> Number of extrapolateStepwise() calls        : " << m_extrapolateStepwiseCalls       );
    ATH_MSG_INFO(   "     -> Number of layers switched in layer2layer     : " << m_layerSwitched                  );
    ATH_MSG_INFO(   "[P] Navigation Initialization ------------------------------------------------------------"  );
    ATH_MSG_INFO(   "      -> Number of start associations                : " << m_startThroughAssociation        ); 
    ATH_MSG_INFO(   "      -> Number of start recalls                     : " << m_startThroughRecall             ); 
    ATH_MSG_INFO(   "      -> Number of start global searches             : " << m_startThroughGlobalSearch       );
    ATH_MSG_INFO(   "      -> Number of destination associations          : " << m_destinationThroughAssociation  ); 
    ATH_MSG_INFO(   "      -> Number of destination recalls               : " << m_destinationThroughRecall       ); 
    ATH_MSG_INFO(   "      -> Number of destination global searches       : " << m_destinationThroughGlobalSearch ); 
    ATH_MSG_INFO(   "[P] Navigation Breaks --------------------------------------------------------------------"  );
    ATH_MSG_INFO(   "     -> Number of navigation breaks: loop            : " << m_navigationBreakLoop            );
    ATH_MSG_INFO(   "     -> Number of navigation breaks: oscillation     : " << m_navigationBreakOscillation     );
    ATH_MSG_INFO(   "     -> Number of navigation breaks: no volume found : " << m_navigationBreakNoVolume        );
    ATH_MSG_INFO(   "     -> Number of navigation breaks: dist. increase  : " << m_navigationBreakDistIncrease    );
    ATH_MSG_INFO(   "     -> Number of navigation breaks: dist. increase  : " << m_navigationBreakVolumeSignature );    
    if (m_navigationBreakDetails && msgLvl(MSG::DEBUG)){
      ATH_MSG_DEBUG(   "   Detailed output for Navigation breaks             : "                                   );        
      ATH_MSG_DEBUG(   "    o " << m_navigationBreakLoop << " loops occured in the following volumes:    "         );        
      std::map<const Trk::TrackingVolume*,int>::iterator volIter = m_loopVolumes.begin();
      std::map<const Trk::TrackingVolume*,int>::iterator volIterEnd = m_loopVolumes.end();
      for ( ; volIter != volIterEnd; ++volIter)
        ATH_MSG_DEBUG(   "          - " << volIter->second << '\t' << " times in '" << (volIter->first)->volumeName() << "'" );
      ATH_MSG_DEBUG(   "    o " << m_navigationBreakOscillation << " osillations occured in following volumes: "   );
      volIter = m_oscillationVolumes.begin();
      volIterEnd = m_oscillationVolumes.end();
      for ( ; volIter != volIterEnd; ++volIter)
        ATH_MSG_DEBUG(   "          - " << volIter->second << '\t' << " times in '" << (volIter->first)->volumeName() << "'" );
      ATH_MSG_DEBUG(   "    o " << m_navigationBreakNoVolume << " times no next volume found of  volumes: "        );       
      volIter = m_noNextVolumes.begin();
      volIterEnd = m_noNextVolumes.end();
      for ( ; volIter != volIterEnd; ++volIter)
        ATH_MSG_DEBUG(   "          - " << volIter->second << '\t' << " times in '" << (volIter->first)->volumeName() << "'" );
      ATH_MSG_DEBUG(   "    o " << m_navigationBreakDistIncrease << " distance increases detected at volumes: "    );        
      volIter = m_distIncreaseVolumes.begin();
      volIterEnd = m_distIncreaseVolumes.end();
      for ( ; volIter != volIterEnd; ++volIter)
         ATH_MSG_DEBUG(   "          - " << volIter->second << '\t' << " times in '" << (volIter->first)->volumeName() << "'" );
      ATH_MSG_DEBUG(   "    o " << m_navigationBreakVolumeSignature << " no propagator configured for volumes: "    );       
      volIter = m_volSignatureVolumes.begin();
      volIterEnd = m_volSignatureVolumes.end();
      for ( ; volIter != volIterEnd; ++volIter)
         ATH_MSG_DEBUG(   "          - " << volIter->second << '\t' << " times in '" << (volIter->first)->volumeName() << "'" );      
    }
    // validation of the overlap search
    ATH_MSG_INFO(   "[P] Overlaps found -----------------------------------------------------------------------"   );
    ATH_MSG_INFO(   "     -> Number of overlap Surface hit                : " << m_overlapSurfaceHit               );
    ATH_MSG_INFO(   " -----------------------------------------------------------------------------------------"   ); 
    // validation of the material collection methods
    if (m_materialEffectsOnTrackValidation){
      ATH_MSG_INFO(   "[P] MaterialEffectsOnTrack collection ----------------------------------------------------" );
      ATH_MSG_INFO(   "     -> Forward successful/calls (ratio)           : " << m_meotSearchSuccessfulFw << "/" 
                             <<  m_meotSearchCallsFw<< " (" << double(m_meotSearchSuccessfulFw)/m_meotSearchCallsFw << ")"  );
      ATH_MSG_INFO(   "     -> Backward successful/calls (ratio)          : " << m_meotSearchSuccessfulBw << "/" 
                             <<  m_meotSearchCallsBw<< " (" << double(m_meotSearchSuccessfulBw)/m_meotSearchCallsBw << ")"  );
      ATH_MSG_INFO(   " -----------------------------------------------------------------------------------------" );         
    }
  }  
 
  delete s_referenceSurface;

  ATH_MSG_INFO( "finalize() successful" );
  return StatusCode::SUCCESS;
}

const Trk::NeutralParameters* Trk::Extrapolator::extrapolate(const xAOD::NeutralParticle& xnParticle,
                                                             const Surface& sf,
                                                             PropDirection dir,
                                                             BoundaryCheck bcheck) const
{
    const Trk::NeutralPerigee& nPerigee = xnParticle.perigeeParameters();
    return extrapolate(nPerigee,sf,dir,bcheck);
}


const Trk::TrackParameters* Trk::Extrapolator::extrapolate(const xAOD::TrackParticle& xtParticle,
                                                           const Surface& sf,
                                                           PropDirection dir,
                                                           BoundaryCheck bcheck,
                                                           ParticleHypothesis particle,
                                                           MaterialUpdateMode matupmode) const
{

   const Trk::Perigee& tPerigee = xtParticle.perigeeParameters();
   //!< @TODO: search for closest parameter in on new curvilinear x/y/z and surface distance ... 
   // ... for the moment ... take the perigee
   return  extrapolate(tPerigee, sf, dir, bcheck, particle, matupmode); 

}



const Trk::TrackParameters* Trk::Extrapolator::extrapolate(const TrackParticleBase& particleBase,
                                                           const Surface& sf,
                                                           PropDirection dir,
                                                           BoundaryCheck bcheck,
                                                           ParticleHypothesis particle,
                                                           MaterialUpdateMode matupmode) const
{

  const Trk::TrackParameters*  closestParameters = 0;
      
  const Trk::CylinderSurface* ccsf = dynamic_cast<const Trk::CylinderSurface*>(&sf);
  if (ccsf) {
   Trk::ComparisonFunction<TrackParameters> tParFinderCylinder(ccsf->bounds().r());
   closestParameters = *(std::min_element(particleBase.trackParameters().begin(), particleBase.trackParameters().end(), tParFinderCylinder));
  } else {
  
    const Trk::StraightLineSurface* slsf = dynamic_cast<const Trk::StraightLineSurface*>(&sf);
    const Trk::PerigeeSurface*      persf = 0;
    if (!slsf) persf = dynamic_cast<const Trk::PerigeeSurface*>(&sf);
  
    if (slsf || persf) {
     Trk::ComparisonFunction<TrackParameters> tParFinderLine(sf.center(), sf.transform().rotation().col(2));
     closestParameters = *(std::min_element(particleBase.trackParameters().begin(), particleBase.trackParameters().end(), tParFinderLine));
    }

  }
  if (!closestParameters){
     Trk::ComparisonFunction<TrackParameters> tParFinderCenter(sf.center());
     closestParameters = *(std::min_element(particleBase.trackParameters().begin(), particleBase.trackParameters().end(), tParFinderCenter));
  }
  return closestParameters ? extrapolate(*closestParameters, sf, dir, bcheck, particle, matupmode) : 0;
}
const Trk::NeutralParameters* Trk::Extrapolator::extrapolate(const NeutralParameters& parameters,
	                                            const Surface& sf,
	                                            PropDirection dir,
	                                            BoundaryCheck bcheck) const
{

   if (m_configurationLevel<10){
      const IPropagator* currentPropagator = m_subPropagators.size() ? m_subPropagators[Trk::Global] : 0;
      if (currentPropagator) return currentPropagator->propagate(parameters, sf, dir, bcheck);
   }
   ATH_MSG_ERROR( "  [!] No default Propagator is configured ! Please check jobOptions." );
   return 0;

}
// Stratetgy Pattern extrapolation methods ---------------------------------------------------------------------------------------/
const Trk::TrackParameters*  Trk::Extrapolator::extrapolate(const IPropagator& prop,
                                                            const Trk::TrackParameters& parm,
                                                            const Trk::Surface& sf,
                                                            Trk::PropDirection dir,
                                                            Trk::BoundaryCheck bcheck,
                                                            Trk::ParticleHypothesis particle,
                                                            MaterialUpdateMode matupmode) const
{ 
    // set the model action of the material effects updators
    for (unsigned int imueot = 0; imueot < m_subUpdators.size(); ++imueot) 
      m_subUpdators[imueot]->modelAction();      
      
    // reset the destination surface
    m_destinationSurface = 0;
    m_lastValidParameters = 0;
    // skip rest of navigation if particle hypothesis is nonInteracting
    if (particle==Trk::nonInteracting || int(dir) > 5) return extrapolateDirectly(prop,parm,sf,dir,bcheck,particle);

   // statistics && sequence output ----------------------------------------
    ++m_extrapolateCalls;
    ++m_methodSequence;
    // the resultParameters
    const Trk::TrackParameters* resultParameters = 0;
    // prepare the values for the startup and call the initialization ------------------------------------------
    const Trk::TrackingVolume*   startVolume     = 0;
    const Trk::TrackingVolume*   destVolume      = 0;
    const Trk::Layer*            nextLayer       = 0; 
    const Trk::TrackingVolume*   nextVolume      = 0;
    const Trk::TrackingVolume*   lastVolume      = 0;
    const Trk::TrackParameters*  refParameters   = 0;
    const Trk::TrackParameters*  lastParameters  = 0;
    const Trk::TrackParameters*  navParameters   = 0;
    const Trk::TrackParameters*  nextParameters  = (&parm);
    // initialize Navigation (calls as well initialize on garbe collection) -------------------------------------
    Trk::PropDirection navDir = initializeNavigation(prop,
                                                     parm,
                                                     sf,
                                                     dir,
                                                     particle,
                                                     refParameters,
                                                     nextLayer,
                                                     nextVolume,
                                                     destVolume);
    // ----------------------------------------------------------------------------------------------------------      
    // if anyDirection has been chosen as a start directive:
    //   -> overwrite the dir with the navigation direction
    dir = (dir == Trk::anyDirection) ? navDir : dir;
    // check for consistency 
    if (dir == Trk::anyDirection || navDir != dir){ 
       // navigation could not be resolved
       ATH_MSG_VERBOSE( "  [!] Navigation direction could not be resolved, switching to extrapolateDirectly()" ); 
       // the extrapolate directly call
       resultParameters = extrapolateDirectly(prop,parm,sf,navDir,bcheck,particle);
       // return and cleanup
       return returnResult(resultParameters,refParameters);
    }
    // ----------------------------------------------------------------------------------------------------------
    startVolume = nextVolume;
    // fallback setup  ------------------------------------------------------------------------------------------
    bool fallback = false;
    // ------- initial distance estimation ----------------------------------------------------------------------
    double currentDistance  = 0.;
    double previousDistance = 0.;
    // reference parameters and distance solution: use consistently one of each
    if (refParameters){
       ATH_MSG_VERBOSE( "  [+] Reference Parameters       -   at " << positionOutput(refParameters->position()) );
       currentDistance = (refParameters->position()-parm.position()).mag();
    } else {
      // using fast but accureate sl distance from surface 
      Trk::DistanceSolution distSol = sf.straightLineDistanceEstimate(parm.position(),dir*parm.momentum().normalized());
      if (distSol.numberOfSolutions()>0 )  
        currentDistance = distSol.absClosest(); 
      else
        currentDistance = fabs(distSol.toPointOfClosestApproach());
      // VERBOSE output
    }
    ATH_MSG_VERBOSE("  [+] Initial 3D-distance to destination - d3 = " << currentDistance);  
    // and for oscillation protection ---------------------------------------------------------------------------
    const Trk::TrackingVolume*   previousVolume  = 0;
    // ----------------------------------------------------------------------------------------------------------
    std::string startVolumeName = (nextVolume) ? nextVolume->volumeName() : "Unknown (ERROR)";
    std::string destVolumeName  = destVolume ? destVolume->volumeName() : "Unknown (blind extrapolation)";
    if (msgLvl(MSG::VERBOSE)){       
      ATH_MSG_VERBOSE( "  [" << m_methodSequence << "] extrapolate() " <<  startVolumeName << " ->  "<< destVolumeName );
      ATH_MSG_VERBOSE( "  [+] Starting position determined - at " << positionOutput(parm.position()) );
      if (nextLayer)
         ATH_MSG_VERBOSE( "  [+] Starting layer determined  - with " << layerRZoutput(*nextLayer) );
    }
    
    // ----------------------------------------------------------------------------------------------------------
    const IPropagator* currentPropagator = 0;
    // ----------------- extrapolation from One Volume to the next Volume  --------------------------------------
    // the loop continues while:
    //       - nextVolume extists
    //       - nextVolume is different from lastVolume (prevent infinite loops)
    //       - nextVolume is different from destinationVolume (change to extrapolateInsideVolume)
    //       - nextParameters exist
    //       - lastVolume is different from previousVolume (prevent oscillation loop, one-time-punch-through allowed)        
    //       - the reinforced navigation can find destination parameters
    //       - the maximum method sequence is not met

    // best starting parameters
    bool updateLastValid  = true;          
    // one-time-punch-through allows for volume2 - volume1 - volume2 (cosmics)
    bool punchThroughDone = false;

    while (nextVolume && 
           nextVolume!=destVolume &&
           nextVolume != lastVolume &&
           nextParameters &&
           m_methodSequence < m_maxMethodSequence){

      // chose the propagtor type
      currentPropagator = subPropagator(*nextVolume);
      if (!currentPropagator){
         // [0] Navigation break : configuration problem or consistency problem of TrackingGeometry
         // output
         ATH_MSG_DEBUG( "  [X] Navigation break [X]"  );
         ATH_MSG_DEBUG( "          - Reason      : No Propagator found for Volume '"<< nextVolume->volumeName() << "'"  );        
         // debug statistics
         ++m_navigationBreakVolumeSignature;
         if (m_navigationBreakDetails) ++m_volSignatureVolumes[nextVolume];
         // trigger the fallback solution
         fallback = true;                  
         break;
      }
             
      // check for the distance to destination ------------------------------------------------------------------------------------
      if (updateLastValid) m_lastValidParameters = nextParameters;  
         // re-initialize (will only overwrite destVolume)
         if (nextVolume->redoNavigation()){
             delete refParameters; refParameters = 0;
             dir = initializeNavigation(*currentPropagator,
                                        *nextParameters,
                                        sf,
                                        dir,
                                        particle,
                                        refParameters,
                                        nextLayer,
                                        nextVolume,
                                        destVolume);
           }
          // avoid the oszillation
          previousVolume = lastVolume; 
          // for the next step to termine if infinite loop occurs
          lastVolume = nextVolume;
          // for memory cleanup and backup
          lastParameters = nextParameters;

          // MS specific code ------------------
          // extrapolation within detached volumes - returns parameters on destination surfaces, or boundary solution
          // handles also dense volume description : for the moment, only Calo included
          if ( nextVolume->geometrySignature()==Trk::MS || (m_useDenseVolumeDescription && nextVolume->geometrySignature()==Trk::Calo) ) {

             if (m_parametersAtBoundary.navParameters && 
                 m_parametersAtBoundary.navParameters != m_parametersAtBoundary.nextParameters) {
                 // extrapolate to volume boundary to avoid navigation break
                 const Trk::TrackParameters* nextPar = currentPropagator->propagate(*m_parametersAtBoundary.nextParameters,
                                                                                    m_parametersAtBoundary.navParameters->associatedSurface(),
                                                                                     dir, 
                                                                                     bcheck,
                                                                                     //*previousVolume,
                                                                                     m_fieldProperties,
										    particle,false,previousVolume);
                 // propagation to boundary 
                 if (nextPar) 
                    throwIntoGarbageBin(nextPar);
                  // set boundary and next parameters
                  m_parametersAtBoundary.boundaryInformation(nextVolume,nextPar,nextPar);
                  nextParameters = m_parametersAtBoundary.nextParameters; 
                  navParameters  = m_parametersAtBoundary.navParameters;       
                 }
                 // start from the nextParameter (which are at volume boundary)
                if (nextParameters) {
631
632
633
634
635
		  if (!m_stepPropagator) { 
		    ATH_MSG_ERROR("extrapolation in Calo/MS called without configured STEP propagator, aborting"); 
		    return 0;  
		  }  
                       resultParameters = extrapolateWithinDetachedVolumes(*m_stepPropagator,
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
                                                                       *nextParameters,
                                                                       sf,
                                                                       *nextVolume,
                                                                       dir,
                                                                       bcheck,
                                                                       particle,
                                                                       matupmode);
                  }
               if (resultParameters){   
                  // destination reached : indicated through result parameters
                  // set the model action of the material effects updators
                  for (unsigned int imueot = 0; imueot < m_subUpdators.size(); ++imueot) m_subUpdators[imueot]->modelAction();            
                  // return the parameters at destination
                  ATH_MSG_DEBUG( "  [+] Destination surface successfully hit.");
                  // return the result (succesful)
                  return returnResult(resultParameters,refParameters);
                } else if (!m_parametersAtBoundary.nextParameters || !m_parametersAtBoundary.nextVolume) {
                  ATH_MSG_DEBUG( "  [-] Destination surface could not be hit.");
                  return returnResult(resultParameters,refParameters);
                 }
            } else {
           // ------------------------------------------------------------------------------------------------
           // standard loop over volumes (but last one)
           // extrapolate to volume boundary - void method as 'm_parametersAtBoundary' hold the information
           extrapolateToVolumeBoundary(*currentPropagator,
                                       *nextParameters,
                                        nextLayer,
                                        *nextVolume,
                                        dir,
                                        bcheck,
                                        particle,
                                        matupmode);
     }        
     // go on with the next volume / get next Volume and Boundary from the private member
     nextVolume     = m_parametersAtBoundary.nextVolume;
     nextParameters = m_parametersAtBoundary.nextParameters;
     navParameters  = m_parametersAtBoundary.navParameters;     
     // new distance estimation ( after step to next volume ) ------------------------------------------------
     previousDistance = currentDistance;
     // make it either from the navParmaters (if the exist) or the nextParameters
     const Trk::TrackParameters* distParameters = m_parametersAtBoundary.navParameters ? 
           m_parametersAtBoundary.navParameters : nextParameters;

     if (distParameters){
        // use consistently either the:
        // (A) reference parameters or the 
        if (refParameters)
            currentDistance = (refParameters->position()-distParameters->position()).mag();
        else {
        // (B) distance solution to surface    
           Trk::DistanceSolution newDistSol = sf.straightLineDistanceEstimate(distParameters->position(),
                                                                              dir*distParameters->momentum().normalized());
           currentDistance = newDistSol.numberOfSolutions() > 0 ? newDistSol.absClosest() : fabs(newDistSol.toPointOfClosestApproach());       
        }
    }          
    ATH_MSG_VERBOSE("  [+] New 3D-distance to destination     - d3 = " << currentDistance << " (from " << 
      ( m_parametersAtBoundary.navParameters ? "boundary parameters" : "last parameters within volume " ) << ")");    
      
    // -------------------------------------------------------------------------------------------------------
    // (1) NAVIGATION BREAK : next Volume is identical to last volume -- LOOP
    if (nextVolume == lastVolume && nextVolume){
        // output         
         ATH_MSG_DEBUG( "  [X] Navigation break [X]"  );
         ATH_MSG_DEBUG( "          - Reason      : Loop detected in TrackingVolume '"<< nextVolume->volumeName() << "'"  );         
         // statistics
          ++m_navigationBreakLoop;
         // record the oscillation volume -- increase the counter for the volume
         if (m_navigationBreakDetails) ++m_loopVolumes[nextVolume];
         // fallback flag
         fallback = true;
         // break it
         break;
    }
    // (2) NAVIGATION BREAK : Oscillation 
    else if (nextVolume == previousVolume && nextVolume) {
         // one time the loop oscillation has been allowed already
        if (punchThroughDone){
           // output
           ATH_MSG_DEBUG( "  [X] Navigation break [X]"  );
           ATH_MSG_DEBUG( "          - Reason      : Oscillation detected in TrackingVolume '"<< nextVolume->volumeName() << "'"  );           
           // statistics
           ++m_navigationBreakOscillation;
           // record the oscillation volume -- increase the counter for the volume
           if (m_navigationBreakDetails) ++m_oscillationVolumes[nextVolume];
           // fallback flag
           fallback = true;
           // break it
           break;
        } else {
          // set the punch-through to true
          punchThroughDone = true;
          ATH_MSG_DEBUG( "  [!] One time punch-through a volume done." );        
        }  
           
    }
    // ------------------- the output interpretationn of the extrapolateToVolumeBoundary
    // (3) NAVIGATION BREAK : no nextVolume found - but not in extrapolateBlindly() mode 
    else if (!nextVolume && !m_parametersOnDetElements && lastVolume && !m_stopWithUpdateZero){
           // output
           ATH_MSG_VERBOSE( "  [X] Navigation break [X]"  );
           ATH_MSG_VERBOSE( "          - Reason      : No next volume found of TrackingVolume '"<< lastVolume->volumeName() << "'"  );
           // statistics
           ++m_navigationBreakNoVolume;
           // record the "no next" volume -- increase the counter for the (last) volume
           if (m_navigationBreakDetails) ++m_noNextVolumes[lastVolume];
           // fallback flag
           fallback = true;
           // break it
         break;
    }
    // ------------------- the output interpretationn of the extrapolateToVolumeBoundary
    // (4) NAVIGATION BREAK : // nextParameters found but distance to surface increases      
     else if (nextParameters 
              && !m_parametersOnDetElements 
              && navParameters
              && nextVolume
              && currentDistance > s_distIncreaseTolerance+previousDistance){
         
          // output
              ATH_MSG_DEBUG( "  [X] Navigation break [X]"  );
              ATH_MSG_DEBUG( "          - Reason      : Distance increase [ " << previousDistance << " to "
                               << currentDistance
                               << "] in TrackingVolume '"<< nextVolume->volumeName() << "'"  );
          // statistics
          ++m_navigationBreakDistIncrease; 
          // record the "dist increase" volume -- increase the counter for the volume
          if (m_navigationBreakDetails) ++m_distIncreaseVolumes[nextVolume];           
          // fallback flag
          fallback = true;
          break;           
     }
    // ------------------- the output interpretationn of the extrapolateToVolumeBoundary
    // (+) update killed track    
    else if ( (!nextParameters && m_stopWithUpdateZero) || !nextVolume ){ 
         ATH_MSG_DEBUG( "  [+] Navigation stop : either the update killed the track, or end of detector/boundary volume reached" );
         return returnResult(resultParameters,refParameters);
    }
    // ------------------- the output interpretationn of the extrapolateToVolumeBoundary
    // (+) end of extrapolate blindly(volume*)
    else if (m_boundaryVolume 
             && navParameters
             && !(m_boundaryVolume->inside(navParameters->position()) ) ) {
        ATH_MSG_DEBUG( "  [+] Navigation stop : next navigation step would lead outside given boundary volume" );
        return returnResult(resultParameters,refParameters);
    }        
    // ------------------- the output interpretationn of the extrapolateToVolumeBoundary
    // (5) NAVIGATION BREAK : // nextParameters found but distance to surface increases 
    else if (nextVolume)
         ATH_MSG_DEBUG( "  [+] next Tracking Volume = " << nextVolume->volumeName() );   
      // set validity of last parameters to cache -----------------------------------------------------------------     
      if (nextParameters 
          && !m_parametersOnDetElements 
          && navParameters 
          && nextVolume
          && currentDistance > previousDistance) 
              updateLastValid = false;
      else 
             updateLastValid = true;
      // reset
      nextParameters = nextParameters ? nextParameters : lastParameters;
      // one volume step invalidates the nextLayer information
      nextLayer = 0;
   }
    
   // ------------------- fallback was triggered in volume to volume loop -------------------------------------- 
   if (fallback){
       // continue with the output
       ATH_MSG_DEBUG( "          - Consequence : "
           << (  m_stopWithNavigationBreak ? "return 0 (configured) " : "switch to extrapolateDirectly() ")   );           
       // stop with navigaiton break or zero update
       if (m_stopWithNavigationBreak || m_stopWithUpdateZero) {
         emptyGarbageBin();
         return 0;     
       }       
       // cleanup the garbage
       if(m_lastValidParameters && lastVolume)  
         currentPropagator = subPropagator(*lastVolume);
         if (!currentPropagator) return returnResult(resultParameters,refParameters);
       // create the result now
       //resultParameters = currentPropagator->propagate(*m_lastValidParameters,sf,Trk::anyDirection,bcheck,*lastVolume,particle);
	 resultParameters = currentPropagator->propagate(*m_lastValidParameters,sf,Trk::anyDirection,bcheck,m_fieldProperties,particle,false,lastVolume);
       // desperate try 
       //resultParameters = resultParameters ? resultParameters : currentPropagator->propagate(parm,sf,dir,bcheck,*startVolume,particle);
	 resultParameters = resultParameters ? resultParameters : currentPropagator->propagate(parm,sf,dir,bcheck,m_fieldProperties,particle,false,startVolume);
       return returnResult(resultParameters,refParameters);
    }

   // ----------------- this is the exit of the extrapolateBlindly() call --------------------------------------
   if ( (&sf) == (s_referenceSurface) ) return returnResult(resultParameters,refParameters);

   // ---------------- extrapolation inside the Volume ----------------------------------------------------------
   if (nextVolume){ 
   
       // chose the propagator fromt he geometry signature
       currentPropagator = subPropagator(*nextVolume);
       // extrapolate inside the volume       
       if (currentPropagator) 
          resultParameters = extrapolateInsideVolume(*currentPropagator,
                                                     *nextParameters,
                                                     sf,
                                                     nextLayer,
                                                     *nextVolume,
                                                     dir,
                                                     bcheck,
                                                     particle,
                                                     matupmode);
                                                                                                          
    }
   // ------------------------------------------------------------------------------------------------------------ 
   // the final - desperate backup --- just try to hit the surface 
   if (!resultParameters && !m_stopWithNavigationBreak && !m_stopWithUpdateZero){
        ATH_MSG_DEBUG( "  [-] Fallback to extrapolateDirectly triggered ! " );
        resultParameters = prop.propagate(*nextParameters,
                                          sf,
                                          dir,
                                          bcheck,
                                          //*startVolume,
                                          m_fieldProperties,
                                          particle, false, startVolume);
   }
   // return whatever you have
   return returnResult(resultParameters,refParameters); 
}

const std::vector<const Trk::TrackParameters*>* Trk::Extrapolator::extrapolateStepwise(
                                                            const IPropagator& prop,
                                                            const Trk::TrackParameters& parm,
                                                            const Trk::Surface& sf,
                                                            Trk::PropDirection dir,
                                                            Trk::BoundaryCheck bcheck,
                                                            Trk::ParticleHypothesis particle) const
{
   // statistics && sequence output ----------------------------------------
   ++m_extrapolateStepwiseCalls;
   ++m_methodSequence;
   ATH_MSG_DEBUG( "F-[" << m_methodSequence << "] extrapolateStepwise(...) " ); 

   // initialize the return parameters vector
   Trk::TrackParametersVector* returnParameters = 0;
   // create a new internal helper vector
   m_parametersOnDetElements = new std::vector<const Trk::TrackParameters*>;
   // run the extrapolation
   const Trk::TrackParameters* parameterOnSf = extrapolate(prop, parm, sf, dir, bcheck, particle);
   // assign the return parameter and set m_parametersOnDetElements = 0;
   returnParameters = m_parametersOnDetElements; m_parametersOnDetElements = 0;
   // add the parameters to the return parameters
   if (parameterOnSf)
       returnParameters->push_back(parameterOnSf);
   else {
    // memory cleanup and return 0    
        std::vector<const Trk::TrackParameters*>::const_iterator tpIter = returnParameters->begin();
        for (; tpIter != returnParameters->end(); ++tpIter) delete (*tpIter);
        delete returnParameters; returnParameters = 0;
   }   
   return returnParameters;
}

const Trk::TrackParameters* Trk::Extrapolator::extrapolate(const IPropagator& prop,
                                                           const Trk::Track& trk,
                                                           const Trk::Surface& sf,
                                                           Trk::PropDirection dir,
                                                           Trk::BoundaryCheck bcheck,
                                                           Trk::ParticleHypothesis particle,
                                                           MaterialUpdateMode matupmode) const
{
 
  // statistics && sequence output ----------------------------------------
  ATH_MSG_DEBUG( "T-[" << ++m_methodSequence << "] extrapolate(const Track&)" ); 

  // intialize the starting propagator
  const IPropagator* searchProp = 0;
  // get the propagator depending on the volume
  if (m_searchLevel<2){
      unsigned int iprop = (m_searchLevel > m_configurationLevel) ? m_searchLevel : m_configurationLevel;
      searchProp = &(*m_propagators[iprop]); 
  }
  // call the navigator
  const Trk::TrackParameters* closestTrackParameters = m_navigator->closestParameters(trk, sf, searchProp);
  if (closestTrackParameters) return(extrapolate(prop, *closestTrackParameters, sf, dir, bcheck, particle, matupmode));
  return 0;               
}  

const Trk::TrackParameters* Trk::Extrapolator::extrapolate(const IPropagator& prop,
                 const TrackParameters& parm,
                 const std::vector< MaterialEffectsOnTrack >& sfMeff,
                 const TrackingVolume& tvol,
                 PropDirection dir,
                 ParticleHypothesis particle,
                 MaterialUpdateMode matupmode) const
{


  // statistics && sequence output ----------------------------------------
  if (m_methodSequence) ++ m_methodSequence;
  ATH_MSG_DEBUG( "D-[" << m_methodSequence << "] extrapolate with given MaterialEffectsOnTrack in Volume '" << tvol.volumeName() << "'." ); 

  const Trk::TrackParameters* fallbackParameters  = 0;
  const Trk::TrackParameters* nextParameters      = &parm;
  
  // loop over the provided material effects on track   
  std::vector< MaterialEffectsOnTrack >::const_iterator sfMeffI = sfMeff.begin();
  std::vector< MaterialEffectsOnTrack >::const_iterator sfMeffE = sfMeff.end();

  for( ; sfMeffI != sfMeffE; ++sfMeffI) {
    // first propagate to the given surface
    //nextParameters = prop.propagate(*nextParameters, sfMeffI->associatedSurface(),dir,true,tvol, particle);
    nextParameters = prop.propagate(*nextParameters, sfMeffI->associatedSurface(),dir,true,m_fieldProperties, particle,false,&tvol);
    // user might have not calculated well which surfaces are intersected ... break if break
    if (!nextParameters) return fallbackParameters;
    throwIntoGarbageBin(nextParameters);
    // the fallback parameters
    fallbackParameters = nextParameters;
    //then update 
    const IMaterialEffectsUpdator* currentUpdator = subMaterialEffectsUpdator(tvol); 
    const Trk::TrackParameters* upnext = currentUpdator ? currentUpdator->update(nextParameters,*sfMeffI,particle,matupmode) : 0; 
    if (!upnext){        
      // update killed the track or config problem. Return
        ATH_MSG_VERBOSE("  [+] Update killed track.");
      break;
    } else if ( upnext != nextParameters ) throwIntoGarbageBin(upnext);
    nextParameters = upnext;
  }  
  return fallbackParameters;
}

const std::vector<const Trk::TrackParameters*>* Trk::Extrapolator::extrapolateBlindly(
                                                                  const IPropagator& prop,
                                                                  const Trk::TrackParameters& parm,
                                                                  Trk::PropDirection dir,
                                                                  Trk::BoundaryCheck bcheck,
                                                                  Trk::ParticleHypothesis particle,
                                                                  const Trk::Volume* boundaryVol) const
{
  
   // statistics && sequence output ----------------------------------------
   ++m_extrapolateBlindlyCalls; 
   ++m_methodSequence;
   ATH_MSG_DEBUG( "F-[" << m_methodSequence << "] extrapolateBlindly() " );
   // assign the boundaryVolume
   m_boundaryVolume = boundaryVol;      
   // initialize the return parameters vector
   Trk::TrackParametersVector* returnParameters = 0;
   // create a new internal helper vector
   m_parametersOnDetElements = new std::vector<const Trk::TrackParameters*>;
   // run the extrapolation    
   const Trk::TrackParameters* parameterOnSf = extrapolate(prop, parm, *s_referenceSurface, dir, bcheck, particle);
   // delete them if necessary
   if (parameterOnSf && parameterOnSf != (&parm)) delete parameterOnSf;
   // assign the return parameter and set m_parametersOnDetElements = 0;
   returnParameters = m_parametersOnDetElements; m_parametersOnDetElements = 0; 
   // reset the boundary Volume
   m_boundaryVolume = 0; 
   // return what you have
   return returnParameters;
}

std::pair<const Trk::TrackParameters*,const Trk::Layer*> Trk::Extrapolator::extrapolateToNextActiveLayer(
                                                        const IPropagator& prop,
                                                        const Trk::TrackParameters& parm,
                                                        PropDirection dir,
                                                        BoundaryCheck bcheck,
                                                        ParticleHypothesis particle,
                                                        MaterialUpdateMode matupmode) const
{
   // statistics && sequence output ----------------------------------------   
   ++m_methodSequence;
   ATH_MSG_DEBUG( "M-[" << m_methodSequence << "] extrapolateToNextActiveLayer(...) " );
   // initialize the return parameters vector
   const Trk::TrackParameters* currPar = &parm;
   const Trk::TrackingVolume*  staticVol = 0;
   const Trk::Surface*         destSurface = 0;
   const Trk::Layer*           assocLayer = 0;

   // -----------------------------------------------------------------------
   // 
   while ( currPar ) {
     //staticVol =  m_navigator->trackingGeometry()->lowestStaticTrackingVolume(currPar->position());    
     assocLayer = 0;
     const Trk::TrackParameters* nextPar =
                    extrapolateToNextMaterialLayer(prop,
                                                  *currPar,
                                                  destSurface,
                                                  staticVol,
                                                  dir,
                                                  bcheck,
                                                  particle,
                                                  matupmode);   
     if (nextPar) { 
         if (m_lastMaterialLayer && m_lastMaterialLayer->surfaceRepresentation().isOnSurface(nextPar->position(),bcheck,m_tolerance,m_tolerance) )
              assocLayer = m_lastMaterialLayer;
	 if (!assocLayer) 
	   ATH_MSG_ERROR( "  [!] No associated layer found  -   at " << positionOutput(nextPar->position()) );
     } else {
       // static volume boundary ?
       if (m_parametersAtBoundary.nextParameters && m_parametersAtBoundary.nextVolume) {
        if (m_parametersAtBoundary.nextVolume->geometrySignature()==Trk::MS ||
	    ( m_parametersAtBoundary.nextVolume->geometrySignature()==Trk::Calo && m_useDenseVolumeDescription )) {
          staticVol = m_parametersAtBoundary.nextVolume;
          nextPar = m_parametersAtBoundary.nextParameters;
          ATH_MSG_DEBUG( "  [+] Static volume boundary: continue loop over active layers in '" 
              << staticVol->volumeName() << "'.");
        } else {   // MSentrance
          nextPar = m_parametersAtBoundary.nextParameters->clone();
          m_parametersAtBoundary.resetBoundaryInformation();
          return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(nextPar,0);          
        }
       } else if (m_parametersAtBoundary.nextParameters ) { // outer boundary
        nextPar = m_parametersAtBoundary.nextParameters->clone();
        m_parametersAtBoundary.resetBoundaryInformation();
        return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(nextPar,0);          
       }
     }
     currPar = nextPar;
     if (currPar && assocLayer && assocLayer->layerType()!=0 ) break;
   }
   // reset the boundary information
   m_parametersAtBoundary.resetBoundaryInformation();
   return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(currPar,assocLayer); 

}

std::pair<const Trk::TrackParameters*,const Trk::Layer*> Trk::Extrapolator::extrapolateToNextActiveLayerM(
                       const IPropagator& prop,
                       const Trk::TrackParameters& parm,
                       PropDirection dir,
                       BoundaryCheck bcheck,
                       std::vector<const Trk::TrackStateOnSurface*>& material,
                       ParticleHypothesis particle,
                       MaterialUpdateMode matupmode) const
{
    
   ATH_MSG_DEBUG( "M-[" << ++m_methodSequence << "] extrapolateToNextActiveLayerM(...) " );
   // initialize the return parameters vector
   const Trk::TrackParameters* currPar = &parm;
   const Trk::TrackingVolume*  staticVol = 0;
   const Trk::Surface*         destSurface = 0;
   const Trk::Layer*           assocLayer = 0;
   // initialize material collection
   m_matstates = &material;

   while ( currPar ) {
     //staticVol =  m_navigator->trackingGeometry()->lowestStaticTrackingVolume(currPar->position());    
     assocLayer = 0;
     const Trk::TrackParameters* nextPar =
       extrapolateToNextMaterialLayer(prop,
                                      *currPar,
                                      destSurface,
                                      staticVol,
                                      dir,
                                      bcheck,
                                      particle,
                                      matupmode);   
     if (nextPar) { 
         if (m_lastMaterialLayer && m_lastMaterialLayer->surfaceRepresentation().isOnSurface(nextPar->position(),bcheck,m_tolerance,m_tolerance) )
          assocLayer = m_lastMaterialLayer;
        if (!assocLayer)  
            ATH_MSG_ERROR( "  [!] No associated layer found  -   at " << positionOutput(nextPar->position()) );
     } else {
       // static volume boundary ?
       if (m_parametersAtBoundary.nextParameters && m_parametersAtBoundary.nextVolume) {
        if (m_parametersAtBoundary.nextVolume->geometrySignature()==Trk::MS ||
            (m_parametersAtBoundary.nextVolume->geometrySignature()==Trk::Calo && m_useDenseVolumeDescription)) {
          staticVol = m_parametersAtBoundary.nextVolume;
          nextPar = m_parametersAtBoundary.nextParameters;
          ATH_MSG_DEBUG( "  [+] Static volume boundary: continue loop over active layers in '" 
              << staticVol->volumeName() << "'.");
        } else {   // MSentrance
          nextPar = m_parametersAtBoundary.nextParameters->clone();
          m_parametersAtBoundary.resetBoundaryInformation();
          return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(nextPar,0);          
        }
       } else if (m_parametersAtBoundary.nextParameters ) { // outer boundary
         nextPar = m_parametersAtBoundary.nextParameters->clone();
        m_parametersAtBoundary.resetBoundaryInformation();
        return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(nextPar,0);          
       }

     }
     currPar = nextPar;
     if (currPar && assocLayer && assocLayer->layerType()!=0 ) break;
   }
   // reset the boundary information
   m_parametersAtBoundary.resetBoundaryInformation();
   m_matstates = 0;   
   m_methodSequence = 0;
   return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(currPar,assocLayer); 
}

const Trk::TrackParameters* Trk::Extrapolator::extrapolateToNextMaterialLayer(const IPropagator& prop,
                        const Trk::TrackParameters& parm,
                        const Trk::Surface* destSurf, 
                        const Trk::TrackingVolume* vol,
                        PropDirection dir,
                        BoundaryCheck bcheck,
                        ParticleHypothesis particle,
                        MaterialUpdateMode matupmode) const
{
  ATH_MSG_DEBUG( "M-[" << ++m_methodSequence << "] extrapolateToNextMaterialLayer(...) " );
 
  // this is the core of the material loop 
  // extrapolation without target surface returns:
  //    A)    trPar at next material layer
  //    B)    boundary parameters (static volume boundary)
  // if target surface:
  //    C)    trPar at target surface
  //
  
  // initialize the return parameters vector
  const Trk::TrackParameters* returnParameters = 0;
  const Trk::TrackParameters* currPar = &parm;
  const Trk::TrackingVolume*  staticVol = 0;
  const Trk::TrackingVolume*  currVol = 0;
  const Trk::TrackingVolume*  nextVol = 0;
  std::vector<unsigned int> solutions;
  const Trk::TrackingVolume* assocVol = 0;  
  //double tol = 0.001;
  double path = 0.;
  bool resolveActive = destSurf ? false : true;
  if (!resolveActive && m_resolveActive ) resolveActive = m_resolveActive;
  if ( m_lastMaterialLayer && !m_lastMaterialLayer->isOnLayer(parm.position()) ) m_lastMaterialLayer = 0;  
  if (!m_highestVolume ) m_highestVolume = m_navigator->highestVolume();

  emptyGarbageBin(&parm);
    
  // resolve current position
  Amg::Vector3D gp = parm.position();
  if ( vol && vol->inside(gp,m_tolerance) ) {
    staticVol = vol; 
  } else {
    staticVol =  m_navigator->trackingGeometry()->lowestStaticTrackingVolume(gp);    
    const Trk::TrackingVolume* nextStatVol = 0;
    if ( m_navigator->atVolumeBoundary(currPar,staticVol,dir,nextStatVol,m_tolerance) && nextStatVol != staticVol ) 
      staticVol = nextStatVol;
  }

  // navigation surfaces
  if( m_navigSurfs.capacity() > m_maxNavigSurf ) m_navigSurfs.reserve(m_maxNavigSurf); 
  m_navigSurfs.clear();

  if (destSurf) m_navigSurfs.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(destSurf,false));

  // alignable frame volume ?
  if ( staticVol && staticVol->geometrySignature()==Trk::Calo ) {
    const Trk::AlignableTrackingVolume* alignTV = dynamic_cast<const Trk::AlignableTrackingVolume*> (staticVol);
    if (alignTV) {
      m_identifiedParameters = 0;
      return extrapolateInAlignableTV(prop,*currPar,destSurf,alignTV,dir,particle);
    }
  }
  
  // update if new static volume
  if ( staticVol && ( staticVol!=m_currentStatic || resolveActive!=m_resolveActive ) ) {    // retrieve boundaries
    m_currentStatic = staticVol;
    m_staticBoundaries.clear();
    const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds = staticVol->boundarySurfaces();
    for (unsigned int ib=0; ib< bounds.size(); ib++ ){
      const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
      m_staticBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
    }

    m_detachedVols.clear();
    m_detachedBoundaries.clear();
    m_denseVols.clear();
    m_denseBoundaries.clear();
    m_layers.clear();
    m_navigLays.clear();

    const std::vector<const Trk::DetachedTrackingVolume*>* detVols = staticVol->confinedDetachedVolumes();
    if (detVols ) {
      std::vector<const Trk::DetachedTrackingVolume*>::const_iterator iTer = detVols->begin();
      for (; iTer != detVols->end(); iTer++) { 
        // active station ?
        const Trk::Layer* layR = (*iTer)->layerRepresentation();
        bool active = ( layR && layR->layerType() ) ? true : false;
         const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > >  detBounds=
         (*iTer)->trackingVolume()->boundarySurfaces();
        if (active) {
          if ( resolveActive ) {
           m_detachedVols.push_back(std::pair<const Trk::DetachedTrackingVolume*,unsigned int> (*iTer,detBounds.size()) );
           for (unsigned int ibb=0; ibb< detBounds.size(); ibb++ ){
             const Trk::Surface& surf = (detBounds[ibb].getPtr())->surfaceRepresentation();
             m_detachedBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
           }
          } else {
	    if (!m_resolveMultilayers || !(*iTer)->multilayerRepresentation() ) {
	      m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&(layR->surfaceRepresentation()),true));
	      m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> ((*iTer)->trackingVolume(),layR));
            } else {
              const std::vector<const Trk::Layer*>* multi = (*iTer)->multilayerRepresentation();
              for (unsigned int i=0;i<multi->size();i++) {
		m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&((*multi)[i]->surfaceRepresentation()),true));
		m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> ((*iTer)->trackingVolume(),(*multi)[i]));
	      }
	    }
          }
	} else if (staticVol->geometrySignature()!=Trk::MS ||
		   !m_useMuonMatApprox || (*iTer)->name().substr((*iTer)->name().size()-4,4)=="PERM" ) {  // retrieve inert detached objects only if needed
          if ((*iTer)->trackingVolume()->zOverAtimesRho()!=0. && 
	      (!(*iTer)->trackingVolume()->confinedDenseVolumes() || !(*iTer)->trackingVolume()->confinedDenseVolumes()->size() )
	      && ( !(*iTer)->trackingVolume()->confinedArbitraryLayers() ||
                   !(*iTer)->trackingVolume()->confinedArbitraryLayers()->size() ) ) {
            m_denseVols.push_back(std::pair<const Trk::TrackingVolume*,unsigned int> 
				  ((*iTer)->trackingVolume(),detBounds.size() ) );
	    for (unsigned int ibb=0; ibb< detBounds.size(); ibb++ ){
	      const Trk::Surface& surf = (detBounds[ibb].getPtr())->surfaceRepresentation();
	      m_denseBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
	    }
	  } 
          const std::vector<const Trk::Layer*>* confLays = (*iTer)->trackingVolume()->confinedArbitraryLayers(); 
	  if ( (*iTer)->trackingVolume()->confinedDenseVolumes() || (confLays && confLays->size()> detBounds.size()) ) {
            m_detachedVols.push_back(std::pair<const Trk::DetachedTrackingVolume*,unsigned int>(*iTer,detBounds.size()));
	    for (unsigned int ibb=0; ibb< detBounds.size(); ibb++ ){
	      const Trk::Surface& surf = (detBounds[ibb].getPtr())->surfaceRepresentation();
	      m_detachedBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
	    }
          } else if ( confLays ) {
	    std::vector<const Trk::Layer*>::const_iterator lIt = confLays->begin();
	    for ( ; lIt!= confLays->end(); lIt++ ){
	      m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&((*lIt)->surfaceRepresentation()),true) );
	      m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> ((*iTer)->trackingVolume(),*lIt) );
	    }            
	  }         
	}
      }
    }
    m_denseResolved    = std::pair<unsigned int,unsigned int> (m_denseVols.size(), m_denseBoundaries.size());
    m_layerResolved    = m_layers.size();
  } 
  
  m_navigSurfs.insert(m_navigSurfs.end(),m_staticBoundaries.begin(),m_staticBoundaries.end());

  // resolve the use of dense volumes
  m_dense = (staticVol->geometrySignature()==Trk::MS && m_useMuonMatApprox ) || (staticVol->geometrySignature()!=Trk::MS && m_useDenseVolumeDescription );
    
  while (currPar && staticVol && !staticVol->confinedDetachedVolumes() ) {
    // propagate to closest surface
    solutions.resize(0);
    const Trk::TrackingVolume* propagVol = m_dense ? staticVol : m_highestVolume; 
    ATH_MSG_DEBUG( "  [+] Starting propagation (static)  at " << positionOutput(currPar->position()) 
        << " in '" << propagVol->volumeName() << "'") ;
    // current static may carry non-trivial material properties, their use is optional; 
    // use highest volume as B field source 
    //const Trk::TrackParameters* nextPar = prop.propagate(*currPar,m_navigSurfs,dir,*propagVol,particle,solutions,path);
    const Trk::TrackParameters* nextPar = prop.propagate(*currPar,m_navigSurfs,dir, m_fieldProperties,particle,solutions,path,false,false,propagVol);
    ATH_MSG_VERBOSE( "  [+] Propagation done" ); 
    if (nextPar) 
        ATH_MSG_DEBUG( "  [+] Position after propagation -   at " << positionOutput(nextPar->position())); 
    if (!nextPar) { m_parametersAtBoundary.resetBoundaryInformation(); return returnParameters; }         
    if (nextPar) {    
      // collect material
      if (propagVol->zOverAtimesRho() != 0. &&  !m_matstates && m_extrapolationCache) {     
        if(checkCache(" extrapolateToNextMaterialLayer" )) {
          if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer");
  	  double dInX0 = fabs(path)/propagVol->x0();    
          ATH_MSG_DEBUG(" add x0 " << dInX0); 
          m_extrapolationCache->updateX0(dInX0);
	  Trk::MaterialProperties materialProperties(*propagVol, fabs(path));
	  double currentqoverp=nextPar->parameters()[Trk::qOverP];
	  Trk::EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1.,dir,particle);
	  ATH_MSG_DEBUG( "  [M] Energy loss: STEP,EnergyLossUpdator:" 
               << nextPar->momentum().mag()-currPar->momentum().mag() << ","<< eloss->deltaE() );
          m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
          if(m_dumpCache) dumpCache(" After");
          delete eloss;
        }
      }
      if (propagVol->zOverAtimesRho() != 0. &&  m_matstates ) {     
	double dInX0 = fabs(path)/propagVol->x0();    
     	
	Trk::MaterialProperties materialProperties(*propagVol, fabs(path));

        double scatsigma=sqrt(m_msupdators[0]->sigmaSquare(materialProperties,1./fabs(nextPar->parameters()[qOverP]),1.,particle));
        Trk::ScatteringAngles *newsa=new Trk::ScatteringAngles(0,0,scatsigma/sin(nextPar->parameters()[Trk::theta]),scatsigma);
	//energy loss
	double currentqoverp=nextPar->parameters()[Trk::qOverP];
	Trk::EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1.,
							       dir,particle);
	// compare energy loss 
	ATH_MSG_DEBUG( "  [M] Energy loss: STEP,EnergyLossUpdator:" 
            << nextPar->momentum().mag()-currPar->momentum().mag() << ","<< eloss->deltaE() );
        // adjust energy loss ?
        // double adj = (particle!=nonInteracting && particle!=nonInteractingMuon && fabs(eloss0->deltaE())> 0.) ?
	//                   (nextPar->momentum().mag()-currPar->momentum().mag())/eloss0->deltaE() : 1.;
	//Trk::EnergyLoss* eloss = new Trk::EnergyLoss(adj*eloss0->deltaE(),adj*eloss0->sigmaDeltaE()); 
        //delete eloss0;

	// use curvilinear TPs to simplify retrieval by fitters
	Trk::CurvilinearParameters* cvlTP = new Trk::CurvilinearParameters(nextPar->position(),nextPar->momentum(),nextPar->charge());
	Trk::MaterialEffectsOnTrack* mefot =  new Trk::MaterialEffectsOnTrack(dInX0,newsa,eloss,cvlTP->associatedSurface());   
	m_matstates->push_back(new TrackStateOnSurface(0,cvlTP,0,mefot));
        if(m_extrapolationCache) {
              if(m_dumpCache) dumpCache(" mat states extrapolateToNextMaterialLayer");
              m_extrapolationCache->updateX0(dInX0);
              m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
              if(m_dumpCache) dumpCache(" After");
	}
	ATH_MSG_DEBUG("  [M] Collecting material from static volume '"<<propagVol->volumeName()<< "', t/X0 = " << dInX0);
      }
    }
    throwIntoGarbageBin(nextPar);
    currPar = nextPar;
    unsigned int isurf = destSurf ? 1 : 0 ; 
    if (destSurf && solutions[0]==0) return nextPar->clone();
    if (destSurf && solutions.size()>1 && solutions[1]==0) return nextPar->clone();
    if (solutions[0] <= isurf + m_staticBoundaries.size() ) {  // static volume boundary
      // use global coordinates to retrieve attached volume (just for static!)
      const Trk::TrackingVolume* nextVol = 
  m_currentStatic->boundarySurfaces()[solutions[0]-isurf].getPtr()->attachedVolume(nextPar->position(),nextPar->momentum(),dir) ;
      m_parametersAtBoundary.boundaryInformation(nextVol,currPar,currPar);
      if ( !nextVol ) ATH_MSG_DEBUG( "  [!] World boundary at position R,z: "  << nextPar->position().perp()<<"," << nextPar->position().z());
      else {
         ATH_MSG_DEBUG( "M-S Crossing to static volume '"<< nextVol->volumeName() << "'.'");  
      }
    }
    return returnParameters;
  }  
 
  if (!staticVol || (!staticVol->confinedDetachedVolumes()) || !currPar ) {
    return returnParameters;
  }

  // reset remaining counters
  m_currentDense = m_dense ?  m_currentStatic : m_highestVolume;
  m_navigBoundaries.clear(); 
1360
1361
1362
1363
  if (m_denseVols.size()>m_denseResolved.first) m_denseVols.resize(m_denseResolved.first);
  while (m_denseBoundaries.size()>m_denseResolved.second) m_denseBoundaries.pop_back();
  if (m_layers.size()>m_layerResolved)  m_navigLays.resize(m_layerResolved);
  while (m_layers.size()>m_layerResolved) m_layers.pop_back();
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614

  // current detached volumes
  // collect : subvolume boundaries, ordered/unordered layers, confined dense volumes
  ////////////////////////////////////////////////////// 
  //const Trk::DetachedTrackingVolume* currentActive = 0;
  if( m_navigVolsInt.capacity() > m_maxNavigVol ) m_navigVolsInt.reserve(m_maxNavigVol); 
  m_navigVolsInt.clear();

  gp = currPar->position();    
  std::vector<const Trk::DetachedTrackingVolume*>* detVols =  m_navigator->trackingGeometry()->lowestDetachedTrackingVolumes(gp);    
  std::vector<const Trk::DetachedTrackingVolume*>::iterator dIter = detVols->begin();
  for (; dIter != detVols->end(); dIter++) {
    const Trk::Layer* layR = (*dIter)->layerRepresentation();
    bool active = ( layR && layR->layerType() ) ? true : false;
    if (active && !resolveActive) continue; 
    if (!active && staticVol->geometrySignature()==Trk::MS && m_useMuonMatApprox && (*dIter)->name().substr((*dIter)->name().size()-4,4)!="PERM") continue;
    const Trk::TrackingVolume* dVol = (*dIter)->trackingVolume();
    // detached volume exit ?
    bool dExit =  m_navigator->atVolumeBoundary(currPar,dVol,dir,nextVol,m_tolerance) && !nextVol;
    if (dExit) continue;
    // inert material 
    const std::vector<const Trk::TrackingVolume*>* confinedDense = dVol->confinedDenseVolumes();
    const std::vector<const Trk::Layer*>*          confinedLays  = dVol->confinedArbitraryLayers();
    
    if (!active && !confinedDense && !confinedLays) continue; 
    const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds=dVol->boundarySurfaces();
    if (!active && !confinedDense && confinedLays->size()<= bounds.size()) continue;
    if (confinedDense || confinedLays ) {
      m_navigVolsInt.push_back(std::pair<const Trk::TrackingVolume*,unsigned int> (dVol,bounds.size()) );
      for (unsigned int ib=0; ib< bounds.size(); ib++ ){
	const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
	m_navigBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
      }
      // collect dense volume boundary
      if (confinedDense) {
	std::vector<const Trk::TrackingVolume*>::const_iterator vIter = confinedDense->begin();
	for (; vIter != confinedDense->end(); vIter++) {
	  const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds=
	    (*vIter)->boundarySurfaces();
	  m_denseVols.push_back(std::pair<const Trk::TrackingVolume*,unsigned int> (*vIter,bounds.size()) );
	  for (unsigned int ib=0; ib< bounds.size(); ib++ ){
	    const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
	    m_denseBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
	  }
	}
      }
      // collect unordered layers
      if (confinedLays) {
	for (unsigned int il = 0; il < confinedLays->size(); il++) {
	  m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&((*confinedLays)[il]->surfaceRepresentation()),true));   
	  m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> (dVol,(*confinedLays)[il]) );
	}    
      }
    } else {   // active material
      const Trk::TrackingVolume* detVol= dVol->associatedSubVolume(gp);
      if ( !detVol && dVol->confinedVolumes()) {
	std::vector<const Trk::TrackingVolume*> subvols = dVol->confinedVolumes()->arrayObjects();
	for (unsigned int iv=0;iv<subvols.size();iv++) {
	  if ( subvols[iv]->inside(gp,m_tolerance) ) {
	    detVol = subvols[iv]; 
	    break;
	  }
	}
      }
      
      if (!detVol) detVol = dVol;
      bool vExit =  m_navigator->atVolumeBoundary(currPar,detVol,dir,nextVol,m_tolerance) && nextVol!=detVol;
      if ( vExit && nextVol && nextVol->inside(gp,m_tolerance)) { detVol = nextVol; vExit = false; } 
      if ( !vExit ) {
	const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds= detVol->boundarySurfaces();
	m_navigVolsInt.push_back(std::pair<const Trk::TrackingVolume*,unsigned int> (detVol,bounds.size()) );
	for (unsigned int ib=0; ib< bounds.size(); ib++ ){
	  const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
	  m_navigBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
	}
	if ( detVol->zOverAtimesRho() != 0.) {
	  m_denseVols.push_back(std::pair<const Trk::TrackingVolume*,unsigned int> (detVol,bounds.size()) );
	  for (unsigned int ib=0; ib< bounds.size(); ib++ ){
	    const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
	    m_denseBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
	  }
	} 
	// layers ?
	if ( detVol->confinedLayers() ) {
	  const Trk::Layer* lay = detVol->associatedLayer(gp);
	  //if (lay && ( (*dIter)->layerRepresentation()
	  //	       &&(*dIter)->layerRepresentation()->layerType()>0 ) ) currentActive=(*dIter);  
	  if (lay) {
	    m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&(lay->surfaceRepresentation()),true));
	    m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> (detVol,lay) );
	  }
	  const Trk::Layer* nextLayer = detVol->nextLayer(currPar->position(),dir*currPar->momentum().unit(),true);      
	  if (nextLayer && nextLayer != lay ) {
	    m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&(nextLayer->surfaceRepresentation()),true));
	    m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> (detVol,nextLayer) );
	  }
	} else if ( detVol->confinedArbitraryLayers() ) {
	  const std::vector<const Trk::Layer*>* layers = detVol->confinedArbitraryLayers();
	  for (unsigned int il = 0; il < layers->size(); il++) {
	    m_layers.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&((*layers)[il]->surfaceRepresentation()),true));   
	    m_navigLays.push_back(std::pair<const Trk::TrackingVolume*,const Trk::Layer*> (detVol,(*layers)[il]) );
	  }    
	}
      }
    }
  }
  delete detVols;    
   
  // m_navigSurfs contains destination surface (if it exists), static volume boundaries  
  // complete with TG m_layers/dynamic layers, m_denseBoundaries, m_navigBoundaries, m_detachedBoundaries

  if (m_layers.size()) m_navigSurfs.insert(m_navigSurfs.end(),m_layers.begin(),m_layers.end());
  if (m_denseBoundaries.size()) m_navigSurfs.insert(m_navigSurfs.end(),m_denseBoundaries.begin(),m_denseBoundaries.end());
  if (m_navigBoundaries.size()) m_navigSurfs.insert(m_navigSurfs.end(),m_navigBoundaries.begin(),m_navigBoundaries.end());
  if (m_detachedBoundaries.size()) m_navigSurfs.insert(m_navigSurfs.end(),m_detachedBoundaries.begin(),m_detachedBoundaries.end());

  /*
  bool detachedBoundariesIncluded = false;
  if (!m_doMuonDynamic && (m_activeOverlap || !currentActive) ) {
    if (m_detachedBoundaries.size()) m_navigSurfs.insert(m_navigSurfs.end(),m_detachedBoundaries.begin(),m_detachedBoundaries.end());
    detachedBoundariesIncluded = true;
  } 
  */

  // current dense
  m_currentDense =  m_highestVolume;
  if (m_dense && !m_denseVols.size()) m_currentDense = m_currentStatic;
  else {
    for (unsigned int i=0;i<m_denseVols.size(); i++) {
      const Trk::TrackingVolume* dVol = m_denseVols[i].first;
      if ( dVol->inside(currPar->position(),m_tolerance)  && dVol->zOverAtimesRho()!=0. ) {
         if ( !m_navigator->atVolumeBoundary(currPar,dVol,dir,nextVol,m_tolerance) || nextVol == dVol ) m_currentDense = dVol;
      } 
    }
  }
   
  // ready to propagate      
  // till: A/ static volume boundary(bcheck=true) , B/ material layer(bcheck=true), C/ destination surface(bcheck=false)
  // update of m_navigSurfs required if I/ entry into new navig volume, II/ exit from currentActive without overlaps
   
   nextVol = 0;
   while (currPar) {      
     double path=0.;
     std::vector<unsigned int> solutions;
     // verify that material input makes sense
     Amg::Vector3D tp = currPar->position()+2*m_tolerance*dir*currPar->momentum().normalized();
     if (!(m_currentDense->inside(tp,0.)) ) { 
       m_currentDense =  m_highestVolume;
       if (m_dense && !m_denseVols.size()) m_currentDense = m_currentStatic;
       else {
	 for (unsigned int i=0;i<m_denseVols.size(); i++) {
	   const Trk::TrackingVolume* dVol = m_denseVols[i].first;
	   if ( dVol->inside(tp,0.)  && dVol->zOverAtimesRho()!=0. ) m_currentDense = dVol;
	 }
       }
     } 
     // propagate now
     ATH_MSG_DEBUG( "  [+] Starting propagation at position  " << positionOutput(currPar->position())  
         << " (current momentum: " << currPar->momentum().mag() << ")" ); 
     ATH_MSG_DEBUG( "  [+] " << m_navigSurfs.size() << " target surfaces in '" << m_currentDense->volumeName() <<"'.");   
     //const Trk::TrackParameters* nextPar = prop.propagate(*currPar,m_navigSurfs,dir,*m_currentDense,particle,solutions,path);
     const Trk::TrackParameters* nextPar = prop.propagate(*currPar,m_navigSurfs,dir, m_fieldProperties,particle,solutions,path,false,false,m_currentDense);
     ATH_MSG_VERBOSE( "  [+] Propagation done. " ); 
     if (nextPar)  
        ATH_MSG_DEBUG( "  [+] Position after propagation -   at " << positionOutput(nextPar->position())); 
     // check missing volume boundary
     if (nextPar && !(m_currentDense->inside(nextPar->position(),m_tolerance)
		      || m_navigator->atVolumeBoundary(nextPar,m_currentDense,dir,assocVol,m_tolerance) ) ) {
       ATH_MSG_DEBUG( "  [!] ERROR: missing volume boundary for volume"<< m_currentDense->volumeName() );
       if ( m_currentDense->zOverAtimesRho() != 0.) {     
         ATH_MSG_DEBUG( "  [!] ERROR: trying to recover: repeat the propagation step in"<< m_highestVolume->volumeName() );
         m_currentDense = m_highestVolume;
         delete nextPar;
         continue;
       }
     }
     if (nextPar)  ATH_MSG_DEBUG( "  [+] Number of intersection solutions: " << solutions.size() );
     if (nextPar) throwIntoGarbageBin(nextPar);
     if (nextPar) {    
       if (m_currentDense->zOverAtimesRho() != 0. &&  !m_matstates && m_extrapolationCache) {     
         if(checkCache( " extrapolateToNextMaterialLayer dense")) {
           if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer dense ");
           double dInX0 = fabs(path)/m_currentDense->x0();  
           m_extrapolationCache->updateX0(dInX0);
	   Trk::MaterialProperties materialProperties(*m_currentDense, fabs(path) );
           double currentqoverp=nextPar->parameters()[Trk::qOverP];
           Trk::EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1.,dir,particle);
            m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
           if(m_dumpCache) dumpCache(" After");
           delete eloss;
         }
       }
       // collect material
       if ( m_currentDense->zOverAtimesRho() != 0. && m_matstates) {     
        double dInX0 = fabs(path)/m_currentDense->x0();  
	if( path*dir < 0. ) ATH_MSG_WARNING(" got negative path!! " << path );
	Trk::MaterialProperties materialProperties(*m_currentDense, fabs(path) );
         double scatsigma=sqrt(m_msupdators[0]->sigmaSquare(materialProperties,1./fabs(nextPar->parameters()[qOverP]),1.,particle));
         Trk::ScatteringAngles *newsa=new Trk::ScatteringAngles(0,0,scatsigma/sin(nextPar->parameters()[Trk::theta]),scatsigma);   
        //energy loss
        double currentqoverp=nextPar->parameters()[Trk::qOverP];
        Trk::EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1.,
                                                                       dir,particle);
        // compare energy loss 
	ATH_MSG_DEBUG( "  [M] Energy loss: STEP,EnergyLossUpdator:" 
            << nextPar->momentum().mag()-currPar->momentum().mag() << ","<< eloss->deltaE() );
    
        // adjust energy loss ? 
	// double adj = (particle!=nonInteracting && particle!=nonInteractingMuon && fabs(eloss0->deltaE())>0) ? (nextPar->momentum().mag()-currPar->momentum().mag())/eloss0->deltaE() : 1;
	// Trk::EnergyLoss* eloss = new Trk::EnergyLoss(adj*eloss0->deltaE(),adj*eloss0->sigmaDeltaE()); 
        // delete eloss0;
         
        // use curvilinear TPs to simplify retrieval by fitters
	Trk::CurvilinearParameters* cvlTP = new Trk::CurvilinearParameters(nextPar->position(),nextPar->momentum(),nextPar->charge());
      	Trk::MaterialEffectsOnTrack* mefot = new Trk::MaterialEffectsOnTrack(dInX0,newsa,eloss,cvlTP->associatedSurface());           
        m_matstates->push_back(new TrackStateOnSurface(0,cvlTP,0,mefot));
        if(m_extrapolationCache) {
              if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer dense");
              m_extrapolationCache->updateX0(dInX0);
              m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
              if(m_dumpCache) dumpCache(" After");
	}
        ATH_MSG_DEBUG("  [M] Collecting material from dense volume '" 
            << m_currentDense->volumeName()<< "', t/X0 = " << dInX0);
       }
       // destination surface
       if (destSurf && solutions[0]==0 ) return nextPar->clone();
       if (destSurf && solutions.size()>1 && solutions[1]==0 ) return nextPar->clone();
       // destination surface missed ? 
       if (destSurf) {
        double dist = 0.;
        Trk::DistanceSolution distSol = destSurf->straightLineDistanceEstimate(nextPar->position(),
                                                                                          nextPar->momentum().normalized());
        if (distSol.numberOfSolutions()>0 ) {
          dist = distSol.first();
          if ( distSol.numberOfSolutions()>1 && fabs(dist) < m_tolerance ) dist = distSol.second();
          if ( distSol.numberOfSolutions()>1 && dist*dir < 0. && distSol.second()*dir > 0. ) dist = distSol.second();    
         } else {
           dist = distSol.toPointOfClosestApproach();
         } 
        if (dist*dir < 0.) {
          ATH_MSG_DEBUG( "  [+] Destination surface missed ? "<< dist << "," << dir );
          m_parametersAtBoundary.resetBoundaryInformation();
          return returnParameters;
        }
        ATH_MSG_DEBUG( "  [+] New 3D-distance to destinatiion    - d3 = " << dist*dir ); 
       }
       
       int iDest = destSurf ? 1 : 0;
       unsigned int iSol  = 0;
       while ( iSol < solutions.size() ) {         
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
	 if ( solutions[iSol] < iDest + m_staticBoundaries.size() ) {
	   
	   // material attached ?
	   const Trk::Layer*  mb =  m_navigSurfs[solutions[iSol]].first->materialLayer();  
	   if (mb) {
	     if (mb->layerMaterialProperties() && mb->layerMaterialProperties()->fullMaterial(nextPar->position()) ) {
	       
	       const IMaterialEffectsUpdator* currentUpdator = subMaterialEffectsUpdator(*m_currentStatic);
	       if ( currentUpdator)  {
		 const Trk::TrackParameters* upNext = currentUpdator->update(nextPar, *mb, dir, particle, matupmode);
		 if (upNext && upNext!= nextPar ) throwIntoGarbageBin(upNext);
		 nextPar = upNext;
	       }
	       if (!nextPar) {
		 ATH_MSG_VERBOSE( "  [+] Update may have killed track - return." );
		 m_parametersAtBoundary.resetBoundaryInformation();
		 return returnParameters;
	       }
	       
	       // collect material
               const Trk::MaterialProperties* lmat = mb->fullUpdateMaterialProperties(*nextPar);
	       double lx0 = lmat->x0();
	       double layThick = mb->thickness();
            
	       double thick = 0.; 
	       double costr = fabs(nextPar->momentum().normalized().dot(mb->surfaceRepresentation().normal())) ;  
            
	       if ( mb->surfaceRepresentation().isOnSurface(mb->surfaceRepresentation().center(),false,0.,0.) )        
		 thick = fmin(mb->surfaceRepresentation().bounds().r(),
                             layThick/fabs(nextPar->momentum().normalized().dot(mb->surfaceRepresentation().normal())) );
	       else {
		 //const Trk::CylinderBounds* cyl = dynamic_cast<const Trk::CylinderBounds*> (&(nextLayer->surfaceRepresentation().bounds()));
		 //double hmax = cyl ? cyl->halflengthZ() : nextLayer->surfaceRepresentation().bounds().r();
		 thick = fmin(2*mb->thickness(), layThick/(1-costr));                  
	       }

	       if (!m_matstates && m_extrapolationCache) {     
		 if(checkCache(" extrapolateToNextMaterialLayer thin")) {
		   double dInX0 = thick/lx0;    
		   if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer thin ");
		   m_extrapolationCache->updateX0(dInX0);
		   double currentqoverp=nextPar->parameters()[Trk::qOverP];
		   EnergyLoss* eloss = m_elossupdators[0]->energyLoss(*lmat,fabs(1./currentqoverp),1./costr,dir,particle);
		   m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
		   if(m_dumpCache) dumpCache(" After");
		   delete eloss;
		 }
	       }
	       
	       if (m_matstates) {
		 double dInX0 = thick/lx0;    
		 double scatsigma=sqrt(m_msupdators[0]->sigmaSquare(*lmat,1./fabs(nextPar->parameters()[qOverP]),1.,particle));
		 Trk::ScatteringAngles *newsa=new Trk::ScatteringAngles(0,0,scatsigma/sin(nextPar->parameters()[Trk::theta]),scatsigma);
		 //energy loss
		 double currentqoverp=nextPar->parameters()[Trk::qOverP];
		 EnergyLoss* eloss = m_elossupdators[0]->energyLoss(*lmat,fabs(1./currentqoverp),1./costr,dir,particle);
		 
		 // use curvilinear TPs to simplify retrieval by fitters
		 Trk::CurvilinearParameters* cvlTP = new Trk::CurvilinearParameters(nextPar->position(),nextPar->momentum(),nextPar->charge());
		 Trk::MaterialEffectsOnTrack* mefot =  new Trk::MaterialEffectsOnTrack(dInX0,newsa,eloss,cvlTP->associatedSurface());
		 if(m_extrapolationCache) {
		   if(checkCache(" mat states extrapolateToNextMaterialLayer thin" )) {
		     if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer thin");
		     m_extrapolationCache->updateX0(dInX0);
		     m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
		     if(m_dumpCache) dumpCache(" After");
		   }
		 }     
		 m_matstates->push_back(new TrackStateOnSurface(0,cvlTP,0,mefot));
	       }	       
	     }
	   }  // end material update at massive (static volume) boundary	   

1688
1689
1690
           // static volume boundary; return to the main loop 
           unsigned int index = solutions[iSol]-iDest;
           // use global coordinates to retrieve attached volume (just for static!)
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
	   nextVol = (m_currentStatic->boundarySurfaces())[index].getPtr()->attachedVolume(nextPar->position(),nextPar->momentum(),dir);
	   // double check the next volume
	   if ( nextVol && !(nextVol->inside(nextPar->position()+0.01*dir*nextPar->momentum().normalized(),m_tolerance) ) ) {
	     ATH_MSG_DEBUG( "  [!] WARNING: wrongly assigned static volume ?"<< m_currentStatic->volumeName()<<"->" << nextVol->volumeName() );
	     nextVol = m_navigator->trackingGeometry()->lowestStaticTrackingVolume(nextPar->position()+0.01*nextPar->momentum().normalized());
	     if (nextVol) ATH_MSG_DEBUG( "  new search yields: "<< nextVol->volumeName() );          
	   }
	   // end double check - to be removed after validation of the geometry gluing 
	   if (nextVol != m_currentStatic ) {
	     m_parametersAtBoundary.boundaryInformation(nextVol,nextPar,nextPar);         
	     ATH_MSG_DEBUG("  [+] StaticVol boundary reached of '" <<m_currentStatic->volumeName() << "'.");
	     if ( m_navigator->atVolumeBoundary(nextPar,m_currentStatic,dir,assocVol,m_tolerance) && assocVol != m_currentStatic )
	       m_currentDense = m_useMuonMatApprox ? nextVol : m_highestVolume;
	     // no next volume found --- end of the world
	     if ( !nextVol )
	       ATH_MSG_DEBUG( "  [+] Word boundary reached        - at " << positionOutput(nextPar->position()) );
	     // next volume found and parameters are at boundary
	     if ( nextVol && nextPar ){ 
	       ATH_MSG_DEBUG( "  [+] Crossing to next volume '" << nextVol->volumeName() << "'");
	       ATH_MSG_DEBUG( "  [+] Crossing position is         - at " <<  positionOutput(nextPar->position()) );  
	     }     
	     return returnParameters;
	   }
1714
1715
         } else if ( solutions[iSol] < iDest + m_staticBoundaries.size() + m_layers.size() ) {
           // next layer; don't return passive material layers unless required 
1716
	  unsigned int index = solutions[iSol]-iDest-m_staticBoundaries.size();
1717
1718
1719
          const Trk::Layer* nextLayer = m_navigLays[index].second;
          // material update HERE and NOW (pre/post udpdate ? ) 
          // don't repeat if identical to last update && input parameters on the layer
1720
1721
1722
1723
1724
	  bool collect = true;
	  if ( nextLayer == m_lastMaterialLayer &&  nextLayer->surfaceRepresentation().type()!=Trk::Surface::Cylinder ) {
	    ATH_MSG_DEBUG( "  [!] This layer is identical to the one with last material update, return layer without repeating the update" );
	    collect = false;
	    if (!destSurf && (nextLayer->layerType()>0 || m_returnPassiveLayers) ) return nextPar->clone();
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
          }
          double layThick = nextLayer->thickness();
          if (collect && layThick>0.) {                         // collect material
	    // get the right updator
	    const IMaterialEffectsUpdator* currentUpdator = subMaterialEffectsUpdator(*m_currentStatic);
	    const Trk::TrackParameters* upNext = currentUpdator ? currentUpdator->update(nextPar, *nextLayer, dir, particle,matupmode) : nextPar;
	    if (!upNext) {
	      ATH_MSG_VERBOSE( "  [+] Update may have killed track - return." );
	      m_parametersAtBoundary.resetBoundaryInformation();
	      return returnParameters;
	    } else if ( upNext != nextPar ) throwIntoGarbageBin(upNext);

            nextPar = upNext;               
            
            // collect material
            double lx0 = nextLayer->fullUpdateMaterialProperties(*nextPar)->x0();
            
            double thick = 0.;
             double costr = fabs(nextPar->momentum().normalized().dot(nextLayer->surfaceRepresentation().normal())) ;  
            
            if ( nextLayer->surfaceRepresentation().isOnSurface(nextLayer->surfaceRepresentation().center(),false,0.,0.) )        
              thick = fmin(nextLayer->surfaceRepresentation().bounds().r(),
                             layThick/fabs(nextPar->momentum().normalized().dot(nextLayer->surfaceRepresentation().normal())) );
            else {
              //const Trk::CylinderBounds* cyl = dynamic_cast<const Trk::CylinderBounds*> (&(nextLayer->surfaceRepresentation().bounds()));
              //double hmax = cyl ? cyl->halflengthZ() : nextLayer->surfaceRepresentation().bounds().r();
              thick = fmin(2*nextLayer->thickness(), layThick/(1-costr));                  
            }

            if (!m_matstates && m_extrapolationCache) {     
              if(checkCache(" extrapolateToNextMaterialLayer thin")) {
                double dInX0 = thick/lx0;    
                if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer thin ");
                m_extrapolationCache->updateX0(dInX0);
                Trk::MaterialProperties materialProperties(*nextLayer->fullUpdateMaterialProperties(*nextPar)); //!< @TODO check        
                double currentqoverp=nextPar->parameters()[Trk::qOverP];
                EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1./costr,dir,particle);
                m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
                if(m_dumpCache) dumpCache(" After");
                delete eloss;
              }
            }

            if (m_matstates) {
               double dInX0 = thick/lx0;    
               Trk::MaterialProperties materialProperties(*nextLayer->fullUpdateMaterialProperties(*nextPar)); //!< @TODO check        
               double scatsigma=sqrt(m_msupdators[0]->sigmaSquare(materialProperties,1./fabs(nextPar->parameters()[qOverP]),1.,particle));
               Trk::ScatteringAngles *newsa=new Trk::ScatteringAngles(0,0,scatsigma/sin(nextPar->parameters()[Trk::theta]),scatsigma);
               //energy loss
               double currentqoverp=nextPar->parameters()[Trk::qOverP];
               EnergyLoss* eloss = m_elossupdators[0]->energyLoss(materialProperties,fabs(1./currentqoverp),1./costr,
                                                                 dir,particle);

	       // use curvilinear TPs to simplify retrieval by fitters
	       Trk::CurvilinearParameters* cvlTP = new Trk::CurvilinearParameters(nextPar->position(),nextPar->momentum(),nextPar->charge());
	       Trk::MaterialEffectsOnTrack* mefot =  new Trk::MaterialEffectsOnTrack(dInX0,newsa,eloss,cvlTP->associatedSurface());
               if(m_extrapolationCache) {
                 if(checkCache(" mat states extrapolateToNextMaterialLayer thin" )) {
                   if(m_dumpCache) dumpCache(" extrapolateToNextMaterialLayer thin");
                   m_extrapolationCache->updateX0(dInX0);
                   m_extrapolationCache->updateEloss(eloss->meanIoni(),eloss->sigmaIoni(),eloss->meanRad(),eloss->sigmaRad());
                   if(m_dumpCache) dumpCache(" After");
	         }
               }     
	       m_matstates->push_back(new TrackStateOnSurface(0,cvlTP,0,mefot));
            }
            //     
             ATH_MSG_VERBOSE("  [M] Collecting material at material layer t/X0 = " << thick/lx0 );
	     if (m_cacheLastMatLayer) m_lastMaterialLayer = nextLayer; 
            if (!destSurf && (nextLayer->layerType()>0 || m_returnPassiveLayers) ) return nextPar->clone();
          }
          if ( resolveActive ) { 
            // if ordered layers, retrieve the next layer and replace the current one in the list
            if (m_navigLays[index].first && m_navigLays[index].first->confinedLayers()) {
              const Trk::Layer* newLayer = m_navigLays[index].first->nextLayer(nextPar->position(),dir*nextPar->momentum().normalized(),true);
              if (newLayer) { 
                 m_navigLays[index].second = newLayer;
                 m_navigSurfs[solutions[iSol]].first = &(newLayer->surfaceRepresentation());
              }            
            }
          }
          currPar = nextPar;     
         } else if ( solutions[iSol] < iDest + m_staticBoundaries.size() + m_layers.size() + m_denseBoundaries.size() ) {
           // dense volume boundary
           unsigned int index = solutions[iSol] - iDest -m_staticBoundaries.size()- m_layers.size();
	   std::vector< std::pair<const Trk::TrackingVolume*,unsigned int> >::iterator dIter = m_denseVols.begin();
           while ( index >= (*dIter).second && dIter!= m_denseVols.end() ) {
             index -= (*dIter).second ; 
             dIter++;
           }
           if ( dIter != m_denseVols.end() ) {
             currVol = (*dIter).first;
	     nextVol = ( (*dIter).first->boundarySurfaces())[index].getPtr()->attachedVolume(*nextPar,dir);
             // boundary orientation not reliable 
	     Amg::Vector3D tp = nextPar->position()+2*m_tolerance*dir*nextPar->momentum().normalized();
	     if (currVol->inside(tp,m_tolerance)) {
	       m_currentDense = currVol;
	     } else if (!nextVol || !nextVol->inside(tp,m_tolerance) ) {   // search for dense volumes
	       m_currentDense =  m_highestVolume;
	       if (m_dense && !m_denseVols.size()) m_currentDense = m_currentStatic;
	       else {
		 for (unsigned int i=0;i<m_denseVols.size(); i++) {
		   const Trk::TrackingVolume* dVol = m_denseVols[i].first;
		   if ( dVol->inside(tp,0.)  && dVol->zOverAtimesRho()!=0. ){
		     m_currentDense = dVol;
		     ATH_MSG_DEBUG( "  [+] Next dense volume found: '" << m_currentDense->volumeName() << "'."); 
		     break;
		   } 
		 } // loop over dense volumes
	       }
	     } else {
	       m_currentDense = nextVol;
	       ATH_MSG_DEBUG( "  [+] Next dense volume: '" << m_currentDense->volumeName() << "'."); 
	     }
	   }
         } else if ( solutions[iSol] < iDest + m_staticBoundaries.size() + m_layers.size() + m_denseBoundaries.size() 
                     + m_navigBoundaries.size() ) {
           // navig volume boundary
           unsigned int index = solutions[iSol]-iDest-m_staticBoundaries.size()- m_layers.size()-m_denseBoundaries.size();
	   std::vector< std::pair<const Trk::TrackingVolume*,unsigned int> >::iterator nIter = m_navigVolsInt.begin();
           while ( index >= (*nIter).second && nIter!= m_navigVolsInt.end() ) {
             index -= (*nIter).second ; 
             nIter++;
           }
           if ( nIter != m_navigVolsInt.end() ) {
             currVol = (*nIter).first;
             nextVol = ( (*nIter).first->boundarySurfaces())[index].getPtr()->attachedVolume(*nextPar,dir);
             // boundary orientation not reliable 
	     Amg::Vector3D tp = nextPar->position()+2*m_tolerance*dir*nextPar->momentum().normalized();
	     if (nextVol && nextVol->inside(tp,0.)) {
	       ATH_MSG_DEBUG("  [+] Navigation volume boundary, entering volume '" << nextVol->volumeName() << "'.");
	     } else if ( currVol->inside(tp,0.) ) {
	       nextVol = currVol;	   
	       ATH_MSG_DEBUG("  [+] Navigation volume boundary, entering volume '" << nextVol->volumeName() << "'.");
	     } else {
	       nextVol = 0;
	       ATH_MSG_DEBUG("  [+] Navigation volume boundary, leaving volume '" << currVol->volumeName() << "'.");
	     } 
             currPar = nextPar;
             // return only if detached volume boundaries not collected
             //if ( nextVol || !detachedBoundariesIncluded )
             if ( nextVol )
	       return extrapolateToNextMaterialLayer(prop,*currPar,destSurf,m_currentStatic,dir,bcheck,particle,matupmode);                 
           } 
         } else if ( solutions[iSol] < iDest + m_staticBoundaries.size() + m_layers.size() + m_denseBoundaries.size() 
                    + m_navigBoundaries.size() + m_detachedBoundaries.size() ) {
           // detached volume boundary
           unsigned int index = solutions[iSol]-iDest-m_staticBoundaries.size()- m_layers.size()
            - m_denseBoundaries.size() - m_navigBoundaries.size();
          std::vector< std::pair<const Trk::DetachedTrackingVolume*,unsigned int> >::iterator dIter = m_detachedVols.begin();
           while ( index >= (*dIter).second && dIter!= m_detachedVols.end() ) {
             index -= (*dIter).second ; 
             dIter++;
           }
           if ( dIter != m_detachedVols.end() ) {
             currVol = (*dIter).first->trackingVolume();
             // boundary orientation not reliable 
             nextVol = ( (*dIter).first->trackingVolume()->boundarySurfaces())[index].getPtr()->attachedVolume(*nextPar,dir);
	     Amg::Vector3D tp = nextPar->position()+2*m_tolerance*dir*nextPar->momentum().normalized();
	     if (nextVol && nextVol->inside(tp,0.)) {
	       ATH_MSG_DEBUG("  [+] Detached volume boundary, entering volume '" << nextVol->volumeName() << "'.");
	     } else if ( currVol->inside(tp,0.) ) {
	       nextVol = currVol;	   
	       ATH_MSG_DEBUG("  [+] Detached volume boundary, entering volume '" << nextVol->volumeName() << "'.");
	     } else {
	       nextVol = 0;
	       ATH_MSG_DEBUG("  [+] Detached volume boundary, leaving volume '" << currVol->volumeName() << "'.");
	     } 
             currPar = nextPar;
             //if ( nextVol || !detachedBoundariesIncluded)
             if ( nextVol )
	       return extrapolateToNextMaterialLayer(prop,*currPar,destSurf,m_currentStatic,dir,bcheck,particle,matupmode);   
           } 
	}   
	iSol++;
       }
     } else {
       ATH_MSG_DEBUG( "  [!] Propagation failed, return 0" );
       m_parametersAtBoundary.boundaryInformation(m_currentStatic,nextPar,nextPar);     
       return returnParameters;
     }
     currPar = nextPar;
   }

   return returnParameters;
}        


const Trk::TrackParameters* Trk::Extrapolator::extrapolateInAlignableTV(const IPropagator& prop,
                        const Trk::TrackParameters& parm,
                        const Trk::Surface* destSurf, 
                        const Trk::AlignableTrackingVolume* vol,
                        PropDirection dir,
                        ParticleHypothesis particle) const
{
  ATH_MSG_DEBUG( "M-[" << ++m_methodSequence << "] extrapolateInAlignableTV(...) " );
 
  // material loop in sensitive Calo volumes 
  // extrapolation without target surface returns:
  //    A)    boundary parameters (static volume boundary)
  // if target surface:
  //    B)    trPar at target surface
  // material collection done by the propagator ( binned material used ) 
  
  // initialize the return parameters vector
  const Trk::TrackParameters* returnParameters = 0;
  const Trk::TrackParameters* currPar = &parm;
  const Trk::AlignableTrackingVolume*  staticVol = 0;
  const Trk::TrackingVolume*  currVol = 0;
  const Trk::TrackingVolume*  nextVol = 0;
  std::vector<unsigned int> solutions;
  const Trk::TrackingVolume* assocVol = 0;  
  //double tol = 0.001;
  //double path = 0.;
  if (!m_highestVolume ) m_highestVolume = m_navigator->highestVolume();

  emptyGarbageBin(&parm);
    
  // verify current position
  Amg::Vector3D gp = parm.position();
  if ( vol && vol->inside(gp,m_tolerance) ) {
    staticVol = vol; 
  } else {
    currVol =  m_navigator->trackingGeometry()->lowestStaticTrackingVolume(gp);    
    const Trk::TrackingVolume* nextStatVol = 0;
    if ( m_navigator->atVolumeBoundary(currPar,currVol,dir,nextStatVol,m_tolerance) && nextStatVol != currVol ) 
      currVol = nextStatVol;
    if (currVol && currVol != vol) {
      const Trk::AlignableTrackingVolume* aliTG = dynamic_cast<const Trk::AlignableTrackingVolume*> (currVol);
      if (aliTG) staticVol = aliTG;
    }
  }

  if (!staticVol) {
     ATH_MSG_DEBUG( "  [!] failing in retrieval of AlignableTV, return 0" );
     return returnParameters;
  } 

  // TODO if volume entry go to entry of misaligned volume

  // save volume entry if collection present

  if (m_identifiedParameters) {
    const Trk::BinnedMaterial* binMat = staticVol->binnedMaterial();
    if (binMat) {
      const Trk::IdentifiedMaterial* binIDMat = binMat->material(currPar->position());
      if (binIDMat->second>0) m_identifiedParameters->push_back(std::pair<const Trk::TrackParameters* , int>  ( currPar->clone(), binIDMat->second));  
    }
  }
   
  // navigation surfaces
  if( m_navigSurfs.capacity() > m_maxNavigSurf ) m_navigSurfs.reserve(m_maxNavigSurf); 
  m_navigSurfs.clear();

  if (destSurf) m_navigSurfs.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(destSurf,false));
  
  // assume new static volume, retrieve boundaries
  m_currentStatic = staticVol;
  m_staticBoundaries.clear();
  const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds = staticVol->boundarySurfaces();
  for (unsigned int ib=0; ib< bounds.size(); ib++ ){
    const Trk::Surface& surf = (bounds[ib].getPtr())->surfaceRepresentation();
    m_staticBoundaries.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(&surf,true));
  }
  
  m_navigSurfs.insert(m_navigSurfs.end(),m_staticBoundaries.begin(),m_staticBoundaries.end());

  // current dense
  m_currentDense =  staticVol;
   
  // ready to propagate      
  // till: A/ static volume boundary(bcheck=true) , B/ destination surface(bcheck=false)
   
   nextVol = 0;
   while (currPar) {      
     double path=0.;
     std::vector<unsigned int> solutions;
     // propagate now
     ATH_MSG_DEBUG( "  [+] Starting propagation at position  " << positionOutput(currPar->position())  
         << " (current momentum: " << currPar->momentum().mag() << ")" ); 
     ATH_MSG_DEBUG( "  [+] " << m_navigSurfs.size() << " target surfaces in '" << m_currentDense->volumeName() <<"'.");   
     //  arguments : inputParameters, vector of navigation surfaces, propagation direction, b field service, particle type, result,
     //              material collection, intersection collection, path limit, switch for use of path limit, switch for curvilinear on return, current TG volume
     if(m_dumpCache&&m_extrapolationCache) ATH_MSG_DEBUG( "  prop.propagateM " << m_extrapolationCache );
     const Trk::TrackParameters* nextPar = prop.propagateM(*currPar,m_navigSurfs,dir, m_fieldProperties,particle,solutions,
							   m_matstates,m_identifiedParameters,path,false,false,m_currentDense, m_extrapolationCache);
     ATH_MSG_VERBOSE( "  [+] Propagation done. " ); 
     if (nextPar)  
        ATH_MSG_DEBUG( "  [+] Position after propagation -   at " << positionOutput(nextPar->position())); 

     if (nextPar)  ATH_MSG_DEBUG( "  [+] Number of intersection solutions: " << solutions.size() );
     if (nextPar) throwIntoGarbageBin(nextPar);
     if (nextPar) {    
       // destination surface
       if (destSurf && solutions[0]==0 ) return nextPar->clone();
       if (destSurf && solutions.size()>1 && solutions[1]==0 ) return nextPar->clone();
       // destination surface missed ? 
       if (destSurf) {
	 double dist = 0.;
	 Trk::DistanceSolution distSol = destSurf->straightLineDistanceEstimate(nextPar->position(),
										nextPar->momentum().normalized());
	 if (distSol.numberOfSolutions()>0 ) {
	   dist = distSol.first();
	   if ( distSol.numberOfSolutions()>1 && fabs(dist) < m_tolerance ) dist = distSol.second();
	   if ( distSol.numberOfSolutions()>1 && dist*dir < 0. && distSol.second()*dir > 0. ) dist = distSol.second();    
         } else {
           dist = distSol.toPointOfClosestApproach();
         } 
	 if (dist*dir < 0.) {
	   ATH_MSG_DEBUG( "  [+] Destination surface missed ? "<< dist << "," << dir );
	   m_parametersAtBoundary.resetBoundaryInformation();
	   return returnParameters;
	 }
	 ATH_MSG_DEBUG( "  [+] New 3D-distance to destinatiion    - d3 = " << dist*dir ); 
       }
       
       int iDest = destSurf ? 1 : 0;
       unsigned int iSol  = 0;
       while ( iSol < solutions.size() ) {         
	 if ( solutions[iSol] < iDest + m_staticBoundaries.size() ) {
2045
           // TODO if massive boundary coded, add the material effects here 
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
	   // static volume boundary; return to the main loop : TODO move from misaligned to static
	   unsigned int index = solutions[iSol]-iDest;
	   // use global coordinates to retrieve attached volume (just for static!)
	   nextVol = (m_currentStatic->boundarySurfaces())[index].getPtr()->attachedVolume(nextPar->position(),nextPar->momentum(),dir);
	   // double check the next volume
	   if ( nextVol && !(nextVol->inside(nextPar->position()+0.01*dir*nextPar->momentum().normalized(),m_tolerance) ) ) {
	     ATH_MSG_DEBUG( "  [!] WARNING: wrongly assigned static volume ?"<< m_currentStatic->volumeName()<<"->" << nextVol->volumeName() );
	     nextVol = m_navigator->trackingGeometry()->lowestStaticTrackingVolume(nextPar->position()+0.01*nextPar->momentum().normalized());
	     if (nextVol) ATH_MSG_DEBUG( "  new search yields: "<< nextVol->volumeName() );          
	   }
	   // end double check - to be removed after validation of the geometry gluing 
	   // lateral exit from calo sample can be handled here 
	   if (m_identifiedParameters) {
	     const Trk::BinnedMaterial* binMat = staticVol->binnedMaterial();
	     if (binMat) {
	       const Trk::IdentifiedMaterial* binIDMat = binMat->material(nextPar->position());
               // save only if entry to the sample present, the exit missing and non-zero step in the sample
               if (binIDMat && binIDMat->second>0 && m_identifiedParameters->size() &&  m_identifiedParameters->back().second== binIDMat->second) {
                 double s = (nextPar->position()-m_identifiedParameters->back().first->position()).mag(); 
		 if (s>0.001) m_identifiedParameters->push_back(std::pair<const Trk::TrackParameters*,int> (nextPar->clone(), -binIDMat->second));
	       }  
	     }
	   }
           // end lateral exit handling
	   if (nextVol != m_currentStatic ) {
	     m_parametersAtBoundary.boundaryInformation(nextVol,nextPar,nextPar);         
	     ATH_MSG_DEBUG("  [+] StaticVol boundary reached of '" <<m_currentStatic->volumeName() << "'.");
	     if ( m_navigator->atVolumeBoundary(nextPar,m_currentStatic,dir,assocVol,m_tolerance) && assocVol != m_currentStatic )
	       m_currentDense = m_useMuonMatApprox ? nextVol : m_highestVolume;
	     // no next volume found --- end of the world
	     if ( !nextVol )
	       ATH_MSG_DEBUG( "  [+] Word boundary reached        - at " << positionOutput(nextPar->position()) );
	     // next volume found and parameters are at boundary
	     if ( nextVol && nextPar ){ 
	       ATH_MSG_DEBUG( "  [+] Crossing to next volume '" << nextVol->volumeName() << "'");
	       ATH_MSG_DEBUG( "  [+] Crossing position is         - at " <<  positionOutput(nextPar->position()) );  
               if (!destSurf) return nextPar->clone();    //  return value differs between e->surface (cached boundary values used)
                                                          //     implicit : parameters at boundary returned    
	     }     
	     return returnParameters;
	   }
	 }
	 iSol++;
       }
     } else {
       ATH_MSG_DEBUG( "  [!] Propagation failed, return 0" );
       m_parametersAtBoundary.boundaryInformation(m_currentStatic,nextPar,nextPar);     
       return returnParameters;
     }
     currPar = nextPar;
   }
   
   return returnParameters;
}        

std::pair<const Trk::TrackParameters*,const Trk::Layer*> Trk::Extrapolator::extrapolateToNextStation(
                                                                                        const IPropagator& prop,
                                                                                        const Trk::TrackParameters& parm,
                                                                                        PropDirection dir,
                                                                                        BoundaryCheck bcheck,
                                                                                        ParticleHypothesis particle,
                                                                                        MaterialUpdateMode matupmode) const
{
   ATH_MSG_DEBUG( "M-[" << ++m_methodSequence << "] extrapolateToNextStation(...) " );
  // material update on detached volume layer representation only

  //double tol = 0.001;

  emptyGarbageBin(&parm);

  // initialize the return parameters vector
  const Trk::TrackParameters* returnParameters = 0;

  //resolve position: static or detached ?
  const Trk::TrackingVolume* currVol = m_navigator->trackingGeometry()->lowestStaticTrackingVolume(parm.position());
  const Trk::TrackingVolume* nextVol=0;
  if ( m_navigator->atVolumeBoundary(&parm,currVol,dir,nextVol,m_tolerance) && nextVol != currVol ) currVol = nextVol;
  if (!m_highestVolume ) m_highestVolume = m_navigator->highestVolume();
  
  const Trk::TrackParameters* currPar = &parm;
  double path = 0.;
  while ( currPar && currVol && !currVol->confinedDetachedVolumes() ) {
    const Trk::NavigationCell cross = m_navigator->nextDenseTrackingVolume(prop,*currPar,0,dir,particle,*currVol,path);
    currPar = cross.parametersOnBoundary;
    if (currPar) {
      // currPar = cross.parametersOnBoundary->clone();
      currPar = cross.parametersOnBoundary;
      throwIntoGarbageBin(currPar);
    }
    currVol = cross.nextVolume;    
  } 
  
  // no luck
  if (!currPar || !currVol || !currVol->confinedDetachedVolumes() ) return std::pair<const Trk::TrackParameters*,const Trk::Layer*>(returnParameters,0);

  // prepare vector of surfaces
  if( m_navigSurfs.capacity() > m_maxNavigSurf ) m_navigSurfs.reserve(m_maxNavigSurf); 
  if( m_navigVols.capacity() > m_maxNavigVol ) m_navigVols.reserve(m_maxNavigVol); 
  m_navigSurfs.clear();
  m_navigVols.clear();

  // retrieve static volume boundary
  const std::vector< SharedObject<const BoundarySurface<TrackingVolume> > > bounds = currVol->boundarySurfaces();
  for (unsigned int ib=0; ib< bounds.size(); ib++ ){
    const Trk::Surface* nextSurface = &((bounds[ib].getPtr())->surfaceRepresentation());
    m_navigSurfs.push_back(std::pair<const Trk::Surface*,Trk::BoundaryCheck>(nextSurface,true));
  }

  // retrieve DV layer representations
  const std::vector<const Trk::DetachedTrackingVolume*>* detVols = currVol->confinedDetachedVolumes();
  if (detVols) {
    std::vector<const Trk::DetachedTrackingVolume*>::const_iterator dIter = detVols->begin();
    for (; dIter != detVols->end(); dIter++) {
      const Trk::Layer* lay = (*dIter)->layerRepresentation(); 
      if ( lay ) {
2161
	Trk::BoundaryCheck checkBounds = lay->layerType() > 0 ? bcheck : Trk::BoundaryCheck(true);
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399