import math


def point_segment_distance(px, py, x1, y1, x2, y2):
    """ returns the distance from a point in 2-D (px,py) to a line segment
    going from (x1, y1) to (x12, y12), and also returns the x and y coordinates of the closest point in the line segment to (px,py)
    
    This function is adapted from a stackoverflow.com answer provided by user "Alex Martelli"
    at http://stackoverflow.com/questions/2824478/shortest-distance-between-two-line-segments (last accessed November 6, 2014)
    and is under the Creative Commons License http://creativecommons.org/licenses/by-sa/3.0/
    """
    #    print("called with ", px, py, x1, y1, x2, y2)
    dx = x2 - x1
    dy = y2 - y1
    if dx == dy == 0:  # the segment's just a point
        return math.hypot(px - x1, py - y1)
    
        # Calculate the t that minimizes the distance.
    t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy)
    
# See if this represents one of the segment's
        # end points or a point in the middle.
    near_x = 0
    near_y = 0
    
    if t < 0:
        dx = px - x1
        dy = py - y1
        near_x = x1
        near_y = y1
    elif t > 1:
        dx = px - x2
        dy = py - y2
        near_x = x2
        near_y = y2
    else:
        near_x = x1 + t * dx
        near_y = y1 + t * dy
        dx = px - near_x
        dy = py - near_y
    #if math.hypot(dx,dy) < 101:
    #   print "came up with ", math.hypot(dx,dy), near_x, near_y
    return (math.hypot(dx, dy), near_x, near_y)