Lots of fixes and improvements from upstream. Former-commit-id: 261cf24efc8bedec7ee76a8897b9a800a4d663e2