function Umbral=BIN_ErrorMinimo(histograma)
% unsigned char BIN_ErrorMinimo(unsigned long *histograma);

% Objetivo: Pasar los metodos de umbralizacion de C++ a Matlab con un error
% maximo de +/- 1 pixel 

% Autor: David Lopez Peinado GVA/ELAI/UPM
% Correciones: Carlos Platero
% Fecha: 21/05/03
%
%
minimo=1;
j=zeros(256,1);

for t=1:256,
    p1=0;
    mu1=0;
    for i=1:t,
        p1=p1 + histograma(i);
        mu1=mu1 + i*histograma(i);
    end
    if (p1 ~=0)
        mu1=mu1/p1;
    end
    sigma1=0;
    for i=1:t,
        sigma1=sigma1 + ((i-mu1)*(i-mu1)*histograma(i));
    end
    if (p1 ~=0)
        sigma1=sigma1/p1;
    end
    p2=0;
    mu2=0;
    for i=t+1:256,
        p2=p2 + histograma(i);
        mu2=mu2 + (i*histograma(i));
    end
    if (p2 ~=0)
        mu2=mu2/p2;
    end
    sigma2=0;
    for i=t+1:256,
        sigma2=sigma2 + ((i-mu2)*(i-mu2)*(histograma(i)));
    end
    
    if (p2 ~=0)
        sigma2=sigma2/p2;
    end
        
    if((p1>0) & (p2>0) & (sigma1 >0) & (sigma2 >0))
        j(t)=1+(2*((p1*log(sqrt(sigma1)))+(p2*log(sqrt(sigma2)))))-(2*((p1*log(p1))+(p2*log(p2))));
    elseif (p2==0)
        j(t)=1+(2*(p1*log(sqrt(sigma1))))-(2*(p1*log(p1)));
    elseif (p1==0)
        j(t)=1+2*(p2*log(sqrt(sigma2)))-2*(p2*log(p2));
    else
        j(t)=1;
    end
    
    
    if(j(t) < j(minimo))
        minimo = t;
    end
end
Umbral=minimo-1;