lots of code DRYing, and some more adjustments from JeffD (master)