def getSquareSegmentDistance(p, p1, p2):
    """
    Square distance between point and a segment
    """
    x, y = p1
    dx, dy = p2 - p1
    if dx or dy:
        t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy)
        if t > 1:
            x, y = p2
        elif t > 0:
            x += dx * t
            y += dy * t
    dx, dy = p.x - x, p.y - y
    return dx * dx + dy * dy
