% *****************************************************************
% Preskladani obrazu podle chaoticke mapy
% Stagl Lubos
%
% obraz = puvodni obraz
% B = velikost blokove jednotky
% s = chaoticka mapa podle ktere budeme preskladavat
% kolikrat_rotovat = nazev vypovida za vse....
% *****************************************************************

function [obraz_new, chaos] = chaoticky_obraz(obraz,B,s,kolikrat_rotovat)

[m,n]=size(obraz);

obraz_new = zeros(size(obraz));

mat = struct('obr',{zeros(B)},'label',{});
chaos = struct('obr',{zeros(B)},'label',{});

% ***********************************************************************
% pro bloky NxN, rozdeleni do bloku s labelem

cnt = 0;
x_krat = m/B;
y_krat = n/B;

    for j=0:(x_krat-1)
        for k=0:(y_krat-1)
             cnt = cnt+1;
             mat{cnt}.obr = obraz(j*B+1:j*B+B,k*B+1:k*B+B);
             mat{cnt}.label = cnt;
        end 
    end

% *******************************************************************
% preskladavani podle chaoticke mapy

for i=1:kolikrat_rotovat
    cnt = 1;  
        for j=0:(x_krat-1)
            for k=0:(y_krat-1)
                index = find(s==cnt);
                chaos{cnt}.obr = mat{index}.obr;
                chaos{cnt}.label = index;                  % kde se nachazelo cislo pro prehozeni
                cnt = cnt+1;                               % vyhledavani cisel 0.1.2.3...
            end
        end
         mat = chaos;
end

cnt = 0;
    for j=0:(x_krat-1)
        for k=0:(y_krat-1)
             cnt = cnt+1;
             obraz_new(j*B+1:j*B+B,k*B+1:k*B+B) = mat{cnt}.obr;
        end 
    end
    
% figure(254)
% colormap('Gray')
% imagesc(obraz_new)
% title(['Preskladany obraz - ', num2str(kolikrat_rotovat), ' krat']);

end
