//	Vectors.c

#include <math.h>
#include "Vectors2D.h"
#include <BEE.h>			// for BackEnders.h to compile
#include "BackEnders.h"		// for MAX_FLOAT_VAL

//	note these were NOT written for speed.
//	if you'd like them speedy, lemme know - DaveC

vec2	ScalarTimesVec2(double scalar, vec2 *v)
{
	vec2	vector;
	
	vector.dx = v->dx * scalar;
	vector.dy = v->dy * scalar;
	
	return(vector);
}

vec2	SubVec2(vec2 *v1, vec2 *v2)	//	v1 - v2
{
	vec2	vector;
	
	vector.dx = v1->dx - v2->dx;
	vector.dy = v1->dy - v2->dy;
	
	return(vector);
}

double	DotProduct2(vec2 *v1, vec2 *v2)
{
	return(v1->dx * v2->dx + v1->dy * v2->dy);
}

double	Magnitude2(vec2 *vector)
{
	return(sqrt(DotProduct2(vector, vector)));
}

vec2	UnitVec2(vec2 *vector)
{
	return(ScalarTimesVec2(1.0 / Magnitude2(vector), vector));
}


/** PerpDistanceToLine
	
	Returns the distance in pixels.

	Returns MAX_FLOAT_VAL if the hit pt lies off either end.

**/
double
PerpDistanceToLine(Point hit_pt, Point xy1, Point xy2)
{
	double		perp, bDotUnitA;
	vec2		a, b, unitA, c, e;
	
	a.dx = xy2.h - xy1.h;
	a.dy = xy2.v - xy1.v;
	
	b.dx = hit_pt.h - xy1.h;
	b.dy = hit_pt.v - xy1.v;
	
	unitA = UnitVec2(&a);
	
	bDotUnitA = DotProduct2(&b, &unitA);
	
	if (bDotUnitA < 0 || Magnitude2(&b) > Magnitude2(&a)) { 		// off either end
		perp	= MAX_FLOAT_VAL;
	} else {
		c		= ScalarTimesVec2(bDotUnitA, &unitA);
		e		= SubVec2(&b, &c);
		perp	= Magnitude2(&e);
	}

	return perp;
}
