def prep_curve(x_y_tuples, curve_type):
    """
    Prepares and returns a list of x_y tuples by prepending or appending the appropriate endpoints depending on the curve type.
    
    If <curve_type> is 'ROC', (0,1) and (1,0) points will be added to extend the curve to the corners.
    
    If <curve_type> is 'PR', (0,y_0) and (x_n,0) points will be added, where y_0 is the first y-value (precision)
    and x_n is the last x-value (recall). This has the effect of terminating the ends of the curve with line
    segments directly to the axes.
    
    If <curve_type> is 'plain', no points will be added and only the area under the known points will be calculated (no extrapolation).
    """
    sorted_tuples = sorted(x_y_tuples, key=lambda x: (x[0], -x[1]))
    if curve_type == 'PR':
        if sorted_tuples[0][0] != 0:
            sorted_tuples = [(0, sorted_tuples[0][1])] + sorted_tuples
        if sorted_tuples[-1][1] != 0:
            sorted_tuples += [(sorted_tuples[-1][0], 0)]
    elif curve_type == 'ROC':
        if sorted_tuples[0] != (1, 0):
            sorted_tuples = [(1, 0)] + sorted_tuples
        if sorted_tuples[-1] != (0, 1):
            sorted_tuples += [(0, 1)]
    elif curve_type == 'plain':
        pass
    else:
        raise ValueError('Invalid value for curve_type. Got: {}'.format(
            curve_type))
    return sorted_tuples
