Fixed loop algorithm issue