Revert nested logic simplification to preserve original behavior
The previous simplification inadvertently changed the loop behavior.
Reverting to original logic while keeping variable naming improvements.
Co-authored-by: fisker <172584+fisker@users.noreply.github.com>