Refactored. Added some unit tests.