You need to tell us what this is supposed to do.
Commenting your lines of code lets us see what is supposed to happen.
Use variables that give a clue as what they are for, single letter variables are just crap.
My guess is a 'State Machine' is what is needed here.