Refactor and improve the code