nested loop bug fixes