function pic = wave2im(C,S,level,wname)
% WAVEIM - Usporadani koeficientu 2D waveletove transformace pro zobrazeni
%   WAVEIM usporada do PIC koeficienty C urcene dekompozici na urovni 
%   LEVEL pro vlnku WNAME do tvaru vhodne pro zobrazeni. Promenna S 
%   uchovava informace o rozmerech rozkladu na jednotlivych urovnich.
%   Hodnoty C a S jsou ziskane pomoci WAVEDEC2.
%   
%   Obecny tvar funkce:
%   PIC = WAVE2IM(C,S,LEVEL,WNAME)
% 
%   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%   !!! Funkce slouzi pouze pro ukazku rozlozeni koeficientu       !!!
%   !!! waveletove transformace. Pri vypoctech dochazi v nekterych !!!
%   !!! pripadech k orezani okraju jednotlivych keoficientu a tedy !!!
%   !!! PIC neobsahuje vsechny koeficienty.                        !!!
%   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
%
%   Priklad zadavani funkce:
%   pic = wave2im(C,S,level,wname);

%% Urceni vhodnych rozmeru jednotlivych urovni
SOld = S; % zalohovani rozmeru koeficientu jednotlivych urovni
len = length(S)-2;
%%%%%%%%%%%%%%%%%%%%% Sirka a vyska keoficientu %%%%%%%%%%%%%%%%%%%%%
%=========== Urceni pouzitelnych hodnot pro nove rozmery ===========%
for l = 1:2
    u = 1;
    while u ~= 0
        u = mod(S(end-1,l),2^(len-1));
        S(end-1,l) = S(end-1,l) -1;
    end
    S(end-1,l) = S(end-1,l) +1;
%=================== Ulozeni novych rozmeru do S ===================%
    for i = 1:len-1
        S(end-1-i,l) = S(end-1,l)/(2^(i)); 
    end
    S(1,l) = S(2,l);
end
%===================================================================%
%% Urceni keoficientu a jejich pripadne omezeni na jednotlivych urovnich
A{level}{1} = appcoef2(C,SOld,wname,level);
A{level}{1} = A{level}{1}/max(max(A{level}{1}));
if S(1,1) ~= SOld(1,1)
    A{level}{1} = A{level}{1}(end-S(1,1):end-1,end-S(1,2):end-1);
end
%============================ Oramovani ============================%
A{level}{1}(1,1:end)    = ones;
A{level}{1}(1:end,1)    = ones;
A{level}{1}(end,1:end)  = ones;
A{level}{1}(1:end,end)  = ones;
%===================================================================%
k = 2;
for i = level:-1:1
    [A{i}{2},A{i}{3},A{i}{4}] = detcoef2('all',C,SOld,i);
    for r = 2:4
        A{i}{r} = (A{i}{r}/max(max(A{i}{r})));
        if S(k,1) ~= SOld(k,1)
            A{i}{r} = A{i}{r}(end-S(k,1):end-1,end-S(k,2):end-1);
        end
%============================ Oramovani ============================%        
        A{i}{r}(1,1:end)    = ones;
        A{i}{r}(1:end,1)    = ones;
        A{i}{r}(end,1:end)  = ones;
        A{i}{r}(1:end,end)  = ones;
%===================================================================%
    end
    pic = [A{i}{1} A{i}{2};A{i}{3} A{i}{4} ]; % Slozeni dilcich matic
    k = k+1;
    if i>1
    A{i-1}{1} = pic;
    end
end
pic(isnan(pic)) = 0 ; % Doplneni nulami kde jsou NaN/po omezeni koef.