Rearranged some code to make it easier to read