The flow function is long with many loops. I made a pass to clean it up, but it could still be refactored by breaking blocks into functions.