# include "photdbc.h"

/* given a list of images, find all region files which overlap these images.
   if a region file does not exist, we should recognize this fact somehow */

GSCRegion *find_regions (Image *image, int Nimage, int *Nregions, GSCRegion *fullregion) {

  int i, nregions;
  double x, y;
  GSCRegion *regions;
  double MinRA, MaxRA, MinDEC, MaxDEC, ra, dec;

  if (VERBOSE) fprintf (stderr, "finding regions: ");
  
  /* find RA and DEC range of images */
  MinRA = MinDEC = +361;
  MaxRA = MaxDEC = -361;
  for (i = 0; i < Nimage; i++) {
    for (x = 0.0; x <= 1.0; x+=0.25) {
      for (y = 0.0; y <= 1.0; y+=0.25) {
	XY_to_RD (&ra, &dec, image[i].NX*(1.1*x - 0.05), image[i].NY*(1.1*y - 0.05), &image[i].coords);
	MinRA = MIN (ra, MinRA);
	MaxRA = MAX (ra, MaxRA);
	MinDEC = MIN (dec, MinDEC);
	MaxDEC = MAX (dec, MaxDEC);
      }
    }
  }

  /* if images overlap 0,360 boundary, then use -180 to +180 range */
  if (MaxRA - MinRA > 180) {
    MinRA = +361;
    MaxRA = -361;
    for (i = 0; i < Nimage; i++) {
      for (x = 0.0; x <= 1.0; x+=0.25) {
	for (y = 0.0; y <= 1.0; y+=0.25) {
	  XY_to_RD (&ra, &dec, image[i].NX*(1.1*x - 0.05), image[i].NY*(1.1*y - 0.05), &image[i].coords);
	  if (ra > 180) ra -= 360;
	  MinRA = MIN (ra, MinRA);
	  MaxRA = MAX (ra, MaxRA);
	}
      }
    }
  }

  fullregion[0].RA[0] = MinRA;
  fullregion[0].RA[1] = MaxRA;
  fullregion[0].DEC[0] = MinDEC;
  fullregion[0].DEC[1] = MaxDEC;

  /* find all region files containing specified ra, dec range */  
  regions = get_regions (MinRA, MaxRA, MinDEC, MaxDEC, &nregions);

  if (VERBOSE) fprintf (stderr, "%d found\n", nregions);

  *Nregions = nregions;
  return (regions);
}


void getfullregion (Image *image, int Nimage, GSCRegion *fullregion) {

  int i;
  double x, y;
  double MinRA, MaxRA, MinDEC, MaxDEC, ra, dec;

  /* find RA and DEC range of images */
  MinRA = MinDEC = +361;
  MaxRA = MaxDEC = -361;
  for (i = 0; i < Nimage; i++) {
    for (x = 0.0; x <= 1.0; x+=0.25) {
      for (y = 0.0; y <= 1.0; y+=0.25) {
	XY_to_RD (&ra, &dec, image[i].NX*(1.1*x - 0.05), image[i].NY*(1.1*y - 0.05), &image[i].coords);
	MinRA = MIN (ra, MinRA);
	MaxRA = MAX (ra, MaxRA);
	MinDEC = MIN (dec, MinDEC);
	MaxDEC = MAX (dec, MaxDEC);
      }
    }
  }

  /* if images overlap 0,360 boundary, then use -180 to +180 range */
  if (MaxRA - MinRA > 180) {
    MinRA = +361;
    MaxRA = -361;
    for (i = 0; i < Nimage; i++) {
      for (x = 0.0; x <= 1.0; x+=0.25) {
	for (y = 0.0; y <= 1.0; y+=0.25) {
	  XY_to_RD (&ra, &dec, image[i].NX*(1.1*x - 0.05), image[i].NY*(1.1*y - 0.05), &image[i].coords);
	  if (ra > 180) ra -= 360;
	  MinRA = MIN (ra, MinRA);
	  MaxRA = MAX (ra, MaxRA);
	}
      }
    }
  }

  fullregion[0].RA[0] = MinRA;
  fullregion[0].RA[1] = MaxRA;
  fullregion[0].DEC[0] = MinDEC;
  fullregion[0].DEC[1] = MaxDEC;
}
