%This runs the entire analysis of the movie.
%Pass it the array of source images.
%Returns a logical image array for both normal and below-mean analysis.
function [fgresults, fg2results] = runAnalysis(input_images)

    %Do some preprocessing to improve the accuracy of the analysis.
    input_images = doFiltering(input_images);
    
    bgimg = computeBackground(input_images);
    
    figure('Name', 'Background image from frame means')
    imshow(bgimg)

    fgresults = sdthreshold(input_images, bgimg, 2);
    figure('Name', 'Foreground pixels - Frame 29')
    imshow(fgresults(:,:,29))
    
    [v, vunder] = countFgPixels(fgresults);
    figure('Name', 'Foreground pixel bar plot')
    bar(v)
    hold on;
    plot(1:size(v,2), repmat(mean(v), 1, size(v,2)))  %Plot the mean on the same bar chart.
    hold off;
    
    %Select only pixels below the mean.
    bg2 = computeBackground(input_images(:,:,find(vunder > 0)));
    fg2results = sdthreshold(input_images, bg2, 2);
    
    figure('Name', 'Background image from below-average pixel count means')
    imshow(bg2)

    figure('Name', 'Foreground pixels - Frame 29, below-mean fg pixels only')
    imshow(fg2results(:,:,29))

    figure('Name', 'Background differences')
    imshow(histeq(abs(bg2 - bgimg)))
end
