Fixed some bugs found by the static analyzer.

Code Contracts didn't like some things (for good reason).  Refactors code significantly in order to get the static analyzer to go green.