function [DecCode, Maska] = DecodeGrayCode(ImageRef, Image)
% VSTUP:
% ImageRef - referencni snimky
% Image - snimky s gray kodovanim
% VYSTUP:
% DecCode - dekodovany obraz gray kodu
% Mask - maska vyznacujici zajmovou oblast


% Inicializace pameti
[height, width] = size(Image(:,:,1));
GrayCode = zeros(height, width, 8);
DecCode = zeros(height, width);
BinCode = zeros(height, width, 8);
Mask = ones(height, width,8);
MaskRef = ones(height, width,8);
Maska = ones(height, width);

% vytvoreni masky
MaskRef = ImageRef(:,:,2)-ImageRef(:,:,1);
Prah = 0.3;
Maska(MaskRef>Prah) = 1;
Maska(MaskRef<Prah) = 0;


cnt = 1;
% Klasifikace pixelu
for i = 1:2:16
    for k = 1:height
        for l = 1:width
            % referencni urovne
            Ih = Image(k,l,1);
            Il = Image(k,l,2);
            
            % vypocet prahu
            prah = (Ih+Il)/2;
            %rozdil = Ih-Il;
            %odchylka = 0.2;
            % pixel z gray a inverzniho gray kodu
            Ik = Image(k,l,i);
            Ikk = Image(k,l,i+1);
            %rozdil = abs(Ikk-Ik);
            % prahovani a klasifikace pixelu
            %if rozdil > 0.4
                if Ik > prah  && Ikk < prah 
                    GrayCode(k,l,cnt) = 1;
                elseif Ik < prah && Ikk > prah
                    GrayCode(k,l,cnt) = 0;
                else
                    Mask(k,l,cnt) = 0;
                end
        end
    end
    cnt = cnt+1;
end

%Maska = Mask(:,:,1);

% GRAYCODE -> BINCODE prevod z graykodu do binarniho kodu
BinCode(:,:,1) = GrayCode(:,:,1);
for i = 2:8
    x = xor(BinCode(:,:,i-1),GrayCode(:,:,i));
    BinCode(:,:,i) = x;
end

% BINCODE ->DECCODE prevod z binarniho kodu do dekadickeho
DecCode = BinCode(:,:,8)*1 + BinCode(:,:,7)*2 + BinCode(:,:,6)*4 ...
    + BinCode(:,:,5)*8 + BinCode(:,:,4)*16 + BinCode(:,:,3)*32 ...
    + BinCode(:,:,2)*64 + BinCode(:,:,1)*128;
