refactor and clean up the code