Go version uses a fairly fragile if-else pseudo-state machine, should refactor it to use state objects similar to the Python version.