Term re-writing, with test cases.
Merge branch 'master' into output-format