Fix bug in nexthead and nexttail functions