I wrote this and ended up not needing most of it. Perhaps somebody will find it useful.