Reapply from master branch (daa63254f7ca01b2fed41a2c1573c0f932abc1d0)