added most state flow logic