Thanks to @krasnoukhov for providing the initial patch, which this commit is largely based on. This fixes #49.