Big refactor to make the code easier to read