Working on issue #33, this reduces some of the code duplication and cleans some other things up (also has some minor performance improvements for the right situations)