Moved a few lines around to make the code more readable.