refactor and add debug messages