Moved caching function out of main and refactored repeated code.