Refactor, add logging