Incorporate changes from https://gist.github.com/shinzui/866897. EOM