cleaner (and more correct) implementation of collapse