Refactoring code to be more logical