function sc = wpaklim2(C,cfs)
%   WPAKLIM - Omezeni poctu keoficientu transformace Wavelet Packet
% WPAKLIM omezi celkovy pocet keoficientu C na CFS nejvyznamnejsich
% koeficientu. Vystupem bude stromova struktura koeficientu omezeneho 
% poctu koeficientu OUT.
% 
% WPAKLIM pracuje s koeficienty ziskanymi pomoci WPAKDEC a WPAKDEC2.
% 
% Obecny tvar funkce:
% OUT = WPAKLIM(C,CFS)
% clear all;
% close all;
% 

% load cwh;
 c = C;
 %cfs = 4000;

%% Urceni delky bunky
leng = length(c);
%% Definice nejvyssi urovne
%c{1}{1} = [];
%% Ponechani potrebnych vzorku
for i = 2:1:leng
    d = 1;
    for k = 1:4:length(c{i})
        if isempty(c{i}{k}) == 0 || isempty(c{i}{k+1}) == 0 || isempty(c{i}{k+2}) == 0 || isempty(c{i}{k+3}) == 0
          c{i-1}{d} = []; 
            d = d+1; 
        else d = d+1; 
        end        
    end    
end
%% Rozklad 
d = 1;
for i = leng:-1:2
    for k = 1:length(c{i})
        if isempty(c{i}{k}) == 0
            siz = size(c{i}{k});
            s{d} = reshape(c{i}{k},1,siz(1)*siz(2));
            d = d+1; 
        end
    end    
end
%% Usporadani koeficientu do radkoveho vektoru
lin = [];
for i = 1:length(s)
    lin = [lin s{i}  ];
end
%% "Prahovani"
len = length(lin);
if cfs > len;
    cfs = len;
end
[~,Y] = sort(abs(lin),'descend');
val = zeros(1,length(Y));
% val = lin(cfs);

i = 1;
while i<cfs+1 
    val(Y(i)) =lin(Y(i));
    i = i+1;
end
o = 0;

for i = 1:length(s)
    linw{i} = val(o+1:o+length(s{i}));
    o = o+length(s{i});
end
d = 1;
for i = leng:-1:2
    for k = 1:length(c{i})
        if isempty(c{i}{k}) == 0
            siz = size(c{i}{k});
            sc{i}{k} = reshape(linw{d},siz(1),siz(2));
            d = d+1;
        else sc{i}{k} = [];
%         else d = d+1;
        end
    end    
end

 %Slozeni vystupu do puvodniho tvaru s ponechanim CFS keoficientu
% % for i = 2:leng
% %     f = 1;
% %     for k = 1:length(c{i})
% %         if isempty(c{i}{f})==0
% %             out{i}{f} = c{i}{f} .* (abs(c{i}{f})>=val);
% %             f = f+1;
% %         else out{i}{f} = [];
% %              f=f+1;
% %         end 
% %     end
% % end