/* File: star.c --------------------------------------
   Contains:
	double Star(int size)	
		uni-directional transfer test routine
		for the 'Star' logical topology
			size argument is the message length to be used
---------------------------------------------------- */

#include "nettest.h"

double Star ( int iSIZE, int TIMES )
{

	char *Buffer, *buf;
	int iSize, iCount, iProcCount, iNumberOfProc, iMyRank;
	int pool_size,rank,i_am_the_master,remote_rank;
	double dBeginTime, dEndTime, dTime, dLatency;
	double t0,t1,t2;
	double Rate;
	MPI_Status MPIStatus;
	MPI_Status *Statuses;
	MPI_Request *Requests,*sendRequests;
    int bufsize;

	MPI_Comm_size(comm,&iNumberOfProc);
	MPI_Comm_rank(comm,&iMyRank);
	rank = iMyRank;
	i_am_the_master = (rank == 0);
	pool_size = iNumberOfProc;

	bufsize = iSIZE * pool_size;
	buf = Buffer = (char *) malloc (bufsize);
	Statuses = (MPI_Status*) malloc( pool_size * sizeof(MPI_Status));
	Requests = (MPI_Request*) malloc( pool_size * sizeof(MPI_Request));
	sendRequests = (MPI_Request*) malloc( pool_size * sizeof(MPI_Request));
	
	if ( !Buffer || !Statuses || !Requests || !sendRequests)
		finish( "Can't allocate memory");

	/* fill the buffer with values */
	for ( iCount = 0; iCount < iSIZE; iCount++ )
		Buffer [ iCount ] = iCount;
	iSize = iSIZE;

	MPI_Barrier(comm);
	t0 = MPI_Wtime();
	
	if (i_am_the_master) {

		for( iCount = 0; iCount < TIMES; iCount++ ) 
		{
			for(remote_rank = 1; remote_rank < pool_size; remote_rank ++) 
			{		
				buf = Buffer + (iSize * remote_rank);
   	               	MPI_Isend(buf,iSize,MPI_CHAR,remote_rank,iTAG,
							comm,&sendRequests[remote_rank]);
       	            MPI_Irecv(buf, iSize, MPI_CHAR,remote_rank,iTAG,comm,
                            &Requests[remote_rank]);
			}
			MPI_Waitall(pool_size - 1, sendRequests + 1, Statuses + 1);
			MPI_Waitall(pool_size - 1, Requests + 1, Statuses + 1);
			}
	}
	else 	/* If this is not the first (root) process */
		for ( iCount = 0; iCount < TIMES; iCount++ ) 
		{
            MPI_Recv(buf,iSize,MPI_CHAR,iROOT,iTAG,comm,&MPIStatus);
   	        MPI_Send(buf,iSize,MPI_CHAR,iROOT,iTAG,comm);
		}

		
	MPI_Barrier(comm);
	t1 = Wtime ( );
	dTime = t1 - t0;
	Rate = ( 2.0 * (double) iSize * TIMES ) / (dTime);

   free(Buffer);
   free(Requests);
   free(Statuses);

   fflush( stdout );

   return Rate;

} /* End of function Star ( ) */



