Rewrite for handling external SQL

The idea here is to pull a bunch of the data handling and SQL schema jazz out of the main python scripts, and put them in a more appropriate location. A side-effect is that it should be more clear to follow.