function VykresliDendrogram(MatVzd, Metoda)
%
% VykresliDendrogram(MatVzd, Metoda)
%
% Vykresli dendrogram, ziskany zvolenou hierarchichou zhlukovaciou metodou
%
% VSTUP:
% - MatVzd   : Matica vzdialenosti
% - Metoda   : Hierarchicka zhlukovacia metoda:
%              'single', 'average' alebo 'complete'


[m,m1] = size(MatVzd);
k = m;
MatVzd = MatVzd + diag(inf*ones(1,m));  % Na diagonale budeme mat celu dobu 
                                        % nekonecno pre ulahcenie prace

V = linspace(1,m+2,m+2);  % Pozicia objektov vo finalnej linearnej mnozine objektov
F = inf * ones(1,m+1);    % Vzdialenost nasledujuceho zhluku od predchadzajuceho zhluku
                          % bude ulozena na prvej pozicii druheho zhluku
Z = ones(1,m);
for n = 1:m-1
    % Najdi minimalnu vzdialenost v MatVzd(i,j) i<j
	[di,I] = ... 
  [dj,j] = ... 
  i = ...
    
    % Len jedna cast matice vzdialenosti je uvazovana
	if i > j, j1 = j; j = i; i = j1; end
    
	% Kombinacia zhlukov i,j
    switch Metoda
        case 'single'
            MatVzd(i,:) = ...
        case 'complete'
            MatVzd(i,:) = ...
        case 'average'
            MatVzd(i,:) = ...
            Z(i:j-1) = ...
            Z(j) = ...
    end

	MatVzd(:,i) = MatVzd(i,:)';
	MatVzd(i,i) = inf;
	MatVzd(j,:) = []; MatVzd(:,j) = [];
    % Ulozime vzdialenost zhlukov
	F(V(j)) = dj;
    % Posun druhy zhluk v linearnom usporiadani presne za prvym zhlukom
	IV = [1:V(i+1)-1,V(j):V(j+1)-1,V(i+1):V(j)-1,V(j+1):m+1];
    F = F(IV);   % Uloz zaznam pozic objektov a vzdialenosti zhlukov
	V = [V(1:i),V(i+1:j) + V(j+1) - V(j),V(j+2:m-n+3)];
end

S = sort(-F); t = -S(k+1);  % Najdi hladinu zhluku
I = [find(F >= t),m+1];     % Najdi vsetky indexy kde zhluk zacina
DenGram = [I(2:k+1) - I(1:k); F(I(1:k))];

%%%%%%%%%%
[n,m] = size(DenGram);
[S,I] = sort(DenGram(2,:));
C = [0:m-1;1:m;zeros(1,m);2:m+1];
X = zeros(m,4); Y = X;

for i=1:m-1
	X(i,:) = [C(2,I(i)), C(2,I(i)), C(2,C(1,I(i))), C(2,C(1,I(i)))];
	Y(i,:) = [C(3,I(i)), S(i), S(i), C(3,C(1,I(i)))];
	C(:,C(1,I(i))) = [C(1,C(1,I(i))), (C(2,I(i)) + C(2,C(1,I(i))))/2, ...
        S(i), C(4,I(i))]';
	C(1,C(4,I(i))) = C(1,I(i));
end
X(m,:) = [0 0 m+1 m+1];
Y(m,:) = [0 0 0 0];

figure;
plot(X', Y', '-b');
title([Metoda ' linkage']);
h = gca; set(h,'box','off');

return
