refactored logic