Refactoring, Improved tests and general cleanup.