Move some code around to group helper functions together