%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Affine Parameter Calculation
% ----------------------------
%  AUTHOR: Maher Khoury
%    DATE: March 1, 1999
% PURPOSE:
%         Calculates affine motion parameters
%
% Notes on called subroutines:
%   -warp.m warps frame2 back onto frame1 using the calculated parameters
%   -grad.m calculates the image spatio-temporal gradients
%   -Parametric.m calculates the values of the parameters
%
% Variables:
%   -pyrIter        = level of the pyramid
%   -step           = sampling step
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function k = affine(image1,image2);

%% Initialize values of k to be zero %%
k(1:4) = 0;

%%%%% Hierarchical loop %%%%%
for pyrIter=2:-1:0,
  step=2.^pyrIter;

  %% Double the value of the transitional parameters %%
  k = [k(1) k(2) 2.*k(3) 2.*k(4)];

  im1 = corrDn(image1, step);
  im2 = corrDn(image2, step);

  for l=1:3
    %%% Motion compensate frame 2 %%%
    warped = warp(im2,k);

    %%% Get image gradients %%%
    [Ix Iy It] = grad(im1,warped);

    %%% Find residual k's %%%
    resid_k = Parametric(Ix,Iy,It);

    %%% Update the k values %%%
    k = k + resid_k;
  end
end