Wrapped the ###MAIN### block in a function that only runs if the file is called.

The diff looks more messy than it is; except for a few lines, everything is just tabbed over once.