
function ans = mergeImages(A, B, transform)

% Merge images A and B given transformation [tx, ty, theta].
% Return merged image ans.
%
% A and B can be either color or grayscale images.  Returns a
% color or grayscale image appropriately.  The result array is
% of type double, so you may need to divide it by 255 before
% using imshow() with it.

A = double(A);
B = double(B);

[C, xbox1, ybox1] = imtransform(B, getTransform(B, transform));
mask = imtransform(ones(size(B)), getTransform(B, transform));

xbox1 = floor(xbox1);
ybox1 = floor(ybox1);
xbox1(2) = xbox1(1) + size(C, 2) - 1;
ybox1(2) = ybox1(1) + size(C, 1) - 1;

xbox2 = [1 size(A, 2)];
ybox2 = [1 size(A, 1)];
xbox = [min(xbox1(1), xbox2(1)) max(xbox1(2), xbox2(2))];
ybox = [min(ybox1(1), ybox2(1)) max(ybox1(2), ybox2(2))];

d1 = [ybox1(1)-ybox(1) xbox1(1)-xbox(1)];
d2 = [ybox2(1)-ybox(1) xbox2(1)-xbox(1)];

ans = zeros(ybox(2)-ybox(1)+1, xbox(2)-xbox(1)+1, size(C,3));
ans(d1(1)+1:d1(1)+size(C,1), d1(2)+1:d1(2)+size(C,2),:) = C;
ans(d2(1)+1:d2(1)+size(A,1), d2(2)+1:d2(2)+size(A,2),:) = A;

% Remove black border due to antialiasing with black pixels
C = (C./(mask+0.001));
D = ans(d1(1)+1:d1(1)+size(C,1), d1(2)+1:d1(2)+size(C,2),:);

% Average the two images where they overlap
ans(d1(1)+1:d1(1)+size(C,1), d1(2)+1:d1(2)+size(C,2),:) = D + ((C-D).*mask)*0.5;
