# include "fits.h"

/***********************/
int fits_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 (!fits_bintable_format (format, type, &Nval, &Nbytes)) return (FALSE);
  
  Nfields = 0;
  fits_scan (header, "TFIELDS", "%d", 1, &Nfields);
  fits_scan (header, "NAXIS1",  "%d", 1, &Naxis1);
  Nfields ++;
  Naxis1 += Nbytes*Nval;

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

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

  return (TRUE);
}

/***********************/
int fits_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 (!fits_table_format (cformat, type, &Nval, &Nbytes)) return (FALSE);

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

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

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

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

  return (TRUE);
}
