Merges improvements by @nolith from #370 to master