Major overhaul of caching system (work in progress)

See #1124