function writeasc(fid, fmt, data, varargin)
%--------------------------------------------------------------------------
% SYNOPSIS
%
%   writeasc(fid, fmt, data [ sep, bad ])
%
% DESCRIPTION
%
%   Write DATA in the file described by FID. The number fo columns and
%   lines in data is respected while writing data to file. Columns are
%   separated by string SEP (default is two spaces), and NaN values
%   are replaced by string BAD (default is 1.0E38). Padding is carried out
%   so that data will appear in the same columns. Data are written with
%   format specifier FMT. 
%
%--------------------------------------------------------------------------

% Defaults:

sep = '  ';
bad = '1.0E38';

% Arguments

if nargin > 3,
  sep = varargin{1};
end
if nargin > 4,
  bad = varargin{2};
end
  
% Initializations:
good_sep = sep;
bad_sep  = sep;

% Get format length for bad values
len = sscanf(fmt, '%*c%d', 1);
if len < length(bad),
  for i=1:(length(bad)-len),
    good_sep = [ good_sep ' ' ];
  end
end
if len > length(bad),
  for i=1:(len - length(bad)),
    bad_sep = [ bad_sep ' ' ];
  end
end

% Get lines and columns:
lines = size(data,1);
cols  = size(data,2);
for i=1:lines,
  for j=1:cols,
    if isnan(data(i,j)),
      fprintf(fid, bad_sep);
      fprintf(fid, bad);
    else
      fprintf(fid, good_sep);
      fprintf(fid, fmt, data(i,j));
    end
  end
  fprintf(fid, '\n');
end



