Merged OS X and Linux versions as suggested by @bashtage.