Refactored entirely, added tests.