Refactoring, minor improvements and fixes.