Optimized script by taking instance variables outside of while loop.