Gary's refactorings

I tried to do it in small steps with explanations in the commit msg when necessary.

I'm sure there are other improvements that could be made if I had the algorithm in my head, but haven't gone that far. All this is relatively surface.