Code refactoring and minor bug fixes.