import torch


def _format_faces_indices(faces_indices, max_index):
    """
    Format indices and check for invalid values. Indices can refer to
    values in one of the face properties: vertices, textures or normals.
    See comments of the load_obj function for more details.

    Args:
        faces_indices: List of ints of indices.
        max_index: Max index for the face property.

    Returns:
        faces_indices: List of ints of indices.

    Raises:
        ValueError if indices are not in a valid range.
    """
    faces_indices = torch.tensor(faces_indices, dtype=torch.int64)

    # Change to 0 based indexing.
    faces_indices[(faces_indices > 0)] -= 1

    # Negative indexing counts from the end.
    faces_indices[(faces_indices < 0)] += max_index

    # Check indices are valid.
    if not (
        torch.all(faces_indices < max_index) and torch.all(faces_indices >= 0)
    ):
        raise ValueError("Faces have invalid indices.")

    return faces_indices