# include "astro.h"

int czplot (int argc, char **argv) {
  
  int i, kapa;
  double min, range, Rmin, Rmax;
  opihi_flt *out, *r, *d, *x, *y;
  Vector Xvec, Yvec, Zvec, *xvec, *yvec, *zvec;
  Graphdata graphmode;

  if (!style_args (&graphmode, &argc, argv, &kapa)) return FALSE;

  if (argc != 6) {
    gprint (GP_ERR, "USAGE: czplot <x> <y> <z> min max\n");
    return (FALSE);
  }

  min = atof(argv[4]);
  range = atof(argv[5]) - min;
  Rmin = graphmode.coords.crval1 - 180.0;
  Rmax = graphmode.coords.crval1 + 180.0;

  /* find vectors */
  if ((xvec = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if ((yvec = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
  if ((zvec = SelectVector (argv[3], OLDVECTOR, TRUE)) == NULL) return (FALSE);

  REQUIRE_VECTOR_FLT (xvec, FALSE); 
  REQUIRE_VECTOR_FLT (yvec, FALSE); 
  REQUIRE_VECTOR_FLT (zvec, FALSE); 

  if (xvec[0].Nelements != yvec[0].Nelements) {
    gprint (GP_ERR, "vectors %s and %s not the same length\n", argv[1], argv[2]);
    return (FALSE);
  }
  if (xvec[0].Nelements != zvec[0].Nelements) {
    gprint (GP_ERR, "vectors %s and %s not the same length\n", argv[1], argv[3]);
    return (FALSE);
  }
  SetVector (&Xvec, OPIHI_FLT, xvec[0].Nelements);
  SetVector (&Yvec, OPIHI_FLT, xvec[0].Nelements);
  SetVector (&Zvec, OPIHI_FLT, xvec[0].Nelements);
  
  r   = xvec[0].elements.Flt;
  d   = yvec[0].elements.Flt;
  x   = Xvec.elements.Flt;
  y   = Yvec.elements.Flt;
  for (i = 0; i < Zvec.Nelements; i++, r++, d++, x++, y++) {
    *r = ohana_normalize_angle (*r);
    RD_to_XY (x, y, *r, *d, &graphmode.coords);
  }

  out = Zvec.elements.Flt;
  if (zvec->type == OPIHI_FLT) {
    opihi_flt *in  = zvec[0].elements.Flt;
    for (i = 0; i < Zvec.Nelements; i++, in++, out++) {
      *out = MIN (1.0, MAX (0.01, (*in - min) / range));
    }
  } else {
    opihi_int *in  = zvec[0].elements.Int;
    for (i = 0; i < Zvec.Nelements; i++, in++, out++) {
      *out = MIN (1.0, MAX (0.01, (*in - min) / range));
    }
  }

  graphmode.style = 2;
  graphmode.size = -1; /* point size determined by Zvec */
  graphmode.etype = 0;
  PlotVectorTriplet (kapa, &Xvec, &Yvec, &Zvec, &graphmode);

  free (Xvec.elements.Flt);
  free (Yvec.elements.Flt);
  free (Zvec.elements.Flt);

  return (TRUE);

}
