Added unittests and refactored to improve readability