backporting some changes (though I really should've cherrypicked instead)