! This program shows a bug in gcc that becomes visible
! in MPICH
! when passing **allocatable** buffers to functions such as
! MPI_Irecv or MPI_Send
! After the respective function call, the bounds of the buffer argument are changed to C-like 0-based indices
!
! See this issue in MPICH: https://github.com/pmodels/mpich/issues/4170
! When using MPICH compiled with the intel compilers, this bug is not present.
program main
    use mpi_f08
    implicit none

    integer :: i, world_rank, world_size, ierr

    type(MPI_Request) :: request
    type(MPI_Status) :: status

    real, dimension(:), allocatable :: send_buf, recv_buf

    integer, parameter :: tag = 123789

    call MPI_Init(ierr)

    call MPI_Comm_rank(MPI_COMM_WORLD, world_rank, ierr)
    call MPI_Comm_size(MPI_COMM_WORLD, world_size, ierr)

    send_buf = (/1., 2., 3., 4., 5./)
    recv_buf = (/0., 0., 0., 0., 0./)


    write(*, '(a)') "Before Irecv"
    write(*, '(a,i2,a,i2,a,(5f5.1))') "send buf(", lbound(send_buf), ":", ubound(send_buf), ") =", send_buf
    write(*, '(a,i2,a,i2,a,(5f5.1))') "recv buf(", lbound(recv_buf), ":", ubound(recv_buf), ") =", recv_buf

    call MPI_Irecv(recv_buf, 5, MPI_REAL, world_rank, tag, MPI_COMM_WORLD, request, ierr)

    write(*, '(a)') "After Irecv, before Send"
    write(*, '(a,i2,a,i2,a,(5f5.1))') "send buf(", lbound(send_buf), ":", ubound(send_buf), ") =", send_buf
    write(*, '(a,i2,a,i2,a,(5f5.1))') "recv buf(", lbound(recv_buf), ":", ubound(recv_buf), ") =", recv_buf

    call MPI_Send(send_buf, 5, MPI_REAL, world_rank, tag, MPI_COMM_WORLD, ierr)

    write(*, '(a)') "After send, before wait"
    write(*, '(a,i2,a,i2,a,(5f5.1))') "send buf(", lbound(send_buf), ":", ubound(send_buf), ") =", send_buf
    write(*, '(a,i2,a,i2,a,(5f5.1))') "recv buf(", lbound(recv_buf), ":", ubound(recv_buf), ") =", recv_buf

    call MPI_Wait(request, status, ierr)

    write(*, '(a)') "After Wait"
    write(*, '(a,i2,a,i2,a,(5f5.1))') "send buf(", lbound(send_buf), ":", ubound(send_buf), ") =", send_buf
    write(*, '(a,i2,a,i2,a,(5f5.1))') "recv buf(", lbound(recv_buf), ":", ubound(recv_buf), ") =", recv_buf

end program
