/*
 * integrator.c
 *
 * Computes the integral of 4/(1 + x*x) in the interval of
 * sector * SCTOR_SIZE and (sector + 1) * SECTOR_SIZE.
 * This will be used to compute the value of pi
 *
 * By Kamran Karimi
 */

#include "pi.h"

/* function to compute pi. Change this to compute the integral of some
   other function. (you may have to change the limits, assumed to be 0 
   and 1 here) */
__inline__ double f(double val)
{
 return 4.0 / (1.0 + val * val);
} 

/* integrate using the trapezoidal method */
double integrate(int sector, double inc)
{
 double count, result = 0.0;
 double start = sector * SECTOR_SIZE;
 
 result = (f(start) + f(start + SECTOR_SIZE - inc)) / 2.0;
 for(count = start + inc; count < start + SECTOR_SIZE - inc; count += inc)
  result += f(count);
 return result * inc;
}

int main(int argc, char **argv)
{
 int msgid;
 struct message mess;
 int sector;
 double inc;
 
 if(argc != 3)
 {
  printf("USAGE: %s <Sector No.> <Increment>\n", argv[0]);
  exit(0);
 }
 sector = atoi(argv[1]);
 inc = atof(argv[2]);
 if(inc <= 0 || inc >= SECTOR_SIZE)
 {
  fprintf(stderr,"Integrator: Invalid increment\n");
  exit(20);
 }
 msgid = msgget(MSG_KEY, MSG_MODE);
 if(msgid < 0) 
 {
  fprintf(stderr,"Integrator: msgget() failed: %s\n",strerror(errno));
  exit(20);
 }
 mess.mtype = MSG_TYPE; /* not necessary here */
 mess.body.architecture = MY_DIPC_ARCH;
 mess.body.result = integrate(sector, inc);
 if(msgsnd(msgid, (struct msgbuf *)&mess, sizeof(struct body), 0) < 0)
 {
  fprintf(stderr,"Integrator: msgsnd() failed: %s\n", strerror(errno));
  exit(20);
 }
 exit(0);
}
