fixed the failing unit tests
Refactored code to be a bit cleaner in places