Refactor code, add some comments