convert most stuff to be a subroutine to increase maintainability
misc cleanup, no(t much) functional change
Also use AR, NM, etc. if set.  Fold in some common code.