Refactored a lot of code for readability