namespace eval hook {}

proc hook::add {hook func {seq 50}} {
    variable $hook

    lappend $hook [list $func $seq]
    set $hook [lsort -real -index 1 [lsort -unique [set $hook]]]
}

proc hook::set_flag {hook flag} {
    variable F
    set idx [lsearch -exact $F(flags,$hook) $flag]
    set F(flags,$hook) [lreplace $F(flags,$hook) $idx $idx]
}

proc hook::unset_flag {hook flag} {
    variable F
    if {![lcontain $F(flags,$hook) $flag]} {
	lappend F(flags,$hook) $flag
    }
}

proc hook::is_flag {hook flag} {
    variable F
    return [expr ![lcontain $F(flags,$hook) $flag]]
}

proc hook::run {hook args} {
    variable F
    variable $hook

    if {![info exists $hook]} {
	return
    }

    set F(flags,$hook) {}

    foreach func_prio [set $hook] {
	set func [lindex $func_prio 0]
	set code [catch { eval $func $args } state]
        debugmsg hook "$hook: $func -> $state (code $code)"
	if {$code} {
	    ::bgerror "Hook $hook failed\nProcedure\
		       $func returned code $code\n$state"
	}
	if {(!$code) && ([cequal $state stop])} {
	    break
	}
    }
}

