Forked from https://gist.github.com/deviantintegral/0f1066650e3ea5c5ffc1 and initial modifications