Refactored based on https://gist.github.com/simonster/99431fb31bc8dc5ffda4