Clean up code, fix tests