refactoring and bug fixes.