!
! CDDL HEADER START
!
! The contents of this file are subject to the terms of the Common Development
! and Distribution License Version 1.0 (the "License").
!
! You can obtain a copy of the license at
! http://www.opensource.org/licenses/CDDL-1.0.  See the License for the
! specific language governing permissions and limitations under the License.
!
! When distributing Covered Code, include this CDDL HEADER in each file and
! include the License file in a prominent location with the name LICENSE.CDDL.
! If applicable, add the following below this CDDL HEADER, with the fields
! enclosed by brackets "[]" replaced with your own identifying information:
!
! Portions Copyright (c) [yyyy] [name of copyright owner]. All rights reserved.
!
! CDDL HEADER END
!

!
! Copyright (c) 2013--2014, Regents of the University of Minnesota.
! All rights reserved.
!
! Contributors:
!    Ellad B. Tadmor
!    Ryan S. Elliott
!    Stephen M. Whalen
!

!
! Release: This file is part of the kim-api.git package.
!


#include "KIM_API_status.h"
#define THIS_FILE_NAME __FILE__
#define TRUEFALSE(TRUTH) merge(1,0,(TRUTH))

!-------------------------------------------------------------------------------
!
! module mod_neighborlist :
!
!    Module contains type and routines related to neighbor list calculation
!
!-------------------------------------------------------------------------------

module mod_neighborlist

  use, intrinsic :: iso_c_binding
  use KIM_API_F03

  public setup_neighborlist_KIM_access, get_neigh

  type neighObject_type
     integer(c_int), pointer :: neighborList(:,:)
     real(c_double), pointer :: RijList(:,:,:)
  end type neighObject_type

contains

!-------------------------------------------------------------------------------
!
! setup_neighborlist_KIM_access :
!
!    Store necessary pointers in KIM API object to access the neighbor list
!    data and methods.
!
!-------------------------------------------------------------------------------
subroutine setup_neighborlist_KIM_access(pkim, neighObject)
  implicit none

  !-- Transferred variables
  type(c_ptr),                    intent(in) :: pkim
  type(neighObject_type), target, intent(in) :: neighObject

  !-- Local variables
  integer(c_int), parameter :: SizeOne = 1
  integer(c_int)            :: ier, idum

  ! store location of neighObject variable
  !
  ier = kim_api_set_data(pkim, "neighObject", SizeOne, c_loc(neighObject))
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_set_data", ier)
     stop
  endif
  ier = kim_api_set_method(pkim, "get_neigh", SizeOne, c_funloc(get_neigh))
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_set_method", ier)
     stop
  endif

  return

end subroutine setup_neighborlist_KIM_access

!-------------------------------------------------------------------------------
!
! get_neigh neighbor list access function
!
! This function implements Locator and Iterator mode
!
!-------------------------------------------------------------------------------
integer(c_int) function get_neigh(pkim,mode,request,part,numnei,pnei1part, &
                                  pRij) bind(c)
  implicit none

  !-- Transferred variables
  type(c_ptr),    intent(in)  :: pkim
  integer(c_int), intent(in)  :: mode
  integer(c_int), intent(in)  :: request
  integer(c_int), intent(out) :: part
  integer(c_int), intent(out) :: numnei
  type(c_ptr),    intent(out) :: pnei1part
  type(c_ptr),    intent(out) :: pRij

  !-- Local variables
  integer(c_int), parameter :: DIM = 3
  integer(c_int), save :: iterVal = 0
  integer(c_int)  N
  integer(c_int)  partToReturn
  integer(c_int), pointer :: numberOfParticles;   type(c_ptr) :: pnParts
  type(neighObject_type), pointer :: neighObject; type(c_ptr) :: pneighObject
  integer(c_int)  ier, idum

  ! unpack number of particles
  pnParts = kim_api_get_data(pkim, "numberOfParticles", ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_get_data", ier)
     stop
  endif
  call c_f_pointer(pnParts, numberOfParticles)

  ! unpack neighbor list object
  pneighObject = kim_api_get_data(pkim, "neighObject", ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_get_data", ier)
     stop
  endif
  call c_f_pointer(pneighObject, neighObject)

  N = size(neighObject%neighborList, 2)

  ! check mode and request
  if (mode.eq.0) then ! iterator mode
     if (request.eq.0) then ! reset iterator
        iterVal = 0
        get_neigh = KIM_STATUS_NEIGH_ITER_INIT_OK
        return
     elseif (request.eq.1) then ! increment iterator
        iterVal = iterVal + 1
        if (iterVal.gt.N) then
           get_neigh = KIM_STATUS_NEIGH_ITER_PAST_END
           return
        else
           partToReturn = iterVal
        endif
     else
        idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                    "Invalid request in get_neigh", &
                                    KIM_STATUS_NEIGH_INVALID_REQUEST)
        get_neigh = KIM_STATUS_NEIGH_INVALID_REQUEST
        return
     endif
  elseif (mode.eq.1) then ! locator mode
     if ( (request.gt.N) .or. (request.lt.1)) then
        idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                    "Invalid part ID in get_neigh", &
                                    KIM_STATUS_PARTICLE_INVALID_ID)
        get_neigh = KIM_STATUS_PARTICLE_INVALID_ID
        return
     else
        partToReturn = request
     endif
  else ! not iterator or locator mode
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "Invalid mode in get_neigh", &
                                 KIM_STATUS_NEIGH_INVALID_MODE)
     get_neigh = KIM_STATUS_NEIGH_INVALID_MODE
     return
  endif

  ! set the returned part
  part = partToReturn

  ! set the returned number of neighbors for the returned part
  numnei = neighObject%neighborList(1,part)

  ! set the location for the returned neighbor list
  pnei1part = c_loc(neighObject%neighborList(2,part))

  ! set pointer to Rij to appropriate value
  if (associated(neighObject%RijList)) then
    pRij = c_loc(neighObject%RijList(1,1,part))
  else
    pRij = c_null_ptr
  endif

  get_neigh = KIM_STATUS_OK
  return
end function get_neigh

end module mod_neighborlist

!*******************************************************************************
!**
!**  PROGRAM ex_test_ArNe_B2cohesive_NEIGH_RVEC
!**
!**  KIM compliant program to find (using the Golden section search algorithm)
!**  the minimum energy of one particle in a periodic B2 crystal of Ar and Ne as a
!**  function of lattice spacing.
!**
!**  Works with the following NBC methods:
!**        NEIGH_RVEC_H
!**        NEIGH_RVEC_F
!**
!*******************************************************************************

!-------------------------------------------------------------------------------
!
! Main program
!
!-------------------------------------------------------------------------------
program ex_test_ArNe_B2cohesive_NEIGH_RVEC
  use, intrinsic :: iso_c_binding
  use KIM_API_F03
  use mod_neighborlist
  implicit none
  integer(c_int), parameter :: cd = c_double ! used for literal constants

!============================== VARIABLE DEFINITIONS ==========================

  ! parameters controlling behavior of test
  !
  character(len=KIM_KEY_STRING_LENGTH), parameter :: testname = "ex_test_ArNe_B2cohesive_NEIGH_RVEC"
  character(len=KIM_KEY_STRING_LENGTH), parameter :: testkimfile = "descriptor.kim"
  character(len=2), parameter :: specname1   = 'Ar'
  character(len=2), parameter :: specname2   = 'Ne'
  real(c_double),   parameter :: TOL         = 1.0e-8_cd
  real(c_double),   parameter :: B2spacing   = 5.260d0 ! in angstroms
  real(c_double),   parameter :: MinSpacing  = 0.60_cd*B2spacing
  real(c_double),   parameter :: MaxSpacing  = 1.20_cd*B2spacing
  integer(c_int),   parameter :: DIM         = 3
  integer(c_int),   parameter :: SupportHalf = 1            ! True

  ! significant local variables
  !
  real(c_double)  :: rcut               ! cutoff radius of the potential
  real(c_double)  :: FinalSpacing       ! crystal lattice parameter
  real(c_double)  :: FinalEnergy        ! energy per particle of crystal
                                        ! at current spacing
  integer(c_int)  :: CellsPerRcut       ! number of unit cells along
                                        ! box (of size rcut) side
  integer(c_int)  :: N                  ! number of particles

  ! neighbor list
  !
  type(neighObject_type), target :: neighObject
  integer(c_int)  :: NNeighbors  ! maximum number of neighbors for a particle

  ! KIM variables
  !
  character(len=KIM_KEY_STRING_LENGTH) :: modelname  ! KIM-compliant model name
  type(c_ptr)    :: pkim          ! pointer to KIM API object
  integer(c_int) :: ier           ! error flag

  real(c_double), pointer :: cutoff;        type(c_ptr) :: pcutoff


  ! other variables
  !
  real(c_double), external ::  get_model_cutoff_firsttime
  integer(c_int)           ::  idum

!========================= END VARIABLE DEFINITIONS ==========================


  ! Read in KIM Model name to use
  !
  print '("Please enter a KIM-compliant model name: ")'
  read(*,*) modelname


  ! We'll use just two particles (one Ar and one Ne)
  ! for this calculation!
  !
  N = 2


  ! Setup the KIM API object
  !
  call setup_B2_KIM_API_object(pkim, testkimfile, modelname, specname1, specname2)


  ! allocate storage for neighbor lists, compute them for the first time,
  ! and store necessary pointers in KIM API object
  !
  ! First, access the `cutoff' arguemt
  !
  pcutoff = kim_api_get_data(pkim, "cutoff", ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_get_data", ier)
     stop
  endif
  call c_f_pointer(pcutoff, cutoff)
  rcut = cutoff
  !
  ! Second, determine how many neighbors we will need
  !
  CellsPerRcut = ceiling(rcut/MinSpacing+ 0.05_cd) ! the 0.05 is a saftey factor
  NNeighbors = 2*((2*CellsPerRcut + 1)**3)
  !
  ! allocate memory for the neighbor list and Rij vectors
  !
  allocate(neighObject%neighborList(NNeighbors+1,N))
  allocate(neighObject%RijList(3,NNeighbors+1,N))
  call setup_neighborlist_KIM_access(pkim, neighObject)


  ! find equilibrium spacing by minimizing coheseive energy with respect
  ! to the periodic box size
  !
  call NEIGH_RVEC_compute_equilibrium_spacing(pkim, &
         DIM,CellsPerRcut,MinSpacing,MaxSpacing, &
         TOL,N,neighObject,                      &
         .false.,FinalSpacing,FinalEnergy)

  ! print results to screen
  !
  print '(80(''-''))'
  print '("This is Test          : ",A)', trim(testname)
  print '("Results for KIM Model : ",A)', trim(modelname)
  print *
  print '("Found minimum energy configuration to within",ES25.15)', TOL
  print *
  print '("Energy/part = ",ES25.15,"; Spacing = ",ES25.15)', FinalEnergy, &
        FinalSpacing
  print '(80(''-''))'


  ! Don't forget to free and/or deallocate
  !
  deallocate(neighObject%neighborList)
  deallocate(neighObject%RijList)
  call free_KIM_API_object(pkim)

  stop

end program ex_test_ArNe_B2cohesive_NEIGH_RVEC

!-------------------------------------------------------------------------------
!
! NEIGH_RVEC_compute_equilibrium_spacing :
!
!    Use the Golden section search algorithm to find the equilibrium spacing by
!    minimizing the energy of the system with respect to the periodic box size.
!
!-------------------------------------------------------------------------------
subroutine NEIGH_RVEC_compute_equilibrium_spacing(pkim, &
             DIM,CellsPerRcut,MinSpacing,MaxSpacing, &
             TOL,N,neighObject,                      &
             verbose,RetSpacing,RetEnergy)
  use, intrinsic :: iso_c_binding
  use KIM_API_F03
  use mod_neighborlist
  implicit none
  integer(c_int), parameter :: cd = c_double ! used for literal constants

  !-- Transferred variables
  type(c_ptr),            intent(in)    :: pkim
  integer(c_int),         intent(in)    :: DIM
  integer(c_int),         intent(in)    :: CellsPerRcut
  real(c_double),         intent(in)    :: MinSpacing
  real(c_double),         intent(in)    :: MaxSpacing
  real(c_double),         intent(in)    :: TOL
  integer(c_int),         intent(in)    :: N
  type(neighObject_type), intent(inout) :: neighObject
  logical,                intent(in)    :: verbose
  real(c_double),         intent(out)   :: RetSpacing
  real(c_double),         intent(out)   :: RetEnergy

  !-- Local variables
  real(c_double), parameter :: Golden = (1.0_cd + sqrt(5.0_cd))/2.0_cd
  integer(c_int) ier, idum
  real(c_double) Spacings(4)
  real(c_double) Energies(4)
  real(c_double), pointer :: energy;       type(c_ptr) penergy
  real(c_double), pointer :: coords(:,:);  type(c_ptr) pcoor
  real(c_double), pointer :: cutoff;       type(c_ptr) pcutoff
  real(c_double), parameter :: cutpad = 0.750d0 ! in angstroms ! cutoff radius padding
  logical :: halfflag  ! .true. = half neighbor list; .false. = full neighbor list
  character(len=KIM_KEY_STRING_LENGTH) :: NBC_Method

  ! Unpack data from KIM object
  !
  call kim_api_getm_data(pkim, ier, &
       "energy",      penergy, 1, &
       "coordinates", pcoor,   1, &
       "cutoff",      pcutoff, 1)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_getm_data", ier)
     stop
  endif
  call c_f_pointer(penergy, energy)
  call c_f_pointer(pcoor, coords, [DIM,N])
  call c_f_pointer(pcutoff, cutoff)

  ! determine which neighbor list type to use
  !
  ier = kim_api_get_nbc_method(pkim, NBC_Method)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                "kim_api_get_nbc_method", ier)
     stop
  endif
  if (index(NBC_Method,"NEIGH_RVEC_H").eq.1) then
     halfflag = .true.
  elseif (index(NBC_Method,"NEIGH_RVEC_F").eq.1) then
     halfflag = .false.
  else
     ier = KIM_STATUS_FAIL
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "Unknown NBC method", ier)
     return
  endif

  ! Initialize for minimization
  !
  Spacings(1) = MinSpacing
  ! compute new neighbor lists (could be done more intelligently, I'm sure)
  call NEIGH_RVEC_periodic_B2_neighborlist(halfflag, CellsPerRcut,       &
                                           (cutoff+cutpad), Spacings(1), &
                                           neighObject, coords)
  ier = kim_api_model_compute(pkim)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_model_compute", ier)
     stop
  endif
  Energies(1) = energy
  if (verbose) &
     print '("Energy/part = ",ES25.15,"; Spacing = ",ES25.15)', Energies(1), &
           Spacings(1)

  ! setup and compute for max spacing
  Spacings(3) = MaxSpacing
  ! compute new neighbor lists (could be done more intelligently, I'm sure)
  call NEIGH_RVEC_periodic_B2_neighborlist(halfflag, CellsPerRcut,       &
                                           (cutoff+cutpad), Spacings(3), &
                                           neighObject, coords)
  ! Call model compute
  ier = kim_api_model_compute(pkim)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_model_compute", ier)
     stop
  endif
  Energies(3) = energy
  if (verbose) &
     print '("Energy/part = ",ES25.15,"; Spacing = ",ES25.15)', Energies(3), &
           Spacings(3)

  ! setup and compute for first intermediate spacing
  Spacings(2) = MinSpacing + (2.0_cd - Golden)*(MaxSpacing - MinSpacing)
  ! compute new neighbor lists (could be done more intelligently, I'm sure)
  call NEIGH_RVEC_periodic_B2_neighborlist(halfflag, CellsPerRcut,       &
                                           (cutoff+cutpad), Spacings(2), &
                                           neighObject, coords)
  ! Call model compute
  ier = kim_api_model_compute(pkim)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_model_compute", ier)
     stop
  endif
  Energies(2) = energy
  if (verbose) &
     print '("Energy/part = ",ES25.15,"; Spacing = ",ES25.15)', Energies(2), &
           Spacings(2)


  ! iterate until convergence.
  !
  do while (abs(Spacings(3) - Spacings(1)) .gt. TOL)
     ! set new spacing
     Spacings(4) = (Spacings(1) + Spacings(3)) - Spacings(2)
     ! compute new neighbor lists (could be done more intelligently, I'm sure)
     call NEIGH_RVEC_periodic_B2_neighborlist(halfflag, CellsPerRcut,       &
                                              (cutoff+cutpad), Spacings(4), &
                                              neighObject, coords)
     ! Call model compute
     ier = kim_api_model_compute(pkim)
     if (ier.lt.KIM_STATUS_OK) then
        idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                    "kim_api_model_compute", ier)
        stop
     endif
     Energies(4) = energy
     if (verbose) &
        print '("Energy/part = ",ES25.15,"; Spacing = ",ES25.15)', Energies(4),&
              Spacings(4)

     ! determine the new interval
     if (Energies(4) .lt. Energies(2)) then
        ! We want the right-hand interval
        Spacings(1) = Spacings(2); Energies(1) = Energies(2)
        Spacings(2) = Spacings(4); Energies(2) = Energies(4)
     else
        ! We want the left-hand interval
        Spacings(3) = Spacings(1); Energies(3) = Energies(1)
        Spacings(1) = Spacings(4); Energies(1) = Energies(4)
     endif
  enddo

  ! pull out results and return
  !
  RetSpacing = Spacings(2)
  RetEnergy  = Energies(2)

  return

end subroutine NEIGH_RVEC_compute_equilibrium_spacing

!-------------------------------------------------------------------------------
!
! setup_B2_KIM_API_object : Create KIM API object,
!                           allocate memory and set known values.
!
!-------------------------------------------------------------------------------
subroutine setup_B2_KIM_API_object(pkim, testkimfile, modelname, specname1, &
                                   specname2)
  use, intrinsic :: iso_c_binding
  use KIM_API_F03
  implicit none

  !-- Transferred variables
  type(c_ptr),                          intent(out) :: pkim
  character(len=KIM_KEY_STRING_LENGTH), intent(in)  :: testkimfile
  character(len=KIM_KEY_STRING_LENGTH), intent(in)  :: modelname
  character(len=2),                     intent(in)  :: specname1
  character(len=2),                     intent(in)  :: specname2

  !-- Local variables
  integer(c_int)            :: N = 2 ! hard-wired to two particles
  integer(c_int), parameter :: ASpecies = 2  ! hard-wired to two species
  integer(c_int) ier, idum
  integer(c_int), pointer :: numberOfParticles;   type(c_ptr) :: pnParts
  integer(c_int), pointer :: numberOfSpecies;     type(c_ptr) :: pnOfSpecies
  integer(c_int), pointer :: particleSpecies(:);    type(c_ptr) :: pparticleSpecies

  ! Initialize KIM API object
  !
  ier = kim_api_file_init(pkim, testkimfile, modelname)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_file_init", ier)
     stop
  endif
  call kim_api_allocate(pkim, N, ASpecies, ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_allocate", ier)
     stop
  endif

  ! call model's init routine
  !
  ier = kim_api_model_init(pkim)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_model_init", ier)
     stop
  endif

  ! Unpack data from KIM object whose values need to be set
  !
  call kim_api_getm_data(pkim, ier, &
       "numberOfParticles", pnParts,          1, &
       "numberOfSpecies",   pnOfSpecies,      1, &
       "particleSpecies",   pparticleSpecies, 1)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_getm_data", ier)
     stop
  endif
  call c_f_pointer(pnParts,          numberOfParticles)
  call c_f_pointer(pnOfSpecies,      numberOfSpecies)
  call c_f_pointer(pparticleSpecies, particleSpecies, [N])

  ! Set values
  !
  numberOfParticles   = N
  numberOfSpecies = ASpecies
  particleSpecies(1)    = kim_api_get_species_code(pkim, specname1, ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_get_species_code", ier)
     stop
  endif
  particleSpecies(2)    = kim_api_get_species_code(pkim, specname2, ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_get_species_code", ier)
     stop
  endif

  return

end subroutine setup_B2_KIM_API_object

!-------------------------------------------------------------------------------
!
! free_KIM_API_object : Deallocate storage and destroy KIM API object
!
!-------------------------------------------------------------------------------
subroutine free_KIM_API_object(pkim)
  use, intrinsic :: iso_c_binding
  use KIM_API_F03
  implicit none

  !-- Transferred variables
  type(c_ptr), intent(in)  :: pkim

  !-- Local variables
  integer(c_int) ier, idum

  ! call the model destroy function
  !
  ier = kim_api_model_destroy(pkim)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_model_destroy", ier)
     stop
  endif

  ! free all KIM API object storage
  !
  call kim_api_free(pkim, ier)
  if (ier.lt.KIM_STATUS_OK) then
     idum = kim_api_report_error(__LINE__, THIS_FILE_NAME, &
                                 "kim_api_free", ier)
     stop
  endif

  return

end subroutine free_KIM_API_object

!-------------------------------------------------------------------------------
!
! NEIGH_RVEC_periodic_B2_neighborlist
!
!-------------------------------------------------------------------------------
subroutine NEIGH_RVEC_periodic_B2_neighborlist(half,CellsPerHalfSide, cutoff,  &
                                               B2spacing, neighObject, coords)
  use, intrinsic :: iso_c_binding
  use KIM_API_F03
  use mod_neighborlist
  implicit none
  integer(c_int), parameter :: cd = c_double ! used for literal constants

  !-- Transferred variables
  logical,                             intent(in)    :: half
  integer(c_int),                      intent(in)    :: CellsPerHalfSide
  real(c_double),                      intent(in)    :: cutoff
  real(c_double),                      intent(in)    :: B2spacing
  type(neighObject_type),              intent(inout) :: neighObject
  real(c_double), dimension(3,2),      intent(out)   :: coords

  !-- Local variables
  real(c_double) dx(3)
  real(c_double) cutoff2
  real(c_double) B2shifts(3,2)
  real(c_double) latVec(3)
  integer(c_int) part, a, i, j, k, m

  cutoff2 = cutoff**2

  ! Cubic B2 cell positions ----------------------------------------------------
  B2shifts(1,1) = 0.0_cd
  B2shifts(2,1) = 0.0_cd
  B2shifts(3,1) = 0.0_cd
  B2shifts(1,2) = 0.5_cd*B2spacing
  B2shifts(2,2) = 0.5_cd*B2spacing
  B2shifts(3,2) = 0.5_cd*B2spacing

  ! set coords
  coords(:,1) = B2shifts(1,1)
  coords(:,2) = B2shifts(1,2)

  if (half) then
     ! Each part gets half of its own neighbor-self images
     do part = 2,1,-1  ! have part 1 be last in the loop
        a = 1
        do i = 0, CellsPerHalfSide
           latVec(1) = i*B2spacing
           do j = -CellsPerHalfSide, CellsPerHalfSide
              latVec(2) = j*B2spacing
              do k = -CellsPerHalfSide, CellsPerHalfSide
                 latVec(3) = k*B2spacing
                 if (i.gt.0 .or. (i.eq.0 .and. (j.gt.0 .or. &
                                                  (j.eq.0 .and. k.gt.0)))) then
                    dx = latVec
                    if (dot_product(dx,dx).lt.cutoff2) then
                       ! we have a neighbor
                       a = a + 1
                       neighObject%neighborList(a,part) = part
                       neighObject%RijList(:,a-1,part)  = dx
                    endif
                 endif
              enddo
           enddo
        enddo
        ! this part has a-1 neighbors (so far)
        neighObject%neighborList(1,part) = a - 1
     enddo

     ! Part 1 gets all images of part 2; part 2 gets no part 1 images
     do i = -CellsPerHalfSide, CellsPerHalfSide
        latVec(1) = i*B2spacing
        do j = -CellsPerHalfSide, CellsPerHalfSide
           latVec(2) = j*B2spacing
           do k = -CellsPerHalfSide, CellsPerHalfSide
              latVec(3) = k*B2spacing
              dx = (latVec + B2shifts(:,2)) - B2shifts(:,1)
              if (dot_product(dx,dx).lt.cutoff2) then
                 ! we have a neighbor
                 a = a + 1
                 neighObject%neighborList(a,part) = 2
                 neighObject%RijList(:,a-1,part)  = dx
              endif
           enddo
        enddo
     enddo

     ! part 1 has a-1 neighbors
     neighObject%neighborList(1,1) = a - 1
  else
     do part = 1,2
        a = 1
        do i=-CellsPerHalfSide,CellsPerHalfSide
           latVec(1) = i*B2spacing
           do j=-CellsPerHalfSide,CellsPerHalfSide
              latVec(2) = j*B2spacing
              do k=-CellsPerHalfSide,CellsPerHalfSide
                 latVec(3) = k*B2spacing
                 do m=1,2
                    dx = (latVec + B2shifts(:,m)) - B2shifts(:,part)
                    if (dot_product(dx,dx).lt.cutoff2) then
                       if (.not.( (i.eq.0) .and. (j.eq.0) .and. (k.eq.0) .and. &
                                  (m.eq.part) )) then
                          ! we have a neighbor
                          a = a+1
                          neighObject%neighborList(a,part) = m
                          neighObject%RijList(:,a-1,part)  = dx
                       endif
                    endif
                 enddo
              enddo
           enddo
        enddo
        ! part 1 has a-1 neighbors
        neighObject%neighborList(1,part) = a-1
     enddo
  endif

  return

end subroutine NEIGH_RVEC_periodic_B2_neighborlist

