Refactoring and fixe some bugs