refactored and simplified

took out 2-line regions, replaced repeated code with a function, made
another routine slightly more efficient