def on_segment(p, r, q, epsilon):
    """
    Given three colinear points p, q, r, and a threshold epsilone, determine if
    determine if point q lies on line segment pr
    """
    # Taken from http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment
    crossproduct = (q.y - p.y) * (r.x - p.x) - (q.x - p.x) * (r.y - p.y)
    if abs(crossproduct) > epsilon:
        return False   # (or != 0 if using integers)

    dotproduct = (q.x - p.x) * (r.x - p.x) + (q.y - p.y)*(r.y - p.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (r.x - p.x)*(r.x - p.x) + (r.y - p.y)*(r.y - p.y)
    if dotproduct > squaredlengthba:
        return False

    return True