Clean up the dirty loop

Needs testing for possible memory leaks