Reapply from master branch (bfc63a9be37e0cd3c2e5865ed48bbcff58987400)