add caching, fix some memory issues