% FUNCTION Y = FILL_DEFAULT(X,  X_DEFAULT)
%
% Fill absent or empty fields of X with default values in
% 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

function y = fill_default(x, x_default)

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 ] ) );
      if replace
	y = rmfield(y, field);
      end
    end
    
    if replace
      v = eval( [ 'x_default.' field ] );
      eval( [ 'y.' field ' = v;' ] );
    end
  end
end
