The original implementation is rather messy and stateful and has a lot of back and forth logic. It can be vastly improved.