Cleanup and fix algorithm