Moved several chucks of code into their own functions