complete rewrite of collapse function

stupid brain fooled me