Refactored for clarity/extensibility; added test.