Various improvements to folding/rewriting