This function needs a *lot* more documentation. I'm reasonably fluent in Haskell and I have no idea what this does.