function xyinput = dic_cpcorr(CORRSIZE, PRECISION, OPTIMIZE, hwid, base, xyinput_in, input)
%   Copyright 1993-2004 The MathWorks, Inc.
%   $Revision: 1.16.4.4 $  $Date: 2004/10/20 17:54:13 $

if any(xyinput_in(:)<0.5) || any(xyinput_in(:,1)>size(input,2)+0.5) || ...
   any(xyinput_in(:,2)>size(input,1)+0.5)
    msg = sprintf('In function %s, Control Points must be in pixel coordinates.',mfilename);
    eid = sprintf('Images:%s:cpPointsMustBeInPixCoord',mfilename);
    error(eid,msg);
end


% get all rectangle coordinates
rects_input = dic_calc_rects(xyinput_in, CORRSIZE, input);

ncp = size(xyinput_in,1);

xyinput = xyinput_in; % initialize adjusted control points matrix

for icp = 1:ncp

    if base(icp).skip
	% baned by base image (Nan, Inf, Near to edge, ...)
	continue
    end
    
    if isequal(rects_input(icp,3:4),[0 0])
        % near edge, unable to adjust
        continue
    end
    
    sub_input = imcrop(input,rects_input(icp,:));

    inputsize = size(sub_input);

    % make sure finite
    if any(~isfinite(sub_input(:))) 
        % NaN or Inf, unable to adjust
        continue
    end

    sum_T = sum(sub_input(:));
    % DS: double is required by 2007+ versions of Matlab for not known reasons
    denom_T = std(double(sub_input(:)));

    % check that template rectangle sub_input has nonzero std
    if denom_T==0
        % zero standard deviation of template image, unable to adjust
        continue
    end

    norm_cross_corr = dic_normxcorr2(OPTIMIZE, hwid, icp, sub_input, base(icp), sum_T, denom_T);

    % get subpixel resolution from cross correlation
    subpixel = true;
    [xpeak, ypeak, amplitude] = findpeak(norm_cross_corr,subpixel);

    % eliminate any poor correlations
    THRESHOLD = 0.5;
    if (amplitude < THRESHOLD) 
        % low correlation, unable to adjust
        continue
    end
    
    % offset found by cross correlation
    corr_offset = [ (xpeak-inputsize(2)-CORRSIZE) (ypeak-inputsize(1)-CORRSIZE) ];


    % eliminate any big changes in control points
    ind = find(abs(corr_offset) > (CORRSIZE-1));
    if ~isempty(ind)
        % peak of norxcorr2 not well constrained, unable to adjust
        continue
    end

    input_fractional_offset = xyinput(icp,:) - round(xyinput(icp,:)*PRECISION)/PRECISION;
    
    % adjust control point
    xyinput(icp,:) = xyinput(icp,:) - input_fractional_offset - corr_offset + base(icp).base_fractional_offset;

end

