function X = permuteUnformattedRecurrentOutput(X, XHasNoObservationDim, dataFormat)
% Remove the labels and permute the output to the user's ordering
%
%   Copyright 2019-2020 The MathWorks, Inc.

% Remove the labels
X = stripdims(X);

% The internal data is returned as CBT, we need to find the correct
% permutation to return the data in the user's ordering

% Edit the dataFormat to get labels compatible with the recurrent operation
% output
dataFormat = iEnsureDataFormatContainsCBTOnly(dataFormat);

% There is always a T
timeViewIdx = find(dataFormat == 'T');
perm = timeViewIdx;

% If there was a B, use it. Otherwise output array was reshaped as CT.
if ~XHasNoObservationDim
    observationViewIdx = find(dataFormat == 'B');
    perm = [ observationViewIdx timeViewIdx ];
end

% Find the C dimension
channelViewIdx = find(dataFormat == 'C');
if isempty(channelViewIdx)
    % Place the channel dimension at the end
    channelViewIdx = numel(perm)+1;
end
perm = [ channelViewIdx perm ];

% Permutes back in the same order as DataFormat
X = ipermute(X, perm);
end


function dataFormat = iEnsureDataFormatContainsCBTOnly(dataFormat)
% Modify the DataFormat to obtain a version compatible with the output of
% the recurrent operation. This ensure that the format contains at most
% three labels C B T. The possible outputs of this function are
% permutations of the formats CBT, BT and T.

% Remove singleton U labels
dataFormat(dataFormat == 'U') = [];

% Find the S labels
spatialViewIdx = find(dataFormat == 'S');

if any(dataFormat == 'C')
    % Just remove the S labels
    dataFormat(spatialViewIdx) = [];
else
    if ~isempty(spatialViewIdx)
        % There are some spatial dimension but no C. Replace the first S
        % with C
        dataFormat(spatialViewIdx(1)) = 'C';
        dataFormat(spatialViewIdx(2:end)) = [];
    end
end
end