Add utilities to deal with nesting / flattening

I think ultimately this should go to spaces/
I did not try using these functions instead of yours. I can go back to this tomorrow.