import re


def inject(attribute_name, contents, at_attribute,into_stream,replace=True):
	"""
	Inject new attributes and values into a specified SGML element in TT SGML format

	:param attribute_name: name of the attribute to insert
	:param contents: string, one value per line to insert as attribute values
	:param at_attribute: attribute in target element to insert this attribute before (can be same attribute name, replace in place)
	:param into_stream: TT SGML string with elements to add attributes to
	:param replace: boolean, whether to replace existing values of attribute_name when already present
	:return: TT SGML with added attributes
	"""
	insertions = contents.split('\n')
	injected = ""
	i=0
	for line in into_stream.split("\n"):
		if at_attribute + "=" in line:
			if i >= len(insertions):
				raise Exception("Error out of bounds at element " + str(i) + " in document beginning " + into_stream[:1000])
			if len(insertions[i])>0:
				if at_attribute == attribute_name:  # Replace old value of attribute with new one
					line = re.sub(attribute_name+'="[^"]*"',attribute_name+'="'+insertions[i]+'"',line)
				else:  # Place before specific at_attribute
					if replace or " " + attribute_name + "=" not in line:
						line = re.sub(at_attribute+"=",attribute_name+'="'+insertions[i]+'" '+at_attribute+"=",line)
			i += 1
		injected += line + "\n"
	return injected