
#include "SteppingAction.hh"
#include "DetectorConstruction.hh"
#include "G4Polyline.hh"
#include "G4Colour.hh"
#include "G4SteppingManager.hh"
#include "G4VisAttributes.hh"
#include "G4VVisManager.hh"
#include "G4VTouchable.hh"
#include "G4TouchableHistory.hh"
#include "G4Step.hh"
#include "G4Track.hh"
#include "RunAction.hh"
#include "G4ios.hh"
#include "G4UnitsTable.hh"
#include "SteppingActionMessenger.hh"
#include "G4ParticleDefinition.hh"
#include "G4ParticleTypes.hh"
#include "G4UImanager.hh"

SteppingAction::SteppingAction(DetectorConstruction* myDC
                                         , RunAction* myRU)
  :myDetector(myDC) ,runAction(myRU), drawFlag(false)

{new SteppingActionMessenger(this);}

SteppingAction::~SteppingAction()
{ }


void SteppingAction::UserSteppingAction(const G4Step* aStep)
{ const G4SteppingManager* pSM = fpSteppingManager;
 G4TouchableHistory* theTouchable
   = (G4TouchableHistory*)(aStep->GetPreStepPoint()->GetTouchable());
 G4VPhysicalVolume* currentV = theTouchable->GetVolume();  
 G4String name = currentV->GetName();   
 G4double time = aStep->GetTrack()->GetGlobalTime();

 if(drawFlag)
   {
     G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance();
     if(pVVisManager) {
       
//----------Define a line segment
       G4Polyline polyline;
       G4double charge = pSM->GetTrack()->GetDefinition()->GetPDGCharge();
       G4Colour colour;
       if (charge < 0.) colour = G4Colour(1., 0., 0.);
       else if (charge > 0.) colour = G4Colour(0., 0., 1.);
       else  colour = G4Colour(0., 1., 0.);
       if ( pSM->GetTrack()->GetDefinition()==G4Neutron::NeutronDefinition() ) colour = G4Colour(1., 1., 0.);
       G4VisAttributes attribs(colour);
       polyline.SetVisAttributes(attribs );
       polyline.push_back(pSM->GetStep()->GetPreStepPoint()->GetPosition());
       polyline.push_back(pSM->GetStep()->GetPostStepPoint()->GetPosition());
       pVVisManager->Draw(polyline);
     }
   };


 if(name=="physHe3Ar"){
   G4int copyNo = theTouchable ->GetReplicaNumber(1);
   G4double EnergyD =  aStep->GetTotalEnergyDeposit();

   if(EnergyD>0.)
     {
       if(time>1.*ns && time<150000.*ns)
	 {
	   G4String pname =  aStep->GetTrack()->GetDefinition()->GetParticleName();
	   G4cout<<copyNo<<pname<<" time = "<<time/ns<<" energy/keV "<<EnergyD/keV
	   <<G4endl;

	   if(runAction->tube[copyNo]==0)
	     { 
	       runAction->Etube[copyNo] =+EnergyD;
	       runAction->TimeTube[copyNo]=time; 
	       runAction->tube[copyNo]=1;
	     }
	   
	     if(runAction->tube[copyNo]==1) 
	      {
	   	if(fabs(time - runAction->TimeTube[copyNo])>50000.*ns)
	   	  {
	   	  runAction->E1tube[copyNo] += EnergyD;
	   	  }
	   	else
	   	  runAction->Etube[copyNo] += EnergyD;}	       	 
     }
 }
 }
}

// 2005 by G.I.Vasilyev
