Refactored code and added more tests

The test coverage is now at ~95%.