# include "fits.h"

/*********************** fits write header *********************************/
int fits_write_table (char *filename, FTable *table) {
  
  FILE *f;
  int status;
  
  status = TRUE;
  
  f = fopen (filename, "a+");
  if (f == (FILE *) NULL) return (FALSE);
  
  status = fseek (f, 0, SEEK_END);  /* write table to end of file! */
  status = fits_fwrite_table (f, table);

  fclose (f);
  return (status);
}	

/*********************** fits write table *********************************/
int fits_fwrite_table (FILE *f, FTable *table) {
  
  int Nbytes;
  
  Nbytes = fwrite (table[0].buffer, sizeof(char), table[0].size, f);
  
  if (Nbytes != table[0].size) return (FALSE);
  return (TRUE);
}	

/*********************** fits write virtual table *********************************/
int fits_fwrite_vtable (FILE *f, VTable *table) {
  
  int i, Nx, Ny, Npad, offset, start;
  int Nbytes, *row, Nrow;
  char *pad;

  Nrow = table[0].Nrow;
  row = table[0].row;
  fits_scan (table[0].header, "NAXIS1", "%d", 1, &Nx);
  fits_scan (table[0].header, "NAXIS2", "%d", 1, &Ny);

  /* file pointer is at beginning of desired table data */
  start = ftell (f);
  
  for (i = 0; i < Nrow; i++) {
    offset = start + Nx*row[i];
    fseek (f, offset, SEEK_SET);
    Nbytes = fwrite (table[0].buffer[i], sizeof (char), Nx, f);
    if (Nbytes != Nx) { return (FALSE); }
  }
  
  Npad = table[0].size - Nx*Ny;
  ALLOCATE (pad, char, Npad);
  bzero (pad, Npad);

  offset = start + Nx*Ny;
  fseek (f, offset, SEEK_SET);
  Nbytes = fwrite (pad, sizeof (char), Npad, f);
  if (Nbytes != Npad) { return (FALSE); }
  free (pad);

  return (TRUE);
}	


/* this will add data beyond the end of the table in the file if needed,
   filling intervening gap with 0 */
