refactoring and fixing a minor bug