def segment_point_distance_sq(x1, y1, x2, y2, px, py):
    """ Return the distance from segment (x1, y1, x2, y2) to point (px, py) """
    pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
    if pd2 == 0:
        # Points are coincident.
        x = x1
        y = y2
    else:
        # parameter of closest point on the line
        u = ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1)) / pd2
        if u < 0:  # off the end
            x = x1
            y = y1
        elif u > 1.0:  # off the end
            x = x2
            y = y2
        else:  # interpolate
            x = x1 + u * (x2 - x1)
            y = y1 + u * (y2 - y1)
    return (x - px) * (x - px) + (y - py) * (y - py)