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

/***********************/
int gfits_define_bintable_column (Header *header, char *format, char *label, char *comment, char *unit, double bscale, double bzero) {

  int Nfields, Nbytes, Nval, Naxis1;
  char type[16], field[16];
  
  if (!gfits_bintable_format (format, type, &Nval, &Nbytes)) return (FALSE);
  
  Nfields = 0;
  gfits_scan (header, "TFIELDS", "%d", 1, &Nfields);
  gfits_scan (header, "NAXIS1",  "%d", 1, &Naxis1);
  Nfields ++;
  Naxis1 += Nbytes*Nval;

  sprintf (field, "TTYPE%d", Nfields);
  gfits_modify (header, field, "%s", 1, label);
  gfits_modify (header, field, "%C", 1, comment);
  sprintf (field, "TUNIT%d", Nfields);
  gfits_modify (header, field, "%s", 1, unit);
  sprintf (field, "TFORM%d", Nfields);
  gfits_modify (header, field, "%s", 1, format);
  sprintf (field, "TSCAL%d", Nfields);
  gfits_modify (header, field, "%lf", 1, bscale);
  sprintf (field, "TZERO%d", Nfields);
  gfits_modify (header, field, "%lf", 1, bzero);

  /* update TFIELDS & NAXIS1 */
  gfits_modify (header, "TFIELDS", "%d", 1, Nfields);
  gfits_modify (header, "NAXIS1",  "%d", 1, Naxis1);
  header[0].Naxis[0] = Naxis1;

  return (TRUE);
}

/***********************/
int gfits_define_table_column (Header *header, char *format, char *label, char *comment, char *unit) {

  int Nstart, Nfields, Nbytes, Nval, Naxis1;
  char type[16], field[16], cformat[16];

  strcpy (cformat, format);
  if (!gfits_table_format (cformat, type, &Nval, &Nbytes)) return (FALSE);

  Nfields = 0;
  gfits_scan (header, "TFIELDS", "%d", 1, &Nfields);
  gfits_scan (header, "NAXIS1",  "%d", 1, &Naxis1);
  Nstart = Naxis1 + 1;
  Nfields ++;
  Naxis1 += Nbytes*Nval;

  sprintf (field, "TTYPE%d", Nfields);
  gfits_modify (header, field, "%s", 1, label);
  gfits_modify (header, field, "%C", 1, comment);
  sprintf (field, "TUNIT%d", Nfields);
  gfits_modify (header, field, "%s", 1, unit);
  sprintf (field, "TFORM%d", Nfields);
  gfits_modify (header, field, "%s", 1, format);

  sprintf (field, "TBCOL%d", Nfields);
  gfits_modify (header, field, "%d", 1, Nstart);

  gfits_modify (header, "TFIELDS", "%d", 1, Nfields);
  gfits_modify (header, "NAXIS1",  "%d", 1, Naxis1);
  header[0].Naxis[0] = Naxis1;

  return (TRUE);
}
