function [F] = computeF_7point_ransac(which_seven)
%Joshua Stough
%COMP 290-89, Pollefeys
%Assignment 2, Computing F
%Returns the fundamental matrix F, computed using the 
%7 correspondences (columns of corr) specified by the
%7-tuple which_seven.
%If there are 3 real solutions for F, the returned F
%has three dimensions (each slice is another solution).

%%%%%%
%THE ONLY DIFFERENCE BETWEEN COMPUTEF_7POINT AND '_RANSAC
%IS THAT CORR IS GLOBAL IN THIS FUNCTION, TO MAYBE SAVE 
%COPYING.
%%%%%%NOT TRUE ANYMORE!!!

global corr

s = size(corr);
%if (nargin < 2) which_seven = round(1 + (s(2)-1)*rand(1,7)); end

%Build A as in the eight point case, unnormalized.
x = corr(1:2,which_seven);
xp = corr(3:4,which_seven);

%So, x and xp are corresponding points.


%Now, build A.
A = zeros(7,9);
%build each column.
A(:,1) = (xp(1,:).*x(1,:))';
A(:,2) = (xp(1,:).*x(2,:))';
A(:,3) = xp(1,:)';
A(:,4) = (xp(2,:).*x(1,:))';
A(:,5) = (xp(2,:).*x(2,:))';
A(:,6) = xp(2,:)';
A(:,7) = x(1,:)';
A(:,8) = x(2,:)';
A(:,9) = ones(7,1);

%A is now built.  Find the constrained best 
%solution for F.
[U,S,V] = svd(A);

%The last two columns of V are the basis of
%the null space.
f1 = [V(1:3,8)'; V(4:6,8)'; V(7:9,8)'];
f2 = [V(1:3,9)'; V(4:6,9)'; V(7:9,9)'];

syms lambda
%solve det(f1 + lambda*f2) = 0.
S = det(lambda*f1 + (1-lambda)*f2);
sols = solve(S);

sols_r = real(double(real(sols)));
sols_i = double(abs(imag(sols)));
good_sols = sols_i < 1e-20;
%solutions where the imaginary part is close 
%to zero.
k = find(good_sols);

if (nnz(good_sols) == 2)
    disp('Unexpected two solutions found.')
end

F = zeros(3,3,3);
c = 0;
n = size(k);
for i = 1:n(1)
    c = c + 1;
    F(:,:,c) = sols_r(k(i))*f1 + (1-sols_r(k(i)))*f2;
    %F = TP'*F(:,:,c)*T;
end

if abs(det(f1)) < 1e-10
    c = c + 1;
    F(:,:,c) = f1;
    %F = TP'*F(:,:,c)*T;
end

for i = (c+1):3
    F(:,:,i) = eye(3);
end
