Big refactoring and added more tests