Code refactoring and minor fixes.