Refine the loop, add logging