refactoring and some improvements