code refactoring and bug fixes