%COMP 256 Assignment 3
%Adrian Ilie

function res=em(sigma,inliers);

%initialize
data=datagen(sigma,inliers);
extdata=[data;ones(1,100)];
line=ransac(data,sigma, inliers);
line=hough(data,0.01,180,200);
delta=zeros(1,100);
k=power(2,14);%infinity
if sigma==0
    ct=-1e100;
else
    ct=-1/(2*sigma*sigma);
end
lambda=0.5;% in the middle
kn=0.1;
d=inliers*50/100;

c=0;
prevline=[10;10;10];
dist=1e10;
while (c<k)&(dist>0.001)
    %assign points to line or noise (E)
    for i=1:100
        dot=line'*extdata(:,i);
        dot2=dot*dot;
        denom=exp(ct*dot2)*lambda;
        delta(i)=denom/(denom+exp(-kn*(1-lambda)));
    end
    
    dist=line-prevline;
    dist=dist'*dist;
    prevline=line;
    lambda=sum(delta)/100;
    
    %refit the line (M)
    line=linefit2(data,delta);
    
    c=c+1;%next interation
end

if c<k
    figure(1);
    hold on;
    drawline2(line(1),line(2),line(3),'-b');
end

