Improve handling of unplugging

Related to issue #49.