function param = extractParameter(param, errorIDFcn)
% Extract a param if it is wrapped in a dlarray

%   Copyright 2019 The MathWorks, Inc.

if isa(param, 'dlarray')
    fd = param.FormattedData;
    if ~isempty(fd.DimensionMetadata) % formatted dlarray
        % Perform the internal permutations to obtain X in the builtin order
        param = permuteExplicitly(param);
        fd = param.FormattedData;
        
        % Ensure no 'S', 'T' or 'B' dims
        if (~isempty(finddatadim(param,'S')) || ~isempty(finddatadim(param,'B')) || ~isempty(finddatadim(param,'T')))
            error(iGetErrorMessage(errorIDFcn, 'InvalidLabeled'));
        end
        
        % Make sure there is a C dimension
        channelIdx = finddatadim(param, 'C');
        if isempty(channelIdx)
            error(iGetErrorMessage(errorIDFcn, 'InvalidLabeled'));
        end
        
        % Extract param in the ordered format
        [~,param] = extractData(fd);
        
    else % Unformatted dlarray
        % Extract weights in the format needed by builtin convolution functions.
        [~,param] = extractData(fd);
    end
else
    deep.internal.dlarray.validateNonDlarray(param);
end

% Validate there are only 2 dimensions
if ~ismatrix(param)
    error(iGetErrorMessage(errorIDFcn, 'TooManyDimensions'));
end
end

function msg = iGetErrorMessage(errorIDFcn, IDName)
s = errorIDFcn();
msg =  message(s.(IDName));
end
