Moved some code to separate functions, move some code around.