# include "getstar.h"

Image *gimages (char *filename) {
  
  int i, size, Nimage, nimage;
  double zeropt;
  struct stat filestatus;
  FILE *f;
  Image *timage, *image;
  Header header;
  
  f = fopen (ImageCat, "r");
  if (f == (FILE *) NULL) {
    fprintf (stderr, "error opening image cat %s\n", ImageCat);
    exit (1);
  }

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

  fits_scan (&header, "ZERO_PT", "%lf", 1, &zeropt);
  if (fabs (ZeroPt - zeropt) > 1e-4) {
    fprintf (stderr, "ERROR: zero point in image table (%f:%s) inconsistent with zero point in image header (%f:%s)\n",
	     zeropt, ImageCat, ZeroPt, filename);
    exit (1);
  }

  /* advance to data segment */ 
  fseek (f, header.size, SEEK_SET); 

  Nimage = 0;
  fits_scan (&header, "NIMAGES", "%d", 1, &Nimage);
  /* check that file size makes sense */
  if (stat (ImageCat, &filestatus) == -1) {
    fprintf (stderr, "ERROR: failed to get status of image catalog\n");
    exit (1);
  }
  size = Nimage*sizeof(Image) + header.size;
  if (size != filestatus.st_size) {
    fprintf (stderr, "ERROR: image catalog has inconsistent size\n");
    exit (1);
  } 

  ALLOCATE (timage, Image, Nimage);
  nimage = Fread (timage, sizeof(Image), Nimage, f, "image");
  if (nimage != Nimage) {
    fprintf (stderr, "error reading images from table\n");
    exit (1);
  }

  ALLOCATE (image, Image, 1);
  for (i = 0; i < Nimage; i++) {
    if (strcmp (timage[i].name, filename)) continue;
    memcpy (image, &timage[i], sizeof(Image));
    return (image);
  }

  fprintf (stderr, "error: failed to find desired image\n");
  exit (1);
}
