program swapmessage

        include 'mpif.h'
        integer rank, numproc, ierror, root
        integer request
        character(80) message_sent, message_received

        ! Setup default messages.

        message_sent = 'No message sent'
        message_received= 'No message received'
        root = 0

        ! Start up MPI environment
 
        call MPI_INIT(ierror)
        call MPI_COMM_RANK(mpi_comm_world, rank, ierror)
        call MPI_COMM_SIZE(mpi_comm_world, numproc, ierror)
 
        if (numproc > 1) then

        ! swap messages only if we have more than 1processor.
        ! The root process sends a message to processor 1 and then
        ! waits for a reply.  Processor 1 waits for a message from
        ! the root process, adds to it, and then sends it back.

	if (rank == root) then

            message_sent = 'Hello from processor 0'
            
            call MPI_SEND(message_sent, 80, MPI_CHARACTER, 1,1, &
                 MPI_COMM_WORLD, ierror)

            call MPI_RECV(message_received, 80, MPI_CHARACTER, 1,1, &
                 MPI_COMM_WORLD, request ,ierror)               

	else if (rank == 1) then

        ! Processor 1 waits until processor0 sends its message

           call MPI_RECV(message_received, 80, MPI_CHARACTER, 0,1, &
                MPI_COMM_WORLD, request, ierror)

        ! It then constructs a reply.

           message_sent='Proc 1 got this message: '//message_received

        ! And sends it..

           call MPI_SEND(message_sent, 80, MPI_CHARACTER, 0, 1, &
                MPI_COMM_WORLD, ierror)

	endif

           print *,"Processor",rank," sent '",message_sent, "'"
           print *, "Processor",rank, "received '", message_received,"'"
   
	   else
               
           print *,"Not enough processors to demo message passing"
        
	endif
   
        call MPI_FINALIZE(ierror)

        end 
