Move sections of code into function