rewrite to operate on iterators instead