Refactoring, adding better logging, docs.