replace switch statement with if/else
implement state transition more directly
move bit counting into state transition function