A bit of refactoring with simplifing and generalization.