%------------------------------------------------------------------------
%
% Computer Vision (CS766) - Project 2: Panoramic Mosaic Stitching
% Professor Li Zhang
%
% Author: Brandon M. Smith
% Due October 10, 2007
%
% Description:
%      Calculate the final homography that will place img2 correctly
%      over img1. k is the number of random homographies to test
%      before declaring a 'best' homography, H. t is the threshold
%      distance value in pixels for inliers.
%
%------------------------------------------------------------------------

function [H] = calc_final_homography(img1, img2, k, t)

[num, point_pairs] = match(img1, img2);

num_pairs = size(point_pairs, 1);

% rand returns a random float between 0 and 1, EXCLUSIVE of 0 and 1.
% ceil(rand * num_pairs) ==> [1, num_pairs] (inclusive)

p = zeros(2,4);
ptick = zeros(2,4);

H = zeros(3,3);
count_max = 0;
for run=1:k
    %disp('run = ');
    %disp(run);
    for i=1:4
        index = ceil(rand * num_pairs);
        %disp('index = ');
        %disp(index);
        x1 = point_pairs(index,1);
        y1 = point_pairs(index,2);
        x2 = point_pairs(index,3);
        y2 = point_pairs(index,4);

        %disp('x y from img1 = ');
        %disp([x1 y1]);
        %disp('x y from img2 = ');
        %disp([x2 y2]);
    
        p(1,i) = x1;
        p(2,i) = y1;
    
        ptick(1,i) = x2;
        ptick(2,i) = y2;
    end

    temp_H = solve_for_homography(p,ptick);

    count = 0;

    for pair=1:num_pairs
        x = point_pairs(pair,1);
        y = point_pairs(pair,2);
        [xtick, ytick] = get_transformed_xy(x,y,temp_H);
        actualX = point_pairs(pair,3);
        actualY = point_pairs(pair,4);
        %disp([xtick ytick actualX actualY]);
        dist_sqrd = (xtick-actualX)*(xtick-actualX) + (ytick-actualY)*(ytick-actualY);
        if( dist_sqrd < t*t )
            count = count + 1;
        end
    end


    %disp('count=');
    %disp(count);
    
    if(count > count_max)
        count_max = count;
        H = temp_H;
        %disp(count_max);
        %disp(H);
    end
end

%disp('point_pairs(100,:)=');
%disp(point_pairs(100,:));
%disp('point_pairs(110,:)=');
%disp(point_pairs(110,:));
%disp('point_pairs(120,:)=');
%disp(point_pairs(120,:));
%disp('point_pairs(130,:)=');
%disp(point_pairs(130,:));
%disp(size(point_pairs));