# include "dvoshell.h"
static float dr[] = {0.0, 1.0, 1.0, 0.0};
static float dd[] = {0.0, 0.0, 1.0, 1.0};

int showtile (int argc, char **argv) {

  int kapa, Nd, N, NPTS, status, i, InPic;
  Graphdata graphmode;
  Coords coords;
  Vector Xvec, Yvec;
  float r, d, R, D;
  float Ro[90], Do[90];

  /* show tile pattern in viewed region */
  if (!GetGraph (&graphmode, &kapa, NULL)) return (FALSE);

  if (argc != 1) {
    gprint (GP_ERR, "USAGE: showtile [option]\n");
    return (FALSE);
  }
  
  N = 0;
  NPTS = 200;
  ALLOCATE (Xvec.elements, float, NPTS);
  ALLOCATE (Yvec.elements, float, NPTS);

  /* starting position */

  /* reference for coords is this image */
  coords.crpix1 = coords.crpix2 = 0.0;
  coords.crval1 = coords.crval2 = 0.0;
  coords.cdelt1 = coords.cdelt2 = 1.0;
  coords.pc1_1  = coords.pc2_2  = 1.0;
  coords.pc1_2  = coords.pc2_1  = 0.0;
  coords.Npolyterms = 0;
  strcpy (coords.ctype, "RA---TAN");
  
  /* fill in top-left region */
  for (r = 0; r < 3; r += 1.0) {
    gprint (GP_ERR, "r: %f\n", r);
    for (Nd = d = 0; d < 90; Nd ++, d += 1.0) {
      if (r == 0) {
	coords.crval1 = r;
	coords.crval2 = d;
      } else {
	coords.crval1 = Ro[Nd];
	coords.crval2 = Do[Nd];
      }
      for (i = 0; i < 4; i++) {
	fXY_to_RD (&R, &D, dr[i], dd[i], &coords);
	status |= fRD_to_XY (&Xvec.elements[N+2*i], &Yvec.elements[N+2*i], R, D, &graphmode.coords);
	if (i > 0) {
	  Xvec.elements[N+2*i - 1] = Xvec.elements[N+2*i];
	  Yvec.elements[N+2*i - 1] = Yvec.elements[N+2*i];
	}
	if (i == 1) {
	  Ro[Nd] = R;
	  Do[Nd] = D;
	}
      }
      Xvec.elements[N+7] = Xvec.elements[N];
      Yvec.elements[N+7] = Yvec.elements[N];

      /* check if any corner is in plotting region */
      InPic = FALSE;
      for (i = 0; i < 8; i+=2) {
	if ((Xvec.elements[N+i] >= graphmode.xmin) && 
	    (Xvec.elements[N+i] <= graphmode.xmax) && 
	    (Yvec.elements[N+i] >= graphmode.ymin) && 
	    (Yvec.elements[N+i] <= graphmode.ymax))
	  InPic = TRUE;
      }
      if (!InPic) continue;
      N+=8;
      if (N > NPTS - 1) {  /* this is OK because NPTS is made always a multiple of 8 */
	NPTS += 200;
	REALLOCATE (Xvec.elements, float, NPTS);
	REALLOCATE (Yvec.elements, float, NPTS);
      }
    }
  }
  
  Xvec.Nelements = Xvec.Nelements = N;
  if (N > 0) {
    graphmode.style = 2; /* points */
    graphmode.ptype = 100; /* connect pairs of points */
    graphmode.etype = 0;
    PlotVectorPair (kapa, N, Xvec.elements, Yvec.elements, &graphmode);
  }

  free (Xvec.elements);
  free (Yvec.elements);
  return (TRUE);

}
