Reapply from master branch (4234340323b55fcc90137e3d8292426b7a6e834a)