function [ u, v ] = get_motion_vector( MB_in, n, m, ref, MB_size, search_width )


ref_dummy = [ref 255*ones(size(ref,1),1);  255*ones(1, size(ref,2)+1)];

[i,j] = meshgrid((n-1)*MB_size+1-search_width:n*MB_size+search_width,(m-1)*MB_size+1-search_width:m*MB_size+search_width);
i( i <= 0 ) = size(ref_dummy,1);  i( i > size(ref,1) ) = size(ref_dummy,1);
j( j <= 0 ) = size(ref_dummy,2);  j( j > size(ref,2) ) = size(ref_dummy,2);

search_area = reshape ( ref_dummy( sub2ind( size(ref_dummy),i(:),j(:)  ) ) , MB_size+2*search_width, MB_size+2*search_width)';

shift_par =  (size(search_area)-size(MB_in))+1;
cost_fun = zeros(shift_par);
for k = 1 : shift_par(1)
    for l = 1 : shift_par(2)
        cost_fun(k,l) = sum( sum(  (   MB_in - search_area( k:k+MB_size-1, l:l+MB_size-1 )    ).^2  ) );
    end
end
[~,ind] = min(cost_fun(:));
[N,M] = ind2sub(size(cost_fun),ind);

u = M - search_width - 1;
v = N - search_width - 1;

end

