Refactoring and minor fix