Refactored global variables and renamed loopdata to just loop.