%tablica prawdopodobienstw symboli
%hc[kod_binarny, ilosc_bitow]
function hc = BuildHuffTree(P)

	if(nargin==0)
		P   = [0.01, 0.02, 0.07, 0.02, 0.04, 0.14, 0.07, 0.14, 0.49]';

%		P   = [0.15, 0.16, 0.17, 0.17, 0.35]';
	end
    
	N = length(P);
    P = reshape(P, N, 1);
    if(N<=1)
        hc = [0, 1];
        return;
    end

	idx = 1;
	Prob = 2;
	L = 3;
	R = 4;
	Parent = 5;
	Kod = 6;

	ht = zeros(2*N-1, 2);
	ht(:, idx)=[1:2*N-1]';

	ht(1:N, Prob)=P;
	ht(N+1:2*N-1, Prob)=1;


	for i=1:N-1
		[m1, mi1] = min(ht(:, Prob));
		ht(mi1, Prob)=1;
		ht(mi1, Parent) = N+i;
		ht(mi1, Kod) = 0;
		
		[m2, mi2] = min(ht(:, Prob));
		ht(mi2, Prob)=1;
		ht(mi2, Parent) = N+i;
		ht(mi2, Kod) = 1;
		
		ht(N+i, Prob)=m1+m2;
		ht(N+i, L)=mi1;
		ht(N+i, R)=mi2;
	end	
	
	ht;
	
	hc = zeros(N,2);
	ROOT = 2*N-1;

	%disp('œcie¿ki od korzenia do symbolu dla poszczególnych symboli')
	for i=1:N
		b = ht(i, Kod);
		kod = num2str(b);
		p = ht(i, Parent);
		c = b;
		k=1;
		while(p~=ROOT)
			b = ht(p, Kod);
			kod = [kod, num2str(b)];
			p = ht(p, Parent);
			c = c + b*2^k;
			k = k+1;
		end	
		kod = ['s', num2str(i),': ', fliplr(kod)];	%idziemy od korzenia do symbolu
		%disp(kod);
		hc(i, 1)= c;
		hc(i, 2)= k;		%dlugosc kodu
	end
%end BuildHuffTree	

	