Refactor duplication

Refactorings to reduce duplication, and corrections for a couple of bugs I found along the way.