Refactor and optimize code