get variable scope right
break up long fn to provide test attachment point
tidy up fn; remove comments etc