Moved some of the code around to make more sense