Applying improvements suggested by @davidchambers