Pull caching out to a generic function.

Various code cleanup