# include "data.h"

int integrate (int argc, char **argv) {
  
  int i, N, VERBOSE;
  float *X, *Y;
  double start, end, value, range;
  Vector *vecx, *vecy;

  VERBOSE = FALSE;
  if ((N = get_argument (argc, argv, "-v"))) {
    VERBOSE = TRUE;
    remove_argument (N, &argc, argv);
  }

  if (argc != 5) {
    gprint (GP_ERR, "USAGE: integrate <x> <y> start end\n");
    return (FALSE);
  }

  if ((vecx = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if ((vecy = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);

  start = atof (argv[3]);
  end   = atof (argv[4]);

  X = vecx[0].elements;
  Y = vecy[0].elements;

  value = 0;
  range = 0;
  for (i = 0; i < vecx[0].Nelements-1; i++, X++, Y++) {
    if ((*X >= start) && (*X <= end)) {
      value += *Y * (X[1] - X[0]);
      range += (X[1] - X[0]);
    }
  }      

  set_variable ("sum", value); 
  set_variable ("range", range);
  if (VERBOSE) gprint (GP_LOG, "sum: %f\n", value);
  return (TRUE);
}

