# include "data.h"

int histogram (int argc, char **argv) {
  
  int i, bin, Nbins;
  opihi_int *OUT;
  opihi_flt start, end, delta;
  Vector *xvec, *yvec;

  if ((argc != 6) && (argc != 5)) {
    gprint (GP_ERR, "USAGE: hist invec outvec start end [delta]\n");
    return (FALSE);
  }

  delta = 1;
  start = atof (argv[3]);
  end   = atof (argv[4]);
  if (argc == 6) delta = atof (argv[5]);
 
  if ((start == end) || (delta == 0)) {
    gprint (GP_ERR, "error in value: %f to %f, %f\n", start, end, delta);
    return (FALSE);
  }
  delta = fabs (delta);
  if (end - start < 0) {
    delta = -1.0 * delta;
  }
  Nbins = (end - start) / delta;
  /* number here should match number in create.c */

  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if ((yvec = SelectVector (argv[2], ANYVECTOR, TRUE)) == NULL) return (FALSE);

  ResetVector (yvec, OPIHI_INT, Nbins);
  bzero (yvec[0].elements.Int, sizeof(opihi_int)*yvec[0].Nelements);
  if (Nbins < 1) return (TRUE);
  OUT = yvec[0].elements.Int;

  if (xvec[0].type == OPIHI_FLT) {
    opihi_flt *V = xvec[0].elements.Flt;
    for (i = 0; i < xvec[0].Nelements; i++, V++) {
      if (isnan(*V)) continue;
      bin = MIN (MAX (0, (*V - start) / delta), Nbins - 1);
      OUT[bin]++;
    }      
  } else {
    opihi_int *V = xvec[0].elements.Int;
    for (i = 0; i < xvec[0].Nelements; i++, V++) {
      if (isnan(*V)) continue;
      bin = MIN (MAX (0, (*V - start) / delta), Nbins - 1);
      OUT[bin]++;
    }      
  }

  return (TRUE);

}
