function s = write_bin(f, array, varargin)
%
% Writes a double-precision binary file with a header,
% using the same format as serasc2bin.py.
%
% function s = write_bin(filename, array, name, rownames)
% or       s = write_bin(s, array, options)
%     filename : name of file to write;
%
%     array    : 2-d array, nrows x ncolumns
%                 normally, ncolumns >> nrows
%     name     : string, name of array
%     rownames : cell array with nrows string elements,
%                 names of the rows of a
%
%     Options:  (only one for now)
%
%     'start', 52   write array to the file starting at
%                        record 52 (1-based); that is,
%                        replace 52 and following records.
%     To append, omit the 'start' argument pair, or use
%     'start', 0, or use a 'start' value that is beyond
%     the end of the file.  (I don't know whether that
%     will work reliably on non-Linux systems, though,
%     so it is not recommended.)
%
%     s        : input or output, a structure including
%                  the fid of the file.  On input it can
%                  include the 'start' field.  On output
%                  it includes 'ilast', the 1-based index
%                  of the last record written.
%
%     If there is no output argument, the file will be
%     closed.
%
%     EF, JH 2001/04/11
%

[s.nrows, nc] = size(array);

if ischar(f),
   filename = f;
   if length(varargin) >= 2 & iscell(varargin{2})
      name = varargin{1};
      rownames = varargin{2};
      varargin(1:2) = [];
      % Open first with 'w' mode to truncate it.
      s.fid = fopen(filename, 'wb');
      fprintf(s.fid, '%d %d %s\n', s.nrows, s.nrows + 1, name);
      for ii = 1:s.nrows,
         fprintf(s.fid, '%s\n', rownames{ii});
      end
      s.offset = ftell(s.fid);
      fclose(s.fid);
      % Additional writes may require random positioning,
      % for which 'r+' mode is needed.
      s.fid = fopen(filename, 'r+b');
   else     % read info from an existing file
      [ar, sr] = read_bin(filename, 'last', 1);
      fclose(sr.fid);
      s.offset = sr.offset;
      if s.nrows ~= sr.nrows,
         error(sprintf('%d rows in file, %d in array: mismatch', ...
                            sr.nrows, s.nrows));
      end
      s.fid = fopen(filename, 'r+b');
   end
   s.start = 0;
   s = fillstruct(s, varargin);
elseif isstruct(f),
   if isempty(varargin),
      s = f;
      s.start = 0;
   else
      f.start = 0;
      s = fillstruct(f, varargin);
   end
else
   error(['First argument must be a filename, or a structure\n', ...
          'from a previous call to read_bin_incr'])
end

s.start = max(0, s.start);

if s.start == 0,
   fseek(s.fid, 0, 'eof');
else
   offset = s.offset + (s.start - 1) * s.nrows * 8;
   fseek(s.fid, offset, 'bof');
end

count = fwrite(s.fid, array, 'float64');
s.ilast = (ftell(s.fid) - s.offset) / (s.nrows * 8);

if nargout == 0,
   fclose(s.fid);
end

