refactored code a bit for readability