refactored code slightly