@Override
  public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {

    boolean useJavaCC = "--useJavaCC".equals(getArg(args, 0, null));
    if (args.size() > (useJavaCC ? 3 : 2)
        || (args.size() == 1 && (args.get(0).equals("--help") || args.get(0).equals("-help")))) {
      err.println("Usage: idl [--useJavaCC] [in [out]]");
      err.println();
      err.println("If an output path is not specified, outputs to stdout.");
      err.println("If no input or output is specified, takes input from");
      err.println("stdin and outputs to stdout.");
      err.println("The special path \"-\" may also be specified to refer to");
      err.println("stdin and stdout.");
      return -1;
    }

    String inputName = getArg(args, useJavaCC ? 1 : 0, "-");
    File inputFile = "-".equals(inputName) ? null : new File(inputName);
    String outputName = getArg(args, useJavaCC ? 2 : 1, "-");
    File outputFile = "-".equals(outputName) ? null : new File(outputName);

    Schema m = null;
    Protocol p;
    if (useJavaCC) {
      // noinspection deprecation
      try (Idl parser = new Idl(inputFile)) {
        p = parser.CompilationUnit();
        for (String warning : parser.getWarningsAfterParsing()) {
          err.println("Warning: " + warning);
        }
      }
    } else {
      IdlReader parser = new IdlReader();
      IdlFile idlFile = inputFile == null ? parser.parse(in) : parser.parse(inputFile.toPath());
      for (String warning : idlFile.getWarnings()) {
        err.println("Warning: " + warning);
      }
      p = idlFile.getProtocol();
      m = idlFile.getMainSchema();
    }

    PrintStream parseOut = out;
    if (outputFile != null) {
      parseOut = new PrintStream(Files.newOutputStream(outputFile.toPath()));
    }

    if (m == null && p == null) {
      err.println("Error: the IDL file does not contain a schema nor a protocol.");
      return 1;
    }
    try {
      parseOut.print(m == null ? p.toString(true) : m.toString(true));
    } finally {
      if (parseOut != out) // Close only the newly created FileOutputStream
        parseOut.close();
    }
    return 0;
  }
@Test
  void writeIdlAsProtocol() throws Exception {
    String idl = "src/test/idl/protocol.avdl";
    String protocol = "src/test/idl/protocol.avpr";
    String outfile = "target/test-protocol.avpr";

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    List<String> arglist = Arrays.asList(idl, outfile);
    new IdlTool().run(null, null, new PrintStream(buffer), arglist);

    assertEquals(readFileAsString(protocol), readFileAsString(outfile));

    String warnings = readPrintStreamBuffer(buffer);
    assertEquals("Warning: Line 1, char 1: Ignoring out-of-place documentation comment."
        + "\nDid you mean to use a multiline comment ( /* ... */ ) instead?", warnings);
  }