Cleaned things up a bit and added tests.

I did this because I was trying to reproduce an error but it seems it is not
reproducable and the tests indicate that all the cases I cared about and the
case that I believed was causing problems was NOT actually causing problems.