Addressed lots of comments - mostly on code taken from https://gist.github.com/dimus/335286.