def join_endpoints(endpoints, A, B):
    """
    Join B's segment onto the end of A"s and return the segments. Maintain endopints dict.

    """
    Asegment, Bsegment = endpoints[A], endpoints[B]

    # A must be at the end of Asegment
    if Asegment[-1] is not A:
        Asegment.reverse()
    # B must be at the beginning of Bsegment
    if Bsegment[0] is not B:
        Bsegment.reverse()

    Asegment.extend(Bsegment)  # connect
    del endpoints[A], endpoints[B]  # A and B are no longer endopints
    # make two new segments
    endpoints[Asegment[0]] = Asegment
    endpoints[Asegment[-1]] = Asegment

    return Asegment, endpoints