clear
clc
close all
Number =100;

x = 10*rand(1,Number);
y = 10*rand(1,Number);
xc=mean(x);
yc=mean(y);

plot(x,y,'ro');
axis equal;
axis([-2,12, -2,12])
hold on
plot(xc,yc,'ok');
M(1)=getframe;


%pb=[];
p1=findmin(x);
%pb=p1;
xb=x(p1);
yb=y(p1);
x(p1)=[];
y(p1)=[];
x1=x;
y1=y;
x=[xb,x1];
y=[yb,y1];

plot([xc,xb],[yc,yb],'*:k');

M(2)=getframe;
p1=findmax(xb,yb,xc,yc,x,y);
xb=[xb,x(p1)];
yb=[yb,y(p1)];
x(p1)=[];
y(p1)=[];
plot(xb,yb,'*-k');
M(3)=getframe;
Normal=[];
count =3;
while p1~=1
    count = count+1;
p1=findmax(xb(end),yb(end),xb(end-1),yb(end-1),x,y);
xb=[xb,x(p1)];
yb=[yb,y(p1)];
normalEdge = drawDirectionInside(xb(end-2:end),yb(end-2:end));
Normal=[Normal,normalEdge];
plot([xb(end-1),xb(end)],[yb(end-1),yb(end)],'*-r');
plot([xb(end-1),xb(end-1)+normalEdge(1)],[yb(end-1),yb(end-1)+normalEdge(2)],'-');
M(count)=getframe;
x(p1)=[];
y(p1)=[];
end
%plot([xc,xb],[yc,yb],'*-');

normalEdge = drawDirectionInside([xb(end-1:end),xb(2)],[yb(end-1:end),yb(2)]);
Normal=[Normal, normalEdge];
plot([xb(end),xb(end)+normalEdge(1)],[yb(end),yb(end)+normalEdge(2)],'-');
count = count + 1;
M(count)=getframe;
xb(1)=[];
yb(1)=[];

% Now, we try to update

[x_new,y_new] = ginput(1);
plot(x_new,y_new,'o');
for i=1:length(xb)
    value = (x_new-xb(i))*Normal(1,i)+(y_new-yb(i))*Normal(2,i);
    if value<0
        if i==1
            plot([x_new,xb(end)],[y_new,yb(end)],':*');
        else
            plot([x_new,xb(i-1)],[y_new,yb(i-1)],':*');
        end
        count = count + 1;
        M(count)=getframe;
        count1=0;
        while value<0
            if i+count1==length(xb)
            value = (x_new-xb(1))*Normal(1,1)+(y_new-yb(1))*Normal(2,1);
            count1 =  - i+ 1;
            else
            value = (x_new-xb(i+count1+1))*Normal(1,i+count1+1)+(y_new-yb(i+count1+1))*Normal(2,i+count1+1);
            count1 = count1+1;
            end
        end
         if count1+i==1
            plot([x_new,xb(end)],[y_new,yb(end)],':*');
        else
            plot([x_new,xb(i+count1-1)],[y_new,yb(i+count1-1)],':*');
         end
        count = count + 1;
        M(count)=getframe;
    end
end

writegif('convexhull.gif',M,0.1);

% %movie(M,4,3);
%  vidObj = VideoWriter('convexhull_Update.avi');
% 
% set(vidObj,'FrameRate',3);
%     open(vidObj);
%     writeVideo(vidObj,[M,M,M]);
%     close(vidObj);