diff --git a/libxslt/pattern.c b/libxslt/pattern.c
index 058917a5..a97726c3 100644
--- a/libxslt/pattern.c
+++ b/libxslt/pattern.c
@@ -451,11 +451,14 @@ xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) {
     xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0);
 
     /*
-     * detect consecutive XSLT_OP_PREDICATE indicating a direct
-     * matching should be done.
+     * Detect consecutive XSLT_OP_PREDICATE and predicates on ops which
+     * haven't been optimized yet indicating a direct matching should be done.
      */
     for (i = 0;i < comp->nbStep - 1;i++) {
-        if ((comp->steps[i].op == XSLT_OP_PREDICATE) &&
+        xsltOp op = comp->steps[i].op;
+
+        if ((op != XSLT_OP_ELEM) &&
+            (op != XSLT_OP_ALL) &&
 	    (comp->steps[i + 1].op == XSLT_OP_PREDICATE)) {
 
 	    comp->direct = 1;
@@ -655,8 +658,10 @@ xsltTestPredicateMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp,
         isRVT = 0;
 
     /*
-     * Depending on the last selection, one may need to
-     * recompute contextSize and proximityPosition.
+     * Recompute contextSize and proximityPosition.
+     *
+     * TODO: Make this work for additional ops. Currently, only XSLT_OP_ELEM
+     * and XSLT_OP_ALL are supported.
      */
     oldCS = ctxt->xpathCtxt->contextSize;
     oldCP = ctxt->xpathCtxt->proximityPosition;
@@ -1128,7 +1133,8 @@ restart:
 		break;
 	    case XSLT_OP_PREDICATE: {
 		/*
-		 * when there is cascading XSLT_OP_PREDICATE, then use a
+		 * When there is cascading XSLT_OP_PREDICATE or a predicate
+		 * after an op which hasn't been optimized yet, then use a
 		 * direct computation approach. It's not done directly
 		 * at the beginning of the routine to filter out as much
 		 * as possible this costly computation.
diff --git a/tests/docs/Makefile.am b/tests/docs/Makefile.am
index c5dad4c5..e3a4aef3 100644
--- a/tests/docs/Makefile.am
+++ b/tests/docs/Makefile.am
@@ -179,6 +179,8 @@ EXTRA_DIST =	\
 	bug-178.xml \
 	bug-179.xml \
 	bug-180.xml \
+	bug-181.xml \
+	bug-182.xml \
 	character.xml \
 	array.xml \
 	items.xml
diff --git a/tests/docs/bug-181.xml b/tests/docs/bug-181.xml
new file mode 100644
index 00000000..285b69a1
--- /dev/null
+++ b/tests/docs/bug-181.xml
@@ -0,0 +1,4 @@
+
b[2]: b 2
text()[2]: text 2
diff --git a/tests/general/bug-182.xsl b/tests/general/bug-182.xsl new file mode 100644 index 00000000..ecce187c --- /dev/null +++ b/tests/general/bug-182.xsl @@ -0,0 +1,19 @@ + +text()[2]: 
b[2]: