adaptation of patches from https://gist.github.com/zomo/946001