Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session.

The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given.

---------------------------------

The input array of events will consist of one or more of the following strings:

```
APP_PASSIVE_OPEN, APP_ACTIVE_OPEN, APP_SEND, APP_CLOSE, APP_TIMEOUT, RCV_SYN, RCV_ACK, RCV_SYN_ACK, RCV_FIN, RCV_FIN_ACK
```

---------------------------------

The states are as follows and should be returned in all capital letters as shown:

```
CLOSED, LISTEN, SYN_SENT, SYN_RCVD, ESTABLISHED, CLOSE_WAIT, LAST_ACK, FIN_WAIT_1, FIN_WAIT_2, CLOSING, TIME_WAIT
```

---------------------------------

The input will be an array of events. Your job is to traverse the FSM as determined by the events, and return the proper state as a string, all caps, as shown above.

If an event is not applicable to the current state, your code will return `"ERROR"`.

### Action of each event upon each state:
(the format is `INITIAL_STATE: EVENT -> NEW_STATE`)

```
CLOSED: APP_PASSIVE_OPEN -> LISTEN
CLOSED: APP_ACTIVE_OPEN  -> SYN_SENT
LISTEN: RCV_SYN          -> SYN_RCVD
LISTEN: APP_SEND         -> SYN_SENT
LISTEN: APP_CLOSE        -> CLOSED
SYN_RCVD: APP_CLOSE      -> FIN_WAIT_1
SYN_RCVD: RCV_ACK        -> ESTABLISHED
SYN_SENT: RCV_SYN        -> SYN_RCVD
SYN_SENT: RCV_SYN_ACK    -> ESTABLISHED
SYN_SENT: APP_CLOSE      -> CLOSED
ESTABLISHED: APP_CLOSE   -> FIN_WAIT_1
ESTABLISHED: RCV_FIN     -> CLOSE_WAIT
FIN_WAIT_1: RCV_FIN      -> CLOSING
FIN_WAIT_1: RCV_FIN_ACK  -> TIME_WAIT
FIN_WAIT_1: RCV_ACK      -> FIN_WAIT_2
CLOSING: RCV_ACK         -> TIME_WAIT
FIN_WAIT_2: RCV_FIN      -> TIME_WAIT
TIME_WAIT: APP_TIMEOUT   -> CLOSED
CLOSE_WAIT: APP_CLOSE    -> LAST_ACK
LAST_ACK: RCV_ACK        -> CLOSED
```

!["EFSM TCP" ](http://theangelfallseries.com/img/EFSM_TCP.png)

## Examples

```
["APP_PASSIVE_OPEN", "APP_SEND", "RCV_SYN_ACK"] =>  "ESTABLISHED"

["APP_ACTIVE_OPEN"] =>  "SYN_SENT"

["APP_ACTIVE_OPEN", "RCV_SYN_ACK", "APP_CLOSE", "RCV_FIN_ACK", "RCV_ACK"] =>  "ERROR"
```

 

This kata is similar to [Design a Simple Automaton (Finite State Machine)](https://www.codewars.com/kata/design-a-simple-automaton-finite-state-machine), and you may wish to try that kata before tackling this one.

See wikipedia page [Transmission Control Protocol]( http://en.wikipedia.org/wiki/Transmission_Control_Protocol)
for further details.

See http://www.medianet.kent.edu/techreports/TR2005-07-22-tcp-EFSM.pdf page 4, for the FSM diagram used for this kata.

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = 'import abc\n\nclass Condition(abc.ABC):\n    @abc.abstractmethod\n    def check_condition(self, params):\n        pass\n\nclass ConditionEvent(Condition):\n    def __init__(self, event_name):\n        self.event_name = event_name\n\n    def check_condition(self, params):\n        event_name = params\n        return self.event_name == event_name\n\nclass Transition:\n    def __init__(self, fsm, to):\n        self.fsm = fsm\n        self.to = to\n        self.conditions = []\n\n    def check_conditions(self, params):\n        return all(cond.check_condition(params) for cond in self.conditions)\n\n\nclass State:\n    def __init__(self, fsm, name):\n        self.name = name\n        self.transitions = []\n\n    def next_state(self, params):\n        next_state = next((trans.to for trans in self.transitions\n                          if trans.check_conditions(params)), None)\n        return next_state\n\nclass FSM:\n    def __init__(self):\n        self.cur_state_name = None\n        self.states = {}\n\n    def next_state(self, params):\n        cur_state = self.states[self.cur_state_name]\n        next_state = cur_state.next_state(params)\n        if next_state is None:\n            raise RuntimeError("Error")\n        self.cur_state_name = next_state\n\ndef create_scheme():\n    scheme_str = """\nCLOSED: APP_PASSIVE_OPEN -> LISTEN\nCLOSED: APP_ACTIVE_OPEN  -> SYN_SENT\nLISTEN: RCV_SYN          -> SYN_RCVD\nLISTEN: APP_SEND         -> SYN_SENT\nLISTEN: APP_CLOSE        -> CLOSED\nSYN_RCVD: APP_CLOSE      -> FIN_WAIT_1\nSYN_RCVD: RCV_ACK        -> ESTABLISHED\nSYN_SENT: RCV_SYN        -> SYN_RCVD\nSYN_SENT: RCV_SYN_ACK    -> ESTABLISHED\nSYN_SENT: APP_CLOSE      -> CLOSED\nESTABLISHED: APP_CLOSE   -> FIN_WAIT_1\nESTABLISHED: RCV_FIN     -> CLOSE_WAIT\nFIN_WAIT_1: RCV_FIN      -> CLOSING\nFIN_WAIT_1: RCV_FIN_ACK  -> TIME_WAIT\nFIN_WAIT_1: RCV_ACK      -> FIN_WAIT_2\nCLOSING: RCV_ACK         -> TIME_WAIT\nFIN_WAIT_2: RCV_FIN      -> TIME_WAIT\nTIME_WAIT: APP_TIMEOUT   -> CLOSED\nCLOSE_WAIT: APP_CLOSE    -> LAST_ACK\nLAST_ACK: RCV_ACK        -> CLOSED\n"""\n\n    scheme = []\n    for line in scheme_str.splitlines():\n        if not line:\n            continue\n    \n        from_state, rest = line.split(":")\n        event, to_state = rest.split("->")\n        scheme.append((from_state.strip(), to_state.strip(), event.strip()))\n\n    return scheme\n\ndef create_fsm(scheme):\n    fsm = FSM()\n    for from_state_name, to_state_name, event in scheme:\n        try:\n            state = fsm.states[from_state_name]\n        except KeyError:\n            state = fsm.states[from_state_name] = State(fsm, from_state_name)\n    \n        transtion = Transition(fsm, to=to_state_name)\n        transtion.conditions.append(ConditionEvent(event))\n        state.transitions.append(transtion)\n\n    return fsm\n\ndef traverse_TCP_states(events):\n    scheme = create_scheme()\n    fsm = create_fsm(scheme)\n    fsm.cur_state_name = "CLOSED"\n\n    try:\n        for event in events:\n            fsm.next_state(event)\n    except:\n        return "ERROR"\n    else:\n        return fsm.cur_state_name'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'traverse_TCP_states'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 29616