Refactor encode