Joeys patches 2

This is a re-spin of Joey Durkin's set of patches, with minor edits on my behalf. This supersedes pull request #162.