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

Boolean function main(model : Element):
	Element transitions
	Element links
	String transition
	String link
	String place
	Boolean enabled

	transitions = allInstances(model, "PetriNet/Transition")
	// Iterate over all transitions
	while (set_len(transitions) > 0):
		// Check if it is enabled
		transition = set_pop(transitions)
		log("Check transition " + cast_string(transition))

		// Check all incoming P2T links
		links = allIncomingAssociationInstances(model, transition, "PetriNet/P2T")
		enabled = True
		while (set_len(links) > 0):
			link = set_pop(links)

			if (cast_integer(read_attribute(model, link, "weight")) > cast_integer(read_attribute(model, readAssociationSource(model, link), "tokens"))):
				// Too few tokens, so skip
				enabled = False
				break!

		if (enabled):
			log("Enabled!")
			// All checks OK, so update the out locations
			links = allOutgoingAssociationInstances(model, transition, "PetriNet/T2P")
			while (set_len(links) > 0):
				link = set_pop(links)
				place = readAssociationDestination(model, link)
				instantiate_attribute(model, place, "tokens", cast_integer(read_attribute(model, place, "tokens")) + cast_integer(read_attribute(model, link, "weight")))
				log("New tokens TGT: " + cast_string(read_attribute(model, place, "tokens")))

			// All checks OK, and update the in locations
			links = allIncomingAssociationInstances(model, transition, "PetriNet/P2T")
			while (set_len(links) > 0):
				link = set_pop(links)
				place = readAssociationSource(model, link)
				instantiate_attribute(model, place, "tokens", cast_integer(read_attribute(model, place, "tokens")) - cast_integer(read_attribute(model, link, "weight")))
				log("New tokens SRC: " + cast_string(read_attribute(model, place, "tokens")))

			return True!

	return False!
