This supersedes the previous patches. The main change is that this is rebased atop Jon A Cruz's patches (which are included here as the first 2). I also merged two related patches and updated the comments.