      PROGRAM ASSIGNMENT2
      INCLUDE 'mpif.h'
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c This program repeatedly broadcasts a message to all processes and 
c waits for the processes to send the message back.  The average time 
c required for the round trip is calculated.
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c Setting the length of the message to be sent. n is the number of 
c eight byte chunks to be sent.
      Integer           n, length
      Parameter         (n=100)
      Parameter         (length=32*n)

      Character*(length) recmessage
      Character*(length) message
      Character*32      submessage
      Integer           i, j, rank, size, ierr, position
      Integer           status(MPI_STATUS_SIZE)
      Double Precision  begin, finish, avgtime,time(10)


c Initializing MPI and obtaining the process no. and no. of processes.
      call MPI_INIT(ierr)
      call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr)
      call MPI_COMM_SIZE(MPI_COMM_WORLD, size, ierr)
    
c Constructing the message.
      submessage='This is the message being sent. '
      do i=1,n 
         position=32*(i-1)+1
         message(position:position+31)=submessage
      enddo
     
c Beginning sending and timeing messages.
      do i=1,10
         if (rank .eq. 0) begin=MPI_WTIME(ierr)
         call MPI_BCAST(message,length,MPI_CHARACTER,0,
     $               MPI_COMM_WORLD,ierr)
         if (rank .ne. 0) then
            call MPI_SEND(message,length,MPI_CHARACTER,0,1,
     $                MPI_COMM_WORLD,ierr)
          elseif (rank .eq. 0) then
            do j=1,size-1
            call MPI_RECV(recmessage,length,MPI_CHARACTER,
     $               MPI_ANY_SOURCE,1,MPI_COMM_WORLD,status,
     $               ierr)
            enddo
            finish=MPI_WTIME(ierr)
            time(i)=(finish-begin)
         endif
      enddo

c Averaging the times for the ten round trips messages.
         if (rank .eq. 0) then 
            do i=1,10
               avgtime=avgtime+time(i)
            enddo
            avgtime=avgtime/10
            print *,"Average time required for a round trip message " 
            print *," of",length," bytes is",avgtime 
         endif

      call MPI_FINALIZE(ierr)

      end

