refactor and debug