refactoring and fixing bugs