function [ count ] = nistwr(fid, fields, values, MIN_HDR_LENGTH)
% [ COUNT ] = NISTWR(FID, FIELDS, VALUES, MIN_HDR_LENGTH)
%
% Write the header for a NIST-type file.
% It is up to the user to write the actual file data.
% It is also up to the user to make sure that the fields and values
% match the data which is written!
%
% FID - file identifier
% FIELDS - cell array of strings containing field names, e.g. 
%    { 'database_id' 'database_version' 'channel_count' 'sample_count' 'sample_n_bytes' }
% VALUES - cell array of values, e.g.
%    { 'UCLA_MRI' '1.0' 2 266 2 }
%
% NIST header type specifications are computed from values as follows:
%   if ischar(values{i}), values{i} is printed as a string, with type '-sX'
%   elseif rem(values{i},1)==0, values{i} is printed as an integer, with type '-i'
%   else values{i} is printed as a real number, with type '-r'
% 
% MIN_HDR_LENGTH (scalar) specifies the minimum header length.  Default value is 1024,
%   since most LDC databases specify a 1024-byte header.
%
% COUNT - number of bytes written (number of bytes in the header, if successful).
%
% VECTOR-VALUED FIELDS:
%
% If any numeric member of VALUES is non-scalar, it is written out as multiple
% header items, with field names of the form
% %s___%d
% where %s is the true field name given in FIELDS, and %d is the vector index.
% This odd notation allows us to read and write vector-valued fields in a manner
% which can still be parsed by the SPHERE library in C.
%

% Set MIN_HDR_LENGTH
if nargin<4,
  MIN_HDR_LENGTH = 1024;
end

% Start with an empty str
str = sprintf('');

% Add all of the specified fields
for i=1:length(fields),
  if ischar(values{i}),
    str = [ str sprintf('%s -s%d %s\n', fields{i}, length(values{i}), values{i}) ];
  else
    % Numeric types: first, define the type
    if rem(values{i},1),
      valtype='-i';
    else
      valtype='-r';
    end
    % Second, find out whether it is vector or scalar
    if length(values{i})==1,
      str = [ str sprintf('%s %s %g\n', fields{i}, valtype, values{i}) ];
    else,
      for vi=1:length(values{i}),
	str = [ str sprintf('%s___%d %s %g\n', fields{i}, vi, valtype, values{i}(vi)) ];
      end
    end
  end
end;

% End the header
str = [ str sprintf('end_head\n') ];

% Add enough newlines to make str MIN_HDR_LENGTH-16 bytes in length,
% and to make sure that the header length is a multiple of an 8-byte word
header_length = length(str);
if header_length < MIN_HDR_LENGTH-16,
  str = [ str char(repmat(10, [1, MIN_HDR_LENGTH-16-header_length])) ];
  header_length = length(str);
end
if rem(header_length, 8) > 0,
  str = [ str char(repmat(10, [1, 8-rem(header_length,8) ])) ];
  header_length = length(str);
end

% Add on the first 16 bytes.  
% These are added last, so that this function can be easily converted to use non-1024-byte headers
str = [ sprintf('NIST_1A\n%7d\n', header_length+16) str ];
header_length = header_length+16;

% Print the result 
count = fprintf(fid, '%s', str);





