refactor code to make more compact and reduce some bugs