Refactor and optimize