Upgraded version with loop checking