Your posted script has syntax errors so I couldn't find what you were doing wrong because the script won't run as posted. Can you post a version that actually exhibits the problem you're trying to solve.
But, from what has gone before, you're probably overlooking the fact that your script is changing the number of rows as it does each step so what you think of as static values are actually changing during the course of the script.
Dave