Rearranged some of the logic.