updated to reflect comments

avoid infinite loop and duplicate code