Refactor and improve debug and error handling