refactored code to use a function to decrease repetitiveness