You can make this whole proc much cleaner if you instead loop through the contents instead of checking each variable.

Also the sleep(50) is a problem if it isn't in any spawn(), it could halt the MC.