added length checks to prevent crashes in long runs