refactor and fix code