Added documentation, refactoring

Also fixd some potential problems with shared context