fix bugs and refactor code