/*
 * FXT1 codec
 * Version:  1.0
 *
 * Copyright (C) 2004  Daniel Borca   All Rights Reserved.
 *
 * this is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * this is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Make; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.	
 */


Problem:
~~~~~~~~
having 3 points P1(x1, y1), P2(x2, y2) and P3(x3, y3), we need to find
a point P(x, y) on the P1-P2 line, so that distance form P3 to that P is
minimal.  we shall use the oblong squared distance function:
	d(P1, P2) = (X*(x2 - x1))^ + (Y*(y2 - y1))^

Solution:
~~~~~~~~~
analytical equation of P1-P2 line:
	 x - x1    y - y1
	------- = ------- = t
	x2 - x1   y2 - y1

	or

	x = t * (x2 - x1) + x1
	y = t * (y2 - y1) + y1

	where

	x1 <= x <= x2  ==>  0 <= t <= 1

thus d(P3, P) will be:
	d = (X*(x3 - x))^ + (Y*(y3 - y))^
	  = (X*(x3 - (t * (x2 - x1) + x1)))^ + (Y*(y3 - (t * (x2 - x1) + x1)))^
	  = X^*(x3 - x1)^ + Y^*(y3 - y1)^
	  - 2 * t * (X^*(x3 - x1)*dx + Y^*(y3 - y1)*dy)
	  + t^ * (X^*dx^ + Y^*dy^)

	where dx = (x2 - x1) and dy = (y2 - y1)

given the function f = C + Bt + At^, we can find its extrema by using the
first derivative:
	(f' = 2At + B) = 0 when t = -B / 2A

having that said, d will have a minimum at:
	       X^*(x3 - x1)*dx + Y^*(y3 - y1)*dy
	tmin = ---------------------------------
	                X^*dx^ + Y^*dy^

	                 X^*dx                  Y^*dy        x1*X^*dx + y1*Y^*dy
	     = x3 * --------------- + y3 * --------------- - -------------------
	            X^*dx^ + Y^*dy^        X^*dx^ + Y^*dy^     X^*dx^ + Y^*dy^

we can note:
	              X^*dx            Y^*dy
	ivec = ( ---------------, --------------- )
	         X^*dx^ + Y^*dy^  X^*dx^ + Y^*dy^

	         x1*X^*dx + y1*Y^*dy
	base = - -------------------
	           X^*dx^ + Y^*dy^

	tmin = ivecx * x3 + ivecy * y3 + base

discretizing the line with N equidistant points, we scale:
	          N * X^*dx        N * Y^*dy
	iv = ( ---------------, --------------- )
	       X^*dx^ + Y^*dy^  X^*dx^ + Y^*dy^

	          x1*X^*dx + y1*Y^*dy
	b = - N * -------------------
	            X^*dx^ + Y^*dy^

	n = (iv . P3) + b

	Note1: this formula stands for n-component vector
	Note2: (int)n = {0, 1, ... N}, because 0 <= t <= 1
	Note3: when X=Y=1, d is squared euclidean distance!
