I’ve read over this several times and I’m going to be honest, I don’t really understand what you’re trying to do from reading your description.
Looking at the code, I can’t figure out what the code is actually accomplishing, I don’t even see how it can be accomplishing what you think it should be, but this is probably due to my lack of understanding of what you’re trying to do.