Merge in refactoring

This merges in some refactoring I had done awhile ago. I've used it in my extension, and think it makes the code a bit easier to work with.