refactoring logic to make it more readable