def clean_path(path, path_ensemble):
    """Remove useless frames from a path.

    This function remove phasepoints from a path that are
    not needed (e.g. the one in stable states)

    Parameters
    ----------
    path : object like :py:class:`.PathBase`
        The path we try to fix.
    path_ensemble : object like :py:class:`.PathEnsembleExt`
        The path ensemble the path could be added to.

    """
    left, _, right = path_ensemble.interfaces
    ph_min = path.phasepoints[0].copy()
    ph_max = path.phasepoints[0].copy()
    dist_right = float('inf')
    dist_left = float('inf')
    for i, phasepoint in enumerate(path.phasepoints):
        if phasepoint.order[0] < left:
            if left - phasepoint.order[0] <= dist_left:
                dist_left = left - phasepoint.order[0]
                ph_min = phasepoint.copy()
        if phasepoint.order[0] >= right:
            if phasepoint.order[0] - right < dist_right:
                dist_right = phasepoint.order[0] - right
                ph_max = phasepoint.copy()
    erase_list = []
    for i, phasepoint in enumerate(path.phasepoints):
        if not left <= phasepoint.order[0] < right:
            erase_list.append(i)
    erase_list.reverse()
    for i in erase_list:
        if path.length == 0:
            raise RuntimeError('All frames of the path are invalid')
        path.delete(i)
    if path_ensemble.start_condition == 'R':
        path.phasepoints.insert(0, ph_max.copy())
        path.phasepoints.append(ph_max.copy())
    if path_ensemble.start_condition == 'L':
        path.phasepoints.insert(0, ph_min.copy())
        path.phasepoints.append(ph_min.copy())
