/*
** Simple test program 01 for the MIAMI protocol
** Rolf Riesen, December 2009
**
** Usage: test_01 local_port local_host remote_host remote_port rank
** rank should be 0 in one process, and 1 in the other.
**
** Let's send a message!
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#if defined (_MPI_)
#include <mpi.h>
#endif
#include "miami.h"

#define BUF_SIZE	(1024)
#define MSG		"A test message from the sender"



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

char *host1;
char buf[BUF_SIZE];
char *host2;
int port1, port2;
int rank;
int tag;
int handle;
int bytes;
int rc;


    if (argc != 6)   {
	fprintf(stderr, "Usage: %s local_port local_host 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);

    printf("Test I'm running on host %s, rank %d and will connect to host %s, port %d\n", host1, rank, host2, port2);

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

    tag= 12;

    if (rank == 0)   {
	/* I'm the sender. Give the receiver some time to post the receive */
	sleep(1);

	/* Now send the data */
	strcpy(buf, MSG);
	handle= miami_tx_start(buf, strlen(buf) + 1, tag);
	printf("Test Called miami_tx_start(%p, len %d, tag %d) got handle %d\n", buf,
	    (int)strlen(buf) + 1, tag, handle);

	while (!miami_tx_done(handle))   {
	    /* Can't exit until the message has been sent */
	}
	rc= 0;

    } else   {

	/* I'm the receiver */
	handle= miami_rx_start(buf, BUF_SIZE, tag);
	while (!miami_rx_done(handle, &bytes))   {
	    /* Wait for that message */
	}
	printf("Test Got the message \"%s\" of length %d bytes\n", buf, bytes);

	if (bytes != strlen(MSG) + 1)   {
	    printf("ERROR: message length mismatch %d != %d\n", bytes, (int)strlen(MSG) + 1);
	    rc= 1;
	}

	if (strcmp(MSG, buf) != 0)   {
	    printf("ERROR: message content incorrect!\n");
	    rc= 1;
	}
    }

    miami_finalize();

    return rc;

}  /* end of main() */
