Moved some redundant code to a function.