Applied upstream patch to fix some bugs