function mergedStruct = mergeStruct(varargin)
% merges the fields of structures
% 
% mergedStruct = mergeStruct(s1, s2, ..., sN) merges the fields of struct
%   s1 to sN. If field names are not unique, the value of the first 
%   occurance is taken.
%
% See also: mergeList, struct

% MDT: MATLAB developement tools
%   Copyright (C) 2012 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU Lesser General Public License as published 
%   by the Free Software Foundation, either version 3 of the License, or 
%   (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License 
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.

%% Check if inputs are structs
for i = 1:nargin
    if ~isstruct(varargin{i})
        error(['Input ' num2str(i) ' is no structure.']);
    end
end

mergedStruct = struct;
for i = nargin:-1:1
    %% Get field names and values
    names = fieldnames(varargin{i});
    values = struct2cell(varargin{i});
    %% Assign each
    for j = 1:length(names)
        mergedStruct.(names{j}) = values{j};
    end
end
