program main
   use, intrinsic :: iso_c_binding, only: C_PTR, c_f_pointer
   use mpi
   implicit none

   integer :: rank, ierror
   integer :: win
   integer :: group, t_group

   integer, parameter :: N = 50
   type (C_PTR) :: base1
   integer, pointer :: buffer(:)
   integer :: send_buffer(N)
   integer(kind=MPI_ADDRESS_KIND) :: sz
   integer :: i
   integer(kind=MPI_ADDRESS_KIND) :: disp=0
   integer(kind=MPI_ADDRESS_KIND) :: zero=0
   integer :: status(MPI_STATUS_SIZE)


   call MPI_Init(ierror)
   call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierror)
   call MPI_Comm_group(MPI_COMM_WORLD, t_group, ierror)
   call MPI_Group_incl(t_group, 1, [1-rank], group, ierror)



   ! Establish window
   call MPI_Win_create_dynamic(MPI_INFO_NULL, MPI_COMM_WORLD, win, ierror)

   if (rank == 1) then
      sz = 4*N  ! 4 bytes per integer
      call MPI_alloc_mem(sz, MPI_INFO_NULL, base1, ierror)
      call c_f_pointer(base1, buffer, [N])
      buffer = 0
      call MPI_Win_attach(win, buffer(1), sz, ierror)

      ! Why is this step necessary?
      call MPI_Send(base1, 2, MPI_INTEGER, 0, 10, MPI_COMM_WORLD, ierror)
      call MPI_Win_post(group, 0, win, ierror)
   end if


   select case(rank)
   case (0) ! sender
      call MPI_Win_start(group, 0, win, ierror)

      send_buffer = [(i,i=1,N)]

      ! Why is this step necessary?
      call MPI_Recv(disp, 2, MPI_INTEGER, 1, 10, MPI_COMM_WORLD, status, ierror)
      ! The call below appears to work
      call MPI_put(send_buffer(1), N, MPI_INTEGER, 1, disp, N, MPI_INTEGER, win, ierror)
      ! The call below causes a seg fault
!!$      call MPI_put(send_buffer(1), N, MPI_INTEGER, 1, zero, N, MPI_INTEGER, win, ierror)
      call MPI_Win_complete(win, ierror)

   case (1) ! receiver

      call MPI_Win_wait(win, ierror)
      
      print*,'Expect 1 2 ... 50.'
      print*,'Got :', buffer(1:N)

      call MPI_Win_detach(win, base1, ierror)
   end select

   call MPI_Barrier(MPI_COMM_WORLD, ierror)
   call MPI_Win_free(win, ierror)

   call MPI_Finalize(ierror)

end program main

