refactored a lot of code out of cache.c