/* File: istar.c --------------------------------------
   Contains:
	double iStar(int size)	
		bi-directional transfer test routine
		for the 'Star' logical topology
			size argument is the message 
			length to be used
 	returns: measured transfer rate
---------------------------------------------------- */

#include "nettest.h"

double Star2 ( int iSIZE , int TIMES)
{

	unsigned char *Buffer1, *Buffer2;
	int iSize, iCount, iProcCount, iNumberOfProc, iMyRank;
	int pool_size,rank,i_am_the_master;
	double dTime1, dTime2, dTime3, dTime4, dT, dLatency, dLat, dTime;
	MPI_Status  *Statuses;
	MPI_Request *Requests;
	double Rate;
	int req_count;

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


	Statuses      = ( MPI_Status * ) malloc ( iNumberOfProc * 2 * sizeof(MPI_Status) );
	Requests = ( MPI_Request   * ) malloc ( iNumberOfProc * 2 * sizeof(MPI_Request) );

	Buffer1        = ( unsigned char * ) malloc ( iSIZE * iNumberOfProc);
	Buffer2        = ( unsigned char * ) malloc ( iSIZE * iNumberOfProc);

	if ( !Buffer1 || !Buffer2 || !Requests || !Statuses )
		finish( "Can't allocate memory");

   for ( iCount = 0; iCount < iSIZE * iNumberOfProc; iCount++ )
      Buffer1 [ iCount ] = Buffer2 [ iCount ] = iCount;

   MPI_Barrier (comm);


	iSize = iSIZE;

      if(i_am_the_master)
      {
          dTime1 = Wtime ( );

          for ( iCount = 0; iCount < TIMES; iCount++ )
          {
		req_count = 0;
             	
                for ( iProcCount = 1; iProcCount < iNumberOfProc; iProcCount++ ) {
        			MPI_Isend(Buffer1 + iProcCount*iSize,iSize,MPI_CHAR,iProcCount,iSEND_TAG + iProcCount, 
								MPI_COMM_WORLD,&Requests[req_count++]);
					MPI_Irecv(Buffer2  + iProcCount*iSize, iSize, MPI_CHAR, iProcCount,iRECV_TAG + iProcCount,
								MPI_COMM_WORLD,&Requests[req_count++]);

                } 

                MPI_Waitall (req_count,Requests,Statuses);

          }  /* Close iteration count */

		dTime2 = Wtime ( ); /* Timing for iMyRank = 0 */
		dTime = dTime2 - dTime1;
		Rate = ((double) iSize * 2.0 * TIMES) / (dTime);
		
          }  /* End of section for MASTER process */
      else
      {
          for ( iCount = 0; iCount < TIMES; iCount++ )
          {
             MPI_Irecv (Buffer1, iSize, MPI_CHAR, iROOT,
                        iSEND_TAG + iMyRank, comm,&Requests[0]);
             MPI_Isend (Buffer2, iSize, MPI_CHAR, iROOT,
                        iRECV_TAG + iMyRank, comm,&Requests[1]);


             MPI_Waitall (2,Requests,Statuses);

         }  /* End of iteration cycle for other processors */
      } 

   return Rate;

}

