# include "dvoshell.h"

/* db image table */
static Image *image = NULL;
static off_t *subset = NULL;
static off_t Nimage = 0;
static off_t Nsubset = 0;
static Coords mosaic;

/* load images based on parameters and region, etc */
int SetImageSelection (int mosaicMode, SkyRegionSelection *selection) {

  int TimeSelect;
  time_t tzero, tend;

  image = NULL;
  subset = NULL;
  
  TimeSelect = GetTimeSelection (&tzero, &tend);

  if (mosaicMode) {
      /* mosaic defines a frame with 0,0 at the mosaic center, and 1 arcsec / pixel */
      mosaic.crpix1 = mosaic.crpix2 = 0.0;
      mosaic.cdelt1 = mosaic.cdelt2 = 1.0 / 3600;
      mosaic.pc1_1  = mosaic.pc2_2  = 1.0;
      mosaic.pc1_2  = mosaic.pc2_1  = 0.0;
      mosaic.Npolyterms = 0;
      strcpy (mosaic.ctype, "RA---SIN");
  }

  if ((image = LoadImages (&Nimage)) == NULL) return (FALSE);
  BuildChipMatch (image, Nimage);
  image_subset (image, Nimage, &subset, &Nsubset, selection, tzero, (double) tend - tzero, TimeSelect);
  sort_image_subset (image, subset, Nsubset);
  return (TRUE);
}

/* free loaded images */
void FreeImageSelection () {
  if (image != NULL) free (image);
  if (subset != NULL) free (subset);
  image = NULL;
  subset = NULL;
  return;
}

Image *MatchImage (unsigned int time, short int source) { 

  int m;

  m = match_image_subset (image, subset, Nsubset, time, source);
  if (m == -1) return (NULL);
  if (!FindMosaicForImage (image, Nimage, m)) return (NULL);
  return (&image[m]);
}

Coords *MatchMosaic (unsigned int time, short int source) { 

  int m;

  m = match_image_subset (image, subset, Nsubset, time, source);
  if (m == -1) return (NULL);
  mosaic.crval1 = image[m].coords.crval1;
  mosaic.crval2 = image[m].coords.crval2;
  return (&mosaic);
}
