Code refactoring and fixes