refactor and fixed bugs