flags according to trac ticket #212, code formatting, javadoc

Change-Id: Iba0f4e217a5095a3a9a0b6ed06cba6713c783e30
diff --git a/.gitignore b/.gitignore
index 714609d..c304b58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,8 @@
 
 # /
+/.project
+/.classpath
+/.settings/org.eclipse.jdt.core.prefs
 /target
 
 # /src/main/antlr/cosmas/
diff --git a/README.md b/README.md
index 29f270f..a26ab9e 100644
--- a/README.md
+++ b/README.md
@@ -37,35 +37,35 @@
 
 ```json
 {
-    "@context": "http://ids-mannheim.de/ns/KorAP/json-ld/v0.2/context.jsonld",
+    "@context": "http://korap.ids-mannheim.de/ns/KoralQuery/v0.2/context.jsonld",
     "query": {
-        "@type": "korap:group",
+        "@type": "koral:group",
         "operation": "operation:position",
         "frames": [
             "frames:isAround"
         ],
         "operands": [
             {
-                "@type": "korap:span",
+                "@type": "koral:span",
                 "key": "s"
             },
             {
-                "@type": "korap:group",
+                "@type": "koral:group",
                 "operation": "operation:sequence",
                 "operands": [
                     {
-                        "@type": "korap:token",
+                        "@type": "koral:token",
                         "wrap": {
-                            "@type": "korap:term",
+                            "@type": "koral:term",
                             "layer": "orth",
                             "key": "zu",
                             "match": "match:eq"
                         }
                     },
                     {
-                        "@type": "korap:token",
+                        "@type": "koral:token",
                         "wrap": {
-                            "@type": "korap:term",
+                            "@type": "koral:term",
                             "layer": "pos",
                             "key": "ADJA",
                             "match": "match:eq"
diff --git a/src/main/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessor.java b/src/main/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessor.java
index b139206..bdac037 100644
--- a/src/main/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessor.java
+++ b/src/main/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessor.java
@@ -886,7 +886,9 @@
 
                 if (value.startsWith("$")) {
                     value = value.substring(1);
-                    fieldMap.put("caseInsensitive", true);
+                    ArrayList<String> flags = new ArrayList<String>();
+                    flags.add("flags:caseInsensitive");
+                    fieldMap.put("flags", flags);
                 }
 
                 fieldMap.put("key", value);
diff --git a/src/main/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessor.java b/src/main/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessor.java
index 1ec4b9f..eab29f8 100644
--- a/src/main/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessor.java
+++ b/src/main/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessor.java
@@ -96,13 +96,12 @@
         }
 
         /*
-         * ***************************************************************
-         * ***************************************************************
-         * *********** Processing individual node categories *************
-         * ***************************************************************
-         * ***************************************************************
+         ****************************************************************
+         **************************************************************** 
+         *          Processing individual node categories               *
+         ****************************************************************
+         ****************************************************************
          */
-
         if (nodeCat.equals("segment")) {
             processSegment(node);
         }
@@ -158,10 +157,12 @@
         if (nodeCat.equals("meta")) {
             processMeta(node);
         }
-        
-//        if (nodeCat.equals("term") || nodeCat.equals("termGroup")) {
-//            if (inMeta ) putIntoSuperObject(parseTermOrTermGroup(node, false));
-//        }
+
+        // if (nodeCat.equals("term") || nodeCat.equals("termGroup"))
+        // {
+        // if (inMeta ) putIntoSuperObject(parseTermOrTermGroup(node,
+        // false));
+        // }
 
         if (nodeCat.equals("within")
                 && !getNodeCat(node.getParent()).equals("position")) {
@@ -171,22 +172,18 @@
         objectsToPop.push(stackedObjects);
 
         /*
-         * ***************************************************************
-         * ***************************************************************
-         * recursion until 'request' node (root of tree) is processed
-         * *
-         * ***********************************************************
-         * ****
-         * ********************************************************
-         * *******
+         ****************************************************************
+         **************************************************************** 
+         *  Recursion until 'request' node (root of tree) is processed  *
+         ****************************************************************
+         ****************************************************************
          */
         for (int i = 0; i < node.getChildCount(); i++) {
             ParseTree child = node.getChild(i);
             processNode(child);
         }
 
-        // Stuff that happens when leaving a node (taking items off
-        // the stacks)
+        // Stuff that happens when leaving a node (taking items off stacks)
         for (int i = 0; i < objectsToPop.get(0); i++) {
             objectStack.pop();
         }
@@ -198,8 +195,8 @@
         // Cover possible quantification (i.e. repetition) of segment
         ParseTree quantification = getFirstChildWithCat(node, "repetition");
         if (quantification != null) {
-            LinkedHashMap<String, Object> quantGroup = 
-                    KoralObjectGenerator.makeGroup("repetition");
+            LinkedHashMap<String, Object> quantGroup = KoralObjectGenerator
+                    .makeGroup("repetition");
             Integer[] minmax = parseRepetition(quantification);
             quantGroup.put("boundary",
                     KoralObjectGenerator.makeBoundary(minmax[0], minmax[1]));
@@ -210,19 +207,20 @@
     }
 
     private void processSequence(ParseTree node) {
-        // skipe in case of emptyTokenSequence or emptyTokenSequenceClass
-        if (node.getChildCount() == 1 && 
-                getNodeCat(node.getChild(0)).startsWith("emptyTokenSequence"))  {
-            return; 
+        // skip in case of emptyTokenSequence or emptyTokenSequenceClass
+        if (node.getChildCount() == 1
+                && getNodeCat(node.getChild(0))
+                        .startsWith("emptyTokenSequence")) {
+            return;
         }
-        LinkedHashMap<String, Object> sequence = 
-                KoralObjectGenerator.makeGroup("sequence");
+        LinkedHashMap<String, Object> sequence = KoralObjectGenerator
+                .makeGroup("sequence");
         ParseTree distanceNode = getFirstChildWithCat(node, "distance");
 
         if (distanceNode != null) {
             Integer[] minmax = parseDistance(distanceNode);
-            LinkedHashMap<String, Object> distance = 
-                    KoralObjectGenerator.makeDistance("w", minmax[0], minmax[1]);
+            LinkedHashMap<String, Object> distance = KoralObjectGenerator
+                    .makeDistance("w", minmax[0], minmax[1]);
             sequence.put("inOrder", true);
             ArrayList<Object> distances = new ArrayList<Object>();
             distances.add(distance);
@@ -245,8 +243,8 @@
         // object will be either a repetition group or a single empty
         // token
         LinkedHashMap<String, Object> object;
-        LinkedHashMap<String, Object> emptyToken = 
-                KoralObjectGenerator.makeToken();
+        LinkedHashMap<String, Object> emptyToken = KoralObjectGenerator
+                .makeToken();
         if (minmax[0] != 1 || minmax[1] == null || minmax[1] != 1) {
             object = KoralObjectGenerator.makeRepetition(minmax[0], minmax[1]);
             ((ArrayList<Object>) object.get("operands")).add(emptyToken);
@@ -265,8 +263,8 @@
             classId = Integer.parseInt(node.getChild(1).getChild(0)
                     .toStringTree(parser));
         }
-        LinkedHashMap<String, Object> classGroup = 
-                KoralObjectGenerator.makeSpanClass(classId);
+        LinkedHashMap<String, Object> classGroup = KoralObjectGenerator
+                .makeSpanClass(classId);
         addHighlightClass(classId);
         putIntoSuperObject(classGroup);
         objectStack.push(classGroup);
@@ -284,11 +282,11 @@
             negated = true;
             termOrTermGroupChildId += negations.size();
         }
-            
-        System.err.println(negated);
+
         if (getNodeCat(node.getChild(0)).equals("key")) {
             // no 'term' child, but direct key specification: process here
-            LinkedHashMap<String, Object> term = KoralObjectGenerator.makeTerm();
+            LinkedHashMap<String, Object> term = KoralObjectGenerator
+                    .makeTerm();
             String key = node.getChild(0).getText();
             if (getNodeCat(node.getChild(0).getChild(0)).equals("regex")) {
                 isRegex = true;
@@ -301,28 +299,29 @@
             term.put("match", "match:" + matches);
             ParseTree flagNode = getFirstChildWithCat(node, "flag");
             if (flagNode != null) {
+                ArrayList<String> flags = new ArrayList<String>();
                 // substring removes leading slash '/'
                 String flag = getNodeCat(flagNode.getChild(0)).substring(1);
                 if (flag.contains("i"))
-                    term.put("caseInsensitive", true);
-                else if (flag.contains("I"))
-                    term.put("caseInsensitive", false);
+                    flags.add("flags:caseInsensitive");
                 if (flag.contains("x")) {
                     term.put("type", "type:regex");
                     if (!isRegex) {
                         key = QueryUtils.escapeRegexSpecialChars(key);
                     }
                     // overwrite key
-                    term.put("key", ".*?" + key + ".*?"); 
+                    term.put("key", ".*?" + key + ".*?");
+                }
+                if (!flags.isEmpty()) {
+                    term.put("flags", flags);
                 }
             }
             token.put("wrap", term);
         }
         else {
             // child is 'term' or 'termGroup' -> process in extra method
-            LinkedHashMap<String, Object> termOrTermGroup = 
-                    parseTermOrTermGroup(node.getChild(termOrTermGroupChildId),
-                            negated);
+            LinkedHashMap<String, Object> termOrTermGroup = parseTermOrTermGroup(
+                    node.getChild(termOrTermGroupChildId), negated);
             token.put("wrap", termOrTermGroup);
         }
         putIntoSuperObject(token);
@@ -331,8 +330,8 @@
 
     @SuppressWarnings("unchecked")
     private void processAlignment(ParseTree node) {
-        LinkedHashMap<String, Object> alignClass = 
-                KoralObjectGenerator.makeSpanClass(classCounter);
+        LinkedHashMap<String, Object> alignClass = KoralObjectGenerator
+                .makeSpanClass(classCounter);
         LinkedHashMap<String, Object> metaMap = 
                 (LinkedHashMap<String, Object>) requestMap.get("meta");
         if (metaMap.containsKey("alignment")) {
@@ -361,6 +360,9 @@
         if (negations.size() % 2 == 1)
             negated = true;
         LinkedHashMap<String, Object> span = KoralObjectGenerator.makeSpan();
+        LinkedHashMap<String, Object> wrappedTerm = 
+                KoralObjectGenerator.makeTerm();
+        span.put("wrap", wrappedTerm);
         ParseTree keyNode = getFirstChildWithCat(node, "key");
         ParseTree layerNode = getFirstChildWithCat(node, "layer");
         ParseTree foundryNode = getFirstChildWithCat(node, "foundry");
@@ -368,27 +370,27 @@
         ParseTree termNode = getFirstChildWithCat(node, "term");
         ParseTree termGroupNode = getFirstChildWithCat(node, "termGroup");
         if (foundryNode != null)
-            span.put("foundry", foundryNode.getText());
+            wrappedTerm.put("foundry", foundryNode.getText());
         if (layerNode != null) {
             String layer = layerNode.getText();
             if (layer.equals("base"))
                 layer = "lemma";
-            span.put("layer", layer);
+            wrappedTerm.put("layer", layer);
         }
         String key = keyNode.getText();
         // check if key is regular expression
         if (hasChild(keyNode, "regex")) {
             // remove leading/trailing double quotes
-            key = key.substring(1, key.length()-1); 
-            span.put("type", "type:regex");
+            key = key.substring(1, key.length() - 1);
+            wrappedTerm.put("type", "type:regex");
         }
-        span.put("key", key);
+        wrappedTerm.put("key", key);
         if (termOpNode != null) {
             String termOp = termOpNode.getText();
             if (termOp.equals("=="))
-                span.put("match", "match:eq");
+                wrappedTerm.put("match", "match:eq");
             else if (termOp.equals("!="))
-                span.put("match", "match:ne");
+                wrappedTerm.put("match", "match:ne");
         }
         if (termNode != null) {
             LinkedHashMap<String, Object> termOrTermGroup = 
@@ -423,15 +425,15 @@
     private void processRelation(ParseTree node) {
         LinkedHashMap<String, Object> relationGroup = 
                 KoralObjectGenerator.makeGroup("relation");
-        LinkedHashMap<String, Object> relation = 
-                KoralObjectGenerator.makeRelation();
-        LinkedHashMap<String, Object> term = 
-                KoralObjectGenerator.makeTerm();
+        LinkedHashMap<String, Object> relation = KoralObjectGenerator
+                .makeRelation();
+        LinkedHashMap<String, Object> term = KoralObjectGenerator.makeTerm();
         relationGroup.put("relation", relation);
         relation.put("wrap", term);
         if (node.getChild(0).getText().equals("dominates")) {
             term.put("layer", "c");
-        } else if (node.getChild(0).getText().equals("dependency")) {
+        }
+        else if (node.getChild(0).getText().equals("dependency")) {
             term.put("layer", "d");
         }
         ParseTree relSpec = getFirstChildWithCat(node, "relSpec");
@@ -472,15 +474,8 @@
                 log.error(msg);
                 addError(StatusCodes.INVALID_CLASS_REFERENCE, msg);
             }
-            // only allow class id up to 127
-            if (classId > 128) {
-                addWarning("Only class IDs up to 128 are allowed. Your class "
-                        + classId + " has been set back to 128. "
-                        + "Check for possible conflict with other classes.");
-                classId = 128;
-            }
-        } 
-        LinkedHashMap<String, Object> classGroup = 
+        }
+        LinkedHashMap<String, Object> classGroup =
                 KoralObjectGenerator.makeSpanClass(classId);
         addHighlightClass(classId);
         putIntoSuperObject(classGroup);
@@ -503,15 +498,6 @@
                 else {
                     try {
                         int classRef = Integer.parseInt(ref);
-                        // only allow class id up to 128
-                        if (classRef > 128) {
-                            addWarning("Only class references up to 128 are "
-                                    + "allowed. Your reference to class "
-                                    + classRef + " has been set back to 128. "
-                                    + "Check for possible conflict with "
-                                    + "other classes.");
-                            classRef = 128;
-                        }
                         classRefs.add(classRef);
                     }
                     catch (NumberFormatException e) {
@@ -571,7 +557,8 @@
         addWarning("You used the 'meta' keyword in a PoliqarpPlus query. This"
                 + " feature is currently not supported. Please use virtual "
                 + "collections to restrict documents by metadata.");
-        CollectionQueryProcessor cq = new CollectionQueryProcessor(node.getChild(1).getText());
+        CollectionQueryProcessor cq = 
+                new CollectionQueryProcessor(node.getChild(1).getText());
         requestMap.put("collection", cq.getRequestMap().get("collection"));
         for (ParseTree child : getChildren(node)) {
             visited.add(child);
@@ -582,10 +569,14 @@
     private void processWithin(ParseTree node) {
         ParseTree domainNode = node.getChild(1);
         String domain = getNodeCat(domainNode);
-        LinkedHashMap<String, Object> span = KoralObjectGenerator.makeSpan(domain);
-        LinkedHashMap<String, Object> queryObj = (LinkedHashMap<String, Object>) requestMap.get("query");
-        LinkedHashMap<String, Object> contains = KoralObjectGenerator.makePosition(new String[]{"frames:isAround"});
-        ArrayList<Object> operands = (ArrayList<Object>) contains.get("operands");
+        LinkedHashMap<String, Object> span = KoralObjectGenerator
+                .makeSpan(domain);
+        LinkedHashMap<String, Object> queryObj = 
+                (LinkedHashMap<String, Object>) requestMap.get("query");
+        LinkedHashMap<String, Object> contains = KoralObjectGenerator
+                .makePosition(new String[] { "frames:isAround" });
+        ArrayList<Object> operands = 
+                (ArrayList<Object>) contains.get("operands");
         operands.add(span);
         operands.add(queryObj);
         requestMap.put("query", contains);
@@ -638,11 +629,11 @@
                 min = 0;
             else {
                 min = max;
-//                addWarning("Your query contains a segment of the form {n}, where n is some number. This expression is ambiguous. "
-//                        + "It could mean a repetition (\"Repeat the previous element n times!\") or a word form that equals the number, "
-//                        + "enclosed by a \"class\" (which is denoted by braces like '{x}', see the documentation on classes)."
-//                        + "KorAP has by default interpreted the segment as a repetition statement. If you want to express the"
-//                        + "number as a word form inside a class, use the non-shorthand form {[orth=n]}.");
+                // addWarning("Your query contains a segment of the form {n}, where n is some number. This expression is ambiguous. " +
+                // "It could mean a repetition (\"Repeat the previous element n times!\") or a word form that equals the number, "+
+                // "enclosed by a \"class\" (which is denoted by braces like '{x}', see the documentation on classes)."+
+                // "KorAP has by default interpreted the segment as a repetition statement. If you want to express the"+
+                // "number as a word form inside a class, use the non-shorthand form {[orth=n]}.");
             }
         }
         if (maxInfinite) {
@@ -662,10 +653,10 @@
                 frames = new String[] { "frames:matches" };
                 break;
             case "startswith":
-                frames = new String[] { "frames:startsWith", "frames:matches" };
+                frames = new String[] { "frames:startsWith","frames:matches" };
                 break;
             case "endswith":
-                frames = new String[] { "frames:endsWith", "frames:matches" };
+                frames = new String[] { "frames:endsWith","frames:matches" };
                 break;
             case "overlaps":
                 frames = new String[] { "frames:overlapsLeft",
@@ -689,7 +680,8 @@
      *            negated, e.g. through a negation operator preceding
      *            the related token like "![base=foo]". Global
      *            negation affects the term's "match" parameter.
-     * @param mode 'token' or 'span' (tokens and spans are treated 
+     * @param mode
+     *            'token' or 'span' (tokens and spans are treated
      *            differently).
      * @return A term or termGroup object, depending on input
      */
@@ -699,8 +691,8 @@
         String nodeCat = getNodeCat(node);
         if (nodeCat.equals("term")) {
             String key = null;
-            LinkedHashMap<String, Object> term = 
-                    KoralObjectGenerator.makeTerm();
+            LinkedHashMap<String, Object> term = KoralObjectGenerator
+                    .makeTerm();
             // handle negation
             boolean negated = negatedGlobal;
             boolean isRegex = false;
@@ -722,8 +714,8 @@
             if (getNodeCat(keyNode.getChild(0)).equals("regex")) {
                 isRegex = true;
                 term.put("type", "type:regex");
-             // remove leading and trailing quotes
-                key = key.substring(1, key.length() - 1); 
+                // remove leading and trailing quotes
+                key = key.substring(1, key.length() - 1);
             }
             if (mode.equals("span"))
                 term.put("value", key);
@@ -734,14 +726,16 @@
                 String layer = layerNode.getText();
                 if (mode.equals("span")) {
                     term.put("key", layer);
-                } else if (mode.equals("token")) {
+                }
+                else if (mode.equals("token")) {
                     if (layer.equals("base")) {
-                        layer = "lemma"; }
+                        layer = "lemma";
+                    }
                     else if (layer.equals("punct")) {
                         layer = "orth";
                         // will override "type":"type:regex"
-                        term.put("type", "type:punct"); 
-                    }   
+                        term.put("type", "type:punct");
+                    }
                     term.put("layer", layer);
                 }
             }
@@ -759,21 +753,24 @@
             }
             // process possible flags
             if (flagNode != null) {
-             // substring removes leading slash
-                String flag = getNodeCat(flagNode.getChild(0)).substring(1); 
+                ArrayList<String> flags = new ArrayList<String>();
+                // substring removes leading slash
+                String flag = getNodeCat(flagNode.getChild(0)).substring(1);
+
                 if (flag.contains("i"))
-                    term.put("caseInsensitive", true);
-                else if (flag.contains("I"))
-                    term.put("caseInsensitive", false);
+                    flags.add("flags:caseInsensitive");
                 if (flag.contains("x")) {
                     if (!isRegex) {
                         key = QueryUtils.escapeRegexSpecialChars(key);
                     }
-                    // flag 'x' allows submatches: 
+                    // flag 'x' allows submatches:
                     // overwrite key with appended .*?
-                    term.put("key", ".*?" + key + ".*?"); // 
+                    term.put("key", ".*?" + key + ".*?"); //
                     term.put("type", "type:regex");
                 }
+                if (!flags.isEmpty()) {
+                    term.put("flags", flags);
+                }
             }
             return term;
         }
@@ -850,15 +847,19 @@
     }
 
     /**
-     * Basically only increases the min and max counters as required
-     * by Poliqarp
+     * Parses the min and max attributes for a boundary object as defined in 
+     * a distance node. Increases the min and max counters by 1 in order to
+     * reflect the disparity between the <i>distance</i> of operands (which is
+     * 1 in the case of directly succeeding tokens) and the Poliqarpish
+     * <i>number of intermediate tokens</i> (which is 0). 
      * 
-     * @param distanceNode
-     * @return
+     * @param distanceNode A node of category 'distance'
+     * @return An array of two fields, where the first is the min value and the
+     *      second is the max value and may be null.  
      */
     private Integer[] parseDistance(ParseTree distanceNode) {
-        int emptyTokenSeqIndex = getNodeCat(distanceNode).equals("distance") ? 0
-                : 2;
+        int emptyTokenSeqIndex = 
+                getNodeCat(distanceNode).equals("distance") ? 0 : 2;
         Integer[] minmax = parseEmptySegments(distanceNode
                 .getChild(emptyTokenSeqIndex));
         Integer min = minmax[0];
@@ -866,8 +867,6 @@
         min++;
         if (max != null)
             max++;
-        // min = cropToMaxValue(min);
-        // max = cropToMaxValue(max);
         return new Integer[] { min, max };
     }
 
@@ -923,8 +922,8 @@
 
             // Get starting rule from parser
             Method startRule = PoliqarpPlusParser.class.getMethod("request");
-            tree = 
-                 (ParserRuleContext) startRule.invoke(parser, (Object[]) null);
+            tree = (ParserRuleContext) 
+                    startRule.invoke(parser, (Object[]) null);
         }
         // Some things went wrong ...
         catch (Exception e) {
diff --git a/src/main/java/de/ids_mannheim/korap/query/serialize/QuerySerializer.java b/src/main/java/de/ids_mannheim/korap/query/serialize/QuerySerializer.java
index 8c8e591..eb6b61d 100644
--- a/src/main/java/de/ids_mannheim/korap/query/serialize/QuerySerializer.java
+++ b/src/main/java/de/ids_mannheim/korap/query/serialize/QuerySerializer.java
@@ -17,7 +17,8 @@
 
 /**
  * Main class for Koral, serializes queries from concrete QLs to KoralQuery
- * @author Joachim Bingel (bingel@ids-mannheim.de), Michael Hanl (hanl@ids-mannheim.de)
+ * @author Joachim Bingel (bingel@ids-mannheim.de), 
+ *         Michael Hanl (hanl@ids-mannheim.de)
  * @version 0.3.0
  * @since 0.1.0
  */
diff --git a/src/main/java/de/ids_mannheim/korap/query/serialize/QueryUtils.java b/src/main/java/de/ids_mannheim/korap/query/serialize/QueryUtils.java
index e3d32b5..ef06c93 100644
--- a/src/main/java/de/ids_mannheim/korap/query/serialize/QueryUtils.java
+++ b/src/main/java/de/ids_mannheim/korap/query/serialize/QueryUtils.java
@@ -13,7 +13,8 @@
 import java.util.regex.Pattern;
 
 /**
- * @author Joachim Bingel (bingel@ids-mannheim.de), Michael Hanl (hanl@ids-mannheim.de)
+ * @author Joachim Bingel (bingel@ids-mannheim.de), 
+ *         Michael Hanl (hanl@ids-mannheim.de)
  * @date 10/12/2013
  * @version 0.3.0
  * @since 0.1.0
@@ -179,78 +180,6 @@
         return request;
     }
 
-    public static void prepareContext(LinkedHashMap<String, Object> requestMap) {
-        LinkedHashMap<String, Object> context = new LinkedHashMap<String, Object>();
-
-        LinkedHashMap<String, Object> classMap = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> operands = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> operation = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> frame = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> classRef = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> spanRef = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> classRefOp = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> min = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> max = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> exclude = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> distances = new LinkedHashMap<String, Object>();
-        LinkedHashMap<String, Object> inOrder = new LinkedHashMap<String, Object>();
-
-        operation.put("@id", "group:operation/");
-        operation.put("@type", "@id");
-
-        classMap.put("@id", "group:class");
-        classMap.put("@type", "xsd:integer");
-
-        operands.put("@id", "group:operands");
-        operands.put("@container", "@list");
-
-        frame.put("@id", "group:frame/");
-        frame.put("@type", "@id");
-
-        classRef.put("@id", "group:classRef");
-        classRef.put("@type", "xsd:integer");
-
-        spanRef.put("@id", "group:spanRef");
-        spanRef.put("@type", "xsd:integer");
-
-        classRefOp.put("@id", "group:classRefOp");
-        classRefOp.put("@type", "@id");
-
-        min.put("@id", "boundary:min");
-        min.put("@type", "xsd:integer");
-
-        max.put("@id", "boundary:max");
-        max.put("@type", "xsd:integer");
-
-        exclude.put("@id", "group:exclude");
-        exclude.put("@type", "xsd:boolean");
-
-        distances.put("@id", "group:distances");
-        distances.put("@container", "@list");
-
-        inOrder.put("@id", "group:inOrder");
-        inOrder.put("@type", "xsd:boolean");
-
-        context.put("korap",
-                "http://korap.ids-mannheim.de/ns/KorAP/json-ld/v0.1/");
-        context.put("boundary", "korap:boundary/");
-        context.put("group", "korap:group/");
-        context.put("operation", operation);
-        context.put("class", classMap);
-        context.put("operands", operands);
-        context.put("frame", frame);
-        context.put("classRef", classRef);
-        context.put("spanRef", spanRef);
-        context.put("classRefOp", classRefOp);
-        context.put("min", min);
-        context.put("max", max);
-        context.put("exclude", exclude);
-        context.put("distances", distances);
-        context.put("inOrder", inOrder);
-
-        requestMap.put("@context", context);
-    }
-
     public static String escapeRegexSpecialChars(String key) {
         key.replace("\\", "\\\\");
         Pattern p = Pattern
@@ -263,5 +192,4 @@
         return key;
     }
 
-
 }
diff --git a/src/main/java/de/ids_mannheim/korap/query/serialize/TreeTemplate.java b/src/main/java/de/ids_mannheim/korap/query/serialize/TreeTemplate.java
index 7cc8174..2e9d074 100644
--- a/src/main/java/de/ids_mannheim/korap/query/serialize/TreeTemplate.java
+++ b/src/main/java/de/ids_mannheim/korap/query/serialize/TreeTemplate.java
@@ -23,133 +23,145 @@
 
 /**
  * Map representation of syntax tree as returned by ANTLR
+ * 
  * @author Joachim Bingel (bingel@ids-mannheim.de)
  * @version 0.3.0
  * @since 0.1.0
  */
 public class TreeTemplate extends Antlr4AbstractQueryProcessor {
-	private static Logger log = LoggerFactory.getLogger(TreeTemplate.class);
-	/**
-	 * 
-	 * @param tree The syntax tree as returned by ANTLR
-	 * @param parser The ANTLR parser instance that generated the parse tree
-	 */
-	public TreeTemplate(String query) {
-		KoralObjectGenerator.setQueryProcessor(this);
-		process(query);
-	}
+    private static Logger log = LoggerFactory.getLogger(TreeTemplate.class);
 
-	@Override
-	public void process(String query) {
-		ParseTree tree = parseQuery(query);
-		super.parser = this.parser;
-		if (tree != null) {
-			log.debug("ANTLR parse tree: "+tree.toStringTree(parser));
-			processNode(tree);
-		} else {
-			addError(StatusCodes.MALFORMED_QUERY, "Could not parse query >>> "+query+" <<<.");
-		}
-	}
+    /**
+     * 
+     * @param tree
+     *            The syntax tree as returned by ANTLR
+     * @param parser
+     *            The ANTLR parser instance that generated the parse
+     *            tree
+     */
+    public TreeTemplate (String query) {
+        KoralObjectGenerator.setQueryProcessor(this);
+        process(query);
+    }
 
-	private void processNode(ParseTree node) {
-		// Top-down processing
-		if (visited.contains(node)) return;
-		else visited.add(node);
+    @Override
+    public void process(String query) {
+        ParseTree tree = parseQuery(query);
+        super.parser = this.parser;
+        if (tree != null) {
+            log.debug("ANTLR parse tree: " + tree.toStringTree(parser));
+            processNode(tree);
+        }
+        else {
+            addError(StatusCodes.MALFORMED_QUERY, "Could not parse query >>> "
+                    + query + " <<<.");
+        }
+    }
 
-		String nodeCat = getNodeCat(node);
-		openNodeCats.push(nodeCat);
+    private void processNode(ParseTree node) {
+        // Top-down processing
+        if (visited.contains(node))
+            return;
+        else
+            visited.add(node);
 
-		stackedObjects = 0;
+        String nodeCat = getNodeCat(node);
+        openNodeCats.push(nodeCat);
 
-		if (verbose) {
-			System.err.println(" "+objectStack);
-			System.out.println(openNodeCats);
-		}
+        stackedObjects = 0;
 
-		/*
-		 ****************************************************************
-		 **************************************************************** 
-		 * 			Processing individual node categories  				*
-		 ****************************************************************
-		 ****************************************************************
-		 */
+        if (verbose) {
+            System.err.println(" " + objectStack);
+            System.out.println(openNodeCats);
+        }
+        
+        /*
+         ****************************************************************
+         **************************************************************** 
+         *          Processing individual node categories               *
+         ****************************************************************
+         ****************************************************************
+         */
+        objectsToPop.push(stackedObjects);
 
-		objectsToPop.push(stackedObjects);
+        /*
+         ****************************************************************
+         **************************************************************** 
+         *  Recursion until 'request' node (root of tree) is processed  *
+         ****************************************************************
+         ****************************************************************
+         */
+        for (int i = 0; i < node.getChildCount(); i++) {
+            ParseTree child = node.getChild(i);
+            processNode(child);
+        }
 
-		/*
-		 ****************************************************************
-		 **************************************************************** 
-		 *  recursion until 'request' node (root of tree) is processed  *
-		 ****************************************************************
-		 ****************************************************************
-		 */
-		for (int i=0; i<node.getChildCount(); i++) {
-			ParseTree child = node.getChild(i);
-			processNode(child);
-		}
+        /*
+         ***************************************************************
+         ***************************************************************
+         * Stuff that happens after processing the children of a node  *
+         ***************************************************************
+         ***************************************************************
+         */
+        for (int i = 0; i < objectsToPop.pop(); i++) {
+            objectStack.pop();
+        }
 
+        openNodeCats.pop();
 
-		/*
-		 **************************************************************
-		 * Stuff that happens after processing the children of a node *
-		 **************************************************************
-		 */
+    }
 
+    @SuppressWarnings("unused")
+    private void putIntoSuperObject(LinkedHashMap<String, Object> object) {
+        putIntoSuperObject(object, 0);
+    }
 
-		for (int i=0; i<objectsToPop.pop(); i++) {
-			objectStack.pop();
-		}
+    @SuppressWarnings({ "unchecked" })
+    private void putIntoSuperObject(LinkedHashMap<String, Object> object,
+            int objStackPosition) {
+        if (objectStack.size() > objStackPosition) {
+            ArrayList<Object> topObjectOperands = (ArrayList<Object>) objectStack
+                    .get(objStackPosition).get("operands");
+            topObjectOperands.add(0, object);
 
+        }
+        else {
+            requestMap.put("query", object);
+        }
+    }
 
-		openNodeCats.pop();
+    private ParserRuleContext parseQuery(String q) {
+        // TODO replace AqlLexer with lexer for your Antlr4 grammar!
+        Lexer qlLexer = new AqlLexer((CharStream) null);
+        ParserRuleContext tree = null;
+        // Like p. 111
+        try {
+            // Tokenize input data
+            ANTLRInputStream input = new ANTLRInputStream(q);
+            qlLexer.setInputStream(input);
+            CommonTokenStream tokens = new CommonTokenStream(qlLexer);
+            // TODO replace AqlParser with parser for your Antlr4
+            // grammar!
+            parser = new AqlParser(tokens);
 
-	}
+            // Don't throw out erroneous stuff
+            parser.setErrorHandler(new BailErrorStrategy());
+            parser.removeErrorListeners();
 
-	@SuppressWarnings("unused")
-	private void putIntoSuperObject(LinkedHashMap<String, Object> object) {
-		putIntoSuperObject(object, 0);
-	}
+            // Get starting rule from parser
+            // TODO replace AqlParser with parser for your Antlr4
+            // grammar!
+            Method startRule = AqlParser.class.getMethod("start");
+            tree = (ParserRuleContext) startRule
+                    .invoke(parser, (Object[]) null);
+        }
 
-	@SuppressWarnings({ "unchecked" })
-	private void putIntoSuperObject(LinkedHashMap<String, Object> object, int objStackPosition) {
-		if (objectStack.size()>objStackPosition) {
-			ArrayList<Object> topObjectOperands = (ArrayList<Object>) objectStack.get(objStackPosition).get("operands");
-			topObjectOperands.add(0, object);
+        // Some things went wrong ...
+        catch (Exception e) {
+            System.err.println(e.getMessage());
+        }
 
-		} else {
-			requestMap.put("query", object);
-		}
-	}
-
-	private ParserRuleContext parseQuery (String q) {
-		//TODO replace AqlLexer with lexer for your Antlr4 grammar!
-		Lexer qlLexer = new AqlLexer((CharStream)null); 
-		ParserRuleContext tree = null;
-		// Like p. 111
-		try {
-			// Tokenize input data
-			ANTLRInputStream input = new ANTLRInputStream(q);
-			qlLexer.setInputStream(input);
-			CommonTokenStream tokens = new CommonTokenStream(qlLexer);
-			//TODO replace AqlParser with parser for your Antlr4 grammar!
-			parser = new AqlParser(tokens);
-
-			// Don't throw out erroneous stuff
-			parser.setErrorHandler(new BailErrorStrategy());
-			parser.removeErrorListeners();
-
-			// Get starting rule from parser
-			//TODO replace AqlParser with parser for your Antlr4 grammar!
-			Method startRule = AqlParser.class.getMethod("start"); 
-			tree = (ParserRuleContext) startRule.invoke(parser, (Object[])null);
-		}
-
-		// Some things went wrong ...
-		catch (Exception e) {
-			System.err.println( e.getMessage() );
-		}
-
-		// Return the generated tree
-		return tree;
-	}
+        // Return the generated tree
+        return tree;
+    }
 }
\ No newline at end of file
diff --git a/src/test/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessorTest.java b/src/test/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessorTest.java
index be4bcec..a21ff8c 100644
--- a/src/test/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessorTest.java
+++ b/src/test/java/de/ids_mannheim/korap/query/serialize/Cosmas2QueryProcessorTest.java
@@ -85,7 +85,7 @@
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:term", 			res.at("/query/wrap/@type").asText());
         assertEquals("deutscher",			res.at("/query/wrap/key").asText());
-        assertEquals(true,					res.at("/query/wrap/caseInsensitive").asBoolean());
+        assertEquals("flags:caseInsensitive",     res.at("/query/wrap/flags/0").asText());
         assertEquals("orth", 				res.at("/query/wrap/layer").asText());
         assertEquals("match:eq",			res.at("/query/wrap/match").asText());
 
@@ -96,11 +96,10 @@
         assertEquals("operation:sequence",	res.at("/query/operation").asText());
         assertEquals("koral:term", 			res.at("/query/operands/0/wrap/@type").asText());
         assertEquals("deutscher",			res.at("/query/operands/0/wrap/key").asText());
-        assertEquals(true,					res.at("/query/operands/0/wrap/caseInsensitive").asBoolean());
+        assertEquals("flags:caseInsensitive",     res.at("/query/operands/0/wrap/flags/0").asText());
         assertEquals("orth", 				res.at("/query/operands/0/wrap/layer").asText());
         assertEquals("match:eq",			res.at("/query/operands/0/wrap/match").asText());
         assertEquals("Bundestag",			res.at("/query/operands/1/wrap/key").asText());
-        assertEquals(true,					res.at("/query/operands/1/wrap/caseInsensitive").isMissingNode());
     }
 
     @Test
diff --git a/src/test/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessorTest.java b/src/test/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessorTest.java
index e2020f4..8f7a77a 100644
--- a/src/test/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessorTest.java
+++ b/src/test/java/de/ids_mannheim/korap/query/serialize/PoliqarpPlusQueryProcessorTest.java
@@ -180,7 +180,8 @@
         assertEquals("koral:token", 		res.at("/query/@type").asText());
         assertEquals("koral:term",			res.at("/query/wrap/@type").asText());
         assertEquals("deutscher",			res.at("/query/wrap/key").asText());
-        assertEquals("true",				res.at("/query/wrap/caseInsensitive").asText());
+        assertEquals(true,  				res.at("/query/wrap/flags:caseInsensitive").isMissingNode());
+        assertEquals("flags:caseInsensitive",     res.at("/query/wrap/flags/0").asText());
         assertEquals("orth", 				res.at("/query/wrap/layer").asText());
         assertEquals("match:eq",			res.at("/query/wrap/match").asText());
 
@@ -190,7 +191,7 @@
         assertEquals("koral:token", 		res.at("/query/@type").asText());
         assertEquals("koral:term",			res.at("/query/wrap/@type").asText());
         assertEquals("deutscher",			res.at("/query/wrap/key").asText());
-        assertEquals("true",				res.at("/query/wrap/caseInsensitive").asText());
+        assertEquals("flags:caseInsensitive",     res.at("/query/wrap/flags/0").asText());
         assertEquals("orth", 				res.at("/query/wrap/layer").asText());
         assertEquals("match:eq",			res.at("/query/wrap/match").asText());
 
@@ -200,7 +201,7 @@
         assertEquals("koral:token", 		res.at("/query/@type").asText());
         assertEquals("koral:term",			res.at("/query/wrap/@type").asText());
         assertEquals("deutscher",			res.at("/query/wrap/key").asText());
-        assertEquals("false",				res.at("/query/wrap/caseInsensitive").asText());
+        assertEquals(true,                  res.at("/query/wrap/flags/0").isMissingNode());
         assertEquals("orth", 				res.at("/query/wrap/layer").asText());
         assertEquals("match:eq",			res.at("/query/wrap/match").asText());
 
@@ -214,12 +215,12 @@
         assertEquals("deutscher",			operands.get(0).at("/wrap/key").asText());
         assertEquals("orth",				operands.get(0).at("/wrap/layer").asText());
         assertEquals("match:eq",			operands.get(0).at("/wrap/match").asText());
-        assertEquals(true,					operands.get(0).at("/wrap/caseInsensitive").asBoolean());
+        assertEquals("flags:caseInsensitive",     operands.get(0).at("/wrap/flags/0").asText());
         assertEquals("koral:token",			operands.get(1).at("/@type").asText());
         assertEquals("Bundestag",			operands.get(1).at("/wrap/key").asText());
         assertEquals("orth",				operands.get(1).at("/wrap/layer").asText());
         assertEquals("match:eq",			operands.get(1).at("/wrap/match").asText());
-        assertEquals(true,					operands.get(1).at("/wrap/caseInsensitive").isMissingNode());
+        assertEquals(true,					operands.get(1).at("/wrap/flags/0").isMissingNode());
 
         query = "deutscher/i Bundestag";
         qs.setQuery(query, "poliqarpplus");
@@ -231,12 +232,12 @@
         assertEquals("deutscher",			operands.get(0).at("/wrap/key").asText());
         assertEquals("orth",				operands.get(0).at("/wrap/layer").asText());
         assertEquals("match:eq",			operands.get(0).at("/wrap/match").asText());
-        assertEquals(true,					operands.get(0).at("/wrap/caseInsensitive").asBoolean());
+        assertEquals("flags:caseInsensitive",     operands.get(0).at("/wrap/flags/0").asText());
         assertEquals("koral:token",			operands.get(1).at("/@type").asText());
         assertEquals("Bundestag",			operands.get(1).at("/wrap/key").asText());
         assertEquals("orth",				operands.get(1).at("/wrap/layer").asText());
         assertEquals("match:eq",			operands.get(1).at("/wrap/match").asText());
-        assertEquals(true,					operands.get(1).at("/wrap/caseInsensitive").isMissingNode());
+        assertEquals(true,					operands.get(1).at("/wrap/flags:caseInsensitive").isMissingNode());
     }
 
     @Test
@@ -245,46 +246,46 @@
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("s",					res.at("/query/key").asText());
+        assertEquals("s",					res.at("/query/wrap/key").asText());
         
         query = "<\".*\">";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span",          res.at("/query/@type").asText());
-        assertEquals(".*",                  res.at("/query/key").asText());
-        assertEquals("type:regex",          res.at("/query/type").asText());
+        assertEquals(".*",                  res.at("/query/wrap/key").asText());
+        assertEquals("type:regex",          res.at("/query/wrap/type").asText());
 
         query = "<vp>";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
 
         query = "<cnx/c=vp>";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
-        assertEquals("cnx",					res.at("/query/foundry").asText());
-        assertEquals("c",					res.at("/query/layer").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
+        assertEquals("cnx",					res.at("/query/wrap/foundry").asText());
+        assertEquals("c",					res.at("/query/wrap/layer").asText());
 
         query = "<cnx/c!=vp>";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
-        assertEquals("cnx",					res.at("/query/foundry").asText());
-        assertEquals("c",					res.at("/query/layer").asText());
-        assertEquals("match:ne",			res.at("/query/match").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
+        assertEquals("cnx",					res.at("/query/wrap/foundry").asText());
+        assertEquals("c",					res.at("/query/wrap/layer").asText());
+        assertEquals("match:ne",			res.at("/query/wrap/match").asText());
 
         query = "<cnx/c!=vp class!=header>";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
-        assertEquals("cnx",					res.at("/query/foundry").asText());
-        assertEquals("c",					res.at("/query/layer").asText());
-        assertEquals("match:ne",			res.at("/query/match").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
+        assertEquals("cnx",					res.at("/query/wrap/foundry").asText());
+        assertEquals("c",					res.at("/query/wrap/layer").asText());
+        assertEquals("match:ne",			res.at("/query/wrap/match").asText());
         assertEquals("class",				res.at("/query/attr/key").asText());
         assertEquals("header",				res.at("/query/attr/value").asText());
         assertEquals("match:ne",			res.at("/query/attr/match").asText());
@@ -293,10 +294,10 @@
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
-        assertEquals("cnx",					res.at("/query/foundry").asText());
-        assertEquals("c",					res.at("/query/layer").asText());
-        assertEquals("match:ne",			res.at("/query/match").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
+        assertEquals("cnx",					res.at("/query/wrap/foundry").asText());
+        assertEquals("c",					res.at("/query/wrap/layer").asText());
+        assertEquals("match:ne",			res.at("/query/wrap/match").asText());
         assertEquals("class",				res.at("/query/attr/key").asText());
         assertEquals("header",				res.at("/query/attr/value").asText());
         assertEquals("match:eq",			res.at("/query/attr/match").asText());
@@ -305,10 +306,10 @@
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/@type").asText());
-        assertEquals("vp",					res.at("/query/key").asText());
-        assertEquals("cnx",					res.at("/query/foundry").asText());
-        assertEquals("c",					res.at("/query/layer").asText());
-        assertEquals("match:ne",			res.at("/query/match").asText());
+        assertEquals("vp",					res.at("/query/wrap/key").asText());
+        assertEquals("cnx",					res.at("/query/wrap/foundry").asText());
+        assertEquals("c",					res.at("/query/wrap/layer").asText());
+        assertEquals("match:ne",			res.at("/query/wrap/match").asText());
         assertEquals("koral:termGroup",		res.at("/query/attr/@type").asText());
         assertEquals("relation:and",		res.at("/query/attr/relation").asText());
         operands = Lists.newArrayList( res.at("/query/attr/operands").elements());
@@ -555,14 +556,14 @@
         assertEquals("frames:isAround",     res.at("/query/frames/0").asText());
         assertEquals(true,                  res.at("/query/frames/1").isMissingNode());
         assertEquals("koral:span",          res.at("/query/operands/0/@type").asText());
-        assertEquals("s",                   res.at("/query/operands/0/key").asText());
+        assertEquals("s",                   res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:token",         res.at("/query/operands/1/@type").asText());
         assertEquals(true,                  res.at("/query/operands/1/key").isMissingNode());
 
         query = "contains(<s>, []{3})";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals("s",                   res.at("/query/operands/0/key").asText());
+        assertEquals("s",                   res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group",         res.at("/query/operands/1/@type").asText());
         assertEquals("operation:repetition",res.at("/query/operands/1/operation").asText());
         assertEquals("koral:token",         res.at("/query/operands/1/operands/0/@type").asText());
@@ -571,7 +572,7 @@
         query = "contains(<s>, {1:[]{3}})";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals("s",                   res.at("/query/operands/0/key").asText());
+        assertEquals("s",                   res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group",         res.at("/query/operands/1/@type").asText());
         assertEquals("operation:class",     res.at("/query/operands/1/operation").asText());
         assertEquals("operation:repetition",res.at("/query/operands/1/operands/0/operation").asText());
@@ -660,7 +661,7 @@
         assertEquals("koral:group", 		res.at("/query/@type").asText());
         assertEquals("operation:position", 	res.at("/query/operation").asText());
         assertEquals("koral:span", 			res.at("/query/operands/0/@type").asText());
-        assertEquals("s", 					res.at("/query/operands/0/key").asText());
+        assertEquals("s", 					res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group", 		res.at("/query/operands/1/@type").asText());
         assertEquals("operation:repetition",res.at("/query/operands/1/operation").asText());
 
@@ -699,14 +700,14 @@
         assertEquals("frames:isAround",		res.at("/query/frames/0").asText());
         assertEquals(true, 					res.at("/query/frames/1").isMissingNode());
         assertEquals("koral:span", 			res.at("/query/operands/0/@type").asText());
-        assertEquals("s", 					res.at("/query/operands/0/key").asText());
+        assertEquals("s", 					res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:token", 		res.at("/query/operands/1/@type").asText());
 
         query = "contains(<s>,<np>)";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals("s", 		res.at("/query/operands/0/key").asText());
-        assertEquals("np", 		res.at("/query/operands/1/key").asText());
+        assertEquals("s", 		res.at("/query/operands/0/wrap/key").asText());
+        assertEquals("np", 		res.at("/query/operands/1/wrap/key").asText());
 
         query = "contains(<s>,[orth=der][orth=Mann])";
         qs.setQuery(query, "poliqarpplus");
@@ -714,7 +715,7 @@
         assertEquals("koral:group", 			res.at("/query/@type").asText());
         assertEquals("operation:position", 		res.at("/query/operation").asText());
         assertEquals("frames:isAround", 		res.at("/query/frames/0").asText());
-        assertEquals("s", 						res.at("/query/operands/0/key").asText());
+        assertEquals("s", 						res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group", 			res.at("/query/operands/1/@type").asText());
         assertEquals("operation:sequence", 		res.at("/query/operands/1/operation").asText());
         assertEquals("der", 					res.at("/query/operands/1/operands/0/wrap/key").asText());
@@ -726,7 +727,7 @@
         assertEquals("koral:group", 			res.at("/query/@type").asText());
         assertEquals("operation:position", 		res.at("/query/operation").asText());
         assertEquals("frames:isAround", 		res.at("/query/frames/0").asText());
-        assertEquals("s", 						res.at("/query/operands/0/key").asText());
+        assertEquals("s", 						res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group", 			res.at("/query/operands/1/@type").asText());
         assertEquals("operation:sequence", 		res.at("/query/operands/1/operation").asText());
         assertEquals("der", 					res.at("/query/operands/1/operands/0/wrap/key").asText());
@@ -738,12 +739,12 @@
         query = "contains(<s>,startswith(<np>,<pp>))";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals("s", 						res.at("/query/operands/0/key").asText());
+        assertEquals("s", 						res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:group", 			res.at("/query/operands/1/@type").asText());
         assertEquals("frames:startsWith", 		res.at("/query/operands/1/frames/0").asText());
         assertEquals("operation:position", 		res.at("/query/operands/1/operation").asText());
-        assertEquals("np", 						res.at("/query/operands/1/operands/0/key").asText());
-        assertEquals("pp", 						res.at("/query/operands/1/operands/1/key").asText());
+        assertEquals("np", 						res.at("/query/operands/1/operands/0/wrap/key").asText());
+        assertEquals("pp", 						res.at("/query/operands/1/operands/1/wrap/key").asText());
 
         query = "[base=Auto]overlaps(<s>, der)";
         qs.setQuery(query, "poliqarpplus");
@@ -755,7 +756,7 @@
         assertEquals("frames:overlapsLeft", 	res.at("/query/operands/1/frames/0").asText());
         assertEquals("frames:overlapsRight", 	res.at("/query/operands/1/frames/1").asText());
         assertEquals("koral:span", 				res.at("/query/operands/1/operands/0/@type").asText());
-        assertEquals("s", 						res.at("/query/operands/1/operands/0/key").asText());
+        assertEquals("s", 						res.at("/query/operands/1/operands/0/wrap/key").asText());
         assertEquals("koral:token", 			res.at("/query/operands/1/operands/1/@type").asText());
 
         query = "[base=Auto]            overlaps(<s>, der)";
@@ -768,7 +769,7 @@
         assertEquals("frames:overlapsLeft", 	res.at("/query/operands/1/frames/0").asText());
         assertEquals("frames:overlapsRight", 	res.at("/query/operands/1/frames/1").asText());
         assertEquals("koral:span", 				res.at("/query/operands/1/operands/0/@type").asText());
-        assertEquals("s", 						res.at("/query/operands/1/operands/0/key").asText());
+        assertEquals("s", 						res.at("/query/operands/1/operands/0/wrap/key").asText());
         assertEquals("koral:token", 			res.at("/query/operands/1/operands/1/@type").asText());
     };
 
@@ -930,7 +931,7 @@
         assertEquals("koral:token", 		res.at("/query/operands/0/@type").asText());
         assertEquals("Mann", 				res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:span", 			res.at("/query/operands/1/@type").asText());
-        assertEquals("vp", 					res.at("/query/operands/1/key").asText());
+        assertEquals("vp", 					res.at("/query/operands/1/wrap/key").asText());
 
         query = "<vp>[base=Mann]";
         qs.setQuery(query, "poliqarpplus");
@@ -938,7 +939,7 @@
         assertEquals("koral:group", 		res.at("/query/@type").asText());
         assertEquals("operation:sequence", 	res.at("/query/operation").asText());
         assertEquals("koral:span", 			res.at("/query/operands/0/@type").asText());
-        assertEquals("vp", 					res.at("/query/operands/0/key").asText());
+        assertEquals("vp", 					res.at("/query/operands/0/wrap/key").asText());
         assertEquals("koral:token", 		res.at("/query/operands/1/@type").asText());
         assertEquals("Mann", 				res.at("/query/operands/1/wrap/key").asText());
 
@@ -946,13 +947,13 @@
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
         assertEquals("koral:span", 			res.at("/query/operands/2/@type").asText());
-        assertEquals("pp", 					res.at("/query/operands/2/key").asText());
+        assertEquals("pp", 					res.at("/query/operands/2/wrap/key").asText());
 
         query = "<vp>[base=Mann]<pp><np>";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals("pp", 					res.at("/query/operands/2/key").asText());
-        assertEquals("np", 					res.at("/query/operands/3/key").asText());
+        assertEquals("pp", 					res.at("/query/operands/2/wrap/key").asText());
+        assertEquals("np", 					res.at("/query/operands/3/wrap/key").asText());
     }
 
     @Test 
@@ -1069,9 +1070,9 @@
         query = "focus(1000:startswith(<s>,{1000:<np>}))";
         qs.setQuery(query, "poliqarpplus");
         res = mapper.readTree(qs.toJSON());
-        assertEquals(128, 					res.at("/query/classRef/0").asInt());
-        assertEquals(128, 					res.at("/query/operands/0/operands/1/classOut").asInt());
-        assertEquals(128,                     res.at("/meta/highlight/0").asInt());
+        assertEquals(1000, 					res.at("/query/classRef/0").asInt());
+        assertEquals(1000, 					res.at("/query/operands/0/operands/1/classOut").asInt());
+        assertEquals(1000,                  res.at("/meta/highlight/0").asInt());
 
         query = "focus(3: startswith(<s>, {3:[base=der]{1:[mate/p=ADJA]{2:[tt/p=NN]}}}))";
         qs.setQuery(query, "poliqarpplus");
@@ -1127,7 +1128,7 @@
         assertEquals("operation:focus", 	res.at("/query/operation").asText());
         assertEquals(1, 					res.at("/query/spanRef/0").asInt());
         assertEquals(true, 					res.at("/query/spanRef/1").isMissingNode());
-        assertEquals("s", 					res.at("/query/operands/0/key").asText());
+        assertEquals("s", 					res.at("/query/operands/0/wrap/key").asText());
 
         query = "submatch(1,4:<s>)";
         qs.setQuery(query, "poliqarpplus");
@@ -1145,7 +1146,7 @@
         assertEquals(1, 					res.at("/query/spanRef/0").asInt());
         assertEquals(4, 					res.at("/query/spanRef/1").asInt());
         assertEquals("frames:isAround", 	res.at("/query/operands/0/frames/0").asText());
-        assertEquals("s", 					res.at("/query/operands/0/operands/0/key").asText());
+        assertEquals("s", 					res.at("/query/operands/0/operands/0/wrap/key").asText());
         assertEquals("Haus", 				res.at("/query/operands/0/operands/1/wrap/key").asText());
     }
     @Test
@@ -1157,8 +1158,8 @@
         assertEquals("operation:relation", 	res.at("/query/operation").asText());
         assertEquals("koral:relation", 		res.at("/query/relation/@type").asText());
         assertEquals("c",                   res.at("/query/relation/wrap/layer").asText());
-        assertEquals("s", 					res.at("/query/operands/0/key").asText());
-        assertEquals("np", 					res.at("/query/operands/1/key").asText());
+        assertEquals("s", 					res.at("/query/operands/0/wrap/key").asText());
+        assertEquals("np", 					res.at("/query/operands/1/wrap/key").asText());
 
         query = "relatesTo([base=Baum],<np>)";
         qs.setQuery(query, "poliqarpplus");
@@ -1167,7 +1168,7 @@
         assertEquals("operation:relation", 	res.at("/query/operation").asText());
         assertEquals("koral:relation", 		res.at("/query/relation/@type").asText());
         assertEquals("Baum", 				res.at("/query/operands/0/wrap/key").asText());
-        assertEquals("np", 					res.at("/query/operands/1/key").asText());
+        assertEquals("np", 					res.at("/query/operands/1/wrap/key").asText());
 
         query = "relatesTo(Baum,<np>)";
         qs.setQuery(query, "poliqarpplus");