Moved some code to functions