function [c,S] = wpakdec2(im,level,wname)
% WPAKDEC2 - 2D dekompozice Wavelet Packet
%   WPAKDEC2 ziska pro vstupni 2D signal dekompozici transformace Wavelet
%   Packet C do urovne dekompozice LEVEL pro vlnku WNAME. Funkce vyuziva
%   vnlky implementovani v programu MATLAB.
%   Seznam dostupny pomoci HELP WAVEINFO 
%   Funkce dale uchovava informace o rozmerech dekompozice na jednotlivych
%   urovnich
%   Dekompozice se provadi pomoci WAVEDEC2
%   
%   WPAKDEC2 urci nejlepsi baze ohodnocenim pdostromu pomoci Shannonovy
%   entropie.
%     
%   Obecny rvar funkce:
%   [C,S] = WPAKDEC2(IM,LEVEL,WNAME)

%% Definice vstupnich promennych
level = level*2;
c{1}{1} = im(:,:,1);
%% dekompozice a urceni entropie prvni urovne
en{1}{1} = wentropy(c{1}{1},'shannon');
[C,S{2}{1}] = wavedec2(c{1}{1},1,wname);
len = length(C)/4;
c{2}{1} = reshape(C(1:(len)),S{2}{1}(1,1),S{2}{1}(1,2));
c{2}{2} = reshape(C(len+1:2*len),S{2}{1}(1,1),S{2}{1}(1,2));
c{2}{3} = reshape(C(2*len+1:3*len),S{2}{1}(1,1),S{2}{1}(1,2));
c{2}{4} = reshape(C(3*len+1:4*len),S{2}{1}(1,1),S{2}{1}(1,2));
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,S{tmp+1}{i*2-3}] = wavedec2(c{tmp}{i/2},1,wname);
            len = length(C)/4;
            c{tmp+1}{i*2-3} = reshape(C(1:(len)),S{tmp+1}{i*2-3}(1,1),S{tmp+1}{i*2-3}(1,2));
            c{tmp+1}{i*2-2} = reshape(C(len+1:2*len),S{tmp+1}{i*2-3}(1,1),S{tmp+1}{i*2-3}(1,2));
            c{tmp+1}{i*2-1} = reshape(C(2*len+1:3*len),S{tmp+1}{i*2-3}(1,1),S{tmp+1}{i*2-3}(1,2));
            c{tmp+1}{i*2}   = reshape(C(3*len+1:4*len),S{tmp+1}{i*2-3}(1,1),S{tmp+1}{i*2-3}(1,2));
        else
            S{tmp+1}{i*2-3} = [];
            c{tmp+1}{i*2-3}=[];
            c{tmp+1}{i*2-2}= [];
            c{tmp+1}{i*2-1} = [];
            c{tmp+1}{i*2}= [];
        end
        S{tmp+1}{i*2-2} = [];
        S{tmp+1}{i*2-1} = [];
        S{tmp+1}{i*2} = [];
        end
%% Urceni entropie pro dalsi 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