optimize and add some comments