I made a version that is a bit shorter - I think it should yield the same results. Take a look if you're interested :) https://gist.github.com/NAndreasson/789034d7d053f967ed8f