# include "fits.h"

/*********************** fits read Theader ***********************************/
int fits_read_Theader (char *filename, Header *Theader) {
  
  FILE *f;
  Header header;
  int status, Nbytes;
  
  status = fits_read_header (filename, &header);
  if (!status) {
    fprintf (stderr, "error reading header of FITS file %s\n", filename);
    return (FALSE);
  }

  f = fopen (filename, "r");
  if (f == NULL) {
    Theader[0].buffer = NULL;
    fits_free_header (&header);
    return (FALSE);
  }

  Nbytes = fits_matrix_size (&header);
  fseek (f, Nbytes, SEEK_SET);
  fits_free_header (&header);

  status = fits_load_Theader (f, Theader);
  fclose (f);
  return (status);
}	

/* load table from STREAM positioned at beginning of table header */
/*********************** fits load Theader ***********************************/
int fits_load_Theader (FILE *f, Header *Theader) {
  
  char *p;
  int i, done, status, Nbytes;
  
  Theader[0].size = 0;
  done = FALSE;
  ALLOCATE (Theader[0].buffer, char, 1);

  for (i = 0; !done; i++) {
    REALLOCATE (Theader[0].buffer, char, (i + 1)*FT_RECORD_SIZE);
    Nbytes = fread (&Theader[0].buffer[i*FT_RECORD_SIZE], 
		    sizeof(char), FT_RECORD_SIZE, f);
    Theader[0].size += Nbytes;
    if (Nbytes != FT_RECORD_SIZE) 
      done = TRUE;
    p = fits_header_field (Theader, "END", 1);
    if (p != NULL)
      done = TRUE;
  }

  Theader[0].bscale = 0;
  Theader[0].bzero  = 0;
  for (i = 0; i < FT_MAX_NAXES; i++)
    Theader[0].Naxis[i] = 0;

  status = TRUE;
  status &= fits_scan (Theader,  "BITPIX", "%d", 1, &Theader[0].bitpix);
  status &= fits_scan (Theader,  "NAXIS",  "%d", 1, &Theader[0].Naxes);
  if (!status) return (FALSE);
				                           
  fits_scan (Theader,  "NAXIS1", "%d", 1, &Theader[0].Naxis[0]);
  fits_scan (Theader,  "NAXIS2", "%d", 1, &Theader[0].Naxis[1]);
  fits_scan (Theader,  "NAXIS3", "%d", 1, &Theader[0].Naxis[2]);
  fits_scan (Theader,  "NAXIS4", "%d", 1, &Theader[0].Naxis[3]);
  fits_scan (Theader,  "NAXIS5", "%d", 1, &Theader[0].Naxis[4]);
  fits_scan (Theader,  "NAXIS6", "%d", 1, &Theader[0].Naxis[5]);
  fits_scan (Theader,  "NAXIS7", "%d", 1, &Theader[0].Naxis[6]);
  fits_scan (Theader,  "NAXIS8", "%d", 1, &Theader[0].Naxis[7]);
  fits_scan (Theader,  "NAXIS9", "%d", 1, &Theader[0].Naxis[8]);
  fits_scan (Theader, "NAXIS10", "%d", 1, &Theader[0].Naxis[9]);

  return (TRUE);
}	

/*********************** fits fread Theader ***********************************/
int fits_fread_Theader (FILE *f, Header *Theader) {
  
  int status;
  
  status = fits_load_Theader (f, Theader);
  return (status);
}
