function myfun

% The following code was written by Anthony Ripa, Henrick Goldwurm, and Zain Abidin
% Cite: Gregory Cordts
% Cite: http://stackoverflow.com/questions/2773606/gaussian-filter-in-matlab
% Cite: http://www.mathworks.com/matlabcentral/answers/28996
% Cite: http://www.mathworks.com/matlabcentral/newsreader/view_thread/57055
% Cite: http://www.mathworks.com/matlabcentral/fileexchange/5457
% Cite: http://stackoverflow.com/questions/6536737/matlab-increase-image-saturation
% Cite: http://www.mathworks.com/help/images/ref/regionprops.html#bqkf8jb
% Cite Tomás Yago

vid =videoinput('winvideo',1);
set(vid,'ReturnedColorSpace','RGB');
triggerconfig(vid,'Manual');
start(vid);
G=fspecial('gaussian',[40 40],8);
pause(5);
a=getsnapshot(vid);
a = normalize(a);
Ag=imfilter(a,G,'same');
z1=0;
y1=0;
z=0;
y=0;
NewDist = 10^5
OldDist = 10^5
result=input('Hit 0 for Chase OR Hit 1 for Run away. ');
for x=1:500
    b=getsnapshot(vid);
    b = normalize(b);
    
    big=max(a-b,b-a);
    
    Cg=imfilter(big,G,'same');
    m=times(double(Cg>.5),double(Cg));
    bin=rgb2gray(m);
    fill=imfill(bin, 'holes');
    label=bwlabel(fill);
    area=bwarea(label);
    cent=regionprops(label,'Centroid');
    b = min(area);
    num = numel(cent);
    for n=1:num
        if n>1
            z1=cent(n-1).Centroid(1);
            y1=cent(n-1).Centroid(2);
        end
        z=cent(n).Centroid(1);
        y=cent(n).Centroid(2);
    end
    new=[label];
    imshow(new);
    hold on
    for k=1:num
        plot(cent(k).Centroid(1),cent(k).Centroid(2), 'ro');
    end
    hold off
    drawnow;
    impixelinfo;
    NewDist = sqrt((z1-z)^2+(y1-y)^2)
    if (NewDist<40)
        break
    end
    csvwrite('orders.txt',NewDist>OldDist)
    if (result)
        csvwrite('orders.txt',NewDist<OldDist)
    end;
    system('NXT++ test\Debug\Final.exe');
    
    OldDist = NewDist
end;
stop(vid);
delete(vid)
clear vid;
end

function outputimage = normalize(inputimage)
inputimage=double(inputimage);
forebright=sum(inputimage(:))/(240 * 320 * 3);
outputimage=inputimage/forebright;
end
