Fix for part of Redmine 3572, plus some tidy-up.

The expand.c change should be more intelligible if viewed with ?w=1 or git diff -b.