
  !=========================================================================!
  ! Key Internal Variables:                                                 !
  !          seedname - the seedname  that was passed on the command line   !
  !-------------------------------------------------------------------------!
  ! Rajany K. V. on 13/March/2023 using the libcastep.so and castep_lib.f90 !                                          !
  ! written by Peter Byrne.                                                 !
  !=========================================================================!
  
  subroutine castepfunc(input_seed, initial, is_root, communicator, &
                        energy, forces, new_lattice, new_positions, natoms)

  !castep_lib.mod is used to call the functions in the corresponding library
  use castep_lib, only     :  initialise, calculate_energy, calculate_forces,&
                              update_lattice_and_positions

  implicit none

  !Rajany: this is the double used in castep
  integer, parameter :: dp=selected_real_kind(15,300)
  logical, save :: initialised = .false.
  
  character(len=*), intent(in)         :: input_seed
  logical         , intent(in)         :: initial
  logical         , intent(in)         :: is_root
  integer(kind=4) , intent(in)         :: communicator
  real(kind=dp)   , intent(inout)      :: energy
  real(kind=dp), dimension(:,:), allocatable,  intent(out) :: forces
  real(kind=dp), dimension(3,3), intent(inout)             :: new_lattice
  real(kind=dp), dimension(:,:), intent(in)                :: new_positions
  integer(kind=4) , intent(in)         :: natoms

  !Rajany: Other arguments
  integer                              :: linput
  character(len=:), allocatable        :: input_seedname


  linput=len(trim(adjustl(input_seed)))

  allocate(character(len=linput):: input_seedname)
  allocate(forces(3,natoms))
  !print *, forces  
  !flush(6)
  input_seedname = input_seed(1:linput)

  if(initial) then
      if(is_root) then
          write(*, '(/A/)') " ChemShell/CASTEP: initialising..." ! New line !! .. text string new line
          call flush(6)
      endif
      call initialise(communicator,input_seedname)
      !write(*,'(/A/)') "Initialized"
      !call flush(6)
      !endif
  else
      call update_lattice_and_positions(new_lattice, new_positions)
      !write(*,'(/A/)') "Updated positions"
      !call flush(6)
  endif

  call calculate_energy(energy)
  call calculate_forces(forces)

  deallocate(input_seedname)
end subroutine castepfunc
