refactored code to make it more easy to understand and dry