Some refactoring and fixes.