The quantity of logic in this file is indicative that it should be broken down into either modules or classes.

As it stands, there is quite a bit of shared state between all these methods which will make it very difficult to add features going forward. One change in one of these methods could make another method work improperly.

Think about how you could organize the code into classes or modules to group like behavior and state.