Redo pr 211

Re-applies pull #211 and adds a commit that tweaks some of the code style.

r?