function out = EscapeForCom(in)
% EscapeForCom  Recursively convert any MATLAB data object to cell arrays.
% Call this function before calling COM method GetWorkspaceData().
    if ischar(in)
        out = in;
    elseif numel(in) > 1
        if ndims(in) > 2
            out = { size(in), reshape(in, numel(in), 1), niifm.UidND() };
            out{2} = niifm.EscapeForCom(out{2});
        elseif isstruct(in)
            names = fieldnames(in(1));
            values = cell(size(in));
            for k = 1:numel(values)
                values{k} = struct2cell(in(k));
                for l = 1:numel(values{k})
                    values{k}{l} = niifm.EscapeForCom(values{k}{l});
                end
            end
            out = { names, values, niifm.UidStructArray() };
        elseif isnumeric(in)
            if ~isreal(in)
                out = { real(in), imag(in), niifm.UidComplex() };
            else
                out = in;
            end
        elseif islogical(in)
            out = in;
        else
            ThrowTypeNotSupportedError(in)
        end
    elseif numel(in) == 1
        if isstruct(in)
            names = fieldnames(in);
            values = struct2cell(in);
            for k = 1:numel(values)
                values{k} = niifm.EscapeForCom(values{k});
            end
            out = { names, values, niifm.UidStruct() };
        elseif isnumeric(in)
            if ~isreal(in)
                out = { real(in), imag(in), niifm.UidComplex() };
                out{1} = niifm.EscapeForCom(out{1});
                out{2} = niifm.EscapeForCom(out{2});
            elseif isnan(in)
                if isa(in, 'single')
                    out = { niifm.UidSglNaN() };
                else
                    out = { niifm.UidDblNaN() };
                end
            else
                out = in;
            end
        elseif islogical(in)
            out = in;
        else
            ThrowTypeNotSupportedError(in)
        end
    else
        out = { niifm.UidEmpty() };
    end
end

function ThrowTypeNotSupportedError(in)
    error('Type ''%s'' is not supported.',class(in))
end