Refactor a little, introduce thread-safety, caching.