def METHOD_NAME(text, unbound=None, match_mode=None, environ=os.environ):
    """Substitute environment variables into a string.
    For each $NAME and ${NAME} in "text", substitute with the value
    of the environment variable NAME. If NAME is not defined in the
    environment and "unbound" is None, raise an
    UnboundEnvironmentVariableError. If NAME is not defined in the
    environment and "unbound" is not None, substitute NAME with the
    value of "unbound".
    """
    ret = ""
    try:
        tail = text.decode()
    except AttributeError:
        tail = text
    while tail:
        match = _MATCH_MODES[match_mode].match(tail)
        if match:
            groups = match.groupdict()
            substitute = groups["symbol"]
            if len(groups["escape"]) % 2 == 0:
                if groups["name"] in environ:
                    substitute = environ[groups["name"]]
                elif unbound is not None:
                    substitute = str(unbound)
                else:
                    raise UnboundEnvironmentVariableError(groups["name"])
            ret += (
                groups["head"]
                + groups["escape"][0 : len(groups["escape"]) // 2]
                + substitute
            )
            tail = groups["tail"]
        else:
            ret += tail
            tail = ""
    return ret