#include <stdio.h>
#include "localmpi.h"
#include "extern.h"

int handle_returns()
{
    int         procs_done; // Counters
    int         src;        // Process ID to receive from
    int         tag = 0;    // Message ID
    char        msg[MAX_MSG_LEN+1];

    int         recd_msg[20];
    memset ( recd_msg, '\0', sizeof ( recd_msg ) );

    // Perform the following loop until all the processes are finished

    for ( procs_done = 1; procs_done < num_procs; )
    {
        for ( src = 1; src < num_procs; src++ )
    {
        if ( ! recd_msg[src] )
        {
            int     recd;   // Check to see if a message is received
        MPI_Status  status; // Information on receive status

        // Perform a nonblocking test for a message from src

            mpi_err = MPI_Iprobe ( src, tag, MPI_COMM_WORLD, &recd, &status );
        if ( mpi_err != MPI_SUCCESS )
        {
            handle_err ( "handle_returns" );
            return ( 1 );
        }

        if ( recd )
        {
            recd_msg[src] = 1;
            mpi_err = MPI_Recv ( msg, MAX_MSG_LEN + 1, MPI_CHAR, src, tag, MPI_COMM_WORLD, &status );
            if ( mpi_err != MPI_SUCCESS )
            {
            handle_err ( "handle_returns" );
            return ( 1 );
            }
            printf ( "%s\n", msg );
            procs_done++;
        }
        }
    }
    }

    return ( 0 );
}