Code refactoring and some fixes.