final code with working iterator