fix minor bugs and refactor code