This got a first review from @hyc a while ago, but I've made several changes and added a brand-new test script, so posting it now for further review.
The test script passes with --disable-rewrite
as well as --enable-rewrite
(and identified a couple of bugs before getting there).