refactor main.py, flesh out functions from main function

@stdweird, @wpoely86: please review?

The diff is going to look a bit messy, maybe you want to look at the actual new `main.py` instead...
I couldn't figure out why it was there, but I may have found a reason for it in the unit tests... It looks kind of silly here, since if we have changed to a different directory in any of the code before here, not returning back to the original directory is a bug more than anything else, and should be fixed there instead.