Flatten and reapply #202 on top of master.

This collapses #202 and fixes incompatibilities with changes on master that occurred since it was opened.