Refactor and fix all tests