function[KT,NU,DS] = kant(P)
% Funkce pro vypocet kanonickeho tvaru matice prechodu rozlozitelneho HMR
% Syntaxe: [KT,NU,DS] = kant(P)
% Vstupni parametr: P ... matice prechodu HMR
% Vystupni parametry: KT ... matice prechodu v kanonickem tvaru
%                     NU ... nove usporadani
%                     DS ... tabulka dosazitelnych stavu
% Vytvoril: Vaculik Karel

n = size(P,1);
akt = 1;
KT = P;
C = zeros(n);
sorted = 0;
newsort = 1:n;
while akt<=n
	row = find(P(akt,:));
    col = find(P(akt,:)==0);
	nr = length(row);
    nc = length(col);
    s = 1; 
	while s<=nr
        k = 1;
		while k<=nc
			if P(row(s),col(k))~=0
				row = [row col(k)];
				nr = nr+1;
				col(k) = [];
                nc = nc-1;
            else
                k = k+1;
            end;
		end;
        s = s+1;
	end;
    for k = 1:nr
        C(akt,row(k)) = 1;
    end;
    akt = akt+1;
end;
DS = C;
akt = 1;
while akt<=n
    if C(akt,akt)==1
        if sum(C(akt,:))<(n)
            row = find(C(akt,:));
            nr = length(row);
            newfind = true;
            for k=1:nr
                if C(akt,:) == C(row(k),:) else
                    newfind = false; break;
                end;
            end;
            if newfind==true
                col = find(C(akt,(sorted+1):n)==0)+sorted;
                akt = akt+nr-1;
                C = C([1:sorted row col],[1:sorted row col]);
                newsort = newsort([1:sorted row col]);
                sorted = sorted+nr;
            end;       
        end;
    end;
    akt = akt+1;
end;
KT = KT(newsort,newsort);
NU = newsort;

end
