function V = FindV(Cblock, gridloc, NX, sr, lamda);
% This function finds a matching block in the next frame NX 
% to the block Cblock in its vicinity -sr/+sr around its original
% location 'gridloc'
% The output is 'bestV' the corrsponding translation

bs = size(Cblock); hbs = (bs(1)-1)/2;

bestV   = [0,0]; 
bestSSD = inf;

% Search for the translation 'bestV' of the block Cblock witch yields
% the lowest SSD.
SSD = zeros(2*sr+1,2*sr+1);

for r = -sr:sr
    for c = -sr:sr
        
        % Get a block from P cut at the location gridloc + [r,c] 
        loc     = gridloc + [r c];
        NXblock = NX(loc(1)-hbs:loc(1)+hbs, loc(2)-hbs:loc(2)+hbs);
        
        % Calc figure of merit SSD
        SSD(r+sr+1,c+sr+1) = sum(sum( abs(Cblock - NXblock).^2 )) + lamda*(r^2 + c^2);
        %lamda+mat = 
        
        % Calc figure of merit SSD
        %currentSSD = sum(sum(abs(Cblock - NXblock)));
        % Store global minimum
        %if currentSSD < bestSSD
        %    bestSSD = currentSSD;
        %    bestV = [r,c];
        %end
        
    end 
end

%NXblockC = NX(gridloc(1)-hbs-1:gridloc(1)+hbs+1, gridloc(2)-hbs-1:gridloc(2)+hbs+1);
%Cblock, NXblockC,
%SSD

% Search for the Vector
% How? Which one is the right one if there are several which yield the same global minimum?
% 1) go circular

point = [];
[sizex sizey] = size(SSD); midx = (sizex-1)/2+1; midy = (sizey-1)/2+1;
%midx = hbs+1; midy = hbs+1;

[indexx indexy] = find(SSD == min(SSD(:)));
index = [indexx indexy]; normindex = index - midx*ones(size(index));

dist = [];
%[sizeindx sizeindy] = size(indexx);
for s = 1:size(indexx)
    dist(s) = sqrt(normindex(s,1)^2 + normindex(s,2)^2);
end

bestindrow = find(dist == min(dist(:)));
point = index(bestindrow(1),:);

V = -(point-[midx, midy]);        
        