Refactoring, fixes and cleanup.