# Append a keyed list element to a list.
# Replace any existing element with this key

################################################################
# proc appendKeyedPair {list key value}--
#    Return a new keyed list with a key and value appended to the end 
#    of the provided keyed list
# Arguments
#   listName	The list to have new values appended to it
#   key		The key for the new key/value pair
#   value	The value to associate with this key
# 
# Results
#   The contents of listName are modified
# 
proc appendKeyedPair {listName key value} {
    upvar $listName list
    if {[set pos [lsearch $list $key ]] >= 0} {
        # Keys are on even list locations
        if {($pos & 1) == 0} {
	  # If key/Val pair exists, remove them.
          set list [lreplace $list $pos $pos+1]
	}
    }
    lappend list $key $value
    return $list
}

################################################################
# proc getValue {listName key}--
#    Retrieve the value associated with a key
# Arguments
#   list	The keyed list
#   key		The key to search for
# 
# Results
#   No side effects.
# 

proc getValue {listName key} {
    upvar $listName list

    set start 0
    for {set pos [lsearch $list $key]} \
        {($pos >= 0) && (($pos & 1) == 1)} \
        {set pos [lsearch -start $pos+1 $list $key]} {
    }
    if {$pos >= 0} {
      return [lindex $list $pos+1]
    } else {
      return ""
    }
}

################################################################
# proc deleteElement {listName key}--
#    Return a keyed list with this key and associated value removed
#    from the provided list
# Arguments
#   listName	Name of the keyed list
#   key		A key into the list
# 
# Results
#   no side effects
# 
proc deleteElement {listName key} {
    upvar $listName list
    set pos [lsearch $list $key]
    if {($pos >= 0) && (($pos & 1) == 0)} {
       set list [lreplace $list $pos $pos+1]
    }
    return $list
}


################################################################
# proc replaceValue {listName key newVal}--
#    Return a keyed list in which the value associated with this
#    key has been replaced by a new value.
# Arguments
#   listName	The name of the keyed list to modify
#   key		A key to search for
#   newVal	A new value to replace the original value for this key.
# 
# Results
#   no side effects.
# 
proc replaceValue {listName key newVal} {
    upvar $listName list
    
    for {set pos [lsearch $list $key]} \
        {($pos >= 0) && (($pos & 1) == 1)} \
        {set pos [lsearch -start $pos+1 $list $key]} {
    }
    if {($pos >= 0)} {
       incr pos
       set list [lreplace $list $pos $pos $newVal]
    } else {
       lappend list $key $newVal
    }
    return $list
}
