function str = merge_options(str, varargin)
% Merges fields from one structure into another.

% Copyright 2012 Levente Hunyadi

validateattributes(str, {'struct'}, {'scalar'}, 1);
if nargin > 2  % merge named options, passed as fun('Name', value)
    for k = 1 : 2 : numel(varargin)
        field = varargin{k};
        validateattributes(field, {'char'}, {'nonempty','row'}, 1 + k);
        str.(field) = varargin{k+1};
    end    
elseif nargin > 1  % merge a single structure
    arg = varargin{1};
    validateattributes(arg, {'struct'}, {'scalar'}, 2);
    fields = fieldnames(arg);
    for k = 1 : numel(fields)
        field = fields{k};
        str.(field) = arg.(field);
    end
end
