/* 
   Brian Bailey, Jon Herlocker, and Alex Safonov

*/


#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>

/* define global variables here - this is a read only variable */
int numprocessors;

/* declare external functions here */
extern void primegeneratemaster(int id, unsigned numbers[], unsigned len);
extern void primegenerateslave(int id);

#define NNUMBERS 100
unsigned numbers[NNUMBERS];

int main(int argc, char **argv)
{
    int i, myid, next, rc, namelen;
    /* Numbers to be factored */
    /* unsigned numbers[] = { 1568675693, 1980, 210, 2, 4, 10, 13, 18, 25, 27, 33, 45, 64609, 5402250, 1784930922, 223092870 } ; */
    unsigned len = sizeof(numbers)/sizeof(numbers[0]);

    /* initialize the MPI library */
    MPI_Init(&argc,&argv);

    /* retrieve the number of processors */
    MPI_Comm_size(MPI_COMM_WORLD,&numprocessors);

    /* determine which process I am */
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);

    /* make the 0th process the process that feeds the primes to the
       other four
    */
    if (myid == 0)
    {
      if (argc > 1 && argv[1][0] != '-') {
	/* skip program name in argv[0] */
	argv++; argc--;
	/* parse arguments as numbers to be factored */
	for (len = 0; 
	     (len < NNUMBERS) && (argc > 0) && (numbers[len]=atoi(*argv)) != 0; 
	     len++, argv++, argc--)
	  ;
	printf("factoring %d number(s) specified on the command line\n", len);
      } else {
	/* generate NNUMBERS "random" numbers */
	len = NNUMBERS;
	srandom(1);
	for (i = 0; i < len; i++) {
	  numbers[i] = random();
	}
	printf("factoring %d randomly generated number(s)\n", len);
      }

      primegeneratemaster(myid, numbers, len);
    }
    else
      primegenerateslave(myid);

    MPI_Finalize();

}



