code cleanup

factor out a common function