Refactor cache, write tests