candidates.add(t);
if (selected == null) selected = t; else { if (t.precedence < selected.precedence || t.priority < selected.priority) continue; selected = t; }
  TemplateNode getTemplate(QName mode, Node context, boolean applyImports)    throws TransformerException  {    if (debug)      {        System.err.println("getTemplate: mode="+mode+" context="+context);      }    Set candidates = new TreeSet();    for (Iterator j = templates.iterator(); j.hasNext(); )      {        Template t = (Template) j.next();        boolean isMatch = t.matches(mode, context);        if (applyImports)          {            if (currentTemplate == null)              {                String msg = "current template may not be null " +                  "during apply-imports";                throw new TransformerException(msg);              }            if (!currentTemplate.imports(t))              {                isMatch = false;              }          }        //System.err.println("\t"+context+" "+t+"="+isMatch);        if (isMatch)          {            candidates.add(t);          }      }    //System.err.println("\tcandidates="+candidates);    if (candidates.isEmpty())      {        // Apply built-in template        // Current template is unchanged        if (debug)          {            System.err.println("\tbuiltInTemplate context="+context);          }        switch (context.getNodeType())          {          case Node.ELEMENT_NODE:          case Node.DOCUMENT_NODE:          case Node.DOCUMENT_FRAGMENT_NODE:          case Node.PROCESSING_INSTRUCTION_NODE:          case Node.COMMENT_NODE:            return builtInNodeTemplate;          case Node.TEXT_NODE:          case Node.ATTRIBUTE_NODE:            return builtInTextTemplate;          default:            return null;          }      }    else      {        Template t = (Template) candidates.iterator().next();        // Set current template        currentTemplate = t;        if (debug)          {            System.err.println("\ttemplate="+t+" context="+context);          }        return t.node;      }  }