Reapply from master branch (ccca49ff5ed4d7c1546b9306bac5790df9ee6b21)