Refactor code into frewer functions