Moved functions and variables around to make the everything easier to understand