function frames = simulate(img, warp, isShown)
% Created by Yuandong Tian, Oct. 5, 2009
% Email: yuandong@andrew.cmu.edu
% Given (the gradient of) water heights, simulate water distortion according to Eqn. 1

[h, w, nChannel] = size(img);
nFrame = size(warp.Xs, 3);

isShown = exist('isShown', 'var') && isShown;

[X, Y] = meshgrid(1:w, 1:h);
if nChannel == 1
    frames = zeros(h, w, nFrame);
else
    frames = zeros(h, w, nChannel, nFrame);
end;

for i = 1:nFrame
    % 
    Xnew = reshape(X + warp.Xs(:, :, i), h*w, 1);
    Ynew = reshape(Y + warp.Ys(:, :, i), h*w, 1);
    
    valid = (Xnew >= 1 & Xnew <= w & Ynew >= 1 & Ynew <= h);
    
    imgCurr = zeros(h, w, nChannel);
    currFrame = zeros(h*w, 1);
    for k = 1:nChannel
        currFrame(valid) = interp2(img(:, :, k), Xnew(valid), Ynew(valid));
        imgCurr(:, :, k) = reshape(currFrame, h, w);
    end;

    if isShown
        imshow(imgCurr);
        pause(0.01);
    end;
    if nChannel > 1
        frames(:, :, :, i) = imgCurr;
    else
        frames(:, :, i) = imgCurr;
    end;
end;
