# include "delstar.h"

Image *gimages (char *filename) {
 
  FILE *f;
  Header header;
  char line[64], photcode[64], *c;
  struct tm timeptr;
  double tmp, jd;
  Image *image;
  int Nsec, Nc;

  ALLOCATE (image, Image, 1);
  /* load header */
  if (!fits_read_header (filename, &header)) {
    fprintf (stderr, "ERROR: can't find image file %s\n", filename);
    Shutdown ();
  }

  /* open file */
  f = fopen (filename, "r");
  if (f == NULL) {
    fprintf (stderr, "ERROR: can't find data file %s\n", filename);
    Shutdown ();
  }
  fseek (f, header.size, SEEK_SET); 

  /* add file name to image structure */
  c = strrchr (filename, 0x2f);
  if (c == (char *) NULL) {
    strcpy (image[0].name, filename);
  } else { 
    strcpy (image[0].name, (c+1));
  }

  /* get astrometry information */
  if (!GetCoords (&image[0].coords, &header)) {
    fprintf (stderr, "ERROR: no astrometric solution in header\n");
    Shutdown ();
  }
  while (image[0].coords.crval1 < 0) image[0].coords.crval1 += 360.0;
  while (image[0].coords.crval1 > 360.0) image[0].coords.crval1 -= 360.0;

  /* CERROR in data file is in pixels, convert to 20*arcsec */
  image[0].cerror = tmp * 50.0 * image[0].coords.cdelt1 * 3600.0;
  while (image[0].coords.crval1 < 0) image[0].coords.crval1 += 360.0;
  while (image[0].coords.crval1 > 360.0) image[0].coords.crval1 -= 360.0;
 
  /* get other header info */
  fits_scan (&header, "NAXIS1",   "%hd", 1, &image[0].NX); 
  fits_scan (&header, "NAXIS2",   "%hd", 1, &image[0].NY);

  fits_scan (&header, "PHOTCODE", "%s", 1, photcode);
  Nc = GetPhotcodeCodebyName (photcode);
  if (!Nc) {
    fprintf (stderr, "ERROR: photcode %s not found in photcode table\n", photcode);
    Shutdown ();
  }
  image[0].source = Nc;

  tmp = 0;
  fits_scan (&header, "FLIMIT",   "%lf", 1, &tmp);
  image[0].detection_limit = tmp * 10.0;

  tmp = 0;
  fits_scan (&header, "FSATUR",   "%lf", 1, &tmp);
  image[0].saturation_limit = tmp * 10.0;

  if (!fits_scan (&header, "TZERO",   "%d",  1, &image[0].tzero)) {
    image[0].tzero = parse_time (&header);
  }

  tmp = 0;
  fits_scan (&header, "TRATE",   "%lf", 1, &tmp);
  image[0].trate = 10000 * tmp;

  tmp = 0;
  fits_scan (&header, "AIRMASS", "%lf", 1, &tmp);
  image[0].secz = 1000*tmp;

  /* secz is in units milli-airmass */
  image[0].Mcal =  ALPHA*(image[0].secz - 1000);
  image[0].Xm   = NO_MAG;

  free (header.buffer);
 
  return (image);
}
