Added exit condition for inner loop.