Extract duplicate code into functions
Separate internal Python imports from external
Use lowercase function names
Clarify function names

Removes the need for several comments.
Create a `main` function

Avoids a lot of global variables.