function [uplo, rowPerm, colPerm] = hIsPermutedTriangular(A)
%Check if matrix is permuted triangular and return permutations
%   


%   Copyright 2020-2021 The MathWorks, Inc.

assert(ismatrix(A) && size(A, 1) == size(A, 2), "Input must be 2D and square.");

rowPerm = [];
colPerm = [];
uplo = 'NotTriangular';

% If we know it's not permuted-triangular give up now.
if A.Metadata.IsPermutedTriangular.isKnown() && ~A.Metadata.IsPermutedTriangular.get()
    return;
end

% Check for permuted triangular and find the required permutations.
rowNnz = sum(A ~= 0, 2)';
colNnz = sum(A ~= 0, 1);
n = size(A, 1);

if all(colNnz <= n:-1:1) % row lo
    [~, rowPerm] = sort(rowNnz, 'ascend');
    uplo = 'LowerTriangular';
elseif all(colNnz <= 1:n) % row up
    [~, rowPerm] = sort(rowNnz, 'descend');
    uplo = 'UpperTriangular';
elseif all(rowNnz <= 1:n) % col lo
    [~, colPerm] = sort(colNnz, 'descend');
    uplo = 'LowerTriangular';
elseif all(rowNnz <= n:-1:1) % col up
    [~, colPerm] = sort(colNnz, 'ascend');
    uplo = 'UpperTriangular';
end

% If it is 'NotTriangular', it is not permuted-triangular.
A.Metadata.IsPermutedTriangular.set(~strcmp(uplo, 'NotTriangular'));
end
