# include "relastro.h"

# define MARKTIME(MSG,...) { \
  float dtime; \
  gettimeofday (&stop, (void *) NULL); \
  dtime = DTIME (stop, start); \
  fprintf (stderr, MSG, __VA_ARGS__); }

SkyList *load_images (FITS_DB *db, SkyRegion *region) {

  Image     *image, *subset;
  off_t      Nimage, Nsubset;
  off_t     *LineNumber;
  struct timeval start, stop;

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

  gettimeofday (&start, (void *) 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
  skylist = SkyListByPatch (sky, -1, region);
  MARKTIME("  setup sky: %f sec\n", dtime);

  // convert database table to internal structure
  image = gfits_table_get_Image (&db[0].ftable, &Nimage, &db[0].swapped);
  MARKTIME("  convert image table: %f sec\n", dtime);

  // select the images which overlap the selected sky regions
  subset = select_images (skylist, image, Nimage, &LineNumber, &Nsubset);
  MARKTIME("  select images: %f sec\n", dtime);

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

  initImages (subset, Nsubset);
  MARKTIME("  init images: %f sec\n", dtime);

  initMosaics (subset, Nsubset);
  MARKTIME("  init mosaics: %f sec\n", dtime);
  
  /* unlock, if we can (else, unlocked below) */
  if (!UPDATE) dvo_image_unlock (db); 

  return (skylist);
}
