# include "fits.h"
int FT_UNSIGN_MODE;

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

  fclose (f);
  return (TRUE);
}	

int fits_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 = fits_header_field (header, "END", 1);
    if (p != NULL)
      done = TRUE;
  }

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

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

  return (TRUE);

}

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

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