fixed bugs and refactoring