Misc refactoring + better logging