# include "relphot.h"

static int   Nimage;
static int   *Line;
static Image *image;

GSCRegion *load_images (char *seed, int *nregion, GSCRegion *fullregion) {

  GSCRegion *region;
  int       Nregion, Ntimage;
  Image     *timage;

  region = name_region (seed, &Nregion);

  /* find images which supplied all measurements */
  timage = find_images (region, Nregion, &Ntimage, &Line);
  free (Line);

  /* find all region files which touch images */
  region = find_regions (timage, Ntimage, &Nregion, fullregion);
  free (timage);

  /* find images which supplied all measurements for all regions */
  image = find_images (region, Nregion, &Nimage, &Line);
  getfullregion (image, Nimage, fullregion);

  initImages (image, Nimage);
  initMosaics (image, Nimage);
  
  *nregion = Nregion;
  return (region);

}

void wimages () {
  
  int i, status, mode;
  FILE *f;
  Header header;

  setMcalFinal (image, Nimage);

  if (!fits_read_header (ImageCat, &header)) {
    fprintf (stderr, "ERROR: can't find %s\n", ImageCat);
    exit (0);
  }
  
  f = fopen (ImageCat, "r+");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't open image catalog file to append: %s\n", ImageCat);
    exit (0);
  }
  mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
  chmod (ImageCat, mode);

  if (VERBOSE) fprintf (stderr, "writing out %d images\n", Nimage);
  for (i = 0; i < Nimage; i++) {
    fseek (f, header.size + Line[i]*sizeof(Image), SEEK_SET);
    status = Fwrite (&image[i], sizeof(Image), 1, f, "image");
    if (status != 1) {
      fprintf (stderr, "ERROR: failure writing image data to catalog %s\n", ImageCat);
      exit (0);
    }
  }

  fclose (f);
}
