//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//*
//             LOW ENERGY MUON SPIN RELAXATION, ROTATION, RADIATION 
// 
//  ID    :LEMuSRCryoSD.cc , v 1.2
//  AUTHOR: Taofiq PARAISO
//  DATE  : 2006-01-19 15:17
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//
//
//  &           &&&&&&&&&&                            &&&&&&&         &&&&&&&&
//  &           &                                   &&      &&       &       &&
//  &           &                   &      &       &                &       &&
//  &           &&&&&&&            &      &         &&&&&&         &&&&&&&&  
//  &           &                 &      &&                &      &      &&
//  &           &                &&     &  &     &&      &&      &        &
//  &&&&&&&&&&  &&&&&&&&&&      &  &&&&&    &&    &&&&&&&       &        &&   
//                             &
//                            &
//                           &
//                         &  
//                               CRYOSD   
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$//

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


LEMuSRCryoSD::LEMuSRCryoSD(G4String name)
:G4VSensitiveDetector(name)
{

  G4String HCname;
  collectionName.insert(HCname="CryoCollection");
  positionResolution = 1*mm;


  // ROOT
  BookRoot();
}

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

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

G4bool LEMuSRCryoSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
  //  G4cout << "PROCESS HIT"<<G4endl;
	  mu=0;e=0;g=0;  
  
	  //  LEMuSRCryoHit* aHit;
  p_name = aStep->GetTrack()->GetDefinition()->GetParticleName(); // particle name
	  if(p_name=="mu+")mu=1;
	  if(p_name=="Mu")e=1;
	  //	  G4cout<<"mu+ "<< mu <<" mu "<<e;
  
 
  if( CheckCondition(aStep))
    {
      GetDatas(aStep);
      getHit();
      FillRoot();
    }
  
  /* Obsolete: to be removed
  // Define Hit
  aHit = new LEMuSRCryoHit();
  
  //++++++++++++++ set hit values _______________
  aHit->SetParticleName(p_name);
  aHit->SetSpin(spin);
  
  aHit->SetMomentum( hitmom );
  aHit->SetPosition( hitpos );
  
  aHit->SetTimeOfFlight( tof);
  aHit->SetEnergyDeposition( edep );
   
  
  CryoCollection->insert( aHit );
  //  aHit->Print();
  //  aHit->print("Statistics/SCIS.Hits");
  aHit->Draw();
  
  PrintAll();
  */  
  
  return true;
}

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

}

G4bool LEMuSRCryoSD::CheckCondition(const G4Step* aStep)
{
  G4bool condition=false;
  if(p_name == "mu+"||p_name == "Mu")
    {
      if(aStep->GetTrack()->GetNextVolume()->GetLogicalVolume()->GetName()=="lv_SAH2")
	{ 
	  condition=true;
	}
    }
  return condition;
 
}  


void LEMuSRCryoSD::clear()
{
  delete CryoCollection;
} 

void LEMuSRCryoSD::DrawAll()
{
} 

void LEMuSRCryoSD::PrintAll()
{

} 


void LEMuSRCryoSD::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();

 
}


void LEMuSRCryoSD::getHit()
{
  theHit.kenergy       = kinen/keV;
  theHit.tenergy       = toten/keV;
  theHit.edeposit      = edep/keV;
  theHit.localtime     = tof/ns;
  theHit.globaltime    = globaltime/ns;
  theHit.proptime      = proptime/ns;
  theHit.positionx     = hitpos.x()/mm;
  theHit.positiony     = hitpos.y()/mm;
  theHit.positionz     = hitpos.z()/mm;
  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 LEMuSRCryoSD::BookRoot()
{
  // open root file
  myFile = new TFile("SDCryoE0.root", "RECREATE");
  //  myFile->SetCompressionLevel(1);

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

  tree->Branch("cryoHit",&theHit.kenergy,"kenergy/F:tenergy/F:edeposit/F:localtime/F:globaltime:propertime/F:positionx/F:positiony:positionz:momdirx:momdiry:momdirz/F:foil/F:muon/I:muonium/I:gamma/I:runID/I");

}

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

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

