include "io.alh"
include "primitives.alh"
include "metamodels.alh"
include "core_algorithm.alh"
include "random.alh"

Void function task_management():
	String taskname
	Element task_root
	Element task_frame
	Element output_value
	Element input_value
	Boolean gen_output

	// Initialize the basic formalisms before allowing new users
	initialize_MMs()
	initialize_core()
	taskname = "task_manager"
	
	while (True):
		gen_output = True
		while (True):
			if (bool_not(other_has_output("task_manager"))):
				while (dict_in(read_root(), taskname)):
					taskname = cast_string(random_string(20))
				break!
			elif (has_input()):
				taskname = input()
				if (dict_in(read_root(), taskname)):
					sleep(0.05)
				else:
					gen_output = False
					break!
			else:
				sleep(0.05)
			
		// Task is gone, so make sure that we create a new one already

		task_root = create_node()
		task_frame = create_node()
		output_value = create_node()
		input_value = create_node()
		dict_add_fast(task_root, "frame", task_frame)
		dict_add_fast(task_root, "globals", create_node())
		dict_add_fast(task_root, "output", output_value)
		dict_add_fast(task_root, "last_output", output_value)
		dict_add_fast(task_root, "input", input_value)
		dict_add_fast(task_root, "last_input", input_value)
		dict_add_fast(task_frame, "evalstack", create_node())
		dict_add_fast(task_frame, "returnvalue", create_node())
		dict_add_fast(task_frame, "phase", "init")
		dict_add_fast(task_frame, "IP", dict_read(dict_read(read_root(), "__hierarchy"), "__IP"))
		dict_add_fast(task_frame, "symbols", create_node())

		//Add this only at the end, as otherwise the task will already be detected
		dict_add_fast(read_root(), taskname, task_root)
		if (gen_output):
			output(taskname)
	return!
