#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/time.h>

int main(int argc, char *argv[])
{
    	int nvalues = 100;
    	int node, size;
    	int i, soma, somatotal;
    	int slotsize, mybegin;
    	char *hostname = (char *)calloc(32, sizeof(char));
    	double start_time = 0, end_time, parallel_time, serial_time;
		struct timeval tv;
    	// MPI_Status status;
    	// int tag = 1

    MPI_Init(&argc, &argv);  /* Initialize MPI    */

   	MPI_Comm_rank(MPI_COMM_WORLD, &node); /* Getmy rank    */

 	MPI_Comm_size(MPI_COMM_WORLD, &size);  /* Get the total number of processors */

	if (node == 0) {
		if (argc > 1)
			nvalues = atoi(argv[1]);

		gettimeofday(&tv, NULL);
		start_time = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;

		int serialSum = 0;
		for (i = 0; i < nvalues; i++)
		  serialSum += i;

		end_time = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
		serial_time = end_time - start_time;
		printf("\nSerial Time Elapsed %3.2f sec.\n", serial_time);

		printf("Soma Serie de %d valores: %d\n", nvalues, serialSum);

		gettimeofday(&tv, NULL);
		start_time = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
		slotsize = nvalues / size;

		/*
		for (i = 1; i < size; i++)
			MPI_Send(&slotsize, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
	} else {
		MPI_Recv(&slotsize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
	*/

	}
	MPI_Bcast(&slotsize, 1, MPI_INT, 0,  MPI_COMM_WORLD);
	
	soma = 0; 
	mybegin = slotsize * node;
 	for(i = mybegin; i < mybegin+slotsize; i++)
        	soma += i;

	//printf("Soma parcial de %d valores entre %d e %d no %d = %d\n",slotsize, mybegin, i, node, soma);
	MPI_Reduce(&soma, &somatotal, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
	
	/* if (node != 0) {
		gethostname(hostname, sizeof(char) * 32);
		printf("A SOMA parcial %d no %d of %d processada por %s = %d\n", mybegin, node, size, hostname, soma);
	} else {
		gethostname(hostname, sizeof(char) * 32);
		printf("A SOMA Total agregada no %d of %d processada por %s = %d\n", node, size, hostname, somatotal);
	}
	*/
	if (node == 0) {
		gettimeofday(&tv, NULL);
		end_time = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
		parallel_time = end_time - start_time;
		printf("\nParalell Time Elapsed %3.2f sec.\n", parallel_time);
		// gethostname(hostname, sizeof(char) * 32);
		// printf("Soma Total no %d (%s) = %d\n", node, hostname, somatotal);
		printf("Soma Total (no %d) = %d\n", node, somatotal);
	}
	MPI_Finalize();   /* Terminate MPI        */
	return 0;
    	
}

