def lineProjection(x, y, p1, p2, ditchOutOfSegment=True):
    """
    Returns projection of point x, y on line p1 p2.
    Adapted from Grumdrig, http://stackoverflow.com/a/1501725/2037879.

    If *ditchOutOfSegment* is set, this function will return None if point p
    cannot be projected on the segment, i.e. if there's no line perpendicular
    to p1 p2 that intersects both p and a point of p1 p2.
    This is useful for certain GUI usages. Set by default.
    """
    bX = p2.x - p1.x
    bY = p2.y - p1.y
    l2 = bX * bX + bY * bY
    if not l2:
        return p1.x, p1.y, 0.0
    aX = x - p1.x
    aY = y - p1.y
    t = (aX * bX + aY * bY) / l2
    if ditchOutOfSegment:
        if t < 0:
            return p1.x, p1.y, t
        elif t > 1:
            return p2.x, p2.y, t
    projX = p1.x + t * bX
    projY = p1.y + t * bY
    return projX, projY, t
