Refactored some code to work more logically