%COMP 256 Assignment 2
%Adrian Ilie

function newim = imgwarp(im, warp);
%warps an image using linear interpolation

[h,w,d] = size(im);
warp=double(warp);

%bounding box
y = warp*[[1;1;1], [1;h;1], [w;h;1] [w;1;1]];
y(1,:) = y(1,:)./y(3,:);
y(2,:) = y(2,:)./y(3,:);
bbox = [ceil(min(y(1,:)));ceil(max(y(1,:)));ceil(min(y(2,:)));ceil(max(y(2,:)));];
[x,y] = meshgrid(bbox(1):bbox(2),bbox(3):bbox(4));
a = inv(warp)*[x(:) y(:) ones(prod(size(x)),1)]';
x(:) = a(1,:)./a(3,:);
y(:) = a(2,:)./a(3,:);
im = double(im);
for i=1:d
    newim(:,:,i) = interp2(im(:,:,i),x,y,'linear');
end
newim=uint8(newim);