Refactored. Should be ready for unit tests.