Clean up the code and fix tests