function C = wpakdec(im,level,wname)
% WPAKDEC - 2D dekompozice Wavelet Packet
%   WPAKDEC ziska pro vstupni 2D signal dekompozici transformace Wavelet
%   Packet do urovne dekompozice LEVEL pro vlnku WNAME. Funkce vyuziva
%   vlnky implementovane v programu MATLAB. 
%   Seznam dostupny pomoci HELP WAVEINFO 
%   Dekompozice se provadi pomoci DWT2
% 
%   WPAKDEC urci nejlepsi baze ohodnocenim pdostromu pomoci Shannonovy
%   entropie.
% 
%   Obecny tvar funkce:
%   C = WPAKDEC(IM,LEVEL,WNAME)
%
%   Pro rekonstrukci pomoci WPAKREC je potrebne nastavit DWTMODE: 'per'
%   V jinem pripade se doporucuje pouzit funkce WPAKREC2.

%% Definice vstupnich promennych
level = level*2;
C{1}{1} = im;
%% dekompozice a urceni entropie prvni urovne
en{1}{1} = wentropy(C{1}{1},'shannon');
[C{2}{1},C{2}{2},C{2}{3},C{2}{4}] = dwt2(C{1}{1},wname);
en{2} = cell(1,4);
for i = 1:4
   en{2}{i} = wentropy(C{2}{i},'shannon');
end
%% dekompozice pro dalsi urovne
for tmp = 2:(level/2)
        for i = 2:2:(2^(tmp*2)/2)
        if isempty(C{tmp}{i/2}) == 0
       [C{tmp+1}{i*2-3},C{tmp+1}{i*2-2},C{tmp+1}{i*2-1},C{tmp+1}{i*2}]= ...
           dwt2(C{tmp}{i/2},wname);
        else
            C{tmp+1}{i*2-3}=[];
            C{tmp+1}{i*2-2}= [];
            C{tmp+1}{i*2-1} = [];
            C{tmp+1}{i*2}= [];
        end
        end
%% Urceni entropie pro ostatni urovne
    for i = 1:length(C{tmp+1})
    en{tmp+1}{i} = wentropy(C{tmp+1}{i},'shannon');
    end

    for i = 2:2:(2^(tmp*2)/2)
    ent{tmp+1}{i/2} = en{tmp+1}{i*2-3}+en{tmp+1}{i*2-2}+en{tmp+1}{i*2-1}+en{tmp+1}{i*2};
    end
%% Porovnani entropie s entropii odpovidajiciho uzlu "rodice"
    for i = 2:2:(2^(tmp*2)/2)
    if ent{tmp+1}{i/2} > en{tmp}{i/2}
        C{tmp+1}{i*2-3} = [];C{tmp+1}{i*2-2} = [];
        C{tmp+1}{i*2-1} = [];C{tmp+1}{i*2} = [];
    end
    end
end