implemented proper state machine