Code refactoring and some improvements