attempt at simplifying https://gist.github.com/kachayev/21e7fe149bc5ae0bd878