Apply patch for bug 17250 (http://issues.apache.org/bugzilla/show_bug.cgi?id=17250) with some additional minor improvements.