//
// ********************************************************************
// * License and Disclaimer                                           *
// *                                                                  *
// * The  Geant4 software  is  copyright of the Copyright Holders  of *
// * the Geant4 Collaboration.  It is provided  under  the terms  and *
// * conditions of the Geant4 Software License,  included in the file *
// * LICENSE and available at  http://cern.ch/geant4/license .  These *
// * include a list of copyright holders.                             *
// *                                                                  *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work  make  any representation or  warranty, express or implied, *
// * regarding  this  software system or assume any liability for its *
// * use.  Please see the license in the file  LICENSE  and URL above *
// * for the full disclaimer and the limitation of liability.         *
// *                                                                  *
// * This  code  implementation is the result of  the  scientific and *
// * technical work of the GEANT4 collaboration.                      *
// * By using,  copying,  modifying or  distributing the software (or *
// * any work based  on the software)  you  agree  to acknowledge its *
// * use  in  resulting  scientific  publications,  and indicate your *
// * acceptance of all terms of the Geant4 Software license.          *
// ********************************************************************
//
//
// $Id: G4PenelopeAnnihilationTest.cc,v 1.4 2006/06/29 19:44:14 gunter Exp $
// GEANT4 tag $Name: geant4-09-03-cand-01 $
//
// -------------------------------------------------------------------
//      GEANT 4 class file --- Copyright CERN 1998
//      CERN Geneva Switzerland
//
//
//      File name:     G4PenelopeGammaConversionTest.cc
//
//      Author:        Francesco Longo
// 
//      Creation date: 04 january 2001
//
//      Modifications: Luciano Pandola  (03 july 2003)
//                     Adapted in order to test G4PenelopeAnnihilationTest
//                     Minor modification in n-tuple filling
//                     Updated analysis to AIDA 3.0 
//
// -------------------------------------------------------------------

#include "globals.hh"
#include "G4ios.hh"

#include "G4ParticleDefinition.hh"
#include "G4ParticleTypes.hh"
#include "G4ParticleTable.hh"
#include "G4Material.hh"
#include "G4MaterialTable.hh"
#include "G4VDiscreteProcess.hh"
#include "G4VProcess.hh"
#include "G4ProcessManager.hh"

#include "G4PenelopeAnnihilation.hh"
#include "G4eplusAnnihilation.hh"

#include "G4EnergyLossTables.hh"
#include "G4VParticleChange.hh"
#include "G4ParticleChange.hh"
#include "G4DynamicParticle.hh"
#include "G4ForceCondition.hh"

#include "G4PenelopeBremsstrahlung.hh"
#include "G4PenelopeIonisation.hh"
#include "G4MultipleScattering.hh"
#include "G4eIonisation.hh"
#include "G4eBremsstrahlung.hh"
#include "G4eplusAnnihilation.hh"

#include "G4ComptonScattering.hh"
#include "G4PhotoElectricEffect.hh"

#include "G4RunManager.hh"

#include "G4Electron.hh"
#include "G4Positron.hh"
#include "G4Gamma.hh"

#include "G4GRSVolume.hh"
#include "G4Box.hh"
#include "G4PVPlacement.hh"
#include "G4Step.hh"
#include "G4ProductionCutsTable.hh"
#include "G4MaterialCutsCouple.hh"

#include "G4UnitsTable.hh"
#include "AIDA/IManagedObject.h"

#include <memory>
#include "AIDA/IAnalysisFactory.h"
#include "AIDA/ITreeFactory.h"
#include "AIDA/ITree.h"
#include "AIDA/IHistogramFactory.h"
#include "AIDA/IHistogram1D.h"
#include "AIDA/IHistogram2D.h"
#include "AIDA/IHistogram3D.h"
#include "AIDA/ITupleFactory.h"
#include "AIDA/ITuple.h"


G4int main()
{

  // Setup

  G4int nIterations = 100000;
  G4int materialId = 3;

  //G4cout.setf(std::ios::scientific,std::ios::floatfield );

  // -------------------------------------------------------------------

  // ---- HBOOK initialization

  std::auto_ptr< AIDA::IAnalysisFactory > af( AIDA_createAnalysisFactory() );
  std::auto_ptr< AIDA::ITreeFactory > tf (af->createTreeFactory());
  std::auto_ptr< AIDA::ITree > tree (tf->create("pen_ann_test.hbook","hbook",false,true));
  G4cout << "Tree store: " << tree->storeName() << G4endl;
  std::auto_ptr< AIDA::ITupleFactory > tpf (af->createTupleFactory(*tree));
  std::auto_ptr< AIDA::IHistogramFactory > hf (af->createHistogramFactory(*tree));
 
  // ---- secondary ntuple ------
  AIDA::ITuple* ntuple1 = tpf->create("1","Secondary Ntuple","double eprimary,px_1,py_1,pz_1,e_1,theta_1,px_2,py_2,pz_2,e_2,theta_2");

  // ---- table ntuple ------
  AIDA::ITuple* ntuple2 = tpf->create("2","Mean Free Path Ntuple","double kinen,mfp");
    

  //--------- Materials definition ---------

  G4Material* Si  = new G4Material("Silicon",   14., 28.055*g/mole, 2.33*g/cm3);
  G4Material* Fe  = new G4Material("Iron",      26., 55.85*g/mole, 7.87*g/cm3);
  G4Material* Cu  = new G4Material("Copper",    29., 63.55*g/mole, 8.96*g/cm3);
  G4Material*  W  = new G4Material("Tungsten", 74., 183.85*g/mole, 19.30*g/cm3);
  G4Material* Pb  = new G4Material("Lead",      82., 207.19*g/mole, 11.35*g/cm3);
  G4Material*  U  = new G4Material("Uranium", 92., 238.03*g/mole, 18.95*g/cm3);

  G4Element*   H  = new G4Element ("Hydrogen", "H", 1. ,  1.01*g/mole);
  G4Element*   O  = new G4Element ("Oxygen"  , "O", 8. , 16.00*g/mole);
  G4Element*   C  = new G4Element ("Carbon"  , "C", 6. , 12.00*g/mole);
  G4Element*  Cs  = new G4Element ("Cesium"  , "Cs", 55. , 132.905*g/mole);
  G4Element*   I  = new G4Element ("Iodine"  , "I", 53. , 126.9044*g/mole);

  G4Material*  maO = new G4Material("Oxygen", 8., 16.00*g/mole, 1.1*g/cm3);

  G4Material* water = new G4Material ("Water" , 1.*g/cm3, 2);
  water->AddElement(H,2);
  water->AddElement(O,1);

  G4Material* ethane = new G4Material ("Ethane" , 0.4241*g/cm3, 2);
  ethane->AddElement(H,6);
  ethane->AddElement(C,2);
  
  G4Material* csi = new G4Material ("CsI" , 4.53*g/cm3, 2);
  csi->AddElement(Cs,1);
  csi->AddElement(I,1);


  // Interactive set-up

  G4cout << "How many interactions? " << G4endl;
  G4cin >> nIterations;

  if (nIterations <= 0) G4Exception("Wrong input");

  G4double initEnergy = 1.0*MeV; 
  G4double initX = 0.; 
  G4double initY = 0.; 
  G4double initZ = 1.;
  
  G4cout << "Enter the initial particle energy E (MeV)" << G4endl; 
  G4cin >> initEnergy ;

  initEnergy = initEnergy*MeV;
  
  if (initEnergy  < 0.) G4Exception("Wrong input");

  static const G4MaterialTable* theMaterialTable = G4Material::GetMaterialTable();

  G4int nMaterials = G4Material::GetNumberOfMaterials();

  G4cout << "Available materials are: " << G4endl;
  for (G4int mat = 0; mat < nMaterials; mat++)
    {
      G4cout << mat << ") "
	     << (*theMaterialTable)[mat]->GetName()
	     << G4endl;
    }
  
  G4cout << "Which material? " << G4endl;
  G4cin >> materialId;
  
  G4Material* material = (*theMaterialTable)[materialId] ;

  G4cout << "The selected material is: "
	 << material->GetName()
	 << G4endl;
  
  G4double dimX = 1*mm;
  G4double dimY = 1*mm;
  G4double dimZ = 1*mm;
  
  // Geometry 
  
  G4Box* theFrame = new G4Box ("Frame",dimX, dimY, dimZ);
  
  G4LogicalVolume* logicalFrame = new G4LogicalVolume(theFrame,
						      (*theMaterialTable)[materialId],
						      "LFrame", 0, 0, 0);
  logicalFrame->SetMaterial(material); 
  
  G4PVPlacement* physicalFrame = new G4PVPlacement(0,G4ThreeVector(),
						   "PFrame",logicalFrame,0,false,0);

  G4RunManager* rm = new G4RunManager();
  G4cout << "World is defined " << G4endl;
  rm->GeometryHasBeenModified();
  rm->DefineWorldVolume(physicalFrame);

  // Particle definitions
  
  G4ParticleDefinition* gamma = G4Gamma::GammaDefinition();
  G4ParticleDefinition* electron = G4Electron::ElectronDefinition();
  G4ParticleDefinition* positron = G4Positron::PositronDefinition();
  
  G4ProductionCutsTable* cutsTable = G4ProductionCutsTable::GetProductionCutsTable();
  G4ProductionCuts* cuts = cutsTable->GetDefaultProductionCuts();
  G4double cutG=1*micrometer;
  G4double cutE=1*micrometer;
  cuts->SetProductionCut(cutG, 0); //gammas
  cuts->SetProductionCut(cutE, 1); //electrons
  cuts->SetProductionCut(cutE, 2); //positrons
  G4cout << "Cuts are defined " << G4endl;

  //G4Gamma::SetEnergyRange(2.5e-4*MeV,1e5*MeV);
  //G4Electron::SetEnergyRange(2.5e-4*MeV,1e5*MeV);
  //G4Positron::SetEnergyRange(2.5e-4*MeV,1e5*MeV);

  cutsTable->UpdateCoupleTable();
  //cutsTable->DumpCouples();
  const G4MaterialCutsCouple* theCouple = cutsTable->GetMaterialCutsCouple(material,cuts);
  G4int indx=theCouple->GetIndex();
  
  // Processes 
  
  
  G4int processType;
  G4cout << "Standard [1] or Penelope [2] Positron Annihilation?" << G4endl;
  G4cin >> processType;
  if ( !(processType == 1 || processType == 2))
    {
      G4Exception("Wrong input");
    }

  G4VProcess* positronProcess;

  if (processType == 1)
    {
      positronProcess = new G4eplusAnnihilation();
      G4cout << "The selected model is Standard" << G4endl;
    }
  else if (processType == 2)
    {
      positronProcess = new G4PenelopeAnnihilation();
      G4cout << "The selected model is Penelope" << G4endl;
    }
  
  G4VProcess* theeplusMultipleScattering  = new G4MultipleScattering();
  G4VProcess* theeplusIonisation          = new G4PenelopeIonisation();
  G4VProcess* theeplusBremsstrahlung      = new G4PenelopeBremsstrahlung();

  //----------------
  // process manager  
  //----------------


  G4ForceCondition* condition;
  
  //positron
  
  G4ProcessManager* pProcessManager = new G4ProcessManager(positron);
  positron->SetProcessManager(pProcessManager);
  pProcessManager->AddProcess(positronProcess);
 
  // Create a DynamicParticle  
  
  G4double eEnergy = initEnergy*MeV;
  G4ParticleMomentum eDirection(initX,initY,initZ);
  G4DynamicParticle dynamicPositron(positron,eDirection,eEnergy);

  dynamicPositron.DumpInfo(0);
  
  // Track 

  G4ThreeVector aPosition(0.,0.,0.);
  G4double aTime = 0. ;
  
  G4Track* gTrack = new G4Track(&dynamicPositron,aTime,aPosition);

  G4GRSVolume* touche = new G4GRSVolume(physicalFrame, NULL, aPosition);   
  gTrack->SetTouchableHandle(touche); //verificare!!!!!!!!!!!!


  // Step 

  G4Step* step = new G4Step();  
  step->SetTrack(gTrack);

  G4StepPoint* aPoint = new G4StepPoint();
  aPoint->SetPosition(aPosition);
  aPoint->SetMaterial(material);
  aPoint->SetMaterialCutsCouple(theCouple);
  G4double safety = 10000.*cm;
  aPoint->SetSafety(safety);
  step->SetPreStepPoint(aPoint);
 
  // Check applicability
  
  if (! (positronProcess->IsApplicable(*positron)))
    {
      G4Exception("Not Applicable");
    }
  else 
    {
      G4cout<< "applicability OK" << G4endl;
    }

  positronProcess->BuildPhysicsTable(*positron);

  G4cout<< "table OK" << G4endl;
  
  // Test GetMeanFreePath()
  // E' protected! Il membro accessibile e' DumpMeanFreePath()
  
  G4Material* apttoMaterial ;
  G4String MaterialName ;
  
  G4double minArg = 100*eV,maxArg = 100*GeV, argStp;
  const G4int pntNum = 300;
  G4double Tkin[pntNum+1];
  G4double meanFreePath=0. ;

  argStp = (std::log10(maxArg)-std::log10(minArg))/pntNum;
  
  for(G4int d = 0; d < pntNum+1; d++)
    { 
      Tkin[d] = std::pow(10,(std::log10(minArg) + d*argStp));
    }
 
  G4double sti = 1.*mm;
  step->SetStepLength(sti);
  
  //  for ( G4int J = 0 ; J < nMaterials ; J++ )
  //  {
  apttoMaterial = (*theMaterialTable)[materialId] ;
  MaterialName  = apttoMaterial->GetName() ;
  logicalFrame->SetMaterial(apttoMaterial); 
  
  gTrack->SetStep(step);

  G4eplusAnnihilation* positronStdProcess =
    (G4eplusAnnihilation*) positronProcess;
  G4PenelopeAnnihilation* positronPenProcess = 
    (G4PenelopeAnnihilation*) positronProcess;
    
  for (G4int i=0 ; i<pntNum; i++)
    {
      dynamicPositron.SetKineticEnergy(Tkin[i]);
      if (processType == 1)
	{
	  meanFreePath=positronStdProcess
	    ->GetMeanFreePath(*gTrack, sti, condition);
	}
      else if (processType == 2)
	{
	  meanFreePath=positronPenProcess
	    ->DumpMeanFreePath(*gTrack, sti, condition);
	}

      ntuple2->fill(ntuple2->findColumn("kinen"),Tkin[i]/MeV);
      ntuple2->fill(ntuple2->findColumn("mfp"),meanFreePath/cm);
      ntuple2->addRow();

    
      //      G4cout << meanFreePath/cm << G4endl;

    }
  G4cout << "Mean Free Path OK" << G4endl;
  
  // --------- Test the DoIt 
  
  G4cout << "DoIt in " << material->GetName() << G4endl;


  dynamicPositron.SetKineticEnergy(eEnergy);
  G4int iter;
  initEnergy += 2.0*electron_mass_c2;

  for (iter=0; iter<nIterations; iter++)
    {
      
      step->SetStepLength(1*micrometer);
      
      G4cout  <<  "Iteration = "  <<  iter 
	      << "  -  Step Length = " 
	      << step->GetStepLength()/mm << " mm "
	      << G4endl;
      
    
      gTrack->SetStep(step); 
           
      G4VParticleChange* dummy;
      
      G4cout << "eEnergy: " << eEnergy/MeV << " MeV" << G4endl;
      if (eEnergy>0.0) 
	{
	  dummy = positronProcess->PostStepDoIt(*gTrack, *step);
	  G4cout << "Chiamo il Post Step " << G4endl;
	}
      else
	{
	  dummy = positronProcess->AtRestDoIt(*gTrack,*step);
	  G4cout << "Chiamo l'At Rest" << G4endl;
	}

      G4ParticleChange* particleChange = (G4ParticleChange*) dummy;
      
      // Secondaries physical quantities 
           
      // Secondaries 
      G4cout << " secondaries " << 
	particleChange->GetNumberOfSecondaries() << G4endl;
      G4double px_1,py_1,pz_1,e_1,theta_1;
      G4double px_2,py_2,pz_2,e_2,theta_2;
 

      for (G4int i = 0; i < (particleChange->GetNumberOfSecondaries()); i++) 
	{
	  
	  G4Track* finalParticle = particleChange->GetSecondary(i) ;
	  
	  G4double e    = finalParticle->GetTotalEnergy();
	  G4double px   = (finalParticle->GetMomentum()).x();
	  G4double py   = (finalParticle->GetMomentum()).y();
	  G4double pz   = (finalParticle->GetMomentum()).z();
	  G4double theta   = (finalParticle->GetMomentum()).theta();
	  theta = theta/deg; //conversion in degrees
	  if (e > initEnergy)
	    {
	      G4cout << "WARNING: eFinal > eInit " << G4endl;
	    }
	  
	  G4String particleName = 
	    finalParticle->GetDefinition()->GetParticleName();
	  G4cout << "Initial energy " << eEnergy/MeV << G4endl;
	  G4cout  << "==== Final " 
		  <<  particleName  <<  " "  
		  << "energy: " <<  e/MeV  <<  " MeV,  " 
		  << "(px,py,pz): ("
		  <<  px/MeV  <<  "," 
		  <<  py/MeV  <<  ","
		  <<  pz/MeV  << ") MeV "
		  <<  G4endl;   
	  
	  if (particleName == "gamma") {
	    if (i == 0) {	   
	      px_1=px;
	      py_1=py;
	      pz_1=pz;
	      e_1=e;
	      theta_1=theta;
	    }
	    else if (i == 1)
	      {
		px_2 = px;
		py_2 = py;
		pz_2 = pz;
		e_2 = e;
		theta_2 = theta;
	      }
	    else 
	      {
		G4Exception("There are more than 3 gammas?!?");
	      }
	  }
	  delete particleChange->GetSecondary(i);
	}
      
      	  // Fill the secondaries ntuple

      // Normalize all to the energy of primary
      // for gammas initEnergy=initP
      ntuple1->fill(ntuple1->findColumn("eprimary"),eEnergy);
      ntuple1->fill(ntuple1->findColumn("px_1"),px_1/initEnergy);
      ntuple1->fill(ntuple1->findColumn("py_1"),py_1/initEnergy);
      ntuple1->fill(ntuple1->findColumn("pz_1"),pz_1/initEnergy);
      ntuple1->fill(ntuple1->findColumn("e_1"),e_1/initEnergy);
      ntuple1->fill(ntuple1->findColumn("theta_1"),theta_1);
      ntuple1->fill(ntuple1->findColumn("px_2"),px_2/initEnergy);
      ntuple1->fill(ntuple1->findColumn("py_2"),py_2/initEnergy);
      ntuple1->fill(ntuple1->findColumn("pz_2"),pz_2/initEnergy);
      ntuple1->fill(ntuple1->findColumn("e_2"),e_2/initEnergy);
      ntuple1->fill(ntuple1->findColumn("theta_2"),theta_2);
      ntuple1->addRow();
      particleChange->Clear();
      
    } 
  
  
  G4cout  << "Iteration number: "  <<  iter << G4endl;
  
  G4cout << "Committing.............." << G4endl;
  tree->commit();
  G4cout << "Closing the tree........" << G4endl;
  tree->close();
  
  delete step;


  G4cout << "END OF THE MAIN PROGRAM" << G4endl;
  return 0;
}

















