refactor

the final changes look quite extensive, but I committed each incremental change with a message explaining my reasoning.  I haven't had a chance to test this with actual data, so pull into a new branch and do some testing before merging to master.

Related to that, there should be some sample data for each scenario in the repo in a 'test' directory or something for testing purposes.