function y = fill_default(x, x_default)

% function y = fill_default(x,  x_default)
%
% Fill absent or empty fields of structure x with default values in
% structure x_default. Resulting structure is Y.
%
% Example:
%
%  x_default.a = 1;
%  x_default.b = 2;
%  x_default.c = 3;
%  x.a = 'myvalue';
%  x.b = [];
%  y = fill_default(x, x_default);
%  disp(y);
%      a: 'myvalue'
%      b: 2
%      c: 3
%
%
% -- by G. Lathoud, 2005-08-26

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

if isempty(x)
  y = x_default;
else
  y = x;
  fields = fieldnames(x_default);
  for a = 1:length(fields)
    field = fields{ a };
    
    replace = ~isfield(y, field);
    
    if ~replace   % if field present but has empty value
      replace = isempty( eval( [ 'y.' field ] ) );
    end
    
    if replace
      eval( [ 'y.' field ' = x_default.' field ';' ] );
    end
  end
end

y = orderfields( y );
