/*
**  Usage:
**      direction = intercept_course(origin, target, velocity);
**
**  Arguments:
**      origin       an object with position (x,y)
**      target       an object with position (x,y) and speed (speed,hspeed,vspeed)
**      velocity     the speed of the projectile
**
**  Returns:
**      direction    direction to fire in degrees
**                   or (-1) if no solution found
**
**  copyright (c) 2006, John Leffingwell
**  www.planetxot.com
*/

var origin,target,velocity,dir;
origin = argument0;
target = argument1;
velocity = argument2;
dir = -1;
if (velocity == target.speed) velocity *= 1.0001;
var x0,y0,z0,x1,y1,z1,a,b,c,d,e,f,t,t0,t1,xi,yi;
x0 = (target).x - (origin).x;
y0 = (target).y - (origin).y;
z0 = 0;
x1 = (target).hspeed;
y1 = (target).vspeed;
z1 = velocity;
a = (x1*x1 + y1*y1 - z1*z1);
if (a != 0) {
    b = 2 * (x0*x1 + y0*y1);
    c = (x0*x0 + y0*y0);
    d = (b*b - 4*a*c);
    if (d >= 0) {
        e = sqrt(d);
        f = (2*a);
        t0 = (-b + e)/f;
        t1 = (-b - e)/f;
        if ((t0 > 0) && (t1 > 0)) {
            t = min(t0,t1);
        }else{
            t = max(0,t0,t1);
        }
        if (t > 0) {
            xi = (target).x + t * (target).hspeed;
            yi = (target).y + t * (target).vspeed;
            dir = point_direction((origin).x,(origin).y,xi,yi);
        }
    }
}
return dir;