Add some comments and refactor code