refactored algorithm into smaller methods, fixed tests