Bug fixes, added logging, refactored