function [residual] = compute_residual(corr, F)
%Joshua Stough
%COMP 290-89, Pollefeys
%Assignment 2, Computing F

%This function computes the residual error, as 
%described on p. 272, given the point correspondences
%to consider and the fundamental matrix F.

%With so much other code already written for this
%assignment, the below is pretty much a paste, from
%computeF_RANSAC or guided_matching_ZNCC.

s = size(corr);

X = corr(1:2,:);
X(3,:) = ones(1,s(2));
XP = corr(3:4,:);
XP(3,:) = ones(1,s(2));

lx = F*X;
lxp = F'*XP;
%normalize the lines.
lxnorms = sqrt(sum(lx(1:2,:).^2));
lxpnorms = sqrt(sum(lxp(1:2,:).^2));
lxnorms(lxnorms == 0) = 1e-15;
lxpnorms(lxpnorms == 0) = 1e-15;

lx = lx./(ones(3,1)*lxnorms);
lxp = lxp./(ones(3,1)*lxpnorms);

%lx and lxp are the normalized epipolar lines in image2 and image1
%respectively.

residual = sum(sum(lxp.*X).^2 + sum(lx.*XP).^2)/s(2)

