Refactored some code and fixed some tests