# include "dvo.h"

void image_subset (Image *image, int Nimage, int **Subset, int *Nsubset,
	      Graphdata *graph, int RegionSelect, 
	      unsigned long int tzero, double trange, int TimeSelect) 
{

  int i, j, flipped, status, InPic;
  int *subset;
  int N, n, npts;
  double r, d, x[4], y[4], Rmin, Rmax, Rmid;
  double X[8], Y[8];

  if (RegionSelect) {
    Rmin = graph[0].coords.crval1 - 182.0;
    Rmax = graph[0].coords.crval1 + 182.0;
    Rmid = 0.5*(Rmin + Rmax);
  }

  if (trange < 0) {
    tzero = tzero + trange;
    trange = fabs (trange);
  }
  status = InPic = TRUE;
  npts = 200;
  ALLOCATE (subset, int, npts);
  n = N = 0;
  for (i = 0; i < Nimage; i++) {
    if (TimeSelect && ((image[i].tzero < tzero) || (image[i].tzero+image[i].trate*image[i].NY > tzero + trange))) continue;
    if (RegionSelect) {
      /* project this image to screen display coords */
      x[0] = 0;           y[0] = 0;
      x[1] = image[i].NX; y[1] = 0;
      x[2] = image[i].NX; y[2] = image[i].NY;
      x[3] = 0;           y[3] = image[i].NY;
      status = FALSE;
      flipped = FALSE;
      for (j = 0; j < 4; j++) {
	XY_to_RD (&r, &d, x[j], y[j], &image[i].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 |= RD_to_XY (&X[2*j], &Y[2*j], r, d, &graph[0].coords);
	if (j > 0) {
	  X[2*j - 1] = X[2*j];
	  Y[2*j - 1] = Y[2*j];
	}
      }
      X[7] = X[0];
      Y[7] = Y[0];
      InPic = FALSE;
      for (j = 0; status && (j < 8); j+=2) {
	if ((X[j] >= graph[0].xmin) && 
	    (X[j] <= graph[0].xmax) && 
	    (Y[j] >= graph[0].ymin) && 
	    (Y[j] <= graph[0].ymax))
	  InPic = TRUE;
      }
    }
    if (InPic && status) {
      subset[n] = i;
      n++;
      if (n > npts - 1) {
	npts += 200;
	REALLOCATE (subset, int, npts);
      }
    }
  }

  REALLOCATE (subset, int, MAX (n, 1));
  *Subset = subset;
  *Nsubset = n;
  return;
}

/* this routine fills the subset index with the list of selected images.
   images may be selected on the basis of the region or on a time range 
*/
