function [CHECK,adds]=wrapper_fast(avi_name,block_size,search_size)
%function [CHECK,adds]=wrapper_fast(avi_name,block_size,search_size)
%This function takes as input the avi file upon which the "Winner Update Fast SAD
%Matching Algorithm is to be implemented.
%
%avi_name: string of the name of the avi file sequence
%block_size: the size of the block (must be power of 2) that is to be matched across frames
%search_size: number of pixels in either up/down or left/right from the original block location
%to be searched

%The first frame is an anchor frame.  The next 14 frames match the blocks from the first frame.


%adds: number of integer adds performed
%CHECK: locations of blocks

%check to see that the block size is valid:
if round(log2(block_size))~=log2(block_size)
    error('Block Size must be power of 2')
end
%Open and manipulate the data of the avi sequence:
Length=aviinfo(avi_name);
num_frames=Length.NumFrames;
for i=1:num_frames
    temp=aviread(avi_name,i);
    temp=temp.cdata;
    temp=rgb2gray(temp) ;
    movie(1:Length.Height,1:Length.Width,i)=uint16(temp);
end
%Define how often (frames) to re_initialize the blocks
new_blocks=15;
cols=Length.Width;
rows=Length.Height;
row_start=log2(block_size)+2;
row_end=rows-block_size-log2(block_size);
col_start=log2(block_size)+2;
col_end=cols-block_size-log2(block_size);

%adds keeps track of the number of integer adds needed for the method
adds=0;


%Go through each frame and perform either the extraction of anchor frame blocks or 
%the block matching.
for i=1:Length.NumFrames-1
disp(i)

    if mod(i,new_blocks)==1
        count=1;
        for I=row_start:block_size:row_end
            for J=col_start:block_size:col_end
                initial_locations(count,:)=[I J];
                count=count+1;
            end
        end
        locations=initial_locations;
        CHECK(:,:,i)=locations;
        
        count=count-1;
        template=bsp(movie(:,:,i),block_size);
        [R,C,D]=size(template);
        adds=adds+4*R*C*D;
    else
        BSP=bsp(movie(:,:,i),block_size);
        [R,C,D]=size(BSP);
        adds=adds+4*R*C*D;
        for I=1:count
            row_template=initial_locations(I,1);
            col_template=initial_locations(I,2);
            %The fast_SAD function peforms the matching
            [row_out,col_out,SAD,adds]=fast_SAD(BSP,template(row_template:row_template+block_size-1,col_template:col_template+block_size-1,:),locations(I,1),locations(I,2),search_size,adds);
            locations(I,:)=[row_out,col_out];
            CHECK(:,:,i)=locations;
        end
    end

end
