# include "dvo.h"

int imbox (int argc, char **argv) {
  
  int i, j, status, InPic, flipped, Nextend;
  Vector Xvec, Yvec;
  double r, d, x[4], y[4], Rmin, Rmax, Rmid;
  Header header;
  Coords coords;
  Graphdata graphmode;
  int Ngraph;

  if (argc != 2) {
    fprintf (stderr, "USAGE: imbox (filename)\n");
    return (FALSE);
  }
  Ngraph = 0;
  if (!GetGraph (&graphmode, NULL, &Ngraph)) return (FALSE);

  if (!fits_read_header (argv[1], &header)) {
    fprintf (stderr, "file not found\n");
    return (FALSE);
  }
  
  Nextend = 0;
  if (header.Naxes == 0) {
    fits_scan (&header, "NEXTEND", "%d", 1, &Nextend);
  }
  
  Rmin = graphmode.coords.crval1 - 182.0;
  Rmax = graphmode.coords.crval1 + 182.0;
  Rmid = 0.5*(Rmin + Rmax);
  
  /* project this image to screen display coords */
  ALLOCATE (Xvec.elements, float, 8);
  ALLOCATE (Yvec.elements, float, 8);

  for (i = Nextend ? 0 : -1; i < Nextend; i++) {
    if (Nextend) {
      fits_read_Xheader (argv[1], &header, i);
    }
    if (!GetCoords (&coords, &header)) {
      fprintf (stderr, "can't get WCS info from header\n");
      return (TRUE);
    }
    x[0] = 0;               y[0] = 0;
    x[1] = header.Naxis[0]; y[1] = 0;
    x[2] = header.Naxis[0]; y[2] = header.Naxis[1];
    x[3] = 0;               y[3] = header.Naxis[1];
    status = FALSE;
    flipped = FALSE;
    for (j = 0; j < 4; j++) {
      XY_to_RD (&r, &d, x[j], y[j], &coords);
      while ((j == 0) && (r < Rmin)) { flipped = TRUE; r += 360.0; }
      while ((j == 0) && (r > Rmax)) { flipped = TRUE; r -= 360.0; }
      if ((j > 0) && flipped) {
	while (r < Rmid) r+= 360.0;
	while (r > Rmid) r-= 360.0;
      }
      status |= fRD_to_XY (&Xvec.elements[2*j], &Yvec.elements[2*j], r, d, &graphmode.coords);
      if (j > 0) {
	Xvec.elements[2*j - 1] = Xvec.elements[2*j];
	Yvec.elements[2*j - 1] = Yvec.elements[2*j];
      }
    }
    Xvec.elements[7] = Xvec.elements[0];
    Yvec.elements[7] = Yvec.elements[0];
    InPic = FALSE;
    for (j = 0; j < 8; j+=2) {
      if ((Xvec.elements[j] >= graphmode.xmin) && 
	  (Xvec.elements[j] <= graphmode.xmax) && 
	  (Yvec.elements[j] >= graphmode.ymin) && 
	  (Yvec.elements[j] <= graphmode.ymax))
	InPic = TRUE;
    }

    Xvec.Nelements = Xvec.Nelements = 8;
    if (InPic) {
      graphmode.style = 2; /* points */
      graphmode.ptype = 100; /* connect pairs of points */
      graphmode.etype = 0;
      PrepPlotting (8, &graphmode);
      PlotVector (8, Xvec.elements);
      PlotVector (8, Yvec.elements);
    }
  }

  fits_free_header (&header);
  free (Xvec.elements);
  free (Yvec.elements);
  return (TRUE);

}


