A lot of little cleanups, turning bits of code into more literate functions