I think you need to check the structure of what you are doing.
I can see a problem with how you are doing it.
This isn't to say it won't work.
Just how I think, there is a different way to do it and it is a lot easier.
And I don't mean that with the code. I mean with how you are doing it with the code you posted - well.... reading around it and what I finally got it to do.
It introduced feedback where things were done multiple times over for no benefit to the need - as I see it.
Yeah, but I shall go back to what I said: there is an easier way to do it.
Alas I can't add a lot of blank lines. This site forces only single lines, so I can't put a big SPOILER gap and a few thoughts on some things I can see as problematic.
But I don't want to show you this as it won't make you learn.
Being spoon fed the answer (or an answer) isn't the best way to learn.
Alas you need to go through the hard times to learn.
I am still learning after ..... 2 years.
I think I am only just off my learner plates.