import networkx as nx


def get_boundary(surf, vertices, remove_danglers=False):
    """Return interior and exterior boundary sets for `vertices`.
    If `remove_danglers` is True vertices in the internal boundary with
    only one neighbor in the internal boundary will be moved to the external
    boundary.
    """
    if not len(vertices):
        return [], []


    # Use networkx to get external boundary
    external_boundary = set(nx.node_boundary(surf.graph, vertices))

    # Find adjacent vertices to get inner boundary
    internal_boundary = set.union(*[set(surf.graph[v].keys())
                                    for v in external_boundary]).intersection(set(vertices))

    if remove_danglers:
        ingraph = surf.graph.subgraph(internal_boundary)
        danglers = [n for n,d in ingraph.degree().items() if d==1]
        while danglers:
            internal_boundary -= set(danglers)
            external_boundary |= set(danglers)

            ingraph = surf.graph.subgraph(internal_boundary)
            danglers = [n for n,d in ingraph.degree().items() if d<2]

    return list(internal_boundary), list(external_boundary)