# include "astro.h"

int cplot (int argc, char **argv) {
  
  int i, kapa, Npts, status, leftside;
  opihi_flt *x, *y, *r, *d, Rmin, Rmax, Rmid;
  Vector Xvec, Yvec, *xvec, *yvec;
  Graphdata graphmode;

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

  if (argc != 3) {
    gprint (GP_ERR, "USAGE: cplot <ra> <dec> [style]\n");
    return (FALSE);
  }

  Rmin = graphmode.coords.crval1 - 182.0;
  Rmax = graphmode.coords.crval1 + 182.0;
  Rmid = 0.5*(Rmin + Rmax);

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

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

  if (xvec[0].Nelements != yvec[0].Nelements) {
    gprint (GP_ERR, "vectors are not the same length\n");
    return (FALSE);
  }

  SetVector (&Xvec, OPIHI_FLT, xvec[0].Nelements);
  SetVector (&Yvec, OPIHI_FLT, xvec[0].Nelements);
  
  r = xvec[0].elements.Flt;
  d = yvec[0].elements.Flt;
  x = Xvec.elements.Flt;
  y = Yvec.elements.Flt;
  
  Npts = 0;
  for (i = 0; i < Xvec.Nelements; i++, r++, d++) {
    *r = ohana_normalize_angle (*r);
    while (*r < Rmin) *r += 360.0;
    while (*r > Rmax) *r -= 360.0;

    // for pair-by-pair connections, check on second point if we straddle the back midline
    if ((graphmode.ptype == 100) && (i % 2)) {
      leftside = (r[-1] < Rmid); // if first of the pair is left, second must be as well
      if ( leftside && (r[0] > Rmid + 90)) { r[0] -= 360.0; }
      if (!leftside && (r[0] < Rmid - 90)) { r[0] += 360.0; }
    }
    status = RD_to_XY (x, y, *r, *d, &graphmode.coords);

    // if we fail on one of the points, drop the corresponding pair
    if (!status) {
      if (graphmode.ptype == 100) {
	if (i % 2) {
	  // for odd points, skip previous also
	  x--;
	  y--;
	  Npts--;
	} else {
	  // for even points, skip previous also
	  i++;
	  r++;
	  d++;
	}
      }
      continue;
    }
    x++;
    y++;
    Npts++;
  }
  Xvec.Nelements = Npts;
  Yvec.Nelements = Npts;

  graphmode.etype = 0;
  PlotVectorPair (kapa, &Xvec, &Yvec, &graphmode);
  
  free (Xvec.elements.Ptr);
  free (Yvec.elements.Ptr);
    
  return (TRUE);
}

