#include "pvm3.h"
#include "pvm_imagelib.h"

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

  
  int TaskIDs[255];
  int NumberOfMachines = 0;
  int NumberOfChildren = 0;
  int bogus1;
  struct pvmhostinfo *bogus2;
  int NumberOfTasks;

  char * type;
  int thresh;
  char * imageName;
  Image * image;

  long offset,imageSize,width,amountToRead,amountToProcess;
  long ReadRemainder,ProcessRemainder,amountsent;

  int current;

  NumberOfTasks = atoi(argv[2]);
  imageName = argv[1];
  if (argc > 3){
    type = argv[3];
    thresh = atoi(argv[4]); 
    }
#ifdef debug
  pvm_catchout(stdout);
#endif
  pvm_config(&NumberOfMachines,&bogus1,&bogus2);
  if (!(NumberOfTasks <= 0))
    NumberOfMachines = NumberOfTasks;
#ifdef debug
  printf("The cluster consists of %d machine(s)\n",NumberOfMachines);
#endif
  NumberOfChildren = pvm_spawn("pvm_edgedetect_child",(char **)0, 0, "",NumberOfMachines ,TaskIDs );
  if (NumberOfChildren != NumberOfMachines){   
    pvm_exit();
    exit(-1);
  }
  

  image = readImage(imageName,0);
  imageSize = image->isize;
  offset = image->boffset;//+imageSize%3;
  
  width = image->width;
  amountToRead = (image->size - image->boffset)/NumberOfChildren;
  amountToProcess = image->isize/NumberOfChildren;
  amountsent = offset;
  //make sure we get all the data
  ReadRemainder = (image->size - image->boffset)%NumberOfChildren;
  ProcessRemainder = image->isize%NumberOfChildren;

  for (current = 0; current < NumberOfChildren;current++){
    pvm_initsend(PvmDataDefault);

    pvm_pkstr(imageName);
    pvm_pkstr(type);
    pvm_pklong(&offset,1,1);
    pvm_pklong(&width,1,1);
    pvm_pklong(&amountToRead,1,1);
    pvm_pkint(&thresh,1,1);
    pvm_send(TaskIDs[current],1);

#ifdef debug
    printf("current %d, name %s, offset %d, width %d, amount %d,remainder %d, sent %d\n",
	  current,imageName,offset,width,amountToRead,ReadRemainder,amountsent);
#endif

    offset = offset+amountToRead;
    amountsent = amountsent + amountToRead;
    if (current == (NumberOfChildren -2)){
      amountToRead = amountToRead + ReadRemainder;

#ifdef debug 
      printf("sizer = %d\n",NumberOfChildren%3);
#endif
    }

  }

  writeHeader(image->FileHeader,image->InfoHeader);
#ifdef debug
  printf("total sent = %d\n",amountsent);
#endif
  for (current = 0; current < NumberOfChildren ; current++)
    pvm_recv(-1,-1);

  pvm_exit();
  exit(0);
}

