rewrite using python generator; also code cleanup.