//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//*
//             LOW ENERGY MUON SPIN RELAXATION, ROTATION, RADIATION 
// 
//  ID    :LEMuSRMcpSD.cc , v 1.3
//  AUTHOR: Taofiq PARAISO
//  DATE  : 2004-09-17 10:20
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
//
//  &           &&&&&&&&&&                            &&&&&&&         &&&&&&&&
//  &           &                                   &&      &&       &       &&
//  &           &                   &      &       &                &       &&
//  &           &&&&&&&            &      &         &&&&&&         &&&&&&&&  
//  &           &                 &      &&                &      &      &&
//  &           &                &&     &  &     &&      &&      &        &
//  &&&&&&&&&&  &&&&&&&&&&      &  &&&&&    &&    &&&&&&&       &        &&   
//                             &
//                            &
//                           &
//                         &  
//                               MCP SD   
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//

#include "LEMuSRMcpSD.hh"
#include "LEMuSRDetectorConstruction.hh"
#include "G4HCofThisEvent.hh"
#include "G4TouchableHistory.hh"
#include "G4Track.hh"
#include "G4Step.hh"
#include "G4ios.hh"
#include "G4VProcess.hh"

// ROOT
#include "TROOT.h"
#include "TApplication.h"
#include "TSystem.h"
#include "TH1.h"
#include "TPad.h"
#include "TCanvas.h"
#include "LEMuSRPrimaryGeneratorAction.hh"

LEMuSRMcpSD::LEMuSRMcpSD(G4String name)
:G4VSensitiveDetector(name)
{

  G4String HCname;
  collectionName.insert(HCname="McpCollection");
  positionResolution = 0.1*mm;


  // ROOT
  BookRoot();
}

LEMuSRMcpSD::~LEMuSRMcpSD()
{
  // ROOT
  WriteRoot();
}

void LEMuSRMcpSD::Initialize(G4HCofThisEvent* HCE)
{
  static int HCID = -1;
  McpCollection = new LEMuSRMcpHitsCollection
    (SensitiveDetectorName,collectionName[0]); 
  if(HCID<0)
    { HCID = GetCollectionID(0); }
  HCE->AddHitsCollection(HCID,McpCollection);
}

G4bool LEMuSRMcpSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
  
  p_name = aStep->GetTrack()->GetDefinition()->GetParticleName();  
  
  if( CheckCondition(aStep))
    {
      GetDatas(aStep);
      getHit();
      FillRoot();
    }
  
  
  //PrintAll();
  
  return true;
}

void LEMuSRMcpSD::EndOfEvent(G4HCofThisEvent*)
{
  /*
    G4int NbHits = McpCollection->entries();
    G4cout << "\n-------->Hits Collection: in this event they are " << NbHits 
    << " hits in the  mcp: " << G4endl;
    for (G4int i=0;i<NbHits;i++) (*McpCollection)[i]->Print();
  */
}

G4bool LEMuSRMcpSD::CheckCondition(const G4Step* aStep)
{
  
  G4bool condition=false;
  mu=e=g=0;
  
  
  
  if(aStep->GetPreStepPoint()->GetGlobalTime()/ns<1000.)
    {
      if(p_name == "e+"&&aStep->GetTrack()->GetNextVolume()->GetLogicalVolume()->GetName()!="lv_DMCP")
	{	  
	  if( aStep->GetTrack()->GetCreatorProcess())      
	    {
	      if( aStep->GetTrack()->GetCreatorProcess()->GetProcessName()=="Decay")
		{
		  condition=false;//true;
		}
	    }
	}
      //      if(p_name == "proton")
      if(p_name == "mu+"||p_name == "Mu")
	{
	  condition=true;
	  if(p_name=="mu+")mu=1;
	  if(p_name=="Mu")e=1;
	}
      if(p_name == "gamma")
	{
	  g=1;
	  condition=false;//true;
	}
    }

  
  return condition;
  
  
}  


void LEMuSRMcpSD::clear()
{
  delete McpCollection;
} 

void LEMuSRMcpSD::DrawAll()
{
} 

void LEMuSRMcpSD::PrintAll()
{

  // Define Hit
   
  LEMuSRMcpHit* aHit;
  aHit = new LEMuSRMcpHit();
  
 //++++++++++++++ set hit values _______________
  aHit->SetParticleName(p_name);
  aHit->SetSpin(spin);
  
  aHit->SetMomentum( hitmom );
  aHit->SetPosition( hitpos );
  
  aHit->SetTimeOfFlight( tof );
  aHit->SetEnergyDeposition( edep );
  
  
  //  McpCollection->insert( aHit );
  //  aHit->Print();
  //  aHit->print("Statistics/SCIS.Hits");
  //  aHit->Draw();
  

} 


void LEMuSRMcpSD::GetDatas(const G4Step *aStep)
{
  // Get datas
  //a  Volume, name, spin
  vname =  aStep->GetPreStepPoint()->GetPhysicalVolume()->GetName();  
  spin=  aStep->GetTrack()->GetDefinition()->GetPDGSpin(); // spin in units of 1
  
  //b Position momentum
  hitpos = aStep->GetPreStepPoint()->GetPosition()/cm; // position
  hitmom = aStep->GetPreStepPoint()->GetMomentumDirection(); // momentum
  
  //c Times
  tof =  aStep->GetPreStepPoint()->GetLocalTime()/ns; // time since track creation
  globaltime =  aStep->GetPreStepPoint()->GetGlobalTime()/ns;// time since event creation
  proptime =  aStep->GetTrack()->GetDynamicParticle()->GetProperTime()/ns; // particle's proper time
  
  //d Energy
  edep = aStep->GetTotalEnergyDeposit(); 
  
  toten =  LEMuSRPrimaryGeneratorAction::GetPGA()->energy/keV;//aStep->GetTrack()->GetTotalEnergy();
  
  kinen =  aStep->GetPreStepPoint()->GetKineticEnergy();


}


void LEMuSRMcpSD::getHit()
{
  theHit.kenergy       = kinen;
  theHit.tenergy       = toten;
  theHit.edeposit      = edep;
  theHit.localtime     = tof;
  theHit.globaltime    = globaltime;
  theHit.proptime      = proptime;
  theHit.positionx     = hitpos.x();
  theHit.positiony     = hitpos.y();
  theHit.positionz     = hitpos.z();
  theHit.momdirx       = hitmom.x();
  theHit.momdiry       = hitmom.y();
  theHit.momdirz       = hitmom.z();
  theHit.foil          = LEMuSRDetectorConstruction::GetInstance()->cfthk;
  theHit.muon          = mu;
  theHit.positron      = e;
  theHit.gamma         = g;
  theHit.runid         = G4RunManager::GetRunManager()->GetCurrentRun()->GetRunID();
}

//                                     ROOT METHODS

void LEMuSRMcpSD::BookRoot()
{
  // open root file
  myFile = new TFile("SDMcp.root", "RECREATE");
  //  myFile->SetCompressionLevel(1);

  tree = new TTree ("tree"," Mcp Datas");

  tree->Branch("mcpHit",&theHit.kenergy,"kenergy/F:init_energy/F:edeposit/F:localtime/F:globaltime:propertime/F:positionx/F:positiony:positionz:momentumx:momentumy:momentumz/F:foil/F:muon/I:muonium/I:gamma/I:ID/I");

}

void LEMuSRMcpSD::FillRoot()
{
  tree->Fill();
}

void LEMuSRMcpSD::WriteRoot()
{
  myFile->Write();
  myFile->Close();
}

