/*
** Simple test program 02 for the MIAMI protocol
** Rolf Riesen, December 2009
**
** Usage: test_03 local_host local_port remote_host remote_port rank
** rank should be 0 in one process, and 1 in the other.
**
** Let a message arrive before it is posted on the receive side.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#if defined (_MPI_)
#include <mpi.h>
#endif
#include "miami.h"

#define VALUE	(100)

int
main(int argc, char *argv[])
{

char *host1;
char *host2;
int sbuf;
int rbuf;
int port1, port2;
int rank;
int tag;
int shandle, rhandle;
int bytes;
int rc;


    if (argc != 6)   {
	fprintf(stderr, "Usage: %s local_host local_port remote_host remote_port rank\n", argv[0]);
	return -1;
    }

    host1= argv[1];
    host2= argv[3];
    port1= strtol(argv[2], NULL, 10);
    port2= strtol(argv[4], NULL, 10);
    rank= strtol(argv[5], NULL, 10);

    miami_init(host1, port1, host2, port2);
#if defined (_MPI_)
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

    tag= 12;
    rc= 0;

    if (rank == 0)   {
	/* I'm the sender */

	/* Fill the send buffer */
	sbuf= VALUE;

	/* Send the data */
	shandle= miami_tx_start(&sbuf, sizeof(int), tag);

	while (!miami_tx_done(shandle))   {
	}

    } else   {

	/* I'm the receiver. Wait a while for the sender to send data */
	sleep(1);

	/* Clear the receive buffer */
	rbuf= 0;

	/* Receive and handle any pending messages */
	miami_progress();

	/* Post a receive */
	rhandle= miami_rx_start(&rbuf, sizeof(int), tag);
	while (!miami_rx_done(rhandle, &bytes))   {
	    /* Wait for that message */
	}

	if (rbuf == VALUE)   {
	    printf("Test Got expected value %d from sender\n", rbuf);
	} else   {
	    printf("ERROR: Got unexpected value %d from sender. Expected %d\n", rbuf, VALUE);
	    rc= 1;
	}
    }

    miami_finalize();

    return rc;

}  /* end of main() */
