minor refactoring, logging, proper exception handling