% Adapted from A. Efros
% (http://graphics.cs.cmu.edu/courses/15-463/2010_fall/hw/proj1/)

close all;
% name of the input file
imname = '00153v.jpg';

% read in the image
fullim = imread(imname);

% convert to double matrix (might want to do this later on to same memory)
fullim = im2double(fullim);

% compute the height of each part (just 1/3 of total)
height = floor(size(fullim,1)/3);
% separate color channels
B = fullim(1:height,1:end);
G = fullim(height+1:height*2,1:end);
R = fullim(height*2+1:height*3,1:end);

% Align the images
% Functions that might be useful to you for aligning the images include: 
% "circshift", "sum", and "imresize" (for multiscale)
%%%%%aG = align(G,B);
%%%%%aR = align(R,B);

C = normxcorr2(G, B);
[val, linind] = max(C(:));
[i, j] = ind2sub(size(C), linind);
shift = [i-size(G,1) j-size(G,2)];
B = circshift(B, -shift);
figure; imshow(B);

C = normxcorr2(G, R);
[val, linind] = max(C(:));
[i, j] = ind2sub(size(C), linind);
shift = [i-size(G,1) j-size(G,2)];
R = circshift(R, -shift);


im = cat(3, R, G, B);

imshow(im);

% open figure
%% figure(1);

% create a color image (3D array)
% ... use the "cat" command
% show the resulting image
% ... use the "imshow" command
% save result image
%% imwrite(colorim,['result-' imname]);
