Reapply from master branch (d9138312b4da1024816bbecd89f168722220f9cf)