Refactored some code.  Bugfixes.