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

#include "LEMuSROScintSD.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"


LEMuSROScintSD::LEMuSROScintSD(G4String name)
:G4VSensitiveDetector(name)
{

  G4String HCname;
  collectionName.insert(HCname="OuterScintCollection");
  positionResolution = 5*mm;


  // ROOT
  BookRoot();
}

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

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

G4bool LEMuSROScintSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
  //  G4cout << "PROCESS HIT"<<G4endl;
  
  LEMuSROScintHit* aHit;
  p_name = aStep->GetTrack()->GetDefinition()->GetParticleName(); // particle name
  
 
  if( CheckCondition(aStep))
    {
      GetDatas(aStep);
      getHit();
      FillRoot();
    }
  

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

  
  PrintAll();
  
  
  return true;
}

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

}

G4bool LEMuSROScintSD::CheckCondition(const G4Step* aStep)
{
  G4bool condition=false;
  
  if(p_name == "e+"&&aStep->GetTrack()->GetNextVolume()->GetLogicalVolume()->GetName()!="lv_SCOS")
    {	  
      if( aStep->GetTrack()->GetCreatorProcess())      
	{
	  if( aStep->GetTrack()->GetCreatorProcess()->GetProcessName()=="Decay")
	    {
	      condition=true;
	    }
	}
    }
 
  return condition;
 
}  


void LEMuSROScintSD::clear()
{
  delete ScintCollection;
} 

void LEMuSROScintSD::DrawAll()
{
} 

void LEMuSROScintSD::PrintAll()
{

} 


void LEMuSROScintSD::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(); // position
  hitmom = aStep->GetPreStepPoint()->GetMomentum(); // momentum
  
  //c Times
  tof =  aStep->GetPreStepPoint()->GetLocalTime(); // time since track creation
  globaltime =  aStep->GetPreStepPoint()->GetGlobalTime();// time since event creation
  proptime =  aStep->GetPreStepPoint()->GetProperTime(); // particle's proper time
  
  //d Energy
  edep = aStep->GetTotalEnergyDeposit(); 
  
  toten =  aStep->GetTrack()->GetTotalEnergy();
  
  kinen =  aStep->GetTrack()->GetKineticEnergy();

  //e OScint ID

}


void LEMuSROScintSD::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();
      if (vname=="pv_SCISl") 
	{
	   theHit.scLeft = globaltime;//+=1;//
	}
      else if (vname=="pv_SCISb")
	{
	   theHit.scBottom =globaltime ;//+=1;
	}
      else if (vname=="pv_SCISr") 
	{
	   theHit.scRight =globaltime;//+=1;
	}
      else if (vname=="pv_SCISt")
	{
	   theHit.scTop = globaltime;//+=1;
	}
}

//                                     ROOT METHODS

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

  tree = new TTree ("tree","Outer Scintillator Datas");

  tree->Branch("scintHit",&theHit.kenergy,"kenergy/F:tenergy/F:edeposit/F:localtime/F:globaltime:propertime/F:positionx/F:positiony:positionz:momdirx:momdiry:momdirz/F:Left/F:Right/F:Bottom/F:Top/F:runID");

}

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

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