better error handling, debug messages, and session management and closing