function C = dic_normxcorr2(OPTIMIZE, hwid, icp, T, base, sum_T, denom_T)
%   Copyright 1993-2004 The MathWorks, Inc.
%   $Revision: 1.12.4.6 $  $Date: 2004/10/20 17:54:20 $

%   We normalize the cross correlation to get correlation coefficients using
%   the definition of Haralick and Shapiro, Volume II (p. 317), generalized
%   to two-dimensions.

[m n] = size(T);
mn = m*n;

outsize = size(base.sub_base_fft);

if (OPTIMIZE > 1)
    FT = fft2_cuda(double(rot90(T,2)),outsize(1),outsize(2));
    xcorr_TA = real(ifft2_cuda(FT .* base.sub_base_fft));
else
    FT = fft2(double(rot90(T,2)),outsize(1),outsize(2));
    xcorr_TA = real(ifft2(FT .* base.sub_base_fft));
end

denom = denom_T*base.denom_A;

numerator = (xcorr_TA - base.local_sum_A*sum_T/mn ) / (mn-1);

i_nonzero = base.i_nonzero;

% We know denom_T~=0 from input parsing;
% so denom is only zero where denom_A is zero, and in 
% these locations, C is also zero.
C = zeros(size(numerator));
C(i_nonzero) = numerator(i_nonzero) ./ denom(i_nonzero);
