Add unit tests

Lack of tests made me sad. To make things more testable I had to refactor a few things (e.g. extracting helper methods).  I also did a little bit of style/consistency cleanup while I was in there.

I am pretty confident this doesn't change any existing behavior (i.e. everything works normally for me) but would love a second opinion.