your script is little bloated to really see where is the problem.
can't you show shorter example where it's not working as expected?
_________________________
!

download KiXnet