Move code around to make main function slightly more manageable