function obj = dropTrailingODims(obj)
%DROPTRAILINGODIMS Drop trailing singleton dimensions in obj
%
% If obj contains dimension labels, and has trailing dimensions with label
% 'U' and of size 1, these dimensions are removed.

%   Copyright 2019 The MathWorks, Inc.

dimLabels = obj.FormattedData.DimensionMetadata;

if isempty(dimLabels)
    % no labels, nothing to do
    return
end

viewToData = obj.ViewToDataMap;

if isempty(viewToData)
    if dimLabels(end) ~= 'U'
        % Last label isn't 'U', nothing to do
        return
    end
else
    if dimLabels(viewToData(end)) ~= 'U'
        % Last label in view ordering isn't 'U', nothing to do
        return
    end
end


nd = length(dimLabels);
data = obj.FormattedData.Data;

lastInd = nd+1;
for ii=nd:-1:3
    if isempty(viewToData)
        jj = ii;
    else
        jj = viewToData(ii);
    end
    if dimLabels(jj) == 'U' && size(data, jj) == 1
        lastInd = ii;
    else
        break;
    end
end

if lastInd == nd+1
    return
end

if isempty(viewToData)
    obj.FormattedData.DimensionMetadata(lastInd:end) = [];
else
    dataDimsToDrop = viewToData(lastInd:end);
    
    [fdobj, objdata] = extractData(obj.FormattedData);
    
    fdobj.DimensionMetadata(dataDimsToDrop) = [];
    
    szobjdata = size(objdata);
    szobjdata(end+1:nd) = 1;
    
    szobjdata(dataDimsToDrop) = [];
    objdata = reshape(objdata, szobjdata);
    
    obj.FormattedData = insertData(fdobj, objdata);
    
    [~, iperm] = sort(viewToData(1:lastInd-1));
    perm(iperm) = 1:length(iperm);
    
    obj.ViewToDataMap = perm;
    obj.DataToViewMap = iperm;
end
end
