function [objdata, viewToData, dataToView] = squeezedata(objdata, viewToData)
%SQUEEZEDATA Squeeze underlying data if it contains trailing singletons
%   [OBJDATA, VIEWTODATA, DATATOVIEW] = SQUEEZEDATA(OBJDATA, VIEWTODATA)
%   reshapes OBJDATA such that it doesn't have more dimensions than its
%   permutation into view coordinates.
%   This means that singleton dimensions which are trailing singletons in
%   view order are squeezed out.
%
%   Note: If the original object has dimension labels, outputs viewToData
%   and dataToView may need to be extended to fit the number of labels.

%   Copyright 2019 The MathWorks, Inc.

% If there is no internal permutation, there is nothing to do.
if isempty(viewToData)
    return
end

% If the last dimension is not singleton, there is nothing to do.
if length(viewToData) == 2 || size(objdata, viewToData(end)) ~= 1
    return
end

% Find the number of trailing singleton dimensions of obj
nd = length(viewToData);
szobjdata = size(objdata, 1:nd);
lastInd = nd;
for ii=nd-1:-1:3
    if szobjdata(viewToData(ii)) == 1
        lastInd = ii;
    else
        break;
    end
end

% Construct new size of objdata where all singleton dimensions which map to
% trailing singletons in view are dropped
dataDimsToDrop = viewToData(lastInd:end);
szobjdata(dataDimsToDrop) = [];

% Reshape objdata
objdata = reshape(objdata, szobjdata);

% Compute new permutation vector after dropping trailing singletons
[~, dataToView] = sort(viewToData(1:lastInd-1));

% Reverse permutation
viewToData = [];
viewToData(dataToView) = 1:length(dataToView);

end
