Refactored a little and added test.