optimize and refactor code