# include "getstar.h"

GSCRegion *gregions (image, Nregions)
Image *image;
int *Nregions;
{
  
  GSCRegion *region;
  FILE *f;
  double x, y;
  double dr, dd, dec, ra;
  int i, j, done, nregion, NREGION;
  
  f = fopen (GSCFILE, "r");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't find GSC region file %s\n", GSCFILE);
    exit (1);
  }
  
  /* find regions at image corners */
  NREGION = 10;
  ALLOCATE (region, GSCRegion, NREGION);
  nregion = 0;

  /* look for new regions on grid across image */ 
  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[0].NX*(1.1*x - 0.05), image[0].NY*(1.1*y - 0.05), &image[0].coords);
      aregion (&region[nregion], f, ra, dec);
      done = FALSE;
      for (j = 0; (j < nregion) && !done; j++) {
	if (!strcmp (region[nregion].filename, region[j].filename)) {
	  nregion --;
	  done = TRUE;
	}
      }
      nregion ++;
      if (nregion == NREGION) {
	NREGION += 10;
	REALLOCATE (region, GSCRegion, NREGION);
      }
    }
  }

  if (VERBOSE) {
    fprintf (stderr, "found %d region files:\n", nregion);
    for (i = 0; i < nregion; i++) {
      fprintf (stderr, "  %d %s\n", i, region[i].filename);
    }
  }
  *Nregions = nregion;
  
  fclose (f);
  return (region);
  
}
