Added code to prevent infinite loops