include "primitives.alh"
include "modelling.alh"
include "object_operations.alh"
include "conformance_scd.alh"
include "utils.alh"
include "typing.alh"
include "mini_modify.alh"

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

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

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

	return pick!

Boolean function main(model : Element):
	Element all_blocks
	String element_name
	Float current_time
	String time_block

	all_blocks = allInstances(model, "PartialRuntime/Block")
	while (set_len(all_blocks) > 0):
		element_name = set_pop(all_blocks)
		if (set_len(allOutgoingAssociationInstances(model, element_name, "P2F_block")) > 0):
			// Element already exists in full, so copy existing attributes
            if (is_nominal_instance(model, element_name, "PartialRuntime/ICBlock")):
                instantiate_attribute(model, element_name, "last_in", read_attribute(model, map_P2F(model, element_name), "last_in"))
            if (is_nominal_instance(model, element_name, "PartialRuntime/IntegratorBlock")):
                instantiate_attribute(model, element_name, "last_out", read_attribute(model, map_P2F(model, element_name), "last_out"))
            instantiate_attribute(model, element_name, "signal", read_attribute(model, map_P2F(model, element_name), "signal"))
		else:
			// Element doesn't exist, so initialize with 0.0
            instantiate_attribute(model, element_name, "signal", 0.0)
			instantiate_link(model, "P2F_block", "", element_name, element_name)

	if (set_len(allInstances(model, "FullRuntime/Time")) > 0):
		// Time already exists, so copy the value
		current_time = read_attribute(model, set_pop(allInstances(model, "FullRuntime/Time")), "current_time")
	else:
		// No time yet, so initialize
		current_time = 0.0

	time_block = instantiate_node(model, "PartialRuntime/Time", "")
	instantiate_attribute(model, time_block, "start_time", current_time)
	instantiate_attribute(model, time_block, "current_time", current_time)

	Element all_elements
	String elem
	all_elements = dict_keys(model["model"])
	while (set_len(all_elements) > 0):
		elem = set_pop(all_elements)
		if (string_startswith(read_type(model, elem), "PartialRuntime/")):
			retype(model, elem, "NewFullRuntime/" + cast_string(list_read(string_split_nr(read_type(model, elem), "/", 1), 1)))

	return True!
