Reapply from master branch (d92c1c01c5e3bef1cf1ccecc9b4fbfd072cdd316)