Here's a new version of my original patch, with changes after the feedback from Magnus.