Improvements suggested by @timgraham