bug fixes and refactor of codes