Port of d5e3f9f from branch 'v1' (fix for #9868)
Port of 84c9b02 from branch 'v1' (fix for #9857). Also fixes issue #9872.