Ensured whitespace is collapsed in terms

Also added code to sort the terms before emitting
them and added a test to be sure the whitespace is
really getting removed.