Added logging, general refactoring