refactor and improve the code