protected String addClosing()

in src/main/java/com/atlassian/uwc/converters/smf/FixNesting.java [84:155]


	protected String addClosing(TreeMap<Integer, String> start, TreeMap<Integer, String> end, String input) {
		//foreach key in start, note value
		TreeMap<Integer, String> combined = new TreeMap<Integer, String>();
		combined.putAll(start);
		combined.putAll(end);
		Vector<Integer> indexes = new Vector<Integer>();
		if (!combined.isEmpty())
			indexes.addAll(combined.keySet());
		HashMap<String, Integer> tree = new HashMap<String, Integer>();
		for (int i = 0; i < indexes.size(); i++) {
			int index = indexes.get(i);
			String assocTag = combined.get(index);
			int count = 0;
			String key = assocTag.replaceFirst("^<\\/?", "");
			key = key.replaceFirst(">$", "");
			if (tree.containsKey(key)) count = tree.get(key);
			if (assocTag.startsWith("</")) count--;
			else count++;
			tree.put(key, count);
		}
		Set<String> tags = tree.keySet();
		TreeSet<String> sortedTags = new TreeSet<String>(new NestingOrderComparator());
		sortedTags.addAll(tags);
		Set<Integer> ends = end.keySet();
		Vector<Integer> endsVec = new Vector<Integer>();
		endsVec.addAll(ends);
		int adjustment = 0;
		TreeSet<String> nonZeroTags = new TreeSet<String>();
		for (String tag : tree.keySet()) if (tree.get(tag) != 0) nonZeroTags.add(tag);
		for (String tag : sortedTags) {
			int problem = tree.get(tag);
			if (problem > 0) {
				boolean justadd = isJustAdd(nonZeroTags);
				if (justadd) {
					String addition = "</" + tag + ">";
					input += addition;
					adjustment += addition.length();
				}
				else { 
					//find the last ul or ol
					for (int i = endsVec.size()-1; i >=0 ; i--) {
						Integer index = (Integer) endsVec.get(i);
						if (outerlist.matcher(end.get(index)).find()) {
							String pre = input.substring(0, index+adjustment);
							String post = input.substring(index+adjustment);
							String addition = "</" + tag + ">";
							adjustment += addition.length();
							input = pre + addition + post;
							break;
						}
					}
				}
			}
			else if (problem < 0) {
				for (int i = endsVec.size()-1; i >=0 ; i--) {
					Integer index = (Integer) endsVec.get(i);
					if (end.get(index).contains(tag)) {
						String pre = input.substring(0, index+adjustment);
						String post = input.substring(index+adjustment);
						String find = "<\\/" + tag + ">";
						String newpost = post.replaceFirst(find, "");
						adjustment -= post.length() - newpost.length();
						input = pre + newpost;
						break;
					}
				}
			}
			//ignore 0
			nonZeroTags.remove(tag);
		}
		return input;
	}