include "primitives.alh"
include "modelling.alh"
include "object_operations.alh"

String function map_D2P(model : Element, name : String):
	Element destinations
	String pick

	destinations = allAssociationDestinations(model, name, "D2P_block")

	pick = name
	while (pick == name):
		pick = set_pop(destinations)

	return pick!

Boolean function main(model : Element):
	Element all_blocks
	String element_name
	String new_element_name
	String mm_type_name
	Element all_links

	all_blocks = allInstances(model, "Design/Block")
	while (set_len(all_blocks) > 0):
		element_name = set_pop(all_blocks)
		mm_type_name = "PartialRuntime/" + cast_string(list_read(string_split(read_type(model, element_name), "/"), 1))

		if (set_len(allOutgoingAssociationInstances(model, element_name, "D2P_block")) == 0):
			// New design element, so create in partial runtime model as well
			new_element_name = instantiate_node(model, mm_type_name, "")
			instantiate_link(model, "D2P_block", "", element_name, new_element_name)

		// Always update the value of attributes of PartialRuntime
		new_element_name = map_D2P(model, element_name)
		if (mm_type_name == "PartialRuntime/ConstantBlock"):
            instantiate_attribute(model, new_element_name, "value", read_attribute(model, element_name, "value"))
		elif (mm_type_name == "PartialRuntime/ProbeBlock"):
            instantiate_attribute(model, new_element_name, "name", read_attribute(model, element_name, "name"))

	all_blocks = allInstances(model, "PartialRuntime/Block")
	while (set_len(all_blocks) > 0):
		element_name = set_pop(all_blocks)
		if (set_len(allIncomingAssociationInstances(model, element_name, "D2P_block")) == 0):
			// Old partial runtime element, so remove
			model_delete_element(model, element_name)

	// Delete all existing links
	all_links = allInstances(model, "PartialRuntime/Link")
	while (set_len(all_links) > 0):
		model_delete_element(model, set_pop(all_links))

	all_links = allInstances(model, "PartialRuntime/InitialCondition")
	while (set_len(all_links) > 0):
		model_delete_element(model, set_pop(all_links))

	// Recreate all of them
    all_links = allInstances(model, "Design/Link")
    while (set_len(all_links) > 0):
        element_name = set_pop(all_links)
        instantiate_link(model, "PartialRuntime/Link", "", map_D2P(model, readAssociationSource(model, element_name)), map_D2P(model, readAssociationDestination(model, element_name)))

    all_links = allInstances(model, "Design/InitialCondition")
    while (set_len(all_links) > 0):
        element_name = set_pop(all_links)
        instantiate_link(model, "PartialRuntime/InitialCondition", "", map_D2P(model, readAssociationSource(model, element_name)), map_D2P(model, readAssociationDestination(model, element_name)))


	return True!
