Lots of refactoring
Fixed broken test