Patches applied from Brian Benett's gist.