does anyone have any idea of how to do this?
This is not Python, the "else" is always connected to the last "if" before it. See Mark's post, it should make it very clear for you.
Putting begin-end where appropriate certainly solves this.
Then, you are lucky that you used the same variable in both loops (as Josh spotted) which turned it to compile time error, not only semantic error which could go unnoticed.
Make a habit of using begin-end with if statement.