#include "pgm.h"

CkChareID mainhandle;
int slices;
int numChares;

main::main(CkArgMsg * m)
{ 
  Range *pMsg ;
  int i, low = 0;

  slices = atoi(m->argv[1]);    // readonly initialization
  numChares = atoi(m->argv[2]); // readonly initialization

  for (i=0; i<numChares; i++) {
    pMsg = new Range;
    pMsg->low = low;
    low += slices/numChares ; // must be a divisor
    pMsg->high = low-1;
    CProxy_integrate::ckNew(pMsg);  
  }
  count = numChares;
  integral = 0.0;
  mainhandle = thishandle; // readonly initialization
}

void main::results(DataMsg *msg) 
{ 
  integral += msg->x;
  if (0 == --count) {
    CkPrintf("all results in. integral is: %f \n", integral);
    CkExit();
  }
}

integrate::integrate(Range *m)
{ 
  int i;
  double sum, x, width;
  
  width = 1.0/slices;
  sum = 0.0;
  for (i=m->low; i<= m->high; i++) {
    x = i*width;
    sum = sum + (1/(1+x))*width;
  }

  DataMsg *result = new DataMsg;
  result->x = sum;
  CProxy_main mainproxy(mainhandle);
  mainproxy.results(result);

  delete m;
  delete this;
}

#include "pgm.def.h"
