code refactoring and fixes