function f = medianovy_filtr(data, r, R)
[m,n] = size(data);
f = size(data);
k = 0;
while true
    for i = 1:m
        for j = 1:n
            % určení hranice okolí
            if i <= r; i_start = 1; i_end = i+r;
            elseif i >= m-r; i_start = i-r; i_end = m;
            else; i_start = i-r; i_end = i+r;
            end
    
            if j <= r; j_start = 1; j_end = j+r;
            elseif j >= n-r; j_start = j-r; j_end = n;
            else; j_start = j-r; j_end = j+r;
            end
            % spočítání mediánu
            window_values = reshape(data(i_start:i_end,j_start:j_end),[],1);
            med = quantile(window_values(:),0.5);
            % kritérium R
            if data(i,j)/med > R
                f(i,j) = med;
                k = k + 1;
            else
                f(i,j) = data(i,j);
            end
        end
    end
    if k/m/n*100 < 0.5
        return
    elseif k/m/n*100 > 1
        R = R + 0.01;
        k = 0;
    else
        R = R + 0.005;
        k = 0;
    end
end


end