code for https://gist.github.com/6ca21baf77a47d72b23c