function module(v){
    return Math.sqrt(v[0] * v[0] + v[1] * v[1])
}

Point.prototype = new Array
Point.prototype.constructor = Point
function Point(x, y) {
    if (x instanceof Array){
        this[0] = x[0]
        this[1] = x[1]
    }
    else {
        this[0] = x
        this[1] = y
    }
}

Point.orientation = function(p1, p2, p3) {
    /* > 0 : Anticlockwise
     * = 0 : Collinear
     * < 0 : Clockwise
     */

    return (p3[1] - p2[1]) * (p2[0] - p1[0]) - (p2[1] - p1[1]) * (p3[0] - p2[0])
}

Point.add = function (a,b) {
    return new Point(a[0] + b[0], a[1] + b[1] )
}

Point.prototype.add = function (b) {
    return Point.add(this, b )
}

Point.subs = function (a,b) {
    return new Point(a[0] - b[0], a[1] - b[1] )
}

Point.prototype.subs = function (b) {
    return Point.subs(this, b )
}

Point.mul = function(k, v) {
    if (typeof(k) == "number" || k instanceof Number)
        return new Point(k * v[0], k * v[1])
}



function Segment(a, b) {
    if (a instanceof Point)
        this.org = a
    else
        this.org = new Point(a)
    if (b instanceof Point)
        this.end = b
    else
        this.end = new Point(b)

    this.dir = Vector.subs(b, a)
}

/*
See:
https://www.geeksforgeeks.org/orientation-3-ordered-points/
https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
 */
Segment.prototype.eval = function(t) {
    return Vector.add( this.org, Vector.mul( t, this.dir ))
}

/* Can you reach the line that passes through b from the origin of a forward ?*/
Segment.intersects = function (a, b) {
    var o1 = Point.orientation( a.org, a.end, b.org )
    var o2 = Point.orientation( a.org, a.end, b.end )
    var o3 = Point.orientation( b.org, b.end, a.org )
    var o4 = Point.orientation( b.org, b.end, a.end )

    return (o1 * o2 < 0 && o3 * o4 < 0) || o1*o2*o3*04 == 0
}

Segment.prototype.intersects = function (b) {
    return Segment.intersects(this, b)
}

/* Does the lines that pass through segment a and b intersect ? Where?*/
Segment.intersection = function (a, b) {

    var k = a.dir[0] * b.dir[1] - a.dir[1] * b.dir[0]
    k = 1 / k
    var it = [ [b.org[0] - a.org[0]],
               [b.org[1] - a.org[1]]
             ]
    var coef = [  k * ( b.dir[1] * it[0] - b.dir[0] * it[1] ),
                 -k * (-a.dir[1] * it[0] + a.dir[0] * it[1] )
               ]

    return coef
}

Segment.prototype.intersect = function (b) {
    var d = Segment.intersection(this, b)[0]
    var pos = Vector.mul( d, this.dir )
    return (new Point(this.org[0], this.org[1])).add( pos )
}
