Fixes #21 and #46

This should re-introduce the changes brought in by #21 and thereby fix #46. I've also incorporated a few other fixes that I've been working on that overlap with the affected code. The new code is based on that suggested in #46 by @nzakas.

I don't use NodeJS myself, so have not verified that everything works like it should.