Updated with fixes for looping