# include "fits.h"

/* a basic table header (extension) is different from a primary header
   in that it has the word XTENSION and a type for the first line,
   instead of SIMPLE */

/*********************** fits create Theader *********************************/
int fits_create_Theader (Header *header, char *type) {
  
  int i;
  char axis[10];
  
  header[0].size = 2880;
  ALLOCATE (header[0].buffer, char, 2880);
  
  for (i = 0; i < 2880; i++) 
  header[0].buffer[i] = ' ';
  strncpy (header[0].buffer, "END", 3);
  
  fits_modify (header, "XTENSION", "%s", 1, type);
  fits_modify (header, "BITPIX", "%d", 1, header[0].bitpix);
  fits_modify (header, "NAXIS",  "%d", 1, header[0].Naxes);
  
  for (i = 0; i < header[0].Naxes; i++) {
    sprintf (axis, "NAXIS%d", i + 1);
    fits_modify (header,  axis, "%d", 1, header[0].Naxis[i], 1);
  }
  
  /* PCOUNT & GCOUNT are not implemented, but they are required to be here */
  fits_modify (header, "PCOUNT", "%d", 1, 0);
  fits_modify (header, "GCOUNT", "%d", 1, 1);
  if (!strcmp (type, "IMAGE")) {
    fits_modify (header, "BSCALE", "%lf", 1, header[0].bscale);
    fits_modify (header, "BZERO",  "%lf", 1, header[0].bzero);
  }

  return (TRUE);
}	

/*********************** fits create table header *********************************/
int fits_create_table_header (Header *header, char *type, char *extname) {
  
  int i, valid;
  char axis[10];

  /* check valid table types */
  valid = FALSE;
  valid |= !strcmp (type, "TABLE");
  valid |= !strcmp (type, "BINTABLE");
  if (!valid) return (FALSE);

  /* create empty header buffer */
  header[0].size = 2880;
  ALLOCATE (header[0].buffer, char, 2880);
  
  for (i = 0; i < 2880; i++) 
  header[0].buffer[i] = ' ';
  strncpy (header[0].buffer, "END", 3);

  /* a table has BITPIX = 8, NAXIS = 2 */
  header[0].simple = FALSE;
  header[0].unsign = FALSE;
  header[0].extend = FALSE;
  header[0].bitpix = 8;
  header[0].bscale = 1;
  header[0].bzero  = 0;
  header[0].Naxes  = 2;
  for (i = 0; i < FT_MAX_NAXES; i++)
    header[0].Naxis[i] = 0;
  
  /* required keywords */
  fits_modify (header, "XTENSION", "%s", 1, type);
  fits_modify (header, "BITPIX", "%d", 1, header[0].bitpix);
  fits_modify (header, "NAXIS",  "%d", 1, header[0].Naxes);
  
  for (i = 0; i < header[0].Naxes; i++) {
    sprintf (axis, "NAXIS%d", i + 1);
    fits_modify (header,  axis, "%d", 1, header[0].Naxis[i], 1);
  }
  
  /* PCOUNT & GCOUNT are not implemented, but they are required to be here */
  fits_modify (header, "PCOUNT", "%d", 1, 0);
  fits_modify (header, "GCOUNT", "%d", 1, 1);
  if (!strcmp (type, "IMAGE")) {
    fits_modify (header, "BSCALE", "%lf", 1, header[0].bscale);
    fits_modify (header, "BZERO",  "%lf", 1, header[0].bzero);
  }

  fits_modify (header, "TFIELDS", "%d", 1, 0);
  fits_modify (header, "EXTNAME", "%s", 1, extname);
  
  return (TRUE);
}	
