general purpose refactor where code was hard to read, and a performance improvement