Refactored some code, moved into utils