Added Logging & Caching

Also much refactoring to make things (hopefully) easier to understand.