Port from master b9aa463af749cf23b83fca36ca45f43b6a91b3e and
3334a5d8de0fa6f3ad706b582d98fce72d52d77c