fixed loop, added improved version