Added automatic logging (disabled by default), improved error handling