class VectorDrawableTransformer {

  public static String merge(@NotNull String drawable1, @NotNull String drawable2) {
    KXmlParser parser = new KXmlParser();

    try {
      parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
      parser.setInput(CharSequences.getReader(drawable1, true));
      int token;
      // Skip to the first tag.
      //noinspection StatementWithEmptyBody
      while ((token = parser.nextToken()) != XmlPullParser.END_DOCUMENT && token != XmlPullParser.START_TAG) {
      }
      if (parser.getEventType() != XmlPullParser.START_TAG || !"vector".equals(parser.getName()) || parser.getPrefix() != null) {
        return drawable1; // Not a vector drawable.
      }

      StringBuilder result = new StringBuilder(drawable1.length() + drawable2.length());

      Indenter indenter = new Indenter(drawable1);
      // Copy contents of the first drawable before the </vector> tag.
      int startLine = 1;
      int startColumn = 1;
      while ((token = parser.nextToken()) != XmlPullParser.END_DOCUMENT && token != XmlPullParser.END_TAG ||
             parser.getDepth() > 1) {
        int endLineNumber = parser.getLineNumber();
        int endColumnNumber = parser.getColumnNumber();
        indenter.copy(startLine, startColumn, endLineNumber, endColumnNumber, "", result);
        startLine = endLineNumber;
        startColumn = endColumnNumber;
      }

      parser.setInput(CharSequences.getReader(drawable2, true));
      //noinspection StatementWithEmptyBody
      while ((token = parser.nextToken()) != XmlPullParser.END_DOCUMENT && token != XmlPullParser.START_TAG) {
      }
      // Skip to the first tag.
      if (parser.getEventType() != XmlPullParser.START_TAG || !"vector".equals(parser.getName()) || parser.getPrefix() != null) {
        return drawable1; // Not a vector drawable.
      }
      startLine = parser.getLineNumber();
      startColumn = parser.getColumnNumber();

      indenter = new Indenter(drawable2);
      // Copy contents of the second drawable after the opening <vector> tag.
      while (parser.nextToken() != XmlPullParser.END_DOCUMENT) {
        int endLineNumber = parser.getLineNumber();
        int endColumnNumber = parser.getColumnNumber();
        indenter.copy(startLine, startColumn, endLineNumber, endColumnNumber, "", result);
        startLine = endLineNumber;
        startColumn = endColumnNumber;
      }

      return result.toString();
    }
    catch (XmlPullParserException | IOException e) {
      return drawable1;  // Ignore and return the original drawable.
    }
  }

  private  VectorDrawableTransformer();

}