optimize and fix bug