function X = f_3DArray2KD(X, sz, k)
% f_3DArray2KD  Inverse of f_KDArray2ThreeD: reshape 3D tensor back to K-way tensor
%
%   This function reverses the transformation done by f_KDArray2ThreeD.
%   It reshapes a 3D tensor back into its original K-mode tensor form,
%   based on the provided shape and unfolding mode.
%
%   Inputs:
%       X  - 3D tensor of shape [sz(R), prod(sz(vC)), sz(k)]
%       sz - Original size vector of the K-way tensor
%       k  - Mode used in the unfolding (1-based index)
%
%   Output:
%       X  - Reshaped tensor of size sz, with original mode order restored

K = length(sz);  % Number of modes (dimensionality)

% Build cyclic index extension: idx_aug = [K, 1, 2, ..., K, 1, 2, ..., K]
idx_aug = [K, 1:K, 1:K];

% Get mode R and its complement vC, based on cyclic relationship
R = idx_aug(k);
vC = idx_aug((k+2):(K-3+k+2));

% Determine permutation applied earlier: [R, vC, k]
idx_p = [R, vC, k];

% Reshape 3D tensor back into a K-way tensor with permuted dimensions
X = reshape(X, [sz(R), sz(vC), sz(k)]);

% Invert the permutation to get back to original mode order
idx_new = zeros(1, K);  % Initialize permutation index
for kk = 1:K
    idx_new(kk) = find(idx_p == kk);  % Recover position of each mode
end

% Apply inverse permutation to restore original dimension order
X = permute(X, idx_new);
end
