Applied upstream patch to fix various bugs