function NCcorr = detectcorr(template_name, reference_name)

% Read template and reference images as DOUBLE arrays T and R 
%   respectively, then convert to GRAYSCALE
%   e.g. template_name = 'waldo.jpg', reference_name = 'whereswaldo.jpg'
R = imread(reference_name);
R = rgb2gray(im2double(R));
T = imread(template_name);
T = rgb2gray(im2double(T));
Tsize = size(T);

% Compute the correlation
Ccorr = xcorr2(R,T);

% Find the row and col index of max. corr.
fprintf('Corr matrix size: %d \n', size(Ccorr));
[maxval, maxidx] = max(Ccorr(:));
[r, c] = ind2sub(size(Ccorr), maxidx);

% Draw a rectangle of size Tsize around the image region best
% matching the template. 
figure(101); clf;
subplot(121); imshow(R); hold on
rectangle(  'Position',[c-Tsize(2) r-Tsize(1) Tsize(2) Tsize(1)], ...
            'EdgeColor','r','LineWidth',2);
title('Detection by Correlation')


NCcorr = ...
% PLEASE FILL IN THE ABOVE LINE, TO COMPUTE THE *NORMALIZED*
% CORRELATION, AS DESCRIBED IN THE PROBLEM SPECIFICATION. 
%
% PLEASE IMPLEMENT THIS USING CALLS TO xcorr2 OR conv2 AND ELEMENTARY
% OPERATIONS (i.e., please don't just call a library function that computes
% the NCC). THANKS!

% Find the row and col index of max. normalized correlation
fprintf('Corr matrix size: %d \n', size(NCcorr));
[maxval, maxidx] = max(NCcorr(:));
[r, c] = ind2sub(size(NCcorr), maxidx);

% Draw a rectangle of size Tsize around the image region best
% matching the template. 
subplot(122); imshow(R); hold on
rectangle(  'Position',[c-Tsize(2) r-Tsize(1) Tsize(2) Tsize(1)], ...
            'EdgeColor','r','LineWidth',2);
title('Detection by Normalized Correlation')

end