Refactor and debug core logic.