Reduce duplication

A few refactorings to get rid of duplicated code.