Refactored a bunch of code to make it more readable