Shuffle some code around and improve formatting