Added exception handling.
Refactored and added some tests.