Refactored. Tested.