program hybrid_caf_mpi
include 'mpif.h'

   integer :: my_rank, numb_procs

   integer      :: i, num_ranks, rank
   real(kind=8) :: not_coarray_var
   real(kind=8) :: coarray[*]
   real(kind=8) :: send_buf, sum, RESULT1, RESULT2

   call MPI_INIT(ierr)
   call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr)
   call MPI_COMM_SIZE(MPI_COMM_WORLD, num_ranks, ierr)

   print*, 'total mpi_ranks is', num_ranks,'my mpi_rank is', rank
   my_rank   = this_image()
   numb_procs = num_images()
   send_buf = 1.0

   !do i=1, numb_procs
   !   if (my_rank == i) then
   !      print*, 'total_images is',numb_procs,'my image is ',my_rank
   !      send_buf = 1.0
   !       coarray[i] = 2*i
   !   end if
   !   sync all
   !end do
   call MPI_REDUCE(coarray[my_rank],RESULT2,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD,ierr);
   call MPI_ALLREDUCE(send_buf, RESULT1, 1, MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD,ierr);
   call MPI_BARRIER (MPI_COMM_WORLD, ierr)

      do i=1, numb_procs
      if (my_rank == i) then
         print*, 'total_images is',numb_procs,'my image is ',my_rank
         coarray[i] = RESULT1*i
      end if
      sync all
      end do



   if (my_rank == 1) then
    do i=1, numb_procs
   print*,'my coarray rank is ',my_rank,'value of coarray is ',coarray[i]
     end do
   end if

   call MPI_BARRIER (MPI_COMM_WORLD, ierr)

   call MPI_Finalize(ierr)

end program hybrid_caf_mpi


