import re


def _transform_rpaths(orig_rpaths, orig_root, new_prefixes):
    """Return an updated list of RPATHs where each entry in the original list
    starting with the old root is relocated to another place according to the
    mapping passed as argument.

    Args:
        orig_rpaths (list): list of the original RPATHs
        orig_root (str): original root to be substituted
        new_prefixes (dict): dictionary that maps the original prefixes to
            where they should be relocated

    Returns:
        List of paths
    """
    new_rpaths = []
    for orig_rpath in orig_rpaths:
        # If the original RPATH doesn't start with the target root
        # append it verbatim and proceed
        if not orig_rpath.startswith(orig_root):
            new_rpaths.append(orig_rpath)
            continue

        # Otherwise inspect the mapping and transform + append any prefix
        # that starts with a registered key
        for old_prefix, new_prefix in new_prefixes.items():
            if orig_rpath.startswith(old_prefix):
                new_rpaths.append(
                    re.sub(re.escape(old_prefix), new_prefix, orig_rpath)
                )

    return new_rpaths