module MW_ions_radius
   use MW_stdio
   use MW_kinds, only: wp
   use MW_algorithms, only: MW_algorithms_t
   use MW_cgaim, only: MW_cgaim_t
   use MW_system, only: MW_system_t
   use MW_ion, only: MW_ion_t

   implicit none
   private

   ! Public subroutines
   ! ------------------
   public :: compute

contains

   !================================================================================
   !> Compute charges on electrode
   !!
   !! The charge is evaluated by minimizing the Coulomb energy of the system
   !!
   !! The energy can be cast into E = Q*AQ - Q*b + c
   !!
   !! where Q  is the vector of charges on the electrodes
   !!       b  is the potential felt by the electrode due to the melt ions
   !!       AQ is the potential felt by the electrode du to other electrode atoms
   !!       c  is the energy due to melt ions interactions
   !!       *  denotes the transpose of a vector/matrix
   !!
   !! By construction A is a matrix symmetric positive definite
   !! The preconditioned conjugate gradient algorithm is used to find a solution to
   !! the system
   !!
!  subroutine compute(system,cgaim, algorithms)
   subroutine compute(system,algorithms)
      use MW_cgaim, only: MW_cgaim_solve => solve
      use MW_ion, only: MW_ion_t
      implicit none

      ! Parameters in
      ! -------------
      type(MW_system_t), intent(inout) :: system !< system parameters
!     type(MW_cgaim_t), intent(in) :: cgaim !< system parameters
      type(MW_algorithms_t), intent(inout) :: algorithms !< cg algorithm parameters

      ! Local
      ! -----
      integer :: num,radius_ions_now!,itmax
      real(wp), allocatable, dimension(:)     :: p
!      real(wp) :: tolaim,ftolaim

!     padding=mod(system%num_ions,cache_line_size)
      num=system%num_ions
!     if(padding>0)num=num+cache_line_size+padding

!     num=system%ions(system%num_ion_types)%count
!     write(6,*)size(system%deltas_ions,1)
!     write(6,*)size(system%epsilons_ions,1)
!     write(6,*)size(system%dipoles_ions,1)

      allocate(p(num*4))

!     itmax=cgaim%max_iterations
!     tolaim=cgaim%tol
!     ftolaim=cgaim%tol

      radius_ions_now=system%radius_ions_step(1)

      p(1:num)=system%deltas_ions(1:num,radius_ions_now)
      p(num+1:2*num)=system%epsilons_ions(1:num,1,radius_ions_now)
      p(2*num+1:3*num)=system%epsilons_ions(1:num,2,radius_ions_now)
      p(3*num+1:4*num)=system%epsilons_ions(1:num,3,radius_ions_now)

      call MW_cgaim_solve(algorithms%cgaim,system,p,num)
!     call MW_cgaim_solve(system,p,num,itmax,tolaim,ftolaim)

      system%deltas_ions(1:num,radius_ions_now)=p(1:num)
      system%epsilons_ions(1:num,1,radius_ions_now)=p(num+1:2*num)
      system%epsilons_ions(1:num,2,radius_ions_now)=p(2*num+1:3*num)
      system%epsilons_ions(1:num,3,radius_ions_now)=p(3*num+1:4*num)

   end subroutine compute

   ! ================================================================================

end module MW_ions_radius
