% This function summarizes the basics of writing a FITS bintable
% with a single HDU
define write_bintable (filename, extname, data_struct, keyword_struct, history)
{
   variable fp = fits_open_file (filename, "c");
   if (fp == NULL)
     {
	vmessage ("Failed to create file %s", filename);
	return -1;
     }

   fits_write_binary_table (fp, extname, data_struct, keyword_struct);
   () = _fits_write_history (fp, history);

   fp = NULL;
   return 0;
}

% Create a struct to hold the bintable data
% (each struct field defines a column of the same name)
variable d = struct
{
   bin_lo, bin_hi, counts, stat_err
};
d.bin_lo = [0.0:10.0:0.01];
d.bin_hi = d.bin_lo + 0.01;
d.counts = @d.bin_lo;
d.counts[*] = 0.0;
d.stat_err = @d.counts;

% Create a struct to contain the header keywords
% (each struct field defines a keyword of the same name)
variable k = struct
{
   object, telescop, instrume, exposure
};

k.object = "Cyg X-1";
k.telescop = "CHANDRA";
k.instrume = "HETG";
k.exposure = 1.e5;

variable filename, extname, history;
filename = "data.fits";
extname = "NONE";
history = sprintf ("FITS bintable creation demo:  %S", time);

() = write_bintable (filename, extname, d, k, history);

