//  Example Slave Program
//  slave1.c

#include <stdio.h> 
#include <iostream.h>
#include "/usr/pvm3/include/pvm3.h"
#define  NUMX 400
#define  NUMY 400

main()
{  int mytid;       /* my task id */
   int me, step,i, nproc, master, msgtype;
   int tids[NUMX];
   int result[NUMY];
   float data[NUMX];
   float mdata[NUMY];
   float check;
   int iter;
   float imag,ral;
   

    /* enroll in pvm */
       mytid = pvm_mytid();               // Get my processor ID
       cout<<"Got id"<<endl;
    /* Receive data from master */
       msgtype = 0;

       pvm_recv( -1, msgtype );                  // Get ready to receive initial data
       cout<<"Got message type"<<endl;
       pvm_upkint(&nproc, 1, 1);                 // Unpack number of slave processors
       pvm_upkint(tids, nproc, 1);               // Unpack array of processor IDs

       
       pvm_upkfloat(data, NUMX, 1); // Unpack X data array
       pvm_upkfloat(mdata, NUMY, 1); //Unpack Y data array
       cout<<"received data"<<endl;       

    /* Determine which slave I am (0 -- nproc-1) */
    for( i=0; i<nproc ; i++ )
       if( mytid == tids[i] ){ me = i; break; }  // Determine array position

    /* Do calculations with data */
    float temp;
    for (step=0; step<NUMY; step++)
      {
        check=0;
	iter=0;
	imag=mdata[step];
	ral=data[me];
        while ((check<4)&&(iter<100)) 
          {
 	//plots the points for the equation
	  temp=ral;
          ral= ( (ral*ral) - (imag*imag) + temp );
 	  imag= ( (imag) + (2*temp*imag) );
 	  check= ( (ral*ral) + (imag*imag) );
	  iter++;
          }
        if (check<4) result[step]=0;
 	if (check>=4) result[step]=iter;
       }

    /* Send result to master */
    pvm_initsend( PvmDataDefault );                    // Get ready to send data
    pvm_pkint( &me, 1, 1 );                      // Pack which processor I am

//    int temp2=3;
//    pvm_pkint(&temp2,1,1);
//   for (int o=0; o<NUMY; o++)
//     result[o]=(int)(mdata[o]*100);

    pvm_pkint(result, NUMY, 1 );                // Pack the resultant sum
    msgtype = 5;                          // Identify message type
    master = pvm_parent();                       // Find out where I came from
    pvm_send( master, msgtype );                 // Send message back to parent process

    /* Program finished. Exit PVM before stopping */
    pvm_exit();
}

