Misc github patches

Cherry-picked patches from github PRs, with some tweaks as needed.

Fixes #1010, #1013, #1017, #1018, #1022.