Loop detection along with some minor improvements