Flying bug fix

Loop bug and undefined variable fix by T-Max