function [pos score] = stitch( image1, image2 )

[h1 w1] = size(image1);
[h2 w2] = size(image2);

m1 = mean(mean(image1));
m2 = mean(mean(image2));

h = max(h1, h2);
w = max(w1, w2);

% Pad with mean. (No padding seemed to work fine).
I1 = ones(h*1, w*1) * m1;
I2 = ones(h*1, w*1) * m2;

% Pad with rand.
%I1 = rand(h*1.5, w*1.5);
%I2 = rand(h*1.5, w*1.5);

I1(1:h1, 1:w1) = image1(:,:);
I2(1:h2, 1:w2) = image2(:,:);

% Get the fft position.
[y x] = mosaic(I1, I2);

[height1 width1] = size(I1);
[height2 width2] = size(I2);

% Check the 4 possible orientations
c1 = corr2(I2(1:y, 1:x), I1(height1-y+1:height1, width1-x+1:width1));
c2 = corr2(I2(1:y, x:width2), I1(height1-y+1:height1, 1:width1-x+1));
c3 = corr2(I2(y:height2, 1:x), I1(1:height1-y+1, width1-x+1:width1));
c4 = corr2(I2(y:height2, x:width2), I1(1:height1-y+1, 1:width1-x+1));

y = y-1;
x = x-1;

% Given the best orientation, create a stitched image.
if ( c1 >= c2 && c1 >= c3 && c1 >= c4 )
    pos = [height2-y width2-x];
    score = c1;
elseif ( c2 >= c3 && c2 >= c4 )
    pos = [height2-y -x];
    score = c2;
elseif ( c3 >= c4 )
    pos = [-y width2-x];
    score = c3;
else
    pos = [-y -x];
    score = c4;
end

end

