# include "data.h"

int peak (int argc, char **argv) {
  
  int i, N, imax, QUIET;
  double start, end, xmax, ymax;
  float *X, *Y;
  Vector *vecx, *vecy;

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

  if ((argc != 5) && (argc != 3)) {
    gprint (GP_ERR, "USAGE: peak <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);

  if (argc == 5) {
    start = atof (argv[3]);
    end   = atof (argv[4]);
  } else {
    start = vecx[0].elements[0];
    end   = vecx[0].elements[vecx[0].Nelements - 1];
  }

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

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

  set_variable ("peakval", ymax);
  set_variable ("peakpos", xmax);
  set_variable ("peaknum", imax);

  if (!QUIET) gprint (GP_LOG, "peak %f @ %f (%d)\n", ymax, xmax, imax);

  return (TRUE);
}
