function out = UnescapeForCom(in)
% UnescapeForCom   Recursively convert an escaped cell array to MATLAB
% data object.  See EscapeForCom for more details.  Call this function
% after calling COM method PutWorkspaceData().
    if iscell(in)
        % 'in' must be a cell row vector and the last element is uid.
        uid = in{end};
        if uid == niifm.UidND()
            AssertCellArrayLength(in, 3);
            inner = niifm.UnescapeForCom(in{2});
            out = reshape(inner, in{1});
        elseif uid == niifm.UidStructArray()
            AssertCellArrayLength(in, 3);
            names = in{1};
            values = in{2};
            for k = 1:numel(values)
                for l = 1:numel(values{k})
                    values{k}{l} = niifm.UnescapeForCom(values{k}{l});
                end
            end
            out = cellfun(@(val) cell2struct(val, names), values);
        elseif uid == niifm.UidStruct()
            AssertCellArrayLength(in, 3);
            names = in{1};
            values = in{2};
            for k = 1:numel(values)
                values{k} = niifm.UnescapeForCom(values{k});
            end
            out = cell2struct(values, names);
        elseif uid == niifm.UidComplex()
            AssertCellArrayLength(in, 3);
            out = complex(in{1}, in{2});
        else
            error('NI:Unexpected', 'Internal error: unrecognized uid');
        end
    else
        out = in;
    end
end

function AssertCellArrayLength(c, l)
    if length(c) ~= l
        error('NI:Unexpected', 'Internal error: illegal escaped data');
    end
end

