This supersedes my previous set of patches. Changes are to fix some rebase errors so that it compiles after each patch applies, and some further rebasing to rearrange the patches and split them into a more logical order.