rewrote detector as state machine