function [flag, num_pre_ransac_matches, num_post_ransac_matches, model, matches, definite_inliers] = ...
    SURFPairwiseMatchFeatureSets(frames1, desc1, fileName1, frames2, desc2, fileName2, metric, PLOT_FIGURES)
% [flag, num_pre_ransac_matches, num_post_ransac_matches, model, pre_ransac_matches, post_ransac_matches] = ...
% SURFPairwiseMatchFeatureSets(frames1, desc1, fileName1, frames2, desc2, fileName2, metric, plotFigures)
% Matches two feature sets by ANN, ratio test, and RANSAC.

THRESHOLD = 0.8; 

%write features to file
dlmwrite('data/features1.txt', desc1, 'delimiter', '\t');
dlmwrite('data/features2.txt', desc2, 'delimiter', '\t');

%generate ann_result in O(N^2)
ann_result = zeros(2*size(desc1, 1), 2);
for i = 1:size(desc1, 1)
    dist = sqrt(sum((repmat(desc1(i, :), size(desc2, 1), 1) - desc2).^2, 2));
    [val, idx] = sort(dist);
    %nearest and second-nearest
    ann_result(2*i-1, 1) = idx(1); %idx
    ann_result(2*i-1, 2) = val(1); %dist
    ann_result(2*i, 1) = idx(2); %idx
    ann_result(2*i, 2) = val(2); %dist
end

%calculate matches
idx = ann_result(:,1);
dist = ann_result(:,2);
idx1 = 1:length(desc1); idx2 = idx(1:2:end)';  %both row vectors
dist1 = dist(1:2:end); dist2 = dist(2:2:end);
idx1_match = idx1(find(dist1 < THRESHOLD*dist2));
idx2_match = idx2(find(dist1 < THRESHOLD*dist2));
matches = [idx1_match; idx2_match];

%do ransac on the matches
if strcmp(metric, 'perspective')
    [definite_inliers, flag, model] = PerspectivePairwiseRansac(frames1', frames2', matches);
else
    [definite_inliers, flag, model] = AffinePairwiseRansac(frames1', frames2', matches);
end

disp( sprintf('Number of feature matches pre-ransac %d', size(matches,2)) );
disp( sprintf('Number of feature matches post-ransac %d', size(definite_inliers,2)) );
num_pre_ransac_matches = size(matches, 2);
num_post_ransac_matches = size(definite_inliers, 2);

if (PLOT_FIGURES)
    %pre-ransac output
    grayimage1 = imresize(imreadbw(fileName1), [480 640], 'bicubic', 32);
    grayimage2 = imresize(imreadbw(fileName2), [480 640], 'bicubic', 32);

    plotmatches(grayimage1, grayimage2, frames1', frames2', matches);
    pause(3);

    %post-ransac output
    if (flag ~= -1)
        plotmatches(grayimage1, grayimage2, frames1', frames2', definite_inliers);
        pause(3);
    end

end
