Thanks Paul McMillan, Aymeric Augustin, and Erik Romijn for reviews. Backport of fd23c06023 from master
fd23c06023