def _text_point_at_line_end(size, p1, p2):
    """
    Calculate position of the text relative to a line defined by points
    p1 and p2.

    Parameters:
     - size: text size, a (width, height) tuple
     - p1:      beginning of line segment
     - p2:      end of line segment
    """
    name_dx = 0.0
    name_dy = 0.0
    ofs = 5
    dx = float(p2[0]) - float(p1[0])
    dy = float(p2[1]) - float(p1[1])
    name_w, name_h = size
    if dy == 0:
        rc = 1000.0
    else:
        rc = dx / dy
    abs_rc = abs(rc)
    h = dx > 0
    v = dy > 0
    if abs_rc > 6:
        if h:
            name_dx = ofs
            name_dy = -ofs - name_h
        else:
            name_dx = -ofs - name_w
            name_dy = -ofs - name_h
    elif 0 <= abs_rc <= 0.2:
        if v:
            name_dx = -ofs - name_w
            name_dy = ofs
        else:
            name_dx = -ofs - name_w
            name_dy = -ofs - name_h
    else:
        r = abs_rc < 1.0
        align_left = h ^ r
        align_bottom = v ^ r
        if align_left:
            name_dx = ofs
        else:
            name_dx = -ofs - name_w
        if align_bottom:
            name_dy = -ofs - name_h
        else:
            name_dy = ofs
    return p1[0] + name_dx, p1[1] + name_dy
