# include "relphot.h"

SkyList *load_images (FITS_DB *db, char *regionName, SkyRegion *region, int RegionSelect) {

  Image     *image, *subset;
  int        Nimage, Nsubset, Nchar;
  int       *LineNumber;

  SkyTable *sky = NULL;
  SkyList *skylist = NULL;

  // load the current sky table (layout of all SkyRegions) 
  sky = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, TRUE, SKY_DEPTH, VERBOSE);
  SkyTableSetFilenames (sky, CATDIR, "cpt");
  
  // determine the populated SkyRegions overlapping the requested area
  if (RegionSelect) {
    skylist = SkyListByPatch (sky, -1, region);
  } else {
    Nchar = strlen(regionName);
    if (!strcmp (&regionName[Nchar-4], ".cpt")) regionName[Nchar-4] = 0;
    skylist = SkyListByName (sky, regionName);
  }

  // convert database table to internal structure
  image = gfits_table_get_Image (&db[0].ftable, &Nimage, &db[0].swapped);

  // select the images which overlap the selected sky regions
  subset = select_images (skylist, image, Nimage, &LineNumber, &Nsubset);

  gfits_vtable_from_ftable (&db[0].ftable, &db[0].vtable, LineNumber, Nsubset);

  initImages (subset, Nsubset);
  initMosaics (subset, Nsubset);
  
  return (skylist);
}

int reload_images (FITS_DB *db) {

  Image     *image;
  int        Nimage, Nx, i;
  VTable    *vtable;

  image = getimages (&Nimage);

  vtable = &db[0].vtable;

  gfits_scan (vtable[0].header, "NAXIS1", "%d", 1, &Nx);
  for (i = 0; i < Nimage; i++) {
    memcpy (vtable[0].buffer[i], &image[i], Nx);
  }
  return (TRUE);
}
