# include "uniphot.h"

Image *load_images (int *nimage) {

  int    i, Nimage, status, equiv;
  FILE  *f;
  Image *image;
  Header header;

  if (VERBOSE) fprintf (stderr, "finding images\n");

  /* open image datafile */
  if ((f = fopen (ImageCat, "r")) == (FILE *) NULL) {
    fprintf (stderr, "ERROR: can't open image table %s\n", ImageCat);
    exit (1);
  }

  /* read header */
  if (!fits_fread_header (f, &header)) {
    fprintf (stderr, "ERROR: can't read image table header %s\n", ImageCat);
    exit (1);
  }

  /* read number of images */
  Nimage = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimage);
  if (Nimage == 0) {
    fprintf (stderr, "ERROR: No images in catalog %s (1)\n", ImageCat);
    exit (1);
  }

  /* load all images */
  ALLOCATE (image, Image, Nimage);
  status = Fread (image, sizeof(Image), Nimage, f, "image");
  if (status != Nimage) {
    fprintf (stderr, "ERROR: couldn't read all images from image catalog: %s\n", ImageCat);
    exit (1);
  }
  fclose (f);

  /* mark images to be calibrated */
  for (i = 0; i < Nimage; i++) {
      
    image[i].code |= ID_IMAGE_NOCAL;

    /* select images by photcode */
    equiv = GetPhotcodeEquivCodebyCode (image[i].source);
    if (equiv != photcode[0].code) continue;

    /* select images by time */
    if (TimeSelect) {
      if (image[i].tzero < TSTART) continue;
      if (image[i].tzero > TSTOP) continue;
    }

    image[i].code &= ~ID_IMAGE_NOCAL;
  }
  *nimage = Nimage;
  return (image);
}
