cherry pick out Mistobaan's patches

In #65 @Mistobaan had some solid patches. But the atomic operations
weren't necessary. So, cherry pick everything except the atomic patches
into this PR.

Thanks @Mistobaan!