Refactored, sorted and added tests.