Cache refactoring

Review and (manually) test carefully before merging this one