package routing

import (
	

	
)

func segmentIntersectsBox(,  *geo.Point,  *geo.Box) bool {
	if  == nil ||  == nil ||  == nil || .TopLeft == nil {
		return false
	}
	 := math.Min(.TopLeft.X, .TopLeft.X+.Width)
	 := math.Max(.TopLeft.X, .TopLeft.X+.Width)
	 := math.Min(.TopLeft.Y, .TopLeft.Y+.Height)
	 := math.Max(.TopLeft.Y, .TopLeft.Y+.Height)
	if math.Max(.X, .X) <  ||  < math.Min(.X, .X) ||
		math.Max(.Y, .Y) <  ||  < math.Min(.Y, .Y) {
		return false
	}
	 := func( *geo.Point) bool {
		return  <= .X && .X <=  &&  <= .Y && .Y <= 
	}
	if () || () {
		return true
	}
	,  := 0.0, 1.0
	 := func(, , ,  float64) bool {
		if  == 0 {
			return  <=  &&  <= 
		}
		 := ( - ) / 
		 := ( - ) / 
		if  >  {
			,  = , 
		}
		 = math.Max(, )
		 = math.Min(, )
		return  <= 
	}
	if !(.X, .X-.X, , ) ||
		!(.Y, .Y-.Y, , ) {
		return false
	}
	return  < 
}

func orientation(, ,  *geo.Point) float64 {
	 := .X - .X
	 := .Y - .Y
	 := .X - .X
	 := .Y - .Y
	return * - *
}

func intersects(, , ,  *geo.Point) bool {
	 := orientation(, , )
	 := orientation(, , )
	 := orientation(, , )
	 := orientation(, , )
	if  == 0 &&  == 0 &&  == 0 &&  == 0 {
		return closedIntervalsOverlap(.X, .X, .X, .X) &&
			closedIntervalsOverlap(.Y, .Y, .Y, .Y)
	}
	return straddlesLine(, ) && straddlesLine(, )
}

func straddlesLine(,  float64) bool {
	return  == 0 ||  == 0 || ( < 0) != ( < 0)
}

func closedIntervalsOverlap(, , ,  float64) bool {
	,  := math.Min(, ), math.Max(, )
	,  := math.Min(, ), math.Max(, )
	return  <=  &&  <= 
}