function [lvl T] = prah_kittler2(obr)

% obr = 1 - obr;
h = imhist(obr);
p = h/sum(h);
% imwrite(obr,'vyrezx.bmp'); %odstranit
maximum = max(max(p));
poz_max = find(p==maximum);
poz_max = poz_max(1);
poz_min1 = 1;
poz_min2 = 255;
for i = poz_max:255
    if p(i+1)==0 && p(i)~=0
        poz_min2 = i;
        i=256;
    end
end
i = 0;
while i ~=poz_max-2
    i = i + 1;
    if p(poz_max-i-1)==0 && p(poz_max-i)~=0
        poz_min1 = poz_max-i;
        i=poz_max-2;
    end
end
p2 = p;
p = p(poz_min1:poz_min2);
h2 = h(poz_min1:poz_min2);
% figure(23)
% plot (p)

if length(p) == 1
    lvl = 1;
    Topt = 1;
    T =1;
else
    for i = 1:length(p)
        P1 = sum(p(1:i));
        P2 = sum(p(i+1:end));

        u1 = sum([1:i].*p(1:i)')/P1;
        sigma_1 = sqrt(sum((([1:i]-u1).^2) .*p(1:i)')/P1);

        u2 = sum([i+1:length(p)].*p(i+1:end)')/P2;
        sigma_2 = sqrt(sum(([i+1:length(p)]-u2).^2 .* p(i+1:end)')/P2);

    %     T(i) = P * log(sf) + (1-P) * log(sb) - P*log(P) - (1-P)* log(1-P);
        T(i) = 1 + 2*(P1*log(sigma_1)+P2*log(sigma_2))-2*(P1*log(P1)+P2*log(P2));
    end
    if length(T(T>0))>0
        Topt = (find(T == min(T(T>0))));
        lvl = (poz_min1+Topt(1))/256;
    else
        lvl = 1;
    end
end