import operator


def output_SGML(conll_tokens, markstart_dict, markend_dict):
	"""
	Outputs analysis results as CWB SGML (with nesting), one token per line and markables in <referent> tags

	:param conll_tokens: List of all processed ParsedToken objects in the document
	:param markstart_dict: Dictionary from markable starting token ids to Markable objects
	:param markend_dict: Dictionary from markable ending token ids to Markable objects
	:return: serialized SGML
	"""

	output_string = ""
	for out_tok in conll_tokens:
		if int(out_tok.id) in markstart_dict:
			for out_mark in sorted(markstart_dict[int(out_tok.id)], key=operator.attrgetter('end'), reverse=True):
				output_string += '<referent id="' + str(out_mark.id) + '" entity="' + out_mark.entity + '" group="' + str(out_mark.group)
				if not out_mark.antecedent == "none":
					output_string += '" antecedent="' + str(out_mark.antecedent.id) + '" type="' + out_mark.coref_type
				output_string += '">\n'
		if int(out_tok.id) > 0:
			output_string += out_tok.text + "\n"
		if int(out_tok.id) in markend_dict:
			for out_mark in markend_dict[int(out_tok.id)]:
				output_string += "</referent>\n"

	return output_string