rewritten up to the last iteration