function [d_max, point] = get_max_distance(p1, p2, points)
% -------------------------------------------------------------------------
% MSc Project - MSc in Communications and Signal Processing
% Department of Electrical and Electronic Engineering
% Imperial College London, 2011
%
% Supervisor  : Dr Pier Luigi Dragotti
% Contributor : Andriy Gelman
% Author      : Jon Onativia Bravo
%
% File        : get_max_distance.m
% -------------------------------------------------------------------------
% Measure the max distance from points to the line (p1, p2).
%
% [d_max, point] = get_max_distance(p1, p2, points)
%
% INPUT:
%  - p1     : Coordinates of the first point that defines the line (1x2).
%  - p2     : Coordinates of the second point that defines the line (1x2).
%  - points : List of points coordinates (Nx2).
%
% OUTPUT:
%  - d_max  : Maximum distance.
%  - point  : Coordinates of the point that is located at maximum distance.
%

%% Output parameters
d_max = 0;
point = [0, 0];

%% Constants for the computation of the distance
p1_x = p1(1);
p1_y = p1(2);
p2_x = p2(1);
p2_y = p2(2);

A = p2_x - p1_x;
B = p2_y - p1_y;
C = 1 / sqrt(A^2 + B^2);


%% Measure the distance of each point to the line (p1, p2)
num_of_points = size(points, 2);
for i = 1 : num_of_points
    cur_x = points(1,i);
    cur_y = points(2,i);
    
    % Compute current distance
    d = abs(A * (p1_y - cur_y) - (p1_x - cur_x) * B) * C;
    
    % If the current distance is bigger, store it and store the points
    % coordinates
    if d > d_max
        d_max    = d;
        point(1) = cur_x;
        point(2) = cur_y;
    end
end

