refactored code (probably needs another refactoring later)