% Input : Avi filename, option = 1 for histogram and 0 for pixel 
% Size of the sliding window size - win_size
% usuage motion_detect('test1.avi',1,5);

function [] = motion_detect(File, option, win_size);

close all;

movie_read = aviread(File);

noofframes = size(movie_read,2)

for i = 1:1:noofframes
    directory = 'framebmps\frame';
    filename = strcat(directory,num2str(i),'.jpg');
    
    imwrite(movie_read(i).cdata,filename,'jpg');
    
end


filename1 = strcat(directory,num2str(1),'.jpg');

for i = 2:1:noofframes
    
    filename2 = strcat(directory,num2str(i),'.jpg');
    
    if option == 1
        
        dis_sim(i-1, 1) = histo(filename1, filename2);
        
    else
        
        dis_sim(i-1, 1) = pixel(filename1, filename2);
        
    end
    
    filename1 = filename2;
end

size(dis_sim)

%plot(dis_sim)

k = 1;
for i = 1:1:(noofframes - (2*win_size) - 1)
    window = dis_sim([i:(i+2*win_size)],1);
    yes_no =  threshold(window, 5);
    
    if yes_no == 1
        motion(i,:) = dis_sim(((i + 2*win_size) - win_size),1);
    end
end

motion

k = 1;
for i = 1:1:size(dis_sim)
    mat = find(motion == dis_sim(i,1));
    if isempty(mat) == 0
        change(k,2) = dis_sim(i,1);
        change(k,1) = i;
        k = k  + 1;
    end
end


figure
plot(dis_sim(:,1))
hold on
plot(change(:,1),change(:,2),'*')
if option == 1
    TITLE('Motion detection using Histogram')
else
    TITLE('Motion detection using Pixel')
end

change(:,1)
pause
close all

for j = 1:size(change(:,1),1)
    figure;imshow(strcat(directory,num2str(change(j,1)-1),'.jpg'));
    figure;imshow(strcat(directory,num2str(change(j,1)),'.jpg'));
    figure;imshow(strcat(directory,num2str(change(j,1)+1),'.jpg'));
    pause
    close all
end