Some code refactoring and comments