refactored logic and tests