Consider looking into indentation. The main benefit is that it makes it easier to read your code - in this case it'd make it clearer to you why the "end" statements are out of place.
The basic rule is this - whenever you write a line that starts a new code block (starting with words such as "while", "if", "for", "repeat", etc), move all lines underneath a bit to the right until you reach the corresponding "closing" statement (such as "end", "else", "elseif", "until", etc).
For eg:
This makes it very, very easy to see where each block starts and eventually finishes. This may sound like it's a cosmetic thing, but I mention it first because it's important - you'll find coding a
lot easier if you use a visual aid like this to keep track of your program flow.
In your case, you've got a "while" loop with an "if" statement and
another "while" loop inside it (containing
another "if" statement inside the latter). Because both of your "while" loops are rigged to never end, once the one inside the first begins, the first loop will never gets to repeat.
You need two merge the loops, and just have one with
all required "if" statements inside it.