function out = merge_structs(in)
    %MERGE_STRUCTS Merges multiple structures into a single structure.
    %   Takes a variable number of structures and joins them in such a way that the output structure contains all the
    %   fields of all input structures. In case of field duplication, the value from the latest input struct is taken.
    
    arguments (Repeating)
         in (1,1) struct
    end

    if nargin == 0
        out = struct();
        return;
    end

    out = in{1};
    for i = 2:numel(in)
        out = mergestr(out, in{i});
    end
end

function out = mergestr(a, b)
    out = a;
    fns = fieldnames(b);
    for i = 1:numel(fns)
        fn = fns{i};
        if isstruct(b.(fn)) && isfield(a, fn) && isstruct(a.(fn))
            out.(fn) = mergestr(a.(fn), b.(fn));
        else
            out.(fn) = b.(fn);
        end
    end

    out = orderfields(out);
end