# include "astro.h"

int cplot (int argc, char **argv) {
  
  int i, kapa, Npts, status, leftside;
  float *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);

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

  ALLOCATE (Xvec.elements, float, xvec[0].Nelements);
  ALLOCATE (Yvec.elements, float, xvec[0].Nelements);
    
  Xvec.Nelements = xvec[0].Nelements;
  Yvec.Nelements = xvec[0].Nelements;
  
  r = xvec[0].elements;
  d = yvec[0].elements;
  x = Xvec.elements;
  y = Yvec.elements;
  
  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 = fRD_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;

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

