function [ beamlets ] = write_ryan_beamlets ( filename, beamlets )
%WRITE_RYAN_BEAMLETS Write beamlet cell array out to Ryan's format
%
%   Example:
%       [ ] = write_ryan_beamlets ( filename, beamlets )
%
%   See also read_ryan_beamlets, open_beamlet_batch.
%
%   Copyleft 1999-, XMO.

if nargin < 2
    error('Usage: write_ryan_beamlets ( filename, beamlets )');
end

fid = fopen(filename, 'w');

if ( fid == -1 )
    error(['cannot open "' filename '"']);
end

fwrite(fid, numel(beamlets), 'int');

for k = 1:numel(beamlets)
    % beamlet number (or index), base 0 for C
    fwrite(fid, beamlets{k}.num, 'int');
    
    fwrite(fid, beamlets{k}.x_count, 'int');
    fwrite(fid, beamlets{k}.y_count, 'int');
    fwrite(fid, beamlets{k}.z_count, 'int');
        
    fwrite(fid, numel(beamlets{k}.non_zero_indices), 'int');
    fwrite(fid, beamlets{k}.non_zero_indices-1, 'int'); % base 0 for C
    fwrite(fid, beamlets{k}.non_zero_values, 'float');
end

fclose(fid);
