#include <stdio.h>
#include <sys/time.h>
#include "mpi.h"



long Time_In_Sec(void)
{
    static struct timeval tp;

    gettimeofday(&tp, (struct timezone *)0);
    return (tp.tv_sec + tp.tv_usec / 1000000);
}

long Time_In_MilliSec(void)
{

    static struct timeval tp;
    gettimeofday(&tp, (struct timezone *)0);
    return (tp.tv_sec*1000 + tp.tv_usec / 1000);

}

long Time_In_MicroSec(void)
{
    static struct timeval tp;
    gettimeofday(&tp, (struct timezone *)0);
    return (tp.tv_sec*1000000 + tp.tv_usec);

}

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

{
    int rank, value;
	FILE *fp;
	long stime, etime;

	MPI_Init( &argc, &argv );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );

    if (rank == 0)
	{
		fp = fopen("data.dat","r");
		if (fp == NULL)
		{
			printf("Cannot open file");
			exit(0);
		}
	}

    stime = Time_In_MicroSec();
    do
	{

	    if (rank == 0)
		{

			fscanf(fp, "%d", &value );

		    //Terminating Condition
			if (feof(fp))
			   value = -1;
	     }


		 MPI_Bcast( &value, 1, MPI_INT, 0, MPI_COMM_WORLD );
		 printf( "Process %d got %d\n", rank, value );
	 }while ( value>=0);

	etime = Time_In_MicroSec();

	if ( rank == 0)
		printf("\nElapsed Time = %ld microsecond\n",etime-stime);

	MPI_Finalize( );
    return 0;
}
