You need to understand how the tcl interpreter defines "words" or arguments passed to the commands to fully understand this. (read and understand this entire page: http://tcl.tk/man/tcl8.4/TclCmd/Tcl.htm )
You've misplaced a } (meant for one of your ifs) and made the 'elseif' part (including the word 'elseif') of that 'if' become arguments passed to foreach. In your code, 6 arguments are passed to 'foreach' and that doesn't work because foreach expects an odd number of arguments (pairs of variable names/values + a command).
Notice how foreach lines up with '} elseif {...' when proper indentation is applied. (my previous post)
Check those braces one more time.
Had a look over i again and again, and still dont see the problem,
i did add another close brace to close that if, but then got
an error about '"chan" no such var'
this code isnt mine anyway, so i dont fully understand it
i know the basics, but heres the code as i have it un edited.