/**
   * Create a compiled stylesheet from an input stream.
   *
   * @param source the source stream
   * @return the compiled stylesheet
   */
  public Templates newTemplates(Source source) throws TransformerConfigurationException {
    String systemId = source.getSystemId();

    try {
      if (systemId != null) {
        StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

        if (stylesheet != null) return stylesheet;
      }

      if (source instanceof DOMSource) {
        Node node = ((DOMSource) source).getNode();

        return generateFromNode(node, systemId);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        Document doc = new QDocument();
        DOMBuilder builder = new DOMBuilder();
        builder.init(doc);
        reader.setContentHandler(builder);

        reader.parse(inputSource);

        return generateFromNode(doc, systemId);
      }

      ReadStream rs = openPath(source);
      try {
        Path path = rs.getPath();

        Document doc = parseXSL(rs);

        if (systemId != null) {
          String mangledName = getMangledName(systemId);
          Path genPath = getWorkPath().lookup(mangledName);

          genPath.setUserPath(systemId);

          return generate(doc, genPath);
        } else return generateFromNode(doc, null);
      } finally {
        if (rs != null) rs.close();
      }
    } catch (TransformerConfigurationException e) {
      throw e;
    } catch (Exception e) {
      throw new XslParseException(e);
    }
  }
  private Templates generateFromNode(Node node, String systemId)
      throws IOException, TransformerConfigurationException {
    Path tempPath = writeTempFile(node);

    String tempId = tempPath.getTail();

    StylesheetImpl stylesheet = loadPrecompiledStylesheet(tempId, tempId, false);

    if (systemId != null) tempPath.setUserPath(systemId);

    if (stylesheet != null) return stylesheet;

    return generate(node, tempPath);
  }