refactored code somewhat