Fixed loop bugs and unexpected behaviors