refactor code and fix bugs