Clean(er) code

Nowhere near perfect yet, but at least some of the mess got cleaned up.