Refactor and logging