Rearranged code slightly to make more sense.