This is a big bit of script, what's the best way to break it up? perhaps have lots of different scripts that are thematically linked and import them?
I guess I would start by making the parts of the script less dependent on each other.
For example, it's usually a bad idea to use global variables, as when you have global variables they can be written to from anywhere in your code, so it will quickly become hard to understand and even if you seperate the code things in one part of the code can have far reaching effects. This includes any variables you read from within a function, but declare in the main body of the script. On the other hand anything that is only assigned to within a function will be local to that function so you know it can't be modified by anything else.
Some ways to deal with global variables: