@SuppressWarnings("unchecked")
  private void internalRead(
      InputStream buffer, List<NavigationFormat> formats, ParserContext context)
      throws IOException {
    int routeCountBefore = context.getRoutes().size();
    NavigationFormat firstSuccessfulFormat = null;

    try {
      for (NavigationFormat<BaseRoute> format : formats) {
        notifyReading(format);

        log.fine(format("Trying to read with %s", format));
        try {
          format.read(buffer, context);

          // if no route has been read, take the first that didn't throw an exception
          if (firstSuccessfulFormat == null) firstSuccessfulFormat = format;
        } catch (Exception e) {
          log.severe(format("Error reading with %s: %s, %s", format, e.getClass(), e));
        }

        if (context.getRoutes().size() > routeCountBefore) {
          context.addFormat(format);
          break;
        }

        try {
          buffer.reset();
        } catch (IOException e) {
          log.severe("Cannot reset() stream to mark()");
          break;
        }
      }
    } finally {
      //noinspection ThrowFromFinallyBlock
      buffer.close();
    }

    if (context.getRoutes().size() == 0 && firstSuccessfulFormat != null)
      context.addFormat(firstSuccessfulFormat);
  }