Refactor code to be unittestable.

I'm ashamed of the fact that I wrote this program with zero unittests!