Hi,
I would utilise a state machine approach. It seems to me you have two states - compressed and expanded. And you want to record everytime it is compressed. So I would do the following:
1. Set the state (any integer) to zero when inside the compressed range. If it is outside this range set it to 1. Utilise an IF loop here.
2. Independent of all this, check for any state changes. Using a shift register in your while loop, check for old state vs the new state. IF the old state was expanded (ie 1) and the new state is compressed (ie 0), increment COUNTER.
Hope this helps.
Regards,
Setu.