Hint: at any one time you can be in one of a number of states
State1: looking for the initial heads.
- if you receive a tail, reset the head count to 0 and stay in State1
- if you receive a head, increment the head count. If the head count reaches M, move to State2
State2: looking for first tail
- if you receive a head, stay in State2. This corresponds to more-than-enough heads, which is still "M heads in a row"
- if you receive a tail, enter State3
State3: counting tails
- if you receive a head, go back to State1. Not enough tails in a row
- if you receive a tail, increment the tail count. If the tail count reaches M, you are done.
This can be packed down to two states if you want to bother.