!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -*- Mode: F90 -*- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! unanimity.f90 --- TP3 : collectives communications
!! 
!! Author          : Denis GIROU (CNRS/IDRIS - France) <Denis.Girou@idris.fr>
!! 
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

program unanimity
  USE MPI
  implicit none

  integer, parameter                :: nb_tests_max=2000
  integer                           :: nb_procs,rank,code, &
                                       nb_tests=0,decision=-1
  real                              :: drawing
  integer, dimension(8)             :: mytime
  integer, dimension(:),allocatable :: seed
  integer                           :: size_seed,i

  call MPI_INIT(code)

  call MPI_COMM_SIZE(MPI_COMM_WORLD,nb_procs,code)

  call MPI_COMM_RANK(MPI_COMM_WORLD,rank,code)

  call my_seed

  do while (decision /= 0 .and. decision /= nb_procs &
       .and. nb_tests <= nb_tests_max)
     nb_tests=nb_tests+1

     ! Choice of the drawing
     call random_number(drawing)

     ! Reduction to collect the sum of each drawing value
     ! and send it to each processes
     call MPI_ALLREDUCE(nint(drawing),decision,1,MPI_INTEGER,MPI_SUM, &
          MPI_COMM_WORLD,code)
  end do

  if (rank == 0) then
     if (nb_tests > nb_tests_max) then
        print *,'We do ',nb_tests_max,' tests without unanimity !'
     else
        print *,'We do ',nb_tests,' tests to obtain unanimity !'
     end if
  end if

  call MPI_FINALIZE(code)

contains
  subroutine my_seed

    ! Size of the seed
    call random_seed(size=size_seed)
    allocate(seed(size_seed))

    ! Seed fixed using execution time
    ! (in ms seconds)
    do i = 1, size_seed
       call date_and_time(values=mytime)
       seed(i)=mytime(8)*mytime(8)*mytime(8)*(rank+1)
    end do

    call random_seed(put=seed(:))
  end subroutine my_seed

end program unanimity
