! See copyright notice in the COPYRIGHT file.
!mpi!nprocs = 2 
program mem_for_mpi_test
  use, intrinsic :: iso_c_binding, only: c_ptr, c_f_pointer
  use hvs_sizeof_module, only: c_sizeof
  use mpi
  use mem_for_mpi_module

  implicit none

  integer          :: iError
  type(c_ptr)      :: buffer
  integer, pointer :: fordat(:)
  integer          :: intsize
  integer          :: myrank
  integer          :: rstat(MPI_STATUS_SIZE)

  call MPI_Init(iError)

  call MPI_Comm_rank(MPI_COMM_WORLD, myrank, iError)

  if (myrank == 0) then
    write(*,*) 'Starting test for alloc_mpif_mem'
  end if
  intsize = c_sizeof(iError)

  ! Allocate 10 integers:
  call alloc_mpif_mem( asize   = intsize*10_MPI_ADDRESS_KIND, &
    &                  baseptr = buffer,                      &
    &                  ierr    = iError                       )
  if (myrank == 0) then
    write(*,*) 'Allocated memory with iError=', iError

    write(*,*) 'Converting C pointer to Fortran array'
  end if
  call c_f_pointer(buffer, fordat, [10])

  if (myrank == 0) then
    write(*,*) 'Assigning a value to the buffer with size:', size(fordat)
    fordat = 42
    write(*,*) 'Sending data from rank 0 to rank 1'
    call MPI_Send(fordat, 10, MPI_Integer, 1, 23, MPI_COMM_WORLD, iError)
  else
    call MPI_Recv(fordat, 10, MPI_Integer, 0, 23, MPI_COMM_WORLD, rstat, iError)
    write(*,*) 'Received data from rank 0 on rank 1'
    if (all(fordat == 42)) then
      write(*,*) 'Freeing MPI allocation again'
      nullify(fordat)
      call free_mpif_mem(buffer)
      write(*,*) 'PASSED'
    else
      write(*,*) 'FAILED'
    end if
  end if

  call MPI_Finalize(iError)

end program mem_for_mpi_test
