Issue 175

This should fix #175.  Please feel free to cherry pick, or let me know what you want changed and I'll compose a new pull request.

(In particular, I have placed the relevant changes, various style and taste issues, and the slightly insane test case in separate commits.  I'm ok with dropping anything as long as I can get 1fb1e78 in.)