refactored code for simpler logic