# include "dvoshell.h"

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

/* load images based on parameters and region, etc */
int SetImageSelection (int mode, int RegionSelect) {

  int Ngraph;
  Graphdata graphsky;
  int TimeSelect;
  time_t tzero, tend;

  image = NULL;
  subset = NULL;
  
  if (RegionSelect) {
    Ngraph = 0;
    if (!GetGraphData (&graphsky, NULL, &Ngraph)) {
      gprint (GP_ERR, "region display not available\n");
      return (FALSE);
    }
  }

  TimeSelect = GetTimeSelection (&tzero, &tend);

  switch (mode) {
    case MEAS_XCCD:
    case MEAS_YCCD:
      break;
    case MEAS_XMOSAIC: 
    case MEAS_YMOSAIC:
      /* 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");
      break;
    default:
      return (TRUE);
  }

  if ((image = LoadImages (&Nimage)) == NULL) return (FALSE);
  BuildChipMatch (image, Nimage);
  image_subset (image, Nimage, &subset, &Nsubset, &graphsky, RegionSelect, 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);
}
