refactor and optimize