Some refactoring and minor fixes.