Tests fixed, code refactored