# include <ohana.h>
# include <gfitsio.h>

/*********************** fits read header ***********************************/
int gfits_read_header (char *filename, Header *header) {
  
  FILE *f;
  
  f = fopen (filename, "r");
  if (f == NULL) {
    header[0].buffer = NULL;
    return (FALSE);
  }
  if (!gfits_load_header (f, header)) {
    fclose (f);
    return (FALSE);
  }

  fclose (f);
  return (TRUE);
}	

int gfits_load_header (FILE *f, Header *header) {

  int i, done, Nbytes, t1, t2;
  char *p;

  header[0].size = 0;
  done = FALSE;
  ALLOCATE (header[0].buffer, char, 1);

  for (i = 0; !done; i++) {
    REALLOCATE (header[0].buffer, char, (i + 1)*FT_RECORD_SIZE);
    Nbytes = fread (&header[0].buffer[i*FT_RECORD_SIZE], 
		    sizeof(char), FT_RECORD_SIZE, f);
    header[0].size += Nbytes;
    if (Nbytes != FT_RECORD_SIZE) {
      return (FALSE);
    }
    if (i == 0) { 
      /* on first block, verify it is a FITS table: SIMPLE .. or XTENSION ... */
      t1 = strncmp (header[0].buffer, "SIMPLE", 6);
      t2 = strncmp (header[0].buffer, "XTENSION", 8);
      if (t1 && t2) return (FALSE);
    }

    p = gfits_header_field (header, "END", 1);
    if (p != NULL)
      done = TRUE;
  }

  header[0].unsign = gfits_get_unsign_mode();
  header[0].bscale = 1;
  header[0].bzero  = 0;
  for (i = 0; i < FT_MAX_NAXES; i++)
    header[0].Naxis[i] = 0;

  gfits_scan (header,  "SIMPLE", "%t",   1, &header[0].simple);
  gfits_scan (header,  "BITPIX", "%d",   1, &header[0].bitpix);
  gfits_scan (header,  "NAXIS",  "%d",   1, &header[0].Naxes);
				                           
  gfits_scan (header,  "EXTEND", "%t",   1, &header[0].extend);
  gfits_scan (header,  "UNSIGN", "%t",   1, &header[0].unsign);
  gfits_scan (header,  "BSCALE", "%lf",  1, &header[0].bscale);
  gfits_scan (header,  "BZERO",  "%lf",  1, &header[0].bzero);
				       
  gfits_scan (header,  "NAXIS1", "%d", 1, &header[0].Naxis[0]);
  gfits_scan (header,  "NAXIS2", "%d", 1, &header[0].Naxis[1]);
  gfits_scan (header,  "NAXIS3", "%d", 1, &header[0].Naxis[2]);
  gfits_scan (header,  "NAXIS4", "%d", 1, &header[0].Naxis[3]);
  gfits_scan (header,  "NAXIS5", "%d", 1, &header[0].Naxis[4]);
  gfits_scan (header,  "NAXIS6", "%d", 1, &header[0].Naxis[5]);
  gfits_scan (header,  "NAXIS7", "%d", 1, &header[0].Naxis[6]);
  gfits_scan (header,  "NAXIS8", "%d", 1, &header[0].Naxis[7]);
  gfits_scan (header,  "NAXIS9", "%d", 1, &header[0].Naxis[8]);
  gfits_scan (header, "NAXIS10", "%d", 1, &header[0].Naxis[9]);

  return (TRUE);

}

int gfits_fread_header (FILE *f, Header *header) {

  int status;
  
  status = gfits_load_header (f, header);
  return (status);
}
