refactored code a bit for efficiency