Further refactoring. Logic now divided into processing fragments and
processing any substitions contained in those fragments. Makes flow cleaner
and cleans up a couple of border cases.