def remove_completed_waypoints(waypoints,
                               target_speeds,
                               ego_vehicle_location,
                               completion_threshold=0.9):
    """Removes waypoints that the ego vehicle has already completed.

    The method first finds the closest waypoint, removes all waypoints
    that are before the closest waypoint, and finally removes the closest
    waypoint if the ego vehicle is very close to it (i.e., close to
    completion).

    Args:
        waypoints (:py:class:`collections.deque`): A double-ended queue of
            initial waypoints.
        ego_vehicle_location (:py:class:`pylot.utils.Location`): The location
            of the ego-vehicle.
        completion_threshold (int): The threshold at which a waypoint is
            considered completed.
    Returns:
        A double-ended queue of trimmed waypoints. (mutates the original queue)
    """
    min_dist = 10000000
    min_index = 0
    index = 0
    for waypoint in waypoints:
        dist = waypoint.location.distance(ego_vehicle_location)
        if dist < min_dist:
            min_dist = dist
            min_index = index
        index += 1

    # Remove waypoints that are before the closest waypoint. The ego
    # vehicle already completed them.
    while min_index > 0:
        waypoints.popleft()
        if target_speeds:
            target_speeds.popleft()
        min_index -= 1

    # The closest waypoint is almost complete, remove it.
    if min_dist < completion_threshold:
        waypoints.popleft()
        if target_speeds:
            target_speeds.popleft()
    return waypoints, target_speeds