function [ u, v ] = get_motion_vector( MB_in, m, n, ref, MB_size, search_width )
% returns the indices of best maching MB on ref to MB_in
%
% MB_in: MB to estimate
% n,m: position of MB_in (in MB coordinates, not pixel (!))
% ref: the reference picture (! - not MB)
% MB_size: macro block (MB) size in pixels (can be different for luma and chroma!)
% search_width: number of pixels to look for MB movement 

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

[i,j] = meshgrid((m-1)*MB_size+1-search_width:m*MB_size+search_width,(n-1)*MB_size+1-search_width:n*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(:));
[M,N] = ind2sub(size(cost_fun),ind);
%[N,M] = ind2sub(size(cost_fun),ind); % én fordítottam meg

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

end

