Added tests, refactored some code