removed duplicate code and improved performance by caching results