does this statement
val = lastVal; // 'save' the value of val to next iteration
do what you say it does? I don't think so...