% FUNCTION WRITE_MATRIX(M, P)
%
% Note: I/O in little endian format
%
% by Guillaume LATHOUD at IDIAP (lathoud@idiap.ch)

function write_matrix(m, p)

% parameters

if nargin < 2
  error('write_matrix needs two parameters');
end

if ~isempty(find(isnan(m)))
  disp('write_matrix: WARNING: there are NaNs in your matrix');
end

if ~isempty(find(isinf(m)))
  disp('write_matrix: WARNING: there are Infs in your matrix');
end


required_fields = { 'name' };
check_param(required_fields, fieldnames(p));

p_default.verbose = 1;
p_default.dir = '';
p_default.header = 0;
p_default.type = 'float64';
p = fill_default(p, p_default);

% verbosity
if p.verbose
  p
end

% open file

f_out = fullfile(p.dir, p.name);
fid_out = fopen(f_out, 'w', 'l');
if fid_out < 0
  error(['write_matrix could not write-open ' f_out]);
end

% write header if asked for it

if p.header
  write_matrix_header(fid_out, p.type, size(m));
end

% write data

fwrite(fid_out, m, p.type);

% close

fclose(fid_out);
