Moved some code around for clarity.