refactored code a bit
added functionality for caching (still needs testing)