Reapply from master branch (6bd5c6a38b8f2c97862fa2182b319467868094eb)