package require emu::autobuild
proc AutoBuildInit {templ} {
}

proc AutoBuild {templ hier} {

    # link tones to words, this will include H-/L-
    LinkFromTimes $hier Word Tone
    
    # make sure that the final tone is linked to something, put it 
    # on the final word if it isn't
    set finaltone [lindex [$hier segments Tone] end]
    set finalword [lindex [$hier segments Word] end]
    if { [$hier seginfo $finaltone parents Word] == {} } {
	$hier seginfo $finaltone parents Word $finalword 
    }

       
    # find words dominating L- or H- and make a phrase which dominates
    # all words since the last one of these
    set words {}
    set isegs {}
#    set pwordchildren {}
    foreach w [$hier segments Word] {

        lappend words $w

        set tones [$hier seginfo $w children Tone]

        foreach t $tones {

            set label [$hier seginfo $t label Tone]

            ## if this label contains H- or L- or H% or L%
            if [regexp {([HL]-)?([HL]%)?} $label ignore inter inton] {
                if {$inter != {}} {
                    ## create an intermediate level segment
                    set interseg [$hier append Intermediate $inter]
                    ## add the words so far as children
                    $hier seginfo $interseg children Word $words
                    set words {}
                    ## append it to the intermediate phrase list
                    lappend isegs $interseg
                    ## make the tone a child of this phase segment
                    $hier seginfo $interseg children Tone $t
                }
                if {$inton != {}} {
                    ## create an intonational level segment
                    set intonseg [$hier append Intonational $inton]
                    ## and intermediate phrases as children
                    $hier seginfo $intonseg children Intermediate $isegs
                    set isegs {}
                    ## make the tone a child of this phase segment
                    $hier seginfo $intonseg children Tone $t
                }
                if {$inton != {} || $inter != {}} {
                    ## detach the boundary tone from the word
                    $hier delete relation $w $t
		}
	    }
        }
        if {[$hier seginfo $w label Word]  == {<SIL>} } {
            if {$words == {}} {
                ## we've just finished an intermediate phrase so unlink
                ## this silence from the phrase
                $hier delete relation $w $interseg
            }
        }
    }
}

