
/*
*       tim.c
*
*       See tim.c
*/

#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <math.h>
#include "pvm3.h"

typedef struct complextype
        {
        float real, imag;
        } Compl;

main(int argc, char *argv[])
//        int argc;
//        char **argv;
{
        int mytid;   /* my task id */
        int dtid;    /* driver task */
        int bufid;
        int n = 0;
	int message;

        struct timeval tv1, tv2;        /* for timing */
        long dt1, dt2;                           /* time for one iter */
        long at1, at2;                   /* accum. time 1 for idle and 2 for busy*/

       /* Mandlebrot variables */
        int i, j, k;
        Compl   z, c;
        float   lengthsq, temp;
        int maxIterations;
	z.real = z.imag = 0.0;
	
	maxIterations = atoi( argv[1] );

        /* enroll in pvm */

        mytid = pvm_mytid();

        /* pack mytid in buffer */

        pvm_initsend(PvmDataRaw);
        pvm_pkint(&mytid, 1, 1);
	
	/* Find out the parent tid */
	dtid = pvm_parent();

	at1 = 0; at2 = 0;
        /* our job is just to echo back to the sender when we get a message */
        while (1) {
         	/* Starts the clock for idle time */
	        gettimeofday(&tv1, (struct timezone*)0);
		pvm_recv(dtid, 0);
		gettimeofday(&tv2, (struct timezone*)0);

		pvm_upkint(&message,1,1);                
		dt1 = ((long)(tv2.tv_sec - tv1.tv_sec)) * 1000000
                                + tv2.tv_usec - tv1.tv_usec;

                at1=at1+dt1;            //acumalate the time idle

		/* Starts the clock for utilalization */
		gettimeofday(&tv1, (struct timezone*)0);
		
		if(message == 0)
		{
			pvm_upkfloat(&c.real,1,1);
			pvm_upkfloat(&c.imag,1,1);
			//perform calculations
			k = 0;
		         do  {                              /* iterate for pixel color */

        		    temp = z.real*z.real - z.imag*z.imag + c.real;
        		    z.imag = 2.0*z.real*z.imag + c.imag;
        		    z.real = temp;
        		    lengthsq = z.real*z.real+z.imag*z.imag;
         		    k++;
			 } while (lengthsq < 4.0 && k < maxIterations);

			pvm_initsend( PvmDataDefault );
			pvm_pkint(&k, 1, 1);
			pvm_send(dtid,0);
			
			z.real = z.imag = 0.0;	//set z back to starting values

			/* Ends the clock for utilalization and cals time busy */
			gettimeofday(&tv2, (struct timezone*)0);
			dt2 = (long)(tv2.tv_sec - tv1.tv_sec) * 1000000
                                + tv2.tv_usec - tv1.tv_usec;
			at2=at2+dt2;		//acumalate the time active
		}
		else if (message == 1)
		{
			pvm_initsend( PvmDataDefault );
			pvm_pklong (&at1,1, 1);
			pvm_pklong (&at2,1,1);
			pvm_send (dtid,0);
			pvm_exit();
			exit(1);
		}
		else
		{
			printf("The number sent was not 1 or 0.\n");
			break;
		}
        }
}



