# include <ohana.h>
# include <gfitsio.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 gfits_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);
  
  gfits_modify (header, "XTENSION", "%s", 1, type);
  gfits_modify (header, "BITPIX", "%d", 1, header[0].bitpix);
  gfits_modify (header, "NAXIS",  "%d", 1, header[0].Naxes);
  
  for (i = 0; i < header[0].Naxes; i++) {
    sprintf (axis, "NAXIS%d", i + 1);
    gfits_modify (header,  axis, "%d", 1, header[0].Naxis[i], 1);
  }
  
  /* PCOUNT & GCOUNT are not implemented, but they are required to be here */
  gfits_modify (header, "PCOUNT", "%d", 1, 0);
  gfits_modify (header, "GCOUNT", "%d", 1, 1);
  if (!strcmp (type, "IMAGE")) {
    gfits_modify (header, "BSCALE", "%lf", 1, header[0].bscale);
    gfits_modify (header, "BZERO",  "%lf", 1, header[0].bzero);
  }

  return (TRUE);
}	

/*********************** fits create table header *********************************/
int gfits_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 */
  gfits_modify (header, "XTENSION", "%s", 1, type);
  gfits_modify (header, "BITPIX", "%d", 1, header[0].bitpix);
  gfits_modify (header, "NAXIS",  "%d", 1, header[0].Naxes);
  
  for (i = 0; i < header[0].Naxes; i++) {
    sprintf (axis, "NAXIS%d", i + 1);
    gfits_modify (header,  axis, "%d", 1, header[0].Naxis[i], 1);
  }
  
  /* PCOUNT & GCOUNT are not implemented, but they are required to be here */
  gfits_modify (header, "PCOUNT", "%d", 1, 0);
  gfits_modify (header, "GCOUNT", "%d", 1, 1);
  if (!strcmp (type, "IMAGE")) {
    gfits_modify (header, "BSCALE", "%lf", 1, header[0].bscale);
    gfits_modify (header, "BZERO",  "%lf", 1, header[0].bzero);
  }

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