Refactor the three main groups of code out of