/*
   Standard Deviation program Slave
   Jim Garlick
*/

#include <stdio.h>
#include <math.h>
#include "pvm3.h"
#include "stddev.h"

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

   /* Initialize some variables */
  int parent_id, bufid, count, i;
  float sum, mean;
  float *data;

    /* Get the task id of the parent process */
  parent_id = pvm_parent();

    /* Recieve the data from the parent */
  bufid = pvm_recv(parent_id, SendData);
    /* Unpack how many numbers we were sent */
  pvm_upkint(&count, 1, 1);
    /* Allocate the array based on the size */
  data = (float*) malloc(count*sizeof(float));
    /* Unpack the entire data array */
  pvm_upkfloat(data, count, 1);

    /* Add up all of the numbers */
  for (sum=0.0, i=0; i<count; i++)
    sum += data[i];

    /* Initialize the send buffer */
  pvm_initsend(PvmDataDefault);
    /* Pack up the sum of these numbers */
  pvm_pkfloat(&sum, 1, 1);
    /* Send it on its merry way... */
  pvm_send(parent_id, SendSum);
    
    /* Now we're ready for the mean. */
  bufid = pvm_recv(parent_id, SendMean);
    /* Unpack the global mean */
  pvm_upkfloat(&mean, 1, 1);

    /* Calculate the partial variance */
  for(sum=0.0, i=0; i<count; i++)
    sum += pow((data[i]-mean), 2);

    /* Initialize the send buffer */
  pvm_initsend(PvmDataDefault);
    /* Pack up the partial variance */
  pvm_pkfloat(&sum, 1, 1);
    /* Send it on its merry way... */
  pvm_send(parent_id, SendSum);
  
    /* Quit PVM */
  pvm_exit();
  exit(0);
}    
