Please help me understand this behavior

Yes, the assignment vs comparison will trip you up.
But the code seems very convoluted to perform relatively simple tasks.

Maybe you’d like to explain what you’re trying to achieve, accompanied by a schematic diagram - and friendly contributors might help you plan it better.