#!/usr/bin/env ruby
require("gsl")
include CONST::CGSM
include CONST::NUM
include Odeiv
include Math

NDIM = 4

proc = Proc.new { |t, r, drdt, coef|
  x = r[0]
  y = r[1]
  vx = r[2]
  vy = r[3]
  r3 = pow_3(sqrt(x*x + y*y))
  drdt[0] = vx
  drdt[1] = vy
  drdt[2] = coef*x/r3
  drdt[3] = coef*y/r3
}


ALPHA_MASS = 3755.7*MEGA*ELECTRON_VOLT/pow_2(SPEED_OF_LIGHT)
#p ALPHA_MASS
Ztarget = 88
coef = 2.0*Ztarget*pow_2(ELECTRON_CHARGE_ESU)/ALPHA_MASS
KinEnergy = 5.3*MEGA*ELECTRON_VOLT
v0 = sqrt(2.0*KinEnergy/ALPHA_MASS)
#printf("%e\n", v0)
#exit

solver = Odeiv::Solver.new(Odeiv::Step::RKF45, [1e-8, 0.0], proc, NDIM)
solver.set_params(coef)

ImpactParameter = [1e-7, 1.0001e-7, 1.0002e-7, 1.0003e-7, 1.001e-7]
ImpactParameter.each_index do |i|
  b = ImpactParameter[i]
#  x0 = 10*b
  x0 = b*4
  
  solver.reset

  r = Vector.new([-x0, b, v0, 0.0])
  h = b/v0/100
  t = 0.0
  tend = 1e10
  
  # initial time step
  
  begin
    file = File.open("rutherford#{i}.dat", "w") 
    while t < tend 
      status = solver.apply(t, tend, h, r)
      break if status != GSL::SUCCESS
      file.printf("%e %e %e %e %e\n", t, r[0], r[1], r[2], r[3])
      break if r[0] > x0
    end
  ensure
    file.close
  end
end

#system("gnuplot -persist rutherford.gp")
#File.delete("rutherford.dat")
