Flatten and reapply #202 on top of master.

This collapses #202 into a single commit, fixing incompatibilities with changes on master that occurred since it was opened.